Repository navigation
Conversation
📝 WalkthroughWalkthroughThe change adds authority-aware caching for active-agent terminal bindings. Active-agent sends now detect stale terminal handles, clear the affected binding, resolve a replacement terminal, and retry once. Readiness and guarded send paths preserve stale-handle errors. Tests cover runtime replacement, stale-handle recovery, cache reset, and explicit-target binding reuse. 🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
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.
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/lib/active-agent-note-send.ts (1)
65-158: 🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick winAdd an idempotency/debounce guard around the pasted prompt.
sendNotesToActiveAgentSessionAttemptcatchesterminal_handle_staleand retries the entire attempt, re-resolving the terminal and re-enteringsendPromptWithGuardedPasteAndEnter. If the first paste RPC is accepted and a later RPC in the same attempt then fails with stale handle, the retry can run the same paste RPC again without a guard insendPromptWithGuardedPasteAndEnter. Add a write-level idempotency check or return the first accepted-paste result instead of restarting send on stale RPC in that path.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID: 58495a02-db23-4e33-80fe-9762f778991d
📥 Commits
Reviewing files that changed from the base of the PR and between 1a0a1ce and a74f7ccaa6200dfc0dd54cbe6906082d43c108f3.
📒 Files selected for processing (5)
src/main/runtime/orca-runtime.test.tssrc/renderer/src/lib/active-agent-note-send.test.tssrc/renderer/src/lib/active-agent-note-send.tssrc/renderer/src/lib/active-agent-note-terminal-binding.tssrc/renderer/src/lib/active-agent-terminal-send-readiness.ts
Greptile SummaryThis PR fixes stale terminal sends after a runtime host identity change by introducing a binding cache (
Confidence Score: 5/5Safe to merge — the change is narrowly scoped to rebinding terminal handles on host identity change and adds no new IPC or credential paths. The retry logic is bounded to one attempt, stale errors propagate cleanly through every helper, the authority-based cache invalidation correctly covers routed and environment targets, and the test suite exercises both the new stale-rebind path and the existing send flows including cache reuse. Files Needing Attention: No files require special attention.
|
| Filename | Overview |
|---|---|
| src/renderer/src/lib/active-agent-note-terminal-binding.ts | New module implementing a module-level binding cache keyed by (runtimeTarget, worktreeId, tabId, leafId); authority string encodes connection generation for invalidation on host identity change. |
| src/renderer/src/lib/active-agent-note-send.ts | Refactored to use resolveActiveAgentTerminal; stale errors are now propagated up through all helper send functions and handled with a single retry via sendNotesToActiveAgentSessionAttempt. |
| src/renderer/src/lib/active-agent-terminal-send-readiness.ts | Splits terminal_handle_stale out of isRuntimeTerminalUnavailable into its own isRuntimeTerminalStale predicate; re-throw guards added in getTerminalAgentSendReadiness and getLegacyTerminalAgentSendStatus. |
| src/renderer/src/lib/active-agent-note-send.test.ts | Adds test for stale-handle rebind path; updates an existing two-send test to reflect cache reuse on the second call (no redundant terminal.list). |
| src/main/runtime/orca-runtime.test.ts | New test verifies replacement runtime rejects old handle with terminal_handle_stale and accepts the reminted handle for the same pane. |
Sequence Diagram
sequenceDiagram
participant C as Caller
participant S as sendNotesToActiveAgentSessionAttempt
participant B as resolveActiveAgentTerminal (cache)
participant R as Runtime RPC
C->>S: sendNotesToActiveAgentSession(worktreeId, prompt, noteTarget)
S->>B: resolveActiveAgentTerminal(state, runtimeTarget, worktreeId, noteTarget)
alt Cache hit and authority matches
B-->>S: cached terminal handle
else Cache miss or authority changed
B->>R: terminal.list
R-->>B: terminals[]
B-->>S: fresh terminal handle (stored in cache)
end
S->>R: terminal.agentStatus / terminal.wait / terminal.send
alt terminal_handle_stale error
R-->>S: throws terminal_handle_stale
S->>B: clearActiveAgentTerminalBinding(...)
alt "staleRetryCount == 0"
S->>S: "recurse with staleRetryCount=1"
S->>B: resolveActiveAgentTerminal (cache miss)
B->>R: terminal.list
R-->>B: reminted handle
B-->>S: new terminal handle
S->>R: terminal.agentStatus / terminal.send
R-->>S: success
S-->>C: status sent
else "staleRetryCount > 0"
S-->>C: status no-active-terminal
end
else success
R-->>S: result
S-->>C: status sent
end
Reviews (2): Last reviewed commit: "docs(renderer): note why non-environment..." | Re-trigger Greptile
|
Reviewing now |
c9dca6a to
ec02973
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.
🧹 Nitpick comments (5)
src/renderer/src/lib/active-agent-note-terminal-binding.test.ts (1)
87-138: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winAdd a negative control so over-broad invalidation cannot pass.
Both invalidation tests bump one generation and require re-resolution. Neither test asserts that an unrelated generation leaves the binding cached. If
getRuntimeBindingAuthorityfolded every generation into one string for all targets, all three tests would still pass, while the gate claims invalidation of "only the affected folder or worktree pane binding".Add one case that bumps a generation unrelated to the resolved target and requires
findActiveRuntimeTerminalto stay at one call.🧪 Proposed additional test
+ it('keeps a local binding cached when an unrelated SSH authority reconnects', async () => { + const state = {} as Parameters<typeof resolveActiveAgentTerminal>[0] + const resolve = async (): Promise<void> => { + await resolveActiveAgentTerminal(state, { kind: 'local' }, 'worktree-local', { + tabId: 'tab-local', + leafId: 'leaf-local' + }) + } + + await resolve() + testState.nestedSshGeneration += 1 + testState.environmentSshGeneration += 1 + await resolve() + + expect(testState.findActiveRuntimeTerminal).toHaveBeenCalledTimes(1) + })config/reliability-gates.jsonc (2)
6595-6596: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winMark or remove the superseded command.
Line 6595 and line 6596 are identical except that 6595 adds
src/renderer/src/lib/active-agent-note-terminal-binding.test.ts. Both entries stay incommands, so a runner that executes every command runs the same ten files twice. Other gates in this file mark retained history explicitly, for example the comment at line 4663 that labels historical evidence commands.Remove line 6596, or add a comment that marks it as historical.
🧹 Proposed change
"commands": [ "pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/orca-runtime.test.ts src/main/runtime/rpc/terminal-send.test.ts src/main/ipc/pty.test.ts src/main/providers/agent-foreground-process.test.ts src/main/providers/local-pty-provider.test.ts src/main/providers/windows-conpty-process-membership.test.ts src/main/daemon/daemon-foreground-confirmation-protocol.test.ts src/main/daemon/pty-subprocess.test.ts src/renderer/src/lib/active-agent-note-send.test.ts src/renderer/src/lib/active-agent-note-terminal-binding.test.ts src/renderer/src/components/browser-pane/BrowserAnnotationSendMenuContent.test.tsx", - "pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/orca-runtime.test.ts src/main/runtime/rpc/terminal-send.test.ts src/main/ipc/pty.test.ts src/main/providers/agent-foreground-process.test.ts src/main/providers/local-pty-provider.test.ts src/main/providers/windows-conpty-process-membership.test.ts src/main/daemon/daemon-foreground-confirmation-protocol.test.ts src/main/daemon/pty-subprocess.test.ts src/renderer/src/lib/active-agent-note-send.test.ts src/renderer/src/components/browser-pane/BrowserAnnotationSendMenuContent.test.tsx" + // Historical evidence command; superseded by the entry above, which adds the terminal-binding test. + "pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/orca-runtime.test.ts src/main/runtime/rpc/terminal-send.test.ts src/main/ipc/pty.test.ts src/main/providers/agent-foreground-process.test.ts src/main/providers/local-pty-provider.test.ts src/main/providers/windows-conpty-process-membership.test.ts src/main/daemon/daemon-foreground-confirmation-protocol.test.ts src/main/daemon/pty-subprocess.test.ts src/renderer/src/lib/active-agent-note-send.test.ts src/renderer/src/components/browser-pane/BrowserAnnotationSendMenuContent.test.tsx" ],
6673-6679: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winRecord an evidence run for the new assertions.
This gate adds a test file and two assertions, but
evidenceRunsforterminal-input.guarded-agent-send-authorizationstill records only the 2026-07-11 run of the previous command. No recorded run coversactive-agent-note-terminal-binding.test.ts.Add an
evidenceRunsentry for the updated command so the gate's assertions and its recorded evidence stay aligned.Also note: the assertion text says these generations "invalidate only the affected folder or worktree pane binding". The current tests prove invalidation but not exclusivity. See the related comment on
src/renderer/src/lib/active-agent-note-terminal-binding.test.ts.src/renderer/src/lib/active-agent-note-send.test.ts (2)
415-424: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winMove the handle assertion out of the mock implementation.
expect(params.terminal).toBe('term-new-runtime')runs inside theterminal.sendbranch. If it fails, the thrown assertion becomes an RPC rejection, so the failure surfaces as an unexpected send result instead of a handle mismatch. The other tests in this block already use the collect-then-assert pattern, for examplepasteHandlesat line 521.Collect the send handles and assert them after the call.
🧪 Proposed change
let listCount = 0 const methods: string[] = [] + const sendHandles: string[] = [] @@ if (method === 'terminal.send') { - expect(params.terminal).toBe('term-new-runtime') + sendHandles.push(params.terminal) return { @@ expect(listCount).toBe(2) + expect(sendHandles).toEqual(['term-new-runtime', 'term-new-runtime']) expect(methods).toEqual([
558-561: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick winTighten the paste predicate so the no-replay oracle cannot pass on a submit frame.
pasteHandlesrecords anyterminal.sendwhoseparams.textis a string. The no-replay guarantee depends on that predicate separating the prompt paste from the submit frame. If a submit frame ever carries atextfield, this test records it as a paste and the assertion on line 582 still passes with the wrong shape.Match the prompt content instead of the field type.
🧪 Proposed change
if (method === 'terminal.send') { - if (typeof params.text === 'string') { + if (params.text === 'notes' || params.text === 'next notes') { pasteHandles.push(params.terminal) }Also applies to: 581-582
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID: bceac652-905a-4cbf-96b9-e9b495536c4f
📒 Files selected for processing (7)
config/reliability-gates.jsoncsrc/main/runtime/orca-runtime.test.tssrc/renderer/src/lib/active-agent-note-send.test.tssrc/renderer/src/lib/active-agent-note-send.tssrc/renderer/src/lib/active-agent-note-terminal-binding.test.tssrc/renderer/src/lib/active-agent-note-terminal-binding.tssrc/renderer/src/lib/active-agent-terminal-send-readiness.ts
🚧 Files skipped from review as they are similar to previous changes (4)
- src/main/runtime/orca-runtime.test.ts
- src/renderer/src/lib/active-agent-note-terminal-binding.ts
- src/renderer/src/lib/active-agent-note-send.ts
- src/renderer/src/lib/active-agent-terminal-send-readiness.ts
|
I ran an independent verification of this PR — reproduction-first, against both the PR base and the version the linked issue reports. Summary: the fix is real and I recommend merging it, but it does not fix what #11191 describes, so please don't let it close that issue. The literal issue sequence does not reproduce — even on the reported release. I built an oracle for the exact sequence in #11191 (host restart completes, then the user clicks Send) and ran it against three trees:
The reason is that What this PR genuinely does fix. There is a real TOCTOU window between that fresh Adversarial review of the fix — no blockers. One recursive retry only, so no loop; the binding is cleared before the second-stale return, so no permanent refusal; each attempt recomputes the target from owner state rather than inferring a host from handle text, so multiple reachable runtimes stay owner-selected; same-generation sends still reuse the cache; and after bracketed-paste bytes are accepted, staleness converts to a partial-submit failure without ever replaying prompt bytes. Two notes for the author:
Recommendation: merge on its own merits; keep #11191 open (or narrow it), and chase the reporter's actual symptom separately, because whatever they hit is still unexplained. |
Summary
terminal.list, re-resolve through the current runtime authority once, preserving same-generation sends and existing server reminting.Related to #11191.
Screenshots
No visual change
Testing
pnpm lintpnpm typecheckpnpm testpnpm buildFocused validation run in this session:
pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/lib/active-agent-note-send.test.ts, 35 tests passed.pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/orca-runtime.test.ts -t "stale terminal handles|remints a terminal handle", 2 tests passed.pnpm run typecheck:webpnpm run typecheck:nodepnpm exec oxlintandpnpm exec oxfmt --checkgit diff --checkThe complete renderer and runtime test-file run passed 1,000 tests; one existing runtime fixture failed on Windows because it creates a
/tmpdirectory. The focused tests for this change pass.AI Review Report
The renderer binding is keyed by the existing worktree route and connection-generation authority. A stale handle clears the pane-key binding and permits one remint lookup, then stops. Same-generation sends reuse the binding, local/SSH/paired routing remains owner-derived, and the existing legacy runtime fallback remains unchanged. The runtime test confirms that a replacement runtime rejects the old handle and accepts its reminted handle.
Security Audit
The change prevents sends to stale runtime identities. Re-resolution uses the existing owner route and terminal list, cannot infer a host from handle text, and adds no IPC or credential path.
Notes
Independent verification found that the completed-restart-then-send sequence described in #11191 already succeeds on the PR base and v1.4.159, so this PR does not close that issue. This change addresses the narrower race where the runtime is replaced after
terminal.listbut before the first terminal operation. #11191 remains open for the original report.PR #11742 covers server-side tmuxCompat reminting only. No visual change.