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 网关 401 改为友好文案并重新获取凭据 (#3282)

Dash3b9b82e421ef
diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.ts
index 84859bf1af..fd982d1e77 100644
--- a/apps/desktop/src/main/maker-ipc/register.ts
+++ b/apps/desktop/src/main/maker-ipc/register.ts
@@ -37,7 +37,12 @@ import type {
} from '@cindy/maker-core';
import { storedCustomProviderId } from '@cindy/model-providers';
import { createId } from '@paralleldrive/cuid2';
-import { redactSensitiveText } from '@cindy/maker-shared/error-redaction';
+import {
+ GATEWAY_PROXY_TOKEN_INVALID_REASON,
+ isCindyGatewayProviderId,
+ isGatewayProxyTokenInvalidError,
+ redactSensitiveText,
+} from '@cindy/maker-shared/error-redaction';
import { permissionModeOrAsk } from '@cindy/maker-shared/permission-mode';
import {
isProductTurnCompletionTailEvent,
@@ -3075,7 +3080,10 @@ function handleAgentIslandEventAfterBroadcast(
const service = getAgentIslandService();
if (!service) return;
const meta = sessionMetaForIsland(session);
- if (isRemoteAuthRetryErrorEvent(session, event)) {
+ if (
+ isRemoteAuthRetryErrorEvent(session, event) ||
+ isGatewayProxyTokenRecoveryErrorEvent(session.id, event)
+ ) {
service.deferRemoteAuthRetryError(meta, event);
return;
}
@@ -3149,6 +3157,16 @@ function isRemoteAuthRetryErrorEvent(
);
}
+function isGatewayProxyTokenRecoveryErrorEvent(sessionId: string, event: AgentEvent): boolean {
+ if (event.type !== 'error' || !isTerminalTurnErrorEvent(event)) return false;
+ const data = event.data as { message?: unknown; reason?: unknown } | undefined;
+ return (
+ isCindyGatewayProviderId(getSessionProvider(sessionId)) &&
+ (data?.reason === GATEWAY_PROXY_TOKEN_INVALID_REASON ||
+ isGatewayProxyTokenInvalidError(typeof data?.message === 'string' ? data.message : ''))
+ );
+}
+
function handleAgentIslandInteractionAfterBroadcast(
session: { id: string; agentKind?: unknown; workDir?: unknown; workspaceKind?: unknown },
request: InteractionRequest,
@@ -4042,6 +4060,7 @@ export function wireSessionToIpc(session: ReturnType<Maker['getSession']>): void
// 提前声明在终止型 error 块与 done/terminal 边界块两处均需使用的持久化条件标志。
let isPlannedUpgradeClose = false;
let isRemoteAuthRetry = false;
+ let isGatewayProxyTokenRecovery = false;
if (isTerminalTurnErrorEvent(event)) {
finalizeTurnChangeSet(session.id, null, 'partial');
// **任何**终态失败都先把上一条重连记录钉成失败 —— 不管这次错误本身是否值得自愈。
@@ -4081,6 +4100,7 @@ export function wireSessionToIpc(session: ReturnType<Maker['getSession']>): void
// sdkError === 'authentication_failed' 以及 message 命中 authentication_error /
// invalid api key / 401 的情形。本地会话(无 remoteHostId)无 auto-retry,不跳过。
isRemoteAuthRetry = isRemoteAuthRetryErrorEvent(session, event);
+ isGatewayProxyTokenRecovery = isGatewayProxyTokenRecoveryErrorEvent(session.id, event);
if (!isPlannedUpgradeClose) {
agentInputCoordinatorHolder?.onTurnEvent(
session.id,
@@ -4367,6 +4387,7 @@ export function wireSessionToIpc(session: ReturnType<Maker['getSession']>): void
isTerminalTurnErrorEvent(event) &&
!isPlannedUpgradeClose &&
!isRemoteAuthRetry &&
+ !isGatewayProxyTokenRecovery &&
!autoResumeSuppressesPersist &&
isContextOverflowErrorData(attributedEvent.data)
? (contextOverflowRolloverHolder?.claim(session.id) ?? 'idle')
@@ -4412,6 +4433,7 @@ export function wireSessionToIpc(session: ReturnType<Maker['getSession']>): void
event.type === 'error' &&
!isPlannedUpgradeClose &&
!isRemoteAuthRetry &&
+ !isGatewayProxyTokenRecovery &&
!autoResumeSuppressesPersist
) {
onTurnErrorEvent(
@@ -4443,7 +4465,10 @@ export function wireSessionToIpc(session: ReturnType<Maker['getSession']>): void
// _turnStartedAtBySession 之前保存一份,让 deferred 路径能正确做 /clear 竞态 cap。
// 自愈压住 error 行时同理:补落发生在 resetTurnPersistState 之后(退避 3–20 秒,
// 或决策推迟的那一小段),不先存一份会让 /clear 竞态 cap 判错。
- if (event.type === 'error' && (isRemoteAuthRetry || autoResumeSuppressesPersist)) {
+ if (
+ event.type === 'error' &&
+ (isRemoteAuthRetry || isGatewayProxyTokenRecovery || autoResumeSuppressesPersist)
+ ) {
saveTurnStartedAtForDeferred(session.id);
}
// turn 收尾打标:本 turn 已知持久化(assistant flush / orphan tool_result /
diff --git a/apps/desktop/src/renderer/__tests__/errorBannerGatewayProxyToken.test.tsx b/apps/desktop/src/renderer/__tests__/errorBannerGatewayProxyToken.test.tsx
new file mode 100644
index 0000000000..48c827d097
--- /dev/null
+++ b/apps/desktop/src/renderer/__tests__/errorBannerGatewayProxyToken.test.tsx
@@ -0,0 +1,130 @@
+// @vitest-environment jsdom
+
+/**
+ * ErrorBanner — LiteLLM 网关 token 失效:
+ * 原文(VerificationTokenTable / Invalid proxy server token)不得直接展示;
+ * 换成可读提示,原文折叠在「查看原始错误」。
+ */
+
+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 }),
+ initReactI18next: { type: '3rdParty', init: () => undefined },
+}));
+
+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 { ErrorMessageCard } from '@/components/chat/ErrorMessageCard';
+
+const LITELLM_401 =
+ 'Failed to authenticate. API Error: 401 Authentication Error, Invalid proxy server token passed. Received API Key = [REDACTED], Key Hash (Token) =[REDACTED] Unable to find token in cache or `LiteLLM_VerificationTokenTable`';
+
+beforeEach(() => {
+ useCodexRuntimeRouteMock.mockReturnValue({ authInjection: 'env-key' });
+});
+
+afterEach(() => {
+ cleanup();
+ vi.clearAllMocks();
+});
+
+describe('ErrorBanner — LiteLLM 网关凭据失效', () => {
+ it('replaces LiteLLM verification-table copy and does not offer Retry', () => {
+ const onRetry = vi.fn();
+ render(
+ createElement(ErrorBanner, {
+ error: LITELLM_401,
+ errorReason: 'gateway-proxy-token-invalid',
+ retryText: 'retry-token',
+ onRetry,
+ agentKind: 'cc',
+ providerId: 'xd',
+ errorSourceProviderId: 'xd',
+ }),
+ );
+
+ expect(screen.getByText('chat.errorBanner.gatewayProxyTokenInvalidNoRetry')).toBeTruthy();
+ expect(screen.queryByText('chat.errorBanner.gatewayProxyTokenInvalid')).toBeNull();
+ expect(screen.queryByText(/LiteLLM_VerificationTokenTable/)).toBeNull();
+ expect(screen.queryByText(/Invalid proxy server token/)).toBeNull();
+ expect(screen.queryByTitle('chat.errorBanner.retryTitle')).toBeNull();
+ expect(onRetry).not.toHaveBeenCalled();
+ });
+
+ it('still classifies by message when reason is missing', () => {
+ render(
+ createElement(ErrorBanner, {
+ error: LITELLM_401,
+ onRetry: vi.fn(),
+ agentKind: 'cc',
+ errorSourceProviderId: 'xd',
+ }),
+ );
+
+ expect(screen.getByText('chat.errorBanner.gatewayProxyTokenInvalidNoRetry')).toBeTruthy();
+ });
+
+ it('keeps a custom LiteLLM provider error as provider-owned raw text', () => {
+ render(
+ createElement(ErrorBanner, {
+ error: LITELLM_401,
+ onRetry: vi.fn(),
+ agentKind: 'cc',
+ providerId: 'custom-litellm',
+ errorSourceProviderId: 'custom-litellm',
+ }),
+ );
+
+ expect(screen.queryByText('chat.errorBanner.gatewayProxyTokenInvalid')).toBeNull();
+ expect(screen.getByText(LITELLM_401)).toBeTruthy();
+ });
+
+ it('folds the original LiteLLM text behind show-raw', () => {
+ render(
+ createElement(ErrorBanner, {
+ error: LITELLM_401,
+ errorReason: 'gateway-proxy-token-invalid',
+ onRetry: vi.fn(),
+ agentKind: 'cc',
+ }),
+ );
+
+ fireEvent.click(screen.getByText('chat.errorBanner.networkShowRaw'));
+ expect(screen.getByText(LITELLM_401)).toBeTruthy();
+ });
+});
+
+describe('ErrorMessageCard — LiteLLM 网关凭据失效', () => {
+ it('uses history copy that does not ask the user to click Retry', () => {
+ render(
+ createElement(ErrorMessageCard, {
+ message: LITELLM_401,
+ reason: 'gateway-proxy-token-invalid',
+ providerId: 'xd',
+ }),
+ );
+
+ expect(screen.getByText('chat.errorBanner.gatewayProxyTokenInvalidNoRetry')).toBeTruthy();
+ expect(screen.queryByText('chat.errorBanner.gatewayProxyTokenInvalid')).toBeNull();
+ expect(screen.queryByText(/LiteLLM_VerificationTokenTable/)).toBeNull();
+ });
+});
diff --git a/apps/desktop/src/renderer/__tests__/fastModeMirrorOnPatched.test.ts b/apps/desktop/src/renderer/__tests__/fastModeMirrorOnPatched.test.ts
index 317d5ebaac..d70762ea7c 100644
--- a/apps/desktop/src/renderer/__tests__/fastModeMirrorOnPatched.test.ts
+++ b/apps/desktop/src/renderer/__tests__/fastModeMirrorOnPatched.test.ts
@@ -5,7 +5,7 @@
* 幂等(值未变 = no-op,不与本机乐观切换打架);patch 不含 fastMode 时不动。
*/
import { describe, it, expect } from 'vitest';
-import { makerChatStore } from '@/lib/makerChatStore';
+import { buildCreateOptsForCurrentSession, makerChatStore } from '@/lib/makerChatStore';
// 模块级 sessions Map 跨用例持久 → 每个用例用唯一 sessionId 隔离。
let n = 0;
@@ -61,6 +61,31 @@ describe('makerChatStore.mirrorSessionFields', () => {
expect(makerChatStore.getSnapshot(s).agentSwitchIntent).toBeNull();
});
+ it('applies the switched provider snapshot so later createOpts do not keep the old source', () => {
+ const s = sid();
+ makerChatStore.mirrorSessionFields(s, { providerId: 'xd' });
+ makerChatStore.noteAgentSwitchIntent(s, 'codex', {
+ model: 'gpt-5.5',
+ providerId: 'openai',
+ });
+ makerChatStore.mirrorSessionFields(s, { agentKind: 'codex' });
+ expect(makerChatStore.getSnapshot(s).sessionProviderId).toBe('openai');
+ expect(makerChatStore.getSnapshot(s).agentSwitchIntent).toBeNull();
+ expect(buildCreateOptsForCurrentSession(s, 'gpt-5.5', 'high', 'default', '/tmp').providerId).toBe(
+ 'openai',
+ );
+ });
+
+ it('mirrors an explicit same-agent provider patch into later createOpts', () => {
+ const s = sid();
+ makerChatStore.mirrorSessionFields(s, { providerId: 'xd' });
+ makerChatStore.mirrorSessionFields(s, { providerId: 'custom-litellm' });
+ expect(makerChatStore.getSnapshot(s).sessionProviderId).toBe('custom-litellm');
+ expect(
+ buildCreateOptsForCurrentSession(s, 'gpt-5.5', 'high', 'default', '/tmp').providerId,
+ ).toBe('custom-litellm');
+ });
+
it('SET_MODEL 取消广播只清展示 intent,不改真实引擎', () => {
const s = sid();
makerChatStore.noteAgentSwitchIntent(s, 'codex', { model: 'gpt-5.5', providerId: null });
diff --git a/apps/desktop/src/renderer/__tests__/makerChatStoreTextDeltaBatching.test.ts b/apps/desktop/src/renderer/__tests__/makerChatStoreTextDeltaBatching.test.ts
index 0b5b47bdee..53c444c9a4 100644
--- a/apps/desktop/src/renderer/__tests__/makerChatStoreTextDeltaBatching.test.ts
+++ b/apps/desktop/src/renderer/__tests__/makerChatStoreTextDeltaBatching.test.ts
@@ -117,6 +117,8 @@ const MODEL = 'gpt-5';
const EFFORT = 'medium';
const PERMISSION_MODE = 'default';
const WORKING_DIR = 'C:\\workspace';
+const LITELLM_INVALID_PROXY_TOKEN =
+ 'Invalid proxy server token passed; Unable to find token in cache or `LiteLLM_VerificationTokenTable`';
function serverMessage(
patch: Omit<Message, 'toolUseId' | 'agentMeta'> &
@@ -201,6 +203,50 @@ function projection(
};
}
+function activeTurnRecoveryItem(
+ text = 'hello gateway',
+ clientId = 'user-client',
+ providerId: string | null | undefined = 'xd',
+): AgentInputQueuedMessage {
+ return {
+ clientId,
+ text,
+ persistedContent: text,
+ model: MODEL,
+ effort: EFFORT,
+ permissionMode: PERMISSION_MODE,
+ workingDir: WORKING_DIR,
+ chatMessage: {
+ clientId,
+ role: 'user',
+ content: text,
+ createdAt: '2026-01-01T00:00:01.000Z',
+ },
+ createOpts: {
+ agentKind: 'claude-code',
+ workingDir: WORKING_DIR,
+ model: MODEL,
+ ...(providerId !== undefined ? { providerId } : {}),
+ effort: EFFORT,
+ permissionMode: PERMISSION_MODE,
+ },
+ };
+}
+
+function emitGatewayProxyTokenFailure(
+ data: Record<string, unknown>,
+ source: 'claude-code' | 'codex' = 'claude-code',
+): void {
+ onEvent?.({
+ sessionId: SESSION_ID,
+ event: { type: 'error', source, data },
+ });
+ onEvent?.({
+ sessionId: SESSION_ID,
+ event: { type: 'done', source, data: { is_error: true } },
+ });
+}
+
function installElectronBridge(): void {
onEvent = undefined;
onStatusChanged = undefined;
@@ -266,6 +312,12 @@ function installElectronBridge(): void {
size: 1,
})),
safeStorageRead: vi.fn(async () => 'local-key'),
+ modelAccess: {
+ retry: vi.fn(async () => ({ state: 'ok', source: 'server', endpoint: 'https://gw.test' })),
+ rotate: vi.fn(),
+ getStatus: vi.fn(),
+ onStatusChange: vi.fn(),
+ },
localDb: {
messages: {
onCreated: (cb: (data: unknown) => void) => {
@@ -2192,6 +2244,301 @@ describe('makerChatStore text delta batching', () => {
);
});
+ it('re-fetches Cindy credentials and resends on LiteLLM invalid proxy token', async () => {
+ vi.mocked(sessionService.get).mockResolvedValue({
+ agentKind: 'claude-code',
+ remoteHostId: null,
+ sdkSessionId: null,
+ fastMode: false,
+ contextTokens: 0,
+ contextWindow: 0,
+ totalCostUsd: 0,
+ workingDir: WORKING_DIR,
+ model: MODEL,
+ effort: EFFORT,
+ permissionMode: PERMISSION_MODE,
+ } as unknown as Awaited<ReturnType<typeof sessionService.get>>);
+ makerChatStore.ensureInitialMessages(SESSION_ID);
+ await flushPromises();
+ emitDbMessageCreated({
+ id: 'user-row',
+ clientId: 'user-client',
+ role: 'user',
+ content: 'hello gateway',
+ createdAt: '2026-01-01T00:00:01.000Z',
+ });
+ onInputProjection?.(
+ projection(SESSION_ID, {
+ error: LITELLM_INVALID_PROXY_TOKEN,
+ recovery: { kind: 'active-turn', item: activeTurnRecoveryItem() },
+ errorRetryText: 'retry:user-client',
+ }),
+ );
+
+ emitGatewayProxyTokenFailure({
+ isTerminal: true,
+ reason: 'gateway-proxy-token-invalid',
+ message: LITELLM_INVALID_PROXY_TOKEN,
+ });
+ await flushPromises();
+
+ expect(window.electronAPI.modelAccess.retry).toHaveBeenCalledOnce();
+ expect(window.electronAPI.modelAccess.rotate).not.toHaveBeenCalled();
+ expect(window.electronAPI.maker.closeSession).toHaveBeenCalledWith(SESSION_ID, {
+ preserveWorkspace: true,
+ });
+ expect(input.retryLastError).toHaveBeenCalledOnce();
+ expect(input.enqueue).not.toHaveBeenCalled();
+ expect(input.persistTurnErrorDeferred).not.toHaveBeenCalled();
+ expect(makerChatStore.getSnapshot(SESSION_ID).error).toBeNull();
+ });
+
+ it('does not retry the same gateway failure root after the failed turn done tail', async () => {
+ onInputProjection?.(
+ projection(SESSION_ID, {
+ error: LITELLM_INVALID_PROXY_TOKEN,
+ recovery: { kind: 'active-turn', item: activeTurnRecoveryItem() },
+ errorRetryText: 'retry:user-client',
+ }),
+ );
+ emitGatewayProxyTokenFailure({
+ isTerminal: true,
+ reason: 'gateway-proxy-token-invalid',
+ message: LITELLM_INVALID_PROXY_TOKEN,
+ });
+ await flushPromises();
+ await flushPromises();
+ expect(window.electronAPI.modelAccess.retry).toHaveBeenCalledOnce();
+
+ const retriedItem = activeTurnRecoveryItem('hello gateway', 'retry-client');
+ retriedItem.supersedesUserClientId = 'user-client';
+ onInputProjection?.(
+ projection(SESSION_ID, {
+ error: LITELLM_INVALID_PROXY_TOKEN,
+ recovery: { kind: 'active-turn', item: retriedItem },
+ errorRetryText: 'retry:retry-client',
+ }),
+ );
+ emitGatewayProxyTokenFailure({
+ isTerminal: true,
+ reason: 'gateway-proxy-token-invalid',
+ message: LITELLM_INVALID_PROXY_TOKEN,
+ });
+ await flushPromises();
+
+ expect(window.electronAPI.modelAccess.retry).toHaveBeenCalledOnce();
+ expect(input.retryLastError).toHaveBeenCalledOnce();
+ expect(input.persistTurnErrorDeferred).toHaveBeenCalledOnce();
+ expect(makerChatStore.getSnapshot(SESSION_ID).error).toContain('LiteLLM_VerificationTokenTable');
+ });
+
+ it('persists the deferred error when Cindy credential re-fetch fails', async () => {
+ vi.mocked(window.electronAPI.modelAccess.retry).mockResolvedValueOnce({
+ state: 'failed',
+ source: null,
+ endpoint: null,
+ errorCode: 'NETWORK_ERROR',
+ });
+ onInputProjection?.(
+ projection(SESSION_ID, {
+ error: LITELLM_INVALID_PROXY_TOKEN,
+ recovery: { kind: 'active-turn', item: activeTurnRecoveryItem() },
+ errorRetryText: 'retry:user-client',
+ }),
+ );
+
+ emitGatewayProxyTokenFailure({
+ isTerminal: true,
+ reason: 'gateway-proxy-token-invalid',
+ message: LITELLM_INVALID_PROXY_TOKEN,
+ });
+ await flushPromises();
+
+ expect(window.electronAPI.modelAccess.retry).toHaveBeenCalledOnce();
+ expect(input.retryLastError).not.toHaveBeenCalled();
+ expect(input.persistTurnErrorDeferred).toHaveBeenCalledOnce();
+ expect(makerChatStore.getSnapshot(SESSION_ID).error).toContain('LiteLLM_VerificationTokenTable');
+ });
+
+ it('does not treat a custom LiteLLM provider token error as Cindy credentials', async () => {
+ onInputProjection?.(
+ projection(SESSION_ID, {
+ error: LITELLM_INVALID_PROXY_TOKEN,
+ recovery: {
+ kind: 'active-turn',
+ item: activeTurnRecoveryItem('hello custom gateway', 'custom-client', 'custom-litellm'),
+ },
+ errorRetryText: 'retry:custom-client',
+ }),
+ );
+
+ onEvent?.({
+ sessionId: SESSION_ID,
+ event: {
+ type: 'error',
+ source: 'claude-code',
+ data: { isTerminal: true, message: LITELLM_INVALID_PROXY_TOKEN },
+ },
+ });
+ await flushPromises();
+
+ expect(window.electronAPI.modelAccess.retry).not.toHaveBeenCalled();
+ expect(input.retryLastError).not.toHaveBeenCalled();
+ expect(input.persistTurnErrorDeferred).not.toHaveBeenCalled();
+ expect(makerChatStore.getSnapshot(SESSION_ID).error).toContain('LiteLLM_VerificationTokenTable');
+ });
+
+ it('does not guess Cindy credentials when queued createOpts omitted providerId', async () => {
+ vi.mocked(sessionService.get).mockResolvedValue({
+ agentKind: 'claude-code',
+ remoteHostId: null,
+ providerId: 'custom-litellm',
+ sdkSessionId: null,
+ fastMode: false,
+ contextTokens: 0,
+ contextWindow: 0,
+ totalCostUsd: 0,
+ workingDir: WORKING_DIR,
+ model: MODEL,
+ effort: EFFORT,
+ permissionMode: PERMISSION_MODE,
+ } as unknown as Awaited<ReturnType<typeof sessionService.get>>);
+ const omittedProviderItem = activeTurnRecoveryItem('hello omitted provider', 'omit-client');
+ delete omittedProviderItem.createOpts.providerId;
+ onInputProjection?.(
+ projection(SESSION_ID, {
+ error: LITELLM_INVALID_PROXY_TOKEN,
+ recovery: {
+ kind: 'active-turn',
+ item: omittedProviderItem,
+ },
+ errorRetryText: 'retry:omit-client',
+ }),
+ );
+
+ emitGatewayProxyTokenFailure({
+ isTerminal: true,
+ message: LITELLM_INVALID_PROXY_TOKEN,
+ });
+ await flushPromises();
+
+ expect(window.electronAPI.modelAccess.retry).not.toHaveBeenCalled();
+ expect(input.retryLastError).not.toHaveBeenCalled();
+ expect(input.persistTurnErrorDeferred).toHaveBeenCalledOnce();
+ expect(makerChatStore.getSnapshot(SESSION_ID).error).toContain('LiteLLM_VerificationTokenTable');
+ });
+
+ it('waits for the failed turn done before refreshing Cindy credentials', async () => {
+ onInputProjection?.(
+ projection(SESSION_ID, {
+ error: LITELLM_INVALID_PROXY_TOKEN,
+ recovery: { kind: 'active-turn', item: activeTurnRecoveryItem() },
+ errorRetryText: 'retry:user-client',
+ }),
+ );
+
+ onEvent?.({
+ sessionId: SESSION_ID,
+ event: {
+ type: 'error',
+ source: 'codex',
+ data: {
+ isTerminal: true,
+ reason: 'gateway-proxy-token-invalid',
+ message: LITELLM_INVALID_PROXY_TOKEN,
+ },
+ },
+ });
+ await flushPromises();
+ expect(window.electronAPI.modelAccess.retry).not.toHaveBeenCalled();
+
+ onEvent?.({
+ sessionId: SESSION_ID,
+ event: { type: 'done', source: 'codex', data: { is_error: true } },
+ });
+ await flushPromises();
+
+ expect(window.electronAPI.modelAccess.retry).toHaveBeenCalledOnce();
+ expect(input.retryLastError).toHaveBeenCalledOnce();
+ });
+
+ it('fails closed instead of guessing a retry target when active-turn recovery is missing', async () => {
+ onEvent?.({
+ sessionId: SESSION_ID,
+ event: {
+ type: 'error',
+ source: 'claude-code',
+ data: {
+ isTerminal: true,
+ reason: 'gateway-proxy-token-invalid',
+ message: LITELLM_INVALID_PROXY_TOKEN,
+ },
+ },
+ });
+ await flushPromises();
+
+ expect(window.electronAPI.modelAccess.retry).not.toHaveBeenCalled();
+ expect(input.retryLastError).not.toHaveBeenCalled();
+ expect(input.persistTurnErrorDeferred).toHaveBeenCalledWith(
+ SESSION_ID,
+ expect.objectContaining({ reason: 'gateway-proxy-token-invalid' }),
+ null,
+ );
+ expect(makerChatStore.getSnapshot(SESSION_ID).error).toContain('LiteLLM_VerificationTokenTable');
+ });
+
+ it('does not refresh local credentials for a device-link forwarded gateway error', async () => {
+ remoteProjectsStore.pinSessionOrigin('device-1', SESSION_ID);
+ onRemotePush?.({
+ deviceId: 'device-1',
+ channel: 'maker:input:projection',
+ payload: projection(SESSION_ID, {
+ error: LITELLM_INVALID_PROXY_TOKEN,
+ recovery: { kind: 'active-turn', item: activeTurnRecoveryItem() },
+ errorRetryText: 'retry:user-client',
+ }),
+ });
+ onRemotePush?.({
+ deviceId: 'device-1',
+ channel: 'maker:event',
+ payload: {
+ sessionId: SESSION_ID,
+ event: {
+ type: 'error',
+ source: 'claude-code',
+ data: {
+ isTerminal: true,
+ reason: 'gateway-proxy-token-invalid',
+ message: LITELLM_INVALID_PROXY_TOKEN,
+ },
+ },
+ },
+ });
+ await flushPromises();
+
+ expect(window.electronAPI.modelAccess.retry).not.toHaveBeenCalled();
+ expect(input.retryLastError).not.toHaveBeenCalled();
+ expect(input.persistTurnErrorDeferred).not.toHaveBeenCalled();
+ });
+
+ it('does not re-fetch credentials for a generic 401', async () => {
+ onEvent?.({
+ sessionId: SESSION_ID,
+ event: {
+ type: 'error',
+ source: 'claude-code',
+ data: { isTerminal: true, errorStatus: 401, message: 'Authorization: [REDACTED]' },
+ },
+ });
+ await flushPromises();
+
+ expect(window.electronAPI.modelAccess.retry).not.toHaveBeenCalled();
+ expect(window.electronAPI.modelAccess.rotate).not.toHaveBeenCalled();
+ expect(makerChatStore.getSnapshot(SESSION_ID).error).toBe(
+ 'Authorization: [REDACTED] (HTTP 401)',
+ );
+ });
+
it('does not run the legacy remote auth retry path for Codex auth errors', async () => {
vi.mocked(sessionService.get).mockResolvedValue({
agentKind: 'codex',
diff --git a/apps/desktop/src/renderer/components/chat/ErrorBanner.tsx b/apps/desktop/src/renderer/components/chat/ErrorBanner.tsx
index a1465450fa..ab9c02900c 100644
--- a/apps/desktop/src/renderer/components/chat/ErrorBanner.tsx
+++ b/apps/desktop/src/renderer/components/chat/ErrorBanner.tsx
@@ -14,6 +14,7 @@
import { useEffect, useState } from 'react';
import { isCodexResumeNotReadyProjectionError } from '@cindy/maker-shared/agent-input-projection';
+import { isCindyGatewayProxyTokenInvalidError } from '@cindy/maker-shared/error-redaction';
import {
AlertCircle,
Check,
@@ -183,9 +184,9 @@ export function ErrorBanner({
// - isCodexAuthMissing: codex session + 401/Missing bearer pattern。
// - isCodexRemoteAuthMissing: 远端 codex + 上面命中 → 显「同步登录态」按钮。
// - isCodexLocalOAuthAuthMissing: 本地 codex + oauth-bearer spawn(走订阅) + 401 → hide
- // Retry + 引导 user codex login。**env-key spawn(走网关)不命中**: 网关 401 通常是 gateway
- // key 过期 / rate-limit / proxy 故障, makerChatStore 已经在 401 时自动 refresh
- // gateway key, retry 即可恢复; 强行 hide Retry + 显 "codex login" 反而误导。
+ // Retry + 引导 user codex login。**env-key spawn(走网关)不命中**: LiteLLM 网关 token
+ // 失效由 makerChatStore 重新拉取 model-access 凭据后自动重试; 强行 hide Retry +
+ // 显 "codex login" 反而误导。
// 父组件 (CCAgentSessionView) 必须只对 codex session 传 agentKind='codex' +
// remoteHostId; Claude session 的 401 走默认 retry 流程不应被吞。
// xAI / 自定义来源的真实凭证由 provider-oauth proxy 注入;显式 providerId 是权威来源,
@@ -295,11 +296,17 @@ export function ErrorBanner({
const isClaudeGatewayOpusPlanMismatch = errorReason === CLAUDE_GATEWAY_OPUS_PLAN_MISMATCH_REASON;
const isClaudeSubscriptionOpusPlanMismatch =
errorReason === CLAUDE_SUBSCRIPTION_OPUS_PLAN_MISMATCH_REASON;
+ const isGatewayProxyTokenInvalid = isCindyGatewayProxyTokenInvalidError({
+ reason: errorReason,
+ message: error,
+ providerId: errorSourceProviderId?.trim() || providerId?.trim() || null,
+ });
// 订阅套餐错误保留 Retry:用户重新连接 Anthropic 后可从当前错误卡片重试;
// Gateway 错误则隐藏 Retry,改走切换到 Claude.ai 的明确恢复动作。
const hideRetry =
isSilentStopExhausted ||
isClaudeGatewayOpusPlanMismatch ||
+ isGatewayProxyTokenInvalid ||
isCodexThreadStale ||
showInvalidEncryptedContentRecovery ||
(isCodexRemoteAuthMissing && !syncedSinceError) ||
@@ -348,6 +355,8 @@ export function ErrorBanner({
displayError = t('chat.errorBanner.claudeGatewayOpusPlanMismatch');
} else if (isClaudeSubscriptionOpusPlanMismatch) {
displayError = t('chat.errorBanner.claudeSubscriptionOpusPlanMismatch');
+ } else if (isGatewayProxyTokenInvalid) {
+ displayError = t('chat.errorBanner.gatewayProxyTokenInvalidNoRetry');
} else if (isGatewayQuotaExhausted) {
// 「配额或余额不足,请检查供应商账户」对网关用户是半句话:账户就在 Cindy 里,
// 该说的是「去充值」而不是「去检查」。右端的内联出口负责「去哪充」。
@@ -575,7 +584,8 @@ export function ErrorBanner({
isCodexUsageLimitError ||
terminalRateLimitRetryProgress ||
isClaudeGatewayOpusPlanMismatch ||
- isClaudeSubscriptionOpusPlanMismatch) && (
+ isClaudeSubscriptionOpusPlanMismatch ||
+ isGatewayProxyTokenInvalid) && (
// 网络类与过载类的原始错误折叠可查:友好文案替换了原文,但排障(端口/URL/
// errno/上游原话)仍需要原文,点击展开。新增控件走 --error-fg token(规则 16;
// 本组件其余 red-600/400 为历史存量,error 属语义豁免色但新代码仍走 token)。
diff --git a/apps/desktop/src/renderer/components/chat/ErrorMessageCard.tsx b/apps/desktop/src/renderer/components/chat/ErrorMessageCard.tsx
index ca3b92fdfe..3aab896c33 100644
--- a/apps/desktop/src/renderer/components/chat/ErrorMessageCard.tsx
+++ b/apps/desktop/src/renderer/components/chat/ErrorMessageCard.tsx
@@ -20,6 +20,7 @@
import { useEffect, useState } from 'react';
import { AlertCircle } from 'lucide-react';
import { useTranslation } from 'react-i18next';
+import { isCindyGatewayProxyTokenInvalidError } from '@cindy/maker-shared/error-redaction';
import {
isStreamInterruptedErrorMessage,
unwrapProviderErrorDisplay,
@@ -27,19 +28,37 @@ import {
import { decodeRemoteErrorMessage } from '../../lib/makerChatStore';
import { ERROR_REASON_I18N_KEYS } from './errorReasonI18n';
-export function ErrorMessageCard({ message, reason }: { message: string; reason?: string }) {
+export function ErrorMessageCard({
+ message,
+ reason,
+ providerId,
+}: {
+ message: string;
+ reason?: string;
+ providerId?: string;
+}) {
const { t } = useTranslation();
const [showRaw, setShowRaw] = useState(false);
const decoded = decodeRemoteErrorMessage(message);
const i18nKey = reason ? ERROR_REASON_I18N_KEYS[reason] : undefined;
const isStreamInterrupted = isStreamInterruptedErrorMessage(message, reason);
+ const isGatewayProxyTokenInvalid = isCindyGatewayProxyTokenInvalidError({
+ reason,
+ message: decoded,
+ providerId: providerId ?? null,
+ });
const unwrapped = unwrapProviderErrorDisplay(decoded);
const text = isStreamInterrupted
? t('chat.errorBanner.streamInterruptedNoRetry')
- : i18nKey
- ? t(i18nKey)
- : unwrapped;
- const showRawToggle = isStreamInterrupted || (!i18nKey && unwrapped !== decoded);
+ : isGatewayProxyTokenInvalid
+ ? t('chat.errorBanner.gatewayProxyTokenInvalidNoRetry')
+ : i18nKey
+ ? t(i18nKey)
+ : unwrapped;
+ const showRawToggle =
+ isStreamInterrupted ||
+ isGatewayProxyTokenInvalid ||
+ (!i18nKey && unwrapped !== decoded);
useEffect(() => {
setShowRaw(false);
diff --git a/apps/desktop/src/renderer/components/chat/MessageStream.tsx b/apps/desktop/src/renderer/components/chat/MessageStream.tsx
index 60515be527..a5b44ff052 100644
--- a/apps/desktop/src/renderer/components/chat/MessageStream.tsx
+++ b/apps/desktop/src/renderer/components/chat/MessageStream.tsx
@@ -6367,7 +6367,13 @@ const MessageItem = memo(function MessageItem({
// 历史里的 turn 失败记录(role='error' 持久化行)——静态时间线卡,
// live 报错仍走输入框上方的 ErrorBanner,两者不会同时出现
// (error 行落库时不广播,只在历史加载路径进入消息流)。
- return <ErrorMessageCard message={message.content} reason={message.errorReason} />;
+ return (
+ <ErrorMessageCard
+ message={message.content}
+ reason={message.errorReason}
+ providerId={message.errorProviderId}
+ />
+ );
case 'thinking':
// Defensive fallback only — MessageStream renders thinking inline.
return (
diff --git a/apps/desktop/src/renderer/components/chat/errorReasonI18n.ts b/apps/desktop/src/renderer/components/chat/errorReasonI18n.ts
index 48b881b9eb..7e701b0c5a 100644
--- a/apps/desktop/src/renderer/components/chat/errorReasonI18n.ts
+++ b/apps/desktop/src/renderer/components/chat/errorReasonI18n.ts
@@ -1,3 +1,4 @@
+import { GATEWAY_PROXY_TOKEN_INVALID_REASON } from '@cindy/maker-shared/error-redaction';
import {
CLAUDE_GATEWAY_OPUS_PLAN_MISMATCH_REASON,
CLAUDE_SUBSCRIPTION_OPUS_PLAN_MISMATCH_REASON,
@@ -35,4 +36,5 @@ export const ERROR_REASON_I18N_KEYS: Record<string, string> = {
[CLAUDE_GATEWAY_OPUS_PLAN_MISMATCH_REASON]: 'chat.errorBanner.claudeGatewayOpusPlanMismatch',
[CLAUDE_SUBSCRIPTION_OPUS_PLAN_MISMATCH_REASON]:
'chat.errorBanner.claudeSubscriptionOpusPlanMismatch',
+ [GATEWAY_PROXY_TOKEN_INVALID_REASON]: 'chat.errorBanner.gatewayProxyTokenInvalidNoRetry',
};
diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.json
index 6f5b9f7c33..a60f6be851 100644
--- a/apps/desktop/src/renderer/i18n/locales/en/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json
@@ -7130,6 +7130,8 @@
"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",
+ "gatewayProxyTokenInvalid": "Cindy AI credentials are no longer valid. Click Retry. If it happens again, sign out and sign back in",
+ "gatewayProxyTokenInvalidNoRetry": "Cindy AI credentials are no longer valid. If it happens again, sign out and sign back in",
"silentStopContinue": "Continue",
"silentStopContinueTitle": "Continue the current task",
"piTransportClosed": "Remote Pi connection interrupted (SSH channel closed). The remote task is still running — reconnect to continue.",
diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.json
index e2c515a6d1..2acf34613e 100644
--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json
@@ -7127,6 +7127,8 @@
"streamInterruptedNoRetry": "モデル出力が途中で中断されました。一時的な上流障害であることが多いので、しばらくしてから再試行してください",
"networkShowRaw": "元のエラーを表示",
"networkHideRaw": "元のエラーを隠す",
+ "gatewayProxyTokenInvalid": "Cindy AI の認証情報が無効になりました。「再試行」をクリックしてください。繰り返す場合はサインアウトしてから再ログインしてください",
+ "gatewayProxyTokenInvalidNoRetry": "Cindy AI の認証情報が無効になりました。繰り返す場合はサインアウトしてから再ログインしてください",
"silentStopContinue": "続行",
"silentStopContinueTitle": "現在のタスクを続行",
"piTransportClosed": "リモート Pi の接続が切断されました(SSH チャンネルが閉じました)。リモートのタスクは実行中のままです。再接続すると続行できます。",
diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.json
index 26051f0270..950cea6f73 100644
--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json
@@ -7127,6 +7127,8 @@
"streamInterruptedNoRetry": "모델 출력이 중간에 중단되었습니다. 보통은 일시적인 상위 서비스 장애입니다. 잠시 후 다시 시도해 주세요",
"networkShowRaw": "원본 오류 보기",
"networkHideRaw": "원본 오류 숨기기",
+ "gatewayProxyTokenInvalid": "Cindy AI 자격 증명이 더 이상 유효하지 않습니다. 재시도를 클릭하세요. 반복되면 로그아웃 후 다시 로그인하세요",
+ "gatewayProxyTokenInvalidNoRetry": "Cindy AI 자격 증명이 더 이상 유효하지 않습니다. 반복되면 로그아웃 후 다시 로그인하세요",
"silentStopContinue": "계속",
"silentStopContinueTitle": "현재 작업 계속",
"piTransportClosed": "원격 Pi 연결이 끊어졌습니다(SSH 채널 닫힘). 원격 작업은 계속 실행 중입니다. 다시 연결하면 계속할 수 있습니다.",
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 9c2948a121..d74045b361 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
@@ -7127,6 +7127,8 @@
"streamInterruptedNoRetry": "模型输出中途中断了。通常是上游暂时故障,请稍后重试。",
"networkShowRaw": "查看原始错误",
"networkHideRaw": "收起原始错误",
+ "gatewayProxyTokenInvalid": "Cindy AI 凭据已失效。请点击「重试」。若仍失败,请退出后重新登录",
+ "gatewayProxyTokenInvalidNoRetry": "Cindy AI 凭据已失效。若后续仍失败,请退出后重新登录",
"silentStopContinue": "继续",
"silentStopContinueTitle": "继续当前任务",
"piTransportClosed": "远端 Pi 连接已中断(SSH 通道关闭)。远端任务仍在运行,重新连接后可以继续。",
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 4877c722f4..9643569d26 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
@@ -7126,6 +7126,8 @@
"streamInterruptedNoRetry": "模型輸出中途中斷了。通常是上游暫時故障,請稍後重試。",
"networkShowRaw": "檢視原始錯誤",
"networkHideRaw": "收起原始錯誤",
+ "gatewayProxyTokenInvalid": "Cindy AI 憑據已失效。請點「重試」。若仍失敗,請退出後重新登入",
+ "gatewayProxyTokenInvalidNoRetry": "Cindy AI 憑據已失效。若後續仍失敗,請退出後重新登入",
"silentStopContinue": "繼續",
"silentStopContinueTitle": "繼續當前任務",
"piTransportClosed": "遠端 Pi 連線已中斷(SSH 通道關閉)。遠端任務仍在執行,重新連線後可以繼續。",
diff --git a/apps/desktop/src/renderer/lib/makerChatStore.ts b/apps/desktop/src/renderer/lib/makerChatStore.ts
index 8ba1cf619a..6bc40d3c96 100644
--- a/apps/desktop/src/renderer/lib/makerChatStore.ts
+++ b/apps/desktop/src/renderer/lib/makerChatStore.ts
@@ -30,7 +30,12 @@ import {
} from '@/contexts/dataOwnerGeneration';
import { isDataOwnerPushStamp } from '../../shared/dataOwnerPush';
import { dbToMakerAgentKind } from '../../shared/agentKindConversion';
-import { redactSensitiveText } from '@cindy/maker-shared/error-redaction';
+import {
+ GATEWAY_PROXY_TOKEN_INVALID_REASON,
+ isCindyGatewayProviderId,
+ isGatewayProxyTokenInvalidError,
+ redactSensitiveText,
+} from '@cindy/maker-shared/error-redaction';
import {
formatRemoteError,
isDeviceUnresponsiveRemoteError,
@@ -2319,6 +2324,12 @@ export interface SessionChatState {
* agent 据此选 transport (stdio vs SSH-bridged daemon)。
*/
remoteHostId: string | null;
+ /**
+ * 当前会话显式选定的供应商。undefined = 尚未从 session 行水合;
+ * null = 隐式 Cindy 网关默认来源。只用于给新排队项打 createOpts.providerId 快照,
+ * 不能拿来给历史 error 行重新分类。
+ */
+ sessionProviderId?: string | null;
/** Internal: prevents infinite auth-retry loops for remote sessions. */
_authRetryInFlight?: boolean;
/** Internal: clientId of the last user message that triggered auth-retry (prevents re-retrying same message). */
@@ -2329,6 +2340,8 @@ export interface SessionChatState {
data: Record<string, unknown> | null;
agentMeta: Record<string, unknown> | null;
};
+ /** Internal: root user input whose rejected Cindy gateway credential was already retried. */
+ _gatewayProxyTokenRetriedRootClientId?: string;
/**
* Internal: consecutive auto-retry count for this session. Hard cap against
* the rare loop where the key refreshes successfully every time but the
@@ -3534,6 +3547,54 @@ const _activeViewSessions = new Map<string, number>();
// reloaded history shows only the persisted ErrorMessageCard.
const _pendingErrorClearOnLeave = new Set<string>();
+/** Terminal error 后、配对 done 到达前,凭据刷新必须等 host 空闲。 */
+const GATEWAY_PROXY_TOKEN_TURN_SETTLE_MS = 5_000;
+const gatewayProxyTokenTurnSettledWaiters = new Map<string, Array<() => void>>();
+
+function notifyGatewayProxyTokenTurnSettled(sessionId: string): void {
+ const waiters = gatewayProxyTokenTurnSettledWaiters.get(sessionId);
+ if (!waiters || waiters.length === 0) return;
+ gatewayProxyTokenTurnSettledWaiters.delete(sessionId);
+ for (const waiter of waiters) waiter();
+}
+
+function waitForGatewayProxyTokenTurnSettled(
+ sessionId: string,
+ dataOwnerAtIngress: DataOwnerGeneration,
+): Promise<void> {
+ return new Promise((resolve) => {
+ let settled = false;
+ const finish = () => {
+ if (settled) return;
+ settled = true;
+ clearTimeout(timer);
+ const remaining = gatewayProxyTokenTurnSettledWaiters.get(sessionId);
+ if (remaining) {
+ const next = remaining.filter((waiter) => waiter !== finish);
+ if (next.length === 0) gatewayProxyTokenTurnSettledWaiters.delete(sessionId);
+ else gatewayProxyTokenTurnSettledWaiters.set(sessionId, next);
+ }
+ resolve();
+ };
+ const timer = setTimeout(finish, GATEWAY_PROXY_TOKEN_TURN_SETTLE_MS);
+ const waiters = gatewayProxyTokenTurnSettledWaiters.get(sessionId) ?? [];
+ waiters.push(finish);
+ gatewayProxyTokenTurnSettledWaiters.set(sessionId, waiters);
+ if (!isDataOwnerGenerationCurrent(dataOwnerAtIngress)) finish();
+ });
+}
+
+function resolveGatewayRecoveryProviderId(
+ createOpts: { providerId?: string | null } | undefined,
+ session: Pick<SessionChatState, 'agentSwitchIntent' | 'sessionProviderId'>,
+): string | null | undefined {
+ if (createOpts && Object.prototype.hasOwnProperty.call(createOpts, 'providerId')) {
+ return createOpts.providerId ?? null;
+ }
+ if (session.agentSwitchIntent) return session.agentSwitchIntent.providerId;
+ return session.sessionProviderId;
+}
+
function enterView(sessionId: string): () => void {
_activeViewSessions.set(sessionId, (_activeViewSessions.get(sessionId) ?? 0) + 1);
_lastViewedAt.delete(sessionId);
@@ -6882,35 +6943,72 @@ function initGlobalListeners(options: GlobalListenerOptions = {}): void {
// Legacy CC/XD remote auth-retry: 在 reducer 写 error 之前拦截,避免 error banner 闪烁。
if (event.type === 'error') {
const errData =
- (event.data as { sdkError?: string; message?: string; errorStatus?: number }) ?? {};
+ (event.data as {
+ sdkError?: string;
+ message?: string;
+ errorStatus?: number;
+ reason?: string;
+ }) ?? {};
const isAuthError =
errData.sdkError === 'authentication_failed' ||
errData.errorStatus === 401 ||
/authentication_error|invalid.*api.key|401/i.test(errData.message ?? '');
+ const isGatewayProxyTokenInvalid =
+ errData.reason === GATEWAY_PROXY_TOKEN_INVALID_REASON ||
+ isGatewayProxyTokenInvalidError(errData.message ?? '');
const preSnap = getOrCreateState(sessionId);
const authRetryCount = preSnap._authRetryCount ?? 0;
- if (
+ const ownsGatewayProxyTokenRecovery = ownsRemoteAuthRetry && !ingress.remoteDeviceId;
+ const recoveryProviderId =
+ preSnap.inputRecovery?.kind === 'active-turn'
+ ? resolveGatewayRecoveryProviderId(preSnap.inputRecovery.item.createOpts, preSnap)
+ : undefined;
+ const translatorClassifiedGateway =
+ errData.reason === GATEWAY_PROXY_TOKEN_INVALID_REASON;
+ const explicitCustomGatewayProvider =
+ recoveryProviderId !== undefined && !isCindyGatewayProviderId(recoveryProviderId);
+ const gatewayRecovery =
+ isGatewayProxyTokenInvalid &&
+ preSnap.inputRecovery?.kind === 'active-turn' &&
+ (translatorClassifiedGateway || !explicitCustomGatewayProvider)
+ ? preSnap.inputRecovery
+ : null;
+ const isCindyGatewayProxyTokenInvalid =
+ translatorClassifiedGateway || gatewayRecovery !== null;
+ const gatewayRetryRootClientId = gatewayRecovery
+ ? (gatewayRecovery.item.supersedesUserClientId ?? gatewayRecovery.item.clientId)
+ : null;
+ const canRecoverGatewayProxyToken =
+ ownsGatewayProxyTokenRecovery &&
+ gatewayRecovery !== null &&
+ gatewayRetryRootClientId !== null &&
+ !preSnap._authRetryInFlight &&
+ preSnap._gatewayProxyTokenRetriedRootClientId !== gatewayRetryRootClientId;
+ const canRecoverRemoteCcAuth =
ownsRemoteAuthRetry &&
isAuthError &&
- preSnap.remoteHostId &&
+ !isGatewayProxyTokenInvalid &&
+ Boolean(preSnap.remoteHostId) &&
preSnap.agentKind === 'claude-code' &&
!preSnap._authRetryInFlight &&
- authRetryCount < MAX_REMOTE_AUTH_RETRIES
- ) {
+ authRetryCount < MAX_REMOTE_AUTH_RETRIES;
+ if (canRecoverGatewayProxyToken || canRecoverRemoteCcAuth) {
const lastUser = [...preSnap.messages].reverse().find((m) => m.role === 'user');
- const lastUserClientId = lastUser?.clientId;
+ const retryOwnerClientId = gatewayRecovery?.item.clientId ?? lastUser?.clientId;
// Per-message retry guard: same user message only auto-retried once.
// Session-level count guard (_authRetryCount): hard cap on consecutive
// retries — the per-message guard can't stop a chain because each retry
// sends a fresh user message with a new clientId.
- if (lastUserClientId && preSnap._authRetryAttemptedClientId === lastUserClientId) {
+ if (retryOwnerClientId && preSnap._authRetryAttemptedClientId === retryOwnerClientId) {
// Already retried this message — show error, don't loop.
} else {
setState(sessionId, (s) => ({
...s,
_authRetryInFlight: true,
- _authRetryAttemptedClientId: lastUserClientId,
- _authRetryCount: (s._authRetryCount ?? 0) + 1,
+ _authRetryAttemptedClientId: retryOwnerClientId,
+ ...(isGatewayProxyTokenInvalid
+ ? { _gatewayProxyTokenRetriedRootClientId: gatewayRetryRootClientId ?? undefined }
+ : { _authRetryCount: (s._authRetryCount ?? 0) + 1 }),
}));
const retryText =
lastUser && typeof lastUser.content === 'string' && lastUser.content.length > 0
@@ -6928,21 +7026,56 @@ function initGlobalListeners(options: GlobalListenerOptions = {}): void {
void (async () => {
try {
if (!isDataOwnerGenerationCurrent(dataOwnerAtIngress)) return;
- // 本地 only:网关 key 不再有服务器副本可拉。改为校验本机 safeStorage 是否
- // 有 key —— 有则关闭并重发会话(重连时把本机 key 重新下发给 remote host);
- // 没有则中止重试,让 error banner 浮现,提示用户在本机重填 key。
- const localKey = await window.electronAPI.safeStorageRead(
- providerSecretStorageKey('xd'),
- );
- if (!isDataOwnerGenerationCurrent(dataOwnerAtIngress)) return;
- if (!localKey) {
- throw new Error('no local api key available');
+ if (isGatewayProxyTokenInvalid) {
+ await waitForGatewayProxyTokenTurnSettled(sessionId, dataOwnerAtIngress);
+ if (!isDataOwnerGenerationCurrent(dataOwnerAtIngress)) return;
+ if (
+ !translatorClassifiedGateway &&
+ recoveryProviderId === undefined
+ ) {
+ const row = await sessionService.get(sessionId);
+ if (!isDataOwnerGenerationCurrent(dataOwnerAtIngress)) return;
+ if (!isCindyGatewayProviderId(row.providerId ?? null)) {
+ throw new Error('custom provider owns this LiteLLM token error');
+ }
+ }
+ const status = await window.electronAPI.modelAccess.retry();
+ if (!isDataOwnerGenerationCurrent(dataOwnerAtIngress)) return;
+ if (status.state !== 'ok') {
+ throw new Error('model-access credentials retry failed');
+ }
}
- // preserveWorkspace: 鉴权重连是瞬态 close+resend,会话继续,工作区必须保留。
- await makerApiFor(sessionId).closeSession(sessionId, { preserveWorkspace: true });
- await new Promise((r) => setTimeout(r, 1500));
- if (!isDataOwnerGenerationCurrent(dataOwnerAtIngress)) return;
- if (hasRetryPayload) {
+ // 本机 Claude gateway-spawn 把 ANTHROPIC_API_KEY 冻在子进程里,
+ // proxy 对隐式/默认 Cindy 网关是 x-api-key passthrough。只重拉凭据
+ // 不重建会话的话,retryLastError 仍会带上已被拒的旧 token。
+ const recreateLocalClaudeGatewaySession =
+ isGatewayProxyTokenInvalid &&
+ !preSnap.remoteHostId &&
+ preSnap.agentKind === 'claude-code';
+ if (preSnap.remoteHostId || recreateLocalClaudeGatewaySession) {
+ if (preSnap.remoteHostId) {
+ const localKey = await window.electronAPI.safeStorageRead(
+ providerSecretStorageKey('xd'),
+ );
+ if (!isDataOwnerGenerationCurrent(dataOwnerAtIngress)) return;
+ if (!localKey) {
+ throw new Error('no local api key available');
+ }
+ }
+ await makerApiFor(sessionId).closeSession(sessionId, { preserveWorkspace: true });
+ if (preSnap.remoteHostId) {
+ await new Promise((r) => setTimeout(r, 1500));
+ }
+ if (!isDataOwnerGenerationCurrent(dataOwnerAtIngress)) return;
+ }
+ if (isGatewayProxyTokenInvalid) {
+ await retryLastError(sessionId);
+ if (!isDataOwnerGenerationCurrent(dataOwnerAtIngress)) return;
+ const postRetry = getOrCreateState(sessionId);
+ if (postRetry.error !== null || postRetry.inputRecovery !== null) {
+ throw new Error('gateway credential retry did not take effect');
+ }
+ } else if (hasRetryPayload) {
const row = await sessionService.get(sessionId);
if (!isDataOwnerGenerationCurrent(dataOwnerAtIngress)) return;
if (row.workingDir && row.model) {
@@ -6976,14 +7109,16 @@ function initGlobalListeners(options: GlobalListenerOptions = {}): void {
}
} catch {
if (!isDataOwnerGenerationCurrent(dataOwnerAtIngress)) return;
- // 重试失败——main 侧已跳过持久化(isRemoteAuthRetry),在此补落。
- // device-link 控制端经 makerApiFor 路由到被控端 main(不直调本地 IPC);
- // 同时透传 agentMeta 供 flushAssistantBlock 边界 meta 兜底与 dedup key。
- void makerApiFor(sessionId).input.persistTurnErrorDeferred(
- sessionId,
- event.data as Record<string, unknown> | null,
- event.agentMeta ?? null,
- );
+ if (
+ isCindyGatewayProxyTokenInvalid ||
+ (preSnap.remoteHostId && preSnap.agentKind === 'claude-code')
+ ) {
+ void makerApiFor(sessionId).input.persistTurnErrorDeferred(
+ sessionId,
+ event.data as Record<string, unknown> | null,
+ event.agentMeta ?? null,
+ );
+ }
const terminalErrorEvent = {
sessionId,
type: 'error',
@@ -7013,9 +7148,8 @@ function initGlobalListeners(options: GlobalListenerOptions = {}): void {
// 等价于旧行为(重启后错误丢失)—— 保守起见不做 deferred。
if (
ownsRemoteAuthRetry &&
- isAuthError &&
- preSnap.remoteHostId &&
- preSnap.agentKind === 'claude-code' &&
+ ((ownsGatewayProxyTokenRecovery && isCindyGatewayProxyTokenInvalid) ||
+ (isAuthError && preSnap.remoteHostId && preSnap.agentKind === 'claude-code')) &&
!preSnap._authRetryInFlight
) {
void makerApiFor(sessionId).input.persistTurnErrorDeferred(
@@ -7030,6 +7164,7 @@ function initGlobalListeners(options: GlobalListenerOptions = {}): void {
// done / error 副作用 (从老 stream listener 搬过来)
if (isProductTurnDoneEvent(event)) {
+ notifyGatewayProxyTokenTurnSettled(sessionId);
if (
event.source === 'codex' &&
(event.data as { silentStop?: boolean } | null | undefined)?.silentStop !== true
@@ -9983,6 +10118,10 @@ function ensureInitialMessages(sessionId: string): void {
if (s.remoteHostId !== nextRemoteHostId) {
updates.remoteHostId = nextRemoteHostId;
}
+ const nextSessionProviderId = session.providerId ?? null;
+ if (s.sessionProviderId !== nextSessionProviderId) {
+ updates.sessionProviderId = nextSessionProviderId;
+ }
if (session.sdkSessionId && s.sdkSessionId !== session.sdkSessionId) {
updates.sdkSessionId = session.sdkSessionId;
}
@@ -11795,6 +11934,11 @@ export function buildCreateOptsForCurrentSession(
...(current.remoteHostId ? { remoteHostId: current.remoteHostId } : {}),
...(opts?.vendorOptions ? { vendorOptions: opts.vendorOptions } : {}),
...(current.sdkSessionId ? { resumeSessionId: current.sdkSessionId } : {}),
+ ...(current.agentSwitchIntent
+ ? { providerId: current.agentSwitchIntent.providerId }
+ : current.sessionProviderId !== undefined
+ ? { providerId: current.sessionProviderId }
+ : {}),
};
}
@@ -14591,20 +14735,26 @@ function sendUiTrigger(sessionId: string, prompt: string): Promise<void> {
*/
function noteAgentSwitched(sessionId: string, agentKind: 'claude-code' | 'codex' | 'pi'): void {
if (!sessionId) return;
- setState(sessionId, (s) =>
- s.agentKind === agentKind && s.sdkSessionId === null && s.agentSwitchIntent === null
- ? s
- : {
- ...s,
- agentKind,
- sdkSessionId: null,
- agentSwitchIntent: null,
- // 意图被真实切换消费掉也是一次变更,在途读回据此作废。
- ...(s.agentSwitchIntent === null
- ? {}
- : { agentSwitchIntentRev: s.agentSwitchIntentRev + 1 }),
- },
- );
+ setState(sessionId, (s) => {
+ const nextProviderId = s.agentSwitchIntent ? s.agentSwitchIntent.providerId : s.sessionProviderId;
+ if (
+ s.agentKind === agentKind &&
+ s.sdkSessionId === null &&
+ s.agentSwitchIntent === null &&
+ s.sessionProviderId === nextProviderId
+ ) {
+ return s;
+ }
+ return {
+ ...s,
+ agentKind,
+ sdkSessionId: null,
+ agentSwitchIntent: null,
+ ...(s.agentSwitchIntent ? { sessionProviderId: s.agentSwitchIntent.providerId } : {}),
+ // 意图被真实切换消费掉也是一次变更,在途读回据此作废。
+ ...(s.agentSwitchIntent === null ? {} : { agentSwitchIntentRev: s.agentSwitchIntentRev + 1 }),
+ };
+ });
}
/**
@@ -14788,6 +14938,7 @@ function mirrorSessionFields(
fastMode?: unknown;
planModeEnabled?: unknown;
agentKind?: unknown;
+ providerId?: unknown;
agentSwitchIntent?: unknown;
agentSwitchIntentCanceled?: unknown;
}
@@ -14815,12 +14966,30 @@ function mirrorSessionFields(
agentKind: nextKind,
sdkSessionId: null,
// 意图被真实切换消费 = 一次意图变更,推进修订号让在途读回作废。
+ // 同时把目标 provider 写进 createOpts 快照,避免后续排队项仍带旧来源。
...(intentApplied
- ? { agentSwitchIntent: null, agentSwitchIntentRev: s.agentSwitchIntentRev + 1 }
+ ? {
+ agentSwitchIntent: null,
+ agentSwitchIntentRev: s.agentSwitchIntentRev + 1,
+ sessionProviderId: s.agentSwitchIntent?.providerId,
+ }
: {}),
};
});
}
+ if ('providerId' in patch) {
+ const nextProviderId =
+ typeof patch.providerId === 'string'
+ ? patch.providerId
+ : patch.providerId === null
+ ? null
+ : undefined;
+ if (nextProviderId !== undefined) {
+ setState(sessionId, (s) =>
+ s.sessionProviderId === nextProviderId ? s : { ...s, sessionProviderId: nextProviderId },
+ );
+ }
+ }
if (typeof patch.fastMode === 'boolean') {
const next = patch.fastMode;
setState(sessionId, (s) => (s.fastMode === next ? s : { ...s, fastMode: next }));
diff --git a/packages/maker-core/src/agents/claude-code/__tests__/translator-error-result.test.ts b/packages/maker-core/src/agents/claude-code/__tests__/translator-error-result.test.ts
index cfa202642a..be0f438b0d 100644
--- a/packages/maker-core/src/agents/claude-code/__tests__/translator-error-result.test.ts
+++ b/packages/maker-core/src/agents/claude-code/__tests__/translator-error-result.test.ts
@@ -25,12 +25,13 @@ function createTurnState(): TurnState {
};
}
-function createCtx(tracker: UsageTracker) {
+function createCtx(tracker: UsageTracker, providerId: string | null = 'xd') {
return {
rt: newRuntimeState(),
turn: createTurnState(),
log: { debug: vi.fn(), info: vi.fn(), warn: vi.fn() },
getModel: () => 'codex/gpt-5.5',
+ getProviderId: () => providerId,
getEffort: () => 'high' as const,
getPermissionMode: () => 'auto' as const,
onSessionId: vi.fn(),
@@ -176,6 +177,9 @@ describe('Claude Code translator is_error result guard', () => {
expect(serialized).not.toContain('secret-token');
expect(serialized).not.toContain('hash-abc');
expect(serialized).toContain('[REDACTED]');
+ expect(error?.data).toMatchObject({
+ reason: 'gateway-proxy-token-invalid',
+ });
expect(JSON.stringify(ctx.log.debug.mock.calls)).not.toContain('secret-token');
expect(JSON.stringify(ctx.log.warn.mock.calls)).not.toContain('secret-token');
expect(ctx.log.warn).toHaveBeenCalledWith(
@@ -184,6 +188,42 @@ describe('Claude Code translator is_error result guard', () => {
);
});
+ it('does not classify a custom LiteLLM provider error as a Cindy credential failure', async () => {
+ const tracker = new UsageTracker();
+ const queue = createAsyncQueue<AgentEvent>();
+ const ctx = createCtx(tracker, 'custom-litellm');
+
+ translateSdkMessage(
+ {
+ type: 'result',
+ is_error: true,
+ result:
+ 'Invalid proxy server token; Unable to find token in LiteLLM_VerificationTokenTable',
+ stop_reason: 'end_turn',
+ total_cost_usd: 0,
+ usage: { input_tokens: 1, output_tokens: 0 },
+ modelUsage: {
+ 'codex/gpt-5.5': {
+ inputTokens: 1,
+ outputTokens: 0,
+ costUSD: 0,
+ contextWindow: 272_000,
+ },
+ },
+ },
+ queue,
+ ctx,
+ );
+
+ const events = await drain(queue);
+ const error = events.find((event) => event.type === 'error');
+ expect(error?.data).toMatchObject({
+ message: 'Invalid proxy server token; Unable to find token in LiteLLM_VerificationTokenTable',
+ isTerminal: true,
+ });
+ expect(error?.data).not.toHaveProperty('reason');
+ });
+
it('preserves non-secret status and quota signals from a redacted terminal result', async () => {
const tracker = new UsageTracker();
const queue = createAsyncQueue<AgentEvent>();
diff --git a/packages/maker-core/src/agents/claude-code/index.ts b/packages/maker-core/src/agents/claude-code/index.ts
index aa17b1c94c..00fe20d734 100644
--- a/packages/maker-core/src/agents/claude-code/index.ts
+++ b/packages/maker-core/src/agents/claude-code/index.ts
@@ -4531,6 +4531,7 @@ export class ClaudeCodeAgent extends BaseAgent {
turn: turnState,
log,
getModel: () => mutableModel,
+ getProviderId: () => mutableProviderId,
getModelContextWindow: () => resolveModelContextWindow(mutableModel),
getEffort: () => mutableEffort,
getPermissionMode: () => mutablePermissionMode,
diff --git a/packages/maker-core/src/agents/claude-code/translator.ts b/packages/maker-core/src/agents/claude-code/translator.ts
index 101f1c23cc..fb273faf3b 100644
--- a/packages/maker-core/src/agents/claude-code/translator.ts
+++ b/packages/maker-core/src/agents/claude-code/translator.ts
@@ -19,6 +19,8 @@ import type { AgentEvent, AgentTaskStatus, AgentTaskUsage, AgentTaskUpdateEventD
import { normalizeWorkflowProgressEntries } from '@cindy/maker-shared/agent-task';
import {
extractNonSecretErrorSignals,
+ GATEWAY_PROXY_TOKEN_INVALID_REASON,
+ isCindyGatewayProxyTokenInvalidError,
redactSensitiveText,
} from '@cindy/maker-shared/error-redaction';
import {
@@ -530,6 +532,8 @@ interface TranslateContext {
* 不会因为闭包捕获 startSession 时的初始值而打陈旧数据。
*/
getModel: () => string;
+ /** 当前 turn 的 provider 路由;null = 兼容旧会话的隐式默认来源。 */
+ getProviderId?: () => string | null;
/**
* Maker capabilities 中当前模型的 contextWindow。
* Claude Code SDK 对未知第三方模型会回 200K 默认值; maker 侧配置更准时用它覆盖。
@@ -2122,7 +2126,14 @@ function handleResult(
// 上下文超限带稳定 reason key(判定在上方 endTurn 前已算好): renderer 靠它
// 隐藏必败的 Retry(原样重发必然再撞同一个 4xx)并给出压缩 / 新开会话入口;
// 文案匹配仅作历史持久化错误行的兜底(overload reason 同款分层)。
- const overflowReason = isContextOverflowTurn ? { reason: CONTEXT_OVERFLOW_REASON } : {};
+ const classifiedReason = isContextOverflowTurn
+ ? { reason: CONTEXT_OVERFLOW_REASON }
+ : isCindyGatewayProxyTokenInvalidError({
+ providerId: ctx.getProviderId?.() ?? null,
+ message: [errorMessage, errDetail, pendingApiError?.message].filter(Boolean).join('\n'),
+ })
+ ? { reason: GATEWAY_PROXY_TOKEN_INVALID_REASON }
+ : {};
queue.push({
type: 'error',
data: pendingApiError
@@ -2130,7 +2141,7 @@ function handleResult(
message: errorMessage,
sdkError: pendingApiError.sdkError,
isTerminal: true,
- ...overflowReason,
+ ...classifiedReason,
...(errorStatus !== undefined ? { errorStatus } : {}),
...(usageLimit ? { usageLimit: true } : {}),
...(pendingApiError.retryAttempt !== undefined
@@ -2144,7 +2155,7 @@ function handleResult(
? {
message: errDetail,
isTerminal: true,
- ...overflowReason,
+ ...classifiedReason,
...(errorStatus !== undefined ? { errorStatus } : {}),
...(usageLimit ? { usageLimit: true } : {}),
}
diff --git a/packages/maker-shared/src/errorRedaction.test.ts b/packages/maker-shared/src/errorRedaction.test.ts
index 5e89117594..acb4d899f4 100644
--- a/packages/maker-shared/src/errorRedaction.test.ts
+++ b/packages/maker-shared/src/errorRedaction.test.ts
@@ -2,6 +2,9 @@ import { describe, expect, it } from 'vitest';
import {
extractNonSecretErrorSignals,
+ GATEWAY_PROXY_TOKEN_INVALID_REASON,
+ isCindyGatewayProxyTokenInvalidError,
+ isGatewayProxyTokenInvalidError,
matchesDeterministicUsageExhaustionText,
redactSensitiveText,
} from './errorRedaction.js';
@@ -209,3 +212,34 @@ describe('redactSensitiveText', () => {
);
});
});
+
+describe('isGatewayProxyTokenInvalidError', () => {
+ it('matches LiteLLM invalid proxy-token 401 copy after redaction', () => {
+ expect(
+ isGatewayProxyTokenInvalidError(
+ 'Failed to authenticate. API Error: 401 Authentication Error, Invalid proxy server token passed. Received API Key = [REDACTED], Key Hash (Token) =[REDACTED] Unable to find token in cache or `LiteLLM_VerificationTokenTable`',
+ ),
+ ).toBe(true);
+ expect(isGatewayProxyTokenInvalidError('Invalid proxy server token passed')).toBe(true);
+ expect(GATEWAY_PROXY_TOKEN_INVALID_REASON).toBe('gateway-proxy-token-invalid');
+ });
+
+ it('does not treat generic 401 or Claude.ai auth failures as gateway token loss', () => {
+ expect(isGatewayProxyTokenInvalidError('401 Unauthorized')).toBe(false);
+ expect(isGatewayProxyTokenInvalidError('authentication_failed')).toBe(false);
+ expect(isGatewayProxyTokenInvalidError('Missing bearer')).toBe(false);
+ expect(isGatewayProxyTokenInvalidError('')).toBe(false);
+ });
+
+ it('scopes Cindy gateway classification away from custom LiteLLM providers', () => {
+ const message = 'Invalid proxy server token; LiteLLM_VerificationTokenTable';
+ expect(
+ isCindyGatewayProxyTokenInvalidError({ reason: GATEWAY_PROXY_TOKEN_INVALID_REASON }),
+ ).toBe(true);
+ expect(isCindyGatewayProxyTokenInvalidError({ message, providerId: null })).toBe(true);
+ expect(isCindyGatewayProxyTokenInvalidError({ message, providerId: 'xd' })).toBe(true);
+ expect(isCindyGatewayProxyTokenInvalidError({ message, providerId: 'custom-litellm' })).toBe(
+ false,
+ );
+ });
+});
diff --git a/packages/maker-shared/src/errorRedaction.ts b/packages/maker-shared/src/errorRedaction.ts
index 47883d66c1..8f8d05e5c9 100644
--- a/packages/maker-shared/src/errorRedaction.ts
+++ b/packages/maker-shared/src/errorRedaction.ts
@@ -166,3 +166,33 @@ function matchHeaderField(
while (/\s/.test(input[cursor] ?? '')) cursor += 1;
return cursor;
}
+
+/**
+ * LiteLLM 虚拟 Key 401:请求带的网关 token 不在 VerificationTokenTable。
+ * 与 Claude.ai / Codex 订阅 401 不是同一类,不能当成「去重新登录第三方」。
+ */
+export const GATEWAY_PROXY_TOKEN_INVALID_REASON = 'gateway-proxy-token-invalid';
+
+/** Cindy 内置网关:显式 `xd`,或旧会话未写 provider 的隐式默认来源。 */
+export function isCindyGatewayProviderId(providerId: string | null | undefined): boolean {
+ return providerId == null || providerId === 'xd';
+}
+
+export function isGatewayProxyTokenInvalidError(message: string): boolean {
+ if (!message) return false;
+ return /invalid[\s_-]*proxy[\s_-]*server[\s_-]*token|LiteLLM_VerificationTokenTable/i.test(
+ message,
+ );
+}
+
+export function isCindyGatewayProxyTokenInvalidError(input: {
+ reason?: string | null;
+ message?: string | null;
+ providerId?: string | null;
+}): boolean {
+ if (input.reason === GATEWAY_PROXY_TOKEN_INVALID_REASON) return true;
+ return (
+ isCindyGatewayProviderId(input.providerId) &&
+ isGatewayProxyTokenInvalidError(input.message ?? '')
+ );
+}