From 4cf4e38d459f3863c78454fab9b19a6d9de9161b Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Sun, 18 Oct 2026 11:47:38 -0700 Subject: [PATCH 01/34] fix(native-chat): a usage limit reads as a pause with its reset time and a Continue, not a failure Claude, Codex and Grok chats that hit the account's usage limit now end the turn on one warning row that names the limit and, in the reader's clock, when it resets, with Continue to pick the turn back up. Each adapter reads its protocol's typed limit signal into a `usageLimitReached` failure fact; older clients keep the host's sentence. --- .../src/session/MobileNativeChatNoticeRow.tsx | 6 +- src/main/acp/acp-dialects/grok-dialect.ts | 5 +- .../acp/acp-timeline-turn-failures.test.ts | 9 +- src/main/acp/acp-turn-failures.ts | 25 ++- src/main/claude/claude-message-journaling.ts | 3 + src/main/claude/claude-result-journaling.ts | 9 +- .../claude-structured-journal-translation.ts | 3 + .../claude-structured-provider-fallback.ts | 27 ++- src/main/claude/claude-usage-limits.test.ts | 101 +++++++++++ src/main/claude/claude-usage-limits.ts | 170 ++++++++++++++++++ ...codex-structured-journal-generic-frames.ts | 18 +- src/main/codex/codex-usage-limits.test.ts | 65 +++++++ src/main/codex/codex-usage-limits.ts | 98 ++++++++++ .../NativeChatInterruptedContinue.test.tsx | 3 +- .../NativeChatInterruptedContinue.tsx | 56 +++++- .../native-chat/NativeChatNoticeRow.test.tsx | 55 +++++- .../native-chat/NativeChatNoticeRow.tsx | 25 ++- .../NativeChatStructuredSession.tsx | 23 ++- .../agent-session-failure-words-text.ts | 2 + .../agent-session-usage-limit-words-text.ts | 61 +++++++ .../native-chat-orca-stop-context.ts | 7 +- src/renderer/src/i18n/locales/en.json | 11 +- src/renderer/src/i18n/locales/es.json | 11 +- src/renderer/src/i18n/locales/fr.json | 11 +- src/renderer/src/i18n/locales/ja.json | 11 +- src/renderer/src/i18n/locales/ko.json | 11 +- src/renderer/src/i18n/locales/zh.json | 11 +- src/shared/agent-session-failure-copy.ts | 12 ++ src/shared/agent-session-failure-words.ts | 11 ++ src/shared/agent-session-failure.ts | 13 ++ src/shared/agent-session-usage-limit-words.ts | 64 +++++++ src/shared/agent-session-usage-limit.ts | 59 ++++++ src/shared/native-chat-orca-stop-cut.ts | 65 ++++--- src/shared/native-chat-types.ts | 2 + src/shared/native-chat-usage-limit-cut.ts | 31 ++++ .../structured-agent-session-status-block.ts | 3 + 36 files changed, 1010 insertions(+), 87 deletions(-) create mode 100644 src/main/claude/claude-usage-limits.test.ts create mode 100644 src/main/claude/claude-usage-limits.ts create mode 100644 src/main/codex/codex-usage-limits.test.ts create mode 100644 src/main/codex/codex-usage-limits.ts create mode 100644 src/renderer/src/components/native-chat/agent-session-usage-limit-words-text.ts create mode 100644 src/shared/agent-session-usage-limit-words.ts create mode 100644 src/shared/agent-session-usage-limit.ts create mode 100644 src/shared/native-chat-usage-limit-cut.ts 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..320370bf4f06 100644 --- a/src/main/acp/acp-timeline-turn-failures.test.ts +++ b/src/main/acp/acp-timeline-turn-failures.test.ts @@ -165,7 +165,7 @@ 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('names a usage-limited turn the provider gave no words for', async () => { const f = await openAcpFixtureRig() const lane = f.lane() const prompt = lane.openPrompt('c1', 1000) @@ -182,7 +182,12 @@ describe('a failed ACP turn says why', () => { ) 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' } + } ]) 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 ba87ec6a5050..efa033f212e6 100644 --- a/src/main/acp/acp-turn-failures.ts +++ b/src/main/acp/acp-turn-failures.ts @@ -61,7 +61,10 @@ export function acpSignInRequiredRefusal( * 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 }) @@ -103,22 +106,28 @@ export class AcpTurnFailures { const diagnostic = detail ?? (written?.text ? providerDiagnostic(written.text, 'person') : undefined) 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) 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-message-journaling.ts b/src/main/claude/claude-message-journaling.ts index 1bc7b69d41a7..0387702ca969 100644 --- a/src/main/claude/claude-message-journaling.ts +++ b/src/main/claude/claude-message-journaling.ts @@ -34,6 +34,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 +54,7 @@ export type ClaudeMessageJournalContext = { * latch; this module asks it rather than tracking a copy. */ turn: ClaudeOpenTurn authenticationFailures: ClaudeAuthenticationFailures + usageLimits: ClaudeUsageLimits threadGoal: ClaudeThreadGoal } @@ -94,6 +96,7 @@ export function journalClaudeMessage( ctx.threadGoal.observe(message) const body = ctx.authenticationFailures.assistant(message) ?? + ctx.usageLimits.assistant(message) ?? ctx.threadGoal.report(message, claudeMessageIdentity(envelope), observedAt) ?? claudeMessageBody(outputEnvelope) const identity = diff --git a/src/main/claude/claude-result-journaling.ts b/src/main/claude/claude-result-journaling.ts index 9e68e852f352..af9cf918374c 100644 --- a/src/main/claude/claude-result-journaling.ts +++ b/src/main/claude/claude-result-journaling.ts @@ -26,6 +26,7 @@ export type ClaudeResultJournalContext = Pick< | 'corrections' | 'turn' | 'authenticationFailures' + | 'usageLimits' | 'threadGoal' > & { prompts: ClaudeJournalPrompts @@ -44,6 +45,7 @@ export function journalClaudeResult( prompts, context, authenticationFailures, + usageLimits, threadGoal, goalBackgroundWork }: ClaudeResultJournalContext, @@ -92,12 +94,15 @@ export function journalClaudeResult( } const kind = claudeProviderFrameKind(message) const failure = claudeResultFailure(message, leftToStop) - const alreadyShown = authenticationFailures.resultAlreadyShown(message) + // A failed root result the limit refused writes the limit's row, not the result's. + const usageLimit = settlesTurn ? usageLimits.result(message, failure !== null) : null + const alreadyShown = + authenticationFailures.resultAlreadyShown(message) || usageLimit === 'shown' if ((failure || !isSettledClaudeResultKind(kind)) && !alreadyShown) { providerFallback.append( kind, message, - failure?.text, + usageLimit === 'shown' ? null : (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..8b1eff5a60c1 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( 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-usage-limits.test.ts b/src/main/claude/claude-usage-limits.test.ts new file mode 100644 index 000000000000..ed293fb67723 --- /dev/null +++ b/src/main/claude/claude-usage-limits.test.ts @@ -0,0 +1,101 @@ +import { describe, expect, it } from 'vitest' +import { 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: `ask-${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: `ask-${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('ends the turn on one limit row, again when the CLI does not repeat the rejection', () => { + const t = setup() + t.handle(userFrame('turn-a', 1_000)) + t.handle(rateLimitEvent('rejected', 1_100)) + t.handle(refusedFrame('a', 1_200, LIMIT_TEXT)) + t.handle(failedResult('a', 1_300, LIMIT_TEXT)) + // 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, limitRow]) + expect(messageTexts(t)).not.toContain(LIMIT_TEXT) + t.translator.dispose() + }) + + 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() + }) +}) diff --git a/src/main/claude/claude-usage-limits.ts b/src/main/claude/claude-usage-limits.ts new file mode 100644 index 000000000000..88b9b12cb4bd --- /dev/null +++ b/src/main/claude/claude-usage-limits.ts @@ -0,0 +1,170 @@ +import { agentSessionFailureFact, providerDiagnostic } from '../../shared/agent-session-failure' +import { + agentSessionFailureWords, + type AgentSessionFailureRowWords +} from '../../shared/agent-session-failure-words' +import { BoundedMap } from '../../shared/bounded-map' +import { + usageLimitResetsAt, + type AgentSessionUsageLimit, + type AgentSessionUsageLimitWindow +} from '../../shared/agent-session-usage-limit' +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', 'blocking_limit'] + +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') + : '' +} + +/** + * The account's usage limits as Claude reports them: the limit an API-error frame names + * (`api_error: usage_limit_reached`), else a `rate_limit_event` saying a limit is `rejected` with + * no paid usage to fall back on. Only those mean the account's own limit: the CLI shares the + * frame's `error: rate_limit` with throttles and policy refusals that no reset clears. The CLI + * repeats an unchanged rejection only now and then, so each one stands until a reading allows that + * limit again or its reset passes. + */ +export class ClaudeUsageLimits { + /** Each limit refusing requests, by Claude's name for it, with its reset (ms) if it gave one. */ + private readonly rejected = new Map() + private readonly shown = new BoundedMap({ maxEntries: 128 }) + /** The root turn's request was refused with `rate_limit`: its failed result may be the limit. */ + private turnRefused = false + + constructor(private readonly now: () => number = Date.now) {} + + observe(message: Record): void { + if (message.type === 'rate_limit_event') { + this.record(claudeRecord(message.rate_limit_info)) + } + } + + /** The limit's row in place of an API-error frame the limit refused; null for any other frame. */ + assistant(message: Record): ClaudeUsageLimitRow | null { + if (message.type !== 'assistant' || message.error !== 'rate_limit') { + return null + } + const named = + message.api_error === 'usage_limit_reached' + ? claudeRecord(claudeRecord(message.api_error_params)?.rate_limit_info) + : null + if (named) { + this.record(named) + } + if (message.parent_tool_use_id == null) { + this.turnRefused = true + } + const row = this.row(messageText(message)) + const key = row ? this.key(message) : null + if (key) { + this.shown.set(key, true) + } + return row + } + + /** For a failed root result: the limit's row, or `shown` when its API-error frame already wrote + * it. Null for any other result, which keeps its own row. */ + result(message: Record, failed: boolean): ClaudeUsageLimitRow | 'shown' | null { + const refused = this.turnRefused + this.turnRefused = false + const key = this.key(message) + if (key !== null && this.shown.delete(key)) { + return failed ? 'shown' : null + } + const status = message.api_error_status + const reason = claudeText(message.terminal_reason) + const limited = + failed && + (refused || reason === 'blocking_limit') && + (status == null || status === 429) && + (reason === null || LIMIT_TERMINAL_REASONS.includes(reason)) + return limited ? this.row(claudeText(message.result) ?? '') : null + } + + 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): ClaudeUsageLimitRow | null { + const limit = this.limit() + if (!limit) { + return null + } + return { + kind: 'status', + tone: 'warning', + ...agentSessionFailureWords( + agentSessionFailureFact('usageLimitReached', { + ...(limit.window || limit.resetsAt ? { usageLimit: limit } : {}), + detail: providerDiagnostic(providerText, 'person') + }), + { agentName: 'Claude', provider: 'claude', surface: 'row' } + ) + } + } + + private key(message: Record): string | null { + const uuid = claudeText(message.user_message_uuid) + return uuid + ? JSON.stringify([message.session_id, message.parent_tool_use_id ?? null, uuid]) + : null + } +} diff --git a/src/main/codex/codex-structured-journal-generic-frames.ts b/src/main/codex/codex-structured-journal-generic-frames.ts index 64e80bffc2b5..e2139faf43d6 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' 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..f821e835acbe --- /dev/null +++ b/src/main/codex/codex-usage-limits.test.ts @@ -0,0 +1,65 @@ +import { describe, expect, it } from 'vitest' +import type { AgentJournalItemBody } from '../../shared/agent-session-journal-types' +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() + }) +}) diff --git a/src/main/codex/codex-usage-limits.ts b/src/main/codex/codex-usage-limits.ts new file mode 100644 index 000000000000..49f6dcbcb6ad --- /dev/null +++ b/src/main/codex/codex-usage-limits.ts @@ -0,0 +1,98 @@ +import { agentSessionFailureFact, providerDiagnostic } from '../../shared/agent-session-failure' +import { + usageLimitResetsAt, + type AgentSessionUsageLimit, + type AgentSessionUsageLimitWindow +} from '../../shared/agent-session-usage-limit' +import { + classifyCodexRateLimitWindows, + 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 } + +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 === undefined || 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 windows = classifyCodexRateLimitWindows(this.snapshot) + const spent = (['session', 'weekly'] as const).flatMap((window) => { + const snapshot = windows[window] + return snapshot && snapshot.usedPercent >= 100 + ? [{ window, resetsAt: snapshot.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/renderer/src/components/native-chat/NativeChatInterruptedContinue.test.tsx b/src/renderer/src/components/native-chat/NativeChatInterruptedContinue.test.tsx index 854c3b5d308f..a01f060584a1 100644 --- a/src/renderer/src/components/native-chat/NativeChatInterruptedContinue.test.tsx +++ b/src/renderer/src/components/native-chat/NativeChatInterruptedContinue.test.tsx @@ -83,7 +83,8 @@ function Harness(props: Props): React.JSX.Element { sessionId: 'session-1', journalItems: props.journalItems ?? cutChat, submissions: props.submissions ?? [], - isWorking: props.isWorking ?? false + isWorking: props.isWorking ?? false, + sendMessage: () => true }) return ( diff --git a/src/renderer/src/components/native-chat/NativeChatInterruptedContinue.tsx b/src/renderer/src/components/native-chat/NativeChatInterruptedContinue.tsx index 5d489c38a4e3..eea8d352ce28 100644 --- a/src/renderer/src/components/native-chat/NativeChatInterruptedContinue.tsx +++ b/src/renderer/src/components/native-chat/NativeChatInterruptedContinue.tsx @@ -11,6 +11,10 @@ import type { AgentJournalSubmission } from '../../../../shared/agent-session-journal-types' import { latestNativeChatOrcaStopCut } from '../../../../shared/native-chat-orca-stop-cut' +import { + latestNativeChatUsageLimitCut, + NATIVE_CHAT_USAGE_LIMIT_CONTINUE_MESSAGE +} from '../../../../shared/native-chat-usage-limit-cut' import { AGENT_SESSION_CONTINUE_INTERRUPTED_RUNTIME_CAPABILITY } from '../../../../shared/agent-session-continue-interrupted-capability' import type { NativeChatOrcaStopView } from './native-chat-orca-stop-context' import { useStructuredAgentSessionHostLabel } from './use-structured-agent-session-host-label' @@ -43,8 +47,10 @@ export function useNativeChatInterruptedContinuation(input: { isWorking: boolean /** Stable; a Continue click is the user's newer action, so it clears the composer's error. */ reportComposerError: (text: null) => void + /** Sends as the composer does; false when the chat took nothing. */ + sendMessage: (text: string) => boolean }): NativeChatInterruptedContinuation { - const { target, sessionId, reportComposerError } = input + const { target, sessionId, reportComposerError, sendMessage } = input const hostLabel = useStructuredAgentSessionHostLabel(target) const capability = useStructuredAgentSessionHostCapabilityState( target, @@ -58,6 +64,11 @@ export function useNativeChatInterruptedContinuation(input: { () => latestNativeChatOrcaStopCut(input.journalItems, input.submissions), [input.journalItems, input.submissions] ) + // Any host: Continue past a usage limit is the person's own message, which every host takes. + const usageLimitCut = useMemo( + () => latestNativeChatUsageLimitCut(input.journalItems, input.submissions), + [input.journalItems, input.submissions] + ) // The cut this client already asked to continue: hidden until the journal shows what came of it. const [asked, setAsked] = useState(null) const [failedOn, setFailedOn] = useState(null) @@ -65,6 +76,20 @@ export function useNativeChatInterruptedContinuation(input: { capability === 'supported' && cut && !input.isWorking && !resuming && asked !== cut.turnItemId ? cut.turnItemId : null + const usageLimitTurnItemId = + usageLimitCut && !input.isWorking && !resuming && asked !== usageLimitCut.turnItemId + ? usageLimitCut.turnItemId + : null + const continueUsageLimit = useCallback((): void => { + if (usageLimitTurnItemId === null) { + return + } + setAsked(usageLimitTurnItemId) + // A send the chat refused says why in the composer, as any send does; Continue comes back. + if (!sendMessage(NATIVE_CHAT_USAGE_LIMIT_CONTINUE_MESSAGE)) { + setAsked(null) + } + }, [usageLimitTurnItemId, sendMessage]) const continueNow = useCallback((): void => { if (offered === null) { return @@ -93,9 +118,19 @@ export function useNativeChatInterruptedContinuation(input: { remoteHost, continueAvailable, offeredTurnItemId: offered, - continueNow + continueNow, + usageLimitTurnItemId, + continueUsageLimit }), - [hostLabel, remoteHost, continueAvailable, offered, continueNow] + [ + hostLabel, + remoteHost, + continueAvailable, + offered, + continueNow, + usageLimitTurnItemId, + continueUsageLimit + ] ) const failedHere = failedOn !== null && cut?.turnItemId === failedOn @@ -112,15 +147,20 @@ export function useNativeChatInterruptedContinuation(input: { /** Continue, on the row that says Orca stopped this reply: the one action that picks it back up. */ export function NativeChatInterruptedContinueButton({ - onContinue + onContinue, + explanation: shownExplanation }: { onContinue: () => void + /** What Continue does here, when it is not picking up a reply Orca's stop cut off. */ + explanation?: string }): React.JSX.Element { const explanationId = useId() - const explanation = translate( - 'components.native-chat.interruptedContinue.explanation', - 'Continue, and the agent first checks whether its last step finished.' - ) + const explanation = + shownExplanation ?? + translate( + 'components.native-chat.interruptedContinue.explanation', + 'Continue, and the agent first checks whether its last step finished.' + ) return ( <> diff --git a/src/renderer/src/components/native-chat/NativeChatNoticeRow.test.tsx b/src/renderer/src/components/native-chat/NativeChatNoticeRow.test.tsx index 63a12f7ce1f5..fbdd21f5e08b 100644 --- a/src/renderer/src/components/native-chat/NativeChatNoticeRow.test.tsx +++ b/src/renderer/src/components/native-chat/NativeChatNoticeRow.test.tsx @@ -32,13 +32,23 @@ it('keeps a skipped compaction warning truthful instead of showing the success s expect(screen.queryByText('Context compacted')).toBeNull() }) +type ContinueOffer = Pick & + Partial> + function orcaStopView( hostLabel: string | null, continueAvailable: boolean, remoteHost: boolean, - offer: Pick + offer: ContinueOffer ): NativeChatOrcaStopView { - return { hostLabel, remoteHost, continueAvailable, ...offer } + return { + hostLabel, + remoteHost, + continueAvailable, + usageLimitTurnItemId: null, + continueUsageLimit: () => {}, + ...offer + } } const NO_OFFER = { offeredTurnItemId: null, continueNow: () => {} } @@ -49,7 +59,7 @@ function renderStatus( continueAvailable = false, remoteHost = false, agentName?: string, - offer: Pick = NO_OFFER + offer: ContinueOffer = NO_OFFER ) { const [message] = projectStructuredItemsToNativeChat([ { @@ -212,6 +222,45 @@ describe('the row an Orca stop leaves', () => { }) }) +describe('the row a usage limit leaves', () => { + const resetsAt = new Date(2026, 9, 18, 15, 0).getTime() + const row: AgentJournalStatusItem = { + kind: 'status', + tone: 'warning', + ...agentSessionFailureWords( + agentSessionFailureFact('usageLimitReached', { + usageLimit: { window: 'session', resetsAt } + }), + { agentName: 'Claude', surface: 'row' } + ) + } + + it('says when the limit resets in this clock, and continues the turn it ended', () => { + vi.useFakeTimers({ now: new Date(2026, 9, 18, 12, 30), toFake: ['Date'] }) + const continueUsageLimit = vi.fn() + renderStatus(row, null, false, false, 'Claude', { + ...NO_OFFER, + usageLimitTurnItemId: 'cut-turn', + continueUsageLimit + }) + vi.useRealTimers() + const clock = new Intl.DateTimeFormat(undefined, { hour: 'numeric', minute: '2-digit' }).format( + resetsAt + ) + expect( + screen.getByText(`Claude hit its session limit. It resets at ${clock}.`) + ).toBeInTheDocument() + fireEvent.click(screen.getByRole('button', { name: 'Continue' })) + expect(continueUsageLimit).toHaveBeenCalledTimes(1) + }) + + it('tells a chat that has no Continue to send a message', () => { + renderStatus(row, null, false, false, 'Claude') + expect(screen.getByText(/Send a message once it resets to continue\.$/)).toBeInTheDocument() + expect(screen.queryByRole('button', { name: 'Continue' })).toBeNull() + }) +}) + describe('notice rows', () => { it('keeps unmatched host auth wording and its next step', async () => { await i18n.changeLanguage('fr') diff --git a/src/renderer/src/components/native-chat/NativeChatNoticeRow.tsx b/src/renderer/src/components/native-chat/NativeChatNoticeRow.tsx index c1d15aa7cab8..7f47ccf6f03e 100644 --- a/src/renderer/src/components/native-chat/NativeChatNoticeRow.tsx +++ b/src/renderer/src/components/native-chat/NativeChatNoticeRow.tsx @@ -28,6 +28,7 @@ import { import { readWholeAgentSessionFailureFact } from '../../../../shared/agent-session-failure' import { agentSessionFailureSentence } from '../../../../shared/agent-session-failure-words' import { sayAgentSessionFailureTranslated } from './agent-session-failure-words-text' +import { formatUsageLimitResetClock } from '../../../../shared/agent-session-usage-limit' const HOST_STATUS_WORDS: Record string> = { 'history-repaired': () => @@ -133,6 +134,9 @@ export function NativeChatNoticeRow({ const continueOffered = orcaStop?.turnItemId !== undefined && orcaStop.turnItemId === orcaStopView.offeredTurnItemId const failure = readWholeAgentSessionFailureFact(block.failure) + const usageLimitContinue = + block.usageLimitTurnItemId !== undefined && + block.usageLimitTurnItemId === orcaStopView.usageLimitTurnItemId // Only reword auth text fully described by its fact; host text may also carry command advice. const authSurface = failure?.kind === 'notSignedIn' @@ -142,7 +146,18 @@ export function NativeChatNoticeRow({ : undefined const text = named ? nativeChatOrcaStopRowText(orcaStop.cause, machine, { continueAvailable, remoteHost }) - : failure && authSurface + : failure?.kind === 'usageLimitReached' + ? agentSessionFailureSentence( + failure, + 'row', + { + agentName, + retryControl: usageLimitContinue, + usageLimitReset: formatUsageLimitResetClock + }, + sayAgentSessionFailureTranslated + ) + : failure && authSurface ? agentSessionFailureSentence( failure, authSurface, @@ -174,6 +189,14 @@ export function NativeChatNoticeRow({

{text}

{continueOffered ? ( + ) : usageLimitContinue ? ( + ) : null} {claudeSignIn && isClaudeSignInFailureKind(block.failure?.kind) ? ( diff --git a/src/renderer/src/components/native-chat/NativeChatStructuredSession.tsx b/src/renderer/src/components/native-chat/NativeChatStructuredSession.tsx index bcd81ef62faf..ee1d7ffd35ac 100644 --- a/src/renderer/src/components/native-chat/NativeChatStructuredSession.tsx +++ b/src/renderer/src/components/native-chat/NativeChatStructuredSession.tsx @@ -1,7 +1,7 @@ import { cn } from '@/lib/utils' import { NATIVE_CHAT_APPEARANCE_ROOT_CLASS } from './native-chat-appearance-style' import { useNativeChatStoreAppearanceStyle } from './use-native-chat-store-appearance-style' -import { useMemo, useRef, useState } from 'react' +import { useCallback, useMemo, useRef, useState } from 'react' import { agentSessionPromptQuestions } from '../../../../shared/agent-session-question-answer' import { structuredAgentSessionPaneKey } from '../../../../shared/structured-agent-session-projection' import { useStructuredChatLiveSession } from './use-structured-chat-live-session' @@ -127,14 +127,6 @@ export function NativeChatStructuredSession( const hostHeld = hostPermission.sendBlockedReason !== null const submits = useStructuredNativeChatSubmitReveal(controller, provisionalLaunch.retry, hostHeld) const promptResponse = useStructuredPromptResponseHold(submits.respond) - const continuation = useNativeChatInterruptedContinuation({ - target: props.target, - sessionId: props.sessionId, - journalItems: controller.journalItems, - submissions: controller.submissions, - isWorking: controller.isWorking || hostHeld, - reportComposerError - }) const needsFailureFacts = submits.queuedMessages.cards.some((card) => card.state === 'returned') || controller.submissions.some( @@ -234,6 +226,19 @@ export function NativeChatStructuredSession( onSubmitted: submits.revealLatest, sendBlockedReason: hostPermission.sendBlockedReason ?? install.sendBlockedReason }) + const sendContinuation = useCallback( + (text: string) => structuredTransport.send(text, []) !== false, + [structuredTransport] + ) + const continuation = useNativeChatInterruptedContinuation({ + target: props.target, + sessionId: props.sessionId, + journalItems: controller.journalItems, + submissions: controller.submissions, + isWorking: controller.isWorking || hostHeld, + reportComposerError, + sendMessage: sendContinuation + }) // Said once: on the pane when the failure took it, else in the composer's notices. const sessionError = diff --git a/src/renderer/src/components/native-chat/agent-session-failure-words-text.ts b/src/renderer/src/components/native-chat/agent-session-failure-words-text.ts index 036f0d14c8eb..a7f6ea94d02b 100644 --- a/src/renderer/src/components/native-chat/agent-session-failure-words-text.ts +++ b/src/renderer/src/components/native-chat/agent-session-failure-words-text.ts @@ -13,6 +13,7 @@ import { ATTACHMENT_FAILURE_PIECES } from './agent-session-failure-attachment-wo import { STOP_FAILURE_PIECES } from './agent-session-failure-stop-words-text' import { PROVIDER_EXIT_PIECES } from './agent-session-provider-exit-words-text' import { PROVIDER_RETRY_PIECES } from './agent-session-provider-retry-words-text' +import { USAGE_LIMIT_PIECES } from './agent-session-usage-limit-words-text' // The pieces a refusal notice says too keep the notice's keys, so each has one translation. const PIECES: Record string> = @@ -251,6 +252,7 @@ const PIECES: Record translate('components.native-chat.failureWords.hostStopped', COPY.hostStopped, values), ...PROVIDER_RETRY_PIECES, + ...USAGE_LIMIT_PIECES, previousExitUnverifiable: (values) => translate( 'components.native-chat.failureWords.previousExitUnverifiable', diff --git a/src/renderer/src/components/native-chat/agent-session-usage-limit-words-text.ts b/src/renderer/src/components/native-chat/agent-session-usage-limit-words-text.ts new file mode 100644 index 000000000000..e02e972ebd30 --- /dev/null +++ b/src/renderer/src/components/native-chat/agent-session-usage-limit-words-text.ts @@ -0,0 +1,61 @@ +// Desktop words for a usage limit an agent hit, kept beside the other failure pieces' translations. + +import { translate } from '@/i18n/i18n' +import { + AGENT_SESSION_FAILURE_COPY as COPY, + type AgentSessionFailureCopyId, + type AgentSessionFailureCopyValues +} from '../../../../shared/agent-session-failure-copy' + +export const USAGE_LIMIT_PIECES = { + usageLimitReached: (values) => + translate( + 'components.native-chat.failureWords.usageLimitReached', + COPY.usageLimitReached, + values + ), + usageLimitReachedNamed: (values) => + translate( + 'components.native-chat.failureWords.usageLimitReachedNamed', + COPY.usageLimitReachedNamed, + values + ), + usageLimitWindowSession: (values) => + translate( + 'components.native-chat.failureWords.usageLimitWindowSession', + COPY.usageLimitWindowSession, + values + ), + usageLimitWindowWeekly: (values) => + translate( + 'components.native-chat.failureWords.usageLimitWindowWeekly', + COPY.usageLimitWindowWeekly, + values + ), + usageLimitWindowWeeklyModel: (values) => + translate( + 'components.native-chat.failureWords.usageLimitWindowWeeklyModel', + COPY.usageLimitWindowWeeklyModel, + values + ), + usageLimitWindowCredits: (values) => + translate( + 'components.native-chat.failureWords.usageLimitWindowCredits', + COPY.usageLimitWindowCredits, + values + ), + usageLimitResetsAt: (values) => + translate( + 'components.native-chat.failureWords.usageLimitResetsAt', + COPY.usageLimitResetsAt, + values + ), + usageLimitSendAfterReset: (values) => + translate( + 'components.native-chat.failureWords.usageLimitSendAfterReset', + COPY.usageLimitSendAfterReset, + values + ) +} satisfies Partial< + Record string> +> diff --git a/src/renderer/src/components/native-chat/native-chat-orca-stop-context.ts b/src/renderer/src/components/native-chat/native-chat-orca-stop-context.ts index 430531c526dd..8475da06ee76 100644 --- a/src/renderer/src/components/native-chat/native-chat-orca-stop-context.ts +++ b/src/renderer/src/components/native-chat/native-chat-orca-stop-context.ts @@ -11,6 +11,9 @@ export type NativeChatOrcaStopView = { /** The cut turn whose row carries Continue right now, if any. */ offeredTurnItemId: string | null continueNow: () => void + /** The turn a usage limit ended whose row carries Continue right now, if any. */ + usageLimitTurnItemId: string | null + continueUsageLimit: () => void } export const NativeChatOrcaStopContext = createContext({ @@ -18,7 +21,9 @@ export const NativeChatOrcaStopContext = createContext({ remoteHost: false, continueAvailable: false, offeredTurnItemId: null, - continueNow: () => {} + continueNow: () => {}, + usageLimitTurnItemId: null, + continueUsageLimit: () => {} }) export function useNativeChatOrcaStopView(): NativeChatOrcaStopView { diff --git a/src/renderer/src/i18n/locales/en.json b/src/renderer/src/i18n/locales/en.json index e59129b8a20c..216ae67550f6 100644 --- a/src/renderer/src/i18n/locales/en.json +++ b/src/renderer/src/i18n/locales/en.json @@ -18372,6 +18372,14 @@ "providerRetryNumber": "Retry {{attempt}}.", "providerRetryNumberOf": "Retry {{attempt}} of {{maxRetries}}.", "providerRetryLastError": "Last error: {{detail}}.", + "usageLimitReached": "{{agent}} hit its usage limit.", + "usageLimitReachedNamed": "{{agent}} hit its {{window}} limit.", + "usageLimitWindowSession": "session", + "usageLimitWindowWeekly": "weekly", + "usageLimitWindowWeeklyModel": "weekly model", + "usageLimitWindowCredits": "extra usage", + "usageLimitResetsAt": "It resets at {{when}}.", + "usageLimitSendAfterReset": "Send a message once it resets to continue.", "previousExitUnverifiable": "Couldn't stop {{agent}} from before.", "sessionNotRestored": "{{agent}} couldn't reopen its earlier session, so this chat continues in a new one. {{agent}} doesn't remember the earlier messages.", "argumentsUnsupportedOption": "Saved Arguments contain an unsupported option ({{option}}).", @@ -19010,7 +19018,8 @@ "interruptedContinue": { "continue": "Continue", "failed": "Couldn't continue this chat. Try again, or send a message.", - "explanation": "Continue, and the agent first checks whether its last step finished." + "explanation": "Continue, and the agent first checks whether its last step finished.", + "usageLimitExplanation": "Asks the agent to continue where it left off. Use it once the limit resets." }, "claudeSignIn": { "signingIn": "Signing in…" diff --git a/src/renderer/src/i18n/locales/es.json b/src/renderer/src/i18n/locales/es.json index 42ccb8bb7b7d..7c184a02a9dd 100644 --- a/src/renderer/src/i18n/locales/es.json +++ b/src/renderer/src/i18n/locales/es.json @@ -18118,6 +18118,14 @@ "providerRetryNumber": "Reintento {{attempt}}.", "providerRetryNumberOf": "Reintento {{attempt}} de {{maxRetries}}.", "providerRetryLastError": "Último error: {{detail}}.", + "usageLimitReached": "{{agent}} alcanzó su límite de uso.", + "usageLimitReachedNamed": "{{agent}} alcanzó su límite {{window}}.", + "usageLimitWindowSession": "de sesión", + "usageLimitWindowWeekly": "semanal", + "usageLimitWindowWeeklyModel": "semanal del modelo", + "usageLimitWindowCredits": "de uso adicional", + "usageLimitResetsAt": "Se restablece a las {{when}}.", + "usageLimitSendAfterReset": "Envía un mensaje cuando se restablezca para continuar.", "previousExitUnverifiable": "No se pudo detener la ejecución anterior de {{agent}}.", "sessionNotRestored": "{{agent}} no pudo reabrir su sesión anterior, así que este chat continúa en una nueva. {{agent}} no recuerda los mensajes anteriores.", "agentCommandNotSignedIn": "Inicia sesión en {{agent}} con `{{loginCommand}}` en el equipo donde se ejecuta este chat.", @@ -18721,7 +18729,8 @@ "interruptedContinue": { "continue": "Continuar", "failed": "No se pudo continuar este chat. Inténtalo de nuevo o envía un mensaje.", - "explanation": "Continúa y el agente comprobará primero si su último paso terminó." + "explanation": "Continúa y el agente comprobará primero si su último paso terminó.", + "usageLimitExplanation": "Pide al agente que continúe donde lo dejó. Úsalo cuando se restablezca el límite." }, "rewind": { "unsupported": "Este chat no puede volver a un mensaje anterior.", diff --git a/src/renderer/src/i18n/locales/fr.json b/src/renderer/src/i18n/locales/fr.json index 3187af85220e..1b2bafc85c5f 100644 --- a/src/renderer/src/i18n/locales/fr.json +++ b/src/renderer/src/i18n/locales/fr.json @@ -18227,6 +18227,14 @@ "providerRetryNumber": "Nouvelle tentative {{attempt}}.", "providerRetryNumberOf": "Nouvelle tentative {{attempt}} sur {{maxRetries}}.", "providerRetryLastError": "Dernière erreur : {{detail}}.", + "usageLimitReached": "{{agent}} a atteint sa limite d’utilisation.", + "usageLimitReachedNamed": "{{agent}} a atteint sa limite {{window}}.", + "usageLimitWindowSession": "de session", + "usageLimitWindowWeekly": "hebdomadaire", + "usageLimitWindowWeeklyModel": "hebdomadaire du modèle", + "usageLimitWindowCredits": "d’utilisation supplémentaire", + "usageLimitResetsAt": "Elle se réinitialise à {{when}}.", + "usageLimitSendAfterReset": "Envoyez un message après sa réinitialisation pour continuer.", "previousExitUnverifiable": "Impossible d'arrêter l'exécution précédente de {{agent}}.", "sessionNotRestored": "{{agent}} n'a pas pu rouvrir sa session précédente, cette discussion continue donc dans une nouvelle. {{agent}} ne se souvient pas des messages précédents.", "agentCommandNotSignedIn": "Connectez-vous à {{agent}} avec `{{loginCommand}}` sur l’ordinateur qui exécute ce chat.", @@ -18830,7 +18838,8 @@ "interruptedContinue": { "continue": "Continuer", "failed": "Impossible de poursuivre cette conversation. Réessayez ou envoyez un message.", - "explanation": "Continuez, et l'agent vérifiera d'abord si sa dernière étape s'est terminée." + "explanation": "Continuez, et l'agent vérifiera d'abord si sa dernière étape s'est terminée.", + "usageLimitExplanation": "Demande à l’agent de reprendre là où il s’était arrêté. À utiliser une fois la limite réinitialisée." }, "rewind": { "unsupported": "Ce chat ne peut pas revenir à un message antérieur.", diff --git a/src/renderer/src/i18n/locales/ja.json b/src/renderer/src/i18n/locales/ja.json index 828aa7a2b013..23f51a3b622c 100644 --- a/src/renderer/src/i18n/locales/ja.json +++ b/src/renderer/src/i18n/locales/ja.json @@ -18158,6 +18158,14 @@ "providerRetryNumber": "{{attempt}} 回目の再試行です。", "providerRetryNumberOf": "{{maxRetries}} 回中 {{attempt}} 回目の再試行です。", "providerRetryLastError": "直近のエラー: {{detail}}。", + "usageLimitReached": "{{agent}} が使用量の上限に達しました。", + "usageLimitReachedNamed": "{{agent}} が{{window}}の上限に達しました。", + "usageLimitWindowSession": "セッション", + "usageLimitWindowWeekly": "週間", + "usageLimitWindowWeeklyModel": "モデル別の週間", + "usageLimitWindowCredits": "追加使用量", + "usageLimitResetsAt": "{{when}} にリセットされます。", + "usageLimitSendAfterReset": "リセット後にメッセージを送信すると続行できます。", "previousExitUnverifiable": "以前の {{agent}} を停止できませんでした。", "sessionNotRestored": "{{agent}} は以前のセッションを再開できなかったため、このチャットは新しいセッションで続行します。{{agent}} は以前のメッセージを覚えていません。", "agentCommandNotSignedIn": "このチャットを実行しているコンピューターで `{{loginCommand}}` を使って {{agent}} にサインインしてください。", @@ -18761,7 +18769,8 @@ "interruptedContinue": { "continue": "続行", "failed": "このチャットを続行できませんでした。もう一度試すか、メッセージを送信してください。", - "explanation": "続行すると、Agent はまず最後の手順が完了したかどうかを確認します。" + "explanation": "続行すると、Agent はまず最後の手順が完了したかどうかを確認します。", + "usageLimitExplanation": "中断したところから続けるよう Agent に依頼します。上限がリセットされてから使ってください。" }, "rewind": { "unsupported": "このチャットは以前のメッセージに戻れません。", diff --git a/src/renderer/src/i18n/locales/ko.json b/src/renderer/src/i18n/locales/ko.json index 6ecee7803550..cd4564d3fc30 100644 --- a/src/renderer/src/i18n/locales/ko.json +++ b/src/renderer/src/i18n/locales/ko.json @@ -18158,6 +18158,14 @@ "providerRetryNumber": "{{attempt}}번째 재시도입니다.", "providerRetryNumberOf": "{{maxRetries}}회 중 {{attempt}}번째 재시도입니다.", "providerRetryLastError": "마지막 오류: {{detail}}.", + "usageLimitReached": "{{agent}}이(가) 사용 한도에 도달했습니다.", + "usageLimitReachedNamed": "{{agent}}이(가) {{window}} 한도에 도달했습니다.", + "usageLimitWindowSession": "세션", + "usageLimitWindowWeekly": "주간", + "usageLimitWindowWeeklyModel": "모델별 주간", + "usageLimitWindowCredits": "추가 사용량", + "usageLimitResetsAt": "{{when}}에 초기화됩니다.", + "usageLimitSendAfterReset": "초기화된 후 메시지를 보내면 계속할 수 있습니다.", "previousExitUnverifiable": "이전에 실행된 {{agent}}을(를) 중지하지 못했습니다.", "sessionNotRestored": "{{agent}}이(가) 이전 세션을 다시 열 수 없어 이 채팅은 새 세션에서 계속됩니다. {{agent}}은(는) 이전 메시지를 기억하지 않습니다.", "agentCommandNotSignedIn": "이 채팅을 실행하는 컴퓨터에서 `{{loginCommand}}`으로 {{agent}}에 로그인하세요.", @@ -18761,7 +18769,8 @@ "interruptedContinue": { "continue": "계속", "failed": "이 채팅을 계속할 수 없습니다. 다시 시도하거나 메시지를 보내세요.", - "explanation": "계속하면 에이전트가 먼저 마지막 단계가 완료되었는지 확인합니다." + "explanation": "계속하면 에이전트가 먼저 마지막 단계가 완료되었는지 확인합니다.", + "usageLimitExplanation": "중단한 곳부터 계속하도록 에이전트에 요청합니다. 한도가 초기화된 후 사용하세요." }, "rewind": { "unsupported": "이 채팅은 이전 메시지로 돌아갈 수 없습니다.", diff --git a/src/renderer/src/i18n/locales/zh.json b/src/renderer/src/i18n/locales/zh.json index 778f6639eb9b..c7f437098396 100644 --- a/src/renderer/src/i18n/locales/zh.json +++ b/src/renderer/src/i18n/locales/zh.json @@ -18123,6 +18123,14 @@ "providerRetryNumber": "第 {{attempt}} 次重试。", "providerRetryNumberOf": "第 {{attempt}} 次重试,共 {{maxRetries}} 次。", "providerRetryLastError": "上次错误:{{detail}}。", + "usageLimitReached": "{{agent}} 已达到使用上限。", + "usageLimitReachedNamed": "{{agent}} 已达到{{window}}上限。", + "usageLimitWindowSession": "会话", + "usageLimitWindowWeekly": "每周", + "usageLimitWindowWeeklyModel": "模型每周", + "usageLimitWindowCredits": "额外用量", + "usageLimitResetsAt": "将在 {{when}} 重置。", + "usageLimitSendAfterReset": "重置后发送消息即可继续。", "previousExitUnverifiable": "无法停止之前的 {{agent}}。", "sessionNotRestored": "{{agent}} 无法重新打开之前的会话,因此此聊天将在新会话中继续。{{agent}} 不记得之前的消息。", "agentCommandNotSignedIn": "请在运行此聊天的电脑上使用 `{{loginCommand}}` 登录 {{agent}}。", @@ -18726,7 +18734,8 @@ "interruptedContinue": { "continue": "继续", "failed": "无法继续此聊天。请重试,或发送一条消息。", - "explanation": "继续后,智能体会先检查其上一步是否已完成。" + "explanation": "继续后,智能体会先检查其上一步是否已完成。", + "usageLimitExplanation": "让代理从中断处继续。请在上限重置后使用。" }, "rewind": { "unsupported": "此聊天无法返回到更早的消息。", diff --git a/src/shared/agent-session-failure-copy.ts b/src/shared/agent-session-failure-copy.ts index 83f80a1f3903..6892964fa656 100644 --- a/src/shared/agent-session-failure-copy.ts +++ b/src/shared/agent-session-failure-copy.ts @@ -144,6 +144,14 @@ export const AGENT_SESSION_FAILURE_COPY = { providerRetryNumber: 'Retry {{attempt}}.', providerRetryNumberOf: 'Retry {{attempt}} of {{maxRetries}}.', providerRetryLastError: 'Last error: {{detail}}.', + usageLimitReached: '{{agent}} hit its usage limit.', + usageLimitReachedNamed: '{{agent}} hit its {{window}} limit.', + usageLimitWindowSession: 'session', + usageLimitWindowWeekly: 'weekly', + usageLimitWindowWeeklyModel: 'weekly model', + usageLimitWindowCredits: 'extra usage', + usageLimitResetsAt: 'It resets at {{when}}.', + usageLimitSendAfterReset: 'Send a message once it resets to continue.', previousExitUnverifiable: "Couldn't stop {{agent}} from before.", sessionNotRestored: "{{agent}} couldn't reopen its earlier session, so this chat continues in a new one. {{agent}} doesn't remember the earlier messages." @@ -160,6 +168,10 @@ export type AgentSessionFailureCopyValues = { loginCommand?: string slashCommand?: string detail?: string + /** A usage limit's name, from the `usageLimitWindow*` pieces. */ + window?: string + /** When a usage limit resets, in the reader's clock. */ + when?: string option?: string limit?: string size?: string diff --git a/src/shared/agent-session-failure-words.ts b/src/shared/agent-session-failure-words.ts index 2d163cf3b7e9..b2410f558ebe 100644 --- a/src/shared/agent-session-failure-words.ts +++ b/src/shared/agent-session-failure-words.ts @@ -28,6 +28,10 @@ import { } from './agent-session-failure-copy' import { START_REFUSAL_RESUMABLE } from './agent-session-start-refusal-resumable' import { providerRetryWords, withRetryCause } from './agent-session-provider-retry-words' +import { + usageLimitWords, + type AgentSessionUsageLimitResetWords +} from './agent-session-usage-limit-words' import { commandRefusedByReason } from './agent-session-command-refusal-words' import { joinSentences } from './sentence-joining' import { @@ -72,6 +76,8 @@ export type AgentSessionFailureWordsContext = { retryControl?: boolean /** A direct create has no submitted message to send again. */ messageSubmitted?: boolean + /** How this reader says a usage limit's reset; without it the words name no time. */ + usageLimitReset?: AgentSessionUsageLimitResetWords } /** Person-facing provider text is quoted, but bounded so the sentence stays one. */ @@ -295,6 +301,11 @@ const FAILURE_SENTENCES = { retry?.cause ) : providerRetryWords(say, agent(say, context), retry), + usageLimitReached: (context, { usageLimit }, _surface, say) => + usageLimitWords(say, agent(say, context), usageLimit, { + resetWords: context.usageLimitReset, + continueControl: context.retryControl + }), previousExitUnverifiable: namingAgent('previousExitUnverifiable'), sessionNotRestored: namingAgent('sessionNotRestored') } satisfies Record diff --git a/src/shared/agent-session-failure.ts b/src/shared/agent-session-failure.ts index 2d5984331e6a..c69e1eae1e33 100644 --- a/src/shared/agent-session-failure.ts +++ b/src/shared/agent-session-failure.ts @@ -12,6 +12,10 @@ import { type AgentSessionArgumentProblem } from './agent-session-argument-problem' export type { AgentSessionArgumentProblem } from './agent-session-argument-problem' +import { + readAgentSessionUsageLimit, + type AgentSessionUsageLimit +} from './agent-session-usage-limit' import { structuralValuesEqualIgnoringUndefined } from './structural-value-equality' import { @@ -69,6 +73,8 @@ export const AGENT_SESSION_FAILURE_KINDS = [ 'hostStopped', /** The provider is retrying a request its API refused; not a failure yet. */ 'providerRetrying', + /** The account hit one of the agent's usage limits, which ended the turn until it resets. */ + 'usageLimitReached', /** A child a Stop could not prove gone: its exit is unverifiable. Kept for rows hosts wrote. */ 'previousExitUnverifiable', /** The agent could not reopen the chat's saved session, so a fresh one without its memory continues it. */ @@ -90,6 +96,7 @@ const STATUS_ROW_ONLY_FAILURE_KINDS = [ 'backgroundTaskNotStopped', 'answerUnconfirmed', 'providerRetrying', + 'usageLimitReached', 'previousExitUnverifiable', 'sessionNotRestored' ] as const satisfies readonly AgentSessionFailureKind[] @@ -165,6 +172,8 @@ export type AgentSessionFailureFact = { attachment?: AgentSessionAttachmentProblem /** On `providerRetrying`: why the provider is retrying. */ retry?: AgentSessionProviderRetry + /** On `usageLimitReached`: which limit, and when it resets. */ + usageLimit?: AgentSessionUsageLimit /** A safe option name from Orca's saved Arguments parser, never an error message. */ argumentProblem?: AgentSessionArgumentProblem /** Written only where Orca proves the agent never received the message: a Stop's withdrawal is @@ -207,6 +216,7 @@ export function agentSessionFailureFact( refusal?: AgentSessionRefusalReference attachment?: AgentSessionAttachmentProblem retry?: AgentSessionProviderRetry + usageLimit?: AgentSessionUsageLimit argumentProblem?: AgentSessionArgumentProblem neverReachedAgent?: true backgroundStop?: AgentSessionBackgroundStop @@ -223,6 +233,7 @@ export function agentSessionFailureFact( ...(extra.refusal ? { refusal: extra.refusal } : {}), ...(extra.attachment ? { attachment: extra.attachment } : {}), ...(extra.retry ? { retry: extra.retry } : {}), + ...(extra.usageLimit ? { usageLimit: extra.usageLimit } : {}), ...(extra.argumentProblem ? { argumentProblem: extra.argumentProblem } : {}), ...(extra.neverReachedAgent ? { neverReachedAgent: true as const } : {}), ...(extra.backgroundStop ? { backgroundStop: extra.backgroundStop } : {}) @@ -293,6 +304,7 @@ export function readAgentSessionFailureFact(value: unknown): AgentSessionFailure const refusal = readAgentSessionRefusalReference(value.refusal) const attachment = readAttachmentProblem(value.attachment) const retry = readProviderRetry(value.retry) + const usageLimit = readAgentSessionUsageLimit(value.usageLimit) const argumentProblem = readAgentSessionArgumentProblem(value.argumentProblem) return agentSessionFailureFact(value.kind, { ...(value.account === 'managed' || value.account === 'system' @@ -302,6 +314,7 @@ export function readAgentSessionFailureFact(value: unknown): AgentSessionFailure ...(refusal ? { refusal } : {}), ...(attachment ? { attachment } : {}), ...(retry ? { retry } : {}), + ...(usageLimit ? { usageLimit } : {}), ...(argumentProblem ? { argumentProblem } : {}), ...(value.neverReachedAgent === true ? { neverReachedAgent: true as const } : {}), ...(value.backgroundStop === 'task' || value.backgroundStop === 'all' diff --git a/src/shared/agent-session-usage-limit-words.ts b/src/shared/agent-session-usage-limit-words.ts new file mode 100644 index 000000000000..eda749fd1beb --- /dev/null +++ b/src/shared/agent-session-usage-limit-words.ts @@ -0,0 +1,64 @@ +// The words for a usage limit an agent hit: which limit, when it resets, and how to continue. + +import { + sayAgentSessionFailureEnglish, + type AgentSessionFailureCopyId, + type AgentSessionFailureCopyValues, + type AgentSessionFailureSay +} from './agent-session-failure-copy' +import { + formatUsageLimitResetClock, + type AgentSessionUsageLimit, + type AgentSessionUsageLimitWindow +} from './agent-session-usage-limit' +import { joinSentences } from './sentence-joining' + +/** A reset time in the reader's own clock. The host writes none: its time zone need not be the + * reader's, and a saved wait goes stale. */ +export type AgentSessionUsageLimitResetWords = (resetsAt: number) => string | null + +const WINDOW_COPY = { + session: 'usageLimitWindowSession', + weekly: 'usageLimitWindowWeekly', + weeklyModel: 'usageLimitWindowWeeklyModel', + credits: 'usageLimitWindowCredits' +} as const satisfies Record + +export function usageLimitWords( + say: AgentSessionFailureSay, + agent: AgentSessionFailureCopyValues, + limit: AgentSessionUsageLimit | undefined, + context: { + resetWords?: AgentSessionUsageLimitResetWords + /** The surface offers its own Continue, so the words leave out sending a message. */ + continueControl?: boolean + } +): string { + const lead = limit?.window + ? say('usageLimitReachedNamed', { ...agent, window: say(WINDOW_COPY[limit.window]) }) + : say('usageLimitReached', agent) + const reset = limit?.resetsAt !== undefined ? context.resetWords?.(limit.resetsAt) : null + return joinSentences([ + lead, + ...(reset ? [say('usageLimitResetsAt', { when: reset })] : []), + ...(context.continueControl ? [] : [say('usageLimitSendAfterReset')]) + ]) +} + +/** A usage-limit line for a reader that has no agent name to reword it with (the phone): the host's + * sentence, then the reset in this reader's clock. Any other line keeps its text. */ +export function usageLimitLineText(block: { + text: string + failure?: { kind: string; usageLimit?: AgentSessionUsageLimit } +}): string { + const resetsAt = + block.failure?.kind === 'usageLimitReached' ? block.failure.usageLimit?.resetsAt : undefined + return resetsAt === undefined + ? block.text + : joinSentences([ + block.text, + sayAgentSessionFailureEnglish('usageLimitResetsAt', { + when: formatUsageLimitResetClock(resetsAt) + }) + ]) +} diff --git a/src/shared/agent-session-usage-limit.ts b/src/shared/agent-session-usage-limit.ts new file mode 100644 index 000000000000..02b0a066b29a --- /dev/null +++ b/src/shared/agent-session-usage-limit.ts @@ -0,0 +1,59 @@ +// Which of the agent's usage limits a turn hit and when it resets, as the provider reported it. +// Carried on a `usageLimitReached` failure fact; every reader words it in its own clock. + +/** `session`: the rolling few-hour limit. `weekly`: the account's weekly limit. `weeklyModel`: a + * weekly limit on one model. `credits`: paid usage beyond the plan ran out. */ +export const AGENT_SESSION_USAGE_LIMIT_WINDOWS = [ + 'session', + 'weekly', + 'weeklyModel', + 'credits' +] as const +export type AgentSessionUsageLimitWindow = (typeof AGENT_SESSION_USAGE_LIMIT_WINDOWS)[number] + +export type AgentSessionUsageLimit = { + window?: AgentSessionUsageLimitWindow + /** Epoch ms. Absent when the provider gave none, or any limit it hit had none. */ + resetsAt?: number +} + +/** Past this, a reset time is not one a person waits for, so the words leave it out. */ +const MAX_RESET_WAIT_MS = 31 * 24 * 60 * 60 * 1000 + +/** A reset time worth saying, as epoch ms: finite, positive and within a month of `now`. */ +export function usageLimitResetsAt(value: unknown, now: number): number | undefined { + return typeof value === 'number' && + Number.isFinite(value) && + value > 0 && + value - now <= MAX_RESET_WAIT_MS + ? value + : undefined +} + +/** A limit as a reader meets it; undefined when it names nothing this build knows. */ +export function readAgentSessionUsageLimit(value: unknown): AgentSessionUsageLimit | undefined { + if (typeof value !== 'object' || value === null || Array.isArray(value)) { + return undefined + } + const record: Record = { ...value } + const window = AGENT_SESSION_USAGE_LIMIT_WINDOWS.find((known) => known === record.window) + const resetsAt = + typeof record.resetsAt === 'number' && Number.isFinite(record.resetsAt) && record.resetsAt > 0 + ? record.resetsAt + : undefined + return window || resetsAt + ? { ...(window ? { window } : {}), ...(resetsAt ? { resetsAt } : {}) } + : undefined +} + +/** A reset time in the reader's own clock: the time alone today, else with its day. */ +export function formatUsageLimitResetClock(resetsAt: number, now: number = Date.now()): string { + const at = new Date(resetsAt) + const today = at.toDateString() === new Date(now).toDateString() + return new Intl.DateTimeFormat( + undefined, + today + ? { hour: 'numeric', minute: '2-digit' } + : { weekday: 'short', month: 'short', day: 'numeric', hour: 'numeric', minute: '2-digit' } + ).format(at) +} diff --git a/src/shared/native-chat-orca-stop-cut.ts b/src/shared/native-chat-orca-stop-cut.ts index cab5825ea6e1..cf6e825c821d 100644 --- a/src/shared/native-chat-orca-stop-cut.ts +++ b/src/shared/native-chat-orca-stop-cut.ts @@ -8,7 +8,7 @@ import { isRootAgentJournalItem } from './agent-session-journal-producer' import type { AgentJournalRenderItem, AgentJournalSubmission } from './agent-session-journal-types' import { STALE_SESSION_ROW_PREFIX } from './agent-session-stop-row-identity' import { readAgentJournalTurn, readAgentJournalTurnOutcome } from './agent-session-turn-record' -import { agentTurnVerdict } from './agent-turn-outcome' +import { agentTurnVerdict, type AgentTurnOutcome } from './agent-turn-outcome' import { structuredAgentSessionCommandTurnItemIds } from './structured-agent-session-command-entry' import { isStructuredAgentSessionNonRequestRow } from './structured-agent-session-latest-request' @@ -36,19 +36,18 @@ export type NativeChatOrcaStopCut = { } /** - * The latest root turn, when an Orca stop cut it and nothing was sent since: no request after it, - * and no send still on its way. A steer into that turn or a conversation command asks for nothing - * new (`isStructuredAgentSessionNonRequestRow`). Null otherwise. + * The latest root turn, when nothing was sent since: no request after it, and no send still on its + * way. A steer into that turn or a conversation command asks for nothing new + * (`isStructuredAgentSessionNonRequestRow`). Null otherwise. */ -export function latestNativeChatOrcaStopCut( +export function latestNativeChatTurnSinceRequest( items: readonly AgentJournalRenderItem[], submissions: readonly Pick[] -): NativeChatOrcaStopCut | null { +): { turnItem: AgentJournalRenderItem; verdict: AgentTurnOutcome | null } | null { if (submissions.some((submission) => submission.dispatchState === 'pending')) { return null } const commandTurns = structuredAgentSessionCommandTurnItemIds(items) - let turnIndex = -1 for (let index = items.length - 1; index >= 0; index -= 1) { const item = items[index]! if ( @@ -60,29 +59,43 @@ export function latestNativeChatOrcaStopCut( if (item.body.kind === 'message' && item.body.role === 'user') { return null } - if (readAgentJournalTurn(item.body)) { - turnIndex = index - break + const turn = readAgentJournalTurn(item.body) + if (turn) { + return { + turnItem: item, + verdict: agentTurnVerdict({ state: turn.state, outcome: readAgentJournalTurnOutcome(turn) }) + } } } - const turnItem = items[turnIndex] - const turn = turnItem ? readAgentJournalTurn(turnItem.body) : null - if ( - !turnItem || - !turn || - agentTurnVerdict({ state: turn.state, outcome: readAgentJournalTurnOutcome(turn) }) !== - 'interruption' - ) { - return null - } + return null +} + +/** The rows inside one turn that answer `read`, first match wins. */ +export function findInNativeChatTurn( + items: readonly AgentJournalRenderItem[], + turnItemId: string, + read: (item: AgentJournalRenderItem) => T | null +): T | null { for (const item of items) { - const cause = - item.turnScope?.kind === 'turn' && item.turnScope.turnItemId === turnItem.itemId - ? orcaStopCauseOfRow(item) - : null - if (cause) { - return { turnItemId: turnItem.itemId, cause } + const inTurn = item.turnScope?.kind === 'turn' && item.turnScope.turnItemId === turnItemId + const found = inTurn ? read(item) : null + if (found !== null) { + return found } } return null } + +/** The latest root turn, when an Orca stop cut it and nothing was sent since. Null otherwise. */ +export function latestNativeChatOrcaStopCut( + items: readonly AgentJournalRenderItem[], + submissions: readonly Pick[] +): NativeChatOrcaStopCut | null { + const latest = latestNativeChatTurnSinceRequest(items, submissions) + if (!latest || latest.verdict !== 'interruption') { + return null + } + const turnItemId = latest.turnItem.itemId + const cause = findInNativeChatTurn(items, turnItemId, orcaStopCauseOfRow) + return cause ? { turnItemId, cause } : null +} diff --git a/src/shared/native-chat-types.ts b/src/shared/native-chat-types.ts index ea35e3ac5318..09e1828acd0b 100644 --- a/src/shared/native-chat-types.ts +++ b/src/shared/native-chat-types.ts @@ -68,6 +68,8 @@ export type NativeChatTextBlock = { failure?: AgentSessionFailureFact /** On the line about a reply Orca's own stop cut off: why, and the turn it cut. */ orcaStop?: AgentSessionOrcaStop & { turnItemId?: string } + /** On a usage-limit line: the turn the limit ended, which its Continue picks up. */ + usageLimitTurnItemId?: string } /** A tool invocation by the agent. `input` is the (already-serialized) tool diff --git a/src/shared/native-chat-usage-limit-cut.ts b/src/shared/native-chat-usage-limit-cut.ts new file mode 100644 index 000000000000..b9c6e6b2a72d --- /dev/null +++ b/src/shared/native-chat-usage-limit-cut.ts @@ -0,0 +1,31 @@ +// A turn one of the agent's usage limits ended, as its row says, and whether the chat still sits on +// it. Derived from the journal each time, never stored; the chat offers Continue from it. + +import { readAgentSessionFailureFact } from './agent-session-failure' +import type { AgentJournalRenderItem, AgentJournalSubmission } from './agent-session-journal-types' +import type { AgentSessionUsageLimit } from './agent-session-usage-limit' +import { findInNativeChatTurn, latestNativeChatTurnSinceRequest } from './native-chat-orca-stop-cut' + +/** What the agent is sent when the person continues a turn its usage limit ended. */ +export const NATIVE_CHAT_USAGE_LIMIT_CONTINUE_MESSAGE = 'Continue where you left off.' + +/** The limit a row reports, when it is a usage-limit row. */ +function usageLimitOfRow(item: AgentJournalRenderItem): AgentSessionUsageLimit | null { + if (item.body.kind !== 'status') { + return null + } + const fact = readAgentSessionFailureFact(item.body.failure) + return fact?.kind === 'usageLimitReached' ? (fact.usageLimit ?? {}) : null +} + +/** The latest root turn, when a usage limit ended it and nothing was sent since. Null otherwise. */ +export function latestNativeChatUsageLimitCut( + items: readonly AgentJournalRenderItem[], + submissions: readonly Pick[] +): { turnItemId: string } | null { + const latest = latestNativeChatTurnSinceRequest(items, submissions) + return latest?.verdict === 'failure' && + findInNativeChatTurn(items, latest.turnItem.itemId, usageLimitOfRow) !== null + ? { turnItemId: latest.turnItem.itemId } + : null +} diff --git a/src/shared/structured-agent-session-status-block.ts b/src/shared/structured-agent-session-status-block.ts index 2febb6af6872..b3edb125c53d 100644 --- a/src/shared/structured-agent-session-status-block.ts +++ b/src/shared/structured-agent-session-status-block.ts @@ -28,6 +28,9 @@ export function structuredAgentSessionStatusBlock( ...(body.tone !== undefined ? { tone: body.tone } : {}), ...(body.providerFrame ? { providerFrame: body.providerFrame } : {}), ...(failure ? { failure } : {}), + ...(failure?.kind === 'usageLimitReached' && turnScope?.kind === 'turn' + ? { usageLimitTurnItemId: turnScope.turnItemId } + : {}), ...(orcaStop ? { orcaStop: { From 16dc2c1100735d3c24f961abb05d9e6f66339ed4 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Sun, 18 Oct 2026 11:56:52 -0700 Subject: [PATCH 02/34] fix(native-chat): keep the failure words and chat session files within their line budgets Moves the attachment-problem sentences to their own file and hands the composer's send straight to Continue. --- .../NativeChatInterruptedContinue.test.tsx | 2 +- .../NativeChatInterruptedContinue.tsx | 11 ++-- .../NativeChatStructuredSession.tsx | 8 +-- .../agent-session-attachment-failure-words.ts | 51 +++++++++++++++++++ src/shared/agent-session-failure-words.ts | 35 +------------ 5 files changed, 62 insertions(+), 45 deletions(-) create mode 100644 src/shared/agent-session-attachment-failure-words.ts diff --git a/src/renderer/src/components/native-chat/NativeChatInterruptedContinue.test.tsx b/src/renderer/src/components/native-chat/NativeChatInterruptedContinue.test.tsx index a01f060584a1..28a0dd42ac9a 100644 --- a/src/renderer/src/components/native-chat/NativeChatInterruptedContinue.test.tsx +++ b/src/renderer/src/components/native-chat/NativeChatInterruptedContinue.test.tsx @@ -84,7 +84,7 @@ function Harness(props: Props): React.JSX.Element { journalItems: props.journalItems ?? cutChat, submissions: props.submissions ?? [], isWorking: props.isWorking ?? false, - sendMessage: () => true + send: () => true }) return ( diff --git a/src/renderer/src/components/native-chat/NativeChatInterruptedContinue.tsx b/src/renderer/src/components/native-chat/NativeChatInterruptedContinue.tsx index eea8d352ce28..78298ec4f673 100644 --- a/src/renderer/src/components/native-chat/NativeChatInterruptedContinue.tsx +++ b/src/renderer/src/components/native-chat/NativeChatInterruptedContinue.tsx @@ -21,6 +21,7 @@ import { useStructuredAgentSessionHostLabel } from './use-structured-agent-sessi import { useNativeChatRestartResuming } from '../native-chat-resume-on-restart-store' import { useNativeChatLaunchResumePending } from '../native-chat-launch-resume-decision' import type { NativeChatComposerNoticeContent } from './native-chat-composer-notice' +import type { NativeChatStructuredComposerTransport } from './native-chat-composer-types' type ContinueAnswer = { outcome?: string } @@ -47,10 +48,10 @@ export function useNativeChatInterruptedContinuation(input: { isWorking: boolean /** Stable; a Continue click is the user's newer action, so it clears the composer's error. */ reportComposerError: (text: null) => void - /** Sends as the composer does; false when the chat took nothing. */ - sendMessage: (text: string) => boolean + /** The composer's send; false when the chat took nothing. */ + send: NativeChatStructuredComposerTransport['send'] }): NativeChatInterruptedContinuation { - const { target, sessionId, reportComposerError, sendMessage } = input + const { target, sessionId, reportComposerError, send } = input const hostLabel = useStructuredAgentSessionHostLabel(target) const capability = useStructuredAgentSessionHostCapabilityState( target, @@ -86,10 +87,10 @@ export function useNativeChatInterruptedContinuation(input: { } setAsked(usageLimitTurnItemId) // A send the chat refused says why in the composer, as any send does; Continue comes back. - if (!sendMessage(NATIVE_CHAT_USAGE_LIMIT_CONTINUE_MESSAGE)) { + if (send(NATIVE_CHAT_USAGE_LIMIT_CONTINUE_MESSAGE, []) === false) { setAsked(null) } - }, [usageLimitTurnItemId, sendMessage]) + }, [usageLimitTurnItemId, send]) const continueNow = useCallback((): void => { if (offered === null) { return diff --git a/src/renderer/src/components/native-chat/NativeChatStructuredSession.tsx b/src/renderer/src/components/native-chat/NativeChatStructuredSession.tsx index ee1d7ffd35ac..415c8851b73c 100644 --- a/src/renderer/src/components/native-chat/NativeChatStructuredSession.tsx +++ b/src/renderer/src/components/native-chat/NativeChatStructuredSession.tsx @@ -1,7 +1,7 @@ import { cn } from '@/lib/utils' import { NATIVE_CHAT_APPEARANCE_ROOT_CLASS } from './native-chat-appearance-style' import { useNativeChatStoreAppearanceStyle } from './use-native-chat-store-appearance-style' -import { useCallback, useMemo, useRef, useState } from 'react' +import { useMemo, useRef, useState } from 'react' import { agentSessionPromptQuestions } from '../../../../shared/agent-session-question-answer' import { structuredAgentSessionPaneKey } from '../../../../shared/structured-agent-session-projection' import { useStructuredChatLiveSession } from './use-structured-chat-live-session' @@ -226,10 +226,6 @@ export function NativeChatStructuredSession( onSubmitted: submits.revealLatest, sendBlockedReason: hostPermission.sendBlockedReason ?? install.sendBlockedReason }) - const sendContinuation = useCallback( - (text: string) => structuredTransport.send(text, []) !== false, - [structuredTransport] - ) const continuation = useNativeChatInterruptedContinuation({ target: props.target, sessionId: props.sessionId, @@ -237,7 +233,7 @@ export function NativeChatStructuredSession( submissions: controller.submissions, isWorking: controller.isWorking || hostHeld, reportComposerError, - sendMessage: sendContinuation + send: structuredTransport.send }) // Said once: on the pane when the failure took it, else in the composer's notices. diff --git a/src/shared/agent-session-attachment-failure-words.ts b/src/shared/agent-session-attachment-failure-words.ts new file mode 100644 index 000000000000..696637f14284 --- /dev/null +++ b/src/shared/agent-session-attachment-failure-words.ts @@ -0,0 +1,51 @@ +// The words for an attachment a message could not carry: which check it failed, and the limit. + +import type { + AgentSessionAttachmentProblem, + AgentSessionAttachmentProblemReason +} from './agent-session-failure' +import type { AgentSessionFailureSay } from './agent-session-failure-copy' +import type { AgentSessionFailureWordsContext } from './agent-session-failure-words' + +const BYTES_PER_MB = 1024 * 1024 + +function agent(say: AgentSessionFailureSay, { agentName }: AgentSessionFailureWordsContext) { + return { agent: agentName ?? say('theAgent') } +} + +// The number only; each language's sentence carries its own unit. +function megabytes(bytes: number): string { + return String(Math.round((bytes / BYTES_PER_MB) * 10) / 10) +} + +const ATTACHMENT_SENTENCES = { + empty: (say) => say('attachmentEmpty'), + tooLarge: (say, _, { limit }) => + limit ? say('attachmentLargerThan', { size: megabytes(limit) }) : say('attachmentTooLarge'), + tooMany: (say, context, { limit }) => + limit + ? say('attachmentAtMost', { ...agent(say, context), limit: String(limit) }) + : say('attachmentTooMany'), + totalTooLarge: (say, _, { limit }) => + limit + ? say('attachmentTotalMoreThan', { size: megabytes(limit) }) + : say('attachmentTotalTooLarge'), + unsupportedType: (say, context) => say('attachmentUnsupportedType', agent(say, context)), + notAFile: (say) => say('attachmentNotAFile'), + noSource: (say) => say('attachmentNoSource') +} satisfies Record< + AgentSessionAttachmentProblemReason, + ( + say: AgentSessionFailureSay, + context: AgentSessionFailureWordsContext, + problem: AgentSessionAttachmentProblem + ) => string +> + +export function attachmentProblemSentence( + say: AgentSessionFailureSay, + context: AgentSessionFailureWordsContext, + problem: AgentSessionAttachmentProblem +): string { + return ATTACHMENT_SENTENCES[problem.reason](say, context, problem) +} diff --git a/src/shared/agent-session-failure-words.ts b/src/shared/agent-session-failure-words.ts index b2410f558ebe..b42e72554ab4 100644 --- a/src/shared/agent-session-failure-words.ts +++ b/src/shared/agent-session-failure-words.ts @@ -9,8 +9,6 @@ import { isSubmissionRejectionFact, - type AgentSessionAttachmentProblem, - type AgentSessionAttachmentProblemReason, type AgentSessionFailureFact, type AgentSessionFailureKind, type ProviderDiagnostic, @@ -33,6 +31,7 @@ import { type AgentSessionUsageLimitResetWords } from './agent-session-usage-limit-words' import { commandRefusedByReason } from './agent-session-command-refusal-words' +import { attachmentProblemSentence } from './agent-session-attachment-failure-words' import { joinSentences } from './sentence-joining' import { DISPATCH_REJECTED_CANCELLED, @@ -82,7 +81,6 @@ export type AgentSessionFailureWordsContext = { /** Person-facing provider text is quoted, but bounded so the sentence stays one. */ const MAX_QUOTED_DETAIL_CHARS = 512 -const BYTES_PER_MB = 1024 * 1024 type Sentence = ( context: AgentSessionFailureWordsContext, @@ -174,35 +172,6 @@ function couldNot(verb: 'couldNotStart' | 'couldNotRestart'): Sentence { } } -// The number only; each language's sentence carries its own unit. -function megabytes(bytes: number): string { - return String(Math.round((bytes / BYTES_PER_MB) * 10) / 10) -} - -const ATTACHMENT_SENTENCES = { - empty: (say) => say('attachmentEmpty'), - tooLarge: (say, _, { limit }) => - limit ? say('attachmentLargerThan', { size: megabytes(limit) }) : say('attachmentTooLarge'), - tooMany: (say, context, { limit }) => - limit - ? say('attachmentAtMost', { ...agent(say, context), limit: String(limit) }) - : say('attachmentTooMany'), - totalTooLarge: (say, _, { limit }) => - limit - ? say('attachmentTotalMoreThan', { size: megabytes(limit) }) - : say('attachmentTotalTooLarge'), - unsupportedType: (say, context) => say('attachmentUnsupportedType', agent(say, context)), - notAFile: (say) => say('attachmentNotAFile'), - noSource: (say) => say('attachmentNoSource') -} satisfies Record< - AgentSessionAttachmentProblemReason, - ( - say: AgentSessionFailureSay, - context: AgentSessionFailureWordsContext, - problem: AgentSessionAttachmentProblem - ) => string -> - const FAILURE_SENTENCES = { providerStartFailed: (context, _fact, _surface, say) => joinSentences([say('providerStartFailed', agent(say, context)), ...startRetry(say, context)]), @@ -248,7 +217,7 @@ const FAILURE_SENTENCES = { ), attachmentInvalid: (context, fact, _surface, say) => fact.attachment - ? ATTACHMENT_SENTENCES[fact.attachment.reason](say, context, fact.attachment) + ? attachmentProblemSentence(say, context, fact.attachment) : say('attachmentInvalid'), attachmentUnreadable: (_context, _fact, _surface, say) => say('attachmentUnreadable'), emptyMessage: (_context, _fact, _surface, say) => say('emptyMessage'), From 71e91e3db67811087f7fb057675c9ba610611b65 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Sun, 18 Oct 2026 12:03:07 -0700 Subject: [PATCH 03/34] fix(native-chat): drop a check the shown branch already rules out --- src/main/claude/claude-result-journaling.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/claude/claude-result-journaling.ts b/src/main/claude/claude-result-journaling.ts index af9cf918374c..6a0da067da70 100644 --- a/src/main/claude/claude-result-journaling.ts +++ b/src/main/claude/claude-result-journaling.ts @@ -102,7 +102,7 @@ export function journalClaudeResult( providerFallback.append( kind, message, - usageLimit === 'shown' ? null : (usageLimit ?? failure?.text), + usageLimit ?? failure?.text, undefined, { reportsFailure: failure !== null }, // A result that settles no turn is a CHILD's result: this From 3d4e2b76a86088f168106e7cc94e3c218327dd7e Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Sun, 18 Oct 2026 12:10:21 -0700 Subject: [PATCH 04/34] fix(i18n): ship the usage-limit failure words in the runtime catalog --- src/renderer/src/i18n/en-runtime-required.json | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/src/renderer/src/i18n/en-runtime-required.json b/src/renderer/src/i18n/en-runtime-required.json index 2ef0bb0848c8..eb8c1a47a073 100644 --- a/src/renderer/src/i18n/en-runtime-required.json +++ b/src/renderer/src/i18n/en-runtime-required.json @@ -2988,7 +2988,15 @@ "stopRefusedQuoted": "{{agent}} didn't stop: {{detail}}.", "theAgent": "The agent", "thenSendAgain": "Then send your message again.", - "writeFailed": "Orca couldn't hand this message to the agent, so it was not sent." + "writeFailed": "Orca couldn't hand this message to the agent, so it was not sent.", + "usageLimitReached": "{{agent}} hit its usage limit.", + "usageLimitReachedNamed": "{{agent}} hit its {{window}} limit.", + "usageLimitResetsAt": "It resets at {{when}}.", + "usageLimitSendAfterReset": "Send a message once it resets to continue.", + "usageLimitWindowCredits": "extra usage", + "usageLimitWindowSession": "session", + "usageLimitWindowWeekly": "weekly", + "usageLimitWindowWeeklyModel": "weekly model" }, "notices": { "compaction": "Context compacted", From adb3b929333cf726b982a7041874a5bd5956c1c5 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Sun, 18 Oct 2026 14:17:14 -0700 Subject: [PATCH 05/34] fix(native-chat): reconcile usage failures by owning turn and typed cause --- .../acp/acp-timeline-turn-failures.test.ts | 10 +- src/main/acp/acp-turn-failures.ts | 13 +-- src/main/claude/claude-message-journaling.ts | 24 +++-- src/main/claude/claude-open-turn.ts | 7 ++ src/main/claude/claude-result-journaling.ts | 17 +++- src/main/claude/claude-usage-limits.test.ts | 55 ++++++++++- src/main/claude/claude-usage-limits.ts | 98 +++++++++---------- ...codex-structured-journal-generic-frames.ts | 4 +- src/main/codex/codex-usage-limits.test.ts | 19 ++++ src/main/codex/codex-usage-limits.ts | 23 +++-- src/shared/native-chat-usage-limit-cut.ts | 3 +- 11 files changed, 182 insertions(+), 91 deletions(-) diff --git a/src/main/acp/acp-timeline-turn-failures.test.ts b/src/main/acp/acp-timeline-turn-failures.test.ts index 320370bf4f06..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 usage-limited turn the provider gave no words for', 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,13 +179,14 @@ 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: 'warning', text: 'The agent hit its usage limit. Send a message once it resets to continue.', - failure: { kind: 'usageLimitReached' } + 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 efa033f212e6..2e9e2e3756aa 100644 --- a/src/main/acp/acp-turn-failures.ts +++ b/src/main/acp/acp-turn-failures.ts @@ -96,19 +96,16 @@ export class AcpTurnFailures { ): ProviderTimelineEvent[] { const written = this.rows.peek(turn) const detail = text === undefined ? undefined : providerDiagnostic(text, 'person') - if ( - written !== undefined && - (written.text !== '' || !detail) && - (!notSignedIn || written.notSignedIn) - ) { - return [] - } const diagnostic = - detail ?? (written?.text ? providerDiagnostic(written.text, 'person') : undefined) + (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 && written.text === (diagnostic?.text ?? '') && + written.notSignedIn === authenticationRequired && written.usageLimited === usageLimited) { + return [] + } this.rows.set(turn, { text: diagnostic?.text ?? '', notSignedIn: authenticationRequired, diff --git a/src/main/claude/claude-message-journaling.ts b/src/main/claude/claude-message-journaling.ts index 0387702ca969..85124c62b435 100644 --- a/src/main/claude/claude-message-journaling.ts +++ b/src/main/claude/claude-message-journaling.ts @@ -94,23 +94,31 @@ 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) + // The terminal fact belongs to the actual turn, including frames without a user stamp. + if (envelope.role === 'assistant') { + openOutputTurn() + } + const usageLimit = ctx.usageLimits.assistant(message, ctx.turn) const body = ctx.authenticationFailures.assistant(message) ?? - ctx.usageLimits.assistant(message) ?? + usageLimit ?? ctx.threadGoal.report(message, claudeMessageIdentity(envelope), observedAt) ?? claudeMessageBody(outputEnvelope) - const identity = + const terminalIdentity = usageLimit && producerRef === null && ctx.turn.identity + ? { provider: 'orca' as const, clientMessageId: `terminal-failure:claude:${agentJournalItemKey(ctx.turn.identity)}` } + : null + const identity = terminalIdentity ?? (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 diff --git a/src/main/claude/claude-open-turn.ts b/src/main/claude/claude-open-turn.ts index e7c36ddaac04..ab6791c913ef 100644 --- a/src/main/claude/claude-open-turn.ts +++ b/src/main/claude/claude-open-turn.ts @@ -21,6 +21,7 @@ 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 type { ClaudeUsageLimitEvidence } from './claude-usage-limits' import type { ClaudeStartedSend } from './claude-structured-session-state' export type ClaudeOpenTurnDeps = { @@ -35,6 +36,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 +127,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 +146,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 +171,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 } } @@ -187,10 +192,12 @@ export class ClaudeOpenTurn { settle(end: ClaudeTurnEnd, contextUsage?: AgentSessionContextUsage): void { // 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.usageLimitEvidence = null this.current = null } this.deps.sink.setActivity?.(null) diff --git a/src/main/claude/claude-result-journaling.ts b/src/main/claude/claude-result-journaling.ts index 6a0da067da70..6d82fa1e8009 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 { agentJournalItemKey } from '../../shared/agent-session-journal-item-key' import type { ClaudeContextFacts } from './claude-context-facts' import { claudeCommandResultEnd } from './claude-command-turn' import type { ClaudeMessageJournalContext } from './claude-message-journaling' @@ -63,6 +64,8 @@ export function journalClaudeResult( } // 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`). @@ -95,9 +98,17 @@ export function journalClaudeResult( const kind = claudeProviderFrameKind(message) const failure = claudeResultFailure(message, leftToStop) // A failed root result the limit refused writes the limit's row, not the result's. - const usageLimit = settlesTurn ? usageLimits.result(message, failure !== null) : null - const alreadyShown = - authenticationFailures.resultAlreadyShown(message) || usageLimit === 'shown' + const usageLimit = settlesTurn ? usageLimits.result(message, failure !== null, usageEvidence) : null + if (usageLimit && endedTurnIdentity) { + sink.appendItem( + { provider: 'orca', clientMessageId: `terminal-failure:claude:${agentJournalItemKey(endedTurnIdentity)}` }, + usageLimit, + { turnScope: endedTurnScope } + ) + sink.publish() + return + } + const alreadyShown = authenticationFailures.resultAlreadyShown(message) if ((failure || !isSettledClaudeResultKind(kind)) && !alreadyShown) { providerFallback.append( kind, diff --git a/src/main/claude/claude-usage-limits.test.ts b/src/main/claude/claude-usage-limits.test.ts index ed293fb67723..30edbb4ba3d1 100644 --- a/src/main/claude/claude-usage-limits.test.ts +++ b/src/main/claude/claude-usage-limits.test.ts @@ -1,5 +1,5 @@ -import { describe, expect, it } from 'vitest' -import { frame, setup, userFrame } from './claude-context-usage-test-support' +import { describe, expect, it, vi } from 'vitest' +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 @@ -62,8 +62,13 @@ describe('a Claude usage limit', () => { const t = setup() t.handle(userFrame('turn-a', 1_000)) t.handle(rateLimitEvent('rejected', 1_100)) - t.handle(refusedFrame('a', 1_200, LIMIT_TEXT)) - t.handle(failedResult('a', 1_300, LIMIT_TEXT)) + t.handle(assistantFrame('first', 1_150, 20)) + 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')) // 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)) @@ -84,6 +89,48 @@ describe('a Claude usage limit', () => { t.translator.dispose() }) + it('keeps typed other causes and replacement turns separate from the account snapshot', () => { + const t = setup() + t.handle(userFrame('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('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: 'blocking_limit', 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.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('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('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)) diff --git a/src/main/claude/claude-usage-limits.ts b/src/main/claude/claude-usage-limits.ts index 88b9b12cb4bd..8f62621260c0 100644 --- a/src/main/claude/claude-usage-limits.ts +++ b/src/main/claude/claude-usage-limits.ts @@ -3,12 +3,12 @@ import { agentSessionFailureWords, type AgentSessionFailureRowWords } from '../../shared/agent-session-failure-words' -import { BoundedMap } from '../../shared/bounded-map' 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 = { @@ -40,20 +40,14 @@ function messageText(message: Record): string { : '' } -/** - * The account's usage limits as Claude reports them: the limit an API-error frame names - * (`api_error: usage_limit_reached`), else a `rate_limit_event` saying a limit is `rejected` with - * no paid usage to fall back on. Only those mean the account's own limit: the CLI shares the - * frame's `error: rate_limit` with throttles and policy refusals that no reset clears. The CLI - * repeats an unchanged rejection only now and then, so each one stands until a reading allows that - * limit again or its reset passes. - */ +export type ClaudeUsageLimitEvidence = { + cause: 'quota' | 'other' | 'untyped' + row: ClaudeUsageLimitRow | null +} + +// Account observations outlive turns because unchanged rejection notifications are throttled. export class ClaudeUsageLimits { - /** Each limit refusing requests, by Claude's name for it, with its reset (ms) if it gave one. */ private readonly rejected = new Map() - private readonly shown = new BoundedMap({ maxEntries: 128 }) - /** The root turn's request was refused with `rate_limit`: its failed result may be the limit. */ - private turnRefused = false constructor(private readonly now: () => number = Date.now) {} @@ -63,46 +57,53 @@ export class ClaudeUsageLimits { } } - /** The limit's row in place of an API-error frame the limit refused; null for any other frame. */ - assistant(message: Record): ClaudeUsageLimitRow | null { - if (message.type !== 'assistant' || message.error !== 'rate_limit') { + assistant(message: Record, turn: ClaudeOpenTurn): ClaudeUsageLimitRow | null { + if (message.type !== 'assistant') { return null } - const named = - message.api_error === 'usage_limit_reached' - ? claudeRecord(claudeRecord(message.api_error_params)?.rate_limit_info) - : null - if (named) { - this.record(named) + 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)) } - if (message.parent_tool_use_id == null) { - this.turnRefused = true - } - const row = this.row(messageText(message)) - const key = row ? this.key(message) : null - if (key) { - this.shown.set(key, true) + 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 && (typed || (refused && decision === 'untyped'))) { + turn.usageLimitEvidence = { cause, row } } return row } - /** For a failed root result: the limit's row, or `shown` when its API-error frame already wrote - * it. Null for any other result, which keeps its own row. */ - result(message: Record, failed: boolean): ClaudeUsageLimitRow | 'shown' | null { - const refused = this.turnRefused - this.turnRefused = false - const key = this.key(message) - if (key !== null && this.shown.delete(key)) { - return failed ? 'shown' : null + 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 = - failed && - (refused || reason === 'blocking_limit') && - (status == null || status === 429) && - (reason === null || LIMIT_TERMINAL_REASONS.includes(reason)) - return limited ? this.row(claudeText(message.result) ?? '') : null + evidence?.cause === 'quota' || + ((evidence?.cause === 'untyped' || reason === 'blocking_limit') && + (status == null || status === 429) && + (reason === null || LIMIT_TERMINAL_REASONS.includes(reason))) + if (!limited) { + return null + } + const prior = evidence?.row + const text = claudeText(message.result) ?? '' + const detail = prior?.failure.detail?.text ?? '' + return ( + this.row(text.length > detail.length ? text : detail, evidence?.cause === 'quota') ?? + prior ?? null + ) } private record(info: Record | null): void { @@ -143,9 +144,9 @@ export class ClaudeUsageLimits { return { ...(window ? { window } : {}), ...(resetsAt ? { resetsAt } : {}) } } - private row(providerText: string): ClaudeUsageLimitRow | null { + private row(providerText: string, typed = false): ClaudeUsageLimitRow | null { const limit = this.limit() - if (!limit) { + if (!limit && !typed) { return null } return { @@ -153,18 +154,11 @@ export class ClaudeUsageLimits { tone: 'warning', ...agentSessionFailureWords( agentSessionFailureFact('usageLimitReached', { - ...(limit.window || limit.resetsAt ? { usageLimit: limit } : {}), + ...(limit && (limit.window || limit.resetsAt) ? { usageLimit: limit } : {}), detail: providerDiagnostic(providerText, 'person') }), { agentName: 'Claude', provider: 'claude', surface: 'row' } ) } } - - private key(message: Record): string | null { - const uuid = claudeText(message.user_message_uuid) - return uuid - ? JSON.stringify([message.session_id, message.parent_tool_use_id ?? null, uuid]) - : null - } } diff --git a/src/main/codex/codex-structured-journal-generic-frames.ts b/src/main/codex/codex-structured-journal-generic-frames.ts index e2139faf43d6..f9907dfd9edf 100644 --- a/src/main/codex/codex-structured-journal-generic-frames.ts +++ b/src/main/codex/codex-structured-journal-generic-frames.ts @@ -158,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 index f821e835acbe..818fbb2c6504 100644 --- a/src/main/codex/codex-usage-limits.test.ts +++ b/src/main/codex/codex-usage-limits.test.ts @@ -1,5 +1,6 @@ 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 @@ -62,4 +63,22 @@ describe('a Codex usage limit', () => { ]) 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 index 49f6dcbcb6ad..43356a27e15f 100644 --- a/src/main/codex/codex-usage-limits.ts +++ b/src/main/codex/codex-usage-limits.ts @@ -5,7 +5,6 @@ import { type AgentSessionUsageLimitWindow } from '../../shared/agent-session-usage-limit' import { - classifyCodexRateLimitWindows, type CodexRateLimitWindowsSnapshot } from '../rate-limits/codex-rate-limit-window-classification' import { @@ -17,7 +16,7 @@ import { const RATE_LIMITS_UPDATED = 'notification:account/rateLimits/updated' const USAGE_LIMIT_ERRORS = ['usageLimitExceeded', 'rateLimitExceeded'] -type CodexAccountRateLimits = CodexRateLimitWindowsSnapshot & { rateLimitReachedType?: unknown } +type CodexAccountRateLimits = CodexRateLimitWindowsSnapshot & { rateLimitReachedType?: unknown; planType?: unknown } function record(value: unknown): Record | null { return typeof value === 'object' && value !== null && !Array.isArray(value) ? { ...value } : null @@ -39,7 +38,7 @@ export class CodexUsageLimits { } 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 === undefined || update.limitId === 'codex')) { + if (update && (update.limitId == null || update.limitId === 'codex')) { // An update may carry only the fields that changed. this.snapshot = { ...this.snapshot, @@ -70,12 +69,18 @@ export class CodexUsageLimits { /** 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 windows = classifyCodexRateLimitWindows(this.snapshot) - const spent = (['session', 'weekly'] as const).flatMap((window) => { - const snapshot = windows[window] - return snapshot && snapshot.usedPercent >= 100 - ? [{ window, resetsAt: snapshot.resetsAt }] - : [] + 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') diff --git a/src/shared/native-chat-usage-limit-cut.ts b/src/shared/native-chat-usage-limit-cut.ts index b9c6e6b2a72d..0434f195383d 100644 --- a/src/shared/native-chat-usage-limit-cut.ts +++ b/src/shared/native-chat-usage-limit-cut.ts @@ -1,6 +1,7 @@ // A turn one of the agent's usage limits ended, as its row says, and whether the chat still sits on // it. Derived from the journal each time, never stored; the chat offers Continue from it. +import { isRootAgentJournalItem } from './agent-session-journal-producer' import { readAgentSessionFailureFact } from './agent-session-failure' import type { AgentJournalRenderItem, AgentJournalSubmission } from './agent-session-journal-types' import type { AgentSessionUsageLimit } from './agent-session-usage-limit' @@ -11,7 +12,7 @@ export const NATIVE_CHAT_USAGE_LIMIT_CONTINUE_MESSAGE = 'Continue where you left /** The limit a row reports, when it is a usage-limit row. */ function usageLimitOfRow(item: AgentJournalRenderItem): AgentSessionUsageLimit | null { - if (item.body.kind !== 'status') { + if (!isRootAgentJournalItem(item) || item.body.kind !== 'status') { return null } const fact = readAgentSessionFailureFact(item.body.failure) From 22af3337a337ae2b91299e2b9cd87eeda7cd7a5d Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Sun, 18 Oct 2026 14:20:34 -0700 Subject: [PATCH 06/34] fix(codex): keep snapshot import type-only --- src/main/codex/codex-usage-limits.ts | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/src/main/codex/codex-usage-limits.ts b/src/main/codex/codex-usage-limits.ts index 43356a27e15f..820ec2337833 100644 --- a/src/main/codex/codex-usage-limits.ts +++ b/src/main/codex/codex-usage-limits.ts @@ -4,9 +4,7 @@ import { type AgentSessionUsageLimit, type AgentSessionUsageLimitWindow } from '../../shared/agent-session-usage-limit' -import { - type CodexRateLimitWindowsSnapshot -} from '../rate-limits/codex-rate-limit-window-classification' +import type { CodexRateLimitWindowsSnapshot } from '../rate-limits/codex-rate-limit-window-classification' import { readCodexErrorAdditionalDetails, readCodexErrorInfo, From 31b4d34001bbd85431c33f8b0edf33c6b4fa8da4 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Sun, 18 Oct 2026 14:32:05 -0700 Subject: [PATCH 07/34] fix(claude): open refusal turns without opening empty placeholders --- src/main/claude/claude-message-journaling.ts | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/src/main/claude/claude-message-journaling.ts b/src/main/claude/claude-message-journaling.ts index 85124c62b435..96365a1f8f17 100644 --- a/src/main/claude/claude-message-journaling.ts +++ b/src/main/claude/claude-message-journaling.ts @@ -100,8 +100,10 @@ export function journalClaudeMessage( assistant: envelope.role === 'assistant' } const openOutputTurn = (): void => ctx.turn.ensureOpen(message, source, observedAt) - // The terminal fact belongs to the actual turn, including frames without a user stamp. - if (envelope.role === 'assistant') { + const messageBody = claudeMessageBody(outputEnvelope) + // A refusal needs its owning turn before the canonical write; empty placeholders open nothing. + if (envelope.role === 'assistant' && + (messageBody || typeof message.api_error === 'string' || message.error === 'rate_limit')) { openOutputTurn() } const usageLimit = ctx.usageLimits.assistant(message, ctx.turn) @@ -109,7 +111,7 @@ export function journalClaudeMessage( ctx.authenticationFailures.assistant(message) ?? usageLimit ?? ctx.threadGoal.report(message, claudeMessageIdentity(envelope), observedAt) ?? - claudeMessageBody(outputEnvelope) + messageBody const terminalIdentity = usageLimit && producerRef === null && ctx.turn.identity ? { provider: 'orca' as const, clientMessageId: `terminal-failure:claude:${agentJournalItemKey(ctx.turn.identity)}` } : null From a6fef63058ed8493bd4816e8f8403a74b0932583 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Sun, 18 Oct 2026 14:22:45 -0700 Subject: [PATCH 08/34] fix(native-chat): bind usage Continue to the latest idle failed turn --- ...structured-agent-session-host-mutations.ts | 43 +++++++--- ...ent-session-queued-action-receipts.test.ts | 78 ++++++++++++++++++- .../agent-session-write-notice-text.ts | 2 + .../src/i18n/en-runtime-required.json | 1 + src/renderer/src/i18n/locales/en.json | 1 + src/renderer/src/i18n/locales/es.json | 1 + src/renderer/src/i18n/locales/fr.json | 1 + src/renderer/src/i18n/locales/ja.json | 1 + src/renderer/src/i18n/locales/ko.json | 1 + src/renderer/src/i18n/locales/zh.json | 1 + .../agent-session-create-capabilities.ts | 4 + src/shared/agent-session-refusal-details.ts | 1 + .../agent-session-refusal-reason-words.ts | 1 + src/shared/agent-session-write-notice-copy.ts | 1 + .../structured-agent-session-params.ts | 2 + ...ctured-agent-session-send-mutation.spec.ts | 10 +++ .../structured-agent-session-send-mutation.ts | 6 +- 17 files changed, 144 insertions(+), 11 deletions(-) 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 4aae2cf0d08d..cb91c2661d09 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 { AGENT_CHAT_PERMISSION_MODE_OPTION_ID } from '../../../shared/agent-chat-permission-mode' import type { AgentJournalMessageItem } from '../../../shared/agent-session-journal-types' import type { @@ -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..108290a4716f 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,10 @@ // another command already used is refused. import { afterEach, beforeEach, describe, expect, it } from 'vitest' +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 +16,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 +554,74 @@ 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', text: 'Usage limit reached', failure: { kind: 'usageLimitReached' } + }, { 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() + expect(await rig.host.send(CALLER, params(turnItemId))).toMatchObject(superseded) + expect(journal.snapshot()).toEqual(before) + 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/agent-session-write-notice-text.ts b/src/renderer/src/components/native-chat/agent-session-write-notice-text.ts index 9478be67461e..7d053d69b685 100644 --- a/src/renderer/src/components/native-chat/agent-session-write-notice-text.ts +++ b/src/renderer/src/components/native-chat/agent-session-write-notice-text.ts @@ -46,6 +46,8 @@ const SENTENCES: Record string> = { translate('components.native-chat.writeNotice.outcomeUnknown', COPY.outcomeUnknown), sendOutcomeLost: () => translate('components.native-chat.writeNotice.sendOutcomeLost', COPY.sendOutcomeLost), + continuationSuperseded: () => + translate('components.native-chat.writeNotice.continuationSuperseded', COPY.continuationSuperseded), questionChanged: () => translate('components.native-chat.writeNotice.questionChanged', COPY.questionChanged), cancelNotSaved: () => diff --git a/src/renderer/src/i18n/en-runtime-required.json b/src/renderer/src/i18n/en-runtime-required.json index eb8c1a47a073..ef5e31b317bf 100644 --- a/src/renderer/src/i18n/en-runtime-required.json +++ b/src/renderer/src/i18n/en-runtime-required.json @@ -3131,6 +3131,7 @@ "outcomeUnknown": "Orca couldn't confirm what happened. Check the chat.", "ownerUnproven": "The previous agent in this chat may still be running.", "promptPending": "The agent is waiting for an answer to a question or approval.", + "continuationSuperseded": "This chat has moved on. Check the latest messages before continuing.", "questionChanged": "This question was already answered or has changed.", "queueTooLarge": "Too much text is waiting in the queue.", "quitTerminalAgent": "Quit that agent to continue the chat here.", diff --git a/src/renderer/src/i18n/locales/en.json b/src/renderer/src/i18n/locales/en.json index 216ae67550f6..afed1b818965 100644 --- a/src/renderer/src/i18n/locales/en.json +++ b/src/renderer/src/i18n/locales/en.json @@ -18410,6 +18410,7 @@ "capacity": "Orca on the computer running this chat has hit a request limit. Update Orca there, then try again.", "outcomeUnknown": "Orca couldn't confirm what happened. Check the chat.", "sendOutcomeLost": "Orca couldn't confirm your message reached the agent. Check the chat, then send it again if needed.", + "continuationSuperseded": "This chat has moved on. Check the latest messages before continuing.", "questionChanged": "This question was already answered or has changed.", "cancelNotSaved": "Couldn't cancel this question or approval.", "historyUnreadable": "Orca couldn't read this chat's saved history.", diff --git a/src/renderer/src/i18n/locales/es.json b/src/renderer/src/i18n/locales/es.json index 7c184a02a9dd..f35b8e8f43e5 100644 --- a/src/renderer/src/i18n/locales/es.json +++ b/src/renderer/src/i18n/locales/es.json @@ -18151,6 +18151,7 @@ "capacity": "Orca en el equipo que ejecuta este chat alcanzó un límite de solicitudes. Actualice Orca en ese equipo y vuelva a intentarlo.", "outcomeUnknown": "Orca no pudo confirmar qué pasó. Revise el chat.", "sendOutcomeLost": "Orca no pudo confirmar que su mensaje llegó al agente. Revise el chat y vuelva a enviarlo si es necesario.", + "continuationSuperseded": "This chat has moved on. Check the latest messages before continuing.", "questionChanged": "Esta pregunta ya se respondió o ha cambiado.", "cancelNotSaved": "No se pudo cancelar esta pregunta o aprobación.", "historyUnreadable": "Orca no pudo leer el historial guardado de este chat.", diff --git a/src/renderer/src/i18n/locales/fr.json b/src/renderer/src/i18n/locales/fr.json index 1b2bafc85c5f..abd6bc46ea96 100644 --- a/src/renderer/src/i18n/locales/fr.json +++ b/src/renderer/src/i18n/locales/fr.json @@ -18260,6 +18260,7 @@ "capacity": "Orca sur l'ordinateur qui exécute ce chat a atteint une limite de requêtes. Mettez à jour Orca sur cet ordinateur, puis réessayez.", "outcomeUnknown": "Orca n'a pas pu confirmer ce qui s'est passé. Vérifiez le chat.", "sendOutcomeLost": "Orca n'a pas pu confirmer que votre message est parvenu à l'agent. Vérifiez le chat, puis renvoyez-le si nécessaire.", + "continuationSuperseded": "This chat has moved on. Check the latest messages before continuing.", "questionChanged": "Cette question a déjà reçu une réponse ou a changé.", "cancelNotSaved": "Impossible d'annuler cette question ou cette approbation.", "historyUnreadable": "Orca n'a pas pu lire l'historique enregistré de ce chat.", diff --git a/src/renderer/src/i18n/locales/ja.json b/src/renderer/src/i18n/locales/ja.json index 23f51a3b622c..690be3a5b4b1 100644 --- a/src/renderer/src/i18n/locales/ja.json +++ b/src/renderer/src/i18n/locales/ja.json @@ -18191,6 +18191,7 @@ "capacity": "このチャットを実行しているコンピューターの Orca がリクエストの上限に達しました。そのコンピューターで Orca を更新してから、もう一度お試しください。", "outcomeUnknown": "Orca は何が起きたかを確認できませんでした。チャットを確認してください。", "sendOutcomeLost": "Orca はメッセージが Agent に届いたことを確認できませんでした。チャットを確認し、必要であればもう一度送信してください。", + "continuationSuperseded": "This chat has moved on. Check the latest messages before continuing.", "questionChanged": "この質問はすでに回答済みか、変更されています。", "cancelNotSaved": "この質問または承認をキャンセルできませんでした。", "historyUnreadable": "Orca はこのチャットの保存済み履歴を読み取れませんでした。", diff --git a/src/renderer/src/i18n/locales/ko.json b/src/renderer/src/i18n/locales/ko.json index cd4564d3fc30..85fbacd12b4c 100644 --- a/src/renderer/src/i18n/locales/ko.json +++ b/src/renderer/src/i18n/locales/ko.json @@ -18191,6 +18191,7 @@ "capacity": "이 채팅을 실행하는 컴퓨터의 Orca가 요청 한도에 도달했습니다. 해당 컴퓨터에서 Orca를 업데이트한 다음 다시 시도하세요.", "outcomeUnknown": "Orca가 무슨 일이 있었는지 확인하지 못했습니다. 채팅을 확인하세요.", "sendOutcomeLost": "Orca가 메시지가 에이전트에 전달되었는지 확인하지 못했습니다. 채팅을 확인하고 필요하면 다시 보내세요.", + "continuationSuperseded": "This chat has moved on. Check the latest messages before continuing.", "questionChanged": "이 질문은 이미 답변되었거나 변경되었습니다.", "cancelNotSaved": "이 질문 또는 승인을 취소하지 못했습니다.", "historyUnreadable": "Orca가 이 채팅의 저장된 기록을 읽지 못했습니다.", diff --git a/src/renderer/src/i18n/locales/zh.json b/src/renderer/src/i18n/locales/zh.json index c7f437098396..077b6b86140c 100644 --- a/src/renderer/src/i18n/locales/zh.json +++ b/src/renderer/src/i18n/locales/zh.json @@ -18156,6 +18156,7 @@ "capacity": "运行此聊天的计算机上的 Orca 已达到请求上限。请在那台计算机上更新 Orca,然后重试。", "outcomeUnknown": "Orca 无法确认发生了什么。请查看聊天。", "sendOutcomeLost": "Orca 无法确认你的消息已送达智能体。请查看聊天,如有需要请重新发送。", + "continuationSuperseded": "This chat has moved on. Check the latest messages before continuing.", "questionChanged": "此问题已被回答或已更改。", "cancelNotSaved": "无法取消此问题或审批。", "historyUnreadable": "Orca 无法读取此聊天的已保存历史记录。", diff --git a/src/shared/agent-session-create-capabilities.ts b/src/shared/agent-session-create-capabilities.ts index 3e5bccea7c74..6a146236e3ba 100644 --- a/src/shared/agent-session-create-capabilities.ts +++ b/src/shared/agent-session-create-capabilities.ts @@ -19,7 +19,11 @@ export const AGENT_SESSION_SEND_OPTIONS_RUNTIME_CAPABILITY = // older host refuses `accountEnv`. A client sends it only to a host advertising this. export const AGENT_SESSION_ACCOUNT_ENV_RUNTIME_CAPABILITY = 'agent-session.account-env.v1' as const +export const AGENT_SESSION_SEND_USAGE_LIMIT_CONTINUATION_RUNTIME_CAPABILITY = + 'agent-session.send-usage-limit-continuation.v1' as const + export const AGENT_SESSION_CREATE_RUNTIME_CAPABILITIES = [ + AGENT_SESSION_SEND_USAGE_LIMIT_CONTINUATION_RUNTIME_CAPABILITY, AGENT_SESSION_CREATE_TAB_ID_RUNTIME_CAPABILITY, AGENT_SESSION_CREATE_MESSAGE_RUNTIME_CAPABILITY, AGENT_SESSION_SEND_OPTIONS_RUNTIME_CAPABILITY, diff --git a/src/shared/agent-session-refusal-details.ts b/src/shared/agent-session-refusal-details.ts index 0f44e4f4785e..bd5bc9a4b018 100644 --- a/src/shared/agent-session-refusal-details.ts +++ b/src/shared/agent-session-refusal-details.ts @@ -48,6 +48,7 @@ export const AGENT_SESSION_REFUSAL_REASONS = { 'conversationCommandInFlight', 'handoffInFlight', 'turnActive', + 'continuationSuperseded', 'promptPending', 'backgroundTasksRunning', 'messagesUnsettled', diff --git a/src/shared/agent-session-refusal-reason-words.ts b/src/shared/agent-session-refusal-reason-words.ts index 6fd418277394..974417fd6304 100644 --- a/src/shared/agent-session-refusal-reason-words.ts +++ b/src/shared/agent-session-refusal-reason-words.ts @@ -90,6 +90,7 @@ const REASON_WORDS = { conversationCommandInFlight: causeWords('commandRunning', 'wait', 'waitForCommand'), // The chat's agent process is being replaced, which a start or restart does. handoffInFlight: AGENT_STARTING, + continuationSuperseded: causeWords('continuationSuperseded', 'nothingLeft'), turnActive: causeWords('turnActive', 'wait', 'waitForTurn'), promptPending: causeWords('promptPending', 'actFirst', 'answerFirst'), backgroundTasksRunning: causeWords('backgroundTasksRunning', 'wait', 'waitForBackgroundTasks'), diff --git a/src/shared/agent-session-write-notice-copy.ts b/src/shared/agent-session-write-notice-copy.ts index c270731bb9a0..cbd7f88f82af 100644 --- a/src/shared/agent-session-write-notice-copy.ts +++ b/src/shared/agent-session-write-notice-copy.ts @@ -36,6 +36,7 @@ export const AGENT_SESSION_WRITE_NOTICE_COPY = { outcomeUnknown: "Orca couldn't confirm what happened. Check the chat.", sendOutcomeLost: "Orca couldn't confirm your message reached the agent. Check the chat, then send it again if needed.", + continuationSuperseded: 'This chat has moved on. Check the latest messages before continuing.', questionChanged: 'This question was already answered or has changed.', cancelNotSaved: "Couldn't cancel this question or approval.", historyUnreadable: "Orca couldn't read this chat's saved history.", diff --git a/src/shared/rpc-contract/structured-agent-session-params.ts b/src/shared/rpc-contract/structured-agent-session-params.ts index da29e7ab640c..8663f0f84e61 100644 --- a/src/shared/rpc-contract/structured-agent-session-params.ts +++ b/src/shared/rpc-contract/structured-agent-session-params.ts @@ -147,6 +147,8 @@ export const SendParams = z /** The composer's model and effort for the turn this send starts; the host records them on the * chat. Sent only when `agent-session.send-options.v1` is advertised. Operation fingerprint only. */ options: AgentSessionOptions.optional(), + // Strict payload: only hosts advertising the bound usage-limit send capability accept this. + usageLimitContinuationOfTurnItemId: Identifier('Invalid source turn item id').optional(), body: SendBody }) .strict() diff --git a/src/shared/structured-agent-session-send-mutation.spec.ts b/src/shared/structured-agent-session-send-mutation.spec.ts index 031cfc773f34..abb2759e4fc3 100644 --- a/src/shared/structured-agent-session-send-mutation.spec.ts +++ b/src/shared/structured-agent-session-send-mutation.spec.ts @@ -89,6 +89,16 @@ describe('send fingerprints never cover the sender', () => { expect(SendParams.safeParse({ ...carried, body: BODY }).success).toBe(true) }) + it('binds source controls only into the operation hash while preserving the legacy payload', () => { + const input = { sessionId: 'session-1', clientOperationId: 'op-1', expectedRuntimeFence: 1, body: BODY } + const legacy = structuredAgentSessionMessageSendMutation(input) + const bound = structuredAgentSessionMessageSendMutation({ ...input, usageLimitContinuationOfTurnItemId: 'turn-1' }) + expect(legacy).not.toHaveProperty('usageLimitContinuationOfTurnItemId') + expect(legacy.envelope.payloadFingerprint).not.toBe(bound.envelope.payloadFingerprint) + expect(agentSessionSendBodyFingerprint('session-1', bound.body)).toBe(legacy.envelope.payloadFingerprint) + expect(SendParams.safeParse(bound).success).toBe(true) + }) + it('refuses a client send whose body names a sender', () => { const params = (body: unknown) => ({ envelope: { diff --git a/src/shared/structured-agent-session-send-mutation.ts b/src/shared/structured-agent-session-send-mutation.ts index 73dd8ca8270e..d64f56838749 100644 --- a/src/shared/structured-agent-session-send-mutation.ts +++ b/src/shared/structured-agent-session-send-mutation.ts @@ -8,6 +8,7 @@ import { structuredAgentSessionPayloadFingerprint } from './structured-agent-ses export type StructuredAgentSessionSendControl = { delivery?: 'queue-if-active' options?: Readonly> + usageLimitContinuationOfTurnItemId?: string } export type StructuredAgentSessionSendMutation = StructuredAgentSessionSendControl & { @@ -21,7 +22,10 @@ export function agentSessionSendControlFields( ): StructuredAgentSessionSendControl { return { ...(send.delivery ? { delivery: send.delivery } : {}), - ...(send.options ? { options: send.options } : {}) + ...(send.options ? { options: send.options } : {}), + ...(send.usageLimitContinuationOfTurnItemId + ? { usageLimitContinuationOfTurnItemId: send.usageLimitContinuationOfTurnItemId } + : {}) } } From 9ec8a6b88b86b07124d6b82e95e6918e8fbe9d63 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Sun, 18 Oct 2026 14:36:49 -0700 Subject: [PATCH 09/34] test(native-chat): isolate stale Continue from ordinary delivery progress --- ...structured-agent-session-queued-action-receipts.test.ts | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) 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 108290a4716f..f5de7d6d4b30 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 @@ -603,9 +603,12 @@ describe('source-bound ordinary Continue', () => { 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() + 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()).toEqual(before) + 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) From b9fd04f54112675eb7e2b8563b300b4909672725 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Sun, 18 Oct 2026 14:48:23 -0700 Subject: [PATCH 10/34] test(native-chat): use a braced journal assertion --- .../structured-agent-session-queued-action-receipts.test.ts | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) 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 f5de7d6d4b30..2b92e3e388b4 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 @@ -559,7 +559,9 @@ describe('an id reused across commands', () => { 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') + 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, { From d94f5af00c803ab9adc0576e95ed740ef739dadc Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Sun, 18 Oct 2026 14:52:50 -0700 Subject: [PATCH 11/34] test(native-chat): build failure rows through their word factory --- .../structured-agent-session-queued-action-receipts.test.ts | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) 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 2b92e3e388b4..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,7 @@ // 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' @@ -569,7 +570,8 @@ describe('source-bound ordinary Continue', () => { startedAt: NOW, completedAt: NOW }, { fence: 1, turnScope: { kind: 'thread' } }) await journal.appendItem({ provider: 'orca', clientMessageId: `failure-${id}` }, { - kind: 'status', text: 'Usage limit reached', failure: { kind: 'usageLimitReached' } + kind: 'status', + ...agentSessionFailureWords({ kind: 'usageLimitReached' }, { surface: 'row' }) }, { fence: 1, turnScope: { kind: 'turn', turnItemId } }) return { journal, turnItemId } } From b3a760d49d54de69eaf0be02cc669b1719e88c85 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Sun, 18 Oct 2026 15:00:13 -0700 Subject: [PATCH 12/34] fix(claude): retain terminal failure evidence through result reconciliation --- src/main/claude/claude-usage-limits.test.ts | 8 ++++++-- src/main/claude/claude-usage-limits.ts | 16 ++++++++++------ 2 files changed, 16 insertions(+), 8 deletions(-) diff --git a/src/main/claude/claude-usage-limits.test.ts b/src/main/claude/claude-usage-limits.test.ts index 30edbb4ba3d1..84c95aa89793 100644 --- a/src/main/claude/claude-usage-limits.test.ts +++ b/src/main/claude/claude-usage-limits.test.ts @@ -62,7 +62,7 @@ describe('a Claude usage limit', () => { const t = setup() t.handle(userFrame('turn-a', 1_000)) t.handle(rateLimitEvent('rejected', 1_100)) - t.handle(assistantFrame('first', 1_150, 20)) + t.handle(frame({ ...assistantFrame('first', 1_150, 20).message, user_message_uuid: 'ask-a' }, 1_150)) t.handle(frame({ ...refusedFrame('a', 1_200, LIMIT_TEXT).message, user_message_uuid: undefined, @@ -84,7 +84,11 @@ describe('a Claude usage limit', () => { detail: { text: LIMIT_TEXT, audience: 'person' } } } - expect(statusRows(t)).toEqual([limitRow, limitRow]) + 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() }) diff --git a/src/main/claude/claude-usage-limits.ts b/src/main/claude/claude-usage-limits.ts index 8f62621260c0..e3183e07bc06 100644 --- a/src/main/claude/claude-usage-limits.ts +++ b/src/main/claude/claude-usage-limits.ts @@ -98,11 +98,11 @@ export class ClaudeUsageLimits { return null } const prior = evidence?.row - const text = claudeText(message.result) ?? '' - const detail = prior?.failure.detail?.text ?? '' + const details = [prior?.failure.detail?.text, claudeText(message.result)] + .filter((value): value is string => Boolean(value)) return ( - this.row(text.length > detail.length ? text : detail, evidence?.cause === 'quota') ?? - prior ?? null + this.row([...new Set(details)].join('\n'), evidence?.cause === 'quota' || prior != null, + prior?.failure.usageLimit) ?? prior ?? null ) } @@ -144,8 +144,12 @@ export class ClaudeUsageLimits { return { ...(window ? { window } : {}), ...(resetsAt ? { resetsAt } : {}) } } - private row(providerText: string, typed = false): ClaudeUsageLimitRow | null { - const limit = this.limit() + private row( + providerText: string, + typed = false, + previousLimit?: AgentSessionUsageLimit + ): ClaudeUsageLimitRow | null { + const limit = this.limit() ?? previousLimit ?? null if (!limit && !typed) { return null } From 1262d01b6d91637d3ff77da28a5d1c83353528ac Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Sun, 18 Oct 2026 14:30:10 -0700 Subject: [PATCH 13/34] fix(native-chat): complete usage Continue through the composer sender --- .../NativeChatInterruptedContinue.test.tsx | 103 +++++++++++++++++- .../NativeChatInterruptedContinue.tsx | 92 ++++++++++++++-- .../native-chat/NativeChatNoticeRow.test.tsx | 7 ++ .../native-chat/NativeChatNoticeRow.tsx | 6 +- .../NativeChatStructuredSession.tsx | 6 +- .../NativeChatTranscriptChrome.tsx | 18 ++- .../native-chat/native-chat-composer-types.ts | 4 +- .../native-chat-orca-stop-context.ts | 1 + .../native-chat-structured-user-action.ts | 17 +++ ...tured-agent-session-message-sender.test.ts | 6 +- .../structured-agent-session-pending-sends.ts | 1 + .../structured-agent-session-send-attempt.ts | 5 +- .../structured-agent-session-send-slot.ts | 9 ++ ...se-native-chat-structured-composer-send.ts | 15 +-- ...tive-chat-structured-composer-transport.ts | 5 +- .../use-structured-agent-session-sends.ts | 11 +- .../src/i18n/en-runtime-required.json | 3 + src/renderer/src/i18n/locales/en.json | 1 + src/renderer/src/i18n/locales/es.json | 1 + src/renderer/src/i18n/locales/fr.json | 1 + src/renderer/src/i18n/locales/ja.json | 1 + src/renderer/src/i18n/locales/ko.json | 1 + src/renderer/src/i18n/locales/zh.json | 1 + 23 files changed, 270 insertions(+), 45 deletions(-) create mode 100644 src/renderer/src/components/native-chat/native-chat-structured-user-action.ts diff --git a/src/renderer/src/components/native-chat/NativeChatInterruptedContinue.test.tsx b/src/renderer/src/components/native-chat/NativeChatInterruptedContinue.test.tsx index 28a0dd42ac9a..e4b76adbc03a 100644 --- a/src/renderer/src/components/native-chat/NativeChatInterruptedContinue.test.tsx +++ b/src/renderer/src/components/native-chat/NativeChatInterruptedContinue.test.tsx @@ -1,6 +1,6 @@ // @vitest-environment happy-dom import '@testing-library/jest-dom/vitest' -import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react' +import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react' import { useState } from 'react' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' @@ -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,6 +39,12 @@ 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 { 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 { agentJournalItemKey } from '../../../../shared/agent-session-journal-item-key' import type { @@ -72,6 +83,8 @@ type Props = { submissions?: readonly Pick[] isWorking?: boolean target?: RuntimeClientTarget + transport?: NativeChatStructuredComposerTransport + pending?: readonly { phase: 'sending' | 'recorded' }[] } function Harness(props: Props): React.JSX.Element { @@ -80,11 +93,13 @@ function Harness(props: Props): React.JSX.Element { const continuation = useNativeChatInterruptedContinuation({ reportComposerError: setComposerError, target: props.target ?? PAIRED, + agent: 'codex', sessionId: 'session-1', journalItems: props.journalItems ?? cutChat, submissions: props.submissions ?? [], isWorking: props.isWorking ?? false, - send: () => true + pending: props.pending ?? [], + transport: props.transport ?? { send: () => true, dispatchCommand: async () => ({ handled: false, accepted: false, error: null }), optionSnapshot: [], onError: () => {}, runtime: 'remote', sessionId: 'session-1', runtimeEnvironmentId: 'studio-mac' } }) return ( @@ -95,6 +110,10 @@ function Harness(props: Props): React.JSX.Element { + {continuation.view.usageLimitTurnItemId === null ? null : ( + + )} {/* As the cut's own row shows it. */} {continuation.view.offeredTurnItemId === null ? null : ( @@ -115,7 +134,11 @@ beforeEach(() => { mocks.call.mockReset() }) -afterEach(cleanup) +afterEach(() => { + cleanup() + resetStructuredAgentSessionSendsForTests() + clearNativeChatComposerDraftsForTests() +}) describe('Continue on a reply an Orca stop cut off', () => { it("asks the chat's own host, paired or local, to continue that cut turn", () => { @@ -275,3 +298,77 @@ describe('Continue on a reply an Orca stop cut off', () => { expect(screen.getByTestId('error')).toHaveTextContent('none') }) }) + + +it('keeps the draft through Continue admission, refusal, uncertainty and recorded-before-journal', async () => { + const items: AgentJournalRenderItem[] = [ + { ...cutChat[0]!, body: { kind: 'turn', turnId: 'cut', state: 'completed', outcome: 'failure', startedAt: 1, completedAt: 5 } }, + { ...cutChat[1]!, body: { kind: 'status', text: 'Limit', failure: { kind: 'usageLimitReached' } } } + ] + const scope = structuredAgentSessionDraftScopeKey('session-1') + const draft = { text: 'My unfinished request', images: [{ id: 'attached', path: '/tmp/photo.png' }] } + updateNativeChatComposerDraft(scope, draft, 'immediate') + const options = { model: 'gpt-current', effort: 'high' } + const uploading = { id: 'upload', path: '', pending: true, pendingName: 'next.png' } + const reveal = vi.fn() + function LiveHarness() { + const sends = useStructuredAgentSessionSends({ + sessionId: 'session-1', target: PAIRED, fence: 1, submissions: [], queuedMessageIds: [], + queue: { capability: 'unsupported', enabled: false }, historyLoaded: false, sendOptions: () => options + }) + const transport: NativeChatStructuredComposerTransport = { + send: (text, images, request) => sends.send(text, images.map((image) => ({ path: image.path, previewUri: image.path })), request), + onSubmitted: reveal, onError: vi.fn(), dispatchCommand: async () => ({ handled: false, accepted: false, error: null }), + optionSnapshot: [], runtime: 'remote', sessionId: 'session-1', runtimeEnvironmentId: 'studio-mac' + } + return <>{uploading.pendingName} + } + let answer = Promise.withResolvers() + mocks.call.mockImplementation(() => answer.promise) + const { rerender } = render() + mocks.capability = 'unknown' + rerender() + expect(continueButton()).toBeDisabled() + mocks.capability = 'supported' + rerender() + fireEvent.click(screen.getByRole('button', { name: 'compose' })) + fireEvent.click(continueButton()!) + expect(screen.getByTestId('error')).toHaveTextContent('none') + expect(continueButton()).toBeNull() + await waitFor(() => expect(mocks.call).toHaveBeenCalledOnce()) + expect(mocks.call.mock.calls[0]).toMatchObject([PAIRED, 'agentSession.send', { + body: { kind: 'message', role: 'user', blocks: [{ type: 'text', text: 'Continue where you left off.' }] }, + options, usageLimitContinuationOfTurnItemId: TURN + }]) + expect(reveal).toHaveBeenCalledOnce() + expect(reportStructuredSessionUserInput).toHaveBeenCalledWith('session-1', 'studio-mac') + expect(emitNativeChatMessageSent).toHaveBeenCalledWith({ agent: 'codex', runtime: 'remote' }) + await act(async () => answer.resolve({ ok: false, refusal: { code: 'agent_session_operation_invalid', details: { reason: 'providerRejected' }, message: 'Refused' } })) + await waitFor(() => expect(continueButton()).toBeInTheDocument()) + expect(screen.getByTestId('error')).toHaveTextContent(FAILED) + expect(readNativeChatComposerDraft(scope)).toMatchObject(draft) + // An old host gets the exact plain-send control shape, including after an uncertain attempt. + mocks.capability = 'unsupported' + answer = Promise.withResolvers() + rerender() + fireEvent.click(continueButton()!) + await waitFor(() => expect(mocks.call).toHaveBeenCalledTimes(2)) + expect(mocks.call.mock.calls[1][2]).not.toHaveProperty('usageLimitContinuationOfTurnItemId') + await act(async () => answer.reject(new Error('connection lost'))) + await waitFor(() => expect(screen.getByTestId('error')).toHaveTextContent('Check the chat before trying again.')) + expect(screen.getByTestId('error')).not.toHaveTextContent('was not sent') + expect(readNativeChatComposerDraft(scope)).toMatchObject(draft) + mocks.capability = 'supported' + answer = Promise.withResolvers() + rerender() + fireEvent.click(continueButton()!) + await waitFor(() => expect(mocks.call).toHaveBeenCalledTimes(3)) + const id = mocks.call.mock.calls[2][2].envelope.clientOperationId + await act(async () => answer.resolve({ ok: true, fence: 1, cursor: { epoch: 'e', sequence: 5 }, + value: { clientMessageId: id, submission: { clientMessageId: id, dispatchState: 'accepted' } } })) + // Accepted before the journal arrives: the recorded sender entry still owns availability. + expect(continueButton()).toBeNull() + expect(readNativeChatComposerDraft(scope)).toMatchObject(draft) + expect(screen.getByText('next.png')).toBeInTheDocument() + expect(options).toEqual({ model: 'gpt-current', effort: 'high' }) +}) diff --git a/src/renderer/src/components/native-chat/NativeChatInterruptedContinue.tsx b/src/renderer/src/components/native-chat/NativeChatInterruptedContinue.tsx index 78298ec4f673..a259046044ad 100644 --- a/src/renderer/src/components/native-chat/NativeChatInterruptedContinue.tsx +++ b/src/renderer/src/components/native-chat/NativeChatInterruptedContinue.tsx @@ -1,8 +1,13 @@ -import { useCallback, useId, useMemo, useState } from 'react' +import { useCallback, useEffect, useId, useMemo, useState } from 'react' import { Play } from 'lucide-react' import { Button } from '@/components/ui/button' import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip' import { translate } from '@/i18n/i18n' +import { structuredAgentLabel } from '@/lib/structured-agent-session-launch-label' +import type { AgentType } from '../../../../shared/agent-status-types' +import { AGENT_SESSION_SEND_USAGE_LIMIT_CONTINUATION_RUNTIME_CAPABILITY } from '../../../../shared/agent-session-create-capabilities' +import { completeNativeChatStructuredUserAction } from './native-chat-structured-user-action' +import { getStructuredAgentSessionPendingSends, type StructuredAgentSessionPendingSend } from './structured-agent-session-pending-sends' import { callStructuredAgentSession } from '@/runtime/structured-agent-session-client' import { useStructuredAgentSessionHostCapabilityState } from '@/runtime/structured-agent-session-host-capability' import type { RuntimeClientTarget } from '../../../../shared/runtime-client-target' @@ -41,6 +46,7 @@ export type NativeChatInterruptedContinuation = { */ export function useNativeChatInterruptedContinuation(input: { target: RuntimeClientTarget + agent: AgentType sessionId: string journalItems: readonly AgentJournalRenderItem[] submissions: readonly Pick[] @@ -49,14 +55,19 @@ export function useNativeChatInterruptedContinuation(input: { /** Stable; a Continue click is the user's newer action, so it clears the composer's error. */ reportComposerError: (text: null) => void /** The composer's send; false when the chat took nothing. */ - send: NativeChatStructuredComposerTransport['send'] + transport: NativeChatStructuredComposerTransport + pending: readonly Pick[] }): NativeChatInterruptedContinuation { - const { target, sessionId, reportComposerError, send } = input + const { target, sessionId, reportComposerError, transport, agent } = input const hostLabel = useStructuredAgentSessionHostLabel(target) const capability = useStructuredAgentSessionHostCapabilityState( target, AGENT_SESSION_CONTINUE_INTERRUPTED_RUNTIME_CAPABILITY ) + const usageCapability = useStructuredAgentSessionHostCapabilityState( + target, + AGENT_SESSION_SEND_USAGE_LIMIT_CONTINUATION_RUNTIME_CAPABILITY + ) // The restart prompt or the launch's own resume is carrying this chat on, or the launch may still // decide to; it resumes only this machine's chats. const launchPending = useNativeChatLaunchResumePending() && target.kind === 'local' @@ -72,25 +83,55 @@ export function useNativeChatInterruptedContinuation(input: { ) // The cut this client already asked to continue: hidden until the journal shows what came of it. const [asked, setAsked] = useState(null) + const [usageFailure, setUsageFailure] = useState<{ + turnItemId: string + unconfirmed: boolean + } | null>(null) const [failedOn, setFailedOn] = useState(null) + useEffect(() => { + if (input.pending.length > 0) { + setUsageFailure(null) + } + }, [input.pending]) const offered = capability === 'supported' && cut && !input.isWorking && !resuming && asked !== cut.turnItemId ? cut.turnItemId : null const usageLimitTurnItemId = - usageLimitCut && !input.isWorking && !resuming && asked !== usageLimitCut.turnItemId + usageLimitCut && + !input.isWorking && + !resuming && + input.pending.length === 0 && + !transport.sendOut && + transport.sendBlockedReason === undefined ? usageLimitCut.turnItemId : null const continueUsageLimit = useCallback((): void => { - if (usageLimitTurnItemId === null) { + if ( + usageLimitTurnItemId === null || + usageCapability === 'unknown' || + getStructuredAgentSessionPendingSends(sessionId).length > 0 + ) { return } - setAsked(usageLimitTurnItemId) - // A send the chat refused says why in the composer, as any send does; Continue comes back. - if (send(NATIVE_CHAT_USAGE_LIMIT_CONTINUE_MESSAGE, []) === false) { - setAsked(null) + const turnItemId = usageLimitTurnItemId + setUsageFailure(null) + reportComposerError(null) + const admission = transport.send(NATIVE_CHAT_USAGE_LIMIT_CONTINUE_MESSAGE, [], { + callerKeepsText: true, + ...(usageCapability === 'supported' ? { usageLimitContinuationOfTurnItemId: turnItemId } : {}), + onSettled: (outcome) => { + if (outcome === 'returned' || outcome === 'unconfirmed') { + setUsageFailure({ turnItemId, unconfirmed: outcome === 'unconfirmed' }) + } + } + }) + if (admission === false) { + setUsageFailure({ turnItemId, unconfirmed: false }) + } else { + completeNativeChatStructuredUserAction(agent, transport, admission === true) } - }, [usageLimitTurnItemId, send]) + }, [usageLimitTurnItemId, usageCapability, sessionId, reportComposerError, transport, agent]) const continueNow = useCallback((): void => { if (offered === null) { return @@ -121,6 +162,7 @@ export function useNativeChatInterruptedContinuation(input: { offeredTurnItemId: offered, continueNow, usageLimitTurnItemId, + usageLimitContinueDisabled: usageCapability === 'unknown', continueUsageLimit }), [ @@ -130,6 +172,7 @@ export function useNativeChatInterruptedContinuation(input: { offered, continueNow, usageLimitTurnItemId, + usageCapability, continueUsageLimit ] ) @@ -140,18 +183,37 @@ export function useNativeChatInterruptedContinuation(input: { "Couldn't continue this chat. Try again, or send a message." ) : null + const usageFailedHere = + usageFailure?.turnItemId === usageLimitCut?.turnItemId && usageFailure + ? usageFailure.unconfirmed + ? translate( + 'components.native-chat.interruptedContinue.unconfirmed', + "Couldn't confirm whether {{agent}} received Continue. Check the chat before trying again.", + { agent: structuredAgentLabel(agent) } + ) + : translate( + 'components.native-chat.interruptedContinue.failed', + "Couldn't continue this chat. Try again, or send a message." + ) + : null return { view, - continueError: failedHere ? { text: failedHere, onDismiss: () => setFailedOn(null) } : null + continueError: usageFailedHere + ? { text: usageFailedHere, onDismiss: () => setUsageFailure(null) } + : failedHere + ? { text: failedHere, onDismiss: () => setFailedOn(null) } + : null } } /** Continue, on the row that says Orca stopped this reply: the one action that picks it back up. */ export function NativeChatInterruptedContinueButton({ onContinue, + disabled, explanation: shownExplanation }: { onContinue: () => void + disabled?: boolean /** What Continue does here, when it is not picking up a reply Orca's stop cut off. */ explanation?: string }): React.JSX.Element { @@ -166,7 +228,13 @@ export function NativeChatInterruptedContinueButton({ <> - diff --git a/src/renderer/src/components/native-chat/NativeChatNoticeRow.test.tsx b/src/renderer/src/components/native-chat/NativeChatNoticeRow.test.tsx index fbdd21f5e08b..c88a4ef85b26 100644 --- a/src/renderer/src/components/native-chat/NativeChatNoticeRow.test.tsx +++ b/src/renderer/src/components/native-chat/NativeChatNoticeRow.test.tsx @@ -457,6 +457,13 @@ describe('notice rows', () => { expect(disclosure?.querySelector('summary')).not.toHaveTextContent('Check the configuration') expect(disclosure?.querySelector('pre')).toHaveTextContent('Check the configuration') }) + it('retains person-facing usage details without inventing a provider frame', () => { + renderStatus({ kind: 'status', text: 'Usage limit reached', tone: 'warning', + failure: { kind: 'usageLimitReached', detail: { audience: 'person', text: 'Your allowance resets tomorrow.' } } }) + const disclosure = screen.getByText('Details').closest('details') + expect(disclosure?.querySelector('pre')).toHaveTextContent('Your allowance resets tomorrow.') + expect(screen.queryByText('codex')).not.toBeInTheDocument() + }) it('keeps the column layout of command output in monospace', () => { const text = 'Context Usage\n⛁ ⛁ ⛶ gpt-4o · 16.6k/128k tokens (13%)\n ⛁ Skills: 304 tokens' diff --git a/src/renderer/src/components/native-chat/NativeChatNoticeRow.tsx b/src/renderer/src/components/native-chat/NativeChatNoticeRow.tsx index 7f47ccf6f03e..a0a9259ee479 100644 --- a/src/renderer/src/components/native-chat/NativeChatNoticeRow.tsx +++ b/src/renderer/src/components/native-chat/NativeChatNoticeRow.tsx @@ -165,6 +165,8 @@ export function NativeChatNoticeRow({ sayAgentSessionFailureTranslated ) : block.text + const detail = failure?.detail?.audience === 'person' && failure.detail.text.trim() !== text.trim() + ? failure.detail.text : undefined const tone = named ? 'notice' : look.kind === 'line' ? look.tone : null const Icon = tone === 'warning' @@ -192,6 +194,7 @@ export function NativeChatNoticeRow({ ) : usageLimitContinue ? ( ) : null} - {block.providerFrame ? ( + {block.providerFrame || detail ? ( ) : null} diff --git a/src/renderer/src/components/native-chat/NativeChatStructuredSession.tsx b/src/renderer/src/components/native-chat/NativeChatStructuredSession.tsx index 415c8851b73c..f22dc93bc079 100644 --- a/src/renderer/src/components/native-chat/NativeChatStructuredSession.tsx +++ b/src/renderer/src/components/native-chat/NativeChatStructuredSession.tsx @@ -227,13 +227,13 @@ export function NativeChatStructuredSession( sendBlockedReason: hostPermission.sendBlockedReason ?? install.sendBlockedReason }) const continuation = useNativeChatInterruptedContinuation({ + ...controller, target: props.target, + agent: props.agent, sessionId: props.sessionId, - journalItems: controller.journalItems, - submissions: controller.submissions, isWorking: controller.isWorking || hostHeld, reportComposerError, - send: structuredTransport.send + transport: structuredTransport }) // Said once: on the pane when the failure took it, else in the composer's notices. diff --git a/src/renderer/src/components/native-chat/NativeChatTranscriptChrome.tsx b/src/renderer/src/components/native-chat/NativeChatTranscriptChrome.tsx index d9c273e8c2c6..0f10aa3d745e 100644 --- a/src/renderer/src/components/native-chat/NativeChatTranscriptChrome.tsx +++ b/src/renderer/src/components/native-chat/NativeChatTranscriptChrome.tsx @@ -310,12 +310,14 @@ export function NativeChatAgentControls({ export function ProviderFrameRow({ block, - summary + summary, + detail }: { block: NativeChatBlock summary?: string + detail?: string }): React.JSX.Element | null { - if (block.type !== 'text' || !block.providerFrame) { + if (block.type !== 'text' || (!block.providerFrame && !detail)) { return null } const frame = block.providerFrame @@ -325,9 +327,11 @@ export function ProviderFrameRow({ › - {frame.provider} + {frame ? ( + {frame.provider} + ) : null} {summary ?? nativeChatProviderFrameSummary(block)} - {frame.payload.truncated ? ( + {frame?.payload.truncated ? ( ·{' '} {translate('components.native-chat.providerFrame.byteLength', '{{value0}} bytes', { @@ -340,8 +344,10 @@ export function ProviderFrameRow({ data-native-chat-code-content className="scrollbar-sleek mt-1 max-h-64 overflow-auto whitespace-pre-wrap rounded-md border border-border bg-muted p-2 font-mono text-chat-code text-foreground" > - {frame.payload.head} - {frame.payload.truncated ? '\n…' : ''} + {detail} + {detail && frame ? '\n\n' : ''} + {frame?.payload.head} + {frame?.payload.truncated ? '\n…' : ''} ) diff --git a/src/renderer/src/components/native-chat/native-chat-composer-types.ts b/src/renderer/src/components/native-chat/native-chat-composer-types.ts index fcbcb2c59bf3..a4be879cfcf1 100644 --- a/src/renderer/src/components/native-chat/native-chat-composer-types.ts +++ b/src/renderer/src/components/native-chat/native-chat-composer-types.ts @@ -1,3 +1,4 @@ +import type { StructuredAgentSessionSendRequest } from './structured-agent-session-send-slot' import type { NativeChatComposerNotice } from './native-chat-composer-notice' import type { AgentSessionConversationCommand } from '../../../../shared/agent-session-conversation-command' import type { StructuredAgentContextUsage } from '../../../../shared/structured-agent-session-context-usage' @@ -35,7 +36,8 @@ export type NativeChatStructuredComposerTransport = { conversationCommands?: readonly AgentSessionConversationCommand[] send: ( text: string, - attachments: readonly NativeChatComposerImageAttachment[] + attachments: readonly NativeChatComposerImageAttachment[], + request?: StructuredAgentSessionSendRequest ) => boolean | 'queued' /** A send is out: Send stays disabled, and a send returns false, until it settles. */ sendOut?: boolean diff --git a/src/renderer/src/components/native-chat/native-chat-orca-stop-context.ts b/src/renderer/src/components/native-chat/native-chat-orca-stop-context.ts index 8475da06ee76..5104738666bc 100644 --- a/src/renderer/src/components/native-chat/native-chat-orca-stop-context.ts +++ b/src/renderer/src/components/native-chat/native-chat-orca-stop-context.ts @@ -13,6 +13,7 @@ export type NativeChatOrcaStopView = { continueNow: () => void /** The turn a usage limit ended whose row carries Continue right now, if any. */ usageLimitTurnItemId: string | null + usageLimitContinueDisabled?: boolean continueUsageLimit: () => void } diff --git a/src/renderer/src/components/native-chat/native-chat-structured-user-action.ts b/src/renderer/src/components/native-chat/native-chat-structured-user-action.ts new file mode 100644 index 000000000000..24fc24c97498 --- /dev/null +++ b/src/renderer/src/components/native-chat/native-chat-structured-user-action.ts @@ -0,0 +1,17 @@ +import { emitNativeChatMessageSent } from '@/lib/native-chat-telemetry' +import { reportStructuredSessionUserInput } from '@/lib/worker-terminal-takeover-report' +import type { AgentType } from '../../../../shared/agent-status-types' +import type { NativeChatStructuredComposerTransport } from './native-chat-composer-types' + +// User admission owns takeover and reveal; draft consumption belongs only to draft submission. +export function completeNativeChatStructuredUserAction( + agent: AgentType, + transport: NativeChatStructuredComposerTransport, + revealsTranscript: boolean +): void { + emitNativeChatMessageSent({ agent, runtime: transport.runtime }) + if (revealsTranscript) { + transport.onSubmitted?.() + } + reportStructuredSessionUserInput(transport.sessionId, transport.runtimeEnvironmentId) +} diff --git a/src/renderer/src/components/native-chat/structured-agent-session-message-sender.test.ts b/src/renderer/src/components/native-chat/structured-agent-session-message-sender.test.ts index 10895d689683..80b4fdae65c6 100644 --- a/src/renderer/src/components/native-chat/structured-agent-session-message-sender.test.ts +++ b/src/renderer/src/components/native-chat/structured-agent-session-message-sender.test.ts @@ -137,16 +137,18 @@ describe('structured agent session message sender', () => { it('carries the options read at the send on its request, and nothing without them', async () => { const calls = deferredCalls() - const a = send('a', { options: { model: 'opus', effort: 'high' } }) + const a = send('a', { options: { model: 'opus', effort: 'high' }, + usageLimitContinuationOfTurnItemId: 'limited-turn', callerKeepsText: true }) await flush() expect(mocks.call.mock.calls[0][2]).toMatchObject({ - options: { model: 'opus', effort: 'high' } + options: { model: 'opus', effort: 'high' }, usageLimitContinuationOfTurnItemId: 'limited-turn' }) calls[0].resolve(okSubmission(a.clientMessageId, 'accepted')) await a.outcome send('b') await flush() expect(mocks.call.mock.calls[1][2]).not.toHaveProperty('options') + expect(mocks.call.mock.calls[1][2]).not.toHaveProperty('usageLimitContinuationOfTurnItemId') }) it.each([ diff --git a/src/renderer/src/components/native-chat/structured-agent-session-pending-sends.ts b/src/renderer/src/components/native-chat/structured-agent-session-pending-sends.ts index a96c533f8b30..7a31a69ec61b 100644 --- a/src/renderer/src/components/native-chat/structured-agent-session-pending-sends.ts +++ b/src/renderer/src/components/native-chat/structured-agent-session-pending-sends.ts @@ -12,6 +12,7 @@ export type StructuredAgentSessionPendingSend = { queuedAt: number delivery?: 'queue-if-active' options?: Readonly> + usageLimitContinuationOfTurnItemId?: string /** * `sending`: on its way, its one request out or about to be; the chat takes no other send meanwhile. * `recorded`: the host holds it; an open chat draws it until the host's row or card arrives. diff --git a/src/renderer/src/components/native-chat/structured-agent-session-send-attempt.ts b/src/renderer/src/components/native-chat/structured-agent-session-send-attempt.ts index c24a900bfe37..b791c6857764 100644 --- a/src/renderer/src/components/native-chat/structured-agent-session-send-attempt.ts +++ b/src/renderer/src/components/native-chat/structured-agent-session-send-attempt.ts @@ -130,7 +130,10 @@ export async function attemptStructuredAgentSessionSend(args: { expectedRuntimeFence: fence, body: entry.body, ...(entry.delivery ? { delivery: entry.delivery } : {}), - ...(entry.options ? { options: entry.options } : {}) + ...(entry.options ? { options: entry.options } : {}), + ...(entry.usageLimitContinuationOfTurnItemId + ? { usageLimitContinuationOfTurnItemId: entry.usageLimitContinuationOfTurnItemId } + : {}) }) type SendAnswer = AgentSessionMutationResult let answer: StructuredAgentSessionSendAnswer diff --git a/src/renderer/src/components/native-chat/structured-agent-session-send-slot.ts b/src/renderer/src/components/native-chat/structured-agent-session-send-slot.ts index aad2f2edbc5e..1206d01509df 100644 --- a/src/renderer/src/components/native-chat/structured-agent-session-send-slot.ts +++ b/src/renderer/src/components/native-chat/structured-agent-session-send-slot.ts @@ -6,6 +6,7 @@ import { structuredAgentSessionSendBody, type StructuredAgentSessionAttachment } from '../../../../shared/structured-agent-session-send-mutation' +import type { StructuredAgentSessionSendOutcome } from './structured-agent-session-send-runtime' import { createBrowserUuid } from '@/lib/browser-uuid' import { getStructuredAgentSessionPendingSends, @@ -24,11 +25,16 @@ export type StructuredAgentSessionSendInput = { options?: Readonly> /** The caller keeps the text if it comes back, instead of the chat's composer. */ callerKeepsText?: true + usageLimitContinuationOfTurnItemId?: string /** Made while the chat read Stopping: drawn after that turn until the host records it. */ sentWhileStopping?: true now?: number } +export type StructuredAgentSessionSendRequest = Pick< + StructuredAgentSessionSendInput, 'callerKeepsText' | 'usageLimitContinuationOfTurnItemId' +> & { onSettled?: (outcome: StructuredAgentSessionSendOutcome) => void } + /** Takes the chat's one send slot, drawn as sending; null while another send of the chat is out. */ export function takeStructuredAgentSessionSendSlot( input: StructuredAgentSessionSendInput @@ -45,6 +51,9 @@ export function takeStructuredAgentSessionSendSlot( queuedAt: input.now ?? Date.now(), ...(input.delivery ? { delivery: input.delivery } : {}), ...(input.options ? { options: input.options } : {}), + ...(input.usageLimitContinuationOfTurnItemId + ? { usageLimitContinuationOfTurnItemId: input.usageLimitContinuationOfTurnItemId } + : {}), ...(input.callerKeepsText ? { callerKeepsText: true as const } : {}), ...(input.sentWhileStopping ? { sentWhileStopping: true as const } : {}), ...(attachments.some((attachment) => attachment.connectionId) diff --git a/src/renderer/src/components/native-chat/use-native-chat-structured-composer-send.ts b/src/renderer/src/components/native-chat/use-native-chat-structured-composer-send.ts index 9d065e6a923c..b39498b4cf25 100644 --- a/src/renderer/src/components/native-chat/use-native-chat-structured-composer-send.ts +++ b/src/renderer/src/components/native-chat/use-native-chat-structured-composer-send.ts @@ -1,6 +1,5 @@ import { useCallback } from 'react' -import { emitNativeChatMessageSent } from '@/lib/native-chat-telemetry' -import { reportStructuredSessionUserInput } from '@/lib/worker-terminal-takeover-report' +import { completeNativeChatStructuredUserAction } from './native-chat-structured-user-action' import { isStructuredAgentSessionComposerCommand, isStructuredAgentSessionGoalCommand, @@ -101,17 +100,7 @@ export function useNativeChatStructuredComposerSend({ if (!accepted) { return } - emitNativeChatMessageSent({ agent, runtime: structuredTransport.runtime }) - if (revealsTranscript) { - structuredTransport.onSubmitted?.() - } - // A real user send is a takeover, exactly as typing into a worker's pane is. Only past - // `accepted`, and only from this hook: orchestration's own pointer nudges never reach - // the composer at all. - reportStructuredSessionUserInput( - structuredTransport.sessionId, - structuredTransport.runtimeEnvironmentId - ) + completeNativeChatStructuredUserAction(agent, structuredTransport, revealsTranscript) // Why: the send settles after a round trip, while this or another composer of the same // conversation may have changed the draft; only what was sent leaves it. const left = nativeChatComposerDraftLeftAfterSend( diff --git a/src/renderer/src/components/native-chat/use-native-chat-structured-composer-transport.ts b/src/renderer/src/components/native-chat/use-native-chat-structured-composer-transport.ts index 05f783fb7030..0377339d6992 100644 --- a/src/renderer/src/components/native-chat/use-native-chat-structured-composer-transport.ts +++ b/src/renderer/src/components/native-chat/use-native-chat-structured-composer-transport.ts @@ -45,7 +45,7 @@ export function useNativeChatStructuredComposerTransport(args: { : Promise.resolve(false) : null return { - send: (text, attachments) => + send: (text, attachments, request) => sendBlockedReason === null && sendThroughLaunch(text, attachments.length > 0, () => controller.send( @@ -54,7 +54,8 @@ export function useNativeChatStructuredComposerTransport(args: { path, previewUri: path, ...(connectionId ? { connectionId } : {}) - })) + })), + request ) ), dispatchCommand: (text: string) => diff --git a/src/renderer/src/components/native-chat/use-structured-agent-session-sends.ts b/src/renderer/src/components/native-chat/use-structured-agent-session-sends.ts index 8108b426fe8a..96623e2d3fec 100644 --- a/src/renderer/src/components/native-chat/use-structured-agent-session-sends.ts +++ b/src/renderer/src/components/native-chat/use-structured-agent-session-sends.ts @@ -1,3 +1,4 @@ +import type { StructuredAgentSessionSendRequest } from './structured-agent-session-send-slot' import { useCallback, useEffect, useSyncExternalStore } from 'react' import type { AgentJournalCursor, @@ -93,7 +94,8 @@ export function useStructuredAgentSessionSends(args: { const send = useCallback( ( text: string, - attachments: readonly StructuredAgentSessionAttachment[] = [] + attachments: readonly StructuredAgentSessionAttachment[] = [], + request?: StructuredAgentSessionSendRequest ): boolean | 'queued' => { if (!text.trim() && attachments.length === 0) { return false @@ -105,6 +107,10 @@ export function useStructuredAgentSessionSends(args: { target, text, attachments, + ...(request?.callerKeepsText ? { callerKeepsText: request.callerKeepsText } : {}), + ...(request?.usageLimitContinuationOfTurnItemId + ? { usageLimitContinuationOfTurnItemId: request.usageLimitContinuationOfTurnItemId } + : {}), ...(delivery ? { delivery } : {}), ...(options ? { options } : {}), ...(stopping ? { sentWhileStopping: true as const } : {}) @@ -113,6 +119,9 @@ export function useStructuredAgentSessionSends(args: { if (!sent) { return false } + if (request?.onSettled) { + void sent.outcome.then(request.onSettled) + } // The same projection that draws the transcript decides it. const admitted = getStructuredAgentSessionPendingSends(sessionId).filter( (entry) => entry.clientMessageId === sent.clientMessageId diff --git a/src/renderer/src/i18n/en-runtime-required.json b/src/renderer/src/i18n/en-runtime-required.json index ef5e31b317bf..b3ff4a15aeb3 100644 --- a/src/renderer/src/i18n/en-runtime-required.json +++ b/src/renderer/src/i18n/en-runtime-required.json @@ -3088,6 +3088,9 @@ "usedManySummary": "Used {{toolCount}} tools", "usedOneSummary": "Used 1 tool" }, + "interruptedContinue": { + "unconfirmed": "Couldn't confirm whether {{agent}} received Continue. Check the chat before trying again." + }, "writeNotice": { "agentRefused": "The agent turned this down.", "agentStarting": "The agent is still starting.", diff --git a/src/renderer/src/i18n/locales/en.json b/src/renderer/src/i18n/locales/en.json index afed1b818965..a71d7c68a789 100644 --- a/src/renderer/src/i18n/locales/en.json +++ b/src/renderer/src/i18n/locales/en.json @@ -19020,6 +19020,7 @@ "continue": "Continue", "failed": "Couldn't continue this chat. Try again, or send a message.", "explanation": "Continue, and the agent first checks whether its last step finished.", + "unconfirmed": "Couldn't confirm whether {{agent}} received Continue. Check the chat before trying again.", "usageLimitExplanation": "Asks the agent to continue where it left off. Use it once the limit resets." }, "claudeSignIn": { diff --git a/src/renderer/src/i18n/locales/es.json b/src/renderer/src/i18n/locales/es.json index f35b8e8f43e5..eae44fccf07d 100644 --- a/src/renderer/src/i18n/locales/es.json +++ b/src/renderer/src/i18n/locales/es.json @@ -18731,6 +18731,7 @@ "continue": "Continuar", "failed": "No se pudo continuar este chat. Inténtalo de nuevo o envía un mensaje.", "explanation": "Continúa y el agente comprobará primero si su último paso terminó.", + "unconfirmed": "Couldn't confirm whether {{agent}} received Continue. Check the chat before trying again.", "usageLimitExplanation": "Pide al agente que continúe donde lo dejó. Úsalo cuando se restablezca el límite." }, "rewind": { diff --git a/src/renderer/src/i18n/locales/fr.json b/src/renderer/src/i18n/locales/fr.json index abd6bc46ea96..6a7f41594b86 100644 --- a/src/renderer/src/i18n/locales/fr.json +++ b/src/renderer/src/i18n/locales/fr.json @@ -18840,6 +18840,7 @@ "continue": "Continuer", "failed": "Impossible de poursuivre cette conversation. Réessayez ou envoyez un message.", "explanation": "Continuez, et l'agent vérifiera d'abord si sa dernière étape s'est terminée.", + "unconfirmed": "Couldn't confirm whether {{agent}} received Continue. Check the chat before trying again.", "usageLimitExplanation": "Demande à l’agent de reprendre là où il s’était arrêté. À utiliser une fois la limite réinitialisée." }, "rewind": { diff --git a/src/renderer/src/i18n/locales/ja.json b/src/renderer/src/i18n/locales/ja.json index 690be3a5b4b1..786dcab99d21 100644 --- a/src/renderer/src/i18n/locales/ja.json +++ b/src/renderer/src/i18n/locales/ja.json @@ -18771,6 +18771,7 @@ "continue": "続行", "failed": "このチャットを続行できませんでした。もう一度試すか、メッセージを送信してください。", "explanation": "続行すると、Agent はまず最後の手順が完了したかどうかを確認します。", + "unconfirmed": "Couldn't confirm whether {{agent}} received Continue. Check the chat before trying again.", "usageLimitExplanation": "中断したところから続けるよう Agent に依頼します。上限がリセットされてから使ってください。" }, "rewind": { diff --git a/src/renderer/src/i18n/locales/ko.json b/src/renderer/src/i18n/locales/ko.json index 85fbacd12b4c..5df6ff653859 100644 --- a/src/renderer/src/i18n/locales/ko.json +++ b/src/renderer/src/i18n/locales/ko.json @@ -18771,6 +18771,7 @@ "continue": "계속", "failed": "이 채팅을 계속할 수 없습니다. 다시 시도하거나 메시지를 보내세요.", "explanation": "계속하면 에이전트가 먼저 마지막 단계가 완료되었는지 확인합니다.", + "unconfirmed": "Couldn't confirm whether {{agent}} received Continue. Check the chat before trying again.", "usageLimitExplanation": "중단한 곳부터 계속하도록 에이전트에 요청합니다. 한도가 초기화된 후 사용하세요." }, "rewind": { diff --git a/src/renderer/src/i18n/locales/zh.json b/src/renderer/src/i18n/locales/zh.json index 077b6b86140c..c08c69ee8e95 100644 --- a/src/renderer/src/i18n/locales/zh.json +++ b/src/renderer/src/i18n/locales/zh.json @@ -18736,6 +18736,7 @@ "continue": "继续", "failed": "无法继续此聊天。请重试,或发送一条消息。", "explanation": "继续后,智能体会先检查其上一步是否已完成。", + "unconfirmed": "Couldn't confirm whether {{agent}} received Continue. Check the chat before trying again.", "usageLimitExplanation": "让代理从中断处继续。请在上限重置后使用。" }, "rewind": { From c975f76a4427ef686b9cbd526a75da3eb4fb27db Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Sun, 18 Oct 2026 14:31:12 -0700 Subject: [PATCH 14/34] test(native-chat): provide the composer options surface in Continue coverage --- .../NativeChatInterruptedContinue.test.tsx | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/src/renderer/src/components/native-chat/NativeChatInterruptedContinue.test.tsx b/src/renderer/src/components/native-chat/NativeChatInterruptedContinue.test.tsx index e4b76adbc03a..7b5bbe2fe55c 100644 --- a/src/renderer/src/components/native-chat/NativeChatInterruptedContinue.test.tsx +++ b/src/renderer/src/components/native-chat/NativeChatInterruptedContinue.test.tsx @@ -78,6 +78,13 @@ const cutChat: AgentJournalRenderItem[] = [ } ] +const optionsSurface: NativeChatStructuredComposerTransport['optionsSurface'] = { + getSnapshot: () => [], + setOption: async () => ({ snapshot: [] }), + invokeAction: async () => ({ snapshot: [] }), + subscribe: () => () => {} +} + type Props = { journalItems?: readonly AgentJournalRenderItem[] submissions?: readonly Pick[] @@ -99,7 +106,7 @@ function Harness(props: Props): React.JSX.Element { submissions: props.submissions ?? [], isWorking: props.isWorking ?? false, pending: props.pending ?? [], - transport: props.transport ?? { send: () => true, dispatchCommand: async () => ({ handled: false, accepted: false, error: null }), optionSnapshot: [], onError: () => {}, runtime: 'remote', sessionId: 'session-1', runtimeEnvironmentId: 'studio-mac' } + 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 ( @@ -319,7 +326,7 @@ it('keeps the draft through Continue admission, refusal, uncertainty and recorde const transport: NativeChatStructuredComposerTransport = { send: (text, images, request) => sends.send(text, images.map((image) => ({ path: image.path, previewUri: image.path })), request), onSubmitted: reveal, onError: vi.fn(), dispatchCommand: async () => ({ handled: false, accepted: false, error: null }), - optionSnapshot: [], runtime: 'remote', sessionId: 'session-1', runtimeEnvironmentId: 'studio-mac' + optionsSurface, optionSnapshot: [], runtime: 'remote', sessionId: 'session-1', runtimeEnvironmentId: 'studio-mac' } return <>{uploading.pendingName} } From 78d44f4cd16e5f0e57ff95ad64e7637260b1c4fb Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Sun, 18 Oct 2026 14:52:59 -0700 Subject: [PATCH 15/34] test(native-chat): use typed failure words in renderer fixtures --- .../native-chat/NativeChatInterruptedContinue.test.tsx | 3 ++- .../native-chat/NativeChatNoticeRow.test.tsx | 10 ++++++++-- 2 files changed, 10 insertions(+), 3 deletions(-) diff --git a/src/renderer/src/components/native-chat/NativeChatInterruptedContinue.test.tsx b/src/renderer/src/components/native-chat/NativeChatInterruptedContinue.test.tsx index 7b5bbe2fe55c..23452547fd19 100644 --- a/src/renderer/src/components/native-chat/NativeChatInterruptedContinue.test.tsx +++ b/src/renderer/src/components/native-chat/NativeChatInterruptedContinue.test.tsx @@ -46,6 +46,7 @@ import { clearNativeChatComposerDraftsForTests, readNativeChatComposerDraft, upd 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, @@ -310,7 +311,7 @@ describe('Continue on a reply an Orca stop cut off', () => { it('keeps the draft through Continue admission, refusal, uncertainty and recorded-before-journal', async () => { const items: AgentJournalRenderItem[] = [ { ...cutChat[0]!, body: { kind: 'turn', turnId: 'cut', state: 'completed', outcome: 'failure', startedAt: 1, completedAt: 5 } }, - { ...cutChat[1]!, body: { kind: 'status', text: 'Limit', failure: { kind: 'usageLimitReached' } } } + { ...cutChat[1]!, body: { kind: 'status', ...agentSessionFailureWords({ kind: 'usageLimitReached' }, { surface: 'row' }) } } ] const scope = structuredAgentSessionDraftScopeKey('session-1') const draft = { text: 'My unfinished request', images: [{ id: 'attached', path: '/tmp/photo.png' }] } diff --git a/src/renderer/src/components/native-chat/NativeChatNoticeRow.test.tsx b/src/renderer/src/components/native-chat/NativeChatNoticeRow.test.tsx index c88a4ef85b26..bc8a661d75d8 100644 --- a/src/renderer/src/components/native-chat/NativeChatNoticeRow.test.tsx +++ b/src/renderer/src/components/native-chat/NativeChatNoticeRow.test.tsx @@ -458,8 +458,14 @@ describe('notice rows', () => { expect(disclosure?.querySelector('pre')).toHaveTextContent('Check the configuration') }) it('retains person-facing usage details without inventing a provider frame', () => { - renderStatus({ kind: 'status', text: 'Usage limit reached', tone: 'warning', - failure: { kind: 'usageLimitReached', detail: { audience: 'person', text: 'Your allowance resets tomorrow.' } } }) + renderStatus({ + kind: 'status', tone: 'warning', + ...agentSessionFailureWords( + agentSessionFailureFact('usageLimitReached', { + detail: { audience: 'person', text: 'Your allowance resets tomorrow.' } + }), { surface: 'row' } + ) + }) const disclosure = screen.getByText('Details').closest('details') expect(disclosure?.querySelector('pre')).toHaveTextContent('Your allowance resets tomorrow.') expect(screen.queryByText('codex')).not.toBeInTheDocument() From ef15a0c2c9897a8a23095728fc28148556fee0d5 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Sun, 18 Oct 2026 14:54:02 -0700 Subject: [PATCH 16/34] test(native-chat): match the remote send payload apart from transport options --- .../native-chat/NativeChatInterruptedContinue.test.tsx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/renderer/src/components/native-chat/NativeChatInterruptedContinue.test.tsx b/src/renderer/src/components/native-chat/NativeChatInterruptedContinue.test.tsx index 23452547fd19..2ba423ec37d1 100644 --- a/src/renderer/src/components/native-chat/NativeChatInterruptedContinue.test.tsx +++ b/src/renderer/src/components/native-chat/NativeChatInterruptedContinue.test.tsx @@ -344,7 +344,7 @@ it('keeps the draft through Continue admission, refusal, uncertainty and recorde expect(screen.getByTestId('error')).toHaveTextContent('none') expect(continueButton()).toBeNull() await waitFor(() => expect(mocks.call).toHaveBeenCalledOnce()) - expect(mocks.call.mock.calls[0]).toMatchObject([PAIRED, 'agentSession.send', { + expect(mocks.call.mock.calls[0].slice(0, 3)).toMatchObject([PAIRED, 'agentSession.send', { body: { kind: 'message', role: 'user', blocks: [{ type: 'text', text: 'Continue where you left off.' }] }, options, usageLimitContinuationOfTurnItemId: TURN }]) From d02e69aeae31aab39e1ea16604ada5b573a73939 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Sun, 18 Oct 2026 14:57:08 -0700 Subject: [PATCH 17/34] fix(native-chat): replace the previous sender notice on Continue --- .../NativeChatInterruptedContinue.test.tsx | 13 ++++++++++++- .../native-chat/NativeChatInterruptedContinue.tsx | 8 +++++++- 2 files changed, 19 insertions(+), 2 deletions(-) diff --git a/src/renderer/src/components/native-chat/NativeChatInterruptedContinue.test.tsx b/src/renderer/src/components/native-chat/NativeChatInterruptedContinue.test.tsx index 2ba423ec37d1..831fe1c1169e 100644 --- a/src/renderer/src/components/native-chat/NativeChatInterruptedContinue.test.tsx +++ b/src/renderer/src/components/native-chat/NativeChatInterruptedContinue.test.tsx @@ -41,8 +41,17 @@ vi.mock('./use-structured-agent-session-host-label', () => ({ 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 { + 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' @@ -340,7 +349,9 @@ it('keeps the draft through Continue admission, refusal, uncertainty and recorde mocks.capability = 'supported' rerender() fireEvent.click(screen.getByRole('button', { name: 'compose' })) + act(() => setStructuredAgentSessionSendNotice('session-1', 'Previous send failed')) fireEvent.click(continueButton()!) + expect(getStructuredAgentSessionSendNotice('session-1')).toBeNull() expect(screen.getByTestId('error')).toHaveTextContent('none') expect(continueButton()).toBeNull() await waitFor(() => expect(mocks.call).toHaveBeenCalledOnce()) diff --git a/src/renderer/src/components/native-chat/NativeChatInterruptedContinue.tsx b/src/renderer/src/components/native-chat/NativeChatInterruptedContinue.tsx index a259046044ad..ae7515094e1b 100644 --- a/src/renderer/src/components/native-chat/NativeChatInterruptedContinue.tsx +++ b/src/renderer/src/components/native-chat/NativeChatInterruptedContinue.tsx @@ -7,7 +7,11 @@ import { structuredAgentLabel } from '@/lib/structured-agent-session-launch-labe import type { AgentType } from '../../../../shared/agent-status-types' import { AGENT_SESSION_SEND_USAGE_LIMIT_CONTINUATION_RUNTIME_CAPABILITY } from '../../../../shared/agent-session-create-capabilities' import { completeNativeChatStructuredUserAction } from './native-chat-structured-user-action' -import { getStructuredAgentSessionPendingSends, type StructuredAgentSessionPendingSend } from './structured-agent-session-pending-sends' +import { + getStructuredAgentSessionPendingSends, + publishStructuredAgentSessionSends, + type StructuredAgentSessionPendingSend +} from './structured-agent-session-pending-sends' import { callStructuredAgentSession } from '@/runtime/structured-agent-session-client' import { useStructuredAgentSessionHostCapabilityState } from '@/runtime/structured-agent-session-host-capability' import type { RuntimeClientTarget } from '../../../../shared/runtime-client-target' @@ -117,6 +121,8 @@ export function useNativeChatInterruptedContinuation(input: { const turnItemId = usageLimitTurnItemId setUsageFailure(null) reportComposerError(null) + // Keeping the draft must not keep the previous send's error. + publishStructuredAgentSessionSends(sessionId, { notice: null }) const admission = transport.send(NATIVE_CHAT_USAGE_LIMIT_CONTINUE_MESSAGE, [], { callerKeepsText: true, ...(usageCapability === 'supported' ? { usageLimitContinuationOfTurnItemId: turnItemId } : {}), From 9f01f029110593b27b000aec46e4626f14415640 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Sun, 18 Oct 2026 15:07:00 -0700 Subject: [PATCH 18/34] fix(native-chat): clear superseded Continue notices before rendering --- .../native-chat/NativeChatInterruptedContinue.tsx | 10 ++++------ 1 file changed, 4 insertions(+), 6 deletions(-) diff --git a/src/renderer/src/components/native-chat/NativeChatInterruptedContinue.tsx b/src/renderer/src/components/native-chat/NativeChatInterruptedContinue.tsx index ae7515094e1b..6bb4be5bfa54 100644 --- a/src/renderer/src/components/native-chat/NativeChatInterruptedContinue.tsx +++ b/src/renderer/src/components/native-chat/NativeChatInterruptedContinue.tsx @@ -1,4 +1,4 @@ -import { useCallback, useEffect, useId, useMemo, useState } from 'react' +import { useCallback, useId, useMemo, useState } from 'react' import { Play } from 'lucide-react' import { Button } from '@/components/ui/button' import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip' @@ -92,11 +92,9 @@ export function useNativeChatInterruptedContinuation(input: { unconfirmed: boolean } | null>(null) const [failedOn, setFailedOn] = useState(null) - useEffect(() => { - if (input.pending.length > 0) { - setUsageFailure(null) - } - }, [input.pending]) + if (usageFailure !== null && input.pending.length > 0) { + setUsageFailure(null) + } const offered = capability === 'supported' && cut && !input.isWorking && !resuming && asked !== cut.turnItemId ? cut.turnItemId From 1598940702c477a9b7661d47ea90d54e2c2e28a9 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Sun, 18 Oct 2026 15:17:31 -0700 Subject: [PATCH 19/34] fix(native-chat): preserve ordinary composer send arguments --- .../use-native-chat-structured-composer-transport.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/renderer/src/components/native-chat/use-native-chat-structured-composer-transport.ts b/src/renderer/src/components/native-chat/use-native-chat-structured-composer-transport.ts index 0377339d6992..c1e5ca5aebd9 100644 --- a/src/renderer/src/components/native-chat/use-native-chat-structured-composer-transport.ts +++ b/src/renderer/src/components/native-chat/use-native-chat-structured-composer-transport.ts @@ -45,7 +45,7 @@ export function useNativeChatStructuredComposerTransport(args: { : Promise.resolve(false) : null return { - send: (text, attachments, request) => + send: (text, attachments, ...request) => sendBlockedReason === null && sendThroughLaunch(text, attachments.length > 0, () => controller.send( @@ -55,7 +55,7 @@ export function useNativeChatStructuredComposerTransport(args: { previewUri: path, ...(connectionId ? { connectionId } : {}) })), - request + ...request ) ), dispatchCommand: (text: string) => From 502950ebb71b3401f1dfe9d11b1dcbad2b2f01b4 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Sun, 18 Oct 2026 16:03:39 -0700 Subject: [PATCH 20/34] fix(claude): resolve terminal ownership and preserve resultless quota failures --- .../claude-context-usage-test-support.ts | 45 +++-- src/main/claude/claude-message-journaling.ts | 32 +++- src/main/claude/claude-open-turn.ts | 11 +- src/main/claude/claude-result-journaling.ts | 33 +++- src/main/claude/claude-terminal-failure.ts | 171 ++++++++++++++++++ src/main/claude/claude-usage-limits.test.ts | 106 +++++++++++ src/main/claude/claude-usage-limits.ts | 22 +-- .../structured-agent-session-transition.ts | 2 +- .../NativeChatInterruptedContinue.test.tsx | 24 ++- .../NativeChatInterruptedContinue.tsx | 9 +- 10 files changed, 409 insertions(+), 46 deletions(-) create mode 100644 src/main/claude/claude-terminal-failure.ts diff --git a/src/main/claude/claude-context-usage-test-support.ts b/src/main/claude/claude-context-usage-test-support.ts index 9823401e264b..f7b9a24b2f4c 100644 --- a/src/main/claude/claude-context-usage-test-support.ts +++ b/src/main/claude/claude-context-usage-test-support.ts @@ -11,13 +11,19 @@ import type { StructuredAgentSessionEventSink, StructuredAgentSessionRevisionJournal } from '../native-chat/agent-session-wire/structured-agent-session-event-sink' +import type { StructuredAgentSessionTransitionJournal } from '../native-chat/agent-session-wire/structured-agent-session-transition' 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 +36,15 @@ export function journal() { revision: (existing?.revision ?? 0) + 1, sequence: existing?.sequence ?? rows.size + 1, observedAt: existing?.observedAt ?? options?.observedAt ?? clock.now, - body + ...options, body }) } const scans = { count: 0 } - const bound: StructuredAgentSessionRevisionJournal = { + const bound: StructuredAgentSessionRevisionJournal & StructuredAgentSessionTransitionJournal = { + item: (itemId) => rows.get(itemId) ?? null, + canonicalItemId: (itemId) => itemId, + submissions: () => [], + visitItemsWithLinkage: (visit) => { for (const row of rows.values()) { visit(row.itemId, row.sequence, row.body, row) } }, epoch: 'test', visitItems: (visit) => { scans.count += 1 @@ -49,14 +59,27 @@ export function journal() { 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 sink: StructuredAgentSessionEventSink = { - appendItem, + appendItem: (...args) => run(() => appendItem(...args)), + journalItems: () => bound, + tryAppendTransition: (transition) => { + run(() => { + for (const step of transition.steps) { + if (step.kind === 'item') { + const resolved = step.resolve(bound) + if (resolved) { appendItem(resolved.identity, resolved.body, step.options) } + } + } + transition.onPublished?.() + }) + return { accepted: true } + }, tryReviseResolvedItem: revise, tryReviseResolvedItemAndPublish: revise, appendTombstone: () => {}, @@ -65,7 +88,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 } } export function frame(message: Record, observedAt: number, startsTurn = false) { @@ -146,8 +169,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 96365a1f8f17..7844c2b83fee 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 { resolveClaudeTerminalOwner, 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' @@ -101,6 +103,21 @@ export function journalClaudeMessage( } 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') + const owner = terminal ? resolveClaudeTerminalOwner(ctx.sink, ctx.turn, message) : undefined + if (owner === null) { + return true + } + if (owner?.identity && !owner.current) { + const body = ctx.usageLimits.assistant(message) ?? messageBody ?? ordinaryFailure + if (body) { + writeClaudeTerminalFailure(ctx.sink, owner.identity, body) + } + return true + } // A refusal needs its owning turn before the canonical write; empty placeholders open nothing. if (envelope.role === 'assistant' && (messageBody || typeof message.api_error === 'string' || message.error === 'rate_limit')) { @@ -111,11 +128,10 @@ export function journalClaudeMessage( ctx.authenticationFailures.assistant(message) ?? usageLimit ?? ctx.threadGoal.report(message, claudeMessageIdentity(envelope), observedAt) ?? - messageBody - const terminalIdentity = usageLimit && producerRef === null && ctx.turn.identity - ? { provider: 'orca' as const, clientMessageId: `terminal-failure:claude:${agentJournalItemKey(ctx.turn.identity)}` } - : null - const identity = terminalIdentity ?? + messageBody ?? ordinaryFailure + const terminalIdentity = terminal && ctx.turn.identity && (usageLimit || message.api_error) + ? ctx.turn.identity : null + const identity = (body && envelope.role === 'assistant' ? ctx.streamedBlocks.reconcile(envelope)?.identity : null) ?? claudeMessageIdentity(envelope) @@ -126,7 +142,11 @@ export function journalClaudeMessage( // 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 ab6791c913ef..b1cd17041b48 100644 --- a/src/main/claude/claude-open-turn.ts +++ b/src/main/claude/claude-open-turn.ts @@ -21,6 +21,7 @@ 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 { finalizeClaudeTerminalTurn } from './claude-terminal-failure' import type { ClaudeUsageLimitEvidence } from './claude-usage-limits' import type { ClaudeStartedSend } from './claude-structured-session-state' @@ -96,6 +97,10 @@ export class ClaudeOpenTurn { return this.current?.startedAt ?? null } + get isReopenSuppressed(): boolean { + return this.reopenSuppressed + } + get isOpen(): boolean { return this.current !== null } @@ -226,10 +231,14 @@ export class ClaudeOpenTurn { contextUsage?: AgentSessionContextUsage ): void { const item = claudeTurnLifecycleItem(turn, end) + const write = { lifecycle: item.body, ...(contextUsage ? { contextUsage } : {}) } + if (end && finalizeClaudeTerminalTurn(this.deps.sink, item.identity, write, this)) { + 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 6d82fa1e8009..bed9412401dc 100644 --- a/src/main/claude/claude-result-journaling.ts +++ b/src/main/claude/claude-result-journaling.ts @@ -5,6 +5,11 @@ // the open turn and every collaborator this writes through. import { agentJournalItemKey } from '../../shared/agent-session-journal-item-key' +import { + claudeTerminalFailureIdentity, + resolveClaudeTerminalOwner, + 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' @@ -58,6 +63,20 @@ export function journalClaudeResult( // diagnostic below still runs: a child's failure is reportable even when // it ends no turn. const settlesTurn = isRootClaudeFrame(message) + const owner = settlesTurn ? resolveClaudeTerminalOwner(sink, turn, message) : undefined + if (owner === null) { + return + } + if (owner?.identity && !owner.current) { + const failureIdentity = claudeTerminalFailureIdentity(agentJournalItemKey(owner.identity)) + const prior = sink.journalItems?.()?.itemBody(agentJournalItemKey(failureIdentity)) + const usageLimit = prior?.kind === 'status' && prior.failure?.kind === 'usageLimitReached' + ? usageLimits.result(message, claudeResultFailure(message, false) !== null, { cause: 'quota' }) : null + if (usageLimit) { + writeClaudeTerminalFailure(sink, owner.identity, usageLimit) + } + return + } const commandEnd = settlesTurn ? claudeCommandResultEnd(turn, sink, message, observedAt) : null if (commandEnd === 'another-input') { return @@ -71,6 +90,11 @@ export function journalClaudeResult( // 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 + const failure = claudeResultFailure(message, leftToStop) + const usageLimit = settlesTurn ? usageLimits.result(message, failure !== null, usageEvidence) : null + if (usageLimit && endedTurnIdentity) { + writeClaudeTerminalFailure(sink, endedTurnIdentity, usageLimit) + } if (settlesTurn) { prompts.retryPendingCancellations() turn.suppressReopenOnFailure(message.is_error === true) @@ -96,16 +120,7 @@ export function journalClaudeResult( sink.publish() } const kind = claudeProviderFrameKind(message) - const failure = claudeResultFailure(message, leftToStop) - // A failed root result the limit refused writes the limit's row, not the result's. - const usageLimit = settlesTurn ? usageLimits.result(message, failure !== null, usageEvidence) : null if (usageLimit && endedTurnIdentity) { - sink.appendItem( - { provider: 'orca', clientMessageId: `terminal-failure:claude:${agentJournalItemKey(endedTurnIdentity)}` }, - usageLimit, - { turnScope: endedTurnScope } - ) - sink.publish() return } const alreadyShown = authenticationFailures.resultAlreadyShown(message) diff --git a/src/main/claude/claude-terminal-failure.ts b/src/main/claude/claude-terminal-failure.ts new file mode 100644 index 000000000000..6d84d324d5c7 --- /dev/null +++ b/src/main/claude/claude-terminal-failure.ts @@ -0,0 +1,171 @@ +import { + agentJournalItemKey, + parseAgentJournalItemKey +} from '../../shared/agent-session-journal-item-key' +import type { + AgentJournalItemBody, + AgentJournalItemIdentity, + AgentJournalRenderItem +} 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 { latestNativeChatTurnSinceRequest } from '../../shared/native-chat-orca-stop-cut' +import type { StructuredAgentSessionEventSink } 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' +import type { ClaudeOpenTurn } from './claude-open-turn' +import { claudeText } from './claude-structured-item-translation' +import { claudeTurnLifecycleIdentity } from './claude-turn-lifecycle-item' + +export function claudeTerminalFailureIdentity(turnItemId: string): AgentJournalItemIdentity { + return { provider: 'orca', clientMessageId: `terminal-failure:claude:${turnItemId}` } +} + +function latestClosedWork(sink: StructuredAgentSessionEventSink): AgentJournalRenderItem | null { + const journal = sink.journalItems?.() + if (!journal) { + return null + } + const items: AgentJournalRenderItem[] = [] + journal.visitItemsWithLinkage((itemId) => { + const item = journal.item(itemId) + if (item) { + items.push(item) + } + }) + items.sort((a, b) => a.sequence - b.sequence) + return latestNativeChatTurnSinceRequest(items, journal.submissions())?.turnItem ?? null +} + +// Historical correlation wins over a newer cursor; unknown accepted work keeps its diagnostic. +export function resolveClaudeTerminalOwner( + sink: StructuredAgentSessionEventSink, + turn: ClaudeOpenTurn, + frame: Record +): { identity: AgentJournalItemIdentity | null; current: boolean } | null { + const journal = sink.journalItems?.() + const sessionId = claudeText(frame.session_id) + const stamp = claudeText(frame.user_message_uuid) + const uuid = stamp ?? (frame.type === 'assistant' ? claudeText(frame.uuid) : null) + let owner: AgentJournalRenderItem | null = null + if (journal && sessionId && uuid) { + const candidate = journal.item(agentJournalItemKey(claudeTurnLifecycleIdentity(sessionId, uuid))) + if (candidate?.body.kind === 'turn' && isRootAgentJournalItem(candidate)) { + owner = candidate + } else if (stamp) { + const echo = journal.canonicalItemId( + agentJournalItemKey({ provider: 'claude', sessionId, uuid: stamp }) + ) + journal.visitItemsWithLinkage((itemId, _sequence, body) => { + const identity = parseAgentJournalItemKey(itemId) + if ( + body.kind === 'turn' && body.userItemId && identity?.provider === 'legacy' && + identity.agent === 'claude' && identity.sessionId === sessionId && + journal.canonicalItemId(body.userItemId) === echo + ) { + const candidate = journal.item(itemId) + if (candidate && isRootAgentJournalItem(candidate)) { + owner = candidate + } + } + }) + } + } + if (owner) { + return { + identity: parseAgentJournalItemKey(owner.itemId), + current: owner.itemId === (turn.identity && agentJournalItemKey(turn.identity)) + } + } + if (turn.identity) { + return { identity: turn.identity, current: true } + } + if (turn.isReopenSuppressed && latestClosedWork(sink)) { + return null + } + return { identity: null, current: false } +} + +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) => { + 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 merged = prior?.kind === 'usageLimitReached' && next?.kind === 'usageLimitReached' + ? { ...body, ...agentSessionFailureWords({ + ...prior, ...next, + usageLimit: next.usageLimit ?? prior.usageLimit, + detail: providerDiagnostic( + [...new Set([prior.detail?.text, next.detail?.text].filter(Boolean))].join('\n'), 'person' + ) + }, { agentName: 'Claude', provider: 'claude', surface: 'row' }) } + : body + return JSON.stringify(merged) === JSON.stringify(old) + ? null : { identity: failureIdentity, body: merged } + }, options) +} + +// Every ending reads its own quota fact after preceding assistant writes have landed. +export function finalizeClaudeTerminalTurn( + sink: StructuredAgentSessionEventSink, + identity: AgentJournalItemIdentity, + write: AgentJournalTurnRowWrite, + turn: ClaudeOpenTurn +): boolean { + if (!sink.tryAppendTransition || !write.lifecycle) { + return false + } + const lifecycle = write.lifecycle + const target = { identity } + const reservedBytes = agentJournalTurnRowReservedBytes(target, write) + let failed = false + sink.tryAppendTransition({ + lifecycle: true, + publish: true, + steps: [{ + kind: 'item', reservedBytes, options: { turnScope: { kind: 'thread' } }, + resolve: (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 = lifecycle.outcome ?? (quota ? (stopped ? 'cancellation' : 'failure') : undefined) + failed = outcome === 'failure' + return resolveAgentJournalTurnRowWrite(journal, target, { + ...write, lifecycle: { ...lifecycle, ...(outcome ? { outcome } : {}) } + }, reservedBytes) + } + }], + onPublished: () => { + const current = turn.identity + if ( + failed && (!current || agentJournalItemKey(current) === agentJournalItemKey(identity)) && + latestClosedWork(sink)?.itemId === agentJournalItemKey(identity) + ) { + turn.suppressReopenOnFailure(true) + } + } + }) + return true +} diff --git a/src/main/claude/claude-usage-limits.test.ts b/src/main/claude/claude-usage-limits.test.ts index 84c95aa89793..3b77e79070b0 100644 --- a/src/main/claude/claude-usage-limits.test.ts +++ b/src/main/claude/claude-usage-limits.test.ts @@ -1,4 +1,7 @@ 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. @@ -150,3 +153,106 @@ describe('a Claude usage limit', () => { 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([false, true])('reconciles replay and late detail without touching newer work (provider-opened %s)', (providerOpened) => { + const t = setup() + if (!providerOpened) { t.handle(userFrame('owner', 1000)) } + const refusal = quota('owner', providerOpened ? undefined : 'owner') + t.handle(refusal) + t.handle(frame({ ...failedResult('owner', 1200, LIMIT_TEXT).message, user_message_uuid: 'owner' }, 1200)) + const endpoints = t.items().filter((item) => item.body.kind === 'turn') + t.handle(refusal) + t.handle(frame({ ...failedResult('owner', 1300, LIMIT_TEXT).message, user_message_uuid: 'owner' }, 1300)) + expect(statusRows(t)).toHaveLength(1) + expect(t.items().filter((item) => item.body.kind === 'turn')).toEqual(endpoints) + t.handle(userFrame('newer', 2000)) + t.handle(refusal) + t.handle(frame({ ...failedResult('owner', 2200, 'New provider explanation').message, user_message_uuid: 'owner' }, 2200)) + expect(t.translator.currentTurnId).toBe('newer') + expect(t.turnRow('newer')?.body).toMatchObject({ state: 'running' }) + expect(statusRows(t)).toHaveLength(1) + expect(statusRows(t)[0]?.failure?.detail?.text).toContain('New provider explanation') + t.translator.dispose() +}) + +it.each(['idle', 'exit'] as const)('keeps quota failure through a deferred resultless %s and merges late detail', (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', observedAt: 1200 }) + } + t.flush() + expect(t.turnRow('owner')?.body).toMatchObject({ + state: ending === 'idle' ? 'completed' : 'interrupted', outcome: 'failure' + }) + expect(latestNativeChatUsageLimitCut(t.items(), [])).not.toBeNull() + const end = t.turnRow('owner') + t.handle(frame({ ...failedResult('owner', 1400, 'Later explanation').message, user_message_uuid: 'owner' }, 1400)) + t.flush() + expect(t.turnRow('owner')).toEqual(end) + expect(statusRows(t)).toHaveLength(1) + expect(statusRows(t)[0]?.failure?.detail?.text).toContain('Later explanation') + 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' }, 1150)) + } + const stopAt = mode === 'before' ? 1150 : 1300 + t.sink.journalStopDecidesTurn = (_turnId, endAt) => + (mode === 'before' || mode === 'after') && endAt >= stopAt + 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 { + t.handle({ type: 'ended', sessionId: 'orca-session', observedAt: 1200 }) + } + 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 index e3183e07bc06..5f9d3b2a10cc 100644 --- a/src/main/claude/claude-usage-limits.ts +++ b/src/main/claude/claude-usage-limits.ts @@ -42,7 +42,6 @@ function messageText(message: Record): string { export type ClaudeUsageLimitEvidence = { cause: 'quota' | 'other' | 'untyped' - row: ClaudeUsageLimitRow | null } // Account observations outlive turns because unchanged rejection notifications are throttled. @@ -57,7 +56,7 @@ export class ClaudeUsageLimits { } } - assistant(message: Record, turn: ClaudeOpenTurn): ClaudeUsageLimitRow | null { + assistant(message: Record, turn?: ClaudeOpenTurn): ClaudeUsageLimitRow | null { if (message.type !== 'assistant') { return null } @@ -68,13 +67,13 @@ export class ClaudeUsageLimits { } 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 decision = !typed && root ? (turn?.usageLimitEvidence?.cause ?? cause) : cause const row = decision !== 'other' && refused ? this.row(messageText(message), decision === 'quota') : null - if (root && (typed || (refused && decision === 'untyped'))) { - turn.usageLimitEvidence = { cause, row } + if (root && turn?.isOpen && (typed || (refused && decision === 'untyped'))) { + turn.usageLimitEvidence = { cause: row ? 'quota' : cause } } return row } @@ -97,13 +96,7 @@ export class ClaudeUsageLimits { if (!limited) { return null } - const prior = evidence?.row - const details = [prior?.failure.detail?.text, claudeText(message.result)] - .filter((value): value is string => Boolean(value)) - return ( - this.row([...new Set(details)].join('\n'), evidence?.cause === 'quota' || prior != null, - prior?.failure.usageLimit) ?? prior ?? null - ) + return this.row(claudeText(message.result) ?? '', evidence?.cause === 'quota') } private record(info: Record | null): void { @@ -146,10 +139,9 @@ export class ClaudeUsageLimits { private row( providerText: string, - typed = false, - previousLimit?: AgentSessionUsageLimit + typed = false ): ClaudeUsageLimitRow | null { - const limit = this.limit() ?? previousLimit ?? null + const limit = this.limit() if (!limit && !typed) { return null } diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-transition.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-transition.ts index a6b5b9b30be9..084f98b0a5d6 100644 --- a/src/main/native-chat/agent-session-wire/structured-agent-session-transition.ts +++ b/src/main/native-chat/agent-session-wire/structured-agent-session-transition.ts @@ -26,7 +26,7 @@ import { structuredAgentSessionJournalAppendOptions } from './structured-agent-s /** What a transition step reads: rows by key, every row, and the turns they joined. */ export type StructuredAgentSessionTransitionJournal = Pick< AgentSessionJournal, - 'epoch' | 'visitItems' | 'itemBody' | 'item' | 'visitItemsWithLinkage' + 'epoch' | 'visitItems' | 'itemBody' | 'item' | 'visitItemsWithLinkage' | 'submissions' | 'canonicalItemId' > export type StructuredAgentSessionTransitionStep = diff --git a/src/renderer/src/components/native-chat/NativeChatInterruptedContinue.test.tsx b/src/renderer/src/components/native-chat/NativeChatInterruptedContinue.test.tsx index 831fe1c1169e..109a1a81ab24 100644 --- a/src/renderer/src/components/native-chat/NativeChatInterruptedContinue.test.tsx +++ b/src/renderer/src/components/native-chat/NativeChatInterruptedContinue.test.tsx @@ -1,6 +1,6 @@ // @vitest-environment happy-dom import '@testing-library/jest-dom/vitest' -import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react' +import { act, cleanup, fireEvent, render, renderHook, screen, waitFor } from '@testing-library/react' import { useState } from 'react' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' @@ -391,3 +391,25 @@ it('keeps the draft through Continue admission, refusal, uncertainty and recorde expect(screen.getByText('next.png')).toBeInTheDocument() expect(options).toEqual({ model: 'gpt-current', effort: 'high' }) }) + +it('keeps the notice view stable while Continue invokes the latest committed transport', () => { + const items: AgentJournalRenderItem[] = [ + { ...cutChat[0]!, body: { kind: 'turn', turnId: 'cut', state: 'completed', outcome: 'failure', startedAt: 1, completedAt: 5 } }, + { ...cutChat[1]!, body: { kind: 'status', ...agentSessionFailureWords({ kind: 'usageLimitReached' }, { surface: 'row' }) } } + ] + const first = vi.fn(() => true) + const latest = vi.fn(() => true) + const transport: NativeChatStructuredComposerTransport = { + send: first, dispatchCommand: async () => ({ handled: false, accepted: false, error: null }), + optionsSurface, optionSnapshot: [], onError: () => {}, runtime: 'remote', sessionId: 'session-1' + } + const input = { target: PAIRED, agent: 'codex' as const, sessionId: 'session-1', journalItems: items, + submissions: [], isWorking: false, pending: [], reportComposerError: vi.fn(), transport } + const { result, rerender } = renderHook((props) => useNativeChatInterruptedContinuation(props), { initialProps: input }) + const view = result.current.view + rerender({ ...input, transport: { ...transport, send: latest } }) + expect(result.current.view).toBe(view) + act(() => view.continueUsageLimit()) + expect(first).not.toHaveBeenCalled() + expect(latest).toHaveBeenCalledOnce() +}) diff --git a/src/renderer/src/components/native-chat/NativeChatInterruptedContinue.tsx b/src/renderer/src/components/native-chat/NativeChatInterruptedContinue.tsx index 6bb4be5bfa54..416ccd7831f5 100644 --- a/src/renderer/src/components/native-chat/NativeChatInterruptedContinue.tsx +++ b/src/renderer/src/components/native-chat/NativeChatInterruptedContinue.tsx @@ -1,4 +1,4 @@ -import { useCallback, useId, useMemo, useState } from 'react' +import { useCallback, useId, useLayoutEffect, useMemo, useRef, useState } from 'react' import { Play } from 'lucide-react' import { Button } from '@/components/ui/button' import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip' @@ -63,6 +63,10 @@ export function useNativeChatInterruptedContinuation(input: { pending: readonly Pick[] }): NativeChatInterruptedContinuation { const { target, sessionId, reportComposerError, transport, agent } = input + const latestTransport = useRef(transport) + useLayoutEffect(() => { + latestTransport.current = transport + }, [transport]) const hostLabel = useStructuredAgentSessionHostLabel(target) const capability = useStructuredAgentSessionHostCapabilityState( target, @@ -121,6 +125,7 @@ export function useNativeChatInterruptedContinuation(input: { reportComposerError(null) // Keeping the draft must not keep the previous send's error. publishStructuredAgentSessionSends(sessionId, { notice: null }) + const transport = latestTransport.current const admission = transport.send(NATIVE_CHAT_USAGE_LIMIT_CONTINUE_MESSAGE, [], { callerKeepsText: true, ...(usageCapability === 'supported' ? { usageLimitContinuationOfTurnItemId: turnItemId } : {}), @@ -135,7 +140,7 @@ export function useNativeChatInterruptedContinuation(input: { } else { completeNativeChatStructuredUserAction(agent, transport, admission === true) } - }, [usageLimitTurnItemId, usageCapability, sessionId, reportComposerError, transport, agent]) + }, [usageLimitTurnItemId, usageCapability, sessionId, reportComposerError, agent]) const continueNow = useCallback((): void => { if (offered === null) { return From 1a35fa197e5dd8f765b6ca4884fa18008ad1b651 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Sun, 18 Oct 2026 16:07:45 -0700 Subject: [PATCH 21/34] fix(claude): keep repeated terminal detail unchanged and complete test fixtures --- src/main/claude/claude-terminal-failure.ts | 8 +++++--- src/main/claude/claude-usage-limits.test.ts | 6 ++++-- .../native-chat/NativeChatInterruptedContinue.test.tsx | 2 +- 3 files changed, 10 insertions(+), 6 deletions(-) diff --git a/src/main/claude/claude-terminal-failure.ts b/src/main/claude/claude-terminal-failure.ts index 6d84d324d5c7..21a5050f2b7a 100644 --- a/src/main/claude/claude-terminal-failure.ts +++ b/src/main/claude/claude-terminal-failure.ts @@ -109,13 +109,15 @@ export function writeClaudeTerminalFailure( 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( - [...new Set([prior.detail?.text, next.detail?.text].filter(Boolean))].join('\n'), 'person' - ) + detail: providerDiagnostic(detail, 'person') }, { agentName: 'Claude', provider: 'claude', surface: 'row' }) } : body return JSON.stringify(merged) === JSON.stringify(old) diff --git a/src/main/claude/claude-usage-limits.test.ts b/src/main/claude/claude-usage-limits.test.ts index 3b77e79070b0..81db051d47ef 100644 --- a/src/main/claude/claude-usage-limits.test.ts +++ b/src/main/claude/claude-usage-limits.test.ts @@ -166,9 +166,11 @@ it.each([false, true])('reconciles replay and late detail without touching newer t.handle(refusal) t.handle(frame({ ...failedResult('owner', 1200, LIMIT_TEXT).message, user_message_uuid: 'owner' }, 1200)) const endpoints = t.items().filter((item) => item.body.kind === 'turn') + const warning = t.items().find((item) => item.body.kind === 'status') t.handle(refusal) t.handle(frame({ ...failedResult('owner', 1300, LIMIT_TEXT).message, user_message_uuid: 'owner' }, 1300)) expect(statusRows(t)).toHaveLength(1) + expect(t.items().find((item) => item.body.kind === 'status')).toEqual(warning) expect(t.items().filter((item) => item.body.kind === 'turn')).toEqual(endpoints) t.handle(userFrame('newer', 2000)) t.handle(refusal) @@ -187,7 +189,7 @@ it.each(['idle', 'exit'] as const)('keeps quota failure through a deferred resul if (ending === 'idle') { t.handle(frame({ type: 'system', subtype: 'session_state_changed', state: 'idle' }, 1200)) } else { - t.handle({ type: 'ended', sessionId: 'orca-session', observedAt: 1200 }) + t.handle({ type: 'ended', sessionId: 'orca-session', reason: 'Provider exited', observedAt: 1200 }) } t.flush() expect(t.turnRow('owner')?.body).toMatchObject({ @@ -222,7 +224,7 @@ it.each(['before', 'after', 'child', 'ordinary', 'success', 'other', 'superseded } else if (mode === 'superseded') { t.handle(userFrame('newer', 1200)) } else { - t.handle({ type: 'ended', sessionId: 'orca-session', observedAt: 1200 }) + t.handle({ type: 'ended', sessionId: 'orca-session', reason: 'Provider exited', observedAt: 1200 }) } t.flush() const outcome = mode === 'before' ? 'cancellation' : mode === 'after' ? 'failure' diff --git a/src/renderer/src/components/native-chat/NativeChatInterruptedContinue.test.tsx b/src/renderer/src/components/native-chat/NativeChatInterruptedContinue.test.tsx index 109a1a81ab24..71b2a1bc7297 100644 --- a/src/renderer/src/components/native-chat/NativeChatInterruptedContinue.test.tsx +++ b/src/renderer/src/components/native-chat/NativeChatInterruptedContinue.test.tsx @@ -401,7 +401,7 @@ it('keeps the notice view stable while Continue invokes the latest committed tra const latest = vi.fn(() => true) const transport: NativeChatStructuredComposerTransport = { send: first, dispatchCommand: async () => ({ handled: false, accepted: false, error: null }), - optionsSurface, optionSnapshot: [], onError: () => {}, runtime: 'remote', sessionId: 'session-1' + optionsSurface, optionSnapshot: [], onError: () => {}, runtime: 'remote', sessionId: 'session-1', runtimeEnvironmentId: 'studio-mac' } const input = { target: PAIRED, agent: 'codex' as const, sessionId: 'session-1', journalItems: items, submissions: [], isWorking: false, pending: [], reportComposerError: vi.fn(), transport } From b6a0073ae82ae0350d151d241fc399b481b4781b Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Sun, 18 Oct 2026 16:23:33 -0700 Subject: [PATCH 22/34] fix(claude): resolve deferred terminal replays after owning journal writes --- src/main/claude/claude-command-turn.test.ts | 1 + .../claude-context-usage-test-support.ts | 10 +- src/main/claude/claude-message-journaling.ts | 25 ++- src/main/claude/claude-open-turn.ts | 16 ++ src/main/claude/claude-result-journaling.ts | 27 ++- src/main/claude/claude-terminal-failure.ts | 177 +++++++++++------- src/main/claude/claude-turn-lifecycle-item.ts | 2 + src/main/claude/claude-turn-opening.ts | 3 + src/main/claude/claude-usage-limits.test.ts | 35 ++-- .../journal-item-appender.ts | 9 +- .../journal-step-writer.ts | 4 +- .../structured-agent-session-event-sink.ts | 5 +- ...tructured-agent-session-resolved-append.ts | 7 +- .../structured-agent-session-transition.ts | 4 +- 14 files changed, 204 insertions(+), 121 deletions(-) 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 f7b9a24b2f4c..a660c3ab3e54 100644 --- a/src/main/claude/claude-context-usage-test-support.ts +++ b/src/main/claude/claude-context-usage-test-support.ts @@ -36,7 +36,7 @@ export function journal({ deferred = false } = {}) { revision: (existing?.revision ?? 0) + 1, sequence: existing?.sequence ?? rows.size + 1, observedAt: existing?.observedAt ?? options?.observedAt ?? clock.now, - ...options, body + ...options, turnScope: existing?.turnScope ?? options.turnScope, body }) } const scans = { count: 0 } @@ -54,14 +54,16 @@ export function journal({ deferred = false } = {}) { }, itemBody: (itemId) => rows.get(itemId)?.body ?? null } - const revise: NonNullable = ( + const revise: NonNullable = ( _reservedBytes, resolve, - options + options, + onPublished ) => { run(() => { const resolved = resolve(bound) if (resolved) { appendItem(resolved.identity, resolved.body, options) } + onPublished?.() }) return { accepted: true } } @@ -73,7 +75,7 @@ export function journal({ deferred = false } = {}) { for (const step of transition.steps) { if (step.kind === 'item') { const resolved = step.resolve(bound) - if (resolved) { appendItem(resolved.identity, resolved.body, step.options) } + if (resolved) { appendItem(resolved.identity, resolved.body, { ...step.options, turnScope: resolved.turnScope ?? step.options.turnScope }) } } } transition.onPublished?.() diff --git a/src/main/claude/claude-message-journaling.ts b/src/main/claude/claude-message-journaling.ts index 7844c2b83fee..7741d2dbf4af 100644 --- a/src/main/claude/claude-message-journaling.ts +++ b/src/main/claude/claude-message-journaling.ts @@ -6,7 +6,7 @@ // read off an explicit context, so the open turn and the collaborators it // writes through stay owned by the translator. -import { resolveClaudeTerminalOwner, writeClaudeTerminalFailure } from './claude-terminal-failure' +import { queueClaudeTerminalFailure, 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' @@ -107,22 +107,21 @@ export function journalClaudeMessage( ? { 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') - const owner = terminal ? resolveClaudeTerminalOwner(ctx.sink, ctx.turn, message) : undefined - if (owner === null) { - return true + // The existing opener establishes first output; a failed closed turn cannot reopen here. + if (envelope.role === 'assistant' && (!terminal || !ctx.turn.isOpen) && + (messageBody || typeof message.api_error === 'string' || message.error === 'rate_limit')) { + openOutputTurn() } - if (owner?.identity && !owner.current) { + if (terminal && !ctx.turn.ownsTerminal(message)) { const body = ctx.usageLimits.assistant(message) ?? messageBody ?? ordinaryFailure - if (body) { - writeClaudeTerminalFailure(ctx.sink, owner.identity, body) - } + queueClaudeTerminalFailure(ctx.sink, ctx.turn, message, body, () => { + if (body) { + ctx.sink.appendItem(claudeMessageIdentity(envelope), body, { turnScope: { kind: 'thread' }, observedAt }) + ctx.sink.publish() + } + }) return true } - // A refusal needs its owning turn before the canonical write; empty placeholders open nothing. - 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) ?? diff --git a/src/main/claude/claude-open-turn.ts b/src/main/claude/claude-open-turn.ts index b1cd17041b48..70cd589c3470 100644 --- a/src/main/claude/claude-open-turn.ts +++ b/src/main/claude/claude-open-turn.ts @@ -23,6 +23,7 @@ import type { ClaudeCommandTurn } from './claude-command-turn' import { createClaudeTurnOpener, type ClaudeTurnSource } from './claude-turn-opening' import { finalizeClaudeTerminalTurn } from './claude-terminal-failure' import type { ClaudeUsageLimitEvidence } from './claude-usage-limits' +import { claudeText } from './claude-structured-item-translation' import type { ClaudeStartedSend } from './claude-structured-session-state' export type ClaudeOpenTurnDeps = { @@ -37,6 +38,7 @@ export type ClaudeOpenTurnDeps = { export class ClaudeOpenTurn { private current: ClaudeCurrentTurn | null = null + private cursorGeneration = 0 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 @@ -69,6 +71,17 @@ export class ClaudeOpenTurn { }) } + get generation(): number { + return this.cursorGeneration + } + + ownsTerminal(frame: Record): boolean { + const stamp = claudeText(frame.user_message_uuid) + const input = this.current?.command?.sentUuid ?? this.current?.inputUuid + return this.current !== null && + (!stamp || !input || stamp === input || (Array.isArray(frame.user_message_uuids) && frame.user_message_uuids.includes(input))) + } + get id(): string | null { return this.current?.turnId ?? null } @@ -132,6 +145,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.cursorGeneration += 1 this.usageLimitEvidence = null this.deps.onOpen?.() if (this.current) { @@ -151,6 +165,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.cursorGeneration += 1 this.usageLimitEvidence = null this.deps.onOpen?.() if (this.current) { @@ -195,6 +210,7 @@ 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 { + this.cursorGeneration += 1 // Every settle is a provider cycle ending (result, idle, child exit). this.cycleWorkObserved = false this.usageLimitEvidence = null diff --git a/src/main/claude/claude-result-journaling.ts b/src/main/claude/claude-result-journaling.ts index bed9412401dc..09187142b21a 100644 --- a/src/main/claude/claude-result-journaling.ts +++ b/src/main/claude/claude-result-journaling.ts @@ -4,10 +4,8 @@ // 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 { agentJournalItemKey } from '../../shared/agent-session-journal-item-key' import { - claudeTerminalFailureIdentity, - resolveClaudeTerminalOwner, + queueClaudeTerminalFailure, writeClaudeTerminalFailure } from './claude-terminal-failure' import type { ClaudeContextFacts } from './claude-context-facts' @@ -63,18 +61,17 @@ export function journalClaudeResult( // diagnostic below still runs: a child's failure is reportable even when // it ends no turn. const settlesTurn = isRootClaudeFrame(message) - const owner = settlesTurn ? resolveClaudeTerminalOwner(sink, turn, message) : undefined - if (owner === null) { - return - } - if (owner?.identity && !owner.current) { - const failureIdentity = claudeTerminalFailureIdentity(agentJournalItemKey(owner.identity)) - const prior = sink.journalItems?.()?.itemBody(agentJournalItemKey(failureIdentity)) - const usageLimit = prior?.kind === 'status' && prior.failure?.kind === 'usageLimitReached' - ? usageLimits.result(message, claudeResultFailure(message, false) !== null, { cause: 'quota' }) : null - if (usageLimit) { - writeClaudeTerminalFailure(sink, owner.identity, usageLimit) - } + if (settlesTurn && !turn.ownsTerminal(message)) { + const failure = claudeResultFailure(message) + const body = usageLimits.result(message, failure !== null, { cause: 'quota' }) + queueClaudeTerminalFailure(sink, turn, message, body, () => { + const kind = claudeProviderFrameKind(message) + if (failure || !isSettledClaudeResultKind(kind)) { + providerFallback.append(kind, message, failure?.text, undefined, + { reportsFailure: failure !== null }, + () => ({ turnScope: { kind: 'thread' }, observedAt })) + } + }) return } const commandEnd = settlesTurn ? claudeCommandResultEnd(turn, sink, message, observedAt) : null diff --git a/src/main/claude/claude-terminal-failure.ts b/src/main/claude/claude-terminal-failure.ts index 21a5050f2b7a..e78eee400d40 100644 --- a/src/main/claude/claude-terminal-failure.ts +++ b/src/main/claude/claude-terminal-failure.ts @@ -11,7 +11,11 @@ import { isRootAgentJournalItem } from '../../shared/agent-session-journal-produ import { readAgentSessionFailureFact, providerDiagnostic } from '../../shared/agent-session-failure' import { agentSessionFailureWords } from '../../shared/agent-session-failure-words' import { latestNativeChatTurnSinceRequest } from '../../shared/native-chat-orca-stop-cut' -import type { StructuredAgentSessionEventSink } from '../native-chat/agent-session-wire/structured-agent-session-event-sink' +import type { StructuredAgentSessionTransitionJournal } from '../native-chat/agent-session-wire/structured-agent-session-transition' +import type { + StructuredAgentSessionEventSink, + StructuredAgentSessionRevisionJournal +} from '../native-chat/agent-session-wire/structured-agent-session-event-sink' import { agentJournalTurnRowReservedBytes, resolveAgentJournalTurnRowWrite, @@ -25,8 +29,9 @@ export function claudeTerminalFailureIdentity(turnItemId: string): AgentJournalI return { provider: 'orca', clientMessageId: `terminal-failure:claude:${turnItemId}` } } -function latestClosedWork(sink: StructuredAgentSessionEventSink): AgentJournalRenderItem | null { - const journal = sink.journalItems?.() +function latestClosedWork( + journal: StructuredAgentSessionTransitionJournal | null | undefined +): AgentJournalRenderItem | null { if (!journal) { return null } @@ -42,12 +47,11 @@ function latestClosedWork(sink: StructuredAgentSessionEventSink): AgentJournalRe } // Historical correlation wins over a newer cursor; unknown accepted work keeps its diagnostic. -export function resolveClaudeTerminalOwner( - sink: StructuredAgentSessionEventSink, - turn: ClaudeOpenTurn, +function resolveClaudeTerminalOwner( + journal: StructuredAgentSessionTransitionJournal, + suppressed: boolean, frame: Record -): { identity: AgentJournalItemIdentity | null; current: boolean } | null { - const journal = sink.journalItems?.() +): AgentJournalItemIdentity | null | undefined { const sessionId = claudeText(frame.session_id) const stamp = claudeText(frame.user_message_uuid) const uuid = stamp ?? (frame.type === 'assistant' ? claudeText(frame.uuid) : null) @@ -76,18 +80,12 @@ export function resolveClaudeTerminalOwner( } } if (owner) { - return { - identity: parseAgentJournalItemKey(owner.itemId), - current: owner.itemId === (turn.identity && agentJournalItemKey(turn.identity)) - } - } - if (turn.identity) { - return { identity: turn.identity, current: true } + return parseAgentJournalItemKey(owner.itemId) } - if (turn.isReopenSuppressed && latestClosedWork(sink)) { + if (suppressed && latestClosedWork(journal)) { return null } - return { identity: null, current: false } + return undefined } export function writeClaudeTerminalFailure( @@ -105,24 +103,82 @@ export function writeClaudeTerminalFailure( return } const reservedBytes = Buffer.byteLength(JSON.stringify({ failureIdentity, body }), 'utf8') + 8192 - revise.call(sink, reservedBytes, (journal) => { - 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 } - }, options) + 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 } +} + +// Cursor-less and positively different work wait for preceding ownership writes, never for a new cursor. +export function queueClaudeTerminalFailure( + sink: StructuredAgentSessionEventSink, + turn: ClaudeOpenTurn, + frame: Record, + body: AgentJournalItemBody | null, + fallback: () => void +): void { + const generation = turn.generation + const cursorless = !turn.isOpen + const suppressed = turn.isReopenSuppressed + let unowned = false + const finish = (): void => { + if (unowned) { + fallback() + if (cursorless && turn.generation === generation && frame.type === 'result') { + turn.suppressReopenOnFailure(frame.is_error === true) + } + } + } + if (!sink.tryAppendTransition) { + unowned = true + finish() + return + } + sink.tryAppendTransition({ + lifecycle: true, + publish: true, + steps: [{ + kind: 'item', + reservedBytes: Buffer.byteLength(JSON.stringify({ frame, body }), 'utf8') + 8192, + options: { turnScope: { kind: 'thread' } }, + resolve: (journal) => { + const identity = resolveClaudeTerminalOwner(journal, suppressed, frame) + unowned = identity === undefined + if (!identity || !body) { + return null + } + const turnItemId = agentJournalItemKey(identity) + const prior = journal.itemBody(agentJournalItemKey(claudeTerminalFailureIdentity(turnItemId))) + if (frame.type === 'result' && !(prior?.kind === 'status' && prior.failure?.kind === 'usageLimitReached')) { + return null + } + const merged = mergeClaudeTerminalFailure(journal, identity, body) + return merged ? { ...merged, turnScope: { kind: 'turn', turnItemId } as const } : null + } + }], + onPublished: finish + }) } // Every ending reads its own quota fact after preceding assistant writes have landed. @@ -132,41 +188,34 @@ export function finalizeClaudeTerminalTurn( write: AgentJournalTurnRowWrite, turn: ClaudeOpenTurn ): boolean { - if (!sink.tryAppendTransition || !write.lifecycle) { + 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) let failed = false - sink.tryAppendTransition({ - lifecycle: true, - publish: true, - steps: [{ - kind: 'item', reservedBytes, options: { turnScope: { kind: 'thread' } }, - resolve: (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 = lifecycle.outcome ?? (quota ? (stopped ? 'cancellation' : 'failure') : undefined) - failed = outcome === 'failure' - return resolveAgentJournalTurnRowWrite(journal, target, { - ...write, lifecycle: { ...lifecycle, ...(outcome ? { outcome } : {}) } - }, reservedBytes) - } - }], - onPublished: () => { - const current = turn.identity - if ( - failed && (!current || agentJournalItemKey(current) === agentJournalItemKey(identity)) && - latestClosedWork(sink)?.itemId === agentJournalItemKey(identity) - ) { - turn.suppressReopenOnFailure(true) - } + 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 + failed = outcome === 'failure' + return resolveAgentJournalTurnRowWrite(journal, target, { + ...write, lifecycle: { ...lifecycle, ...(outcome ? { outcome } : {}) } + }, reservedBytes) + }, { turnScope: { kind: 'thread' } }, () => { + const current = turn.identity + if ( + failed && (!current || agentJournalItemKey(current) === agentJournalItemKey(identity)) && + latestClosedWork(sink.journalItems?.())?.itemId === agentJournalItemKey(identity) + ) { + turn.suppressReopenOnFailure(true) } }) return true diff --git a/src/main/claude/claude-turn-lifecycle-item.ts b/src/main/claude/claude-turn-lifecycle-item.ts index be2433bcd15e..0850bb8416db 100644 --- a/src/main/claude/claude-turn-lifecycle-item.ts +++ b/src/main/claude/claude-turn-lifecycle-item.ts @@ -11,6 +11,8 @@ import type { ClaudeCommandTurn } from './claude-command-turn' export type ClaudeCurrentTurn = { sessionId: string + /** Live correlation can precede the user echo that supplies the durable association. */ + inputUuid?: string turnId: string startedAt: number /** Host clock at the send that opened the turn; absent when the provider diff --git a/src/main/claude/claude-turn-opening.ts b/src/main/claude/claude-turn-opening.ts index 77c1de53cb7d..4add8119618d 100644 --- a/src/main/claude/claude-turn-opening.ts +++ b/src/main/claude/claude-turn-opening.ts @@ -45,6 +45,7 @@ export function claudeTurnOpenedBySendEcho( input.frame.parent_tool_use_id === null ? { sessionId: envelope.sessionId, + inputUuid: envelope.uuid, turnId: envelope.uuid, startedAt: input.observedAt, ...(input.requestedAt === undefined ? {} : { requestedAt: input.requestedAt }), @@ -113,9 +114,11 @@ export function createClaudeTurnOpener(deps: { if ((!send && deps.isSuppressed()) || deps.isTurnOpen()) { return } + const inputUuid = claudeText(frame.user_message_uuid) deps.open( { sessionId: source.sessionId, + ...(inputUuid ? { inputUuid } : {}), turnId: source.uuid, startedAt: observedAt, ...(send?.requestedAt === undefined ? {} : { requestedAt: send.requestedAt }), diff --git a/src/main/claude/claude-usage-limits.test.ts b/src/main/claude/claude-usage-limits.test.ts index 81db051d47ef..11f23355cd05 100644 --- a/src/main/claude/claude-usage-limits.test.ts +++ b/src/main/claude/claude-usage-limits.test.ts @@ -22,7 +22,7 @@ const refusedFrame = (uuid: string, at: number, text: string) => { type: 'assistant', uuid, - user_message_uuid: `ask-${uuid}`, + user_message_uuid: `turn-${uuid}`, error: 'rate_limit', is_api_error_message: true, message: { role: 'assistant', content: [{ type: 'text', text }] } @@ -38,7 +38,7 @@ const failedResult = (uuid: string, at: number, text: string) => is_error: true, result: text, uuid: `result-${uuid}`, - user_message_uuid: `ask-${uuid}`, + user_message_uuid: `turn-${uuid}`, duration_ms: 10 }, at @@ -65,7 +65,7 @@ describe('a Claude usage limit', () => { const t = setup() t.handle(userFrame('turn-a', 1_000)) t.handle(rateLimitEvent('rejected', 1_100)) - t.handle(frame({ ...assistantFrame('first', 1_150, 20).message, user_message_uuid: 'ask-a' }, 1_150)) + 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, @@ -98,11 +98,11 @@ describe('a Claude usage limit', () => { it('keeps typed other causes and replacement turns separate from the account snapshot', () => { const t = setup() - t.handle(userFrame('limited', 1_000)) + 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('credits', 2_000)) + 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' @@ -120,13 +120,13 @@ describe('a Claude usage limit', () => { const clock = vi.spyOn(Date, 'now').mockReturnValue(RESETS_AT_S * 1000 - 1000) try { const t = setup() - t.handle(userFrame('typed', 1000)) + 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('expired', 2000)) + 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') @@ -160,22 +160,25 @@ const quota = (uuid: string, stamp?: string) => frame({ }, 1100) it.each([false, true])('reconciles replay and late detail without touching newer work (provider-opened %s)', (providerOpened) => { - const t = setup() + const t = setup({ deferred: true }) if (!providerOpened) { t.handle(userFrame('owner', 1000)) } const refusal = quota('owner', providerOpened ? undefined : 'owner') t.handle(refusal) t.handle(frame({ ...failedResult('owner', 1200, LIMIT_TEXT).message, user_message_uuid: 'owner' }, 1200)) - const endpoints = t.items().filter((item) => item.body.kind === 'turn') - const warning = t.items().find((item) => item.body.kind === 'status') t.handle(refusal) t.handle(frame({ ...failedResult('owner', 1300, LIMIT_TEXT).message, user_message_uuid: 'owner' }, 1300)) - expect(statusRows(t)).toHaveLength(1) - expect(t.items().find((item) => item.body.kind === 'status')).toEqual(warning) - expect(t.items().filter((item) => item.body.kind === 'turn')).toEqual(endpoints) t.handle(userFrame('newer', 2000)) - t.handle(refusal) - t.handle(frame({ ...failedResult('owner', 2200, 'New provider explanation').message, user_message_uuid: 'owner' }, 2200)) + const stampedReplay = frame({ ...refusal.message, user_message_uuid: 'owner' }, 2100) + t.handle(stampedReplay) + t.handle(frame({ ...failedResult('owner', 2200, LIMIT_TEXT).message, user_message_uuid: 'owner' }, 2200)) + t.flush() + expect(statusRows(t)).toHaveLength(1) + expect(t.items().find((item) => item.body.kind === 'status')?.revision).toBe(1) expect(t.translator.currentTurnId).toBe('newer') + const endpoints = t.items().filter((item) => item.body.kind === 'turn') + t.handle(frame({ ...failedResult('owner', 2300, 'New provider explanation').message, user_message_uuid: 'owner' }, 2300)) + t.flush() + expect(t.items().filter((item) => item.body.kind === 'turn')).toEqual(endpoints) expect(t.turnRow('newer')?.body).toMatchObject({ state: 'running' }) expect(statusRows(t)).toHaveLength(1) expect(statusRows(t)[0]?.failure?.detail?.text).toContain('New provider explanation') @@ -214,7 +217,7 @@ it.each(['before', 'after', 'child', 'ordinary', 'success', 'other', 'superseded } if (mode === 'other') { t.handle(frame({ ...refusedFrame('other', 1150, 'Requires credits').message, - api_error: 'model_requires_usage_credits' }, 1150)) + api_error: 'model_requires_usage_credits', user_message_uuid: 'owner' }, 1150)) } const stopAt = mode === 'before' ? 1150 : 1300 t.sink.journalStopDecidesTurn = (_turnId, endAt) => diff --git a/src/main/native-chat/agent-session-journal/journal-item-appender.ts b/src/main/native-chat/agent-session-journal/journal-item-appender.ts index c3b7d65c0a38..ce0e1bd25f88 100644 --- a/src/main/native-chat/agent-session-journal/journal-item-appender.ts +++ b/src/main/native-chat/agent-session-journal/journal-item-appender.ts @@ -1,7 +1,8 @@ import { agentJournalItemKey } from '../../../shared/agent-session-journal-item-key' import type { AgentJournalItemBody, - AgentJournalItemIdentity + AgentJournalItemIdentity, + AgentJournalTurnScope } from '../../../shared/agent-session-journal-types' import { journalItemRowBuilder } from './journal-row-builders' import type { JournalReducerState } from './journal-reducer' @@ -12,7 +13,11 @@ import type { JournalOperationReceipt } from './journal-row-writer' // A module-level Error's lazy stack retains the bundle's startup code and read buffer. class NothingResolvedError extends Error {} -export type JournalResolvedItem = { identity: AgentJournalItemIdentity; body: AgentJournalItemBody } +export type JournalResolvedItem = { + identity: AgentJournalItemIdentity + body: AgentJournalItemBody + turnScope?: AgentJournalTurnScope +} export class JournalItemAppender { constructor( diff --git a/src/main/native-chat/agent-session-journal/journal-step-writer.ts b/src/main/native-chat/agent-session-journal/journal-step-writer.ts index c0b62ce50c4c..9309b80ef410 100644 --- a/src/main/native-chat/agent-session-journal/journal-step-writer.ts +++ b/src/main/native-chat/agent-session-journal/journal-step-writer.ts @@ -53,6 +53,8 @@ export class JournalStepWriter { const resolved = step.resolve() return resolved === null ? [] - : [journalItemRowBuilder(this.deps.state, resolved.identity, resolved.body, step.options)] + : [journalItemRowBuilder(this.deps.state, resolved.identity, resolved.body, { + ...step.options, ...(resolved.turnScope ? { turnScope: resolved.turnScope } : {}) + })] } } 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 a533b38f22ca..9f94f44829dd 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 @@ -69,7 +69,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. */ @@ -134,7 +134,8 @@ export type StructuredAgentSessionEventSink = StructuredAgentSessionTransitionSi tryReviseResolvedItemAndPublish?( reservedBytes: number, resolve: StructuredAgentSessionRevisionResolver, - options: StructuredAgentSessionRevisionOptions + options: StructuredAgentSessionRevisionOptions, + onPublished?: () => void ): StructuredAgentSessionSinkAdmission /** Queues one journal-derived lifecycle append; a null resolution is a no-op. */ tryAppendLifecycleTransition?( diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-resolved-append.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-resolved-append.ts index d3640db2a0cf..197a2b5f4018 100644 --- a/src/main/native-chat/agent-session-wire/structured-agent-session-resolved-append.ts +++ b/src/main/native-chat/agent-session-wire/structured-agent-session-resolved-append.ts @@ -31,7 +31,7 @@ export function createStructuredAgentSessionResolvedAppend( reservedBytes: number, resolve: (journal: StructuredAgentSessionRevisionJournal) => ResolvedItem | null, options: StructuredAgentSessionItemAppendOptions, - input: { publish: boolean; lifecycle?: true; overflow: string } + input: { publish: boolean; lifecycle?: true; overflow: string; onPublished?: () => void } ) => queue.submit( { @@ -55,6 +55,7 @@ export function createStructuredAgentSessionResolvedAppend( ) if (landed !== null && input.publish) { bound.publish() + input.onPublished?.() } } }, @@ -77,8 +78,8 @@ export function createStructuredAgentSessionResolvedAppend( tryAppendResolvedItemAndPublish: identityOnly(true), tryReviseResolvedItem: (reservedBytes, resolve, options) => submit(reservedBytes, resolve, options, { publish: false, overflow: ITEM_OVERFLOW }), - tryReviseResolvedItemAndPublish: (reservedBytes, resolve, options) => - submit(reservedBytes + 1, resolve, options, { publish: true, overflow: ITEM_OVERFLOW }), + tryReviseResolvedItemAndPublish: (reservedBytes, resolve, options, onPublished) => + submit(reservedBytes + 1, resolve, options, { publish: true, overflow: ITEM_OVERFLOW, onPublished }), tryAppendLifecycleTransition: (identitySizeBound, body, resolveIdentity, options) => submit( estimateStructuredAgentSessionItemBytes(identitySizeBound, body), diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-transition.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-transition.ts index 084f98b0a5d6..9d049e0b84db 100644 --- a/src/main/native-chat/agent-session-wire/structured-agent-session-transition.ts +++ b/src/main/native-chat/agent-session-wire/structured-agent-session-transition.ts @@ -10,7 +10,8 @@ import type { AgentJournalItemBody, - AgentJournalItemIdentity + AgentJournalItemIdentity, + AgentJournalTurnScope } from '../../../shared/agent-session-journal-types' import type { JournalLifecycleMutationInput } from '../agent-session-journal/journal-row-builders' import type { AgentSessionJournal } from '../agent-session-journal/journal-store' @@ -38,6 +39,7 @@ export type StructuredAgentSessionTransitionStep = resolve: (journal: StructuredAgentSessionTransitionJournal) => { identity: AgentJournalItemIdentity body: AgentJournalItemBody + turnScope?: AgentJournalTurnScope } | null options: StructuredAgentSessionItemAppendOptions } From 5dd097298e9ac0df0b51acf6684f5934679c064d Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Sun, 18 Oct 2026 16:25:57 -0700 Subject: [PATCH 23/34] refactor(native-chat): share tombstone append within the sink line budget --- .../structured-agent-session-event-sink.ts | 27 +++++++------------ 1 file changed, 10 insertions(+), 17 deletions(-) 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 9f94f44829dd..b16e6bbded9b 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 @@ -289,6 +289,14 @@ export function createDeferredStructuredAgentSessionEventSink(deps: { options ) + const appendTombstone: NonNullable = ( + identity, + options = {} + ) => queue.submit({ + bytes: Buffer.byteLength(agentJournalItemKey(identity), 'utf8') + 256, + run: (bound) => bound.journal.appendTombstone(identity, { fence: bound.fence }) + }, options) + return { exitObservation: () => exit, sink: { @@ -313,23 +321,8 @@ export function createDeferredStructuredAgentSessionEventSink(deps: { }, tryAppendLifecycleBatch: appendLifecycleBatch, bindReadingControl: (control) => queue.bindReadingControl(control), - appendTombstone: (identity, options = {}) => { - queue.submit( - { - bytes: Buffer.byteLength(agentJournalItemKey(identity), 'utf8') + 256, - run: (bound) => bound.journal.appendTombstone(identity, { fence: bound.fence }) - }, - options - ) - }, - tryAppendTombstone: (identity, options = {}) => - queue.submit( - { - bytes: Buffer.byteLength(agentJournalItemKey(identity), 'utf8') + 256, - run: (bound) => bound.journal.appendTombstone(identity, { fence: bound.fence }) - }, - options - ), + appendTombstone: (identity, options) => void appendTombstone(identity, options), + tryAppendTombstone: appendTombstone, publish: (options = {}) => void publish(options), written: queue.written, setActivity: (activity) => { From aab312ea6b801ed1914fc37fd94647e8815c75e8 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Sun, 18 Oct 2026 16:26:37 -0700 Subject: [PATCH 24/34] fix(claude): retain both input and echo correlation on the live turn --- src/main/claude/claude-open-turn.ts | 4 +++- src/main/claude/claude-turn-opening.ts | 2 +- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/src/main/claude/claude-open-turn.ts b/src/main/claude/claude-open-turn.ts index 70cd589c3470..5e55d9431573 100644 --- a/src/main/claude/claude-open-turn.ts +++ b/src/main/claude/claude-open-turn.ts @@ -78,8 +78,10 @@ export class ClaudeOpenTurn { ownsTerminal(frame: Record): boolean { const stamp = claudeText(frame.user_message_uuid) const input = this.current?.command?.sentUuid ?? this.current?.inputUuid + const inputs = frame.user_message_uuids return this.current !== null && - (!stamp || !input || stamp === input || (Array.isArray(frame.user_message_uuids) && frame.user_message_uuids.includes(input))) + (!stamp || !input || stamp === input || stamp === this.current.turnId || + (Array.isArray(inputs) && (inputs.includes(input) || inputs.includes(this.current.turnId)))) } get id(): string | null { diff --git a/src/main/claude/claude-turn-opening.ts b/src/main/claude/claude-turn-opening.ts index 4add8119618d..b9b6c9edcb6f 100644 --- a/src/main/claude/claude-turn-opening.ts +++ b/src/main/claude/claude-turn-opening.ts @@ -45,7 +45,7 @@ export function claudeTurnOpenedBySendEcho( input.frame.parent_tool_use_id === null ? { sessionId: envelope.sessionId, - inputUuid: envelope.uuid, + inputUuid: claudeText(input.frame.user_message_uuid) ?? envelope.uuid, turnId: envelope.uuid, startedAt: input.observedAt, ...(input.requestedAt === undefined ? {} : { requestedAt: input.requestedAt }), From aebb7ec20a3e4ef72b80eaf2c0bbc60865cdc539 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Sun, 18 Oct 2026 16:38:26 -0700 Subject: [PATCH 25/34] fix(claude): preserve unowned result completion after terminal resolution --- src/main/claude/claude-result-journaling.ts | 66 ++++++++++----------- src/main/claude/claude-terminal-failure.ts | 5 +- 2 files changed, 34 insertions(+), 37 deletions(-) diff --git a/src/main/claude/claude-result-journaling.ts b/src/main/claude/claude-result-journaling.ts index 09187142b21a..affeab73ce59 100644 --- a/src/main/claude/claude-result-journaling.ts +++ b/src/main/claude/claude-result-journaling.ts @@ -17,7 +17,7 @@ import { claudeResultFailure, isSettledClaudeResultKind } from './claude-structured-provider-fallback' -import { claudeTurnEndForResult } from './claude-turn-lifecycle-item' +import { claudeTurnEndForResult, type ClaudeTurnEnd } from './claude-turn-lifecycle-item' import { claudeFrameParentRef, isRootClaudeFrame } from './claude-turn-opening' import type { ClaudeGoalBackgroundWork } from './claude-background-task-tracker' @@ -61,6 +61,34 @@ export function journalClaudeResult( // diagnostic below still runs: a child's failure is reportable even when // it ends no turn. const settlesTurn = isRootClaudeFrame(message) + const endedTurnScope = turn.turnScope + const endedTurnIdentity = turn.identity + const usageEvidence = turn.usageLimitEvidence + const endedTurnStartedAt = turn.startedAt + const turnId = settlesTurn ? turn.id : null + const leftToStop = turnId !== null && sink.journalStopDecidesTurn?.(turnId, observedAt) === true + const complete = (commandEnd?: ClaudeTurnEnd | null): void => { + if (settlesTurn) { + turn.suppressReopenOnFailure(message.is_error === true) + corrections.abandon() + context.settle(message, commandEnd ?? claudeTurnEndForResult(message, observedAt, leftToStop)) + streamedBlocks.clear() + streamedText.settle() + } + const goal = threadGoal.settle(message, { + backgroundWork: goalBackgroundWork(), + stoppedByPerson: leftToStop, + turnStartedAt: endedTurnStartedAt + }, observedAt) + if (goal) { + sink.appendItem(goal.identity, goal.body, { turnScope: endedTurnScope }) + sink.publish() + } + } + // An owed prompt resolution is independent of which turn owns this result. + if (settlesTurn) { + prompts.retryPendingCancellations() + } if (settlesTurn && !turn.ownsTerminal(message)) { const failure = claudeResultFailure(message) const body = usageLimits.result(message, failure !== null, { cause: 'quota' }) @@ -71,51 +99,19 @@ export function journalClaudeResult( { reportsFailure: failure !== null }, () => ({ turnScope: { kind: 'thread' }, observedAt })) } - }) + }, () => complete()) return } 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 const failure = claudeResultFailure(message, leftToStop) const usageLimit = settlesTurn ? usageLimits.result(message, failure !== null, usageEvidence) : null if (usageLimit && endedTurnIdentity) { writeClaudeTerminalFailure(sink, endedTurnIdentity, usageLimit) } - if (settlesTurn) { - prompts.retryPendingCancellations() - 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 - ) - if (goal) { - sink.appendItem(goal.identity, goal.body, { turnScope: endedTurnScope }) - sink.publish() - } + complete(commandEnd) const kind = claudeProviderFrameKind(message) if (usageLimit && endedTurnIdentity) { return diff --git a/src/main/claude/claude-terminal-failure.ts b/src/main/claude/claude-terminal-failure.ts index e78eee400d40..02284fabe38a 100644 --- a/src/main/claude/claude-terminal-failure.ts +++ b/src/main/claude/claude-terminal-failure.ts @@ -136,7 +136,8 @@ export function queueClaudeTerminalFailure( turn: ClaudeOpenTurn, frame: Record, body: AgentJournalItemBody | null, - fallback: () => void + fallback: () => void, + completeUnowned?: () => void ): void { const generation = turn.generation const cursorless = !turn.isOpen @@ -146,7 +147,7 @@ export function queueClaudeTerminalFailure( if (unowned) { fallback() if (cursorless && turn.generation === generation && frame.type === 'result') { - turn.suppressReopenOnFailure(frame.is_error === true) + completeUnowned?.() } } } From 8f69aa7c4c4abfb13c0b1e1d7a8267d9d2fcc8fa Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Sun, 18 Oct 2026 16:43:13 -0700 Subject: [PATCH 26/34] fix(claude): allow unassociated successful goal completion --- src/main/claude/claude-terminal-failure.ts | 2 +- src/main/claude/claude-thread-goal-journaling.test.ts | 7 +++++-- 2 files changed, 6 insertions(+), 3 deletions(-) diff --git a/src/main/claude/claude-terminal-failure.ts b/src/main/claude/claude-terminal-failure.ts index 02284fabe38a..1fd14d657906 100644 --- a/src/main/claude/claude-terminal-failure.ts +++ b/src/main/claude/claude-terminal-failure.ts @@ -82,7 +82,7 @@ function resolveClaudeTerminalOwner( if (owner) { return parseAgentJournalItemKey(owner.itemId) } - if (suppressed && latestClosedWork(journal)) { + if (suppressed && (frame.type !== 'result' || frame.is_error === true) && latestClosedWork(journal)) { return null } return undefined diff --git a/src/main/claude/claude-thread-goal-journaling.test.ts b/src/main/claude/claude-thread-goal-journaling.test.ts index 07fffc8e32ba..02e18406a531 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' @@ -17,11 +18,12 @@ function goalSink( journalGoal: AgentJournalThreadGoal | null = null, journalRow?: { identity: AgentJournalItemIdentity; body: AgentJournalItemBody } ) { - const rows: { identity: AgentJournalItemIdentity; body: AgentJournalItemBody }[] = [] + const state = journal() + 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 +48,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', From edda62550cd5fbe394abf08b57dd9ac26c458b15 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Sun, 18 Oct 2026 17:33:45 -0700 Subject: [PATCH 27/34] fix(claude): keep terminal completion on the live turn --- .../claude-context-usage-test-support.ts | 32 ++-- src/main/claude/claude-message-journaling.ts | 15 +- src/main/claude/claude-open-turn.ts | 34 +---- src/main/claude/claude-result-journaling.ts | 57 +++---- .../claude-structured-journal-translation.ts | 5 +- src/main/claude/claude-terminal-failure.ts | 143 +----------------- .../claude-thread-goal-journaling.test.ts | 14 +- src/main/claude/claude-turn-lifecycle-item.ts | 2 - src/main/claude/claude-turn-opening.ts | 3 - src/main/claude/claude-usage-limits.test.ts | 53 ++----- .../journal-item-appender.ts | 9 +- .../journal-step-writer.ts | 4 +- .../structured-agent-session-event-sink.ts | 3 +- ...tructured-agent-session-resolved-append.ts | 7 +- .../structured-agent-session-transition.ts | 6 +- 15 files changed, 78 insertions(+), 309 deletions(-) diff --git a/src/main/claude/claude-context-usage-test-support.ts b/src/main/claude/claude-context-usage-test-support.ts index a660c3ab3e54..659c01c45910 100644 --- a/src/main/claude/claude-context-usage-test-support.ts +++ b/src/main/claude/claude-context-usage-test-support.ts @@ -11,7 +11,8 @@ import type { StructuredAgentSessionEventSink, StructuredAgentSessionRevisionJournal } from '../native-chat/agent-session-wire/structured-agent-session-event-sink' -import type { StructuredAgentSessionTransitionJournal } from '../native-chat/agent-session-wire/structured-agent-session-transition' +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' @@ -40,11 +41,8 @@ export function journal({ deferred = false } = {}) { }) } const scans = { count: 0 } - const bound: StructuredAgentSessionRevisionJournal & StructuredAgentSessionTransitionJournal = { + const bound: StructuredAgentSessionRevisionJournal = { item: (itemId) => rows.get(itemId) ?? null, - canonicalItemId: (itemId) => itemId, - submissions: () => [], - visitItemsWithLinkage: (visit) => { for (const row of rows.values()) { visit(row.itemId, row.sequence, row.body, row) } }, epoch: 'test', visitItems: (visit) => { scans.count += 1 @@ -57,31 +55,21 @@ export function journal({ deferred = false } = {}) { const revise: NonNullable = ( _reservedBytes, resolve, - options, - onPublished + options ) => { run(() => { const resolved = resolve(bound) if (resolved) { appendItem(resolved.identity, resolved.body, options) } - onPublished?.() }) 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 = { + journalStopDecidesTurn: (turnId, at) => personStopDecidesTurn(stopState, turnId, at), appendItem: (...args) => run(() => appendItem(...args)), - journalItems: () => bound, - tryAppendTransition: (transition) => { - run(() => { - for (const step of transition.steps) { - if (step.kind === 'item') { - const resolved = step.resolve(bound) - if (resolved) { appendItem(resolved.identity, resolved.body, { ...step.options, turnScope: resolved.turnScope ?? step.options.turnScope }) } - } - } - transition.onPublished?.() - }) - return { accepted: true } - }, tryReviseResolvedItem: revise, tryReviseResolvedItemAndPublish: revise, appendTombstone: () => {}, @@ -90,7 +78,7 @@ export function journal({ deferred = false } = {}) { 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, flush } + return { sink, clock, appends, rows, turnRow, items, scans, flush, queueStop } } export function frame(message: Record, observedAt: number, startsTurn = false) { diff --git a/src/main/claude/claude-message-journaling.ts b/src/main/claude/claude-message-journaling.ts index 7741d2dbf4af..d8b296490157 100644 --- a/src/main/claude/claude-message-journaling.ts +++ b/src/main/claude/claude-message-journaling.ts @@ -6,7 +6,7 @@ // read off an explicit context, so the open turn and the collaborators it // writes through stay owned by the translator. -import { queueClaudeTerminalFailure, writeClaudeTerminalFailure } from './claude-terminal-failure' +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' @@ -107,21 +107,10 @@ export function journalClaudeMessage( ? { 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') - // The existing opener establishes first output; a failed closed turn cannot reopen here. - if (envelope.role === 'assistant' && (!terminal || !ctx.turn.isOpen) && + if (envelope.role === 'assistant' && (messageBody || typeof message.api_error === 'string' || message.error === 'rate_limit')) { openOutputTurn() } - if (terminal && !ctx.turn.ownsTerminal(message)) { - const body = ctx.usageLimits.assistant(message) ?? messageBody ?? ordinaryFailure - queueClaudeTerminalFailure(ctx.sink, ctx.turn, message, body, () => { - if (body) { - ctx.sink.appendItem(claudeMessageIdentity(envelope), body, { turnScope: { kind: 'thread' }, observedAt }) - ctx.sink.publish() - } - }) - return true - } const usageLimit = ctx.usageLimits.assistant(message, ctx.turn) const body = ctx.authenticationFailures.assistant(message) ?? diff --git a/src/main/claude/claude-open-turn.ts b/src/main/claude/claude-open-turn.ts index 5e55d9431573..2e972efdcc86 100644 --- a/src/main/claude/claude-open-turn.ts +++ b/src/main/claude/claude-open-turn.ts @@ -21,9 +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 { finalizeClaudeTerminalTurn } from './claude-terminal-failure' +import { refineClaudeQuotaTurnEnd } from './claude-terminal-failure' import type { ClaudeUsageLimitEvidence } from './claude-usage-limits' -import { claudeText } from './claude-structured-item-translation' import type { ClaudeStartedSend } from './claude-structured-session-state' export type ClaudeOpenTurnDeps = { @@ -38,7 +37,6 @@ export type ClaudeOpenTurnDeps = { export class ClaudeOpenTurn { private current: ClaudeCurrentTurn | null = null - private cursorGeneration = 0 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 @@ -71,19 +69,6 @@ export class ClaudeOpenTurn { }) } - get generation(): number { - return this.cursorGeneration - } - - ownsTerminal(frame: Record): boolean { - const stamp = claudeText(frame.user_message_uuid) - const input = this.current?.command?.sentUuid ?? this.current?.inputUuid - const inputs = frame.user_message_uuids - return this.current !== null && - (!stamp || !input || stamp === input || stamp === this.current.turnId || - (Array.isArray(inputs) && (inputs.includes(input) || inputs.includes(this.current.turnId)))) - } - get id(): string | null { return this.current?.turnId ?? null } @@ -112,10 +97,6 @@ export class ClaudeOpenTurn { return this.current?.startedAt ?? null } - get isReopenSuppressed(): boolean { - return this.reopenSuppressed - } - get isOpen(): boolean { return this.current !== null } @@ -147,7 +128,6 @@ 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.cursorGeneration += 1 this.usageLimitEvidence = null this.deps.onOpen?.() if (this.current) { @@ -167,7 +147,6 @@ 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.cursorGeneration += 1 this.usageLimitEvidence = null this.deps.onOpen?.() if (this.current) { @@ -212,14 +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 { - this.cursorGeneration += 1 + 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.usageLimitEvidence = null this.current = null } @@ -246,11 +227,12 @@ 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 (end && finalizeClaudeTerminalTurn(this.deps.sink, item.identity, write, this)) { + if (quotaEnd && refineClaudeQuotaTurnEnd(this.deps.sink, item.identity, write)) { return } writeAgentJournalTurnRow( diff --git a/src/main/claude/claude-result-journaling.ts b/src/main/claude/claude-result-journaling.ts index affeab73ce59..74df8eb43b17 100644 --- a/src/main/claude/claude-result-journaling.ts +++ b/src/main/claude/claude-result-journaling.ts @@ -4,10 +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 { - queueClaudeTerminalFailure, - writeClaudeTerminalFailure -} from './claude-terminal-failure' +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' @@ -17,7 +14,7 @@ import { claudeResultFailure, isSettledClaudeResultKind } from './claude-structured-provider-fallback' -import { claudeTurnEndForResult, type ClaudeTurnEnd } from './claude-turn-lifecycle-item' +import { claudeTurnEndForResult } from './claude-turn-lifecycle-item' import { claudeFrameParentRef, isRootClaudeFrame } from './claude-turn-opening' import type { ClaudeGoalBackgroundWork } from './claude-background-task-tracker' @@ -67,41 +64,10 @@ export function journalClaudeResult( const endedTurnStartedAt = turn.startedAt const turnId = settlesTurn ? turn.id : null const leftToStop = turnId !== null && sink.journalStopDecidesTurn?.(turnId, observedAt) === true - const complete = (commandEnd?: ClaudeTurnEnd | null): void => { - if (settlesTurn) { - turn.suppressReopenOnFailure(message.is_error === true) - corrections.abandon() - context.settle(message, commandEnd ?? claudeTurnEndForResult(message, observedAt, leftToStop)) - streamedBlocks.clear() - streamedText.settle() - } - const goal = threadGoal.settle(message, { - backgroundWork: goalBackgroundWork(), - stoppedByPerson: leftToStop, - turnStartedAt: endedTurnStartedAt - }, observedAt) - if (goal) { - sink.appendItem(goal.identity, goal.body, { turnScope: endedTurnScope }) - sink.publish() - } - } - // An owed prompt resolution is independent of which turn owns this result. + // Retry owed prompt cancellations before a command result can return. if (settlesTurn) { prompts.retryPendingCancellations() } - if (settlesTurn && !turn.ownsTerminal(message)) { - const failure = claudeResultFailure(message) - const body = usageLimits.result(message, failure !== null, { cause: 'quota' }) - queueClaudeTerminalFailure(sink, turn, message, body, () => { - const kind = claudeProviderFrameKind(message) - if (failure || !isSettledClaudeResultKind(kind)) { - providerFallback.append(kind, message, failure?.text, undefined, - { reportsFailure: failure !== null }, - () => ({ turnScope: { kind: 'thread' }, observedAt })) - } - }, () => complete()) - return - } const commandEnd = settlesTurn ? claudeCommandResultEnd(turn, sink, message, observedAt) : null if (commandEnd === 'another-input') { return @@ -111,7 +77,22 @@ export function journalClaudeResult( if (usageLimit && endedTurnIdentity) { writeClaudeTerminalFailure(sink, endedTurnIdentity, usageLimit) } - complete(commandEnd) + if (settlesTurn) { + turn.suppressReopenOnFailure(message.is_error === true) + corrections.abandon() + context.settle(message, commandEnd ?? claudeTurnEndForResult(message, observedAt, leftToStop)) + streamedBlocks.clear() + streamedText.settle() + } + 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) if (usageLimit && endedTurnIdentity) { return diff --git a/src/main/claude/claude-structured-journal-translation.ts b/src/main/claude/claude-structured-journal-translation.ts index 8b1eff5a60c1..5232ac200e19 100644 --- a/src/main/claude/claude-structured-journal-translation.ts +++ b/src/main/claude/claude-structured-journal-translation.ts @@ -272,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-terminal-failure.ts b/src/main/claude/claude-terminal-failure.ts index 1fd14d657906..5b7867dd0d85 100644 --- a/src/main/claude/claude-terminal-failure.ts +++ b/src/main/claude/claude-terminal-failure.ts @@ -1,17 +1,11 @@ -import { - agentJournalItemKey, - parseAgentJournalItemKey -} from '../../shared/agent-session-journal-item-key' +import { agentJournalItemKey } from '../../shared/agent-session-journal-item-key' import type { AgentJournalItemBody, - AgentJournalItemIdentity, - AgentJournalRenderItem + 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 { latestNativeChatTurnSinceRequest } from '../../shared/native-chat-orca-stop-cut' -import type { StructuredAgentSessionTransitionJournal } from '../native-chat/agent-session-wire/structured-agent-session-transition' import type { StructuredAgentSessionEventSink, StructuredAgentSessionRevisionJournal @@ -21,73 +15,11 @@ import { resolveAgentJournalTurnRowWrite, type AgentJournalTurnRowWrite } from '../native-chat/agent-session-timeline/agent-journal-turn-row-revision' -import type { ClaudeOpenTurn } from './claude-open-turn' -import { claudeText } from './claude-structured-item-translation' -import { claudeTurnLifecycleIdentity } from './claude-turn-lifecycle-item' export function claudeTerminalFailureIdentity(turnItemId: string): AgentJournalItemIdentity { return { provider: 'orca', clientMessageId: `terminal-failure:claude:${turnItemId}` } } -function latestClosedWork( - journal: StructuredAgentSessionTransitionJournal | null | undefined -): AgentJournalRenderItem | null { - if (!journal) { - return null - } - const items: AgentJournalRenderItem[] = [] - journal.visitItemsWithLinkage((itemId) => { - const item = journal.item(itemId) - if (item) { - items.push(item) - } - }) - items.sort((a, b) => a.sequence - b.sequence) - return latestNativeChatTurnSinceRequest(items, journal.submissions())?.turnItem ?? null -} - -// Historical correlation wins over a newer cursor; unknown accepted work keeps its diagnostic. -function resolveClaudeTerminalOwner( - journal: StructuredAgentSessionTransitionJournal, - suppressed: boolean, - frame: Record -): AgentJournalItemIdentity | null | undefined { - const sessionId = claudeText(frame.session_id) - const stamp = claudeText(frame.user_message_uuid) - const uuid = stamp ?? (frame.type === 'assistant' ? claudeText(frame.uuid) : null) - let owner: AgentJournalRenderItem | null = null - if (journal && sessionId && uuid) { - const candidate = journal.item(agentJournalItemKey(claudeTurnLifecycleIdentity(sessionId, uuid))) - if (candidate?.body.kind === 'turn' && isRootAgentJournalItem(candidate)) { - owner = candidate - } else if (stamp) { - const echo = journal.canonicalItemId( - agentJournalItemKey({ provider: 'claude', sessionId, uuid: stamp }) - ) - journal.visitItemsWithLinkage((itemId, _sequence, body) => { - const identity = parseAgentJournalItemKey(itemId) - if ( - body.kind === 'turn' && body.userItemId && identity?.provider === 'legacy' && - identity.agent === 'claude' && identity.sessionId === sessionId && - journal.canonicalItemId(body.userItemId) === echo - ) { - const candidate = journal.item(itemId) - if (candidate && isRootAgentJournalItem(candidate)) { - owner = candidate - } - } - }) - } - } - if (owner) { - return parseAgentJournalItemKey(owner.itemId) - } - if (suppressed && (frame.type !== 'result' || frame.is_error === true) && latestClosedWork(journal)) { - return null - } - return undefined -} - export function writeClaudeTerminalFailure( sink: StructuredAgentSessionEventSink, identity: AgentJournalItemIdentity, @@ -130,64 +62,11 @@ function mergeClaudeTerminalFailure( ? null : { identity: failureIdentity, body: merged } } -// Cursor-less and positively different work wait for preceding ownership writes, never for a new cursor. -export function queueClaudeTerminalFailure( - sink: StructuredAgentSessionEventSink, - turn: ClaudeOpenTurn, - frame: Record, - body: AgentJournalItemBody | null, - fallback: () => void, - completeUnowned?: () => void -): void { - const generation = turn.generation - const cursorless = !turn.isOpen - const suppressed = turn.isReopenSuppressed - let unowned = false - const finish = (): void => { - if (unowned) { - fallback() - if (cursorless && turn.generation === generation && frame.type === 'result') { - completeUnowned?.() - } - } - } - if (!sink.tryAppendTransition) { - unowned = true - finish() - return - } - sink.tryAppendTransition({ - lifecycle: true, - publish: true, - steps: [{ - kind: 'item', - reservedBytes: Buffer.byteLength(JSON.stringify({ frame, body }), 'utf8') + 8192, - options: { turnScope: { kind: 'thread' } }, - resolve: (journal) => { - const identity = resolveClaudeTerminalOwner(journal, suppressed, frame) - unowned = identity === undefined - if (!identity || !body) { - return null - } - const turnItemId = agentJournalItemKey(identity) - const prior = journal.itemBody(agentJournalItemKey(claudeTerminalFailureIdentity(turnItemId))) - if (frame.type === 'result' && !(prior?.kind === 'status' && prior.failure?.kind === 'usageLimitReached')) { - return null - } - const merged = mergeClaudeTerminalFailure(journal, identity, body) - return merged ? { ...merged, turnScope: { kind: 'turn', turnItemId } as const } : null - } - }], - onPublished: finish - }) -} - -// Every ending reads its own quota fact after preceding assistant writes have landed. -export function finalizeClaudeTerminalTurn( +// Refine only the ending row after its quota and any person Stop have landed. +export function refineClaudeQuotaTurnEnd( sink: StructuredAgentSessionEventSink, identity: AgentJournalItemIdentity, - write: AgentJournalTurnRowWrite, - turn: ClaudeOpenTurn + write: AgentJournalTurnRowWrite ): boolean { const revise = sink.tryReviseResolvedItemAndPublish if (!revise || !write.lifecycle || write.lifecycle.outcome !== undefined) { @@ -196,7 +75,6 @@ export function finalizeClaudeTerminalTurn( const lifecycle = write.lifecycle const target = { identity } const reservedBytes = agentJournalTurnRowReservedBytes(target, write) - let failed = false revise.call(sink, reservedBytes, (journal) => { const itemId = agentJournalItemKey(identity) const row = journal.item(agentJournalItemKey(claudeTerminalFailureIdentity(itemId))) @@ -206,18 +84,9 @@ export function finalizeClaudeTerminalTurn( const stopped = lifecycle.completedAt !== undefined && sink.journalStopDecidesTurn?.(lifecycle.turnId, lifecycle.completedAt) const outcome = quota ? (stopped ? 'cancellation' : 'failure') : undefined - failed = outcome === 'failure' return resolveAgentJournalTurnRowWrite(journal, target, { ...write, lifecycle: { ...lifecycle, ...(outcome ? { outcome } : {}) } }, reservedBytes) - }, { turnScope: { kind: 'thread' } }, () => { - const current = turn.identity - if ( - failed && (!current || agentJournalItemKey(current) === agentJournalItemKey(identity)) && - latestClosedWork(sink.journalItems?.())?.itemId === agentJournalItemKey(identity) - ) { - turn.suppressReopenOnFailure(true) - } - }) + }, { 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 02e18406a531..f117ee156e5e 100644 --- a/src/main/claude/claude-thread-goal-journaling.test.ts +++ b/src/main/claude/claude-thread-goal-journaling.test.ts @@ -16,9 +16,10 @@ 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 state = journal() + const state = journal({ deferred }) const rows = state.appends let stopped = false const backgroundTasks = new ClaudeBackgroundTaskTracker() @@ -76,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. @@ -90,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-turn-lifecycle-item.ts b/src/main/claude/claude-turn-lifecycle-item.ts index 0850bb8416db..be2433bcd15e 100644 --- a/src/main/claude/claude-turn-lifecycle-item.ts +++ b/src/main/claude/claude-turn-lifecycle-item.ts @@ -11,8 +11,6 @@ import type { ClaudeCommandTurn } from './claude-command-turn' export type ClaudeCurrentTurn = { sessionId: string - /** Live correlation can precede the user echo that supplies the durable association. */ - inputUuid?: string turnId: string startedAt: number /** Host clock at the send that opened the turn; absent when the provider diff --git a/src/main/claude/claude-turn-opening.ts b/src/main/claude/claude-turn-opening.ts index b9b6c9edcb6f..77c1de53cb7d 100644 --- a/src/main/claude/claude-turn-opening.ts +++ b/src/main/claude/claude-turn-opening.ts @@ -45,7 +45,6 @@ export function claudeTurnOpenedBySendEcho( input.frame.parent_tool_use_id === null ? { sessionId: envelope.sessionId, - inputUuid: claudeText(input.frame.user_message_uuid) ?? envelope.uuid, turnId: envelope.uuid, startedAt: input.observedAt, ...(input.requestedAt === undefined ? {} : { requestedAt: input.requestedAt }), @@ -114,11 +113,9 @@ export function createClaudeTurnOpener(deps: { if ((!send && deps.isSuppressed()) || deps.isTurnOpen()) { return } - const inputUuid = claudeText(frame.user_message_uuid) deps.open( { sessionId: source.sessionId, - ...(inputUuid ? { inputUuid } : {}), turnId: source.uuid, startedAt: observedAt, ...(send?.requestedAt === undefined ? {} : { requestedAt: send.requestedAt }), diff --git a/src/main/claude/claude-usage-limits.test.ts b/src/main/claude/claude-usage-limits.test.ts index 11f23355cd05..9697f4280918 100644 --- a/src/main/claude/claude-usage-limits.test.ts +++ b/src/main/claude/claude-usage-limits.test.ts @@ -61,17 +61,20 @@ function messageTexts(t: ReturnType): string[] { } describe('a Claude usage limit', () => { - it('ends the turn on one limit row, again when the CLI does not repeat the rejection', () => { + it.each([false, true])('keeps one limit row across a result and idle (quota first %s)', (quotaFirst) => { const t = setup() - t.handle(userFrame('turn-a', 1_000)) + if (!quotaFirst) { t.handle(userFrame('turn-a', 1_000)) } t.handle(rateLimitEvent('rejected', 1_100)) - t.handle(frame({ ...assistantFrame('first', 1_150, 20).message, user_message_uuid: 'turn-a' }, 1_150)) + 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)) @@ -159,33 +162,7 @@ const quota = (uuid: string, stamp?: string) => frame({ user_message_uuid: stamp, api_error: 'usage_limit_reached' }, 1100) -it.each([false, true])('reconciles replay and late detail without touching newer work (provider-opened %s)', (providerOpened) => { - const t = setup({ deferred: true }) - if (!providerOpened) { t.handle(userFrame('owner', 1000)) } - const refusal = quota('owner', providerOpened ? undefined : 'owner') - t.handle(refusal) - t.handle(frame({ ...failedResult('owner', 1200, LIMIT_TEXT).message, user_message_uuid: 'owner' }, 1200)) - t.handle(refusal) - t.handle(frame({ ...failedResult('owner', 1300, LIMIT_TEXT).message, user_message_uuid: 'owner' }, 1300)) - t.handle(userFrame('newer', 2000)) - const stampedReplay = frame({ ...refusal.message, user_message_uuid: 'owner' }, 2100) - t.handle(stampedReplay) - t.handle(frame({ ...failedResult('owner', 2200, LIMIT_TEXT).message, user_message_uuid: 'owner' }, 2200)) - t.flush() - expect(statusRows(t)).toHaveLength(1) - expect(t.items().find((item) => item.body.kind === 'status')?.revision).toBe(1) - expect(t.translator.currentTurnId).toBe('newer') - const endpoints = t.items().filter((item) => item.body.kind === 'turn') - t.handle(frame({ ...failedResult('owner', 2300, 'New provider explanation').message, user_message_uuid: 'owner' }, 2300)) - t.flush() - expect(t.items().filter((item) => item.body.kind === 'turn')).toEqual(endpoints) - expect(t.turnRow('newer')?.body).toMatchObject({ state: 'running' }) - expect(statusRows(t)).toHaveLength(1) - expect(statusRows(t)[0]?.failure?.detail?.text).toContain('New provider explanation') - t.translator.dispose() -}) - -it.each(['idle', 'exit'] as const)('keeps quota failure through a deferred resultless %s and merges late detail', (ending) => { +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')) @@ -199,12 +176,6 @@ it.each(['idle', 'exit'] as const)('keeps quota failure through a deferred resul state: ending === 'idle' ? 'completed' : 'interrupted', outcome: 'failure' }) expect(latestNativeChatUsageLimitCut(t.items(), [])).not.toBeNull() - const end = t.turnRow('owner') - t.handle(frame({ ...failedResult('owner', 1400, 'Later explanation').message, user_message_uuid: 'owner' }, 1400)) - t.flush() - expect(t.turnRow('owner')).toEqual(end) - expect(statusRows(t)).toHaveLength(1) - expect(statusRows(t)[0]?.failure?.detail?.text).toContain('Later explanation') t.translator.dispose() }) @@ -219,16 +190,20 @@ it.each(['before', 'after', 'child', 'ordinary', 'success', 'other', 'superseded t.handle(frame({ ...refusedFrame('other', 1150, 'Requires credits').message, api_error: 'model_requires_usage_credits', user_message_uuid: 'owner' }, 1150)) } - const stopAt = mode === 'before' ? 1150 : 1300 - t.sink.journalStopDecidesTurn = (_turnId, endAt) => - (mode === 'before' || mode === 'after') && endAt >= stopAt + 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 diff --git a/src/main/native-chat/agent-session-journal/journal-item-appender.ts b/src/main/native-chat/agent-session-journal/journal-item-appender.ts index ce0e1bd25f88..c3b7d65c0a38 100644 --- a/src/main/native-chat/agent-session-journal/journal-item-appender.ts +++ b/src/main/native-chat/agent-session-journal/journal-item-appender.ts @@ -1,8 +1,7 @@ import { agentJournalItemKey } from '../../../shared/agent-session-journal-item-key' import type { AgentJournalItemBody, - AgentJournalItemIdentity, - AgentJournalTurnScope + AgentJournalItemIdentity } from '../../../shared/agent-session-journal-types' import { journalItemRowBuilder } from './journal-row-builders' import type { JournalReducerState } from './journal-reducer' @@ -13,11 +12,7 @@ import type { JournalOperationReceipt } from './journal-row-writer' // A module-level Error's lazy stack retains the bundle's startup code and read buffer. class NothingResolvedError extends Error {} -export type JournalResolvedItem = { - identity: AgentJournalItemIdentity - body: AgentJournalItemBody - turnScope?: AgentJournalTurnScope -} +export type JournalResolvedItem = { identity: AgentJournalItemIdentity; body: AgentJournalItemBody } export class JournalItemAppender { constructor( diff --git a/src/main/native-chat/agent-session-journal/journal-step-writer.ts b/src/main/native-chat/agent-session-journal/journal-step-writer.ts index 9309b80ef410..c0b62ce50c4c 100644 --- a/src/main/native-chat/agent-session-journal/journal-step-writer.ts +++ b/src/main/native-chat/agent-session-journal/journal-step-writer.ts @@ -53,8 +53,6 @@ export class JournalStepWriter { const resolved = step.resolve() return resolved === null ? [] - : [journalItemRowBuilder(this.deps.state, resolved.identity, resolved.body, { - ...step.options, ...(resolved.turnScope ? { turnScope: resolved.turnScope } : {}) - })] + : [journalItemRowBuilder(this.deps.state, resolved.identity, resolved.body, step.options)] } } 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 b16e6bbded9b..a8ffb202e766 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 @@ -134,8 +134,7 @@ export type StructuredAgentSessionEventSink = StructuredAgentSessionTransitionSi tryReviseResolvedItemAndPublish?( reservedBytes: number, resolve: StructuredAgentSessionRevisionResolver, - options: StructuredAgentSessionRevisionOptions, - onPublished?: () => void + options: StructuredAgentSessionRevisionOptions ): StructuredAgentSessionSinkAdmission /** Queues one journal-derived lifecycle append; a null resolution is a no-op. */ tryAppendLifecycleTransition?( diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-resolved-append.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-resolved-append.ts index 197a2b5f4018..d3640db2a0cf 100644 --- a/src/main/native-chat/agent-session-wire/structured-agent-session-resolved-append.ts +++ b/src/main/native-chat/agent-session-wire/structured-agent-session-resolved-append.ts @@ -31,7 +31,7 @@ export function createStructuredAgentSessionResolvedAppend( reservedBytes: number, resolve: (journal: StructuredAgentSessionRevisionJournal) => ResolvedItem | null, options: StructuredAgentSessionItemAppendOptions, - input: { publish: boolean; lifecycle?: true; overflow: string; onPublished?: () => void } + input: { publish: boolean; lifecycle?: true; overflow: string } ) => queue.submit( { @@ -55,7 +55,6 @@ export function createStructuredAgentSessionResolvedAppend( ) if (landed !== null && input.publish) { bound.publish() - input.onPublished?.() } } }, @@ -78,8 +77,8 @@ export function createStructuredAgentSessionResolvedAppend( tryAppendResolvedItemAndPublish: identityOnly(true), tryReviseResolvedItem: (reservedBytes, resolve, options) => submit(reservedBytes, resolve, options, { publish: false, overflow: ITEM_OVERFLOW }), - tryReviseResolvedItemAndPublish: (reservedBytes, resolve, options, onPublished) => - submit(reservedBytes + 1, resolve, options, { publish: true, overflow: ITEM_OVERFLOW, onPublished }), + tryReviseResolvedItemAndPublish: (reservedBytes, resolve, options) => + submit(reservedBytes + 1, resolve, options, { publish: true, overflow: ITEM_OVERFLOW }), tryAppendLifecycleTransition: (identitySizeBound, body, resolveIdentity, options) => submit( estimateStructuredAgentSessionItemBytes(identitySizeBound, body), diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-transition.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-transition.ts index 9d049e0b84db..a6b5b9b30be9 100644 --- a/src/main/native-chat/agent-session-wire/structured-agent-session-transition.ts +++ b/src/main/native-chat/agent-session-wire/structured-agent-session-transition.ts @@ -10,8 +10,7 @@ import type { AgentJournalItemBody, - AgentJournalItemIdentity, - AgentJournalTurnScope + AgentJournalItemIdentity } from '../../../shared/agent-session-journal-types' import type { JournalLifecycleMutationInput } from '../agent-session-journal/journal-row-builders' import type { AgentSessionJournal } from '../agent-session-journal/journal-store' @@ -27,7 +26,7 @@ import { structuredAgentSessionJournalAppendOptions } from './structured-agent-s /** What a transition step reads: rows by key, every row, and the turns they joined. */ export type StructuredAgentSessionTransitionJournal = Pick< AgentSessionJournal, - 'epoch' | 'visitItems' | 'itemBody' | 'item' | 'visitItemsWithLinkage' | 'submissions' | 'canonicalItemId' + 'epoch' | 'visitItems' | 'itemBody' | 'item' | 'visitItemsWithLinkage' > export type StructuredAgentSessionTransitionStep = @@ -39,7 +38,6 @@ export type StructuredAgentSessionTransitionStep = resolve: (journal: StructuredAgentSessionTransitionJournal) => { identity: AgentJournalItemIdentity body: AgentJournalItemBody - turnScope?: AgentJournalTurnScope } | null options: StructuredAgentSessionItemAppendOptions } From ab64f1e150f4ce5d2bac1d0910349759279904f1 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Sun, 18 Oct 2026 17:59:11 -0700 Subject: [PATCH 28/34] fix(claude): keep typed notices separate from quota failures --- src/main/claude/claude-message-journaling.ts | 2 +- src/main/claude/claude-open-turn.ts | 1 - src/main/claude/claude-terminal-failure.ts | 2 +- src/main/claude/claude-usage-limits.test.ts | 20 ++++++++++++++ .../structured-agent-session-event-sink.ts | 27 ++++++++++++------- 5 files changed, 39 insertions(+), 13 deletions(-) diff --git a/src/main/claude/claude-message-journaling.ts b/src/main/claude/claude-message-journaling.ts index d8b296490157..b7e6b133eec2 100644 --- a/src/main/claude/claude-message-journaling.ts +++ b/src/main/claude/claude-message-journaling.ts @@ -117,7 +117,7 @@ export function journalClaudeMessage( usageLimit ?? ctx.threadGoal.report(message, claudeMessageIdentity(envelope), observedAt) ?? messageBody ?? ordinaryFailure - const terminalIdentity = terminal && ctx.turn.identity && (usageLimit || message.api_error) + const terminalIdentity = terminal && ctx.turn.identity && usageLimit ? ctx.turn.identity : null const identity = (body && envelope.role === 'assistant' diff --git a/src/main/claude/claude-open-turn.ts b/src/main/claude/claude-open-turn.ts index 2e972efdcc86..88b5a2bd2eae 100644 --- a/src/main/claude/claude-open-turn.ts +++ b/src/main/claude/claude-open-turn.ts @@ -201,7 +201,6 @@ export class ClaudeOpenTurn { this.deps.endOpenWork(end.completedAt) if (this.current) { this.publish(this.current, end, contextUsage, quotaEnd) - this.usageLimitEvidence = null this.current = null } this.deps.sink.setActivity?.(null) diff --git a/src/main/claude/claude-terminal-failure.ts b/src/main/claude/claude-terminal-failure.ts index 5b7867dd0d85..1afb24d1d5aa 100644 --- a/src/main/claude/claude-terminal-failure.ts +++ b/src/main/claude/claude-terminal-failure.ts @@ -16,7 +16,7 @@ import { type AgentJournalTurnRowWrite } from '../native-chat/agent-session-timeline/agent-journal-turn-row-revision' -export function claudeTerminalFailureIdentity(turnItemId: string): AgentJournalItemIdentity { +function claudeTerminalFailureIdentity(turnItemId: string): AgentJournalItemIdentity { return { provider: 'orca', clientMessageId: `terminal-failure:claude:${turnItemId}` } } diff --git a/src/main/claude/claude-usage-limits.test.ts b/src/main/claude/claude-usage-limits.test.ts index 9697f4280918..e7c1633b78f6 100644 --- a/src/main/claude/claude-usage-limits.test.ts +++ b/src/main/claude/claude-usage-limits.test.ts @@ -99,6 +99,26 @@ describe('a Claude usage limit', () => { 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)) 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 a8ffb202e766..461cf3730f56 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 @@ -288,14 +288,6 @@ export function createDeferredStructuredAgentSessionEventSink(deps: { options ) - const appendTombstone: NonNullable = ( - identity, - options = {} - ) => queue.submit({ - bytes: Buffer.byteLength(agentJournalItemKey(identity), 'utf8') + 256, - run: (bound) => bound.journal.appendTombstone(identity, { fence: bound.fence }) - }, options) - return { exitObservation: () => exit, sink: { @@ -320,8 +312,23 @@ export function createDeferredStructuredAgentSessionEventSink(deps: { }, tryAppendLifecycleBatch: appendLifecycleBatch, bindReadingControl: (control) => queue.bindReadingControl(control), - appendTombstone: (identity, options) => void appendTombstone(identity, options), - tryAppendTombstone: appendTombstone, + appendTombstone: (identity, options = {}) => { + queue.submit( + { + bytes: Buffer.byteLength(agentJournalItemKey(identity), 'utf8') + 256, + run: (bound) => bound.journal.appendTombstone(identity, { fence: bound.fence }) + }, + options + ) + }, + tryAppendTombstone: (identity, options = {}) => + queue.submit( + { + bytes: Buffer.byteLength(agentJournalItemKey(identity), 'utf8') + 256, + run: (bound) => bound.journal.appendTombstone(identity, { fence: bound.fence }) + }, + options + ), publish: (options = {}) => void publish(options), written: queue.written, setActivity: (activity) => { From 08d519d87a490e5ead6c3c21a6376e03282e3771 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Sun, 18 Oct 2026 18:08:00 -0700 Subject: [PATCH 29/34] fix(claude): preserve context-limit failures as ordinary errors --- src/main/claude/claude-usage-limits.test.ts | 8 +++++++- src/main/claude/claude-usage-limits.ts | 4 ++-- 2 files changed, 9 insertions(+), 3 deletions(-) diff --git a/src/main/claude/claude-usage-limits.test.ts b/src/main/claude/claude-usage-limits.test.ts index e7c1633b78f6..45ee1520724b 100644 --- a/src/main/claude/claude-usage-limits.test.ts +++ b/src/main/claude/claude-usage-limits.test.ts @@ -132,10 +132,16 @@ describe('a Claude usage limit', () => { }, 2_100)) t.handle(frame({ ...failedResult('credits', 2_200, 'This model requires usage credits').message, - terminal_reason: 'blocking_limit', api_error_status: 429 + 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() }) diff --git a/src/main/claude/claude-usage-limits.ts b/src/main/claude/claude-usage-limits.ts index 5f9d3b2a10cc..cee66cf9b2d1 100644 --- a/src/main/claude/claude-usage-limits.ts +++ b/src/main/claude/claude-usage-limits.ts @@ -21,7 +21,7 @@ const CLAUDE_LIMIT_WINDOWS: Record = { } /** The ends a result reports when a limit refused its request; any other is a different failure. */ -const LIMIT_TERMINAL_REASONS = ['api_error', 'blocking_limit'] +const LIMIT_TERMINAL_REASONS = ['api_error'] export type ClaudeUsageLimitRow = AgentSessionFailureRowWords & { kind: 'status' @@ -90,7 +90,7 @@ export class ClaudeUsageLimits { const reason = claudeText(message.terminal_reason) const limited = evidence?.cause === 'quota' || - ((evidence?.cause === 'untyped' || reason === 'blocking_limit') && + (evidence?.cause === 'untyped' && (status == null || status === 429) && (reason === null || LIMIT_TERMINAL_REASONS.includes(reason))) if (!limited) { From a2b83966bd4eefd01e1e307e4a539b9963f95c82 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Sun, 18 Oct 2026 18:14:22 -0700 Subject: [PATCH 30/34] fix(native-chat): keep quota failures visible in collapsed turns --- ...NativeChatMessageList.turn-status.test.tsx | 42 ++++++++++++++++++- src/shared/native-chat-turn-fold.ts | 2 +- 2 files changed, 42 insertions(+), 2 deletions(-) diff --git a/src/renderer/src/components/native-chat/NativeChatMessageList.turn-status.test.tsx b/src/renderer/src/components/native-chat/NativeChatMessageList.turn-status.test.tsx index 8f84c3db5c9c..2e1191d5c0ae 100644 --- a/src/renderer/src/components/native-chat/NativeChatMessageList.turn-status.test.tsx +++ b/src/renderer/src/components/native-chat/NativeChatMessageList.turn-status.test.tsx @@ -2,7 +2,7 @@ import '@testing-library/jest-dom/vitest' -import { cleanup, render, screen } from '@testing-library/react' +import { cleanup, fireEvent, render, screen } from '@testing-library/react' import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from 'vitest' // Why: these fixtures have neither inline visual owners nor sender navigation. @@ -24,6 +24,8 @@ afterEach(() => { expect(unusedChatLeaves.inlineVisual).not.toHaveBeenCalled() expect(unusedChatLeaves.openSender).not.toHaveBeenCalled() }) +import { TooltipProvider } from '@/components/ui/tooltip' +import { NativeChatOrcaStopContext } from './native-chat-orca-stop-context' import { agentSessionFailureWords } from '../../../../shared/agent-session-failure-words' import type { AgentJournalItemBody, @@ -245,6 +247,44 @@ afterEach(cleanup) readPhase: 'ready' } + it.each(['claude', 'codex', 'grok'] as const)('keeps a collapsed %s quota failure and Continue visible', (agent) => { + const items: AgentJournalRenderItem[] = [ + journalItem(1, { kind: 'message', role: 'user', blocks: [{ type: 'text', text: 'Start' }] }), + journalItem(2, { kind: 'turn', turnId: 'turn-1', userItemId: 'item-1', + state: 'completed', outcome: 'failure', startedAt: 1000, completedAt: 2000 }), + { ...journalItem(3, { kind: 'message', role: 'assistant', blocks: [{ type: 'text', text: 'Earlier work' }] }), + turnScope: { kind: 'turn', turnItemId: 'item-2' } }, + { ...journalItem(4, { kind: 'status', tone: 'warning', ...agentSessionFailureWords({ + kind: 'usageLimitReached', usageLimit: { window: 'session', resetsAt: Date.now() + 3600_000 }, + detail: { text: 'The provider refused this request.', audience: 'person' } + }, { surface: 'row' }) }), turnScope: { kind: 'turn', turnItemId: 'item-2' } } + ] + const continueUsageLimit = vi.fn() + render( + + + + + + ) + expect(screen.getByRole('button', { name: 'Toggle turn details' })).toHaveAttribute('aria-expanded', 'false') + expect(screen.queryByText('Earlier work')).toBeNull() + expect(screen.getByText(/hit its session limit/)).toBeVisible() + expect(screen.getByText('Details')).toBeVisible() + const button = screen.getByRole('button', { name: 'Continue' }) + expect(button).toBeVisible() + fireEvent.click(button) + expect(continueUsageLimit).toHaveBeenCalledOnce() + }) + // The turn still runs while a Stop ends it, so its bar keeps the running clock; only the tail line // says the turn is stopping, and the bar settles to "Interrupted after" once the turn ends. describe("the turn bar while a person's Stop ends the turn", () => { diff --git a/src/shared/native-chat-turn-fold.ts b/src/shared/native-chat-turn-fold.ts index 0e0b3aa1358e..6d1a5ed07f38 100644 --- a/src/shared/native-chat-turn-fold.ts +++ b/src/shared/native-chat-turn-fold.ts @@ -66,7 +66,7 @@ export function nativeChatTurnFoldRow( reportsFailure: message.blocks.some( (block) => block.type === 'text' && - block.tone === 'error' && + (block.tone === 'error' || block.failure?.kind === 'usageLimitReached') && block.presentation !== AGENT_SESSION_ORCA_STOP_PRESENTATION ), explainsTurn: message.blocks.some( From 3a38c84afa0ef92a21fda114f096f181fee2b997 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Sun, 18 Oct 2026 18:17:57 -0700 Subject: [PATCH 31/34] fix(native-chat): return keyboard Continue focus to the composer --- .../NativeChatInterruptedContinue.test.tsx | 9 +++++++-- .../native-chat/NativeChatInterruptedContinue.tsx | 13 ++++++++----- .../NativeChatMessageList.turn-status.test.tsx | 6 +++--- .../native-chat/NativeChatStructuredSession.tsx | 1 + .../native-chat/native-chat-orca-stop-context.ts | 2 +- 5 files changed, 20 insertions(+), 11 deletions(-) diff --git a/src/renderer/src/components/native-chat/NativeChatInterruptedContinue.test.tsx b/src/renderer/src/components/native-chat/NativeChatInterruptedContinue.test.tsx index 71b2a1bc7297..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 { act, cleanup, fireEvent, render, renderHook, screen, waitFor } from '@testing-library/react' -import { useState } from 'react' +import { useRef, useState } from 'react' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' const mocks = vi.hoisted(() => { @@ -105,10 +105,12 @@ type Props = { } 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', @@ -120,6 +122,7 @@ function Harness(props: Props): React.JSX.Element { }) return ( +