Skip to content

refactor(orchestration): one function for six agent-to-agent sends - #24901

Merged
brennanb2025 merged 8 commits into
mainfrom
brennanb2025/agent-send-one-path
Oct 3, 2026
Merged

brennanb2025 merged 8 commits into
mainfrom
brennanb2025/agent-send-one-path

Conversation

@brennanb2025

@brennanb2025 brennanb2025 commented Oct 2, 2026 •

Copy link
Copy Markdown
Contributor
Files Added Deleted Net
Test 6 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​609 $\color{#cf222e}{\Huge{\mathbf{−}}}$​25 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​584
Prod 11 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​325 $\color{#cf222e}{\Huge{\mathbf{−}}}$​173 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​152

ELI5

Agents in Orca send each other messages: a coordinator agent hands a worker agent its task, and agents leave each other mail. Before this PR, six different pieces of code each sent those messages their own way. A few other agent-to-agent senders still do; they stay where they are for now and are listed, with the step that moves them, under "What is not moved yet".

Two of the six send into a chat-style agent session: the code that delivers mail to a chat agent, and the code that gives a chat worker its task. Each had its own copy of "send the message, wait until the agent has actually taken it or turned it down, then report which". The other four type a worker's task into a terminal running an agent: assigning a task to a running worker, starting a worker, the coordinator's automatic task loop, and a worker running on another machine. Each called the terminal-typing code directly.

That blocks the next steps. A message you type into a busy chat waits in the chat's queue and goes out when the agent finishes its current turn (the work it is doing in reply to the last message); a message from another agent never waits, it goes in at once and joins the turn in progress. Nothing records which agent sent a message either, so the chat shows it as if you had typed it. Fixing either means changing every copy of the send, and separate copies drift apart.

This PR moves those six onto one function, sendAgentTurn, and changes nothing about how any message is sent.

What this changes for you

Nothing yet. This is step 1 of 4.

Before After
Another agent messages a busy chat Handed over at once; joins the running turn Same
A coordinator sends a worker its task (chat or terminal) Sent at once Same: same wait, same errors
You type into a busy chat Waits in the chat's queue if queueing is on Same, byte for byte
Saved data, messages between apps, UI — No change

The plan: A (this PR) one send function. B record who sent each message and show it. C agent messages go through the chat's existing queue, so a busy chat holds them as a visible queued message, like yours. D an explicit "send now" option, and clicking a message's sender opens that agent.

What Changed

A few words used below:

  • Host: the part of Orca that runs a chat session and accepts messages into it.
  • Request: what a sender gives the host for one message: the text, the chat's id, a message id that stays the same if the send is retried, and a fingerprint (a hash of what is being sent) the host uses to tell a retry of the same message from a different message under the same id.
  • Queued message: a message a busy chat holds until the agent's turn ends. When the turn ends, the queue sends it as a new message with an id of its own (the queue's "hand-off").

One function, one argument. sendAgentTurn in src/main/runtime/orchestration/send-agent-turn.ts takes one argument that names the target and the message together, so a message meant for a chat can never be sent to a terminal or the other way round:

  • A chat: { kind: 'structured-session', host, sessionId, callerKey, turn: { body, delivery, operationId, expectedRuntimeFence } }. It sends through the host's own send, the same path your typed message takes, queue decision included. If the host answers "not taken yet" (pending), it waits for the final answer with the same time limit the two old copies used (ORCHESTRATION_READINESS_TIMEOUT_MS), and keeps the first answer if that wait fails or runs out. It returns refused, queued (with the host's report of where the message sits in the queue) or sent (with the host's record of the message).
  • A terminal: { kind: 'terminal', runtime, handle, turn: { purpose: 'dispatch-preamble', body, operationId } }. purpose says what kind of text this is, which decides how it is typed. The only kind today is a worker's task message, typed with the same options (dispatchPreambleSendOptions(operationId)) all four terminal senders used before. Any other kind of terminal message will need a purpose of its own rather than borrowing the task message's options.

Each sender still reads the result its own way, with the same outcome as before: the chat mail code maps it to accepted / rejected / unknown / unattached, the chat worker's task keeps its dispatch_preamble_undelivered and operation_unknown errors, and the terminal senders get the terminal code's own result back unchanged.

delivery: 'queue' | 'now'. Every sender passes 'now', which sends no delivery field to the host, exactly as before. 'queue' (for step C) asks the host to hold the message in the queue while the agent is busy, as your typed messages are with queueing on.

One request builder. The request and its fingerprint are now built inside sendAgentTurn, from exactly the fields it sends, by a new shared builder, src/shared/structured-agent-session-send-mutation.ts. Before, senders computed a fingerprint over the text only, which the host refuses for a 'queue' send because it fingerprints the delivery choice too. The chat's own outgoing-message code (structuredAgentSessionSendMutation in src/shared/structured-agent-session-outbox.ts) now calls the same builder, and so does agent.launch, which already went through that function. What your typed messages send is identical to before: the builder is that code moved, not rewritten.

Unused code removed. The chat mail code computed its own fingerprint (structuredPointerPayloadFingerprint) and passed it and the text through structured-pointer-operation-id.ts and structured-mailbox-pointer-delivery.ts only to copy it into the request. It never decided anything: whether a retry reuses its message id is decided by which batch of mail it stands for. Both are gone, and the fingerprint the host receives is the same value.

A retried queued message waits for the right thing. If a 'queue' message is retried after the queue already sent it, the host answers with the queue's hand-off, which has its own id. sendAgentTurn now waits on the hand-off's id. For a 'now' send the two ids are always the same, so nothing any sender does today changes.

A guard against new copies. send-agent-turn-boundary.test.ts scans the shipped src/main source and fails when a file not on its list:

  • types an agent prompt into a terminal (sendTerminalAgentPrompt) or writes raw text into a terminal (sendTerminal);
  • calls a chat host's send directly, or sendStructuredAgentSessionTurn;
  • waits for a sent message's final answer itself (waitForSendSettlement);
  • calls agent.launch's prompt helpers, or the terminal mail writer.

It finds a host by name: a receiver whose name ends in host or Host, including a call such as requireInstalledHost(), (await runtime.ensureStructuredAgentSessionHost()), host! or (host as X). It does not catch a host reached under another name (const h = host, hostFor(id), sessions.get(id)!) or a pulled-out method (const { send } = host). Each file still allowed is listed with its reason, and a self-test checks the patterns against planted lines.

What is not moved yet

Sender Where Label Why
Your own typed message (agentSession.send) structured-agent-session-send-compatibility.ts intended It is your send, and the host path sendAgentTurn itself sits on. How long it waits depends on the app version that sent it.
Orca's message that resumes a chat after a restart structured-agent-session-restart-continuation.ts, …-restart-resume-wiring.ts intended Orca's own message after a restart, not one agent messaging another. It waits in two separate steps: first for the agent to receive it, then for the final answer.
/compact structured-conversation-compaction.ts intended A command, not a message.
Claude agent teams' tmux send-keys claude-agent-teams-tmux-dispatcher.ts intended Keystrokes the Claude CLI itself sends to its teammates' panes. Orca relays them and is not the sender.
agent.launch into a new chat agent-launch-structured-prompt.ts temporary, follow-up B The first turn of the chat that launch just created, so nothing can queue ahead of it and the send is right as is. It still needs the sender, which B adds.
agent.launch into a terminal agent-launch-terminal-prompt.ts temporary, follow-up B With reuseTerminal it types into an agent that is already running, which is an ordinary agent message. It needs a terminal purpose of its own and the sender.
orca terminal send --enter terminal-send-method.ts temporary, follow-up B Agents use it to message other agents. It has its own checks before typing, its own wait for the agent to accept the text, and its own record of what was sent, so moving it needs a terminal purpose of its own.
Terminal mail notice ("you have new mail") writeOrchestrationPointerPty / …WithSettlement temporary, follow-up C It types the text, then presses Enter as a separate, checked step and records each attempt, which the terminal-typing code above does not do. Moving it now would change how it writes.

Why

The goal is one function for "send a message to an agent", built only from the send path your own message already takes, so that queueing (C) and the sender's name (B) are each added once. This follows the common pattern: one send function on top of the host's own send, with the host deciding whether a message queues or goes now.

Alternatives considered: keeping the six copies and changing each in C and B, which is what would drift; and a new sender just for agent messages with its own queue, which would duplicate the chat's existing, tested queue.

Linked Issue

None. Maintainer change, step A of the agent-messaging plan above.

Visual Proof

N/A. No visible change: every message is sent exactly as before, and no UI changed.

Testing

  • I manually tested these changes locally
  • Automated tests added/updated, or explained why not below

New tests:

  • send-agent-turn.test.ts: 'now' sends no delivery field; a pending answer is waited out through the host's own wait with the same time limit; a failed or expired wait keeps the first answer; a refusal is returned; 'queue' asks for queue-if-active with the fingerprint the host computes; a retried queued message keeps its reported state; a terminal message is typed with the task-message options and returns or throws exactly what the terminal code does.
  • send-agent-turn-host.test.ts, against the real host and its storage, so every request must pass the host's own checks: a 'queue' message to a busy chat is held in the queue; retrying it returns the earlier answer instead of being refused; 'now' and 'queue' to an idle chat are sent; 'now' to a busy chat joins the turn in progress and never the queue; a retried 'queue' message the queue already sent waits for the hand-off's final answer. With the old text-only fingerprint all four 'queue' cases fail; with the old wait id the last one fails.
  • send-agent-turn-boundary.test.ts: the guard above.

Existing tests edited:

  • structured-mailbox-pointer-host.test.ts: no longer passes the removed fingerprint; adds a case that a queued answer reads as unknown, as before.
  • orchestration-structured-worker-session.test.ts: adds a case that a queued answer gives operation_unknown, as before.
  • structured-pointer-operation-id.test.ts: drops the text input and the fingerprint checks of the removed code.

Run locally: tc:node and tc:cli typechecks; the tests above plus the moved senders' existing tests (task assignment, coordinator, federation, worker start, chat worker, chat mail) and the shared and renderer outgoing-message tests (53 files, 519 tests); full oxlint, anti-slop and the changed-lines quality gate. Not run locally: the suites that test old and new app versions talking to each other. No bytes sent between apps change, and CI runs them.

Review

Agent skill upstream boundary

  • Not applicable, or this change follows docs/reference/agent-skill-sharing-upstream-boundary.md and copies or mechanically translates no upstream skill-installer source, tests, fixtures, registry entries, path tables, comments, or documentation.

Notes

  • Security: no new way in; the host's own checks still decide every send.
  • Cross-platform, SSH and federation: a terminal message is still typed by the worker machine's own Orca; SSH, WSL and remote terminal handling sit inside that code and are untouched.
  • Mobile and older app versions: what a typed message sends is unchanged, so mixed versions see no difference.
  • Performance: the chat mail and chat worker task fingerprints now use the shared JavaScript hash your typed messages already used (a reviewer measured about 0.1 ms for a 20 KB message); its output is identical.

Checklist

  • This PR is small and focused
  • I explained what changed and why (ELI5, the user-facing before/after, the mechanism, and why over the alternatives)
  • Before/after screenshots or videos attached for UI changes, or N/A with reason
  • Self-reviewed for correctness, security, and performance
  • Cross-platform, SSH/remote, and path/shortcut impact considered (or N/A)
  • pnpm lint, pnpm typecheck, pnpm test, and pnpm build pass (or CI will cover; local preferred)

…e sendAgentTurn

The structured mail-pointer lane and the structured worker preamble each carried a copy of
"send, wait out a pending start, read the verdict", and four dispatch-preamble sites typed into
a terminal directly. They now share sendAgentTurn, built from host.send, the host's settlement
waiter and sendTerminalAgentPrompt. Every caller passes delivery 'now', so nothing sends
differently; a source-scan ratchet keeps new direct sends out.

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

✅ No new issues found.

Reviewed changes

  • One send path (send-agent-turn.ts) — sendAgentTurn centralizes the agent-to-agent send for structured chats (host.send + optional waitForSendSettlement with the readiness budget, first answer kept on a failed/expired wait) and for terminals (sendTerminalAgentPrompt with dispatchPreambleSendOptions), returning refused | queued | sent.
  • Six callers migrated — the structured mail-pointer lane, structured worker preamble, dispatch --inject, PTY worker delivery, the coordinator loop, and the federated worker host now route through it; each keeps its own reading of the outcome.
  • delivery option — now sends no delivery field (byte-identical to before); queue maps to queue-if-active, unit-tested but unused in this PR.
  • Two tests — send-agent-turn.test.ts covers the send/wait/refusal/queue/terminal paths, and send-agent-turn-boundary.test.ts is a source-scan ratchet pinning the sendAgentTurn, sendTerminalAgentPrompt, and waitForSendSettlement allowlists.

I traced each migrated caller against the removed code and confirmed the outcomes are unchanged: the two structured callers never send delivery, so the new queued early-return cannot alter their unknown / operation_unknown mapping, and the four terminal callers passed exactly dispatchPreambleSendOptions(operationId) before and after. The terminal runtime type deliberately uses method syntax (bivariance) so the wider RuntimeAgentPromptWriteOptions runtime remains assignable; only the narrow options object is ever passed.

Locally the two new tests pass (10 tests) and the affected suites pass (orchestration-structured-worker-session, coordinator, federation, tasks-dispatch, composed-workers — 107 tests).

Pullfrog  | Fix it ➔ | View workflow run | Using deepseek-v4.1-flash (free via Pullfrog for OSS) | 𝕏

@coderabbitai

coderabbitai Bot commented Oct 2, 2026 •

Copy link
Copy Markdown
Contributor

Review in Change Stack →

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

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration
  • Configuration used: Repository UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 72a1781a-075c-47ed-92ef-5256644682a6
📥 Commits

Reviewing files that changed from the base of the PR and between 512b9fd and 2b49dbd.

📒 Files selected for processing (3)
  • src/main/runtime/orchestration/send-agent-turn-boundary.test.ts
  • src/main/runtime/orchestration/send-agent-turn-host.test.ts
  • src/main/runtime/orchestration/send-agent-turn.ts

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 7 remain after this review.


📝 Walkthrough

Walkthrough

The change adds sendAgentTurn for terminal and structured-session sends. Structured-session callers use it for mailbox-pointer messages and worker preambles. Terminal dispatch callers use it to send preambles with an operation ID and purpose-derived options. Structured pointer operation reuse now uses session and message IDs instead of a body fingerprint. Tests cover send outcomes, settlement behavior, terminal receipts, and source-call boundaries.

Priority: ⬇️ Low

Merge Risk: ⚪ Minimal · up to 2b49d

No actionable merge-blocking issue was established; the change is mergeable after normal checks.

Security Architecture Review

Security architecture risk: 🔵 Low · up to 2b49d

The inspected delivery paths retain their existing destinations, identity checks, and delivery settings. No introduced security issue was identified, but interruption and recovery behavior is not fully established.

Retained concerns
No architecture-level concerns identified.

Security review details

Security Blast Radius

  • inferred — For the compared callers, message content continues to reach the same selected structured session or terminal, including federated worker delivery. Routing through the helper does not itself grant a broader target scope or additional execution authority.

Trust Boundaries and Controls

  • observed — The helper forwards structured caller keys and runtime fences rather than replacing host admission. The worker retains its durable-record precondition, and terminal callers retain the existing primitive and request-correlated options. These are preserved controls, not a complete verification of upstream authorization.

Resilience and Maintainability Implications

  • observed — Inspected host-test source asserts that replaying a queued operation does not create a second draft and that settlement follows the handoff submission identity. Combined with conservative pending fallback, this supports preserved duplicate-send and acknowledgement containment in the exercised flows; it does not establish complete crash recovery.
🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 40.91% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 22 functions across 15 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
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.
Title check ✅ Passed The title clearly summarizes the main change: centralizing six agent-to-agent sends in one function. It is concise and specific.
Description check ✅ Passed The description is detailed and covers the required explanation, changes, rationale, testing, visual proof, and checklist. The linked-issue section explains that this is a maintainer change, which mat…
  • Fix all pre-merge checks with AI
✨ 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.

…and pair target with turn

A `queue` send was refused by a real host: callers supplied a fingerprint over the body alone
while the host digests body and delivery. sendAgentTurn now builds the envelope with the
composer's own builder (extracted to structured-agent-session-send-mutation), so the fingerprint
is always over exactly the fields sent; `now` sends keep the identical digest. The pointer lane
no longer carries a fingerprint it cannot get right.

sendAgentTurn takes one argument, a union on kind that carries its own target and turn, resolved
by an exhaustive switch; the terminal turn names its purpose (only the dispatch preamble today)
instead of every terminal send inheriting the task lead line. A queued outcome keeps the host's
draft receipt, and both structured callers read outcomes exhaustively with unchanged behaviour.

The boundary test now also fences direct structured host sends, catches optional, bracket and
bound member uses, has a planted-offender self-test, and pins the unmoved terminal mail pointer
and agent-teams tmux senders.

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

✅ No new issues found.

Reviewed changes

Re-reviewed the three commits since the prior pullfrog review (8675772): 1ea47ca refines the single-send path, bd267515 is the origin/main merge, and 512b9fdc is a formatting/max-lines fix. Behavior stays as intended.

  • Fingerprint derived inside sendAgentTurn — the composer's envelope builder is extracted into structured-agent-session-send-mutation.ts, and sendAgentTurn now builds the send envelope itself, so a queue send digests delivery exactly as the host does (the earlier callers fingerprinted the body alone, which a real host refused).
  • One argument, discriminated on kind — sendAgentTurn takes a single union carrying its own target and turn, resolved by an exhaustive switch; a terminal turn names its purpose, so only a dispatch preamble gets the coordinator's task lead line.
  • queued outcome keeps the draft receipt — both structured callers read the outcome exhaustively with unchanged mapping (unknown for the mail lane, operation_unknown for the worker preamble).
  • Pointer lane simplified — payloadFingerprint is gone from the pointer send input and structuredPointerPayloadFingerprint is removed, since the shared builder derives it.
  • Tests strengthened — send-agent-turn-host.test.ts exercises the real host (queue held as a draft, retry replay, idle now/queue settle); queued-answer arms were added to the pointer-host and worker-session suites; the source-scan ratchet now fences structured host sends and optional/bracket/bound member uses with a planted-offender self-test.
  • 512b9fdc only inlines the buildDispatchPreamble call in federation.ts to stay under the max-lines gate and adopts the prefer-template fix in the ratchet.

I traced the shipped now sends to confirm they produce the byte-identical fingerprint they did before (the builder's fields are unchanged when delivery is absent), and ran the delta's tests: send-agent-turn, send-agent-turn-host, send-agent-turn-boundary, structured-mailbox-pointer-host, structured-pointer-operation-id, structured-agent-session-outbox.queue-delivery, and the worker-session suite. All pass except one pre-existing, unrelated test in the worker-session suite (registers the identity BEFORE the session is created) that fails with AppEnvironment not initialized on this local runner and is untouched by this PR.

Pullfrog  | View workflow run | Using deepseek-v4.1-flash (free via Pullfrog for OSS) | 𝕏

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

✅ No new issues found.

Reviewed changes

Re-reviewed the three commits since the prior pullfrog review (512b9fdc). They fix the settlement id used when a replayed queue turn was already handed off, add the real-host test that catches it, and widen the send-boundary ratchet. Behavior of the shipped now sends is unchanged.

  • Settlement wait keys on the submission's id — sendAgentTurn waits on answered.clientMessageId instead of the send's operationId. A replayed queue turn whose draft already handed off answers with a submission under the fresh hand-off id, so the old argument missed the journal entry, rejected as missing, and kept the first pending answer. Shipped now sends are unaffected because both ids are equal there.
  • Real-host regression test — 4bc2680 re-plays a queue send after its draft went out, records the id passed to waitForSendSettlement, and asserts the replay stays unsettled until the hand-off is accepted. I verified it fails without the fix.
  • Ratchet widened — the boundary scan now covers HOST_RECEIVER caller shapes (requireInstalledHost(), casts, non-null assertions), raw sendTerminal writes, and the agent.launch prompt helpers, and drops the now-redundant tmuxSendKeysText pin.

I ran the three touched suites (send-agent-turn, send-agent-turn-host, send-agent-turn-boundary): 22 pass.

Pullfrog  | View workflow run | Using deepseek-v4.1-flash (free via Pullfrog for OSS) | 𝕏

@brennanb2025 brennanb2025 changed the title refactor(orchestration): one shared function sends every agent-to-agent message refactor(orchestration): one function for six agent-to-agent sends Oct 3, 2026
@brennanb2025

Copy link
Copy Markdown
Contributor Author

Review status: ready for a human look (head 2b49dbd5750)

The problem. Six places in Orca send one agent's message into another agent, a worker's task or a "you have mail" notice, and each had its own copy of "send it, wait until the agent takes it, report the result". The two planned next steps can't be built on six copies: agent messages waiting in a busy chat's queue like a typed message does, and showing who sent each message.

What changes for you. Nothing visible. This is step 1 of 4: those six senders now share one function, sendAgentTurn, and every message goes out exactly as before.

Fixed during review

  • The queue option the PR prepares for step 3 was refused by the real chat host on every send, because the message fingerprint covered the text only. The fingerprint is now built inside the function from exactly what is sent, using the same builder your typed messages use (byte-identical to before). A new test against the real host proves it.
  • A retried queued message waited on the wrong id and returned early. It now waits on the id the host actually sent.
  • The function now takes one argument pairing the target with the message, so a chat message can't be sent to a terminal and the other way round. A terminal message also names its kind.
  • The guard test that keeps new code on the shared function now also catches direct chat sends in more forms and raw terminal writes. It labels each sender left out as intended or temporary.
  • The PR description was rewritten: it leads with the problem, uses no internal shorthand, and lists the unmoved senders with their follow-up step.

Deferred

  • Nits: comment wording, a redundant field in one result shape.
  • The guard test compares against full file lists, so two unrelated PRs that each add a matching call can both pass and turn main red together. That is maintenance friction, not a bug.
  • For step 3: the chat history code computes a message's fingerprint from the text alone, while queued messages are stored with a fingerprint that also covers the delivery mode. So the two may not match for queued messages (pre-existing, not verified). A returned "sent" result may also be a live object rather than a snapshot.
  • CI gap (separate PR): the job selector doesn't run the cross-version suites when the shared message builder or the orchestration code changes. It skipped them here.

Verified

  • Two review rounds plus a narrow check of the fixes, and a readiness checklist. No P0-P2 issues remain.

  • Typecheck (node, cli), 53 targeted test files (519 tests), full lint. CI is green.

  • All 13 cross-version test files pass locally, run one at a time.

  • Live QA on a separate Mac with a dev build of this branch, driven by Grok:

    Scenario Result
    Task sent to a terminal worker Pass: typed and submitted once, the agent replied, task completed
    orchestration dispatch --inject into the same terminal Pass: exactly one new message
    Task sent to a chat worker Pass: one message, still one after 60 s, the agent replied, no error notice
    Mail to an idle chat worker Pass: exactly one "You have 1 orchestration message" notice, the agent read the mail and replied
    Mail to a chat worker that is busy, in a turn that never checks mail Pass: no notice during the turn, exactly one 56 ms after it ended, stable for 60 s

    Terminal worker gets its task once and completes
    dispatch --inject into the same terminal
    Chat worker gets one task message and replies
    Mail notice arrives once, after the busy turn ends

Not verified live: the automatic coordinator loop (the CLI no longer starts it) and federation (it needs a second server). The tests cover both, and line-by-line review against main found them identical.

@brennanb2025
brennanb2025 merged commit 0c4e26e into main Oct 3, 2026
34 checks passed
nwparker added a commit that referenced this pull request Oct 4, 2026
* fix: preserve registered account credentials after enrollment errors

* refactor(orchestration): one function for six agent-to-agent sends (#24901)

* refactor(orchestration): send every agent-to-agent message through one sendAgentTurn

The structured mail-pointer lane and the structured worker preamble each carried a copy of
"send, wait out a pending start, read the verdict", and four dispatch-preamble sites typed into
a terminal directly. They now share sendAgentTurn, built from host.send, the host's settlement
waiter and sendTerminalAgentPrompt. Every caller passes delivery 'now', so nothing sends
differently; a source-scan ratchet keeps new direct sends out.

* test(orchestration): the refusal fixture uses a real wire refusal code

* fix(orchestration): derive the send fingerprint inside sendAgentTurn and pair target with turn

A `queue` send was refused by a real host: callers supplied a fingerprint over the body alone
while the host digests body and delivery. sendAgentTurn now builds the envelope with the
composer's own builder (extracted to structured-agent-session-send-mutation), so the fingerprint
is always over exactly the fields sent; `now` sends keep the identical digest. The pointer lane
no longer carries a fingerprint it cannot get right.

sendAgentTurn takes one argument, a union on kind that carries its own target and turn, resolved
by an exhaustive switch; the terminal turn names its purpose (only the dispatch preamble today)
instead of every terminal send inheriting the task lead line. A queued outcome keeps the host's
draft receipt, and both structured callers read outcomes exhaustively with unchanged behaviour.

The boundary test now also fences direct structured host sends, catches optional, bracket and
bound member uses, has a planted-offender self-test, and pins the unmoved terminal mail pointer
and agent-teams tmux senders.

* fix(orchestration): keep federation.ts under max-lines and satisfy prefer-template in the send ratchet

* fix(orchestration): wait on the answered submission's id when a replayed queue turn was already handed off

* test(orchestration): pin that a replayed queue turn waits for its hand-off to settle

* test(orchestration): fence call-result and cast host sends, raw terminal writes and the launch-prompt helpers

* feat(native-chat): a Claude subagent waiting on a permission prompt reads as waiting (#22634)

* feat(native-chat): a Claude subagent waiting on a permission prompt reads as waiting

A subagent's permission request reaches the parent session's callback naming the
subagent that asked (agent_id) and the tool call it gates (tool_use_id). The
pending request is recorded with the asking agent. On every drain the child-work
producer re-derives which children a pending request blocks and hands that set
to the Claude child decoder, the one owner of each child's live edges: a blocked
child reads waiting on every live edge it reports, and a child that starts or
stops waiting is a live edge of its own. Answering, denying or cancelling the
request returns the child to its prior live state; nothing is stored beyond the
pending requests.

A live task_updated carrying an error now reaches the record as the child's last
message, without an ending or a new state.

The replay test drives a scrubbed capture of the real CLI (foreground allow,
deny, interrupt, background allow, and the main agent's own request) through the
real adapter into the host's child records.

* test(native-chat): a subagent's request names it before its tool call is read

* docs(agent-status): a subagent asking for approval waits in every lane; the parent row keeps the session's own attention

* test(native-chat): hand canUseTool the asking agent without widening the helper's cast

* test(native-chat): an interrupted Claude subagent settles cancelled, not failed

A captured interrupt shows the spawn call's error result ("The user doesn't want
to proceed…") arriving before the subagent's own `task_updated {status: killed}`.
The spawn result ends nothing (the child ends only on its own terminal frame), so
the child stays live until its `killed` status settles it cancelled. A genuine
failure, captured with the subagent on a model that does not exist, sends its
`failed` status before the error result and still ends failed. Both captures now
replay through the real adapter into the host's records.

* fix(native-chat): a Claude subagent's prompt makes the parent row wait, not block

A subagent's pending prompt made the whole session `attention`, which reads as
the main agent's own `blocked` and outranks the fold's waiting arm, so the
parent row read blocked where a CLI Claude parent reads waiting. The main
agent's state now reads only its own pending prompts.

- A Claude prompt row carries the linkage of the agent that raised it: the one
  the permission request names, or the owner of the tool call it gates. The
  same join decides which child reads waiting, so the two cannot disagree.
- The status summary projects the session's own status from root prompts only;
  every other reader (delivery gates, teardown, restart) still asks whether
  anyone is waiting on a human.
- An answer keeps the prompt row's linkage by the journal's own rule: a
  revision that names no producer keeps the row's existing one.
- The child-tool queries gain the prompt's producer, so a prompt row and a
  child record answer "which agent" from the same join.

* test(native-chat): say which ids the permission capture scrubs and which are its own

* fix(native-chat): the status clock dates attention by the session's own asks only

The session's status is now `attention` only for its own pending prompt, so the
clock's fallback to a subagent's ask could no longer be reached, and it read the
journal by a different rule than the status it dates. Both now read root prompts.

The journal also stamps a Codex subagent's prompt with its thread (#22532), so a
Codex child's approval is that child's wait in the Codex lane too. Two tests
written for the earlier rule are updated: a subagent's ask leaves a running
session `working` on its turn's clock, and a Codex child's answered approval
leaves the settled parent's Activity row done with nothing unread.

* fix(native-chat): a completion still says the user is asked when a subagent asks

The turn-completion feed marked a completion `awaitingUser` from the status
summary's `attention`. The status now means the session's own agent is waiting,
so a subagent's pending approval stopped reaching the completion. The projection
now also says whether anyone is waiting on the user, as the delivery gates,
teardown and restart ask it, and the completion reads that.

The waiting-subagent replay answers its prompt with the adapter's current
response shape.

* revert(native-chat): a live Claude task's error stays out of the child's last message

No capture shows a live task_updated carrying an error, and it is unrelated to
a subagent waiting on a permission request; it leaves this PR.

* test(native-chat): settle the Claude session's startup before replaying a subagent's request

A startup frame drained child work during the first await, so answering a
request freed the child even with the answer's own republish removed.

* fix(native-chat): a Claude subagent's prompt row names it as its other rows do

The prompt row stamped only the asking agent's id, so a nested subagent's
request lost the agent that spawned it, its spawn call and its run. It now takes
the linkage the asker's own rows take: the gated tool call's, when that names the
same agent, else the one resolved through the agent's spawn call. The provider's
agent id stays the asker's id.

* fix(native-chat): a subagent's request makes the parent row wait without a child record

The parent row learned that a subagent needed the user only from that
subagent's child record, so a request no record carried (a Codex child the host
never registered, a Claude task past the live cap) left the row working or done
while the approval card sat in the chat.

"Someone in this session must answer" is now one derived session fact. The
projection names two facts instead of a mode flag: the main agent's own status
(attention only for its own request) and structuredAgentSessionAwaitsUser (any
pending prompt). The status summary publishes the second as an optional
awaitsUser, and the shared fold reads it: the main agent's own ask is blocked,
otherwise awaitsUser or a waiting child record makes the row wait. Every caller
picks the fact it means: the completion edge's awaitingUser and the delivery
gate read awaitsUser; the quit snapshot folds the same two inputs the sidebar
does.

* fix(native-chat): a client that predates awaitsUser still reads a subagent's request as attention

A status summary's status is now the main agent's own, so a client built before
the split would read a subagent's request as working (or idle) and fold it with
code that has no awaitsUser input. Clients advertise
agent-session.status-awaits-user.v1; at agentSession.subscribeStatus the host
sends any client that does not the pre-split summary: attention whenever
awaitsUser is set, without the main agent's own tool line, verdict and clock.
The feed and every in-process reader keep the canonical summary. Transitional,
like the turn-item downgrade.

* test(native-chat): a Codex subagent's approval makes its settled parent's Activity row wait

The test pinned the parent row done while a Codex child asked, through a harness
that fed no child records, so it proved nothing about the ask. It now drives the
ask twice through the real host status store: with no child record (the
session's awaitsUser alone) and with the child's own record waiting from
thread/status/changed. Both read waiting with needsAttention while the ask is
open, then done with nothing unread.

* docs(agent-status): a subagent's request reaches the parent row through awaitsUser in every structured lane

The store reference said a Codex child's request still read as the main agent's
blocked and that only the Codex hook lane fed a waiting child. Both structured
lanes stamp the asking child and feed child records, and awaitsUser carries the
request when no record does. The liveness comment goes back to main's: a child's
blocked is a failed task on an older host's legacy rows.

* fix(native-chat): the restart dialog still headlines a subagent's pending approval

The quit snapshot now records the main agent's own state, so a subagent asking
while the main agent worked recorded `working` and the dialog said "Was
mid-reply" where it used to say "Waiting for your approval". The headline now
comes from the snapshot's pending prompt, whoever raised it, with the existing
copy; `state` stays the main agent's own.

* test(orchestration): a subagent's pending approval holds structured mail delivery

Scoping the delivery gate to the main agent's own request left every gate test
green; a subagent's request now has its own case.

* fix(native-chat): a subagent's request is dated by when it was raised, on every client

Since the summary's clock became the main agent's own, nothing dated a wait
that only a subagent's request held: a pre-split client was sent attention with
no clock, where the old host dated it by the subagent's prompt, and a new
client's waiting row fell back to the time it first saw it, so after a reload a
request the user had already read could read unread again.

The session fact is now when someone started being asked: awaitsUserSince, the
oldest pending prompt whoever raised it, and its presence is what awaitsUser
meant. A row waiting on someone else's request takes that as its clock; the
downgrade for a client without the capability dates its attention by it, which
is what the old host published. A cross-version test pinned to the last
pre-split release runs the same journals through that release's projection and
through this one plus the downgrade, and compares the whole summary. The Codex
end-to-end test also reads the host's own status row, and keeps a read ask read
through a later row and a reload.

* test(native-chat): the pre-split parity check compares only the fields the split owns

An additive summary field is safe for old clients, so comparing whole summaries
against the pinned release would redden on one. The wire comment now says how
the downgrade dates attention: the main agent's own oldest ask, else
awaitsUserSince.

* test(runtime): an aged host-held working summary states that nobody is asked

The test built its working summary by overriding the status of a published
approval summary, which still carried awaitsUserSince, so the row correctly
read waiting. It now drops the request as its scenario says.

* fix(native-chat): the chat's subagent block says waiting when the strip does

While a Claude subagent's request was open, the sidebar and the composer strip
read waiting but the subagent block in the chat history a few pixels above
still read "Kicked off 1 subagent working": it shows the journal's roster
state, and the journal records no wait.

The structured chat now hands its transcript the subagents the strip shows
waiting, read from the host's child records through the strip's own row model
and matched by the provider id the roster names each one by. A running entry
the host says is waiting reads waiting in the group row, its entry and its
section head, with the strip's word and the question colour; it reads the
journal's state again as soon as the host stops reporting the wait.

* fix(native-chat): a collapsed subagent group shows a wait beside a failed sibling

A failed sibling took the group row's one alert slot, so a group with a waiting,
a working and a failed child read "1 working +1 failed" and hid the wait; it
now reads "1 working +1 waiting +1 failed". The waiting set keeps its identity
while a child frame changes no wait, so the transcript's subagent rows do not
re-render on every frame, and the test of a wait ending now updates one mounted
row instead of remounting it.

* refactor(claude): one needs-input state on the parent; the asking subagent alone reads waiting

Drop the split of the main agent's own status from a session-wide "someone must
answer" fact: awaitsUserSince, the agent-session.status-awaits-user.v1
capability and its old-client downgrade, and every reader change that only
consumed them (fold, equality, ingest, delivery gate, turn-completion feed,
quit snapshot, resume headline, status clock, status bridge, attention
dispatch) go back to main. The parent row again reads one needs-input state
for a pending request whoever asked, dated as before.

Kept: a request's owner recorded once on its prompt row with full producer
linkage; the asking subagent's own record reads waiting, re-derived on every
update; the chat history's subagent block reads that same state; an answered
subagent request stays in its subagent's group.

A subagent now waits only on a request the user can still answer (its card
open, no answer underway), and the adapter frees it before the host records an
answer or dismissal. So a waiting child record always sits beside the pending
card, and main's fold never reads the parent as waiting on it: no window after
an answer, and no ~3 s wait after a card dismissed by Stop.

* fix(claude): a subagent waits only beside its committed card

A subagent's wait was pushed to the host as soon as its request arrived,
while the request's card row reached the journal at least a microtask later.
So every subagent request published the parent row as waiting before
blocked (the main agent's own fold reads a waiting child that way), and
Activity got an extra unread "waiting" event that main never shows.

The card is now the one record of an open request. The translator records
the asker on the card once (its row's linkage) and counts the card open only
after the sink confirms its rows landed, then publishes the wait; anything
that closes the card (an answer underway, a dismissal handed to the host,
Claude's own withdrawal, the session's end) frees the subagent first. So
every publish that shows a subagent waiting also shows its pending card, and
the parent reads one needs-input state, exactly as on main.

This retires the registry's view of pending requests (unclaimed(), the
asking-child join) and the translator's holdsOpen. The prompt row's linkage
takes one rule: the agent the provider names, else the gated call's owner.

The parent-row proof now runs through the real deferred sink, durable
journal and status feed, publishing as production does, and checks at every
publish that waiting subagents have pending cards and that the parent row
matches a host fed no waits.

* fix(native-chat): a closed sink's dropped writes never read as landed

The sink's written() resolved ok when the sink was closed with writes still
queued, so a subagent's prompt card could count as open with no row in the
journal. written() now reports a close that dropped writes admitted so far
as not landed; drained() and lifecycleBarrier() keep reading a closed sink as
settled.

Tests: a card never opens when its sink closes first; a card Claude withdraws
while the sink holds the cancelled row back closes at once; two subagents
asking at once, and the main agent asking beside a subagent, keep the parent
row as before with each waiting subagent beside its own card; a process that
dies mid-request leaves no subagent waiting.

* fix(claude): a withdrawn subagent request frees its child before its card closes

Main's sink now hands each write to the journal as it is submitted, and an idle journal commits it
and runs the publication at once. Claude's own withdrawal of a subagent's request therefore closed
the card and published the parent row before the child's wait was freed, so one publish showed the
subagent waiting beside no pending card (fg-interrupt replay). The child's wait now also requires the
request to still be open in the registry, and a withdrawal republishes child work before the
journal takes the close.

* refactor(claude): trim subagent request waiting to the common pattern and its essential tests

The chat history no longer marks a subagent block as waiting: the approval card itself carries the
request, and the asking subagent's row in the sidebar and composer strip reads waiting, as before.
NativeChatWaitingSubagentsProvider, native-chat-waiting-subagents.ts and their renderer changes go.

A subagent waits while its request is still open and unanswered in the prompt registry and its card
has landed in the journal. The registry check also covers a withdrawal under backpressure, so the
card list no longer filters pending cancellations itself.

Tests: one integration file replays the captured CLI frames through the real adapter, sink, journal
and status feed (renamed claude-subagent-permission-request.test.ts), with the asking subagent's
state timeline, attribution, nested linkage and a card write that waits for the journal. The
producer-harness waiting test, the redundant prompt-card cases, the harness reducer swap and three
unused captures (deny, interrupt, main agent, failed subagent) are removed.

* test(claude): pin the parent row's dating when a subagent asked first, and narrow the oracle's claim

* Turn desktop notifications on or off per machine (#24518)

* feat(notifications): turn desktop notifications on or off per machine

Settings > Notifications lists each machine (this computer, SSH targets,
paired Orca servers) with a switch. Muted machines are stored as an
opt-out list so a newly added machine still notifies. Both notification
senders now name the machine a workspace runs on, and main skips the
desktop banner for a muted one; phone push is unchanged.

* fix(notifications): preserve phone alerts and honor machine mutes

* fix(notifications): bind machine mutes to configured sources

* fix(notifications): preserve chat completion subscriptions on owner collisions

* fix(notifications): reduce machine settings clutter with a collapsed section

* fix(notifications): align machine disclosure with settings rows

* fix(notifications): clarify machine switches affect only this computer

* fix: distinguish unavailable account metadata from absence

* fix(accounts): resolve registered profile UUIDs consistently

* Replace agentArgsOverride with unified removeAgentArgs approach (#25091)

Consolidate override detection and removal into removeAgentArgs. Previously
catalogs used agentArgsOverride to detect conflicts and removeAgentArgs to
strip them; now removeAgentArgs handles both by returning stripped tokens.
This eliminates redundancy and makes the intent clearer.

Enhance removeAgentArgOption with optional value filtering to support
selective removal for complex cases like Codex config overrides.

* Reuse the ancestor path while building mobile agent rows (#24539)

Preserve traversal order and cycle guards using one call-local path Set rather than a copy at every depth.

* Release waiting terminal output when a mobile subscription fails to start (#24547)

Dispose the failed subscription record’s existing terminal backlog before rethrowing its original start error.

* Avoid cloning terminal agent owners twice in relay listings (#24713)

Capture the existing host-age expression at its original time, then use one call-local fresh owner clone for the length check and unchanged published owner field.

* Reuse prepared statements for internal worker checks (#24573)

* Reuse prepared statements across remaining Dispatch reads

Use the existing schema-pinned complete Dispatch column list in five remaining read modules, enabling the existing bounded statement cache without caching results.

* Reuse prepared statements for internal worker checks

Use the existing complete Dispatch projection only for named-field internal consumers; preserve original wildcard reads for every returned failure snapshot.

* Prepare the Activity search query once per filtered list (#24701)

Lazily reuse a call-local search predicate inside the existing filter, using unchanged byte gates and thread text cache.

* Avoid rescanning shared chunks in the plain Node build guard (#24717)

Reuse a successful unchanged chunk-code verdict within one synchronous writeBundle invocation, while preserving traversal and current-code reads.

* Select the latest stable release tag in one pass (#24786)

Replace filter/sort/last selection with one traversal using the unchanged stable-tag regex and numeric comparator; update on equality to preserve the original last spelling. Both actual callers own private plain arrays from Git stdout.

* Avoid Resource Manager renders when terminal removal leaves its inventory unchanged (#24806)

Reuse the private React state object only when the existing single/bulk removal helper returns its identical inventory; keep every lifecycle revision, tombstone, known-ID write and helper invocation in its original order.

* Cancel pending cursor updates when a terminal closes (#24566)

Reuse the existing pane frame tracker to cancel owned deferred focus-class updates during existing cleanup, with disposed guards against late or reentrant delivery.

* Cancel terminal preview fit frames when the preview closes (#24712)

Reuse the existing frame tracker inside the box-fit owner, suppress scheduling after disposal and cancel pending frames at the start of the existing effect cleanup.

* Skip new mobile toast work after feedback owner cleanup (#24759)

Reuse the existing mobile mounted-ref lifecycle pattern at toast presentation entry, preserving admitted clipboard outcomes and every live animation/sequence/timer operation.

* Release terminal side effects after they have been delivered (#24548)

Clear consumed queue slots after successful apply or overflow carry; preserve backing identity across reentrant callbacks and report actual retained slots.

* Release relay handshake timers when a host connection leaves (#24554)

Reuse the existing first-frame finish pattern to remove stage-owned timer/message/close callbacks on receipt, timeout or close; check OPEN after successful async assignment verification.

* Avoid restarting error timers on closed mobile relay links (#24567)

Check the existing irreversible closed flag before scheduling the existing missing-close fallback timer.

* Avoid restarting error timers after mobile relay pairing closes (#24568)

Check the existing pairing owner closed flag before allocating its missing-close fallback alarm.

* Delete unreturned clipboard cache files after a failed write (#24599)

Reuse existing provider-copy best-effort deletion for a newly created clipboard cache file whose write fails before its URI reaches the caller.

* Skip new legacy file inventories after mobile search cleanup (#24792)

Reuse the existing mobile mounted-ref pattern only at legacy fallback entry after completed passive cleanup; preserve admitted work and all live search/authority/cache paths. Correct only the strict fully-unmounted inventory scenario and its sole golden.

* Discard completed AI Vault cancellation IDs in the relay worker (#24820)

Use the relay child's existing pending Set to ignore cancellation IDs after completion, matching its desktop sibling; preserve admitted active/queued cancellation and the bundled private sender's complete replies, errors and ownership.

* Release completed updater setup timers and callbacks (#24920)

Cancel completed deferred updater fallbacks in finally, clear only their exact pending callback, and drop the captured timer before the original fallback guard runs; preserve destroyed admission, successor ownership and updater/quit callbacks.

* Check daemon idle state without building discarded terminal inventories (#24749)

* Check daemon idle state without building discarded terminal inventories

Replace the private idle predicate full public inventory with a host-local full pass that still reads every Session liveness getter in original order.

* Remove overwritten daemon test mock assignment

* Preserve the registered account ID when selecting UUID variants

* fix(updater): keep macOS Orca open when background instances block updates (#24952)

* fix(updater): guard macOS installs against running app instances

* fix(updater): match native app blockers and preserve quit lifecycle

* fix(updater): keep ordinary macOS quit on Squirrel's install-on-exit path

Converting every quit with a staged update into quitAndInstall made Cmd+Q
relaunch Orca, refused the quit when background instances existed, and
hijacked app.relaunch()+app.quit() restart flows (profile switch, admin
restart) into an update install racing the relaunched old app. Only
Update & Restart runs the running-instance preflight now; the
quit-without-install allowance is no longer reachable and is removed.

* fix(updater): preserve quit intent through macOS staging

* test(native-chat): explicitly model legacy published tab ownership

---------

Co-authored-by: OrcaWin <[email protected]>
Co-authored-by: m4air <[email protected]>

---------

Co-authored-by: Brennan Benson <[email protected]>
Co-authored-by: Jinjing <[email protected]>
Co-authored-by: OrcaWin <[email protected]>
Co-authored-by: OrcaWin <[email protected]>
Co-authored-by: m4air <[email protected]>
brennanb2025 added a commit that referenced this pull request Oct 4, 2026
…C request path change (#25061)

* ci: run cross-version wire suites when agent sends or orchestration change

The selector skipped the cross-version wire job for #24901, which changed the
shared agent-send path, the structured send envelope builders, and orchestration
RPC code. Route the send payload/fingerprint builders, src/main/runtime/orchestration/,
and the orchestration RPC methods to the job, and pin each rule in a test.

* ci: run cross-version wire suites only for code they execute

The agent-session suites now build their send through the shared outbox
builder and check it against the release host's schema and fingerprint,
so the send builder and outbox are selected exactly. Load-only
orchestration rules are dropped; the dispatcher-path files every suite
request runs through are selected instead.

* ci: run the release's own send admission, cover queued sends and the RPC reply builder

* test(cross-version): a wrong send fingerprint must be refused, so an agreed one is not vacuous
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