Skip to content

fix(notes): send AI notes to open structured chat sessions - #24221

Merged
brennanb2025 merged 4 commits into
mainfrom
brennanb2025/fix-ai-notes-session
Oct 1, 2026
Merged

brennanb2025 merged 4 commits into
mainfrom
brennanb2025/fix-ai-notes-session

Conversation

@brennanb2025

@brennanb2025 brennanb2025 commented Sep 30, 2026 •

Copy link
Copy Markdown
Contributor
Files Added Deleted Net
Test 14 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​596 $\color{#cf222e}{\Huge{\mathbf{−}}}$​93 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​503
Prod 21 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​473 $\color{#cf222e}{\Huge{\mathbf{−}}}$​212 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​261

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

Before After
Notes menu with a structured chat open Chat not listed; only "New agent" Chat listed with its status ("Idle", "Done · 3m ago", "Failed"), the same status its sidebar row shows
A brand-new chat that has not had a turn yet Not listed Listed in the notes menu. It is not a sidebar send target, because the sidebar has no row for it yet, so opening the menu does not move or highlight the sidebar
Sending notes to that chat Not possible Note appears in the chat as your message and is sent to the agent
The chat's agent fails to take the message n/a Message stays in the chat with "Your message was not sent · Retry", same as a typed message
Chat waiting on an approval or question n/a Listed but disabled: "Agent needs permission" (same rule as terminal agents)
"Sending notes…" toast after an instant send Could stay stuck on screen Settles to "Notes sent." and clears
"Sending notes…" toast when the send is refused (any agent kind) Spinner dismissed, separate message shown The spinner is replaced in place by a closable info toast with the reason, which clears on its own

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.

  • That shared list holds only agents the sidebar has a row for: an agent with a status entry. A chat before its first turn has no status entry yet, so it is added only by the notes menu's own layer (deriveStatuslessStructuredAgentSendTargets, used by deriveNotesSendAgentTargets), 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 an AgentMessageTarget, either { kind: 'terminal', tabId, leafId } or { kind: 'structured-session', sessionId }. The notes menu and the sidebar send action both call it:

  • A terminal target goes through the existing guarded paste path, unchanged.
  • A chat target is queued on that chat's outbox with the same enqueue its composer uses. If the chat's start had failed, it is restarted with the same rule the composer applies (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 useState plus a ref, with localStorage as a second copy.

  • The smell: anything outside the view had to write storage behind the hook's back. The launch-prompt path already did that, and the hook carried a mirrorPersisted step to catch up after it.
  • Now: the outbox lives in a per-session store in 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 with useSyncExternalStore and still drains it: fence, queue capability, single-flight and retry are all unchanged.
  • Who writes it: the composer, the launch-prompt settlement, Stop/withdraw, the retry and probe steps, and outside senders all go through appendStructuredAgentSessionOutboxMessage / commitStructuredAgentSessionOutbox.
  • What was deleted: mirrorPersisted and 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 explicit drainAgain.
  • First message of a new chat: marking it as "being sent" is now a required save, the same as for a composer message. If that save fails (browser storage full), the message stays queued and the open chat sends it, instead of sitting as "sending" forever with no Retry.

4. Toast. The notes loading toast is settled in place with the same id. A separate toast.dismiss could run before the loading toast mounted when the send resolved instantly, which left "Sending notes…" on screen. Success settles with toast.success and a refused send with toast.info. It must be a typed call: sonner's toast.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.send directly? 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 mirrorPersisted already patched. With a store, every writer changes one copy and the view just subscribes.

Bug class removed:

  • Divergent outbox copies between the view and storage.
  • Late writes from a send that finishes after its view closed bringing back an entry that was already cleared. Settlement now reads the live outbox.
  • Appends and launch updates that re-read storage "with recovery" and flipped other in-flight sends to unconfirmed. Only the entry being settled gets that view now.

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

  • Delivery still needs the chat view to be mounted (temporary). Queuing and state no longer depend on the view, but the drain (the step that actually sends to the host) still runs in the open chat, because it needs the chat's journal subscription for the fence and queue state.
    • Why it is safe now: every send surface targets the worktree the notes belong to, and that worktree is always mounted while its notes can be sent. A chat that is mounted but hidden keeps reading its journal while it has undelivered messages, so a note queued for a background chat tab still goes out.
    • Follow-up that removes it: a per-session drainer at the app root that subscribes to the new outbox store and the chat's journal, so delivery no longer depends on the chat view. This PR's store is its prerequisite.
  • Notes are sent directly, not placed in the chat's draft for the user to send (intended). This keeps the existing Orca behavior for terminal agents, where "Send notes to" sends immediately. Chats now match it.

Known weaknesses

  • "Notes sent." means queued in the chat. If the chat's queue is held on an earlier failed message, the note waits behind it, visible in the chat with the others. The notes list treats it as delivered, the same as a message typed into the composer.
  • Cancelled chat starts drop queued notes. If a chat's start is cancelled (its tab is closed while starting, or its worktree is removed), the chat's outbox is discarded, notes included. Composer text is discarded the same way.
  • A chat before its first turn reads "Idle" in the menu. It has no status yet and no sidebar row to match, so the menu shows the default.
  • Not fixed here (pre-existing, affects terminals too): with the notes menu open, clicking an agent row in the left sidebar closes the menu on mouse-down before the row's click runs, so nothing is sent. The store action behind that click is fixed and tested; the click itself is a separate bug.

Visual Proof

Before this PR: an open Claude chat is not offered.

Before: Send notes to lists no chat

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"):

Source Control notes menu lists the structured chat

The diff "AI notes" → This file menu lists the same chat:

Diff AI notes menu lists the structured 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".

Browser annotations send menu lists the chat

The note lands in the chat as the user's message, with Retry:

Note delivered into the chat

A refused send: the spinner is replaced by a closable info toast.

Info toast replaces the spinner

20 seconds later no toast is left, and the note is still unsent (AI notes 1):

No stuck toast after 20 s

The refused note never entered the chat:

Chat without the failed note

After storage is freed, the same note lands in the chat:

Same note delivered after freeing storage

A brand-new chat with no turn is listed, and the sidebar does not jump or highlight:

New chat listed, sidebar unchanged

The new chat received the note:

New chat received the note

Terminal agents are unchanged: the stub echoes the pasted notes.

Terminal agent received notes

After the outbox refactor, the chat's own composer still sends; a typed message looks the same as the notes:

Composer send

"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:

New chat launched with notes

Before and after an app restart on the same profile: the same messages, none resent.

Chat before restart

Chat after restart, no resend

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 ps after every launch).

Scenario Result
Chat listed with its status in the Source Control notes menu, the diff "AI notes" menu and the browser annotations Send menu Pass
Note lands in the chat as the user's message and keeps Retry like a typed message; the toast settles to success and clears (about 4 s) Pass
Refused send (browser storage filled to its limit): the spinner is replaced in place by a closable info toast that clears on its own (about 4 s); the note stays unsent and never enters the chat; after storage is freed the same note is delivered Pass
Brand-new chat with no turn is listed and receives notes; opening the menu does not move or highlight the sidebar Pass
Notes to a terminal agent are pasted as before Pass
The chat's own composer still sends Pass
"New agent → Claude" from the notes menu opens a chat with the notes as its first message Pass
Quit and relaunch on the same profile: messages reload, no duplicates, nothing resent Pass

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:

  • A real agent reply (stubs only).
  • A refused send on the terminal path. Four attempts to get a terminal target that Orca lists but then refuses were all either accepted or correctly dropped from the menu. The toast change is shared by every refusal, and the chat path exercised it.
  • The sidebar row click (blocked by the pre-existing menu-dismiss bug above).
  • A chat whose view isn't mounted (covered by unit tests only).

Automated: 80 affected test files, 712 tests, all pass. Web typecheck, oxlint, and the changed-code quality gate are clean. New tests cover:

  • chat targets in the shared derivation (a chat with status is listed, a chat before its first turn is listed only for the notes menu, disabled while waiting on permission, other worktrees and tab kinds skipped);
  • the sidebar send routing a chat by session, and no sidebar reveal for a chat before its first turn;
  • the outbox store (notifies an open chat, appends without disturbing an in-flight send, keeps state when a required save fails, releases with its last subscriber, launch settlement sees only its own entry as unconfirmed);
  • a hook-level test that a message queued from outside is drained by the open chat;
  • a new chat's first message whose save fails stays queued and is sent once the chat is ready;
  • a refused notes send leaves a non-loading toast, checked against real sonner toast state, not a mocked toast (the old test asserted the exact buggy call and could not see this);
  • a failed chat's menu row reads "Failed" and a stopped terminal agent's reads "Interrupted", as their sidebar rows do.

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.

  • I manually tested these changes locally
  • Automated tests added/updated

Notes

  • SSH/remote: chats queue and drain against the worktree's own runtime target, the same one the chat view uses, so remote sessions deliver on their host. The wire format is unchanged: the same agentSession.send the composer sends.
  • Paired web client: it runs the same renderer code, so its composer and outbox now go through the same store.
  • Mobile: unaffected.
  • Folder workspaces: same surfaces as git worktrees.
  • Cross-platform: no platform-specific code.

Checklist

  • I explained what changed and why (ELI5, the user-facing before/after, the mechanism, and why over the alternatives)
  • Before/after screenshots attached
  • Self-reviewed for correctness, security, and performance
  • Cross-platform, SSH/remote, and path/shortcut impact considered

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.
@brennanb2025
brennanb2025 marked this pull request as ready for review September 30, 2026 22:57
@greptile-apps

greptile-apps Bot commented Sep 30, 2026 •

Copy link
Copy Markdown

RetriggerConfidence Score: 4/5

[Medium risk] Refactors how AI notes route to open chat sessions.

The PR does not appear safe to merge while notes can still be accepted for a chat closed during the sidebar action’s asynchronous import.

Findings

  1. P1 Closed chat receives success ▶
  2. P2 Interrupted renders retain outboxes ▶

Summary

This PR adds structured chats to AI-notes send targets and routes notes through the chat outbox. It also shares target derivation with sidebar actions and aligns menu status and toast feedback.

Diagram
%%{init: {'theme': 'neutral'}}%%
flowchart LR
  N[AI notes menu or sidebar] --> T{Send target}
  T -->|Terminal| P[Guarded terminal paste]
  T -->|Structured chat| O[Session outbox]
  O --> V[Mounted chat drains queue]
  V --> H[Agent session send]
Loading

Reviews (2) · Last reviewed commit: "Merge remote-tracking branch 'origin/mai..."

Comment on lines +153 to +160
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)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 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

Comment on lines +133 to +137
export function loadStructuredAgentSessionOutbox(
sessionId: string,
load: () => StructuredAgentSessionOutboxEntry[]
): StructuredAgentSessionOutboxEntry[] {
return holdOutbox(sessionId, load).entries

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

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

@coderabbitai

coderabbitai Bot commented Sep 30, 2026 •

Copy link
Copy Markdown
Contributor

Review in Change Stack →

Navigate logical layers of code changes, visualize relationships, and explore their blast radius.

Important

Review skipped

Review was skipped as selected files did not have any reviewable changes.

⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Advanced

Run ID: 0778db5e-c317-43f9-9f7f-868771011e18

📥 Commits

Reviewing files that changed from the base of the PR and between 5d89ea6 and 8495369.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Use the checkbox below for a quick retry:

  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

The 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 5d89e

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 Review

Security architecture risk: 🔵 Low · up to 5d89e

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
No architecture-level concerns identified.

Security review details

Security Blast Radius

  • inferred — The new reachable destinations are eligible structured chats in the chosen worktree. The observed path carries note text to the selected session, but does not establish broader tenant, environment or credential exposure; downstream authority enforcement remains outside verified coverage.

Trust Boundaries and Controls

  • observed — Delivery checks session identity and the entry's current queued state, stages durably, and uses a session-specific fenced send. These are renderer-side controls; independent host authorization was not verified.

Resilience and Maintainability Implications

  • observed — Shared snapshots coordinate mounted hooks within one renderer. Dispatch-generation checks reject obsolete completions, while ownership retirement invalidates a matching in-flight send before removing host-owned entries. Cross-renderer atomicity was not established.

Hardening Proposals

  • proposed — Consider explicit failed-cleanup recovery, such as a durable cancellation marker or retried deletion, so cancellation cannot appear settled while stale entries remain persisted. This addresses an inherited cleanup limitation, not a verified PR-introduced vulnerability.
🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 27.12% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 59 functions across 35 files. 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 and concisely describes the primary change: sending AI notes to open structured chat sessions.
Description check ✅ Passed The description is detailed and covers the user impact, implementation, rationale, visual proof, testing, limitations, and compatibility considerations. It is mostly complete, although it omits some t…
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 💡
  • Commit to this branch
  • Create a new PR
  • Autopilot · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Autopilot is currently an internal CodeRabbit preview.


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: 1


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Advanced

Run ID: b63b99b1-03c9-423d-8b20-b9a5e0a696ff

📥 Commits

Reviewing files that changed from the base of the PR and between ed462b2 and 5d89ea6.

📒 Files selected for processing (35)
  • src/renderer/src/components/editor/ReviewNotesSendMenuContent.test.tsx
  • src/renderer/src/components/editor/ReviewNotesSendMenuContent.tsx
  • src/renderer/src/components/native-chat/NativeChatStructuredSession.test-harness.tsx
  • src/renderer/src/components/native-chat/structured-agent-session-outbox-dispatch.ts
  • src/renderer/src/components/native-chat/structured-agent-session-outbox-retry.ts
  • src/renderer/src/components/native-chat/structured-agent-session-outbox-storage.test.ts
  • src/renderer/src/components/native-chat/structured-agent-session-outbox-storage.ts
  • src/renderer/src/components/native-chat/structured-agent-session-withdrawn-message-restore.ts
  • src/renderer/src/components/native-chat/use-native-chat-provisional-launch.ts
  • src/renderer/src/components/native-chat/use-structured-agent-session-outbox-fence.test.tsx
  • src/renderer/src/components/native-chat/use-structured-agent-session-outbox-ownership.ts
  • src/renderer/src/components/native-chat/use-structured-agent-session-outbox-rejection-cause.test.tsx
  • src/renderer/src/components/native-chat/use-structured-agent-session-outbox-unconfirmed-probe.ts
  • src/renderer/src/components/native-chat/use-structured-agent-session-outbox.draft-hand-off.test.tsx
  • src/renderer/src/components/native-chat/use-structured-agent-session-outbox.external-send.test.tsx
  • src/renderer/src/components/native-chat/use-structured-agent-session-outbox.queue-delivery.test.tsx
  • src/renderer/src/components/native-chat/use-structured-agent-session-outbox.stop-parks-in-doubt.test.tsx
  • src/renderer/src/components/native-chat/use-structured-agent-session-outbox.test.tsx
  • src/renderer/src/components/native-chat/use-structured-agent-session-outbox.ts
  • src/renderer/src/components/sidebar/WorktreeCardAgents.send-target.test.tsx
  • src/renderer/src/components/sidebar/WorktreeCardAgents.tsx
  • src/renderer/src/components/sidebar/worktree-card-send-target-inputs.test.ts
  • src/renderer/src/components/sidebar/worktree-card-send-target-inputs.ts
  • src/renderer/src/components/sidebar/worktree-list/listing/use-agent-send-target.ts
  • src/renderer/src/lib/active-agent-note-send-result.ts
  • src/renderer/src/lib/agent-message-send.ts
  • src/renderer/src/lib/agent-message-target.ts
  • src/renderer/src/lib/notes-send-agent-targets.test.ts
  • src/renderer/src/lib/notes-send-agent-targets.ts
  • src/renderer/src/lib/running-agent-targets.test.ts
  • src/renderer/src/lib/running-agent-targets.ts
  • src/renderer/src/lib/structured-agent-session-launch-prompt.ts
  • src/renderer/src/lib/structured-agent-session-launch.ts
  • src/renderer/src/store/slices/ui-agent-send-target.test.ts
  • src/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({

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.

🗄️ 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/src

Repository: 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 1200

Repository: 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 1000

Repository: 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 120

Repository: stablyai/orca

Length of output: 3398


🏁 Script executed:

sed -n '1,180p' src/renderer/src/store/slices/tabs/tabs-close-actions.ts

Repository: 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.

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

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 — deriveRunningAgentSendTargets now returns terminal and structured targets as a tagged union; deriveStatuslessStructuredAgentSendTargets adds 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 sendMessageToAgent routes terminal targets to the existing guarded paste path and chat targets onto the chat's outbox, relaunching a failed start via the extracted relaunchFailedStructuredAgentSessionForMessage.
  • Outbox moved into a per-session store — structured-agent-session-outbox-storage.ts holds and persists one copy per session; the chat view subscribes with useSyncExternalStore and drains, and mirrorPersisted/per-view state are removed. onlyIfSaved commits leave the held copy untouched when the save fails.
  • Toast settling — the loading toast is settled in place with toast.success/toast.info and { id: pending } instead of a separate dismiss.
  • Menu row status — agentRowDisplayDotState now 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).

Pullfrog  | Fix all ➔ | Fix 👍s ➔ | View workflow run | Using 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([

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.

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?

@brennanb2025

Copy link
Copy Markdown
Contributor Author

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 8495369f898)

  • P1: a failed notes send left a spinner notice on screen for good. The "Sending notes…" notice was updated in place with toast.message, which keeps it in its loading state. Any send that didn't go through (agent not ready, needs permission, storage full…) left a spinner that never closed and couldn't be dismissed, and this hit terminal agents too. It is now replaced by an info notice that closes on its own. The test now checks the real notice state and fails on the old code.
  • P3: a new chat's first message could get stuck on "sending". When "New agent" launched a chat with notes and the browser's storage was full, that message stayed on "sending" with no Retry, and later messages overtook it. The save is now required, so on failure the message stays queued and the chat sends it.
  • P3: a brand-new chat made the sidebar highlight an empty card. A chat with no turn yet is still offered in the notes menu, but it no longer makes the sidebar scroll to and highlight a card that has nothing to click.
  • P3: the menu showed "Done" for an agent the sidebar showed as "Failed". The menu now uses the sidebar's status function. The same mismatch already affected terminal rows (since fix(agent-status): report a stale pane that still holds a PTY as unverifiable, not idle #18012), and they are corrected too.
  • The PR description now labels "delivery only while the chat is open" as a temporary difference and names its follow-up. It also drops a listed weakness that turned out not to exist: the chat title does already match the tab strip.
  • Merged current main. CI's earlier typecheck failure was inherited from main and fixed there by test: stop main failing on three tests the store and close-cause changes crossed #24231.

Deferred (not in this PR)

  • P2, existed before this PR (found in QA): a terminal whose title still reads "✳ Claude Code" after the agent has gone, or whose title was set by hand, is listed as an idle Claude. Sending notes to it pastes them into the shell, and each line runs as a command. This PR doesn't touch that code. It needs its own fix, because a note containing a real command would run.
  • P3: when storage is full, the failure notice says the agent "did not accept the notes (session-outbox-unsaved)" instead of saying storage is full.
  • P3: "Notes sent." means queued in the chat, the same as the composer. The PR description lists this as a known weakness.
  • P3, existed before this PR: a chat's saved message queue is never deleted when its worktree is removed.
  • Follow-up: send a chat's queued messages without needing the chat view mounted. The new store this PR adds is the prerequisite.
  • Nits (naming, redundant checks, test gaps) are in the review ledger.

What was verified

  • Review: two rounds. Round 1 had separate reviewers for the message-queue change and the send targets and a design review; round 2 reviewed only the fixes. The design review concluded the change should land as one PR with this design: moving the chat's queue into a store is needed, not just tidier, because on main a message added from outside the chat view is silently dropped. A separate check found that one chat can't be open in two tabs at once, and the host ignores a repeat send of the same message anyway. The readiness checklist passed with no P0 to P2.
  • Live QA on the M4Air at b06911ea78c, on a dev build with its own home folder and profile and stand-in agent programs. It ran on a Claude agent because Grok's usage balance was used up. Everything passed: chats listed in all three menus, notes delivered to a chat, a failed send's notice clearing on its own, a brand-new chat, terminal sends, the chat's own composer, launching a new chat with notes, and nothing resent after a restart. Screenshots are embedded in the PR description.
  • Automated: web and main-process typechecks pass. 80 affected test files (717 tests) pass, plus 25 tests in 3 newly matching files from main. CI on 8495369f898: 19 passed, 14 skipped, 0 failed.

Not verified

  • A real agent's reply; QA used stand-in agents only.
  • The menu status fix live; it landed after the QA run and is covered by unit tests only.
  • A failed send to a terminal agent live; the chat path exercised the same notice code.
  • Clicking an agent row in the sidebar while the notes menu is open. That is blocked by an existing bug where the menu closes before the click lands, and it is out of scope here.
  • Delivery to a chat whose view isn't mounted; unit tests only. No send surface reaches that case today.

@brennanb2025
brennanb2025 merged commit 6729f1b into main Oct 1, 2026
33 checks passed
brennanb2025 added a commit that referenced this pull request Oct 1, 2026
…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.
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.

1 participant