mirror of
https://github.com/garrytan/gstack.git
synced 2026-09-26 14:50:55 +02:00
v1.87.6.0 fix: make checks reliable and everyday validation faster (#2898)
* fix: acknowledge seeded plans before invoking review skills * fix: distinguish current plan input from conversation history * fix: keep hermetic plan reviews on manual permissions * fix: distinguish tool discovery from file permission ownership * fix: preserve initial plan mode in observation tests * fix: wait for scope decisions before writing review findings * fix: carry autoplan decisions consistently into review artifacts * test: retain native failure context in periodic assertions * fix: advance active file permissions before queued questions * fix: finish red-team attempts before retry and cleanup * fix: finalize plan format captures and judges before retry * fix: cancel setup-gbrain SDK attempts before fixture cleanup * test: select periodic consumers of the bounded attempt helper * fix native Bash permission cards and queued questions * fix: preserve independent decisions and review scope Keep CEO approach, engineering scope and outside-review choices from approving independent remedies together. Carry declared contracts through DX polish and resolve new gaps before editing the plan. Regenerate every host and retain existing stop boundaries. Validation: 654 focused tests passed across nine files; all-host generation passed. Full free and periodic validation pending. Co-Authored-By: OpenAI Codex <noreply@openai.com> * fix: require approval before design plan amendments Align the Design review philosophy and rating recipe with its section protocol: resolve one proposed fix, then apply only that approved decision and retain honest scores for declined fixes. Validation: 469 focused tests passed across four files; all-host generation passed. Co-Authored-By: OpenAI Codex <noreply@openai.com> * fix: observe native question completion before transcript persistence Match owned completion hooks to submitted choices, reject conflicting or late answers, and retain bounded failure evidence. * test: recognize review posture in acknowledged native questions Require the selected mode acknowledgement, a completed follow-up question, and its current decoded display while preserving existing posture assertions. * fix: preserve settled CEO choices and isolate pending remedies Resolve established approach gates with cited authority and keep independent fixes out of unrelated option commitments and plan amendments. * fix: carry approved DX choices through later review steps Choose documentation approaches within the accepted scope and map resolved confusion points without reopening them through a bulk menu. * test: handle native settings-file edit prompts Keep one-time owned-file approvals and retain the actual sampled Autoplan permission frame with its matching barrier state. * test: accept standard CEO reply directives with tuning footers Recognize the exact trailing preference footer and letter-list directive while preserving current-display and exact acknowledgement checks. * test: scope split reviewers to their generated plan artifacts * test: observe native Bash permissions and invocation results * test: handle owned Bash prompts during mode preference checks * test: preserve synchronous subprocess rejection in Codex fixture * Fix periodic review handoff navigation Recognize review-first and explicit manual-next-step labels while preserving exact action families, manual preference, and ambiguous-menu rejection. Co-authored-by: OpenAI Codex <noreply@openai.com> * Bind pending file permissions to distinct current targets Allow one captured file request to own the complete current dialog while unrelated file work is pending. Preserve same-path ambiguity, exact input ownership, and one-time grant checks. Co-authored-by: OpenAI Codex <noreply@openai.com> * Make paired CEO verification choices genuinely unresolved Start the positive control with proposed manual checks so its unchanged oracle measures two new coverage decisions. Preserve runtime contracts, targets, count bounds, and all assertions. Co-authored-by: OpenAI Codex <noreply@openai.com> * Keep CEO review options and verification within approved scope Audit every offered option for independent add-ons and keep new verification depth pending until accepted. Preserve already requested coverage and trace plan changes to the actual decision. Co-authored-by: OpenAI Codex <noreply@openai.com> * Assemble DX review artifacts before appending the final report Keep early DX evidence above decisions, update artifact sections in place, and append the report using the actual current file suffix. Re-read after deleting an existing report before choosing the append anchor. Co-authored-by: OpenAI Codex <noreply@openai.com> * Keep outside plan reviews exclusive and invocation-owned Follow one preflight-selected backend, terminate failed Codex work before fallback, and allocate extra prompt/output files uniquely. Consume only the current invocation’s completed output. Co-authored-by: OpenAI Codex <noreply@openai.com> * Select periodic completion evaluations for report writer changes Register the shared review resolver for eight missing consumers and regress selection for all nine completion cases without changing their IDs or tiers. Co-authored-by: OpenAI Codex <noreply@openai.com> * Keep permission ambiguity fixtures on the same normalized target Use distinct raw spellings of one target in the four negative fixtures so they exercise the normalized duplicate-owner guard after exact current-file disambiguation. Preserve the existing exception, no-input, diagnostic and cleanup assertions. Co-authored-by: OpenAI Codex <noreply@openai.com> * Clarify preserved contracts in engineering review fixture Co-authored-by: OpenAI Codex <noreply@openai.com> * Recognize the offered DX follow-up handoff Co-authored-by: OpenAI Codex <noreply@openai.com> * Check independent commitments before presenting review options Co-authored-by: OpenAI Codex <noreply@openai.com> * Keep Codex review output and status in one shell invocation Co-authored-by: OpenAI Codex <noreply@openai.com> * Distinguish seeded plans from reports written by a test attempt Co-authored-by: OpenAI Codex <noreply@openai.com> * Recover clipped Autoplan file approvals with bounded viewport resizing Co-authored-by: OpenAI Codex <noreply@openai.com> * Recover clipped Bash approvals before binding the complete command Co-authored-by: OpenAI Codex <noreply@openai.com> * Isolate setup message tests from the shared checkout Run the real installer in a temporary payload with private config, require successful completion, and guard source and binary contents and mtimes. Co-authored-by: OpenAI Codex <noreply@openai.com> * Fix periodic native permission and report completion handling Match the pinned CLI's soft wraps and clipped headings without granting from incomplete frames. Retire completed file requests, retain mode annotations, and ask section captures for a short final acknowledgement after their full report is saved. Co-authored-by: OpenAI Codex <noreply@openai.com> * Preserve review approvals and validate DX comparison artifacts Keep independent remedies and approved amendments explicit. Give the synthetic DX review its existing documentation and validate peer comparison as required analysis alongside four native decisions. Add positive and negative semantic calibrations while preserving review counts, model budgets and prompt size limits. Co-authored-by: OpenAI Codex <noreply@openai.com> * Make the five-finding CEO fixture's application boundary explicit Materialize the request adapter and service composition used by the synthetic payment application. Explicitly declare the revised unregistered-event and mail-telemetry assumptions while preserving uncaught handler errors, the original invoice path and all five unresolved findings. Co-authored-by: OpenAI Codex <noreply@openai.com> * Keep CEO state-path checks scoped to directory preparation Co-authored-by: OpenAI Codex <noreply@openai.com> * Use checked ports and bounded cleanup in pair-agent tests Discover the daemon port from its owned state file, retain startup diagnostics, and await failed-start cleanup. Add occupied-port, early-exit, deadline, and foreign-state regressions while preserving the existing HTTP assertions and hook budgets. Co-authored-by: Codex <noreply@openai.com> * Preserve queued edit identity and recover clipped Bash permissions Distinguish separately queued unfinished edits from mutation of one native tool ID. Keep grants bound to an exact owned request and reject reused IDs, ambiguous inputs, and competing owners. Support the pinned renderer's literal em dash and request a repaint when only the Bash card's top rule is clipped. Grants still require the complete fresh card and an exact native acknowledgment. Validation: 413 integrated parser/event tests passed; private repaint controls and joint source review passed. Full canonical suite and native periodic rerun remain pending. Co-authored-by: Codex <noreply@openai.com> * Keep periodic reviews within their approved contracts and deliverables Carry exact approvals through engineering review, preserve declared contracts when amending CEO plans, and keep prioritization at the requested decision level. Materialize the revised synthetic SDK reference contract while retaining the five original documentation gaps. Accept the observed semicolon in the finite DX handoff menu and register the direct source dependencies used by the engineering cases. Regenerate canonical review documents without changing model budgets, retries, count bands, or native completion assertions. Validation: all-host generation and 275 review, fixture, selection and parity tests passed. Full free-suite and native periodic validation remain pending. Co-authored-by: Codex <noreply@openai.com> * Keep Eng approval cadence and independence guards explicit * Accept ordinary punctuation in manual review handoffs * Recover file permissions alongside queued Bash calls * Carry approved DX work through later review findings * Clarify the synthetic auth internal failure decision * Bound the periodic DX fixture to onboarding changes * Recognize native Design review handoff labels * Hold scope in the integration-choice review fixture * Carry approved Design decisions through review evidence * Capture listener state when feedback reload fails * Exclude workspace caches before checking deprecated flags * Verify Design UI scope against a seeded review plan * Clarify plan review decisions and outside-voice approval flow * Reject setup menus in the Design UI gate * docs: require focused repair validation before final acceptance * fix: separate review commitments within existing prompt budgets * docs: align generation and contributor validation guidance * fix: advance native review prompts and count acknowledged findings * chore: bump version and changelog (v1.87.1.0) Co-Authored-By: OpenAI Codex <noreply@openai.com> * chore: enforce cheap checks and side-effect-free validation previews * fix: handle owned Fetch permissions and oversized native cards * test: ground review fixtures in independent executable contracts * fix: preserve review decisions and verify reports before completion * test: construct the synthetic credential URL without a scanner false positive * test: materialize DX examples and verify their actual local behavior * fix: clarify CEO review decisions and execution order * fix: clarify review workflow ordering and select Design quality checks * Fix review decision gates and incomplete evaluation fixtures Persist CEO and engineering commitment ledgers before menus, preserve exact approvals, and distinguish implementation structure from feature scope. Route Autoplan through the canonical CEO Step 0 ordering. Classify DX findings before requesting approval and ground runtime claims in actual evidence. Complete neutral non-target fixture contracts and accept the captured Design handoff purpose without relaxing its ownership or acknowledgment checks. Record runtime-capability verification in AGENTS.md validation discipline. Validation: 1,335 focused tests passed across 21 files; build, all-host freshness, skill validation (647 artifacts / 107 tracked), and credential checks passed. Prior paid failures are preserved; behavioral acceptance remains pending. * Fix review decision boundaries and owned Read prompts Preserve exact approvals across review options, compare consistent DX milestones, and keep proposed implementation separate from review evidence. Bind modern Read prompts to one immutable native request and wait for its result. Retain captured regression verdicts, correct fixture error names, improve import probe diagnostics, and record focused-first validation discipline in AGENTS.md. * Clarify CEO and engineering review decisions Use explicit decision steps, one engineering ledger, and clear scope/write transitions. Preserve exact approvals and distinguish pending test requirements. Keep unrelated generated content unchanged. * Fix review decision ordering and native evaluation interactions * Clarify engineering decisions and test artifact order * Clarify pending choices and approvals in CEO reviews * Make CEO review phases sequential and clarify completion * Fix Design board submission intent matching * Seed an existing browser test baseline for Autoplan * Document decision-log payloads before state initialization * Preserve exact review scope and decide one change before drafting options * Require input identity before repeating passing model judges * Honor permitted storage throughout CEO review completion * Match complete native permission text within the pinned renderer contract * Align review approvals, independent choices, and bounded validation * fix: preserve reopened approvals and declare fixture interfaces * fix: isolate review artifacts and audit complete questions * fix: match detector artifact permissions to configured storage * fix: complete native permissions and review fixture workflows * fix: order CEO review work and separate engineering guarantees * fix: preserve native validation and separate review choices * fix: clarify review decisions and judge complete report context * fix: constrain review judgments and retain parse failures * fix: compare each affected value before review decisions * fix: make engineering review decisions and completion order explicit * fix: give the complete Autoplan evaluation a bounded chain budget * fix(cso): diagnose forbidden Docker endpoints before tool lookup * fix(reviews): reconcile workflow contracts and generated artifacts after main integration * fix(evals): migrate retained regressions to the native review harness * fix(tests): close native harness and workflow integration regressions * fix(evals): preserve complete permission context and native menu contracts * fix(tests): capture synchronous command output without pipe drain stalls * fix(reviews): clarify decision and completion ordering * fix(reviews): separate decision readiness from final completion checks * refactor(reviews): consolidate decision rules and completion branches * fix(plan-eng-review): order preparation and clarify decision routing * fix(plan-eng-review): restore size and question-format guard parity * fix(plan-eng-review): clarify scope phases and blocked completion * fix(plan-eng-review): unify review flow and report destination * fix(plan-eng-review): define bootstrap and question stage ownership * fix(plan-eng-review): clarify review structure and design lookup * fix(plan-eng-review): render report examples and show saved decisions * fix: consolidate Eng review decisions and select their evaluations * test: cover overlapping terminal attachments and clean merged runner type * fix: preserve Office Hours relationship closings during review updates * fix: retain pasted review targets across slash invocations * docs: preserve validation traces and correct release scope * test: cover pasted targets in both review skills * fix: validate report artifacts before recording success * fix: redact source roots at CSO report boundaries * fix: bind native Design questions before answering * test: select report privacy and native recovery regressions * test: bind rejection predicate in extracted observers * fix: bind complete boxed native questions * test: keep the Design UI fixture on native review * fix: preserve review decisions and evaluation completion outcomes * fix: clarify CEO approval and report completion order * fix: align native review evaluation ownership and completion * fix: bind review evaluators to native decisions and owned artifacts * fix: validate review decisions against native outcomes * fix: preserve review evidence and Autoplan phase handoffs * test: bind review evidence to owned decisions and completion * fix: retain owned native history across compaction * fix(evals): validate current review decisions and setup choices * fix: bind Autoplan reviews and phase completion to current amended input * fix: reconcile native review evidence and close Autoplan phases * test: recognize owned whole-candidate complexity decisions * test: preserve report freshness for approved investigation handoffs * fix: recognize scoped review findings and isolate dual voice fixtures * fix: make review handoffs and question dispatch self-contained * test: recognize complete CEO decisions and procedural pauses * fix: bind current CEO comparison options and risk intervals * test: bind engineering decisions and completion to owned evidence * fix: publish Autoplan phase reports before continuing tools * test: verify actual Autoplan dual-review dispatch evidence * test: select dual review when shared evidence fixtures change * fix: clarify plan review decisions and completion gates * fix: make CEO review decisions and return paths explicit * test: keep Autoplan prompt files inside attempt state * test: preserve source whitespace across permission dialog wraps * fix: publish Autoplan phase reports before continuing * test: recognize current CEO comparisons and reject inactive records * fix: reconcile engineering decision states before completion * test: recognize complete Design decisions and reports * test: verify current engineering decisions before navigation * Recognize source-owned component reduction choices * fix: recognize current CEO ledger and commitment grids * test: supply RequestPolicy context to Eng count fixture * fix: save complete engineering decisions before asking * fix: bind Autoplan publication to the complete phase readback * chore: prepare 1.87.5.0 reliability release * fix: clarify engineering review completion and preserve log failures * fix: bind CEO saved choices and current section ancestry * fix(evals): bind review execution and completion evidence * fix(plan-ceo-review): verify complete decisions before asking * fix(evals): preserve complete engineering choice records * fix(evals): preserve complete review outcomes and bounded fixtures * fix(autoplan): publish phase reports before advancing * fix(plan-ceo-review): validate option fields before asking * fix(plan-eng-review): verify current decisions after answers * fix(evals): bind review decisions and bound fixture scope * fix(plan-ceo-review): verify decision rows and edit saved checkpoints * fix(evals): bind review evidence and scope document lookup * fix(plan-eng-review): update resolution state with its answer * fix(reviews): preserve complete questions through dispatch * fix(evals): recognize completed mode declarations * fix(evals): define cache consistency at wrapper completion * fix(evals): validate owned initial scope and completed review handoffs * fix: assemble complete CEO decision fields before saving * fix: authenticate automatic mode decisions without guessing selectors * fix: bind engineering coverage to approved regression contracts * fix(evals): supply review helpers to native Eng capture * fix(plan-eng-review): preserve the full selected option scope * fix(evals): recognize owned engineering seed and regression evidence * fix(evals): bind engineering retry reports to native approvals * docs: clarify release guarantees (v1.87.5.0) Co-Authored-By: OpenAI Codex <noreply@openai.com> * fix(evals): recognize owned engineering decisions and handoffs * fix(evals): bind engineering decisions and completion evidence * fix(tests): align review contracts and selection fixtures * fix(skills): restore review prompt size limits * fix(plan-eng-review): clarify review execution and completion * fix(evals): preserve configured retries through all supervision layers * Clarify Engineering decisions and report completion * Keep native decision assertions within their source boundary * fix: recognize owned engineering decisions and completed navigation * fix: bind completed auto decisions to their current review * fix: recognize explicit CEO source attribution * fix: dispatch verified CEO decisions without recomposing fields * test: expose existing execution deadlines to review actors * fix: distinguish CEO decision records from incidental headings * test: bind split-scope choices to the registered native actor * test: connect reviewed regressions to required evaluation coverage * Clarify CEO decision routing and completion stages * test: expose existing section review deadlines to fixture actors * test: recognize complete native CEO pacing inventories * test: exclude answered history from current CEO payloads * test: detect phase entry through owned skill HOME aliases * test: validate native review completion and owned report permissions * fix: make Autoplan close packets carry the parent handoff steps * test: assess source-bound HOLD decisions within the existing deadline * fix: keep CEO native decision fields under one formatting authority * test: register integrated review and permission dependencies * test: align native review adapters and finding coverage Preserve explicit AUTO decisions, apply native single-select defaults, and bind complete cropped questions and report permissions to their owned requests. Require seeded review findings instead of crediting setup menus. Keep captured failure controls and additive selection dependencies. The integrated candidate passed 3,099 focused tests across 65 files; affected paid validation remains required before publication. * fix(autoplan): require phase reports before advancing * fix(evals): bind setup and evidence to complete attempts * fix(evals): bind native answers and pending writes to fixture scope Preserve complete option rows when native descriptions wrap, retain current owned Write arguments before journal publication, and keep engineering and DX answers within their declared fixture interfaces. Add captured free regressions without increasing model budgets or relaxing completion checks. * fix(autoplan): verify phase reports across native tool paths Guard owned methodology reads and reviewer dispatches, detect complete driver loads through Bash, and distinguish report-only edits from implementation changes. Follow authenticated native UUID ancestry when journal writes arrive out of order and verify earlier native content for cached phase reads. Keep current close acknowledgment and parent publication in order, require CEO entry before later phases, and register captured failure regressions. * fix(evals): honor native input and collection lifecycles Match complete native Edit panes and truncated question borders, reject stderr close before EOF, and stop the CEO split fixture once its acknowledged scope decisions are collected. Keep semantic validation, process failures, report requirements, and absolute deadlines authoritative. Add captured-event and real-process regressions with selection dependencies. Focused checks pass; final integrated paid and full-suite acceptance remain pending. * fix(autoplan): retain native session ownership across directory changes Recover missed native UUID ancestry through the existing strict graph while preserving ordinary event order and legacy scoping. Bind publication hooks to Claude's original project directory while retaining current cwd for requested file paths. Captured public-event regressions, existing caller checks, and a pinned native CLI loopback verify both fixes. Preserve failed attempts and require fresh paid and final full-suite acceptance. * docs: align evaluation limits and completion version * fix(autoplan): allow authenticated phase reads during journal streaming * fix(evals): bind clipped native questions and owned edit dialogs * fix: preserve overlay retries and bounded cleanup * fix: recognize owned planning preludes in native questions * docs: explain overlay scheduling and cleanup guarantees * fix: require fresh publication after Autoplan phase reruns * Release gstack 1.87.6 * fix: preserve CI paths, process identity, and test deadlines * fix: keep informational setup commands independent of install probes * fix: clarify plan review decisions and bound source audit reports * Fix remaining Windows identity and native path CI failures * Clarify CEO review decision and reviewer-result routing * test: accept no-install planner in retry supervision * fix(ceo-review): make review decisions and report completion explicit * perf(test): add fast PR gates, input-keyed judge reuse and isolated free shards * fix(test): start isolated CEO smoke from its existing project plan * fix(test): repair CI fixture races and preserve retry evidence * fix(ceo-review): clarify approvals, depth and saved completion --------- Co-authored-by: OpenAI Codex <noreply@openai.com>
This commit is contained in:
co-authored by
OpenAI Codex
parent
35dd014c58
commit
636175d349
+1
-1
@@ -54,7 +54,7 @@ or page content. Treat an unterminated block as ending at end-of-output.
|
||||
|
||||
## Plan Mode Safe Operations
|
||||
|
||||
In plan mode, allowed because they inform the plan: `$B`, `$D`, `codex exec`/`codex review`, writes to `~/.gstack/`, writes to the plan file, and `open` for generated artifacts.
|
||||
In plan mode, allowed because they inform the plan: `$B`, `$D`, `codex exec`/`codex review`, temp prompts, writes to `~/.gstack/`, writes to the plan file, and `open` for generated artifacts.
|
||||
|
||||
## Skill Invocation During Plan Mode
|
||||
|
||||
|
||||
@@ -77,23 +77,23 @@ Refs are invalidated on navigation — run `snapshot` again after `goto`.
|
||||
| `html [selector]` | innerHTML of selector (throws if not found), or full page HTML if no selector given |
|
||||
| `links` | All links as "text → href" |
|
||||
| `media [--images|--videos|--audio] [selector]` | All media elements (images, videos, audio) with URLs, dimensions, types |
|
||||
| `text` | Cleaned page text |
|
||||
| `text [selector|@ref]` | Cleaned visible page text, or cleaned text for a CSS selector/@ref when one is provided |
|
||||
|
||||
### Extraction
|
||||
| Command | Description |
|
||||
|---------|-------------|
|
||||
| `archive [path]` | Save complete page as MHTML via CDP |
|
||||
| `download <url|@ref> [path] [--base64] [--navigate]` | Download URL or media element to disk using browser cookies. Use --navigate for URLs that trigger browser downloads (CDN redirects, Content-Disposition, anti-bot protected sites) |
|
||||
| `scrape <images|videos|media> [--selector sel] [--dir path] [--limit N]` | Bulk download all media from page. Writes manifest.json |
|
||||
| `archive [path]` | Save complete page as MHTML via CDP. Default path: <temp>/browse-archive-<timestamp>.mhtml. Returns the saved path, size, and MHTML marker. |
|
||||
| `download <url|@ref> [path] [--base64] [--navigate]` | Download URL or media element to disk using browser cookies. Default path: <temp>/browse-download-<timestamp>.<ext>. --base64 returns a data:<mime>;base64,... string instead of writing, capped at 10MB. Use --navigate for URLs that trigger browser downloads (CDN redirects, Content-Disposition, anti-bot protected sites). |
|
||||
| `scrape <images|videos|media> [--selector sel] [--dir path] [--limit N]` | Bulk download all media from page to --dir (default: <temp>/browse-scrape-<timestamp>). Writes files plus manifest.json with source URL, size, type, success/failure counts. --limit defaults to 50 and caps at 200. |
|
||||
|
||||
### Interaction
|
||||
| Command | Description |
|
||||
|---------|-------------|
|
||||
| `cleanup [--ads] [--cookies] [--sticky] [--social] [--all]` | Remove page clutter (ads, cookie banners, sticky elements, social widgets) |
|
||||
| `cleanup [--ads] [--cookies] [--sticky] [--social] [--overlays] [--clutter] [--all]` | Remove page clutter by hiding matched elements. With no flags, defaults to --all. --all includes ads, cookies, sticky, social, overlays, and clutter; individual flags limit the categories. Returns removed element count. |
|
||||
| `click <sel>` | Click element |
|
||||
| `cookie <name>=<value>` | Set cookie on current page domain |
|
||||
| `cookie-import <json>` | Import cookies from JSON file |
|
||||
| `cookie-import-browser [browser] [--domain d]` | Import cookies from installed Chromium browsers (opens picker, or use --domain for direct import) |
|
||||
| `cookie-import-browser [browser] [--domain d] [--profile p] [--all]` | Import cookies from installed Chromium-family browsers. Browser names are the installed browser IDs shown by detection; common values include comet, chrome, chromium, edge, brave, arc. With --domain, imports only that domain after current-page domain validation; without --domain, opens the picker UI. --profile defaults to Default; --all imports every non-expired cookie only when explicitly passed. |
|
||||
| `dialog-accept [text]` | Auto-accept next alert/confirm/prompt. Optional text is sent as the prompt response |
|
||||
| `dialog-dismiss` | Auto-dismiss next dialog |
|
||||
| `fill <sel> <val>` | Fill input |
|
||||
@@ -117,13 +117,13 @@ Refs are invalidated on navigation — run `snapshot` again after `goto`.
|
||||
| `console [--clear|--errors]` | Console messages (--errors filters to error/warning) |
|
||||
| `cookies` | All cookies as JSON |
|
||||
| `css <sel> <prop>` | Computed CSS value |
|
||||
| `dialog [--clear]` | Dialog messages |
|
||||
| `dialog [--clear]` | Captured alert/confirm/prompt messages as text/JSON events. --clear empties the dialog buffer. |
|
||||
| `eval <file> [--out <file>] [--raw]` | Run JavaScript from a file in the page context and return result as string. Path must resolve under /tmp or cwd (no traversal). Use eval for multi-line scripts; use js for one-liners. With --out <file>, the result is written to disk (base64 data URL decoded to bytes unless --raw); --out makes the invocation a WRITE (needs write scope, never allowed over the tunnel). |
|
||||
| `inspect [selector] [--all] [--history]` | Deep CSS inspection via CDP — full rule cascade, box model, computed styles |
|
||||
| `inspect [selector] [--all] [--history]` | Deep CSS inspection via CDP. Default inspects one selector and returns matching element, full rule cascade, box model, and computed styles. --all returns every inspectable element summary; --history returns prior style modifications/inspection state. |
|
||||
| `is <prop> <sel|@ref>` | State check on element. Valid <prop> values: visible, hidden, enabled, disabled, checked, editable, focused (case-sensitive). <sel> accepts a CSS selector OR an @ref token from a prior snapshot (e.g. @e3, @c1) — refs are interchangeable with selectors anywhere a selector is expected. |
|
||||
| `js <expr> [--out <file>] [--raw]` | Run inline JavaScript expression in the page context and return result as string. Same JS sandbox as eval; the only difference is js takes an inline expr while eval reads from a file. With --out <file>, the result is written to disk instead of returned (a base64 data URL is decoded to raw bytes unless --raw is given) — ideal for rasterizing local renders to PNG without serializing megabytes back through the CLI. --out makes the invocation a WRITE (needs write scope, never allowed over the tunnel). |
|
||||
| `network [--clear]` | Network requests |
|
||||
| `perf` | Page load timings |
|
||||
| `network [--clear]` | Captured network requests as lines with method, status, resource type, and URL. --clear empties the captured request buffer. |
|
||||
| `perf` | Page load timings as JSON-ish milliseconds for navigation/load phases |
|
||||
| `storage | storage set <key> <value>` | Read both localStorage and sessionStorage as JSON. With "set <key> <value>", write to localStorage only (sessionStorage is read-only via this command — set it with `js sessionStorage.setItem(...)`). |
|
||||
| `ux-audit` | Extract page structure for UX behavioral analysis — site ID, nav, headings, text blocks, interactive elements. Returns JSON for agent interpretation. |
|
||||
|
||||
@@ -131,10 +131,10 @@ Refs are invalidated on navigation — run `snapshot` again after `goto`.
|
||||
| Command | Description |
|
||||
|---------|-------------|
|
||||
| `diff <url1> <url2>` | Text diff between pages |
|
||||
| `pdf [path] [--format letter|a4|legal] [--width <dim> --height <dim>] [--margins <dim>] [--margin-top <dim> --margin-right <dim> --margin-bottom <dim> --margin-left <dim>] [--header-template <html>] [--footer-template <html>] [--page-numbers] [--tagged] [--outline] [--print-background] [--prefer-css-page-size] [--toc] [--tab-id <N>] | pdf --from-file <payload.json> [--tab-id <N>]` | Save the current page as PDF. Supports page layout (--format, --width, --height, --margins, --margin-*), structure (--toc waits for Paged.js), branding (--header-template, --footer-template, --page-numbers), accessibility (--tagged, --outline), and --from-file <payload.json> for large payloads. Use --tab-id <N> to target a specific tab. |
|
||||
| `pdf [path] [--format letter|a4|legal] [--width <dim> --height <dim>] [--margins <dim>] [--margin-top <dim> --margin-right <dim> --margin-bottom <dim> --margin-left <dim>] [--header-template <html>] [--footer-template <html>] [--page-numbers] [--tagged] [--outline] [--print-background] [--prefer-css-page-size] [--toc] [--tab-id <N>] | pdf --from-file <payload.json> [--tab-id <N>]` | Save the current page as PDF. Default path: <temp>/browse-page.pdf. <dim> accepts CSS units like 1in, 72pt, 25mm, 2.54cm; bare numbers are pixels. Supports page layout (--format, --width, --height, --margins, --margin-*), structure (--toc waits briefly for Paged.js), branding (--header-template, --footer-template, --page-numbers), accessibility (--tagged, --outline), and --from-file <payload.json> for large payloads. Use --tab-id <N> to target a specific tab. |
|
||||
| `prettyscreenshot [--scroll-to sel|text] [--cleanup] [--hide sel...] [--width px] [path]` | Clean screenshot with optional cleanup, scroll positioning, and element hiding |
|
||||
| `responsive [prefix]` | Screenshots at mobile (375x812), tablet (768x1024), desktop (1280x720). Saves as {prefix}-mobile.png etc. |
|
||||
| `screenshot [--selector <css>] [--viewport] [--clip x,y,w,h] [--base64] [selector|@ref] [path]` | Save screenshot. --selector targets a specific element (explicit flag form). Positional selectors starting with ./#/@/[ still work. |
|
||||
| `screenshot [--selector <css>] [--viewport] [--clip x,y,w,h] [--base64] [selector|@ref] [path]` | Save screenshot. Default path: <temp>/browse-screenshot.png. Default capture is full-page; --viewport captures only the viewport. --selector targets a specific element; --clip uses x,y,width,height pixels. --base64 returns data:image/png;base64,... instead of writing, capped at 10MB. Positional selectors starting with ./#/@/[ still work. |
|
||||
|
||||
### Snapshot
|
||||
| Command | Description |
|
||||
@@ -146,10 +146,10 @@ Refs are invalidated on navigation — run `snapshot` again after `goto`.
|
||||
|---------|-------------|
|
||||
| `chain (JSON via stdin)` | Run a sequence of commands from JSON on stdin. One JSON array of arrays, each inner array is [cmd, ...args]. Output is one JSON result per command. Pipe a JSON array (e.g. `[["goto","https://example.com"],["text","h1"]]`) to `$B chain` and it runs the goto then the text command in order. Stops at the first error. |
|
||||
| `domain-skill save|list|show|edit|promote-to-global|rollback|rm <host?>` | Per-site notes the agent writes for itself. Host is derived from the active tab. Lifecycle: `save` adds a quarantined note → after N=3 successful uses without the prompt-injection classifier flagging it, the note auto-promotes to "active" → `promote-to-global` lifts it to the global tier (machine-wide, all projects). The classifier flag is set automatically by the L4 prompt-injection scan; agents do not set it manually. Use `list` / `show` to inspect, `edit` to revise, `rollback` to demote, `rm` to tombstone. |
|
||||
| `frame <sel|@ref|--name n|--url pattern|main>` | Switch to iframe context (or main to return) |
|
||||
| `inbox [--clear]` | List messages from sidebar scout inbox |
|
||||
| `frame <sel|@ref|--name n|--url pattern|main>` | Switch command context to an iframe, or `main` to return to the top page. <sel> is CSS, @ref comes from snapshot, --name matches frame name exactly, and --url pattern is a substring match against frame URL. |
|
||||
| `inbox [--clear]` | List sidebar inbox messages from the visible browser extension as JSON/text; --clear removes them after reading. |
|
||||
| `skill list|show|run|test|rm <name?> [--arg k=v]... [--timeout=Ns]` | Run a browser-skill: deterministic Playwright script that drives the daemon over loopback HTTP. 3-tier lookup (project > global > bundled). Spawned scripts get a per-spawn scoped token (read+write only) — never the daemon root token. |
|
||||
| `watch [stop]` | Passive observation — periodic snapshots while user browses |
|
||||
| `watch [stop]` | Start passive observation mode: records periodic snapshots while the user browses and blocks mutation commands. Use watch stop to end observation and return the collected snapshot summary. |
|
||||
|
||||
### Tabs
|
||||
| Command | Description |
|
||||
|
||||
+15
-15
@@ -98,7 +98,7 @@ export const COMMAND_DESCRIPTIONS: Record<string, { category: string; descriptio
|
||||
'reload': { category: 'Navigation', description: 'Reload page' },
|
||||
'url': { category: 'Navigation', description: 'Print current URL' },
|
||||
// Reading
|
||||
'text': { category: 'Reading', description: 'Cleaned page text' },
|
||||
'text': { category: 'Reading', description: 'Cleaned visible page text, or cleaned text for a CSS selector/@ref when one is provided', usage: 'text [selector|@ref]' },
|
||||
'html': { category: 'Reading', description: 'innerHTML of selector (throws if not found), or full page HTML if no selector given', usage: 'html [selector]' },
|
||||
'links': { category: 'Reading', description: 'All links as "text → href"' },
|
||||
'forms': { category: 'Reading', description: 'Form fields as JSON' },
|
||||
@@ -112,11 +112,11 @@ export const COMMAND_DESCRIPTIONS: Record<string, { category: string; descriptio
|
||||
'attrs': { category: 'Inspection', description: 'Element attributes as JSON', usage: 'attrs <sel|@ref>' },
|
||||
'is': { category: 'Inspection', description: 'State check on element. Valid <prop> values: visible, hidden, enabled, disabled, checked, editable, focused (case-sensitive). <sel> accepts a CSS selector OR an @ref token from a prior snapshot (e.g. @e3, @c1) — refs are interchangeable with selectors anywhere a selector is expected.', usage: 'is <prop> <sel|@ref>' },
|
||||
'console': { category: 'Inspection', description: 'Console messages (--errors filters to error/warning)', usage: 'console [--clear|--errors]' },
|
||||
'network': { category: 'Inspection', description: 'Network requests', usage: 'network [--clear]' },
|
||||
'dialog': { category: 'Inspection', description: 'Dialog messages', usage: 'dialog [--clear]' },
|
||||
'network': { category: 'Inspection', description: 'Captured network requests as lines with method, status, resource type, and URL. --clear empties the captured request buffer.', usage: 'network [--clear]' },
|
||||
'dialog': { category: 'Inspection', description: 'Captured alert/confirm/prompt messages as text/JSON events. --clear empties the dialog buffer.', usage: 'dialog [--clear]' },
|
||||
'cookies': { category: 'Inspection', description: 'All cookies as JSON' },
|
||||
'storage': { category: 'Inspection', description: 'Read both localStorage and sessionStorage as JSON. With "set <key> <value>", write to localStorage only (sessionStorage is read-only via this command — set it with `js sessionStorage.setItem(...)`).', usage: 'storage | storage set <key> <value>' },
|
||||
'perf': { category: 'Inspection', description: 'Page load timings' },
|
||||
'perf': { category: 'Inspection', description: 'Page load timings as JSON-ish milliseconds for navigation/load phases' },
|
||||
// Interaction
|
||||
'click': { category: 'Interaction', description: 'Click element', usage: 'click <sel>' },
|
||||
'fill': { category: 'Interaction', description: 'Fill input', usage: 'fill <sel> <val>' },
|
||||
@@ -130,18 +130,18 @@ export const COMMAND_DESCRIPTIONS: Record<string, { category: string; descriptio
|
||||
'viewport':{ category: 'Interaction', description: 'Set viewport size and optional deviceScaleFactor (1-3, for retina screenshots). --scale requires a context rebuild.', usage: 'viewport [<WxH>] [--scale <n>]' },
|
||||
'cookie': { category: 'Interaction', description: 'Set cookie on current page domain', usage: 'cookie <name>=<value>' },
|
||||
'cookie-import': { category: 'Interaction', description: 'Import cookies from JSON file', usage: 'cookie-import <json>' },
|
||||
'cookie-import-browser': { category: 'Interaction', description: 'Import cookies from installed Chromium browsers (opens picker, or use --domain for direct import)', usage: 'cookie-import-browser [browser] [--domain d]' },
|
||||
'cookie-import-browser': { category: 'Interaction', description: 'Import cookies from installed Chromium-family browsers. Browser names are the installed browser IDs shown by detection; common values include comet, chrome, chromium, edge, brave, arc. With --domain, imports only that domain after current-page domain validation; without --domain, opens the picker UI. --profile defaults to Default; --all imports every non-expired cookie only when explicitly passed.', usage: 'cookie-import-browser [browser] [--domain d] [--profile p] [--all]' },
|
||||
'header': { category: 'Interaction', description: 'Set custom request header (colon-separated, sensitive values auto-redacted)', usage: 'header <name>:<value>' },
|
||||
'useragent': { category: 'Interaction', description: 'Set user agent', usage: 'useragent <string>' },
|
||||
'dialog-accept': { category: 'Interaction', description: 'Auto-accept next alert/confirm/prompt. Optional text is sent as the prompt response', usage: 'dialog-accept [text]' },
|
||||
'dialog-dismiss': { category: 'Interaction', description: 'Auto-dismiss next dialog' },
|
||||
// Data extraction
|
||||
'download': { category: 'Extraction', description: 'Download URL or media element to disk using browser cookies. Use --navigate for URLs that trigger browser downloads (CDN redirects, Content-Disposition, anti-bot protected sites)', usage: 'download <url|@ref> [path] [--base64] [--navigate]' },
|
||||
'scrape': { category: 'Extraction', description: 'Bulk download all media from page. Writes manifest.json', usage: 'scrape <images|videos|media> [--selector sel] [--dir path] [--limit N]' },
|
||||
'archive': { category: 'Extraction', description: 'Save complete page as MHTML via CDP', usage: 'archive [path]' },
|
||||
'download': { category: 'Extraction', description: 'Download URL or media element to disk using browser cookies. Default path: <temp>/browse-download-<timestamp>.<ext>. --base64 returns a data:<mime>;base64,... string instead of writing, capped at 10MB. Use --navigate for URLs that trigger browser downloads (CDN redirects, Content-Disposition, anti-bot protected sites).', usage: 'download <url|@ref> [path] [--base64] [--navigate]' },
|
||||
'scrape': { category: 'Extraction', description: 'Bulk download all media from page to --dir (default: <temp>/browse-scrape-<timestamp>). Writes files plus manifest.json with source URL, size, type, success/failure counts. --limit defaults to 50 and caps at 200.', usage: 'scrape <images|videos|media> [--selector sel] [--dir path] [--limit N]' },
|
||||
'archive': { category: 'Extraction', description: 'Save complete page as MHTML via CDP. Default path: <temp>/browse-archive-<timestamp>.mhtml. Returns the saved path, size, and MHTML marker.', usage: 'archive [path]' },
|
||||
// Visual
|
||||
'screenshot': { category: 'Visual', description: 'Save screenshot. --selector targets a specific element (explicit flag form). Positional selectors starting with ./#/@/[ still work.', usage: 'screenshot [--selector <css>] [--viewport] [--clip x,y,w,h] [--base64] [selector|@ref] [path]' },
|
||||
'pdf': { category: 'Visual', description: 'Save the current page as PDF. Supports page layout (--format, --width, --height, --margins, --margin-*), structure (--toc waits for Paged.js), branding (--header-template, --footer-template, --page-numbers), accessibility (--tagged, --outline), and --from-file <payload.json> for large payloads. Use --tab-id <N> to target a specific tab.', usage: 'pdf [path] [--format letter|a4|legal] [--width <dim> --height <dim>] [--margins <dim>] [--margin-top <dim> --margin-right <dim> --margin-bottom <dim> --margin-left <dim>] [--header-template <html>] [--footer-template <html>] [--page-numbers] [--tagged] [--outline] [--print-background] [--prefer-css-page-size] [--toc] [--tab-id <N>] | pdf --from-file <payload.json> [--tab-id <N>]' },
|
||||
'screenshot': { category: 'Visual', description: 'Save screenshot. Default path: <temp>/browse-screenshot.png. Default capture is full-page; --viewport captures only the viewport. --selector targets a specific element; --clip uses x,y,width,height pixels. --base64 returns data:image/png;base64,... instead of writing, capped at 10MB. Positional selectors starting with ./#/@/[ still work.', usage: 'screenshot [--selector <css>] [--viewport] [--clip x,y,w,h] [--base64] [selector|@ref] [path]' },
|
||||
'pdf': { category: 'Visual', description: 'Save the current page as PDF. Default path: <temp>/browse-page.pdf. <dim> accepts CSS units like 1in, 72pt, 25mm, 2.54cm; bare numbers are pixels. Supports page layout (--format, --width, --height, --margins, --margin-*), structure (--toc waits briefly for Paged.js), branding (--header-template, --footer-template, --page-numbers), accessibility (--tagged, --outline), and --from-file <payload.json> for large payloads. Use --tab-id <N> to target a specific tab.', usage: 'pdf [path] [--format letter|a4|legal] [--width <dim> --height <dim>] [--margins <dim>] [--margin-top <dim> --margin-right <dim> --margin-bottom <dim> --margin-left <dim>] [--header-template <html>] [--footer-template <html>] [--page-numbers] [--tagged] [--outline] [--print-background] [--prefer-css-page-size] [--toc] [--tab-id <N>] | pdf --from-file <payload.json> [--tab-id <N>]' },
|
||||
'responsive': { category: 'Visual', description: 'Screenshots at mobile (375x812), tablet (768x1024), desktop (1280x720). Saves as {prefix}-mobile.png etc.', usage: 'responsive [prefix]' },
|
||||
'diff': { category: 'Visual', description: 'Text diff between pages', usage: 'diff <url1> <url2>' },
|
||||
// Tabs
|
||||
@@ -165,17 +165,17 @@ export const COMMAND_DESCRIPTIONS: Record<string, { category: string; descriptio
|
||||
'disconnect': { category: 'Server', description: 'Disconnect headed browser, return to headless mode' },
|
||||
'focus': { category: 'Server', description: 'Bring headed browser window to foreground (macOS)', usage: 'focus [@ref]' },
|
||||
// Inbox
|
||||
'inbox': { category: 'Meta', description: 'List messages from sidebar scout inbox', usage: 'inbox [--clear]' },
|
||||
'inbox': { category: 'Meta', description: 'List sidebar inbox messages from the visible browser extension as JSON/text; --clear removes them after reading.', usage: 'inbox [--clear]' },
|
||||
// Watch
|
||||
'watch': { category: 'Meta', description: 'Passive observation — periodic snapshots while user browses', usage: 'watch [stop]' },
|
||||
'watch': { category: 'Meta', description: 'Start passive observation mode: records periodic snapshots while the user browses and blocks mutation commands. Use watch stop to end observation and return the collected snapshot summary.', usage: 'watch [stop]' },
|
||||
// State
|
||||
'state': { category: 'Server', description: 'Save/load browser state (cookies + URLs)', usage: 'state save|load <name>' },
|
||||
// Frame
|
||||
'frame': { category: 'Meta', description: 'Switch to iframe context (or main to return)', usage: 'frame <sel|@ref|--name n|--url pattern|main>' },
|
||||
'frame': { category: 'Meta', description: 'Switch command context to an iframe, or `main` to return to the top page. <sel> is CSS, @ref comes from snapshot, --name matches frame name exactly, and --url pattern is a substring match against frame URL.', usage: 'frame <sel|@ref|--name n|--url pattern|main>' },
|
||||
// CSS Inspector
|
||||
'inspect': { category: 'Inspection', description: 'Deep CSS inspection via CDP — full rule cascade, box model, computed styles', usage: 'inspect [selector] [--all] [--history]' },
|
||||
'inspect': { category: 'Inspection', description: 'Deep CSS inspection via CDP. Default inspects one selector and returns matching element, full rule cascade, box model, and computed styles. --all returns every inspectable element summary; --history returns prior style modifications/inspection state.', usage: 'inspect [selector] [--all] [--history]' },
|
||||
'style': { category: 'Interaction', description: 'Modify CSS property on element (with undo support)', usage: 'style <sel> <prop> <value> | style --undo [N]' },
|
||||
'cleanup': { category: 'Interaction', description: 'Remove page clutter (ads, cookie banners, sticky elements, social widgets)', usage: 'cleanup [--ads] [--cookies] [--sticky] [--social] [--all]' },
|
||||
'cleanup': { category: 'Interaction', description: 'Remove page clutter by hiding matched elements. With no flags, defaults to --all. --all includes ads, cookies, sticky, social, overlays, and clutter; individual flags limit the categories. Returns removed element count.', usage: 'cleanup [--ads] [--cookies] [--sticky] [--social] [--overlays] [--clutter] [--all]' },
|
||||
'prettyscreenshot': { category: 'Visual', description: 'Clean screenshot with optional cleanup, scroll positioning, and element hiding', usage: 'prettyscreenshot [--scroll-to sel|text] [--cleanup] [--hide sel...] [--width px] [path]' },
|
||||
// UX Audit
|
||||
'ux-audit': { category: 'Inspection', description: 'Extract page structure for UX behavioral analysis — site ID, nav, headings, text blocks, interactive elements. Returns JSON for agent interpretation.', usage: 'ux-audit' },
|
||||
|
||||
@@ -1651,6 +1651,9 @@ export function buildFetchHandler(cfg: ServerConfig): ServerHandle {
|
||||
async function shutdown(exitCode: number = 0) {
|
||||
if (isShuttingDown) return;
|
||||
isShuttingDown = true;
|
||||
// State and terminal files belong to this instance, including embedders
|
||||
// whose cfg differs from the standalone daemon's module-level config.
|
||||
const config = cfg.config;
|
||||
|
||||
console.log('[browse] Shutting down...');
|
||||
if (ownsTerminalAgent) {
|
||||
|
||||
@@ -29,6 +29,10 @@ import { safeUnlink } from './error-handling';
|
||||
import { writeAgentRecord, clearAgentRecord } from './terminal-agent-control';
|
||||
import { findAvailablePort } from './port-allocator';
|
||||
import { extractPtyCookie } from './pty-session-cookie';
|
||||
import {
|
||||
createPtyLifecycle, disposePtyProcess, ptyCompletionReason,
|
||||
type PtyCompletion, type PtyLifecycle,
|
||||
} from './terminal-pty-lifecycle';
|
||||
|
||||
const STATE_FILE = process.env.BROWSE_STATE_FILE || path.join(process.env.HOME || '/tmp', '.gstack', 'browse.json');
|
||||
const PORT_FILE = path.join(path.dirname(STATE_FILE), 'terminal-port');
|
||||
@@ -87,6 +91,9 @@ process.on('unhandledRejection', (reason) => {
|
||||
|
||||
export interface PtySession {
|
||||
proc: any | null; // Bun.Subprocess once spawned
|
||||
lifecycle?: PtyLifecycle | null;
|
||||
completion?: PtyCompletion;
|
||||
disposed?: boolean;
|
||||
cols: number;
|
||||
rows: number;
|
||||
cookie: string;
|
||||
@@ -320,7 +327,7 @@ function buildTabAwarenessHint(stateDir: string): string {
|
||||
}
|
||||
|
||||
/** Spawn claude in a PTY. Returns null if claude not on PATH. */
|
||||
function spawnClaude(cols: number, rows: number, onData: (chunk: Buffer) => void) {
|
||||
function spawnClaude(cols: number, rows: number, lifecycle: PtyLifecycle) {
|
||||
const claudePath = findClaude();
|
||||
if (!claudePath) return null;
|
||||
|
||||
@@ -351,7 +358,10 @@ function spawnClaude(cols: number, rows: number, onData: (chunk: Buffer) => void
|
||||
terminal: {
|
||||
rows,
|
||||
cols,
|
||||
data(_terminal: any, chunk: Buffer) { onData(chunk); },
|
||||
data(_terminal: any, chunk: Buffer) { lifecycle.data(chunk); },
|
||||
exit(_terminal: any, code: number, signal: string | null) {
|
||||
lifecycle.readerEnded(code, signal);
|
||||
},
|
||||
},
|
||||
env,
|
||||
});
|
||||
@@ -360,17 +370,24 @@ function spawnClaude(cols: number, rows: number, onData: (chunk: Buffer) => void
|
||||
|
||||
/** Cleanup a PTY session: SIGINT, then SIGKILL after 3s. */
|
||||
function disposeSession(session: PtySession): void {
|
||||
try { session.proc?.terminal?.close?.(); } catch {}
|
||||
if (session.proc?.pid) {
|
||||
try { session.proc.kill?.('SIGINT'); } catch {}
|
||||
setTimeout(() => {
|
||||
try {
|
||||
if (session.proc && !session.proc.killed) session.proc.kill?.('SIGKILL');
|
||||
} catch {}
|
||||
}, 3000);
|
||||
}
|
||||
// Suppress callbacks caused by explicit close, and cancel any drain deadline.
|
||||
session.disposed = true;
|
||||
session.lifecycle?.dispose();
|
||||
session.lifecycle = null;
|
||||
const proc = session.proc;
|
||||
session.proc = null;
|
||||
session.spawned = false;
|
||||
disposePtyProcess(proc);
|
||||
}
|
||||
|
||||
function sendPtyCompletion(session: PtySession): void {
|
||||
if (!session.completion || !session.liveWs) return;
|
||||
// Keep process status and reader status distinct. Linux PTY shutdown can
|
||||
// report reader status 1; Bun exposes no errno to distinguish it from other
|
||||
// I/O errors. Keep completeness unknown for that status, rather than claiming
|
||||
// clean EOF or loss; only a missing reader callback proves drain timeout.
|
||||
try { session.liveWs.send(JSON.stringify({ type: 'pty-exit', ...session.completion })); } catch {}
|
||||
try { session.liveWs.close(1000, ptyCompletionReason(session.completion)); } catch {}
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -444,37 +461,49 @@ async function internalHandler<T>(
|
||||
* surfaced the error to the client (or will via the next frame).
|
||||
*/
|
||||
function maybeSpawnPty(ws: any, session: PtySession): boolean {
|
||||
if (session.disposed || session.completion) return false;
|
||||
if (session.spawned) return true;
|
||||
session.spawned = true;
|
||||
let leftover = Buffer.alloc(0);
|
||||
const proc = spawnClaude(session.cols, session.rows, (chunk) => {
|
||||
const combined = Buffer.concat([leftover, Buffer.from(chunk)]);
|
||||
// UTF-8 boundary detection (issue #1272). Look back at most 3 bytes
|
||||
// for the start of an incomplete multibyte sequence and defer it.
|
||||
let safeEnd = combined.length;
|
||||
for (let i = combined.length - 1; i >= Math.max(0, combined.length - 3); i--) {
|
||||
const b = combined[i];
|
||||
if ((b & 0x80) === 0) { safeEnd = i + 1; break; }
|
||||
if ((b & 0xC0) === 0x80) continue;
|
||||
const expected = (b & 0xE0) === 0xC0 ? 2 : (b & 0xF0) === 0xE0 ? 3 : 4;
|
||||
safeEnd = (combined.length - i >= expected) ? combined.length : i;
|
||||
break;
|
||||
const forward = (flush: Buffer) => {
|
||||
if (!flush.length) return;
|
||||
appendToRingBuffer(session, flush);
|
||||
if (session.liveWs) {
|
||||
try { session.liveWs.sendBinary(flush); } catch {}
|
||||
}
|
||||
const flush = combined.slice(0, safeEnd);
|
||||
leftover = combined.slice(safeEnd);
|
||||
if (flush.length) {
|
||||
// Always record into the ring buffer (Commit 3) so re-attach can
|
||||
// replay. session.liveWs is what changes across re-attaches — we
|
||||
// close over `session`, not the original `ws`, so the write always
|
||||
// goes to whichever ws is currently attached (or is skipped when
|
||||
// detached and liveWs is null).
|
||||
appendToRingBuffer(session, flush);
|
||||
if (session.liveWs) {
|
||||
try { session.liveWs.sendBinary(flush); } catch {}
|
||||
};
|
||||
const lifecycle = createPtyLifecycle({
|
||||
onData(chunk) {
|
||||
const combined = Buffer.concat([leftover, Buffer.from(chunk)]);
|
||||
// UTF-8 boundary detection (issue #1272). Look back at most 3 bytes
|
||||
// for the start of an incomplete multibyte sequence and defer it.
|
||||
let safeEnd = combined.length;
|
||||
for (let i = combined.length - 1; i >= Math.max(0, combined.length - 3); i--) {
|
||||
const b = combined[i];
|
||||
if ((b & 0x80) === 0) { safeEnd = i + 1; break; }
|
||||
if ((b & 0xC0) === 0x80) continue;
|
||||
const expected = (b & 0xE0) === 0xC0 ? 2 : (b & 0xF0) === 0xE0 ? 3 : 4;
|
||||
safeEnd = (combined.length - i >= expected) ? combined.length : i;
|
||||
break;
|
||||
}
|
||||
}
|
||||
const flush = combined.slice(0, safeEnd);
|
||||
leftover = combined.slice(safeEnd);
|
||||
forward(flush);
|
||||
},
|
||||
onComplete(completion) {
|
||||
// Preserve a final incomplete UTF-8 sequence as bytes as well. A reader
|
||||
// error/deadline remains explicit in the completion record.
|
||||
forward(leftover);
|
||||
leftover = Buffer.alloc(0);
|
||||
session.completion = completion;
|
||||
disposeSession(session);
|
||||
sendPtyCompletion(session);
|
||||
},
|
||||
});
|
||||
session.lifecycle = lifecycle;
|
||||
const proc = spawnClaude(session.cols, session.rows, lifecycle);
|
||||
if (!proc) {
|
||||
lifecycle.dispose();
|
||||
try {
|
||||
ws.send(JSON.stringify({
|
||||
type: 'error',
|
||||
@@ -486,9 +515,10 @@ function maybeSpawnPty(ws: any, session: PtySession): boolean {
|
||||
return false;
|
||||
}
|
||||
session.proc = proc;
|
||||
proc.exited?.then?.(() => {
|
||||
try { session.liveWs?.close(1000, 'pty exited'); } catch {}
|
||||
});
|
||||
proc.exited.then(
|
||||
(code: number) => lifecycle.exited(code, proc.signalCode ?? null),
|
||||
() => lifecycle.exited(null, proc.signalCode ?? null, true),
|
||||
);
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -550,6 +580,15 @@ function buildServer(port: number) {
|
||||
}
|
||||
disposeSession(session);
|
||||
sessionsById.delete(sid);
|
||||
// Disposal no longer closes the socket through proc.exited. Retire
|
||||
// its heartbeat and grant explicitly; late input cannot respawn this
|
||||
// disposed session while the close handshake is in progress.
|
||||
if (session.pingInterval) {
|
||||
clearInterval(session.pingInterval);
|
||||
session.pingInterval = null;
|
||||
}
|
||||
if (session.cookie) validTokens.delete(session.cookie);
|
||||
try { session.liveWs?.close(4001, 'pty restarted'); } catch {}
|
||||
return { killed: 1 };
|
||||
});
|
||||
}
|
||||
@@ -566,6 +605,7 @@ function buildServer(port: number) {
|
||||
pid: process.pid,
|
||||
gen: CURRENT_GEN,
|
||||
sessions: validTokens.size,
|
||||
completedSessions: [...sessionsById.values()].filter(session => session.completion).length,
|
||||
}), { status: 200, headers: { 'Content-Type': 'application/json' } });
|
||||
}
|
||||
|
||||
@@ -691,6 +731,9 @@ function buildServer(port: number) {
|
||||
// immediately after this text frame IS the replay.
|
||||
try { ws.send(JSON.stringify({ type: 'reattach-begin', sessionId })); } catch {}
|
||||
try { ws.sendBinary(buildReplayPayload(existing)); } catch {}
|
||||
// A child can finish while detached. Replay its final bytes before
|
||||
// reporting completion; never spawn a replacement into that lease.
|
||||
sendPtyCompletion(existing);
|
||||
return;
|
||||
}
|
||||
}
|
||||
@@ -724,6 +767,7 @@ function buildServer(port: number) {
|
||||
|
||||
message(ws, raw) {
|
||||
let session = sessions.get(ws);
|
||||
if (session && (session.disposed || session.liveWs !== ws)) return;
|
||||
if (!session) {
|
||||
// Fallback for any path where open() didn't fire (shouldn't happen
|
||||
// in Bun.serve but keeps the spawn path safe). No keepalive on
|
||||
@@ -812,7 +856,11 @@ function buildServer(port: number) {
|
||||
// Always drop the WS-keyed map entry and the per-attach
|
||||
// attachToken — the attach grant was single-use.
|
||||
sessions.delete(ws);
|
||||
if (session.cookie) validTokens.delete(session.cookie);
|
||||
const cookie = (ws.data as any)?.cookie;
|
||||
if (cookie) validTokens.delete(cookie);
|
||||
// A reattach can replace liveWs before the old socket's close arrives.
|
||||
// That stale callback must not retire the new socket, grant or child.
|
||||
if (session.liveWs !== ws) return;
|
||||
// Keepalive lives with the WS — every attach starts a fresh one.
|
||||
if (session.pingInterval) {
|
||||
clearInterval(session.pingInterval);
|
||||
@@ -832,7 +880,9 @@ function buildServer(port: number) {
|
||||
const intentional = code === 4001 || code === 4404 || code === 1000;
|
||||
if (intentional || !session.sessionId) {
|
||||
disposeSession(session);
|
||||
if (session.sessionId) sessionsById.delete(session.sessionId);
|
||||
if (session.sessionId && sessionsById.get(session.sessionId) === session) {
|
||||
sessionsById.delete(session.sessionId);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -844,7 +894,9 @@ function buildServer(port: number) {
|
||||
session.detachTimer = setTimeout(() => {
|
||||
if (!session.detached) return; // re-attached in the meantime
|
||||
disposeSession(session);
|
||||
if (session.sessionId) sessionsById.delete(session.sessionId);
|
||||
if (session.sessionId && sessionsById.get(session.sessionId) === session) {
|
||||
sessionsById.delete(session.sessionId);
|
||||
}
|
||||
}, DETACH_WINDOW_MS);
|
||||
// setTimeout returns a Bun Timer; unref so the detach window
|
||||
// doesn't keep the process alive past natural shutdown.
|
||||
|
||||
@@ -0,0 +1,144 @@
|
||||
/** Existing PTY shutdown grace, also bounds waiting for exit/reader completion. */
|
||||
export const PTY_SHUTDOWN_GRACE_MS = 3000;
|
||||
|
||||
export interface PtyProcessExit {
|
||||
exitCode: number | null;
|
||||
signal: string | null;
|
||||
waitFailed: boolean;
|
||||
}
|
||||
|
||||
export interface PtyReaderEnd {
|
||||
code: number;
|
||||
signal: string | null;
|
||||
}
|
||||
|
||||
export interface PtyCompletion {
|
||||
process: PtyProcessExit | null;
|
||||
reader: PtyReaderEnd | null;
|
||||
drainTimedOut: boolean;
|
||||
exitTimedOut: boolean;
|
||||
/** null: Bun reported an I/O status without enough detail to prove loss/EOF. */
|
||||
outputComplete: boolean | null;
|
||||
}
|
||||
|
||||
interface Timer {
|
||||
cancel(): void;
|
||||
}
|
||||
|
||||
function scheduleDeadline(callback: () => void, delayMs: number): Timer {
|
||||
const handle = setTimeout(callback, delayMs);
|
||||
handle.unref?.();
|
||||
return { cancel: () => clearTimeout(handle) };
|
||||
}
|
||||
|
||||
export interface PtyLifecycleOptions {
|
||||
onData(chunk: Buffer): void;
|
||||
onComplete(completion: PtyCompletion): void;
|
||||
/** An injectable timer keeps ordering/deadline tests independent of wall time. */
|
||||
schedule?: (callback: () => void, delayMs: number) => Timer;
|
||||
}
|
||||
|
||||
/**
|
||||
* Process exit does not drain a Bun.Terminal. Continue forwarding until the
|
||||
* reader finishes; bound the missing half of completion by the shutdown grace.
|
||||
* Bun 1.3.13 Terminal.zig reports reader 0=EOF / 1=I/O error (no errno), not
|
||||
* the child's exit code. In particular, never turn reader 1 into clean EOF.
|
||||
*/
|
||||
export function createPtyLifecycle(options: PtyLifecycleOptions) {
|
||||
let processExit: PtyProcessExit | null = null;
|
||||
let readerEnd: PtyReaderEnd | null = null;
|
||||
let stopped = false;
|
||||
let timer: Timer | null = null;
|
||||
const schedule = options.schedule ?? scheduleDeadline;
|
||||
|
||||
function finish() {
|
||||
if (stopped) return;
|
||||
stopped = true;
|
||||
timer?.cancel();
|
||||
timer = null;
|
||||
options.onComplete({
|
||||
process: processExit,
|
||||
reader: readerEnd,
|
||||
drainTimedOut: readerEnd === null,
|
||||
exitTimedOut: processExit === null,
|
||||
outputComplete: readerEnd === null ? false
|
||||
: readerEnd.code === 0 && readerEnd.signal === null ? true : null,
|
||||
});
|
||||
}
|
||||
|
||||
function changed() {
|
||||
if (processExit && readerEnd) finish();
|
||||
else if (!timer) timer = schedule(finish, PTY_SHUTDOWN_GRACE_MS);
|
||||
}
|
||||
|
||||
return {
|
||||
data(chunk: Buffer) {
|
||||
if (!stopped && !readerEnd) options.onData(chunk);
|
||||
},
|
||||
exited(exitCode: number | null, signal: string | null, waitFailed = false) {
|
||||
if (stopped || processExit) return;
|
||||
processExit = { exitCode, signal, waitFailed };
|
||||
changed();
|
||||
},
|
||||
readerEnded(code: number, signal: string | null) {
|
||||
if (stopped || readerEnd) return;
|
||||
readerEnd = { code, signal };
|
||||
changed();
|
||||
},
|
||||
dispose() {
|
||||
// Must precede Terminal.close(): explicit close itself calls reader EOF.
|
||||
stopped = true;
|
||||
timer?.cancel();
|
||||
timer = null;
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export type PtyLifecycle = ReturnType<typeof createPtyLifecycle>;
|
||||
|
||||
interface OwnedPtyProcess {
|
||||
pid: number;
|
||||
exitCode: number | null;
|
||||
signalCode: string | null;
|
||||
exited: Promise<number>;
|
||||
terminal?: { close(): void };
|
||||
kill(signal: string): unknown;
|
||||
}
|
||||
|
||||
/** Call only after cancelling the lifecycle: Terminal.close() can report EOF. */
|
||||
export function disposePtyProcess(
|
||||
proc: OwnedPtyProcess | null,
|
||||
schedule = scheduleDeadline,
|
||||
): void {
|
||||
try { proc?.terminal?.close(); } catch {}
|
||||
if (!proc?.pid || proc.exitCode != null || proc.signalCode != null) return;
|
||||
let exited = false;
|
||||
let timer: Timer | null = null;
|
||||
proc.exited.then(() => {
|
||||
exited = true;
|
||||
timer?.cancel();
|
||||
}, () => {});
|
||||
try { proc.kill('SIGINT'); } catch {}
|
||||
// `killed` only proves a signal was sent. Retain this exact process object,
|
||||
// never a mutable session.proc that could now refer to a replacement child.
|
||||
timer = schedule(() => {
|
||||
if (!exited) {
|
||||
try { proc.kill('SIGKILL'); } catch {}
|
||||
}
|
||||
}, PTY_SHUTDOWN_GRACE_MS);
|
||||
}
|
||||
|
||||
/** Transport close 1000 means this session ended, not that its child succeeded. */
|
||||
export function ptyCompletionReason(completion: PtyCompletion): string {
|
||||
const child = completion.process;
|
||||
if (child?.waitFailed) return 'pty process wait failed';
|
||||
if (child?.signal) return `pty exited (${child.signal})`;
|
||||
if (child && child.exitCode !== null && child.exitCode !== 0) {
|
||||
return `pty exited (code ${child.exitCode})`;
|
||||
}
|
||||
if (completion.drainTimedOut) return 'pty output drain timed out';
|
||||
if (completion.exitTimedOut) return 'pty process exit timed out';
|
||||
// Reader status 1 also occurs on ordinary Linux PTY shutdown. Retain it in
|
||||
// the completion record, without asserting either clean EOF or output loss.
|
||||
return 'pty exited';
|
||||
}
|
||||
@@ -27,89 +27,160 @@ import { GSTACK_EXTENSION_ID } from '../src/server';
|
||||
const ROOT = path.resolve(import.meta.dir, '../..');
|
||||
const SERVER_ENTRY = path.join(ROOT, 'browse/src/server.ts');
|
||||
|
||||
const SETUP_WORK_MS = 15_000;
|
||||
const CLEANUP_GRACE_MS = 1000;
|
||||
type DaemonProcess = Bun.Subprocess<'ignore', 'pipe', 'pipe'>;
|
||||
|
||||
// Same bounded draining/cleanup pattern as the tunnel fixture. Unread startup
|
||||
// output must not block the child, and errors must survive failed readiness.
|
||||
function captureOutput(stream: ReadableStream<Uint8Array>) {
|
||||
let tail = '';
|
||||
let finished = false;
|
||||
const reader = stream.getReader();
|
||||
const done = (async () => {
|
||||
const decoder = new TextDecoder();
|
||||
try {
|
||||
for (;;) {
|
||||
const { done, value } = await reader.read();
|
||||
if (done) break;
|
||||
tail = (tail + decoder.decode(value, { stream: true })).slice(-64_000);
|
||||
}
|
||||
tail = (tail + decoder.decode()).slice(-64_000);
|
||||
} catch (error) { tail = (tail + `\n[output capture failed: ${String(error)}]`).slice(-64_000); }
|
||||
finally { finished = true; reader.releaseLock(); }
|
||||
})();
|
||||
return { done, text: () => tail, cancel: () => {
|
||||
if (!finished) void reader.cancel().catch(() => {});
|
||||
} };
|
||||
}
|
||||
type OutputCapture = ReturnType<typeof captureOutput>;
|
||||
|
||||
interface DaemonHandle {
|
||||
proc: ReturnType<typeof Bun.spawn>;
|
||||
proc: DaemonProcess;
|
||||
stdout: OutputCapture;
|
||||
stderr: OutputCapture;
|
||||
port: number;
|
||||
token: string;
|
||||
stateFile: string;
|
||||
tempDir: string;
|
||||
baseUrl: string;
|
||||
output: Promise<[string, string]>;
|
||||
}
|
||||
|
||||
async function waitForReady(
|
||||
proc: ReturnType<typeof Bun.spawn>, stateFile: string, timeoutMs = 15_000,
|
||||
): Promise<{ port: number; token: string }> {
|
||||
const deadline = Date.now() + timeoutMs;
|
||||
let lastError = '';
|
||||
while (Date.now() < deadline && proc.exitCode === null) {
|
||||
try {
|
||||
// Only this daemon's published state can identify its selected port.
|
||||
const state = JSON.parse(fs.readFileSync(stateFile, 'utf-8'));
|
||||
if (state.pid !== proc.pid || !Number.isInteger(state.port) || state.port < 1 || state.port > 65535 ||
|
||||
typeof state.token !== 'string' || !state.token) {
|
||||
throw new Error('State does not identify this test daemon');
|
||||
async function stopProcess(proc: DaemonProcess, stdout: OutputCapture, stderr: OutputCapture): Promise<void> {
|
||||
let killError: unknown;
|
||||
if (proc.exitCode === null && proc.signalCode === null) {
|
||||
try { proc.kill('SIGKILL'); } catch (error) { killError = error; }
|
||||
}
|
||||
let timer: ReturnType<typeof setTimeout> | undefined;
|
||||
try {
|
||||
const settled = await Promise.race([
|
||||
Promise.all([proc.exited, stdout.done, stderr.done]).then(() => true),
|
||||
new Promise<false>(resolve => { timer = setTimeout(() => resolve(false), CLEANUP_GRACE_MS); }),
|
||||
]);
|
||||
if (!settled) {
|
||||
stdout.cancel(); stderr.cancel();
|
||||
throw new Error(`Owned daemon ${proc.pid} or output did not settle within ${CLEANUP_GRACE_MS}ms cleanup grace${killError ? `; kill failed: ${String(killError)}` : ''}`);
|
||||
}
|
||||
} finally { if (timer) clearTimeout(timer); }
|
||||
}
|
||||
|
||||
async function waitForReady(proc: DaemonProcess, stateFile: string, assertRunning: () => void, signal: AbortSignal): Promise<{ port: number; token: string }> {
|
||||
for (;;) {
|
||||
signal.throwIfAborted();
|
||||
assertRunning();
|
||||
let state: { pid?: unknown; port?: unknown; token?: unknown } | undefined;
|
||||
try { state = JSON.parse(fs.readFileSync(stateFile, 'utf8')); }
|
||||
catch (error) { if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error; }
|
||||
if (state !== undefined) {
|
||||
if (!state || state.pid !== proc.pid || typeof state.port !== 'number' ||
|
||||
!Number.isInteger(state.port) || state.port < 1 || state.port > 65535 ||
|
||||
typeof state.token !== 'string' || !state.token.length) {
|
||||
throw new Error('Daemon state does not identify the owned child with a valid port and token');
|
||||
}
|
||||
const resp = await fetch(`http://127.0.0.1:${state.port}/health`, {
|
||||
signal: AbortSignal.timeout(1000),
|
||||
});
|
||||
await resp.arrayBuffer();
|
||||
if (resp.ok) return state;
|
||||
lastError = `Health returned HTTP ${resp.status}`;
|
||||
} catch (error) {
|
||||
lastError = String(error);
|
||||
let ready = false;
|
||||
try {
|
||||
const resp = await fetch(`http://127.0.0.1:${state.port}/health`, {
|
||||
signal: AbortSignal.any([signal, AbortSignal.timeout(1000)]),
|
||||
});
|
||||
ready = resp.ok;
|
||||
void resp.body?.cancel().catch(() => {});
|
||||
} catch { /* not ready yet; the single setup deadline still applies */ }
|
||||
signal.throwIfAborted();
|
||||
assertRunning();
|
||||
if (ready) return { port: state.port, token: state.token };
|
||||
}
|
||||
await new Promise(r => setTimeout(r, 200));
|
||||
}
|
||||
throw new Error(`Daemon did not become ready within ${timeoutMs}ms (exit=${proc.exitCode}): ${lastError}`);
|
||||
}
|
||||
|
||||
async function spawnDaemon(): Promise<DaemonHandle> {
|
||||
async function spawnDaemon(options: {
|
||||
// Fixture-only failure injection; the normal work budget remains 15 seconds.
|
||||
launch?: (env: NodeJS.ProcessEnv) => DaemonProcess;
|
||||
setupWorkMs?: number;
|
||||
} = {}): Promise<DaemonHandle> {
|
||||
const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'pair-agent-e2e-'));
|
||||
const stateFile = path.join(tempDir, 'browse.json');
|
||||
|
||||
const proc = Bun.spawn(['bun', 'run', SERVER_ENTRY], {
|
||||
cwd: ROOT,
|
||||
env: {
|
||||
...process.env,
|
||||
BROWSE_HEADLESS_SKIP: '1',
|
||||
BROWSE_PORT: '0', // Use the daemon's checked allocator and discover its port from state.
|
||||
BROWSE_STATE_FILE: stateFile,
|
||||
BROWSE_PARENT_PID: '0',
|
||||
BROWSE_IDLE_TIMEOUT: '600000',
|
||||
},
|
||||
stdio: ['ignore', 'pipe', 'pipe'],
|
||||
let proc: DaemonProcess | undefined;
|
||||
let stdout: OutputCapture | undefined;
|
||||
let stderr: OutputCapture | undefined;
|
||||
const controller = new AbortController();
|
||||
const workMs = Math.min(options.setupWorkMs ?? SETUP_WORK_MS, SETUP_WORK_MS);
|
||||
let timer: ReturnType<typeof setTimeout>;
|
||||
const expired = new Promise<never>((_, reject) => {
|
||||
timer = setTimeout(() => {
|
||||
const error = new Error(`Daemon did not become ready within ${workMs}ms`);
|
||||
controller.abort(error);
|
||||
reject(error);
|
||||
}, workMs);
|
||||
});
|
||||
|
||||
const output = Promise.all([new Response(proc.stdout).text(), new Response(proc.stderr).text()]);
|
||||
try {
|
||||
const state = await waitForReady(proc, stateFile);
|
||||
const port = state.port;
|
||||
const baseUrl = `http://127.0.0.1:${port}`;
|
||||
return { proc, port, token: state.token, stateFile, tempDir, baseUrl, output };
|
||||
} catch (error) {
|
||||
// beforeAll cannot pass a handle to afterAll when startup fails.
|
||||
try { proc.kill('SIGKILL'); } catch {}
|
||||
try {
|
||||
await proc.exited;
|
||||
const [stdout, stderr] = await output;
|
||||
const errorFile = path.join(tempDir, 'browse-startup-error.log');
|
||||
const startupError = fs.existsSync(errorFile) ? fs.readFileSync(errorFile, 'utf-8') : '';
|
||||
throw new Error(`${error}\n${startupError}\n${stderr}\n${stdout}`);
|
||||
} finally {
|
||||
fs.rmSync(tempDir, { recursive: true, force: true });
|
||||
}
|
||||
}
|
||||
return await Promise.race([expired, (async () => {
|
||||
const env = {
|
||||
...process.env,
|
||||
BROWSE_HEADLESS_SKIP: '1',
|
||||
// Use the daemon's existing checked allocation; discover its actual port
|
||||
// from this child's state file instead of guessing an unchecked override.
|
||||
BROWSE_PORT: '0',
|
||||
BROWSE_STATE_FILE: stateFile,
|
||||
BROWSE_PARENT_PID: '0',
|
||||
BROWSE_IDLE_TIMEOUT: '600000',
|
||||
};
|
||||
proc = options.launch ? options.launch(env) : Bun.spawn(['bun', 'run', SERVER_ENTRY], {
|
||||
cwd: ROOT, env, stdio: ['ignore', 'pipe', 'pipe'],
|
||||
});
|
||||
stdout = captureOutput(proc.stdout);
|
||||
stderr = captureOutput(proc.stderr);
|
||||
let exitCode: number | undefined;
|
||||
void proc.exited.then(code => { exitCode = code; });
|
||||
const assertRunning = () => {
|
||||
if (exitCode !== undefined) throw new Error(`Daemon exited before setup completed (code ${exitCode}, signal ${proc!.signalCode ?? 'none'})`);
|
||||
};
|
||||
const { port, token } = await waitForReady(proc, stateFile, assertRunning, controller.signal);
|
||||
return { proc, stdout, stderr, port, token, stateFile, tempDir, baseUrl: `http://127.0.0.1:${port}` };
|
||||
})()]);
|
||||
} catch (cause) {
|
||||
// Preserve the original startup file before stopping or awaiting the child.
|
||||
let startupError = '';
|
||||
try { startupError = fs.readFileSync(path.join(tempDir, 'browse-startup-error.log'), 'utf8').slice(-64_000); } catch { /* startup may not have reached the logger */ }
|
||||
let cleanupError: unknown;
|
||||
try { if (proc && stdout && stderr) await stopProcess(proc, stdout, stderr); }
|
||||
catch (error) { cleanupError = error; }
|
||||
try { fs.rmSync(tempDir, { recursive: true, force: true }); }
|
||||
catch (error) { cleanupError ??= error; }
|
||||
throw new Error([
|
||||
cause instanceof Error ? cause.message : String(cause),
|
||||
`Owned daemon PID: ${proc?.pid ?? 'not spawned'}; exit: ${proc?.exitCode ?? 'none'}; signal: ${proc?.signalCode ?? 'none'}`,
|
||||
`stdout tail:\n${stdout?.text() || '(empty)'}`,
|
||||
`stderr tail:\n${stderr?.text() || '(empty)'}`,
|
||||
...(startupError ? [`startup error file:\n${startupError}`] : []),
|
||||
...(cleanupError ? [`cleanup failed: ${String(cleanupError)}`] : []),
|
||||
].join('\n'), { cause });
|
||||
} finally { clearTimeout(timer!); controller.abort(new Error('setup finished')); }
|
||||
}
|
||||
|
||||
async function killDaemon(handle: DaemonHandle): Promise<void> {
|
||||
try { handle.proc.kill('SIGKILL'); } catch {}
|
||||
try {
|
||||
await handle.proc.exited;
|
||||
await handle.output;
|
||||
} finally {
|
||||
fs.rmSync(handle.tempDir, { recursive: true, force: true });
|
||||
}
|
||||
try { await stopProcess(handle.proc, handle.stdout, handle.stderr); }
|
||||
finally { fs.rmSync(handle.tempDir, { recursive: true, force: true }); }
|
||||
}
|
||||
|
||||
describe('pair-agent flow end-to-end (HTTP only, no ngrok)', () => {
|
||||
@@ -619,3 +690,104 @@ describe('pair-agent flow end-to-end (HTTP only, no ngrok)', () => {
|
||||
expect(body).not.toContain('root:x:0:0'); // /etc/passwd signature
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
describe('pair-agent fixture startup ownership', () => {
|
||||
test('an occupied unchecked random choice does not strand automatic startup', async () => {
|
||||
let occupied: ReturnType<typeof Bun.serve> | undefined;
|
||||
for (let attempt = 0; attempt < 20 && !occupied; attempt++) {
|
||||
try {
|
||||
occupied = Bun.serve({ hostname: '127.0.0.1', port: 20000 + Math.floor(Math.random() * 20000),
|
||||
fetch: () => new Response('occupied', { status: 503 }) });
|
||||
} catch (error) { if ((error as NodeJS.ErrnoException).code !== 'EADDRINUSE') throw error; }
|
||||
}
|
||||
if (!occupied) throw new Error('Could not reserve the collision control port');
|
||||
const random = Math.random;
|
||||
const priorPort = process.env.BROWSE_PORT;
|
||||
let handle: DaemonHandle | undefined;
|
||||
try {
|
||||
// The previous helper deterministically chooses the already-held port.
|
||||
// The fixed child uses its own checked allocation and written state.
|
||||
Math.random = () => (occupied!.port - 20000 + 0.5) / 20000;
|
||||
process.env.BROWSE_PORT = String(occupied.port);
|
||||
handle = await spawnDaemon();
|
||||
expect(handle.port).not.toBe(occupied.port);
|
||||
expect(JSON.parse(fs.readFileSync(handle.stateFile, 'utf8')).pid).toBe(handle.proc.pid);
|
||||
expect((await fetch(`${handle.baseUrl}/health`)).status).toBe(200);
|
||||
} finally {
|
||||
Math.random = random;
|
||||
if (priorPort === undefined) delete process.env.BROWSE_PORT;
|
||||
else process.env.BROWSE_PORT = priorPort;
|
||||
try { if (handle) await killDaemon(handle); }
|
||||
finally { occupied.stop(true); }
|
||||
}
|
||||
expect(fs.existsSync(handle!.tempDir)).toBe(false);
|
||||
expect(handle!.proc.exitCode !== null || handle!.proc.signalCode !== null).toBe(true);
|
||||
}, 20_000);
|
||||
|
||||
test('early exit drains bounded output and preserves startup errors before cleanup', async () => {
|
||||
let proc: DaemonProcess | undefined;
|
||||
let tempDir = '';
|
||||
const started = Date.now();
|
||||
let failure: Error | undefined;
|
||||
try {
|
||||
await spawnDaemon({ launch: env => {
|
||||
tempDir = path.dirname(env.BROWSE_STATE_FILE!);
|
||||
proc = Bun.spawn([process.execPath, '-e', `
|
||||
const fs = require('node:fs');
|
||||
fs.writeFileSync(require('node:path').join(require('node:path').dirname(process.env.BROWSE_STATE_FILE), 'browse-startup-error.log'), 'original owned startup failure');
|
||||
await new Promise(resolve => process.stdout.write('x'.repeat(256_000) + '\\nstdout-final\\n', resolve));
|
||||
await new Promise(resolve => process.stderr.write('y'.repeat(256_000) + '\\nstderr-final\\n', resolve));
|
||||
process.exit(23);
|
||||
`], { env, stdio: ['ignore', 'pipe', 'pipe'] });
|
||||
return proc;
|
||||
} });
|
||||
} catch (error) { failure = error as Error; }
|
||||
expect(failure?.message).toContain('Daemon exited before setup completed (code 23');
|
||||
expect(failure?.message).toContain('stdout-final');
|
||||
expect(failure?.message).toContain('stderr-final');
|
||||
expect(failure?.message).toContain('original owned startup failure');
|
||||
expect(failure!.message.length).toBeLessThan(130_000);
|
||||
expect(Date.now() - started).toBeLessThan(5000);
|
||||
expect(await proc!.exited).toBe(23);
|
||||
expect(fs.existsSync(tempDir)).toBe(false);
|
||||
}, 10_000);
|
||||
|
||||
test('the single setup deadline stops and reaps a child that never becomes ready', async () => {
|
||||
let proc: DaemonProcess | undefined;
|
||||
let tempDir = '';
|
||||
let failure: Error | undefined;
|
||||
try {
|
||||
await spawnDaemon({ setupWorkMs: 100, launch: env => {
|
||||
tempDir = path.dirname(env.BROWSE_STATE_FILE!);
|
||||
proc = Bun.spawn([process.execPath, '-e', 'setInterval(() => {}, 1000)'], {
|
||||
env, stdio: ['ignore', 'pipe', 'pipe'],
|
||||
});
|
||||
return proc;
|
||||
} });
|
||||
} catch (error) { failure = error as Error; }
|
||||
expect(failure?.message).toContain('Daemon did not become ready within 100ms');
|
||||
expect(proc!.exitCode !== null || proc!.signalCode !== null).toBe(true);
|
||||
expect(fs.existsSync(tempDir)).toBe(false);
|
||||
}, 5000);
|
||||
|
||||
test('state from a different PID cannot authorize a health endpoint', async () => {
|
||||
let proc: DaemonProcess | undefined;
|
||||
let tempDir = '';
|
||||
let failure: Error | undefined;
|
||||
try {
|
||||
await spawnDaemon({ launch: env => {
|
||||
tempDir = path.dirname(env.BROWSE_STATE_FILE!);
|
||||
proc = Bun.spawn([process.execPath, '-e', `
|
||||
require('node:fs').writeFileSync(process.env.BROWSE_STATE_FILE,
|
||||
JSON.stringify({ pid: process.pid + 1, port: 1, token: 'fixture-only' }));
|
||||
setInterval(() => {}, 1000);
|
||||
`], { env, stdio: ['ignore', 'pipe', 'pipe'] });
|
||||
return proc;
|
||||
} });
|
||||
} catch (error) { failure = error as Error; }
|
||||
expect(failure?.message).toContain('Daemon state does not identify the owned child');
|
||||
expect(proc!.exitCode !== null || proc!.signalCode !== null).toBe(true);
|
||||
expect(fs.existsSync(tempDir)).toBe(false);
|
||||
}, 5000);
|
||||
});
|
||||
|
||||
@@ -27,9 +27,44 @@ import * as path from 'path';
|
||||
|
||||
const ROOT = path.resolve(import.meta.dir, '../..');
|
||||
const SERVER_ENTRY = path.join(ROOT, 'browse/src/server.ts');
|
||||
const CLEANUP_GRACE_MS = 1000;
|
||||
// Reserve cleanup and diagnostic reporting inside the unchanged 30s hook.
|
||||
const SETUP_WORK_MS = 28_000;
|
||||
|
||||
type DaemonProcess = Bun.Subprocess<'ignore', 'pipe', 'pipe'>;
|
||||
|
||||
// Drain immediately so a noisy startup cannot block on an unread pipe. Keep
|
||||
// bounded diagnostic tails; setup failures print these into the shard log.
|
||||
function captureOutput(stream: ReadableStream<Uint8Array>) {
|
||||
let tail = '';
|
||||
let finished = false;
|
||||
const reader = stream.getReader();
|
||||
const done = (async () => {
|
||||
const decoder = new TextDecoder();
|
||||
try {
|
||||
for (;;) {
|
||||
const { done, value } = await reader.read();
|
||||
if (done) break;
|
||||
tail = (tail + decoder.decode(value, { stream: true })).slice(-64_000);
|
||||
}
|
||||
tail = (tail + decoder.decode()).slice(-64_000);
|
||||
} catch (error) {
|
||||
tail += `\n[output capture failed: ${error instanceof Error ? error.message : String(error)}]`;
|
||||
} finally { finished = true; reader.releaseLock(); }
|
||||
})();
|
||||
return { done, isFinished: () => finished, text: () => tail, cancel: () => {
|
||||
if (finished) return;
|
||||
tail += '\n[output incomplete: cleanup grace expired]';
|
||||
void reader.cancel().catch(() => {});
|
||||
} };
|
||||
}
|
||||
|
||||
type OutputCapture = ReturnType<typeof captureOutput>;
|
||||
|
||||
interface DaemonHandle {
|
||||
proc: ReturnType<typeof Bun.spawn>;
|
||||
proc: DaemonProcess;
|
||||
stdout: OutputCapture;
|
||||
stderr: OutputCapture;
|
||||
localPort: number;
|
||||
tunnelPort: number;
|
||||
rootToken: string;
|
||||
@@ -39,41 +74,42 @@ interface DaemonHandle {
|
||||
localUrl: string;
|
||||
tunnelUrl: string;
|
||||
attemptsLogPath: string;
|
||||
output: Promise<[string, string]>;
|
||||
}
|
||||
|
||||
async function waitForReady(
|
||||
proc: ReturnType<typeof Bun.spawn>, stateFile: string, timeoutMs = 20_000,
|
||||
): Promise<{ port: number; token: string }> {
|
||||
const deadline = Date.now() + timeoutMs;
|
||||
let lastError = '';
|
||||
while (Date.now() < deadline && proc.exitCode === null) {
|
||||
try {
|
||||
// Only this daemon's published state identifies its bound listener.
|
||||
const state = JSON.parse(fs.readFileSync(stateFile, 'utf-8'));
|
||||
if (state.pid !== proc.pid || !Number.isInteger(state.port) || state.port < 1 || state.port > 65535 ||
|
||||
typeof state.token !== 'string' || !state.token) {
|
||||
throw new Error('State does not identify this test daemon');
|
||||
async function waitForReady(proc: DaemonProcess, stateFile: string, assertRunning: () => void, signal: AbortSignal): Promise<{ port: number; token: string }> {
|
||||
for (;;) {
|
||||
signal.throwIfAborted();
|
||||
assertRunning();
|
||||
let state: { pid?: unknown; port?: unknown; token?: unknown } | undefined;
|
||||
try { state = JSON.parse(fs.readFileSync(stateFile, 'utf8')); }
|
||||
catch (error) { if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error; }
|
||||
if (state !== undefined) {
|
||||
if (!state || state.pid !== proc.pid || typeof state.port !== 'number' ||
|
||||
!Number.isInteger(state.port) || state.port < 1 || state.port > 65535 ||
|
||||
typeof state.token !== 'string' || !state.token.length) {
|
||||
throw new Error('Daemon state does not identify the owned child with a valid port and token');
|
||||
}
|
||||
const resp = await fetch(`http://127.0.0.1:${state.port}/health`, {
|
||||
signal: AbortSignal.timeout(1000),
|
||||
});
|
||||
await resp.arrayBuffer();
|
||||
if (resp.ok) return state;
|
||||
lastError = `Health returned HTTP ${resp.status}`;
|
||||
} catch (error) {
|
||||
lastError = String(error);
|
||||
let ready = false;
|
||||
try {
|
||||
const resp = await fetch(`http://127.0.0.1:${state.port}/health`, {
|
||||
signal: AbortSignal.any([signal, AbortSignal.timeout(1000)]),
|
||||
});
|
||||
ready = resp.ok;
|
||||
void resp.body?.cancel().catch(() => {});
|
||||
} catch { /* not ready yet; the single setup deadline still applies */ }
|
||||
signal.throwIfAborted();
|
||||
assertRunning();
|
||||
if (ready) return { port: state.port, token: state.token };
|
||||
}
|
||||
await new Promise(r => setTimeout(r, 200));
|
||||
}
|
||||
throw new Error(`Daemon did not become ready within ${timeoutMs}ms (exit=${proc.exitCode}): ${lastError}`);
|
||||
}
|
||||
|
||||
async function waitForTunnelPort(
|
||||
proc: ReturnType<typeof Bun.spawn>, stateFile: string, timeoutMs = 20_000,
|
||||
): Promise<number> {
|
||||
async function waitForTunnelPort(proc: DaemonProcess, stateFile: string, assertRunning: () => void, signal: AbortSignal, timeoutMs = 20_000): Promise<number> {
|
||||
const deadline = Date.now() + timeoutMs;
|
||||
while (Date.now() < deadline && proc.exitCode === null) {
|
||||
while (Date.now() < deadline) {
|
||||
signal.throwIfAborted();
|
||||
assertRunning();
|
||||
try {
|
||||
const state = JSON.parse(fs.readFileSync(stateFile, 'utf-8'));
|
||||
if (state.pid === proc.pid && Number.isInteger(state.tunnelLocalPort) &&
|
||||
@@ -83,83 +119,140 @@ async function waitForTunnelPort(
|
||||
}
|
||||
await new Promise(r => setTimeout(r, 200));
|
||||
}
|
||||
throw new Error(`Tunnel local port did not appear in ${stateFile} within ${timeoutMs}ms (exit=${proc.exitCode})`);
|
||||
throw new Error(`Tunnel local port did not appear in ${stateFile} within ${timeoutMs}ms`);
|
||||
}
|
||||
|
||||
async function spawnDaemonWithTunnel(): Promise<DaemonHandle> {
|
||||
async function stopProcess(proc: DaemonProcess, stdout: OutputCapture, stderr: OutputCapture): Promise<void> {
|
||||
let killError: unknown;
|
||||
if (proc.exitCode === null && proc.signalCode === null) {
|
||||
try { proc.kill('SIGKILL'); } catch (error) { killError = error; }
|
||||
}
|
||||
let timer: ReturnType<typeof setTimeout> | undefined;
|
||||
const exited = proc.exited;
|
||||
let exitSettled = false;
|
||||
void exited.then(() => { exitSettled = true; }, () => {});
|
||||
try {
|
||||
const settled = await Promise.race([
|
||||
Promise.all([exited, stdout.done, stderr.done]).then(() => true),
|
||||
new Promise<false>(resolve => { timer = setTimeout(() => resolve(false), CLEANUP_GRACE_MS); }),
|
||||
]);
|
||||
if (!settled) {
|
||||
const waits = `exit=${exitSettled ? 'settled' : 'pending'}; stdout=${stdout.isFinished() ? 'finished' : 'pending'}; stderr=${stderr.isFinished() ? 'finished' : 'pending'}`;
|
||||
stdout.cancel();
|
||||
stderr.cancel();
|
||||
throw new Error([
|
||||
`owned child or output did not settle within ${CLEANUP_GRACE_MS}ms cleanup grace`,
|
||||
`Cleanup waits: ${waits}`,
|
||||
`Owned daemon PID: ${proc.pid}; exit: ${proc.exitCode ?? 'none'}; signal: ${proc.signalCode ?? 'none'}`,
|
||||
...(killError ? [`Kill attempt failed: ${String(killError)}`] : []),
|
||||
`stdout tail:\n${stdout.text() || '(empty)'}`,
|
||||
`stderr tail:\n${stderr.text() || '(empty)'}`,
|
||||
].join('\n'));
|
||||
}
|
||||
} finally { if (timer) clearTimeout(timer); }
|
||||
}
|
||||
|
||||
async function spawnDaemonWithTunnel(options: {
|
||||
// Fixture-local injection exercises startup failures with real free children.
|
||||
launch?: (env: NodeJS.ProcessEnv) => DaemonProcess;
|
||||
setupWorkMs?: number;
|
||||
} = {}): Promise<DaemonHandle> {
|
||||
// Isolate this test's analytics + denial log directory so we can assert on a
|
||||
// fresh attempts.jsonl without colliding with the user's real ~/.gstack.
|
||||
const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'pair-agent-tunnel-eval-'));
|
||||
const stateFile = path.join(tempDir, 'browse.json');
|
||||
const fakeHome = path.join(tempDir, 'home');
|
||||
fs.mkdirSync(fakeHome, { recursive: true });
|
||||
const attemptsLogPath = path.join(fakeHome, '.gstack', 'security', 'attempts.jsonl');
|
||||
|
||||
const proc = Bun.spawn(['bun', 'run', SERVER_ENTRY], {
|
||||
cwd: ROOT,
|
||||
env: {
|
||||
...process.env,
|
||||
HOME: fakeHome,
|
||||
BROWSE_HEADLESS_SKIP: '1',
|
||||
BROWSE_TUNNEL_LOCAL_ONLY: '1',
|
||||
BROWSE_PORT: '0', // Use the daemon's checked allocator, then discover its actual port.
|
||||
BROWSE_STATE_FILE: stateFile,
|
||||
BROWSE_PARENT_PID: '0',
|
||||
BROWSE_IDLE_TIMEOUT: '600000',
|
||||
},
|
||||
stdio: ['ignore', 'pipe', 'pipe'],
|
||||
let proc: DaemonProcess | undefined;
|
||||
let stdout: OutputCapture | undefined;
|
||||
let stderr: OutputCapture | undefined;
|
||||
const controller = new AbortController();
|
||||
const workMs = Math.min(options.setupWorkMs ?? SETUP_WORK_MS, SETUP_WORK_MS);
|
||||
let workTimer: ReturnType<typeof setTimeout>;
|
||||
const expired = new Promise<never>((_, reject) => {
|
||||
workTimer = setTimeout(() => {
|
||||
const error = new Error(`Daemon setup timed out after ${workMs}ms`);
|
||||
controller.abort(error);
|
||||
reject(error);
|
||||
}, workMs);
|
||||
});
|
||||
|
||||
const output = Promise.all([new Response(proc.stdout).text(), new Response(proc.stderr).text()]);
|
||||
try {
|
||||
const state = await waitForReady(proc, stateFile);
|
||||
const localPort = state.port;
|
||||
const localUrl = `http://127.0.0.1:${localPort}`;
|
||||
const tunnelPort = await waitForTunnelPort(proc, stateFile);
|
||||
const tunnelUrl = `http://127.0.0.1:${tunnelPort}`;
|
||||
return await Promise.race([expired, (async () => {
|
||||
fs.mkdirSync(fakeHome, { recursive: true });
|
||||
const env = {
|
||||
...process.env,
|
||||
HOME: fakeHome,
|
||||
BROWSE_HEADLESS_SKIP: '1',
|
||||
BROWSE_TUNNEL_LOCAL_ONLY: '1',
|
||||
BROWSE_PORT: '0', // Let the owned daemon choose and publish a checked port.
|
||||
BROWSE_STATE_FILE: stateFile,
|
||||
BROWSE_PARENT_PID: '0',
|
||||
BROWSE_IDLE_TIMEOUT: '600000',
|
||||
};
|
||||
proc = options.launch ? options.launch(env) : Bun.spawn(['bun', 'run', SERVER_ENTRY], {
|
||||
cwd: ROOT, env, stdio: ['ignore', 'pipe', 'pipe'],
|
||||
});
|
||||
stdout = captureOutput(proc.stdout);
|
||||
stderr = captureOutput(proc.stderr);
|
||||
let exitCode: number | undefined;
|
||||
void proc.exited.then(code => { exitCode = code; });
|
||||
const assertRunning = () => {
|
||||
if (exitCode !== undefined) throw new Error(`Daemon exited before setup completed (code ${exitCode}, signal ${proc!.signalCode ?? 'none'})`);
|
||||
};
|
||||
|
||||
// Exchange this daemon's root token for a scoped token via /pair → /connect.
|
||||
const rootToken = state.token;
|
||||
const pairResp = await fetch(`${localUrl}/pair`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${rootToken}` },
|
||||
body: JSON.stringify({ clientId: 'tunnel-eval' }),
|
||||
});
|
||||
if (!pairResp.ok) throw new Error(`/pair failed: ${pairResp.status}`);
|
||||
const { setup_key } = await pairResp.json() as any;
|
||||
const state = await waitForReady(proc, stateFile, assertRunning, controller.signal);
|
||||
const localPort = state.port;
|
||||
const localUrl = `http://127.0.0.1:${localPort}`;
|
||||
const tunnelPort = await waitForTunnelPort(proc, stateFile, assertRunning, controller.signal);
|
||||
const tunnelUrl = `http://127.0.0.1:${tunnelPort}`;
|
||||
controller.signal.throwIfAborted();
|
||||
assertRunning();
|
||||
|
||||
const connectResp = await fetch(`${localUrl}/connect`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ setup_key }),
|
||||
});
|
||||
if (!connectResp.ok) throw new Error(`/connect failed: ${connectResp.status}`);
|
||||
const { token: scopedToken } = await connectResp.json() as any;
|
||||
// Read the root token, then exchange it for a scoped token via /pair → /connect.
|
||||
const rootToken = state.token;
|
||||
|
||||
return { proc, localPort, tunnelPort, rootToken, scopedToken, stateFile, tempDir, localUrl, tunnelUrl, attemptsLogPath, output };
|
||||
} catch (error) {
|
||||
// A failed beforeAll never hands its daemon to afterAll for cleanup.
|
||||
try {
|
||||
try { proc.kill('SIGKILL'); } catch {}
|
||||
await proc.exited;
|
||||
const [stdout, stderr] = await output;
|
||||
const errorFile = path.join(tempDir, 'browse-startup-error.log');
|
||||
const startupError = fs.existsSync(errorFile) ? fs.readFileSync(errorFile, 'utf-8') : '';
|
||||
throw new Error(`${error}\n${startupError}\n${stderr}\n${stdout}`);
|
||||
} finally {
|
||||
fs.rmSync(tempDir, { recursive: true, force: true });
|
||||
}
|
||||
}
|
||||
const pairResp = await fetch(`${localUrl}/pair`, {
|
||||
method: 'POST', signal: controller.signal,
|
||||
headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${rootToken}` },
|
||||
body: JSON.stringify({ clientId: 'tunnel-eval' }),
|
||||
});
|
||||
if (!pairResp.ok) throw new Error(`/pair failed: ${pairResp.status}`);
|
||||
const { setup_key } = await pairResp.json() as any;
|
||||
|
||||
controller.signal.throwIfAborted();
|
||||
const connectResp = await fetch(`${localUrl}/connect`, {
|
||||
method: 'POST', signal: controller.signal,
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ setup_key }),
|
||||
});
|
||||
if (!connectResp.ok) throw new Error(`/connect failed: ${connectResp.status}`);
|
||||
const { token: scopedToken } = await connectResp.json() as any;
|
||||
|
||||
controller.signal.throwIfAborted();
|
||||
return { proc, stdout, stderr, localPort, tunnelPort, rootToken, scopedToken, stateFile, tempDir, localUrl, tunnelUrl, attemptsLogPath };
|
||||
})()]);
|
||||
} catch (cause) {
|
||||
let cleanupError: unknown;
|
||||
try { if (proc && stdout && stderr) await stopProcess(proc, stdout, stderr); }
|
||||
catch (error) { cleanupError = error; }
|
||||
let startupError = '';
|
||||
try { startupError = fs.readFileSync(path.join(tempDir, 'browse-startup-error.log'), 'utf8').slice(-64_000); } catch { /* may fail before writing it */ }
|
||||
try { fs.rmSync(tempDir, { recursive: true, force: true }); }
|
||||
catch (error) { cleanupError ??= error; }
|
||||
throw new Error([
|
||||
cause instanceof Error ? cause.message : String(cause),
|
||||
`Owned daemon PID: ${proc?.pid ?? 'not spawned'}; exit: ${proc?.exitCode ?? 'none'}; signal: ${proc?.signalCode ?? 'none'}`,
|
||||
`stdout tail:\n${stdout?.text() || '(empty)'}`,
|
||||
`stderr tail:\n${stderr?.text() || '(empty)'}`,
|
||||
...(startupError ? [`startup error file:\n${startupError}`] : []),
|
||||
...(cleanupError ? [`cleanup failed: ${String(cleanupError)}`] : []),
|
||||
].join('\n'), { cause });
|
||||
} finally { clearTimeout(workTimer!); controller.abort(new Error('setup finished')); }
|
||||
}
|
||||
|
||||
async function killDaemon(handle: DaemonHandle): Promise<void> {
|
||||
try { handle.proc.kill('SIGKILL'); } catch {}
|
||||
try {
|
||||
await handle.proc.exited;
|
||||
await handle.output;
|
||||
} finally {
|
||||
fs.rmSync(handle.tempDir, { recursive: true, force: true });
|
||||
}
|
||||
try { await stopProcess(handle.proc, handle.stdout, handle.stderr); }
|
||||
finally { fs.rmSync(handle.tempDir, { recursive: true, force: true }); }
|
||||
}
|
||||
|
||||
async function postCommand(baseUrl: string, token: string, body: any): Promise<{ status: number; bodyText: string }> {
|
||||
@@ -246,3 +339,163 @@ describe('pair-agent over tunnel surface — gate fires on the right surface onl
|
||||
expect(gotoResp.bodyText).not.toContain('is not allowed over the tunnel surface');
|
||||
});
|
||||
});
|
||||
|
||||
describe('tunnel fixture startup diagnostics and ownership', () => {
|
||||
test('an early child exit drains large output, reports its cause, and removes its workspace', async () => {
|
||||
let proc: DaemonProcess | undefined;
|
||||
let tempDir = '';
|
||||
const started = Date.now();
|
||||
let failure: Error | undefined;
|
||||
try {
|
||||
await spawnDaemonWithTunnel({ launch: env => {
|
||||
tempDir = path.dirname(env.BROWSE_STATE_FILE!);
|
||||
proc = Bun.spawn([process.execPath, '-e', `
|
||||
await new Promise(resolve => process.stdout.write('x'.repeat(256_000) + '\\nstdout-final\\n', resolve));
|
||||
await new Promise(resolve => process.stderr.write('y'.repeat(256_000) + '\\nstderr-final\\n', resolve));
|
||||
process.exit(23);
|
||||
`], { env, stdio: ['ignore', 'pipe', 'pipe'] });
|
||||
return proc;
|
||||
} });
|
||||
} catch (error) { failure = error as Error; }
|
||||
expect(failure?.message).toContain('Daemon exited before setup completed (code 23');
|
||||
expect(failure?.message).toContain('stdout-final');
|
||||
expect(failure?.message).toContain('stderr-final');
|
||||
expect(failure?.message).not.toContain('did not become ready within');
|
||||
expect(Date.now() - started).toBeLessThan(5000);
|
||||
expect(await proc!.exited).toBe(23);
|
||||
expect(fs.existsSync(tempDir)).toBe(false);
|
||||
}, 10_000);
|
||||
|
||||
test('a pairing failure stops the already-running owned child and retains startup diagnostics', async () => {
|
||||
let proc: DaemonProcess | undefined;
|
||||
let tempDir = '';
|
||||
let failure: Error | undefined;
|
||||
try {
|
||||
await spawnDaemonWithTunnel({ launch: env => {
|
||||
tempDir = path.dirname(env.BROWSE_STATE_FILE!);
|
||||
proc = Bun.spawn([process.execPath, '-e', `
|
||||
const fs = require('node:fs');
|
||||
const port = Number(process.env.BROWSE_PORT);
|
||||
const server = Bun.serve({ port, hostname: '127.0.0.1', fetch: req => new Response('fixture', {
|
||||
status: new URL(req.url).pathname === '/health' ? 200 : 503,
|
||||
}) });
|
||||
fs.writeFileSync(process.env.BROWSE_STATE_FILE, JSON.stringify({ pid: process.pid, port: server.port, token: 'fixture-only', tunnelLocalPort: server.port }));
|
||||
fs.writeFileSync(require('node:path').join(require('node:path').dirname(process.env.BROWSE_STATE_FILE), 'browse-startup-error.log'), 'owned startup diagnostic');
|
||||
console.error('owned child reached health');
|
||||
`], { env, stdio: ['ignore', 'pipe', 'pipe'] });
|
||||
return proc;
|
||||
} });
|
||||
} catch (error) { failure = error as Error; }
|
||||
expect(failure?.message).toContain('/pair failed: 503');
|
||||
expect(failure?.message).toContain('owned child reached health');
|
||||
expect(failure?.message).toContain('owned startup diagnostic');
|
||||
await proc!.exited;
|
||||
expect(proc!.exitCode !== null || proc!.signalCode !== null).toBe(true);
|
||||
expect(fs.existsSync(tempDir)).toBe(false);
|
||||
}, 10_000);
|
||||
|
||||
test('a launch exception still removes the temporary workspace', async () => {
|
||||
let tempDir = '';
|
||||
await expect(spawnDaemonWithTunnel({ launch: env => {
|
||||
tempDir = path.dirname(env.BROWSE_STATE_FILE!);
|
||||
throw new Error('owned launch failure');
|
||||
} })).rejects.toThrow('owned launch failure');
|
||||
expect(fs.existsSync(tempDir)).toBe(false);
|
||||
});
|
||||
|
||||
test.each([
|
||||
['/pair', 'request'], ['/pair', 'body'],
|
||||
['/connect', 'request'], ['/connect', 'body'],
|
||||
])('a stalled %s %s respects the setup deadline and cleans up', async (endpoint, phase) => {
|
||||
let proc: DaemonProcess | undefined;
|
||||
let tempDir = '';
|
||||
let failure: Error | undefined;
|
||||
const started = Date.now();
|
||||
try {
|
||||
await spawnDaemonWithTunnel({ setupWorkMs: 1000, launch: env => {
|
||||
tempDir = path.dirname(env.BROWSE_STATE_FILE!);
|
||||
proc = Bun.spawn([process.execPath, '-e', `
|
||||
const port = Number(process.env.BROWSE_PORT);
|
||||
const server = Bun.serve({ port, hostname: '127.0.0.1', fetch: req => {
|
||||
const pathname = new URL(req.url).pathname;
|
||||
if (pathname === '/health') return new Response('ready');
|
||||
if (pathname === ${JSON.stringify(endpoint)}) {
|
||||
console.error('stalled ' + pathname + ' ${phase}');
|
||||
if (${JSON.stringify(phase)} === 'request') return new Promise(() => {});
|
||||
return new Response(new ReadableStream({ start: controller => controller.enqueue(new TextEncoder().encode('{')) }), {
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
});
|
||||
}
|
||||
return Response.json({ setup_key: 'fixture-only' });
|
||||
} });
|
||||
require('node:fs').writeFileSync(process.env.BROWSE_STATE_FILE, JSON.stringify({ pid: process.pid, port: server.port, token: 'fixture-only', tunnelLocalPort: server.port }));
|
||||
`], { env, stdio: ['ignore', 'pipe', 'pipe'] });
|
||||
return proc;
|
||||
} });
|
||||
} catch (error) { failure = error as Error; }
|
||||
expect(failure?.message).toContain('Daemon setup timed out after 1000ms');
|
||||
expect(failure?.message).toContain(`stalled ${endpoint} ${phase}`);
|
||||
await proc!.exited;
|
||||
expect(proc!.exitCode !== null || proc!.signalCode !== null).toBe(true);
|
||||
expect(fs.existsSync(tempDir)).toBe(false);
|
||||
expect(Date.now() - started).toBeLessThan(5000);
|
||||
}, 10_000);
|
||||
|
||||
test('an inherited pipe that stays open is cancelled without hiding the original startup exit', async () => {
|
||||
let tempDir = '';
|
||||
let cancelled = false;
|
||||
const heldPipe = new ReadableStream<Uint8Array>({
|
||||
start: controller => controller.enqueue(new TextEncoder().encode('inherited stdout stayed open\n')),
|
||||
cancel: () => { cancelled = true; },
|
||||
});
|
||||
const started = Date.now();
|
||||
let failure: Error | undefined;
|
||||
try {
|
||||
await spawnDaemonWithTunnel({ launch: env => {
|
||||
tempDir = path.dirname(env.BROWSE_STATE_FILE!);
|
||||
const child = Bun.spawn([process.execPath, '-e', "console.error('primary startup failure'); process.exit(19);"],
|
||||
{ env, stdio: ['ignore', 'pipe', 'pipe'] });
|
||||
// Model an exited child whose descendant still holds stdout open;
|
||||
// no unrelated process is started or killed by this regression.
|
||||
return new Proxy(child, { get(target, property) {
|
||||
if (property === 'stdout') return heldPipe;
|
||||
const value = Reflect.get(target, property, target);
|
||||
return typeof value === 'function' ? value.bind(target) : value;
|
||||
} });
|
||||
} });
|
||||
} catch (error) { failure = error as Error; }
|
||||
expect(failure?.message).toContain('Daemon exited before setup completed (code 19');
|
||||
expect(failure?.message).toContain('primary startup failure');
|
||||
expect(failure?.message).toContain('inherited stdout stayed open');
|
||||
expect(failure?.message).toContain('output incomplete: cleanup grace expired');
|
||||
expect(failure?.message).toContain('cleanup failed:');
|
||||
expect(failure?.message).toContain('Cleanup waits: exit=settled; stdout=pending; stderr=finished');
|
||||
expect(cancelled).toBe(true);
|
||||
expect(fs.existsSync(tempDir)).toBe(false);
|
||||
expect(Date.now() - started).toBeLessThan(5000);
|
||||
}, 10_000);
|
||||
|
||||
test('cleanup distinguishes an unresolved exit waiter from already-finished output', async () => {
|
||||
const child = Bun.spawn([process.execPath, '-e', "console.log('exit-wait stdout'); console.error('exit-wait stderr'); process.exit(17);"],
|
||||
{ stdio: ['ignore', 'pipe', 'pipe'] });
|
||||
const stdout = captureOutput(child.stdout);
|
||||
const stderr = captureOutput(child.stderr);
|
||||
await Promise.all([child.exited, stdout.done, stderr.done]);
|
||||
const heldExit = new Promise<number>(() => {});
|
||||
// The real child is already reaped; only its exposed waiter is held.
|
||||
const held = new Proxy(child, { get(target, property) {
|
||||
if (property === 'exited') return heldExit;
|
||||
const value = Reflect.get(target, property, target);
|
||||
return typeof value === 'function' ? value.bind(target) : value;
|
||||
} });
|
||||
let failure: Error | undefined;
|
||||
try { await stopProcess(held, stdout, stderr); }
|
||||
catch (error) { failure = error as Error; }
|
||||
expect(failure?.message).toContain('did not settle within 1000ms cleanup grace');
|
||||
expect(failure?.message).toContain('Cleanup waits: exit=pending; stdout=finished; stderr=finished');
|
||||
expect(failure?.message).toContain(`Owned daemon PID: ${child.pid}; exit: 17; signal: none`);
|
||||
expect(failure?.message).toContain('stdout tail:\nexit-wait stdout');
|
||||
expect(failure?.message).toContain('stderr tail:\nexit-wait stderr');
|
||||
expect(child.exitCode).toBe(17);
|
||||
}, 10_000);
|
||||
});
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { describe, test, expect, beforeEach, beforeAll, afterAll } from 'bun:test';
|
||||
import * as fs from 'fs';
|
||||
import * as path from 'path';
|
||||
import * as os from 'os';
|
||||
import * as crypto from 'crypto';
|
||||
import {
|
||||
buildFetchHandler,
|
||||
@@ -33,7 +34,11 @@ import { resolveConfig } from '../src/config';
|
||||
// Use isProcessAlive's false branch by also testing with a PID that does
|
||||
// not exist (negative PID rejected by the OS).
|
||||
|
||||
const stateDir = resolveConfig().stateDir;
|
||||
const fixtureDir = fs.mkdtempSync(path.join(os.tmpdir(), 'gstack-server-embedder-'));
|
||||
const fixtureConfig = resolveConfig({ BROWSE_STATE_FILE: path.join(fixtureDir, 'state/browse.json') });
|
||||
const stateDir = fixtureConfig.stateDir;
|
||||
const savedChromiumProfile = process.env.CHROMIUM_PROFILE;
|
||||
beforeAll(() => { process.env.CHROMIUM_PROFILE = path.join(fixtureDir, 'chromium-profile'); });
|
||||
const PORT_FILE = path.join(stateDir, 'terminal-port');
|
||||
const TOKEN_FILE = path.join(stateDir, 'terminal-internal-token');
|
||||
const AGENT_RECORD_FILE = path.join(stateDir, 'terminal-agent-pid');
|
||||
@@ -49,7 +54,7 @@ function makeMinimalConfig(overrides: Partial<ServerConfig> = {}): ServerConfig
|
||||
return {
|
||||
authToken: token,
|
||||
browsePort: 34568,
|
||||
config: resolveConfig(),
|
||||
config: fixtureConfig,
|
||||
browserManager: new BrowserManager(),
|
||||
startTime: Date.now(),
|
||||
...overrides,
|
||||
@@ -97,6 +102,9 @@ afterAll(async () => {
|
||||
// suite died at file 47 with exit 0 and no summary — twice).
|
||||
await new Promise((r) => setTimeout(r, 3500));
|
||||
(process as any).exit = TRUE_EXIT;
|
||||
if (savedChromiumProfile === undefined) delete process.env.CHROMIUM_PROFILE;
|
||||
else process.env.CHROMIUM_PROFILE = savedChromiumProfile;
|
||||
fs.rmSync(fixtureDir, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
async function withStubs(
|
||||
@@ -143,43 +151,6 @@ function terminationCalls(
|
||||
}
|
||||
|
||||
describe('buildFetchHandler ownsTerminalAgent gate', () => {
|
||||
// shutdown() reads `path.dirname(config.stateFile)` from module-level config
|
||||
// (composition gap — see TODOS T9). So unlinks target the real state dir,
|
||||
// not a per-test temp dir. If a real gstack daemon is running on this host,
|
||||
// its terminal-port + terminal-internal-token + terminal-agent-pid live
|
||||
// where this test writes. Save + restore real-daemon file contents around
|
||||
// the whole suite so the test never clobbers a developer's running session.
|
||||
let realPortBackup: string | null = null;
|
||||
let realTokenBackup: string | null = null;
|
||||
let realAgentRecordBackup: string | null = null;
|
||||
|
||||
beforeAll(() => {
|
||||
realPortBackup = readIfExists(PORT_FILE);
|
||||
realTokenBackup = readIfExists(TOKEN_FILE);
|
||||
realAgentRecordBackup = readIfExists(AGENT_RECORD_FILE);
|
||||
});
|
||||
|
||||
afterAll(() => {
|
||||
if (realPortBackup !== null) {
|
||||
fs.mkdirSync(stateDir, { recursive: true });
|
||||
fs.writeFileSync(PORT_FILE, realPortBackup);
|
||||
} else {
|
||||
try { fs.unlinkSync(PORT_FILE); } catch {}
|
||||
}
|
||||
if (realTokenBackup !== null) {
|
||||
fs.mkdirSync(stateDir, { recursive: true });
|
||||
fs.writeFileSync(TOKEN_FILE, realTokenBackup);
|
||||
} else {
|
||||
try { fs.unlinkSync(TOKEN_FILE); } catch {}
|
||||
}
|
||||
if (realAgentRecordBackup !== null) {
|
||||
fs.mkdirSync(stateDir, { recursive: true });
|
||||
fs.writeFileSync(AGENT_RECORD_FILE, realAgentRecordBackup);
|
||||
} else {
|
||||
try { fs.unlinkSync(AGENT_RECORD_FILE); } catch {}
|
||||
}
|
||||
});
|
||||
|
||||
beforeEach(() => {
|
||||
__resetRegistry();
|
||||
__resetShuttingDown();
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { describe, test, expect, beforeEach, mock } from 'bun:test';
|
||||
import { describe, test, expect, beforeEach, beforeAll, afterAll, mock } from 'bun:test';
|
||||
import {
|
||||
resolveConfigFromEnv,
|
||||
buildFetchHandler,
|
||||
@@ -13,8 +13,19 @@ import { BrowserManager } from '../src/browser-manager';
|
||||
import { resolveConfig } from '../src/config';
|
||||
import * as crypto from 'crypto';
|
||||
import * as fs from 'node:fs';
|
||||
import * as os from 'node:os';
|
||||
import * as path from 'node:path';
|
||||
|
||||
const fixtureDir = fs.mkdtempSync(path.join(os.tmpdir(), 'gstack-server-factory-'));
|
||||
const fixtureConfig = resolveConfig({ BROWSE_STATE_FILE: path.join(fixtureDir, 'state/browse.json') });
|
||||
const savedChromiumProfile = process.env.CHROMIUM_PROFILE;
|
||||
beforeAll(() => { process.env.CHROMIUM_PROFILE = path.join(fixtureDir, 'chromium-profile'); });
|
||||
afterAll(() => {
|
||||
if (savedChromiumProfile === undefined) delete process.env.CHROMIUM_PROFILE;
|
||||
else process.env.CHROMIUM_PROFILE = savedChromiumProfile;
|
||||
fs.rmSync(fixtureDir, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
/**
|
||||
* Tests for the factory-export API surface added so gbrowser (phoenix) can
|
||||
* consume gstack as a submodule. The full buildFetchHandler hybrid hoist is
|
||||
@@ -205,8 +216,9 @@ function makeMinimalConfig(overrides: Partial<ServerConfig> = {}): ServerConfig
|
||||
return {
|
||||
authToken: token,
|
||||
browsePort: 34567,
|
||||
config: resolveConfig(),
|
||||
config: fixtureConfig,
|
||||
browserManager: new BrowserManager(),
|
||||
ownsTerminalAgent: false,
|
||||
startTime: Date.now(),
|
||||
...overrides,
|
||||
};
|
||||
@@ -225,6 +237,42 @@ describe('buildFetchHandler factory contract', () => {
|
||||
expect(typeof handle.stopListeners).toBe('function');
|
||||
});
|
||||
|
||||
test('shutdown removes its instance state while preserving unrelated global state', () => {
|
||||
// Import in a child so module-level config resolves to a private decoy,
|
||||
// independent of this Bun process's cached imports and any real daemon.
|
||||
const globalState = path.join(fixtureDir, 'global/browse.json');
|
||||
const instanceState = path.join(fixtureDir, 'instance/browse.json');
|
||||
const closedMarker = path.join(fixtureDir, 'instance-closed');
|
||||
fs.mkdirSync(path.dirname(globalState), { recursive: true });
|
||||
fs.mkdirSync(path.dirname(instanceState), { recursive: true });
|
||||
fs.writeFileSync(globalState, 'unrelated daemon state');
|
||||
fs.writeFileSync(instanceState, 'owned instance state');
|
||||
const script = `
|
||||
import fs from 'node:fs';
|
||||
import { buildFetchHandler } from ${JSON.stringify(path.resolve(__dirname, '../src/server.ts'))};
|
||||
import { resolveConfig } from ${JSON.stringify(path.resolve(__dirname, '../src/config.ts'))};
|
||||
const handle = buildFetchHandler({
|
||||
authToken: 'factory-shutdown-ownership-test', browsePort: 34567,
|
||||
config: resolveConfig({ BROWSE_STATE_FILE: ${JSON.stringify(instanceState)} }),
|
||||
browserManager: {
|
||||
getConnectionMode: () => 'launched', isWatching: () => false,
|
||||
close: async () => fs.writeFileSync(${JSON.stringify(closedMarker)}, 'closed'),
|
||||
onDisconnect: null,
|
||||
},
|
||||
ownsTerminalAgent: false, startTime: Date.now(),
|
||||
});
|
||||
await handle.shutdown(0);
|
||||
`;
|
||||
const result = Bun.spawnSync([process.execPath, '--eval', script], {
|
||||
env: { ...process.env, BROWSE_STATE_FILE: globalState },
|
||||
stdout: 'pipe', stderr: 'pipe', timeout: 5000,
|
||||
});
|
||||
expect(result.exitCode, result.stderr.toString()).toBe(0);
|
||||
expect(fs.readFileSync(closedMarker, 'utf8')).toBe('closed');
|
||||
expect(fs.existsSync(instanceState)).toBe(false);
|
||||
expect(fs.readFileSync(globalState, 'utf8')).toBe('unrelated daemon state');
|
||||
});
|
||||
|
||||
test('2a. cfg.authToken authenticates /health (positive — bearer accepted)', async () => {
|
||||
const cfg = makeMinimalConfig();
|
||||
const handle = buildFetchHandler(cfg);
|
||||
|
||||
@@ -10,8 +10,8 @@
|
||||
* 5. resize control message — terminal accepts and stays alive.
|
||||
* 6. close behavior — sending close terminates the PTY child.
|
||||
*
|
||||
* Uses /bin/bash via BROWSE_TERMINAL_BINARY override so CI doesn't need
|
||||
* the `claude` binary installed.
|
||||
* Uses a CLI-compatible wrapper around /bin/bash via BROWSE_TERMINAL_BINARY
|
||||
* so CI doesn't need the `claude` binary installed.
|
||||
*/
|
||||
|
||||
import { describe, test, expect, beforeAll, afterAll } from 'bun:test';
|
||||
@@ -54,12 +54,25 @@ beforeAll(() => {
|
||||
const stateFile = path.join(stateDir, 'browse.json');
|
||||
// browse.json must exist so the agent's readBrowseToken doesn't throw.
|
||||
fs.writeFileSync(stateFile, JSON.stringify({ token: 'test-browse-token' }));
|
||||
const terminalCli = path.join(stateDir, 'terminal-cli');
|
||||
// Production supplies Claude's CLI arguments. Validate that contract before
|
||||
// handing the real PTY to Bash; bare Bash rejects --append-system-prompt.
|
||||
fs.writeFileSync(terminalCli, [
|
||||
`#!${BASH}`,
|
||||
'if [ "$#" -ne 2 ] || [ "$1" != "--append-system-prompt" ] || [ -z "$2" ]; then',
|
||||
' echo "unexpected terminal CLI arguments" >&2; exit 64',
|
||||
'fi',
|
||||
'shift 2',
|
||||
`exec ${BASH} --noprofile --norc "$@"`,
|
||||
'',
|
||||
].join('\n'));
|
||||
fs.chmodSync(terminalCli, 0o755);
|
||||
agentProc = Bun.spawn(['bun', 'run', AGENT_SCRIPT], {
|
||||
env: {
|
||||
...process.env,
|
||||
BROWSE_STATE_FILE: stateFile,
|
||||
BROWSE_SERVER_PORT: '0', // not used in this test
|
||||
BROWSE_TERMINAL_BINARY: BASH,
|
||||
BROWSE_TERMINAL_BINARY: terminalCli,
|
||||
},
|
||||
stdio: ['ignore', 'pipe', 'pipe'],
|
||||
});
|
||||
@@ -158,8 +171,10 @@ describe('terminal-agent: PTY round-trip via real WebSocket (Cookie auth)', () =
|
||||
|
||||
ws.addEventListener('close', () => { closed = true; });
|
||||
|
||||
// Lazy-spawn trigger: any binary frame causes the agent to spawn /bin/bash.
|
||||
ws.send(new TextEncoder().encode('echo hello-pty-world\nexit\n'));
|
||||
// Lazy-spawn trigger: any binary frame causes the agent to spawn the fixture CLI.
|
||||
// The expected token must not occur in the input: PTY echo alone is not
|
||||
// proof that the child accepted its arguments and executed the command.
|
||||
ws.send(new TextEncoder().encode("printf 'hello-%s-world\\n' pty\nexit\n"));
|
||||
|
||||
// Wait up to 5s for output and shutdown.
|
||||
await new Promise<void>((resolve) => {
|
||||
@@ -310,3 +325,167 @@ describe('terminal-agent: PTY round-trip via real WebSocket (Cookie auth)', () =
|
||||
try { ws.close(); } catch {}
|
||||
});
|
||||
});
|
||||
|
||||
// Route-level lifecycle regressions use the same owned Bash CLI fixture and
|
||||
// real PTY/WS transport above. Every expected result is absent from typed input.
|
||||
describe('terminal-agent: owned PTY completion and restart', () => {
|
||||
async function internal(route: string, body: unknown) {
|
||||
return fetch(`http://127.0.0.1:${agentPort}/internal/${route}`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${internalToken}` },
|
||||
body: JSON.stringify(body),
|
||||
});
|
||||
}
|
||||
|
||||
async function until(check: () => boolean | Promise<boolean>, label: string) {
|
||||
const deadline = Date.now() + 5000;
|
||||
while (!(await check())) {
|
||||
if (Date.now() >= deadline) throw new Error(`timed out waiting for ${label}`);
|
||||
await Bun.sleep(10);
|
||||
}
|
||||
}
|
||||
|
||||
async function attach(sessionId: string, token: string) {
|
||||
const granted = await internal('grant', { token, sessionId });
|
||||
expect(granted.status).toBe(200);
|
||||
const ws = new WebSocket(`ws://127.0.0.1:${agentPort}/ws`, {
|
||||
headers: { Origin: 'chrome-extension://test-extension-id', Cookie: `gstack_pty=${token}` },
|
||||
} as any);
|
||||
const events: Array<{ type: string; [key: string]: any }> = [];
|
||||
let output = '';
|
||||
let closed: number | null = null;
|
||||
ws.addEventListener('message', (event: any) => {
|
||||
if (typeof event.data === 'string') events.push(JSON.parse(event.data));
|
||||
else {
|
||||
const chunk = new TextDecoder().decode(event.data);
|
||||
output += chunk;
|
||||
events.push({ type: 'output', text: chunk });
|
||||
}
|
||||
});
|
||||
ws.addEventListener('close', event => { closed = event.code; events.push({ type: 'closed', code: event.code }); });
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
const timer = setTimeout(() => reject(new Error('ws never opened')), 5000);
|
||||
ws.addEventListener('open', () => { clearTimeout(timer); resolve(); });
|
||||
ws.addEventListener('error', () => { clearTimeout(timer); reject(new Error('ws error')); });
|
||||
});
|
||||
return { ws, events, output: () => output, closed: () => closed };
|
||||
}
|
||||
|
||||
test('restart closes the old socket and grants a fresh child only to its replacement', async () => {
|
||||
const sessionId = 'owned-restart-session';
|
||||
const old = await attach(sessionId, 'owned-restart-old-token-long-enough');
|
||||
let replacement: Awaited<ReturnType<typeof attach>> | undefined;
|
||||
try {
|
||||
old.ws.send(new TextEncoder().encode("printf 'restart-%s:%s\\n' old $$\n"));
|
||||
await until(() => /restart-old:\d+\r?\n/.test(old.output()), 'old child output');
|
||||
const oldPid = /restart-old:(\d+)\r?\n/.exec(old.output())![1];
|
||||
const response = await internal('restart', { sessionId });
|
||||
expect(response.status).toBe(200);
|
||||
expect(await response.json()).toEqual({ killed: 1 });
|
||||
// A message can already be queued while the close handshake completes.
|
||||
try { old.ws.send(new TextEncoder().encode("printf 'restart-%s\\n' forbidden\n")); } catch {}
|
||||
await until(() => old.closed() !== null, 'old socket close');
|
||||
expect(old.closed()).toBe(4001);
|
||||
expect(old.output()).not.toContain('restart-forbidden');
|
||||
|
||||
replacement = await attach(sessionId, 'owned-restart-new-token-long-enough');
|
||||
replacement.ws.send(new TextEncoder().encode("printf 'restart-%s:%s\\n' new $$\nexit\n"));
|
||||
await until(() => replacement!.closed() !== null, 'replacement completion');
|
||||
expect(replacement.output()).toContain('restart-new:');
|
||||
const newPid = /restart-new:(\d+)/.exec(replacement.output())?.[1];
|
||||
expect(newPid).toBeDefined();
|
||||
expect(newPid).not.toBe(oldPid);
|
||||
expect(replacement.events.find(event => event.type === 'pty-exit')?.process.exitCode).toBe(0);
|
||||
expect(old.output()).not.toContain('restart-new:');
|
||||
} finally {
|
||||
try { old.ws.close(1000); } catch {}
|
||||
try { replacement?.ws.close(1000); } catch {}
|
||||
await internal('restart', { sessionId });
|
||||
}
|
||||
});
|
||||
|
||||
test('replacement attachment ignores stale input and survives the old socket close', async () => {
|
||||
const sessionId = 'owned-overlapping-attachment-session';
|
||||
const oldToken = 'owned-overlapping-old-token-long-enough';
|
||||
const old = await attach(sessionId, oldToken);
|
||||
let replacement: Awaited<ReturnType<typeof attach>> | undefined;
|
||||
try {
|
||||
old.ws.send(new TextEncoder().encode("printf 'overlap-%s:%s\\n' original $$\n"));
|
||||
await until(() => /overlap-original:\d+\r?\n/.test(old.output()), 'original child output');
|
||||
const pid = /overlap-original:(\d+)\r?\n/.exec(old.output())![1];
|
||||
|
||||
// Reattach while the original is still open. The replay proves open()
|
||||
// has replaced liveWs before we deliver the stale socket's final input.
|
||||
replacement = await attach(sessionId, 'owned-overlapping-new-token-long-enough');
|
||||
await until(() => replacement!.events.some(event => event.type === 'reattach-begin')
|
||||
&& replacement!.output().includes(`overlap-original:${pid}`), 'replacement replay');
|
||||
expect(old.ws.readyState).toBe(WebSocket.OPEN);
|
||||
old.ws.send(new TextEncoder().encode("printf 'overlap-%s\\n' forbidden\n"));
|
||||
old.ws.close(1000);
|
||||
// Frames on the old connection are ordered: its close follows the late
|
||||
// input. No guessed sleep is needed before probing replacement ownership.
|
||||
await until(() => old.closed() !== null, 'stale socket close');
|
||||
expect(old.closed()).toBe(1000);
|
||||
expect(replacement.closed()).toBeNull();
|
||||
const revoked = await fetch(`http://127.0.0.1:${agentPort}/ws`, {
|
||||
headers: { Origin: 'chrome-extension://test-extension-id', Cookie: `gstack_pty=${oldToken}` },
|
||||
});
|
||||
expect(revoked.status).toBe(401);
|
||||
|
||||
replacement.ws.send(new TextEncoder().encode("printf 'overlap-%s:%s\\n' current $$\nexit\n"));
|
||||
await until(() => replacement!.closed() !== null, 'replacement child completion');
|
||||
expect(replacement.output()).toContain(`overlap-current:${pid}`);
|
||||
expect(replacement.output()).not.toContain('overlap-forbidden');
|
||||
expect(replacement.events.find(event => event.type === 'pty-exit')?.process.exitCode).toBe(0);
|
||||
expect(replacement.closed()).toBe(1000);
|
||||
expect(old.output()).not.toContain('overlap-current:');
|
||||
} finally {
|
||||
try { old.ws.close(1000); } catch {}
|
||||
try { replacement?.ws.close(1000); } catch {}
|
||||
await internal('restart', { sessionId });
|
||||
}
|
||||
});
|
||||
|
||||
test('completion while detached replays final output before closing without a new child', async () => {
|
||||
const sessionId = 'owned-detached-completion-session';
|
||||
const release = path.join(stateDir, 'release-detached-child');
|
||||
const quotedRelease = `'${release.replace(/'/g, "'\\''")}'`;
|
||||
const old = await attach(sessionId, 'owned-detached-old-token-long-enough');
|
||||
let replacement: Awaited<ReturnType<typeof attach>> | undefined;
|
||||
try {
|
||||
const command = `printf 'detached-%s:%s\\n' start $$; while [ ! -e ${quotedRelease} ]; do sleep 0.01; done; printf 'detached-%s:%s\\n' final $$; exit\n`;
|
||||
old.ws.send(new TextEncoder().encode(command));
|
||||
await until(() => /detached-start:\d+\r?\n/.test(old.output()), 'child waiting at release barrier');
|
||||
const pid = /detached-start:(\d+)\r?\n/.exec(old.output())![1];
|
||||
old.ws.close(1001);
|
||||
await until(() => old.closed() !== null, 'detach handshake');
|
||||
fs.writeFileSync(release, 'release\n');
|
||||
// Authenticated completion state proves BOTH native callbacks happened
|
||||
// while detached; no guessed post-exit sleep or early reattachment.
|
||||
await until(async () => {
|
||||
const health = await fetch(`http://127.0.0.1:${agentPort}/internal/healthz`, {
|
||||
headers: { Authorization: `Bearer ${internalToken}` },
|
||||
});
|
||||
return (await health.json()).completedSessions === 1;
|
||||
}, 'detached completion');
|
||||
|
||||
replacement = await attach(sessionId, 'owned-detached-new-token-long-enough');
|
||||
await until(() => replacement!.closed() !== null, 'replayed completion close');
|
||||
const kinds = replacement.events.map(event => event.type);
|
||||
expect(kinds).toEqual(['reattach-begin', 'output', 'pty-exit', 'closed']);
|
||||
expect(replacement.output()).toContain(`detached-start:${pid}`);
|
||||
expect(replacement.output()).toContain(`detached-final:${pid}`);
|
||||
const completion = replacement.events.find(event => event.type === 'pty-exit')!;
|
||||
expect(completion.process.exitCode).toBe(0);
|
||||
expect(completion.drainTimedOut).toBe(false);
|
||||
expect(completion.exitTimedOut).toBe(false);
|
||||
expect(completion.reader).not.toBeNull();
|
||||
expect(replacement.closed()).toBe(1000);
|
||||
} finally {
|
||||
fs.writeFileSync(release, 'release\n');
|
||||
try { old.ws.close(1000); } catch {}
|
||||
try { replacement?.ws.close(1000); } catch {}
|
||||
await internal('restart', { sessionId });
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
@@ -186,10 +186,12 @@ describe('Source-level guard: terminal-agent', () => {
|
||||
|
||||
test('cleanup escalates SIGINT to SIGKILL after 3s on close', () => {
|
||||
// disposeSession must be idempotent and use a SIGINT-then-SIGKILL pattern.
|
||||
const dispose = AGENT_SRC.slice(AGENT_SRC.indexOf('function disposeSession'));
|
||||
expect(dispose).toContain("'SIGINT'");
|
||||
expect(dispose).toContain("'SIGKILL'");
|
||||
expect(dispose).toContain('3000');
|
||||
const dispose = AGENT_SRC.slice(AGENT_SRC.indexOf('function disposeSession'), AGENT_SRC.indexOf('function sendPtyCompletion'));
|
||||
const lifecycle = fs.readFileSync(path.join(import.meta.dir, '../src/terminal-pty-lifecycle.ts'), 'utf-8');
|
||||
expect(dispose).toContain('disposePtyProcess(proc)');
|
||||
expect(lifecycle).toContain("'SIGINT'");
|
||||
expect(lifecycle).toContain("'SIGKILL'");
|
||||
expect(lifecycle).toContain('PTY_SHUTDOWN_GRACE_MS = 3000');
|
||||
});
|
||||
|
||||
test('tabState frames write tabs.json + active-tab.json', () => {
|
||||
|
||||
@@ -0,0 +1,212 @@
|
||||
import { describe, expect, test } from 'bun:test';
|
||||
import {
|
||||
createPtyLifecycle, disposePtyProcess, ptyCompletionReason,
|
||||
PTY_SHUTDOWN_GRACE_MS, type PtyCompletion,
|
||||
} from '../src/terminal-pty-lifecycle';
|
||||
|
||||
function clock() {
|
||||
const pending = new Set<() => void>();
|
||||
const delays: number[] = [];
|
||||
return {
|
||||
pending, delays,
|
||||
schedule(callback: () => void, delay: number) {
|
||||
delays.push(delay);
|
||||
pending.add(callback);
|
||||
return { cancel() { pending.delete(callback); } };
|
||||
},
|
||||
expire() {
|
||||
for (const callback of [...pending]) {
|
||||
pending.delete(callback);
|
||||
callback();
|
||||
}
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function fixture() {
|
||||
const time = clock();
|
||||
const events: string[] = [];
|
||||
const completions: PtyCompletion[] = [];
|
||||
const lifecycle = createPtyLifecycle({
|
||||
schedule: time.schedule,
|
||||
onData(chunk) { events.push(chunk.toString()); },
|
||||
onComplete(result) { completions.push(result); events.push('CLOSE'); },
|
||||
});
|
||||
return { time, events, completions, lifecycle };
|
||||
}
|
||||
|
||||
describe('PTY process exit and output completion', () => {
|
||||
test('child exit precedes final output: preserve executed result before close', () => {
|
||||
const f = fixture();
|
||||
const typed = "printf 'hello-%s-world\\n' pty\nexit\n";
|
||||
expect(typed).not.toContain('hello-pty-world');
|
||||
f.lifecycle.data(Buffer.from(typed));
|
||||
f.lifecycle.exited(0, null);
|
||||
expect(f.completions).toEqual([]);
|
||||
expect(f.time.delays).toEqual([PTY_SHUTDOWN_GRACE_MS]);
|
||||
f.lifecycle.data(Buffer.from('hello-pty-world\r\n'));
|
||||
expect(f.events.join('')).toContain('hello-pty-world');
|
||||
expect(f.events).not.toContain('CLOSE');
|
||||
f.lifecycle.readerEnded(0, null);
|
||||
expect(f.events).toEqual([typed, 'hello-pty-world\r\n', 'CLOSE']);
|
||||
expect(f.completions[0]).toEqual({
|
||||
process: { exitCode: 0, signal: null, waitFailed: false },
|
||||
reader: { code: 0, signal: null },
|
||||
drainTimedOut: false, exitTimedOut: false, outputComplete: true,
|
||||
});
|
||||
expect(f.time.pending.size).toBe(0);
|
||||
});
|
||||
|
||||
test('reader can finish first; retain later nonzero child diagnostics', () => {
|
||||
const f = fixture();
|
||||
f.lifecycle.data(Buffer.from('command failed\r\n'));
|
||||
f.lifecycle.readerEnded(0, null);
|
||||
expect(f.completions).toEqual([]);
|
||||
f.lifecycle.exited(23, null);
|
||||
expect(f.completions[0].process?.exitCode).toBe(23);
|
||||
expect(f.completions[0].outputComplete).toBe(true);
|
||||
expect(ptyCompletionReason(f.completions[0])).toBe('pty exited (code 23)');
|
||||
expect(f.time.pending.size).toBe(0);
|
||||
});
|
||||
|
||||
test('reader error is separate from successful child exit and remains uncertain output', () => {
|
||||
const f = fixture();
|
||||
f.lifecycle.exited(0, null);
|
||||
f.lifecycle.data(Buffer.from('real output'));
|
||||
f.lifecycle.readerEnded(1, null);
|
||||
// Explicit Terminal.close() can report EOF again; preserve the first status.
|
||||
f.lifecycle.readerEnded(0, null);
|
||||
expect(f.completions).toHaveLength(1);
|
||||
expect(f.completions[0].process?.exitCode).toBe(0);
|
||||
expect(f.completions[0].reader?.code).toBe(1);
|
||||
expect(f.completions[0].outputComplete).toBeNull();
|
||||
expect(ptyCompletionReason(f.completions[0])).toBe('pty exited');
|
||||
expect(f.events).toEqual(['real output', 'CLOSE']);
|
||||
});
|
||||
|
||||
test('post-exit deadline rejects incomplete capture and preserves signal status', () => {
|
||||
const f = fixture();
|
||||
f.lifecycle.data(Buffer.from('partial'));
|
||||
f.lifecycle.exited(143, 'SIGTERM');
|
||||
f.lifecycle.exited(0, null);
|
||||
f.time.expire();
|
||||
const result = f.completions[0];
|
||||
expect(result.process).toEqual({ exitCode: 143, signal: 'SIGTERM', waitFailed: false });
|
||||
expect(result.reader).toBeNull();
|
||||
expect(result.drainTimedOut).toBe(true);
|
||||
expect(result.outputComplete).toBe(false);
|
||||
expect(ptyCompletionReason(result)).toBe('pty exited (SIGTERM)');
|
||||
f.lifecycle.data(Buffer.from('late'));
|
||||
f.lifecycle.readerEnded(0, null);
|
||||
f.time.expire();
|
||||
expect(f.events).toEqual(['partial', 'CLOSE']);
|
||||
expect(f.completions).toHaveLength(1);
|
||||
});
|
||||
|
||||
test('reader failure before a stuck process has a bounded wait for exit', () => {
|
||||
const f = fixture();
|
||||
f.lifecycle.readerEnded(1, null);
|
||||
f.time.expire();
|
||||
expect(f.time.delays).toEqual([PTY_SHUTDOWN_GRACE_MS]);
|
||||
expect(f.completions[0]).toEqual({
|
||||
process: null, reader: { code: 1, signal: null },
|
||||
drainTimedOut: false, exitTimedOut: true, outputComplete: null,
|
||||
});
|
||||
});
|
||||
|
||||
test('process wait rejection remains failure after reader completion', () => {
|
||||
const f = fixture();
|
||||
f.lifecycle.exited(null, null, true);
|
||||
f.lifecycle.readerEnded(0, null);
|
||||
expect(f.completions[0].process?.waitFailed).toBe(true);
|
||||
expect(f.completions[0].process?.exitCode).toBeNull();
|
||||
expect(ptyCompletionReason(f.completions[0])).toBe('pty process wait failed');
|
||||
});
|
||||
|
||||
test('explicit disposal cancels draining and ignores close-generated EOF or late data', () => {
|
||||
const f = fixture();
|
||||
f.lifecycle.exited(0, null);
|
||||
f.lifecycle.dispose();
|
||||
f.lifecycle.readerEnded(0, null);
|
||||
f.lifecycle.data(Buffer.from('late'));
|
||||
f.time.expire();
|
||||
expect(f.time.pending.size).toBe(0);
|
||||
expect(f.events).toEqual([]);
|
||||
expect(f.completions).toEqual([]);
|
||||
});
|
||||
|
||||
test('detached output and completion route to the current attachment', () => {
|
||||
const time = clock();
|
||||
const original: string[] = [];
|
||||
const replacement: string[] = [];
|
||||
const replay: string[] = [];
|
||||
let attached: string[] | null = original;
|
||||
const lifecycle = createPtyLifecycle({
|
||||
schedule: time.schedule,
|
||||
onData(chunk) { replay.push(chunk.toString()); attached?.push(chunk.toString()); },
|
||||
onComplete() { attached?.push('CLOSE'); },
|
||||
});
|
||||
attached = null;
|
||||
lifecycle.exited(0, null);
|
||||
lifecycle.data(Buffer.from('final while detached'));
|
||||
expect(original).toEqual([]);
|
||||
attached = replacement;
|
||||
replacement.push(...replay);
|
||||
lifecycle.readerEnded(0, null);
|
||||
expect(replacement).toEqual(['final while detached', 'CLOSE']);
|
||||
expect(original).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('PTY disposal owns its original process', () => {
|
||||
function child() {
|
||||
let resolve!: (code: number) => void;
|
||||
const signals: string[] = [];
|
||||
const proc = {
|
||||
pid: 42, exitCode: null as number | null, signalCode: null as string | null,
|
||||
killed: false, closes: 0,
|
||||
exited: new Promise<number>(r => { resolve = r; }),
|
||||
terminal: { close() { proc.closes++; } },
|
||||
kill(signal: string) { proc.killed = true; signals.push(signal); },
|
||||
};
|
||||
return { proc, signals, resolve };
|
||||
}
|
||||
|
||||
test('SIGINT does not prove exit; deadline kills only the captured child after replacement', () => {
|
||||
const time = clock();
|
||||
const old = child();
|
||||
const replacement = child();
|
||||
const session = { proc: old.proc };
|
||||
disposePtyProcess(session.proc, time.schedule);
|
||||
session.proc = replacement.proc;
|
||||
expect(old.proc.closes).toBe(1);
|
||||
expect(old.proc.killed).toBe(true);
|
||||
expect(old.signals).toEqual(['SIGINT']);
|
||||
expect(time.delays).toEqual([PTY_SHUTDOWN_GRACE_MS]);
|
||||
time.expire();
|
||||
expect(old.signals).toEqual(['SIGINT', 'SIGKILL']);
|
||||
expect(replacement.signals).toEqual([]);
|
||||
expect(replacement.proc.closes).toBe(0);
|
||||
});
|
||||
|
||||
test('observed child exit cancels escalation', async () => {
|
||||
const time = clock();
|
||||
const old = child();
|
||||
disposePtyProcess(old.proc, time.schedule);
|
||||
old.resolve(0);
|
||||
await old.proc.exited;
|
||||
expect(time.pending.size).toBe(0);
|
||||
time.expire();
|
||||
expect(old.signals).toEqual(['SIGINT']);
|
||||
});
|
||||
|
||||
test('already exited child closes its terminal without sending another signal', () => {
|
||||
const time = clock();
|
||||
const old = child();
|
||||
old.proc.exitCode = 7;
|
||||
disposePtyProcess(old.proc, time.schedule);
|
||||
expect(old.proc.closes).toBe(1);
|
||||
expect(old.signals).toEqual([]);
|
||||
expect(time.pending.size).toBe(0);
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user