Skip to content
Merged
Show file tree
Hide file tree
Changes from 6 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -673,7 +673,7 @@ describe('useMobileStructuredAgentSession', () => {
expect(retryId).not.toBe(firstId)
})

it('marks a retried send as retryUnknown after ambiguous delivery', async () => {
it('uses a fresh operation id when a send delivery is ambiguous', async () => {
act(() => {
renderer = create(createElement(Harness))
})
Expand All @@ -695,12 +695,12 @@ describe('useMobileStructuredAgentSession', () => {
const calls = sendRequest.mock.calls.filter(([method]) => method === 'agentSession.send')
expect(calls).toHaveLength(2)
expect(calls[0]![1]).not.toHaveProperty('retryUnknown')
expect(calls[1]![1]).toMatchObject({ retryUnknown: true })
expect(calls[1]![1]).not.toHaveProperty('retryUnknown')
const firstId = (calls[0]![1] as { envelope: { clientOperationId: string } }).envelope
.clientOperationId
const retryId = (calls[1]![1] as { envelope: { clientOperationId: string } }).envelope
.clientOperationId
expect(retryId).toBe(firstId)
expect(retryId).not.toBe(firstId)
})

it('keeps structured option changes dispatched after unknown delivery', async () => {
Expand Down
8 changes: 4 additions & 4 deletions mobile/src/session/use-mobile-structured-agent-session.ts
Original file line number Diff line number Diff line change
Expand Up @@ -115,7 +115,7 @@ export function useMobileStructuredAgentSession(args: {
if (result.status === 'unknown') {
// Prompt/option/cancel plans cannot redispatch an unknown ledger row;
// issue a fresh id so a retry can be admitted after the user checks the
// stream. Sends opt into explicit retryUnknown below.
// stream. Sends rotate operation ids on retry below.
operationIdsRef.current.delete(key)
return result
}
Expand Down Expand Up @@ -186,11 +186,10 @@ export function useMobileStructuredAgentSession(args: {
if (commandOutcome !== null) {
return commandOutcome
}
const body = structuredAgentSessionSendBody(text, sendAttachments)
if (body.blocks.length === 0) {
const fields = { body: structuredAgentSessionSendBody(text, sendAttachments) }
if (fields.body.blocks.length === 0) {
return 'rejected'
}
const fields = { body }
const key = `${sessionKey}:agentSession.send:${JSON.stringify(fields)}`
const priorOperationId = operationIdsRef.current.get(key)
const clientOperationId = retainOperationId(key, priorOperationId)
Expand All @@ -210,6 +209,7 @@ export function useMobileStructuredAgentSession(args: {
return 'accepted'
}
if (result.status === 'unknown') {
operationIdsRef.current.delete(key)
return 'unknown'
}
operationIdsRef.current.delete(key)
Expand Down
6 changes: 1 addition & 5 deletions src/main/claude/claude-structured-compaction.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ import type { ClaudeSession, ClaudeStructuredSessionEvent } from './claude-struc
import type { StructuredSessionCompaction } from '../native-chat/agent-session-wire/structured-session-compaction'
import { dispatchClaudeTurn } from './claude-structured-dispatch'
import type { StructuredAgentSessionAdapter } from '../native-chat/agent-session-wire/structured-agent-session-adapter'
import { dispatchDoubtProvesUndelivered } from '../native-chat/agent-session-journal/journal-dispatch-doubt-reasons'
/** Compaction needs no ack deadline of its own: `compactions.run` keeps its own
* 180s completion window and settles on Claude's terminal `result` frame, so
* the dispatch here only has to report a refusal to send. */
Expand All @@ -18,10 +17,7 @@ export function compactClaudeSession(
const result = await dispatchClaudeTurn(session, {
body: { kind: 'message', role: 'user', blocks: [{ type: 'text', text: '/compact' }] }
})
if (
result.state === 'rejected' ||
(result.state === 'unknown' && dispatchDoubtProvesUndelivered(result.reason))
) {
if (result.state === 'rejected') {
return { error: result.reason }
}
return undefined
Expand Down
7 changes: 3 additions & 4 deletions src/main/claude/claude-structured-dispatch.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -372,14 +372,13 @@ describe('Claude structured dispatch image limits', () => {
.fn()
.mockRejectedValue(claudeUnwrittenUserMessageError(new Error('broken pipe')))

// A refused write is a transport fact, and the only thing besides child exit
// that puts one message's delivery in doubt.
// A refused write is not doubt: the frame never left, so it is a rejection.
await expect(
dispatchClaudeTurn(session, {
clientMessageId: 'client-2',
body: userMessage([{ type: 'text', text: 'two' }])
})
).resolves.toEqual({ state: 'unknown', reason: 'provider_write_failed: broken pipe' })
).resolves.toEqual({ state: 'rejected', reason: 'provider_write_failed: broken pipe' })
expect(session.dispatchWaiters).toEqual([firstWaiter])

const firstUuid = (firstWaiter as { sentUuid?: string }).sentUuid
Expand All @@ -401,7 +400,7 @@ describe('Claude structured dispatch image limits', () => {

await expect(
dispatchClaudeTurn(session, { clientMessageId: 'client-1', body })
).resolves.toEqual({ state: 'unknown', reason: 'provider_write_failed: broken pipe' })
).resolves.toEqual({ state: 'rejected', reason: 'provider_write_failed: broken pipe' })
expect(session.dispatchWaiters).toHaveLength(0)
expect(session.retiredDispatchWaiters).toHaveLength(0)

Expand Down
25 changes: 12 additions & 13 deletions src/main/claude/claude-structured-dispatch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,10 +15,11 @@ import {
claudeDispatchInvokesSlashCommand,
claudeDispatchMessageContent
} from './claude-structured-dispatch-content'
import { dispatchWriteOutcomeUnknownReason } from '../native-chat/agent-session-journal/journal-dispatch-doubt-reasons'
import {
dispatchWriteFailureReason,
dispatchWriteOutcomeUnknownReason
} from '../native-chat/agent-session-journal/journal-dispatch-doubt-reasons'
DISPATCH_REJECTED_QUEUE_FULL,
dispatchWriteFailureReason
} from '../../shared/structured-agent-session-dispatch-rejection'
import { claudeUserMessageWasProvablyUnwritten } from './claude-agent-sdk-user-message-queue'

const MAX_RETIRED_DISPATCH_WAITERS = 64
Expand Down Expand Up @@ -263,7 +264,7 @@ export async function dispatchClaudeTurn(
return { state: 'rejected', reason: (error as Error).message }
}
if (session.dispatchWaiters.length >= MAX_ACTIVE_DISPATCH_WAITERS) {
return { state: 'rejected', reason: 'claude structured dispatch queue is full' }
return { state: 'rejected', reason: DISPATCH_REJECTED_QUEUE_FULL }
}
const dispatchSequence = ++session.dispatchSequence
// Read the sent content, not the journal blocks: only the mapped trailing prompt decides
Expand Down Expand Up @@ -299,21 +300,19 @@ export async function dispatchClaudeTurn(
}
}
}
const provablyUnwritten = claudeUserMessageWasProvablyUnwritten(error)
if (provablyUnwritten) {
if (claudeUserMessageWasProvablyUnwritten(error)) {
forgetWaiter(session, waiter)
forgetRetiredWaiter(session, waiter)
waiter.resolve(null)
} else if (!waiter.retired) {
// The frame was never handed to the SDK's input pump, so this is not doubt:
// the message provably did not happen, which is what `rejected` means.
return { state: 'rejected', reason: dispatchWriteFailureReason(error) }
}
if (!waiter.retired) {
retireWaiter(session, waiter)
waiter.resolve(null)
}
return {
state: 'unknown',
reason: provablyUnwritten
? dispatchWriteFailureReason(error)
: dispatchWriteOutcomeUnknownReason(error)
}
return { state: 'unknown', reason: dispatchWriteOutcomeUnknownReason(error) }
}
// The write is the admission signal. Awaiting the echo here would block on the
// turn already running, which is why the deadline this replaces kept declaring
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ describe('ClaudeStructuredSessionAdapter turns and controls', () => {
expect(settled).not.toHaveBeenCalled()
})

it('puts delivery in doubt only when the write itself fails', async () => {
it('rejects a send whose frame the transport never took', async () => {
const claude = fakeClaude({ replayUuid: null })
const adapter = await acquired(claude)
claude.connections[0]!.send = async () => {
Expand All @@ -68,7 +68,7 @@ describe('ClaudeStructuredSessionAdapter turns and controls', () => {
body: USER_MESSAGE,
fence: 7
})
).resolves.toEqual({ state: 'unknown', reason: 'provider_write_failed: broken pipe' })
).resolves.toEqual({ state: 'rejected', reason: 'provider_write_failed: broken pipe' })
})

it('requires an acknowledged interrupt and supports controlled options', async () => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,10 +16,8 @@ import type {
AgentSessionJournalIdentity
} from '../../../shared/agent-session-journal-types'
import { hasUnansweredStructuredAgentSessionDispatch } from '../../../shared/structured-agent-session-projection'
import {
DISPATCH_DOUBT_RETRY_IN_PROGRESS,
dispatchDoubtProvesUndelivered
} from './journal-dispatch-doubt-reasons'
import { DISPATCH_DOUBT_CODEX_TURN_UNNAMED } from './journal-dispatch-doubt-reasons'
import { dispatchWriteFailureReason } from '../../../shared/structured-agent-session-dispatch-rejection'
import { digestPayload } from './journal-payload-bounds'
import {
reconcileSubmissions,
Expand Down Expand Up @@ -170,56 +168,59 @@ describe('crash between provider accept and journal commit', () => {
expect(restarted.cursor()).toEqual(cursor)
})

it('preserves a proven write failure while retiring its live dispatch', async () => {
it('leaves a rejected write failure settled across a restart', async () => {
const journal = await open()
await journal.appendSubmission({
clientMessageId: 'cm_write_failed',
payloadFingerprint: digestPayload('safe to retry'),
body: userMessage('safe to retry'),
payloadFingerprint: digestPayload('never left the process'),
body: userMessage('never left the process'),
fence: 1
})
await journal.resolveDispatch({
clientMessageId: 'cm_write_failed',
state: 'unknown',
reason: 'provider_write_failed: broken pipe',
state: 'rejected',
reason: dispatchWriteFailureReason(new Error('broken pipe')),
fence: 1
})

const restarted = await open()
await restarted.markPendingSubmissionsUnknown(2)

// A restart re-opens what it could not answer. This one is already answered,
// so recovery must not reopen it as doubt.
expect(restarted.submissions()[0]).toMatchObject({
dispatchState: 'unknown',
reason: 'provider_write_failed: broken pipe',
recovered: true
dispatchState: 'rejected',
reason: 'provider_write_failed: broken pipe'
})
expect(dispatchDoubtProvesUndelivered(restarted.submissions()[0]?.reason)).toBe(true)
expect(restarted.submissions()[0]?.recovered).toBeUndefined()
expect(hasUnansweredStructuredAgentSessionDispatch(restarted.submissions())).toBe(false)
})

it('turns an interrupted retry marker into recovery doubt', async () => {
it('keeps a codex turn it could not name in doubt, never rejected', async () => {
const journal = await open()
await journal.appendSubmission({
clientMessageId: 'cm_retrying',
payloadFingerprint: digestPayload('retry interrupted'),
body: userMessage('retry interrupted'),
clientMessageId: 'cm_codex_unnamed',
payloadFingerprint: digestPayload('codex is running this'),
body: userMessage('codex is running this'),
fence: 1
})
await journal.resolveDispatch({
clientMessageId: 'cm_retrying',
clientMessageId: 'cm_codex_unnamed',
state: 'unknown',
reason: DISPATCH_DOUBT_RETRY_IN_PROGRESS,
reason: DISPATCH_DOUBT_CODEX_TURN_UNNAMED,
fence: 1
})

const restarted = await open()
await restarted.markPendingSubmissionsUnknown(2, 'provider_exited_before_acknowledgement')

// The turn IS started; recovery may not overwrite that with a weaker guess,
// and it may never become a rejection, which would license a re-delivery.
expect(restarted.submissions()[0]).toMatchObject({
dispatchState: 'unknown',
reason: 'provider_exited_before_acknowledgement',
reason: DISPATCH_DOUBT_CODEX_TURN_UNNAMED,
recovered: true
})
expect(dispatchDoubtProvesUndelivered(restarted.submissions()[0]?.reason)).toBe(false)
})

it('reports a rejected submission as never delivered, and never re-sends it', async () => {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,17 +1,15 @@
// Why a submission is in doubt, and whether Orca may put the message on the
// wire a second time.

import type { AgentJournalDispatchState } from '../../../shared/agent-session-journal-types'
// Why a submission is `unknown` — the one state that admits it cannot tell.
//
// `unknown` is never raised by elapsed time; what survives is a process fact that
// ENDS THE WAIT without answering it. Nothing here proves a message reached a
// provider, and nothing here proves it did not: a fact that proves non-delivery
// is a rejection and lives in `structured-agent-session-dispatch-rejection.ts`.
//
// `unknown` is never raised by elapsed time; what survives is a process fact.
// But a process fact that ends the WAIT is not the same claim as one that
// proves the message never reached a provider, and only the second justifies a
// re-delivery. The allowlist below names the reasons that carry the stronger
// claim, and it is deliberately FAIL-CLOSED: a reason nobody adds to it is
// refused. Refusing a legitimate retry costs the user one re-typed message;
// allowing an illegitimate one silently sends the model a second copy, which is
// the harm this whole path exists to remove. When those two are in tension,
// choose the re-type.
// That leaves the invariant this file exists to state: Orca NEVER re-delivers a
// message under its own id on the strength of an `unknown`, whatever the reason
// says. A retry that could be a second delivery is the harm this whole path
// exists to remove, and a user who wants the message sent anyway rotates the id
// — one re-typed message, and a first delivery by construction.

/** A previous process wrote the message and died before learning its outcome. */
export const DISPATCH_DOUBT_HOST_RESTARTED = 'host_restarted_before_acknowledgement'
Expand All @@ -22,53 +20,17 @@ export const DISPATCH_DOUBT_PROVIDER_EXITED = 'provider_exited_before_acknowledg
/** The adapter took the message and only the journal write failed after it. */
export const DISPATCH_DOUBT_PERSISTENCE_FAILED = 'dispatch_result_persistence_failed'

/** A retry was durably armed but had not yet recorded its dispatch outcome. */
export const DISPATCH_DOUBT_RETRY_IN_PROGRESS = 'dispatch_retry_in_progress'

/** Codex owns a turn it started but did not name, because its turn-start still
* settles on a deadline. Delete this once Codex settles on the app-server's
* turn-start response instead; until then this reason is never re-delivered,
* which is what the allowlist below already does by omitting it. */
* settles on a deadline. The turn IS running, so this must never be treated as
* proof of non-delivery. Delete it once Codex settles on the app-server's
* turn-start response instead. */
export const DISPATCH_DOUBT_CODEX_TURN_UNNAMED =
'codex app-server started a turn it did not name in time'

/** The transport refused the frame; the underlying error follows the colon. */
export const DISPATCH_DOUBT_WRITE_FAILED = 'provider_write_failed'

/** The SDK took the frame, but its input pump did not prove whether the write completed. */
export const DISPATCH_DOUBT_WRITE_OUTCOME_UNKNOWN = 'provider_write_outcome_unknown'

export function dispatchWriteFailureReason(error: unknown): string {
const detail = error instanceof Error ? error.message : String(error)
return `${DISPATCH_DOUBT_WRITE_FAILED}: ${detail}`
}

export function dispatchWriteOutcomeUnknownReason(error: unknown): string {
const detail = error instanceof Error ? error.message : String(error)
return `${DISPATCH_DOUBT_WRITE_OUTCOME_UNKNOWN}: ${detail}`
}

/**
* The allowlist. True only where the frame is known never to have been taken by
* a provider, so sending it again is a first delivery rather than a second.
*
* A dead child and a dead host are NOT on this list. Both end the wait, neither
* proves non-delivery: the message was already written to that child's stdin,
* and Claude resumes the same provider session by id, so a message that child
* processed before dying is in the conversation Orca resumes. Deciding those
* needs the message matched against provider history — which is exactly what
* `journal-submission-reconciler.ts` does, and that module has no caller yet.
*/
export function dispatchDoubtProvesUndelivered(reason: string | null | undefined): boolean {
return (
reason === DISPATCH_DOUBT_WRITE_FAILED ||
reason?.startsWith(`${DISPATCH_DOUBT_WRITE_FAILED}: `) === true
)
}

export function dispatchMayMatchProviderEcho(
state: AgentJournalDispatchState,
reason: string | null
): boolean {
return state !== 'rejected' && !(state === 'unknown' && dispatchDoubtProvesUndelivered(reason))
}
Original file line number Diff line number Diff line change
@@ -1,11 +1,8 @@
import {
DISPATCH_DOUBT_HOST_RESTARTED,
DISPATCH_DOUBT_RETRY_IN_PROGRESS
} from './journal-dispatch-doubt-reasons'
import { DISPATCH_DOUBT_HOST_RESTARTED } from './journal-dispatch-doubt-reasons'
import type { AgentSessionJournal } from './journal-store'

/** Settles every submission a process fact left unanswerable. The retry policy
* separately decides whether that fact proves the provider never received it. */
/** Settles every submission a process fact left unanswerable. Doubt is never
* proof of non-delivery, so nothing here ever becomes re-deliverable. */
export async function markJournalPendingSubmissionsUnknown(
journal: AgentSessionJournal,
fence: number,
Expand All @@ -19,12 +16,9 @@ export async function markJournalPendingSubmissionsUnknown(
(entry.dispatchState === 'unknown' && entry.recovered !== true)
)
for (const entry of unresolved) {
// An earlier reason already names a sharper fact than "the host restarted".
const resolvedReason =
entry.dispatchState === 'unknown' &&
entry.reason !== null &&
entry.reason !== DISPATCH_DOUBT_RETRY_IN_PROGRESS
? entry.reason
: reason
entry.dispatchState === 'unknown' && entry.reason !== null ? entry.reason : reason
await journal.resolveDispatch({
clientMessageId: entry.clientMessageId,
state: 'unknown',
Expand Down
Loading
Loading