Files
gstack/browse/test/session-tabs.test.ts
Garry Tanandcapy-ai[bot] 9d9d4c31bb v1.93.0.0 wave(browse): #3700 #3773 #3779 #3817 #3842 (#3858)
* feat(loadouts): Opus 5.5 lite loadout with explicit model detection (GSTA-161)

modules/loadouts.json gains the lite loadout (eleven coaching preamble
pieces dropped; upgrade-check and brain-sync kept) and a models map that
sends only claude-opus-5-5 (and its dated snapshots) to it. Detection is
explicit: Capy passes --model to the installer, Claude Code opts in with
./setup --loadout lite; anything unmapped, invalid or unreadable serves full.
The checkout always stays the full render.

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* docs(loadouts): Opus 5.5 lite, detection order, Capy SKILL_ROOT, setup --loadout; troubleshooting anchors; changelog fragment (GSTA-161)

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* fix(loadouts): claude_loadout read through CONFIG_BIN; capy skill context ceiling for the --model line (GSTA-161)

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* fix: pre-landing review fixes (prune keeps a reused loadout folder, GSTACK_LOADOUT_SKILL_ROOT, claude_loadout guard test) (GSTA-161)

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* fix: pre-landing review fixes (Capy skill passes the model as GSTACK_MODEL so an older installer ignores it) (GSTA-161)

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* fix: pre-landing review fixes (prune only owned, unused folders; full root from the canonical Claude install; fallback reason and source) (GSTA-161)

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* docs: loadout source example, install and resolve commands, Capy launch-file note (GSTA-161)

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* feat(autoplan): --ceo-only runs the CEO review alone with zero questions (GST-537)

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* fix: pre-landing review fixes

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* test: classify autoplan-ceo-only in the Codex host metadata

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* fix: select autoplan-ceo-only on the skills it runs; say it needs Claude Code

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* test: run autoplan-ceo-only in the marathon lane

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* docs: changelog entry for /autoplan --ceo-only

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* test: count the autoplan-ceo-only paid file in the shard inventory

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* feat: gstack-autoplan next --ceo-only runs the CEO review alone and ends reviewed (GST-537)

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* fix: budget and close recover a budget-stopped CEO-only run; reviewed is at rest for checkpoints

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* fix: CEO-only finish leaves owner-only cap items undecided, refuses marker phase flags and a plan at the report path, and replaces ceo-review.md atomically

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* fix: the CEO-only report-path guard compares real paths and refuses at the finish when the report file is the plan

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* docs: CEO_ONLY_CONFLICT covers a plan linked to the report path

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* test(browse): failing-first device and touch tests (GSTA-227 F3, #3058)

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* fix: the report-path guard keeps the lexical check, skips safe hard links and compares bigint file ids

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* browse: per-session tabs for parallel agents; tab pins stop moving the shared active tab (#1961)

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* browse: keep the server.ts tab-pin anchor comment for source guards

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* feat(browse): per-tab phone emulation and touch input ($B device, tap, swipe, pinch, touch; #3058, GSTA-227 F3)

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* test: copy lib/result-codes-autoplan.ts into the fixtures that copy the result-code tables, and keep it out of derived closures

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* docs(qa, aside): touch pointer in /qa, Aside touch recipe verified on Aside 1.26, report Phones row (GSTA-227 F3, #3058)

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* browse: drop the sessions paragraph from /browse to stay inside the parity cap

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* changelog: F3 phone emulation and touch entry

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* browse: hide the ps window in the session harness walk

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* docs: the decisions.jsonl status list names auto_kept

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* test(browse): session cap, LRU eviction, headed release and scoped auto-session rows

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* browse: sessions keep tab <id> picks, sidebar claude stays on the user's tab, pinned rebuild and state load rebind the scope

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* fix: pre-landing review fixes (touch cancel with no finger held is a no-op)

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* fix: Step 11 review fixes (headed tab adoption, pinned viewport reset, CLI retry keeps --session, rebuild id remap, --json notice, evicted-session reset, device kept after annotated captures, render opts out of sessions, session: client ids reserved)

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* fix: headed viewport auto keeps the user's active tab; render's closetab opts out of sessions

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* docs: sessions, phone emulation and touch in BROWSER.md; session: client ids reserved; TODOS #1961/#3058 shipped

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* test: copy lib/result-codes-browse.ts into the fixtures that copy the result-code modules

lib/result-codes.ts imports ./result-codes-browse, so fixtures with an explicit
lib list failed with 'Cannot find module'. pr-dependencies lists it with the other
reason-code modules as selection data. GSTA-227

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* feat: gstack-clean reclaims per-repo .gstack scratch and logs, dry run by default (#2627)

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* browse: name the Aside touch recipe's coordinates <tap-x>/<tap-y> with a numeric grammar

The generated-bash lint (INV-3) rejected the free-text <x>/<y> placeholders. GSTA-227

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* fix(clean): leave hard-linked and unreadable logs alone; cut through a no-follow descriptor checked against the evaluated inode

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* test(clean): tests that expect tmp removal see a quiet ps, so a codex elsewhere on the host cannot flake them

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* fix(clean): an unlistable tmp/ skips its group; liveness asked once per group on apply; BROWSER.md says which logs reset at daemon start

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* fix(clean): write output synchronously so --json reaches a pipe whole; test fixes for root, wrapper git and the ps stub

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* fix(clean): every change rechecks the verified folder and the measured file; full writes; EPIPE ends output quietly

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* test(clean): the early-close test checks the bin's own exit status

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* docs: list gstack-clean among the standalone CLIs

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* test(clean): copied-install fixtures and the dependency list carry lib/result-codes-clean.ts

The remote pregate failed 11 cases in gstack-doctor, plan-tune-cathedral and
timeline-stop-hook-slug: each copies an explicit list of lib/result-codes-*.ts
files into a temp install, and lib/result-codes.ts now imports
./result-codes-clean. Same lists GSTA-168 extended for result-codes-eval.

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* chore: regenerate gstack-doctor-components.sh for the gstack-clean result codes

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* qa: fold the touch pointer into the Phases sentence to fit the parity size cap after the main merge

qa's union was 95988 bytes (ratio 1.142 > maxSizeRatio 1.142, train 75). Now 95975 (1.1419). GSTA-227

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* docs: #3058 troubleshooting 'Fixed in' lines name v1.92.10.0 after the main merge

GSTA-227

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* test(clean): classify gstack-tasks rows files (tasks-*) as kept, after main added the producer

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* docs: #3058 troubleshooting 'Fixed in' lines name v1.92.20.0 after the main merge

GSTA-227

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* fix: pre-landing review fixes (restore the lib/result-codes-plan.ts ratchet row the base merge dropped)

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* test(clean): the producer scan ends a name at a colon, so prose after a path names the file (train 78)

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* docs: #3058 troubleshooting 'Fixed in' lines name v1.92.30.0 after the main merge

GSTA-227

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* outside-voice-api: caller receipts, stop_reason, OpenAI max_completion_tokens

A caller can write its own egress receipt (sink, consent, payload class);
the default stays the outside-voice receipt, so existing callers send and
record the same bytes. The result carries the provider's stop reason, and
an OpenAI request gets max_completion_tokens only when the caller sets an
output limit (GST-537 PR 3).

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* autoplan gate: item classes and the owner's answer provenance

Gate items carry item_class, ruleKept() names the keep-direction pick, and
answered decision rows record owner_mode, owner_named, rec_hash and
answered_role parsed from the owner's own words (GST-537 PR 3).

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* autoplan: shadow-mode decider module, frozen prompt and spend accounting

The switch (off by default, fixed at init), the lease, one model call per
gate with a page retry and a truncation retry under one deadline, the
once-per-revision record with its journaled sha256, the 10% audit mark,
and shadow-labeled ledger rows that count against the cap, show as
shadow= on GATE_SPEND and stay out of the per-voice price (GST-537 PR 3).

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* gstack-autoplan: shadow every published gate, the shadow export, config and docs

Every driver command that prints a gate records the shadow first and
checkpoints after it; answer waits for a live lease and records a dead
one retrospectively; gstack-autoplan shadow exports answered revisions
for taste-replay R2 (SHADOW_BEFORE_ANSWER otherwise); gstack-config
autoplan_shadow / autoplan_shadow_model; gstack-artifact validate checks
the record's hash (GST-537 PR 3).

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* changelog: shadow mode for the CEO-only decider (GST-537 PR 3)

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* autoplan shadow: /ship review fixes

- register test/fixtures/shadow-fake-model.ts in FREE_FIXTURES (free-fixtures inventory failed)
- withRunLock: count dead-owner reclaims apart from waitMs iterations, so a long wait can still reclaim
- buildPage: fill the decider template in one pass, so slot names inside the plan stay plan text
- revise regate: the shared publish step prints the GATE and ESCALATE lines once

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* autoplan shadow: reply files never follow a link; the retry reserves against the current cap

- a model reply is written by temp file and rename, so a link at the reply path is replaced, not written through
- each shadow reservation reads the run's current spend cap, so a budget change during the call is not undone

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* outside-voice-api: write the egress receipt under the caller's env

callModel resolved the receipt's state root from process.env even when the caller passed env, so the shadow
tests wrote to the real ~/.gstack (the free-suite home-containment guard caught it). The receipt now uses
req.env; the shadow tests give the fake model a private HOME, GSTACK_HOME and GSTACK_STATE_ROOT, and the receipt
test no longer sets process.env to pass.

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* fix(autoplan): CEO-only runs leave main's open Critical/High finding items to the owner (no decision row)

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* fix(autoplan): shadow pages carry main's finding items; a finding item is never ceo_eligible

After merging #3767 (main 90a170c), open Critical/High findings are gate items
(item_class finding). The shadow records one row per gate item, so its pages now
include them. A CEO-only run leaves those items to the owner, so their rows are
ceo_eligible false (rule_pick was already null). The shadow fixtures follow
main's gate (items, counts, "Do it" tokens); the two merge adapters follow
main's doNext(out, rest, price) and its per-voice reservation (--estimate-usd).

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* docs: #3058 troubleshooting 'Fixed in' lines name v1.92.61.0 after the main merge

GSTA-227

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* fix(investigate): drop the five-phase step procedure (GST-938)

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* changelog: GST-938 fragment wording

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* fix(investigate): keep the web-search sanitize guard; update BROWSER.md and docs/skills.md (review pass 1)

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* changelog: GST-938 wording

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* test(investigate): pin the web-search guard; changelog size (adversarial review)

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* test(clean): classify restamp-staging.json, the restamp producer main gained after #3779's base (wave browse)

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* fix: pre-landing review fixes (wave browse): scoped newtab keeps a concurrent tab switch; shadow validate catches a deleted record; a failed shadow publish is journaled

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* fix: a failed shadow publish journals under the run lock and never throws (wave browse review pass 2)

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* docs(unattended): shadow publish failures and the missing-record validate check (wave browse docs audit)

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* changelog: wave browse integrator fixes fragment

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* fix: shadow reader dedupes by run folder, so two runs started in the same second both count (wave browse CI free-suite 16)

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* chore: regenerate doctor result anchors in generator order (wave browse rebuild without #3818)

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* changelog: name the wave fragment after the rebuilt wave

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

---------

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>
2026-11-02 14:49:46 +00:00

415 lines
20 KiB
TypeScript

/**
* Per-session tabs (#1961) through the real command dispatch (server.ts
* handleCommandInternal on the module's own BrowserManager). Four sessions
* drive their own tabs at the same time; a slow fixture route forces the
* commands to overlap instead of relying on scheduler timing. The first two
* steps are the before: unsessioned callers share one tab, and the BROWSE_TAB
* pin moved the global active tab for everyone else while it ran. Runs in a
* child process so the module-level server state never touches this process.
*/
import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
import { spawnSync } from 'node:child_process';
import * as fs from 'node:fs';
import * as os from 'node:os';
import * as path from 'node:path';
let dir = '';
let steps: Record<string, any> = {};
const SCRIPT = (root: string) => `
import { __testInternals__ } from ${JSON.stringify(path.resolve(import.meta.dir, '../src/server.ts'))};
const fixture = Bun.serve({ port: 0, hostname: '127.0.0.1', async fetch(req) {
const u = new URL(req.url);
const s = u.searchParams.get('s') || 'x';
const ms = Number(u.searchParams.get('ms') || 0);
if (ms) await Bun.sleep(ms);
const html = '<!doctype html><title>' + s + '</title><h1>' + s + '</h1><input id="q" aria-label="query">'
+ '<button onclick="document.title = document.title + \\'-clicked\\'">Go ' + s + '</button>';
return new Response(html, { headers: { 'Content-Type': 'text/html' } });
} });
const U = (s, ms = 0) => 'http://127.0.0.1:' + fixture.port + '/page?s=' + s + '&ms=' + ms;
const bm = __testInternals__.browserManager;
const run = (command, args = [], extra = {}, tokenInfo = null) => __testInternals__.handleCommandInternal({ command, args, ...extra }, tokenInfo);
const owned = (owner) => [...bm.pages.keys()].filter(id => bm.getTabOwner(id) === owner);
const steps = {};
await bm.launch();
await run('goto', [U('root')]);
const rootTab = bm.getActiveTabId();
{ // before: two unsessioned agents share the one active tab
const a = run('goto', [U('a', 400)]);
await Bun.sleep(100);
const b = run('goto', [U('b')]);
await Promise.all([a, b]);
steps.shared = { title: (await run('js', ['document.title'])).result };
await run('goto', [U('root')]);
}
{ // BROWSE_TAB pin: an unsessioned caller during the pinned command, and the global tab afterwards
const t2 = JSON.parse((await run('newtab', ['--json'])).result).tabId;
const t3 = JSON.parse((await run('newtab', ['--json'])).result).tabId;
bm.switchTab(rootTab, { bringToFront: false });
const pinned = run('goto', [U('p', 400)], { tabId: t2 });
await Bun.sleep(100);
const during = (await run('url')).result;
await pinned;
const p1 = run('goto', [U('p1', 200)], { tabId: t2 });
await Bun.sleep(100);
const p2 = run('goto', [U('p2', 400)], { tabId: t3 });
await Promise.all([p1, p2]);
steps.pin = { during, activeAfter: bm.getActiveTabId(), rootTab };
await bm.closeTab(t2); await bm.closeTab(t3);
bm.switchTab(rootTab, { bringToFront: false });
}
{ // four sessions at once, three rounds, overlapping on the slow route
const names = ['a', 'b', 'c', 'd'];
const seen = [];
const flow = async (s, round) => {
await run('goto', [U(s, 60 * (names.indexOf(s) + 1) + 40 * round)], { session: s });
const snap = (await run('snapshot', ['-i'], { session: s })).result;
await run('click', ['button'], { session: s });
await run('fill', ['#q', 'hello-' + s], { session: s });
const title = (await run('js', ['document.title'], { session: s })).result;
const value = (await run('js', ["document.querySelector('#q').value"], { session: s })).result;
seen.push({ s, round, snapOk: snap.includes('Go ' + s), title, value });
};
let unsessioned = '';
for (let round = 0; round < 3; round++) {
const all = Promise.all(names.map(s => flow(s, round)));
await Bun.sleep(80);
unsessioned = (await run('url')).result;
await all;
}
steps.sessions = { seen, unsessioned, activeAfter: bm.getActiveTabId(), rootTab,
tabsPer: names.map(s => owned('session:' + s).length) };
}
{ // first use from four parallel commands opens one tab
await Promise.all([1, 2, 3, 4].map(() => run('url', [], { session: 'e' })));
steps.firstUse = { tabs: owned('session:e').length };
}
{ // chain subcommands stay on the session tab
const r = await run('chain', [JSON.stringify([['goto', U('ch', 200)], ['js', 'document.title']])], { session: 'a' });
steps.chain = { result: r.result, rootUrl: (await run('url')).result };
}
{ // per-session newtab and tabs
await run('newtab', [U('n2')], { session: 'c' });
steps.newtab = { title: (await run('js', ['document.title'], { session: 'c' })).result,
tabsC: owned('session:c').length, activeAfter: bm.getActiveTabId(), rootTab,
tabs: (await run('tabs', [], { session: 'c' })).result };
}
{ // a closed session tab: reads fail with the reset code, goto reopens
const id = owned('session:a')[0];
await bm.closeTab(id);
const text = await run('text', [], { session: 'a' });
const goto = await run('goto', [U('a2')], { session: 'a' });
steps.reset = { textStatus: text.status, text: text.result, gotoStatus: goto.status, goto: goto.result,
title: (await run('js', ['document.title'], { session: 'a' })).result };
}
{ // context recreation keeps the session's page
await run('goto', [U('rb')], { session: 'b' });
const ua = await run('useragent', ['Mozilla/5.0 gstack-session-test'], { session: 'b' });
steps.rebuild = { uaStatus: ua.status, url: (await run('url', [], { session: 'b' })).result, tabsB: owned('session:b').length };
}
{ // context recreation under a tab pin keeps every tab and the global active tab
const home = bm.getActiveTabId();
const t = JSON.parse((await run('newtab', [U('pinrb'), '--json'])).result).tabId;
bm.switchTab(home, { bringToFront: false });
const before = bm.pages.size;
const ua = await run('useragent', ['Mozilla/5.0 gstack-pin-test'], { tabId: t });
const pinned = [...bm.pages.entries()].find(([, p]) => p.url().includes('s=pinrb'))?.[0];
steps.pinRebuild = { status: ua.status, result: ua.result, before, after: bm.pages.size, rootUrl: (await run('url')).result,
pinnedUrl: pinned === undefined ? null : (await run('url', [], { tabId: pinned })).result };
if (pinned !== undefined) await bm.closeTab(pinned);
}
{ // only root may name a session; names are validated
const scoped = { token: 't', clientId: 'agent-x', type: 'session', scopes: ['read', 'write', 'admin', 'meta'], tabPolicy: 'shared', rateLimit: 0, createdAt: new Date().toISOString(), commandCount: 0 };
const denied = await run('url', [], { session: 'z' }, scoped);
const bad = await run('url', [], { session: 'bad name!' });
steps.auth = { deniedStatus: denied.status, denied: denied.result, zTabs: owned('session:z').length, badStatus: bad.status, bad: bad.result };
}
{ // idle sessions are closed on the next session lookup
process.env.BROWSE_SESSION_IDLE_MINUTES = '0.01';
await Bun.sleep(1200);
await run('url', [], { session: 'fresh' });
steps.sweep = { a: owned('session:a').length, d: owned('session:d').length, fresh: owned('session:fresh').length };
}
{ // a session the CLI derived on its own is ignored for a scoped token
const scoped = { token: 't', clientId: 'agent-y', type: 'session', scopes: ['read', 'write', 'admin', 'meta'], tabPolicy: 'shared', rateLimit: 0, createdAt: new Date().toISOString(), commandCount: 0 };
const auto = await run('url', [], { session: 'auto1', sessionAuto: true }, scoped);
steps.auto = { status: auto.status, tabs: owned('session:auto1').length };
}
{ // the session cap: refused while every other session is busy, LRU eviction once one is idle
process.env.BROWSE_SESSION_IDLE_MINUTES = '0';
process.env.BROWSE_MAX_SESSIONS = '1';
const busy = run('goto', [U('busy', 600)], { session: 'fresh' });
await Bun.sleep(150);
const limited = await run('url', [], { session: 'limit' });
await busy;
const freshTab = owned('session:fresh')[0];
const evicted = await run('url', [], { session: 'limit2' });
steps.limit = { status: limited.status, result: limited.result, limitTabs: owned('session:limit').length,
evictedStatus: evicted.status, fresh: owned('session:fresh').length, freshOpen: bm.pages.has(freshTab),
limit2: owned('session:limit2').length };
process.env.BROWSE_MAX_SESSIONS = '16';
const victim = await run('url', [], { session: 'fresh' });
steps.evictedRead = { status: victim.status, result: victim.result, tabs: owned('session:fresh').length };
await run('goto', [U('back')], { session: 'fresh' });
steps.evictedRead.reopened = (await run('js', ['document.title'], { session: 'fresh' })).result;
process.env.BROWSE_MAX_SESSIONS = '1';
}
{ // in headed mode an evicted session's tab is released to the user, not closed
const tab = owned('session:limit2')[0];
const mode = bm.getConnectionMode;
bm.getConnectionMode = () => 'headed';
try { await run('url', [], { session: 'limit3' }); } finally { bm.getConnectionMode = mode; }
steps.headed = { open: bm.pages.has(tab), owner: bm.getTabOwner(tab) ?? null, limit2: owned('session:limit2').length };
}
{ // tab <id> inside a session sticks for the session's next command
await run('goto', [U('mine')], { session: 'pick' });
const other = JSON.parse((await run('newtab', [U('theirs'), '--json'])).result).tabId;
const switched = await run('tab', [String(other)], { session: 'pick' });
const next = (await run('js', ['document.title'], { session: 'pick' })).result;
steps.pick = { switched: switched.status, next, owner: bm.getTabOwner(other) ?? null };
}
{ // another session's context rebuild leaves this session on the tab it picked
process.env.BROWSE_MAX_SESSIONS = '16';
await run('goto', [U('first')], { session: 'two' });
const first = owned('session:two')[0];
await run('newtab', [U('second')], { session: 'two' });
await run('tab', [String(first)], { session: 'two' });
const ua = await run('useragent', ['Mozilla/5.0 gstack-other-rebuild'], { session: 'other' });
steps.otherRebuild = { ua: ua.status, title: (await run('js', ['document.title'], { session: 'two' })).result };
}
{ // a first-use notice never prefixes --json output
const r = await run('newtab', [U('j'), '--json'], { session: 'jsonfirst' });
let parsed = null;
try { parsed = JSON.parse(r.result); } catch {}
steps.jsonFirst = { status: r.status, parsed: parsed !== null && typeof parsed.tabId === 'number' };
}
{ // headed mode: a session's new tab is registered once and the user's active tab stays put
const ctx = bm.context;
const listener = (page) => {
const id = bm.nextTabId++;
bm.pages.set(id, page);
bm.tabSessions.set(id, new (bm.tabSessions.values().next().value.constructor)(page));
bm.activeTabId = id;
};
ctx.on('page', listener);
const userTab = bm.getActiveTabId();
const before = bm.pages.size;
try { await run('url', [], { session: 'headednew' }); } finally { ctx.off('page', listener); }
const tab = owned('session:headednew')[0];
steps.headedNew = { activeKept: bm.getActiveTabId() === userTab, added: bm.pages.size - before,
sameObject: [...bm.pages.values()].filter(p => p === bm.pages.get(tab)).length };
}
{ // headed viewport auto under a tab pin rebuilds the pinned tab, not the global one
const userTab = bm.getActiveTabId();
const userPage = bm.pages.get(userTab);
const pinned = JSON.parse((await run('newtab', [U('vp'), '--json'])).result).tabId;
bm.switchTab(userTab, { bringToFront: false });
const mode = bm.connectionMode;
const listener = (page) => {
const id = bm.nextTabId++;
bm.pages.set(id, page);
bm.tabSessions.set(id, new (bm.tabSessions.values().next().value.constructor)(page));
bm.activeTabId = id;
};
bm.context.on('page', listener);
bm.connectionMode = 'headed';
let r;
try { r = await run('viewport', ['auto'], { tabId: pinned }); } finally { bm.connectionMode = mode; bm.context.off('page', listener); }
const pinnedPage = bm.pages.get(pinned);
steps.headedViewport = { status: r.status, userTracked: bm.pages.get(userTab) === userPage,
pinnedLive: bm.pages.has(pinned), pinnedUrl: pinnedPage?.url() ?? null, activeKept: bm.getActiveTabId() === userTab,
sameObject: [...bm.pages.values()].filter(p => p === pinnedPage).length, rootUrl: (await run('url')).result };
}
{ // state save and load inside a session land the session on its own saved page
await run('goto', [U('st')], { session: 'st' });
const save = await run('state', ['save', 'gsta227-session'], { session: 'st' });
const load = await run('state', ['load', 'gsta227-session'], { session: 'st' });
const after = await run('js', ['document.title'], { session: 'st' });
steps.stateLoad = { save: save.status, load: load.status, loadText: load.result, afterStatus: after.status, title: after.result,
rootStatus: (await run('url')).status };
}
{ // an unsessioned tab switch made while a session opens a tab survives the open; closing a pinned tab that is also the global tab moves the global tab
const base = bm.getActiveTabId();
const other = JSON.parse((await run('newtab', ['--json'])).result).tabId;
bm.switchTab(base, { bringToFront: false });
const ctx = bm.context;
const newPage = ctx.newPage;
let release, entered;
const gate = new Promise(r => { release = r; });
const inside = new Promise(r => { entered = r; });
ctx.newPage = async (...a) => { entered(); await gate; return newPage.apply(ctx, a); };
const opening = run('newtab', [], { session: 'race' });
await inside;
bm.switchTab(other, { bringToFront: false });
release();
await opening;
ctx.newPage = newPage;
const raceActive = bm.activeTabId;
bm.switchTab(other, { bringToFront: false });
const closed = await run('closetab', [], { tabId: other });
steps.race = { raceActive, other, closed: closed.status, activeLive: bm.pages.has(bm.activeTabId) };
}
await Bun.write(${JSON.stringify(path.join(root, 'steps.json'))}, JSON.stringify(steps));
fixture.stop(true);
await Promise.race([bm.close(), Bun.sleep(3000)]);
process.exit(0);
`;
beforeAll(() => {
dir = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), 'browse-session-tabs-')));
fs.writeFileSync(path.join(dir, 'drive.ts'), SCRIPT(dir));
const r = spawnSync(process.execPath, [path.join(dir, 'drive.ts')], {
encoding: 'utf8', timeout: 150_000,
env: { ...process.env, GSTACK_HOME: path.join(dir, 'state'), CHROMIUM_PROFILE: path.join(dir, 'profile'),
BROWSE_STATE_FILE: path.join(dir, 'state', 'browse.json'), BROWSE_PARENT_PID: '0' },
});
if (!fs.existsSync(path.join(dir, 'steps.json'))) throw new Error(`driver failed (${r.status}): ${r.stderr.slice(-2000)}`);
steps = JSON.parse(fs.readFileSync(path.join(dir, 'steps.json'), 'utf8'));
}, 180_000);
afterAll(() => { if (dir) fs.rmSync(dir, { recursive: true, force: true }); });
describe('before: callers without a session share one tab', () => {
test('the second agent navigates the first agent away (negative control)', () => {
expect(steps.shared.title).toBe('b');
});
});
describe('a pinned tab no longer moves the global active tab', () => {
test('an unsessioned caller during a pinned command still sees its own tab', () => {
expect(steps.pin.during).toContain('s=root');
});
test('overlapping pinned commands leave the global active tab where it was', () => {
expect(steps.pin.activeAfter).toBe(steps.pin.rootTab);
});
});
describe('four sessions at once (#1961)', () => {
test('every session only ever sees its own page', () => {
expect(steps.sessions.seen).toHaveLength(12);
for (const row of steps.sessions.seen) {
expect(row).toMatchObject({ snapOk: true, title: row.s + '-clicked', value: 'hello-' + row.s });
}
});
test('each session owns one tab and the global active tab is untouched', () => {
expect(steps.sessions.tabsPer).toEqual([1, 1, 1, 1]);
expect(steps.sessions.activeAfter).toBe(steps.sessions.rootTab);
expect(steps.sessions.unsessioned).toContain('s=root');
});
test('parallel first commands of one session open a single tab', () => {
expect(steps.firstUse.tabs).toBe(1);
});
test('chain subcommands run on the session tab', () => {
expect(steps.chain.result).toContain('ch');
expect(steps.chain.rootUrl).toContain('s=root');
});
test('newtab inside a session moves only that session', () => {
expect(steps.newtab).toMatchObject({ title: 'n2', tabsC: 2 });
expect(steps.newtab.activeAfter).toBe(steps.newtab.rootTab);
expect(steps.newtab.tabs).toContain('session:c');
});
});
describe('session lifecycle', () => {
test('an unsessioned tab switch during a session newtab is kept', () => {
expect(steps.race.raceActive).toBe(steps.race.other);
});
test('closing a pinned tab that is the global active tab moves the global tab to a live one', () => {
expect(steps.race).toMatchObject({ closed: 200, activeLive: true });
});
test('a read on a closed session tab fails with the last URL; goto reopens it', () => {
expect(steps.reset.textStatus).not.toBe(200);
expect(steps.reset.text).toContain('BROWSE_SESSION_TAB_RESET');
expect(steps.reset.text).toContain('s=ch');
expect(steps.reset.gotoStatus).toBe(200);
expect(steps.reset.title).toBe('a2');
});
test('context recreation keeps the session on its page', () => {
expect(steps.rebuild.uaStatus).toBe(200);
expect(steps.rebuild.url).toContain('s=rb');
expect(steps.rebuild.tabsB).toBe(1);
});
test('context recreation under a tab pin keeps every tab', () => {
expect(steps.pinRebuild.status).toBe(200);
expect(steps.pinRebuild.result).not.toContain('Browser reset');
expect(steps.pinRebuild.after).toBe(steps.pinRebuild.before);
expect(steps.pinRebuild.rootUrl).toContain('s=root');
expect(steps.pinRebuild.pinnedUrl).toContain('s=pinrb');
});
test('a scoped token cannot name a session and opens no tab', () => {
expect(steps.auth.deniedStatus).toBe(403);
expect(steps.auth.denied).toContain('BROWSE_SESSION_ROOT_ONLY');
expect(steps.auth.zTabs).toBe(0);
});
test('an invalid session name is refused', () => {
expect(steps.auth.badStatus).toBe(400);
expect(steps.auth.bad).toContain('BROWSE_SESSION_INVALID');
});
test('idle sessions are closed on the next lookup', () => {
expect(steps.sweep).toEqual({ a: 0, d: 0, fresh: 1 });
});
test('an automatic session from a scoped token falls through and opens no tab', () => {
expect(steps.auto).toEqual({ status: 200, tabs: 0 });
});
test('at the cap a new session is refused while the others are busy', () => {
expect(steps.limit.status).toBe(429);
expect(steps.limit.result).toContain('BROWSE_SESSION_LIMIT');
expect(steps.limit.limitTabs).toBe(0);
});
test('at the cap the least recently used idle session is evicted', () => {
expect(steps.limit).toMatchObject({ evictedStatus: 200, fresh: 0, freshOpen: false, limit2: 1 });
});
test('tab <id> in a session moves that session to the tab for its next command', () => {
expect(steps.pick).toEqual({ switched: 200, next: 'theirs', owner: null });
});
test('a session evicted at the cap reports the reset on its next read; goto reopens it', () => {
expect(steps.evictedRead.status).toBe(409);
expect(steps.evictedRead.result).toContain('BROWSE_SESSION_TAB_RESET');
expect(steps.evictedRead.result).toContain('s=busy');
expect(steps.evictedRead.tabs).toBe(0);
expect(steps.evictedRead.reopened).toBe('back');
});
test('another session\'s context rebuild keeps this session on the tab it picked', () => {
expect(steps.otherRebuild).toEqual({ ua: 200, title: 'first' });
});
test('the first-use notice never corrupts --json output', () => {
expect(steps.jsonFirst).toEqual({ status: 200, parsed: true });
});
test('headed: a session tab is registered once and the user keeps the active tab', () => {
expect(steps.headedNew).toEqual({ activeKept: true, added: 1, sameObject: 1 });
});
test('headed: viewport auto under a tab pin rebuilds only the pinned tab', () => {
expect(steps.headedViewport).toMatchObject({ status: 200, userTracked: true, pinnedLive: true, activeKept: true, sameObject: 1 });
expect(steps.headedViewport.rootUrl).not.toContain('s=vp');
expect(steps.headedViewport.pinnedUrl).toContain('s=vp');
});
test('state save and load inside a session leave it on its saved page', () => {
expect(steps.stateLoad).toMatchObject({ save: 200, load: 200, afterStatus: 200, title: 'st', rootStatus: 200 });
});
test('in headed mode an evicted session keeps its tab open and unowned', () => {
expect(steps.headed).toEqual({ open: true, owner: null, limit2: 0 });
});
});