Repository navigation
feat(ssh): host-stamped remote foreground identity - #18078
Conversation
|
Note Reviews pausedIt 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 Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Repository UI Review profile: CHILL Plan: Team Run ID: 📒 Files selected for processing (7)
Included review availability: Your plan provides up to 10 included reviews per hour; 5 remain after this review. 📝 WalkthroughWalkthroughThe change adds host-stamped remote foreground-process evidence with PTY incarnation, authority, observation, timing, and platform fences. Daemon, relay, provider, runtime, IPC, preload, and renderer paths forward expected incarnation IDs and evidence results. POSIX process snapshots support validated foreground resolution. Windows and insufficient evidence produce Merge Risk: 🟡 Moderate · up to This PR changes remote pane identity and completion decisions to use host process evidence. At the current head, absolute-path tmux/screen commands can bypass the safety fence, while process-snapshot and PTY lifecycle races plus other open correctness and CI issues can produce incorrect identity/completion behavior or prevent required checks from passing. Merge should wait for fixes or explicit owner acceptance. 🚥 Pre-merge checks | ✅ 3 | ❌ 2❌ Failed checks (2 warnings)
✅ Passed checks (3 passed)
Full details: Docstring CoverageExplanation Docstring coverage is 16.22% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 37 functions across 54 files. (1 skipped: 1 unsupported.) Full details: Description checkExplanation The description explains the change, motivation, behavior, limitations, testing, and compatibility impact. However, it omits the required Linked Issue entry ( Resolution Complete the repository template. Add a linked issue, provide required before/after visual attachments or a compliant explanation, complete the Testing checkboxes, add AI Disclosure details when applicable, complete Review, Agent skill upstream boundary, Notes, and Checklist sections.
✨ Finishing Touches 💡 2📝 Generate docstrings 💡
🛠️ Fix failing CI checks 💡
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. Comment |
There was a problem hiding this comment.
Actionable comments posted: 13
🧹 Nitpick comments (12)
src/main/providers/agent-foreground-process-batch.ts (1)
71-78: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueRemove the discarded
WindowsFenceconstruction.The block builds
fence, discards it withvoid fence, and then returns an unverifiable result that never carries a fence. The valuesrootCreationTime: 'unavailable'andsessionId: 'unavailable'are placeholders that no consumer reads. Removing the block also drops the only use of theWindowsFencetype import in this file.♻️ Proposed cleanup
- const fence: WindowsFence = { - platform: 'windows', - rootProcessId: request.rootPid, - rootCreationTime: 'unavailable', - sessionId: 'unavailable' - } - void fence return { ...metadata, verdict: 'unverifiable', reason: 'windows_ssh_foreground_unavailable' }src/shared/remote-foreground-evidence.test.ts (1)
46-68: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winAdd a case for an authority-generation change.
admitRemoteForegroundEvidencerejects a stale epoch only whenlastAuthorityGeneration === value.authorityGeneration. A host restart mints a new generation and resets the epoch, so an epoch at or belowlastObservationEpochmust still be admitted under a different generation. No case covers that branch, and a future change to the epoch guard would pass this suite.💚 Proposed additional assertion
expect( admitRemoteForegroundEvidence(live, { ...base, lastObservationEpoch: live.observationEpoch }) ).toBeNull() + expect( + admitRemoteForegroundEvidence(live, { + ...base, + lastAuthorityGeneration: 'host-b', + lastObservationEpoch: live.observationEpoch + }) + ).toEqual(live)src/main/daemon/terminal-host-process-inspection.ts (1)
49-70: 📐 Maintainability & Code Quality | 🔵 Trivial | 🏗️ Heavy liftTwo hosts implement the same evidence envelope independently, and the copies already differ. Both sites wrap the shared
resolveRemoteForegroundEvidencewith the same steps: check the retirement tombstone for expiry and incarnation equality, emitincarnation_mismatchwhen the expectation does not match, capture a process-table snapshot, fall back toprocess_table_unreadable, and stampauthorityGeneration,observationEpoch,capturedAgeMs,ptyId, andptyIncarnationId. Only the resolver is shared, so the fence semantics can drift per host. Two differences exist today: the relay rejects an empty-stringexpectedIncarnationIdas a mismatch while the daemon treats it as no expectation at all, and the two derivehasChildProcessesby different methods.
src/main/daemon/terminal-host-process-inspection.ts#L49-L70: move the incarnation-mismatch branch, the snapshot capture, and the unverifiable fallback into one shared helper, and align the empty-string expectation with the relay so an empty value is a mismatch rather than no expectation.src/relay/pty-handler.ts#L2428-L2477: replace the inline snapshot and unverifiable branches with the same shared helper, so a future change to a fence reason or a stamped field applies to both hosts.src/renderer/src/components/terminal-pane/pty-connection/reattach-result-handler.ts (1)
55-55: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winDeclare
remotePtyIncarnationIdonConnectPanePtySessioninstead of a local intersection.This file writes
session.remotePtyIncarnationId, andterminal-keydown-fit.tsreads it throughgetExpectedIncarnationId. Each side declares the member locally, so the writer and the reader are only connected by structural typing. A rename or a type change on one side will not fail typechecking on the other.Add the member to the shared
ConnectPanePtySessiontype and pick it here like the other members in thePick<...>list.src/renderer/src/components/terminal-pane/pty-connection/terminal-keydown-fit.ts (1)
178-179: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value
isRemoteRuntimePtyIdis redundant in this predicate.
isRemoteExecutionHostPtyIdalready returnsisRemoteRuntimePtyId(ptyId) || parseAppSshPtyId(ptyId) !== null, so the second disjunct can never change the result. The same pair appears again on Line 235 and Line 242. Extract one local helper and use it in all three places, so the classification cannot drift between them.♻️ Proposed cleanup
+ const isRemotePtyId = (ptyId: string | null | undefined): boolean => + isRemoteExecutionHostPtyId(ptyId) + session.agentCompletionCoordinator = createAgentCompletionCoordinator({ paneKey: session.cacheKey, statusLane: 'pty', getPtyId: () => session.transport.getPtyId(), - isRemotePtyId: (ptyId) => - Boolean(isRemoteExecutionHostPtyId(ptyId) || isRemoteRuntimePtyId(ptyId)), + isRemotePtyId,src/shared/process-table-snapshot-reader.ts (1)
190-224: 🚀 Performance & Scalability | 🔵 Trivial | 💤 Low valueConfirm the
/procfan-out stays bounded on busy hosts.
readLinuxProcessStartTimesissues one concurrentreadFileper tty-bearing row through a singlePromise.all. On a host with many terminal sessions this opens a large number of simultaneous file handles inside the shared snapshot path. The TTL cache limits the frequency, but not the width of one capture.Consider a small concurrency limit, or restrict the candidate set to the PIDs the caller actually needs.
src/shared/process-table-snapshot.ts (1)
141-146: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueSimplify the dead fallbacks and the duplicated ternary branches.
In the strict parser, group 8 is mandatory in both
macStartMatchandnumericMatch, somatch[8] ?? match[6]always resolves tomatch[8], and line 146 reduces tocommand: match[8]. Lines 141-145 also build the identical object in both branches whenevermatch[7] !== undefined.The lenient parser has the same pattern:
evidenceMatch[5] ?? evidenceMatch[3]andevidenceMatch[8] ?? evidenceMatch[6] ?? evidenceMatch[4]cannot reach their fallbacks, because groups 5 and 8 are mandatory in that regex.♻️ Proposed simplification
rows.push({ pid, ppid, pgid, tpgid, stat: match[5], - ...(numericMatch && match[7] !== undefined - ? { tty: match[6], startTime: match[7] } - : macStartMatch - ? { tty: match[6], startTime: match[7] } - : {}), - command: numericMatch ? (match[8] ?? match[6]) : match[8] + ...(match[7] !== undefined ? { tty: match[6], startTime: match[7] } : {}), + command: match[8] })src/main/runtime/orca-runtime-terminal-create-deduplication.ts (1)
99-105: 🗄️ Data Integrity & Integration | 🔵 Trivial | ⚡ Quick win
reconcileRemoteTerminalCreateomitsincarnationIdfrom the adopted result.This PR adds
incarnationIdtoRuntimeTerminalCreate, andgetPtyExecutionHostMetadatanow populates it for both SSH and local hosts. The reconcile path still returns the adopted terminal without it, even thoughsession.incarnationIdis available from the controller listing at Line 84 and is already stored byrecordPtyWorktree.A client that adopts a reconciled terminal therefore has no incarnation fence, and
admitRemoteForegroundEvidencerejects every evidence record for that pane becauseexpectedIncarnationIdstaysnull. Completion detection degrades tounverifiableuntil the pane rebinds.♻️ Proposed fix
return { handle: adoptedHandle, ptyId: session.id, worktreeId, + ...(session.incarnationId ? { incarnationId: session.incarnationId } : {}), title: session.title || null, surface: 'background' }src/renderer/src/components/terminal-pane/remote-runtime-pty-transport.ts (1)
533-544: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚖️ Poor tradeoff
findReadyHostSessionHandlemutates transport state from inside a lookup.The function name and return type describe a pure selection. Line 541 now writes
authoritativePtyIncarnationIdas a side effect. Three call sites use it:waitForHostSessionHandle(Line 615, Line 665) andwaitForResubscribeHostSessionHandle(Line 812). The resubscribe caller may discard the returned handle (therequire-replacementand same-handle cases), yet the incarnation write already happened.Return the incarnation with the handle and let each caller decide when to adopt it.
♻️ Proposed refactor
- ): string | null { + ): { terminal: string; incarnationId: string | null } | null { const terminalTabs = getHostSessionTerminalSurfaces(snapshot, hostTabId, { matchRequestedLeaf: false }) const selected = leafId ? terminalTabs.find( (tab) => tab.status === 'ready' && tab.parentTabId === hostTabId && tab.leafId === leafId ) : (terminalTabs.find( (tab) => tab.status === 'ready' && tab.parentTabId === hostTabId && tab.isActive ) ?? terminalTabs.find((tab) => tab.status === 'ready' && tab.parentTabId === hostTabId)) if (selected?.status === 'ready') { - authoritativePtyIncarnationId = selected.incarnationId ?? null - return selected.terminal + return { terminal: selected.terminal, incarnationId: selected.incarnationId ?? null } } return null }src/renderer/src/components/terminal-pane/agent-completion-process-monitor.ts (2)
233-233: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick win
requestStartedAtMonotonicis captured before the inspection is queued.
enqueueAgentProcessInspectioncan hold the request beforerunexecutes. The timestamp taken here therefore includes queue wait time, andadmitRemoteForegroundEvidenceadds that wait tocapturedAgeMswhen it applies the 2000 ms budget.Under a busy inspection queue, a fresh host capture can be rejected purely because the request waited in the queue. The result is a dropped remote completion, and it is indistinguishable from genuine staleness.
The fence should measure the transport round trip, not the local queue delay. Capture the timestamp at the start of
run.♻️ Proposed fix
state.inspectionInFlight = true const generationAtRequest = state.inspectionGeneration - const requestStartedAtMonotonic = performance.now() const pendingTitleIdAtRequest = priority === 'pending-title' ? pendingTitle.get()?.id : null enqueueAgentProcessInspection({ priority, canRun: () => !state.disposed, run: async () => { + const requestStartedAtMonotonic = performance.now() let inspectedRecognizedAgent = false
98-102: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueThe response-time binding-key reset is unreachable.
bindRemoteInspectionGenerationalready setsremoteBindingKeyfor the sameptyIdand incarnation at request time (Line 36). The caller at Lines 247-251 also rejects any result whose incarnation changed during the request. SoremoteBindingKey !== bindingKeycannot hold here for a remote PTY.Remove the duplicate reset, or add a comment that names the case it guards.
src/main/daemon/terminal-host-process-inspection.test.ts (1)
35-44: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winAdd coverage for the tombstone
exitedverdict and its expiry boundary.This test covers only the
incarnation_mismatchbranch. That branch returns before the process-table read, so it is the cheapest case to assert.The retired-incarnation path is the only producer of the
exitedverdict, and it is gated by both an incarnation match and a 2-secondexpiresAtwindow. Two cases stay untested: an exited session inspected with the matchingexpectedIncarnationIdinside the window must resolve toverdict: 'exited'withreason: 'pty_exit_<code>', and the same inspection after the window must reject withSessionNotFoundError. Use fake timers to move pastexpiresAtinstead of waiting.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Team
Run ID: 4a7f6d2e-1cb7-4184-b9bf-4d05a8a0a29d
📒 Files selected for processing (60)
docs/plans/ssh-agent-identity-plan.mdsrc/main/daemon/daemon-foreground-process-protocol.tssrc/main/daemon/daemon-pty-adapter-protocol-compatibility.test.tssrc/main/daemon/daemon-pty-process-inspection.tssrc/main/daemon/daemon-pty-router.tssrc/main/daemon/daemon-request-router.tssrc/main/daemon/terminal-host-process-inspection.test.tssrc/main/daemon/terminal-host-process-inspection.tssrc/main/daemon/terminal-host-session-inspection-operations.tssrc/main/daemon/terminal-host.tssrc/main/ipc/pty/ipc/inspect.tssrc/main/ipc/pty/runtime/controller.tssrc/main/ipc/pty/runtime/foreground-process-evidence-capability.tssrc/main/ipc/pty/runtime/inventory-operations.tssrc/main/ipc/pty/runtime/operations.tssrc/main/providers/agent-foreground-process-batch.tssrc/main/providers/agent-foreground-process-remote-evidence.test.tssrc/main/providers/agent-foreground-process.tssrc/main/providers/pty-process-inspection.tssrc/main/providers/pty-provider-contract.tssrc/main/providers/ssh-agent-session-capabilities.tssrc/main/providers/ssh-pty-provider.test.tssrc/main/providers/ssh-pty-provider.tssrc/main/runtime/orca-runtime-create-runtime-owned-mobile-session-terminal.tssrc/main/runtime/orca-runtime-perform-mobile-session-pty-records-refresh.tssrc/main/runtime/orca-runtime-publish-pty-backed-mobile-session-terminal.tssrc/main/runtime/orca-runtime-refresh-pty-worktree-records-with-controller-inventory.tssrc/main/runtime/orca-runtime-resolve-terminal-pane.tssrc/main/runtime/orca-runtime-restore-structured-agent-session-tabs-once.tssrc/main/runtime/orca-runtime-terminal-create-deduplication.tssrc/main/runtime/rpc/methods/terminal/terminal-query-methods.tssrc/main/runtime/rpc/methods/terminal/unary-schemas.tssrc/main/runtime/runtime-pty-controller-contract.tssrc/preload/api/pty-api.tssrc/preload/api/pty-bridge-stream-and-serialization.tssrc/preload/api/ssh-bridge.tssrc/relay/pty-handler-inventory-process-evidence.test.tssrc/relay/pty-handler.tssrc/renderer/src/components/terminal-pane/agent-completion-coordinator-types.tssrc/renderer/src/components/terminal-pane/agent-completion-poll-scheduler.tssrc/renderer/src/components/terminal-pane/agent-completion-process-monitor.tssrc/renderer/src/components/terminal-pane/pane-foreground-agent-tracker.test.tssrc/renderer/src/components/terminal-pane/pane-foreground-agent-tracker.tssrc/renderer/src/components/terminal-pane/pane-foreground-process-reader.tssrc/renderer/src/components/terminal-pane/pty-connection/fresh-spawn-start.tssrc/renderer/src/components/terminal-pane/pty-connection/pane-agent-identity.tssrc/renderer/src/components/terminal-pane/pty-connection/pane-pty-visibility-bind.tssrc/renderer/src/components/terminal-pane/pty-connection/reattach-result-handler.tssrc/renderer/src/components/terminal-pane/pty-connection/terminal-keydown-fit.tssrc/renderer/src/components/terminal-pane/pty-transport-types.tssrc/renderer/src/components/terminal-pane/remote-runtime-pty-transport.tssrc/renderer/src/runtime/runtime-terminal-inspection.tssrc/shared/foreground-process-evidence.tssrc/shared/process-table-snapshot-reader.tssrc/shared/process-table-snapshot.tssrc/shared/remote-foreground-evidence-admission.tssrc/shared/remote-foreground-evidence.test.tssrc/shared/runtime-mobile-session-tab-contracts.tssrc/shared/runtime-terminal-contracts.tstests/e2e/remote-agent-completion-authority.unit.test.ts
Included review availability: Your plan provides up to 10 included reviews per hour; 8 remain after this review.
| * `exited` requires positive host evidence: a host-delivered exit/tombstone tied to the | ||
| exact `authorityGeneration`, PTY id, and `ptyIncarnationId`, or a complete host capture | ||
| that proves the incarnation's anchor is gone according to the host's retirement record. | ||
| A missing map entry, client-side set removal, socket close, or `terminal_gone` with no | ||
| matching host tombstone is `unverifiable`. |
There was a problem hiding this comment.
🗄️ Data Integrity & Integration | 🟠 Major | 🏗️ Heavy lift
🔎 Supported by static analysis
🏁 Script executed:
#!/usr/bin/env bash
set -euo pipefail
sed -n '1,130p' src/main/runtime/unstopped-pty-verification.ts
rg -n -C 8 \
'resolveUnstoppedPtyVerdict|verifyUnstoppedPtys|process-exit|tombstone|status: .exited.' \
src testsRepository: stablyai/orca
Length of output: 50370
🏁 Script executed:
#!/usr/bin/env bash
set -euo pipefail
printf '%s\n' '--- verifier implementation ---'
cat -n src/main/runtime/unstopped-pty-verification.ts | sed -n '1,150p'
printf '%s\n' '--- direct symbol references ---'
rg -n -C 12 --glob '*.ts' --glob '*.tsx' \
'\bresolveUnstoppedPtyVerdict\b|\bverifyUnstoppedPtys\b' src tests
printf '%s\n' '--- relevant plan sections ---'
cat -n docs/plans/ssh-agent-identity-plan.md | sed -n '205,245p;320,350p'Repository: stablyai/orca
Length of output: 23058
🏁 Script executed:
#!/usr/bin/env bash
set -euo pipefail
printf '%s\n' '--- teardown consumer ---'
cat -n src/main/runtime/worktree-teardown.ts | sed -n '190,270p'
printf '%s\n' '--- verdict contract ---'
cat -n src/shared/pty-liveness-verdict.ts | sed -n '1,180p'
printf '%s\n' '--- process-list contract and implementations ---'
rg -n -C 10 \
'listProcesses\s*\(|interface IPtyProvider|type IPtyProvider|PtyProcess' \
src/main/providers src/main src/shared -g '*.ts' -g '*.tsx' | head -n 360
printf '%s\n' '--- scoped repository conventions and learnings ---'
find /tmp/coderabbit-repo-knowledge/stablyai/orca-89dc44e4 -type f -name '*.md' -printRepository: stablyai/orca
Length of output: 35346
🏁 Script executed:
#!/usr/bin/env bash
set -euo pipefail
printf '%s\n' '--- provider contract ---'
cat -n src/main/providers/pty-provider-contract.ts | sed -n '1,150p'
printf '%s\n' '--- local process listing ---'
rg -n -C 12 'function listLocalPtyProcesses|export .*listLocalPtyProcesses|listProcesses\(\)' \
src/main/providers/local-pty-session-operations.ts \
src/main/providers/local-pty-provider.ts \
src/main/providers/ssh-pty-provider.ts
printf '%s\n' '--- applicable repository knowledge ---'
find /tmp/coderabbit-repo-knowledge/stablyai-orca-89dc44e4 -type f -name '*.md' -print 2>/dev/null | head -n 80Repository: stablyai/orca
Length of output: 16169
Scope the tombstone-only exited rule.
resolveUnstoppedPtyVerdict returns status: 'exited' when listProcesses() omits a failed PTY ID. This contradicts the shared PtyLivenessVerdict contract, which requires positive owning-host evidence and treats inventory silence as unverifiable.
If the planned foreground-completion path reuses this verdict, it can treat a non-incarnation-specific inventory result as proof of exit. State that resolveUnstoppedPtyVerdict is outside the foreground-completion contract, or add a separate host-tombstone-based verdict.
| // Multiplexers can make a descendant appear foreground while the user is | ||
| // actually interacting with another session. This relay has no measured | ||
| // multiplexer/session fence, so remain conservative for the whole subtree. | ||
| if ([root, ...descendants].some((row) => /(?:^|\s)(?:tmux|screen)(?:\s|$)/i.test(row.command))) { |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟠 Major | ⚡ Quick win
The multiplexer fence misses tmux/screen launched by an absolute path.
The pattern requires tmux or screen to start at the beginning of the command line or follow whitespace. A command line such as /usr/bin/tmux new-session or /opt/homebrew/bin/tmux attach does not match, because the token is preceded by /. Absolute-path invocation is common, and login shells and wrappers frequently produce it.
When the pattern misses, the resolver continues and can return verdict: 'live' for a subtree that runs inside a multiplexer. That is the exact case the comment above says must stay conservative, because the foreground descendant may belong to a multiplexer window the user is not viewing. The renderer then admits host-stamped evidence and can attribute an agent identity or a completion to the wrong pane.
The added test at src/main/providers/agent-foreground-process-remote-evidence.test.ts:66 uses the bare command tmux new-session, so it does not exercise this path.
Match on the command basename instead of raw text position.
🐛 Proposed fix to match the executable basename
- if ([root, ...descendants].some((row) => /(?:^|\s)(?:tmux|screen)(?:\s|$)/i.test(row.command))) {
+ if (
+ [root, ...descendants].some((row) => {
+ const executable = row.command.trim().split(/\s+/)[0] ?? ''
+ const name = executable.slice(executable.lastIndexOf('/') + 1).toLowerCase()
+ return name === 'tmux' || name === 'screen'
+ })
+ ) {
return { ...metadata, verdict: 'unverifiable', reason: 'multiplexer_boundary' }
}📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| if ([root, ...descendants].some((row) => /(?:^|\s)(?:tmux|screen)(?:\s|$)/i.test(row.command))) { | |
| if ( | |
| [root, ...descendants].some((row) => { | |
| const executable = row.command.trim().split(/\s+/)[0] ?? '' | |
| const name = executable.slice(executable.lastIndexOf('/') + 1).toLowerCase() | |
| return name === 'tmux' || name === 'screen' | |
| }) | |
| ) { | |
| return { ...metadata, verdict: 'unverifiable', reason: 'multiplexer_boundary' } | |
| } |
| this.foregroundEvidenceProbe ?? | ||
| this.mux | ||
| .request('pty.getCapabilities', undefined, { | ||
| signal: options.signal, |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win
Do not bind the shared probe to one caller's signal.
foregroundEvidenceProbe is shared. If the first caller aborts, this signal cancels the physical pty.getCapabilities request. The catch then resolves the shared probe as false, so concurrent callers without an aborted signal also treat a capable relay as unsupported.
Create the physical request without options.signal. Keep cancellation at waitForSshCapabilityProbe. Add a regression test with an aborted first caller and a live concurrent caller.
Proposed fix
.request('pty.getCapabilities', undefined, {
- signal: options.signal,
timeoutMs: 5_000
})📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| signal: options.signal, |
| lifecycle.handlePtyData("printf '\\033]133;A\\007\\033]777;agent=codex\\007\\033]133;D;0\\007'") | ||
| await flushSettleRead(COMMAND_SETTLE_MS) | ||
|
|
||
| expect(publish).not.toHaveBeenCalledWith( | ||
| expect.objectContaining({ agent: 'codex', shellForeground: false }) | ||
| ) |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟠 Major | ⚡ Quick win
The forged-OSC payload contains no escape bytes, so this test does not exercise the fence.
The string literal uses \\033 and \\007. In a JavaScript double-quoted string, \\ produces one backslash, so the data passed to handlePtyData is the literal text \033]133;A\007... and not the ESC and BEL control bytes. createOsc133CommandFinishedScanner matches on real control bytes, so no command-start and no command-finish event fires. tracker.onCommandStarted and tracker.onCommandFinished never run, flushSettleRead has no scheduled read to flush, and publish is never called.
The negative assertion then passes for the wrong reason. A regression that lets forged remote output assert an agent identity would not fail this test.
Use real control bytes, and assert that no agent was published at all so the check cannot pass vacuously.
💚 Proposed fix
- lifecycle.handlePtyData("printf '\\033]133;A\\007\\033]777;agent=codex\\007\\033]133;D;0\\007'")
+ lifecycle.handlePtyData('\x1b]133;A\x07\x1b]777;agent=codex\x07\x1b]133;D;0\x07')
await flushSettleRead(COMMAND_SETTLE_MS)
- expect(publish).not.toHaveBeenCalledWith(
- expect.objectContaining({ agent: 'codex', shellForeground: false })
- )
+ expect(remoteRead).toHaveBeenCalled()
+ expect(publish).not.toHaveBeenCalledWith(expect.objectContaining({ agent: 'codex' }))📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| lifecycle.handlePtyData("printf '\\033]133;A\\007\\033]777;agent=codex\\007\\033]133;D;0\\007'") | |
| await flushSettleRead(COMMAND_SETTLE_MS) | |
| expect(publish).not.toHaveBeenCalledWith( | |
| expect.objectContaining({ agent: 'codex', shellForeground: false }) | |
| ) | |
| lifecycle.handlePtyData('\x1b]133;A\x07\x1b]777;agent=codex\x07\x1b]133;D;0\x07') | |
| await flushSettleRead(COMMAND_SETTLE_MS) | |
| expect(remoteRead).toHaveBeenCalled() | |
| expect(publish).not.toHaveBeenCalledWith(expect.objectContaining({ agent: 'codex' })) |
| }): void => { | ||
| authoritativeExecutionHostId = terminal.executionHostId ?? authoritativeExecutionHostId | ||
| authoritativeHostPlatform = terminal.hostPlatform ?? authoritativeHostPlatform | ||
| authoritativePtyIncarnationId = terminal.incarnationId ?? null |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟠 Major | ⚡ Quick win
adoptExecutionMetadata clears a known incarnation when the terminal record omits it.
The two neighbouring fields preserve their previous value on absence (?? authoritativeExecutionHostId, ?? authoritativeHostPlatform). incarnationId instead resets to null.
Concrete regression in attachHostSessionMirror:
findReadyHostSessionHandlerecords the incarnation from the session-tabs snapshot (Line 541).- The
terminal.resolvePaneblock callsadoptExecutionMetadata(terminal)at Line 921. RuntimeTerminalResolvePane.incarnationIdis optional.getPtyExecutionHostMetadataomits it when the PTY record is missing orpty.incarnationIdis falsy.authoritativePtyIncarnationIdresets tonull, and the result at Lines 956-961 omitsincarnationId.
The renderer's getExpectedIncarnationId then stays null, and admitRemoteForegroundEvidence rejects every record for that pane, because it returns null whenever expectedIncarnationId === null. Remote completion detection stays permanently unverifiable for a pane whose incarnation was already known.
The same reset happens at Line 1532 when waitForPublishedHostSessionHandle calls rebindRemoteTerminalHandle(update.terminalHandle) with one argument (Line 1596); that path has no incarnation to supply.
Clearing on a genuine identity change is correct. Clearing on a merely absent field is not. Distinguish the two.
🐛 Proposed fix
const adoptExecutionMetadata = (terminal: {
executionHostId?: ExecutionHostId
hostPlatform?: NodeJS.Platform
incarnationId?: string | null
}): void => {
authoritativeExecutionHostId = terminal.executionHostId ?? authoritativeExecutionHostId
authoritativeHostPlatform = terminal.hostPlatform ?? authoritativeHostPlatform
- authoritativePtyIncarnationId = terminal.incarnationId ?? null
+ // Why: an absent field is unknown, not a proven identity change. Only an
+ // explicit null retires the fence; undefined keeps the last known value.
+ if (terminal.incarnationId !== undefined) {
+ authoritativePtyIncarnationId = terminal.incarnationId
+ }
}If the reset is deliberate, add the reason as a comment and make resolvePane always carry the incarnation, so the two sources cannot disagree.
📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| authoritativePtyIncarnationId = terminal.incarnationId ?? null | |
| const adoptExecutionMetadata = (terminal: { | |
| executionHostId?: ExecutionHostId | |
| hostPlatform?: NodeJS.Platform | |
| incarnationId?: string | null | |
| }): void => { | |
| authoritativeExecutionHostId = terminal.executionHostId ?? authoritativeExecutionHostId | |
| authoritativeHostPlatform = terminal.hostPlatform ?? authoritativeHostPlatform | |
| // Why: an absent field is unknown, not a proven identity change. Only an | |
| // explicit null retires the fence; undefined keeps the last known value. | |
| if (terminal.incarnationId !== undefined) { | |
| authoritativePtyIncarnationId = terminal.incarnationId | |
| } | |
| } |
| const evidenceMatch = trimmed.match( | ||
| /^(\d+)\s+(\d+)\s+(?:(-?\d+)\s+(-?\d+)\s+)?(\S+)(?:\s+(\S+)\s+(\d+))?\s+(.+)$/ | ||
| ) |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟠 Major | ⚡ Quick win
🔎 Supported by static analysis
🏁 Script executed:
#!/bin/bash
# Description: Locate all callers of the process-table parsers and the row shapes they feed.
set -euo pipefail
echo '--- callers of the parsers ---'
rg -nP -C6 '\b(parseProcessTableRows|parseStrictProcessTableRows)\s*\(' --type=ts
echo
echo '--- every ps argument list in the repo (column shapes) ---'
rg -nP -C3 "['\"]-a?xo['\"]|pid=,ppid=" --type=ts
echo
echo '--- files that build ProcessTableRow-like input strings ---'
rg -nP -C4 '\bProcessTableRow\b' --type=ts -g '!**/node_modules/**'Repository: stablyai/orca
Length of output: 182
🏁 Script executed:
set -euo pipefail
echo '--- repository conventions and learnings ---'
find /tmp/coderabbit-repo-knowledge/stablyai-orca-89dc44e4 -maxdepth 2 -type f -name '*.md' -print
for f in /tmp/coderabbit-repo-knowledge/stablyai-orca-89dc44e4/{repo-conventions,learnings,architecture}/*.md; do
[ -f "$f" ] && { echo "--- $f"; head -80 "$f"; }
done
echo '--- target file ---'
cat -n src/shared/process-table-snapshot.ts
echo '--- parser symbols and direct callers ---'
rg -n -C5 'parse(ProcessTableRows|StrictProcessTableRows)|process-table-snapshot|PS_ARGS|pid=,ppid=' --glob '*.ts' --glob '*.tsx' .Repository: stablyai/orca
Length of output: 50370
🏁 Script executed:
set -euo pipefail
echo '--- target file ---'
wc -l src/shared/process-table-snapshot.ts
cat -n src/shared/process-table-snapshot.ts
echo '--- exact parser references across tracked source ---'
rg -n -C4 'parseProcessTableRows|parseStrictProcessTableRows|process-table-snapshot' --glob '!node_modules/**' --glob '!dist/**' --glob '!build/**' .
echo '--- process-table conventions, if any ---'
rg -n -i -C3 'process.?table|snapshot|ps_args|ps args' /tmp/coderabbit-repo-knowledge/stablyai-orca-89dc44e4/conventions /tmp/coderabbit-repo-knowledge/stablyai-orca-89dc44e4/learnings/src.md /tmp/coderabbit-repo-knowledge/stablyai-orca-89dc44e4/learnings/repo-wide.md || trueRepository: stablyai/orca
Length of output: 50369
🏁 Script executed:
set -euo pipefail
echo '--- snapshot reader and PS_ARGS binding ---'
wc -l src/shared/process-table-snapshot-reader.ts
cat -n src/shared/process-table-snapshot-reader.ts
echo '--- production imports and calls, excluding tests/config ---'
rg -n -C5 'get(ProcessTableSnapshot|StrictProcessTableSnapshot)|parse(ProcessTableRows|StrictProcessTableRows)|PS_ARGS' src --glob '!**/*.test.ts'
echo '--- all direct parser calls, excluding the already inspected target test file ---'
rg -n -C3 'parse(ProcessTableRows|StrictProcessTableRows)\s*\(' src --glob '*.ts' --glob '!src/shared/process-table-snapshot.ts' --glob '!src/shared/process-table-snapshot.test.ts'Repository: stablyai/orca
Length of output: 30630
🏁 Script executed:
set -euo pipefail
echo '--- command-to-process-name consumer ---'
rg -n -C8 'getForegroundProcessNameFromProcessTable|recognizeAgentProcessFromCommandLine|row\.command|command\)' src/main src/relay src/shared --glob '*.ts' --glob '!**/*.test.ts'
echo '--- parser-related test contracts around legacy and numeric command shapes ---'
sed -n '280,375p' src/shared/process-table-snapshot.test.tsRepository: stablyai/orca
Length of output: 50370
Prevent the optional TTY/start-time group from consuming command tokens. When parseProcessTableRows or parseStrictProcessTableRows receives 100 1 100 100 Ss node 8080 server.js, the optional group parses node and 8080 as tty and startTime, so command becomes server.js. This can prevent recognizeAgentProcessFromCommandLine(row.command) from identifying the foreground agent. Anchor the group on a TTY-like token or parse the fixed columns positionally.
Source: Linters/SAST tools
| runtimeCall.mockRejectedValue( | ||
| new Error('Runtime request timed out before terminal.inspectProcess completed') | ||
| ) | ||
| await vi.advanceTimersByTimeAsync(60_000) | ||
| expect(runtimeCall).not.toHaveBeenCalled() |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win
This test does not exercise the transport failure it names.
runtimeCall.mockRejectedValue(...) is set at Line 102, but the assertion at Line 106 is expect(runtimeCall).not.toHaveBeenCalled(). No call ever consumes the rejection, so the mock is dead setup. The body proves only that a remote pane makes no cadence RPC, which the first test already asserts at Line 61.
To cover the stated behavior, trigger an event-driven inspection the way the title tests do, then assert the rejection produces no dispatch and no repeated calls.
The same gap applies to the title at Line 165. It claims process-exit dispatches "only for a positive host tombstone", but the body asserts only the positive case. Add a negative turn in which the second response carries a non-exited verdict, and assert dispatchCompletion receives no process-exit meta.
💚 Proposed fix to exercise the rejected inspection
coordinator.startProcessTracking()
runtimeCall.mockRejectedValue(
new Error('Runtime request timed out before terminal.inspectProcess completed')
)
+ coordinator.observeTitle('Codex working')
+ coordinator.observeTitle('/tmp/failed-inspection')
await vi.advanceTimersByTimeAsync(60_000)
- expect(runtimeCall).not.toHaveBeenCalled()
+ expect(runtimeCall).toHaveBeenCalledOnce()
expect(dispatchCompletion).not.toHaveBeenCalled()📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| runtimeCall.mockRejectedValue( | |
| new Error('Runtime request timed out before terminal.inspectProcess completed') | |
| ) | |
| await vi.advanceTimersByTimeAsync(60_000) | |
| expect(runtimeCall).not.toHaveBeenCalled() | |
| runtimeCall.mockRejectedValue( | |
| new Error('Runtime request timed out before terminal.inspectProcess completed') | |
| ) | |
| coordinator.observeTitle('Codex working') | |
| coordinator.observeTitle('/tmp/failed-inspection') | |
| await vi.advanceTimersByTimeAsync(60_000) | |
| expect(runtimeCall).toHaveBeenCalledOnce() | |
| expect(dispatchCompletion).not.toHaveBeenCalled() |
There was a problem hiding this comment.
Important
The evidence machinery is sound overall — the additive wire field, capability handshake, incarnation/epoch/age admission, and event-only cost invariant are all handled carefully. Two things need attention before merge: the PID-reuse fences listed in the plan aren't actually compared against anything, and the paired-runtime (daemon) path regresses the foregroundProcess compatibility field relative to both the relay and its own prior behavior.
Reviewed changes
- Evidence contract — new
RemoteForegroundEvidence(live/unverifiable/exited) withPosixFence/WindowsFenceand a runtime validator insrc/shared/foreground-process-evidence.ts. - Renderer admission —
admitRemoteForegroundEvidencerejects missing incarnation binding, pty/incarnation mismatch, stale age, and non-increasing epochs on the same authority generation. - Host resolvers — relay
PtyHandler.inspectProcessand daemonTerminalHost.inspectProcessboth delegate toresolveRemoteForegroundEvidence, which enforces POSIX tty/pgid/tpgid/start-time, tty-boundary, multiplexer, and ambiguity fences; Windows-over-SSH staysunverifiable. - Process-table reader —
process-table-snapshot-reader.tsextracts the memoizedpsreader, adds Linux/proc/<pid>/statstart ticks and a macOSlstartmarker, plus agetSnapshotWithAgefor conservative capture age. - Tombstones — relay and daemon retain
{incarnationId, code, expiresAt}on exit and replay a matchingexitedverdict on inspect. - Capability + inventory projection — relay advertises
foregroundProcessEvidenceVersion: 1; mobile auto-refresh is suppressed against legacy hosts and sendsincludeForegroundProcessEvidence: falseto skip host process-table work. - Renderer completion —
pane-foreground-agent-tracker/createPaneForegroundProcessReaderroute remote reads throughinspectRuntimeTerminalProcess; the poll scheduler short-circuits remote cadence.
⚠️ PID-reuse fences are asserted, not compared
The plan (and the PR summary's "Fences" section) lists "anchor PID start time" and "candidate PID start time" as required fences against PID reuse, but resolveRemoteForegroundEvidence only requires a start time to be present on the shell and candidate within the current capture. It never compares that start time against a prior observation, so a shell whose PID was reused by an unrelated process between spawn and inspect is not detected. The incarnation/authority/epoch fencing covers PTY replacement and host restart, but not a live incarnation whose anchor PID silently changed ownership. Either store the spawn-time anchor start marker and compare it here, or document this as an explicit R1 limitation alongside the Windows note.
Technical details
# PID-reuse fence is decorative
## Affected sites
- src/main/providers/agent-foreground-process-batch.ts:80-146 — `resolveRemoteForegroundEvidence` requires `root.startTime` and `candidate.row.startTime` to be non-empty but never compares them to a stored spawn-time value.
## Required outcome
- Detect anchor PID reuse: capture the shell's host-native start marker at spawn and reject `live` when the inspect-time marker differs (or is absent).
- Detect candidate PID reuse: same comparison for the selected foreground process, or document why a single-capture consistency check is sufficient for R1.
## Suggested approach
- Thread a spawn-time start marker into `BatchedForegroundProcessRequest` (alongside `rootPid`/`fallbackProcess`) and compare in the resolver; degrade to `unverifiable` with a stable reason on mismatch.
## Open questions for the human
- Is a single-capture start-time presence check acceptable for R1 (given epoch/incarnation fencing already bounds staleness), or does the plan's reuse fence need implementing now?ℹ️ Nitpicks
foregroundProcesson the daemon path returnsnullfor aliveshell verdict (idle shell), while the relay preserves the shell name viaevidence.processName ?? managed.pty.process— keep the two host paths consistent (see inline comment).- Tombstone retention differs between host implementations: relay
5_000msvs daemon2_000ms, with no shared constant or comment explaining why the reconnect grace window differs. - The macOS
lstartcolumn parsing (macStartMatchinparseStrictProcessTableRows/parseProcessTableRows) and the newtty=/etimes=columns are untested against a real host — the PR notes Linux SSH container validation couldn't run and macOS wasn't exercised at all. A fixture capturing realps -axo … lstart=output would guard this.
DeepSeek Pro (free via Pullfrog for OSS) | 𝕏
| } | ||
| } | ||
| return { | ||
| foregroundProcess: evidence.verdict === 'live' ? evidence.processName : foregroundProcess, |
There was a problem hiding this comment.
For a live verdict with processName: null (idle shell foreground), this returns foregroundProcess: null, whereas the pre-existing daemon behavior returned the shell name (session.getForegroundProcess()), and the relay path preserves it via evidence?.verdict === 'live' ? (evidence.processName ?? managed.pty.process) || null : managed.pty.process || null. Mixed-version or legacy consumers of this compatibility field would see null for an idle shell on the paired-runtime path but a shell name on the SSH path. Mirror the relay fallback: evidence.verdict === 'live' ? (evidence.processName ?? foregroundProcess) : foregroundProcess.
|
Review status for PR #18078\n\n- Two same-model review passes completed; final review is clean with no proven in-scope correctness, compatibility, security, or performance findings.\n- Fixed and pushed:\n - preserved legacy one-argument runtime inspection calls when no incarnation fence is supplied;\n - changed remote descendant traversal to linear time;\n - rejected delayed evidence from previously accepted authority generations;\n - bounded/pruned retired PTY evidence records in both daemon and relay;\n - added focused expiry/capacity coverage.\n- Validation: 7 focused files passed (1,325 tests, 1 skipped); passed; lint/format hooks and passed.\n- OSS precedent review completed privately; the design follows host-authoritative, fenced remote process/session identity with explicit degraded states and additive compatibility fields.\n- Electron/Grok orchestration was started with Playwright CDP-only constraints, but the worker did not produce a final screenshot report before this review ended; no screenshot evidence is claimed here.\n- Required real SSH/Linux validation remains blocked/unverified because the throwaway Docker SSH target could not start with the local Docker daemon unavailable. was not used.\n\nCurrent recommendation: land after the real SSH/Linux validation gate is run successfully; otherwise keep this residual risk explicit. |
Electron CDP validation (ssh-identity-impl worktree)Validated on this branch ( ScenarioLaunched this worktree's Electron app, imported SSH host Visible
BackingSSH PTY GapsRenderer Screenshots (uncropped, not committed): SSH Hosts settings: Local Grok identity: SSH workspace (pre-Grok): SSH Grok identity: |
There was a problem hiding this comment.
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
src/renderer/src/components/terminal-pane/pane-foreground-process-reader.ts (1)
48-48: 🎯 Functional Correctness | 🟠 Major | ⚡ Quick winReject evidence after the PTY binding changes.
expectedIncarnationIdis captured beforereader(...)resolves. The admission call on Line 48 does not compare it with the current binding. If the pane rebinds during the RPC, evidence for the retired incarnation still matches the captured PTY and incarnation and returnsremoteEvidenceAccepted: truefor the new binding. Re-read the current incarnation or use a binding-generation token after the await, then discard the result when it changed.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Team
Run ID: 65a08699-2cf8-4029-868e-3ed224aac2f6
📒 Files selected for processing (10)
src/main/daemon/terminal-host.tssrc/main/providers/agent-foreground-process-batch.tssrc/main/runtime/orca-runtime-restore-structured-agent-session-tabs-once.tssrc/relay/pty-handler.tssrc/renderer/src/components/terminal-pane/agent-completion-process-monitor.tssrc/renderer/src/components/terminal-pane/pane-foreground-process-reader.tssrc/shared/remote-foreground-evidence-admission.tssrc/shared/remote-foreground-evidence.test.tssrc/shared/retired-pty-incarnations.test.tssrc/shared/retired-pty-incarnations.ts
🚧 Files skipped from review as they are similar to previous changes (3)
- src/main/providers/agent-foreground-process-batch.ts
- src/relay/pty-handler.ts
- src/main/daemon/terminal-host.ts
Included review availability: Your plan provides up to 10 included reviews per hour; 5 remain after this review.
Real-host SSH validationHead validated: Environment: Docker Desktop server 29.6.1; disposable Ubuntu 24.04 ARM64 container V1 — PASSReal Codex ran in a real SSH-backed pane. Host-stamped evidence received by the client: {
"foregroundProcess":"codex",
"hasChildProcesses":true,
"foregroundProcessEvidence":{
"authorityGeneration":"1a4dbd0f-6b74-411a-a5d1-e25565f3228c",
"observationEpoch":17,
"capturedAgeMs":1,
"ptyId":"pty2:1a4dbd0f-6b74-411a-a5d1-e25565f3228c:1",
"ptyIncarnationId":"9f3ea6de-425c-4048-9036-df386c326b20",
"verdict":"live",
"processName":"codex",
"fence":{"platform":"posix","shellPid":8034,"shellStartTime":"65652","tty":"pts/0","foregroundPgid":8268,"process":{"pid":8268,"startTime":"77973"}}
}
}V2 — PASSWhile Codex was running, the pane title was changed to V3 — PASSWith Codex live, the remote host emitted marker-shaped bytes directly to the PTY: Before and after evidence remained Codex live with the same fenced identity ( V4 — PASSTwo real-host unverifiable fences were captured: {"verdict":"unverifiable","reason":"multiplexer_boundary","ptyIncarnationId":"9f3ea6de-425c-4048-9036-df386c326b20"}( {"verdict":"unverifiable","reason":"incarnation_mismatch","ptyIncarnationId":"9f3ea6de-425c-4048-9036-df386c326b20"}( V5 — PARTIAL (renderer transport limitation)Natural remote process exit was proven directly against the running relay socket (bypassing the renderer's preflight {"exit":{"id":"pty2:1a4dbd0f-6b74-411a-a5d1-e25565f3228c:8","code":7,"incarnationId":"9d1c9c72-9a0d-4d72-a04e-5971979dc69e"}}
{"inspect":{"authorityGeneration":"1a4dbd0f-6b74-411a-a5d1-e25565f3228c","observationEpoch":335,"capturedAgeMs":0,"ptyId":"pty2:1a4dbd0f-6b74-411a-a5d1-e25565f3228c:8","ptyIncarnationId":"9d1c9c72-9a0d-4d72-a04e-5971979dc69e","verdict":"exited","reason":"pty_exit_7"}}For lost contact, Docker V6 — PASSInstrumented the remote V7 — PASSAfter disconnect/reconnect, the old retired PTY was not reused: {"oldPty":"ssh:ssh-1788379246285-td6ore@@pty2:1a4dbd0f-6b74-411a-a5d1-e25565f3228c:1","inspect":{"foregroundProcess":null,"hasChildProcesses":false,"unavailable":true}}The reattached pane established fresh evidence on the same live incarnation: {"ptyId":"pty2:1a4dbd0f-6b74-411a-a5d1-e25565f3228c:3","ptyIncarnationId":"11bd25e8-0c96-4e83-8b07-302e97b68175","verdict":"live","processName":null,"fence":{"platform":"posix","shellPid":9201,"shellStartTime":"102262","tty":"pts/0","foregroundPgid":9201}}The provider epoch advanced from Disposition
|
|
V5 blocker closed in commit 487d994ceb6296e44a707b175d3ddd638a852d9e (starting HEAD was 9832c18). Refactor:
Audited call sites:
Client-only unverifiable now retains a known agent identity, never confirms shell/exit, never enters process-exit completion, and never counts as a busy process. Host exited remains accepted only from a fenced, admitted host evidence tombstone; terminal_gone/socket loss alone maps to unverifiable. RED proof (baseline 9832c18, blocker reproducer): GREEN proof (487d994ceb, after): |
There was a problem hiding this comment.
Reviewed changes — a single commit landed since the last review pass: fix(ssh): make remote process inspection total.
- Introduced
src/shared/terminal-process-inspection.tsdefiningTerminalProcessInspection = HostProcessInspection | ClientOnlyUnverifiableInspection, plusclientOnlyUnverifiableInspection()(a constructor whose type forbids host-identity fields),isClientOnlyUnverifiableInspection(), andclassifyTerminalProcessInspectionFailure()mappingterminal_gone/timeout/old_host/transport_lossfrom error codes and messages. - Threaded
expectedIncarnationIdthrough the paired-runtimeterminal.inspectProcessRPC (additive optionalTerminalHandlefield) and the preloadinspectProcessbridge. - Added
normalizeInspectionResultat the renderer boundary, collapsing old hosts (missingforegroundProcessEvidence) toold_host, legacyunavailable: truetoterminal_gone, and classified transport/timeout failures to client-only unverifiable results instead of throwing. - Swapped every
unavailable === trueconsumer (close guard, completion monitor, pane tracker, codex restart-eligibility) ontoisClientOnlyUnverifiableInspection.
No new issues found in this delta: the discriminated union is sound, the failure classifier stays conservative (unclassified programming errors still throw, covered by the still throws an unclassified programming error test), and the type-proof test asserts client-only results carry no host metadata.
Approval is held only because the one open review thread — the daemon path returning foregroundProcess: null for a live idle-shell verdict where the relay preserves the shell name via evidence.processName ?? managed.pty.process — is untouched by this commit. It is pre-existing and I am not re-raising it as a new finding.
DeepSeek Pro (free via Pullfrog for OSS) | 𝕏
Real-host SSH validation V5 re-run at
|
487d994 to
1b0a310
Compare
|
Note GitHub couldn't provide a complete incremental comparison for this pull request, so CodeRabbit is performing a full review instead. This review may take a little longer. |
There was a problem hiding this comment.
ℹ️ No new issues in this delta — the measured-age change is sound and the buffer-ceiling spread is mechanical.
Reviewed changes — this run re-reviewed the net delta since the prior Pullfrog review (the branch was rebased, so the seven commit SHAs were rewritten with unchanged subjects).
- Measured capture age —
capturedAgeMsnow carries the real age from a newgetSnapshotWithAgereader method, replacing the hardcoded worst-casePROCESS_TABLE_SNAPSHOT_MAX_STALENESS_MSstamp in both the relay (pty-handler.ts) and the daemon (terminal-host-process-inspection.ts). - Buffer-ceiling spread —
PS_MAX_BUFFER_BYTES(32MB) applied to the two remainingpsinvocations inpty-shell-utils.tsandshell-process-readiness.ts. - Reader extraction — the memoized process-table reader moved into
process-table-snapshot-reader.ts, withprocess-table-index.tsholding the correlation index; ~24 call sites updated via mechanical import changes.
Approval remains held solely on the one pre-existing open thread (the daemon returning foregroundProcess: null for a live idle-shell verdict — terminal-host-process-inspection.ts:72). It is untouched by this delta, so I am not re-raising it here.
ℹ️ Nitpicks
- The
capturedAgeMscontract insrc/shared/foreground-process-evidence.tsstill documents the field asIt is an upper bound, not an estimateand that the producerstamps for that worst case(PROCESS_TABLE_SNAPSHOT_MAX_STALENESS_MS). This delta switched the producer to the measured age, so the docstring is now stale — worth updating so a future reader doesn't assume the field over-approximates when a slowpsscan's rows can be older than the stamp implies.
DeepSeek Pro (free via Pullfrog for OSS) | 𝕏
The design doc does not belong in the product repo; it stays out of the shipped tree while the implementation carries its own comments.
…24413) Paired clients read RuntimeMobileSessionTab.incarnationId to fence remote identity observations (#18078), but projectRuntimeMobileSessionTabs never set it, so remote-runtime-pty-transport always saw null and the fence never engaged. The projection now publishes the incarnation of the PTY record that owns the issued handle, never a stale incarnation persisted on the tab. Ported from #16741 (a68b6f3). Co-authored-by: m4air <[email protected]>
* docs: add SSH agent identity implementation plan * feat(ssh): host-stamped remote foreground identity * fix(runtime): preserve unfenced inspect call shape * perf(ssh): traverse foreground descendants linearly * fix(ssh): bound retired PTY evidence records * test(ssh): cover retired incarnation retention * fix(ssh): make remote process inspection total * Split SSH identity build hot spots * Fix process table snapshot module split * test(ssh): update process inspection expectations * docs: drop the SSH identity plan from the PR The design doc does not belong in the product repo; it stays out of the shipped tree while the implementation carries its own comments. --------- Co-authored-by: Merge Sim <sim@local>





ELI5
An SSH pane used to work out which agent was running in it by reading the tab title — the field you type
task notes into. This makes the remote machine answer instead: it reports what is actually running, stamped
with proof that the answer belongs to this pane.
Before / after
Known limit: SSH to a Windows host still reports unverified. Windows has no foreground-process-group
primitive and the relay has no console/job association, so naming a process there would be a guess. Documented
at the return site and on the type.
Manual testing
Run against a real throwaway Ubuntu 24.04 SSH container (not
ssh localhost), driving the app over CDP with anisolated profile, at this exact head. A real Codex CLI was installed inside the container and run in a real
SSH-backed pane.
verdict:"live",processName:"codex"with a populated fence(
shellPid 8034,tty /dev/pts/0,foregroundPgid 8268, process start times).Claude Codewhile Codex ran; identity stayedcodex.After Ctrl-C with the same misleading title, the pane reported no agent rather than "Claude".
printf '\033]133;A\007forged\033]777;agent=claude\007' > /dev/pts/0on the remotehost with Codex live. Identity unchanged, same incarnation, same fence.
multiplexer_boundaryunder tmux;incarnation_mismatchon a stale incarnation.known agent survived, and identity re-established on reconnect. A genuine remote process exit reported
exitedwith host evidence; a socket close alone could not forgeexited.pswith a counter. Three idle remote panes for over 60 s produced0 inspect calls and 0 remote
psspawns. Five concurrent inspections produced five results fromone host capture.
evidence on a new incarnation.
Summary
Adds optional host-stamped, fenced foreground-process evidence to direct SSH and paired-runtime inspect-process RPCs, with renderer admission and remote completion tracking.
What this changes for users
Until now, an SSH or remote pane worked out which agent was running by reading the tab title — a
decoration field people type task text into. Local macOS and Linux panes already read the real foreground
process; remote panes were the only ones still guessing. Four things change:
Renaming a tab can no longer change which agent Orca thinks is running. Today, titling a tab
"fix the claude bug" while Codex is running can make the pane report Claude, which changes the icon, the
agent-status row, and anything keyed off pane identity. Verified on a real host: with Codex live, the title was
changed to
Claude Codeand the identity stayedcodex.A dropped connection no longer looks like a finished agent. Losing contact with a remote host and a remote
process actually exiting are now different answers (
unverifiablevsexited) rather than the same silence.If your VPN drops or wifi blips, the pane says it cannot verify — it does not report your agent as gone, and it
does not clear the agent you already had. Verified by disconnecting the container's network mid-session and
reconnecting.
Remote output can no longer impersonate an agent. Any command on the remote host can print bytes into your
terminal, including bytes shaped like shell-integration markers. Identity now comes from the host's own process
table, not from the byte stream, so a remote
printfcannot claim to be an agent. Verified by emittingmarker-shaped
OSC 133/OSC 777bytes at a live pane: identity did not move.Honest unknowns instead of confident wrong answers. When the host cannot prove what is running — the agent
is inside
tmux, the process group is ambiguous, the PID was reused, or the pane was reattached to a differentprocess — the pane reports that it cannot verify rather than naming a plausible-looking agent. A wrong agent
name is worse than no name, because you cannot tell which panes to trust.
No new background work. Remote hosts are inspected on real events (spawn, attach, reconnect, command
boundary, focus), never on a timer. An idle host with several remote panes performs zero inspections and zero
remote process-table reads; a burst of events shares a single host capture. Measured on a real host over 60
seconds: 0 inspect calls, 0 remote
psspawns.Known limitation: SSH to a Windows host still reports
unverifiable. Windows has no foregroundprocess-group primitive, and the relay has neither the Windows process table nor a console/job association, so
naming a process there would be a guess. It degrades honestly instead. Lifting this needs a separate,
measured change.
Cost invariant
Remote identity is event-triggered only: no periodic remote identity poll, no remote active-agent cadence, and no hot-window rearm. Idle hosts with many remote panes and no qualifying events perform exactly zero identity RPCs and zero process-table spawns; qualifying bursts coalesce to one shared host capture.
Fences
A live verdict requires authority generation and monotonic observation epoch, PTY id and incarnation, conservative capture age, anchor PID start time, controlling tty, foreground process group, candidate PID start time, multiplexer boundary, ambiguity checks, and complete process-table capture. Missing or failed fences produce unverifiable; exited is emitted only from a matching host tombstone.
Mixed versions
Old client plus new host remains compatible through the additive optional field and legacy fields/list-row schema. New client plus old host treats absent evidence or transport failure as client-side unverifiable with no host metadata, never as a name or exit; automatic legacy inventory polling is suppressed when the capability is absent.
SSH to Windows
SSH-to-Windows remains unverifiable because the relay has no measured ConPTY/job foreground association or creation-time/session fence; returning a descendant name would be an unfenced guess. The code documents this limitation at both return sites and on WindowsFence.
Validation
Focused renderer/relay/daemon/provider suites: 219 tests passed. Typecheck and changed-code quality checks pass. Real-host Linux SSH container validation could not run because the Docker CLI is present but the Docker daemon is unavailable; ssh localhost was not used.