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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions mobile/src/i18n/locales/de.json
Original file line number Diff line number Diff line change
Expand Up @@ -1911,6 +1911,7 @@
"providerRetrying": "{{agent}} ist auf ein vorübergehendes Problem gestoßen und versucht es erneut.",
"providerRetryingQuoted": "{{agent}} versucht es erneut: {{detail}}.",
"providerStartFailed": "{{agent}} wurde beendet, bevor der Start abgeschlossen war.",
"savedConversationMissing": "{{agent}} konnte den gespeicherten Verlauf dieses Chats nicht finden.",
"queueFull": "Zu viele Nachrichten warteten auf den Agenten, daher wurde diese Nachricht nicht gesendet.",
"quitTerminalAgent": "Diesen Agenten beenden, um den Chat hier fortzusetzen.",
"runCommandAgain": "/{{command}} erneut ausführen.",
Expand Down
1 change: 1 addition & 0 deletions mobile/src/i18n/locales/en.json
Original file line number Diff line number Diff line change
Expand Up @@ -2505,6 +2505,7 @@
"commandRefusedTryAgain": "This command didn't run. Try it again.",
"theAgent": "The agent",
"providerStartFailed": "{{agent}} stopped before it finished starting.",
"savedConversationMissing": "{{agent}} couldn't find this chat's saved conversation.",
"runCommandAgain": "Run /{{command}} again.",
"sendToTryAgain": "Send your message to try again.",
"sendAgainToTryOnceMore": "Send your message again to try once more.",
Expand Down
1 change: 1 addition & 0 deletions mobile/src/i18n/locales/es.json
Original file line number Diff line number Diff line change
Expand Up @@ -1976,6 +1976,7 @@
"providerRetrying": "{{agent}} tuvo un problema temporal y está reintentando.",
"providerRetryingQuoted": "{{agent}} está reintentando: {{detail}}.",
"providerStartFailed": "{{agent}} se detuvo antes de terminar de iniciarse.",
"savedConversationMissing": "{{agent}} no pudo encontrar la conversación guardada de este chat.",
"queueFull": "Había demasiados mensajes esperando al agente, así que este no se envió.",
"quitTerminalAgent": "Cierre ese agente para continuar el chat aquí.",
"runCommandAgain": "Vuelva a ejecutar /{{command}}.",
Expand Down
1 change: 1 addition & 0 deletions mobile/src/i18n/locales/fr.json
Original file line number Diff line number Diff line change
Expand Up @@ -1976,6 +1976,7 @@
"providerRetrying": "{{agent}} a rencontré un problème temporaire et réessaie.",
"providerRetryingQuoted": "{{agent}} réessaie : {{detail}}.",
"providerStartFailed": "{{agent}} s'est arrêté avant d'avoir fini de démarrer.",
"savedConversationMissing": "{{agent}} n’a pas trouvé la conversation enregistrée de ce chat.",
"queueFull": "Trop de messages attendaient l'agent, ce message n'a donc pas été envoyé.",
"quitTerminalAgent": "Quittez cet agent pour continuer le chat ici.",
"runCommandAgain": "Relancez /{{command}}.",
Expand Down
1 change: 1 addition & 0 deletions mobile/src/i18n/locales/ja.json
Original file line number Diff line number Diff line change
Expand Up @@ -1907,6 +1907,7 @@
"providerRetrying": "{{agent}} で一時的な問題が発生したため、再試行しています。",
"providerRetryingQuoted": "{{agent}} は再試行しています: {{detail}}。",
"providerStartFailed": "{{agent}} は起動が完了する前に停止しました。",
"savedConversationMissing": "{{agent}} はこのチャットの保存された会話を見つけられませんでした。",
"queueFull": "Agent を待っているメッセージが多すぎたため、このメッセージは送信されませんでした。",
"quitTerminalAgent": "ここでチャットを続けるには、その Agent を終了してください。",
"runCommandAgain": "/{{command}} をもう一度実行してください。",
Expand Down
1 change: 1 addition & 0 deletions mobile/src/i18n/locales/ko.json
Original file line number Diff line number Diff line change
Expand Up @@ -1907,6 +1907,7 @@
"providerRetrying": "{{agent}}에 일시적인 문제가 발생하여 다시 시도하고 있습니다.",
"providerRetryingQuoted": "{{agent}}이(가) 다시 시도하고 있습니다: {{detail}}.",
"providerStartFailed": "{{agent}}이(가) 시작을 마치기 전에 중지되었습니다.",
"savedConversationMissing": "{{agent}}에서 이 채팅의 저장된 대화를 찾을 수 없습니다.",
"queueFull": "에이전트를 기다리는 메시지가 너무 많아 이 메시지는 전송되지 않았습니다.",
"quitTerminalAgent": "여기에서 채팅을 계속하려면 해당 에이전트를 종료하세요.",
"runCommandAgain": "/{{command}}을(를) 다시 실행하세요.",
Expand Down
1 change: 1 addition & 0 deletions mobile/src/i18n/locales/pt.json
Original file line number Diff line number Diff line change
Expand Up @@ -1976,6 +1976,7 @@
"providerRetrying": "{{agent}} encontrou um problema temporário e está tentando novamente.",
"providerRetryingQuoted": "{{agent}} está tentando novamente: {{detail}}.",
"providerStartFailed": "{{agent}} parou antes de terminar de iniciar.",
"savedConversationMissing": "{{agent}} não conseguiu encontrar a conversa salva deste chat.",
"queueFull": "Havia mensagens demais aguardando o agente, por isso esta mensagem não foi enviada.",
"quitTerminalAgent": "Encerre esse agente para continuar o chat aqui.",
"runCommandAgain": "Execute /{{command}} novamente.",
Expand Down
1 change: 1 addition & 0 deletions mobile/src/i18n/locales/ru.json
Original file line number Diff line number Diff line change
Expand Up @@ -2041,6 +2041,7 @@
"providerRetrying": "{{agent}} столкнулся с временной неполадкой и повторяет попытку.",
"providerRetryingQuoted": "{{agent}} повторяет попытку: {{detail}}.",
"providerStartFailed": "{{agent}} остановился до завершения запуска.",
"savedConversationMissing": "{{agent}} не удалось найти сохранённую беседу этого чата.",
"queueFull": "Слишком много сообщений ожидает агента, поэтому это сообщение не отправлено.",
"quitTerminalAgent": "Завершите работу этого агента, чтобы продолжить чат здесь.",
"runCommandAgain": "Выполните /{{command}} снова.",
Expand Down
1 change: 1 addition & 0 deletions mobile/src/i18n/locales/tr.json
Original file line number Diff line number Diff line change
Expand Up @@ -1911,6 +1911,7 @@
"providerRetrying": "{{agent}} geçici bir sorunla karşılaştı ve yeniden deniyor.",
"providerRetryingQuoted": "{{agent}} yeniden deniyor: {{detail}}.",
"providerStartFailed": "{{agent}}, başlatılması tamamlanmadan durdu.",
"savedConversationMissing": "{{agent}} bu sohbetin kayıtlı konuşmasını bulamadı.",
"queueFull": "Ajana iletilmeyi bekleyen çok fazla mesaj olduğu için bu mesaj gönderilmedi.",
"quitTerminalAgent": "Sohbete burada devam etmek için o ajandan çıkın.",
"runCommandAgain": "/{{command}} komutunu yeniden çalıştırın.",
Expand Down
1 change: 1 addition & 0 deletions mobile/src/i18n/locales/zh-Hant.json
Original file line number Diff line number Diff line change
Expand Up @@ -1907,6 +1907,7 @@
"providerRetrying": "{{agent}} 遇到暫時性問題,正在重試。",
"providerRetryingQuoted": "{{agent}} 正在重試:{{detail}}。",
"providerStartFailed": "{{agent}} 在完成啟動前已停止。",
"savedConversationMissing": "{{agent}} 找不到此聊天已儲存的對話。",
"queueFull": "等待代理程式處理的訊息過多,因此此訊息未傳送。",
"quitTerminalAgent": "請結束該代理程式,以便在此處繼續聊天。",
"runCommandAgain": "請重新執行 /{{command}}。",
Expand Down
1 change: 1 addition & 0 deletions mobile/src/i18n/locales/zh.json
Original file line number Diff line number Diff line change
Expand Up @@ -1907,6 +1907,7 @@
"providerRetrying": "{{agent}} 遇到临时问题,正在重试。",
"providerRetryingQuoted": "{{agent}} 正在重试:{{detail}}。",
"providerStartFailed": "{{agent}} 在完成启动前已停止。",
"savedConversationMissing": "{{agent}} 找不到此聊天已保存的对话。",
"queueFull": "等待智能体处理的消息过多,因此此消息未发送。",
"quitTerminalAgent": "请退出该智能体,以便在此处继续聊天。",
"runCommandAgain": "请重新运行 /{{command}}。",
Expand Down
17 changes: 17 additions & 0 deletions mobile/src/session/agent-session-failure-copy.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import { expect, it } from 'vitest'
import { agentSessionFailureSentence } from '../../../src/shared/agent-session/failures/agent-session-failure-words'
import { sayMobileAgentSessionFailure } from './agent-session-failure-copy'

it('gives new-chat guidance while keeping a missing conversation diagnostic private', () => {
expect(
agentSessionFailureSentence(
{
kind: 'savedConversationMissing',
detail: { text: 'No conversation found with session ID: private-id', audience: 'log' }
},
'row',
{ agentName: 'Claude' },
sayMobileAgentSessionFailure
)
).toBe("Claude couldn't find this chat's saved conversation. Start a new chat to continue.")
})
6 changes: 6 additions & 0 deletions mobile/src/session/agent-session-start-failure-copy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,12 @@ import type {
import { translate } from '../i18n/mobile-i18n'

export const START_FAILURE_COPY = {
savedConversationMissing: (values) =>
translate(
'session.failure.savedConversationMissing',
"{{agent}} couldn't find this chat's saved conversation.",
values
),
theAgent: (values) => translate('session.failure.theAgent', 'The agent', values),
providerStartFailed: (values) =>
translate(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -141,6 +141,21 @@ describe('MobileNativeChatMessage status notices', () => {
)
})

it("rewords the host's missing saved conversation words in the reader's language", async () => {
await activateMobileUiLocale('fr')
const host = agentSessionFailureWords(agentSessionFailureFact('savedConversationMissing'), {
surface: 'row',
agentName: 'Claude'
})
const text = renderNotice(
{ kind: 'status', tone: 'error', ...host },
{ hostName: null, agentName: 'Claude' }
)
expect(text.props.children).toBe(
'Claude n’a pas trouvé la conversation enregistrée de ce chat. Démarrez un nouveau chat pour continuer.'
)
})

it.each(['without reset', 'with reset', 'from an old host'] as const)(
'draws an OpenCode usage warning %s',
(source) => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import {
type NativeChatTextBlock
} from '../../../../../src/shared/native-chat/native-chat-types'
import { readWholeAgentSessionFailureFact } from '../../../../../src/shared/agent-session/failures/agent-session-failure'
import { agentSessionFailureSentence } from '../../../../../src/shared/agent-session/failures/agent-session-failure-words'
import { nativeChatOrcaStopRowText } from '../../../../../src/shared/native-chat/native-chat-orca-stop-words'
import {
MobileNativeChatNoticeContext,
Expand All @@ -25,6 +26,7 @@ import { useMobileColorScheme } from '../../../theme/use-mobile-color-scheme'
import { nativeChatHostStatusCopy, nativeChatNoticeCopy } from './native-chat-notice-copy'
import { nativeChatOrcaStopSay } from './native-chat-orca-stop-copy'
import { nativeChatUsageLimitText } from './native-chat-usage-limit-copy'
import { sayMobileAgentSessionFailure } from '../../agent-session-failure-copy'
import type { Translate } from '../../../i18n/mobile-i18n'
import { useMobileTranslation } from '../../../i18n/use-mobile-translation'
import { NATIVE_CHAT_STOPPED_BEFORE_START_PRESENTATION } from '../../../../../src/shared/native-chat/native-chat-stopped-before-start'
Expand Down Expand Up @@ -52,8 +54,19 @@ function noticeLineText(
)
}
const failure = readWholeAgentSessionFailureFact(notice.failure)
return failure?.kind === 'usageLimitReached'
? nativeChatUsageLimitText(failure.usageLimit, names.agentName, t)
if (failure?.kind === 'usageLimitReached') {
return nativeChatUsageLimitText(failure.usageLimit, names.agentName, t)
}
// Only reword text fully described by its fact; other host text stays as written.
const context = { agentName: names.agentName }
const surface =
failure?.kind === 'savedConversationMissing'
? (['row', 'rejection'] as const).find(
(candidate) => notice.text === agentSessionFailureSentence(failure, candidate, context)
)
: undefined
return failure && surface
? agentSessionFailureSentence(failure, surface, context, sayMobileAgentSessionFailure)
: notice.text
}

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{"type":"result","subtype":"error_during_execution","duration_ms":0,"duration_api_ms":0,"is_error":true,"num_turns":0,"stop_reason":null,"session_id":"00000000-0000-4000-8000-00000000dead","total_cost_usd":0,"usage":{"output_tokens_details":{"thinking_tokens":0},"input_tokens":0,"cache_creation_input_tokens":0,"cache_read_input_tokens":0,"output_tokens":0,"server_tool_use":{"web_search_requests":0,"web_fetch_requests":0},"service_tier":"standard","cache_creation":{"ephemeral_1h_input_tokens":0,"ephemeral_5m_input_tokens":0},"inference_geo":"","iterations":[],"speed":"standard","fallback_credit":null},"modelUsage":{},"permission_denials":[],"uuid":"d72d18b6-9b60-4154-b20b-fde0ca20dce3","errors":["No conversation found with session ID: 00000000-0000-4000-8000-00000000dead"],"result_index":0}
2 changes: 2 additions & 0 deletions src/main/claude/claude-journal-translator-contract.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,8 @@ export type ClaudeJournalTranslatorDeps = {
account?: () => AgentSessionAccountKind | undefined
model?: () => string | undefined
goalBackgroundWork?: () => ClaudeGoalBackgroundWork
/** True when this acquisition's pending startup took a turnless failure result and will fail with it. */
acceptStartupFailure?: (message: Record<string, unknown>) => boolean
}

export type ClaudeJournalTranslator = {
Expand Down
30 changes: 29 additions & 1 deletion src/main/claude/claude-result-journaling.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import {
import { claudeTurnEndForResult } from './claude-turn-lifecycle-item'
import { claudeFrameParentRef, isRootClaudeFrame } from './claude-turn-opening'
import type { ClaudeGoalBackgroundWork } from './claude-background-task-tracker'
import type { ClaudeJournalTranslatorDeps } from './claude-journal-translator-contract'

export type ClaudeResultJournalContext = Pick<
ClaudeMessageJournalContext,
Expand All @@ -27,6 +28,20 @@ export type ClaudeResultJournalContext = Pick<
prompts: ClaudeJournalPrompts
context: ClaudeContextFacts
goalBackgroundWork: () => ClaudeGoalBackgroundWork
acceptStartupFailure?: ClaudeJournalTranslatorDeps['acceptStartupFailure']
}

const namesClaudeInput = (value: unknown): boolean => typeof value === 'string' && value !== ''

/** Input it answered (receipts, a resumed turn) or model round-trips mean the result is a turn's own. */
function claudeResultShowsTurnWork(message: Record<string, unknown>): boolean {
return (
namesClaudeInput(message.user_message_uuid) ||
(Array.isArray(message.user_message_uuids) &&
message.user_message_uuids.some(namesClaudeInput)) ||
namesClaudeInput(message.resume_reason) ||
(typeof message.num_turns === 'number' && message.num_turns > 0)
)
}

export function journalClaudeResult(
Expand All @@ -42,7 +57,8 @@ export function journalClaudeResult(
assistantFailures,
usageLimits,
threadGoal,
goalBackgroundWork
goalBackgroundWork,
acceptStartupFailure
}: ClaudeResultJournalContext,
message: Record<string, unknown>,
observedAt: number
Expand Down Expand Up @@ -96,6 +112,18 @@ export function journalClaudeResult(
return
}
const alreadyShown = assistantFailures.resultAlreadyShown(message)
// Only a still-starting acquisition that fails its open with this failure may take over its row.
if (
failure &&
settlesTurn &&
endedTurnIdentity === null &&
!usageLimit &&
!alreadyShown &&
!claudeResultShowsTurnWork(message) &&
acceptStartupFailure?.(message) === true
) {
return
}
if ((failure || !isSettledClaudeResultKind(kind)) && !alreadyShown) {
providerFallback.append(
kind,
Expand Down
40 changes: 40 additions & 0 deletions src/main/claude/claude-stream-json-exit-error.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
import { readFileSync } from 'node:fs'
import { expect, it } from 'vitest'
import {
claudeStartupResultError,
claudeStreamJsonExitError
} from './claude-stream-json-exit-error'
import { providerStartupFailureFact } from '../native-chat/agent-session-wire/structured-agent-session-failure-text'
import { retryableStructuredAgentSessionStart } from '../native-chat/agent-session-wire/structured-agent-session-start-retry'

const frame = JSON.parse(
readFileSync(new URL('./__fixtures__/claude-missing-conversation.jsonl', import.meta.url), 'utf8')
)

it('treats the recorded missing-conversation exit as an explained final refusal', () => {
const error = claudeStreamJsonExitError(frame.errors[0], {
code: 1,
signal: null,
processless: false
})
expect(providerStartupFailureFact(error)).toMatchObject({
kind: 'savedConversationMissing',
detail: { text: expect.stringContaining(frame.errors[0]), audience: 'log' }
})
expect(retryableStructuredAgentSessionStart(error)).toBe(false)
})

it('reads the same refusal from the recorded result, and leaves other startup results retryable', () => {
const refusal = claudeStartupResultError(frame)
expect(providerStartupFailureFact(refusal)).toEqual({
kind: 'savedConversationMissing',
detail: { text: frame.errors[0], audience: 'log' }
})
expect(retryableStructuredAgentSessionStart(refusal)).toBe(false)
const generic = claudeStartupResultError({ ...frame, errors: ['managed settings failed'] })
expect(providerStartupFailureFact(generic)).toMatchObject({
kind: 'startFailed',
detail: { text: 'managed settings failed', audience: 'log' }
})
expect(retryableStructuredAgentSessionStart(generic)).toBe(true)
})
36 changes: 34 additions & 2 deletions src/main/claude/claude-stream-json-exit-error.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,40 @@ import type { ProviderProcessExit } from '../provider-process/managed-provider-p
import { providerExitStatusText } from '../provider-process/provider-process-exit-status'
import { providerStderrForDisplay } from '../provider-process/provider-spawn-failure-report'
import { AgentSessionAcquisitionRefusal } from '../native-chat/agent-session-wire/structured-agent-session-adapter'
import { ClaudeControlRequestError } from './claude-agent-sdk-control-requests'

// Claude Code's own startup refusal: as root it exits before initialize rather than skip permissions.
const CLAUDE_ROOT_FULL_ACCESS_REFUSAL = /--dangerously-skip-permissions cannot be used with root/
const CLAUDE_MISSING_CONVERSATION =
/^No conversation found with session ID: [0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\s*$/im

/** Claude Code's typed startup refusals, from its stderr or a startup result's `errors`. */
function claudeStartupRefusalReason(detail: string) {
return CLAUDE_ROOT_FULL_ACCESS_REFUSAL.test(detail)
? 'fullAccessAsRoot'
: CLAUDE_MISSING_CONVERSATION.test(detail)
? 'savedConversationMissing'
: null
}

/** A startup failure Claude reported as a result: it proves no exit, so only a typed refusal is final. */
export function claudeStartupResultError(message: Record<string, unknown>): Error {
const errors = Array.isArray(message.errors)
? message.errors.filter((entry): entry is string => typeof entry === 'string').join('\n')
: ''
const diagnostic = providerDiagnostic(
errors.trim() || (typeof message.result === 'string' ? message.result : ''),
'log'
)
const text = `claude reported a startup failure${diagnostic ? `: ${diagnostic.text}` : ''}`
const reason = claudeStartupRefusalReason(errors)
return withProviderDiagnostic(
reason
? new AgentSessionAcquisitionRefusal(text, reason)
: new ClaudeControlRequestError('startup', text),
diagnostic
)
}

export function claudeStreamJsonExitError(
stderrTail: string,
Expand All @@ -21,10 +52,11 @@ export function claudeStreamJsonExitError(
const message = `claude stream-json exited${how ? ` ${how}` : ''}${detail ? `: ${detail}` : ''}`
const diagnostic = providerDiagnostic([how, detail].filter(Boolean).join('\n'), 'log')
// The typed refusal replaces this error in failure facts, so it carries the diagnostic too.
const refusal = CLAUDE_ROOT_FULL_ACCESS_REFUSAL.test(detail)
const refusalReason = claudeStartupRefusalReason(detail)
const refusal = refusalReason
? withProviderDiagnostic(
Object.assign(
new AgentSessionAcquisitionRefusal(message, 'fullAccessAsRoot'),
new AgentSessionAcquisitionRefusal(message, refusalReason),
cause ? { cause } : {}
),
diagnostic
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import { ClaudeBackgroundTaskTracker } from '../claude-background-task-tracker'
import { ClaudeChildWorkDecoder } from '../claude-child-work-decoder'
import { ClaudeSlashCommandCatalog } from '../claude-slash-command-catalog'
import { createClaudeInitProof } from './claude-structured-init-proof'
import { createClaudeStartupOutcome } from './claude-structured-startup-outcome'
import { claudeProviderHandleLink } from './claude-structured-owner-identity'

export function sessionFor(send: Mock = vi.fn().mockResolvedValue(undefined)): ClaudeSession {
Expand Down Expand Up @@ -48,7 +49,8 @@ export function sessionFor(send: Mock = vi.fn().mockResolvedValue(undefined)): C
claudeConfigDir: '/claude-home',
cwd: '/work',
history: { leafUuid: null, covered: true, contextActivity: 0 },
onLateRefusal: () => {}
onLateRefusal: () => {},
startup: createClaudeStartupOutcome()
}
}
}
Expand Down
Loading
Loading