Repository navigation
Conversation
…it (stablyai#15630) * Increase shell readiness timeout to match daemon barrier Slow interactive rc files can take longer than 1.5s to initialize. Raise the startup command readiness timeout from 1.5s to 15s to match the daemon barrier and prevent queued commands from executing mid-startup. * fix(terminal): keep a quick command queued until its own spawn takes it (STA-4876) Triggering a quick command opened a terminal tab titled with the command's label, the shell started and drew its prompt, and the command never ran. TerminalPane snapshots `pendingStartupByTabId[tabId]` in a useState lazy initializer, and a mount effect deleted the entry immediately. The pane's key is `${tab.id}-${tab.generation ?? 0}`, so anything that bumps generation before the command reaches a shell — the stall-recovery remount fired from `requestTerminalPaneRecovery`, or the allDead activation regeneration — mounted a second pane that re-read an emptied slot and spawned with no command at all. The loss was permanent, which is why every scope failed alike: repo, global and agent-prompt all funnel through the same queue-then-snapshot sequence. Spend the entry at `onPtySpawn` instead, which is the one point that proves this pane's own fresh spawn exists. A pane retired mid-connect never reaches it, so the command stays queued for the next mount; reattach skips `onPtySpawn`, so it cannot spend a command it never delivers. Three details are load-bearing: - Ownership is reference identity (`paneOwnsQueuedStartup`). Setup and issue splits borrow the same `deps.startup` field for their own one-shot payload, and that payload can be structurally identical to the queued command, so a truthiness test would let a split pane spend a command it never runs. - The consume runs after `bindActivePanePty`. While the tab still has no ptyId, the queued entry is the only thing holding its worktree out of the retention-budget force-park, so dropping it first unmounts the pane mid-spawn. - The callback is one-shot. `onPtySpawn` fires on every fresh spawn a pane makes, including hibernation wake and the respawn ladder, and a command queued after the first launch belongs to that later launch. Known residual, documented at the call site: the consume tracks "a pty exists", not "the command ran". Windows embeds short commands in the shell argv, so they execute before the spawn resolves and a pane retired in that window re-delivers on remount; on POSIX the write waits for shell-ready, so a pty that dies in that window loses a command already spent. Closing either needs a delivery signal from main rather than this callback. Both windows are narrow, and both are strictly better than losing the command unconditionally. * fix(terminal): guard the queued-startup wiring the review found untested Follow-ups from the final review pass on this branch. - Collapse the ownership + one-shot decision into `createQueuedStartupConsumer` so the call site is a single call rather than inline logic no test could reach. Two mutants survived the whole suite before this: relaxing ownership to a truthiness check, and dropping the one-shot guard. Both now fail. - Rewrite the throwing-consume test. It asserted `updateTabPtyId` had been called, which runs *before* the callback, so it passed with the try/catch deleted. It now asserts the throw does not escape into the connect promise, which is the invariant the try/catch actually provides. - Correct the `onQueuedStartupSpawned` docblock. It claimed the callback is "the first moment the command is guaranteed to reach a shell"; the diff's own caveat says otherwise, since Windows runs an argv-embedded command before this fires and a POSIX shell can die before the shell-ready write. It marks a live shell, not delivery. No behavior change: the consumer is the same predicate and the same one-shot, moved behind one exported seam. * fix(terminal): roll shell wrapper isolation into a fresh daemon * Revert "Increase shell readiness timeout to match daemon barrier" This reverts commit 6ab273e. * Condense queued startup spawn comment Simplify the multi-paragraph explanation into a concise summary that captures the key points: spawn must wait until after the pane is bound to preserve the worktree from force-parking, and the behavior differs between POSIX and Windows for delivery timing. * fix(terminal): prevent consuming replaced queued startup commands When a queued startup is replaced before the pane's first spawn, the one-shot guard alone still allows consuming the replacement. Add isStillQueued callback to verify the slot still holds the originally captured command (STA-4876). --------- Co-authored-by: Jinwoo-H <jinwoo0825@gmail.com>
…blyai#15635) * Fix flaky CI tests by adding retry logic and increasing timeouts Add Electron launch retry for CI runners where startup wedges before reaching 'ready', with fresh profile per attempt to avoid mid-init state. Increase skill install lock timeout from 100ms to 5s to account for fsync cost plus retry duration on loaded CI runners. * shorten comments
DialogContent used an implicit grid column, which sizes to min-content: an unbreakable token such as a long filename in the title widened the column past the panel, so the title overflowed and the justify-end footer buttons rendered outside the visible surface. Pin the column to minmax(0,1fr) and let long titles wrap.
* fix(terminal): mark captured shortcut input interactive Refresh the interactive-redraw timestamp after a captured shortcut send succeeds, so the composer redraw that follows takes the low-latency foreground path instead of waiting out the 1s coalesce fallback. Orca's captured shortcut path sends directly through the captured pane transport to preserve pane, PTY and transport identity, and so bypasses xterm's onData -- the only place that previously stamped the timestamp. An idle pane therefore scheduled the post-Shift+Enter redraw as ordinary throughput. Measured in a real Pi pane on Windows: ~1029ms before, ~16-20ms after, at an identical ~2.3KB redraw. Stale pane bindings and rejected transport sends cannot refresh it. Fixes stablyai#10203 Refs stablyai#13598 * fix(terminal): keep captured shortcuts out of the pane-teardown signal lastTerminalInputAt has two readers, and the previous commit only meant to change one of them. onExit reads it as "the user never typed into this pane" to keep a newborn pane mounted when its shell dies on startup (the failing-.envrc direnv case, pty-connection.ts onExit) so the error stays visible and the worktree stays active. Stamping it from a captured shortcut therefore made a single Shift+Enter before that exit close the tab and bounce the user to Landing -- on every platform, since captured shortcuts are not Windows-only. Split the redraw window onto its own timestamp so captured shortcuts open the fast path without arming the teardown, and leave onExit's behaviour byte-identical to main. * test(terminal): pin the captured-shortcut wiring and its staleness guard Deleting the onAccepted block, or replacing its binding-identity check with true, both left the whole suite green — so nothing pinned the part of this PR that actually ships. Cover both against the existing IME keyboard harness. --------- Co-authored-by: OrcaWin <293788423+OrcaWin@users.noreply.github.com>
…lyai#13598) * fix(terminal): preserve Shift+Enter during routing confirmation Keep previously trusted CSI-u routing active only while local foreground revalidation is pending. Clear pending authority on inconclusive reads and never promote display-only identity.\n\nRefs stablyai#12541\nRefs stablyai#13597 * fix(terminal): respect global WSL routing gate * fix(terminal): bound the retained routing capability to a live read Two holes in the previous commit let one provider read authorize CSI-u indefinitely. First, routingConfirmationPending satisfied its own precondition, so a pending entry re-published itself on every reconfirmation request. Only one of the five callers is the Shift+Enter burst timer; the others fire on accepted submit/interrupt bytes, focus and visibility changes, and onAgentExited -- the last of which runs precisely when a shell title proves the agent is gone. On cmd.exe and Git Bash there is no OSC boundary to publish over the entry, so nothing decayed it. Second, the flag was published even when no confirmation read was actually scheduled -- a hidden pane, a command read already in flight, or a null pty id -- and only the read's inconclusive settle clears it. Require routingTrusted to grant the capability, and publish the flag only after sampling reports a read in flight, so it cannot outlive the read that justifies it. This also makes the canConfirmRouting gate redundant: the tracker already refuses WSL, SSH and remote pty ids. * review round 2: bound the retained capability to any in-flight read onVisiblePtyBound refuses to schedule while a higher-authority command read owns the pane, so gating the pending publish on it mistook 'a command-finished read already owns this' for 'no read at all' and dropped CSI-u for >=350ms — the window stablyai#13598 exists to close. Ask the tracker whether any read is in flight instead, and settle the visible confirmation from the command-finished branch that publishes nothing, so the flag cannot outlive the read that justifies it. * review round 2: tighten the reconfirmation gate and its comments hasReadInFlight already covers the visible-pty read that visibleForegroundSamplePending tracked, so the disjunction was redundant. Collapse the stacked Why blocks into one. * review round 3: release the retained capability when a read is abandoned Every outcome path now clears routingConfirmationPending, but the two abort guards in readForeground return without publishing or settling. A pty rebind during the multi-second inspection RPC — a detach/remount emits no onExit, so the store entry survives — therefore stranded the flag permanently, leaving Shift+Enter on CSI-u with nothing left to revalidate it. Worse, once sampling is suppressed by a live hook row the pane routes bytes on hook evidence alone, which the resolver excludes precisely because PTY output can forge it. Settle an abandoned read unless a newer generation will settle for it. * review round 4: release the retained capability at every exit without a successor Rounds 2 and 3 closed the outcome paths and the aborted-read paths, but two review lanes independently proved a third: cancelPendingRead bumps the generation, so a cancel never settles, and dispose plus the three untrackable early returns schedule no successor to settle for them. The store entry outlives the tracker — detach/remount emits no PTY exit — so the flag latched there with no read left alive. A visible remount self-heals, but a hidden pane does not: the dashboard card resolves the encoding for any pane key regardless of visibility. Release the capability from whichever exit ends the read, and say in the entry's own doc comment that the flag is Shift+Enter-scoped. * test(terminal): pin the remaining capability-release exits dispose and the command-finished exit were covered; the visible-bind and command-start variants are the same three-line pattern and were not. Neutering the release now kills all four. --------- Co-authored-by: OrcaWin <293788423+OrcaWin@users.noreply.github.com>
…bility source (stablyai#15232) (stablyai#15430) Co-authored-by: Brennan Benson <79079362+brennanb2025@users.noreply.github.com>
… cursor workspace (stablyai#15824) Fixes STA-5076. list-issues capped at 50 by default and hard-clamped at 250, with hasMore buried under result.meta and no stderr warning for --json, so a page that stopped early read as a complete answer. Omitting --limit now walks Linear's pages until they run out (meta.limit is null), and --limit <n> is the only cap, paging past Linear's 250-per-request maximum to reach it. result.truncated sits next to result.issues and is set only when a cap actually held results back; human output prints "truncated: showing N". The read still has to fit the CLI's 60s RPC budget, so a 20s wall-clock deadline and a 200-page ceiling stop the walk early and report truncated with a continuation cursor rather than failing the command. Also: - issued --cursor values bind the resolved workspace, so call -> nextCursor -> call works without --workspace; raw Linear cursors still need one and now carry nextSteps - issued cursors whose payload smuggles back `all` or an empty workspace are rejected at decode, since either would widen the read past the bound workspace - JSON issue rows carry priorityLabel (none/urgent/high/medium/low), matching orca linear priority set - truncated and priorityLabel are optional on the wire, so a host that predates either is not read as "complete"; readers fall back to meta.hasMore - the truncation line prints the rows actually rendered, so a remote result with no meta.returned cannot print "showing undefined"
…relay (stablyai#15827) * fix(ssh): let fork-PR worktrees add their contributor remote via the relay Creating a workspace from a fork PR on an SSH host failed with "Destructive git remote operations are not allowed via exec". The relay's git.exec allowlist blocked every `remote` write subcommand, but SSH fork-PR creation has to run `git remote add <fork> <url>` on the host before it can fetch and track the contributor's branch, so the whole create aborted. Allow exactly the two shapes that flow needs -- `remote add <name> <url>` and `remote remove <name>` -- validated with the same remote-name and URL rules the relay already applies to every pushTarget-carrying RPC. Everything else (set-url, rename, prune, extra operands, flags before the action) stays blocked, and the URL must be a github.com clone/ssh URL, so no new reach is granted beyond what push/fetch already accept. `remote remove` was blocked too, which silently leaked fork remotes on SSH hosts: worktree removal swallows the cleanup error. It works again now. A host still running an older relay gets an actionable "reconnect to deploy the latest relay" message instead of the raw policy error. * test(git-exec): pin remote read/write mutation classification Misclassifying `git remote` / `remote get-url` as mutating would flush the relay and SSH provider git read caches on every remote probe, so pin both directions.
…ts and graph syncs (stablyai#15644)
* feat(process): add the Windows-correct child-process chokepoint Six decisions have to be made every time Orca starts a child process -- console visibility, argument quoting, .cmd interpretation, binary resolution, timeout policy, and how the tree is later terminated. POSIX forgives all six. Windows punishes each differently, and made per-call site across 172 files they were right in some and wrong in others. runProcess/spawnProcess make them once: - windowsHide unconditionally, shell:false unconditionally (shell:true concatenates argv unescaped and silently disables windowsHide) - .cmd/.bat routed through cmd.exe /d /v:off /s /c with a verbatim line, because Node refuses to spawn them otherwise (EINVAL) The encoding was derived by measurement on Windows 11, not from the docs. An embedded quote is written "" rather than \" so cmd's naive quote count stays even -- with \" the parity flips and every later & | < > on the line stops being data. Measured before the fix, argv ["a b", 'c"d', "e%F%g", "h&i", "j^k"] arrived as ["a b", 'c"d', "e^%F^%g", "h"]: the & truncated the argument and ran its remainder as a command. Each % is broken out of the quoted run as "^%" because %VAR% expands even inside quotes. The import-boundary test is a ratchet seeded at today's 172 files; it only shrinks. * fix(process): route the console-flashing spawn sites through the chokepoint The ssh -G config probe fires on every connect and reconnect, and ssh.exe is console-subsystem, so a GUI-subsystem parent gets a fresh visible conhost that takes foreground -- keystrokes typed into an Orca terminal at that moment go into the black box (stablyai#10488, stablyai#14543). Same for the ProxyJump tunnel, the ProxyCommand cmd.exe wrapper, the font enumeration and the DPAPI cookie decrypt. Also stops spawning powershell by bare name: PATH under Electron is not the user's, so where policy has pruned the System32 entry the spawn fails and the font picker silently reports five hardcoded families rather than an error (stablyai#11771). Deletes system-fonts' 40-line bespoke execFileText -- timeout, output cap and kill are the chokepoint's job now. Adds runProcessSync so the sync callers have a compliant path; without one the ratchet could never reach zero. The three suites that mocked child_process directly now mock runProcess, which is the point: how a process gets started is no longer each module's business. Ratchet 173 -> 170. * fix(process): do not report a deliberately killed child as timed out runProcessSync inferred a timeout from signal === 'SIGTERM'. Measured: a real timeout sets error.code ETIMEDOUT and kills with SIGTERM, but so does anything else that terminates the child -- and those cases set no error at all. Reading the signal alone reports a process someone stopped on purpose as having timed out, which callers retry. * refactor(process): hold the ratchet as data and migrate the pwsh probes The allowlist and the adversarial argument corpus are read only by tests, so they were production modules in name only; they move to __fixtures__. pwsh.ts carried isTimeoutError() purely to reconcile two spellings of the same event -- execFileSync reports a timeout as ETIMEDOUT, the execFile callback as a SIGTERM kill with no code. runProcess reports one timedOut flag, so the helper and the reasoning behind it both go. Its sync probe also spawned without windowsHide, which flashes a console and steals foreground on every cold cache read. * refactor(process): migrate five more spawn sites onto the chokepoint Each one deletes a hand-rolled promise/timeout/kill wrapper and stops re-deciding console visibility for itself. Ratchet 170 -> 164. Two things this surfaced, both kept: runProcess now accepts string chunks as well as buffers. A stream someone called setEncoding on emits strings, and concatenating those as buffers throws inside a data handler -- where the rejection has nowhere to go and the caller simply hangs rather than failing. ProcessSpec keeps its AbortSignal. I had removed it as unused; the macOS PAM preflight passes one through from its own caller. ipc/app.ts is deliberately NOT migrated. Its probe spawns a three-stage pipeline detached so a timeout can reap the group with one negative-pid SIGKILL; runProcess kills only the root, which would orphan the plutil stages. Migrating it needs the chokepoint to own POSIX process-group termination first -- the same guarantee job objects give on Windows. Reverted and left on the ratchet. * test(process): do not assert a POSIX signal on Windows Windows has no signals, so the same deliberate kill reports an exit code there and a signal on POSIX. What has to hold on both is that neither shape reads as a timeout. Caught by running the suite on Windows. (cherry picked from commit 0a6e990) * fix(process): settle a timed-out run even when the child ignores the kill close only fires once the child is actually gone, so a child that traps SIGTERM never emits it and the promise outlives its own deadline forever. That is the same wedge shape just fixed for the process table, and it is worse here: pwsh.ts and the snapshot reader both cache an in-flight probe, so one unkillable child hands every later caller the same dead promise. After the deadline it now escalates to SIGKILL and settles regardless, reporting timedOut with whatever output arrived. (cherry picked from commit 78ac169) * fix(process): escalate an aborted child too, not just a timed-out one The grace escalation I added covered the timeout path and left abort on the old one, so an aborted caller with an unkillable child still waited forever -- the same defect, one path over. The macOS PAM preflight is a real caller that passes an AbortSignal. Both paths now share one stop-and-settle, and the result reports timedOut honestly: false when the caller aborted. (cherry picked from commit 7e9523a) * fix(windows): stop percent escaping from forging an escaped quote escapePercentForCmd ran as a post-pass over the quoted string, so it inserted a quote wherever a percent was -- including straight after a backslash. CommandLineToArgvW reads backslash-quote as an escaped quote, so C:\Users\%USERNAME%\x arrived corrupted. That is about as common as Windows paths get, and my 20-case corpus had no backslash-before-percent entry to catch it. Percent handling is now part of the quoting loop, where the backslash run is known and can be doubled before the inserted quote. Two corpus cases cover the shape. The program path gets the same treatment. It was quoted but not percent-escaped, so a launcher under C:\Users\%USERNAME%\ had its own path expanded on the cmd hop. quoteWindowsArgument no longer takes a boolean. Passing it to values.map() handed map's index in as the flag -- which is how the first version of this fix was written, and the corpus test caught it. Separately: an AbortSignal that was already aborted never fires the event, so runProcess ran the child to its full timeout for a caller who had already given up. (cherry picked from commit f7e2e56)
stablyai#15353) Adds a configurable, unbound-by-default `dashboard.toggle` action that toggles the Agent Dashboard (in-window drawer or pop-out, per the existing mode setting). - Wired through window-shortcut-policy, main-window dispatch, browser-guest dispatch, preload, and the renderer IPC handler. - Opening the in-window drawer reveals the sidebar first; closing leaves it alone. - Gated on the `experimentalAgentDashboardPopout` experiment, and the Settings shortcut row is hidden while that experiment is off.
stablyai#15850) Fork-PR setup adds the contributor's remote, then fetches the head. If that fetch fails the create aborts, but the remote stayed behind with no owner: cleanup only runs on worktree removal, and no worktree was ever created. Each retry then left another orphaned pr-* remote. Roll the remote back on fetch failure, on both the local and SSH paths, and only when this call is what added it -- a reused remote (Orca-created or not) is left alone.
* Remove agent map view from dashboard Removes the view toggle and simplifies the dashboard to show only the kanban board layout. * Assert boardProps is initialized on drawer open
…erShell (stablyai#15749) * perf(windows): read the process table natively instead of forking PowerShell Seven independent readers each forked powershell.exe to run Get-CimInstance Win32_Process, with a wmic fallback that Windows 11 24H2 has removed. On a domain-joined host with PowerShell Transcription enabled by policy, one of them running every ~2s recorded ~289GB across 1.4 million files (stablyai#15209). The same scan cost ~700ms and ran per pane (stablyai#15036), and a Group Policy or AV block turned it into 'unavailable', which callers read as 'no evidence' -- which is how a PTY tree survives its own teardown (stablyai#9045, stablyai#10475). A Toolhelp32 snapshot answers the same question with no child process. Measured on Windows 11 with 1050 processes, p50/p95: pid+ppid+name 15.9 / 17.5 ms +memory +command line 30.6 / 33.7 ms Get-CimInstance 706 / 723 ms Two upstream defects needed patching, both found by running it on real hardware. The binding requires Spectre-mitigated libraries our agents do not carry (node-pty is patched the same way). And enumeration stopped after 1024 processes: on a host with 1051 the module returned exactly 1024, and the querying process was itself among the 27 missing -- a truncated snapshot silently hides the descendants teardown is looking for, which is the failure this whole change exists to remove. Migrated: the foreground/descendant reader (the stablyai#15209 scraper and the teardown identity gate) and the port scanner's PID attribution. NOT migrated: the memory collector and three identity probes, which need Win32_Process.CreationDate and have no native equivalent. Start time is a proxy for identity anyway; an inherited job handle is the real answer, so those belong with the job-object work rather than here. Packaging follows the windows-native-registry contract exactly: optional, absent from onlyBuiltDependencies so macOS/Linux never run node-gyp, win32-only in the packaged runtime. Asserted by the existing contract test, which also stops pinning a whole source literal that only tested its own formatting. * chore(process): ratchet the child_process allowlist down windows-foreground-process-rows.ts no longer spawns anything, so its allowlist line is stale. The guard fails on a stale entry as well as a new one, precisely so a migrated file cannot keep a slot open and hide the next regression in the same path. * fix(ports): import the process-table reader the scanner uses Missing import: the migration replaced the PowerShell call but the new symbol was never imported, so tsc failed. Vitest transpiles without typechecking, which is why the port-scanner suite stayed green. * fix(deps): sync this branch's lockfile with its patch set Same class as the fix on the tip branch: pnpm records a hash per patched dependency, and this branch introduces the windows-process-tree patch without its lockfile entry matching. Every job here failed at install with ERR_PNPM_LOCKFILE_CONFIG_MISMATCH. Verified with --frozen-lockfile, which is what CI runs and what my local runs were not. * test(relay): drive the relay's Windows fixtures from the native snapshot Two relay cases fed a PowerShell CIM payload through a mocked execFile. That reader is gone, so both failed -- deterministically, on every PR run for this branch and the one above it. I did not catch it because my own verification sweep was 'src/main src/shared config/scripts' and never included src/relay. The relay is a first-class consumer of the process table; leaving it out of the sweep is how a deterministic failure survived six review rounds.
Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
* fix(windows): own PTY process trees with job objects Teardown used to answer 'is this tree mine, and how do I kill it?' by scraping the process table, walking parent pids back to Orca, and running taskkill /T /F only if the walk said yes. Every step is a guess, and the code said so itself: windows-pty-root-identity.ts:35 already named the fix -- 'an inherited handle / Job Object'. The guesses fail in the ways users report. A pid walk cannot survive pid reuse, so teardown refused whenever it could not prove ownership, and a refused kill is an orphaned agent tree holding the worktree directory open (stablyai#9045, stablyai#10475, stablyai#10087). A descendant that reparented is invisible to the walk. The scrape itself could be blocked by policy, which read as 'no evidence'. node-pty now creates a job object per ConPTY and assigns the shell under CREATE_SUSPENDED, before it can spawn anything -- assigning afterwards leaves a window in which a fast child escapes. Termination is one TerminateJobObject; liveness is QueryInformationJobObject. Verified on Windows 11 against a shell whose grandchild was spawned detached: job membership came back [shell, grandchild] and one call killed both. Neither a parent-pid walk nor GetConsoleProcessList sees that grandchild -- it leaves the console and reparents, which is exactly the claude.exe/node.exe/cmd.exe orphan in stablyai#9045. KILL_ON_JOB_CLOSE means a daemon that dies without unwinding no longer strands shells (stablyai#9195, stablyai#10415). The job is the daemon's, not the app's, so an app-main crash still leaves sessions alive -- the guarantee win-crash-survival-e2e asserts. Both entry points report unavailable rather than a false success when a pty has no job: an outer job without BREAKAWAY_OK can refuse the assignment, and a pty from an older build has none. Reading 'we could not tell' as 'already dead' is the original bug, so the old probe stays as the fallback. * test(windows): pin job ownership against a real detached grandchild The unit tests pin the contract; this pins what the contract is for. A grandchild spawned detached leaves the pane's console and reparents, so GetConsoleProcessList and a parent-pid walk both miss it -- that is the process that outlived its pane and held the worktree directory open. Includes a guard that this build actually has job support, so a node-pty rebuilt from unpatched sources fails loudly instead of letting every assertion pass vacuously. * fix(windows): correct the job liveness contract to what Windows actually does I claimed an emptied tree would report [] and that this was the evidence a stale registry entry lacks (stablyai#15549). Running it on Windows 11 showed otherwise: node-pty drops its handle record and closes the job when the shell exits, so a dead tree reports null. Null therefore means unverifiable in the sense of docs/reference/ssh-execution-boundary.md -- no job support, not a ConPTY, or no longer tracked -- and is never evidence that processes died. A caller reading it as proof of death would have been right by accident after a normal exit and wrong on a host that refused the assignment. What the API does add is descendant liveness for a tree that is still tracked, including children that detached from the console. * fix(windows): stop a clean shell exit from reaping backgrounded processes Measured on Windows 11: with JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE on the per-PTY job, releasing the handle when the shell exits also killed whatever the user had backgrounded. Typing 'exit' in a pane reaped a detached server that survived before this patch. That is a behaviour change nobody asked for. The approved change was that killing the terminal daemon reaps its shells -- not that a clean exit reaps your background job. The job's purpose is to make an EXPLICIT teardown exact, which TerminateJobObject still does. Reaping a dead daemon's shells now needs the daemon-level job the design called for: the daemon assigns itself, children inherit membership, and its closure on daemon death reaps them without touching clean-exit semantics. Not in this PR; noted in the reference doc. * test(windows): pin that a clean exit leaves backgrounded work alone The counterpart to the tree-kill test. Without it, re-adding JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE would look like a tightening rather than the regression it is. * fix(windows): stop a winpty pty id from matching a ConPTY job winpty.cc and conpty.cc each mint their 'pty' id from an independent counter, and windowsPtyAgent stores both in the same _pty field. So a winpty-backed terminal's id can collide with a live ConPTY baton -- and closing that pane would have terminated an unrelated pane's entire process tree. Both job entry points now take the shell pid and the native side refuses unless GetProcessId(hShell) matches, which makes the id unforgeable. Two more from the same read-through: - ResumeThread's failure was ignored. A shell left suspended is a pane that never prints and never exits, which is far harder to diagnose than a failed spawn; it now cleans up and throws. - handle->hJob was assigned before LoadConptyDll, which can throw. A baton carrying a job but never reaching SetupExitCallback has nothing left to close it, so the assignment moved down beside hShell. * docs(windows): record the unsynchronised node-pty baton table Pre-existing upstream -- the exit thread erases while the main thread reads -- but terminatePtyJob adds an instance of it, so it belongs in writing rather than in someone's head. * fix(windows): close four gaps found in review BREAKAWAY. The per-PTY job set no limits, so a child asking for CREATE_BREAKAWAY_FROM_JOB was refused with ERROR_ACCESS_DENIED. Installers, msiexec and some updater and service-control paths spawn that way deliberately -- they worked before this patch and would have failed only inside an Orca terminal, which is the worst shape a bug report can take. JOB_OBJECT_LIMIT_BREAKAWAY_OK restores it; a child still has to ask, so ordinary descendants stay owned. EMPTY IS NOT UNAVAILABLE. The native reader returns an empty list -- not an error -- when CreateToolhelp32Snapshot fails, which is what an EDR hook or a restricted token produces. Callers read that as 'nothing is running' and teardown concludes a live PTY root is already gone. The snapshot must contain the querying process; nothing else is unfalsifiable, and one predicate catches empty, truncated and permission-filtered tables alike. NO DEADLINE. Replacing execFile dropped its 3s timeout. The vendored reader latches a module-global while a request is in flight and clears it only after draining its callbacks, with no try/catch -- so one wedge leaves every later call queued behind a promise that never settles, and the process table is dead for the life of the app. The bound is back. GUESSED IMAGE PATH. executablePath was derived from the first space-delimited token, which reads 'C:\Program' out of an unquoted 'C:\Program Files\nodejs\node.exe ...'. Wrong evidence is worse than none, and the only consumer already had the full path in , so the field is gone rather than repaired. Also: remove_pty_baton no longer sits inside assert(), which NDEBUG would compile away along with the call, and the job accessors hold a lock across lookup and use -- handle values are recycled, so an unguarded read could pass the shell-pid check against an unrelated process and terminate the wrong job. * fix(windows): apply the job lock once per accessor The patch script matched a string its own replacement still contained, so PtyTerminateJob got two lock_guards named guard and PtyListJobProcessIds got none. MSVC caught it: error C2374 redefinition. * test(windows): pin that a child can still break away from the job Verified on Windows 11: 'start /b' writes its marker and no access-denied appears. Without JOB_OBJECT_LIMIT_BREAKAWAY_OK this fails, and it fails only inside an Orca terminal -- so the failure would look like Orca corrupting unrelated software rather than like a job-object change. * fix(windows): stop the ownership guard from reading a closing handle The guard called GetProcessId(hShell) to prove identity, but the exit watcher closes hShell on another thread -- so the guard could read a closed handle, and under strict handle checks that is fatal rather than merely wrong. Worse, it widened the gap between validating hJob and using it from two instructions to a kernel round-trip, and handle values recycle: the likeliest occupant of a freshly recycled value in this process is another pane's job. The pid never needed a handle. It is captured at spawn and compared as a DWORD, so the guard touches no handle at all, and hShell is now closed inside the same lock as hJob. Also from review: - reject CR/LF in a cmd argument. cmd ends the command at a raw line break whatever the quote state, so there is no escape for it; encoding one anyway truncates the argument and can leave the remainder to run as a command. Agent prompts are this encoder's motivating input. - ask the process table only for the fields a caller needs. Memory and CommandLine each cost an OpenProcess per process, inline, for every process on the box -- and the 1024 bound is patched out. Ancestry reads now skip both. - corpus gains the degenerate quote-only and two-quote arguments. - PtyListJobProcessIds' docblock still taught the empty-list contract that was corrected on the TS side, and now records that the ConPTY console host is never a job member. - drop a write to NumberOfAssignedProcesses, which is output-only. - pty_baton::hShell is initialised; ownsShell was only safe because && short-circuited ahead of it. The backgrounded-child test is rescoped: 'start /b' uses CREATE_NEW_CONSOLE, not CREATE_BREAKAWAY_FROM_JOB, so it proves job membership does not block backgrounding -- not that BREAKAWAY_OK works. That flag rests on the Win32 contract, and I have said so rather than letting the test imply coverage it does not have. * fix(windows): bound retries after the process table wedges The 3s deadline stops a caller hanging, but the timed-out call leaves its callback in the vendored module's queue -- and that queue drains only when the latched request completes, which in this wedge never happens. Retrying at the caller's poll rate would add a closure per tick forever. A 30s cooldown bounds it to one probe, and a late callback clears the cooldown because it proves the reader recovered. Also pins the deadlock invariant in the patch: the exit thread's lock must close before tsfn.BlockingCall, because that waits on the JS thread and the JS thread can be waiting on the same mutex inside PtyTerminateJob. Correct today by scoping; a comment so a later refactor does not widen it. * revert(windows): drop the field-selection API, which cannot pay off I added it for a real perf finding -- Memory and CommandLine each cost an OpenProcess per process -- and then never wired a caller, so the claim that ancestry reads skip them was wrong. Wiring it would have been worse than leaving it dead. The only ancestry consumer is the teardown identity probe, which needs a snapshot that started AFTER it asked, for pid-recycle detection. Bypassing the shared reader to get narrow fields would let that request join a scan already in flight -- trading a correctness guarantee for milliseconds. Field selection only pays off if callers can ask for less, and they cannot: one shared snapshot serves every caller so a 32-wide teardown collapses into a single scan, which means it has to carry every field. The reasoning now lives next to the flags instead of in a dead export. * fix(process): three P1s from review — a crash vector and two wedge bugs STDIN EPIPE COULD TAKE DOWN THE MAIN PROCESS. A child that exits without reading makes the queued write fail with EPIPE, and an unhandled error on a stream is an uncaught exception. The child's own error listener does not cover its stdin stream, so runProcess({ input }) against a short-lived child was a crash, not a failed call. THE COOLDOWN LEAKED A BATCH PER CYCLE INSTEAD OF BOUNDING IT. At expiry every concurrent caller passed the check before any of them re-armed it, so each enqueued a callback into the still-latched native queue and each cycle leaked another batch. The cooldown is now re-armed BEFORE probing, so exactly one caller gets through. A SYNCHRONOUS THROW LEFT ITS DEADLINE RUNNING. The timer was declared inside the try, so catch could not clear it; it fired later and wedged a reader that had already recovered. Hoisted and cleared, and wedge state now carries a generation so a request that lost its deadline cannot mutate it on behalf of the one that replaced it. Found by review once the prompts were short enough for the reviewer to finish -- the previous two rounds died on prompt length. * fix(process): stop a stream error from crashing the main process Same class as the stdin EPIPE finding, two instances further on: stdout and stderr had data listeners and no error listeners, and an unhandled error on a stream is an uncaught exception. Scoped to runProcess, which owns the child outright. spawnProcess hands the streams to its caller, and a blanket handler there defeats callers that track and remove their own listeners -- the SSH ProxyCommand transport does exactly that, and its cleanup test caught the attempt. Documented on spawnProcess so the boundary is explicit rather than inferred. * fix(windows): validate the ConPTY DLL before creating the process LoadConptyDll throws when conpty.dll is missing -- a real state, and one this branch hit during development. It ran after CreateProcessW and ResumeThread but before the baton and the exit watcher were installed, so a throw leaked the job, process and thread handles and left an untracked shell tree running. Once per attempt, so a broken install accumulates orphan shells on every retry. Resolving the DLL first costs nothing and leaves exactly two throws after creation: the CreateProcessW failure, where nothing exists yet, and the resume failure, which already cleans up after itself. This also closes the same leak for hProcess and hThread, which predates the job work. * feat(windows): add the daemon-level job the design called for The plan specified two nested jobs and I built one. That gap is why dropping KILL_ON_JOB_CLOSE from the per-PTY job cost the approved guarantee that a dead daemon reaps its shells -- I had one job trying to answer two questions, and the two answers conflict. They are separate jobs. The per-PTY job answers 'kill exactly this pane's tree, now', and cannot be kill-on-close because its handle is released when the shell exits, which would reap whatever the user backgrounded. The daemon assigns itself to a second job that IS kill-on-close; its handle is released only when the daemon dies. Children inherit membership, so every pty is covered and the per-PTY jobs nest inside it. Daemon, never app: an app-main crash must still leave sessions alive, which win-crash-survival-e2e asserts. Both jobs carry BREAKAWAY_OK, or a child asking to break away is refused at whichever level lacks it. Restores stablyai#9195 and stablyai#10415, which I withdrew from this PR earlier. * docs(windows): record what the host job does not cover An app-hosted PTY gets a per-PTY job but no crash reaping, because the alternative is a kill-on-close job on the app -- which is precisely what the crash-survival guarantee forbids. * ci(windows): run the win32 suites in the PR windows job Both were skip-on-non-win32 and had only ever run on one machine I drive by hand -- which went unreachable at exactly the moment I needed to verify the percent-escaping fix. Verification that depends on one box is not verification. The job already builds node-pty from patched source and already runs a useConptyDll test, so the ConPTY runtime files are in place by this step. This also makes the encoder a gate: the corpus is the only thing standing between an agent prompt and a mangled argv, and it now runs against real cmd.exe on every PR. * fix(deps): refresh the lockfile for the current patch hashes pnpm records a hash per patched dependency, and I regenerated both patches repeatedly across the review rounds without refreshing the lockfile. Every local run used --frozen-lockfile's looser sibling, so nothing caught it until CI did: ERR_PNPM_LOCKFILE_CONFIG_MISMATCH Cannot proceed with the frozen installation. The current "patchedDependencies" configuration doesn't match the value found in the lockfile Verified with pnpm install --frozen-lockfile locally this time. * ci(windows): build node-pty from source before the win32 suites CI proved the encoder fix on real cmd.exe -- 26/26 -- and in the same run proved the job suite had been testing an unpatched binary. node-pty prefers its upstream prebuild, which does not contain this patch, so every job-object export was absent and isPtyJobOwnershipAvailable() was false. That guard is why the failure was loud rather than a vacuous pass, and it is the reason the assertion exists. Packaging was never affected: rebuild-native-deps.mjs already builds node-pty from source for Electron and restores the ConPTY runtime files. The gap was the node-runtime test environment only. Not changing requiresPatchedNodePtySourceBuild's win32 exemption here. Its premise -- that the patch is Unix-only -- is now false, but lifting it also needs pnpm rebuild to force a source build, and I cannot validate that on macOS and Linux from here. Recorded as a follow-up instead of changed blind. * test(windows): gate the host-job guarantee in CI The daemon-level job had one hand-run proof and no automated coverage -- the same shape of gap that let an unpatched node-pty go unnoticed until CI caught it. It needs a real second process, because the assertion is about what happens when that process is force-killed: a host in a kill-on-close job must strand neither its pty nor a grandchild spawned detached, which is the process a parent-pid walk cannot see. Runs in the Windows PR job alongside the per-pty and encoder suites, so both halves of the two-job design are now gated rather than asserted. * fix(windows): serialise host-job creation Two callers racing PtyAssignCurrentProcessToJob would each create a job, put the process in both, and leak the first handle -- and the handle is what keeps a kill-on-close job alive, so a leaked one is never released. 'Only JS calls it' is not a guarantee: a worker thread with its own N-API env shares these statics. Also records the ordering requirement it depends on. AssignProcessToJobObject adds only the named process; children inherit membership, but a pty that already exists does not join retroactively and would not be reaped. The daemon assigns at startup, before the ConPTY warmup and before any session, which is correct today and now stated rather than implied. * fix(daemon): keep the host job off the startup path Assigning the host job at daemon startup resolves the node-pty native module, which loads the ConPTY addon -- and paying that before the endpoint is published delayed readiness enough that daemon-boot-smoke failed on windows-latest, deterministically. windows-conpty-warmup already carries the comment for this exact hazard ('setImmediate keeps the ready/handshake path ahead of the warm-up') and I put an eager load in front of it anyway. Moved to the pty spawn path, which already pays ConPTY cost, and memoised. Children inherit job membership, so assigning immediately before the first spawn still covers every pty -- and nothing can spawn one before the endpoint exists.
…ns (stablyai#15886) W2 gave every ConPTY pane a job object and wired `terminateOwnedTree` into `local-pty-provider.ts`. Measured in stablyai#11047: worktree delete does not execute there. It runs in the terminal daemon, so on the path that matters the sweep still fell back to a parent-pid walk -- which a detached, reparented grandchild is not in. That process is the one that holds the worktree cwd open, so the delete this was meant to fix could still fail. Expose the job on `SubprocessHandle` and use it at the three daemon call sites (`terminal-session-teardown.ts` x2, `session-termination-controller.ts`). Also: on Windows `forceKill()` returned early after any `kill()`, to avoid double-closing the ConPTY handle node-pty owns. Correct, but it left force-kill a permanent no-op -- and a wedged ConPTY never fires `onExit`, so such a session had no escalation at all (stablyai#9854). Terminating the job is that escalation, and it does not touch node-pty's handle. A tree-walking guard now fails if any production `killWithDescendantSweep` call omits `terminateOwnedTree`, since the option is optional by design and its absence is invisible in review -- exactly how this gap survived W2. Co-authored-by: OrcaWin <orcawin@users.noreply.github.com> Co-authored-by: hanbong5938 <hanbong5938@users.noreply.github.com>
…stablyai#15887) * fix(win32): hide the console window for agent-browser and git helpers W1 routed most child processes through `runProcess`, which always sets `windowsHide`. Six call sites still spawn directly, so each one opens a real console window on Windows: it flashes and steals foreground. For the git status poll, that is once per poll (stablyai#10488). A ratchet now scans every file that imports `child_process` and fails on a call without the flag. Its allowlist starts at the 76 files that still offend and can only shrink — it doubles as the worklist for routing them through the chokepoint, which is where the flag stops being a per-call-site decision at all. Diagnosed in stablyai#14589; the SSH and cookie-import sites it also covered are already fixed on main by the W1 migration. Co-authored-by: OrcaWin <orcawin@users.noreply.github.com> * test(wsl): stop the exec-mode guard scanning historical release checkouts The cross-version e2e lane checks whole past releases out under `tests/e2e/.cross-version-checkouts/`. The guard walked into them, so on any machine that had run that lane it reported 21 offenders -- every one a copy of shipped code we cannot edit -- and failed. Skip dot-directories; the >500-file vacuity assertion still holds. --------- Co-authored-by: OrcaWin <orcawin@users.noreply.github.com>
…ult (stablyai#16043) Three bugs in one screen, reported in stablyai#15256 with a diff of the user's orca-data.json showing defaultTuiAgent going from "claude" to null. 1. The Auto pill's handler writes null, and it was rendered as the ACTIVE choice whenever the stored agent was merely not detected right now. So the pill that already looked selected was destructive: one click erased the setting, and a later successful detection did not bring it back. Auto is now active only when null is actually stored. Detection is a transient fact; the stored value is not, and this control reports the stored value. 2. With zero agents detected there were no agent pills at all, so the stored choice was both invisible and unrecoverable -- nothing to click to put it back. The stored agent is now always offered, labelled as saved but not currently detected. 3. Refresh lived inside the Installed section, which only renders when at least one agent was found, so the only retry control vanished in exactly the state that needs it. An empty result now renders its own Refresh. This matters more now than when it was filed: stablyai#16028 makes WSL detection legitimately return an empty set on machines where the only agent was a Windows binary reached through interop, so the empty path is about to get more traffic. Each of the three tests was verified to fail with its own fix reverted.
… as a WSL install (stablyai#16028) * fix(preflight): do not count a Windows binary reached through interop as a WSL install WSL appends the Windows PATH to the guest PATH by default, so on a distro with no guest `claude`, `command -v claude` resolves to `/mnt/c/Users/me/.../claude.exe`. That path is POSIX-absolute, so the existing absolute-path check accepted it and preflight reported the agent as installed in the distro. That is worse than reporting it absent. Absent tells the user to install it; a false positive launches a Windows executable inside a Linux session, where it sees Windows paths, no guest $HOME and none of the distro's config -- and the failure surfaces later, somewhere less obvious. Rejects `/mnt/<drive>/` and any `.exe`, case-insensitively. A genuine guest install is unaffected. * fix(preflight): skip Windows mounts during the PATH walk, not after it The review caught this and it is the more important half of the fix. Rejecting the interop path in TypeScript happens after the guest walk has already stopped on it: the lookup breaks at the first executable, and the version-manager fallback dirs are APPENDED, so they sit behind the Windows entries WSL appends. A user with claude in nvm AND on the Windows PATH therefore went from a false positive to "not installed" -- the exact stablyai#9725 population the fallback dirs exist to serve. Worse than the bug being fixed. The lookup now takes `skipWindowsMountDirs` and skips those PATH components mid-walk, so the guest binary behind the shadow is still found. Matched by mount metadata from /proc/mounts (drvfs/9p/virtiofs), not by a `/mnt` name: the automount root is configurable, and `/mnt` is an ordinary directory on a Linux box. That also closes the custom-root hole the reviewers found in the name-based predicate. The TypeScript check stays as a secondary net for a mount the guest does not report, with a comment saying why it must never be the thing that decides. Proven with a real /bin/sh: a Windows `claude` ahead of an nvm `claude` on PATH now resolves to the nvm one. Credit: review counsel, and community PR stablyai#12794 (spfcraze), which proposed this shape first. * fix(preflight): let the mount table be the only word on what is a Windows path The name-based check could veto a path the walk had deliberately kept. /mnt/d is a perfectly ordinary Linux mount, so a guest binary there was resolved correctly by the walk and then discarded by its name -- the stablyai#9725 false negative, reintroduced by the belt-and-braces net I added "just in case". And if awk were missing, the name rule became the only rule, which is precisely the failure it was supposed to backstop. The walk skips components the guest itself reports as drvfs/9p/virtiofs. That is authoritative. Without a mount table we now degrade to main's behaviour (the old false positive) rather than inventing a new false negative. Net: one predicate, three fixtures and an import deleted.
…i#16032) * fix(wsl): budget the whole command line, not just the script The argv/stdin threshold measured `script.length`, but the cap applies to the finished command line -- which also carries `PATH=<login PATH>` and `HOME=`. A login PATH is itself a few KB. That produced a perverse band: with a long enough PATH, a 7,999-char hook was placed on argv and CreateProcess refused it, while the SAME hook at 8,001 chars flipped to stdin and ran. Size decided how a hook behaved, in the wrong direction, and the failure looked like "your setup hook failed" with nothing pointing at length. Now the argv form is built, measured, and only used if the whole line fits; otherwise the script goes to stdin as before. The count over-estimates slightly (it charges quoting for every argument) because over-counting is the safe direction for a cap. The regression test uses a 7,000-char script -- deliberately under any script-only threshold -- with a 27KB PATH, and asserts it lands on stdin. My first attempt used 7,999 + `echo `, which is 8,004 and flipped under the old rule too, so it passed either way and proved nothing. Credit: Grok. * fix(wsl): charge quoting and measure the line that is actually spawned Two under-counts the review found in the estimator I added. The doc comment claimed it over-counts. It did not: libuv escapes every `"` and doubles a backslash run before a quote, so a quote-dense script costs more than its length. And `wsl.exe` plus `-d <distro> --exec` are prepended AFTER the measurement, so ~45 characters of the budget were never counted. Together those put a quote-heavy ~26KB script on argv and over the real 32767 ceiling -- where the old script-only rule would have sent it to stdin and it would have run. A narrower band than the one this PR removes, but the same shape of bug, so worth closing before merge rather than after. Now charges one character per `"` or backslash and measures the full spawn line. New test: 26,000 quote characters must land on stdin; verified to fail with the quoting charge removed.
* fix(terminal): retain failed local console panes * fix(terminal): preserve failed pane restart context * fix(terminal): scope capacity recovery to PTY binding --------- Co-authored-by: OrcaWin <293788423+OrcaWin@users.noreply.github.com>
…#15883) Co-authored-by: Melih <mberatsanli@gmail.com>
… with detection (stablyai#16053) * perf(preflight): read the WSL mount table once per shell, not once per CLI The prelude is embedded in the lookup script, and the caller wraps that in `for cmd in <every agent>`, so the unconditional assignment forked awk once per probed CLI -- 36 of them inside the distro against a 10s detection budget. The comment claimed it was read once outside the loop; it was not. `${x+set}` rather than `[ -n ... ]`: a host with no Windows mounts yields the empty string, which must still count as read. Pinned by counting real awk forks through /bin/sh with a stub on PATH, because nothing covered this expression at all -- a wrong-field mutation shipped green. Verified to bind: the unconditional form counts 4 for 4 commands. * fix(wsl): make launch resolve the same binary detection reported Agent detection skips Windows mounts during the PATH walk; the Codex WSL command builder and the WSL branch of isCommandOnPath did not. So Orca could report the guest codex as installed and then launch the Windows one sitting ahead of it on PATH, or disagree with itself between preflight and detection about the same distro. Both now pass the same option. Verified on a real Windows host against a real WSL2 distro, with a Windows binary planted ahead of a guest one on PATH: plain `command -v orcaprobe` -> /mnt/c/Users/neil/orca-agree/orcaprobe this lookup -> /home/neil/.orca-agree/bin/orcaprobe That host reports /mnt/c as 9p, which the mount expression matches, so the fstype list is confirmed against hardware rather than fixtures. * test(preflight): prove the memoised mount list applies past the first command Counting awk forks with a stub that reports no mounts cannot see what the hoist trades correctness for. A mutant that empties `_orca_win_mounts` inside the walk keeps the fork count at 1 and keeps every existing test green, while every agent after the first stops skipping /mnt. This runs two commands behind a stubbed Windows mount and asserts both resolve to the guest binary. Verified against that exact mutant. Credit: review counsel.
…stablyai#15998) * fix(runtime): classify tui-idle from the visible screen only The adopted-PTY tui-idle probe added in stablyai#15569 read the provider snapshot as `scrollbackAnsi + data`, and the Codex readiness classifier matches the startup banner. For a daemon-hosted adopted worker — where the retained tail stays empty forever — every wait re-probed and could resolve `satisfied: true` off banner history while Codex was actively working, turning a loud timeout into a silent false ready. - probe now requests and parses the visible grid, never scrollback - retirement of a timed-out provider acquisition is checked before the re-acquire branch, so a wider row request can no longer resurrect a hung provider - probe builds its result before clearing the poll interval, so a stale handle cannot leave the waiter with neither poll nor probe Fixture follow-ups from the same review: - resume legs pin the captured `launchConfig.agentCommand` to the fake instead of bare `codex`, which resolved the machine's real Codex off PATH - the command override is quoted for the Windows shell the runtime will actually use, and specs pin that shell alongside the override - fake agents acknowledge a bare submit after a short grace, so an unbracketed delivery path fails with a diagnosable ACK instead of a suite timeout Refs STA-4907, STA-4885 * test: assert tui-idle probes serialize visible grid only - Verify idle timeout probes exclude scrollback from serialization - Add test case for Git Bash shell path quoting with apostrophes - Simplify verbose test helper comments * test: improve fake agent paste protocol validation Refactor paste end detection to properly track both begin and end markers, validate bracketed paste protocol (RFC 2544) through chronological event sequencing, and emit correct error messages for protocol violations. This ensures reliable detection of when pastes complete even when delivered across multiple chunks, and correctly distinguishes between bracketed and unbracketed paste modes. * fix(runtime): reject provider snapshots when live output advances Provider snapshots become stale when live output is received after the snapshot is requested. Reject snapshots where the current output sequence exceeds the snapshot sequence, preventing callers from consuming outdated terminal state. Add tests verifying stale frame rejection.
…tablyai#16149) * refactor(renderer): use terminal paste sanitizer directly * fix(runtime): order visible probe timeout settlement * fix(runtime): skip unorderable visible probes
…5172) * rm unused files * remove unused files * Refactor PTY IPC and add host environment paths - Split PTY handlers out of inline baseline checks - Rename local PTY shell provider for clarity - Pass userDataPath and resourcesPath to host environment * Establish PTY daemon identity before first await in spawn flow Move identity setup, session ID minting, and hidden delivery state to the beginning of preflight, ensuring these complete synchronously before any awaited operations. Defer async operations like folder workspace validation; add liveness tracking for SSH provider failures. Refactor pane spawn reservation to prevent concurrent spawns from creating duplicate providers. * Add incarnationId tracking throughout PTY exit lifecycle Track PTY incarnation IDs in exit messages sent to renderer, and add cause tracking for exit events. This enables proper lifecycle state management when PTYs can be respawned or have multiple concurrent instances. Also adds deadline support to process listing operations and stop-request tracking for better shutdown observability. * Use fake timers in SFTP namespace tests for deterministic abort handling Tests now use `vi.useFakeTimers()` to control time during abort scenarios, advancing timers explicitly instead of waiting on real async delays. Ensures more reliable test execution without flakiness from timing-dependent behavior. * Fix PTY spawn lifecycle: handle concurrent races and cleanup abandoned a Properly release Agent Teams leader handles when spawns are abandoned or fail, restore provisional PTY sizes on reattachment, and settle concurrent spawn races for the same pane. Add validation guards for destroyed renderers and improve handler re-registration to reset delivery state before bridging a new window. * Move PTY cleanup to localized error boundaries Restore provisional PTY size when build-options fails and guard pre-allocated handle registration. This ensures cleanup happens at the point of error, not deferred to the general catch block. * Replace Promise.resolve() with vi.waitFor in PTY claim test Wait explicitly for the providerSpawn call to be made using vi.waitFor() instead of relying on event-loop yielding. This makes the test more deterministic and reduces flakiness from timing assumptions. * Redact PTY IDs in pending data drop diagnostics Prevent workspace paths embedded in session IDs from leaking through diagnostic logs by using redactPtyIdForDiagnostics. * Mark PTY exit events as observed by provider Exit handlers now receive `providerExitObserved: true` to distinguish definitive provider-witnessed exits from inferred state changes. Preserves optional exit cause when present. * Add defensive input validation to PTY IPC handlers Validate that IPC arguments are present and the correct type before passing them to handler logic. Uses optional chaining and type checks to safely handle malformed requests from the renderer process. * Replace direct Electron imports with PTY host bindings Abstract app, ipcMain, and powerMonitor access through getter functions to support multiple host environments and improve testability. * Defend against transient PTY setup failures with state cleanup Host-env setup failures now trigger cleanup of runtime-allocated PTY state. Cached PTY geometry is preserved after transient reattach failures but cleared when the provider reports the PTY exited before the spawn reply—preventing stale geometry from corrupting future operations. Error handling now distinguishes expired SSH sessions and early-exit conditions to preserve geometry appropriately.
…iation stablyai#15172's split modules pass providerExitObserved to onPtyExit, but the option was declared by stablyai#15212, which this release deliberately does not carry — it is only reachable via stablyai#15166, whose split silently drops the SSH reconnect model-paint gate from stablyai#14844 (STA-5395). Widen the option type so the split typechecks, and take stablyai#15212's assertion updates for the three test files that observe the call shape. The behaviour stablyai#15212 adds — reconciling agent status on a certified process death — is NOT included; the option is accepted and unused.
…ai#16414) * fix(remote): stop an empty host inventory settling the mirror An inventory with zero published snapshots satisfied `settles.length === fullInventory.publishedSnapshotCount` as `0 === 0` and fired the environment-wide host-mirror verdict with no host evidence behind it. A live relay/SSH-paired host answers exactly that until its renderer's first publish, so the drained resume sweep forked a second agent onto a PTY the host was still running. Gate that one case behind a `terminal.list` readiness probe: it reads the PTY controller, not the session-tab mirror, so it sees live PTYs the mirror has not published. Only "no terminals" settles; live or unverifiable leaves waiters parked for the next inventory or per-worktree frame — a host with genuinely zero terminals still settles, so panes do not park forever. Fixes STA-5377 * fix(remote): fence host readiness probes by generation * fix(remote): preserve legacy terminal probe fallback
…73) (stablyai#16345) * test(pty): pin the renderer-liveness guard STA-2373 relies on (STA-5373) STA-5373 reported that stablyai#15927 dropped the `webContents.isDestroyed()` half of the guard stablyai#10065 added for STA-2373, and that the app therefore dies when a daemon death fans out to every pane. The guard is present on main: stablyai#15172 restored it at both senders when it split the PTY monolith, and a per-file count across v1.4.188..HEAD shows only relocation (pty.ts:4 -> write-input.ts:2 + bind-listeners.ts:2). The reported 4 -> 0 was scoped to `src/main/ipc/pty.ts`, now a 39-line barrel. No production fix is needed. What was real is that nothing pinned the guard — it survived stablyai#15927 only because stablyai#15172 happened to re-expand it — and the shared PTY test fake made that invisible: its `webContents` had no `isDestroyed` at all, so both guards passed vacuously in every suite. That is also why they are written defensively as `typeof ... === 'function' && ...`. - Give the fake an `isDestroyed` mock, re-stubbed to `false` each beforeEach rather than left `undefined`, so "alive" is stated rather than accidental. - Cover both senders red/green: the daemon-death fan-out (bind-listeners.ts:37) and the per-write reporter (write-input.ts:57). Verified red against a window-only guard and green with the real one. The per-write case needs a chunked write. A single-chunk write is already fenced by `isPtyWriteEventFromMainWindow`, which rejects the event once the WebContents is gone; only the multi-chunk path yields a macrotask mid-write, letting the renderer die after the sender check passes. That is the sole route to this sender with a dead WebContents, and what makes its own guard load-bearing. Also deletes `src/main/ipc/pty-renderer-surface.ts`: zero importers repo-wide, and its `isRendererGone` is exactly the weakened predicate. Its comment claims the headless path "now passes null", but register-headless-runtime.ts:26 still fakes `{ isDestroyed: () => true }` — stablyai#15172 rolled that back too. Adopting it would reintroduce STA-5373 for real. Verified: 17 tests across the two pty write suites; full src/main/ipc run 3156 pass (4 pre-existing @parcel/watcher failures in filesystem-watcher-real and worktree-base-directory-poller, unrelated and failing identically on a pristine tree); pnpm typecheck clean; oxlint clean. * docs(pty): correct headless-path comments the stablyai#15172 rebase left stale stablyai#15927 made `registerPtyHandlers` accept `BrowserWindow | null` so the headless path could pass null instead of faking a window. stablyai#15172 reverted that signature while splitting the PTY monolith, but the comments describing it survived, so three of them now document an API that does not exist. - orcad-entry.ts: the module docstring claimed orcad installs its controller via `registerPtyHandlers(null, …)`. It uses `registerHeadlessPtyRuntime`, and null is not accepted. It also claimed desktop surfaces are "declared rather than faked" — true except for the renderer window, which is still faked. - register-headless-runtime.ts: record why the fake is safe rather than leaving `isDestroyed: () => true` looking arbitrary. It is load-bearing: every renderer-liveness guard reads it and skips, so no send is attempted. Also gives the fake a `webContents.isDestroyed`. The real guards check both, and a missing method reads as "alive" — the same gap this PR fixes in the test fake. No behavior change: the window-level check already short-circuits. Verified: 45 tests across the liveness-guard, startup-barrier, management and kill/exit suites; pnpm typecheck clean; oxlint clean. (cherry picked from commit 0bfd380)
…tablyai#16569) A push target that reuses an existing Orca-created fork remote inherits ownership of it (`remoteCreated = isRemoteCreatedByKnownWorktree(...)`), so the final worktree to be deleted can remove it. Rollback then reused that same flag to decide whether to undo its own work -- but a reused remote was not added by this call, and a live sibling worktree is still pushing to it. A failed fetch during create therefore deleted a remote another worktree depends on. Track `remoteAddedHere` separately: ownership stays inherited for cleanup, while rollback only removes a remote this call actually added. Both the local and the SSH path had the same bug and are fixed together. Original work by Jinjing (AmethystLiang) in 616d2a4ec8c; split out of that branch so the release fix in stablyai#16550 stayed a clean cherry-pick. (cherry picked from commit 1c9fb84)
(cherry picked from commit 2f5f5ce)
…inding (stablyai#16550) Co-authored-by: Neil <4138956+nwparker@users.noreply.github.com> (cherry picked from commit e4d95e0)
…auto-sync-fork-with-upstream-stablyai-orca-ru-20260826T2302
Resolve every differing path against config/fork-ownership.json after the -X ours merge of upstream v1.4.190: 785 upstream-owned paths reset to the tag, 16 removed, 83 fork exceptions restored to the fork side, 551 seam and feature paths left on their real three-way merge for hand review.
v1.4.190 dissolves src/main/ipc/pty.ts (8030 lines) into 73 modules under src/main/ipc/pty/ and leaves a 39-line barrel. -X ours defended the fork's stale monolith while the merge took the new siblings, so both implementations were live at once. Move the terminal-dock ack'd-send seam into the modules that now own the code (write-input.ts, write.ts, register-handlers.ts), restore pty.ts to the tag's barrel, and repoint the manifest's seam and residual entries together. Also repair two hunks -X ours discarded: tab-types.ts lost upstream's ExecutionHostId import while keeping the executionHostId field that uses it, and web-session-tabs-sync.ts's two fork call sites lost the environmentId argument buildTerminalUnifiedTab now needs for executionHostId.
A whole-file exception wins outright, so upstream's unrelated work under those paths is dropped every sync. Replay v1.4.188..v1.4.190 into each, keeping the fork's own lines: - package.json: take the runtime-electron ratchet in lint, the four new build/smoke scripts, and the @vscode/windows-process-tree optional dep and patch entry. pnpm-lock.yaml resolves to the tag, so --frozen-lockfile fails without the dep. - package-electron-runtime-contract.test.mjs: take the process-tree contract and the loosened rebuild-script assertions, keeping the fork's macOS-only release and golden-matrix expectations. - pr.yml: take the runtime-electron ratchet, the orcad terminal smoke, the new shell-contract and Windows test files, and the patched node-pty rebuild, keeping fork_ownership_guard. - TerminalPane.tsx: take the TerminalProcessExitOverlay feature, which the tag's pty-connection deps already expect. - reliability-gates.jsonc: take the tag outright. The fork copy holds no fork-specific threshold — identical policy block, no fork-only gate, just four missing gates and nine stale evidence sets. - max-lines-baseline.txt: prune the pty.ts entry the module split retired. - STYLEGUIDE.md: name the shadow-floating token main.css now defines.
v1.4.190 makes runWslProcess the one chokepoint for wsl.exe (stablyai#15903, stablyai#15923) and runProcess the one chokepoint for child processes (stablyai#15746), and both are now ratcheted. The fork's live-plugin-marketplace WSL source still called execFile('wsl.exe', buildWslExecArgs(...)) directly, which broke five checks from one cause: - child-process-import-boundary: a direct node:child_process import, and the offender count 153 over its 152 ceiling - wsl-invocation-boundary (unit and package (windows)): a direct wsl.exe spawn - skill-discovery-wsl-plugins: upstream's test mocks runWslProcess and expects two calls; the fork's execFile bypassed the mock, so the scan consumed the metadata frames and parseWslSkillDiscoveryOutput rejected record kind F - the feature's own WSL tests, which mocked child_process Adopt the sibling reader's migrated shape (loginPath 'none', shell 'bash', maxOutputBytes, throw on non-zero or timeout) — the payload is that reader's and stays bash. The runner takes the script unencoded, so the test's base64 decode is gone; the --exec assertion is replaced by one on the spec the fork now owns, since --exec and payload transport moved into the runner.
zpyoung
deleted the
zpyoung/auto-sync-fork-with-upstream-stablyai-orca-ru-20260826T2302
branch
August 26, 2026 23:54
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Absorbs upstream stable v1.4.190 (
6e4f817101daa18d82824b69243d9079baa9c416) into the fork.Resolution
v1.4.190at6e4f817101mainv1.4.188atf32ce85904auto-ours— clean merge conflicted on 3 paths, retried with-X ours, no tree conflicts, no surviving conflict markersorigin/backup/main-20260826-230524Zatd63e0ca6c1v1.4.190 is a module-split release.
eb1792985fdissolvessrc/main/ipc/pty.ts(8,030 lines) into 73 modules undersrc/main/ipc/pty/, leaving a 39-line barrel.-X oursdefended the fork's stale monolith while the merge took the new siblings, so both implementations were live at once. Handled in6a79baa796.Ownership lists
1,435 differing paths classified by
config/scripts/sync-upstream-file-ownership.mjsagainstconfig/fork-ownership.json:checkout.txt— 785 upstream-owned paths reset to the tag. Only one differed from the merged tree after-X ours:src/main/codex-accounts/wsl-codex-command.test.ts.remove.txt— 16 paths the tag dropped or the fork deliberately deletes.ours.txt— 83 fork exceptions restored to the fork side.merge-review.txt— 551 seam and feature paths left on their real three-way merge, reviewed by hand (below).merge-review.txt— hand review--verify-seamspassed on the raw merge (388/388 lines across 200 files), but--verify-residualscaught three seam files whose measured footprint had drifted. All three were the paths that conflicted on the clean-merge attempt:src/main/ipc/pty.tssrc/renderer/src/runtime/web-session-tabs-sync.ts-X oursdropped the newenvironmentIdargument at both fork call sites ofbuildTerminalUnifiedTab, which the tag's signature now requires forexecutionHostId. Restored; re-baselined to +144/-28 (the fork has two call sites where the tag has one).src/shared/tab-types.ts-X oursdropped upstream'sExecutionHostIdimport while keeping theexecutionHostId?field that uses it — a latent TS2304. Import restored; budget unchanged at +4/-0.The remaining 548 paths are fork-only files under a feature glob, or seam files whose declared lines and residual budgets both verified unchanged.
pty seam re-homing. The fork's 96-line
terminal-dockack'd-send seam moved into the modules that now own the code:src/main/ipc/pty/ipc/write-input.ts—writePtyProviderInputAcknowledged,writePtyProviderInputAcknowledgedChunks,writePtyInputProvablyLive, and thesplitTerminalInputChunksimport (+85/-1)src/main/ipc/pty/ipc/write.ts— thepty:writeInputAcceptedhandler (+13/-0)src/main/ipc/pty/register-handlers.ts— itsremoveHandlerteardown (+1/-0)src/main/ipc/pty.tsis back to the tag's barrel; the manifest'sseamsandresidualsentries were repointed together. Preload and renderer sides ofwriteInputAcceptedwere untouched by the split and needed no change.Checklists
Tier-2 forked-copy replay — 16 copies, no replay needed. Every copy headed by
FORK-COPY-OFrecordedf32ce85904(v1.4.188). All 16 recorded upstream sources are unchanged between v1.4.188 and v1.4.190, none exist at the tag, and all are covered by a feature glob.FORK-COPY-SHAadvanced to6e4f817101on all 16 per the reference's rule that headers move together even on an unchanged path. Two copies carry a leading vitest pragma that puts the headers on lines 2–3; parsed accordingly.Tier-4 pending-upstream — 21 entries, all still valid. Every declared path still exists, and all 7
docs/fork-upstreaming.mdledger anchors resolve — no stale manifest row, no orphaned ledger entry. OnlyTerminalPane.tsxsaw upstream movement in range (below).Upstream feature collision — 11 features, all
none. Upstream touched no file undersrc/renderer/src/components/native-chat/,src/main/native-chat/, orsrc/renderer/src/components/right-sidebar/in this range, clearingnative-chat-relay,native-chat-coloring,native-chat-width,native-chat-session-options, anddirty-branch-indicator.ac103f5d90routes project-group rename/delete to the owning host but does not touch cross-repo group membership (worktree-groups). The skills commits (8d1557c225,1ce2e562b3,29109f6647,9e335e9a37) add a WSL/Hermes discovery source and fix upload staging; none attribute a skill to its plugin or read a live marketplace directory (skill-plugin-attribution,live-plugin-marketplaces). Theagent-resumecommits restore Copilot/Kimi sessions after restart, a different mechanism fromsession-handoff.TerminalProcessExitOverlayis a pane overlay, not a composer (terminal-dock,agent-composer).Exceptions that discarded upstream work
A whole-file exception wins outright, so upstream's unrelated work under those paths is dropped every sync. Nine
ours.txtpaths saw upstream movement in range; all were replayed in8e1c5b50b0, keeping the fork's own lines:package.json— took thecheck:runtime-electron-ratchetstep inlint, the four newbuild:orcad/smoke:*/ ratchet scripts, and the@vscode/windows-process-tree@0.8.0optional dependency plus its patch entry.pnpm-lock.yamlresolves to the tag, so--frozen-lockfilefails without the dependency. Kept the fork's version, sandboxedtestscript,test:sandbox, fork localization checker, and React Doctor rule overrides.config/scripts/package-electron-runtime-contract.test.mjs— three-way merged with v1.4.188 as base: took the new process-tree contract test and the loosened rebuild-script assertions (the tag'srebuild-native-deps.mjsnow uses a multi-entry spread the fork's pinned literal no longer matches), kept the fork's macOS-only release and golden-matrix expectations..github/workflows/pr.yml— took the runtime-Electron ratchet, theorcadterminal smoke, the new shell-contract and Windows test files, and the patched node-pty rebuild, keepingfork_ownership_guard.src/renderer/src/components/terminal-pane/TerminalPane.tsx— took the wholeTerminalProcessExitOverlayfeature, which the tag'spty-connection-typesdeps already expect.config/reliability-gates.jsonc— took the tag outright. The fork copy holds no fork-specific threshold: identicalpolicyblock, no fork-only gate, and every difference is upstream's newer evidence against the stale inherited copy (4 missing gates, 9 stale evidence sets). 84 → 88 gates.config/max-lines-baseline.txt— pruned thesrc/main/ipc/pty.tsentry the module split retired.docs/STYLEGUIDE.md— named theshadow-floatingtokenmain.cssnow defines.docs/assets/readme-downloads.svg,resources/skills/release-mapping.json— deliberately not replayed. Both are fork-owned artifacts by design; the release-mapping exception exists precisely because upstream's rows namestablyai/orcatags absent from this remote.Verification
Step 8 gate, all green locally:
pnpm install --frozen-lockfile--verify-seams--verify-residualsvsv1.4.190pnpm typecheck(after clearingconfig/*.tsbuildinfo)pnpm lint.github/scripts/check-fork-ownership.mjsTests are deliberately left to this PR's own CI. Vitest cannot run on the machine the sync runs from; the
testmatrix here runs the same suite on clean hosted runners, sharded 16 ways across two Node versions, as a required check forverify.