Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

fix(pi): report output limits without heuristic interruption

zqchris834696692d7f
diff --cc apps/desktop/src/main/maker-ipc/__tests__/interruptedTurnAutoResume.test.ts
index 58793ece1e,58793ece1e..625df73aad
--- a/apps/desktop/src/main/maker-ipc/__tests__/interruptedTurnAutoResume.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/interruptedTurnAutoResume.test.ts
@@@ -90,7 -90,7 +90,7 @@@ describe('isInterruptedTurnError', () =
});
it('rejects errors that carry a stable reason (已分类,另有处置路径)', () => {
-- for (const reason of ['turn-failed', 'silent-stop-exhausted']) {
++ for (const reason of ['turn-failed', 'silent-stop-exhausted', 'output-limit']) {
expect(
isInterruptedTurnError({
sdkError: 'server_error',
diff --cc apps/desktop/src/renderer/__tests__/errorMessageRestore.test.ts
index a46ea3ff5c,99e96f87a3..6b095f0de3
--- a/apps/desktop/src/renderer/__tests__/errorMessageRestore.test.ts
+++ b/apps/desktop/src/renderer/__tests__/errorMessageRestore.test.ts
@@@ -71,13 -77,6 +77,14 @@@ describe('mapServerMessages — persist
expect(ERROR_REASON_I18N_KEYS.session_event_loop_crashed).toBe('logic.errors.turnFailed');
});
- it('maps Pi output guards to stable localized copy', () => {
- expect(ERROR_REASON_I18N_KEYS['output-degeneration']).toBe(
- 'logic.errors.outputDegeneration',
- );
- expect(ERROR_REASON_I18N_KEYS['output-limit']).toBe('logic.errors.outputLimit');
++ it('restores a Pi output limit for localized history rendering', () => {
++ const mapped = makerChatStore.__mapServerMessagesForTest([
++ errorRow('output-limit', { message: 'Pi reached the model output limit.', reason: 'output-limit' }),
++ ]);
++ expect(mapped[0]).toMatchObject({ role: 'error', errorReason: 'output-limit', isStreaming: false });
++ expect(ERROR_REASON_I18N_KEYS[mapped[0]!.errorReason!]).toBe('logic.errors.outputLimit');
+ });
+
it('restores the overload reason from persisted rows so history can localize it', () => {
const mapped = makerChatStore.__mapServerMessagesForTest([
errorRow('e-overload', {
diff --cc apps/desktop/src/renderer/components/chat/errorReasonI18n.ts
index 608dba9bdf,26cc2a25a3..e5ce402f05
--- a/apps/desktop/src/renderer/components/chat/errorReasonI18n.ts
+++ b/apps/desktop/src/renderer/components/chat/errorReasonI18n.ts
@@@ -17,10 -18,9 +18,10 @@@ export const ERROR_REASON_I18N_KEYS: Re
'empty-response': 'logic.errors.emptyResponse',
'turn-failed': 'logic.errors.turnFailed',
'silent-stop-exhausted': 'logic.errors.silentStopExhausted',
- 'output-degeneration': 'logic.errors.outputDegeneration',
+ 'output-limit': 'logic.errors.outputLimit',
tool_use_loop_detected: 'logic.errors.toolUseLoopDetected',
'permission-tighten-interrupt-failed': 'logic.errors.permissionTightenInterruptFailed',
+ 'runtime-selection-cancelled': 'newChat.chatInput.switchFailed',
'codex-auto-review-unavailable': 'logic.errors.codexAutoReviewUnavailable',
'host-shell-command-blocked': 'logic.errors.hostShellCommandBlocked',
upstream_response_idle_timeout: 'logic.errors.upstreamResponseIdleTimeout',
diff --cc apps/desktop/src/renderer/i18n/locales/en/common.json
index 813921f9b6,7482e31f93..571486dfd3
--- a/apps/desktop/src/renderer/i18n/locales/en/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json
@@@ -10568,8 -11406,6 +11406,7 @@@
"qrExpired": "QR code expired, please start again",
"registrationFailed": "Creation failed, please retry later",
"silentStopExhausted": "The model returned empty responses repeatedly; auto-resume is paused. Click \"Continue\" to resume the task.",
- "outputDegeneration": "The response became highly repetitive, so Cindy stopped it. If the repetition was intentional, resend your request with /allow-repetitive-output at the beginning.",
+ "outputLimit": "The model reached its output limit, so this response may be incomplete. Send the next message to continue.",
"permissionTightenInterruptFailed": "Failed to stop the running task while tightening permissions; it may keep running without approval prompts until it finishes. Stop it manually if needed.",
"codexAutoReviewUnavailable": "Auto-review is temporarily unavailable. The current action was blocked and permissions switched to Default. Retry the request; Cindy will ask when needed.",
"hostShellCommandBlocked": "Cindy blocked a shell command that would bypass the embedded iOS Simulator. Use the iOS Simulator tool for device control, app launches, interaction, screenshots, and diagnostics.",
diff --cc apps/desktop/src/renderer/i18n/locales/ja/common.json
index 51d260ae04,0a039f4dfc..39921763e3
--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json
@@@ -10552,8 -11390,6 +11390,7 @@@
"qrExpired": "QR コードが期限切れです。最初からやり直してください",
"registrationFailed": "作成に失敗しました。後でもう一度お試しください",
"silentStopExhausted": "モデルが空の応答を繰り返し返したため、自動再開を一時停止しました。「続行」をクリックしてタスクを再開してください。",
- "outputDegeneration": "応答内容に大量の繰り返しが発生したため、Cindy は今回の出力を停止しました。意図した繰り返しの場合は、リクエストの先頭に /allow-repetitive-output を付けて再送信してください。",
+ "outputLimit": "モデルが出力上限に達したため、この応答は不完全な可能性があります。次のメッセージを送信して続行できます。",
"permissionTightenInterruptFailed": "権限を厳格化する際に実行中のタスクを停止できませんでした。タスクは終了まで確認なしで実行され続ける可能性があります。必要に応じて手動で停止してください。",
"codexAutoReviewUnavailable": "自動レビューは一時的に利用できません。現在の操作をブロックし、デフォルト権限に切り替えました。もう一度実行してください。必要な場合は確認します。",
"hostShellCommandBlocked": "Cindy は内蔵 iOS シミュレータを迂回するシェルコマンドをブロックしました。デバイスの操作、アプリの起動、画面操作、スクリーンショット、診断には iOS シミュレータツールを使用してください。",
diff --cc apps/desktop/src/renderer/i18n/locales/ko/common.json
index eee1131f5a,27ae82451a..98b7e49be8
--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json
@@@ -10552,8 -11390,6 +11390,7 @@@
"qrExpired": "QR 코드가 만료됨. 다시 시작하세요",
"registrationFailed": "생성 실패. 잠시 후 다시 시도하세요",
"silentStopExhausted": "모델이 빈 응답을 반복해서 반환하여 자동 재개가 일시 중지되었습니다. \"계속\"을 클릭하여 작업을 재개하세요.",
- "outputDegeneration": "응답 내용이 과도하게 반복되어 Cindy가 이번 출력을 중지했습니다. 의도한 반복이라면 요청 맨 앞에 /allow-repetitive-output을 추가해 다시 보내 주세요.",
+ "outputLimit": "모델이 출력 한도에 도달하여 이번 응답은 불완전할 수 있습니다. 다음 메시지를 보내 계속할 수 있습니다.",
"permissionTightenInterruptFailed": "권한을 강화하는 동안 실행 중인 작업을 중지하지 못했습니다. 작업이 끝날 때까지 확인 없이 계속 실행될 수 있습니다. 필요하면 수동으로 중지하세요.",
"codexAutoReviewUnavailable": "자동 리뷰를 일시적으로 사용할 수 없습니다. 현재 작업을 차단하고 기본 권한으로 전환했습니다. 다시 시도하세요. 필요한 경우 확인을 요청합니다.",
"hostShellCommandBlocked": "Cindy가 내장 iOS 시뮬레이터를 우회하는 셸 명령을 차단했습니다. 기기 제어, 앱 실행, 화면 조작, 스크린샷, 진단에는 iOS 시뮬레이터 도구를 사용하세요.",
diff --cc apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
index 48f89516c6,5849fcb6c0..f80f80bd60
--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
@@@ -10544,8 -11390,6 +11390,7 @@@
"qrExpired": "二维码已过期,请重新开始",
"registrationFailed": "创建失败,请稍后重试",
"silentStopExhausted": "模型连续多次返回空响应,自动续跑已暂停。点击「继续」恢复任务。",
- "outputDegeneration": "回复内容出现大量重复,Cindy 已停止本轮输出。如果确实需要重复内容,请在请求开头添加 /allow-repetitive-output 后重新发送。",
+ "outputLimit": "模型已达到输出长度上限,本轮回复可能不完整。可以直接发送下一条消息继续。",
"permissionTightenInterruptFailed": "收紧权限时未能停止正在运行的任务,它可能会继续免确认执行直到结束;如有需要请手动停止。",
"codexAutoReviewUnavailable": "自动审批暂时不可用,当前操作已阻止并切换为默认权限。请重试,需要时会询问你。",
"hostShellCommandBlocked": "Cindy 已阻止会绕过内嵌模拟器的 Shell 命令。请改用模拟器工具控制设备、启动应用、操作界面、截图和诊断。",
diff --cc apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
index 915ab6e21a,f018d4eb9b..29954cc77f
--- a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
@@@ -10544,8 -11390,6 +11390,7 @@@
"qrExpired": "二維碼已過期,請重新開始",
"registrationFailed": "建立失敗,請稍後重試",
"silentStopExhausted": "模型連續多次返回空響應,自動續跑已暫停。點選「繼續」恢復任務。",
- "outputDegeneration": "回覆內容出現大量重複,Cindy 已停止本輪輸出。如果確實需要重複內容,請在請求開頭加入 /allow-repetitive-output 後重新傳送。",
+ "outputLimit": "模型已達到輸出長度上限,本輪回覆可能不完整。可以直接傳送下一則訊息繼續。",
"permissionTightenInterruptFailed": "收緊權限時未能停止正在執行的任務,它可能會繼續免確認執行直到結束;如有需要請手動停止。",
"codexAutoReviewUnavailable": "自動審批暫時不可用,當前操作已阻止並切換為預設權限。請重試,需要時會詢問你。",
"hostShellCommandBlocked": "Cindy 已阻止會繞過內嵌模擬器的 Shell 命令。請改用模擬器工具控制裝置、啟動 App、操作介面、截圖和診斷。",
diff --cc apps/mobile/src/__tests__/inputProjection.test.ts
index 4b19c4a4a9,4b19c4a4a9..2ae6425703
--- a/apps/mobile/src/__tests__/inputProjection.test.ts
+++ b/apps/mobile/src/__tests__/inputProjection.test.ts
@@@ -15,7 -15,7 +15,7 @@@ import
import { buildMobileUploadedAttachment } from '@/session/attachments';
import { parseAttachmentOssRef } from '@/session/attachmentOssRef';
import { textComposerDocument } from '@/session/composerDocument';
--import { localizeToolLoopError } from '@/session/toolLoopErrorI18n';
++import { localizeAgentError } from '@/session/agentErrorI18n';
import type { RemoteSession } from '@/session/types';
const ATTACHMENT_SHA256 = 'a'.repeat(64);
@@@ -396,8 -396,8 +396,17 @@@ describe('inputProjection', () =>
}).toolLoop).toBeNull();
});
++ it('localizes the output-limit reason carried by the live projection', () => {
++ const projection = normalizeInputProjection({
++ sessionId: 'output-limit', error: 'Pi reached the model output limit.', errorReason: 'output-limit',
++ });
++ expect(localizeAgentError(projection.errorReason, projection.toolLoop ?? null)).toBe(
++ i18n.t('session.tail.outputLimit'),
++ );
++ });
++
it('localizes live tool-loop errors instead of rendering the host message', () => {
-- const localized = localizeToolLoopError(
++ const localized = localizeAgentError(
'tool_use_loop_detected',
{ kind: 'contract', count: 3 },
);
diff --cc apps/mobile/src/__tests__/messageNormalize.test.ts
index 74b13f65ed,6be623bab8..9971561cc5
--- a/apps/mobile/src/__tests__/messageNormalize.test.ts
+++ b/apps/mobile/src/__tests__/messageNormalize.test.ts
@@@ -998,6 -1038,6 +1038,14 @@@ describe('normalizeRemoteMessages', ()
expect(items[1].body).toBe('something exploded');
});
++ it('localizes a persisted output limit in message history', () => {
++ const items = normalizeRemoteMessages([message({
++ id: 'output-limit', role: 'error',
++ content: JSON.stringify({ message: 'Pi reached the model output limit.', reason: 'output-limit' }),
++ })]);
++ expect(items[0]).toMatchObject({ kind: 'system', label: 'error', body: i18n.t('session.tail.outputLimit') });
++ });
++
it('localizes persisted tool-loop errors from reason and bounded details', () => {
const items = normalizeRemoteMessages([
message({
diff --cc apps/mobile/src/__tests__/sessionTailBannerModel.test.ts
index 9014a43f62,9014a43f62..b68434f44d
--- a/apps/mobile/src/__tests__/sessionTailBannerModel.test.ts
+++ b/apps/mobile/src/__tests__/sessionTailBannerModel.test.ts
@@@ -89,6 -89,6 +89,17 @@@ describe('resolveSessionTailBanner —
expect((state as { text: string }).text).toContain('设置 → 模型供应商');
});
++ it('localizes a persisted output limit and keeps manual continuation available', () => {
++ const state = resolveSessionTailBanner(baseInput({
++ messages: [errorRow('limit', '2026-01-01T00:00:02.000Z', {
++ message: 'Pi reached the model output limit.', reason: 'output-limit',
++ })],
++ }));
++ expect(state).toMatchObject({
++ kind: 'error-tail', text: i18n.t('session.tail.outputLimit'), retryable: true,
++ });
++ });
++
it('localizes a tool-loop tail from its stable reason and structured details', () => {
const state = resolveSessionTailBanner(baseInput({
messages: [errorRow('e1', '2026-01-01T00:00:02.000Z', {
diff --cc apps/mobile/src/i18n/locales/en/session.json
index 6cc5c97aba,e7c2f76248..d846213c2f
--- a/apps/mobile/src/i18n/locales/en/session.json
+++ b/apps/mobile/src/i18n/locales/en/session.json
@@@ -423,6 -469,6 +469,7 @@@
"continueTask": "Continue Task",
"retry": "Retry",
"ignore": "Ignore",
++ "outputLimit": "The model reached its output limit, so this response may be incomplete. Send the next message to continue.",
"toolUseLoopDetected": "The model repeated a tool call too many times, so Cindy stopped this turn to prevent an infinite loop. Send a new message to continue.",
"toolUseLoopDetectedWithCount": "The model kept repeating invalid tool calls, so Cindy stopped this turn after {{count}} failures to prevent an infinite loop. Send a new message to continue.",
"toolUseLoopDetectedConsecutiveWithCount": "The model repeated the same tool call {{count}} times, so Cindy stopped this turn to prevent an infinite loop. Send a new message to continue.",
diff --cc apps/mobile/src/i18n/locales/ja/session.json
index 850a3e6c43,b5f8a89902..885c20bacd
--- a/apps/mobile/src/i18n/locales/ja/session.json
+++ b/apps/mobile/src/i18n/locales/ja/session.json
@@@ -423,6 -469,6 +469,7 @@@
"continueTask": "タスクを続ける",
"retry": "再試行",
"ignore": "無視",
++ "outputLimit": "モデルが出力上限に達したため、この応答は不完全な可能性があります。次のメッセージを送信して続行できます。",
"toolUseLoopDetected": "モデルがツール呼び出しを繰り返したため、無限ループを防ぐためこのターンを停止しました。新しいメッセージを送信して続行できます。",
"toolUseLoopDetectedWithCount": "モデルが無効なツール呼び出しを繰り返したため、無限ループを防ぐために {{count}} 回の失敗後にこのターンを停止しました。新しいメッセージを送信して続行できます。",
"toolUseLoopDetectedConsecutiveWithCount": "モデルが同じツール呼び出しを {{count}} 回繰り返したため、無限ループを防ぐためこのターンを停止しました。新しいメッセージを送信して続行できます。",
diff --cc apps/mobile/src/i18n/locales/ko/session.json
index d50aa2cfd1,72988edde9..521f611f12
--- a/apps/mobile/src/i18n/locales/ko/session.json
+++ b/apps/mobile/src/i18n/locales/ko/session.json
@@@ -423,6 -469,6 +469,7 @@@
"continueTask": "작업 계속",
"retry": "다시 시도",
"ignore": "무시",
++ "outputLimit": "모델이 출력 한도에 도달하여 이번 응답은 불완전할 수 있습니다. 다음 메시지를 보내 계속할 수 있습니다.",
"toolUseLoopDetected": "모델이 도구 호출을 너무 많이 반복하여 무한 루프를 방지하기 위해 이번 턴을 중지했습니다. 새 메시지를 보내 계속할 수 있습니다.",
"toolUseLoopDetectedWithCount": "모델이 잘못된 도구 호출을 반복하여 무한 루프를 방지하기 위해 {{count}}회 실패 후 이번 턴을 중지했습니다. 새 메시지를 보내 계속할 수 있습니다.",
"toolUseLoopDetectedConsecutiveWithCount": "모델이 동일한 도구 호출을 {{count}}회 반복하여 무한 루프를 막기 위해 이번 턴을 중단했습니다. 새 메시지를 보내 계속할 수 있습니다.",
diff --cc apps/mobile/src/i18n/locales/zh-CN/session.json
index 436cf9b751,84407c4225..69a04f6eb2
--- a/apps/mobile/src/i18n/locales/zh-CN/session.json
+++ b/apps/mobile/src/i18n/locales/zh-CN/session.json
@@@ -423,6 -469,6 +469,7 @@@
"continueTask": "继续任务",
"retry": "重试",
"ignore": "忽略",
++ "outputLimit": "模型已达到输出长度上限,本轮回复可能不完整。可以直接发送下一条消息继续。",
"toolUseLoopDetected": "模型重复调用工具次数过多,Cindy 已停止本轮以避免无限循环。可以发送新消息继续。",
"toolUseLoopDetectedWithCount": "模型连续触发了无效的工具调用,Cindy 已在 {{count}} 次失败后停止本轮,以避免无限循环。可以发送新消息继续。",
"toolUseLoopDetectedConsecutiveWithCount": "模型重复调用同一个工具 {{count}} 次,Cindy 已停止本轮以避免无限循环。可以发送新消息继续。",
diff --cc apps/mobile/src/i18n/locales/zh-TW/session.json
index a4dbca8b35,b135f82f8a..ae755c82ea
--- a/apps/mobile/src/i18n/locales/zh-TW/session.json
+++ b/apps/mobile/src/i18n/locales/zh-TW/session.json
@@@ -423,6 -469,6 +469,7 @@@
"continueTask": "繼續任務",
"retry": "重試",
"ignore": "忽略",
++ "outputLimit": "模型已達到輸出長度上限,本輪回覆可能不完整。可以直接傳送下一則訊息繼續。",
"toolUseLoopDetected": "模型重複呼叫工具次數過多,Cindy 已停止這一輪以避免無限迴圈。可以傳送新訊息繼續。",
"toolUseLoopDetectedWithCount": "模型連續觸發無效的工具呼叫,Cindy 已在 {{count}} 次失敗後停止本輪,以避免無限迴圈。可以傳送新訊息繼續。",
"toolUseLoopDetectedConsecutiveWithCount": "模型重複呼叫同一個工具 {{count}} 次,Cindy 已停止本輪以避免無限迴圈。可以傳送新訊息繼續。",
diff --cc apps/mobile/src/session/InlineQueueSection.tsx
index ae2fd61dab,ae2fd61dab..39b3a67c08
--- a/apps/mobile/src/session/InlineQueueSection.tsx
+++ b/apps/mobile/src/session/InlineQueueSection.tsx
@@@ -25,7 -25,7 +25,7 @@@ import { Pause, Play } from 'lucide-rea
import { describeAgentAuthError } from '@/device-link/remoteStatus';
import type { InputProjection } from '@/session/types';
import { inputProjectionErrorI18nKey } from '@/session/inputProjectionError';
--import { localizeToolLoopError } from '@/session/toolLoopErrorI18n';
++import { localizeAgentError } from '@/session/agentErrorI18n';
import {
fontWeight,
iconSize,
@@@ -65,7 -65,7 +65,7 @@@ export function InlineQueueSection(
if (!hasBanner) return null;
const controlsDisabled = busy || !!readOnlyReason;
-- const localizedToolLoopError = localizeToolLoopError(
++ const localizedAgentError = localizeAgentError(
projection.errorReason,
projection.toolLoop ?? null,
);
@@@ -73,7 -73,7 +73,7 @@@
? inputProjectionErrorI18nKey(projection.error)
: null;
const projectionError = projection.error
-- ? localizedToolLoopError
++ ? localizedAgentError
?? (projectionErrorKey
? t(projectionErrorKey)
: (describeAgentAuthError(projection.error) ?? projection.error))
diff --cc apps/mobile/src/session/agentErrorI18n.ts
index 3470527574,3470527574..62238e358b
--- a/apps/mobile/src/session/agentErrorI18n.ts
+++ b/apps/mobile/src/session/agentErrorI18n.ts
@@@ -42,14 -42,14 +42,15 @@@ export function parseMobileToolLoopErro
}
/**
-- * Localize the stable tool-loop reason for both the normal message stream and
++ * Localize stable agent error reasons for both the normal message stream and
* the session-tail banner. Returning null keeps unrelated error rows on their
* existing auth-guidance/raw-message paths.
*/
--export function localizeToolLoopError(
++export function localizeAgentError(
reason: unknown,
toolLoop: MobileToolLoopErrorDetails | null,
): string | null {
++ if (reason === 'output-limit') return i18n.t('session.tail.outputLimit');
if (reason !== 'tool_use_loop_detected') return null;
if (!toolLoop) return i18n.t('session.tail.toolUseLoopDetected');
return i18n.t(TOOL_LOOP_I18N_KEYS[toolLoop.kind], { count: toolLoop.count });
diff --cc apps/mobile/src/session/inputProjection.ts
index b08414782f,b08414782f..445e6e58b8
--- a/apps/mobile/src/session/inputProjection.ts
+++ b/apps/mobile/src/session/inputProjection.ts
@@@ -9,7 -9,7 +9,7 @@@ import
} from '@cindy/maker-shared/agent-input-projection';
import type { InputProjection, QueuedRemoteMessage, RemoteImageRef, RemoteSession } from '@/session/types';
import type { RemoteSerializedAttachment } from '@/session/types';
--import { parseMobileToolLoopErrorDetails } from '@/session/toolLoopErrorI18n';
++import { parseMobileToolLoopErrorDetails } from '@/session/agentErrorI18n';
import { permissionModeOrAsk } from '@cindy/maker-shared/permission-mode';
import {
composerDocumentsEqual,
diff --cc apps/mobile/src/session/messageNormalize.ts
index 0157ecd61f,722f7100bc..3d7bea2a78
--- a/apps/mobile/src/session/messageNormalize.ts
+++ b/apps/mobile/src/session/messageNormalize.ts
@@@ -48,9 -50,10 +50,10 @@@ import
type RemoteMoney,
} from '@/session/remoteMoney';
import {
-- localizeToolLoopError,
++ localizeAgentError,
parseMobileToolLoopErrorDetails,
--} from '@/session/toolLoopErrorI18n';
++} from '@/session/agentErrorI18n';
+ import type { MobileToolInputProjection } from '@/session/messageToolPayloadProjection';
export type NormalizedRemoteMessageKind =
| 'user'
@@@ -260,7 -296,7 +296,7 @@@ export function normalizeRemoteMessages
const rawText = typeof c?.message === 'string' ? c.message : contentToPreview(message.content);
const toolLoop = parseMobileToolLoopErrorDetails(c?.toolLoop);
const errText =
-- describeAgentAuthError(rawText) ?? localizeToolLoopError(c?.reason, toolLoop) ?? rawText;
++ describeAgentAuthError(rawText) ?? localizeAgentError(c?.reason, toolLoop) ?? rawText;
result.push({
key: messageNormalizeKey(message),
source: message,
diff --cc apps/mobile/src/session/sessionTailBannerModel.ts
index 3ba9c9d7fd,3ba9c9d7fd..0889744e0f
--- a/apps/mobile/src/session/sessionTailBannerModel.ts
+++ b/apps/mobile/src/session/sessionTailBannerModel.ts
@@@ -30,10 -30,10 +30,10 @@@ import { describeAgentAuthError } from
import { i18n } from '@/i18n';
import type { InputProjection, QueuedRemoteMessage, RemoteMessage, RemoteSession } from '@/session/types';
import {
-- localizeToolLoopError,
++ localizeAgentError,
parseMobileToolLoopErrorDetails,
type MobileToolLoopErrorDetails,
--} from '@/session/toolLoopErrorI18n';
++} from '@/session/agentErrorI18n';
export interface SessionTailErrorBanner {
kind: 'error-tail';
@@@ -100,11 -100,11 +100,11 @@@ export function resolveSessionTailBanne
const tail = findErrorTailMessage(input.messages);
if (tail && !input.hiddenErrorClientIds.has(tail.clientId)) {
const nonRetryableGuidance = describeNonRetryableTailError(tail.text);
-- const toolLoopGuidance = localizeToolLoopError(tail.reason, tail.toolLoop);
++ const agentErrorGuidance = localizeAgentError(tail.reason, tail.toolLoop);
return {
kind: 'error-tail',
clientId: tail.clientId,
-- text: nonRetryableGuidance ?? toolLoopGuidance ?? tail.text,
++ text: nonRetryableGuidance ?? agentErrorGuidance ?? tail.text,
continueKind: tail.reason === APP_EXIT_INTERRUPTED_REASON ? 'interrupted' : 'error',
retryable: nonRetryableGuidance === null,
};
diff --cc apps/mobile/src/session/types.ts
index 8fff0c87aa,6018b40a09..c7cf2aff83
--- a/apps/mobile/src/session/types.ts
+++ b/apps/mobile/src/session/types.ts
@@@ -1,7 -1,8 +1,8 @@@
import type { MobileSessionAgentSwitchIntent } from '@cindy/maker-shared/device-link-contract';
import type { AgentInputReference } from '@cindy/maker-shared/agent-input-projection';
import type { RemoteMoney } from '@/session/remoteMoney';
--import type { MobileToolLoopErrorDetails } from '@/session/toolLoopErrorI18n';
++import type { MobileToolLoopErrorDetails } from '@/session/agentErrorI18n';
+ import type { MobileToolInputProjection } from '@/session/messageToolPayloadProjection';
export type RemoteSessionStatus = 'active' | 'archived' | 'deleted';
export type RemoteMessageRole =
diff --cc packages/maker-core/src/agents/pi/__tests__/pi-translator.test.ts
index 285a6bd8e6,cf62ae2186..51a4424855
--- a/packages/maker-core/src/agents/pi/__tests__/pi-translator.test.ts
+++ b/packages/maker-core/src/agents/pi/__tests__/pi-translator.test.ts
@@@ -442,53 -486,6 +486,118 @@@ describe('pi translator', () =>
}));
});
- it('preserves length-limited text but reports that the Pi response is incomplete', () => {
++ it.each(['DeepSeek-V4-Flash-0731', 'claude-sonnet-4-6'])('preserves length-limited text and usage for %s', (model) => {
+ const ctx = createPiTranslateContext(noopLogger);
+ const { queue, events } = makeQueue();
+
+ translatePiEvent(ev({ type: 'agent_start' }), queue, ctx);
+ translatePiEvent(
+ ev({
+ type: 'message_end',
+ message: {
+ role: 'assistant',
+ content: [{ type: 'text', text: 'a long but incomplete answer' }],
- model: 'DeepSeek-V4-Flash-0731',
++ model,
+ stopReason: 'length',
+ usage: { input: 100, output: 16_000 },
+ },
+ }),
+ queue,
+ ctx,
+ );
+ translatePiEvent(ev({ type: 'agent_settled' }), queue, ctx);
+
+ expect(events.filter((event) => event.type === 'text')).toContainEqual(
+ expect.objectContaining({
+ data: expect.objectContaining({
+ text: 'a long but incomplete answer',
+ isFinal: true,
+ }),
+ }),
+ );
+ expect(events.filter((event) => event.type === 'error')).toEqual([
+ expect.objectContaining({
+ source: 'pi',
+ data: expect.objectContaining({
+ reason: 'output-limit',
+ isTerminal: true,
+ }),
+ }),
+ ]);
+ expect((events.find((event) => event.type === 'done')?.data as {
+ result?: unknown;
+ usage?: { outputTokens?: unknown };
+ })).toMatchObject({
+ result: 'a long but incomplete answer',
- usage: { outputTokens: 16_000 },
++ status: 'failed',
++ usage: { inputTokens: 100, outputTokens: 16_000 },
+ });
+ });
+
++ it.each([['empty', ''], ['logs', '2026-09-09 INFO health check succeeded\n'.repeat(1_000)], ['JSON', JSON.stringify(Array(20_000).fill(0))]])(
++ 'uses the provider stop reason rather than text repetition (%s)',
++ (_label, text) => {
++ const ctx = createPiTranslateContext(noopLogger);
++ const { queue, events } = makeQueue();
++ translatePiEvent(ev({ type: 'agent_start' }), queue, ctx);
++ translatePiEvent(ev({ type: 'message_start', message: { role: 'assistant' } }), queue, ctx);
++ translatePiEvent(ev({ type: 'message_update', assistantMessageEvent: {
++ type: 'text_delta', delta: text, contentIndex: 0,
++ } }), queue, ctx);
++ translatePiEvent(ev({ type: 'message_end', message: {
++ role: 'assistant', content: [{ type: 'text', text }], stopReason: 'length',
++ usage: { input: 10, output: 16_000 },
++ } }), queue, ctx);
++ expect(events.filter((event) => event.type === 'error')).toEqual([]);
++ translatePiEvent(ev({ type: 'agent_settled' }), queue, ctx);
++ translatePiEvent(ev({ type: 'agent_settled' }), queue, ctx);
++ expect(events.filter((event) => event.type === 'error')).toHaveLength(1);
++ const done = events.filter((event) => event.type === 'done');
++ expect(done).toHaveLength(1);
++ expect(done[0]?.data).toMatchObject({ status: 'failed', result: text, usage: { outputTokens: 16_000 } });
++ expect(done[0]?.data).not.toHaveProperty('silentStop');
++
++ events.length = 0;
++ translatePiEvent(ev({ type: 'agent_start' }), queue, ctx);
++ translatePiEvent(ev({ type: 'message_end', message: {
++ role: 'assistant', content: [{ type: 'text', text }], stopReason: 'stop',
++ } }), queue, ctx);
++ translatePiEvent(ev({ type: 'agent_settled' }), queue, ctx);
++ expect(events.filter((event) => event.type === 'error')).toEqual([]);
++ expect(events.find((event) => event.type === 'done')?.data).toMatchObject({ status: 'completed', result: text });
++ },
++ );
++
++ it.each(['stop', 'error', 'aborted', 'host-stop'])(
++ 'does not retain a length error when the final outcome is %s', (outcome) => {
++ const ctx = createPiTranslateContext(noopLogger);
++ const { queue, events } = makeQueue();
++ translatePiEvent(ev({ type: 'agent_start' }), queue, ctx);
++ translatePiEvent(ev({ type: 'message_end', message: {
++ role: 'assistant', content: [{ type: 'text', text: 'partial answer' }], stopReason: 'length',
++ usage: { input: 10, output: 16_000 },
++ } }), queue, ctx);
++ if (outcome === 'host-stop') {
++ markPiHostAbortRequested(ctx);
++ } else {
++ translatePiEvent(ev({ type: 'message_end', message: {
++ role: 'assistant', content: [{ type: 'text', text: 'recovered answer' }],
++ stopReason: outcome, ...(outcome === 'error' ? { errorMessage: 'provider rejected request' } : {}),
++ usage: { input: 20, output: 100 },
++ } }), queue, ctx);
++ }
++ translatePiEvent(ev({ type: 'agent_settled' }), queue, ctx);
++ const errors = events.filter((event) => event.type === 'error');
++ expect(errors).toHaveLength(outcome === 'error' ? 1 : 0);
++ expect(errors.some((event) => (event.data as { reason?: string }).reason === 'output-limit')).toBe(false);
++ expect(events.find((event) => event.type === 'done')?.data).toMatchObject({
++ status: outcome === 'stop' ? 'completed' : outcome === 'error' ? 'failed' : 'cancelled',
++ result: outcome === 'stop' ? 'recovered answer' : '',
++ usage: { outputTokens: outcome === 'host-stop' ? 16_000 : 16_100 },
++ });
++ },
++ );
++
it('drops a pending provider error when Pi auto-retry succeeds', () => {
const ctx = createPiTranslateContext(noopLogger);
const { queue, events } = makeQueue();
diff --cc packages/maker-core/src/agents/pi/translator.ts
index e9662ae07c,e4e727d729..f4367474d2
--- a/packages/maker-core/src/agents/pi/translator.ts
+++ b/packages/maker-core/src/agents/pi/translator.ts
@@@ -937,17 -930,14 +930,24 @@@ export function translatePiEvent
stopPiGenerationHeartbeat(ctx);
const hostAbortRequested = isCurrentTurnHostAbortRequested(ctx);
const pendingAssistantError = hostAbortRequested ? null : ctx.pendingAssistantError;
- ctx.pendingAssistantError = null;
- const pendingSafetyError = ctx.pendingSafetyError;
- ctx.pendingSafetyError = null;
- const terminalError = pendingSafetyError ?? pendingAssistantError;
- const outcome = pendingAssistantError
++ // Classify the final assistant message at settlement, after native retries
++ // and continuations have had a chance to recover. A host Stop still wins.
++ const outputLimited = !hostAbortRequested
++ && !ctx.terminalAssistantErrorEmitted
++ && ctx.finalAssistantStopReason === 'length';
++ const terminalError = pendingAssistantError ?? (outputLimited ? {
++ message: 'Pi reached the model output limit. The response may be incomplete.',
++ sdkError: 'Pi response stopped at the model output limit',
++ reason: 'output-limit',
++ } : null);
+ const outcome = terminalError
? 'failed'
: hostAbortRequested || ctx.finalAssistantStopReason === 'aborted'
? 'cancelled'
: 'completed';
+ ctx.pendingAssistantError = null;
clearPiHostAbortRequests(ctx);
- if (pendingAssistantError) {
+ if (terminalError) {
queue.push({
type: 'error',
data: {
@@@ -964,10 -966,12 +976,12 @@@
// 本 turn 最终 assistant 回复文本。与 CC/Codex 的 done.data.result 对齐:
// register.ts 的 will-assistant-message 出口钩子与 Orca worker 终态 finalText
// 都读 done.data.result,不带上就会对 Pi 静默跳过这些钩子(codex review P1)。
- // 本地安全止损也必须保留已经产生的正文,便于用户确认中断点;普通
- // provider 失败/用户取消仍保持空 result,避免把半截失败响应当成功答案。
- result: pendingSafetyError || outcome === 'completed' ? ctx.finalAssistantText : '',
- result: outcome === 'completed' ? ctx.finalAssistantText : '',
++ result: outputLimited || outcome === 'completed' ? ctx.finalAssistantText : '',
status: outcome,
+ // Reuse the host's bounded silent-stop continuation guard. This
+ // continues the same conversation after completed tools; it does not
+ // replay the original user request or its side effects.
+ ...(silentStop ? { silentStop: true } : {}),
// ghost 订阅 did-turn-end 的 usage 上报(subscriptionGateway.normalizeTurnUsage
// 认 camelCase);与 CC/Codex 的 done.usage 对齐,让插件能显示 pi turn 的用量。
usage: {
@@@ -1127,12 -1132,15 +1142,15 @@@
return;
}
++ // Pi v0.84.3 extension telemetry. If it ever leaks onto the RPC stream,
++ // ignore it: compaction_end already carries aborted/errorMessage.
case 'queue_update':
case 'thinking_level_changed':
case 'summarization_retry_scheduled':
case 'summarization_retry_attempt_start':
case 'summarization_retry_finished':
case 'bash_execution_update':
- // Pi v0.84.3 extension telemetry. If it ever leaks onto the RPC stream,
- // ignore it: compaction_end already carries aborted/errorMessage.
+ case 'session_compact_failed':
return;
case 'extension_error': {
diff --cc packages/maker-core/src/maker.shutdown.test.ts
index 0bafef7f7d,e44e11d2db..1240067509
--- a/packages/maker-core/src/maker.shutdown.test.ts
+++ b/packages/maker-core/src/maker.shutdown.test.ts
@@@ -63,6 -63,6 +63,7 @@@ function createHandle(overrides: Partia
abort: async () => undefined,
close: async () => undefined,
events: async function* () {
++ yield* [];
await new Promise<never>(() => undefined);
},
getUsageSnapshot: () => ({ tokenUsage: 0, contextTokens: 0, contextWindow: 0, costUsd: 0 }),
@@@ -86,7 -86,75 +87,75 @@@ function createAgent(handle: AgentSessi
} as unknown as BaseAgent;
}
-function createDeferred<T = void>(): { promise: Promise<T>; resolve: (value?: T | PromiseLike<T>) => void } {
- let resolve!: (value?: T | PromiseLike<T>) => void;
- const promise = new Promise<T>((res) => { resolve = res; });
++function createDeferred(): { promise: Promise<void>; resolve: () => void } {
++ let resolve!: () => void;
++ const promise = new Promise<void>((res) => { resolve = res; });
+ return { promise, resolve };
+ }
+
describe('Maker.shutdown', () => {
+ it('waits for deferred startup cleanup hooks before resolving', async () => {
+ const stopped = createDeferred();
+ const cleanupGate = createDeferred();
+ let cleanupEntered = false;
+ const pending = new AgentStartupCleanupPendingError('startup cleanup pending', {
+ cause: new Error('adapter startup failed'),
+ whenStopped: stopped.promise,
+ });
+ const agent = createAgent(createHandle({ agentKind: 'pi' }));
+ agent.startSession = vi.fn().mockRejectedValue(pending);
+ const maker = new Maker({
+ agents: { pi: agent },
+ storage: createStorage(),
+ logger,
+ lifecycleHooks: {
+ onStartCleanupSucceeded: async () => {
+ cleanupEntered = true;
+ await cleanupGate.promise;
+ },
+ },
+ });
+ await expect(maker.createSession({ id: 's-deferred-cleanup', agentKind: 'pi', workingDir: '/w', model: 'm' }))
+ .rejects.toBe(pending);
+
+ let shutdownSettled = false;
+ const shutdown = maker.shutdown().then(() => { shutdownSettled = true; });
+ stopped.resolve();
+ await vi.waitFor(() => expect(cleanupEntered).toBe(true));
+ expect(shutdownSettled).toBe(false);
+
+ cleanupGate.resolve();
+ await shutdown;
+ expect(shutdownSettled).toBe(true);
+ });
+
+ it('waits for session lifecycle cleanup hooks before resolving', async () => {
+ let releaseCleanup!: () => void;
+ const cleanupGate = new Promise<void>((resolve) => { releaseCleanup = resolve; });
+ let cleanupEntered = false;
+ const maker = new Maker({
+ agents: { 'claude-code': createAgent(createHandle({})) },
+ storage: createStorage(),
+ logger,
+ lifecycleHooks: {
+ onClose: async () => {
+ cleanupEntered = true;
+ await cleanupGate;
+ },
+ },
+ });
+ await maker.createSession({ id: 's-cleanup', agentKind: 'claude-code', workingDir: '/w', model: 'm' });
+
+ let shutdownSettled = false;
+ const shutdown = maker.shutdown().then(() => { shutdownSettled = true; });
+ await vi.waitFor(() => expect(cleanupEntered).toBe(true));
+ expect(shutdownSettled).toBe(false);
+
+ releaseCleanup();
+ await shutdown;
+ expect(shutdownSettled).toBe(true);
+ });
+
it('detaches remote-capable sessions instead of full-closing them', async () => {
const close = vi.fn(async () => undefined);
const detach = vi.fn(async () => undefined);