From c2fced0c98dd417820559fa363404e01e80e32bf Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Mon, 16 Nov 2026 21:17:17 -0800 Subject: [PATCH] fix(native-chat): deliver other agents' messages to chat agents directly again (#43380) * fix(native-chat): deliver other agents' messages to chat agents directly again #43093 sent chat agents only a pointer at `orca orchestration check` for mail from other agents, while the chat showed the full message, so the agent never received what the chat displayed and every message cost an extra tool call. Chat agents again receive each orchestration message whole, with its sender header, exactly as the chat card shows it; a message too large for one chat message still falls back to the pointer. The Approve once control from #43093 is unchanged. Tracked in STA-15406. * fix(orchestration): keep custody hold and owner wake for mail not delivered whole Whole-delivered mail is read on settle. A pointer or in-doubt send still holds while custody is unreadable, is handed to the mailbox's new owner when the chat lost it, and a send made obsolete by a handoff wakes that owner. --- .../structured-agent-session-handover.ts | 7 +- .../worker-follow-up-lineage.ts | 8 +- .../structured-mail-custody.ts | 42 +++++----- .../structured-mail-provider-body.ts | 29 ------- .../structured-mail/structured-mail-source.ts | 5 +- .../structured-mail/structured-mail-whole.ts | 78 +++++++++++++++++++ ...tructured-mailbox-pointer-delivery.test.ts | 16 ++-- .../structured-mailbox-pointer-delivery.ts | 2 +- ...red-chat-coordinator-fake-codex-fixture.ts | 9 +-- ...-chat-coordinator-mail-rig.test-fixture.ts | 6 +- .../structured-chat-coordinator-mail.test.ts | 40 ++++------ ...ructured-chat-dispatch-worker-mail.test.ts | 6 +- .../structured-chat-dispatch-worker.test.ts | 12 ++- ...tructured-chat-mail-reconciliation.test.ts | 15 ++-- .../structured-chat-worker-reuse.test.ts | 14 ++-- .../launch/worker-dispatch-preamble.ts | 8 +- .../settled-worker-follow-through.ts | 13 +++- 17 files changed, 175 insertions(+), 135 deletions(-) delete mode 100644 src/main/runtime/orchestration/mailbox/structured-mail/structured-mail-provider-body.ts create mode 100644 src/main/runtime/orchestration/mailbox/structured-mail/structured-mail-whole.ts diff --git a/src/main/native-chat/agent-session-wire/delivery/structured-agent-session-handover.ts b/src/main/native-chat/agent-session-wire/delivery/structured-agent-session-handover.ts index f612beb5113..749e50500ca 100644 --- a/src/main/native-chat/agent-session-wire/delivery/structured-agent-session-handover.ts +++ b/src/main/native-chat/agent-session-wire/delivery/structured-agent-session-handover.ts @@ -26,7 +26,6 @@ import { } from '../operations/structured-agent-session-command-turn' import type { StoppedHistoryDelivery } from '../../../../shared/agent-session/lifecycle/stopping/agent-session-stopped-history' import { withStoppedHistory } from '../../../../shared/agent-session/lifecycle/stopping/agent-session-stopped-history' -import { structuredMailProviderBody } from '../../../runtime/orchestration/mailbox/structured-mail/structured-mail-provider-body' import { markStructuredAgentSessionInputUnadmitted, beginStructuredAgentSessionHandover, @@ -66,8 +65,6 @@ export async function beginSubmissionHandover( ) return null } - // The journal keeps what people see; the agent is sent only what it may act on. - const sent = structuredMailProviderBody(body) // Join only current turns; persist stopped-history carry before writing to the provider. const turnScope = await readContextStructuredAgentSessionTurnScope(ctx) let carried: StoppedHistoryDelivery | null = null @@ -109,7 +106,7 @@ export async function beginSubmissionHandover( turnScope: AGENT_JOURNAL_THREAD_SCOPE, body }) - return carried ? withStoppedHistory(sent, carried.messages) : sent + return carried ? withStoppedHistory(body, carried.messages) : body } // Preserve handover time so turn-open cannot re-anchor elapsed work. const requestedAt = await structuredAgentSessionHandoverOrigin(ctx.journal, submission) @@ -133,7 +130,7 @@ export async function beginSubmissionHandover( ? await dispatchSafely( ctx, clientMessageId, - carried ? withStoppedHistory(sent, carried.messages) : sent, + carried ? withStoppedHistory(body, carried.messages) : body, requestedAt, submission.options, queued, diff --git a/src/main/runtime/orchestration/db/dispatch-context/worker-follow-up-lineage.ts b/src/main/runtime/orchestration/db/dispatch-context/worker-follow-up-lineage.ts index a53a3eacbec..d80a0c9fc65 100644 --- a/src/main/runtime/orchestration/db/dispatch-context/worker-follow-up-lineage.ts +++ b/src/main/runtime/orchestration/db/dispatch-context/worker-follow-up-lineage.ts @@ -166,14 +166,14 @@ export function markUnreadFollowUpMail(db: OrchestrationDb, dispatchId: string): } /** In the follow-up's claim, so its first `check` finds the mail. A terminal's start prompt is that mail's - * wake; a pointer whose Enter is in flight keeps its stamps to settle. A chat gets each message as a card + * wake; a pointer whose Enter is in flight keeps its stamps to settle. A chat is handed each message whole * after its Task, so the mail stays undelivered for that. */ export function takeFollowUpMail( db: OrchestrationDb, fromDispatchId: string, toDispatchId: string ): void { - const chat = receivesMailAsChatCards(db.getDispatchContextById(fromDispatchId)?.assignee_handle) + const chat = receivesMailWhole(db.getDispatchContextById(fromDispatchId)?.assignee_handle) db.db .prepare( `UPDATE messages @@ -190,8 +190,8 @@ export function takeFollowUpMail( markUnreadFollowUpMail(db, toDispatchId) } -/** A chat worker, assigned by session or started by Orca, gets each message as a chat card rather than a terminal pointer. */ -export function receivesMailAsChatCards(assigneeHandle: string | null | undefined): boolean { +/** A chat worker, assigned by session or started by Orca, gets mail whole rather than a pointer at `check`. */ +export function receivesMailWhole(assigneeHandle: string | null | undefined): boolean { return ( parseOrcaSessionAddress(assigneeHandle) !== null || isStructuredWorkerHandle(assigneeHandle) ) diff --git a/src/main/runtime/orchestration/mailbox/structured-mail/structured-mail-custody.ts b/src/main/runtime/orchestration/mailbox/structured-mail/structured-mail-custody.ts index 9f6d5aa2fc8..d5cf1c4cb44 100644 --- a/src/main/runtime/orchestration/mailbox/structured-mail/structured-mail-custody.ts +++ b/src/main/runtime/orchestration/mailbox/structured-mail/structured-mail-custody.ts @@ -6,6 +6,7 @@ import type { StructuredMailSendRow } from '../../db/messages/structured-mail-se import type { StructuredMailboxPointerHost } from '../structured-pointer/structured-mailbox-pointer-host-contract' import type { StructuredPointerTarget } from '../structured-pointer/structured-mailbox-pointer-delivery' import { structuredMailboxCustody } from '../routing/structured-session-mail-target' +import { structuredMailWasDeliveredWhole } from './structured-mail-whole' import type { JournalMailObservation } from '../../../../native-chat/agent-session-journal/journal-mail-observation' import { reconcileLifecycleMessage } from '../../workers/lifecycle/lifecycle-reconciliation' import type { QueuedMessageOwed } from '../../../../native-chat/agent-session-journal/queued-messages/queued-message-consume-error' @@ -227,36 +228,39 @@ export function settleStructuredMailAttempt( const release = () => { decision.released = db.releaseStructuredMailSend(row) } + // A pointer or in-doubt send left the mail unread: hold it while custody is unreadable, and tell + // its owner now when the chat lost the mailbox and can no longer `check` it. + const retireUnconsumed = () => { + if (owed === 'unavailable') { + decision.outstanding = true + return + } + retire(false) + if (owed === 'stale') { + db.markAsUndelivered([row.message_id]) + decision.released = true + } + } switch (state.kind) { case 'accepted': { const message = db.getMessageById(row.message_id) if (message) { reconcileLifecycleMessage(db, message) } - // Unreadable custody keeps the attempt until a later observation can tell whether its owner moved. - if (owed === 'unavailable') { - decision.outstanding = true + const corrected = db.getMessageById(row.message_id) + if ( + corrected && + !corrected.read && + structuredMailWasDeliveredWhole(row, corrected, observation) + ) { + retire(true) break } - // The agent was sent a pointer, not the mail: it stays unread until `check` takes it. - retire(false) - if (owed === 'stale') { - // A chat that lost the mailbox cannot `check` it: its owner now, terminal or chat, is told. - db.markAsUndelivered([row.message_id]) - decision.released = true - } + retireUnconsumed() break } case 'unknown': - if (owed === 'unavailable') { - decision.outstanding = true - break - } - retire(false) - if (owed === 'stale') { - db.markAsUndelivered([row.message_id]) - decision.released = true - } + retireUnconsumed() break case 'refused': release() diff --git a/src/main/runtime/orchestration/mailbox/structured-mail/structured-mail-provider-body.ts b/src/main/runtime/orchestration/mailbox/structured-mail/structured-mail-provider-body.ts deleted file mode 100644 index 1e696e7a4b7..00000000000 --- a/src/main/runtime/orchestration/mailbox/structured-mail/structured-mail-provider-body.ts +++ /dev/null @@ -1,29 +0,0 @@ -import { - orchestrationMailNotice, - readAgentMessageSource -} from '../../../../../shared/agent-session/journal/agent-session-message-source' -import type { AgentJournalMessageItem } from '../../../../../shared/agent-session/journal/agent-session-journal-types' -import { - localOrchestrationCliCommand, - type OrchestrationCliCommand -} from '../../workers/launch/orchestration-cli-command' -import { formatMessagePointer } from '../formatting/message-formatting' - -/** What the agent itself is sent for a mail card: Orca's pointer at `check`, never another agent's - * words. Mail read through `check` reaches the agent as tool output, which no reviewer counts as the - * user's authorization; a person's own messages pass through unchanged. */ -export function structuredMailProviderBody( - body: AgentJournalMessageItem, - cliCommand: OrchestrationCliCommand = localOrchestrationCliCommand() -): AgentJournalMessageItem { - const mail = orchestrationMailNotice(readAgentMessageSource(body.from)) - if (!mail) { - return body - } - const pointer = formatMessagePointer( - Math.max(1, mail.messages.length), - mail.mailbox, - cliCommand - ).trim() - return { ...body, blocks: [{ type: 'text', text: pointer }] } -} diff --git a/src/main/runtime/orchestration/mailbox/structured-mail/structured-mail-source.ts b/src/main/runtime/orchestration/mailbox/structured-mail/structured-mail-source.ts index 1791d6cc18a..c9f943ca41a 100644 --- a/src/main/runtime/orchestration/mailbox/structured-mail/structured-mail-source.ts +++ b/src/main/runtime/orchestration/mailbox/structured-mail/structured-mail-source.ts @@ -106,8 +106,9 @@ export function structuredMailSource(input: { } } -/** One orchestration message as one chat card: the whole message, with who it is from, for people. - * `whole` is false when it would exceed a chat message's limit; that card then shows the pointer. */ +/** One orchestration message as one chat message: the whole message, with who it is from. + * `whole` is false when it would exceed a chat message's limit; that one then points at `check` + * and stays unread there. */ export function structuredMailMessage(input: { db: OrchestrationDb mailboxHandle: string diff --git a/src/main/runtime/orchestration/mailbox/structured-mail/structured-mail-whole.ts b/src/main/runtime/orchestration/mailbox/structured-mail/structured-mail-whole.ts new file mode 100644 index 00000000000..ec93dce26f3 --- /dev/null +++ b/src/main/runtime/orchestration/mailbox/structured-mail/structured-mail-whole.ts @@ -0,0 +1,78 @@ +import type { JournalMailObservation } from '../../../../native-chat/agent-session-journal/journal-mail-observation' +import type { StructuredMailSendRow } from '../../db/messages/structured-mail-send-store' +import type { MessageRow } from '../../db/orchestration-records' +import { + orchestrationMailNotice, + readAgentMessageSource +} from '../../../../../shared/agent-session/journal/agent-session-message-source' + +/** Compare the admitted fields, never a newly rendered address or reply line. */ +export function structuredMailWasDeliveredWhole( + attempt: StructuredMailSendRow, + message: MessageRow, + observation: JournalMailObservation +): boolean { + const { body } = observation + if ( + observation.state.kind !== 'accepted' || + !body || + body.kind !== 'message' || + message.id !== attempt.message_id + ) { + return false + } + const mail = orchestrationMailNotice(readAgentMessageSource(body.from)) + if ( + !mail || + mail.mailbox !== attempt.mailbox_handle || + !Array.isArray(body.blocks) || + body.blocks.length !== 1 + ) { + return false + } + const block = body.blocks[0] + if (block?.type !== 'text' || typeof block.text !== 'string') { + return false + } + const matches = mail.messages.filter((member) => member.messageId === attempt.message_id) + const member = matches.length === 1 ? matches[0] : undefined + const content = member?.content + if ( + !member || + !content || + member.runId !== message.run_id || + member.from !== message.from_handle + ) { + return false + } + let end = 0 + const equal = ( + range: readonly [number, number] | undefined, + value: string | null, + required = false + ) => { + if (!required && !value) { + return range === undefined + } + if (!range || !Array.isArray(range) || range.length !== 2) { + return false + } + const [start, stop] = range + if ( + !Number.isInteger(start) || + !Number.isInteger(stop) || + start < end || + stop < start || + stop > block.text.length + ) { + return false + } + end = stop + return block.text.slice(start, stop) === value + } + return ( + equal(content.subject, message.subject, true) && + equal(content.body, message.body) && + equal(content.payload, message.payload) + ) +} diff --git a/src/main/runtime/orchestration/mailbox/structured-pointer/structured-mailbox-pointer-delivery.test.ts b/src/main/runtime/orchestration/mailbox/structured-pointer/structured-mailbox-pointer-delivery.test.ts index e46f1e50cd7..d00d1b7d4e7 100644 --- a/src/main/runtime/orchestration/mailbox/structured-pointer/structured-mailbox-pointer-delivery.test.ts +++ b/src/main/runtime/orchestration/mailbox/structured-pointer/structured-mailbox-pointer-delivery.test.ts @@ -274,8 +274,8 @@ const flush = async () => { } } -describe('structured mailbox delivery: each message as its own card', () => { - it('points the new owner at mail whose handoff to the old owner won stale-card withdrawal', async () => { +describe('structured mailbox delivery: each message whole', () => { + it('settles a handoff that wins stale-card withdrawal without sending it to the new owner', async () => { const h = harness({ busy: true }) h.receive('m1') await h.deliver() @@ -286,12 +286,12 @@ describe('structured mailbox delivery: each message as its own card', () => { return { kind: 'accepted' } }) h.delivery.withdrawStale() - // The old owner was only pointed at `check`, which it can no longer read: the new owner is. - await vi.waitFor(() => - expect(h.sent.map(({ sessionId }) => sessionId)).toEqual(['session-1', 'session-2']) - ) - expect(h.sent[0]!.operationId).toBe(first) - expect(h.mail.get('m1')?.read).toBe(0) + await vi.waitFor(() => expect(h.mail.get('m1')?.read).toBe(1)) + expect(h.records.size).toBe(0) + expect(h.sent.map(({ sessionId, operationId }) => [sessionId, operationId])).toEqual([ + ['session-1', first] + ]) + expect(h.mail.get('m1')?.delivered_at).toBe('now') }) }) diff --git a/src/main/runtime/orchestration/mailbox/structured-pointer/structured-mailbox-pointer-delivery.ts b/src/main/runtime/orchestration/mailbox/structured-pointer/structured-mailbox-pointer-delivery.ts index fd2208a949b..eb454c522e0 100644 --- a/src/main/runtime/orchestration/mailbox/structured-pointer/structured-mailbox-pointer-delivery.ts +++ b/src/main/runtime/orchestration/mailbox/structured-pointer/structured-mailbox-pointer-delivery.ts @@ -1,4 +1,4 @@ -/** Chats queue each message as its own card, one per turn behind work/questions (shown whole, sent as a pointer); terminals keep the PTY pointer lane. */ +/** Chats queue whole mail one per turn behind work/questions; terminals keep the PTY pointer lane. */ import type { MessageRow } from '../../db/orchestration-records' import type { OrchestrationDb } from '../../db/orchestration-db' diff --git a/src/main/runtime/orchestration/terminal-authority/structured-sessions/structured-chat-coordinator-fake-codex-fixture.ts b/src/main/runtime/orchestration/terminal-authority/structured-sessions/structured-chat-coordinator-fake-codex-fixture.ts index dd5988e1356..9b13be1e3d2 100644 --- a/src/main/runtime/orchestration/terminal-authority/structured-sessions/structured-chat-coordinator-fake-codex-fixture.ts +++ b/src/main/runtime/orchestration/terminal-authority/structured-sessions/structured-chat-coordinator-fake-codex-fixture.ts @@ -186,18 +186,11 @@ export function resetProviderFaults(): void { providerFaults.turnStarts = 0 } -/** A chat card holds the whole orchestration message: its subject and its reply command. */ +/** A chat got the whole orchestration message: its subject and its reply command. */ export function isWholeMail(text: string): boolean { return text.includes('\nSubject: ') && /\[[^\]\n]*: orca(-dev)? orchestration /.test(text) } -/** What the agent itself is sent for that card: only Orca's pointer at `check`. */ -export function isMailPointer(text: string): boolean { - return /^You have 1 orchestration message\. Run `orca(-dev)? orchestration check( --run \S+)?`\.$/.test( - text - ) -} - export function turnText(turn: { text: string }): string { const input: unknown = JSON.parse(turn.text) return Array.isArray(input) diff --git a/src/main/runtime/orchestration/terminal-authority/structured-sessions/structured-chat-coordinator-mail-rig.test-fixture.ts b/src/main/runtime/orchestration/terminal-authority/structured-sessions/structured-chat-coordinator-mail-rig.test-fixture.ts index 4abcee17be2..18503816394 100644 --- a/src/main/runtime/orchestration/terminal-authority/structured-sessions/structured-chat-coordinator-mail-rig.test-fixture.ts +++ b/src/main/runtime/orchestration/terminal-authority/structured-sessions/structured-chat-coordinator-mail-rig.test-fixture.ts @@ -310,11 +310,7 @@ afterEach(async () => { // Asynchronous pointer edges need slack under parallel load. export const WAIT = { timeout: 10_000, interval: 10 } -export { - isMailPointer, - isWholeMail, - turnText -} from './structured-chat-coordinator-fake-codex-fixture' +export { isWholeMail, turnText } from './structured-chat-coordinator-fake-codex-fixture' export function restartRuntime(): void { runtime = startRuntime() diff --git a/src/main/runtime/orchestration/terminal-authority/structured-sessions/structured-chat-coordinator-mail.test.ts b/src/main/runtime/orchestration/terminal-authority/structured-sessions/structured-chat-coordinator-mail.test.ts index feab394b423..89c9043a57a 100644 --- a/src/main/runtime/orchestration/terminal-authority/structured-sessions/structured-chat-coordinator-mail.test.ts +++ b/src/main/runtime/orchestration/terminal-authority/structured-sessions/structured-chat-coordinator-mail.test.ts @@ -21,7 +21,6 @@ import { coordinatorRunAndTask, clearChat, WAIT, - isMailPointer, isWholeMail, turnText } from './structured-chat-coordinator-mail-rig.test-fixture' @@ -80,34 +79,26 @@ describe('a worker result reaches the structured chat that coordinates it', () = }) describe("another agent's message in a structured chat", () => { - it('is shown whole in the chat but sent to the agent only as a pointer at check, unlike the person', async () => { + it('is sent to the agent exactly as the chat shows it, with no check needed', async () => { const chat = await openChat(COORDINATOR) const { runId, taskId } = await coordinatorRunAndTask() await finishWorker(taskId) await vi.waitFor(() => expect(chat.turns).toHaveLength(1), WAIT) - // Dev builds run the CLI as `orca-dev`. - const pointer = turnText(chat.turns[0]!).replace('`orca-dev ', '`orca ') - expect(pointer).toBe( - `You have 1 orchestration message. Run \`orca orchestration check --run ${runId}\`.` - ) + const sent = turnText(chat.turns[0]!) + expect(isWholeMail(sent)).toBe(true) + expect(sent).toContain('\nSubject: Done') + expect(sent).toContain('"outcome":"succeeded"') + expect(sent).not.toContain('orchestration check') const snapshot = await readTestHostJournal(host, COORDINATOR) - const card = snapshot.items.find( - (item) => - item.body?.kind === 'message' && - item.body.blocks.some((block) => block.type === 'text' && isWholeMail(block.text)) + const shown = snapshot.items.flatMap((item) => + item.body?.kind === 'message' && item.body.from?.kind === 'agent' + ? item.body.blocks.flatMap((block) => (block.type === 'text' ? [block.text] : [])) + : [] ) - expect(card?.body).toMatchObject({ from: { kind: 'agent' } }) + expect(shown).toEqual([sent]) await settleTurn(COORDINATOR, 0) - expect(unread(`run:${runId}`)).toHaveLength(1) - - expect(await sendUserMessage(COORDINATOR, 'I approve the deploy')).toMatchObject({ ok: true }) - await vi.waitFor(() => expect(chat.turns).toHaveLength(2), WAIT) - expect(turnText(chat.turns[1]!)).toBe('I approve the deploy') - - const checked = await call('orchestration.check', {}, { sessionId: COORDINATOR }) - expect(checked).toMatchObject({ runId, count: 1, messages: [{ type: 'worker_done' }] }) - expect(unread(`run:${runId}`)).toEqual([]) + await vi.waitFor(() => expect(unread(`run:${runId}`)).toEqual([]), WAIT) }) }) @@ -125,15 +116,12 @@ describe('a /clear keeps the chat its orchestration address', () => { const next = connectionFor(cleared) expect(codex.connections.slice(opened)).toEqual([next]) expect(next.methods.filter((method) => method.startsWith('thread/'))).toEqual(['thread/start']) - expect(isMailPointer(turnText(next.turns[0]!))).toBe(true) + expect(isWholeMail(turnText(next.turns[0]!))).toBe(true) await settleTurn(cleared, 0) await expect( call('orchestration.runCurrent', {}, { sessionId: cleared }) ).resolves.toMatchObject({ run: { id: runId } }) - await expect(call('orchestration.check', {}, { sessionId: cleared })).resolves.toMatchObject({ - runId, - count: 1 - }) + await vi.waitFor(() => expect(unread(`run:${runId}`)).toEqual([]), WAIT) expect(db.getRunRaw(runId)).toMatchObject({ coordinator_orca_session_id: COORDINATOR, consumer_generation: generation diff --git a/src/main/runtime/orchestration/terminal-authority/structured-sessions/structured-chat-dispatch-worker-mail.test.ts b/src/main/runtime/orchestration/terminal-authority/structured-sessions/structured-chat-dispatch-worker-mail.test.ts index c357e14df76..b330fa7f066 100644 --- a/src/main/runtime/orchestration/terminal-authority/structured-sessions/structured-chat-dispatch-worker-mail.test.ts +++ b/src/main/runtime/orchestration/terminal-authority/structured-sessions/structured-chat-dispatch-worker-mail.test.ts @@ -14,7 +14,7 @@ import { coordinatorRunAndTask, db, host, - isMailPointer, + isWholeMail, observationClock, openChat, restartRuntime, @@ -33,7 +33,7 @@ async function idleEdges(sessionId: string): Promise { await host.flushStreamedEvents(sessionId) } -/** Coordinator mail to the peer chat's Dispatch, pointed at for a provider that died before taking it. */ +/** Coordinator mail to the peer chat's Dispatch, handed whole to a provider that died before taking it. */ async function heldDispatchMail(): Promise { await openChat(COORDINATOR) const chat = await openChat(PEER_CHAT) @@ -46,7 +46,7 @@ async function heldDispatchMail(): Promise { const mailbox = `dispatch:${idOf(dispatch)}` await call('orchestration.send', { to: mailbox, subject: 'more' }, { sessionId: COORDINATOR }) await vi.waitFor(() => expect(chat.turns).toHaveLength(1), WAIT) - expect(isMailPointer(turnText(chat.turns[0]!))).toBe(true) + expect(isWholeMail(turnText(chat.turns[0]!))).toBe(true) chat.handlers.onExit?.(new Error('provider died before the echo')) await idleEdges(PEER_CHAT) expect(chat.turns).toHaveLength(1) diff --git a/src/main/runtime/orchestration/terminal-authority/structured-sessions/structured-chat-dispatch-worker.test.ts b/src/main/runtime/orchestration/terminal-authority/structured-sessions/structured-chat-dispatch-worker.test.ts index 80f2f8fa60e..dab65ff1634 100644 --- a/src/main/runtime/orchestration/terminal-authority/structured-sessions/structured-chat-dispatch-worker.test.ts +++ b/src/main/runtime/orchestration/terminal-authority/structured-sessions/structured-chat-dispatch-worker.test.ts @@ -9,7 +9,6 @@ import { testOrcaSessionId } from '../../../../../shared/agent-session/identity/ import { idOf } from '../../../rpc/orchestration/callers/session.test-fixture' import { sendChatTask } from '../../../rpc/methods/orchestration/chat-task-delivery' import { - isMailPointer, providerFaults, type FakeConnection } from './structured-chat-coordinator-fake-codex-fixture' @@ -176,7 +175,7 @@ describe('a chat as the assignee of orchestration dispatch', () => { expect(dispatchCount()).toEqual({ n: 0 }) }) - it("points the chat at its coordinator's Dispatch mail, which its own check reads once", async ({ + it("hands the chat its coordinator's mail to the Dispatch whole, so its own check has nothing left", async ({ onTestFinished }) => { const accepted = Promise.withResolvers() @@ -224,19 +223,18 @@ describe('a chat as the assignee of orchestration dispatch', () => { ) await vi.waitFor(() => expect(worker.turns).toHaveLength(1), WAIT) - expect(isMailPointer(turnText(worker.turns[0]!))).toBe(true) + expect(turnText(worker.turns[0]!)).toMatch( + /Subject: also check the tests\n\[Reply: orca(-dev)? orchestration reply --id msg_\w+ --body "\.\.\."\]/ + ) expect(await queuedCardTexts(PEER_CHAT)).toEqual([]) await settleTurn(PEER_CHAT, 0) await accepted.promise try { expect(await call('orchestration.check', {}, { sessionId: PEER_CHAT })).toMatchObject({ - messages: [{ subject: 'also check the tests' }] + messages: [] }) } finally { release.resolve() } - expect(await call('orchestration.check', {}, { sessionId: PEER_CHAT })).toMatchObject({ - messages: [] - }) }) }) diff --git a/src/main/runtime/orchestration/terminal-authority/structured-sessions/structured-chat-mail-reconciliation.test.ts b/src/main/runtime/orchestration/terminal-authority/structured-sessions/structured-chat-mail-reconciliation.test.ts index 84e2ca8470c..9e70d62df5c 100644 --- a/src/main/runtime/orchestration/terminal-authority/structured-sessions/structured-chat-mail-reconciliation.test.ts +++ b/src/main/runtime/orchestration/terminal-authority/structured-sessions/structured-chat-mail-reconciliation.test.ts @@ -8,7 +8,7 @@ import { JournalSqlOwner } from '../../../../native-chat/agent-session-journal/j import { JournalSqlReaderPool } from '../../../../native-chat/agent-session-journal/journal-sql-reader-pool' import { journalSqlReads } from '../../../../native-chat/agent-session-journal/journal-sql-reads' import { resultOf } from '../../../rpc/orchestration/callers/session.test-fixture' -import { isMailPointer, operationId } from './structured-chat-coordinator-fake-codex-fixture' +import { operationId } from './structured-chat-coordinator-fake-codex-fixture' import { COORDINATOR, PEER_CHAT, @@ -47,7 +47,7 @@ function holdMailRead(sessionId: string, hold: () => Promise): void { } describe('mail checks reconcile the currently owned source attempts', () => { - it('leaves accepted direct mail for the check when its live lease renews during the source read', async ({ + it('keeps accepted whole direct mail consumed when its live lease renews during the source read', async ({ onTestFinished }) => { await openChat(COORDINATOR) @@ -101,11 +101,8 @@ describe('mail checks reconcile the currently owned source attempts', () => { }) expect(host.deps.store.getConversation(PEER_CHAT)!.ownerObservation.lastRenewedAt).toBe(now) releaseCheck.resolve() - expect(await checking).toMatchObject({ - count: 1, - messages: [{ subject: 'already accepted', body: 'the complete mail' }] - }) - expect(isMailPointer(turnText(chat.turns[0]!))).toBe(true) + expect(await checking).toMatchObject({ count: 0, messages: [] }) + expect(chat.turns.map(turnText).join('\n')).toContain('the complete mail') } finally { releaseCheck.resolve() releaseAutomatic.resolve() @@ -168,8 +165,8 @@ describe('mail checks reconcile the currently owned source attempts', () => { await vi.waitFor(() => expect(chat.turns).toHaveLength(2), WAIT) await settleTurn(COORDINATOR, 1) accepted.resolve() - expect(await checking).toMatchObject({ count: 1, messages: [{ from_handle: 'term_worker' }] }) - expect(isMailPointer(turnText(chat.turns[1]!))).toBe(true) + expect(await checking).toMatchObject({ count: 0, messages: [] }) + expect(chat.turns.map(turnText).join('\n')).toContain('(worker_done)') } finally { release.resolve() accepted.resolve() diff --git a/src/main/runtime/orchestration/terminal-authority/structured-sessions/structured-chat-worker-reuse.test.ts b/src/main/runtime/orchestration/terminal-authority/structured-sessions/structured-chat-worker-reuse.test.ts index 3065e38d0c5..41608576a7e 100644 --- a/src/main/runtime/orchestration/terminal-authority/structured-sessions/structured-chat-worker-reuse.test.ts +++ b/src/main/runtime/orchestration/terminal-authority/structured-sessions/structured-chat-worker-reuse.test.ts @@ -15,7 +15,6 @@ import { db, dispatcher, host, - isMailPointer, isWholeMail, openChat, request, @@ -337,22 +336,27 @@ describe('a send to a finished structured worker', () => { await vi.waitFor(async () => { const cards = await queuedCardTexts(identity.sessionId) expect(cards).toHaveLength(2) + expect(cards[0]).toContain('arrive next, one at a time') expect(isWholeMail(cards[1]!)).toBe(true) expect(cards[1]).toContain('and the docs') }, WAIT) + expect((await queuedCardTexts(identity.sessionId)).join('\n')).not.toContain('`check`') reply.resolve() worker.handlers.onNotification?.('turn/completed', { turn: { id: 'turn-1' } }) await host.flushStreamedEvents(identity.sessionId) await vi.waitFor(() => expect(worker.turns).toHaveLength(2), WAIT) + expect(turnText(worker.turns[1]!)).toContain('arrive next, one at a time') await settleTurn(identity.sessionId, 1) await vi.waitFor(() => expect(worker.turns).toHaveLength(3), WAIT) - expect(isMailPointer(turnText(worker.turns[2]!))).toBe(true) + expect(isWholeMail(turnText(worker.turns[2]!))).toBe(true) + expect(turnText(worker.turns[2]!)).toContain('and the docs') await settleTurn(identity.sessionId, 2) const followUp = getFollowUpDispatch(db, firstDispatchId)! - expect(db.getUnreadMessages(`dispatch:${followUp.id}`)).toMatchObject([ - { body: 'and the docs' } - ]) + await vi.waitFor( + () => expect(db.getUnreadMessages(`dispatch:${followUp.id}`)).toEqual([]), + WAIT + ) expect(db.getUnreadMessages(`dispatch:${firstDispatchId}`)).toEqual([]) } finally { reply.resolve() diff --git a/src/main/runtime/orchestration/workers/launch/worker-dispatch-preamble.ts b/src/main/runtime/orchestration/workers/launch/worker-dispatch-preamble.ts index 0bb3b165286..8a362dbc381 100644 --- a/src/main/runtime/orchestration/workers/launch/worker-dispatch-preamble.ts +++ b/src/main/runtime/orchestration/workers/launch/worker-dispatch-preamble.ts @@ -78,8 +78,12 @@ Do only this task, yourself: no subagents or helper workers unless the task asks \`\`\`sh ${ params.unreadMail - ? ` # Messages for this task are waiting; read them: - ${cli} orchestration check${chat ? '' : ` --terminal ${params.workerHandle}`} + ? chat + ? ` # Messages for this task arrive next, one at a time. + +` + : ` # Messages for this task are waiting; read them: + ${cli} orchestration check --terminal ${params.workerHandle} ` : '' diff --git a/src/main/runtime/rpc/methods/orchestration/messaging/settled-worker-follow-through.ts b/src/main/runtime/rpc/methods/orchestration/messaging/settled-worker-follow-through.ts index 2b8efd845c1..89dba12cf2f 100644 --- a/src/main/runtime/rpc/methods/orchestration/messaging/settled-worker-follow-through.ts +++ b/src/main/runtime/rpc/methods/orchestration/messaging/settled-worker-follow-through.ts @@ -6,7 +6,8 @@ import { markUnreadFollowUpMail, getFollowUpDispatch, hasNewUnreadFollowUpMail, - listDispatchesWithFollowUpMail + listDispatchesWithFollowUpMail, + receivesMailWhole } from '../../../../orchestration/db/dispatch-context/worker-follow-up-lineage' import { FOLLOW_UP_MESSAGE_TYPES } from '../../../../orchestration/db/dispatch-context/worker-follow-up-plan' import { @@ -58,6 +59,12 @@ const FOLLOW_UP_TASK = { body: 'You have new orchestration messages. Read them with the `check` command above, then continue.' } +// A chat is handed each message whole right after this Task, one at a time. +const CHAT_FOLLOW_UP_TASK = { + subject: 'New messages', + body: 'You have new orchestration messages. They arrive next, one at a time; act on each.' +} + async function continueUnreadMail( runtime: OrcaRuntimeService, db: OrchestrationDb, @@ -112,7 +119,9 @@ async function continueUnreadMail( db, plan, from: first.from_handle, - message: FOLLOW_UP_TASK, + message: receivesMailWhole(plan.latest.assignee_handle) + ? CHAT_FOLLOW_UP_TASK + : FOLLOW_UP_TASK, takesMailOf: dispatchId }) : plan