Skip to content

fix(runtime): rebind terminal sends after host identity changes (#11191) - #11854

Closed
rodboev wants to merge 4 commits into
stablyai:mainfrom
rodboev:pr/runtime-handle-rebind
Closed

rodboev wants to merge 4 commits into
stablyai:mainfrom
rodboev:pr/runtime-handle-rebind

Conversation

@rodboev

@rodboev rodboev commented Aug 1, 2026 •

Copy link
Copy Markdown
Contributor

Summary

  • Invalidate renderer terminal bindings when runtime connection identity changes.
  • When a runtime replacement races the first terminal operation after 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 lint
  • pnpm typecheck
  • pnpm test
  • pnpm build
  • Added or updated high-quality tests that would catch regressions, or explained why tests were not needed

Focused 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:web
  • pnpm run typecheck:node
  • Changed-file pnpm exec oxlint and pnpm exec oxfmt --check
  • git diff --check

The complete renderer and runtime test-file run passed 1,000 tests; one existing runtime fixture failed on Windows because it creates a /tmp directory. 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.list but before the first terminal operation. #11191 remains open for the original report.

PR #11742 covers server-side tmuxCompat reminting only. No visual change.

@coderabbitai

coderabbitai Bot commented Aug 1, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

The 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)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Linked Issues check ✅ Passed The changes invalidate stale bindings, retry resolution once, distinguish stale handles, and add regression tests for issue #11191.
Out of Scope Changes check ✅ Passed The implementation and tests remain focused on terminal binding invalidation and stale-handle recovery after runtime identity changes.
Description check ✅ Passed The description includes all required sections, summarizes the change, documents testing, and provides AI review, security, and platform notes.
Title check ✅ Passed The title clearly and concisely describes rebinding terminal sends after runtime host identity changes.

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.

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 win

Add an idempotency/debounce guard around the pasted prompt.

sendNotesToActiveAgentSessionAttempt catches terminal_handle_stale and retries the entire attempt, re-resolving the terminal and re-entering sendPromptWithGuardedPasteAndEnter. 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 in sendPromptWithGuardedPasteAndEnter. 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.ts
  • src/renderer/src/lib/active-agent-note-send.test.ts
  • src/renderer/src/lib/active-agent-note-send.ts
  • src/renderer/src/lib/active-agent-note-terminal-binding.ts
  • src/renderer/src/lib/active-agent-terminal-send-readiness.ts

@greptile-apps

greptile-apps Bot commented Aug 1, 2026 •

Copy link
Copy Markdown

Greptile Summary

This PR fixes stale terminal sends after a runtime host identity change by introducing a binding cache (active-agent-note-terminal-binding.ts) keyed on (runtimeTarget, worktreeId, tabId, leafId) with an authority string that encodes the connection generation, and a one-shot stale-error retry path in sendNotesToActiveAgentSessionAttempt.

  • New binding cache: resolveActiveAgentTerminal returns a cached terminal handle if the authority (connection generation snapshot) is unchanged; on authority mismatch the entry is evicted and re-fetched via terminal.list.
  • Stale retry loop: terminal_handle_stale is separated from isRuntimeTerminalUnavailable into its own predicate; every helper function now re-throws it so the outer catch in sendNotesToActiveAgentSessionAttempt can clear the binding and retry exactly once before returning no-active-terminal.
  • Tests: a new renderer test exercises the full stale-rebind flow (two terminal.list calls, correct handle swap, final sent); a new runtime test confirms a replacement runtime rejects the old handle and accepts its reminted counterpart.

Confidence Score: 5/5

Safe 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.

Important Files Changed

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
Loading

Reviews (2): Last reviewed commit: "docs(renderer): note why non-environment..." | Re-trigger Greptile

@AmethystLiang

Copy link
Copy Markdown
Contributor

Reviewing now

@Jinwoo-H
Jinwoo-H force-pushed the pr/runtime-handle-rebind branch from c9dca6a to ec02973 Compare August 5, 2026 05:32
@coderabbitai

coderabbitai Bot commented Aug 5, 2026

Copy link
Copy Markdown
Contributor

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.

@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.

🧹 Nitpick comments (5)
src/renderer/src/lib/active-agent-note-terminal-binding.test.ts (1)

87-138: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Add 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 getRuntimeBindingAuthority folded 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 findActiveRuntimeTerminal to 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 win

Mark 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 in commands, 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 win

Record an evidence run for the new assertions.

This gate adds a test file and two assertions, but evidenceRuns for terminal-input.guarded-agent-send-authorization still records only the 2026-07-11 run of the previous command. No recorded run covers active-agent-note-terminal-binding.test.ts.

Add an evidenceRuns entry 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 win

Move the handle assertion out of the mock implementation.

expect(params.terminal).toBe('term-new-runtime') runs inside the terminal.send branch. 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 example pasteHandles at 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 win

Tighten the paste predicate so the no-replay oracle cannot pass on a submit frame.

pasteHandles records any terminal.send whose params.text is a string. The no-replay guarantee depends on that predicate separating the prompt paste from the submit frame. If a submit frame ever carries a text field, 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

📥 Commits

Reviewing files that changed from the base of the PR and between eebaf47 and ec02973.

📒 Files selected for processing (7)
  • config/reliability-gates.jsonc
  • src/main/runtime/orca-runtime.test.ts
  • src/renderer/src/lib/active-agent-note-send.test.ts
  • src/renderer/src/lib/active-agent-note-send.ts
  • src/renderer/src/lib/active-agent-note-terminal-binding.test.ts
  • src/renderer/src/lib/active-agent-note-terminal-binding.ts
  • src/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

@Jinwoo-H

Jinwoo-H commented Aug 5, 2026

Copy link
Copy Markdown
Contributor

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:

Tree Result
PR base (eebaf47d) completed-restart send passes
Reported release v1.4.159 completed-restart send passes
PR head passes

The reason is that sendNotesToActiveAgentSession already calls a fresh terminal.list at the start of every user action, so there is no cross-send cached handle to go stale. A restart that finished before the click gets the replacement handle and succeeds. That was already true on the build the reporter was running, so "note-send keeps its previous handle until the tab is reopened" cannot be the mechanism.

What this PR genuinely does fix.

There is a real TOCTOU window between that fresh terminal.list and the first use of the handle (terminal.agentStatus / wait / send). A runtime replacement inside that window makes the just-listed handle stale, and the base folds terminal_handle_stale into no-active-terminal — so the send fails with no recovery. That case is red on both the base and v1.4.159, and green with this PR. The bounded single re-resolution is the right shape for it.

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:

  1. The "current host" unit test changes environmentId, but a real same-pair runtime restart keeps the environment ID stable and changes only the runtime-issued handle. My oracle used the stable-ID shape and still passed, so the fix is fine — but the test is exercising an easier case than the real one.
  2. Please soften the description's claim that the base cached handles across completed sends. It doesn't, and the record should say what was actually fixed.

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.

@rodboev

rodboev commented Aug 8, 2026

Copy link
Copy Markdown
Contributor Author

@Jinwoo-H I updated the description to remove Closes #11191 and document the narrower scope. It now describes the stale-handle race between terminal.list and the first terminal operation; #11191 remains open for the completed-restart sequence you tested.

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.

5 participants