diff --git a/mobile/src/session/MobileNativeChatNoticeRow.tsx b/mobile/src/session/MobileNativeChatNoticeRow.tsx
index 66ad951a078c..153b48769a9d 100644
--- a/mobile/src/session/MobileNativeChatNoticeRow.tsx
+++ b/mobile/src/session/MobileNativeChatNoticeRow.tsx
@@ -8,6 +8,7 @@ import {
type NativeChatNoticeTone
} from '../../../src/shared/native-chat-notice'
import { isTextBlock, type NativeChatBlock } from '../../../src/shared/native-chat-types'
+import { usageLimitLineText } from '../../../src/shared/agent-session-usage-limit-words'
import { MobileMarkdown } from '../components/MobileMarkdown'
import { INLINE_TEXT_SELECTION } from '../components/inline-text-selection'
import { colors, radii, spacing, typography } from '../theme/mobile-theme'
@@ -97,6 +98,7 @@ export function MobileNativeChatNoticeRow({
)
case 'line': {
+ const lineText = usageLimitLineText(notice)
const textStyle = [
styles.line,
scaledType(TEXT_SIZE, fontScale),
@@ -105,7 +107,7 @@ export function MobileNativeChatNoticeRow({
if (!look.tone) {
return (
- {notice.text}
+ {lineText}
)
}
@@ -120,7 +122,7 @@ export function MobileNativeChatNoticeRow({
style={styles.toneIcon}
/>
- {notice.text}
+ {lineText}
)
diff --git a/src/main/acp/acp-dialects/grok-dialect.ts b/src/main/acp/acp-dialects/grok-dialect.ts
index b38eea156b2c..c90e229480df 100644
--- a/src/main/acp/acp-dialects/grok-dialect.ts
+++ b/src/main/acp/acp-dialects/grok-dialect.ts
@@ -210,8 +210,5 @@ export const GROK_ACP_DIALECT: AcpDialect = {
contextWindow,
modelEfforts: grokModelEfforts,
promptErrorDetail: (error) => promptErrorDataSchema.safeParse(error.data).data?.message,
- failedTurnText: (stopReason) =>
- stopReason === 'rate_limit'
- ? 'Grok usage limit reached.'
- : 'Grok ended this turn with an error.'
+ failedTurnText: () => 'Grok ended this turn with an error.'
}
diff --git a/src/main/acp/acp-timeline-turn-failures.test.ts b/src/main/acp/acp-timeline-turn-failures.test.ts
index 801b85fd9fb8..45a531d1c4f0 100644
--- a/src/main/acp/acp-timeline-turn-failures.test.ts
+++ b/src/main/acp/acp-timeline-turn-failures.test.ts
@@ -165,14 +165,13 @@ describe('a failed ACP turn says why', () => {
expect(failures.map((failure) => failure.body.text)).toEqual([REASON])
})
- it('names a rate-limited turn the provider gave no words for, without inventing a reason', async () => {
+ it('upgrades an early diagnostic to a usage failure without a later downgrade', async () => {
const f = await openAcpFixtureRig()
const lane = f.lane()
const prompt = lane.openPrompt('c1', 1000)
f.apply(lane.notification('_x.ai/queue/changed', queued(prompt.promptId), 1001))
- f.apply(
- lane.notification('_x.ai/session_notification', ended(prompt.promptId, 'rate_limit'), 1002)
- )
+ f.apply(lane.notification('_x.ai/session_notification', retryFailed, 1002))
+ f.apply(lane.notification('_x.ai/session_notification', ended(prompt.promptId, 'rate_limit'), 1003))
f.apply(
lane.notification(
'_x.ai/session/prompt_complete',
@@ -180,9 +179,15 @@ describe('a failed ACP turn says why', () => {
1003
)
)
+ f.apply(lane.promptFailed('c1', rpcError, 1004))
const failures = statusRows(await f.rig.rows())
expect(failures.map((failure) => failure.body)).toEqual([
- { kind: 'status', tone: 'error', text: 'Grok usage limit reached.' }
+ {
+ kind: 'status',
+ tone: 'warning',
+ text: 'The agent hit its usage limit. Send a message once it resets to continue.',
+ failure: { kind: 'usageLimitReached', detail: { text: REASON, audience: 'person' } }
+ }
])
expect((await f.rig.turns())[0]?.outcome).toBe('failure')
})
diff --git a/src/main/acp/acp-turn-failures.ts b/src/main/acp/acp-turn-failures.ts
index 87bef9789179..a1123deb35f1 100644
--- a/src/main/acp/acp-turn-failures.ts
+++ b/src/main/acp/acp-turn-failures.ts
@@ -59,7 +59,10 @@ export function acpSignInRequiredFailure(
* reason the row still lacks. */
export class AcpTurnFailures {
/** The reason each failed turn's row holds; '' for none yet. */
- private readonly rows = new BoundedMap({
+ private readonly rows = new BoundedMap<
+ string,
+ { text: string; notSignedIn: boolean; usageLimited: boolean }
+ >({
maxEntries: 128
})
@@ -91,32 +94,39 @@ export class AcpTurnFailures {
): ProviderTimelineEvent[] {
const written = this.rows.peek(turn)
const detail = text === undefined ? undefined : providerDiagnostic(text, 'person')
+ const diagnostic =
+ (written?.text ? providerDiagnostic(written.text, 'person') : undefined) ?? detail
+ const authenticationRequired = notSignedIn || written?.notSignedIn === true
+ // A later copy of the reason (the prompt's error answer) names no stop reason of its own.
+ const usageLimited =
+ !authenticationRequired && (stopReason === 'rate_limit' || written?.usageLimited === true)
if (
- written !== undefined &&
- (written.text !== '' || !detail) &&
- (!notSignedIn || written.notSignedIn)
+ written &&
+ written.text === (diagnostic?.text ?? '') &&
+ written.notSignedIn === authenticationRequired &&
+ written.usageLimited === usageLimited
) {
return []
}
- const diagnostic =
- detail ?? (written?.text ? providerDiagnostic(written.text, 'person') : undefined)
- const authenticationRequired = notSignedIn || written?.notSignedIn === true
this.rows.set(turn, {
text: diagnostic?.text ?? '',
- notSignedIn: authenticationRequired
+ notSignedIn: authenticationRequired,
+ usageLimited
})
+ const failure = authenticationRequired
+ ? agentSessionFailureFact('notSignedIn', { detail: diagnostic })
+ : usageLimited
+ ? agentSessionFailureFact('usageLimitReached', { detail: diagnostic })
+ : null
return [
{
type: 'item.update',
item: `turn-failure:${turn}`,
body: {
kind: 'status',
- tone: 'error',
- ...(authenticationRequired
- ? agentSessionFailureWords(
- agentSessionFailureFact('notSignedIn', { detail: diagnostic }),
- { agentName: this.agentName, surface: 'row' }
- )
+ tone: usageLimited ? 'warning' : 'error',
+ ...(failure
+ ? agentSessionFailureWords(failure, { agentName: this.agentName, surface: 'row' })
: {
text:
diagnostic?.text ??
diff --git a/src/main/claude/claude-command-turn.test.ts b/src/main/claude/claude-command-turn.test.ts
index d8dfb63aaadc..f4714bf5497a 100644
--- a/src/main/claude/claude-command-turn.test.ts
+++ b/src/main/claude/claude-command-turn.test.ts
@@ -52,6 +52,7 @@ function harness() {
writes.push(row)
}
const journal: StructuredAgentSessionRevisionJournal = {
+ item: () => null,
epoch: 'epoch-1',
itemBody: (itemId) => rows.get(itemId)?.body ?? null,
visitItems: (visit) => {
diff --git a/src/main/claude/claude-context-usage-test-support.ts b/src/main/claude/claude-context-usage-test-support.ts
index 9823401e264b..659c01c45910 100644
--- a/src/main/claude/claude-context-usage-test-support.ts
+++ b/src/main/claude/claude-context-usage-test-support.ts
@@ -11,13 +11,20 @@ import type {
StructuredAgentSessionEventSink,
StructuredAgentSessionRevisionJournal
} from '../native-chat/agent-session-wire/structured-agent-session-event-sink'
+import { createJournalReducerState } from '../native-chat/agent-session-journal/journal-reducer'
+import { personStopDecidesTurn } from '../native-chat/agent-session-journal/journal-stop-turn-end'
import type { ClaudeContextReportTarget } from './claude-context-facts'
import { createClaudeJournalTranslator } from './claude-structured-journal-translation'
import { claudeTurnLifecycleIdentity } from './claude-turn-lifecycle-item'
/** A journal in miniature: the latest revision per row, its creation clock
* pinned, and revisions resolved against it as a bound sink would. */
-export function journal() {
+export function journal({ deferred = false } = {}) {
+ const queued: (() => void)[] = []
+ const run = (write: () => void): void => {
+ if (deferred) { queued.push(write) } else { write() }
+ }
+ const flush = (): void => { while (queued.length) { queued.shift()!() } }
const clock = { now: 0 }
const appends: { identity: AgentJournalItemIdentity; body: AgentJournalItemBody }[] = []
const rows = new Map()
@@ -30,11 +37,12 @@ export function journal() {
revision: (existing?.revision ?? 0) + 1,
sequence: existing?.sequence ?? rows.size + 1,
observedAt: existing?.observedAt ?? options?.observedAt ?? clock.now,
- body
+ ...options, turnScope: existing?.turnScope ?? options.turnScope, body
})
}
const scans = { count: 0 }
const bound: StructuredAgentSessionRevisionJournal = {
+ item: (itemId) => rows.get(itemId) ?? null,
epoch: 'test',
visitItems: (visit) => {
scans.count += 1
@@ -44,19 +52,24 @@ export function journal() {
},
itemBody: (itemId) => rows.get(itemId)?.body ?? null
}
- const revise: NonNullable = (
+ const revise: NonNullable = (
_reservedBytes,
resolve,
options
) => {
- const resolved = resolve(bound)
- if (resolved) {
- appendItem(resolved.identity, resolved.body, options)
- }
+ run(() => {
+ const resolved = resolve(bound)
+ if (resolved) { appendItem(resolved.identity, resolved.body, options) }
+ })
return { accepted: true }
}
+ const stopState = createJournalReducerState('orca-session', 'test')
+ const queueStop = (turnId: string, at: number): void => run(() => {
+ stopState.queuePauseMarks.latestStop = { sequence: rows.size + 1, event: { reason: 'user-stop', turnId, at } }
+ })
const sink: StructuredAgentSessionEventSink = {
- appendItem,
+ journalStopDecidesTurn: (turnId, at) => personStopDecidesTurn(stopState, turnId, at),
+ appendItem: (...args) => run(() => appendItem(...args)),
tryReviseResolvedItem: revise,
tryReviseResolvedItemAndPublish: revise,
appendTombstone: () => {},
@@ -65,7 +78,7 @@ export function journal() {
const turnRow = (turnId: string) =>
rows.get(agentJournalItemKey(claudeTurnLifecycleIdentity('claude-session', turnId)))
const items = () => [...rows.values()].sort((left, right) => left.sequence - right.sequence)
- return { sink, clock, appends, rows, turnRow, items, scans }
+ return { sink, clock, appends, rows, turnRow, items, scans, flush, queueStop }
}
export function frame(message: Record, observedAt: number, startsTurn = false) {
@@ -146,8 +159,8 @@ export const turnIdentity = (turnId: string) =>
claudeTurnLifecycleIdentity('claude-session', turnId)
/** Every turn the CLI runs opens with an init naming the main model as `modelUsage` keys it. */
-export function setup({ init = 'claude-fable-5-1[1m]' }: { init?: string | null } = {}) {
- const state = journal()
+export function setup({ init = 'claude-fable-5-1[1m]', deferred = false }: { init?: string | null; deferred?: boolean } = {}) {
+ const state = journal({ deferred })
const translator = createClaudeJournalTranslator({ sink: state.sink, coalesceMs: 0 })
const requests: ClaudeContextReportTarget[] = []
translator.subscribeContextUsageRequests((target) => requests.push(target))
diff --git a/src/main/claude/claude-message-journaling.ts b/src/main/claude/claude-message-journaling.ts
index 1bc7b69d41a7..b7e6b133eec2 100644
--- a/src/main/claude/claude-message-journaling.ts
+++ b/src/main/claude/claude-message-journaling.ts
@@ -6,6 +6,8 @@
// read off an explicit context, so the open turn and the collaborators it
// writes through stay owned by the translator.
+import { writeClaudeTerminalFailure } from './claude-terminal-failure'
+import { agentSessionFailureWords } from '../../shared/agent-session-failure-words'
import { agentJournalItemKey } from '../../shared/agent-session-journal-item-key'
import type { StructuredAgentSessionEventSink } from '../native-chat/agent-session-wire/structured-agent-session-event-sink'
import type { ClaudeBackgroundTaskRows } from './claude-background-task-rows'
@@ -34,6 +36,7 @@ import type { ClaudeSubagentIdentities } from './claude-subagent-identities'
import { claudeTurnOpenedBySendEcho, type ClaudeTurnSource } from './claude-turn-opening'
import type { ClaudeOpenTurn } from './claude-open-turn'
import type { ClaudeAuthenticationFailures } from './claude-authentication-failures'
+import type { ClaudeUsageLimits } from './claude-usage-limits'
import type { ClaudeThreadGoal } from './claude-thread-goal'
export type ClaudeMessageJournalContext = {
@@ -53,6 +56,7 @@ export type ClaudeMessageJournalContext = {
* latch; this module asks it rather than tracking a copy. */
turn: ClaudeOpenTurn
authenticationFailures: ClaudeAuthenticationFailures
+ usageLimits: ClaudeUsageLimits
threadGoal: ClaudeThreadGoal
}
@@ -92,28 +96,45 @@ export function journalClaudeMessage(
const stamp = ctx.corrections.stampFor(producerRef)
const outputEnvelope = claudeOutputEnvelope(envelope)
ctx.threadGoal.observe(message)
+ const source: ClaudeTurnSource = {
+ sessionId: envelope.sessionId,
+ uuid: envelope.uuid,
+ assistant: envelope.role === 'assistant'
+ }
+ const openOutputTurn = (): void => ctx.turn.ensureOpen(message, source, observedAt)
+ const messageBody = claudeMessageBody(outputEnvelope)
+ const ordinaryFailure = typeof message.api_error === 'string' && message.api_error !== 'usage_limit_reached'
+ ? { kind: 'status' as const, tone: 'error' as const, ...agentSessionFailureWords({ kind: 'providerRejected' }, { agentName: 'Claude', provider: 'claude', surface: 'row' }) } : null
+ const terminal = envelope.role === 'assistant' && producerRef === null &&
+ (typeof message.api_error === 'string' || message.error === 'rate_limit')
+ if (envelope.role === 'assistant' &&
+ (messageBody || typeof message.api_error === 'string' || message.error === 'rate_limit')) {
+ openOutputTurn()
+ }
+ const usageLimit = ctx.usageLimits.assistant(message, ctx.turn)
const body =
ctx.authenticationFailures.assistant(message) ??
+ usageLimit ??
ctx.threadGoal.report(message, claudeMessageIdentity(envelope), observedAt) ??
- claudeMessageBody(outputEnvelope)
+ messageBody ?? ordinaryFailure
+ const terminalIdentity = terminal && ctx.turn.identity && usageLimit
+ ? ctx.turn.identity : null
const identity =
(body && envelope.role === 'assistant'
? ctx.streamedBlocks.reconcile(envelope)?.identity
: null) ?? claudeMessageIdentity(envelope)
ctx.streamedText.forget(agentJournalItemKey(identity))
const thinking = ctx.streamedThinking.finalize(outputEnvelope, observedAt)
- const source: ClaudeTurnSource = {
- sessionId: envelope.sessionId,
- uuid: envelope.uuid,
- assistant: envelope.role === 'assistant'
- }
- const openOutputTurn = (): void => ctx.turn.ensureOpen(message, source, observedAt)
if (body) {
// Opening before the append is what brackets a turn around its own first
// output; a reader that scans back to the turn record and stops would
// otherwise look straight past the row that opened it.
ctx.turn.ensureOpen(message, source, observedAt)
- ctx.sink.appendItem(identity, body, stamp(identity, body))
+ if (terminalIdentity) {
+ writeClaudeTerminalFailure(ctx.sink, terminalIdentity, body)
+ } else {
+ ctx.sink.appendItem(identity, body, stamp(identity, body))
+ }
changed = true
}
for (const tool of claudeToolUses(outputEnvelope)) {
diff --git a/src/main/claude/claude-open-turn.ts b/src/main/claude/claude-open-turn.ts
index e7c36ddaac04..88b5a2bd2eae 100644
--- a/src/main/claude/claude-open-turn.ts
+++ b/src/main/claude/claude-open-turn.ts
@@ -21,6 +21,8 @@ import {
import { writeAgentJournalTurnRow } from '../native-chat/agent-session-timeline/agent-journal-turn-row-revision'
import type { ClaudeCommandTurn } from './claude-command-turn'
import { createClaudeTurnOpener, type ClaudeTurnSource } from './claude-turn-opening'
+import { refineClaudeQuotaTurnEnd } from './claude-terminal-failure'
+import type { ClaudeUsageLimitEvidence } from './claude-usage-limits'
import type { ClaudeStartedSend } from './claude-structured-session-state'
export type ClaudeOpenTurnDeps = {
@@ -35,6 +37,7 @@ export type ClaudeOpenTurnDeps = {
export class ClaudeOpenTurn {
private current: ClaudeCurrentTurn | null = null
+ usageLimitEvidence: ClaudeUsageLimitEvidence | null = null
/** Provider output may not reopen a turn after the session ended or a turn
* failed: nothing would ever close the turn it opened, and the row would read
* working for the life of the session. Only an accepted send lifts it. */
@@ -125,6 +128,7 @@ export class ClaudeOpenTurn {
* later would sweep THIS turn. The replaced turn is recorded superseded: a newer
* request ended it, whoever sent that request. */
open(turn: ClaudeCurrentTurn, observedAt: number): void {
+ this.usageLimitEvidence = null
this.deps.onOpen?.()
if (this.current) {
this.deps.turnSuperseded()
@@ -143,6 +147,7 @@ export class ClaudeOpenTurn {
/** A conversation command the host opened a turn for. Its row is the host's, already written,
* so only an end is published; the command's result is what ends it. */
beginCommand(turn: ClaudeCurrentTurn): void {
+ this.usageLimitEvidence = null
this.deps.onOpen?.()
if (this.current) {
this.deps.turnSuperseded()
@@ -167,6 +172,7 @@ export class ClaudeOpenTurn {
/** The command was never sent; its turn is the host's to settle. */
forgetCommand(turnId: string): void {
if (this.current?.command && this.current.turnId === turnId) {
+ this.usageLimitEvidence = null
this.current = null
}
}
@@ -185,12 +191,16 @@ export class ClaudeOpenTurn {
/** End the open turn, if one is open, and clear the live activity line. The
* context facts the end brings ride the same revision. */
settle(end: ClaudeTurnEnd, contextUsage?: AgentSessionContextUsage): void {
+ const quotaEnd = this.current !== null && end.outcome === undefined &&
+ this.usageLimitEvidence?.cause === 'quota'
+ this.suppressReopenOnFailure(quotaEnd)
// Every settle is a provider cycle ending (result, idle, child exit).
this.cycleWorkObserved = false
+ this.usageLimitEvidence = null
// Even with no turn open: work a suppressed turn produced still ends here.
this.deps.endOpenWork(end.completedAt)
if (this.current) {
- this.publish(this.current, end, contextUsage)
+ this.publish(this.current, end, contextUsage, quotaEnd)
this.current = null
}
this.deps.sink.setActivity?.(null)
@@ -216,13 +226,18 @@ export class ClaudeOpenTurn {
private publish(
turn: ClaudeCurrentTurn,
end?: ClaudeTurnEnd,
- contextUsage?: AgentSessionContextUsage
+ contextUsage?: AgentSessionContextUsage,
+ quotaEnd = false
): void {
const item = claudeTurnLifecycleItem(turn, end)
+ const write = { lifecycle: item.body, ...(contextUsage ? { contextUsage } : {}) }
+ if (quotaEnd && refineClaudeQuotaTurnEnd(this.deps.sink, item.identity, write)) {
+ return
+ }
writeAgentJournalTurnRow(
this.deps.sink,
{ identity: item.identity },
- { lifecycle: item.body, ...(contextUsage ? { contextUsage } : {}) },
+ write,
{ publish: false, options: item.options }
)
// Keyed apart, so this never replaces the start's publication while it still waits to run.
diff --git a/src/main/claude/claude-result-journaling.ts b/src/main/claude/claude-result-journaling.ts
index 9e68e852f352..74df8eb43b17 100644
--- a/src/main/claude/claude-result-journaling.ts
+++ b/src/main/claude/claude-result-journaling.ts
@@ -4,6 +4,7 @@
// Split out of the translator when that file reached its line budget; the translator still owns
// the open turn and every collaborator this writes through.
+import { writeClaudeTerminalFailure } from './claude-terminal-failure'
import type { ClaudeContextFacts } from './claude-context-facts'
import { claudeCommandResultEnd } from './claude-command-turn'
import type { ClaudeMessageJournalContext } from './claude-message-journaling'
@@ -26,6 +27,7 @@ export type ClaudeResultJournalContext = Pick<
| 'corrections'
| 'turn'
| 'authenticationFailures'
+ | 'usageLimits'
| 'threadGoal'
> & {
prompts: ClaudeJournalPrompts
@@ -44,6 +46,7 @@ export function journalClaudeResult(
prompts,
context,
authenticationFailures,
+ usageLimits,
threadGoal,
goalBackgroundWork
}: ClaudeResultJournalContext,
@@ -55,49 +58,51 @@ export function journalClaudeResult(
// diagnostic below still runs: a child's failure is reportable even when
// it ends no turn.
const settlesTurn = isRootClaudeFrame(message)
- const commandEnd = settlesTurn ? claudeCommandResultEnd(turn, sink, message, observedAt) : null
- if (commandEnd === 'another-input') {
- return
- }
- // Read before the settle below closes it: the result reports that turn's end.
const endedTurnScope = turn.turnScope
+ const endedTurnIdentity = turn.identity
+ const usageEvidence = turn.usageLimitEvidence
const endedTurnStartedAt = turn.startedAt
- // Read before the settle below closes the turn: an error end the journal's Stop rule makes a
- // person's cancellation is theirs to decide as the end is written (`turnEndAfterStop`).
const turnId = settlesTurn ? turn.id : null
const leftToStop = turnId !== null && sink.journalStopDecidesTurn?.(turnId, observedAt) === true
+ // Retry owed prompt cancellations before a command result can return.
if (settlesTurn) {
prompts.retryPendingCancellations()
+ }
+ const commandEnd = settlesTurn ? claudeCommandResultEnd(turn, sink, message, observedAt) : null
+ if (commandEnd === 'another-input') {
+ return
+ }
+ const failure = claudeResultFailure(message, leftToStop)
+ const usageLimit = settlesTurn ? usageLimits.result(message, failure !== null, usageEvidence) : null
+ if (usageLimit && endedTurnIdentity) {
+ writeClaudeTerminalFailure(sink, endedTurnIdentity, usageLimit)
+ }
+ if (settlesTurn) {
turn.suppressReopenOnFailure(message.is_error === true)
corrections.abandon()
context.settle(message, commandEnd ?? claudeTurnEndForResult(message, observedAt, leftToStop))
- // The turn is over. A block still awaiting its final keeps the text the
- // flush above journaled, but its live state goes: an interrupted turn
- // would otherwise retain that text for the life of the session.
streamedBlocks.clear()
streamedText.settle()
}
- const goal = threadGoal.settle(
- message,
- {
- backgroundWork: goalBackgroundWork(),
- stoppedByPerson: leftToStop,
- turnStartedAt: endedTurnStartedAt
- },
- observedAt
- )
+ const goal = threadGoal.settle(message, {
+ backgroundWork: goalBackgroundWork(),
+ stoppedByPerson: leftToStop,
+ turnStartedAt: endedTurnStartedAt
+ }, observedAt)
if (goal) {
sink.appendItem(goal.identity, goal.body, { turnScope: endedTurnScope })
sink.publish()
}
const kind = claudeProviderFrameKind(message)
- const failure = claudeResultFailure(message, leftToStop)
+ if (usageLimit && endedTurnIdentity) {
+ return
+ }
const alreadyShown = authenticationFailures.resultAlreadyShown(message)
if ((failure || !isSettledClaudeResultKind(kind)) && !alreadyShown) {
providerFallback.append(
kind,
message,
- failure?.text,
+ usageLimit ?? failure?.text,
undefined,
{ reportsFailure: failure !== null },
// A result that settles no turn is a CHILD's result: this
diff --git a/src/main/claude/claude-structured-journal-translation.ts b/src/main/claude/claude-structured-journal-translation.ts
index a8da78e9a94d..5232ac200e19 100644
--- a/src/main/claude/claude-structured-journal-translation.ts
+++ b/src/main/claude/claude-structured-journal-translation.ts
@@ -34,6 +34,7 @@ import { claudeChildToolQueries } from './claude-child-tool-queries'
import { journalClaudeMessage, type ClaudeMessageJournalContext } from './claude-message-journaling'
import { journalClaudeResult, type ClaudeResultJournalContext } from './claude-result-journaling'
import { ClaudeAuthenticationFailures } from './claude-authentication-failures'
+import { ClaudeUsageLimits } from './claude-usage-limits'
import { ClaudeThreadGoal } from './claude-thread-goal'
import type { ClaudeGoalBackgroundWork } from './claude-background-task-tracker'
import type { AgentSessionAccountKind } from '../../shared/agent-session-availability'
@@ -170,6 +171,7 @@ export function createClaudeJournalTranslator(
corrections,
turn,
authenticationFailures: new ClaudeAuthenticationFailures(deps.account),
+ usageLimits: new ClaudeUsageLimits(),
threadGoal: new ClaudeThreadGoal(() => deps.sink.journalLinkage?.()?.threadGoalSource())
}
@@ -249,6 +251,7 @@ export function createClaudeJournalTranslator(
journalClaudeResult(resultContext, event.message, event.observedAt ?? Date.now())
} else if (event.type === 'message') {
backgroundTasks.observe(event.message, event.observedAt ?? Date.now())
+ messageContext.usageLimits.observe(event.message)
const kind = claudeProviderFrameKind(event.message)
if (
!handleMessage(
@@ -269,10 +272,7 @@ export function createClaudeJournalTranslator(
}
context.observeResponse(event.message, event.observedAt ?? Date.now())
publishActivity(kind, event.message)
- // The CLI's own turn-over signal, and the only end a turn stopped by a
- // fault with no result frame ever gets. Reopen stays allowed: output
- // after an idle belongs to a turn, and suppressing it would read as
- // idle while the agent works.
+ // Idle also closes faults without a result; the live cause decides failed reopening.
if (claudeSessionStateEndsTurn(event.message)) {
corrections.abandon()
// No verdict: the CLI said the turn is over, not how it ended.
diff --git a/src/main/claude/claude-structured-provider-fallback.ts b/src/main/claude/claude-structured-provider-fallback.ts
index b8a84133e222..53da9cab6f13 100644
--- a/src/main/claude/claude-structured-provider-fallback.ts
+++ b/src/main/claude/claude-structured-provider-fallback.ts
@@ -1,4 +1,8 @@
-import type { AgentJournalTurnScope } from '../../shared/agent-session-journal-types'
+import type {
+ AgentJournalStatusItem,
+ AgentJournalTurnScope
+} from '../../shared/agent-session-journal-types'
+import type { AgentSessionFailureRowWords } from '../../shared/agent-session-failure-words'
import type { StructuredAgentSessionEventSink } from '../native-chat/agent-session-wire/structured-agent-session-event-sink'
import {
boundInlineText,
@@ -132,11 +136,12 @@ export function createClaudeProviderFrameFallback(
/** The frame's turn — the open one once `beforeAppend` ran — or the conversation. */
turnScope: () => AgentJournalTurnScope
): {
- /** `displayText` leads the row when Claude knows the sentence the frame itself does not name. */
+ /** `display` leads the row when Claude knows the sentence the frame itself does not name; a
+ * status body in its place also sets the row's tone and fact. */
append: (
kind: string,
payload: unknown,
- displayText?: string | null,
+ display?: string | null | (AgentSessionFailureRowWords & { tone: string }),
/** Runs only when a row is actually going to be written, so a frame that
* translates to nothing never opens a turn. */
beforeAppend?: () => void,
@@ -149,7 +154,7 @@ export function createClaudeProviderFrameFallback(
let sequence = 0
const retryRun = createClaudeApiRetryRuns()
return {
- append: (kind, payload, displayText, beforeAppend, options, stamp) => {
+ append: (kind, payload, display, beforeAppend, options, stamp) => {
sequence += 1
const retrying = kind === CLAUDE_API_RETRY_FRAME_KIND ? claudeRecord(payload) : null
if (retrying) {
@@ -190,14 +195,20 @@ export function createClaudeProviderFrameFallback(
return false
}
beforeAppend?.()
- const bounded = displayText
- ? boundInlineText(displayText, DEFAULT_JOURNAL_PAYLOAD_LIMITS).text
- : null
+ const bounded =
+ typeof display === 'string' && display
+ ? boundInlineText(display, DEFAULT_JOURNAL_PAYLOAD_LIMITS).text
+ : null
const identity = {
provider: 'orca',
clientMessageId: `provider-frame:claude:${acquisitionId}:${sequence}`
} as const
- const body = bounded ? { ...translated.body, text: bounded } : translated.body
+ const body: AgentJournalStatusItem =
+ display && typeof display === 'object'
+ ? { ...translated.body, ...display }
+ : bounded
+ ? { ...translated.body, text: bounded }
+ : translated.body
sink.appendItem(identity, body, stamp?.(identity, body) ?? { turnScope: turnScope() })
sink.publish()
return true
diff --git a/src/main/claude/claude-terminal-failure.ts b/src/main/claude/claude-terminal-failure.ts
new file mode 100644
index 000000000000..1afb24d1d5aa
--- /dev/null
+++ b/src/main/claude/claude-terminal-failure.ts
@@ -0,0 +1,92 @@
+import { agentJournalItemKey } from '../../shared/agent-session-journal-item-key'
+import type {
+ AgentJournalItemBody,
+ AgentJournalItemIdentity
+} from '../../shared/agent-session-journal-types'
+import { isRootAgentJournalItem } from '../../shared/agent-session-journal-producer'
+import { readAgentSessionFailureFact, providerDiagnostic } from '../../shared/agent-session-failure'
+import { agentSessionFailureWords } from '../../shared/agent-session-failure-words'
+import type {
+ StructuredAgentSessionEventSink,
+ StructuredAgentSessionRevisionJournal
+} from '../native-chat/agent-session-wire/structured-agent-session-event-sink'
+import {
+ agentJournalTurnRowReservedBytes,
+ resolveAgentJournalTurnRowWrite,
+ type AgentJournalTurnRowWrite
+} from '../native-chat/agent-session-timeline/agent-journal-turn-row-revision'
+
+function claudeTerminalFailureIdentity(turnItemId: string): AgentJournalItemIdentity {
+ return { provider: 'orca', clientMessageId: `terminal-failure:claude:${turnItemId}` }
+}
+
+export function writeClaudeTerminalFailure(
+ sink: StructuredAgentSessionEventSink,
+ identity: AgentJournalItemIdentity,
+ body: AgentJournalItemBody
+): void {
+ const turnItemId = agentJournalItemKey(identity)
+ const failureIdentity = claudeTerminalFailureIdentity(turnItemId)
+ const options = { turnScope: { kind: 'turn' as const, turnItemId } }
+ const revise = sink.tryReviseResolvedItemAndPublish
+ if (!revise) {
+ sink.appendItem(failureIdentity, body, options)
+ sink.publish()
+ return
+ }
+ const reservedBytes = Buffer.byteLength(JSON.stringify({ failureIdentity, body }), 'utf8') + 8192
+ revise.call(sink, reservedBytes, (journal) => mergeClaudeTerminalFailure(journal, identity, body), options)
+}
+
+function mergeClaudeTerminalFailure(
+ journal: StructuredAgentSessionRevisionJournal,
+ identity: AgentJournalItemIdentity,
+ body: AgentJournalItemBody
+) {
+ const failureIdentity = claudeTerminalFailureIdentity(agentJournalItemKey(identity))
+ const old = journal.itemBody(agentJournalItemKey(failureIdentity))
+ const prior = old?.kind === 'status' ? readAgentSessionFailureFact(old.failure) : undefined
+ const next = body.kind === 'status' ? readAgentSessionFailureFact(body.failure) : undefined
+ const previousDetail = prior?.detail?.text
+ const incomingDetail = next?.detail?.text
+ const detail = previousDetail && incomingDetail && !previousDetail.includes(incomingDetail)
+ ? `${previousDetail}\n${incomingDetail}` : previousDetail ?? incomingDetail ?? ''
+ const merged = prior?.kind === 'usageLimitReached' && next?.kind === 'usageLimitReached'
+ ? { ...body, ...agentSessionFailureWords({
+ ...prior, ...next,
+ usageLimit: next.usageLimit ?? prior.usageLimit,
+ detail: providerDiagnostic(detail, 'person')
+ }, { agentName: 'Claude', provider: 'claude', surface: 'row' }) }
+ : body
+ return JSON.stringify(merged) === JSON.stringify(old)
+ ? null : { identity: failureIdentity, body: merged }
+}
+
+// Refine only the ending row after its quota and any person Stop have landed.
+export function refineClaudeQuotaTurnEnd(
+ sink: StructuredAgentSessionEventSink,
+ identity: AgentJournalItemIdentity,
+ write: AgentJournalTurnRowWrite
+): boolean {
+ const revise = sink.tryReviseResolvedItemAndPublish
+ if (!revise || !write.lifecycle || write.lifecycle.outcome !== undefined) {
+ return false
+ }
+ const lifecycle = write.lifecycle
+ const target = { identity }
+ const reservedBytes = agentJournalTurnRowReservedBytes(target, write)
+ revise.call(sink, reservedBytes, (journal) => {
+ const itemId = agentJournalItemKey(identity)
+ const row = journal.item(agentJournalItemKey(claudeTerminalFailureIdentity(itemId)))
+ const quota = row?.body.kind === 'status' && isRootAgentJournalItem(row) &&
+ row.turnScope?.kind === 'turn' && row.turnScope.turnItemId === itemId &&
+ readAgentSessionFailureFact(row.body.failure)?.kind === 'usageLimitReached'
+ const stopped = lifecycle.completedAt !== undefined &&
+ sink.journalStopDecidesTurn?.(lifecycle.turnId, lifecycle.completedAt)
+ const outcome = quota ? (stopped ? 'cancellation' : 'failure') : undefined
+ return resolveAgentJournalTurnRowWrite(journal, target, {
+ ...write, lifecycle: { ...lifecycle, ...(outcome ? { outcome } : {}) }
+ }, reservedBytes)
+ }, { turnScope: { kind: 'thread' } })
+ return true
+}
diff --git a/src/main/claude/claude-thread-goal-journaling.test.ts b/src/main/claude/claude-thread-goal-journaling.test.ts
index 07fffc8e32ba..f117ee156e5e 100644
--- a/src/main/claude/claude-thread-goal-journaling.test.ts
+++ b/src/main/claude/claude-thread-goal-journaling.test.ts
@@ -6,6 +6,7 @@ import type {
} from '../../shared/agent-session-journal-types'
import type { StructuredAgentSessionEventSink } from '../native-chat/agent-session-wire/structured-agent-session-event-sink'
import { createClaudeJournalTranslator } from './claude-structured-journal-translation'
+import { journal } from './claude-context-usage-test-support'
import { ClaudeBackgroundTaskTracker } from './claude-background-task-tracker'
import { MOVED_TO_BACKGROUND } from './claude-captured-task-frames.test-fixture'
@@ -15,13 +16,15 @@ const OBJECTIVE = 'reply with exactly the word done'
function goalSink(
journalGoal: AgentJournalThreadGoal | null = null,
- journalRow?: { identity: AgentJournalItemIdentity; body: AgentJournalItemBody }
+ journalRow?: { identity: AgentJournalItemIdentity; body: AgentJournalItemBody },
+ deferred = false
) {
- const rows: { identity: AgentJournalItemIdentity; body: AgentJournalItemBody }[] = []
+ const state = journal({ deferred })
+ const rows = state.appends
let stopped = false
const backgroundTasks = new ClaudeBackgroundTaskTracker()
const sink: StructuredAgentSessionEventSink = {
- appendItem: (identity, body) => rows.push({ identity, body }),
+ ...state.sink,
appendTombstone: vi.fn(),
publish: vi.fn(),
journalStopDecidesTurn: () => stopped,
@@ -46,6 +49,7 @@ function goalSink(
let at = 1_000
const frame = (message: Record, elapsedMs = 1_000) => {
at += elapsedMs
+ state.clock.now = at
backgroundTasks.observe(message)
translator.handle({
type: 'message',
@@ -73,12 +77,12 @@ function goalSink(
const pressStop = () => {
stopped = true
}
- return { frame, reply, result, goals, savedGoal, pressStop }
+ return { frame, reply, result, goals, savedGoal, pressStop, flush: state.flush }
}
describe('Claude /goal journaling', () => {
- it('journals the goal Claude reports, its time, and its completion when Claude ends on its own', () => {
- const { reply, result, goals } = goalSink()
+ it.each([false, true])('journals the goal and its completion before adjacent idle (deferred %s)', (deferred) => {
+ const { frame, reply, result, goals, flush } = goalSink(null, undefined, deferred)
reply('goal-set', '', `Goal set: ${OBJECTIVE}`)
reply('work-1', 'claude-haiku-4-5', 'Working on it.')
// A turn cap stops Claude before the goal passes: the goal stays open and gains the time.
@@ -87,8 +91,11 @@ describe('Claude /goal journaling', () => {
{ subtype: 'error_max_turns', is_error: true, terminal_reason: 'max_turns' },
5_000
)
+ frame({ type: 'system', subtype: 'session_state_changed', state: 'idle' }, 1)
reply('work-2', 'claude-haiku-4-5', 'done')
result('result-2', { subtype: 'success', is_error: false, terminal_reason: 'completed' }, 3_000)
+ frame({ type: 'system', subtype: 'session_state_changed', state: 'idle' }, 1)
+ flush()
expect(goals()).toEqual([
{
diff --git a/src/main/claude/claude-usage-limits.test.ts b/src/main/claude/claude-usage-limits.test.ts
new file mode 100644
index 000000000000..45ee1520724b
--- /dev/null
+++ b/src/main/claude/claude-usage-limits.test.ts
@@ -0,0 +1,264 @@
+import { describe, expect, it, vi } from 'vitest'
+import { latestNativeChatUsageLimitCut } from '../../shared/native-chat-usage-limit-cut'
+import { agentJournalSubmissionKey } from '../../shared/agent-session-journal-item-key'
+import { adapterFor, fakeClaude, identityFor, PROVIDER_SESSION_ID, USER_MESSAGE } from './claude-structured-session-test-support'
+import { assistantFrame, frame, setup, userFrame } from './claude-context-usage-test-support'
+
+// Seconds, as Claude sends them; two hours out so no reset passes mid-test.
+const RESETS_AT_S = Math.floor(Date.now() / 1000) + 2 * 3600
+
+const rateLimitEvent = (status: string, at: number) =>
+ frame(
+ {
+ type: 'rate_limit_event',
+ uuid: `rate-${at}`,
+ rate_limit_info: { status, rateLimitType: 'five_hour', resetsAt: RESETS_AT_S }
+ },
+ at
+ )
+
+const refusedFrame = (uuid: string, at: number, text: string) =>
+ frame(
+ {
+ type: 'assistant',
+ uuid,
+ user_message_uuid: `turn-${uuid}`,
+ error: 'rate_limit',
+ is_api_error_message: true,
+ message: { role: 'assistant', content: [{ type: 'text', text }] }
+ },
+ at
+ )
+
+const failedResult = (uuid: string, at: number, text: string) =>
+ frame(
+ {
+ type: 'result',
+ subtype: 'success',
+ is_error: true,
+ result: text,
+ uuid: `result-${uuid}`,
+ user_message_uuid: `turn-${uuid}`,
+ duration_ms: 10
+ },
+ at
+ )
+
+const LIMIT_TEXT = "You've hit your limit · resets 3pm"
+
+function statusRows(t: ReturnType) {
+ return t.items().flatMap((item) => (item.body.kind === 'status' ? [item.body] : []))
+}
+
+function messageTexts(t: ReturnType): string[] {
+ return t
+ .items()
+ .flatMap((item) =>
+ item.body.kind === 'message'
+ ? item.body.blocks.flatMap((block) => (block.type === 'text' ? [block.text] : []))
+ : []
+ )
+}
+
+describe('a Claude usage limit', () => {
+ it.each([false, true])('keeps one limit row across a result and idle (quota first %s)', (quotaFirst) => {
+ const t = setup()
+ if (!quotaFirst) { t.handle(userFrame('turn-a', 1_000)) }
+ t.handle(rateLimitEvent('rejected', 1_100))
+ if (!quotaFirst) {
+ t.handle(frame({ ...assistantFrame('first', 1_150, 20).message, user_message_uuid: 'turn-a' }, 1_150))
+ }
+ t.handle(frame({
+ ...refusedFrame('a', 1_200, LIMIT_TEXT).message,
+ user_message_uuid: undefined,
+ api_error: 'usage_limit_reached'
+ }, 1_200))
+ t.handle(failedResult('a', 1_300, 'Request failed'))
+ t.handle(frame({ type: 'system', subtype: 'session_state_changed', state: 'idle' }, 1_301))
+ // The CLI throttles an unchanged rejection: the next turn carries none.
+ t.handle(userFrame('turn-b', 2_000))
+ t.handle(refusedFrame('b', 2_200, LIMIT_TEXT))
+ t.handle(failedResult('b', 2_300, LIMIT_TEXT))
+
+ const limitRow = {
+ kind: 'status',
+ tone: 'warning',
+ text: 'Claude hit its session limit. Send a message once it resets to continue.',
+ failure: {
+ kind: 'usageLimitReached',
+ usageLimit: { window: 'session', resetsAt: RESETS_AT_S * 1000 },
+ detail: { text: LIMIT_TEXT, audience: 'person' }
+ }
+ }
+ expect(statusRows(t)).toEqual([
+ { ...limitRow, failure: { ...limitRow.failure,
+ detail: { text: `${LIMIT_TEXT}\nRequest failed`, audience: 'person' } } },
+ limitRow
+ ])
+ expect(messageTexts(t)).not.toContain(LIMIT_TEXT)
+ t.translator.dispose()
+ })
+
+ it('keeps a removed-media notice before later work and its usage-limit warning', () => {
+ const t = setup({ deferred: true })
+ const removed = 'API Error: the image could not be processed and was removed'
+ t.handle(userFrame('turn-a', 1000))
+ t.handle(frame({ ...refusedFrame('media', 1100, removed).message,
+ api_error: 'media_removed', error: undefined, user_message_uuid: 'turn-a' }, 1100))
+ t.handle(assistantFrame('answer', 1200, 20))
+ t.handle(frame({ ...refusedFrame('a', 1300, LIMIT_TEXT).message,
+ api_error: 'usage_limit_reached' }, 1300))
+ t.handle(failedResult('a', 1400, LIMIT_TEXT))
+ t.flush()
+ const visible = t.items().flatMap(({ body }) =>
+ body.kind === 'message' && body.role === 'assistant'
+ ? body.blocks.flatMap((block) => block.type === 'text' ? [block.text] : [])
+ : body.kind === 'status' && body.failure?.kind === 'usageLimitReached' ? ['quota'] : []
+ )
+ expect(visible).toEqual([removed, 'answer', 'quota'])
+ t.translator.dispose()
+ })
+
+ it('keeps typed other causes and replacement turns separate from the account snapshot', () => {
+ const t = setup()
+ t.handle(userFrame('turn-limited', 1_000))
+ t.handle(rateLimitEvent('rejected', 1_100))
+ t.handle(refusedFrame('limited', 1_200, LIMIT_TEXT))
+ // No result: a replacement turn must not inherit the previous refusal.
+ t.handle(userFrame('turn-credits', 2_000))
+ t.handle(frame({
+ ...refusedFrame('credits', 2_100, 'This model requires usage credits').message,
+ api_error: 'model_requires_usage_credits'
+ }, 2_100))
+ t.handle(frame({
+ ...failedResult('credits', 2_200, 'This model requires usage credits').message,
+ terminal_reason: 'api_error', api_error_status: 429
+ }, 2_200))
+ expect(statusRows(t).filter((row) => row.failure?.kind === 'usageLimitReached')).toHaveLength(1)
+ expect(statusRows(t).some((row) => row.text.includes('requires usage credits'))).toBe(true)
+ t.handle(userFrame('turn-context', 2300))
+ t.handle(frame({ ...refusedFrame('context', 2400, 'Prompt is too long').message,
+ error: 'invalid_request' }, 2400))
+ t.handle(frame({ ...failedResult('context', 2500, 'Prompt is too long').message,
+ terminal_reason: 'blocking_limit', api_error_status: null }, 2500))
+ expect(statusRows(t).at(-1)).toMatchObject({ tone: 'error', text: 'Prompt is too long' })
+ t.translator.dispose()
+ })
+
+ it('keeps an explicit quota cause without metadata and expires snapshot inference', () => {
+ const clock = vi.spyOn(Date, 'now').mockReturnValue(RESETS_AT_S * 1000 - 1000)
+ try {
+ const t = setup()
+ t.handle(userFrame('turn-typed', 1000))
+ t.handle(frame({ ...refusedFrame('typed', 1100, LIMIT_TEXT).message,
+ api_error: 'usage_limit_reached' }, 1100))
+ t.handle(failedResult('typed', 1200, LIMIT_TEXT))
+ t.handle(rateLimitEvent('rejected', 1300))
+ clock.mockReturnValue(RESETS_AT_S * 1000 + 1000)
+ t.handle(userFrame('turn-expired', 2000))
+ t.handle(refusedFrame('expired', 2100, 'Request rejected'))
+ t.handle(failedResult('expired', 2200, 'Request rejected'))
+ const limits = statusRows(t).filter((row) => row.failure?.kind === 'usageLimitReached')
+ expect(limits).toHaveLength(1)
+ expect(limits[0]?.failure?.usageLimit).toBeUndefined()
+ t.translator.dispose()
+ } finally {
+ clock.mockRestore()
+ }
+ })
+
+ it('leaves a throttle once the limit allows requests again', () => {
+ const t = setup()
+ t.handle(rateLimitEvent('rejected', 1_100))
+ t.handle(rateLimitEvent('allowed_warning', 1_500))
+ t.handle(userFrame('turn-a', 2_000))
+ t.handle(refusedFrame('a', 2_200, 'API Error: Request rejected (429)'))
+ t.handle(failedResult('a', 2_300, 'API Error: Request rejected (429)'))
+
+ expect(statusRows(t).map((row) => row.failure?.kind)).not.toContain('usageLimitReached')
+ expect(statusRows(t)).toContainEqual(
+ expect.objectContaining({ tone: 'error', text: 'API Error: Request rejected (429)' })
+ )
+ t.translator.dispose()
+ })
+})
+
+const quota = (uuid: string, stamp?: string) => frame({
+ ...refusedFrame(uuid, 1100, LIMIT_TEXT).message,
+ user_message_uuid: stamp, api_error: 'usage_limit_reached'
+}, 1100)
+
+it.each(['idle', 'exit'] as const)('keeps quota failure and Continue through a deferred resultless %s', (ending) => {
+ const t = setup({ deferred: true })
+ t.handle(userFrame('owner', 1000))
+ t.handle(quota('refusal', 'owner'))
+ if (ending === 'idle') {
+ t.handle(frame({ type: 'system', subtype: 'session_state_changed', state: 'idle' }, 1200))
+ } else {
+ t.handle({ type: 'ended', sessionId: 'orca-session', reason: 'Provider exited', observedAt: 1200 })
+ }
+ t.flush()
+ expect(t.turnRow('owner')?.body).toMatchObject({
+ state: ending === 'idle' ? 'completed' : 'interrupted', outcome: 'failure'
+ })
+ expect(latestNativeChatUsageLimitCut(t.items(), [])).not.toBeNull()
+ t.translator.dispose()
+})
+
+it.each(['before', 'after', 'child', 'ordinary', 'success', 'other', 'superseded'] as const)('preserves %s precedence over resultless quota inference', (mode) => {
+ const t = setup({ deferred: true })
+ t.handle(userFrame('owner', 1000))
+ if (mode !== 'ordinary') {
+ t.handle(frame({ ...quota('refusal', 'owner').message,
+ ...(mode === 'child' ? { parent_tool_use_id: 'child-tool' } : {}) }, 1100))
+ }
+ if (mode === 'other') {
+ t.handle(frame({ ...refusedFrame('other', 1150, 'Requires credits').message,
+ api_error: 'model_requires_usage_credits', user_message_uuid: 'owner' }, 1150))
+ }
+ if (mode === 'before') {
+ t.queueStop('owner', 1150)
+ expect(t.sink.journalStopDecidesTurn?.('owner', 1200)).toBe(false)
+ }
+ if (mode === 'success') {
+ t.handle(frame({ type: 'result', subtype: 'success', is_error: false, result: 'done' }, 1200))
+ } else if (mode === 'superseded') {
+ t.handle(userFrame('newer', 1200))
+ } else if (mode === 'before') {
+ t.handle(frame({ type: 'system', subtype: 'session_state_changed', state: 'idle' }, 1200))
+ } else {
+ t.handle({ type: 'ended', sessionId: 'orca-session', reason: 'Provider exited', observedAt: 1200 })
+ }
+ if (mode === 'after') { t.queueStop('owner', 1300) }
+ t.flush()
+ const outcome = mode === 'before' ? 'cancellation' : mode === 'after' ? 'failure'
+ : mode === 'success' ? 'success' : mode === 'superseded' ? 'superseded' : undefined
+ const body = t.turnRow('owner')?.body
+ expect(body?.kind === 'turn' ? body.outcome : null).toEqual(outcome)
+ expect(latestNativeChatUsageLimitCut(t.items(), []) !== null).toBe(mode === 'after')
+ t.translator.dispose()
+})
+
+it('retains a newly accepted pre-echo failure after acquisition has consumed its exact waiter', async () => {
+ const t = setup()
+ t.translator.dispose()
+ const claude = fakeClaude({ replayUuid: null })
+ const adapter = adapterFor(claude)
+ await adapter.acquire({ identity: identityFor(), fence: 7, spawnToken: 'quota-test', events: t.sink })
+ const connection = claude.connections[0]!
+ const emit = (message: Record) => connection.handlers.onMessage?.({
+ parent_tool_use_id: null, ...message, session_id: PROVIDER_SESSION_ID
+ })
+ await adapter.dispatch({ sessionId: 'session-1', clientMessageId: 'first', body: USER_MESSAGE, fence: 7 })
+ emit({ ...connection.sent[0], uuid: 'owner' })
+ emit(quota('refusal', 'owner').message)
+ emit({ ...failedResult('owner', 1200, LIMIT_TEXT).message, user_message_uuid: 'owner' })
+ t.sink.appendItem({ provider: 'orca', clientMessageId: 'new-send' }, USER_MESSAGE, { turnScope: { kind: 'thread' } })
+ await adapter.dispatch({ sessionId: 'session-1', clientMessageId: 'new-send', body: USER_MESSAGE, fence: 7 })
+ const sent = connection.sent.at(-1)!
+ emit({ type: 'result', uuid: 'new-result', user_message_uuid: sent.uuid,
+ subtype: 'error_during_execution', is_error: true, result: 'Fresh request rejected' })
+ expect(t.items().some((item) => item.itemId === agentJournalSubmissionKey('new-send'))).toBe(true)
+ expect(statusRows(t).some((row) => row.text.includes('Fresh request rejected'))).toBe(true)
+ await adapter.closeSession('session-1')
+})
diff --git a/src/main/claude/claude-usage-limits.ts b/src/main/claude/claude-usage-limits.ts
new file mode 100644
index 000000000000..cee66cf9b2d1
--- /dev/null
+++ b/src/main/claude/claude-usage-limits.ts
@@ -0,0 +1,160 @@
+import { agentSessionFailureFact, providerDiagnostic } from '../../shared/agent-session-failure'
+import {
+ agentSessionFailureWords,
+ type AgentSessionFailureRowWords
+} from '../../shared/agent-session-failure-words'
+import {
+ usageLimitResetsAt,
+ type AgentSessionUsageLimit,
+ type AgentSessionUsageLimitWindow
+} from '../../shared/agent-session-usage-limit'
+import type { ClaudeOpenTurn } from './claude-open-turn'
+import { claudeRecord, claudeText } from './claude-structured-item-translation'
+
+const CLAUDE_LIMIT_WINDOWS: Record = {
+ five_hour: 'session',
+ seven_day: 'weekly',
+ seven_day_opus: 'weeklyModel',
+ seven_day_sonnet: 'weeklyModel',
+ seven_day_overage_included: 'weeklyModel',
+ overage: 'credits'
+}
+
+/** The ends a result reports when a limit refused its request; any other is a different failure. */
+const LIMIT_TERMINAL_REASONS = ['api_error']
+
+export type ClaudeUsageLimitRow = AgentSessionFailureRowWords & {
+ kind: 'status'
+ tone: 'warning'
+}
+
+function messageText(message: Record): string {
+ const content = claudeRecord(message.message)?.content
+ return Array.isArray(content)
+ ? content
+ .flatMap((part) => {
+ const value = claudeRecord(part)
+ return value?.type === 'text' && typeof value.text === 'string' ? [value.text] : []
+ })
+ .join('\n')
+ : ''
+}
+
+export type ClaudeUsageLimitEvidence = {
+ cause: 'quota' | 'other' | 'untyped'
+}
+
+// Account observations outlive turns because unchanged rejection notifications are throttled.
+export class ClaudeUsageLimits {
+ private readonly rejected = new Map()
+
+ constructor(private readonly now: () => number = Date.now) {}
+
+ observe(message: Record): void {
+ if (message.type === 'rate_limit_event') {
+ this.record(claudeRecord(message.rate_limit_info))
+ }
+ }
+
+ assistant(message: Record, turn?: ClaudeOpenTurn): ClaudeUsageLimitRow | null {
+ if (message.type !== 'assistant') {
+ return null
+ }
+ const typed = claudeText(message.api_error)
+ const cause = typed === 'usage_limit_reached' ? 'quota' : typed ? 'other' : 'untyped'
+ if (cause === 'quota') {
+ this.record(claudeRecord(claudeRecord(message.api_error_params)?.rate_limit_info))
+ }
+ const refused = message.error === 'rate_limit' || cause === 'quota'
+ const root = message.parent_tool_use_id == null
+ const decision = !typed && root ? (turn?.usageLimitEvidence?.cause ?? cause) : cause
+ const row =
+ decision !== 'other' && refused
+ ? this.row(messageText(message), decision === 'quota')
+ : null
+ if (root && turn?.isOpen && (typed || (refused && decision === 'untyped'))) {
+ turn.usageLimitEvidence = { cause: row ? 'quota' : cause }
+ }
+ return row
+ }
+
+ result(
+ message: Record,
+ failed: boolean,
+ evidence: ClaudeUsageLimitEvidence | null
+ ): ClaudeUsageLimitRow | null {
+ if (!failed || evidence?.cause === 'other') {
+ return null
+ }
+ const status = message.api_error_status
+ const reason = claudeText(message.terminal_reason)
+ const limited =
+ evidence?.cause === 'quota' ||
+ (evidence?.cause === 'untyped' &&
+ (status == null || status === 429) &&
+ (reason === null || LIMIT_TERMINAL_REASONS.includes(reason)))
+ if (!limited) {
+ return null
+ }
+ return this.row(claudeText(message.result) ?? '', evidence?.cause === 'quota')
+ }
+
+ private record(info: Record | null): void {
+ if (!info) {
+ return
+ }
+ const type = claudeText(info.rateLimitType) ?? 'unknown'
+ const overage =
+ info.overageStatus === 'allowed' ||
+ info.overageStatus === 'allowed_warning' ||
+ info.isUsingOverage === true ||
+ info.overageInUse === true
+ if (info.status === 'rejected' && !overage) {
+ const seconds = info.resetsAt
+ const resetsAt =
+ typeof seconds === 'number' ? usageLimitResetsAt(seconds * 1000, this.now()) : undefined
+ this.rejected.set(type, resetsAt ?? null)
+ } else if (info.status === 'allowed' || info.status === 'allowed_warning' || overage) {
+ this.rejected.delete(type)
+ }
+ }
+
+ /** Every refusing limit must reset before a request can run, so the latest reset is the one. */
+ private limit(): AgentSessionUsageLimit | null {
+ const now = this.now()
+ for (const [type, resetsAt] of this.rejected) {
+ if (resetsAt !== null && resetsAt <= now) {
+ this.rejected.delete(type)
+ }
+ }
+ if (this.rejected.size === 0) {
+ return null
+ }
+ const windows = new Set([...this.rejected.keys()].map((type) => CLAUDE_LIMIT_WINDOWS[type]))
+ const window = windows.size === 1 ? [...windows][0] : undefined
+ const resets = [...this.rejected.values()].filter((reset): reset is number => reset !== null)
+ const resetsAt = resets.length === this.rejected.size ? Math.max(...resets) : undefined
+ return { ...(window ? { window } : {}), ...(resetsAt ? { resetsAt } : {}) }
+ }
+
+ private row(
+ providerText: string,
+ typed = false
+ ): ClaudeUsageLimitRow | null {
+ const limit = this.limit()
+ if (!limit && !typed) {
+ return null
+ }
+ return {
+ kind: 'status',
+ tone: 'warning',
+ ...agentSessionFailureWords(
+ agentSessionFailureFact('usageLimitReached', {
+ ...(limit && (limit.window || limit.resetsAt) ? { usageLimit: limit } : {}),
+ detail: providerDiagnostic(providerText, 'person')
+ }),
+ { agentName: 'Claude', provider: 'claude', surface: 'row' }
+ )
+ }
+ }
+}
diff --git a/src/main/codex/codex-structured-journal-generic-frames.ts b/src/main/codex/codex-structured-journal-generic-frames.ts
index 64e80bffc2b5..f9907dfd9edf 100644
--- a/src/main/codex/codex-structured-journal-generic-frames.ts
+++ b/src/main/codex/codex-structured-journal-generic-frames.ts
@@ -25,6 +25,7 @@ import {
import type { CodexRowAttribution } from './codex-subagent-linkage'
import { codexAuthenticationFailure } from './codex-authentication-failure'
import { agentSessionFailureWords } from '../../shared/agent-session-failure-words'
+import { CodexUsageLimits } from './codex-usage-limits'
const OVERFLOW_BUCKET = '__codex-generic-overflow__'
/** A turn's rows by whether a client draws them; each kind has its own cap. */
@@ -70,6 +71,7 @@ export class CodexJournalGenericFrames {
private bookkeepingBytes = 0
private fallbackSequence = 0
private cancelSuppressionFlush: (() => void) | null = null
+ private readonly usageLimits = new CodexUsageLimits()
constructor(
private readonly deps: Pick<
@@ -89,20 +91,24 @@ export class CodexJournalGenericFrames {
payload: unknown,
threadId: string
): CodexJournalTranslationAdmission {
+ if (this.usageLimits.observe(kind, payload)) {
+ return CODEX_JOURNAL_ADMITTED
+ }
const translated = unhandledProviderFrameJournalItem('codex', kind, payload)
// A frame the classifier declines is deliberately not journaled, which is success.
// Failing admission here force-closes the provider through the retry queue.
- const auth =
- kind === 'notification:error' && !readCodexErrorWillRetry(payload)
- ? codexAuthenticationFailure(payload, this.deps.account?.())
- : null
+ const ended = kind === 'notification:error' && !readCodexErrorWillRetry(payload)
+ const usageLimit = ended ? this.usageLimits.failure(payload) : null
+ const failure =
+ usageLimit ?? (ended ? codexAuthenticationFailure(payload, this.deps.account?.()) : null)
return translated
? this.appendFrameRow(threadId, payload, {
...translated,
- body: auth
+ body: failure
? {
...translated.body,
- ...agentSessionFailureWords(auth, {
+ ...(usageLimit ? { tone: 'warning' } : {}),
+ ...agentSessionFailureWords(failure, {
provider: 'codex',
agentName: 'Codex',
surface: 'row'
@@ -152,7 +158,9 @@ export class CodexJournalGenericFrames {
this.fallbackSequence += 1
const identity = {
provider: 'orca' as const,
- clientMessageId: `provider-frame:codex:${this.deps.acquisitionId ?? 'acquisition'}:${this.fallbackSequence}`
+ clientMessageId: translated.body.failure?.kind === 'usageLimitReached' && frameTurnId
+ ? `terminal-failure:codex:${JSON.stringify([threadId, frameTurnId])}`
+ : `provider-frame:codex:${this.deps.acquisitionId ?? 'acquisition'}:${this.fallbackSequence}`
}
const attribution = this.deps.attributionFor(threadId, frameTurnId)
const admission = this.deps.sink.tryAppendItem
diff --git a/src/main/codex/codex-usage-limits.test.ts b/src/main/codex/codex-usage-limits.test.ts
new file mode 100644
index 000000000000..818fbb2c6504
--- /dev/null
+++ b/src/main/codex/codex-usage-limits.test.ts
@@ -0,0 +1,84 @@
+import { describe, expect, it } from 'vitest'
+import type { AgentJournalItemBody } from '../../shared/agent-session-journal-types'
+import { CodexUsageLimits } from './codex-usage-limits'
+import { createCodexJournalTranslator } from './codex-structured-journal-translation'
+
+const RESETS_AT_S = Math.floor(Date.now() / 1000) + 3 * 24 * 3600
+const CODEX_WORDS = "You've hit your usage limit. Try again in 3 days."
+
+function translatorWithRows() {
+ const bodies: AgentJournalItemBody[] = []
+ const translator = createCodexJournalTranslator({
+ primaryThreadId: () => 'thread',
+ sink: {
+ appendItem: (_identity, body) => bodies.push(body),
+ appendTombstone: () => {},
+ publish: () => {}
+ }
+ })
+ const notify = (method: string, params: Record) =>
+ translator.handle({
+ type: 'notification',
+ sessionId: 'session',
+ threadId: 'thread',
+ method,
+ params
+ })
+ return { bodies, translator, notify }
+}
+
+describe('a Codex usage limit', () => {
+ it('names the spent window and its reset from the last usage report', () => {
+ const { bodies, translator, notify } = translatorWithRows()
+ notify('account/rateLimits/updated', {
+ rateLimits: {
+ limitId: 'codex',
+ primary: { usedPercent: 40, windowDurationMins: 300, resetsAt: RESETS_AT_S - 3600 },
+ secondary: { usedPercent: 100, windowDurationMins: 10080, resetsAt: RESETS_AT_S }
+ }
+ })
+ // An update may carry only what changed; the spent weekly window still stands.
+ notify('account/rateLimits/updated', {
+ rateLimits: {
+ primary: { usedPercent: 41, windowDurationMins: 300, resetsAt: RESETS_AT_S - 3600 }
+ }
+ })
+ notify('error', {
+ threadId: 'thread',
+ turnId: 'turn',
+ willRetry: false,
+ error: { codexErrorInfo: 'usageLimitExceeded', message: CODEX_WORDS }
+ })
+
+ expect(bodies.filter((body) => body.kind === 'status')).toEqual([
+ expect.objectContaining({
+ tone: 'warning',
+ text: 'Codex hit its weekly limit. Send a message once it resets to continue.',
+ failure: {
+ kind: 'usageLimitReached',
+ usageLimit: { window: 'weekly', resetsAt: RESETS_AT_S * 1000 },
+ detail: { text: CODEX_WORDS, audience: 'person' }
+ }
+ })
+ ])
+ translator.dispose()
+ })
+ it('merges null account updates and keeps unnamed exhausted windows in reset calculation', () => {
+ const limits = new CodexUsageLimits()
+ const observe = (rateLimits: Record) =>
+ limits.observe('notification:account/rateLimits/updated', { rateLimits })
+ const failure = (code = 'usageLimitExceeded') => limits.failure({
+ error: { codexErrorInfo: code, message: CODEX_WORDS }
+ })
+ observe({ limitId: 'codex', primary: { usedPercent: 100, windowDurationMins: 300, resetsAt: RESETS_AT_S } })
+ observe({ limitId: null, primary: { usedPercent: 100, windowDurationMins: 43200, resetsAt: RESETS_AT_S + 3600 } })
+ expect(failure()?.usageLimit).toEqual({ resetsAt: (RESETS_AT_S + 3600) * 1000 })
+ observe({ secondary: { usedPercent: 100, windowDurationMins: 10080 } })
+ expect(failure('rateLimitExceeded')?.usageLimit).toBeUndefined()
+ observe({ secondary: null, planType: 'free', primary: { usedPercent: 100, resetsAt: RESETS_AT_S } })
+ expect(failure()?.usageLimit).toEqual({ resetsAt: RESETS_AT_S * 1000 })
+ observe({ primary: null })
+ expect(failure()?.usageLimit).toBeUndefined()
+ })
+
+})
diff --git a/src/main/codex/codex-usage-limits.ts b/src/main/codex/codex-usage-limits.ts
new file mode 100644
index 000000000000..820ec2337833
--- /dev/null
+++ b/src/main/codex/codex-usage-limits.ts
@@ -0,0 +1,101 @@
+import { agentSessionFailureFact, providerDiagnostic } from '../../shared/agent-session-failure'
+import {
+ usageLimitResetsAt,
+ type AgentSessionUsageLimit,
+ type AgentSessionUsageLimitWindow
+} from '../../shared/agent-session-usage-limit'
+import type { CodexRateLimitWindowsSnapshot } from '../rate-limits/codex-rate-limit-window-classification'
+import {
+ readCodexErrorAdditionalDetails,
+ readCodexErrorInfo,
+ readCodexErrorMessage
+} from './codex-structured-thread-facts'
+
+const RATE_LIMITS_UPDATED = 'notification:account/rateLimits/updated'
+const USAGE_LIMIT_ERRORS = ['usageLimitExceeded', 'rateLimitExceeded']
+
+type CodexAccountRateLimits = CodexRateLimitWindowsSnapshot & { rateLimitReachedType?: unknown; planType?: unknown }
+
+function record(value: unknown): Record | null {
+ return typeof value === 'object' && value !== null && !Array.isArray(value) ? { ...value } : null
+}
+
+/**
+ * The account's usage as Codex last reported it (`account/rateLimits/updated`), so a turn its usage
+ * limit ended can say which limit and when it resets.
+ */
+export class CodexUsageLimits {
+ private snapshot: CodexAccountRateLimits = {}
+
+ constructor(private readonly now: () => number = Date.now) {}
+
+ /** Whether the frame was a usage report, which this keeps and nothing else journals. */
+ observe(kind: string, payload: unknown): boolean {
+ if (kind !== RATE_LIMITS_UPDATED) {
+ return false
+ }
+ const update = record(record(payload)?.rateLimits)
+ // Another limit id is one model's own bucket, not the account's session or weekly limit.
+ if (update && (update.limitId == null || update.limitId === 'codex')) {
+ // An update may carry only the fields that changed.
+ this.snapshot = {
+ ...this.snapshot,
+ ...Object.fromEntries(Object.entries(update).filter(([, value]) => value !== undefined))
+ }
+ }
+ return true
+ }
+
+ /** The fact for an `error` frame that Codex's usage limit ended the turn with; null otherwise. */
+ failure(payload: unknown) {
+ const error = readCodexErrorInfo(payload)?.error
+ if (!error || !USAGE_LIMIT_ERRORS.includes(error)) {
+ return null
+ }
+ const message = readCodexErrorMessage(payload)
+ const additional = readCodexErrorAdditionalDetails(payload)
+ const text = [message, additional && additional !== message ? additional : null]
+ .filter((part): part is string => part !== null)
+ .join('\n')
+ const limit = this.limit()
+ return agentSessionFailureFact('usageLimitReached', {
+ ...(limit ? { usageLimit: limit } : {}),
+ detail: providerDiagnostic(text, 'person')
+ })
+ }
+
+ /** Every spent window must reset before a turn can run, so the latest reset is the one; none
+ * when any spent window gave no reset. */
+ private limit(): AgentSessionUsageLimit | null {
+ const monthlyPlan = this.snapshot.planType === 'free' || this.snapshot.planType === 'go'
+ const spent = ([['primary', monthlyPlan ? 43200 : 300], ['secondary', 10080]] as const).flatMap(([position, fallback]) => {
+ const raw = this.snapshot[position]
+ if (!raw || typeof raw.usedPercent !== 'number' || !Number.isFinite(raw.usedPercent) || raw.usedPercent < 100) {
+ return []
+ }
+ const duration = raw.windowDurationMins === undefined || raw.windowDurationMins === null
+ ? fallback : raw.windowDurationMins
+ const window = typeof duration === 'number' && Number.isFinite(duration) && duration > 0
+ ? duration >= 43200 ? undefined : duration >= 10080 ? 'weekly' as const : 'session' as const
+ : undefined
+ return [{ window, resetsAt: raw.resetsAt }]
+ })
+ const reached = this.snapshot.rateLimitReachedType
+ const credits = typeof reached === 'string' && reached.endsWith('credits_depleted')
+ const window: AgentSessionUsageLimitWindow | undefined = credits
+ ? 'credits'
+ : spent.length === 1
+ ? spent[0]?.window
+ : undefined
+ const resets = spent.flatMap((entry) =>
+ typeof entry.resetsAt === 'number' ? [entry.resetsAt * 1000] : []
+ )
+ const resetsAt =
+ resets.length > 0 && resets.length === spent.length
+ ? usageLimitResetsAt(Math.max(...resets), this.now())
+ : undefined
+ return window || resetsAt
+ ? { ...(window ? { window } : {}), ...(resetsAt ? { resetsAt } : {}) }
+ : null
+ }
+}
diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-event-sink.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-event-sink.ts
index 1f48f0680584..eab76ae0143c 100644
--- a/src/main/native-chat/agent-session-wire/structured-agent-session-event-sink.ts
+++ b/src/main/native-chat/agent-session-wire/structured-agent-session-event-sink.ts
@@ -68,7 +68,7 @@ export type StructuredAgentSessionIdentityResolver = (
/** What a revision reads: a keyed read for a row it can name, and the scan for one it cannot. */
export type StructuredAgentSessionRevisionJournal = Pick<
AgentSessionJournal,
- 'epoch' | 'visitItems' | 'itemBody'
+ 'epoch' | 'visitItems' | 'itemBody' | 'item'
>
/** Rows already journaled and who produced each, read by a producer that has to agree with them. */
diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-host-mutations.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-host-mutations.ts
index a324b34b7421..411106d73c44 100644
--- a/src/main/native-chat/agent-session-wire/structured-agent-session-host-mutations.ts
+++ b/src/main/native-chat/agent-session-wire/structured-agent-session-host-mutations.ts
@@ -7,6 +7,10 @@
// admitted without the writer lease; the delivery loop starts the provider child a send needs, and
// an operation only the provider can perform starts it before admission.
+import { latestNativeChatUsageLimitCut } from '../../../shared/native-chat-usage-limit-cut'
+import { refuse } from '../../../shared/agent-session-wire'
+import { contextStructuredAgentSessionCurrentWork } from './structured-agent-session-current-work'
+import { shouldQueueStructuredAgentSessionSend } from './structured-agent-session-queued-messages'
import type { AgentJournalMessageItem } from '../../../shared/agent-session-journal-types'
import type {
AgentSessionCancelResult,
@@ -71,6 +75,7 @@ export function sendStructuredAgentSessionTurn(
/** Host-local: whether the sending client can manage an image card. */
queuedImageCards?: boolean
options?: Readonly>
+ usageLimitContinuationOfTurnItemId?: string
/** Host-local, set only by the client-facing `agentSession.send` RPC (the
* renderer's launch prompt included): recorded as the submission's `client`
* origin, so a restart or a close keeps it as a card if it never reached the
@@ -92,15 +97,35 @@ export function sendStructuredAgentSessionTurn(
params.envelope,
{
...plan,
- run: (ctx) =>
- runQueueableStructuredAgentSessionSend(
- context,
- ctx,
- params,
- async () =>
- structuredAgentSessionSendBlock(context.deps.store.getRecord(ctx.sessionId)) ??
- (await plan.run(ctx))
- )
+ run: async (ctx) => {
+ const record = context.deps.store.getRecord(ctx.sessionId)
+ const blocked = structuredAgentSessionSendBlock(record)
+ if (blocked) {
+ return blocked
+ }
+ if (params.usageLimitContinuationOfTurnItemId !== undefined) {
+ const snapshot = ctx.journal.snapshot()
+ const cut = latestNativeChatUsageLimitCut(snapshot.items, snapshot.submissions)
+ if (
+ cut?.turnItemId !== params.usageLimitContinuationOfTurnItemId ||
+ shouldQueueStructuredAgentSessionSend({
+ record,
+ journal: ctx.journal,
+ work: contextStructuredAgentSessionCurrentWork(ctx)
+ })
+ ) {
+ return {
+ ok: false as const,
+ refusal: refuse(
+ 'agent_session_operation_invalid',
+ { reason: 'continuationSuperseded' },
+ 'This chat has moved on. Check the latest messages before continuing.'
+ )
+ }
+ }
+ }
+ return runQueueableStructuredAgentSessionSend(context, ctx, params, () => plan.run(ctx))
+ }
},
sendPreparation(context, params.envelope, arrival, selection)
)
diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-queued-action-receipts.test.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-queued-action-receipts.test.ts
index 83b98e806eec..146fc6d853c6 100644
--- a/src/main/native-chat/agent-session-wire/structured-agent-session-queued-action-receipts.test.ts
+++ b/src/main/native-chat/agent-session-wire/structured-agent-session-queued-action-receipts.test.ts
@@ -3,6 +3,11 @@
// another command already used is refused.
import { afterEach, beforeEach, describe, expect, it } from 'vitest'
+import { agentSessionFailureWords } from '../../../shared/agent-session-failure-words'
+import { agentJournalItemKey } from '../../../shared/agent-session-journal-item-key'
+import { agentSessionSendBodyFingerprint } from '../../../shared/structured-agent-session-send-mutation'
+import { holdLane } from './structured-agent-session-delivery-hold.test-fixture'
+import { structuredAgentSessionHostInstance } from './structured-agent-session-queued-pause'
import { AGENT_SESSION_MAX_NEW_OPERATION_AGE_MS } from '../../../shared/agent-session-host-authority'
import { openTestJournalHostDatabase } from '../agent-session-journal/journal-host-database-test-support'
import {
@@ -12,7 +17,8 @@ import {
} from './structured-agent-session-queued-message-rig.test-fixture'
import {
HOST_TEST_NOW as NOW,
- HOST_TEST_SESSION as SESSION
+ HOST_TEST_SESSION as SESSION,
+ hostTestMessage
} from './structured-agent-session-host-test-data'
const CALLER_SCOPE = { kind: 'caller', callerKey: CALLER.callerKey } as const
@@ -549,3 +555,80 @@ describe('an id reused across commands', () => {
expect(await rig.deleteQueued(second, sendId)).toMatchObject(conflict)
})
})
+
+
+describe('source-bound ordinary Continue', () => {
+ async function limitedTurn(id: string) {
+ const journal = rig.host.collaboratorsForTests().sessions.get(SESSION)?.journal
+ if (!journal) {
+ throw new Error('expected an open journal')
+ }
+ const identity = { provider: 'orca' as const, clientMessageId: id }
+ const turnItemId = agentJournalItemKey(identity)
+ await journal.appendItem(identity, {
+ kind: 'turn', turnId: id, state: 'completed', outcome: 'failure',
+ startedAt: NOW, completedAt: NOW
+ }, { fence: 1, turnScope: { kind: 'thread' } })
+ await journal.appendItem({ provider: 'orca', clientMessageId: `failure-${id}` }, {
+ kind: 'status',
+ ...agentSessionFailureWords({ kind: 'usageLimitReached' }, { surface: 'row' })
+ }, { fence: 1, turnScope: { kind: 'turn', turnItemId } })
+ return { journal, turnItemId }
+ }
+ function params(source: string, id = opId(), options?: Record) {
+ const fields = {
+ body: hostTestMessage('Continue where you left off.'), delivery: 'queue-if-active' as const,
+ usageLimitContinuationOfTurnItemId: source, ...(options ? { options } : {})
+ }
+ return { ...fields, envelope: rig.envelope(fields, 'agentSession.send', id) }
+ }
+ const superseded = { ok: false, refusal: { details: { reason: 'continuationSuperseded' } } }
+
+ it('admits one of two clients, replays its receipt after newer work, and conflicts on changed controls', async () => {
+ const { journal, turnItemId } = await limitedTurn('limited')
+ const first = params(turnItemId)
+ const second = params(turnItemId)
+ const answers = await Promise.all([
+ rig.host.send(CALLER, first), rig.host.send({ callerKey: 'phone' }, second)
+ ])
+ expect(answers[0]).toMatchObject({ ok: true, replayed: false })
+ expect(answers[1]).toMatchObject(superseded)
+ expect(journal.submissions()).toHaveLength(1)
+ expect(journal.queuedMessages.list()).toHaveLength(0)
+ await rig.send('newer ordinary message').result
+ expect(await rig.host.send(CALLER, first)).toMatchObject({ ok: true, replayed: true })
+ for (const changed of [params('another-turn', first.envelope.clientOperationId),
+ params(turnItemId, first.envelope.clientOperationId, { model: 'other' })]) {
+ expect(await rig.host.send(CALLER, changed)).toMatchObject(CONFLICT)
+ }
+ expect(journal.submissions()).toHaveLength(2)
+ })
+
+ it('refuses a stale action and actionable backlog before writing a submission or queue card', async () => {
+ const { journal, turnItemId } = await limitedTurn('old')
+ await rig.send('ordinary message wins').result
+ const before = journal.snapshot().items.map((item) => item.itemId)
+ const requests = journal.submissions().map((entry) => entry.clientMessageId)
+ expect(await rig.host.send(CALLER, params(turnItemId))).toMatchObject(superseded)
+ expect(journal.snapshot().items.map((item) => item.itemId)).toEqual(before)
+ expect(journal.submissions().map((entry) => entry.clientMessageId)).toEqual(requests)
+ expect(journal.queuedMessages.list()).toHaveLength(0)
+ await rig.settleRejected(journal.submissions()[0]!.clientMessageId, 'done')
+ const current = await limitedTurn('current')
+ const release = holdLane(rig.host, SESSION)
+ try {
+ const body = hostTestMessage('backlog')
+ const row = await journal.queuedMessages.insert({
+ messageId: opId(), body, fingerprint: agentSessionSendBodyFingerprint(SESSION, body),
+ hostInstance: structuredAgentSessionHostInstance()
+ })
+ journal.queuedMessages.editLeases.acquire({ callerKey: CALLER.callerKey, editId: 'edit' },
+ { messageId: row.messageId, fingerprint: row.fingerprint })
+ const attempt = rig.host.send(CALLER, params(current.turnItemId))
+ release()
+ expect(await attempt).toMatchObject(superseded)
+ expect(journal.queuedMessages.list()).toHaveLength(1)
+ expect(journal.submissions()).toHaveLength(1)
+ } finally { release() }
+ })
+})
diff --git a/src/renderer/src/components/native-chat/NativeChatInterruptedContinue.test.tsx b/src/renderer/src/components/native-chat/NativeChatInterruptedContinue.test.tsx
index 854c3b5d308f..11fbee17d300 100644
--- a/src/renderer/src/components/native-chat/NativeChatInterruptedContinue.test.tsx
+++ b/src/renderer/src/components/native-chat/NativeChatInterruptedContinue.test.tsx
@@ -1,7 +1,7 @@
// @vitest-environment happy-dom
import '@testing-library/jest-dom/vitest'
-import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'
-import { useState } from 'react'
+import { act, cleanup, fireEvent, render, renderHook, screen, waitFor } from '@testing-library/react'
+import { useRef, useState } from 'react'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
const mocks = vi.hoisted(() => {
@@ -17,7 +17,12 @@ const mocks = vi.hoisted(() => {
}
})
+vi.mock('@/lib/native-chat-telemetry', () => ({ emitNativeChatMessageSent: vi.fn() }))
+vi.mock('@/lib/worker-terminal-takeover-report', () => ({ reportStructuredSessionUserInput: vi.fn() }))
+
vi.mock('@/i18n/i18n', () => ({ translate: (_key: string, fallback: string) => fallback }))
+vi.mock('@/runtime/runtime-rpc-client', () => ({ ensureRuntimeEnvironmentCompatible: async () => {} }))
+vi.mock('@/lib/structured-agent-session-launch-label', () => ({ structuredAgentLabel: () => 'Codex' }))
vi.mock('@/runtime/structured-agent-session-client', () => ({
callStructuredAgentSession: mocks.call
}))
@@ -34,7 +39,23 @@ vi.mock('./use-structured-agent-session-host-label', () => ({
useStructuredAgentSessionHostLabel: () => mocks.hostLabel
}))
+import type { NativeChatStructuredComposerTransport } from './native-chat-composer-types'
+import { useStructuredAgentSessionSends } from './use-structured-agent-session-sends'
+import {
+ getStructuredAgentSessionSendNotice,
+ setStructuredAgentSessionSendNotice
+} from './structured-agent-session-pending-sends'
+import { resetStructuredAgentSessionSendsForTests } from './structured-agent-session-message-sender'
+import {
+ clearNativeChatComposerDraftsForTests,
+ readNativeChatComposerDraft,
+ updateNativeChatComposerDraft,
+ structuredAgentSessionDraftScopeKey
+} from './native-chat-composer-draft-store'
+import { reportStructuredSessionUserInput } from '@/lib/worker-terminal-takeover-report'
+import { emitNativeChatMessageSent } from '@/lib/native-chat-telemetry'
import { TooltipProvider } from '@/components/ui/tooltip'
+import { agentSessionFailureWords } from '../../../../shared/agent-session-failure-words'
import { agentJournalItemKey } from '../../../../shared/agent-session-journal-item-key'
import type {
AgentJournalRenderItem,
@@ -67,26 +88,41 @@ const cutChat: AgentJournalRenderItem[] = [
}
]
+const optionsSurface: NativeChatStructuredComposerTransport['optionsSurface'] = {
+ getSnapshot: () => [],
+ setOption: async () => ({ snapshot: [] }),
+ invokeAction: async () => ({ snapshot: [] }),
+ subscribe: () => () => {}
+}
+
type Props = {
journalItems?: readonly AgentJournalRenderItem[]
submissions?: readonly Pick[]
isWorking?: boolean
target?: RuntimeClientTarget
+ transport?: NativeChatStructuredComposerTransport
+ pending?: readonly { phase: 'sending' | 'recorded' }[]
}
function Harness(props: Props): React.JSX.Element {
+ const composerRef = useRef(null)
// The chat's own composer error, as NativeChatStructuredSession holds it.
const [composerError, setComposerError] = useState(null)
const continuation = useNativeChatInterruptedContinuation({
reportComposerError: setComposerError,
+ focusComposer: () => { composerRef.current?.focus() },
target: props.target ?? PAIRED,
+ agent: 'codex',
sessionId: 'session-1',
journalItems: props.journalItems ?? cutChat,
submissions: props.submissions ?? [],
- isWorking: props.isWorking ?? false
+ isWorking: props.isWorking ?? false,
+ pending: props.pending ?? [],
+ transport: props.transport ?? { send: () => true, dispatchCommand: async () => ({ handled: false, accepted: false, error: null }), optionsSurface, optionSnapshot: [], onError: () => {}, runtime: 'remote', sessionId: 'session-1', runtimeEnvironmentId: 'studio-mac' }
})
return (
+
{continuation.view.offeredTurnItemId ?? 'none'}
{String(continuation.view.continueAvailable)}
{String(continuation.view.remoteHost)}
@@ -94,6 +130,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 : (
@@ -114,7 +154,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", () => {
@@ -274,3 +318,103 @@ 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', ...agentSessionFailureWords({ kind: 'usageLimitReached' }, { surface: 'row' }) } }
+ ]
+ 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 }),
+ optionsSurface, 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' }))
+ act(() => setStructuredAgentSessionSendNotice('session-1', 'Previous send failed'))
+ continueButton()!.focus()
+ fireEvent.click(continueButton()!)
+ expect(screen.getByRole('textbox', { name: 'Composer' })).toHaveFocus()
+ expect(getStructuredAgentSessionSendNotice('session-1')).toBeNull()
+ expect(screen.getByTestId('error')).toHaveTextContent('none')
+ expect(continueButton()).toBeNull()
+ await waitFor(() => expect(mocks.call).toHaveBeenCalledOnce())
+ expect(mocks.call.mock.calls[0].slice(0, 3)).toMatchObject([PAIRED, 'agentSession.send', {
+ body: { kind: 'message', role: 'user', blocks: [{ type: 'text', text: 'Continue where you left off.' }] },
+ options, usageLimitContinuationOfTurnItemId: TURN
+ }])
+ 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' })
+})
+
+it('keeps the notice view stable while Continue invokes the latest committed transport', () => {
+ const items: AgentJournalRenderItem[] = [
+ { ...cutChat[0]!, body: { kind: 'turn', turnId: 'cut', state: 'completed', outcome: 'failure', startedAt: 1, completedAt: 5 } },
+ { ...cutChat[1]!, body: { kind: 'status', ...agentSessionFailureWords({ kind: 'usageLimitReached' }, { surface: 'row' }) } }
+ ]
+ const first = vi.fn(() => true)
+ const latest = vi.fn(() => true)
+ const transport: NativeChatStructuredComposerTransport = {
+ send: first, dispatchCommand: async () => ({ handled: false, accepted: false, error: null }),
+ optionsSurface, optionSnapshot: [], onError: () => {}, runtime: 'remote', sessionId: 'session-1', runtimeEnvironmentId: 'studio-mac'
+ }
+ const input = { target: PAIRED, agent: 'codex' as const, sessionId: 'session-1', journalItems: items,
+ submissions: [], isWorking: false, pending: [], reportComposerError: vi.fn(), focusComposer: vi.fn(), transport }
+ const { result, rerender } = renderHook((props) => useNativeChatInterruptedContinuation(props), { initialProps: input })
+ const view = result.current.view
+ rerender({ ...input, transport: { ...transport, send: latest } })
+ expect(result.current.view).toBe(view)
+ act(() => view.continueUsageLimit())
+ expect(first).not.toHaveBeenCalled()
+ expect(latest).toHaveBeenCalledOnce()
+})
diff --git a/src/renderer/src/components/native-chat/NativeChatInterruptedContinue.tsx b/src/renderer/src/components/native-chat/NativeChatInterruptedContinue.tsx
index 5d489c38a4e3..1bd4437a7a96 100644
--- a/src/renderer/src/components/native-chat/NativeChatInterruptedContinue.tsx
+++ b/src/renderer/src/components/native-chat/NativeChatInterruptedContinue.tsx
@@ -1,8 +1,17 @@
-import { useCallback, useId, useMemo, useState } from 'react'
+import { useCallback, useId, useLayoutEffect, useMemo, useRef, useState } from 'react'
import { Play } from 'lucide-react'
import { Button } from '@/components/ui/button'
import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip'
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,
+ publishStructuredAgentSessionSends,
+ type StructuredAgentSessionPendingSend
+} from './structured-agent-session-pending-sends'
import { callStructuredAgentSession } from '@/runtime/structured-agent-session-client'
import { useStructuredAgentSessionHostCapabilityState } from '@/runtime/structured-agent-session-host-capability'
import type { RuntimeClientTarget } from '../../../../shared/runtime-client-target'
@@ -11,12 +20,17 @@ 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'
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 }
@@ -36,6 +50,7 @@ export type NativeChatInterruptedContinuation = {
*/
export function useNativeChatInterruptedContinuation(input: {
target: RuntimeClientTarget
+ agent: AgentType
sessionId: string
journalItems: readonly AgentJournalRenderItem[]
submissions: readonly Pick[]
@@ -43,13 +58,26 @@ 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
+ /** Returns keyboard focus when the admitted control leaves the transcript. */
+ focusComposer: () => void
+ /** The composer's send; false when the chat took nothing. */
+ transport: NativeChatStructuredComposerTransport
+ pending: readonly Pick[]
}): NativeChatInterruptedContinuation {
- const { target, sessionId, reportComposerError } = input
+ const { target, sessionId, reportComposerError, focusComposer, transport, agent } = input
+ const latestTransport = useRef(transport)
+ useLayoutEffect(() => {
+ latestTransport.current = transport
+ }, [transport])
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'
@@ -58,13 +86,64 @@ 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 [usageFailure, setUsageFailure] = useState<{
+ turnItemId: string
+ unconfirmed: boolean
+ } | null>(null)
const [failedOn, setFailedOn] = useState(null)
+ if (usageFailure !== null && input.pending.length > 0) {
+ setUsageFailure(null)
+ }
const offered =
capability === 'supported' && cut && !input.isWorking && !resuming && asked !== cut.turnItemId
? cut.turnItemId
: null
+ const usageLimitTurnItemId =
+ usageLimitCut &&
+ !input.isWorking &&
+ !resuming &&
+ input.pending.length === 0 &&
+ !transport.sendOut &&
+ transport.sendBlockedReason === undefined
+ ? usageLimitCut.turnItemId
+ : null
+ const continueUsageLimit = useCallback((hadFocus = false): void => {
+ if (
+ usageLimitTurnItemId === null ||
+ usageCapability === 'unknown' ||
+ getStructuredAgentSessionPendingSends(sessionId).length > 0
+ ) {
+ return
+ }
+ const turnItemId = usageLimitTurnItemId
+ setUsageFailure(null)
+ reportComposerError(null)
+ // Keeping the draft must not keep the previous send's error.
+ publishStructuredAgentSessionSends(sessionId, { notice: null })
+ const transport = latestTransport.current
+ const admission = transport.send(NATIVE_CHAT_USAGE_LIMIT_CONTINUE_MESSAGE, [], {
+ callerKeepsText: true,
+ ...(usageCapability === 'supported' ? { usageLimitContinuationOfTurnItemId: turnItemId } : {}),
+ 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)
+ if (hadFocus) { focusComposer() }
+ }
+ }, [usageLimitTurnItemId, usageCapability, sessionId, reportComposerError, focusComposer, agent])
const continueNow = useCallback((): void => {
if (offered === null) {
return
@@ -93,9 +172,21 @@ export function useNativeChatInterruptedContinuation(input: {
remoteHost,
continueAvailable,
offeredTurnItemId: offered,
- continueNow
+ continueNow,
+ usageLimitTurnItemId,
+ usageLimitContinueDisabled: usageCapability === 'unknown',
+ continueUsageLimit
}),
- [hostLabel, remoteHost, continueAvailable, offered, continueNow]
+ [
+ hostLabel,
+ remoteHost,
+ continueAvailable,
+ offered,
+ continueNow,
+ usageLimitTurnItemId,
+ usageCapability,
+ continueUsageLimit
+ ]
)
const failedHere =
failedOn !== null && cut?.turnItemId === failedOn
@@ -104,28 +195,58 @@ 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
+ onContinue,
+ disabled,
+ explanation: shownExplanation
}: {
- onContinue: () => void
+ onContinue: (hadFocus?: boolean) => 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 {
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 (
<>
-
) : null}
- {block.providerFrame ? (
+ {block.providerFrame || detail ? (
) : null}
diff --git a/src/renderer/src/components/native-chat/NativeChatStructuredSession.tsx b/src/renderer/src/components/native-chat/NativeChatStructuredSession.tsx
index bcd81ef62faf..5c1fb5f227e4 100644
--- a/src/renderer/src/components/native-chat/NativeChatStructuredSession.tsx
+++ b/src/renderer/src/components/native-chat/NativeChatStructuredSession.tsx
@@ -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,15 @@ export function NativeChatStructuredSession(
onSubmitted: submits.revealLatest,
sendBlockedReason: hostPermission.sendBlockedReason ?? install.sendBlockedReason
})
+ const continuation = useNativeChatInterruptedContinuation({
+ ...controller,
+ target: props.target,
+ agent: props.agent,
+ sessionId: props.sessionId,
+ isWorking: controller.isWorking || hostHeld,
+ reportComposerError, focusComposer,
+ transport: structuredTransport
+ })
// 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/NativeChatTranscriptChrome.tsx b/src/renderer/src/components/native-chat/NativeChatTranscriptChrome.tsx
index ed8f36a3276b..4be38e25c696 100644
--- a/src/renderer/src/components/native-chat/NativeChatTranscriptChrome.tsx
+++ b/src/renderer/src/components/native-chat/NativeChatTranscriptChrome.tsx
@@ -295,12 +295,14 @@ export function NativeChatAgentControls({
export function ProviderFrameRow({
block,
- summary
+ summary,
+ detail
}: {
block: NativeChatBlock
summary?: string
+ detail?: string
}): React.JSX.Element | null {
- if (block.type !== 'text' || !block.providerFrame) {
+ if (block.type !== 'text' || (!block.providerFrame && !detail)) {
return null
}
const frame = block.providerFrame
@@ -310,9 +312,11 @@ export function ProviderFrameRow({
›
- {frame.provider}
+ {frame ? (
+ {frame.provider}
+ ) : null}
{summary ?? nativeChatProviderFrameSummary(block)}
- {frame.payload.truncated ? (
+ {frame?.payload.truncated ? (
·{' '}
{translate('components.native-chat.providerFrame.byteLength', '{{value0}} bytes', {
@@ -325,8 +329,10 @@ export function ProviderFrameRow({
data-native-chat-code-content
className="scrollbar-sleek mt-1 max-h-64 overflow-auto whitespace-pre-wrap rounded-md border border-border bg-muted p-2 font-mono text-chat-code text-foreground"
>
- {frame.payload.head}
- {frame.payload.truncated ? '\n…' : ''}
+ {detail}
+ {detail && frame ? '\n\n' : ''}
+ {frame?.payload.head}
+ {frame?.payload.truncated ? '\n…' : ''}
)
diff --git a/src/renderer/src/components/native-chat/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/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/components/native-chat/native-chat-composer-types.ts b/src/renderer/src/components/native-chat/native-chat-composer-types.ts
index fcbcb2c59bf3..a4be879cfcf1 100644
--- a/src/renderer/src/components/native-chat/native-chat-composer-types.ts
+++ b/src/renderer/src/components/native-chat/native-chat-composer-types.ts
@@ -1,3 +1,4 @@
+import type { StructuredAgentSessionSendRequest } from './structured-agent-session-send-slot'
import type { NativeChatComposerNotice } from './native-chat-composer-notice'
import type { AgentSessionConversationCommand } from '../../../../shared/agent-session-conversation-command'
import type { StructuredAgentContextUsage } from '../../../../shared/structured-agent-session-context-usage'
@@ -35,7 +36,8 @@ export type NativeChatStructuredComposerTransport = {
conversationCommands?: readonly AgentSessionConversationCommand[]
send: (
text: string,
- attachments: readonly NativeChatComposerImageAttachment[]
+ attachments: readonly NativeChatComposerImageAttachment[],
+ request?: StructuredAgentSessionSendRequest
) => boolean | 'queued'
/** A send is out: Send stays disabled, and a send returns false, until it settles. */
sendOut?: boolean
diff --git a/src/renderer/src/components/native-chat/native-chat-orca-stop-context.ts b/src/renderer/src/components/native-chat/native-chat-orca-stop-context.ts
index 430531c526dd..e9193d201e2a 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,10 @@ 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
+ usageLimitContinueDisabled?: boolean
+ continueUsageLimit: (hadFocus?: boolean) => void
}
export const NativeChatOrcaStopContext = createContext({
@@ -18,7 +22,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/components/native-chat/native-chat-structured-user-action.ts b/src/renderer/src/components/native-chat/native-chat-structured-user-action.ts
new file mode 100644
index 000000000000..24fc24c97498
--- /dev/null
+++ b/src/renderer/src/components/native-chat/native-chat-structured-user-action.ts
@@ -0,0 +1,17 @@
+import { emitNativeChatMessageSent } from '@/lib/native-chat-telemetry'
+import { reportStructuredSessionUserInput } from '@/lib/worker-terminal-takeover-report'
+import type { AgentType } from '../../../../shared/agent-status-types'
+import type { NativeChatStructuredComposerTransport } from './native-chat-composer-types'
+
+// User admission owns takeover and reveal; draft consumption belongs only to draft submission.
+export function completeNativeChatStructuredUserAction(
+ agent: AgentType,
+ transport: NativeChatStructuredComposerTransport,
+ revealsTranscript: boolean
+): void {
+ emitNativeChatMessageSent({ agent, runtime: transport.runtime })
+ if (revealsTranscript) {
+ transport.onSubmitted?.()
+ }
+ reportStructuredSessionUserInput(transport.sessionId, transport.runtimeEnvironmentId)
+}
diff --git a/src/renderer/src/components/native-chat/structured-agent-session-message-sender.test.ts b/src/renderer/src/components/native-chat/structured-agent-session-message-sender.test.ts
index 10895d689683..80b4fdae65c6 100644
--- a/src/renderer/src/components/native-chat/structured-agent-session-message-sender.test.ts
+++ b/src/renderer/src/components/native-chat/structured-agent-session-message-sender.test.ts
@@ -137,16 +137,18 @@ describe('structured agent session message sender', () => {
it('carries the options read at the send on its request, and nothing without them', async () => {
const calls = deferredCalls()
- const a = send('a', { options: { model: 'opus', effort: 'high' } })
+ const a = send('a', { options: { model: 'opus', effort: 'high' },
+ usageLimitContinuationOfTurnItemId: 'limited-turn', callerKeepsText: true })
await flush()
expect(mocks.call.mock.calls[0][2]).toMatchObject({
- options: { model: 'opus', effort: 'high' }
+ options: { model: 'opus', effort: 'high' }, usageLimitContinuationOfTurnItemId: 'limited-turn'
})
calls[0].resolve(okSubmission(a.clientMessageId, 'accepted'))
await a.outcome
send('b')
await flush()
expect(mocks.call.mock.calls[1][2]).not.toHaveProperty('options')
+ expect(mocks.call.mock.calls[1][2]).not.toHaveProperty('usageLimitContinuationOfTurnItemId')
})
it.each([
diff --git a/src/renderer/src/components/native-chat/structured-agent-session-pending-sends.ts b/src/renderer/src/components/native-chat/structured-agent-session-pending-sends.ts
index a96c533f8b30..7a31a69ec61b 100644
--- a/src/renderer/src/components/native-chat/structured-agent-session-pending-sends.ts
+++ b/src/renderer/src/components/native-chat/structured-agent-session-pending-sends.ts
@@ -12,6 +12,7 @@ export type StructuredAgentSessionPendingSend = {
queuedAt: number
delivery?: 'queue-if-active'
options?: Readonly>
+ usageLimitContinuationOfTurnItemId?: string
/**
* `sending`: on its way, its one request out or about to be; the chat takes no other send meanwhile.
* `recorded`: the host holds it; an open chat draws it until the host's row or card arrives.
diff --git a/src/renderer/src/components/native-chat/structured-agent-session-send-attempt.ts b/src/renderer/src/components/native-chat/structured-agent-session-send-attempt.ts
index c24a900bfe37..b791c6857764 100644
--- a/src/renderer/src/components/native-chat/structured-agent-session-send-attempt.ts
+++ b/src/renderer/src/components/native-chat/structured-agent-session-send-attempt.ts
@@ -130,7 +130,10 @@ export async function attemptStructuredAgentSessionSend(args: {
expectedRuntimeFence: fence,
body: entry.body,
...(entry.delivery ? { delivery: entry.delivery } : {}),
- ...(entry.options ? { options: entry.options } : {})
+ ...(entry.options ? { options: entry.options } : {}),
+ ...(entry.usageLimitContinuationOfTurnItemId
+ ? { usageLimitContinuationOfTurnItemId: entry.usageLimitContinuationOfTurnItemId }
+ : {})
})
type SendAnswer = AgentSessionMutationResult
let answer: StructuredAgentSessionSendAnswer
diff --git a/src/renderer/src/components/native-chat/structured-agent-session-send-slot.ts b/src/renderer/src/components/native-chat/structured-agent-session-send-slot.ts
index aad2f2edbc5e..1206d01509df 100644
--- a/src/renderer/src/components/native-chat/structured-agent-session-send-slot.ts
+++ b/src/renderer/src/components/native-chat/structured-agent-session-send-slot.ts
@@ -6,6 +6,7 @@ import {
structuredAgentSessionSendBody,
type StructuredAgentSessionAttachment
} from '../../../../shared/structured-agent-session-send-mutation'
+import type { StructuredAgentSessionSendOutcome } from './structured-agent-session-send-runtime'
import { createBrowserUuid } from '@/lib/browser-uuid'
import {
getStructuredAgentSessionPendingSends,
@@ -24,11 +25,16 @@ export type StructuredAgentSessionSendInput = {
options?: Readonly>
/** The caller keeps the text if it comes back, instead of the chat's composer. */
callerKeepsText?: true
+ usageLimitContinuationOfTurnItemId?: string
/** Made while the chat read Stopping: drawn after that turn until the host records it. */
sentWhileStopping?: true
now?: number
}
+export type StructuredAgentSessionSendRequest = Pick<
+ StructuredAgentSessionSendInput, 'callerKeepsText' | 'usageLimitContinuationOfTurnItemId'
+> & { onSettled?: (outcome: StructuredAgentSessionSendOutcome) => void }
+
/** Takes the chat's one send slot, drawn as sending; null while another send of the chat is out. */
export function takeStructuredAgentSessionSendSlot(
input: StructuredAgentSessionSendInput
@@ -45,6 +51,9 @@ export function takeStructuredAgentSessionSendSlot(
queuedAt: input.now ?? Date.now(),
...(input.delivery ? { delivery: input.delivery } : {}),
...(input.options ? { options: input.options } : {}),
+ ...(input.usageLimitContinuationOfTurnItemId
+ ? { usageLimitContinuationOfTurnItemId: input.usageLimitContinuationOfTurnItemId }
+ : {}),
...(input.callerKeepsText ? { callerKeepsText: true as const } : {}),
...(input.sentWhileStopping ? { sentWhileStopping: true as const } : {}),
...(attachments.some((attachment) => attachment.connectionId)
diff --git a/src/renderer/src/components/native-chat/use-native-chat-structured-composer-send.ts b/src/renderer/src/components/native-chat/use-native-chat-structured-composer-send.ts
index 9d065e6a923c..b39498b4cf25 100644
--- a/src/renderer/src/components/native-chat/use-native-chat-structured-composer-send.ts
+++ b/src/renderer/src/components/native-chat/use-native-chat-structured-composer-send.ts
@@ -1,6 +1,5 @@
import { useCallback } from 'react'
-import { emitNativeChatMessageSent } from '@/lib/native-chat-telemetry'
-import { reportStructuredSessionUserInput } from '@/lib/worker-terminal-takeover-report'
+import { completeNativeChatStructuredUserAction } from './native-chat-structured-user-action'
import {
isStructuredAgentSessionComposerCommand,
isStructuredAgentSessionGoalCommand,
@@ -101,17 +100,7 @@ export function useNativeChatStructuredComposerSend({
if (!accepted) {
return
}
- emitNativeChatMessageSent({ agent, runtime: structuredTransport.runtime })
- if (revealsTranscript) {
- structuredTransport.onSubmitted?.()
- }
- // A real user send is a takeover, exactly as typing into a worker's pane is. Only past
- // `accepted`, and only from this hook: orchestration's own pointer nudges never reach
- // the composer at all.
- reportStructuredSessionUserInput(
- structuredTransport.sessionId,
- structuredTransport.runtimeEnvironmentId
- )
+ completeNativeChatStructuredUserAction(agent, structuredTransport, revealsTranscript)
// Why: the send settles after a round trip, while this or another composer of the same
// conversation may have changed the draft; only what was sent leaves it.
const left = nativeChatComposerDraftLeftAfterSend(
diff --git a/src/renderer/src/components/native-chat/use-native-chat-structured-composer-transport.ts b/src/renderer/src/components/native-chat/use-native-chat-structured-composer-transport.ts
index 05f783fb7030..c1e5ca5aebd9 100644
--- a/src/renderer/src/components/native-chat/use-native-chat-structured-composer-transport.ts
+++ b/src/renderer/src/components/native-chat/use-native-chat-structured-composer-transport.ts
@@ -45,7 +45,7 @@ export function useNativeChatStructuredComposerTransport(args: {
: Promise.resolve(false)
: null
return {
- send: (text, attachments) =>
+ send: (text, attachments, ...request) =>
sendBlockedReason === null &&
sendThroughLaunch(text, attachments.length > 0, () =>
controller.send(
@@ -54,7 +54,8 @@ export function useNativeChatStructuredComposerTransport(args: {
path,
previewUri: path,
...(connectionId ? { connectionId } : {})
- }))
+ })),
+ ...request
)
),
dispatchCommand: (text: string) =>
diff --git a/src/renderer/src/components/native-chat/use-structured-agent-session-sends.ts b/src/renderer/src/components/native-chat/use-structured-agent-session-sends.ts
index 8108b426fe8a..96623e2d3fec 100644
--- a/src/renderer/src/components/native-chat/use-structured-agent-session-sends.ts
+++ b/src/renderer/src/components/native-chat/use-structured-agent-session-sends.ts
@@ -1,3 +1,4 @@
+import type { StructuredAgentSessionSendRequest } from './structured-agent-session-send-slot'
import { useCallback, useEffect, useSyncExternalStore } from 'react'
import type {
AgentJournalCursor,
@@ -93,7 +94,8 @@ export function useStructuredAgentSessionSends(args: {
const send = useCallback(
(
text: string,
- attachments: readonly StructuredAgentSessionAttachment[] = []
+ attachments: readonly StructuredAgentSessionAttachment[] = [],
+ request?: StructuredAgentSessionSendRequest
): boolean | 'queued' => {
if (!text.trim() && attachments.length === 0) {
return false
@@ -105,6 +107,10 @@ export function useStructuredAgentSessionSends(args: {
target,
text,
attachments,
+ ...(request?.callerKeepsText ? { callerKeepsText: request.callerKeepsText } : {}),
+ ...(request?.usageLimitContinuationOfTurnItemId
+ ? { usageLimitContinuationOfTurnItemId: request.usageLimitContinuationOfTurnItemId }
+ : {}),
...(delivery ? { delivery } : {}),
...(options ? { options } : {}),
...(stopping ? { sentWhileStopping: true as const } : {})
@@ -113,6 +119,9 @@ export function useStructuredAgentSessionSends(args: {
if (!sent) {
return false
}
+ if (request?.onSettled) {
+ void sent.outcome.then(request.onSettled)
+ }
// The same projection that draws the transcript decides it.
const admitted = getStructuredAgentSessionPendingSends(sessionId).filter(
(entry) => entry.clientMessageId === sent.clientMessageId
diff --git a/src/renderer/src/i18n/en-runtime-required.json b/src/renderer/src/i18n/en-runtime-required.json
index 18b1e0c439db..7633da4a0197 100644
--- a/src/renderer/src/i18n/en-runtime-required.json
+++ b/src/renderer/src/i18n/en-runtime-required.json
@@ -2995,7 +2995,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",
@@ -3092,6 +3100,9 @@
"usedManySummary": "Used {{toolCount}} tools",
"usedOneSummary": "Used 1 tool"
},
+ "interruptedContinue": {
+ "unconfirmed": "Couldn't confirm whether {{agent}} received Continue. Check the chat before trying again."
+ },
"writeNotice": {
"agentRefused": "The agent turned this down.",
"agentStarting": "The agent is still starting.",
@@ -3135,6 +3146,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 65db048a2b6f..f0e3c2d262b2 100644
--- a/src/renderer/src/i18n/locales/en.json
+++ b/src/renderer/src/i18n/locales/en.json
@@ -18415,6 +18415,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}}).",
@@ -18445,6 +18453,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.",
@@ -19057,7 +19066,9 @@
"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.",
+ "unconfirmed": "Couldn't confirm whether {{agent}} received Continue. Check the chat before trying again.",
+ "usageLimitExplanation": "Asks the agent to continue where it left off. Use it once the limit resets."
},
"claudeSignIn": {
"signingIn": "Signing in…"
diff --git a/src/renderer/src/i18n/locales/es.json b/src/renderer/src/i18n/locales/es.json
index ecf05fea4464..32b7eca75e68 100644
--- a/src/renderer/src/i18n/locales/es.json
+++ b/src/renderer/src/i18n/locales/es.json
@@ -18133,6 +18133,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.",
@@ -18158,6 +18166,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.",
@@ -18735,7 +18744,9 @@
"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ó.",
+ "unconfirmed": "Couldn't confirm whether {{agent}} received Continue. Check the chat before trying again.",
+ "usageLimitExplanation": "Pide al agente que continúe donde lo dejó. Úsalo cuando se restablezca el límite."
},
"rewind": {
"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 deed8d2a09bf..a1a9c528d1b0 100644
--- a/src/renderer/src/i18n/locales/fr.json
+++ b/src/renderer/src/i18n/locales/fr.json
@@ -18242,6 +18242,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.",
@@ -18267,6 +18275,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.",
@@ -18844,7 +18853,9 @@
"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.",
+ "unconfirmed": "Couldn't confirm whether {{agent}} received Continue. Check the chat before trying again.",
+ "usageLimitExplanation": "Demande à l’agent de reprendre là où il s’était arrêté. À utiliser une fois la limite réinitialisée."
},
"rewind": {
"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 9a40633e0577..f505bd7a2806 100644
--- a/src/renderer/src/i18n/locales/ja.json
+++ b/src/renderer/src/i18n/locales/ja.json
@@ -18173,6 +18173,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}} にサインインしてください。",
@@ -18198,6 +18206,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 はこのチャットの保存済み履歴を読み取れませんでした。",
@@ -18775,7 +18784,9 @@
"interruptedContinue": {
"continue": "続行",
"failed": "このチャットを続行できませんでした。もう一度試すか、メッセージを送信してください。",
- "explanation": "続行すると、Agent はまず最後の手順が完了したかどうかを確認します。"
+ "explanation": "続行すると、Agent はまず最後の手順が完了したかどうかを確認します。",
+ "unconfirmed": "Couldn't confirm whether {{agent}} received Continue. Check the chat before trying again.",
+ "usageLimitExplanation": "中断したところから続けるよう Agent に依頼します。上限がリセットされてから使ってください。"
},
"rewind": {
"unsupported": "このチャットは以前のメッセージに戻れません。",
diff --git a/src/renderer/src/i18n/locales/ko.json b/src/renderer/src/i18n/locales/ko.json
index fdb4e1ad3bbe..00c5ac7029ad 100644
--- a/src/renderer/src/i18n/locales/ko.json
+++ b/src/renderer/src/i18n/locales/ko.json
@@ -18173,6 +18173,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}}에 로그인하세요.",
@@ -18198,6 +18206,7 @@
"capacity": "이 채팅을 실행하는 컴퓨터의 Orca가 요청 한도에 도달했습니다. 해당 컴퓨터에서 Orca를 업데이트한 다음 다시 시도하세요.",
"outcomeUnknown": "Orca가 무슨 일이 있었는지 확인하지 못했습니다. 채팅을 확인하세요.",
"sendOutcomeLost": "Orca가 메시지가 에이전트에 전달되었는지 확인하지 못했습니다. 채팅을 확인하고 필요하면 다시 보내세요.",
+ "continuationSuperseded": "This chat has moved on. Check the latest messages before continuing.",
"questionChanged": "이 질문은 이미 답변되었거나 변경되었습니다.",
"cancelNotSaved": "이 질문 또는 승인을 취소하지 못했습니다.",
"historyUnreadable": "Orca가 이 채팅의 저장된 기록을 읽지 못했습니다.",
@@ -18775,7 +18784,9 @@
"interruptedContinue": {
"continue": "계속",
"failed": "이 채팅을 계속할 수 없습니다. 다시 시도하거나 메시지를 보내세요.",
- "explanation": "계속하면 에이전트가 먼저 마지막 단계가 완료되었는지 확인합니다."
+ "explanation": "계속하면 에이전트가 먼저 마지막 단계가 완료되었는지 확인합니다.",
+ "unconfirmed": "Couldn't confirm whether {{agent}} received Continue. Check the chat before trying again.",
+ "usageLimitExplanation": "중단한 곳부터 계속하도록 에이전트에 요청합니다. 한도가 초기화된 후 사용하세요."
},
"rewind": {
"unsupported": "이 채팅은 이전 메시지로 돌아갈 수 없습니다.",
diff --git a/src/renderer/src/i18n/locales/zh.json b/src/renderer/src/i18n/locales/zh.json
index 4e7ec72ae532..ed80b560c1f0 100644
--- a/src/renderer/src/i18n/locales/zh.json
+++ b/src/renderer/src/i18n/locales/zh.json
@@ -18138,6 +18138,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}}。",
@@ -18163,6 +18171,7 @@
"capacity": "运行此聊天的计算机上的 Orca 已达到请求上限。请在那台计算机上更新 Orca,然后重试。",
"outcomeUnknown": "Orca 无法确认发生了什么。请查看聊天。",
"sendOutcomeLost": "Orca 无法确认你的消息已送达智能体。请查看聊天,如有需要请重新发送。",
+ "continuationSuperseded": "This chat has moved on. Check the latest messages before continuing.",
"questionChanged": "此问题已被回答或已更改。",
"cancelNotSaved": "无法取消此问题或审批。",
"historyUnreadable": "Orca 无法读取此聊天的已保存历史记录。",
@@ -18740,7 +18749,9 @@
"interruptedContinue": {
"continue": "继续",
"failed": "无法继续此聊天。请重试,或发送一条消息。",
- "explanation": "继续后,智能体会先检查其上一步是否已完成。"
+ "explanation": "继续后,智能体会先检查其上一步是否已完成。",
+ "unconfirmed": "Couldn't confirm whether {{agent}} received Continue. Check the chat before trying again.",
+ "usageLimitExplanation": "让智能体从中断处继续。请在上限重置后使用。"
},
"rewind": {
"unsupported": "此聊天无法返回到更早的消息。",
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-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-failure-copy.ts b/src/shared/agent-session-failure-copy.ts
index bd7523db85cd..0e407e61663c 100644
--- a/src/shared/agent-session-failure-copy.ts
+++ b/src/shared/agent-session-failure-copy.ts
@@ -146,6 +146,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."
@@ -162,6 +170,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..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,
@@ -28,7 +26,12 @@ 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 { attachmentProblemSentence } from './agent-session-attachment-failure-words'
import { joinSentences } from './sentence-joining'
import {
DISPATCH_REJECTED_CANCELLED,
@@ -72,11 +75,12 @@ 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. */
const MAX_QUOTED_DETAIL_CHARS = 512
-const BYTES_PER_MB = 1024 * 1024
type Sentence = (
context: AgentSessionFailureWordsContext,
@@ -168,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)]),
@@ -242,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'),
@@ -295,6 +270,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-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-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/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/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-turn-fold.ts b/src/shared/native-chat-turn-fold.ts
index 0e0b3aa1358e..6d1a5ed07f38 100644
--- a/src/shared/native-chat-turn-fold.ts
+++ b/src/shared/native-chat-turn-fold.ts
@@ -66,7 +66,7 @@ export function nativeChatTurnFoldRow(
reportsFailure: message.blocks.some(
(block) =>
block.type === 'text' &&
- block.tone === 'error' &&
+ (block.tone === 'error' || block.failure?.kind === 'usageLimitReached') &&
block.presentation !== AGENT_SESSION_ORCA_STOP_PRESENTATION
),
explainsTurn: message.blocks.some(
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..0434f195383d
--- /dev/null
+++ b/src/shared/native-chat-usage-limit-cut.ts
@@ -0,0 +1,32 @@
+// 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'
+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 (!isRootAgentJournalItem(item) || 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/rpc-contract/structured-agent-session-params.ts b/src/shared/rpc-contract/structured-agent-session-params.ts
index b69f44a1589d..e0ddef0c2778 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 choices for the turn this message starts, kept with the message until it is
* dispatched. 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 e30a202f6f2c..fbe50b879f52 100644
--- a/src/shared/structured-agent-session-send-mutation.spec.ts
+++ b/src/shared/structured-agent-session-send-mutation.spec.ts
@@ -125,6 +125,26 @@ 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 }
+ : {})
}
}
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: {