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(desktop): LiteLLM 流中断不再显示成 OpenAI API error (#3113)

Dash2ad9d2de34b1
diff --git a/apps/desktop/src/renderer/__tests__/errorBannerStreamInterrupt.test.tsx b/apps/desktop/src/renderer/__tests__/errorBannerStreamInterrupt.test.tsx
new file mode 100644
index 0000000000..39f1b48156
--- /dev/null
+++ b/apps/desktop/src/renderer/__tests__/errorBannerStreamInterrupt.test.tsx
@@ -0,0 +1,86 @@
+// @vitest-environment jsdom
+
+/**
+ * ErrorBanner — LiteLLM / Responses 流中断展示不变量:
+ * 1. 命中 in-stream 空壳 → 人话文案,不显示 OpenAI 协议外壳。
+ * 2. 有 retryText 时 Retry 仍在(不自动续跑,但用户可点重试)。
+ * 3. 「查看原始错误」展开的是未改写的 `error` 原文。
+ */
+
+import { cleanup, fireEvent, render, screen } from '@testing-library/react';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { createElement } from 'react';
+
+const { useCodexRuntimeRouteMock } = vi.hoisted(() => ({
+ useCodexRuntimeRouteMock: vi.fn(),
+}));
+
+vi.mock('react-i18next', () => ({
+ useTranslation: () => ({ t: (key: string) => key }),
+}));
+
+vi.mock('@/components/ui/confirm-dialog-provider', () => ({
+ useConfirmDialog: () => ({ confirm: async () => true }),
+}));
+
+vi.mock('@/hooks/useCodexRuntimeRoute', () => ({
+ useCodexRuntimeRoute: useCodexRuntimeRouteMock,
+}));
+
+vi.mock('@/hooks/useCodexSessionExpiredPrompt', () => ({
+ isCodexSessionExpiredError: () => false,
+ useCodexSessionExpiredPrompt: () => vi.fn(),
+}));
+
+import { ErrorBanner } from '@/components/chat/ErrorBanner';
+import { UPSTREAM_STREAM_INTERRUPTED_REASON } from '@/utils/streamInterruptError';
+
+const STREAM_RAW =
+ 'OpenAI API error (500): {"message":"litellm.APIError: Response API in-stream error","type":null,"param":null,"code":"500"}';
+
+beforeEach(() => {
+ useCodexRuntimeRouteMock.mockReturnValue({ authInjection: 'env-key' });
+});
+
+afterEach(() => {
+ cleanup();
+ vi.clearAllMocks();
+});
+
+describe('ErrorBanner — LiteLLM 流中断', () => {
+ it('有 retryText 时用人话、保留 Retry、展开仍是未改写原文', () => {
+ const onRetry = vi.fn();
+
+ render(
+ createElement(ErrorBanner, {
+ error: STREAM_RAW,
+ errorReason: UPSTREAM_STREAM_INTERRUPTED_REASON,
+ retryText: 'retry-token',
+ onRetry,
+ agentKind: 'pi',
+ }),
+ );
+
+ expect(screen.getByText('chat.errorBanner.streamInterrupted')).toBeTruthy();
+ expect(screen.queryByText(STREAM_RAW)).toBeNull();
+
+ fireEvent.click(screen.getByTitle('chat.errorBanner.retryTitle'));
+ expect(onRetry).toHaveBeenCalledWith('retry-token');
+
+ fireEvent.click(screen.getByText('chat.errorBanner.networkShowRaw'));
+ expect(screen.getByText(STREAM_RAW)).toBeTruthy();
+ });
+
+ it('没有 retryText 时用人话且不显示 Retry', () => {
+ render(
+ createElement(ErrorBanner, {
+ error: STREAM_RAW,
+ onRetry: vi.fn(),
+ agentKind: 'pi',
+ }),
+ );
+
+ expect(screen.getByText('chat.errorBanner.streamInterruptedNoRetry')).toBeTruthy();
+ expect(screen.queryByTitle('chat.errorBanner.retryTitle')).toBeNull();
+ });
+});
diff --git a/apps/desktop/src/renderer/__tests__/streamInterruptError.test.ts b/apps/desktop/src/renderer/__tests__/streamInterruptError.test.ts
new file mode 100644
index 0000000000..a0bab1cd10
--- /dev/null
+++ b/apps/desktop/src/renderer/__tests__/streamInterruptError.test.ts
@@ -0,0 +1,65 @@
+import { describe, expect, it } from 'vitest';
+
+import {
+ UPSTREAM_STREAM_INTERRUPTED_REASON,
+ isStreamInterruptedErrorMessage,
+ unwrapProviderErrorDisplay,
+} from '@/utils/streamInterruptError';
+
+describe('isStreamInterruptedErrorMessage', () => {
+ it('accepts the classified reason even when the message has been rewritten', () => {
+ expect(
+ isStreamInterruptedErrorMessage('anything', UPSTREAM_STREAM_INTERRUPTED_REASON),
+ ).toBe(true);
+ });
+
+ it('matches the observed LiteLLM envelope without a reason', () => {
+ expect(
+ isStreamInterruptedErrorMessage(
+ 'OpenAI API error (500): {"message":"litellm.APIError: Response API in-stream error","type":null,"param":null,"code":"500"}',
+ ),
+ ).toBe(true);
+ });
+});
+
+describe('unwrapProviderErrorDisplay', () => {
+ it('strips the OpenAI protocol prefix and LiteLLM JSON envelope', () => {
+ expect(
+ unwrapProviderErrorDisplay(
+ 'OpenAI API error (500): {"message":"litellm.APIError: Response API in-stream error","type":null,"param":null,"code":"500"}',
+ ),
+ ).toBe('Response API in-stream error');
+ });
+
+ it('unwraps a Grok overflow that was branded as OpenAI', () => {
+ expect(
+ unwrapProviderErrorDisplay(
+ 'OpenAI API error (400): {"message":"litellm.BadRequestError: XaiException - too long"}',
+ ),
+ ).toBe('XaiException - too long');
+ });
+
+ it('leaves unrelated messages alone', () => {
+ expect(unwrapProviderErrorDisplay('Network error: fetch failed')).toBe(
+ 'Network error: fetch failed',
+ );
+ });
+
+ it('does not strip a bare LiteLLM quota error used by ErrorBanner classification', () => {
+ expect(
+ unwrapProviderErrorDisplay('litellm.BadRequestError: insufficient_quota for this key'),
+ ).toBe('litellm.BadRequestError: insufficient_quota for this key');
+ });
+
+ it('keeps genuine OpenAI / Azure OpenAI provenance and HTTP status', () => {
+ expect(unwrapProviderErrorDisplay('OpenAI API error (400): invalid_prompt')).toBe(
+ 'OpenAI API error (400): invalid_prompt',
+ );
+ expect(
+ unwrapProviderErrorDisplay('Azure OpenAI API error (401): invalid_api_key'),
+ ).toBe('Azure OpenAI API error (401): invalid_api_key');
+ expect(
+ unwrapProviderErrorDisplay('OpenAI API error (400): {"message":"invalid_prompt"}'),
+ ).toBe('OpenAI API error (400): {"message":"invalid_prompt"}');
+ });
+});
diff --git a/apps/desktop/src/renderer/components/chat/ErrorBanner.tsx b/apps/desktop/src/renderer/components/chat/ErrorBanner.tsx
index d99c6aaac2..a1465450fa 100644
--- a/apps/desktop/src/renderer/components/chat/ErrorBanner.tsx
+++ b/apps/desktop/src/renderer/components/chat/ErrorBanner.tsx
@@ -41,6 +41,10 @@ import { cn } from '@/lib/utils';
import { isInvalidEncryptedContentError } from '@/utils/encryptedContentError';
import { isNetworkishErrorMessage, parseReconnectAttemptMessage } from '@/utils/networkError';
import { isOverloadErrorMessage, parseOverloadRetryProgress } from '@/utils/overloadError';
+import {
+ isStreamInterruptedErrorMessage,
+ unwrapProviderErrorDisplay,
+} from '@/utils/streamInterruptError';
import { isQuotaExhaustedErrorMessage } from '@/utils/quotaError';
import { parseTerminalRateLimitRetryProgress } from '@/utils/rateLimitRetry';
import type { UsageLimitRecoveryHint } from '@/lib/usageLimitRecovery';
@@ -261,6 +265,8 @@ export function ErrorBanner({
// 而这条判定驱动的正是本地化文案、重试进度与 hideRetry。文案匹配保留作兜底
// (老 daemon / Anthropic 侧 / 历史持久化错误行 —— 后者只有文案可用)。
const isOverloadError = isOverloadErrorMessage(error, undefined, errorReason);
+ const isStreamInterrupted = isStreamInterruptedErrorMessage(error, errorReason);
+ const unwrappedDisplay = unwrapProviderErrorDisplay(error);
const overloadRetryProgress = parseOverloadRetryProgress(error);
const errorReasonI18nKey = errorReason ? ERROR_REASON_I18N_KEYS[errorReason] : undefined;
const terminalRateLimitRetryProgress = parseTerminalRateLimitRetryProgress(error, errorReason);
@@ -394,6 +400,14 @@ export function ErrorBanner({
maxAttempts: overloadRetryProgress.maxAttempts,
})
: t(safeRetryText ? 'chat.errorBanner.overloadBusy' : 'chat.errorBanner.overloadBusyNoRetry');
+ } else if (isStreamInterrupted) {
+ // LiteLLM / Responses 流中途空壳 500。协议客户端会写成 OpenAI API error,
+ // 对非 OpenAI 模型是误导。只改展示,不自动续跑。
+ displayError = t(
+ safeRetryText
+ ? 'chat.errorBanner.streamInterrupted'
+ : 'chat.errorBanner.streamInterruptedNoRetry',
+ );
} else if (isNetworkishError) {
// 网络类错误:原始英文报错(502/ECONNREFUSED/fetch failed 等)对用户没有
// 行动价值,换成友好文案;原始错误折叠可查(下方「查看原始错误」)。
@@ -416,9 +430,10 @@ export function ErrorBanner({
// the final fallback uses the stable reason map, so auth/network/overload
// recovery behavior keeps its existing priority while generic maker-core
// English fallbacks are localized in both the live and tail banner.
- displayError = errorReasonI18nKey ? t(errorReasonI18nKey) : error;
+ displayError = errorReasonI18nKey ? t(errorReasonI18nKey) : unwrappedDisplay;
hasSpecialGuidance = false;
}
+ const showUnwrappedRaw = !hasSpecialGuidance && !errorReasonI18nKey && unwrappedDisplay !== error;
// 折扣版 GPT (budget, `codex/` 前缀) 走 gateway, 偶发限流 / 后端不可用时, 普通版
// 往往能正常出。仅在通用错误分支 (上面没命中任何特殊分支) 追加一句切普通版的引导
@@ -555,6 +570,8 @@ export function ErrorBanner({
)}
{(isNetworkishError ||
isOverloadError ||
+ isStreamInterrupted ||
+ showUnwrappedRaw ||
isCodexUsageLimitError ||
terminalRateLimitRetryProgress ||
isClaudeGatewayOpusPlanMismatch ||
diff --git a/apps/desktop/src/renderer/components/chat/ErrorMessageCard.tsx b/apps/desktop/src/renderer/components/chat/ErrorMessageCard.tsx
index 5cf21f7e2e..ca3b92fdfe 100644
--- a/apps/desktop/src/renderer/components/chat/ErrorMessageCard.tsx
+++ b/apps/desktop/src/renderer/components/chat/ErrorMessageCard.tsx
@@ -4,8 +4,8 @@
* 渲染历史里持久化的 role='error' 行(turn 失败终态,main 的 onTurnErrorEvent
* 落库)。定位是**事后可追溯的时间线记录**,与输入框上方的 ErrorBanner 分工:
* - ErrorBanner:live 报错,带 Retry / Cancel / auth 同步等交互;
- * - 本卡:历史加载时还原"这一轮在这里失败了",纯展示、无任何交互按钮
- * (历史错误对应的 turn 早已收场,Retry 语义不成立)。
+ * - 本卡:历史加载时还原"这一轮在这里失败了"。Retry 语义不成立(turn 早已收场),
+ * 唯一交互是友好文案/协议拆封后的「查看原始错误」,与 live ErrorBanner 对齐。
*
* 文案:errorReason 是 maker-core 的稳定 key,优先走 i18n(规则 18;与 live
* ErrorBanner 的 reason → i18n 映射同款);没有 reason 或 key 未知时,回退经
@@ -14,18 +14,37 @@
*
* 视觉:走 `--error-bg` / `--error-border` / `--error-fg` 主题 token(规则 16;
* 错误红属跨主题语义豁免色,token 默认值即语义红,非默认主题可按需 override),
- * 与 ErrorBanner 同语义但去掉按钮区,为随内容的 inline 卡。
+ * 与 ErrorBanner 同语义,为随内容的 inline 卡。
*/
+import { useEffect, useState } from 'react';
import { AlertCircle } from 'lucide-react';
import { useTranslation } from 'react-i18next';
+import {
+ isStreamInterruptedErrorMessage,
+ unwrapProviderErrorDisplay,
+} from '@/utils/streamInterruptError';
import { decodeRemoteErrorMessage } from '../../lib/makerChatStore';
import { ERROR_REASON_I18N_KEYS } from './errorReasonI18n';
export function ErrorMessageCard({ message, reason }: { message: string; reason?: string }) {
const { t } = useTranslation();
+ const [showRaw, setShowRaw] = useState(false);
+ const decoded = decodeRemoteErrorMessage(message);
const i18nKey = reason ? ERROR_REASON_I18N_KEYS[reason] : undefined;
- const text = i18nKey ? t(i18nKey) : decodeRemoteErrorMessage(message);
+ const isStreamInterrupted = isStreamInterruptedErrorMessage(message, reason);
+ const unwrapped = unwrapProviderErrorDisplay(decoded);
+ const text = isStreamInterrupted
+ ? t('chat.errorBanner.streamInterruptedNoRetry')
+ : i18nKey
+ ? t(i18nKey)
+ : unwrapped;
+ const showRawToggle = isStreamInterrupted || (!i18nKey && unwrapped !== decoded);
+
+ useEffect(() => {
+ setShowRaw(false);
+ }, [message, reason]);
+
if (!text) return null;
return (
<div
@@ -33,7 +52,27 @@ export function ErrorMessageCard({ message, reason }: { message: string; reason?
data-testid="error-message-card"
>
<AlertCircle size={14} className="shrink-0 mt-[2px] text-[var(--error-fg)]" />
- <span className="min-w-0 text-xs break-all text-[var(--error-fg)]">{text}</span>
+ <div className="flex-1 min-w-0">
+ <span className="block min-w-0 text-xs break-all text-[var(--error-fg)]">{text}</span>
+ {showRawToggle && (
+ <>
+ <button
+ type="button"
+ onClick={() => setShowRaw((v) => !v)}
+ className="mt-0.5 block text-xs underline opacity-70 hover:opacity-50 transition-opacity text-[var(--error-fg)]"
+ >
+ {showRaw
+ ? t('chat.errorBanner.networkHideRaw')
+ : t('chat.errorBanner.networkShowRaw')}
+ </button>
+ {showRaw && (
+ <span className="mt-0.5 block text-xs break-all opacity-70 text-[var(--error-fg)]">
+ {decoded}
+ </span>
+ )}
+ </>
+ )}
+ </div>
</div>
);
}
diff --git a/apps/desktop/src/renderer/components/chat/__tests__/ErrorMessageCard.test.tsx b/apps/desktop/src/renderer/components/chat/__tests__/ErrorMessageCard.test.tsx
new file mode 100644
index 0000000000..f36f539505
--- /dev/null
+++ b/apps/desktop/src/renderer/components/chat/__tests__/ErrorMessageCard.test.tsx
@@ -0,0 +1,51 @@
+// @vitest-environment jsdom
+
+import { cleanup, fireEvent, render, screen } from '@testing-library/react';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import { createElement } from 'react';
+
+vi.mock('react-i18next', () => ({
+ useTranslation: () => ({ t: (key: string) => key }),
+ initReactI18next: { type: '3rdParty', init: () => undefined },
+}));
+
+import { ErrorMessageCard } from '@/components/chat/ErrorMessageCard';
+import { UPSTREAM_STREAM_INTERRUPTED_REASON } from '@/utils/streamInterruptError';
+
+const STREAM_RAW =
+ 'OpenAI API error (500): {"message":"litellm.APIError: Response API in-stream error","type":null,"param":null,"code":"500"}';
+
+afterEach(cleanup);
+
+describe('ErrorMessageCard', () => {
+ it('shows friendly stream-interrupt copy plus a raw-error expander', () => {
+ render(
+ createElement(ErrorMessageCard, {
+ message: STREAM_RAW,
+ reason: UPSTREAM_STREAM_INTERRUPTED_REASON,
+ }),
+ );
+
+ expect(screen.getByText('chat.errorBanner.streamInterruptedNoRetry')).toBeTruthy();
+ expect(screen.queryByText(STREAM_RAW)).toBeNull();
+ fireEvent.click(screen.getByText('chat.errorBanner.networkShowRaw'));
+ expect(screen.getByText(STREAM_RAW)).toBeTruthy();
+ });
+
+ it('keeps genuine OpenAI errors as-is without an expander', () => {
+ const raw = 'OpenAI API error (400): invalid_prompt';
+ render(createElement(ErrorMessageCard, { message: raw }));
+ expect(screen.getByText(raw)).toBeTruthy();
+ expect(screen.queryByText('chat.errorBanner.networkShowRaw')).toBeNull();
+ });
+
+ it('unwraps LiteLLM envelopes and still offers the original', () => {
+ const raw =
+ 'OpenAI API error (400): {"message":"litellm.BadRequestError: XaiException - too long"}';
+ render(createElement(ErrorMessageCard, { message: raw }));
+ expect(screen.getByText('XaiException - too long')).toBeTruthy();
+ expect(screen.queryByText(raw)).toBeNull();
+ fireEvent.click(screen.getByText('chat.errorBanner.networkShowRaw'));
+ expect(screen.getByText(raw)).toBeTruthy();
+ });
+});
diff --git a/apps/desktop/src/renderer/components/chat/errorReasonI18n.ts b/apps/desktop/src/renderer/components/chat/errorReasonI18n.ts
index 90a3ba6bdf..48b881b9eb 100644
--- a/apps/desktop/src/renderer/components/chat/errorReasonI18n.ts
+++ b/apps/desktop/src/renderer/components/chat/errorReasonI18n.ts
@@ -3,6 +3,7 @@ import {
CLAUDE_SUBSCRIPTION_OPUS_PLAN_MISMATCH_REASON,
} from '../../../shared/claudeGatewayError';
import { UPSTREAM_OVERLOAD_REASON } from '@/utils/overloadError';
+import { UPSTREAM_STREAM_INTERRUPTED_REASON } from '@/utils/streamInterruptError';
/**
* Stable maker-core error reason -> renderer i18n key.
@@ -30,6 +31,7 @@ export const ERROR_REASON_I18N_KEYS: Record<string, string> = {
turn_no_event_timeout: 'logic.errors.turnNoEventTimeout',
'context-overflow': 'chat.errorBanner.contextOverflow',
[UPSTREAM_OVERLOAD_REASON]: 'chat.errorBanner.overloadBusyNoRetry',
+ [UPSTREAM_STREAM_INTERRUPTED_REASON]: 'chat.errorBanner.streamInterruptedNoRetry',
[CLAUDE_GATEWAY_OPUS_PLAN_MISMATCH_REASON]: 'chat.errorBanner.claudeGatewayOpusPlanMismatch',
[CLAUDE_SUBSCRIPTION_OPUS_PLAN_MISMATCH_REASON]:
'chat.errorBanner.claudeSubscriptionOpusPlanMismatch',
diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.json
index 462894ad40..7ea7db2cd6 100644
--- a/apps/desktop/src/renderer/i18n/locales/en/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json
@@ -6982,6 +6982,8 @@
"rateLimitRetrying": "Request rate limited — retrying automatically ({{attempt}}/{{maxAttempts}})…",
"overloadBusy": "The model service is busy — the upstream has no capacity right now. Click \"Retry\", or switch to another model.",
"overloadBusyNoRetry": "The model service is busy — the upstream has no capacity right now. Try again later, or switch to another model.",
+ "streamInterrupted": "The model stream was interrupted. This is usually a temporary upstream issue — click Retry.",
+ "streamInterruptedNoRetry": "The model stream was interrupted. This is usually a temporary upstream issue. Try again in a little while.",
"networkShowRaw": "Show raw error",
"networkHideRaw": "Hide raw error",
"silentStopContinue": "Continue",
diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.json
index 04e3e518af..191551ce88 100644
--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json
@@ -6979,6 +6979,8 @@
"rateLimitRetrying": "リクエストがレート制限されました。自動的に再試行しています({{attempt}}/{{maxAttempts}})…",
"overloadBusy": "モデルサービスが混雑しています。上流に空き容量がありません。「再試行」を押すか、別のモデルに切り替えてください",
"overloadBusyNoRetry": "モデルサービスが混雑しています。上流に空き容量がありません。しばらくしてから再試行するか、別のモデルに切り替えてください",
+ "streamInterrupted": "モデル出力が途中で中断されました。一時的な上流障害であることが多いので、「再試行」を押してください",
+ "streamInterruptedNoRetry": "モデル出力が途中で中断されました。一時的な上流障害であることが多いので、しばらくしてから再試行してください",
"networkShowRaw": "元のエラーを表示",
"networkHideRaw": "元のエラーを隠す",
"silentStopContinue": "続行",
diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.json
index a829df0f5f..e5bda4178d 100644
--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json
@@ -6979,6 +6979,8 @@
"rateLimitRetrying": "요청이 속도 제한에 걸렸습니다. 자동으로 다시 시도하는 중({{attempt}}/{{maxAttempts}})…",
"overloadBusy": "모델 서비스가 혼잡합니다. 상위 서비스에 여유 용량이 없습니다. \"재시도\"를 누르거나 다른 모델로 바꿔 보세요",
"overloadBusyNoRetry": "모델 서비스가 혼잡합니다. 상위 서비스에 여유 용량이 없습니다. 잠시 후 다시 시도하거나 다른 모델로 바꿔 보세요",
+ "streamInterrupted": "모델 출력이 중간에 중단되었습니다. 보통은 일시적인 상위 서비스 장애입니다. \"재시도\"를 눌러 주세요",
+ "streamInterruptedNoRetry": "모델 출력이 중간에 중단되었습니다. 보통은 일시적인 상위 서비스 장애입니다. 잠시 후 다시 시도해 주세요",
"networkShowRaw": "원본 오류 보기",
"networkHideRaw": "원본 오류 숨기기",
"silentStopContinue": "계속",
diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
index c282f24e35..bd389b2f41 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
@@ -6979,6 +6979,8 @@
"rateLimitRetrying": "请求受到限流,正在自动重试({{attempt}}/{{maxAttempts}})…",
"overloadBusy": "模型服务繁忙,上游暂时没有可用容量。可点击「重试」,或换一个模型。",
"overloadBusyNoRetry": "模型服务繁忙,上游暂时没有可用容量。可稍后重试,或换一个模型。",
+ "streamInterrupted": "模型输出中途中断了。通常是上游暂时故障,可点击「重试」。",
+ "streamInterruptedNoRetry": "模型输出中途中断了。通常是上游暂时故障,请稍后重试。",
"networkShowRaw": "查看原始错误",
"networkHideRaw": "收起原始错误",
"silentStopContinue": "继续",
diff --git a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
index b4a9ea2483..3ac43858f7 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
@@ -6978,6 +6978,8 @@
"rateLimitRetrying": "請求受到限流,正在自動重試({{attempt}}/{{maxAttempts}})…",
"overloadBusy": "模型服務繁忙,上游暫時沒有可用容量。可點選「重試」,或換一個模型。",
"overloadBusyNoRetry": "模型服務繁忙,上游暫時沒有可用容量。可稍後重試,或換一個模型。",
+ "streamInterrupted": "模型輸出中途中斷了。通常是上游暫時故障,可點選「重試」。",
+ "streamInterruptedNoRetry": "模型輸出中途中斷了。通常是上游暫時故障,請稍後重試。",
"networkShowRaw": "檢視原始錯誤",
"networkHideRaw": "收起原始錯誤",
"silentStopContinue": "繼續",
diff --git a/apps/desktop/src/renderer/utils/streamInterruptError.ts b/apps/desktop/src/renderer/utils/streamInterruptError.ts
new file mode 100644
index 0000000000..df7677ff24
--- /dev/null
+++ b/apps/desktop/src/renderer/utils/streamInterruptError.ts
@@ -0,0 +1,63 @@
+/**
+ * 流式输出中途被掐断(renderer 侧)。ErrorBanner 用它把
+ * `OpenAI API error (500): … Response API in-stream error` 换成友好文案,
+ * 原文折叠可查。不跨 bundle 共享 maker-core 代码,与 overload / network 同款惯例。
+ */
+
+export const UPSTREAM_STREAM_INTERRUPTED_REASON = 'upstream-stream-interrupted';
+
+const STREAM_INTERRUPTED_RE = /Response API in-stream error/i;
+
+export function isStreamInterruptedErrorMessage(
+ message: string,
+ reason?: string | null,
+): boolean {
+ if (reason === UPSTREAM_STREAM_INTERRUPTED_REASON) return true;
+ return STREAM_INTERRUPTED_RE.test(message);
+}
+
+const OPENAI_API_ERROR_PREFIX = /^(?:Azure )?OpenAI API error \(\d+\):\s*/i;
+const LITELLM_ERROR_PREFIX = /^litellm\.\w+Error:\s*/;
+
+function isLiteLlmEnvelope(text: string): boolean {
+ return /litellm\./i.test(text) || LITELLM_ERROR_PREFIX.test(text);
+}
+
+function unwrapLiteLlmInner(text: string): string {
+ const stripped = text.replace(LITELLM_ERROR_PREFIX, '').trim();
+ return stripped.length > 0 ? stripped : text;
+}
+
+/**
+ * 兜底展示时剥掉 **LiteLLM 套在 OpenAI Responses 客户端上的协议外壳**。
+ * Pi 的 Responses 客户端不分厂商,一律写成 `OpenAI API error`;LiteLLM 再套 JSON。
+ * 真 OpenAI / Azure OpenAI 错误保留前缀与状态码。只改展示,不改落盘。
+ */
+export function unwrapProviderErrorDisplay(message: string): string {
+ const text = message.trim();
+ const prefixMatch = text.match(OPENAI_API_ERROR_PREFIX);
+ if (!prefixMatch) return text.length > 0 ? text : message;
+
+ const rest = text.slice(prefixMatch[0].length).trim();
+ if (rest.startsWith('{')) {
+ try {
+ const parsed: unknown = JSON.parse(rest);
+ if (
+ parsed &&
+ typeof parsed === 'object' &&
+ 'message' in parsed &&
+ typeof (parsed as { message: unknown }).message === 'string'
+ ) {
+ const inner = (parsed as { message: string }).message.trim();
+ if (inner.length > 0 && isLiteLlmEnvelope(inner)) {
+ return unwrapLiteLlmInner(inner);
+ }
+ }
+ } catch {
+ // 不是 JSON 就落到下面的 litellm.XxxError 直配。
+ }
+ }
+
+ if (isLiteLlmEnvelope(rest)) return unwrapLiteLlmInner(rest);
+ return message;
+}
diff --git a/packages/maker-core/src/agents/index.ts b/packages/maker-core/src/agents/index.ts
index b307b0b4ce..4731e8e3f9 100644
--- a/packages/maker-core/src/agents/index.ts
+++ b/packages/maker-core/src/agents/index.ts
@@ -65,6 +65,11 @@ export {
CONTEXT_OVERFLOW_REASON,
isContextOverflowErrorMessage,
} from './shared/context-overflow-error.js';
+// ErrorBanner 用人话替换 LiteLLM / Responses 空壳流中断,不驱动自动续跑。
+export {
+ UPSTREAM_STREAM_INTERRUPTED_REASON,
+ isStreamInterruptedErrorMessage,
+} from './shared/stream-interrupt-error.js';
// 同上理由(同 bundle 直接复用,不造第三份):desktop 的中断自愈判据要认「网络到不了
// 上游」这一类 —— 那类同样是"连不上"而不是"请求有问题",续跑一次就能过去。
export { isNetworkishErrorMessage } from './shared/network-error.js';
diff --git a/packages/maker-core/src/agents/pi/__tests__/pi-translator.test.ts b/packages/maker-core/src/agents/pi/__tests__/pi-translator.test.ts
index 67f129602c..0fba48762c 100644
--- a/packages/maker-core/src/agents/pi/__tests__/pi-translator.test.ts
+++ b/packages/maker-core/src/agents/pi/__tests__/pi-translator.test.ts
@@ -381,6 +381,59 @@ describe('pi translator', () => {
]);
});
+ it('classifies LiteLLM Response API in-stream errors without auto-retry markers', () => {
+ const ctx = createPiTranslateContext(noopLogger);
+ const { queue, events } = makeQueue();
+ const rawError =
+ 'OpenAI API error (500): {"message":"litellm.APIError: Response API in-stream error","type":null,"param":null,"code":"500"}';
+
+ translatePiEvent(ev({ type: 'agent_start' }), queue, ctx);
+ translatePiEvent(
+ ev({
+ type: 'message_end',
+ message: {
+ role: 'assistant',
+ content: [],
+ stopReason: 'error',
+ errorMessage: rawError,
+ },
+ }),
+ queue,
+ ctx,
+ );
+ translatePiEvent(ev({ type: 'agent_settled' }), queue, ctx);
+
+ const errors = events.filter((event) => event.type === 'error');
+ expect(errors).toEqual([
+ expect.objectContaining({
+ source: 'pi',
+ data: expect.objectContaining({
+ message: rawError,
+ isTerminal: true,
+ reason: 'upstream-stream-interrupted',
+ }),
+ }),
+ ]);
+ });
+
+ it('keeps LiteLLM in-stream auto-retries silent instead of reusing the overload marker', () => {
+ const ctx = createPiTranslateContext(noopLogger);
+ const { queue, events } = makeQueue();
+
+ translatePiEvent(
+ ev({
+ type: 'auto_retry_start',
+ attempt: 2,
+ maxAttempts: 3,
+ errorMessage: 'litellm.APIError: Response API in-stream error',
+ }),
+ queue,
+ ctx,
+ );
+
+ expect(events.filter((event) => event.type === 'error')).toHaveLength(0);
+ });
+
it('keeps unclassified Pi auto-retries silent instead of reusing the overload marker', () => {
const ctx = createPiTranslateContext(noopLogger);
const { queue, events } = makeQueue();
diff --git a/packages/maker-core/src/agents/pi/translator.ts b/packages/maker-core/src/agents/pi/translator.ts
index 7ba4440d48..c84c1afa36 100644
--- a/packages/maker-core/src/agents/pi/translator.ts
+++ b/packages/maker-core/src/agents/pi/translator.ts
@@ -38,6 +38,10 @@ import {
CONTEXT_OVERFLOW_REASON,
isContextOverflowErrorMessage,
} from '../shared/context-overflow-error.js';
+import {
+ UPSTREAM_STREAM_INTERRUPTED_REASON,
+ isStreamInterruptedErrorMessage,
+} from '../shared/stream-interrupt-error.js';
import type { PiRpcEvent } from './rpc-client.js';
import { parsePiSubagentProgress, type PiSubagentUsage } from './subagent-progress.js';
@@ -67,7 +71,7 @@ interface PiPendingAssistantError {
sdkError: string;
errorStatus?: 401 | 429 | 529;
usageLimit?: true;
- reason?: typeof CONTEXT_OVERFLOW_REASON;
+ reason?: typeof CONTEXT_OVERFLOW_REASON | typeof UPSTREAM_STREAM_INTERRUPTED_REASON;
}
interface PiThinkingBlock {
@@ -346,7 +350,9 @@ function piAssistantErrorOf(rawError: string): PiPendingAssistantError {
...(signals.usageLimit ? { usageLimit: true } : {}),
...(isContextOverflowErrorMessage(redactedError)
? { reason: CONTEXT_OVERFLOW_REASON }
- : {}),
+ : isStreamInterruptedErrorMessage(redactedError)
+ ? { reason: UPSTREAM_STREAM_INTERRUPTED_REASON }
+ : {}),
};
}
diff --git a/packages/maker-core/src/agents/shared/stream-interrupt-error.test.ts b/packages/maker-core/src/agents/shared/stream-interrupt-error.test.ts
new file mode 100644
index 0000000000..833510ee62
--- /dev/null
+++ b/packages/maker-core/src/agents/shared/stream-interrupt-error.test.ts
@@ -0,0 +1,28 @@
+import { describe, expect, it } from 'vitest';
+
+import { isStreamInterruptedErrorMessage } from './stream-interrupt-error.js';
+
+describe('isStreamInterruptedErrorMessage', () => {
+ it('matches the observed Pi + LiteLLM envelope', () => {
+ expect(
+ isStreamInterruptedErrorMessage(
+ 'OpenAI API error (500): {"message":"litellm.APIError: Response API in-stream error","type":null,"param":null,"code":"500"}',
+ ),
+ ).toBe(true);
+ expect(
+ isStreamInterruptedErrorMessage('litellm.APIError: Response API in-stream error'),
+ ).toBe(true);
+ });
+
+ it('does not treat ordinary 5xx / overload / overflow as a stream interrupt', () => {
+ expect(isStreamInterruptedErrorMessage('provider 500 from upstream')).toBe(false);
+ expect(isStreamInterruptedErrorMessage('HTTP status 529: overloaded')).toBe(false);
+ expect(
+ isStreamInterruptedErrorMessage(
+ "This model's maximum prompt length is 500000 but the request contains 978177 tokens.",
+ ),
+ ).toBe(false);
+ expect(isStreamInterruptedErrorMessage('OpenAI API error (400): invalid_prompt')).toBe(false);
+ expect(isStreamInterruptedErrorMessage('')).toBe(false);
+ });
+});
diff --git a/packages/maker-core/src/agents/shared/stream-interrupt-error.ts b/packages/maker-core/src/agents/shared/stream-interrupt-error.ts
new file mode 100644
index 0000000000..b0d63b6ef5
--- /dev/null
+++ b/packages/maker-core/src/agents/shared/stream-interrupt-error.ts
@@ -0,0 +1,24 @@
+/**
+ * 流式输出中途被掐断 —— LiteLLM / OpenAI Responses 前门把空壳
+ * `error` / `response.failed` 事件填成 `Response API in-stream error`。
+ *
+ * **只负责识别与展示**,不驱动自动续跑。过载 / 网络类才走自动重试;
+ * 这族错误在大上下文的 Grok 上常常连打几次仍失败,换模型才是逃生口。
+ *
+ * 消费方:
+ * - pi translator:终态 error 附带 `UPSTREAM_STREAM_INTERRUPTED_REASON`;
+ * - renderer ErrorBanner / ErrorMessageCard:人话替换 `OpenAI API error` 外壳。
+ */
+
+export const UPSTREAM_STREAM_INTERRUPTED_REASON = 'upstream-stream-interrupted';
+
+/**
+ * LiteLLM 在 Responses 流里收到没有 message 的 error 事件时写死的 fallback。
+ * 这句足够独特,不认裸 `500` / 裸 `API error`。
+ */
+const STREAM_INTERRUPTED_RE = /Response API in-stream error/i;
+
+/** 是否是 Responses / LiteLLM 流中途被掐的空壳错误。 */
+export function isStreamInterruptedErrorMessage(message: string): boolean {
+ return STREAM_INTERRUPTED_RE.test(message);
+}