Skip to content

Show Claude's AskUserQuestion card in desktop Chat when the agent runs on a paired headless server - #12223

Merged
nwparker merged 10 commits into
mainfrom
nwparker/bugbash-11761
Aug 4, 2026
Merged

nwparker merged 10 commits into
mainfrom
nwparker/bugbash-11761

Conversation

@nwparker

@nwparker nwparker commented Aug 3, 2026 •

Copy link
Copy Markdown
Contributor

Summary

When Claude ran on a paired headless host (orca serve, incl. over SSH), AskUserQuestion rendered in the desktop Chat UI as a plain collapsed tool call. No question card appeared, the composer stayed mounted over a pane whose TUI was parked on a selector, and the next typed message committed the highlighted option instead of being sent. Three independent defects had to line up for the card to appear, and all three were broken. A fourth — in the shared transcript parser the new fallback leans on — is fixed here too:

  1. The host projection threw the payload away. buildPtyMobileAgentStatus published a full status entry only for retained OSC-9999 rows; a pane whose status arrives over the HTTP agent-hook server fell through to an identity-only branch that hard-codes prompt: '' and derives state from the pane title alone (done unless pty.lastAgentStatus is working/permission), so agentType + providerSession were the only real information it shipped (src/main/runtime/orca-runtime.ts:29378). getHookAgentRowForPane (src/main/runtime/orca-runtime.ts:29538) reduced the row to identity fields, discarding state, toolName, toolInput, interactivePrompt and lastAssistantMessage.

    It now also returns live — the newest fresh row's status fields, narrowed by the new pickParsedAgentStatusPayload (src/shared/agent-status-types.ts:186) so hook transport identity (launchToken, connectionId, promptInteractionKey, providerSessionOnly, receivedAt) never reaches a client. Selection already bounds that row by AGENT_STATUS_STALE_AFTER_MS and never takes a providerSessionOnly resume row (not even Pi's); resolveHookLiveAgentRow (src/main/runtime/orca-runtime.ts:29504) then decides whether it may be published — never past the #1437 non-agent-title suppression unless a question is genuinely pending, and never over live title evidence that is newer than the hook row. Retained OSC rows keep precedence (#7970 unchanged), and the identity-only branch stays as the last resort — that is what retires the card when the agent exits.

  2. Nothing republished session.tabs on a hook status change, and notifyMobileSessionTabsChanged re-emits at an unchanged snapshotVersion, which clients drop on their monotonic gate (src/renderer/src/runtime/web-session-tabs-sync.ts:247). touchMobileSessionTabsForWorktree / touchMobileSessionTabsForPane (src/main/runtime/orca-runtime.ts:6447) bump the version and schedule a coalesced emit; createHookStatusSessionTabsInvalidator (src/main/agent-hooks/hook-status-session-tabs-invalidation.ts:9) keeps a repeated same-state ping free. Teardown is wired to the new additive subscribePaneStatusClear seam (src/main/agent-hooks/server.ts:654) rather than the window-owned single slot, so it also exists under headless serve and covers the SSH transient-disconnect batch. The provider-session push at src/main/index.ts:2107 gets the same version bump — it was silently dropped by the client gate for the same reason.

  3. The desktop card had no transcript fallback. NativeChatInteractiveCard resolved only from live status; mobile has always resolved askFromStatus ?? extractPendingAsk(messages). It now does the same (src/renderer/src/components/native-chat/NativeChatInteractiveCard.tsx:65), fed the command-boundary-trimmed messages so an ask abandoned via /clear stays gone (src/renderer/src/components/native-chat/NativeChatView.tsx:432).

  4. extractPendingAsk could report an ask as pending forever. It matches tool results to tool calls by a global FIFO (tool_use_id is dropped at decode time in src/main/native-chat/transcript-record-blocks.ts:84, so id pairing is impossible downstream), and a tool call that never gets a result shifts that FIFO for the rest of the transcript. Real transcripts contain such orphans: a tool the user ESC'd, and an AskUserQuestion the user escaped out of and typed past (measured: 3 of the 400 most recent local Claude transcripts, one of them an orphaned ask). On desktop the resulting card replaces the composer, so a stale ask was unsendable chat, not just a stray card. extractPendingAsk (src/shared/native-chat-ask.ts:97) now drops in-flight calls at a turn boundary — a user turn or the decoders' interrupt row (isInterruptedStatusMessage, src/shared/native-chat-types.ts:137) — because the turn that owned them is over and their results are never coming. Claude's tool-result turns decode as role tool, not user, so normal FIFO resolution is untouched. Mobile shares this parser and gets the same fix.

Closes #11761

ELI5

Claude sometimes stops and asks you to pick between a few options. Orca normally shows that as a little card with buttons. But when Claude was running on a remote machine you were connected to, the remote machine only told your laptop "an agent lives here" — it forgot to pass along the actual question. So your laptop showed a boring grey box, kept the normal message field open, and anything you typed got swallowed as an accidental answer to the question you never saw. This change makes the remote machine send the whole question, makes it tell your laptop promptly when something changed, and — as a backstop — lets your laptop dig the unanswered question out of the conversation it already downloaded. The card now shows up, and it goes away again when the agent stops or the connection drops.

Fix proof

Both repro tests before the fix:

 RUN  v4.1.5

 ❯ src/main/runtime/orca-runtime-ask-user-question-projection.bug-11761.test.ts (1 test | 1 failed) 10ms
     × carries the hook interactivePrompt and toolName to paired clients 9ms

⎯⎯⎯⎯⎯⎯⎯ Failed Tests 1 ⎯⎯⎯⎯⎯⎯⎯

 FAIL  ... > headless AskUserQuestion projection (#11761) > carries the hook interactivePrompt and toolName to paired clients
AssertionError: expected { type: 'terminal', …(11) } to deeply equal ObjectContaining{…}

- Expected
+ Received

- ObjectContaining {
-   "agentStatus": ObjectContaining {
+ {
+   "agentStatus": {
      "agentType": "claude",
-     "interactivePrompt": "{\"questions\":[{\"question\":\"Tabs or spaces?\",\"header\":\"Style\",\"multiSelect\":false,\"options\":[{\"label\":\"Tabs\"},{\"label\":\"Spaces\"}]}]}",
-     "state": "waiting",
-     "toolName": "AskUserQuestion",
+     "paneKey": "ask-tab:11111111-1111-4111-8111-111111111111",
+     "prompt": "",
+     "providerSession": {
+       "id": "ac1f6b90-2f77-4f0e-9c5e-1d2f6a4b8c31",
+       "key": "session_id",
+       "transcriptPath": "/transcripts/ac1f6b90.jsonl",
+     },
+     "state": "done",
+     "stateHistory": [],
...
 Test Files  1 failed (1)
      Tests  1 failed (1)
 RUN  v4.1.5

 ❯ src/renderer/src/components/native-chat/NativeChatInteractiveCard.bug-11761.test.tsx (1 test | 1 failed) 10ms
     × renders the question card from the transcript when live status is missing 9ms

⎯⎯⎯⎯⎯⎯⎯ Failed Tests 1 ⎯⎯⎯⎯⎯⎯⎯

 FAIL  ... > desktop chat transcript fallback for AskUserQuestion (#11761) > renders the question card from the transcript when live status is missing
Error: expect(received).toBeInTheDocument()

received value must be an HTMLElement or an SVGElement.
Received has type:  Null
Received has value: null
 ❯ src/renderer/src/components/native-chat/NativeChatInteractiveCard.bug-11761.test.tsx:75:51
     73|     )
     74|
     75|     expect(screen.queryByText('Tabs or spaces?')).toBeInTheDocument()
       |                                                   ^

 Test Files  1 failed (1)
      Tests  1 failed (1)

After the fix, promoted into permanent regression suites (orca-runtime-hook-agent-status-projection.test.ts, and folded into the existing NativeChatInteractiveCard.test.tsx):

 RUN  v4.1.5

 ✓ NativeChatInteractiveCard.test.tsx > NativeChatInteractiveCard answer lifecycle > keeps the card retryable when no PTY answer was sent 28ms
 ✓ NativeChatInteractiveCard.test.tsx > NativeChatInteractiveCard answer lifecycle > cancels delayed PTY writes when the owning card unmounts 11ms
 ✓ NativeChatInteractiveCard.test.tsx > NativeChatInteractiveCard answer lifecycle > cancels delayed PTY writes when desktop send authority is lost 9ms
 ✓ NativeChatInteractiveCard.test.tsx > NativeChatInteractiveCard answer lifecycle > shows the paced send as busy and freezes the snapshotted answer 9ms
 ✓ NativeChatInteractiveCard.test.tsx > NativeChatInteractiveCard answer lifecycle > cancels the old answer sequence when a replacement prompt arrives 12ms
 ✓ NativeChatInteractiveCard.test.tsx > NativeChatInteractiveCard answer lifecycle > keeps a verified send visible until delivery succeeds 24ms
 ✓ NativeChatInteractiveCard.test.tsx > NativeChatInteractiveCard answer lifecycle > restores a verified send for retry when delivery is rejected 18ms
 ✓ NativeChatInteractiveCard.test.tsx > NativeChatInteractiveCard transcript fallback > renders a pending transcript ask and reports the composer replacement 2ms
 ✓ NativeChatInteractiveCard.test.tsx > NativeChatInteractiveCard transcript fallback > prefers live status over the transcript when both carry a prompt 4ms
 ✓ NativeChatInteractiveCard.test.tsx > NativeChatInteractiveCard transcript fallback > still renders while the mirrored status says the agent is working 2ms
 ✓ NativeChatInteractiveCard.test.tsx > NativeChatInteractiveCard transcript fallback > stays dismissed after answering while the transcript call is still pending 7ms
 ✓ NativeChatInteractiveCard.test.tsx > NativeChatInteractiveCard transcript fallback > clears once the FIFO tool result lands 2ms
 ✓ NativeChatInteractiveCard.test.tsx > NativeChatInteractiveCard transcript fallback > drops an ask abandoned by /clear 0ms
 ✓ orca-runtime-hook-agent-status-projection.test.ts > headless hook agent-status projection (#11761) > carries the hook state, tool and interactivePrompt to paired clients 5ms
 ✓ orca-runtime-hook-agent-status-projection.test.ts > headless hook agent-status projection (#11761) > publishes no hook transport identity to clients 1ms
 ✓ orca-runtime-hook-agent-status-projection.test.ts > headless hook agent-status projection (#11761) > falls back to identity-only done once the hook row goes stale 1ms
 ✓ orca-runtime-hook-agent-status-projection.test.ts > headless hook agent-status projection (#11761) > never fabricates live state from a resume-identity row 0ms
 ✓ orca-runtime-hook-agent-status-projection.test.ts > headless hook agent-status projection (#11761) > never fabricates live state from a pi resume-identity row 0ms
 ✓ orca-runtime-hook-agent-status-projection.test.ts > headless hook agent-status projection (#11761) > prefers a retained OSC 9999 row over the hook row 5ms
 ✓ orca-runtime-hook-agent-status-projection.test.ts > headless hook agent-status projection (#11761) > keeps a shell-reclaimed pane identity-only when the hook row has just a toolName 2ms
 ✓ orca-runtime-hook-agent-status-projection.test.ts > headless hook agent-status projection (#11761) > keeps a pending question visible even under a non-agent title 1ms
 ✓ orca-runtime-hook-agent-status-projection.test.ts > headless hook agent-status projection (#11761) > keeps the title-derived working state when the hook row predates the title 2ms
 ✓ orca-runtime-hook-agent-status-projection.test.ts > headless hook agent-status projection (#11761) > publishes a hook row received after the latest title observation 1ms
 ✓ orca-runtime-hook-agent-status-projection.test.ts > hook-driven session tabs republish (#11761) > bumps the snapshot version and emits through the coalescer 51ms
 ✓ orca-runtime-hook-agent-status-projection.test.ts > hook-driven session tabs republish (#11761) > ignores a pane with no resolvable workspace 51ms
 ✓ orca-runtime-hook-agent-status-projection.test.ts > hook-driven session tabs republish (#11761) > retires the question card after the pane status is cleared 52ms

 Test Files  2 passed (2)
      Tests  28 passed (28)

No regressions

src/main/runtime/orca-runtime.test.ts + all of src/main/agent-hooks/ + all of src/renderer/src/components/native-chat/:

 RUN  v4.1.5

 Test Files  96 passed (96)
      Tests  2178 passed | 4 skipped (2182)
   Duration  15.97s

Client-mirror and shared-parser suites (src/renderer/src/runtime/ incl. web-session-tabs-sync.test.ts and sync-runtime-graph-agent-status-projection.test.ts, plus src/shared/agent-status-types.test.ts, native-chat-ask.test.ts, agent-hook-listener.test.ts):

 RUN  v4.1.5

 Test Files  59 passed (59)
      Tests  731 passed (731)
   Duration  3.08s

SSH relay hook integration (src/main/ssh/ssh-relay-session-agent-hooks.integration.test.ts):

 Test Files  1 passed (1)
      Tests  8 passed (8)

Session-tabs neighbours (mobile-session-tabs-notify-coalescer.test.ts, rpc/methods/session-tabs{,-schemas,-move-validation}.test.ts, remote-runtime-session-tabs-inflight.test.ts, web-session-tabs-sync.test.ts, hook-status-session-tabs-invalidation.test.ts):

 Test Files  7 passed (7)
      Tests  130 passed (130)

node config/scripts/check-max-lines-ratchet.mjs → max-lines ratchet OK — 352 grandfathered suppression(s), no new bypasses.

Trade-offs

  • On a headless host a hook-derived question card disappears after AGENT_STATUS_STALE_AFTER_MS (30 min) of hook silence, because the row's receivedAt freezes while the agent blocks. This is deliberate — it is what stops a zombie card after the agent exits — and the transcript fallback keeps the card up past it.
  • The transcript fallback is intentionally not gated on state === 'working', because that mirrored channel is exactly what fails in the reported topology. The cost: a transcript that leaves a question tool unresolved can show a card where the composer would otherwise be. /clear boundaries are honoured, the card clears when the ask's tool result lands or when the turn ends (a new user turn or an interrupt row — see summary item 4; an earlier version of this description claimed the FIFO alone was enough to clear it, which was false while one orphaned tool call could desync the FIFO permanently), and Cancel restores the composer in one click (writing ESC to the pane, same as today's live-card cancel). What remains: a genuinely unresolved ask at the end of a transcript still shows a card, which is the intended behaviour. A phantom card is recoverable; a missing card re-opens the fabricated-consent hole.
  • Provider-session identity pushes were previously dropped by the client's version gate and are now delivered. Strictly better, but it is a visible timing change — transcript identity will start arriving promptly instead of incidentally.
  • NativeChatView.tsx sat exactly on its 400-line budget, so launchPromptVisible was inlined into the one memo that used it. Behaviour is unchanged; this avoids a max-lines disable.
  • Mobile's own vitest project could not be exercised in this worktree (its node_modules is not installed here). No files under mobile/ were touched, and mobile/src/session/mobile-native-chat-ask.ts is a bare export * of the shared parser, so mobile picks up item 4 verbatim.
  • Verification scope: automated suites on macOS only. The reported topology — Windows desktop client paired to a headless Linux orca serve host — was not exercised end to end; the Linux/Windows and SSH-relay arguments below are code-path reasoning plus the SSH relay integration suite, not a manual repro on that hardware.

Screenshots

Captured end-to-end in the real Electron app on macOS via a new Playwright spec (tests/e2e/native-chat-ask-user-question-card.spec.ts, committed to this branch — Playwright discovers it under the electron-headless project via testMatch: '**/*.spec.ts', verified with --list, so it runs rather than being silently skipped). The spec reproduces the reported topology from the client's side: live status arrives carrying agent identity and state: 'working' but no interactivePrompt/toolName — exactly what the host projection dropped — while the pending AskUserQuestion exists only in the transcript. Identical spec, identical payload, run against origin/main and against this branch.

Before — origin/main (e8d4818). The ask is present but inert: a collapsed 1× AskUserQuestion {"questions":["[…]"]} tool call in the stream, and the ordinary Send a message… composer mounted underneath. This is the reported bug — the session reads as working while the agent is blocked on you. The spec fails here, timing out waiting for the question text:

Error: expect(locator).toBeVisible() failed
Expected: visible
  - Expect "toBeVisible" with timeout 10000ms
> 147 |       await expect(orcaPage.getByText(QUESTION)).toBeVisible({ timeout: 10_000 })

01-before-plain-tool-call-and-composer.png

After — this branch (df5d588). Same transcript, same status. The card renders from the transcript fallback and replaces the composer; the collapsed tool call is still visible above it, so the two shots differ only in what this PR adds.

02-after-question-card.png

Answerable, not just visible. Selecting Spaces checks the option and flips the button from Skip to Send answer:

03-after-option-selected.png

Sending it dismisses the card and restores the composer — the visible signal that the answer was accepted:

04-after-answered-composer-restored.png

✓ 1 [electron-headless] › native-chat-ask-user-question-card.spec.ts › Desktop chat AskUserQuestion card (#11761)
  › renders the answerable question card from the transcript when live status carries no ask (7.2s)
  1 passed (12.1s)

Scope of this capture, stated plainly. This exercises the desktop half — summary items 3 and 4, the transcript fallback and the parser — end-to-end in the real app. It does not exercise the host projection (items 1 and 2) over a real paired headless orca serve; that rig was not available, so those remain covered by the unit suites above. The capture deliberately simulates their failure (status arriving without the ask payload) rather than reproducing their cause.

Cross-platform

No platform-conditional code, no keyboard accelerators, no filesystem paths, no path.join sites, and no Git invocation — so the Git 2.25 baseline and GitCapabilityCache rules do not apply.

  • macOS / Linux / Windows: the host-side projection and republish run wherever the main process runs, including orca serve and WSL; the renderer change is pure React. The reported topology (Windows desktop client paired to a Linux host) is symmetric with the reverse. paneKey comparisons stay exact-string via makePaneKey/parsePaneKey, so no case-folding assumption is introduced.
  • SSH-remote: hook rows ingested over the relay land in the same lastStatusByPaneKey cache and get the same projection, enriched-status emit and republish. connectionId is deliberately dropped by pickParsedAgentStatusPayload, so per-host transport identity is not leaked into client-visible status, and the invalidator's forgetConnection makes the SSH transient-disconnect batch republish every pane on that host instead of stranding a waiting dot and a live card.
  • Folder workspaces (non-git): the projection is keyed by worktreeId/paneKey only. getTerminalWorktreeIdForPaneKey resolves leaf then PTY records identically for folder workspaces, and mobileSessionTabsByWorktree keys are the same opaque workspace ids. No git-worktree assumption is added.
  • Provider-agnostic: nothing GitHub- or GitLab-specific is touched. The projection applies to every HTTP-hook agent (Claude, OpenCode, Cursor, Copilot, Pi, …), not only Claude.

Performance

  • Projection: one extra bounded field in a scan that already existed, plus one fixed ~10-field object literal per terminal tab per session.tabs build. interactivePrompt is copied by string reference, not deep-cloned.
  • Republish: extra session.tabs emissions on material hook transitions only. Double-bounded by the change detector (same field set the retained-OSC path uses, so a repeated same-state ping costs zero emissions) and by the existing mobileSessionTabsNotifyCoalescer, so cadence stays at or below what the OSC/title path already produces.
  • Renderer: extractPendingAsk walks the transcript blocks. It is memoized on sessionAfterCommandBoundaries.messages identity and skipped entirely whenever a status-derived card exists. That input changes only when the transcript file changes — streaming text lives in sessionWithPending, which is deliberately not passed — so it stays off the hot render path. Mobile already runs this same scan on lower-powered devices.

Security

No new IPC channels, no command execution, no path handling, no auth surface change. The change is net reducing exposure: the projection previously could not leak hook transport fields because it published nothing, and pickParsedAgentStatusPayload is what keeps that true now that it publishes status — launchToken (the hook-authority secret), connectionId, promptInteractionKey and providerSessionOnly are explicitly excluded, and a regression test asserts the exact published key set. providerSessionOnly resume rows are never projected as live state.

AI Review Report

Reviewed by independent subagents in a loop until clean, across two hostile lenses — correctness/regressions and cross-platform + remote + performance.

  • Review loop count: 3 round(s)
  • Final verdict: CLEAN — no outstanding findings.

Finding raised and resolved during the loop (1) — no longer outstanding:

  • major extractPendingAsk could report a permanently-pending ask, and the desktop card that consumes it replaces the composer ({questionActive ? null : <NativeChatComposer/>}, NativeChatView.tsx:440), so the pane became unsendable. Confirmed real, and confirmed against real data: scanning the 400 most recent local Claude transcripts found 3 with a non-trailing orphan tool_use, one of which is an orphaned AskUserQuestion at record 229 of 11 030 — every render of that conversation after the fallback landed would have pinned a dead question card over the composer for the remaining 10 800 records.
    • Fixed by the turn-boundary reset in src/shared/native-chat-ask.ts (summary item 4). The reviewer's proposed alternative — restoring tool_use_id pairing end-to-end — was not taken: it fixes the orphan-desync half but not the orphaned-ask half (the ask that never gets a result at all, which is the case actually observed in real transcripts), at a much larger blast radius across the block types and every decoder.
    • Regression coverage that fails without the fix: 4 cases in src/shared/native-chat-ask.test.ts (orphan behind an interrupt row, orphan behind a plain-text interrupt turn, ask abandoned by an interrupt, ask the user typed past). The parser owns this behaviour, so the coverage lives in the parser's own suite rather than being duplicated at the card level. Both Claude interrupt flavours are covered: the interruptedMessageId record (decodes to a system status row) and the bare [Request interrupted by user] record (decodes to a user turn).

Verification of the remediation (src/shared/native-chat-ask.test.ts + NativeChatInteractiveCard.test.tsx; reverting the turn-boundary reset fails exactly the 4 parser cases listed above and leaves NativeChatInteractiveCard.test.tsx fully green — measured, not assumed)

 RUN  v4.1.5

 Test Files  2 passed (2)
      Tests  27 passed (27)

Neighbouring suites — all of src/shared, src/renderer/src/components/native-chat, src/main/native-chat:

 Test Files  467 passed | 3 skipped (470)
      Tests  4432 passed | 15 skipped (4447)

This PR's other suites — src/main/agent-hooks, orca-runtime-hook-agent-status-projection.test.ts, src/renderer/src/runtime:

 Test Files  90 passed (90)
      Tests  1119 passed | 3 skipped (1122)

oxlint (default, native-plugins, type-aware --deny-warnings), typecheck:node, typecheck:web, typecheck:cli and check-max-lines-ratchet.mjs are all clean.

Remediation applied between rounds: 2 pass(es). Findings judged false-positive were rejected with evidence rather than coded around.

Made with Orca 🐋

…uns on a paired headless host

Three gaps kept the question card off the desktop when the agent ran on a
remote `orca serve` host:

- The `session.tabs` projection reduced HTTP agent-hook rows to identity only,
  hard-coding `state: 'done'` and an empty prompt, so `toolName` and the full
  `interactivePrompt` never left the host. It now publishes the newest fresh
  hook row's status fields, bounded by the same staleness window `agentType`
  uses, excluding `providerSessionOnly` resume rows, and yielding to live
  title evidence unless a question is actually pending.
- Nothing republished `session.tabs` when only a hook row changed, and the
  re-emit carried an unchanged `snapshotVersion` that clients drop on their
  monotonic gate. Material hook transitions and pane/SSH status clears now
  bump the version and schedule a coalesced emit.
- The desktop card resolved only from live status. It now falls back to the
  pending ask in the transcript, matching mobile, so a relay gap can no longer
  leave the composer mounted over a pane parked on a selector.

Closes #11761

Co-authored-by: Orca <[email protected]>
@coderabbitai

coderabbitai Bot commented Aug 3, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Note

Reviews paused

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

Use the following commands to manage reviews:

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

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

The change adds normalized hook-status projection and live agent-status resolution. It updates mobile session tabs when meaningful pane or provider-session state changes occur and clears tracking during pane or connection cleanup. It adds multi-subscriber pane-clear notifications. Native chat cards can recover unresolved questions from command-boundary-trimmed transcripts while live prompts remain authoritative. Tests cover runtime projection, invalidation, cleanup, precedence, and prompt lifecycle behavior.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 23.53% 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
Title check ✅ Passed The title clearly states the primary user-visible change: showing Claude’s AskUserQuestion card in desktop Chat for paired headless hosts.
Description check ✅ Passed The description covers the user-visible change, screenshots, extensive testing, AI review, security, and platform-specific notes.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • Create stacked PR
  • Commit on current branch

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

❤️ Share

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

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 3


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: e489e07a-00b3-4b91-b81b-22c25a7d1e5f

📥 Commits

Reviewing files that changed from the base of the PR and between 8b311ae and 83f66c5.

📒 Files selected for processing (10)
  • src/main/agent-hooks/hook-status-session-tabs-invalidation.test.ts
  • src/main/agent-hooks/hook-status-session-tabs-invalidation.ts
  • src/main/agent-hooks/server.ts
  • src/main/index.ts
  • src/main/runtime/orca-runtime-hook-agent-status-projection.test.ts
  • src/main/runtime/orca-runtime.ts
  • src/renderer/src/components/native-chat/NativeChatInteractiveCard.test.tsx
  • src/renderer/src/components/native-chat/NativeChatInteractiveCard.tsx
  • src/renderer/src/components/native-chat/NativeChatView.tsx
  • src/shared/agent-status-types.ts

Comment thread src/main/agent-hooks/server.ts Resolved
Comment thread src/main/runtime/orca-runtime.ts Resolved
nwparker and others added 2 commits August 3, 2026 00:08
`resolveHookLiveAgentRow` compared a hook `receivedAt` (epoch ms) against
title stamps that are title-observation sequence numbers, so the guard could
never fire — any fresh hook row overrode live title-derived state, and a manual
rename (the one epoch writer) inverted it. Stamp the live OSC title path with
wall-clock ms and compare against that alone.

The regression test fabricated epoch-valued title stamps production never
writes; it now drives the title through `onPtyData`, and a new case pins the
opposite direction (hook row newer than the title wins).

Co-authored-by: Orca <[email protected]>
…tion card

extractPendingAsk pairs tool results to calls by a global FIFO (tool_use_id
is dropped at decode time), so one call that never gets a result desyncs the
queue for the rest of the transcript and strands an answered ask as pending.
Real transcripts also hold asks the user escaped and typed past. On desktop
that card replaces the composer, so the pane became unsendable.

Drop in-flight calls at a turn boundary — a user turn or the decoders'
interrupt row — since the turn that owned them is over. Claude's tool-result
turns decode as role 'tool', so normal FIFO resolution is untouched.

Co-authored-by: Orca <[email protected]>

@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/main/runtime/orca-runtime.ts (1)

29497-29541: 🗄️ Data Integrity & Integration | 🟡 Minor | ⚡ Quick win

Hook-derived agent status still drops worktreeId for panes with no local PTY.

resolveHookLiveAgentRow declares an optional worktreeId field in its return type, but the returned object at Line 29535-29539 never sets it. getHookAgentRowForPane is the only source of hookRow.live, and it never extracts worktreeId from the winning entry — it returns only providerSession, agentType, live, and timestamps.

The caller in buildPtyMobileAgentStatus resolves worktree identity as pty?.worktreeId ?? liveRow.worktreeId (Line 29451-29453). When pty is null — the case for a pane whose hook status arrives only through relayed rows with no local PTY record, such as a paired headless host reached over SSH — liveRow.worktreeId is always undefined, so the published agentStatus.worktreeId stays absent.

Thread entry.worktreeId from the winning live row through getHookAgentRowForPane and into resolveHookLiveAgentRow's return so hook status keeps its worktree attribution even when no local PTY backs the pane.

🛠️ Proposed fix to thread worktreeId through the hook-status helpers
   private getHookAgentRowForPane(rows: readonly AgentStatusIpcPayload[]): {
     providerSession: AgentProviderSessionMetadata | null
     providerSessionAgentType: string | null
     providerSessionReceivedAt: number | null
     agentType: string | null
     live: ParsedAgentStatusPayload | null
     liveReceivedAt: number | null
     liveStateStartedAt: number | null
+    liveWorktreeId: string | undefined
   } {
     ...
     return {
       providerSession: session?.providerSession ?? null,
       providerSessionAgentType: session?.agentType ?? null,
       providerSessionReceivedAt: session?.receivedAt ?? null,
       agentType: agent?.agentType ?? null,
       live: live ? pickParsedAgentStatusPayload(live) : null,
       liveReceivedAt: live?.receivedAt ?? null,
-      liveStateStartedAt: live?.stateStartedAt ?? null
+      liveStateStartedAt: live?.stateStartedAt ?? null,
+      liveWorktreeId: live?.worktreeId
     }
   }

   private resolveHookLiveAgentRow(
     hookRow: {
       live: ParsedAgentStatusPayload | null
       liveReceivedAt: number | null
       liveStateStartedAt: number | null
+      liveWorktreeId?: string
     },
     pty: RuntimePtyWorktreeRecord | null,
     nonAgentTitle: boolean
   ): {
     payload: ParsedAgentStatusPayload
     updatedAt: number
     stateStartedAt: number
     worktreeId?: string
   } | null {
     ...
     return {
       payload: live,
       updatedAt: receivedAt,
-      stateStartedAt: hookRow.liveStateStartedAt ?? receivedAt
+      stateStartedAt: hookRow.liveStateStartedAt ?? receivedAt,
+      worktreeId: hookRow.liveWorktreeId
     }
   }

Based on learnings, this is the same concern a prior review raised on this hook-status resolution code path ("resolveHookLiveAgentRow exposes an optional worktreeId, but the returned object never sets it"). As per path instructions, "All changes must support SSH use cases and must not assume local-only execution."

Also applies to: 29558-29605

Source: Path instructions

🧹 Nitpick comments (1)
src/shared/native-chat-ask.ts (1)

101-106: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Shorten this comment.

Lines 101-106 explain the mechanism in six lines. Keep only the non-obvious turn-boundary rule.

As per coding guidelines, comments must be concise, limited to non-obvious information, and preferably one line.

Proposed change
-    // A new user turn (or an interrupt row) ends the turn that owns whatever
-    // calls are still in flight: their results never arrive, and `tool_use_id`
-    // is dropped at decode time so those orphans can never be matched by id.
-    // Without this reset one orphan shifts the result FIFO for the rest of the
-    // transcript and strands an answered ask as a permanent card over the
-    // composer (`#11761`). Claude's tool-result turns decode as role 'tool'.
+    // Discard pending calls from an interrupted or superseded turn (`#11761`).

Source: Coding guidelines


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: b8904984-73bd-4cd7-a1a7-0e1f7aa67394

📥 Commits

Reviewing files that changed from the base of the PR and between 83f66c5 and 2267fd7.

📒 Files selected for processing (6)
  • src/main/runtime/orca-runtime-hook-agent-status-projection.test.ts
  • src/main/runtime/orca-runtime.ts
  • src/renderer/src/components/native-chat/NativeChatInteractiveCard.test.tsx
  • src/shared/native-chat-ask.test.ts
  • src/shared/native-chat-ask.ts
  • src/shared/native-chat-types.ts
🚧 Files skipped from review as they are similar to previous changes (2)
  • src/main/runtime/orca-runtime-hook-agent-status-projection.test.ts
  • src/renderer/src/components/native-chat/NativeChatInteractiveCard.test.tsx

Reuse rather than restate: the invalidator now takes the shared
`AgentHookEventPayload` instead of a locally redeclared row shape, and the
hook live row is a `Pick<>` of the retained OSC snapshot so one projection
branch consumes either carrier. Fold the immediate/coalesced session-tabs
emit into one method (also drops a redundant re-emit on the
provider-session push). Drop card tests that re-route shared-parser
assertions through React. Isolate pane-status-clear subscribers and prove
the no-republish case by version arithmetic instead of a timed silence.

Co-authored-by: Orca <[email protected]>
@nwparker

nwparker commented Aug 4, 2026

Copy link
Copy Markdown
Contributor Author

Follow-up pass on "this is a lot of code" — pushed df5d588. Diff is now 901 / -43 (was 1012 / -34), −111 added lines.

Reuse instead of restatement

  • hook-status-session-tabs-invalidation.ts redeclared a local HookStatusSessionTabsRow because "the server's enriched hook payload type is module-private". The base type — AgentHookEventPayload — is already exported from src/shared/agent-hook-listener.ts, and subscribeEnrichedStatus hands out a subtype of it. The invalidator now takes it directly, which deletes the local shape, the ProjectedStatus mirror and the project() normalizer (85 → 52 lines), and collapses the 11-line adapter literal at the index.ts call site to hookStatusChangedSessionTabs(enriched).
  • resolveHookLiveAgentRow built a bespoke { payload, updatedAt, stateStartedAt, worktreeId? } return type, and the call site rebuilt the same shape from retained field by field. That shape is RuntimeAgentRowSnapshot's status half, so it is now type HookLiveAgentRow = Pick<RuntimeAgentRowSnapshot, 'payload' | 'updatedAt' | 'stateStartedAt' | 'worktreeId'> and the branch is one line: retained ?? this.resolveHookLiveAgentRow(hookRow.live, pty, nonAgentTitle). getHookAgentRowForPane returns one live object instead of three parallel live/liveReceivedAt/liveStateStartedAt fields.
  • touchMobileSessionSnapshotsForPty had a hand-rolled copy of the version bump in its immediate branch. touchMobileSessionTabsForWorktree now takes { immediate } and owns both, which also removes the redundant touch(...) + notifyMobileSessionTabsChanged(...) double-emit on the provider-session push.

Test bulk

  • Dropped the two NativeChatInteractiveCard cases that re-routed shared-parser assertions (orphan-behind-interrupt, ask-typed-past) through React — both are asserted directly in src/shared/native-chat-ask.test.ts, which is where the turn-boundary contract lives. Their three fixture builders went with them. The card keeps the cases that exercise its own wiring: render, live-status precedence, no state gate, dismiss-on-answer, FIFO clear, /clear.
  • Merged the two resume-identity row projection cases into one it.each(['claude', 'pi']) asserting both exclusions.
  • Dropped tracks an SSH-stamped pane like any other from the invalidator suite (subsumed by stays quiet… + the field table + the forgetConnection case).

Kept, because it looked removable and is not

  • pickParsedAgentStatusPayload reads like a candidate for the existing normalizeAgentStatusPayload. It isn't: that returns ParsedAgentStatusPayload | null and emits explicit undefined keys for every absent optional, which would change the published key set the security regression asserts, and it re-runs full field sanitization (including the interactive-prompt limit) on every session.tabs build. The allow-list literal stays.
  • lastOscTitleEpochMs and its guard. Mutating the guard to return live fails exactly the two cases it exists for (keeps a shell-reclaimed pane identity-only…, keeps the title-derived working state when the hook row predates the title) — verified.

Review comments

  1. try/catch each paneStatusClearListeners call — fixed. It is called from three teardown paths and now matches the other fan-outs in the file.
  2. Fixed 50 ms wait cannot prove the negative — fixed. ignores a pane with no resolvable workspace now touches the unresolvable pane and a resolvable one, then asserts snapshotVersion === before + 1 — a pane that wrongly resolved here would bump it twice. No arbitrary constant.
  3. Hook status drops worktreeId — fixed. getHookAgentRowForPane now carries entry.worktreeId into the live row, so pty?.worktreeId ?? liveRow.worktreeId has something to fall back on when no local PTY backs the pane.
  4. Docstring coverage 23.53% — rejected. The repo's own AGENTS.md mandates concise, non-obvious, WHY-not-HOW comments; a per-function docstring quota is the opposite instruction. Every non-trivial new function here already carries a WHY comment.

Verification: orca-runtime.test.ts + orca-runtime-hook-agent-status-projection.test.ts + all of src/main/agent-hooks, src/renderer/src/components/native-chat, src/renderer/src/runtime, native-chat-ask, agent-status-types, mobile-session-tabs-notify-coalescer — 156 files, 2808 passed / 4 skipped. oxlint (default + native-plugins + type-aware --deny-warnings), typecheck:node, typecheck:web, and check-max-lines-ratchet.mjs all clean.

nwparker and others added 3 commits August 3, 2026 23:32
…ctron

Why: the 13 parser unit tests pin extraction, but nothing proved a card
actually renders where an inert tool call used to. This spec reproduces the
paired-headless topology from the client side — live status carrying agent
identity and state 'working' but no interactivePrompt/toolName, with the
pending ask present only in the transcript — and fails on main.

Refs #11761

Co-authored-by: Orca <[email protected]>
Why: oxlint no-unused-vars fails the lint gate on an unused test parameter.

Co-authored-by: Orca <[email protected]>
…spec

The env-var screenshot label and the fixed 2s settle only existed to make
the pre-fix capture comparable; the card assertion already waits.

Co-authored-by: Orca <[email protected]>

@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 (3)
tests/e2e/native-chat-ask-user-question-card.spec.ts (3)

138-147: 🩺 Stability & Availability | 🔵 Trivial | ⚡ Quick win

Scope the text locators to the chat root.

getByText performs a substring match and returns every matching element. expect(...).toBeVisible() raises a strict-mode violation when the locator resolves to more than one element. Both userText and QUESTION are plain sentences that a chat surface can render in more than one place, for example in a message body and in an enclosing container. A second match would fail the test with a strict-mode error instead of a product signal. Scope both locators to the native chat root and reduce them to a single node.

♻️ Proposed locator scoping
-      await expect(orcaPage.locator('[data-native-chat-root="true"]')).toBeVisible({
-        timeout: 15_000
-      })
-      await expect(orcaPage.getByText(userText)).toBeVisible({ timeout: 30_000 })
+      const chatRoot = orcaPage.locator('[data-native-chat-root="true"]')
+      await expect(chatRoot).toBeVisible({ timeout: 15_000 })
+      await expect(chatRoot.getByText(userText).first()).toBeVisible({ timeout: 30_000 })
-      await expect(orcaPage.getByText(QUESTION)).toBeVisible({ timeout: 10_000 })
+      await expect(chatRoot.getByText(QUESTION).first()).toBeVisible({ timeout: 10_000 })

Line 159 keeps orcaPage.getByText(QUESTION) for the count assertion, or switches to chatRoot.getByText(QUESTION) for symmetry. Count assertions are exempt from strict mode.


139-141: 🚀 Performance & Scalability | 🔵 Trivial | 💤 Low value

Replace the fixed 2-second wait with a state assertion.

waitForTimeout adds 2 seconds to every run and does not guarantee that hydration finished on a slow machine. Wait for a concrete rendered signal instead, for example the assistant text block or the tool line, then capture the screenshot.


83-96: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Add the missing Claude transcript fields to this fixture.

The parsed tool-use object keeps Claude fields like tool_use_id, but this fixture represents type: 'tool_use' as type: 'tool-call' and omits id/tool_use_id. Add an id field to the tool_use object if the fixture should remain Claude-format, or rename it to tool-call for a native-chat block if this is intentionally normalized.


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: f355fde9-dd9f-42cc-8fba-4b57f6d8961a

📥 Commits

Reviewing files that changed from the base of the PR and between df5d588 and 33923c6.

📒 Files selected for processing (1)
  • tests/e2e/native-chat-ask-user-question-card.spec.ts

nwparker and others added 3 commits August 3, 2026 23:53
…h guard

#11203 taught pane lookup to recover a reminted tab id by leaf id, so the old
fixture (new tab id, live leaf id) resolved and bumped the snapshot a second
time once this branch merged with main.

Co-authored-by: Orca <[email protected]>
#12346 landed on main after this branch was cut: a nonterminal row restored from
last-status.json is stamped `restoredUnconfirmed` because its transition may have
fired while no receiver was up, and every freshness gate treats it as never-fresh.
The new headless `live` projection here only checked `receivedAt`, so a restart
inside the 30-minute window would republish the hydrated row — resurrecting the
AskUserQuestion card with no agent left to answer it.

`agentType` still reads those rows: they prove identity, just not liveness.

Co-authored-by: Orca <[email protected]>
@nwparker
nwparker merged commit f6878d6 into main Aug 4, 2026
45 checks passed
@nwparker
nwparker deleted the nwparker/bugbash-11761 branch August 4, 2026 07:49
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
…s on a paired headless server (stablyai#12223)

* fix(native-chat): show Claude's AskUserQuestion card when the agent runs on a paired headless host

Three gaps kept the question card off the desktop when the agent ran on a
remote `orca serve` host:

- The `session.tabs` projection reduced HTTP agent-hook rows to identity only,
  hard-coding `state: 'done'` and an empty prompt, so `toolName` and the full
  `interactivePrompt` never left the host. It now publishes the newest fresh
  hook row's status fields, bounded by the same staleness window `agentType`
  uses, excluding `providerSessionOnly` resume rows, and yielding to live
  title evidence unless a question is actually pending.
- Nothing republished `session.tabs` when only a hook row changed, and the
  re-emit carried an unchanged `snapshotVersion` that clients drop on their
  monotonic gate. Material hook transitions and pane/SSH status clears now
  bump the version and schedule a coalesced emit.
- The desktop card resolved only from live status. It now falls back to the
  pending ask in the transcript, matching mobile, so a relay gap can no longer
  leave the composer mounted over a pane parked on a selector.

Closes stablyai#11761

Co-authored-by: Orca <[email protected]>

* fix(native-chat): date the hook-row recency guard against a real clock

`resolveHookLiveAgentRow` compared a hook `receivedAt` (epoch ms) against
title stamps that are title-observation sequence numbers, so the guard could
never fire — any fresh hook row overrode live title-derived state, and a manual
rename (the one epoch writer) inverted it. Stamp the live OSC title path with
wall-clock ms and compare against that alone.

The regression test fabricated epoch-valued title stamps production never
writes; it now drives the title through `onPtyData`, and a new case pins the
opposite direction (hook row newer than the title wins).

Co-authored-by: Orca <[email protected]>

* fix(native-chat): stop an orphaned tool call from pinning a dead question card

extractPendingAsk pairs tool results to calls by a global FIFO (tool_use_id
is dropped at decode time), so one call that never gets a result desyncs the
queue for the rest of the transcript and strands an answered ask as pending.
Real transcripts also hold asks the user escaped and typed past. On desktop
that card replaces the composer, so the pane became unsendable.

Drop in-flight calls at a turn boundary — a user turn or the decoders'
interrupt row — since the turn that owned them is over. Claude's tool-result
turns decode as role 'tool', so normal FIFO resolution is untouched.

Co-authored-by: Orca <[email protected]>

* refactor(native-chat): trim the headless AskUserQuestion projection

Reuse rather than restate: the invalidator now takes the shared
`AgentHookEventPayload` instead of a locally redeclared row shape, and the
hook live row is a `Pick<>` of the retained OSC snapshot so one projection
branch consumes either carrier. Fold the immediate/coalesced session-tabs
emit into one method (also drops a redundant re-emit on the
provider-session push). Drop card tests that re-route shared-parser
assertions through React. Isolate pane-status-clear subscribers and prove
the no-republish case by version arithmetic instead of a timed silence.

Co-authored-by: Orca <[email protected]>

* test(native-chat): pin the AskUserQuestion card render under real Electron

Why: the 13 parser unit tests pin extraction, but nothing proved a card
actually renders where an inert tool call used to. This spec reproduces the
paired-headless topology from the client side — live status carrying agent
identity and state 'working' but no interactivePrompt/toolName, with the
pending ask present only in the transcript — and fails on main.

Refs stablyai#11761

Co-authored-by: Orca <[email protected]>

* test(native-chat): drop the unused testInfo parameter

Why: oxlint no-unused-vars fails the lint gate on an unused test parameter.

Co-authored-by: Orca <[email protected]>

* test(native-chat): drop leftover proof scaffolding from the ask-card spec

The env-var screenshot label and the fixed 2s settle only existed to make
the pre-fix capture comparable; the card assertion already waits.

Co-authored-by: Orca <[email protected]>

* test(runtime): use a truly unresolvable pane key in the hook republish guard

stablyai#11203 taught pane lookup to recover a reminted tab id by leaf id, so the old
fixture (new tab id, live leaf id) resolved and bumped the snapshot a second
time once this branch merged with main.

Co-authored-by: Orca <[email protected]>

* fix(runtime): refuse a hydrated unconfirmed hook row as live pane status

stablyai#12346 landed on main after this branch was cut: a nonterminal row restored from
last-status.json is stamped `restoredUnconfirmed` because its transition may have
fired while no receiver was up, and every freshness gate treats it as never-fresh.
The new headless `live` projection here only checked `receivedAt`, so a restart
inside the 30-minute window would republish the hydrated row — resurrecting the
AskUserQuestion card with no agent left to answer it.

`agentType` still reads those rows: they prove identity, just not liveness.

Co-authored-by: Orca <[email protected]>

---------

Co-authored-by: Orca <[email protected]>
Co-authored-by: Neil <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

1 participant