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({
<>
-