Repository navigation
fix(notes): send AI notes to open structured chat sessions - #24221
Conversation
The notes "Send notes to" menu, browser annotations and the sidebar send targets only listed terminal agents, so an open structured chat was never offered. Send targets now include structured chats, and one sendMessageToAgent delivers to either kind. A chat receives the message through its own outbox, the same enqueue its composer uses, so the note shows in the chat and a failed send keeps Retry. To make that possible the desktop outbox state moves out of the chat view's React hook into a per-session store the view subscribes to; the launch-prompt settlement, the composer and outside senders all write that one copy. Also settles the notes loading toast in place, so an instant send can no longer leave "Sending notes..." stuck on screen.
…limit sidebar targets - A failed notes send settled the "Sending notes..." toast with toast.message, which keeps sonner's loading type: the spinner never cleared and the toast could not be closed. Settle it with toast.info on the same id. - A launch prompt whose staging save failed stayed "dispatching" in the open chat, so it was never sent. Staging is now a required save; on failure the entry stays queued and the chat sends it. - A chat before its first turn has no sidebar row, but counted as a sidebar send target, so opening the notes menu revealed and highlighted an empty card. Only the notes menu lists such chats now.
The notes menu picked a row's dot and state word from the plain row state, while the sidebar row uses agentRowDisplayDotState, which shows the main agent's verdict first. A chat whose turn failed read "Done" with a green check in the menu and "Failed" with a red dot in the sidebar. The menu now uses the sidebar's function; terminal rows with a verdict get the same correction.
|
| const [{ activeAgentNotesSendFailureMessage }, { sendMessageToAgent }] = await Promise.all([ | ||
| import('@/lib/active-agent-note-send'), | ||
| import('@/lib/agent-message-send') | ||
| ]) | ||
| const result = await sendMessageToAgent({ | ||
| worktreeId: mode.worktreeId, | ||
| prompt: mode.prompt, | ||
| noteTarget: { tabId: target.tabId, leafId: target.leafId } | ||
| target: runningAgentMessageTarget(target) |
There was a problem hiding this comment.
Closed chat receives success If the chat closes while this action awaits the imports, it sends to the session resolved before the wait without checking that its tab is still open. The outbox can accept the notes after the chat view has unmounted, leaving nothing to deliver them to the agent, while the action marks them delivered and shows a success toast. Recheck the target immediately before enqueueing.
Knowledge Base Used: Agent workspaces and sessions
| export function loadStructuredAgentSessionOutbox( | ||
| sessionId: string, | ||
| load: () => StructuredAgentSessionOutboxEntry[] | ||
| ): StructuredAgentSessionOutboxEntry[] { | ||
| return holdOutbox(sessionId, load).entries |
There was a problem hiding this comment.
Interrupted renders retain outboxes This snapshot loader creates a held outbox during render, but only a later subscription cleanup removes it. If React abandons the render before subscribing, the session’s message array stays in memory indefinitely. Avoid retaining the outbox until it has a subscription that can release it.
|
Navigate logical layers of code changes, visualize relationships, and explore their blast radius. Important Review skippedReview was skipped as selected files did not have any reviewable changes. ⚙️ Run configurationConfiguration used: Repository UI Review profile: CHILL Plan: Advanced Run ID: You can disable this status message by setting the Use the checkbox below for a quick retry:
📝 WalkthroughWalkthroughThe change adds structured agent sessions as message targets alongside terminal targets. A shared send function routes messages to the active terminal session or a structured-session outbox. The outbox now uses shared storage and subscriptions for dispatch, retries, and status updates. Sidebar and review-note flows use the new target shape and update send notifications. Tests cover structured-session targeting, outbox persistence, and send outcomes. Priority: ⬇️ Low Merge Risk: 🔵 Low · up to In a narrow race, sending to a sidebar chat that is closed while the send is starting can report success even though the chat is gone. Re-check the target after the imports before merging, or accept the small risk. Security Architecture ReviewSecurity architecture risk: 🔵 Low · up to The new way to send notes to existing chats retains selection and approval checks. No introduced security weakness was established, but storage-failure recovery and final permission enforcement are not fully verified. Retained concerns Security review detailsSecurity Blast Radius
Trust Boundaries and Controls
Resilience and Maintainability Implications
Hardening Proposals
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✨ Finishing Touches 💡 1📝 Generate docstrings 💡
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: 1
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Advanced
Run ID: b63b99b1-03c9-423d-8b20-b9a5e0a696ff
📒 Files selected for processing (35)
src/renderer/src/components/editor/ReviewNotesSendMenuContent.test.tsxsrc/renderer/src/components/editor/ReviewNotesSendMenuContent.tsxsrc/renderer/src/components/native-chat/NativeChatStructuredSession.test-harness.tsxsrc/renderer/src/components/native-chat/structured-agent-session-outbox-dispatch.tssrc/renderer/src/components/native-chat/structured-agent-session-outbox-retry.tssrc/renderer/src/components/native-chat/structured-agent-session-outbox-storage.test.tssrc/renderer/src/components/native-chat/structured-agent-session-outbox-storage.tssrc/renderer/src/components/native-chat/structured-agent-session-withdrawn-message-restore.tssrc/renderer/src/components/native-chat/use-native-chat-provisional-launch.tssrc/renderer/src/components/native-chat/use-structured-agent-session-outbox-fence.test.tsxsrc/renderer/src/components/native-chat/use-structured-agent-session-outbox-ownership.tssrc/renderer/src/components/native-chat/use-structured-agent-session-outbox-rejection-cause.test.tsxsrc/renderer/src/components/native-chat/use-structured-agent-session-outbox-unconfirmed-probe.tssrc/renderer/src/components/native-chat/use-structured-agent-session-outbox.draft-hand-off.test.tsxsrc/renderer/src/components/native-chat/use-structured-agent-session-outbox.external-send.test.tsxsrc/renderer/src/components/native-chat/use-structured-agent-session-outbox.queue-delivery.test.tsxsrc/renderer/src/components/native-chat/use-structured-agent-session-outbox.stop-parks-in-doubt.test.tsxsrc/renderer/src/components/native-chat/use-structured-agent-session-outbox.test.tsxsrc/renderer/src/components/native-chat/use-structured-agent-session-outbox.tssrc/renderer/src/components/sidebar/WorktreeCardAgents.send-target.test.tsxsrc/renderer/src/components/sidebar/WorktreeCardAgents.tsxsrc/renderer/src/components/sidebar/worktree-card-send-target-inputs.test.tssrc/renderer/src/components/sidebar/worktree-card-send-target-inputs.tssrc/renderer/src/components/sidebar/worktree-list/listing/use-agent-send-target.tssrc/renderer/src/lib/active-agent-note-send-result.tssrc/renderer/src/lib/agent-message-send.tssrc/renderer/src/lib/agent-message-target.tssrc/renderer/src/lib/notes-send-agent-targets.test.tssrc/renderer/src/lib/notes-send-agent-targets.tssrc/renderer/src/lib/running-agent-targets.test.tssrc/renderer/src/lib/running-agent-targets.tssrc/renderer/src/lib/structured-agent-session-launch-prompt.tssrc/renderer/src/lib/structured-agent-session-launch.tssrc/renderer/src/store/slices/ui-agent-send-target.test.tssrc/renderer/src/store/slices/ui/ui-slice-agent-actions.ts
Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 4 remain after this review.
| import('@/lib/active-agent-note-send'), | ||
| import('@/lib/agent-message-send') | ||
| ]) | ||
| const result = await sendMessageToAgent({ |
There was a problem hiding this comment.
🗄️ Data Integrity & Integration | 🟡 Minor | ⚡ Quick win
🔎 Supported by static analysis
🏁 Script executed:
ast-grep outline src/renderer/src/lib/running-agent-targets.ts --items all
ast-grep outline src/renderer/src/components/native-chat/structured-agent-session-outbox-storage.ts --items all
rg -n -C4 --glob '*.{ts,tsx}' \
'\bcommitStructuredAgentSessionOutbox\s*\(|\bappendStructuredAgentSessionOutboxMessage\s*\(|\b(close|remove|delete)[A-Za-z]*(Tab|Session)\s*\(' \
src/renderer/srcRepository: stablyai/orca
Length of output: 45661
🏁 Script executed:
set -eu
printf '%s\n' '--- changed function and diff ---'
git diff --unified=40 ed462b2caa5e280d6a56b2f9c6fed1b2bc2f86db 5d89ea6e9df451c17ce724d9b43aee96c0b771c4 -- src/renderer/src/store/slices/ui/ui-slice-agent-actions.ts
printf '%s\n' '--- target resolver ---'
sed -n '1,280p' src/renderer/src/lib/running-agent-targets.ts
printf '%s\n' '--- outbox storage ---'
sed -n '1,260p' src/renderer/src/components/native-chat/structured-agent-session-outbox-storage.ts
printf '%s\n' '--- sendMessageToAgent bindings ---'
rg -n -C12 '\bsendMessageToAgent\b|runningAgentMessageTarget|resolveRunningAgentSendTarget' src/renderer/src --glob '*.{ts,tsx}'
printf '%s\n' '--- structured agent close bindings ---'
rg -n -C12 'closeUnifiedTab|contentType.*agent-session|structuredAgentSession|structured-agent-session' src/renderer/src/store src/renderer/src/components/tab-group src/renderer/src/components/native-chat src/renderer/src/runtime --glob '*.{ts,tsx}' | head -n 1200Repository: stablyai/orca
Length of output: 42351
🏁 Script executed:
set -eu
printf '%s\n' '--- changed function ---'
sed -n '110,205p' src/renderer/src/store/slices/ui/ui-slice-agent-actions.ts
printf '%s\n' '--- target resolver ---'
sed -n '45,255p' src/renderer/src/lib/running-agent-targets.ts
printf '%s\n' '--- outbox storage ---'
sed -n '100,225p' src/renderer/src/components/native-chat/structured-agent-session-outbox-storage.ts
printf '%s\n' '--- close and send bindings ---'
rg -n -C8 'sendMessageToAgent|resolveRunningAgentSendTarget|commitStructuredAgentSessionOutbox|closeUnifiedTab|contentType.*agent-session|structuredAgentSession' src/renderer/src/store/slices/ui src/renderer/src/components/native-chat src/renderer/src/components/tab-group src/renderer/src/store --glob '*.{ts,tsx}' | head -n 1000Repository: stablyai/orca
Length of output: 42360
🏁 Script executed:
set -eu
printf '%s\n' '--- agent-message-send implementation ---'
sed -n '1,280p' src/renderer/src/lib/agent-message-send.ts
printf '%s\n' '--- closeUnifiedTab declaration and implementation ---'
rg -n -C20 'closeUnifiedTab' src/renderer/src/store src/renderer/src/components/tab-group src/renderer/src/runtime --glob '*.{ts,tsx}' | head -n 1200
printf '%s\n' '--- close implementation candidates ---'
rg -n -C12 'function closeUnifiedTab|closeUnifiedTab:|closeUnifiedTab\\(' src/renderer/src/store --glob '*.{ts,tsx}'Repository: stablyai/orca
Length of output: 41850
🏁 Script executed:
set -eu
files="$(rg -l -F 'closeUnifiedTab' src/renderer/src/store --glob '*.{ts,tsx}' || true)"
printf '%s\n' "$files"
rg -n -F 'closeUnifiedTab:' $files || true
rg -n -F 'closeUnifiedTab =' $files || true
rg -n -F 'closeUnifiedTab(' $files | head -n 120Repository: stablyai/orca
Length of output: 3398
🏁 Script executed:
sed -n '1,180p' src/renderer/src/store/slices/tabs/tabs-close-actions.tsRepository: stablyai/orca
Length of output: 8416
Re-resolve the target after the dynamic imports.
sendPromptToSidebarAgentTarget captures the target before awaiting the imports. Closing the chat removes it from unifiedTabsByWorktree, but sendMessageToAgent still appends to the captured session ID. The append succeeds without checking whether the chat remains open, returns sent, and triggers onPromptDelivered.
Re-resolve and revalidate the target after the imports. Abort if the chat is no longer eligible before calling sendMessageToAgent.
There was a problem hiding this comment.
Important
The sidebar send path resolves its target before it awaits the two dynamic imports, and the new structured branch does not re-validate at delivery the way the terminal branch does. A chat that closes in that window gets the note appended to an outbox whose view is gone, while the action reports success. Details inline.
Reviewed changes
- One send-target list across agent kinds —
deriveRunningAgentSendTargetsnow returns terminal and structured targets as a tagged union;deriveStatuslessStructuredAgentSendTargetsadds pre-first-turn chats for the notes menu only, so the sidebar never reveals a card with no row. - One send entry point — the new
sendMessageToAgentroutes terminal targets to the existing guarded paste path and chat targets onto the chat's outbox, relaunching a failed start via the extractedrelaunchFailedStructuredAgentSessionForMessage. - Outbox moved into a per-session store —
structured-agent-session-outbox-storage.tsholds and persists one copy per session; the chat view subscribes withuseSyncExternalStoreand drains, andmirrorPersisted/per-view state are removed.onlyIfSavedcommits leave the held copy untouched when the save fails. - Toast settling — the loading toast is settled in place with
toast.success/toast.infoand{ id: pending }instead of a separatedismiss. - Menu row status —
agentRowDisplayDotStatenow drives the notes-menu dot so a failed or stopped agent reads the same there as in the sidebar.
I ran the affected suites (running-agent-targets, notes-send-agent-targets, structured-agent-session-outbox-storage, use-structured-agent-session-outbox.external-send, ReviewNotesSendMenuContent, ui-agent-send-target) — all pass. An independent read of the outbox-store concurrency found no newly reachable lost update, duplicate send, or drainAgain loop.
ℹ️ Nitpicks
getSnapshot(loadStructuredAgentSessionOutbox) creates the module-level hold as a side effect of render. A render React abandons before it subscribes would leave a held outbox with no listener (low impact, but worth a comment or a lazy-hold guard if you want it airtight).
DeepSeek Flash (free via Pullfrog for OSS) | 𝕏
| const result = await sendNotesToActiveAgentSession({ | ||
| const agentType = runningAgentSendTargetAgentType(target) | ||
| const label = formatAgentTypeLabel(agentType) | ||
| const [{ activeAgentNotesSendFailureMessage }, { sendMessageToAgent }] = await Promise.all([ |
There was a problem hiding this comment.
The target is resolved at line 127, then sendMessageToAgent is called only after this await Promise.all([...]). The terminal branch re-validates live hook/PTY evidence inside sendNotesToActiveAgentSession, but the new structured branch appends to the session's outbox without confirming the chat is still open. If the chat tab closes during the import gap, beginStructuredAgentSessionTabClose has already discarded that session's outbox; the note is appended for a session with no view, yet sendMessageToAgent returns sent, so onPromptDelivered fires and the notes leave the unsent list while never reaching the agent.
Technical details
# A closed chat can receive a note with no view left to deliver it
## Affected sites
- `src/renderer/src/store/slices/ui/ui-slice-agent-actions.ts:127` — the target is resolved before the `await` at line 153.
- `src/renderer/src/lib/agent-message-send.ts:29` — the `structured-session` branch appends without a liveness check.
- `src/renderer/src/runtime/structured-agent-session-tab-retirement.ts:69` — closing the tab discards the session's outbox first.
## Required outcome
- The check and the append must happen in the same task: no `await` between validating the target and enqueueing the message, or `sendMessageToAgent` itself re-validates the structured target.
## Suggested approach
- Load the dynamic imports first, then resolve/validate the target and call `sendMessageToAgent` with no intervening `await` (the imports do not depend on the target). Alternatively re-check `kind: 'structured-session'` liveness inside `sendMessageToAgent`.
## Open questions for the human
- Is a silently lost note plus a "Sent to …" toast an accepted trade-off here, or should the send surface a failure when the chat closed mid-send?
Review status: ready for review (not merged)The problem: with a structured chat open, "Send notes to" in the AI notes menu (diff notes, Source Control notes, browser annotations) never offered that chat, and the sidebar send targets had the same gap. The only way to get notes into an open chat was to copy them in by hand. What changes for you: open chats now appear in those menus with their status. Sending notes to a chat puts them in the chat as your message and sends them, exactly like typed text: if the agent doesn't take them, they stay in the chat with Retry. A chat waiting on a permission prompt is listed but disabled. Sending to terminal agents works as before. Fixed during review (head
|
…message-stays-held Brings in #24221, which moves the desktop outbox into a per-session store that every writer commits to. Conflicts in the outbox hook, dispatch, retry, ownership and the unconfirmed probe resolve onto that store, keeping this branch's behaviour: - the drain admits and stages from the store's latest list (no render copy); - a failed staging save commits the Retry hold, saved if storage takes it; - Retry rotates an expired kept id; the probe strips a saved failure; - failures seen while the chat is open are recorded before each commit; - the in-memory blocked-head marker #24221 still threaded is dropped.

What this fixes
Problem: With a structured chat open (the Chat UI setting with structured sessions on), "Send notes to" in the AI notes menu never offered that chat. Only "New agent" options appeared, so the only way to get notes into an existing chat was to copy them in by hand.
Who hits it: Anyone sending AI notes (diff notes, Source Control notes, browser annotations) while a structured chat is open in the worktree. The same gap existed in the send targets on the sidebar card rows.
Not affected: Delivery to terminal agents, including the chat view shown over a terminal agent. Those already worked and are delivered exactly as before. Two display changes reach terminal rows too: a refused send now shows an info toast in place of the spinner (change 4), and a terminal agent with a failed or stopped verdict now reads so in the menu (change 5). Mobile is not affected: it has its own send path.
Regression? No. Structured chats were never added to the send-target lists.
ELI5
Orca kept two separate lists of open agents: terminal tabs and chat tabs. The "send notes to…" picker only read the terminal list, so chats were invisible to it. Now the picker reads both, and a note sent to a chat is dropped into that chat's own message queue, as if you had typed it into the chat's message box.
What this changes for you
What changed (mechanism)
1. One list of send targets across agent kinds.
deriveRunningAgentSendTargets(lib/running-agent-targets.ts) now returns terminal targets and structured-chat targets as one tagged union. Chats come from the worktree's workspace tabs (unifiedTabsByWorktree,contentType: 'agent-session'), keyed by the same pane key the chat's status row uses. The notes menu, the sidebar card rows, the sidebar reveal and the sidebar force-visible rule all read this one derivation.deriveStatuslessStructuredAgentSendTargets, used byderiveNotesSendAgentTargets), the same way that layer adds freshly launched terminal agents found by title. This keeps the sidebar from revealing and highlighting a card that has nothing to click.2. One send entry point.
sendMessageToAgent(lib/agent-message-send.ts) takes anAgentMessageTarget, either{ kind: 'terminal', tabId, leafId }or{ kind: 'structured-session', sessionId }. The notes menu and the sidebar send action both call it:relaunchFailedStructuredAgentSessionForMessage, extracted and now shared).3. Root cause: the chat outbox now has one owner. Before, the desktop chat outbox (a chat's queue of unsent messages, persisted to localStorage) was held inside the chat view's React hook as
useStateplus a ref, with localStorage as a second copy.mirrorPersistedstep to catch up after it.structured-agent-session-outbox-storage.ts. It is held in memory while a chat subscribes and persisted on every write. The chat view reads it withuseSyncExternalStoreand still drains it: fence, queue capability, single-flight and retry are all unchanged.appendStructuredAgentSessionOutboxMessage/commitStructuredAgentSessionOutbox.mirrorPersistedand the mounted-view mirroring. The only thing it still did was re-trigger the drain after a launch send settled, and that is now an explicitdrainAgain.4. Toast. The notes loading toast is settled in place with the same id. A separate
toast.dismisscould run before the loading toast mounted when the send resolved instantly, which left "Sending notes…" on screen. Success settles withtoast.successand a refused send withtoast.info. It must be a typed call: sonner'stoast.message()on the loading toast's id keeps it a loading toast, which shows a spinner, never closes on its own and has no close button.5. Menu row status matches the sidebar. The menu's status dot and word for an agent row now come from the same function the sidebar row uses (
agentRowDisplayDotState), which shows the main agent's verdict (failed or interrupted) ahead of the plain state. Before, the menu read the plain state only, so a chat whose turn failed read "Done" with a green check in the menu and "Failed" with a red dot in the sidebar. The menu has one row renderer for both kinds, so terminal rows get the same correction: a terminal agent with a failed or stopped verdict also read "Done" in the menu. That terminal mismatch predates this PR (the menu line came from #18012).Why this approach
Why queue into the chat's outbox instead of calling
agentSession.senddirectly? I tried the direct call first. It delivered, but when the turn failed the message vanished from the chat and the notes were already marked sent. The outbox is what gives a message its bubble, persistence across restarts, and Retry. Going through it makes a note behave exactly like typed text.Why move the outbox into a store instead of letting the open chat register its send function? A registry of mounted views makes the view the owner of delivery. It also needs a second "no view open" path that writes storage behind the view's back, which is the same smell
mirrorPersistedalready patched. With a store, every writer changes one copy and the view just subscribes.Bug class removed:
Why not merge the two target derivations completely? The notes menu also lists agents that have no status entry yet: freshly launched terminal agents found by title (existing behavior), and chats before their first turn. The sidebar can't show a row for those, so its send targets leave them out.
Differences from the common pattern
Known weaknesses
Visual Proof
Before this PR: an open Claude chat is not offered.
After, from the M4Air QA run on an isolated dev build (stub agents; the stub Claude is not signed in, so chat turns fail and messages keep Retry).
The Source Control "Send notes to" menu lists the open chat ("Claude · Idle · Claude Chat"):
The diff "AI notes" → This file menu lists the same chat:
The browser annotations Send menu lists the chat. This shot is from before the status fix in change 5: the sidebar says "Failed" while the menu says "Done".
The note lands in the chat as the user's message, with Retry:
A refused send: the spinner is replaced by a closable info toast.
20 seconds later no toast is left, and the note is still unsent (AI notes 1):
The refused note never entered the chat:
After storage is freed, the same note lands in the chat:
A brand-new chat with no turn is listed, and the sidebar does not jump or highlight:
The new chat received the note:
Terminal agents are unchanged: the stub echoes the pasted notes.
After the outbox refactor, the chat's own composer still sends; a typed message looks the same as the notes:
"New agent → Claude" from the notes menu (the launch-prompt path, which now writes the shared outbox) opens a chat with the notes as its first message:
Before and after an app restart on the same profile: the same messages, none resent.
Testing
Manual (M4Air, macOS, isolated dev build of b06911e): background launch with its own HOME, Codex and Claude config folders and app profile, a mock keychain, and stub agent CLIs first on PATH. The stub Claude answers "Not logged in" in structured mode and echoes its input in a terminal. No real agent ran (checked with
psafter every launch).The QA run was on b06911e, before the menu status fix (change 5); that fix is covered by a unit test only.
Not verified live:
Automated: 80 affected test files, 712 tests, all pass. Web typecheck, oxlint, and the changed-code quality gate are clean. New tests cover:
toast(the old test asserted the exact buggy call and could not see this);Each of the last four fails without its fix, and removing the store's change notification makes the hook-level test fail. The six outbox hook suites now unmount their hooks after each test (
afterEach(cleanup); this repo runs without vitest globals, so testing-library does not do it automatically). They share the per-session store now, and a hook left mounted from one test would drain the next test's outbox.Notes
agentSession.sendthe composer sends.Checklist