diff --git a/mobile/src/session/MobileNativeChatNoticeRow.tsx b/mobile/src/session/MobileNativeChatNoticeRow.tsx index 66ad951a078c..153b48769a9d 100644 --- a/mobile/src/session/MobileNativeChatNoticeRow.tsx +++ b/mobile/src/session/MobileNativeChatNoticeRow.tsx @@ -8,6 +8,7 @@ import { type NativeChatNoticeTone } from '../../../src/shared/native-chat-notice' import { isTextBlock, type NativeChatBlock } from '../../../src/shared/native-chat-types' +import { usageLimitLineText } from '../../../src/shared/agent-session-usage-limit-words' import { MobileMarkdown } from '../components/MobileMarkdown' import { INLINE_TEXT_SELECTION } from '../components/inline-text-selection' import { colors, radii, spacing, typography } from '../theme/mobile-theme' @@ -97,6 +98,7 @@ export function MobileNativeChatNoticeRow({ ) case 'line': { + const lineText = usageLimitLineText(notice) const textStyle = [ styles.line, scaledType(TEXT_SIZE, fontScale), @@ -105,7 +107,7 @@ export function MobileNativeChatNoticeRow({ if (!look.tone) { return ( - {notice.text} + {lineText} ) } @@ -120,7 +122,7 @@ export function MobileNativeChatNoticeRow({ style={styles.toneIcon} /> - {notice.text} + {lineText} ) diff --git a/src/main/acp/acp-dialects/grok-dialect.ts b/src/main/acp/acp-dialects/grok-dialect.ts index b38eea156b2c..c90e229480df 100644 --- a/src/main/acp/acp-dialects/grok-dialect.ts +++ b/src/main/acp/acp-dialects/grok-dialect.ts @@ -210,8 +210,5 @@ export const GROK_ACP_DIALECT: AcpDialect = { contextWindow, modelEfforts: grokModelEfforts, promptErrorDetail: (error) => promptErrorDataSchema.safeParse(error.data).data?.message, - failedTurnText: (stopReason) => - stopReason === 'rate_limit' - ? 'Grok usage limit reached.' - : 'Grok ended this turn with an error.' + failedTurnText: () => 'Grok ended this turn with an error.' } diff --git a/src/main/acp/acp-timeline-turn-failures.test.ts b/src/main/acp/acp-timeline-turn-failures.test.ts index 801b85fd9fb8..45a531d1c4f0 100644 --- a/src/main/acp/acp-timeline-turn-failures.test.ts +++ b/src/main/acp/acp-timeline-turn-failures.test.ts @@ -165,14 +165,13 @@ describe('a failed ACP turn says why', () => { expect(failures.map((failure) => failure.body.text)).toEqual([REASON]) }) - it('names a rate-limited turn the provider gave no words for, without inventing a reason', async () => { + it('upgrades an early diagnostic to a usage failure without a later downgrade', async () => { const f = await openAcpFixtureRig() const lane = f.lane() const prompt = lane.openPrompt('c1', 1000) f.apply(lane.notification('_x.ai/queue/changed', queued(prompt.promptId), 1001)) - f.apply( - lane.notification('_x.ai/session_notification', ended(prompt.promptId, 'rate_limit'), 1002) - ) + f.apply(lane.notification('_x.ai/session_notification', retryFailed, 1002)) + f.apply(lane.notification('_x.ai/session_notification', ended(prompt.promptId, 'rate_limit'), 1003)) f.apply( lane.notification( '_x.ai/session/prompt_complete', @@ -180,9 +179,15 @@ describe('a failed ACP turn says why', () => { 1003 ) ) + f.apply(lane.promptFailed('c1', rpcError, 1004)) const failures = statusRows(await f.rig.rows()) expect(failures.map((failure) => failure.body)).toEqual([ - { kind: 'status', tone: 'error', text: 'Grok usage limit reached.' } + { + kind: 'status', + tone: 'warning', + text: 'The agent hit its usage limit. Send a message once it resets to continue.', + failure: { kind: 'usageLimitReached', detail: { text: REASON, audience: 'person' } } + } ]) expect((await f.rig.turns())[0]?.outcome).toBe('failure') }) diff --git a/src/main/acp/acp-turn-failures.ts b/src/main/acp/acp-turn-failures.ts index 87bef9789179..a1123deb35f1 100644 --- a/src/main/acp/acp-turn-failures.ts +++ b/src/main/acp/acp-turn-failures.ts @@ -59,7 +59,10 @@ export function acpSignInRequiredFailure( * reason the row still lacks. */ export class AcpTurnFailures { /** The reason each failed turn's row holds; '' for none yet. */ - private readonly rows = new BoundedMap({ + private readonly rows = new BoundedMap< + string, + { text: string; notSignedIn: boolean; usageLimited: boolean } + >({ maxEntries: 128 }) @@ -91,32 +94,39 @@ export class AcpTurnFailures { ): ProviderTimelineEvent[] { const written = this.rows.peek(turn) const detail = text === undefined ? undefined : providerDiagnostic(text, 'person') + const diagnostic = + (written?.text ? providerDiagnostic(written.text, 'person') : undefined) ?? detail + const authenticationRequired = notSignedIn || written?.notSignedIn === true + // A later copy of the reason (the prompt's error answer) names no stop reason of its own. + const usageLimited = + !authenticationRequired && (stopReason === 'rate_limit' || written?.usageLimited === true) if ( - written !== undefined && - (written.text !== '' || !detail) && - (!notSignedIn || written.notSignedIn) + written && + written.text === (diagnostic?.text ?? '') && + written.notSignedIn === authenticationRequired && + written.usageLimited === usageLimited ) { return [] } - const diagnostic = - detail ?? (written?.text ? providerDiagnostic(written.text, 'person') : undefined) - const authenticationRequired = notSignedIn || written?.notSignedIn === true this.rows.set(turn, { text: diagnostic?.text ?? '', - notSignedIn: authenticationRequired + notSignedIn: authenticationRequired, + usageLimited }) + const failure = authenticationRequired + ? agentSessionFailureFact('notSignedIn', { detail: diagnostic }) + : usageLimited + ? agentSessionFailureFact('usageLimitReached', { detail: diagnostic }) + : null return [ { type: 'item.update', item: `turn-failure:${turn}`, body: { kind: 'status', - tone: 'error', - ...(authenticationRequired - ? agentSessionFailureWords( - agentSessionFailureFact('notSignedIn', { detail: diagnostic }), - { agentName: this.agentName, surface: 'row' } - ) + tone: usageLimited ? 'warning' : 'error', + ...(failure + ? agentSessionFailureWords(failure, { agentName: this.agentName, surface: 'row' }) : { text: diagnostic?.text ?? diff --git a/src/main/claude/claude-command-turn.test.ts b/src/main/claude/claude-command-turn.test.ts index d8dfb63aaadc..f4714bf5497a 100644 --- a/src/main/claude/claude-command-turn.test.ts +++ b/src/main/claude/claude-command-turn.test.ts @@ -52,6 +52,7 @@ function harness() { writes.push(row) } const journal: StructuredAgentSessionRevisionJournal = { + item: () => null, epoch: 'epoch-1', itemBody: (itemId) => rows.get(itemId)?.body ?? null, visitItems: (visit) => { diff --git a/src/main/claude/claude-context-usage-test-support.ts b/src/main/claude/claude-context-usage-test-support.ts index 9823401e264b..659c01c45910 100644 --- a/src/main/claude/claude-context-usage-test-support.ts +++ b/src/main/claude/claude-context-usage-test-support.ts @@ -11,13 +11,20 @@ import type { StructuredAgentSessionEventSink, StructuredAgentSessionRevisionJournal } from '../native-chat/agent-session-wire/structured-agent-session-event-sink' +import { createJournalReducerState } from '../native-chat/agent-session-journal/journal-reducer' +import { personStopDecidesTurn } from '../native-chat/agent-session-journal/journal-stop-turn-end' import type { ClaudeContextReportTarget } from './claude-context-facts' import { createClaudeJournalTranslator } from './claude-structured-journal-translation' import { claudeTurnLifecycleIdentity } from './claude-turn-lifecycle-item' /** A journal in miniature: the latest revision per row, its creation clock * pinned, and revisions resolved against it as a bound sink would. */ -export function journal() { +export function journal({ deferred = false } = {}) { + const queued: (() => void)[] = [] + const run = (write: () => void): void => { + if (deferred) { queued.push(write) } else { write() } + } + const flush = (): void => { while (queued.length) { queued.shift()!() } } const clock = { now: 0 } const appends: { identity: AgentJournalItemIdentity; body: AgentJournalItemBody }[] = [] const rows = new Map() @@ -30,11 +37,12 @@ export function journal() { revision: (existing?.revision ?? 0) + 1, sequence: existing?.sequence ?? rows.size + 1, observedAt: existing?.observedAt ?? options?.observedAt ?? clock.now, - body + ...options, turnScope: existing?.turnScope ?? options.turnScope, body }) } const scans = { count: 0 } const bound: StructuredAgentSessionRevisionJournal = { + item: (itemId) => rows.get(itemId) ?? null, epoch: 'test', visitItems: (visit) => { scans.count += 1 @@ -44,19 +52,24 @@ export function journal() { }, itemBody: (itemId) => rows.get(itemId)?.body ?? null } - const revise: NonNullable = ( + const revise: NonNullable = ( _reservedBytes, resolve, options ) => { - const resolved = resolve(bound) - if (resolved) { - appendItem(resolved.identity, resolved.body, options) - } + run(() => { + const resolved = resolve(bound) + if (resolved) { appendItem(resolved.identity, resolved.body, options) } + }) return { accepted: true } } + const stopState = createJournalReducerState('orca-session', 'test') + const queueStop = (turnId: string, at: number): void => run(() => { + stopState.queuePauseMarks.latestStop = { sequence: rows.size + 1, event: { reason: 'user-stop', turnId, at } } + }) const sink: StructuredAgentSessionEventSink = { - appendItem, + journalStopDecidesTurn: (turnId, at) => personStopDecidesTurn(stopState, turnId, at), + appendItem: (...args) => run(() => appendItem(...args)), tryReviseResolvedItem: revise, tryReviseResolvedItemAndPublish: revise, appendTombstone: () => {}, @@ -65,7 +78,7 @@ export function journal() { const turnRow = (turnId: string) => rows.get(agentJournalItemKey(claudeTurnLifecycleIdentity('claude-session', turnId))) const items = () => [...rows.values()].sort((left, right) => left.sequence - right.sequence) - return { sink, clock, appends, rows, turnRow, items, scans } + return { sink, clock, appends, rows, turnRow, items, scans, flush, queueStop } } export function frame(message: Record, observedAt: number, startsTurn = false) { @@ -146,8 +159,8 @@ export const turnIdentity = (turnId: string) => claudeTurnLifecycleIdentity('claude-session', turnId) /** Every turn the CLI runs opens with an init naming the main model as `modelUsage` keys it. */ -export function setup({ init = 'claude-fable-5-1[1m]' }: { init?: string | null } = {}) { - const state = journal() +export function setup({ init = 'claude-fable-5-1[1m]', deferred = false }: { init?: string | null; deferred?: boolean } = {}) { + const state = journal({ deferred }) const translator = createClaudeJournalTranslator({ sink: state.sink, coalesceMs: 0 }) const requests: ClaudeContextReportTarget[] = [] translator.subscribeContextUsageRequests((target) => requests.push(target)) diff --git a/src/main/claude/claude-message-journaling.ts b/src/main/claude/claude-message-journaling.ts index 1bc7b69d41a7..b7e6b133eec2 100644 --- a/src/main/claude/claude-message-journaling.ts +++ b/src/main/claude/claude-message-journaling.ts @@ -6,6 +6,8 @@ // read off an explicit context, so the open turn and the collaborators it // writes through stay owned by the translator. +import { writeClaudeTerminalFailure } from './claude-terminal-failure' +import { agentSessionFailureWords } from '../../shared/agent-session-failure-words' import { agentJournalItemKey } from '../../shared/agent-session-journal-item-key' import type { StructuredAgentSessionEventSink } from '../native-chat/agent-session-wire/structured-agent-session-event-sink' import type { ClaudeBackgroundTaskRows } from './claude-background-task-rows' @@ -34,6 +36,7 @@ import type { ClaudeSubagentIdentities } from './claude-subagent-identities' import { claudeTurnOpenedBySendEcho, type ClaudeTurnSource } from './claude-turn-opening' import type { ClaudeOpenTurn } from './claude-open-turn' import type { ClaudeAuthenticationFailures } from './claude-authentication-failures' +import type { ClaudeUsageLimits } from './claude-usage-limits' import type { ClaudeThreadGoal } from './claude-thread-goal' export type ClaudeMessageJournalContext = { @@ -53,6 +56,7 @@ export type ClaudeMessageJournalContext = { * latch; this module asks it rather than tracking a copy. */ turn: ClaudeOpenTurn authenticationFailures: ClaudeAuthenticationFailures + usageLimits: ClaudeUsageLimits threadGoal: ClaudeThreadGoal } @@ -92,28 +96,45 @@ export function journalClaudeMessage( const stamp = ctx.corrections.stampFor(producerRef) const outputEnvelope = claudeOutputEnvelope(envelope) ctx.threadGoal.observe(message) + const source: ClaudeTurnSource = { + sessionId: envelope.sessionId, + uuid: envelope.uuid, + assistant: envelope.role === 'assistant' + } + const openOutputTurn = (): void => ctx.turn.ensureOpen(message, source, observedAt) + const messageBody = claudeMessageBody(outputEnvelope) + const ordinaryFailure = typeof message.api_error === 'string' && message.api_error !== 'usage_limit_reached' + ? { kind: 'status' as const, tone: 'error' as const, ...agentSessionFailureWords({ kind: 'providerRejected' }, { agentName: 'Claude', provider: 'claude', surface: 'row' }) } : null + const terminal = envelope.role === 'assistant' && producerRef === null && + (typeof message.api_error === 'string' || message.error === 'rate_limit') + if (envelope.role === 'assistant' && + (messageBody || typeof message.api_error === 'string' || message.error === 'rate_limit')) { + openOutputTurn() + } + const usageLimit = ctx.usageLimits.assistant(message, ctx.turn) const body = ctx.authenticationFailures.assistant(message) ?? + usageLimit ?? ctx.threadGoal.report(message, claudeMessageIdentity(envelope), observedAt) ?? - claudeMessageBody(outputEnvelope) + messageBody ?? ordinaryFailure + const terminalIdentity = terminal && ctx.turn.identity && usageLimit + ? ctx.turn.identity : null const identity = (body && envelope.role === 'assistant' ? ctx.streamedBlocks.reconcile(envelope)?.identity : null) ?? claudeMessageIdentity(envelope) ctx.streamedText.forget(agentJournalItemKey(identity)) const thinking = ctx.streamedThinking.finalize(outputEnvelope, observedAt) - const source: ClaudeTurnSource = { - sessionId: envelope.sessionId, - uuid: envelope.uuid, - assistant: envelope.role === 'assistant' - } - const openOutputTurn = (): void => ctx.turn.ensureOpen(message, source, observedAt) if (body) { // Opening before the append is what brackets a turn around its own first // output; a reader that scans back to the turn record and stops would // otherwise look straight past the row that opened it. ctx.turn.ensureOpen(message, source, observedAt) - ctx.sink.appendItem(identity, body, stamp(identity, body)) + if (terminalIdentity) { + writeClaudeTerminalFailure(ctx.sink, terminalIdentity, body) + } else { + ctx.sink.appendItem(identity, body, stamp(identity, body)) + } changed = true } for (const tool of claudeToolUses(outputEnvelope)) { diff --git a/src/main/claude/claude-open-turn.ts b/src/main/claude/claude-open-turn.ts index e7c36ddaac04..88b5a2bd2eae 100644 --- a/src/main/claude/claude-open-turn.ts +++ b/src/main/claude/claude-open-turn.ts @@ -21,6 +21,8 @@ import { import { writeAgentJournalTurnRow } from '../native-chat/agent-session-timeline/agent-journal-turn-row-revision' import type { ClaudeCommandTurn } from './claude-command-turn' import { createClaudeTurnOpener, type ClaudeTurnSource } from './claude-turn-opening' +import { refineClaudeQuotaTurnEnd } from './claude-terminal-failure' +import type { ClaudeUsageLimitEvidence } from './claude-usage-limits' import type { ClaudeStartedSend } from './claude-structured-session-state' export type ClaudeOpenTurnDeps = { @@ -35,6 +37,7 @@ export type ClaudeOpenTurnDeps = { export class ClaudeOpenTurn { private current: ClaudeCurrentTurn | null = null + usageLimitEvidence: ClaudeUsageLimitEvidence | null = null /** Provider output may not reopen a turn after the session ended or a turn * failed: nothing would ever close the turn it opened, and the row would read * working for the life of the session. Only an accepted send lifts it. */ @@ -125,6 +128,7 @@ export class ClaudeOpenTurn { * later would sweep THIS turn. The replaced turn is recorded superseded: a newer * request ended it, whoever sent that request. */ open(turn: ClaudeCurrentTurn, observedAt: number): void { + this.usageLimitEvidence = null this.deps.onOpen?.() if (this.current) { this.deps.turnSuperseded() @@ -143,6 +147,7 @@ export class ClaudeOpenTurn { /** A conversation command the host opened a turn for. Its row is the host's, already written, * so only an end is published; the command's result is what ends it. */ beginCommand(turn: ClaudeCurrentTurn): void { + this.usageLimitEvidence = null this.deps.onOpen?.() if (this.current) { this.deps.turnSuperseded() @@ -167,6 +172,7 @@ export class ClaudeOpenTurn { /** The command was never sent; its turn is the host's to settle. */ forgetCommand(turnId: string): void { if (this.current?.command && this.current.turnId === turnId) { + this.usageLimitEvidence = null this.current = null } } @@ -185,12 +191,16 @@ export class ClaudeOpenTurn { /** End the open turn, if one is open, and clear the live activity line. The * context facts the end brings ride the same revision. */ settle(end: ClaudeTurnEnd, contextUsage?: AgentSessionContextUsage): void { + const quotaEnd = this.current !== null && end.outcome === undefined && + this.usageLimitEvidence?.cause === 'quota' + this.suppressReopenOnFailure(quotaEnd) // Every settle is a provider cycle ending (result, idle, child exit). this.cycleWorkObserved = false + this.usageLimitEvidence = null // Even with no turn open: work a suppressed turn produced still ends here. this.deps.endOpenWork(end.completedAt) if (this.current) { - this.publish(this.current, end, contextUsage) + this.publish(this.current, end, contextUsage, quotaEnd) this.current = null } this.deps.sink.setActivity?.(null) @@ -216,13 +226,18 @@ export class ClaudeOpenTurn { private publish( turn: ClaudeCurrentTurn, end?: ClaudeTurnEnd, - contextUsage?: AgentSessionContextUsage + contextUsage?: AgentSessionContextUsage, + quotaEnd = false ): void { const item = claudeTurnLifecycleItem(turn, end) + const write = { lifecycle: item.body, ...(contextUsage ? { contextUsage } : {}) } + if (quotaEnd && refineClaudeQuotaTurnEnd(this.deps.sink, item.identity, write)) { + return + } writeAgentJournalTurnRow( this.deps.sink, { identity: item.identity }, - { lifecycle: item.body, ...(contextUsage ? { contextUsage } : {}) }, + write, { publish: false, options: item.options } ) // Keyed apart, so this never replaces the start's publication while it still waits to run. diff --git a/src/main/claude/claude-result-journaling.ts b/src/main/claude/claude-result-journaling.ts index 9e68e852f352..74df8eb43b17 100644 --- a/src/main/claude/claude-result-journaling.ts +++ b/src/main/claude/claude-result-journaling.ts @@ -4,6 +4,7 @@ // Split out of the translator when that file reached its line budget; the translator still owns // the open turn and every collaborator this writes through. +import { writeClaudeTerminalFailure } from './claude-terminal-failure' import type { ClaudeContextFacts } from './claude-context-facts' import { claudeCommandResultEnd } from './claude-command-turn' import type { ClaudeMessageJournalContext } from './claude-message-journaling' @@ -26,6 +27,7 @@ export type ClaudeResultJournalContext = Pick< | 'corrections' | 'turn' | 'authenticationFailures' + | 'usageLimits' | 'threadGoal' > & { prompts: ClaudeJournalPrompts @@ -44,6 +46,7 @@ export function journalClaudeResult( prompts, context, authenticationFailures, + usageLimits, threadGoal, goalBackgroundWork }: ClaudeResultJournalContext, @@ -55,49 +58,51 @@ export function journalClaudeResult( // diagnostic below still runs: a child's failure is reportable even when // it ends no turn. const settlesTurn = isRootClaudeFrame(message) - const commandEnd = settlesTurn ? claudeCommandResultEnd(turn, sink, message, observedAt) : null - if (commandEnd === 'another-input') { - return - } - // Read before the settle below closes it: the result reports that turn's end. const endedTurnScope = turn.turnScope + const endedTurnIdentity = turn.identity + const usageEvidence = turn.usageLimitEvidence const endedTurnStartedAt = turn.startedAt - // Read before the settle below closes the turn: an error end the journal's Stop rule makes a - // person's cancellation is theirs to decide as the end is written (`turnEndAfterStop`). const turnId = settlesTurn ? turn.id : null const leftToStop = turnId !== null && sink.journalStopDecidesTurn?.(turnId, observedAt) === true + // Retry owed prompt cancellations before a command result can return. if (settlesTurn) { prompts.retryPendingCancellations() + } + const commandEnd = settlesTurn ? claudeCommandResultEnd(turn, sink, message, observedAt) : null + if (commandEnd === 'another-input') { + return + } + const failure = claudeResultFailure(message, leftToStop) + const usageLimit = settlesTurn ? usageLimits.result(message, failure !== null, usageEvidence) : null + if (usageLimit && endedTurnIdentity) { + writeClaudeTerminalFailure(sink, endedTurnIdentity, usageLimit) + } + if (settlesTurn) { turn.suppressReopenOnFailure(message.is_error === true) corrections.abandon() context.settle(message, commandEnd ?? claudeTurnEndForResult(message, observedAt, leftToStop)) - // The turn is over. A block still awaiting its final keeps the text the - // flush above journaled, but its live state goes: an interrupted turn - // would otherwise retain that text for the life of the session. streamedBlocks.clear() streamedText.settle() } - const goal = threadGoal.settle( - message, - { - backgroundWork: goalBackgroundWork(), - stoppedByPerson: leftToStop, - turnStartedAt: endedTurnStartedAt - }, - observedAt - ) + const goal = threadGoal.settle(message, { + backgroundWork: goalBackgroundWork(), + stoppedByPerson: leftToStop, + turnStartedAt: endedTurnStartedAt + }, observedAt) if (goal) { sink.appendItem(goal.identity, goal.body, { turnScope: endedTurnScope }) sink.publish() } const kind = claudeProviderFrameKind(message) - const failure = claudeResultFailure(message, leftToStop) + if (usageLimit && endedTurnIdentity) { + return + } const alreadyShown = authenticationFailures.resultAlreadyShown(message) if ((failure || !isSettledClaudeResultKind(kind)) && !alreadyShown) { providerFallback.append( kind, message, - failure?.text, + usageLimit ?? failure?.text, undefined, { reportsFailure: failure !== null }, // A result that settles no turn is a CHILD's result: this diff --git a/src/main/claude/claude-structured-journal-translation.ts b/src/main/claude/claude-structured-journal-translation.ts index a8da78e9a94d..5232ac200e19 100644 --- a/src/main/claude/claude-structured-journal-translation.ts +++ b/src/main/claude/claude-structured-journal-translation.ts @@ -34,6 +34,7 @@ import { claudeChildToolQueries } from './claude-child-tool-queries' import { journalClaudeMessage, type ClaudeMessageJournalContext } from './claude-message-journaling' import { journalClaudeResult, type ClaudeResultJournalContext } from './claude-result-journaling' import { ClaudeAuthenticationFailures } from './claude-authentication-failures' +import { ClaudeUsageLimits } from './claude-usage-limits' import { ClaudeThreadGoal } from './claude-thread-goal' import type { ClaudeGoalBackgroundWork } from './claude-background-task-tracker' import type { AgentSessionAccountKind } from '../../shared/agent-session-availability' @@ -170,6 +171,7 @@ export function createClaudeJournalTranslator( corrections, turn, authenticationFailures: new ClaudeAuthenticationFailures(deps.account), + usageLimits: new ClaudeUsageLimits(), threadGoal: new ClaudeThreadGoal(() => deps.sink.journalLinkage?.()?.threadGoalSource()) } @@ -249,6 +251,7 @@ export function createClaudeJournalTranslator( journalClaudeResult(resultContext, event.message, event.observedAt ?? Date.now()) } else if (event.type === 'message') { backgroundTasks.observe(event.message, event.observedAt ?? Date.now()) + messageContext.usageLimits.observe(event.message) const kind = claudeProviderFrameKind(event.message) if ( !handleMessage( @@ -269,10 +272,7 @@ export function createClaudeJournalTranslator( } context.observeResponse(event.message, event.observedAt ?? Date.now()) publishActivity(kind, event.message) - // The CLI's own turn-over signal, and the only end a turn stopped by a - // fault with no result frame ever gets. Reopen stays allowed: output - // after an idle belongs to a turn, and suppressing it would read as - // idle while the agent works. + // Idle also closes faults without a result; the live cause decides failed reopening. if (claudeSessionStateEndsTurn(event.message)) { corrections.abandon() // No verdict: the CLI said the turn is over, not how it ended. diff --git a/src/main/claude/claude-structured-provider-fallback.ts b/src/main/claude/claude-structured-provider-fallback.ts index b8a84133e222..53da9cab6f13 100644 --- a/src/main/claude/claude-structured-provider-fallback.ts +++ b/src/main/claude/claude-structured-provider-fallback.ts @@ -1,4 +1,8 @@ -import type { AgentJournalTurnScope } from '../../shared/agent-session-journal-types' +import type { + AgentJournalStatusItem, + AgentJournalTurnScope +} from '../../shared/agent-session-journal-types' +import type { AgentSessionFailureRowWords } from '../../shared/agent-session-failure-words' import type { StructuredAgentSessionEventSink } from '../native-chat/agent-session-wire/structured-agent-session-event-sink' import { boundInlineText, @@ -132,11 +136,12 @@ export function createClaudeProviderFrameFallback( /** The frame's turn — the open one once `beforeAppend` ran — or the conversation. */ turnScope: () => AgentJournalTurnScope ): { - /** `displayText` leads the row when Claude knows the sentence the frame itself does not name. */ + /** `display` leads the row when Claude knows the sentence the frame itself does not name; a + * status body in its place also sets the row's tone and fact. */ append: ( kind: string, payload: unknown, - displayText?: string | null, + display?: string | null | (AgentSessionFailureRowWords & { tone: string }), /** Runs only when a row is actually going to be written, so a frame that * translates to nothing never opens a turn. */ beforeAppend?: () => void, @@ -149,7 +154,7 @@ export function createClaudeProviderFrameFallback( let sequence = 0 const retryRun = createClaudeApiRetryRuns() return { - append: (kind, payload, displayText, beforeAppend, options, stamp) => { + append: (kind, payload, display, beforeAppend, options, stamp) => { sequence += 1 const retrying = kind === CLAUDE_API_RETRY_FRAME_KIND ? claudeRecord(payload) : null if (retrying) { @@ -190,14 +195,20 @@ export function createClaudeProviderFrameFallback( return false } beforeAppend?.() - const bounded = displayText - ? boundInlineText(displayText, DEFAULT_JOURNAL_PAYLOAD_LIMITS).text - : null + const bounded = + typeof display === 'string' && display + ? boundInlineText(display, DEFAULT_JOURNAL_PAYLOAD_LIMITS).text + : null const identity = { provider: 'orca', clientMessageId: `provider-frame:claude:${acquisitionId}:${sequence}` } as const - const body = bounded ? { ...translated.body, text: bounded } : translated.body + const body: AgentJournalStatusItem = + display && typeof display === 'object' + ? { ...translated.body, ...display } + : bounded + ? { ...translated.body, text: bounded } + : translated.body sink.appendItem(identity, body, stamp?.(identity, body) ?? { turnScope: turnScope() }) sink.publish() return true diff --git a/src/main/claude/claude-terminal-failure.ts b/src/main/claude/claude-terminal-failure.ts new file mode 100644 index 000000000000..1afb24d1d5aa --- /dev/null +++ b/src/main/claude/claude-terminal-failure.ts @@ -0,0 +1,92 @@ +import { agentJournalItemKey } from '../../shared/agent-session-journal-item-key' +import type { + AgentJournalItemBody, + AgentJournalItemIdentity +} from '../../shared/agent-session-journal-types' +import { isRootAgentJournalItem } from '../../shared/agent-session-journal-producer' +import { readAgentSessionFailureFact, providerDiagnostic } from '../../shared/agent-session-failure' +import { agentSessionFailureWords } from '../../shared/agent-session-failure-words' +import type { + StructuredAgentSessionEventSink, + StructuredAgentSessionRevisionJournal +} from '../native-chat/agent-session-wire/structured-agent-session-event-sink' +import { + agentJournalTurnRowReservedBytes, + resolveAgentJournalTurnRowWrite, + type AgentJournalTurnRowWrite +} from '../native-chat/agent-session-timeline/agent-journal-turn-row-revision' + +function claudeTerminalFailureIdentity(turnItemId: string): AgentJournalItemIdentity { + return { provider: 'orca', clientMessageId: `terminal-failure:claude:${turnItemId}` } +} + +export function writeClaudeTerminalFailure( + sink: StructuredAgentSessionEventSink, + identity: AgentJournalItemIdentity, + body: AgentJournalItemBody +): void { + const turnItemId = agentJournalItemKey(identity) + const failureIdentity = claudeTerminalFailureIdentity(turnItemId) + const options = { turnScope: { kind: 'turn' as const, turnItemId } } + const revise = sink.tryReviseResolvedItemAndPublish + if (!revise) { + sink.appendItem(failureIdentity, body, options) + sink.publish() + return + } + const reservedBytes = Buffer.byteLength(JSON.stringify({ failureIdentity, body }), 'utf8') + 8192 + revise.call(sink, reservedBytes, (journal) => mergeClaudeTerminalFailure(journal, identity, body), options) +} + +function mergeClaudeTerminalFailure( + journal: StructuredAgentSessionRevisionJournal, + identity: AgentJournalItemIdentity, + body: AgentJournalItemBody +) { + const failureIdentity = claudeTerminalFailureIdentity(agentJournalItemKey(identity)) + const old = journal.itemBody(agentJournalItemKey(failureIdentity)) + const prior = old?.kind === 'status' ? readAgentSessionFailureFact(old.failure) : undefined + const next = body.kind === 'status' ? readAgentSessionFailureFact(body.failure) : undefined + const previousDetail = prior?.detail?.text + const incomingDetail = next?.detail?.text + const detail = previousDetail && incomingDetail && !previousDetail.includes(incomingDetail) + ? `${previousDetail}\n${incomingDetail}` : previousDetail ?? incomingDetail ?? '' + const merged = prior?.kind === 'usageLimitReached' && next?.kind === 'usageLimitReached' + ? { ...body, ...agentSessionFailureWords({ + ...prior, ...next, + usageLimit: next.usageLimit ?? prior.usageLimit, + detail: providerDiagnostic(detail, 'person') + }, { agentName: 'Claude', provider: 'claude', surface: 'row' }) } + : body + return JSON.stringify(merged) === JSON.stringify(old) + ? null : { identity: failureIdentity, body: merged } +} + +// Refine only the ending row after its quota and any person Stop have landed. +export function refineClaudeQuotaTurnEnd( + sink: StructuredAgentSessionEventSink, + identity: AgentJournalItemIdentity, + write: AgentJournalTurnRowWrite +): boolean { + const revise = sink.tryReviseResolvedItemAndPublish + if (!revise || !write.lifecycle || write.lifecycle.outcome !== undefined) { + return false + } + const lifecycle = write.lifecycle + const target = { identity } + const reservedBytes = agentJournalTurnRowReservedBytes(target, write) + revise.call(sink, reservedBytes, (journal) => { + const itemId = agentJournalItemKey(identity) + const row = journal.item(agentJournalItemKey(claudeTerminalFailureIdentity(itemId))) + const quota = row?.body.kind === 'status' && isRootAgentJournalItem(row) && + row.turnScope?.kind === 'turn' && row.turnScope.turnItemId === itemId && + readAgentSessionFailureFact(row.body.failure)?.kind === 'usageLimitReached' + const stopped = lifecycle.completedAt !== undefined && + sink.journalStopDecidesTurn?.(lifecycle.turnId, lifecycle.completedAt) + const outcome = quota ? (stopped ? 'cancellation' : 'failure') : undefined + return resolveAgentJournalTurnRowWrite(journal, target, { + ...write, lifecycle: { ...lifecycle, ...(outcome ? { outcome } : {}) } + }, reservedBytes) + }, { turnScope: { kind: 'thread' } }) + return true +} diff --git a/src/main/claude/claude-thread-goal-journaling.test.ts b/src/main/claude/claude-thread-goal-journaling.test.ts index 07fffc8e32ba..f117ee156e5e 100644 --- a/src/main/claude/claude-thread-goal-journaling.test.ts +++ b/src/main/claude/claude-thread-goal-journaling.test.ts @@ -6,6 +6,7 @@ import type { } from '../../shared/agent-session-journal-types' import type { StructuredAgentSessionEventSink } from '../native-chat/agent-session-wire/structured-agent-session-event-sink' import { createClaudeJournalTranslator } from './claude-structured-journal-translation' +import { journal } from './claude-context-usage-test-support' import { ClaudeBackgroundTaskTracker } from './claude-background-task-tracker' import { MOVED_TO_BACKGROUND } from './claude-captured-task-frames.test-fixture' @@ -15,13 +16,15 @@ const OBJECTIVE = 'reply with exactly the word done' function goalSink( journalGoal: AgentJournalThreadGoal | null = null, - journalRow?: { identity: AgentJournalItemIdentity; body: AgentJournalItemBody } + journalRow?: { identity: AgentJournalItemIdentity; body: AgentJournalItemBody }, + deferred = false ) { - const rows: { identity: AgentJournalItemIdentity; body: AgentJournalItemBody }[] = [] + const state = journal({ deferred }) + const rows = state.appends let stopped = false const backgroundTasks = new ClaudeBackgroundTaskTracker() const sink: StructuredAgentSessionEventSink = { - appendItem: (identity, body) => rows.push({ identity, body }), + ...state.sink, appendTombstone: vi.fn(), publish: vi.fn(), journalStopDecidesTurn: () => stopped, @@ -46,6 +49,7 @@ function goalSink( let at = 1_000 const frame = (message: Record, elapsedMs = 1_000) => { at += elapsedMs + state.clock.now = at backgroundTasks.observe(message) translator.handle({ type: 'message', @@ -73,12 +77,12 @@ function goalSink( const pressStop = () => { stopped = true } - return { frame, reply, result, goals, savedGoal, pressStop } + return { frame, reply, result, goals, savedGoal, pressStop, flush: state.flush } } describe('Claude /goal journaling', () => { - it('journals the goal Claude reports, its time, and its completion when Claude ends on its own', () => { - const { reply, result, goals } = goalSink() + it.each([false, true])('journals the goal and its completion before adjacent idle (deferred %s)', (deferred) => { + const { frame, reply, result, goals, flush } = goalSink(null, undefined, deferred) reply('goal-set', '', `Goal set: ${OBJECTIVE}`) reply('work-1', 'claude-haiku-4-5', 'Working on it.') // A turn cap stops Claude before the goal passes: the goal stays open and gains the time. @@ -87,8 +91,11 @@ describe('Claude /goal journaling', () => { { subtype: 'error_max_turns', is_error: true, terminal_reason: 'max_turns' }, 5_000 ) + frame({ type: 'system', subtype: 'session_state_changed', state: 'idle' }, 1) reply('work-2', 'claude-haiku-4-5', 'done') result('result-2', { subtype: 'success', is_error: false, terminal_reason: 'completed' }, 3_000) + frame({ type: 'system', subtype: 'session_state_changed', state: 'idle' }, 1) + flush() expect(goals()).toEqual([ { diff --git a/src/main/claude/claude-usage-limits.test.ts b/src/main/claude/claude-usage-limits.test.ts new file mode 100644 index 000000000000..45ee1520724b --- /dev/null +++ b/src/main/claude/claude-usage-limits.test.ts @@ -0,0 +1,264 @@ +import { describe, expect, it, vi } from 'vitest' +import { latestNativeChatUsageLimitCut } from '../../shared/native-chat-usage-limit-cut' +import { agentJournalSubmissionKey } from '../../shared/agent-session-journal-item-key' +import { adapterFor, fakeClaude, identityFor, PROVIDER_SESSION_ID, USER_MESSAGE } from './claude-structured-session-test-support' +import { assistantFrame, frame, setup, userFrame } from './claude-context-usage-test-support' + +// Seconds, as Claude sends them; two hours out so no reset passes mid-test. +const RESETS_AT_S = Math.floor(Date.now() / 1000) + 2 * 3600 + +const rateLimitEvent = (status: string, at: number) => + frame( + { + type: 'rate_limit_event', + uuid: `rate-${at}`, + rate_limit_info: { status, rateLimitType: 'five_hour', resetsAt: RESETS_AT_S } + }, + at + ) + +const refusedFrame = (uuid: string, at: number, text: string) => + frame( + { + type: 'assistant', + uuid, + user_message_uuid: `turn-${uuid}`, + error: 'rate_limit', + is_api_error_message: true, + message: { role: 'assistant', content: [{ type: 'text', text }] } + }, + at + ) + +const failedResult = (uuid: string, at: number, text: string) => + frame( + { + type: 'result', + subtype: 'success', + is_error: true, + result: text, + uuid: `result-${uuid}`, + user_message_uuid: `turn-${uuid}`, + duration_ms: 10 + }, + at + ) + +const LIMIT_TEXT = "You've hit your limit · resets 3pm" + +function statusRows(t: ReturnType) { + return t.items().flatMap((item) => (item.body.kind === 'status' ? [item.body] : [])) +} + +function messageTexts(t: ReturnType): string[] { + return t + .items() + .flatMap((item) => + item.body.kind === 'message' + ? item.body.blocks.flatMap((block) => (block.type === 'text' ? [block.text] : [])) + : [] + ) +} + +describe('a Claude usage limit', () => { + it.each([false, true])('keeps one limit row across a result and idle (quota first %s)', (quotaFirst) => { + const t = setup() + if (!quotaFirst) { t.handle(userFrame('turn-a', 1_000)) } + t.handle(rateLimitEvent('rejected', 1_100)) + if (!quotaFirst) { + t.handle(frame({ ...assistantFrame('first', 1_150, 20).message, user_message_uuid: 'turn-a' }, 1_150)) + } + t.handle(frame({ + ...refusedFrame('a', 1_200, LIMIT_TEXT).message, + user_message_uuid: undefined, + api_error: 'usage_limit_reached' + }, 1_200)) + t.handle(failedResult('a', 1_300, 'Request failed')) + t.handle(frame({ type: 'system', subtype: 'session_state_changed', state: 'idle' }, 1_301)) + // The CLI throttles an unchanged rejection: the next turn carries none. + t.handle(userFrame('turn-b', 2_000)) + t.handle(refusedFrame('b', 2_200, LIMIT_TEXT)) + t.handle(failedResult('b', 2_300, LIMIT_TEXT)) + + const limitRow = { + kind: 'status', + tone: 'warning', + text: 'Claude hit its session limit. Send a message once it resets to continue.', + failure: { + kind: 'usageLimitReached', + usageLimit: { window: 'session', resetsAt: RESETS_AT_S * 1000 }, + detail: { text: LIMIT_TEXT, audience: 'person' } + } + } + expect(statusRows(t)).toEqual([ + { ...limitRow, failure: { ...limitRow.failure, + detail: { text: `${LIMIT_TEXT}\nRequest failed`, audience: 'person' } } }, + limitRow + ]) + expect(messageTexts(t)).not.toContain(LIMIT_TEXT) + t.translator.dispose() + }) + + it('keeps a removed-media notice before later work and its usage-limit warning', () => { + const t = setup({ deferred: true }) + const removed = 'API Error: the image could not be processed and was removed' + t.handle(userFrame('turn-a', 1000)) + t.handle(frame({ ...refusedFrame('media', 1100, removed).message, + api_error: 'media_removed', error: undefined, user_message_uuid: 'turn-a' }, 1100)) + t.handle(assistantFrame('answer', 1200, 20)) + t.handle(frame({ ...refusedFrame('a', 1300, LIMIT_TEXT).message, + api_error: 'usage_limit_reached' }, 1300)) + t.handle(failedResult('a', 1400, LIMIT_TEXT)) + t.flush() + const visible = t.items().flatMap(({ body }) => + body.kind === 'message' && body.role === 'assistant' + ? body.blocks.flatMap((block) => block.type === 'text' ? [block.text] : []) + : body.kind === 'status' && body.failure?.kind === 'usageLimitReached' ? ['quota'] : [] + ) + expect(visible).toEqual([removed, 'answer', 'quota']) + t.translator.dispose() + }) + + it('keeps typed other causes and replacement turns separate from the account snapshot', () => { + const t = setup() + t.handle(userFrame('turn-limited', 1_000)) + t.handle(rateLimitEvent('rejected', 1_100)) + t.handle(refusedFrame('limited', 1_200, LIMIT_TEXT)) + // No result: a replacement turn must not inherit the previous refusal. + t.handle(userFrame('turn-credits', 2_000)) + t.handle(frame({ + ...refusedFrame('credits', 2_100, 'This model requires usage credits').message, + api_error: 'model_requires_usage_credits' + }, 2_100)) + t.handle(frame({ + ...failedResult('credits', 2_200, 'This model requires usage credits').message, + terminal_reason: 'api_error', api_error_status: 429 + }, 2_200)) + expect(statusRows(t).filter((row) => row.failure?.kind === 'usageLimitReached')).toHaveLength(1) + expect(statusRows(t).some((row) => row.text.includes('requires usage credits'))).toBe(true) + t.handle(userFrame('turn-context', 2300)) + t.handle(frame({ ...refusedFrame('context', 2400, 'Prompt is too long').message, + error: 'invalid_request' }, 2400)) + t.handle(frame({ ...failedResult('context', 2500, 'Prompt is too long').message, + terminal_reason: 'blocking_limit', api_error_status: null }, 2500)) + expect(statusRows(t).at(-1)).toMatchObject({ tone: 'error', text: 'Prompt is too long' }) + t.translator.dispose() + }) + + it('keeps an explicit quota cause without metadata and expires snapshot inference', () => { + const clock = vi.spyOn(Date, 'now').mockReturnValue(RESETS_AT_S * 1000 - 1000) + try { + const t = setup() + t.handle(userFrame('turn-typed', 1000)) + t.handle(frame({ ...refusedFrame('typed', 1100, LIMIT_TEXT).message, + api_error: 'usage_limit_reached' }, 1100)) + t.handle(failedResult('typed', 1200, LIMIT_TEXT)) + t.handle(rateLimitEvent('rejected', 1300)) + clock.mockReturnValue(RESETS_AT_S * 1000 + 1000) + t.handle(userFrame('turn-expired', 2000)) + t.handle(refusedFrame('expired', 2100, 'Request rejected')) + t.handle(failedResult('expired', 2200, 'Request rejected')) + const limits = statusRows(t).filter((row) => row.failure?.kind === 'usageLimitReached') + expect(limits).toHaveLength(1) + expect(limits[0]?.failure?.usageLimit).toBeUndefined() + t.translator.dispose() + } finally { + clock.mockRestore() + } + }) + + it('leaves a throttle once the limit allows requests again', () => { + const t = setup() + t.handle(rateLimitEvent('rejected', 1_100)) + t.handle(rateLimitEvent('allowed_warning', 1_500)) + t.handle(userFrame('turn-a', 2_000)) + t.handle(refusedFrame('a', 2_200, 'API Error: Request rejected (429)')) + t.handle(failedResult('a', 2_300, 'API Error: Request rejected (429)')) + + expect(statusRows(t).map((row) => row.failure?.kind)).not.toContain('usageLimitReached') + expect(statusRows(t)).toContainEqual( + expect.objectContaining({ tone: 'error', text: 'API Error: Request rejected (429)' }) + ) + t.translator.dispose() + }) +}) + +const quota = (uuid: string, stamp?: string) => frame({ + ...refusedFrame(uuid, 1100, LIMIT_TEXT).message, + user_message_uuid: stamp, api_error: 'usage_limit_reached' +}, 1100) + +it.each(['idle', 'exit'] as const)('keeps quota failure and Continue through a deferred resultless %s', (ending) => { + const t = setup({ deferred: true }) + t.handle(userFrame('owner', 1000)) + t.handle(quota('refusal', 'owner')) + if (ending === 'idle') { + t.handle(frame({ type: 'system', subtype: 'session_state_changed', state: 'idle' }, 1200)) + } else { + t.handle({ type: 'ended', sessionId: 'orca-session', reason: 'Provider exited', observedAt: 1200 }) + } + t.flush() + expect(t.turnRow('owner')?.body).toMatchObject({ + state: ending === 'idle' ? 'completed' : 'interrupted', outcome: 'failure' + }) + expect(latestNativeChatUsageLimitCut(t.items(), [])).not.toBeNull() + t.translator.dispose() +}) + +it.each(['before', 'after', 'child', 'ordinary', 'success', 'other', 'superseded'] as const)('preserves %s precedence over resultless quota inference', (mode) => { + const t = setup({ deferred: true }) + t.handle(userFrame('owner', 1000)) + if (mode !== 'ordinary') { + t.handle(frame({ ...quota('refusal', 'owner').message, + ...(mode === 'child' ? { parent_tool_use_id: 'child-tool' } : {}) }, 1100)) + } + if (mode === 'other') { + t.handle(frame({ ...refusedFrame('other', 1150, 'Requires credits').message, + api_error: 'model_requires_usage_credits', user_message_uuid: 'owner' }, 1150)) + } + if (mode === 'before') { + t.queueStop('owner', 1150) + expect(t.sink.journalStopDecidesTurn?.('owner', 1200)).toBe(false) + } + if (mode === 'success') { + t.handle(frame({ type: 'result', subtype: 'success', is_error: false, result: 'done' }, 1200)) + } else if (mode === 'superseded') { + t.handle(userFrame('newer', 1200)) + } else if (mode === 'before') { + t.handle(frame({ type: 'system', subtype: 'session_state_changed', state: 'idle' }, 1200)) + } else { + t.handle({ type: 'ended', sessionId: 'orca-session', reason: 'Provider exited', observedAt: 1200 }) + } + if (mode === 'after') { t.queueStop('owner', 1300) } + t.flush() + const outcome = mode === 'before' ? 'cancellation' : mode === 'after' ? 'failure' + : mode === 'success' ? 'success' : mode === 'superseded' ? 'superseded' : undefined + const body = t.turnRow('owner')?.body + expect(body?.kind === 'turn' ? body.outcome : null).toEqual(outcome) + expect(latestNativeChatUsageLimitCut(t.items(), []) !== null).toBe(mode === 'after') + t.translator.dispose() +}) + +it('retains a newly accepted pre-echo failure after acquisition has consumed its exact waiter', async () => { + const t = setup() + t.translator.dispose() + const claude = fakeClaude({ replayUuid: null }) + const adapter = adapterFor(claude) + await adapter.acquire({ identity: identityFor(), fence: 7, spawnToken: 'quota-test', events: t.sink }) + const connection = claude.connections[0]! + const emit = (message: Record) => connection.handlers.onMessage?.({ + parent_tool_use_id: null, ...message, session_id: PROVIDER_SESSION_ID + }) + await adapter.dispatch({ sessionId: 'session-1', clientMessageId: 'first', body: USER_MESSAGE, fence: 7 }) + emit({ ...connection.sent[0], uuid: 'owner' }) + emit(quota('refusal', 'owner').message) + emit({ ...failedResult('owner', 1200, LIMIT_TEXT).message, user_message_uuid: 'owner' }) + t.sink.appendItem({ provider: 'orca', clientMessageId: 'new-send' }, USER_MESSAGE, { turnScope: { kind: 'thread' } }) + await adapter.dispatch({ sessionId: 'session-1', clientMessageId: 'new-send', body: USER_MESSAGE, fence: 7 }) + const sent = connection.sent.at(-1)! + emit({ type: 'result', uuid: 'new-result', user_message_uuid: sent.uuid, + subtype: 'error_during_execution', is_error: true, result: 'Fresh request rejected' }) + expect(t.items().some((item) => item.itemId === agentJournalSubmissionKey('new-send'))).toBe(true) + expect(statusRows(t).some((row) => row.text.includes('Fresh request rejected'))).toBe(true) + await adapter.closeSession('session-1') +}) diff --git a/src/main/claude/claude-usage-limits.ts b/src/main/claude/claude-usage-limits.ts new file mode 100644 index 000000000000..cee66cf9b2d1 --- /dev/null +++ b/src/main/claude/claude-usage-limits.ts @@ -0,0 +1,160 @@ +import { agentSessionFailureFact, providerDiagnostic } from '../../shared/agent-session-failure' +import { + agentSessionFailureWords, + type AgentSessionFailureRowWords +} from '../../shared/agent-session-failure-words' +import { + usageLimitResetsAt, + type AgentSessionUsageLimit, + type AgentSessionUsageLimitWindow +} from '../../shared/agent-session-usage-limit' +import type { ClaudeOpenTurn } from './claude-open-turn' +import { claudeRecord, claudeText } from './claude-structured-item-translation' + +const CLAUDE_LIMIT_WINDOWS: Record = { + five_hour: 'session', + seven_day: 'weekly', + seven_day_opus: 'weeklyModel', + seven_day_sonnet: 'weeklyModel', + seven_day_overage_included: 'weeklyModel', + overage: 'credits' +} + +/** The ends a result reports when a limit refused its request; any other is a different failure. */ +const LIMIT_TERMINAL_REASONS = ['api_error'] + +export type ClaudeUsageLimitRow = AgentSessionFailureRowWords & { + kind: 'status' + tone: 'warning' +} + +function messageText(message: Record): string { + const content = claudeRecord(message.message)?.content + return Array.isArray(content) + ? content + .flatMap((part) => { + const value = claudeRecord(part) + return value?.type === 'text' && typeof value.text === 'string' ? [value.text] : [] + }) + .join('\n') + : '' +} + +export type ClaudeUsageLimitEvidence = { + cause: 'quota' | 'other' | 'untyped' +} + +// Account observations outlive turns because unchanged rejection notifications are throttled. +export class ClaudeUsageLimits { + private readonly rejected = new Map() + + constructor(private readonly now: () => number = Date.now) {} + + observe(message: Record): void { + if (message.type === 'rate_limit_event') { + this.record(claudeRecord(message.rate_limit_info)) + } + } + + assistant(message: Record, turn?: ClaudeOpenTurn): ClaudeUsageLimitRow | null { + if (message.type !== 'assistant') { + return null + } + const typed = claudeText(message.api_error) + const cause = typed === 'usage_limit_reached' ? 'quota' : typed ? 'other' : 'untyped' + if (cause === 'quota') { + this.record(claudeRecord(claudeRecord(message.api_error_params)?.rate_limit_info)) + } + const refused = message.error === 'rate_limit' || cause === 'quota' + const root = message.parent_tool_use_id == null + const decision = !typed && root ? (turn?.usageLimitEvidence?.cause ?? cause) : cause + const row = + decision !== 'other' && refused + ? this.row(messageText(message), decision === 'quota') + : null + if (root && turn?.isOpen && (typed || (refused && decision === 'untyped'))) { + turn.usageLimitEvidence = { cause: row ? 'quota' : cause } + } + return row + } + + result( + message: Record, + failed: boolean, + evidence: ClaudeUsageLimitEvidence | null + ): ClaudeUsageLimitRow | null { + if (!failed || evidence?.cause === 'other') { + return null + } + const status = message.api_error_status + const reason = claudeText(message.terminal_reason) + const limited = + evidence?.cause === 'quota' || + (evidence?.cause === 'untyped' && + (status == null || status === 429) && + (reason === null || LIMIT_TERMINAL_REASONS.includes(reason))) + if (!limited) { + return null + } + return this.row(claudeText(message.result) ?? '', evidence?.cause === 'quota') + } + + private record(info: Record | null): void { + if (!info) { + return + } + const type = claudeText(info.rateLimitType) ?? 'unknown' + const overage = + info.overageStatus === 'allowed' || + info.overageStatus === 'allowed_warning' || + info.isUsingOverage === true || + info.overageInUse === true + if (info.status === 'rejected' && !overage) { + const seconds = info.resetsAt + const resetsAt = + typeof seconds === 'number' ? usageLimitResetsAt(seconds * 1000, this.now()) : undefined + this.rejected.set(type, resetsAt ?? null) + } else if (info.status === 'allowed' || info.status === 'allowed_warning' || overage) { + this.rejected.delete(type) + } + } + + /** Every refusing limit must reset before a request can run, so the latest reset is the one. */ + private limit(): AgentSessionUsageLimit | null { + const now = this.now() + for (const [type, resetsAt] of this.rejected) { + if (resetsAt !== null && resetsAt <= now) { + this.rejected.delete(type) + } + } + if (this.rejected.size === 0) { + return null + } + const windows = new Set([...this.rejected.keys()].map((type) => CLAUDE_LIMIT_WINDOWS[type])) + const window = windows.size === 1 ? [...windows][0] : undefined + const resets = [...this.rejected.values()].filter((reset): reset is number => reset !== null) + const resetsAt = resets.length === this.rejected.size ? Math.max(...resets) : undefined + return { ...(window ? { window } : {}), ...(resetsAt ? { resetsAt } : {}) } + } + + private row( + providerText: string, + typed = false + ): ClaudeUsageLimitRow | null { + const limit = this.limit() + if (!limit && !typed) { + return null + } + return { + kind: 'status', + tone: 'warning', + ...agentSessionFailureWords( + agentSessionFailureFact('usageLimitReached', { + ...(limit && (limit.window || limit.resetsAt) ? { usageLimit: limit } : {}), + detail: providerDiagnostic(providerText, 'person') + }), + { agentName: 'Claude', provider: 'claude', surface: 'row' } + ) + } + } +} diff --git a/src/main/codex/codex-structured-journal-generic-frames.ts b/src/main/codex/codex-structured-journal-generic-frames.ts index 64e80bffc2b5..f9907dfd9edf 100644 --- a/src/main/codex/codex-structured-journal-generic-frames.ts +++ b/src/main/codex/codex-structured-journal-generic-frames.ts @@ -25,6 +25,7 @@ import { import type { CodexRowAttribution } from './codex-subagent-linkage' import { codexAuthenticationFailure } from './codex-authentication-failure' import { agentSessionFailureWords } from '../../shared/agent-session-failure-words' +import { CodexUsageLimits } from './codex-usage-limits' const OVERFLOW_BUCKET = '__codex-generic-overflow__' /** A turn's rows by whether a client draws them; each kind has its own cap. */ @@ -70,6 +71,7 @@ export class CodexJournalGenericFrames { private bookkeepingBytes = 0 private fallbackSequence = 0 private cancelSuppressionFlush: (() => void) | null = null + private readonly usageLimits = new CodexUsageLimits() constructor( private readonly deps: Pick< @@ -89,20 +91,24 @@ export class CodexJournalGenericFrames { payload: unknown, threadId: string ): CodexJournalTranslationAdmission { + if (this.usageLimits.observe(kind, payload)) { + return CODEX_JOURNAL_ADMITTED + } const translated = unhandledProviderFrameJournalItem('codex', kind, payload) // A frame the classifier declines is deliberately not journaled, which is success. // Failing admission here force-closes the provider through the retry queue. - const auth = - kind === 'notification:error' && !readCodexErrorWillRetry(payload) - ? codexAuthenticationFailure(payload, this.deps.account?.()) - : null + const ended = kind === 'notification:error' && !readCodexErrorWillRetry(payload) + const usageLimit = ended ? this.usageLimits.failure(payload) : null + const failure = + usageLimit ?? (ended ? codexAuthenticationFailure(payload, this.deps.account?.()) : null) return translated ? this.appendFrameRow(threadId, payload, { ...translated, - body: auth + body: failure ? { ...translated.body, - ...agentSessionFailureWords(auth, { + ...(usageLimit ? { tone: 'warning' } : {}), + ...agentSessionFailureWords(failure, { provider: 'codex', agentName: 'Codex', surface: 'row' @@ -152,7 +158,9 @@ export class CodexJournalGenericFrames { this.fallbackSequence += 1 const identity = { provider: 'orca' as const, - clientMessageId: `provider-frame:codex:${this.deps.acquisitionId ?? 'acquisition'}:${this.fallbackSequence}` + clientMessageId: translated.body.failure?.kind === 'usageLimitReached' && frameTurnId + ? `terminal-failure:codex:${JSON.stringify([threadId, frameTurnId])}` + : `provider-frame:codex:${this.deps.acquisitionId ?? 'acquisition'}:${this.fallbackSequence}` } const attribution = this.deps.attributionFor(threadId, frameTurnId) const admission = this.deps.sink.tryAppendItem diff --git a/src/main/codex/codex-usage-limits.test.ts b/src/main/codex/codex-usage-limits.test.ts new file mode 100644 index 000000000000..818fbb2c6504 --- /dev/null +++ b/src/main/codex/codex-usage-limits.test.ts @@ -0,0 +1,84 @@ +import { describe, expect, it } from 'vitest' +import type { AgentJournalItemBody } from '../../shared/agent-session-journal-types' +import { CodexUsageLimits } from './codex-usage-limits' +import { createCodexJournalTranslator } from './codex-structured-journal-translation' + +const RESETS_AT_S = Math.floor(Date.now() / 1000) + 3 * 24 * 3600 +const CODEX_WORDS = "You've hit your usage limit. Try again in 3 days." + +function translatorWithRows() { + const bodies: AgentJournalItemBody[] = [] + const translator = createCodexJournalTranslator({ + primaryThreadId: () => 'thread', + sink: { + appendItem: (_identity, body) => bodies.push(body), + appendTombstone: () => {}, + publish: () => {} + } + }) + const notify = (method: string, params: Record) => + translator.handle({ + type: 'notification', + sessionId: 'session', + threadId: 'thread', + method, + params + }) + return { bodies, translator, notify } +} + +describe('a Codex usage limit', () => { + it('names the spent window and its reset from the last usage report', () => { + const { bodies, translator, notify } = translatorWithRows() + notify('account/rateLimits/updated', { + rateLimits: { + limitId: 'codex', + primary: { usedPercent: 40, windowDurationMins: 300, resetsAt: RESETS_AT_S - 3600 }, + secondary: { usedPercent: 100, windowDurationMins: 10080, resetsAt: RESETS_AT_S } + } + }) + // An update may carry only what changed; the spent weekly window still stands. + notify('account/rateLimits/updated', { + rateLimits: { + primary: { usedPercent: 41, windowDurationMins: 300, resetsAt: RESETS_AT_S - 3600 } + } + }) + notify('error', { + threadId: 'thread', + turnId: 'turn', + willRetry: false, + error: { codexErrorInfo: 'usageLimitExceeded', message: CODEX_WORDS } + }) + + expect(bodies.filter((body) => body.kind === 'status')).toEqual([ + expect.objectContaining({ + tone: 'warning', + text: 'Codex hit its weekly limit. Send a message once it resets to continue.', + failure: { + kind: 'usageLimitReached', + usageLimit: { window: 'weekly', resetsAt: RESETS_AT_S * 1000 }, + detail: { text: CODEX_WORDS, audience: 'person' } + } + }) + ]) + translator.dispose() + }) + it('merges null account updates and keeps unnamed exhausted windows in reset calculation', () => { + const limits = new CodexUsageLimits() + const observe = (rateLimits: Record) => + limits.observe('notification:account/rateLimits/updated', { rateLimits }) + const failure = (code = 'usageLimitExceeded') => limits.failure({ + error: { codexErrorInfo: code, message: CODEX_WORDS } + }) + observe({ limitId: 'codex', primary: { usedPercent: 100, windowDurationMins: 300, resetsAt: RESETS_AT_S } }) + observe({ limitId: null, primary: { usedPercent: 100, windowDurationMins: 43200, resetsAt: RESETS_AT_S + 3600 } }) + expect(failure()?.usageLimit).toEqual({ resetsAt: (RESETS_AT_S + 3600) * 1000 }) + observe({ secondary: { usedPercent: 100, windowDurationMins: 10080 } }) + expect(failure('rateLimitExceeded')?.usageLimit).toBeUndefined() + observe({ secondary: null, planType: 'free', primary: { usedPercent: 100, resetsAt: RESETS_AT_S } }) + expect(failure()?.usageLimit).toEqual({ resetsAt: RESETS_AT_S * 1000 }) + observe({ primary: null }) + expect(failure()?.usageLimit).toBeUndefined() + }) + +}) diff --git a/src/main/codex/codex-usage-limits.ts b/src/main/codex/codex-usage-limits.ts new file mode 100644 index 000000000000..820ec2337833 --- /dev/null +++ b/src/main/codex/codex-usage-limits.ts @@ -0,0 +1,101 @@ +import { agentSessionFailureFact, providerDiagnostic } from '../../shared/agent-session-failure' +import { + usageLimitResetsAt, + type AgentSessionUsageLimit, + type AgentSessionUsageLimitWindow +} from '../../shared/agent-session-usage-limit' +import type { CodexRateLimitWindowsSnapshot } from '../rate-limits/codex-rate-limit-window-classification' +import { + readCodexErrorAdditionalDetails, + readCodexErrorInfo, + readCodexErrorMessage +} from './codex-structured-thread-facts' + +const RATE_LIMITS_UPDATED = 'notification:account/rateLimits/updated' +const USAGE_LIMIT_ERRORS = ['usageLimitExceeded', 'rateLimitExceeded'] + +type CodexAccountRateLimits = CodexRateLimitWindowsSnapshot & { rateLimitReachedType?: unknown; planType?: unknown } + +function record(value: unknown): Record | null { + return typeof value === 'object' && value !== null && !Array.isArray(value) ? { ...value } : null +} + +/** + * The account's usage as Codex last reported it (`account/rateLimits/updated`), so a turn its usage + * limit ended can say which limit and when it resets. + */ +export class CodexUsageLimits { + private snapshot: CodexAccountRateLimits = {} + + constructor(private readonly now: () => number = Date.now) {} + + /** Whether the frame was a usage report, which this keeps and nothing else journals. */ + observe(kind: string, payload: unknown): boolean { + if (kind !== RATE_LIMITS_UPDATED) { + return false + } + const update = record(record(payload)?.rateLimits) + // Another limit id is one model's own bucket, not the account's session or weekly limit. + if (update && (update.limitId == null || update.limitId === 'codex')) { + // An update may carry only the fields that changed. + this.snapshot = { + ...this.snapshot, + ...Object.fromEntries(Object.entries(update).filter(([, value]) => value !== undefined)) + } + } + return true + } + + /** The fact for an `error` frame that Codex's usage limit ended the turn with; null otherwise. */ + failure(payload: unknown) { + const error = readCodexErrorInfo(payload)?.error + if (!error || !USAGE_LIMIT_ERRORS.includes(error)) { + return null + } + const message = readCodexErrorMessage(payload) + const additional = readCodexErrorAdditionalDetails(payload) + const text = [message, additional && additional !== message ? additional : null] + .filter((part): part is string => part !== null) + .join('\n') + const limit = this.limit() + return agentSessionFailureFact('usageLimitReached', { + ...(limit ? { usageLimit: limit } : {}), + detail: providerDiagnostic(text, 'person') + }) + } + + /** Every spent window must reset before a turn can run, so the latest reset is the one; none + * when any spent window gave no reset. */ + private limit(): AgentSessionUsageLimit | null { + const monthlyPlan = this.snapshot.planType === 'free' || this.snapshot.planType === 'go' + const spent = ([['primary', monthlyPlan ? 43200 : 300], ['secondary', 10080]] as const).flatMap(([position, fallback]) => { + const raw = this.snapshot[position] + if (!raw || typeof raw.usedPercent !== 'number' || !Number.isFinite(raw.usedPercent) || raw.usedPercent < 100) { + return [] + } + const duration = raw.windowDurationMins === undefined || raw.windowDurationMins === null + ? fallback : raw.windowDurationMins + const window = typeof duration === 'number' && Number.isFinite(duration) && duration > 0 + ? duration >= 43200 ? undefined : duration >= 10080 ? 'weekly' as const : 'session' as const + : undefined + return [{ window, resetsAt: raw.resetsAt }] + }) + const reached = this.snapshot.rateLimitReachedType + const credits = typeof reached === 'string' && reached.endsWith('credits_depleted') + const window: AgentSessionUsageLimitWindow | undefined = credits + ? 'credits' + : spent.length === 1 + ? spent[0]?.window + : undefined + const resets = spent.flatMap((entry) => + typeof entry.resetsAt === 'number' ? [entry.resetsAt * 1000] : [] + ) + const resetsAt = + resets.length > 0 && resets.length === spent.length + ? usageLimitResetsAt(Math.max(...resets), this.now()) + : undefined + return window || resetsAt + ? { ...(window ? { window } : {}), ...(resetsAt ? { resetsAt } : {}) } + : null + } +} diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-event-sink.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-event-sink.ts index 1f48f0680584..eab76ae0143c 100644 --- a/src/main/native-chat/agent-session-wire/structured-agent-session-event-sink.ts +++ b/src/main/native-chat/agent-session-wire/structured-agent-session-event-sink.ts @@ -68,7 +68,7 @@ export type StructuredAgentSessionIdentityResolver = ( /** What a revision reads: a keyed read for a row it can name, and the scan for one it cannot. */ export type StructuredAgentSessionRevisionJournal = Pick< AgentSessionJournal, - 'epoch' | 'visitItems' | 'itemBody' + 'epoch' | 'visitItems' | 'itemBody' | 'item' > /** Rows already journaled and who produced each, read by a producer that has to agree with them. */ diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-host-mutations.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-host-mutations.ts index a324b34b7421..411106d73c44 100644 --- a/src/main/native-chat/agent-session-wire/structured-agent-session-host-mutations.ts +++ b/src/main/native-chat/agent-session-wire/structured-agent-session-host-mutations.ts @@ -7,6 +7,10 @@ // admitted without the writer lease; the delivery loop starts the provider child a send needs, and // an operation only the provider can perform starts it before admission. +import { latestNativeChatUsageLimitCut } from '../../../shared/native-chat-usage-limit-cut' +import { refuse } from '../../../shared/agent-session-wire' +import { contextStructuredAgentSessionCurrentWork } from './structured-agent-session-current-work' +import { shouldQueueStructuredAgentSessionSend } from './structured-agent-session-queued-messages' import type { AgentJournalMessageItem } from '../../../shared/agent-session-journal-types' import type { AgentSessionCancelResult, @@ -71,6 +75,7 @@ export function sendStructuredAgentSessionTurn( /** Host-local: whether the sending client can manage an image card. */ queuedImageCards?: boolean options?: Readonly> + usageLimitContinuationOfTurnItemId?: string /** Host-local, set only by the client-facing `agentSession.send` RPC (the * renderer's launch prompt included): recorded as the submission's `client` * origin, so a restart or a close keeps it as a card if it never reached the @@ -92,15 +97,35 @@ export function sendStructuredAgentSessionTurn( params.envelope, { ...plan, - run: (ctx) => - runQueueableStructuredAgentSessionSend( - context, - ctx, - params, - async () => - structuredAgentSessionSendBlock(context.deps.store.getRecord(ctx.sessionId)) ?? - (await plan.run(ctx)) - ) + run: async (ctx) => { + const record = context.deps.store.getRecord(ctx.sessionId) + const blocked = structuredAgentSessionSendBlock(record) + if (blocked) { + return blocked + } + if (params.usageLimitContinuationOfTurnItemId !== undefined) { + const snapshot = ctx.journal.snapshot() + const cut = latestNativeChatUsageLimitCut(snapshot.items, snapshot.submissions) + if ( + cut?.turnItemId !== params.usageLimitContinuationOfTurnItemId || + shouldQueueStructuredAgentSessionSend({ + record, + journal: ctx.journal, + work: contextStructuredAgentSessionCurrentWork(ctx) + }) + ) { + return { + ok: false as const, + refusal: refuse( + 'agent_session_operation_invalid', + { reason: 'continuationSuperseded' }, + 'This chat has moved on. Check the latest messages before continuing.' + ) + } + } + } + return runQueueableStructuredAgentSessionSend(context, ctx, params, () => plan.run(ctx)) + } }, sendPreparation(context, params.envelope, arrival, selection) ) diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-queued-action-receipts.test.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-queued-action-receipts.test.ts index 83b98e806eec..146fc6d853c6 100644 --- a/src/main/native-chat/agent-session-wire/structured-agent-session-queued-action-receipts.test.ts +++ b/src/main/native-chat/agent-session-wire/structured-agent-session-queued-action-receipts.test.ts @@ -3,6 +3,11 @@ // another command already used is refused. import { afterEach, beforeEach, describe, expect, it } from 'vitest' +import { agentSessionFailureWords } from '../../../shared/agent-session-failure-words' +import { agentJournalItemKey } from '../../../shared/agent-session-journal-item-key' +import { agentSessionSendBodyFingerprint } from '../../../shared/structured-agent-session-send-mutation' +import { holdLane } from './structured-agent-session-delivery-hold.test-fixture' +import { structuredAgentSessionHostInstance } from './structured-agent-session-queued-pause' import { AGENT_SESSION_MAX_NEW_OPERATION_AGE_MS } from '../../../shared/agent-session-host-authority' import { openTestJournalHostDatabase } from '../agent-session-journal/journal-host-database-test-support' import { @@ -12,7 +17,8 @@ import { } from './structured-agent-session-queued-message-rig.test-fixture' import { HOST_TEST_NOW as NOW, - HOST_TEST_SESSION as SESSION + HOST_TEST_SESSION as SESSION, + hostTestMessage } from './structured-agent-session-host-test-data' const CALLER_SCOPE = { kind: 'caller', callerKey: CALLER.callerKey } as const @@ -549,3 +555,80 @@ describe('an id reused across commands', () => { expect(await rig.deleteQueued(second, sendId)).toMatchObject(conflict) }) }) + + +describe('source-bound ordinary Continue', () => { + async function limitedTurn(id: string) { + const journal = rig.host.collaboratorsForTests().sessions.get(SESSION)?.journal + if (!journal) { + throw new Error('expected an open journal') + } + const identity = { provider: 'orca' as const, clientMessageId: id } + const turnItemId = agentJournalItemKey(identity) + await journal.appendItem(identity, { + kind: 'turn', turnId: id, state: 'completed', outcome: 'failure', + startedAt: NOW, completedAt: NOW + }, { fence: 1, turnScope: { kind: 'thread' } }) + await journal.appendItem({ provider: 'orca', clientMessageId: `failure-${id}` }, { + kind: 'status', + ...agentSessionFailureWords({ kind: 'usageLimitReached' }, { surface: 'row' }) + }, { fence: 1, turnScope: { kind: 'turn', turnItemId } }) + return { journal, turnItemId } + } + function params(source: string, id = opId(), options?: Record) { + const fields = { + body: hostTestMessage('Continue where you left off.'), delivery: 'queue-if-active' as const, + usageLimitContinuationOfTurnItemId: source, ...(options ? { options } : {}) + } + return { ...fields, envelope: rig.envelope(fields, 'agentSession.send', id) } + } + const superseded = { ok: false, refusal: { details: { reason: 'continuationSuperseded' } } } + + it('admits one of two clients, replays its receipt after newer work, and conflicts on changed controls', async () => { + const { journal, turnItemId } = await limitedTurn('limited') + const first = params(turnItemId) + const second = params(turnItemId) + const answers = await Promise.all([ + rig.host.send(CALLER, first), rig.host.send({ callerKey: 'phone' }, second) + ]) + expect(answers[0]).toMatchObject({ ok: true, replayed: false }) + expect(answers[1]).toMatchObject(superseded) + expect(journal.submissions()).toHaveLength(1) + expect(journal.queuedMessages.list()).toHaveLength(0) + await rig.send('newer ordinary message').result + expect(await rig.host.send(CALLER, first)).toMatchObject({ ok: true, replayed: true }) + for (const changed of [params('another-turn', first.envelope.clientOperationId), + params(turnItemId, first.envelope.clientOperationId, { model: 'other' })]) { + expect(await rig.host.send(CALLER, changed)).toMatchObject(CONFLICT) + } + expect(journal.submissions()).toHaveLength(2) + }) + + it('refuses a stale action and actionable backlog before writing a submission or queue card', async () => { + const { journal, turnItemId } = await limitedTurn('old') + await rig.send('ordinary message wins').result + const before = journal.snapshot().items.map((item) => item.itemId) + const requests = journal.submissions().map((entry) => entry.clientMessageId) + expect(await rig.host.send(CALLER, params(turnItemId))).toMatchObject(superseded) + expect(journal.snapshot().items.map((item) => item.itemId)).toEqual(before) + expect(journal.submissions().map((entry) => entry.clientMessageId)).toEqual(requests) + expect(journal.queuedMessages.list()).toHaveLength(0) + await rig.settleRejected(journal.submissions()[0]!.clientMessageId, 'done') + const current = await limitedTurn('current') + const release = holdLane(rig.host, SESSION) + try { + const body = hostTestMessage('backlog') + const row = await journal.queuedMessages.insert({ + messageId: opId(), body, fingerprint: agentSessionSendBodyFingerprint(SESSION, body), + hostInstance: structuredAgentSessionHostInstance() + }) + journal.queuedMessages.editLeases.acquire({ callerKey: CALLER.callerKey, editId: 'edit' }, + { messageId: row.messageId, fingerprint: row.fingerprint }) + const attempt = rig.host.send(CALLER, params(current.turnItemId)) + release() + expect(await attempt).toMatchObject(superseded) + expect(journal.queuedMessages.list()).toHaveLength(1) + expect(journal.submissions()).toHaveLength(1) + } finally { release() } + }) +}) diff --git a/src/renderer/src/components/native-chat/NativeChatInterruptedContinue.test.tsx b/src/renderer/src/components/native-chat/NativeChatInterruptedContinue.test.tsx index 854c3b5d308f..11fbee17d300 100644 --- a/src/renderer/src/components/native-chat/NativeChatInterruptedContinue.test.tsx +++ b/src/renderer/src/components/native-chat/NativeChatInterruptedContinue.test.tsx @@ -1,7 +1,7 @@ // @vitest-environment happy-dom import '@testing-library/jest-dom/vitest' -import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react' -import { useState } from 'react' +import { act, cleanup, fireEvent, render, renderHook, screen, waitFor } from '@testing-library/react' +import { useRef, useState } from 'react' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' const mocks = vi.hoisted(() => { @@ -17,7 +17,12 @@ const mocks = vi.hoisted(() => { } }) +vi.mock('@/lib/native-chat-telemetry', () => ({ emitNativeChatMessageSent: vi.fn() })) +vi.mock('@/lib/worker-terminal-takeover-report', () => ({ reportStructuredSessionUserInput: vi.fn() })) + vi.mock('@/i18n/i18n', () => ({ translate: (_key: string, fallback: string) => fallback })) +vi.mock('@/runtime/runtime-rpc-client', () => ({ ensureRuntimeEnvironmentCompatible: async () => {} })) +vi.mock('@/lib/structured-agent-session-launch-label', () => ({ structuredAgentLabel: () => 'Codex' })) vi.mock('@/runtime/structured-agent-session-client', () => ({ callStructuredAgentSession: mocks.call })) @@ -34,7 +39,23 @@ vi.mock('./use-structured-agent-session-host-label', () => ({ useStructuredAgentSessionHostLabel: () => mocks.hostLabel })) +import type { NativeChatStructuredComposerTransport } from './native-chat-composer-types' +import { useStructuredAgentSessionSends } from './use-structured-agent-session-sends' +import { + getStructuredAgentSessionSendNotice, + setStructuredAgentSessionSendNotice +} from './structured-agent-session-pending-sends' +import { resetStructuredAgentSessionSendsForTests } from './structured-agent-session-message-sender' +import { + clearNativeChatComposerDraftsForTests, + readNativeChatComposerDraft, + updateNativeChatComposerDraft, + structuredAgentSessionDraftScopeKey +} from './native-chat-composer-draft-store' +import { reportStructuredSessionUserInput } from '@/lib/worker-terminal-takeover-report' +import { emitNativeChatMessageSent } from '@/lib/native-chat-telemetry' import { TooltipProvider } from '@/components/ui/tooltip' +import { agentSessionFailureWords } from '../../../../shared/agent-session-failure-words' import { agentJournalItemKey } from '../../../../shared/agent-session-journal-item-key' import type { AgentJournalRenderItem, @@ -67,26 +88,41 @@ const cutChat: AgentJournalRenderItem[] = [ } ] +const optionsSurface: NativeChatStructuredComposerTransport['optionsSurface'] = { + getSnapshot: () => [], + setOption: async () => ({ snapshot: [] }), + invokeAction: async () => ({ snapshot: [] }), + subscribe: () => () => {} +} + type Props = { journalItems?: readonly AgentJournalRenderItem[] submissions?: readonly Pick[] isWorking?: boolean target?: RuntimeClientTarget + transport?: NativeChatStructuredComposerTransport + pending?: readonly { phase: 'sending' | 'recorded' }[] } function Harness(props: Props): React.JSX.Element { + const composerRef = useRef(null) // The chat's own composer error, as NativeChatStructuredSession holds it. const [composerError, setComposerError] = useState(null) const continuation = useNativeChatInterruptedContinuation({ reportComposerError: setComposerError, + focusComposer: () => { composerRef.current?.focus() }, target: props.target ?? PAIRED, + agent: 'codex', sessionId: 'session-1', journalItems: props.journalItems ?? cutChat, submissions: props.submissions ?? [], - isWorking: props.isWorking ?? false + isWorking: props.isWorking ?? false, + pending: props.pending ?? [], + transport: props.transport ?? { send: () => true, dispatchCommand: async () => ({ handled: false, accepted: false, error: null }), optionsSurface, optionSnapshot: [], onError: () => {}, runtime: 'remote', sessionId: 'session-1', runtimeEnvironmentId: 'studio-mac' } }) return ( +