Skip to content

fix(terminal): one intentional-stop register, and per-run spawn and input facts - #22989

Merged
brennanb2025 merged 20 commits into
mainfrom
brennanb2025/terminal-run-facts
Sep 28, 2026
Merged

brennanb2025 merged 20 commits into
mainfrom
brennanb2025/terminal-run-facts

Conversation

@brennanb2025

@brennanb2025 brennanb2025 commented Sep 26, 2026 •

Copy link
Copy Markdown
Contributor
Files Added Deleted Net
Test 92 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​2427 $\color{#cf222e}{\Huge{\mathbf{−}}}$​562 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​1865
Prod 81 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​710 $\color{#cf222e}{\Huge{\mathbf{−}}}$​312 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​398

ELI5

Sometimes Orca stops a terminal's process on purpose: when you put a worktree to sleep, when a finished agent pane is hibernated, or when Codex restarts after an account switch. The tab is meant to stay, so the process can be woken up or replaced.

On main, the code that reacts to a process ending could not tell those stops apart from a process dying on its own. So when you put a worktree to sleep, Orca deleted its terminal tab from the saved session. After a restart the tab was gone, and waking the worktree opened a brand-new terminal with the old output lost.

This PR keeps one list of stops Orca made on purpose, and every place that reacts to a process ending reads it. A slept tab now survives a restart and wakes with its output.

It also has Orca record two facts about each run of a terminal's process: whether the process was freshly started for its pane, and when input first drove it. The next PR in this series uses them to decide what happens to a tab when its process exits (see "Why the run facts ship first" below).

What Changed

Before (what the user saw): sleep a worktree, quit Orca, reopen it: the terminal tab is gone and the pane is blank. Waking the worktree creates a new tab with a new shell and none of the old output. Hibernating a finished agent pane and a Codex account restart went through the same exit handling, and also removed the pane from the saved session and from what paired devices (phone, web) see.

After: the saved tab, its link to its terminal process, and the identity of that process run all survive the sleep. After a restart Orca restores the same tab and terminal with its output, and the shell works.

Terms used below:

  • Process run: one start of the process behind a terminal. A terminal's id can outlive its process (a restart or a wake starts a new process under the same id), so Orca tags each run with its own id. In the code this is the incarnation.
  • Binding: the saved link from a pane to the terminal process it shows.

Mechanism 1: one list of intentional stops (src/main/runtime/terminal-intentional-stops.ts)

  • On main, four separate "I stopped this on purpose" markers lived in four places. The code that handles a process exit read only one of them (the one for a stop requested by a remote client). So a local sleep, the runtime's sleep, a hibernation and a Codex restart all looked like a process dying on its own, and Orca removed the pane.
  • All four stop paths now write one list, and every exit reader reads it: the main exit handler, the delivery of the exit to the desktop window (its two existing flags, "keep the pane's binding" and "a replacement is taking this pane", now come from the list), and the record of an SSH kill that could not reach the host.
  • An entry names the terminal and the process run it stopped, so a later process that reuses the terminal's id is never mistaken for the stopped one.
  • There are two kinds of stop: reversible (sleep, hibernation; the binding is how the pane wakes) and replaced (a restart hands the pane to a new process). Owners are counted per kind, so if a sleep and a restart stop the same process, its exit carries both labels. A stop that fails removes only its own kind.
  • Reading an exit does not delete the entry, because one stopped process can be reported as exited twice. When a kill's reply arrives before the process's own exit event, Orca reports the exit itself right away. The process's own exit still arrives later and is still processed, because it is what confirms the process is gone and releases its late output. Both reports must get the same answer, and so must the two readers of each report (the main exit handler and the desktop window). The entry therefore expires 30 seconds after its last owner's stop finishes, which is the same window Orca already uses to drop that duplicate exit, or at once if the stop failed. A new process committing under the same terminal id also ends an entry that no exit ever matched to a run.
  • Deleted: markReplacedPtyStop/replacedPtyStopsById, markReversibleStops/reversibleStopOwnersByPtyId (session, controller and controller contract), and the runtime's intentionalHandlelessPtyStops.

Mechanism 2: per-run facts (src/main/runtime/terminal-run-facts.ts, kept in memory per process run, pruned with the runtime's record of the terminal)

  • Freshly started: recorded once per process run, after its binding is saved and the runtime has registered it, at both places a new terminal process is committed (desktop and runtime). Reattaching to a live process, adopting one, or restoring one after a restart does not count as fresh. A run Orca never saw committed reads as not fresh, which gives today's behaviour (the tab closes when its process exits).
  • First input: every write to a terminal now states what it is, with a required TerminalInputKind (src/shared/terminal-input-kind.ts):
    • driving: input that drives the run: keystrokes (including IME and Hangul composition, which xterm reports as user input), paste, drop, quick commands, captured keys, native chat sends, terminal.send and streamed input from any client, typing in the dashboard preview, orchestration dispatch, mailbox pointers, plugins and agent teams;
    • launch: bytes Orca writes to start the run: startup and restored commands, the command a restore re-runs, the SSH background launch command, a worktree-create draft and follow-up, and the agent launch prompt;
    • query-reply: the terminal's automatic answers to the running program (xterm's replies and focus reports, capability replies, headless replies, the focus-in replayed on reattach).
  • Orca records the first driving input at one place, which both write paths (desktop and runtime) call just before the write reaches the process. It is recorded before the write because input such as exit can end the process before the write returns. A payload that is only a terminal reply or only focus reports never counts, whatever its label.
  • The kind is required with no default, so a new writer does not compile until it chooses one. The runtime files that skip type-checking (@ts-nocheck) are covered by a source-scan test that fails on any terminal write there without a kind. The one unavoidable default is input arriving over the network from a client that sends no kind: it counts, unless the payload is only a reply or focus reports.

Why

Why one list. Four separate "stopped on purpose" markers each answered the same question for one caller, and the exit handler asked only one of them. That is why sleep, hibernation and the Codex restart all lost the tab. With one list that every exit path reads, a new kind of stop cannot be forgotten by a reader.

Why a required input kind. An optional "user input" flag had opposite defaults on different write paths, so any writer nobody classified silently took whichever default its path had. Review found three such misses in a row: focus reports from paired devices, typing in the dashboard preview, and a create-time draft tagged on one path but not on its twin in main. A required kind turns an unclassified writer into a compile error instead of a silent default. Where a default cannot be avoided it counts the input, which errs toward today's behaviour (the tab closes on exit) rather than wrongly keeping a tab someone typed into.

Why the run facts ship first, before anything reads them. The next PR in this series has main decide, at the moment a process exits, whether its tab stays or closes. It keeps a tab whose process was freshly started and never received input, and closes the rest. That rule is only as good as its facts, and they have to be recorded by every writer from the moment each process starts; a reader added later cannot recover them for runs already in progress. Threading the input kind through every writer is most of this diff. Landing the facts now, where they change no behaviour of their own, keeps the next PR's actual behaviour change small enough to review on its own. Until then a mislabelled write has no effect, because nothing reads the facts.

Why entries are not deleted when an exit reads them. "Delete on first read" breaks even a single hibernation, because the exit handler and the desktop window both read that exit. It also misreads the process's own late exit after the one Orca reported itself. Tests prove both.

Why launch bytes do not count as input. A prompt passed at launch is the start command, the same fact as a prompt passed on the command line, which never counts. The next PR's rule asks whether anything drove the run after it started.

Why the facts are per process run and kept in memory. A terminal's id can outlive its process (restart, wake, reattach). The next PR needs facts about the process that exited, not about the id, and nothing about a run is useful after the app restarts.

Differences from the common pattern

  • First input: the common pattern records the first input once, at the host's input boundaries, before forwarding it. This PR matches that placement and the write-once rule. It differs in three ways:
    • lifetime: in memory per process run, not saved per terminal row;
    • labelling: each write states its kind at the writer, because Orca's write paths also carry startup commands and terminal replies;
    • replies: terminal replies and focus reports are excluded, where the common pattern counts them.
  • Intentional stops: the common pattern either detaches the process from its session before killing it and ignores that process's later events, or sends the stop reason with the kill and has the exit echo it back. Orca instead records the stop in one list and lets exits read it. A stop can be requested from four different layers, and a stopped process's own late exit must still reach the runtime to confirm the process is gone, release anything waiting on the kill, and discard late output.
  • Remote Orca servers: the desktop's connection to a remote Orca server cannot send a kind without a wire change, so on a remote server the desktop's launch bytes count as input. That errs toward today's behaviour (close on exit). There is no wire change.

Linked Issue

No tracking issue. This is the run-facts step of the terminal tab membership series; it is independent of #22929 and targets main.

Visual Proof

Live on a separate macOS machine, isolated profiles, identical starting state. Open a terminal, echo a marker, Sleep the worktree from the sidebar menu, quit Orca, relaunch, click the worktree.

main (600adba) this PR
after restart main after restart PR after restart
after wake main after wake PR after wake
  • main: 5 s after Sleep the saved session no longer lists the tab, and its binding is deleted; after restart the pane is blank, and wake creates a new tab without the marker.
  • this PR: the saved tab, its binding and its process run survive; after restart the same tab, pane and terminal come back with the marker in the scrollback, and the shell works. Sleep then wake without a restart also keeps the same tab, and typing, paste and Enter reach the shell: PR wake without restart

Testing

  • I manually tested these changes locally (live Electron QA on a separate macOS machine, main vs this PR; see Visual Proof)
  • Automated tests added/updated, or explained why not below

New tests (each proved red by deleting its core line, then restored):

  • A hibernated pane keeps its tab and binding; a Codex restart of a pane the user typed into keeps the tab and binds the replacement; a runtime worktree sleep keeps its tabs and bindings (on a folder workspace).
  • The exit Orca reports itself on a kill, followed by the process's own late exit, keeps the pane; a later process on the same id is never read as stopped; the entry expires when the window closes; a new process ends a stop no exit pinned.
  • A sleep and a restart that stop the same process both label its exit; a runtime kill during that overlap still records the stop as reversible.
  • Fresh spawn: an adoption and a cold restore are not fresh; a re-registration keeps its facts; a new process, or a commit with no process-run id, starts clean.
  • Input kinds, through the real write funnels: terminal.send, stream input, dispatch, mailbox pointers and preview typing are recorded before the write; a launched run stays untyped until a driving write; a create-time draft and follow-up leave the run untyped, and the renderer and main routes for the same draft agree; wire replies, reply-only and focus-report-only payloads are not recorded; a reply mixed with a keystroke is.
  • The renderer tags each kind at the IPC, never merges bytes of different kinds, and keeps kinds across the pre-connect buffer and a remount. IME and Hangul commits reach the PTY as driving input, driven through a real xterm.
  • The source scan fails on a kind-less PTY write planted in a @ts-nocheck runtime file.
  • Both spawn-commit funnels (desktop IPC and runtime) record a run's facts only after its binding save and registration succeed: a spawn discarded for a failed save, or rejected for exiting during start, records nothing and leaves an earlier stop in place.

Suites: typecheck (node, web and CLI), full-repo oxlint, the changed-code quality gate and React Doctor are clean. The main runtime, PTY IPC, plugin, cross-version wire and renderer terminal-pane suites pass; the only failures seen were timeouts under machine load in files this PR does not touch, which pass when run alone. CI is green.

AI Disclosure

Implemented with Claude (Opus) coding agents under Brennan's direction. Reviewed through seven independent AI review loops plus an architecture challenge, with live Electron QA of main against this PR on a separate machine.

Review

Agent skill upstream boundary

  • Not applicable, or this change follows docs/reference/agent-skill-sharing-upstream-boundary.md and copies or mechanically translates no upstream skill-installer source, tests, fixtures, registry entries, path tables, comments, or documentation.

Notes

  • Known issue, not caused by this PR, fixed separately (paired devices only): after a restore that has to start a new process (for example after a reboot), or a wake more than 30 seconds after a sleep, a paired phone or web client can intermittently miss the kept terminal until its tab changes. When a pane's saved process is gone, Orca's first reattach attempt reports it as exited. Once the stop's 30-second window has passed, that report removes the pane, and the new process then adds it back. The desktop always gets the same tab back with its output. But the gate that decides what paired devices see can keep an update it had filtered down to zero tabs. This reproduces on main with no sleep: kill the terminal daemon, then relaunch. This PR makes local wakes reach it because main no longer deletes a slept tab. The root fix, treating a new process for a pane's saved terminal as a replacement rather than a death, lands in its own PR.
  • Known issue, not caused by this PR: during that restart of the process, the saved session briefly lacks the tab between the reattach attempt and the new process being saved, so a crash in that gap loses the tab on the next restart. Main has the same gap on every restore that starts a new process, and the same separate fix removes it.
  • SSH: an SSH exit that arrives after its stop finishes, within the 30-second window, still counts as intentional. Loss of contact is unchanged: an SSH exit that is not confirmed stays "unverifiable".
  • Folder workspaces: nothing here depends on git; the sleep test runs on a folder workspace.
  • Mixed versions: no wire change. The input kind is on same-build desktop IPC and main's internal writes. inputKind: 'query-reply' was already on the terminal.send wire, and input from an older client goes through the same reply check.
  • Performance: one map lookup per exit, and one per driving write only until the run's first input is recorded. The reply check stops running once it is recorded.
  • Windows: no platform-specific paths.
  • Size: most of the diff is threading the required input kind through existing writers and their test expectations. Production code is about +400 net lines.

Author X handle: @BrennanKB5

Checklist

  • This PR is small and focused (focused on one mechanism, but not small: the required input kind touches every terminal writer)
  • I explained what changed and why (ELI5, the user-facing before/after, the mechanism, and why over the alternatives)
  • Before/after screenshots or videos attached for UI changes, or N/A with reason
  • Self-reviewed for correctness, security, and performance
  • Cross-platform, SSH/remote, and path/shortcut impact considered (or N/A)
  • pnpm lint, pnpm typecheck, pnpm test, and pnpm build pass (or CI will cover; local preferred)

…put facts

Main now keeps one register of PTY stops it made on purpose, with an owner
count and a kind: reversible (sleep, hibernation) or replaced (a restart
handing the pane to a new process). It replaces four separate markers, and
every exit path reads it, so a hibernated or restarted pane keeps its tab and
binding through the exit instead of being retired and grafted back.

Main also records two facts per process run, keyed by incarnation: whether the
run was a fresh spawn (from the spawn-commit origin, which now counts a cold
restore as a reattach) and when a client first sent it input a person
produced. Renderer keystroke, paste, drop and quick-command writes carry a
userInput flag; terminal.send, stream input and dispatched agent prompts are
recorded by the runtime, excluding terminal query replies.
… keep its pane

One process can reach the runtime's exit handler twice: main's synthetic exit
when the kill reply overtakes the stream, then the provider's own exit, which
certifies the death. Both must read the same stop, a later process on the
same id must not, and the stop is forgotten when the duplicate-exit window
closes.
@coderabbitai

coderabbitai Bot commented Sep 26, 2026 •

Copy link
Copy Markdown
Contributor

Review in Change Stack →

Navigate logical layers of code changes, visualize relationships, and explore their blast radius.

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

PTY writes now require an input kind: driving, launch, or query-reply. Renderer queues, buffers, transport, preload APIs, IPC, and runtime write paths forward this classification. Run facts record the first qualifying driving input while excluding launch writes, query replies, and focus-report-only payloads. Spawn commits update run facts and intentional-stop state. Intentional stops are tracked by kind and process incarnation, and exit handling uses matching claims to set renderer exit flags.

Priority: ⬇️ Low

Merge Risk: 🔵 Low · up to 4029a

Terminal input can be recorded as having started too early, or not recorded when a malformed IPC write is accepted. These provenance errors do not currently block terminal writes, but should be corrected before the run facts are used for tab behavior. The overlapping-stop exit flags have been fixed.

Security Architecture Review

Security architecture risk: 🟡 Moderate · up to 4029a

Centralizing intentional stops should make terminal recovery more consistent, but it changes which panes survive a process exit. The new input labels also cross several terminal entrypoints. No current security decision using the new run facts was identified; incomplete coverage and an unresolved exit-ordering case warrant review without establishing a vulnerability.

Retained concerns
No architecture-level concerns identified.

Security review details

Security Blast Radius

  • inferred — The principal exposure is terminal state and binding ownership within the running application. Incorrect stop classification could retain a pane that should be retired; no new service, tenant, secret, or deployment authority is evidenced.

Trust Boundaries and Controls

  • observed — The renderer supplies a PTY ID, bytes, and input classification to main. Main checks PTY/provider availability and mobile-driver ownership before writing; its payload guard does not authenticate the classification. Deliberately supplying driving could alter the new fact, but the previous contract already let this renderer supply a userInput flag, and no current authority decision consuming the new fact was identified.

Resilience and Maintainability Implications

  • inferred — Incarnation matching limits cross-process stop claims when both IDs are supplied. A claim lacking an exit incarnation does not get that mismatch check, while a known landed mark can remain through the duplicate-exit window. The reviewed evidence does not establish whether a replacement process can produce such an unlabelled exit in that window.

Hardening Proposals

  • proposed — Before using run facts for tab retention or authorization, define whether driving denotes human input or any client-driven input, validate classification at trust boundaries, and bind delayed writes and exit claims to the process incarnation they describe.
🚥 Pre-merge checks | ✅ 4 | ❓ 1

❌ Failed checks (1 inconclusive)

Check name Status Explanation Resolution
Docstring Coverage ❓ Inconclusive Docstring coverage is 17.65% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 34 functions across 71 files. (95 skipped… Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Title check ✅ Passed The title clearly summarizes the two primary changes: consolidating intentional-stop tracking and adding per-run spawn and input facts.
Description check ✅ Passed The description is complete and directly addresses the template. It explains the user impact, mechanisms, rationale, testing, visual proof, AI disclosure, compatibility considerations, and checklist s…
Full details: Docstring Coverage

Explanation

Docstring coverage is 17.65% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 34 functions across 71 files. (95 skipped: 95 over the file limit.)

✨ Finishing Touches 💡 2
📝 Generate docstrings 💡
  • Commit to this branch
  • Create a new PR
⚔️ Resolve merge conflicts 💡
  • Resolve merge conflict in branch brennanb2025/terminal-run-facts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Advanced

Run ID: ee134418-631c-4001-8989-479344f680bf

📥 Commits

Reviewing files that changed from the base of the PR and between 8846987 and 576c196.

📒 Files selected for processing (62)
  • src/main/ipc/pty-daemon-ssh-lease-lifecycle.test.ts
  • src/main/ipc/pty-pane-restart-replace.test.ts
  • src/main/ipc/pty-ssh-undelivered-kill.test.ts
  • src/main/ipc/pty/delivery/exit.ts
  • src/main/ipc/pty/ipc/renderer-kill.ts
  • src/main/ipc/pty/ipc/spawn-commit-persist.ts
  • src/main/ipc/pty/ipc/write-input-user-input.test.ts
  • src/main/ipc/pty/ipc/write-input.ts
  • src/main/ipc/pty/register-handlers.ts
  • src/main/ipc/pty/runtime/controller-deps.ts
  • src/main/ipc/pty/runtime/controller.ts
  • src/main/ipc/pty/runtime/kill.ts
  • src/main/ipc/pty/runtime/spawn-commit-run-facts.test.ts
  • src/main/ipc/pty/runtime/spawn-commit.ts
  • src/main/ipc/pty/runtime/spawn-preflight-requested-shell.test.ts
  • src/main/ipc/pty/session.ts
  • src/main/persistence/loading-store/pty-binding-span.ts
  • src/main/runtime/orca-runtime-controller-knows-pty-is-live.ts
  • src/main/runtime/orca-runtime-on-pty-exit.ts
  • src/main/runtime/orca-runtime-refresh-floating-workspace-pty-liveness.ts
  • src/main/runtime/orca-runtime-runtime-id.ts
  • src/main/runtime/orca-runtime-sleep-resolved-worktree-terminals.ts
  • src/main/runtime/orca-runtime-stop-exact-terminals-for-worktree.ts
  • src/main/runtime/orca-runtime-write-terminal-agent-prompt.ts
  • src/main/runtime/rpc/methods/terminal/terminal-send-method.ts
  • src/main/runtime/rpc/terminal-send.test.ts
  • src/main/runtime/runtime-pty-controller-contract.ts
  • src/main/runtime/terminal-close-observed-exit-test-fixture.ts
  • src/main/runtime/terminal-intentional-stop-exit.test.ts
  • src/main/runtime/terminal-intentional-stops.test.ts
  • src/main/runtime/terminal-intentional-stops.ts
  • src/main/runtime/terminal-run-facts-input.test.ts
  • src/main/runtime/terminal-run-facts.test.ts
  • src/main/runtime/terminal-run-facts.ts
  • src/preload/api/pty-api.ts
  • src/preload/api/pty-bridge-session-control.ts
  • src/renderer/src/components/terminal-pane/deferred-split-pane-handoff.ts
  • src/renderer/src/components/terminal-pane/keyboard-handlers-ime-enter-keyup.test.tsx
  • src/renderer/src/components/terminal-pane/pty-connection-fresh-spawn-guards.test.ts
  • src/renderer/src/components/terminal-pane/pty-connection/pty-input-forward.ts
  • src/renderer/src/components/terminal-pane/pty-input-write-queue-contract.ts
  • src/renderer/src/components/terminal-pane/pty-input-write-queue.ts
  • src/renderer/src/components/terminal-pane/pty-preconnect-input-buffer.ts
  • src/renderer/src/components/terminal-pane/pty-transport-types.ts
  • src/renderer/src/components/terminal-pane/pty-transport-user-input.test.ts
  • src/renderer/src/components/terminal-pane/pty-transport.ts
  • src/renderer/src/components/terminal-pane/terminal-captured-input-dispatch.test.ts
  • src/renderer/src/components/terminal-pane/terminal-captured-input-dispatch.ts
  • src/renderer/src/components/terminal-pane/terminal-drop-handler.test.ts
  • src/renderer/src/components/terminal-pane/terminal-drop-internal-handler.test.ts
  • src/renderer/src/components/terminal-pane/terminal-drop-path-writer.test.ts
  • src/renderer/src/components/terminal-pane/terminal-drop-path-writer.ts
  • src/renderer/src/components/terminal-pane/terminal-pane-menu-paste.ts
  • src/renderer/src/components/terminal-pane/terminal-pane-paste-execution.ts
  • src/renderer/src/components/terminal-pane/terminal-programmatic-text-paste.ts
  • src/renderer/src/components/terminal-pane/terminal-pty-paste-writer.test.ts
  • src/renderer/src/components/terminal-pane/terminal-pty-paste-writer.ts
  • src/renderer/src/components/terminal-pane/terminal-quick-command-dispatch.test.ts
  • src/renderer/src/components/terminal-pane/terminal-quick-command-dispatch.ts
  • src/renderer/src/components/terminal-pane/use-terminal-pane-mobile-actions.ts
  • src/renderer/src/runtime/runtime-terminal-inspection.test.ts
  • src/renderer/src/runtime/runtime-terminal-inspection.ts
💤 Files with no reviewable changes (5)
  • src/main/runtime/runtime-pty-controller-contract.ts
  • src/main/ipc/pty/runtime/controller.ts
  • src/main/ipc/pty/runtime/controller-deps.ts
  • src/main/ipc/pty/session.ts
  • src/main/ipc/pty/runtime/spawn-preflight-requested-shell.test.ts

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 5 remain after this review.

Comment on lines +36 to +39
if (stop && joinsInFlightStop) {
stop.kind = kind
stop.incarnationId ??= incarnationId
stop.owners += 1

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

🔎 Supported by static analysis

🏁 Script executed:

sed -n '20,62p' src/main/ipc/pty/runtime/undelivered-ssh-kill.ts
sed -n '15,63p' src/renderer/src/components/terminal-pane/pty-exit-delivery.ts
sed -n '20,95p' src/main/runtime/terminal-intentional-stops.ts

Repository: stablyai/orca

Length of output: 5954


🏁 Script executed:

set -o pipefail
printf '%s\n' '--- spawn-run.ts ---'
sed -n '1,90p' src/main/ipc/pty/ipc/spawn-run.ts
printf '%s\n' '--- spawn-options.ts ---'
sed -n '160,215p' src/main/ipc/pty/ipc/spawn-options.ts
printf '%s\n' '--- orca-runtime-sleep-resolved-worktree-terminals.ts ---'
sed -n '1,40p' src/main/runtime/orca-runtime-sleep-resolved-worktree-terminals.ts
sed -n '130,180p' src/main/runtime/orca-runtime-sleep-resolved-worktree-terminals.ts
printf '%s\n' '--- kill.ts ---'
sed -n '1,100p' src/main/ipc/pty/runtime/kill.ts
printf '%s\n' '--- relevant usages ---'
rg -n -C 4 'isReversibleStopInFlight|claimExit|replacedByRestart|recordUndeliveredSshPtyKill|\.mark\(' src/main src/renderer/src/components/terminal-pane

Repository: stablyai/orca

Length of output: 42219


🏁 Script executed:

set -o pipefail
printf '%s\n' '--- replacement and stop mark sites ---'
rg -n -C 8 "intentionalPtyStops\.mark|stopReplacedPty|replacesPtyId|intentionalStop" src/main/runtime src/main/ipc/pty
printf '%s\n' '--- renderer-kill.ts ---'
sed -n '1,165p' src/main/ipc/pty/ipc/renderer-kill.ts
printf '%s\n' '--- undelivered SSH tests around reversible and replacement ---'
rg -n -C 8 "reversible|replaced|undelivered|keepHistory" src/main/ipc/pty-ssh-undelivered-kill.test.ts src/main/runtime/terminal-intentional-stop-exit.test.ts src/main/runtime/terminal-intentional-stops.test.ts 2>/dev/null
printf '%s\n' '--- exit delivery mapping ---'
sed -n '130,170p' src/main/ipc/pty/delivery/exit.ts

Repository: stablyai/orca

Length of output: 41718


🏁 Script executed:

sed -n '1,115p' src/main/runtime/terminal-intentional-stops.ts

Repository: stablyai/orca

Length of output: 3326


Give replacement precedence to the renderer, but track reversible ownership separately.

A replacement owner must make claimExit return 'replaced' so the renderer receives replacedByRestart. However, isReversibleStopInFlight must remain true while any reversible owner is active. kill.ts uses this result to suppress an undelivered SSH kill, and replaying a hibernation kill can terminate a pane that remains live.

Track reversible owners independently while keeping replaced precedence for exit classification.

Suggested fix
 type IntentionalStop = {
   kind: TerminalIntentionalStopKind
+  reversibleOwners: number
   /** Null until known; the first exit that claims the stop pins it to that process. */
   incarnationId: string | null
   owners: number
   stopped: boolean
   expiryTimer?: ReturnType<typeof setTimeout>
@@
     if (stop && joinsInFlightStop) {
-      stop.kind = kind
+      if (kind === 'replaced') stop.kind = kind
+      if (kind === 'reversible') stop.reversibleOwners += 1
       stop.incarnationId ??= incarnationId
       stop.owners += 1
     } else {
       clearTimeout(stop?.expiryTimer)
-      stop = { kind, incarnationId, owners: 1, stopped: false }
+      stop = {
+        kind,
+        reversibleOwners: kind === 'reversible' ? 1 : 0,
+        incarnationId,
+        owners: 1,
+        stopped: false
+      }
       this.stopsByPtyId.set(ptyId, stop)
     }
@@
       }
       settled = true
       owned.stopped ||= stopped
+      if (kind === 'reversible') owned.reversibleOwners -= 1
       owned.owners -= 1
@@
   isReversibleStopInFlight(ptyId: string): boolean {
     const stop = this.stopsByPtyId.get(ptyId)
-    return stop?.kind === 'reversible' && stop.owners > 0
+    return stop !== undefined && stop.owners > 0 && stop.reversibleOwners > 0
   }
 }

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ℹ️ No critical issues — a couple of robustness gaps in the new registers.

Reviewed changes

  • One intentional-stop register. TerminalIntentionalStops replaces markReplacedPtyStop/replacedPtyStopsById, reversibleStopOwnersByPtyId, and intentionalHandlelessPtyStops. Entries are keyed by PTY id, pinned to an incarnation, shared by owner count, survive read, and expire after the duplicate-exit window. All four stop writers and both exit readers (runtime + renderer delivery) now go through it.
  • Per-run facts. TerminalRunFactsRegister records freshSpawn and write-once firstUserInputAt per process. spawnCommitBindingOrigin now treats a cold restore as a reattach. Input provenance is tagged at the writer ({ userInput: true } through pty:write/pty:writeAccepted, and a wrapped reserveWrite on sendTerminal unless the payload is a query reply).
  • Renderer/transport plumbing. PtyInputOptions threads the tag through the write queue (no coalescing across the tag boundary), the preconnect buffer, paste/drop/quick-command paths, and captured input.
  • Tests. 21 new/updated test files covering hibernation, restart, runtime sleep, synthetic + late provider exits, incarnation reuse, expiry, fresh-spawn classification, and input provenance.

Pullfrog  | Fix all ➔ | Fix 👍s ➔ | View workflow run | Using DeepSeek Flash (free via Pullfrog for OSS) | 𝕏

Comment thread src/main/ipc/pty/delivery/exit.ts Outdated
}
}
const intentionalStop =
session.runtime?.intentionalPtyStops?.claimExit(payload.id, payload.incarnationId) ?? null

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This read passes payload.incarnationId raw, while the runtime's read applies exitIncarnationId ?? pty?.incarnationId. claimExit only rejects a mismatch when both incarnations are non-null, so an exit that omits the incarnation can claim a stop pinned to a different process. Because the reversible/sleep/exact-stop markers now persist for the duplicate-exit window (they were deleted at stop completion in the base), a reused PTY id is exposed on those paths — and the renderer would keep the binding (preserveRendererBinding / replacedByRestart) for the wrong process.

Technical details
# Unknown incarnation weakens the deliberate-stop incarnation guard

## Affected sites
- `src/main/ipc/pty/delivery/exit.ts:156-157` — `claimExit(payload.id, payload.incarnationId)` has no `pty?.incarnationId` fallback, unlike `runtime/orca-runtime-on-pty-exit.ts:118-119`.
- `src/main/runtime/terminal-intentional-stops.ts:81-83` — mismatch is only rejected when both sides are truthy; a null mark or a falsy exit matches any process on the id.
- `src/main/ipc/pty/provider/bind-listeners.ts:109-112` — the renderer payload omits `incarnationId` whenever the provider exit had none, so `payload.incarnationId` can be `undefined` at the read above even though the runtime record knows the incarnation.

## Required outcome
- The register's stated invariant ("a later process that reuses the id never matches", `terminal-intentional-stops.ts:6-7`) should hold when either side's incarnation is unknown, or the code/intent should document that it deliberately cannot.
- At minimum, the renderer read should use the same incarnation fallback as the runtime read so both readers agree on which process an exit describes (they must agree — both are read for one exit).

## Suggested approach (optional)
- Pass `exitIncarnationId ?? this.ptysById.get(payload.id)?.incarnationId` into the delivery read, or thread the already-resolved incarnation into `finalizePtyExitForRenderer`.
- Optionally gate the mark's join and `claimExit`'s match on a non-null incarnation when the entry is pinned, so an unknown exit cannot claim a pinned stop.

## Open questions for the human
- Is a committed spawn result with no `incarnationId` (legacy daemon / older SSH relay) a state this register is expected to handle, or is it out of scope for the intentional-stop path?

Comment thread src/main/runtime/terminal-run-facts.ts Resolved
A sleep and a restart that stop the same process now each keep their
label: the exit carries both renderer flags, and a runtime kill during
the sleep still records its SSH stop as reversible. A later stop of an
already-stopped process joins its entry, so a failed repeat cannot erase
the stop that landed.

The cold-restore rule moves into the run facts, so the binding span keeps
labelling a cold restore as a spawn.
Drives a real xterm through the pane's input handling: a macOS
input-source substitution, an iPadOS Hangul syllable, and a composition
the route delivers after a pane switch each reach onData flagged as user
input, which is what tags the write main records.
… are not input

- A landed stop that no exit pinned to an incarnation now ends when a new
  process commits on the same id, so that process's exit is not read as
  the stop. Both spawn-commit funnels report through one runtime method.
- A spawn commit with no incarnation starts its run facts clean, since it
  cannot be told from a new process.
- Stream input that is only focus reports no longer counts as user input;
  the desktop renderer already excludes them through xterm's own signal.
- The IME provenance test uses typed fakes: the pane input and composition
  route installers now take only the fields they read.

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ℹ️ No new issues in the delta — one documentation note below.

Reviewed changes

  • Kept every overlapping stop kind on one exit. TerminalIntentionalStops now stores ownersByKind: Map<kind, {inFlight, stopped}>, and claimExit returns every kind still on the entry, so a sleep and a restart that stop the same process both label the exit (preserveRendererBinding and replacedByRestart).
  • A later stop joins an already-stopped process. A settled entry is joined only by its own known incarnation (joins), and owners.stopped ||= stopped means a failed repeat cannot erase a stop that landed.
  • Cold-restore classification moved into the run facts. spawnCommitBindingOrigin reverts to returning 'spawn' for a cold restore that omits isReattach (keeping the binding span's historical label); recordSpawnCommit maps that to 'cold-restore', so freshSpawn is still false for cold restores.
  • IME/Hangul provenance tests. New terminal-ime-user-input-provenance.test.ts exercises macOS input-source substitution, iPadOS Hangul syllable commits, and a composition delivered after a pane switch, asserting each reaches onData with wasUserInput: true.

All three incremental tests are red for the right reason: the overlapping-stop test fails under the old last-kind-wins model, the SSH-join test fails the same way, and the IME tests rely on xterm's real onUserInput signal. The two prior threads (the renderer-side incarnation fallback in exit.ts and the both-null incarnation early-return in terminal-run-facts.ts) are unchanged by these commits and stay open.

ℹ️ Nitpicks

  • The PR description is stale on the cold restore: its "Fresh spawn" bullet still says "spawnCommitBindingOrigin now also counts a cold restore as a reattach". Commit 0cd6e607fd moved that rule into TerminalRunFactsRegister.recordSpawnCommit, so spawnCommitBindingOrigin now returns 'spawn' for a cold restore that omits isReattach (a cold restore that sets isReattach was already 'reattach'). Worth updating the body so reviewers get the current mechanism.

Pullfrog  | Fix it ➔ | View workflow run | Using DeepSeek Flash (free via Pullfrog for OSS) | 𝕏

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Advanced

Run ID: 220311f9-98d6-4fac-9da4-b4d8013eab02

📥 Commits

Reviewing files that changed from the base of the PR and between 576c196 and fbe1a1a.

⛔ Files ignored due to path filters (1)
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
📒 Files selected for processing (9)
  • src/main/ipc/pty-ssh-undelivered-kill.test.ts
  • src/main/ipc/pty/delivery/exit.ts
  • src/main/persistence/loading-store/pty-binding-span.ts
  • src/main/runtime/orca-runtime-on-pty-exit.ts
  • src/main/runtime/terminal-intentional-stop-exit.test.ts
  • src/main/runtime/terminal-intentional-stops.test.ts
  • src/main/runtime/terminal-intentional-stops.ts
  • src/main/runtime/terminal-run-facts.ts
  • src/renderer/src/components/terminal-pane/terminal-ime-user-input-provenance.test.ts

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 5 remain after this review.

Comment on lines +156 to +157
const intentionalStops =
session.runtime?.intentionalPtyStops?.claimExit(payload.id, payload.incarnationId) ?? []

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

🔎 Supported by static analysis

🏁 Script executed:

sed -n '130,180p' src/main/ipc/pty/delivery/exit.ts
sed -n '95,145p' src/main/runtime/orca-runtime-on-pty-exit.ts
sed -n '85,145p' src/main/ipc/pty/provider/bind-listeners.ts
rg -n 'finalizePtyExitForRenderer|ptyIncarnationById|onPtyExit\(' src/main/ipc/pty src/main/runtime/orca-runtime-on-pty-exit.ts

Repository: stablyai/orca

Length of output: 12602


🏁 Script executed:

#!/bin/bash
set -e
printf '%s\n' '--- exit.ts imports and flow ---'
sed -n '1,190p' src/main/ipc/pty/delivery/exit.ts
printf '%s\n' '--- runtime onPtyExit ---'
sed -n '1,180p' src/main/runtime/orca-runtime-on-pty-exit.ts
printf '%s\n' '--- intentional stop definitions/usages ---'
rg -n -C 5 'intentionalPtyStops|claimExit|markPtyStopRequested|class .*PtyStop|interface .*PtyStop' src/main
printf '%s\n' '--- ownership state and cleanup ---'
cat -n src/main/ipc/pty/provider/ownership-state.ts
cat -n src/main/ipc/pty/provider/state-cleanup.ts
printf '%s\n' '--- provider listener and renderer-exit entrypoints ---'
sed -n '1,145p' src/main/ipc/pty/provider/bind-listeners.ts
sed -n '1,110p' src/main/ipc/pty/delivery/ssh-intake.ts
printf '%s\n' '--- diff for reviewed file and nearby bindings ---'
git diff --unified=30 600adba9f03a4afd850e910e9065434471290d5f fbe1a1a1d1d5dcf8f3a28d7f18711916a713f865 -- src/main/ipc/pty/delivery/exit.ts src/main/ipc/pty/provider/bind-listeners.ts src/main/runtime/orca-runtime-on-pty-exit.ts src/main/ipc/pty/delivery/ssh-intake.ts

Repository: stablyai/orca

Length of output: 42094


🏁 Script executed:

set -e
sed -n '1,190p' src/main/ipc/pty/delivery/exit.ts
sed -n '1,180p' src/main/runtime/orca-runtime-on-pty-exit.ts
rg -n -C 5 'intentionalPtyStops|claimExit|markPtyStopRequested|isCurrentPtyExit|clearProviderPtyState' src/main
cat -n src/main/ipc/pty/provider/ownership-state.ts
cat -n src/main/ipc/pty/provider/state-cleanup.ts
sed -n '1,145p' src/main/ipc/pty/provider/bind-listeners.ts
sed -n '1,110p' src/main/ipc/pty/delivery/ssh-intake.ts
git diff --unified=20 600adba9f03a4afd850e910e9065434471290d5f fbe1a1a1d1d5dcf8f3a28d7f18711916a713f865 -- src/main/ipc/pty/delivery/exit.ts src/main/ipc/pty/provider/bind-listeners.ts src/main/runtime/orca-runtime-on-pty-exit.ts src/main/ipc/pty/delivery/ssh-intake.ts

Repository: stablyai/orca

Length of output: 42868


🏁 Script executed:

set -e
printf '%s\n' '--- claimExit implementation and register ---'
rg -n -C 12 'claimExit|class Intentional|intentionalPtyStops|incarnationId.*null' src/main src/shared
printf '%s\n' '--- provider cleanup implementation ---'
cat -n src/main/ipc/pty/provider/state-cleanup.ts | sed -n '1,130p'
printf '%s\n' '--- ownership implementation ---'
cat -n src/main/ipc/pty/provider/ownership-state.ts

Repository: stablyai/orca

Length of output: 41684


Resolve the incarnation before provider cleanup.

For a non-local provider exit without incarnationId, clearProviderPtyState deletes ptyIncarnationById before renderer finalization. The runtime still resolves pty?.incarnationId, but renderer finalization passes undefined to claimExit. A retained stop from an earlier incarnation can therefore set preserveRendererBinding or replacedByRestart.

Read ptyIncarnationById before cleanup and pass the resolved value to both runtime handling and renderer delivery. Preserve undefined when the exit cannot be identified.

Suggested fix
-import { isCurrentPtyExit, ptyOwnership } from './ownership-state'
+import { isCurrentPtyExit, ptyIncarnationById, ptyOwnership } from './ownership-state'
...
       if (!isCurrentPtyExit(payload)) {
         return
       }
       const syntheticExit = session.consumeSyntheticKillExit(payload.id, payload.incarnationId)
+      const exitIncarnationId =
+        payload.incarnationId ?? ptyIncarnationById.get(payload.id)
       if (!isLocalProvider) {
         clearProviderPtyState(payload.id)
         ptyOwnership.delete(payload.id)
...
-        session.runtime?.onPtyExit(payload.id, payload.code, payload.incarnationId, {
+        session.runtime?.onPtyExit(payload.id, payload.code, exitIncarnationId, {
...
         id: payload.id,
         code: payload.code,
-        ...(payload.incarnationId ? { incarnationId: payload.incarnationId } : {})
+        ...(exitIncarnationId ? { incarnationId: exitIncarnationId } : {})
       })

The dashboard popout's terminal preview writes to the PTY through its own
runtime path, which recorded no input, so a pane typed into only from the
preview read as untyped. It now records before the write, after the
mobile-driver check. One classifier, shared with terminal.send, decides
which provenance-free bytes nobody typed: a whole terminal reply or only
focus reports, which also covers the focus-in a desktop renderer sends
when it reattaches a remote pane.
…t adds

happy-dom serves navigator.userAgent from the prototype, so the test found no
own descriptor to restore and left the iPad user agent in place. The pane-switch
case then ran as a Mac pane only because it followed the Hangul case. Deleting
the own-property stub restores the default platform for every case.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Advanced

Run ID: 856cf7b2-5d0f-4d16-93aa-9ef7d189f473

📥 Commits

Reviewing files that changed from the base of the PR and between fbe1a1a and 9e70668.

📒 Files selected for processing (14)
  • src/main/ipc/pty/ipc/spawn-commit-persist.ts
  • src/main/ipc/pty/runtime/spawn-commit-run-facts.test.ts
  • src/main/ipc/pty/runtime/spawn-commit.ts
  • src/main/runtime/orca-runtime-attach-remote-terminal-source-range-consumer.ts
  • src/main/runtime/orca-runtime-controller-knows-pty-is-live.ts
  • src/main/runtime/orca-runtime-runtime-id.ts
  • src/main/runtime/terminal-intentional-stops.test.ts
  • src/main/runtime/terminal-intentional-stops.ts
  • src/main/runtime/terminal-run-facts-input.test.ts
  • src/main/runtime/terminal-run-facts.test.ts
  • src/main/runtime/terminal-run-facts.ts
  • src/renderer/src/components/terminal-pane/terminal-ime-composition-route.ts
  • src/renderer/src/components/terminal-pane/terminal-ime-user-input-provenance.test.ts
  • src/renderer/src/components/terminal-pane/terminal-pane-pane-input.ts

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 3 remain after this review.

Comment thread src/main/runtime/terminal-run-facts.ts Outdated
Comment on lines +20 to +21
export function isUntypedTerminalInput(payload: string): boolean {
return isTerminalQueryReply(payload) || TERMINAL_FOCUS_REPORTS_ONLY_RE.test(payload)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Exclude coalesced query replies from user-input facts.

If a client sends two query replies in one payload, isTerminalQueryReply(payload) rejects the payload because it recognizes only one complete reply. The focus-report regex also rejects it. The runtime then records firstUserInputAt even though no person sent input. Use the existing extractOnlyTerminalQueryReplies helper for reply-only payloads, and test two consecutive replies. (raw.githubusercontent.com)

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ No new issues found in the delta — the both-null incarnation gap is closed, and the new stop-retirement and input-provenance changes hold up.

Reviewed changes

  • Added TerminalIntentionalStops.noteSpawnCommit: a spawn commit on an id retires a landed stop that no exit ever pinned and has no in-flight owners, so a reused id cannot inherit it. The runtime's new noteTerminalSpawnCommit drives both spawn funnels, recording run facts and retiring the stop together.
  • Extended the no-provenance classifier to focus reports (CSI I / CSI O) through isUntypedTerminalInput, so a paired client's automatic focus replies no longer count as a run's first user input on sendTerminal or the dashboard preview.
  • Recorded the pop-out dashboard preview's raw keystrokes (writeTerminalPreviewInput) as a run's first user input, before the write that could end the process.
  • Fixed TerminalRunFactsRegister.recordSpawnCommit to start a clean run when a commit omits the incarnation, closing the both-null collapse; added a test for it.
  • Narrowed the IME composition route and pane-input parameter types to the fields they read, dropping the test's type assertions.

Pullfrog  | Fix it ➔ | View workflow run | Using DeepSeek Flash (free via Pullfrog for OSS) | 𝕏

…oint reads it

A run's first input was recorded by opposite defaults: the renderer's
pty:write recorded nothing unless a writer opted in, terminal.send recorded
everything that was not a reply, and main's own controller writes recorded
nothing. Each unclassified producer silently took its transport's default, so
the worktree-create draft counted from the renderer and not from main, and
mailbox pointers never counted.

Every host write entry point now takes a required kind: driving, launch or
query-reply. That covers the runtime controller's write and settled write,
the terminal writer, sendTerminal, sendTerminalAgentPrompt, pty:write and
pty:writeAccepted, the renderer transport and the runtime input helpers. The
fact is recorded once, just before the provider write, in the controller
funnel and the pty:write funnel: only driving bytes count, and a payload that
is only a reply or focus reports never does. The per-producer records are
gone.

Launch writes (create-time drafts and follow-ups, the agent launch prompt,
restored and cold-restore startup commands, the SSH background launch) do not
count. Mailbox pointers, dispatch, plugins and agent-team sends do. The
runtime mixins are unchecked by the compiler, and the pane session is an any
bag, so two source scans fail on any write there that leaves out its kind.
…ks every write's kind

The pane-connection session is an `any` bag, so a transport write there that
left out its input kind compiled, and only a text scan over the renderer
caught it. Declaring `transport: PtyTransport` on the session puts those writes
under the compiler, so the scan is gone. One hidden-delivery guard now narrows
a null PTY id itself instead of relying on an untyped predicate.

The main-process scan over `@ts-nocheck` runtime files missed five files whose
directive sits on the second line, below a lint directive, and missed a write
through a local alias of the PTY controller. It now finds both.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Advanced

Run ID: ec02d267-edee-40a3-a857-e2622c949794

📥 Commits

Reviewing files that changed from the base of the PR and between 55fadf1 and 4029a66.

📒 Files selected for processing (145)
  • src/main/ipc/pty/ipc/write-input-chunk-yield.test.ts
  • src/main/ipc/pty/ipc/write-input-user-input.test.ts
  • src/main/ipc/pty/ipc/write-input.ts
  • src/main/ipc/pty/runtime/controller.ts
  • src/main/ipc/pty/runtime/operations.ts
  • src/main/ipc/pty/runtime/spawn-commit-run-facts.test.ts
  • src/main/plugins/plugin-host-methods.test.ts
  • src/main/plugins/plugin-host-service-bindings.ts
  • src/main/runtime/agent-prompt-line-settle.test.ts
  • src/main/runtime/agent-prompt-receipt-correlation.test.ts
  • src/main/runtime/agent-prompt-submission-runtime-hook-and-generation.test.ts
  • src/main/runtime/agent-prompt-submission-runtime.test.ts
  • src/main/runtime/agent-prompt-submission-windows-submit-delay.test.ts
  • src/main/runtime/claude-agent-teams-tmux-dispatcher.ts
  • src/main/runtime/claude-agent-teams-types.ts
  • src/main/runtime/orca-runtime-attach-remote-terminal-source-range-consumer.ts
  • src/main/runtime/orca-runtime-controller-knows-pty-is-live.ts
  • src/main/runtime/orca-runtime-create-pty-headless-terminal-state.ts
  • src/main/runtime/orca-runtime-deliver-pending-messages.ts
  • src/main/runtime/orca-runtime-get-worktree-terminal-provisioning-host.ts
  • src/main/runtime/orca-runtime-resolve-authoritative-terminal-wait-permission.ts
  • src/main/runtime/orca-runtime-resolve-terminal-split-source-authority.ts
  • src/main/runtime/orca-runtime-restore-live-paired-renderer-session-owned-mobile-terminals.ts
  • src/main/runtime/orca-runtime-runtime-id.ts
  • src/main/runtime/orca-runtime-terminal-handle-incarnation.test.ts
  • src/main/runtime/orca-runtime-tests/agent-status-and-waits-part-03.spec.ts
  • src/main/runtime/orca-runtime-tests/agent-status-and-waits.spec.ts
  • src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-13.spec.ts
  • src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-07.spec.ts
  • src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-08.spec.ts
  • src/main/runtime/orca-runtime-tests/terminal-handles-and-agent-status.spec.ts
  • src/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-02.spec.ts
  • src/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-07.spec.ts
  • src/main/runtime/orca-runtime-tests/worktree-setup-and-startup-part-03.spec.ts
  • src/main/runtime/orca-runtime-tests/worktree-setup-and-startup-part-04.spec.ts
  • src/main/runtime/orca-runtime-write-terminal-agent-prompt.ts
  • src/main/runtime/orchestration/coordinator-runtime-contract.ts
  • src/main/runtime/orchestration/mailbox-pointer-pty-write.ts
  • src/main/runtime/orchestration/preamble.ts
  • src/main/runtime/rpc/methods/agent-launch-terminal-prompt.ts
  • src/main/runtime/rpc/methods/orchestration/worker/worker-release-mobile-report.test.ts
  • src/main/runtime/rpc/methods/orchestration/worker/worker-start-prompt-contract.test.ts
  • src/main/runtime/rpc/methods/terminal/terminal-input-delivery.ts
  • src/main/runtime/rpc/methods/terminal/terminal-send-method.ts
  • src/main/runtime/rpc/terminal-agent-prompt-send.test.ts
  • src/main/runtime/rpc/terminal-multiplex-ack-output-budget.test.ts
  • src/main/runtime/rpc/terminal-multiplex-ack-overflow-recovery.test.ts
  • src/main/runtime/rpc/terminal-multiplex-desktop-resize-routing.test.ts
  • src/main/runtime/rpc/terminal-multiplex-input-write-rejection.test.ts
  • src/main/runtime/rpc/terminal-multiplex-output-pause-and-viewport.test.ts
  • src/main/runtime/rpc/terminal-output-batching.test.ts
  • src/main/runtime/rpc/terminal-send.test.ts
  • src/main/runtime/runtime-pty-controller-contract.ts
  • src/main/runtime/runtime-terminal-contracts.ts
  • src/main/runtime/runtime-terminal-writer.ts
  • src/main/runtime/runtime-worktree-startup-readiness.ts
  • src/main/runtime/terminal-input-kind-unchecked-call-sites.test.ts
  • src/main/runtime/terminal-intentional-stop-exit.test.ts
  • src/main/runtime/terminal-interactive-wait-visibility.test.ts
  • src/main/runtime/terminal-query-responder.test.ts
  • src/main/runtime/terminal-run-facts-input.test.ts
  • src/main/runtime/terminal-run-facts.test.ts
  • src/main/runtime/terminal-run-facts.ts
  • src/main/runtime/terminal-send-stale-leaf-liveness.test.ts
  • src/preload/api/pty-api.ts
  • src/preload/api/pty-bridge-session-control.ts
  • src/renderer/src/components/native-chat/claude-model-switch-confirmation.ts
  • src/renderer/src/components/native-chat/native-chat-runtime-image-send.ts
  • src/renderer/src/components/native-chat/native-chat-runtime-send.test.ts
  • src/renderer/src/components/native-chat/native-chat-runtime-send.ts
  • src/renderer/src/components/native-chat/use-native-chat-composer-interrupt.ts
  • src/renderer/src/components/native-chat/use-native-chat-interactive-send.test.tsx
  • src/renderer/src/components/native-chat/use-native-chat-interactive-send.ts
  • src/renderer/src/components/terminal-pane/deferred-split-pane-handoff.test.ts
  • src/renderer/src/components/terminal-pane/keyboard-handlers-ime-enter-keyup.test.tsx
  • src/renderer/src/components/terminal-pane/pty-connection-foreground-write-path.test.ts
  • src/renderer/src/components/terminal-pane/pty-connection-fresh-spawn-guards.test.ts
  • src/renderer/src/components/terminal-pane/pty-connection-hibernation-wake.test.ts
  • src/renderer/src/components/terminal-pane/pty-connection-hook-completion-bell-arbitration.test.ts
  • src/renderer/src/components/terminal-pane/pty-connection-hook-completion-side-effects.test.ts
  • src/renderer/src/components/terminal-pane/pty-connection-interrupt-inference.test.ts
  • src/renderer/src/components/terminal-pane/pty-connection-reattach-mode-reset.test.ts
  • src/renderer/src/components/terminal-pane/pty-connection-replay-payload-handling.test.ts
  • src/renderer/src/components/terminal-pane/pty-connection-setup-split-spawn.test.ts
  • src/renderer/src/components/terminal-pane/pty-connection-ssh-startup-draft-delivery.test.ts
  • src/renderer/src/components/terminal-pane/pty-connection-startup-command-delivery.test.ts
  • src/renderer/src/components/terminal-pane/pty-connection-terminal-input-gating.test.ts
  • src/renderer/src/components/terminal-pane/pty-connection-typed-agent-identity.test.ts
  • src/renderer/src/components/terminal-pane/pty-connection-windows-keyboard-reset.test.ts
  • src/renderer/src/components/terminal-pane/pty-connection/deferred-cold-restore-and-snapshot.ts
  • src/renderer/src/components/terminal-pane/pty-connection/pane-serializer-settle.ts
  • src/renderer/src/components/terminal-pane/pty-connection/pty-input-forward.ts
  • src/renderer/src/components/terminal-pane/pty-connection/replay-data-drain.ts
  • src/renderer/src/components/terminal-pane/pty-input-write-queue-contract.ts
  • src/renderer/src/components/terminal-pane/pty-input-write-queue.test.ts
  • src/renderer/src/components/terminal-pane/pty-input-write-queue.ts
  • src/renderer/src/components/terminal-pane/pty-preconnect-input-buffer.test.ts
  • src/renderer/src/components/terminal-pane/pty-preconnect-input-buffer.ts
  • src/renderer/src/components/terminal-pane/pty-transport-input-kind-call-sites.test.ts
  • src/renderer/src/components/terminal-pane/pty-transport-input-write.test.ts
  • src/renderer/src/components/terminal-pane/pty-transport-reattach-admission.test.ts
  • src/renderer/src/components/terminal-pane/pty-transport-types.ts
  • src/renderer/src/components/terminal-pane/pty-transport-user-input.test.ts
  • src/renderer/src/components/terminal-pane/pty-transport.ts
  • src/renderer/src/components/terminal-pane/remote-runtime-error-surface-dismissal.test.ts
  • src/renderer/src/components/terminal-pane/remote-runtime-pty-query-reply-immediate.test.ts
  • src/renderer/src/components/terminal-pane/remote-runtime-pty-transport-host-session-launch.test.ts
  • src/renderer/src/components/terminal-pane/remote-runtime-pty-transport-host-surface-replacement.test.ts
  • src/renderer/src/components/terminal-pane/remote-runtime-pty-transport-input-coalescing.test.ts
  • src/renderer/src/components/terminal-pane/remote-runtime-pty-transport-input-fallback.test.ts
  • src/renderer/src/components/terminal-pane/remote-runtime-pty-transport-stale-handle-recovery.test.ts
  • src/renderer/src/components/terminal-pane/remote-runtime-pty-transport-sticky-replacement-policy.test.ts
  • src/renderer/src/components/terminal-pane/remote-runtime-pty-transport-stream-reconnect.test.ts
  • src/renderer/src/components/terminal-pane/remote-runtime-pty-transport.ts
  • src/renderer/src/components/terminal-pane/terminal-captured-input-dispatch.test.ts
  • src/renderer/src/components/terminal-pane/terminal-captured-input-dispatch.ts
  • src/renderer/src/components/terminal-pane/terminal-drop-handler.test.ts
  • src/renderer/src/components/terminal-pane/terminal-drop-internal-handler.test.ts
  • src/renderer/src/components/terminal-pane/terminal-drop-path-writer.test.ts
  • src/renderer/src/components/terminal-pane/terminal-drop-path-writer.ts
  • src/renderer/src/components/terminal-pane/terminal-ios-hangul-preedit-coexistence.test.ts
  • src/renderer/src/components/terminal-pane/terminal-pane-menu-paste.ts
  • src/renderer/src/components/terminal-pane/terminal-pane-paste-execution.ts
  • src/renderer/src/components/terminal-pane/terminal-paste-operation-order.test.ts
  • src/renderer/src/components/terminal-pane/terminal-programmatic-text-paste.ts
  • src/renderer/src/components/terminal-pane/terminal-pty-paste-writer.test.ts
  • src/renderer/src/components/terminal-pane/terminal-pty-paste-writer.ts
  • src/renderer/src/components/terminal-pane/terminal-quick-command-dispatch.test.ts
  • src/renderer/src/components/terminal-pane/terminal-quick-command-dispatch.ts
  • src/renderer/src/components/terminal-pane/terminal-startup-command-paste.ts
  • src/renderer/src/components/terminal-pane/use-terminal-pane-mobile-actions.ts
  • src/renderer/src/lib/agent-draft-paste-content.ts
  • src/renderer/src/lib/agent-followup-delivery.test.ts
  • src/renderer/src/lib/agent-followup-delivery.ts
  • src/renderer/src/lib/agent-paste-draft-submit-retry.test.ts
  • src/renderer/src/lib/agent-paste-draft.test.ts
  • src/renderer/src/lib/agent-paste-draft.ts
  • src/renderer/src/lib/launch-agent-background-session-remote.test.ts
  • src/renderer/src/lib/launch-agent-background-session.ts
  • src/renderer/src/lib/new-workspace.test.ts
  • src/renderer/src/lib/startup-draft-input-kind.test.ts
  • src/renderer/src/runtime/runtime-terminal-inspection.test.ts
  • src/renderer/src/runtime/runtime-terminal-inspection.ts
  • src/shared/source-scan/call-argument-scan.ts
  • src/shared/terminal-input-kind.ts

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 4 remain after this review.

}

export type PtyWritePayload = { id: string; data: string }
export type PtyWritePayload = { id: string; data: string; inputKind: TerminalInputKind }

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🗄️ Data Integrity & Integration | 🟡 Minor | ⚡ Quick win

🔎 Supported by static analysis

🏁 Script executed:

rg -n 'isPtyWritePayload|writePtyInputAccepted|writePtyInput\b|recordInput\(' src/main/ipc/pty/ipc/write-input.ts src/main/ipc/pty/register-handlers.ts src/main/runtime/terminal-run-facts.ts
sed -n '20,80p;145,210p' src/main/ipc/pty/ipc/write-input.ts
sed -n '55,78p' src/main/runtime/terminal-run-facts.ts

Repository: stablyai/orca

Length of output: 6342


🏁 Script executed:

set -eu
printf '%s\n' '--- write-input imports, predicate, and handlers ---'
sed -n '1,45p;112,190p' src/main/ipc/pty/ipc/write-input.ts
printf '%s\n' '--- IPC registrations and validation references ---'
rg -n -C 5 'createPtyWriteInput|isPtyWritePayload|writePtyInputAccepted|writePtyInput' src/main/ipc/pty
printf '%s\n' '--- TerminalInputKind declarations and consumers ---'
rg -n -C 4 'TerminalInputKind|inputKind' src/main | head -240

Repository: stablyai/orca

Length of output: 40286


🏁 Script executed:

set -eu
printf '%s\n' '--- TerminalInputKind declaration ---'
sed -n '1,160p' src/shared/terminal-input-kind.ts
printf '%s\n' '--- all direct inputKind validators and payload construction ---'
rg -n -C 3 'inputKind\s*===|inputKind\s*!==|TerminalInputKind|pty:write|pty:writeAccepted' src/shared src/renderer src/main | head -320

Repository: stablyai/orca

Length of output: 29779


Validate inputKind at the renderer IPC boundary.

isPtyWritePayload accepts missing and invalid inputKind values. Both IPC handlers can pass these values to recordInput. recordInput treats them as non-driving and returns, while the PTY write continues. This can omit the first-user-input provenance record.

Add a runtime check for the three allowed TerminalInputKind values.

Suggested fix
+  const isTerminalInputKind = (value: unknown): value is TerminalInputKind =>
+    value === 'driving' || value === 'launch' || value === 'query-reply'
+
   const isPtyWritePayload = (value: unknown): value is PtyWritePayload =>
     typeof value === 'object' &&
     value !== null &&
     typeof (value as { id?: unknown }).id === 'string' &&
     (value as { id: string }).id.length > 0 &&
-    typeof (value as { data?: unknown }).data === 'string'
+    typeof (value as { data?: unknown }).data === 'string' &&
+    isTerminalInputKind((value as { inputKind?: unknown }).inputKind)

Comment on lines +2586 to +2587
// Why no kind: terminal.send has no launch kind, and its query-reply kind is for mobile
// clients, so the host classifies a desktop's bytes itself.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🗄️ Data Integrity & Integration | 🟡 Minor | ⚡ Quick win

🔎 Supported by static analysis

🏁 Script executed:

#!/bin/bash
set -euo pipefail
ast-grep outline src/main/runtime/rpc/methods/terminal/terminal-send-method.ts --match 'terminal|send' || true
ast-grep outline src/main/runtime/terminal-run-facts.ts --match 'input|record' || true
rg -n -C 5 'inputKind|query-reply|launch|driving|terminal\.send|record.*Input' \
  src/main/runtime/rpc/methods/terminal/terminal-send-method.ts \
  src/main/runtime/terminal-run-facts.ts \
  src/renderer/src/components/terminal-pane/remote-runtime-pty-transport.ts \
  src/renderer/src/runtime/runtime-terminal-inspection.ts

Repository: stablyai/orca

Length of output: 42166


🏁 Script executed:

#!/bin/bash
set -euo pipefail
printf '%s\n' '--- input-kind definitions and usages ---'
rg -n -C 4 'export type TerminalInputKind|type TerminalInputKind|inputKind:|sendInput\(|sendRuntimePtyInputVerified|sendRuntimePtyInput\(' \
  src/shared src/renderer/src/components/terminal-pane/remote-runtime-pty-transport.ts \
  src/renderer/src/runtime/runtime-terminal-inspection.ts \
  src/main/runtime/rpc/methods/terminal/terminal-send-method.ts \
  src/main/runtime/terminal-run-facts.ts

printf '%s\n' '--- transport write and startup sections ---'
sed -n '1360,1490p' src/renderer/src/components/terminal-pane/remote-runtime-pty-transport.ts
sed -n '2540,2645p' src/renderer/src/components/terminal-pane/remote-runtime-pty-transport.ts
printf '%s\n' '--- host send handler and run facts ---'
sed -n '20,270p' src/main/runtime/rpc/methods/terminal/terminal-send-method.ts
sed -n '1,125p' src/main/runtime/terminal-run-facts.ts
printf '%s\n' '--- runtime inspection write path ---'
sed -n '210,330p' src/renderer/src/runtime/runtime-terminal-inspection.ts

Repository: stablyai/orca

Length of output: 36109


🏁 Script executed:

#!/bin/bash
set -euo pipefail
printf '%s\n' '--- all transport sendInput declarations and calls ---'
rg -n -C 6 'sendInput(?:Immediate|Accepted)?\b|sendRuntimePtyInput(?:Verified)?\b|inputKind\s*===\s*['\"'\"']launch['\"'\"']|inputKind\s*:\s*['\"'\"']launch['\"'\"']' \
  src/renderer/src/components/terminal-pane/remote-runtime-pty-transport.ts \
  src/renderer/src/runtime src/renderer/src/components \
  src/shared src/main/runtime

printf '%s\n' '--- launch references near transport write flow ---'
rg -n -C 10 'launch|startup|draft|sendInput' src/renderer/src/components/terminal-pane/remote-runtime-pty-transport.ts | tail -n 260

printf '%s\n' '--- transport type/factory and callback declarations ---'
sed -n '1,220p' src/renderer/src/components/terminal-pane/remote-runtime-pty-transport.ts

Repository: stablyai/orca

Length of output: 45666


🏁 Script executed:

#!/bin/bash
set -euo pipefail
printf '%s\n' '--- launch input call sites ---'
rg -n -C 8 "inputKind\s*:\s*['\"]launch['\"]|,\s*['\"]launch['\"]\s*\)|sendRuntimePtyInputVerified|sendRuntimePtyInput\(" \
  src/renderer/src --glob '*.ts' --glob '*.tsx'

printf '%s\n' '--- remote transport factory option types and startup send references ---'
rg -n -C 8 "startupCommandDelivery|launchDraft|resolvedLaunchDraft|createRemoteRuntimePtyTransport|PtyTransportOptions" \
  src/renderer/src/components/terminal-pane/remote-runtime-pty-transport.ts \
  src/renderer/src/components/terminal-pane/pty-transport-types.ts \
  src/renderer/src --glob '*.ts' --glob '*.tsx' | head -n 500

Repository: stablyai/orca

Length of output: 42320


🏁 Script executed:

#!/bin/bash
set -euo pipefail
printf '%s\n' '--- launch caller ---'
fd -i 'agent-followup-delivery.ts' 'launch-agent-background-session.ts' src
for f in $(fd -i 'agent-followup-delivery.ts' 'launch-agent-background-session.ts' src); do
  echo "--- $f ---"
  rg -n -C 12 'sendRuntimePtyInputVerified|window\.api\.pty\.write|launch' "$f"
done

printf '%s\n' '--- host runtime write and fact-record binding ---'
rg -n -C 8 'recordInput\(|runFacts|TerminalRunFactsRegister|inputKind' \
  src/main/runtime --glob '*.ts' | head -n 500

Repository: stablyai/orca

Length of output: 41429


🏁 Script executed:

#!/bin/bash
set -euo pipefail
rg -n -C 10 'resolvedLaunchDraft|TerminalSend|inputKind' \
  src/shared/rpc-contract/terminal-unary-params.ts \
  src/main/runtime/rpc/methods/terminal/terminal-send-method.ts \
  src/main/runtime src/renderer/src/runtime/runtime-terminal-inspection.ts \
  --glob '*.ts' | head -n 700

Repository: stablyai/orca

Length of output: 42323


🏁 Script executed:

#!/bin/bash
set -euo pipefail
rg -n -C 10 'firstUserInputAt' src/main --glob '*.ts' | head -n 300

Repository: stablyai/orca

Length of output: 25828


Preserve 'launch' for remote terminal writes.

The remote terminal.send path drops 'launch' and the host classifies the write as 'driving'. This can set firstUserInputAt for startup text. Extend the remote contract to preserve 'launch'; keep ordinary desktop input as 'driving'.

Suggested fix
--- a/src/shared/rpc-contract/terminal-unary-params.ts
+++ b/src/shared/rpc-contract/terminal-unary-params.ts
@@
-  inputKind: z.enum(['query-reply']).optional(),
+  inputKind: z.enum(['launch', 'query-reply']).optional(),
--- a/src/main/runtime/rpc/methods/terminal/terminal-send-method.ts
+++ b/src/main/runtime/rpc/methods/terminal/terminal-send-method.ts
@@
-                inputKind: params.inputKind === 'query-reply' ? 'query-reply' : 'driving',
+                inputKind: params.inputKind ?? 'driving',
--- a/src/renderer/src/runtime/runtime-terminal-inspection.ts
+++ b/src/renderer/src/runtime/runtime-terminal-inspection.ts
@@
-    { terminal, text: data, client: DESKTOP_RUNTIME_CLIENT },
+    {
+      terminal,
+      text: data,
+      client: DESKTOP_RUNTIME_CLIENT,
+      ...(inputKind === 'launch' ? { inputKind } : {})
+    },
@@
-      { terminal, text: data, client: DESKTOP_RUNTIME_CLIENT },
+      {
+        terminal,
+        text: data,
+        client: DESKTOP_RUNTIME_CLIENT,
+        ...(inputKind === 'launch' ? { inputKind } : {})
+      },

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ℹ️ No new issues in the delta — the TerminalInputKind refactor holds up. One informational note below about paired-host writes, for the follow-up.

Reviewed changes

  • Replaced the userInput flag with a typed kind. A shared TerminalInputKind ('driving' | 'launch' | 'query-reply') now names the kind at every host write entry point — the pty:write/pty:writeAccepted preload and IPC boundary, PtyTransport.sendInput, the runtime controller write/writeWithSettlement, RuntimeTerminalWriter, sendTerminal, sendTerminalAgentPrompt, and the plugin/tmux/worker delegates.
  • One record point. TerminalRunFactsRegister.recordInput is called from both write funnels (ipc/pty/runtime/operations.ts and ipc/pty/ipc/write-input.ts) and owns both the kind check and the payload check (whole query reply, or only focus reports). withUserInputTag, recordUserInput, and the PtyInputOptions tag were deleted.
  • Launch writes no longer count as user input. Worktree startup drafts, startup follow-ups, and the agent launch prompt now write 'launch'; a dispatched agent prompt writes 'driving'; query replies write 'query-reply'. The write queue refuses to coalesce across kinds, and the preconnect buffer and deferred-split handoff preserve the kind across a remount.
  • Tests. New findCallsMissingArgument scanner plus ratchets that fail if any @ts-nocheck/any-bag write site omits its kind, and focused tests for the single record point, the startup-draft kind on both renderer routes, and the preconnect kind handoff. The renderer connection suites that assert 'query-reply' are pinning the unclassified branch (the harness never emits xterm's onUserInput); the real driving path is exercised by pty-transport-user-input.test.ts and the IME provenance suite, so that split is intentional, not a gap.

ℹ️ Paired-host terminal writes cannot mark launch input

A desktop client driving a terminal on a paired remote runtime crosses terminal.send, whose schema carries only inputKind: 'query-reply'. The remote transport drops the kind, so the host labels the write 'driving' and classifies it by bytes. A create-time draft or startup command delivered to a paired-host pane therefore still sets firstUserInputAt, even though the local and SSH-provider paths now mark the same bytes 'launch'. The added comments in runtime-terminal-inspection.ts and remote-runtime-pty-transport.ts acknowledge the classification-by-bytes rule, but not this consequence for the run-facts consumer.

Mergeable as-is — no current reader uses the facts yet. Worth deciding before the tab-membership follow-up ships, since a pane that only received Orca's own startup writes would otherwise look user-driven on a paired host.

Technical details
# Paired-host writes lose the launch kind

## Affected sites
- `src/renderer/src/components/terminal-pane/remote-runtime-pty-transport.ts:2583` — `sendInput(data: string)` takes no kind and ignores the one passed by callers.
- `src/renderer/src/runtime/runtime-terminal-inspection.ts:242-244` — `sendRuntimePtyInputWithinLimit`/`sendRuntimePtyInputVerified` send `terminal.send` without `inputKind` when the target is an environment.
- `src/shared/rpc-contract/terminal-unary-params.ts:118` — `inputKind: z.enum(['query-reply']).optional()`, so the wire has no `launch`.
- `src/main/runtime/rpc/methods/terminal/terminal-send-method.ts:239` — host maps anything but `query-reply` to `'driving'`.
- `src/main/runtime/terminal-run-facts.ts:65-73` — `recordInput` then records by payload, so a non-reply launch byte is counted.

## Required outcome
- Decide whether a paired-host startup/draft write should be distinguishable from a person's input by the run-facts consumer. Either extend the wire (capability-negotiated) or have the consumer tolerate it.

## Open questions for the human
- Is the paired-host case expected to keep tab-membership parity with the local/SSH-provider paths, or is classifying by bytes acceptable for that transport?

Pullfrog  | Fix it ➔ | View workflow run | Using DeepSeek Flash (free via Pullfrog for OSS) | 𝕏

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ No new issues in the new commit.

Reviewed changes

  • Renderer kind enforcement moved to the compiler. ConnectPanePtySession.transport is now typed PtyTransport (the bag keeps its [key: string]: any), so session.transport.sendInput(...) requires a kind at compile time; pty-transport-input-kind-call-sites.test.ts was deleted as redundant.
  • Main-process scan widened. The receiver regex accepts a local controller/Controller alias, the @ts-nocheck filter matches on any line (picking up orca-runtime-sync-window-graph.ts, which opens with a lint directive), and a planted case covers a const controller = this.ptyController; controller.write(...) site.

No production behavior change; the @ts-nocheck ratchet and the compiler now split the coverage cleanly, and the previously skipped directive-on-line-2 files are scanned.

Pullfrog  | Fix it ➔ | View workflow run | Using DeepSeek Flash (free via Pullfrog for OSS) | 𝕏

…-run-facts

# Conflicts:
#	src/main/ipc/pty/ipc/spawn-commit-persist.ts
#	src/main/ipc/pty/runtime/controller-deps.ts
#	src/main/runtime/orca-runtime-on-pty-exit.ts
…ing save succeeds

The runtime spawn funnel reported the commit before its host-session binding save, so a spawn discarded for a failed save still recorded run facts and cleared a landed stop. Report it after the save, and separately on the adopted return, which makes no save. Also align tests and fixtures with main: the removed stop-owner map, required write input kinds, SQLite-backed stores and async binding saves.
The merge moved the renderer funnel's spawn-commit report into the publish step, after the binding save, but no test covered it: deleting the call or moving it back before the save left every suite green. Cover both: a committed spawn records its run facts and supersedes an unpinned landed stop, and a spawn discarded for a failed binding save records nothing and leaves the stop.

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ No new issues found — the runtime spawn funnel now reports its commit only after the binding save succeeds, with a test that fails under the prior ordering.

Reviewed changes

  • Report the runtime spawn commit after its binding save. commitRuntimePtySpawn no longer calls noteTerminalSpawnCommit before the host-session binding write, so a spawn discarded for a failed save can no longer record run facts or retire a landed intentional stop. The adopted branch keeps its own call because it returns without a save.
  • Cover the discarded spawn. spawn-commit-run-facts.test.ts adds a case whose binding save rejects, asserting the run is not fresh and the 'reversible' stop still claims the exit — red under the prior ordering.
  • Merge alignment with main. The merge with #22612 (SQLite profile state) resolved the spawn-commit-persist.ts split by placing the IPC funnel's report in publishPtyIpcSpawnCommit (after the save), and re-aligned the affected tests and fixtures with the removed stop-owner map, the required write input kinds, and async binding saves.

Pullfrog  | Fix it ➔ | View workflow run | Using DeepSeek Flash (free via Pullfrog for OSS) | 𝕏

…tion succeeds

The runtime funnel reported each commit before registering the process, so a spawn that exited during start still recorded run facts and could end a landed stop, while the renderer funnel reports only after registration. Report after registration on both the ordinary and the adopted branch, so only a committed, registered run has facts and an unknown run keeps reading as not fresh.

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ No new issues found — the runtime spawn funnel's commit report now lands after registration, with tests that fail under the prior ordering.

Reviewed changes

  • Report the runtime spawn commit after registration. commitRuntimePtySpawn now calls noteTerminalSpawnCommit only once registerPersistedPtySpawn has resolved, on the ordinary branch (spawn-commit.ts:197) and on the adopted branch (spawn-commit.ts:96, previously before registration). A spawn rejected for exiting during start no longer records run facts or retires a landed intentional stop, matching the renderer funnel. Every successful path still reports exactly once, since registerPersistedPtySpawn either resolves or throws.
  • Pin the rejected-start case. spawn-commit-run-facts.test.ts adds a case parametrized over the new-process and adoption shapes, asserting the run is not fresh and the 'reversible' stop still claims the exit — red under the prior ordering.
  • Broaden the landed-stop supersede test. The existing "a committed spawn supersedes a landed stop" case now runs over both spawn shapes.

The one open prior thread (exit.ts:157, the claimExit incarnation mismatch) is untouched by these commits and remains open; approval is withheld on that basis.

Pullfrog  | Fix it ➔ | View workflow run | Using DeepSeek Flash (free via Pullfrog for OSS) | 𝕏

@brennanb2025

brennanb2025 commented Sep 27, 2026 •

Copy link
Copy Markdown
Contributor Author

Review status

Ready for review. Head 65e6d78ade, merged with current main (merge commits, no force-push). The latest merge adds one fixup: main's new record of an unconfirmed explicit stop now reads the stop's reversibility from the intentional-stop register, like the kill path does. Seven review loops ran. The last two made only test additions and a small symmetry fix, and the final loop found no defects.

What review changed

  • Overlapping stops: a sleep and a restart that stop the same process now both label its exit. Before, the later stop overwrote the earlier one, which lost a renderer flag, and a runtime kill during a sleep was recorded as a permanent SSH stop.
  • Stop lifetime: a new process committing on a PTY id now ends a stop that no exit ever pinned, so an id reused by a daemon too old to report incarnations can't inherit an old stop.
  • Input facts: every PTY write now carries a required input kind (driving, launch, query-reply), recorded at one point just before the provider write. It replaces an optional flag whose default was opposite on different write paths.
    • Review had found three producers that slipped through that way: paired-client focus reports, dashboard preview typing, and a create-time draft tagged on one path but not on its twin.
    • A new writer now fails to compile, or fails the source scan for the runtime's unchecked files, until it picks a kind.
    • Launch bytes (startup commands, create-time drafts, the agent launch prompt) do not count as input.
  • Spawn funnels: both spawn-commit funnels record a run's facts only after its binding save and registration succeed.
  • New tests: IME and Hangul commits are driven through a real xterm and must reach the PTY as driving input.

Live QA (a separate macOS machine, isolated profiles, identical starting state for each arm)

  • main: after Sleep, the saved session drops the tab within 5 s. After a restart the pane is blank, and waking creates a new tab without the old output.
  • This PR: after Sleep, restart and wake, the same tab, pane and terminal come back with the scrollback. Sleep then wake without a restart also keeps the tab, and typing, paste and Enter reach the shell.
  • Screenshots are in the PR body.

Known, pre-existing, fixed separately

  • Paired clients (mobile, web): after a cold restore, or a wake more than 30 s after a sleep, a paired client can intermittently miss the kept terminal until its tab changes.
    • Cause: the attach probe reports the absent old process as an exit, so the surface is retired and then re-created. The paired-client gate then keeps a frame it had fenced down to zero tabs.
    • It reproduces on main with no sleep: kill the terminal daemon, then relaunch.
    • The desktop always gets the tab back.
    • The root fix is to treat a respawn on the saved owner as a replacement, not a death. It lands in its own PR.
  • Persistence gap: the saved session briefly lacks the tab between the attach probe and the new process's commit. Main has the same gap on every cold restore, and the same fix closes it.

Checks

  • Typecheck (node, web, CLI), full-repo lint, the changed-code quality gate and React Doctor are clean.
  • The main runtime, PTY IPC, persistence, plugin, cross-version wire and renderer terminal-pane suites pass. The only local failures were timeouts under machine load in files this PR does not touch, and those pass when run alone.
  • CI on 65e6d78ade: all green (41 passed, 11 skipped), merge state clean. persistence (macos-15-intel) failed once and passed on rerun: a SQLite lock-contention test (sync-database.test.ts:218) that expects a locked-database error within 200 ms took 424 ms on the slow Intel runner. This PR touches no SQLite code. The SSH e2e shards pass now that main's fix for its browser-route regression (fix(browser): a failed SSH route keeps its card while the host redials #23465) has landed.
  • The native Linux Wayland Hangul IME job failed once and passed on rerun. The syllable was lost before xterm: the IME cancelled the composition, and the compositor logged a discarded input event in that exact window. So this PR's input path never saw it. Main's daily scheduled run of the same job fails the same way (09-12, 09-22, 09-25).

Scope note: the diff is large (about 170 files) because the required input kind is threaded through every PTY writer and its test expectations. Production code is about +400 net lines; the rest is tests.

…-run-facts

# Conflicts:
#	src/main/ipc/pty-ssh-undelivered-kill.test.ts
#	src/main/runtime/runtime-pty-controller-contract.ts

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ No new issues found — the merged explicit-close hook now reads reversibility from the intentional-stop register, with tests that pin both the destructive and reversible cases.

Reviewed changes

  • Rebased the merged explicit-close hook onto the new register. The merge of main (#22929, every explicit terminal close commits through one main transaction) added PtyRuntimeController.recordUnconfirmedStop, whose first cut read deps.reversibleStopOwnersByPtyId — a map this PR deletes. Commit e664c0267b rewires it to runtime?.intentionalPtyStops?.isReversibleStopInFlight(ptyId) ?? false, matching the existing read in ipc/pty/runtime/kill.ts:33. The check is equivalent to main's reversibleStopOwnersByPtyId.has: both are true only while a reversible owner is in flight, and runtime is always defined when the controller is installed (runtime?.setPtyController guards it), so the ?? false default is unreachable in production.
  • Covered both outcomes. pty-ssh-undelivered-kill.test.ts records an explicit close's unconfirmed SSH stop and reports false (no replay order) for a local PTY and for one with a reversible stop in flight; the reversible case fails if that hook ever treats the stop as destructible.

The one open prior thread (exit.ts:157, the claimExit incarnation-mismatch guard) is untouched by these commits and remains open; approval is withheld on that basis.

Pullfrog  | Fix it ➔ | View workflow run | Using DeepSeek Flash (free via Pullfrog for OSS) | 𝕏

…-run-facts

# Conflicts:
#	src/main/runtime/orca-runtime-runtime-id.ts

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ No new issues found — the merge of origin/main resolves its one conflict correctly and leaves the branch's mechanism untouched.

Reviewed changes

  • Merged origin/main into the branch (commit 65e6d78ade). The branch's own mechanism files are byte-identical to the last reviewed head e664c0267b; the merge's only conflict was orca-runtime-runtime-id.ts.
  • Kept both sides of that conflict. Main's new tuiIdleEvidenceSource object (from its tui-idle refactor, also read by the new orca-runtime-resolve-exit-waiters.ts) is preserved and spread into terminalIdlePolls and terminalWait, alongside the branch's intentionalPtyStops, terminalRunFacts, noteTerminalSpawnCommit, and the terminalWriter input kind. Main's intentionalHandlelessPtyStops stays deleted; a repo-wide grep finds none of the marker names this PR removed.

The one open prior thread (exit.ts:157, the claimExit incarnation-mismatch guard) is untouched by the merge; approval is withheld on that basis.

Pullfrog  | Fix it ➔ | View workflow run | Using DeepSeek Flash (free via Pullfrog for OSS) | 𝕏

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant