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): 修复 Opus 来源路由竞态 (#1259)

Dash4e50a407fdbc
diff --git a/apps/desktop/src/main/bootstrap-electron.ts b/apps/desktop/src/main/bootstrap-electron.ts
index b6ffb0d255..b400923d92 100644
--- a/apps/desktop/src/main/bootstrap-electron.ts
+++ b/apps/desktop/src/main/bootstrap-electron.ts
@@ -415,6 +415,7 @@ import {
requestProviderModelAutoRefresh,
resetProviderModelAutoRefreshCooldowns,
} from './maker-host/provider-model-auto-refresh.js';
+import { refreshProviderModelsAfterAccountReady } from './maker-host/account-provider-model-refresh.js';
import {
readImDefaultSettingsState,
resetImDefaultSettings,
@@ -5800,37 +5801,20 @@ app.on('ready', async () => {
// 自定义供应商配置在按 userId 切片的 localDb 里:DB ready / 换账号后重新加载并
// 注入 active-catalog(让路由 / 来源栏 / 模型选择器跟随当前账号)。best-effort,不阻塞。
void refreshCustomProvidersIntoCatalog();
- // 自定义 MCP:provider 数组已在上方刷新完成,fire-and-forget 失效 Codex cached
- // spawn 配置,使下一会话按新数组重建。
- // 顺序约束:先 dispose app-server(含 busy 检查),成功后再关 bridge(与 mcpHandlers
- // invalidateCodex 同款模式)。best-effort,不阻塞 DB-ready 其余初始化。
- void (async () => {
- let codexRestarted = false;
- try {
- await restartCodexAfterAuthModeChange();
- codexRestarted = true;
- } catch (err) {
- accountSwitchLog.warn('restartCodexAfterAuthModeChange on account switch failed', {
- error: err instanceof Error ? err.message : String(err),
- });
- }
- if (codexRestarted) {
- try {
- await shutdownCodexEnvironment();
- } catch (err) {
- accountSwitchLog.warn('shutdownCodexEnvironment on account switch failed', {
- error: err instanceof Error ? err.message : String(err),
- });
- }
- }
- // 账号数据就绪 = 启动链路上最早能确定「owner 绑定已认领、网关凭证已下发」的时机,
- // 也是模型清单该被刷新到最新的时机。在这里强制跑一遍(无视冷却),别再等用户去打开
- // 设置页或模型选择器把清单逼出来 —— 那是全新机器首启只看到少数模型的直接原因。
- //
- // 必须排在上面 codex 重启序列**之后**:那条序列末尾会按 auth 边界重读
- // models_cache(cache miss 即清空防串号),并发跑会让刚发现的清单被空快照覆盖。
- void requestProviderModelAutoRefresh('startup');
- })();
+ // 自定义 MCP:provider 数组已在上方刷新完成,失效 Codex cached spawn 配置,
+ // 使下一会话按新数组重建。
+ // 顺序约束与模型发现都保持 best-effort,但这里必须 await 到 settle:LocalDbGate
+ // 只有随后才放行主界面。否则用户能在 Anthropic 清单尚未回来时发送 Opus,
+ // 草稿会按 XD 默认路由建成 provider_id=NULL(issue #1196)。
+ //
+ // 模型发现必须排在 Codex 重启序列之后:后者末尾会按 auth 边界重读
+ // models_cache(cache miss 即清空防串号),并发跑会让刚发现的清单被空快照覆盖。
+ await refreshProviderModelsAfterAccountReady({
+ restartCodex: restartCodexAfterAuthModeChange,
+ shutdownCodexEnvironment,
+ refreshProviderModels: requestProviderModelAutoRefresh,
+ log: accountSwitchLog,
+ });
void sweepStartupDraftImages({
dbClient: getDbClient(),
processStartedAtMs: PROCESS_STARTED_AT_MS,
diff --git a/apps/desktop/src/main/maker-host/__tests__/accountProviderModelRefresh.test.ts b/apps/desktop/src/main/maker-host/__tests__/accountProviderModelRefresh.test.ts
new file mode 100644
index 0000000000..c74761a5e2
--- /dev/null
+++ b/apps/desktop/src/main/maker-host/__tests__/accountProviderModelRefresh.test.ts
@@ -0,0 +1,90 @@
+import { describe, expect, it, vi } from 'vitest';
+
+import { refreshProviderModelsAfterAccountReady } from '../account-provider-model-refresh.js';
+
+function deferred() {
+ let resolve!: () => void;
+ const promise = new Promise<void>((done) => {
+ resolve = done;
+ });
+ return { promise, resolve };
+}
+
+describe('refreshProviderModelsAfterAccountReady', () => {
+ it('waits for Anthropic discovery but not unrelated provider refreshes', async () => {
+ const anthropicRefresh = deferred();
+ const backgroundRefresh = deferred();
+ const events: string[] = [];
+ const operation = refreshProviderModelsAfterAccountReady({
+ restartCodex: async () => {
+ events.push('restart');
+ },
+ shutdownCodexEnvironment: async () => {
+ events.push('shutdown');
+ },
+ refreshProviderModels: async (trigger, providerIds) => {
+ events.push(`refresh:${trigger}:${providerIds?.join(',')}`);
+ await (providerIds?.includes('anthropic')
+ ? anthropicRefresh.promise
+ : backgroundRefresh.promise);
+ },
+ log: { warn: vi.fn() },
+ });
+
+ let settled = false;
+ void operation.then(() => {
+ settled = true;
+ });
+ await vi.waitFor(() => expect(events).toEqual([
+ 'restart',
+ 'shutdown',
+ 'refresh:startup:xd,openai,xai',
+ 'refresh:startup:anthropic',
+ ]));
+ expect(settled).toBe(false);
+
+ anthropicRefresh.resolve();
+ await operation;
+ expect(settled).toBe(true);
+ });
+
+ it('still discovers providers when Codex reset steps fail', async () => {
+ const warn = vi.fn();
+ const refreshProviderModels = vi.fn(async () => {});
+
+ await expect(
+ refreshProviderModelsAfterAccountReady({
+ restartCodex: async () => {
+ throw new Error('restart unavailable');
+ },
+ shutdownCodexEnvironment: vi.fn(async () => {}),
+ refreshProviderModels,
+ log: { warn },
+ }),
+ ).resolves.toBeUndefined();
+
+ expect(refreshProviderModels).toHaveBeenCalledWith('startup', ['xd', 'openai', 'xai']);
+ expect(refreshProviderModels).toHaveBeenCalledWith('startup', ['anthropic']);
+ expect(warn).toHaveBeenCalledWith('restartCodexAfterAuthModeChange on account switch failed', {
+ error: 'restart unavailable',
+ });
+ });
+
+ it('keeps account readiness best-effort when discovery itself fails', async () => {
+ const warn = vi.fn();
+ await expect(
+ refreshProviderModelsAfterAccountReady({
+ restartCodex: vi.fn(async () => {}),
+ shutdownCodexEnvironment: vi.fn(async () => {}),
+ refreshProviderModels: async () => {
+ throw new Error('discovery unavailable');
+ },
+ log: { warn },
+ }),
+ ).resolves.toBeUndefined();
+
+ expect(warn).toHaveBeenCalledWith('Anthropic model startup refresh failed', {
+ error: 'discovery unavailable',
+ });
+ });
+});
diff --git a/apps/desktop/src/main/maker-host/__tests__/claudeGatewayErrorObserver.test.ts b/apps/desktop/src/main/maker-host/__tests__/claudeGatewayErrorObserver.test.ts
new file mode 100644
index 0000000000..0f1dec5a7c
--- /dev/null
+++ b/apps/desktop/src/main/maker-host/__tests__/claudeGatewayErrorObserver.test.ts
@@ -0,0 +1,106 @@
+import { gzipSync } from 'node:zlib';
+
+import type { ResponseObserverCtx } from '@cindy/anthropic-compat-proxy';
+import { beforeEach, describe, expect, it } from 'vitest';
+
+import { CLAUDE_GATEWAY_OPUS_PLAN_MISMATCH_REASON } from '../../../shared/claudeGatewayError.js';
+import {
+ consumeClaudeGatewayOpusPlanMismatch,
+ createClaudeGatewayErrorObserver,
+ resetClaudeGatewayErrorObserverForTest,
+} from '../claude-gateway-error-observer.js';
+import {
+ noteClaudeSessionRequest,
+ recordClaudeRequestRoute,
+ resetClaudeSessionRouteRegistryForTest,
+} from '../claude-session-route-registry.js';
+
+const planError = JSON.stringify({
+ type: 'error',
+ error: {
+ type: 'invalid_request',
+ message: 'Claude Opus is not available with the Claude Pro plan.',
+ },
+});
+
+function ctx(overrides: Partial<ResponseObserverCtx> = {}): ResponseObserverCtx {
+ return {
+ reqId: 1,
+ method: 'POST',
+ url: '/v1/messages',
+ upstreamBase: 'https://gateway.example.com',
+ status: 400,
+ requestHeaders: { 'x-claude-code-session-id': 'sdk-1' },
+ responseHeaders: {},
+ requestBody: Buffer.from(JSON.stringify({ model: 'claude-opus-5' })),
+ ...overrides,
+ };
+}
+
+function drive(c: ResponseObserverCtx, body: Buffer): boolean {
+ const sink = createClaudeGatewayErrorObserver()(c);
+ if (!sink) return false;
+ sink.onData?.(body);
+ sink.onEnd?.();
+ return true;
+}
+
+describe('Claude gateway error observer', () => {
+ beforeEach(() => {
+ resetClaudeSessionRouteRegistryForTest();
+ resetClaudeGatewayErrorObserverForTest();
+ });
+
+ it('records evidence from the exact latest gateway Opus 400 response', () => {
+ recordClaudeRequestRoute(1, 's1', 'gateway');
+
+ expect(drive(ctx(), Buffer.from(planError))).toBe(true);
+ expect(consumeClaudeGatewayOpusPlanMismatch('s1')).toBe(
+ CLAUDE_GATEWAY_OPUS_PLAN_MISMATCH_REASON,
+ );
+ expect(consumeClaudeGatewayOpusPlanMismatch('s1')).toBeNull();
+ });
+
+ it('decodes compressed gateway error bodies', () => {
+ recordClaudeRequestRoute(1, 's1', 'gateway');
+
+ expect(drive(ctx({ responseHeaders: { 'content-encoding': 'gzip' } }), gzipSync(planError))).toBe(true);
+ expect(consumeClaudeGatewayOpusPlanMismatch('s1')).toBe(
+ CLAUDE_GATEWAY_OPUS_PLAN_MISMATCH_REASON,
+ );
+ });
+
+ it.each([
+ { label: 'subscription route', route: 'subscription' as const },
+ { label: 'non-400 response', route: 'gateway' as const, status: 429 },
+ { label: 'non-Opus request', route: 'gateway' as const, model: 'claude-sonnet-5' },
+ { label: 'unrelated error', route: 'gateway' as const, body: '{"error":"busy"}' },
+ ])('does not record evidence for $label', ({ route, status = 400, model = 'claude-opus-5', body = planError }) => {
+ recordClaudeRequestRoute(1, 's1', route);
+
+ drive(
+ ctx({ status, requestBody: Buffer.from(JSON.stringify({ model })) }),
+ Buffer.from(body),
+ );
+ expect(consumeClaudeGatewayOpusPlanMismatch('s1')).toBeNull();
+ });
+
+ it('invalidates old evidence when a later session request starts', () => {
+ recordClaudeRequestRoute(1, 's1', 'gateway');
+ drive(ctx(), Buffer.from(planError));
+ noteClaudeSessionRequest('s1', 2);
+
+ expect(consumeClaudeGatewayOpusPlanMismatch('s1')).toBeNull();
+ });
+
+ it('does not record a response that becomes stale before its body completes', () => {
+ recordClaudeRequestRoute(1, 's1', 'gateway');
+ const sink = createClaudeGatewayErrorObserver()(ctx());
+ expect(sink).toBeTruthy();
+ sink?.onData?.(Buffer.from(planError));
+ noteClaudeSessionRequest('s1', 2);
+ sink?.onEnd?.();
+
+ expect(consumeClaudeGatewayOpusPlanMismatch('s1')).toBeNull();
+ });
+});
diff --git a/apps/desktop/src/main/maker-host/__tests__/claudeSessionRouteObservation.test.ts b/apps/desktop/src/main/maker-host/__tests__/claudeSessionRouteObservation.test.ts
index 98358789ce..3a88438c1d 100644
--- a/apps/desktop/src/main/maker-host/__tests__/claudeSessionRouteObservation.test.ts
+++ b/apps/desktop/src/main/maker-host/__tests__/claudeSessionRouteObservation.test.ts
@@ -10,7 +10,12 @@
* - 请求无 session header → 正常路由, 不记录
*/
-import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import type { RequestTransformCtx, RoutingDecision } from '@cindy/anthropic-compat-proxy';
+
+const routeMocks = vi.hoisted(() => ({
+ resolveSessionRouteDecision: vi.fn<() => RoutingDecision | null>(() => null),
+}));
vi.mock('../logger-adapter', () => ({
createMakerLogger: () => ({
@@ -34,7 +39,7 @@ vi.mock('../claude-fast-mode-log', () => ({
}));
vi.mock('../provider-route', () => ({
// 默认路由会话: 显式供应商解析恒 null; 网关默认决策 = 有 key 才换。
- resolveSessionRouteDecision: vi.fn(() => null),
+ resolveSessionRouteDecision: routeMocks.resolveSessionRouteDecision,
gatewayDefaultRouteDecision: vi.fn((_agent: string, gatewayKey: string | null) =>
gatewayKey ? { headerOverride: { 'x-api-key': gatewayKey } } : null),
}));
@@ -44,15 +49,17 @@ import {
setClaudeProxyGatewayKeyReader,
setClaudeProxySessionIdResolver,
} from '../anthropic-compat-proxy-host';
+import { setSessionProvider, clearSessionProvider } from '../session-provider-store';
import {
readClaudeSessionRoute,
+ takeClaudeRequestRoute,
resetClaudeSessionRouteRegistryForTest,
} from '../claude-session-route-registry';
const SESSION_HEADER = { 'x-claude-code-session-id': 'sdk-abc' };
-function ctxWith(headers: Record<string, string>) {
- return { reqId: 1, method: 'POST', url: '/v1/messages', headers } as never;
+function ctxWith(headers: Record<string, string>, reqId = 1): RequestTransformCtx {
+ return { reqId, method: 'POST', url: '/v1/messages', headers };
}
describe('claude session route observation (routing transform ② 段)', () => {
@@ -61,10 +68,16 @@ describe('claude session route observation (routing transform ② 段)', () => {
beforeEach(() => {
resetClaudeSessionRouteRegistryForTest();
gatewayKey = null;
+ routeMocks.resolveSessionRouteDecision.mockReset();
+ routeMocks.resolveSessionRouteDecision.mockReturnValue(null);
setClaudeProxyGatewayKeyReader(() => gatewayKey);
setClaudeProxySessionIdResolver((sdkId) => (sdkId === 'sdk-abc' ? 'sess-1' : null));
});
+ afterEach(() => {
+ clearSessionProvider('sess-1');
+ });
+
it('records gateway for x-api-key (gateway-spawn) passthrough even when the live key is gone', () => {
const transform = createModelRoutingTransform();
// 本机 key 已清(gatewayKey=null), 但 child 冻结的 x-api-key 仍在请求上。
@@ -74,6 +87,7 @@ describe('claude session route observation (routing transform ② 段)', () => {
);
expect(decision).toBeNull(); // passthrough
expect(readClaudeSessionRoute('sess-1')).toBe('gateway');
+ expect(takeClaudeRequestRoute(1)).toEqual({ sessionId: 'sess-1', route: 'gateway' });
});
it('records gateway for oauth-spawn requests swapped onto the gateway key', () => {
@@ -97,6 +111,42 @@ describe('claude session route observation (routing transform ② 段)', () => {
expect(readClaudeSessionRoute('sess-1')).toBe('subscription');
});
+ it('records exact routes for explicitly selected XD and Anthropic providers', () => {
+ setSessionProvider('sess-1', 'xd');
+ routeMocks.resolveSessionRouteDecision.mockReturnValueOnce({
+ headerOverride: { 'x-api-key': 'sk-gw' },
+ });
+ expect(
+ createModelRoutingTransform()(
+ { model: 'claude-opus-4-8[1m]' },
+ { ...ctxWith(SESSION_HEADER), reqId: 21 } as never,
+ ),
+ ).toEqual({ headerOverride: { 'x-api-key': 'sk-gw' } });
+ expect(takeClaudeRequestRoute(21)).toEqual({ sessionId: 'sess-1', route: 'gateway' });
+
+ setSessionProvider('sess-1', 'anthropic');
+ routeMocks.resolveSessionRouteDecision.mockReturnValueOnce({
+ upstreamOverride: 'https://api.anthropic.com',
+ });
+ expect(
+ createModelRoutingTransform()(
+ { model: 'claude-opus-4-8[1m]' },
+ { ...ctxWith(SESSION_HEADER), reqId: 22 } as never,
+ ),
+ ).toEqual({ upstreamOverride: 'https://api.anthropic.com' });
+ expect(takeClaudeRequestRoute(22)).toEqual({ sessionId: 'sess-1', route: 'subscription' });
+ });
+
+ it('records gateway for an explicitly selected XD passthrough with a frozen child key', () => {
+ setSessionProvider('sess-1', 'xd');
+ const decision = createModelRoutingTransform()(
+ { model: 'claude-opus-4-8[1m]' },
+ ctxWith({ ...SESSION_HEADER, 'x-api-key': 'sk-frozen' }, 23),
+ );
+ expect(decision).toBeNull();
+ expect(takeClaudeRequestRoute(23)).toEqual({ sessionId: 'sess-1', route: 'gateway' });
+ });
+
it('does not record ambiguous no-key non-anthropic passthroughs', () => {
const transform = createModelRoutingTransform();
const decision = transform(
diff --git a/apps/desktop/src/main/maker-host/__tests__/claudeSessionRouteRegistry.test.ts b/apps/desktop/src/main/maker-host/__tests__/claudeSessionRouteRegistry.test.ts
index 6c72e146c6..8b8a6075fb 100644
--- a/apps/desktop/src/main/maker-host/__tests__/claudeSessionRouteRegistry.test.ts
+++ b/apps/desktop/src/main/maker-host/__tests__/claudeSessionRouteRegistry.test.ts
@@ -7,10 +7,14 @@
import { beforeEach, describe, expect, it, vi } from 'vitest';
import {
+ noteClaudeSessionRequest,
onClaudeSessionRouteChange,
+ readLatestClaudeSessionRequestId,
readClaudeSessionRoute,
+ recordClaudeRequestRoute,
recordClaudeSessionRoute,
resetClaudeSessionRouteRegistryForTest,
+ takeClaudeRequestRoute,
} from '../claude-session-route-registry';
describe('claude-session-route-registry', () => {
@@ -60,4 +64,38 @@ describe('claude-session-route-registry', () => {
recordClaudeSessionRoute('s1', 'gateway');
expect(listener).not.toHaveBeenCalled();
});
+
+ it('keeps exact request routes separate from the mutable session-latest route', () => {
+ recordClaudeRequestRoute(11, 's1', 'gateway');
+ recordClaudeRequestRoute(12, 's1', 'subscription');
+
+ expect(readLatestClaudeSessionRequestId('s1')).toBe(12);
+ expect(takeClaudeRequestRoute(11)).toEqual({ sessionId: 's1', route: 'gateway' });
+ expect(takeClaudeRequestRoute(12)).toEqual({ sessionId: 's1', route: 'subscription' });
+ expect(takeClaudeRequestRoute(11)).toBeNull();
+ });
+
+ it('marks a later unknown-route request as latest so older evidence becomes stale', () => {
+ recordClaudeRequestRoute(21, 's1', 'gateway');
+ noteClaudeSessionRequest('s1', 22);
+
+ expect(readLatestClaudeSessionRequestId('s1')).toBe(22);
+ expect(takeClaudeRequestRoute(21)).toEqual({ sessionId: 's1', route: 'gateway' });
+ });
+
+ it('does not let a late async route decision move the latest request backwards', () => {
+ noteClaudeSessionRequest('s1', 32);
+ noteClaudeSessionRequest('s1', 31);
+
+ expect(readLatestClaudeSessionRequestId('s1')).toBe(32);
+ });
+
+ it('bounds request-route storage when responses never arrive', () => {
+ for (let reqId = 1; reqId <= 257; reqId += 1) {
+ recordClaudeRequestRoute(reqId, `s${reqId}`, 'gateway');
+ }
+
+ expect(takeClaudeRequestRoute(1)).toBeNull();
+ expect(takeClaudeRequestRoute(257)).toEqual({ sessionId: 's257', route: 'gateway' });
+ });
});
diff --git a/apps/desktop/src/main/maker-host/__tests__/providerModelAutoRefresh.test.ts b/apps/desktop/src/main/maker-host/__tests__/providerModelAutoRefresh.test.ts
index b68427eb37..45e4994207 100644
--- a/apps/desktop/src/main/maker-host/__tests__/providerModelAutoRefresh.test.ts
+++ b/apps/desktop/src/main/maker-host/__tests__/providerModelAutoRefresh.test.ts
@@ -70,6 +70,25 @@ describe('provider model auto-refresh coordinator', () => {
]);
});
+ it('honors an explicit provider filter without waiting on unrelated sources', async () => {
+ const refreshProvider = vi.fn(async (_providerId: BuiltinRefreshableProviderId) => {});
+ const coordinator = createProviderModelRefreshCoordinator({
+ listProviders: async () => [
+ view('xd', true),
+ view('anthropic', true),
+ view('openai', true),
+ view('xai', true),
+ ],
+ refreshProvider,
+ now: () => 1_000,
+ log: { debug: vi.fn(), warn: vi.fn() },
+ });
+
+ await coordinator.requestAutoRefresh('startup', ['anthropic']);
+ expect(refreshProvider).toHaveBeenCalledOnce();
+ expect(refreshProvider).toHaveBeenCalledWith('anthropic');
+ });
+
it('manual refresh queues behind an automatic flight instead of being represented by it', async () => {
// 行为变更(PR #1076 review,与 forced startup 同一个不变量):手动刷新也是 forced
// 请求,撞上**非强制**在途时不再合并进去,而是排在它后面真跑一次。
diff --git a/apps/desktop/src/main/maker-host/account-provider-model-refresh.ts b/apps/desktop/src/main/maker-host/account-provider-model-refresh.ts
new file mode 100644
index 0000000000..1e4a7ae009
--- /dev/null
+++ b/apps/desktop/src/main/maker-host/account-provider-model-refresh.ts
@@ -0,0 +1,64 @@
+import type {
+ BuiltinRefreshableProviderId,
+ ProviderModelAutoRefreshTrigger,
+} from '../../shared/providerModelRefresh.js';
+
+interface AccountProviderModelRefreshLogger {
+ warn(message: string, meta?: Record<string, unknown>): void;
+}
+
+export interface AccountProviderModelRefreshDeps {
+ restartCodex(): Promise<void>;
+ shutdownCodexEnvironment(): Promise<void>;
+ refreshProviderModels(
+ trigger: ProviderModelAutoRefreshTrigger,
+ providerIds?: readonly BuiltinRefreshableProviderId[],
+ ): Promise<void>;
+ log: AccountProviderModelRefreshLogger;
+}
+
+/**
+ * 账号 DB 就绪后的模型发现屏障。
+ *
+ * Renderer 只有在本函数 settle 后才越过 LocalDbGate,因此新对话拿到的是本次账号
+ * 已经完成 Anthropic 发现的 provider catalog,不会在其清单还没回来时先按 XD
+ * 默认路由建出 provider_id=NULL 的 Opus 对话。其余来源仍强制刷新,但不阻塞主界面;
+ * 各步骤保持 best-effort,失败会留日志而不会把可用的本地 DB 误判成初始化失败。
+ */
+export async function refreshProviderModelsAfterAccountReady(
+ deps: AccountProviderModelRefreshDeps,
+): Promise<void> {
+ let codexRestarted = false;
+ try {
+ await deps.restartCodex();
+ codexRestarted = true;
+ } catch (error) {
+ deps.log.warn('restartCodexAfterAuthModeChange on account switch failed', {
+ error: error instanceof Error ? error.message : String(error),
+ });
+ }
+
+ if (codexRestarted) {
+ try {
+ await deps.shutdownCodexEnvironment();
+ } catch (error) {
+ deps.log.warn('shutdownCodexEnvironment on account switch failed', {
+ error: error instanceof Error ? error.message : String(error),
+ });
+ }
+ }
+
+ void deps.refreshProviderModels('startup', ['xd', 'openai', 'xai']).catch((error) => {
+ deps.log.warn('background provider model startup refresh failed', {
+ error: error instanceof Error ? error.message : String(error),
+ });
+ });
+
+ try {
+ await deps.refreshProviderModels('startup', ['anthropic']);
+ } catch (error) {
+ deps.log.warn('Anthropic model startup refresh failed', {
+ error: error instanceof Error ? error.message : String(error),
+ });
+ }
+}
diff --git a/apps/desktop/src/main/maker-host/anthropic-compat-proxy-host.ts b/apps/desktop/src/main/maker-host/anthropic-compat-proxy-host.ts
index f9a557cf77..879d2d820c 100644
--- a/apps/desktop/src/main/maker-host/anthropic-compat-proxy-host.ts
+++ b/apps/desktop/src/main/maker-host/anthropic-compat-proxy-host.ts
@@ -47,7 +47,13 @@ import {
composeResponseObservers,
createClaudeRateLimitHeadersObserver,
} from './claude-rate-limit-headers-observer.js';
-import { recordClaudeSessionRoute } from './claude-session-route-registry.js';
+import {
+ noteClaudeSessionRequest,
+ recordClaudeRequestRoute,
+ recordClaudeSessionRoute,
+ type ClaudeSessionBillingRoute,
+} from './claude-session-route-registry.js';
+import { createClaudeGatewayErrorObserver } from './claude-gateway-error-observer.js';
import { getSessionProvider } from './session-provider-store.js';
import {
gatewayDefaultRouteDecision,
@@ -154,13 +160,17 @@ export function createModelRoutingTransform(): RoutingTransform {
// 按 content-type 门控),GET / 非 JSON 请求不经过这里 —— 它们由响应侧的
// createClaudeSessionActivityResponseObserver 覆盖(观察器对所有响应生效)。
// 开销 = 一次 header 读 + 一次活跃会话表反解 + Map.set,非 per-token 路径。
- const activitySdkSessionId = ctx.headers['x-claude-code-session-id'];
- if (activitySdkSessionId) {
+ const sdkSessionId = ctx.headers['x-claude-code-session-id'];
+ const sessionId = sdkSessionId && _resolveCcSessionId
+ ? _resolveCcSessionId(sdkSessionId)
+ : null;
+ if (sdkSessionId) {
recordClaudeApiActivity(
- activitySdkSessionId,
- _resolveCcSessionId ? _resolveCcSessionId(activitySdkSessionId) : null,
+ sdkSessionId,
+ sessionId,
);
}
+ if (sessionId) noteClaudeSessionRequest(sessionId, ctx.reqId);
if (!isPlainObject(body)) return null;
const wireModel = typeof body.model === 'string' ? body.model : '';
@@ -180,10 +190,8 @@ export function createModelRoutingTransform(): RoutingTransform {
}
// 会话态(思维深度 / Fast)在决策点解析后**闭包**进 handler —— CC 不会把 bridge 模型的
// effort / fast 放进请求体,而引擎保持零会话概念,不走任何伪 header。
- const sdkSessionId = ctx.headers['x-claude-code-session-id'];
- const xdtSessionId = sdkSessionId && _resolveCcSessionId ? _resolveCcSessionId(sdkSessionId) : null;
- const effort = xdtSessionId ? getSessionEffort(xdtSessionId) : null;
- const fast = xdtSessionId ? getSessionFastMode(xdtSessionId) : false;
+ const effort = sessionId ? getSessionEffort(sessionId) : null;
+ const fast = sessionId ? getSessionFastMode(sessionId) : false;
return {
localHandler: (args) =>
bridgeHandler.handle({ ...args, prefs: { reasoningEffort: effort ?? undefined, fast } }),
@@ -191,19 +199,27 @@ export function createModelRoutingTransform(): RoutingTransform {
}
const gatewayKey = _readGatewayKey();
+ const selectedProviderId = sessionId ? getSessionProvider(sessionId) : null;
// ① 该会话显式选了供应商 → 据 catalog 统一路由。
// x-claude-code-session-id = cc sdkSessionId,经注入的 resolver 反解成 xdt sessionId。
- const sdkSessionId = ctx.headers['x-claude-code-session-id'];
- const sessionId = sdkSessionId && _resolveCcSessionId
- ? _resolveCcSessionId(sdkSessionId)
- : null;
if (sessionId) {
// wireModel 传给 scope 门:cc 内部辅助调用(权限 auto 分类器等 claude-* 小模型请求)
// 不在订阅直连供应商(xai / openai-cc)声明的 modelPrefixes 范围内 → 返回 null,
// 落到下方 ② 段 spawn 默认路由,分类器照常走网关/直连(issue #886)。
const perSession = resolveSessionRouteDecision(sessionId, 'claude-code', gatewayKey, wireModel);
- if (perSession) return perSession;
+ const recordSelectedRoute = <T extends object | null>(route: T): T => {
+ if (route && (selectedProviderId === 'xd' || selectedProviderId === 'anthropic')) {
+ recordClaudeRequestRoute(
+ ctx.reqId,
+ sessionId,
+ selectedProviderId === 'xd' ? 'gateway' : 'subscription',
+ );
+ }
+ return route;
+ };
+ if (perSession instanceof Promise) return perSession.then(recordSelectedRoute);
+ if (perSession) return recordSelectedRoute(perSession);
}
// ② 未显式选供应商 → 据请求凭证判定 spawn 形态(见上方注释)。
@@ -211,6 +227,11 @@ export function createModelRoutingTransform(): RoutingTransform {
// providerId=null 时读)——显式选了供应商但被 scope 门放下来的辅助请求(如 xai 会话
// 的 claude-* 分类器调用)不该往表里写死记录。
const recordDefaultRoute = sessionId !== null && getSessionProvider(sessionId) == null;
+ const recordResolvedDefaultRoute = (route: ClaudeSessionBillingRoute): void => {
+ if (!recordDefaultRoute) return;
+ recordClaudeSessionRoute(sessionId, route);
+ recordClaudeRequestRoute(ctx.reqId, sessionId, route);
+ };
// provider-oauth spawn 的占位 key **不是可用凭证**:scope 门放下来的辅助请求
// (如 openai / xai 来源 cc 会话里 CLI 自发的 claude-* 权限分类器调用)带着它
// passthrough 会在网关吃确定性 401 → 误触发 auto→ask 降级(#831)。与 codex
@@ -221,13 +242,19 @@ export function createModelRoutingTransform(): RoutingTransform {
apiKeyHeader !== null && apiKeyHeader !== CLAUDE_PROVIDER_AUTH_PLACEHOLDER_KEY;
if (hasUsableApiKey) {
// gateway-spawn:自带网关 key,passthrough。
- if (recordDefaultRoute) recordClaudeSessionRoute(sessionId, 'gateway');
+ if (sessionId && selectedProviderId === 'xd') {
+ // 显式 XD 会话在 live gateway key 被清除后,仍可能携带 spawn 时冻结的 x-api-key。
+ // resolveSessionRouteDecision 会因缺 key 返回 null,但这条 passthrough 仍实际进入 XD Gateway。
+ recordClaudeRequestRoute(ctx.reqId, sessionId, 'gateway');
+ } else {
+ recordResolvedDefaultRoute('gateway');
+ }
return null;
}
const decision = gatewayDefaultRouteDecision('claude-code', gatewayKey);
if (decision) {
// oauth-spawn 默认:全量换网关 key(防订阅 token 泄漏到网关)。
- if (recordDefaultRoute) recordClaudeSessionRoute(sessionId, 'gateway');
+ recordResolvedDefaultRoute('gateway');
return decision;
}
if (apiKeyHeader !== null) {
@@ -239,7 +266,7 @@ export function createModelRoutingTransform(): RoutingTransform {
// 没网关 key:Anthropic 模型只能直连(唯一出路),其余 passthrough + 记一条诊断。
// 判据 = 前缀地板 ∪ 目录 anthropic 供应商模型集合(新家族改 OSS 目录即可,无需发版)。
if (isAnthropicWireModel(wireModel, anthropicCatalogModelIds(getActiveCatalog()))) {
- if (recordDefaultRoute) recordClaudeSessionRoute(sessionId, 'subscription');
+ recordResolvedDefaultRoute('subscription');
return { upstreamOverride: ANTHROPIC_DIRECT_UPSTREAM };
}
if (wireModel) {
@@ -282,6 +309,7 @@ export async function ensureAnthropicCompatProxyReady(): Promise<void> {
createClaudeSubagentUsageResponseObserver(),
createClaudeFastModeResponseObserver(log),
createClaudeRateLimitHeadersObserver(),
+ createClaudeGatewayErrorObserver(),
// 后台活动检测:响应流按节流刷新活动时刻(覆盖长 SSE 跨过 turn 结束点仍在吐字的场景)。
createClaudeSessionActivityResponseObserver((sdkSessionId) =>
_resolveCcSessionId ? _resolveCcSessionId(sdkSessionId) : null,
diff --git a/apps/desktop/src/main/maker-host/claude-gateway-error-observer.ts b/apps/desktop/src/main/maker-host/claude-gateway-error-observer.ts
new file mode 100644
index 0000000000..0a86620785
--- /dev/null
+++ b/apps/desktop/src/main/maker-host/claude-gateway-error-observer.ts
@@ -0,0 +1,103 @@
+/**
+ * Claude XD Gateway 错误观察器。
+ *
+ * 路由 transform 与响应 observer 通过 proxy reqId 关联,只有同一个 Opus 请求
+ * 确认走 XD Gateway 且收到特定 400 套餐错误时才留下待消费证据。terminal event
+ * 到达时还要求它仍是该会话最新请求;后续 retry / tool 请求会使旧证据失效。
+ */
+
+import type { ResponseObserver, ResponseObserverCtx } from '@cindy/anthropic-compat-proxy';
+
+import {
+ CLAUDE_GATEWAY_OPUS_PLAN_MISMATCH_REASON,
+ classifyClaudeGatewayError,
+} from '../../shared/claudeGatewayError.js';
+import {
+ readLatestClaudeSessionRequestId,
+ takeClaudeRequestRoute,
+} from './claude-session-route-registry.js';
+import { decodeUpstreamErrorBody } from './provider-upstream-error-observer.js';
+
+const MAX_ERROR_BODY_BYTES = 16 * 1024;
+const MAX_PENDING_SESSIONS = 128;
+
+interface PendingMismatch {
+ reqId: number;
+ reason: typeof CLAUDE_GATEWAY_OPUS_PLAN_MISMATCH_REASON;
+}
+
+const pendingMismatches = new Map<string, PendingMismatch>();
+
+function requestModel(requestBody: Buffer): string {
+ try {
+ const parsed = JSON.parse(requestBody.toString('utf-8')) as { model?: unknown };
+ return typeof parsed.model === 'string' ? parsed.model : '';
+ } catch {
+ return '';
+ }
+}
+
+function recordPendingMismatch(sessionId: string, mismatch: PendingMismatch): void {
+ pendingMismatches.delete(sessionId);
+ pendingMismatches.set(sessionId, mismatch);
+ while (pendingMismatches.size > MAX_PENDING_SESSIONS) {
+ const oldestSessionId = pendingMismatches.keys().next().value as string | undefined;
+ if (oldestSessionId === undefined) break;
+ pendingMismatches.delete(oldestSessionId);
+ }
+}
+
+export function createClaudeGatewayErrorObserver(): ResponseObserver {
+ return (ctx: ResponseObserverCtx) => {
+ const requestRoute = takeClaudeRequestRoute(ctx.reqId);
+ if (!requestRoute || requestRoute.route !== 'gateway' || ctx.status !== 400) return null;
+
+ const modelId = requestModel(ctx.requestBody);
+ if (!modelId.startsWith('claude-opus-')) return null;
+
+ const chunks: Buffer[] = [];
+ let size = 0;
+ return {
+ onData: (chunk: Buffer) => {
+ if (size >= MAX_ERROR_BODY_BYTES) return;
+ const remaining = MAX_ERROR_BODY_BYTES - size;
+ chunks.push(chunk.subarray(0, remaining));
+ size += Math.min(chunk.length, remaining);
+ },
+ onEnd: () => {
+ const encoding = ctx.responseHeaders['content-encoding'];
+ const bodyText = decodeUpstreamErrorBody(
+ Buffer.concat(chunks, size),
+ typeof encoding === 'string' ? encoding : undefined,
+ );
+ const reason = classifyClaudeGatewayError({
+ modelId,
+ requestRoute: requestRoute.route,
+ status: ctx.status,
+ error: bodyText,
+ });
+ if (
+ reason &&
+ readLatestClaudeSessionRequestId(requestRoute.sessionId) === ctx.reqId
+ ) {
+ recordPendingMismatch(requestRoute.sessionId, { reqId: ctx.reqId, reason });
+ }
+ },
+ onError: () => {},
+ };
+ };
+}
+
+/** terminal error 转发点一次性消费;后续请求已开始时保守放弃旧证据。 */
+export function consumeClaudeGatewayOpusPlanMismatch(
+ sessionId: string,
+): typeof CLAUDE_GATEWAY_OPUS_PLAN_MISMATCH_REASON | null {
+ const pending = pendingMismatches.get(sessionId) ?? null;
+ pendingMismatches.delete(sessionId);
+ if (!pending || readLatestClaudeSessionRequestId(sessionId) !== pending.reqId) return null;
+ return pending.reason;
+}
+
+export function resetClaudeGatewayErrorObserverForTest(): void {
+ pendingMismatches.clear();
+}
diff --git a/apps/desktop/src/main/maker-host/claude-session-route-registry.ts b/apps/desktop/src/main/maker-host/claude-session-route-registry.ts
index 86366dc3ef..d71dc8417a 100644
--- a/apps/desktop/src/main/maker-host/claude-session-route-registry.ts
+++ b/apps/desktop/src/main/maker-host/claude-session-route-registry.ts
@@ -1,33 +1,82 @@
/**
- * claude-session-route-registry —— cc 默认路由会话的「生效计费路由」观察表。
+ * claude-session-route-registry —— cc 请求路由观察表。
*
* proxy 的 routingTransform 是路由真值点:每个默认路由请求在那里被判定成
* 走网关(gateway-spawn passthrough / oauth-spawn 换网关 key)还是直连
- * api.anthropic.com 走订阅。本模块在决策点旁路记录 sessionId → 路由,
- * 让 renderer 的计费形态 chip 拿到**会话实际流量的路由**,而不是用全局
+ * api.anthropic.com 走订阅。本模块在决策点旁路记录两份状态:
+ * - sessionId → 最近路由,让 renderer 的计费形态 chip 拿到实际计费形态;
+ * - reqId → 该请求的 sessionId + 精确路由,让响应观察器按请求归因错误。
+ * 前者不能用于错误归因:后续请求可能在旧请求的终态事件到达前覆盖它。
+ * 两份状态都来自实际路由决策,而不是用全局
* 活性凭证状态(网关 key / OAuth 连接态)重算 —— 后者会与 spawn 时冻结的
* 子进程凭证发散(典型:gateway-spawn 会话跑着时连上 OAuth 并清掉网关 key,
* child 仍拿冻结的 x-api-key 走网关,活性重算却会误判成订阅)。
*
* 语义:
- * - 只记「未显式选供应商」的默认路由请求(显式选供应商的会话由 providerId
- * 直接驱动 chip 形态, 不需要观察)。
- * - 记录的是**最近一个请求**的生效路由;凭证中途变化后, 下一个请求会在
+ * - sessionId → 路由只记「未显式选供应商」的默认路由请求(显式供应商的会话由
+ * providerId 直接驱动 chip 形态, 不需要用这份 session 记录)。
+ * - reqId → 路由同时覆盖内置 XD / Anthropic 的显式请求,因为错误归因必须知道
+ * 产生响应的那一笔请求究竟去了哪里。
+ * - session 记录的是**最近一个请求**的生效路由;凭证中途变化后, 下一个请求会在
* transform 里按新状态重判并自动纠正记录。
* - 会话尚未发过请求(新会话 / app 重启后未活动)→ 无记录, 消费方回落
* 活性启发式 —— 此时下一次 spawn 恰按当前凭证决定, 启发式就是正确预测。
*
* 热路径纪律(规则 10):record 每请求调用, 只做 Map 读写 + 同值短路;
* listener 仅在路由值变化时触发(每会话生命周期通常一次)。
- * 条目随 app 生命周期常驻不逐出 —— 每条 ≈ 两个短字符串, 数千会话也可忽略。
+ * 会话路由随 app 生命周期常驻;请求路由会在响应观察时消费,并有容量上限兜住
+ * 连接失败等永远收不到响应的请求。
*/
export type ClaudeSessionBillingRoute = 'gateway' | 'subscription';
+export interface ClaudeRequestRoute {
+ sessionId: string;
+ route: ClaudeSessionBillingRoute;
+}
+
type RouteChangeListener = (sessionId: string, route: ClaudeSessionBillingRoute) => void;
const routes = new Map<string, ClaudeSessionBillingRoute>();
const listeners = new Set<RouteChangeListener>();
+const requestRoutes = new Map<number, ClaudeRequestRoute>();
+const latestRequestIds = new Map<string, number>();
+const MAX_REQUEST_ROUTES = 256;
+
+/** 每个带会话标头的请求一开始就调用;未知路由也会使旧错误证据失效。 */
+export function noteClaudeSessionRequest(sessionId: string, reqId: number): void {
+ const previousReqId = latestRequestIds.get(sessionId);
+ if (previousReqId === undefined || reqId > previousReqId) {
+ latestRequestIds.set(sessionId, reqId);
+ }
+}
+
+/** 路由决策点记录该请求的精确上游类别,供响应观察器按 reqId 消费。 */
+export function recordClaudeRequestRoute(
+ reqId: number,
+ sessionId: string,
+ route: ClaudeSessionBillingRoute,
+): void {
+ noteClaudeSessionRequest(sessionId, reqId);
+ requestRoutes.set(reqId, { sessionId, route });
+ while (requestRoutes.size > MAX_REQUEST_ROUTES) {
+ const oldestReqId = requestRoutes.keys().next().value as number | undefined;
+ if (oldestReqId === undefined) break;
+ requestRoutes.delete(oldestReqId);
+ }
+}
+
+/** 响应观察器用;一次性消费,避免已完成请求常驻。 */
+export function takeClaudeRequestRoute(reqId: number): ClaudeRequestRoute | null {
+ const route = requestRoutes.get(reqId) ?? null;
+ requestRoutes.delete(reqId);
+ return route;
+}
+
+/** 终态归因只接受仍是本会话最新请求的证据。 */
+export function readLatestClaudeSessionRequestId(sessionId: string): number | null {
+ return latestRequestIds.get(sessionId) ?? null;
+}
/** proxy transform 决策点旁路调用;同值幂等(不重复通知)。 */
export function recordClaudeSessionRoute(
@@ -62,4 +111,6 @@ export function onClaudeSessionRouteChange(listener: RouteChangeListener): () =>
export function resetClaudeSessionRouteRegistryForTest(): void {
routes.clear();
listeners.clear();
+ requestRoutes.clear();
+ latestRequestIds.clear();
}
diff --git a/apps/desktop/src/main/maker-host/provider-model-auto-refresh.ts b/apps/desktop/src/main/maker-host/provider-model-auto-refresh.ts
index 1f09c54b08..61216ce55f 100644
--- a/apps/desktop/src/main/maker-host/provider-model-auto-refresh.ts
+++ b/apps/desktop/src/main/maker-host/provider-model-auto-refresh.ts
@@ -32,7 +32,10 @@ export interface ProviderModelAutoRefreshDeps {
}
export interface ProviderModelRefreshCoordinator {
- requestAutoRefresh(trigger: ProviderModelAutoRefreshTrigger): Promise<void>;
+ requestAutoRefresh(
+ trigger: ProviderModelAutoRefreshTrigger,
+ providerIds?: readonly BuiltinRefreshableProviderId[],
+ ): Promise<void>;
refreshManually(providerId: BuiltinRefreshableProviderId): Promise<void>;
resetCooldowns(providerId?: BuiltinRefreshableProviderId): void;
}
@@ -181,7 +184,7 @@ export function createProviderModelRefreshCoordinator(
}
return {
- async requestAutoRefresh(trigger): Promise<void> {
+ async requestAutoRefresh(trigger, providerIds): Promise<void> {
syncScope();
let providers: ProviderView[];
try {
@@ -206,7 +209,8 @@ export function createProviderModelRefreshCoordinator(
}
}
- const ids = BUILTIN_REFRESHABLE_PROVIDER_IDS.filter((id) => connectedIds.has(id));
+ const requestedIds = providerIds ?? BUILTIN_REFRESHABLE_PROVIDER_IDS;
+ const ids = requestedIds.filter((id) => connectedIds.has(id));
// 启动期无视冷却(见 `'startup'` trigger 注释);in-flight 合并仍生效,所以并发的
// 启动触发与手动刷新不会各起一次 codex app-server。
const force = isForcedProviderModelAutoRefreshTrigger(trigger);
@@ -257,8 +261,9 @@ export function resetProviderModelAutoRefreshCooldowns(
*/
export async function requestProviderModelAutoRefresh(
trigger: ProviderModelAutoRefreshTrigger,
+ providerIds?: readonly BuiltinRefreshableProviderId[],
): Promise<void> {
- await configuredCoordinator?.requestAutoRefresh(trigger);
+ await configuredCoordinator?.requestAutoRefresh(trigger, providerIds);
}
export async function refreshProviderModelsManually(
diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.ts
index a5d64a30cc..5a2aa07d7c 100644
--- a/apps/desktop/src/main/maker-ipc/register.ts
+++ b/apps/desktop/src/main/maker-ipc/register.ts
@@ -501,6 +501,7 @@ import {
setClaudeBackgroundActivityBroadcaster,
} from '../maker-host/claude-session-background-activity.js';
import { readClaudeSessionRoute } from '../maker-host/claude-session-route-registry.js';
+import { consumeClaudeGatewayOpusPlanMismatch } from '../maker-host/claude-gateway-error-observer.js';
import { setLiveCcSessionBridge } from '../maker-host/claude-transcript-relocation.js';
import {
CredentialModeSwitchBusyError,
@@ -2668,7 +2669,27 @@ export function wireSessionToIpc(session: ReturnType<Maker['getSession']>): void
// 转发事件到所有 window。interaction_dismissed 单独走专用 channel,
// 让 renderer chat store 不必扫所有 vendor-raw 找它。
registration.disposers.push(session.onEvent((event: AgentEvent) => {
- const broadcastEvent = redactEventForRenderer(event);
+ let attributedEvent = event;
+ if (event.type === 'error' && isTerminalTurnErrorEvent(event)) {
+ const reason = !session.remoteHostId && session.agentKind === 'claude-code'
+ ? consumeClaudeGatewayOpusPlanMismatch(session.id)
+ : null;
+ if (reason) {
+ const eventData = event.data && typeof event.data === 'object' && !Array.isArray(event.data)
+ ? (event.data as Record<string, unknown>)
+ : {};
+ attributedEvent = {
+ ...event,
+ data: { ...eventData, reason },
+ };
+ log.warn('Claude Opus plan error attributed to XD Gateway route', {
+ sessionId: session.id,
+ model: session.model,
+ reason,
+ });
+ }
+ }
+ const broadcastEvent = redactEventForRenderer(attributedEvent);
if (event.type === 'interaction_dismissed') {
const data = event.data as { requestId?: unknown; reason?: unknown };
if (typeof data.requestId === 'string') {
@@ -2812,8 +2833,8 @@ export function wireSessionToIpc(session: ReturnType<Maker['getSession']>): void
if (event.source === 'claude-code' || event.source === 'codex') {
turnModelPromiseBySession.delete(session.id);
}
- const errData = event.type === 'error'
- ? (event.data as
+ const errData = attributedEvent.type === 'error'
+ ? (attributedEvent.data as
| { message?: unknown; reason?: unknown; sdkError?: unknown; errorStatus?: unknown }
| undefined)
: undefined;
@@ -3015,14 +3036,18 @@ export function wireSessionToIpc(session: ReturnType<Maker['getSession']>): void
) {
onTurnErrorEvent(
session.id,
- event.data as { message?: unknown; reason?: unknown; sdkError?: unknown } | null,
+ attributedEvent.data as {
+ message?: unknown;
+ reason?: unknown;
+ sdkError?: unknown;
+ } | null,
eventAgentMeta,
);
}
// 压住的错误详情必须在这里存一份:决策推迟场景下 onResumableTurnError 还没被调用过
// (它自己那份 set 发生在接管成立时),不存就无从补落。同 clientId 内容,覆盖无害。
if (autoResumeSuppressesPersist) {
- autoResumeBookkeeping.stashSuppressedError(session.id, event.data);
+ autoResumeBookkeeping.stashSuppressedError(session.id, attributedEvent.data);
}
// deferred 路径保存 turn 开始时刻:isRemoteAuthRetry 时 onTurnErrorEvent 被跳过,
// renderer 会稍后调 persistTurnErrorDeferred IPC。在 resetTurnPersistState 清掉
diff --git a/apps/desktop/src/renderer/components/chat/ErrorBanner.tsx b/apps/desktop/src/renderer/components/chat/ErrorBanner.tsx
index c6707f66cf..bbddc57034 100644
--- a/apps/desktop/src/renderer/components/chat/ErrorBanner.tsx
+++ b/apps/desktop/src/renderer/components/chat/ErrorBanner.tsx
@@ -30,6 +30,7 @@ import { cn } from '@/lib/utils';
import { isInvalidEncryptedContentError } from '@/utils/encryptedContentError';
import { isNetworkishErrorMessage, parseReconnectAttemptMessage } from '@/utils/networkError';
import { isOverloadErrorMessage, parseOverloadRetryProgress } from '@/utils/overloadError';
+import { CLAUDE_GATEWAY_OPUS_PLAN_MISMATCH_REASON } from '../../../shared/claudeGatewayError';
interface ErrorBannerProps {
error: string;
@@ -59,6 +60,9 @@ interface ErrorBannerProps {
/** 当前会话显式选择的模型来源。OpenAI 重连只能处理 openai / 无显式来源的历史会话;
* 其它 provider 的 OAuth 错误必须留给对应来源处理。 */
providerId?: string | null;
+ /** XD Gateway 返回了误导性的 Claude Pro/Opus 套餐错误时,切到已连接的
+ * Claude.ai 订阅来源并重试本轮。未连接 Anthropic 时不提供此操作。 */
+ onSwitchToClaudeSubscription?: () => Promise<void>;
silentEncryptedRetryEnabled?: boolean;
onForkStripEncrypted?: () => void | Promise<void>;
forkStripEncryptedRunning?: boolean;
@@ -83,6 +87,7 @@ export function ErrorBanner({
deviceLinkDeviceId,
modelId,
providerId,
+ onSwitchToClaudeSubscription,
silentEncryptedRetryEnabled = false,
onForkStripEncrypted,
forkStripEncryptedRunning = false,
@@ -197,8 +202,10 @@ export function ErrorBanner({
// scheduler / goal)失败时没有安全的 recovery target,errorRetryText 会是 null;
// 此时不能一边隐藏按钮,一边仍提示用户“点击重试”。
const isSilentStopExhausted = errorReason === 'silent-stop-exhausted';
+ const isClaudeGatewayOpusPlanMismatch = errorReason === CLAUDE_GATEWAY_OPUS_PLAN_MISMATCH_REASON;
const hideRetry =
isSilentStopExhausted ||
+ isClaudeGatewayOpusPlanMismatch ||
isCodexThreadStale ||
showInvalidEncryptedContentRecovery ||
(isCodexRemoteAuthMissing && !syncedSinceError) ||
@@ -206,8 +213,10 @@ export function ErrorBanner({
isCodexLocalOAuthAuthMissing;
const safeRetryText = !hideRetry && retryText ? retryText : null;
const [showRawNetworkError, setShowRawNetworkError] = useState(false);
+ const [switchingClaudeSubscription, setSwitchingClaudeSubscription] = useState(false);
useEffect(() => {
setShowRawNetworkError(false);
+ setSwitchingClaudeSubscription(false);
}, [error]);
// hasSpecialGuidance: 是否命中下面任一「有专属可操作指引」的特殊分支。用一个在
@@ -231,6 +240,8 @@ export function ErrorBanner({
: t('chat.errorBanner.codexSessionExpired');
} else if (isCodexLocalOAuthAuthMissing) {
displayError = t('chat.errorBanner.codexAuthMissingLocal');
+ } else if (isClaudeGatewayOpusPlanMismatch) {
+ displayError = t('chat.errorBanner.claudeGatewayOpusPlanMismatch');
} else if (isOverloadError) {
// 服务过载:上游模型没有可用容量。原始英文("Selected model is at capacity")
// 对用户没有行动价值,换成友好文案 + 明确的下一步;原始错误折叠可查。
@@ -288,6 +299,20 @@ export function ErrorBanner({
(isNetworkishError && !isRecoverable) ||
(isOverloadError && !overloadRetryProgress));
+ const handleSwitchToClaudeSubscription = async (): Promise<void> => {
+ if (!onSwitchToClaudeSubscription || switchingClaudeSubscription) return;
+ setSwitchingClaudeSubscription(true);
+ try {
+ await onSwitchToClaudeSubscription();
+ } catch (e) {
+ const ipcErr = extractIpcError(e);
+ const msg = ipcErr?.message ?? (e instanceof Error ? e.message : String(e));
+ toast.error(t('chat.errorBanner.claudeSubscriptionSwitchFailed', { msg }));
+ } finally {
+ setSwitchingClaudeSubscription(false);
+ }
+ };
+
// 走跟 Settings/RemoteHostDetail 同款的 check → confirm → sync 三步:
// 1. checkCodexAuth: 探远端是否已有 auth.json (有则要 confirm 覆盖)
// 2. 弹 confirm dialog: 显安全警告 + "共享 SSH 账号 = 凭证可能被偷"
@@ -382,7 +407,7 @@ export function ErrorBanner({
{t('chat.errorBanner.budgetModelHint')}
</span>
)}
- {(isNetworkishError || isOverloadError) && (
+ {(isNetworkishError || isOverloadError || isClaudeGatewayOpusPlanMismatch) && (
// 网络类与过载类的原始错误折叠可查:友好文案替换了原文,但排障(端口/URL/
// errno/上游原话)仍需要原文,点击展开。新增控件走 --error-fg token(规则 16;
// 本组件其余 red-600/400 为历史存量,error 属语义豁免色但新代码仍走 token)。
@@ -421,6 +446,25 @@ export function ErrorBanner({
{t('chat.errorBanner.codexSessionExpiredLogin')}
</button>
)}
+ {isClaudeGatewayOpusPlanMismatch && onSwitchToClaudeSubscription && (
+ <button
+ type="button"
+ onClick={() => void handleSwitchToClaudeSubscription()}
+ disabled={switchingClaudeSubscription}
+ className={cn(
+ 'shrink-0 flex select-none items-center gap-1 text-xs font-medium',
+ 'text-[var(--error-fg-strong)]',
+ 'hover:opacity-70 transition-opacity',
+ 'disabled:cursor-not-allowed disabled:opacity-50',
+ )}
+ title={t('chat.errorBanner.switchClaudeSubscriptionTitle')}
+ >
+ <Spinner icon={RefreshCw} size={12} spinning={switchingClaudeSubscription} />
+ {switchingClaudeSubscription
+ ? t('chat.errorBanner.switchingClaudeSubscription')
+ : t('chat.errorBanner.switchClaudeSubscription')}
+ </button>
+ )}
{isCodexRemoteAuthMissing && !syncedSinceError && (
<button
type="button"
diff --git a/apps/desktop/src/renderer/components/chat/ErrorMessageCard.tsx b/apps/desktop/src/renderer/components/chat/ErrorMessageCard.tsx
index f55a495f7d..513d63d229 100644
--- a/apps/desktop/src/renderer/components/chat/ErrorMessageCard.tsx
+++ b/apps/desktop/src/renderer/components/chat/ErrorMessageCard.tsx
@@ -21,6 +21,7 @@ import { AlertCircle } from 'lucide-react';
import { useTranslation } from 'react-i18next';
import { decodeRemoteErrorMessage } from '../../lib/makerChatStore';
import { UPSTREAM_OVERLOAD_REASON } from '@/utils/overloadError';
+import { CLAUDE_GATEWAY_OPUS_PLAN_MISMATCH_REASON } from '../../../shared/claudeGatewayError';
/** 稳定 reason key → i18n。error-tail-banner(CCAgentSessionView)复用同一映射,
* 保证尾部可操作红条与历史静态卡展示同一段文案。 */
@@ -38,6 +39,7 @@ export const ERROR_REASON_I18N_KEYS: Record<string, string> = {
// 注释说的那个一致性: 不映射的话同一条过载错误会出现「尾部红条本地化、历史静态
// 卡英文原文」的分裂 —— 而 codex 的过载原文还会随版本改措辞。
[UPSTREAM_OVERLOAD_REASON]: 'chat.errorBanner.overloadBusyNoRetry',
+ [CLAUDE_GATEWAY_OPUS_PLAN_MISMATCH_REASON]: 'chat.errorBanner.claudeGatewayOpusPlanMismatch',
};
export function ErrorMessageCard({ message, reason }: { message: string; reason?: string }) {
diff --git a/apps/desktop/src/renderer/components/chat/InterruptedTurnBanner.tsx b/apps/desktop/src/renderer/components/chat/InterruptedTurnBanner.tsx
index 828de11be2..0bfa33d0aa 100644
--- a/apps/desktop/src/renderer/components/chat/InterruptedTurnBanner.tsx
+++ b/apps/desktop/src/renderer/components/chat/InterruptedTurnBanner.tsx
@@ -116,6 +116,7 @@ export function ErrorTailErrorBanner({
deviceLinkDeviceId,
modelId,
providerId,
+ onSwitchToClaudeSubscription,
silentEncryptedRetryEnabled,
onForkStripEncrypted,
forkStripEncryptedRunning,
@@ -134,6 +135,7 @@ export function ErrorTailErrorBanner({
deviceLinkDeviceId?: string | null;
modelId?: string;
providerId?: string | null;
+ onSwitchToClaudeSubscription?: () => Promise<void>;
silentEncryptedRetryEnabled?: boolean;
onForkStripEncrypted?: () => void | Promise<void>;
forkStripEncryptedRunning?: boolean;
@@ -155,6 +157,7 @@ export function ErrorTailErrorBanner({
deviceLinkDeviceId={deviceLinkDeviceId}
modelId={modelId}
providerId={providerId}
+ onSwitchToClaudeSubscription={onSwitchToClaudeSubscription}
silentEncryptedRetryEnabled={silentEncryptedRetryEnabled}
onForkStripEncrypted={onForkStripEncrypted}
forkStripEncryptedRunning={forkStripEncryptedRunning}
diff --git a/apps/desktop/src/renderer/components/chat/__tests__/ErrorBannerCodexOAuth.test.tsx b/apps/desktop/src/renderer/components/chat/__tests__/ErrorBannerCodexOAuth.test.tsx
index 8aaf9936c3..6c5047a277 100644
--- a/apps/desktop/src/renderer/components/chat/__tests__/ErrorBannerCodexOAuth.test.tsx
+++ b/apps/desktop/src/renderer/components/chat/__tests__/ErrorBannerCodexOAuth.test.tsx
@@ -6,6 +6,7 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';
import { ErrorBanner } from '../ErrorBanner';
import { useCodexAuth } from '@/hooks/useCodexAuth';
import { useCodexSessionExpiredPrompt } from '@/hooks/useCodexSessionExpiredPrompt';
+import { CLAUDE_GATEWAY_OPUS_PLAN_MISMATCH_REASON } from '../../../../shared/claudeGatewayError';
type AuthStateChangedPayload = {
agentKind: 'claude-code' | 'codex';
@@ -551,14 +552,103 @@ describe('ErrorBanner OpenAI connection recovery', () => {
expect(onContinueAfterUsageReset).toHaveBeenCalledOnce();
rerender(
+ <ErrorBanner error="A normal failure" retryText="retry this turn" onRetry={vi.fn()} />,
+ );
+ expect(
+ screen.queryByRole('button', { name: 'chat.errorBanner.continueAfterReset' }),
+ ).toBeNull();
+ });
+
+ it('replaces the misleading Claude Pro error with its XD Gateway attribution', () => {
+ render(
<ErrorBanner
- error="A normal failure"
+ error="Claude Opus is not available with the Claude Pro plan. Run /logout and /login."
+ errorReason={CLAUDE_GATEWAY_OPUS_PLAN_MISMATCH_REASON}
retryText="retry this turn"
onRetry={vi.fn()}
+ agentKind="cc"
+ modelId="claude-opus-5"
/>,
);
+
+ expect(screen.getByText('chat.errorBanner.claudeGatewayOpusPlanMismatch')).toBeTruthy();
+ expect(screen.queryByRole('button', { name: 'chat.errorBanner.retry' })).toBeNull();
expect(
- screen.queryByRole('button', { name: 'chat.errorBanner.continueAfterReset' }),
+ screen.queryByRole('button', { name: 'chat.errorBanner.switchClaudeSubscription' }),
).toBeNull();
});
+
+ it('switches the conversation to Claude.ai through the explicit recovery action', async () => {
+ const switching = deferred<void>();
+ const onSwitchToClaudeSubscription = vi.fn(() => switching.promise);
+ render(
+ <ErrorBanner
+ error="Claude Opus is not available with the Claude Pro plan."
+ errorReason={CLAUDE_GATEWAY_OPUS_PLAN_MISMATCH_REASON}
+ retryText="retry this turn"
+ onRetry={vi.fn()}
+ onSwitchToClaudeSubscription={onSwitchToClaudeSubscription}
+ agentKind="cc"
+ modelId="claude-opus-5"
+ />,
+ );
+
+ fireEvent.click(
+ screen.getByRole('button', { name: 'chat.errorBanner.switchClaudeSubscription' }),
+ );
+ expect(onSwitchToClaudeSubscription).toHaveBeenCalledOnce();
+ expect(
+ (
+ screen.getByRole('button', {
+ name: 'chat.errorBanner.switchingClaudeSubscription',
+ }) as HTMLButtonElement
+ ).disabled,
+ ).toBe(true);
+
+ await act(async () => {
+ switching.resolve();
+ await switching.promise;
+ });
+ expect(
+ (
+ screen.getByRole('button', {
+ name: 'chat.errorBanner.switchClaudeSubscription',
+ }) as HTMLButtonElement
+ ).disabled,
+ ).toBe(false);
+ });
+
+ it('restores the Claude.ai recovery action when switching fails', async () => {
+ const onSwitchToClaudeSubscription = vi.fn(async () => {
+ throw new Error('route update failed');
+ });
+ render(
+ <ErrorBanner
+ error="Claude Opus is not available with the Claude Pro plan."
+ errorReason={CLAUDE_GATEWAY_OPUS_PLAN_MISMATCH_REASON}
+ retryText="retry this turn"
+ onRetry={vi.fn()}
+ onSwitchToClaudeSubscription={onSwitchToClaudeSubscription}
+ agentKind="cc"
+ modelId="claude-opus-5"
+ />,
+ );
+
+ fireEvent.click(
+ screen.getByRole('button', { name: 'chat.errorBanner.switchClaudeSubscription' }),
+ );
+
+ await waitFor(() =>
+ expect(mocks.toastError).toHaveBeenCalledWith(
+ 'chat.errorBanner.claudeSubscriptionSwitchFailed',
+ ),
+ );
+ expect(
+ (
+ screen.getByRole('button', {
+ name: 'chat.errorBanner.switchClaudeSubscription',
+ }) as HTMLButtonElement
+ ).disabled,
+ ).toBe(false);
+ });
});
diff --git a/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx b/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx
index 7b31ba5922..4a753e9ccc 100644
--- a/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx
+++ b/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx
@@ -26,6 +26,10 @@ import type { CSSProperties, ReactNode } from 'react';
import { useLocation, useNavigate, useOutletContext, useParams } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import type { AgentInputReference } from '@cindy/maker-shared/agent-input-projection';
+import {
+ connectedProvidersForAgent,
+ providerOffersModel,
+} from '@cindy/model-providers';
import { useProportionalWidth } from '@/hooks/useProportionalWidth';
import {
Activity,
@@ -1249,6 +1253,27 @@ export function CCAgentSessionView({
const { providers: localProviders } = useProviders();
const { providers: deviceProviders } = useDeviceProviders(remoteDeviceId);
const providers = remoteDeviceId ? deviceProviders : localProviders;
+ const canSwitchToClaudeSubscription = useMemo(() => {
+ if (
+ remoteDeviceId ||
+ session?.remoteHostId ||
+ session?.agentKind !== 'cc' ||
+ !session.model
+ ) {
+ return false;
+ }
+ return connectedProvidersForAgent(localProviders, 'claude-code').some(
+ (provider) =>
+ provider.id === 'anthropic' &&
+ providerOffersModel(provider, session.model, 'claude-code'),
+ );
+ }, [
+ localProviders,
+ remoteDeviceId,
+ session?.agentKind,
+ session?.model,
+ session?.remoteHostId,
+ ]);
// 该会话 agent 的能力(agent 级 hasFastMode + 旧被控端拍平回退用 availableModels);按 remoteDeviceId 作用域。
const { capabilities: sessionCaps } = useAgentCapabilities(displayAgentKind, remoteDeviceId);
// 这里曾有 useErrorReadAck:ErrorBanner 在视图内聚焦驻留 1.5s 即 explicit 清红点。
@@ -2553,16 +2578,50 @@ export function CCAgentSessionView({
// interrupted-turn-resume:main 判定失败 turn 已有 assistant 产出时,会用隐藏的
// 规范化续跑指令(CONTINUE_AFTER_ERROR_PROMPT)替代重发原文;零产出仍重发原文。
// 判定与文案都在 main(规则 9),renderer 只发意图。
- // Retry / silent-stop 继续都**不在这里 ack 红点**(PR #879 review P1):这两个 store
- // 方法内部吞掉异步失败,点击时就清点会在恢复失败(retry 被拒 / 续跑入队失败)时留下
+ // Retry / silent-stop 继续都**不在这里 ack 红点**(PR #879 review P1):点击时就清点
+ // 会在恢复失败(retry 被拒 / 续跑入队失败)时留下
// 「横幅还在、红点没了」,而 live-only 的错误没有任何重算能把它恢复。
// 成功路径已经有更可靠的收敛点:turn 真正跑起来 → store 清掉终止错误 →
// useSessionRunningStatus 在 running 上升沿把 orphan 的 error 角标 explicit 清掉。
// 失败路径则天然保留红点,与仍在展示的横幅一致。
const handleRetry = useCallback(() => {
- retryLastError();
+ void retryLastError().catch((error) => {
+ log.warn('retryLastError failed', error);
+ });
}, [retryLastError]);
+ const handleSwitchToClaudeSubscription = useCallback(async (): Promise<void> => {
+ if (!sessionId || !session || !canSwitchToClaudeSubscription) return;
+ const model = session.model;
+ const previousProviderId = session.providerId ?? null;
+
+ await window.electronAPI.maker.setModel(sessionId, model, 'anthropic');
+ try {
+ await sessionService.update(sessionId, {
+ model,
+ providerId: 'anthropic',
+ });
+ } catch (error) {
+ // runtime route 已先切换;若持久化失败就回滚,避免当前进程与 DB 对同一会话
+ // 产生两个 provider 真源。
+ await window.electronAPI.maker
+ .setModel(sessionId, model, previousProviderId)
+ .catch((rollbackError) => {
+ log.warn('Claude subscription recovery rollback failed', rollbackError);
+ });
+ throw error;
+ }
+
+ await refreshServerSession();
+ await retryLastError();
+ }, [
+ canSwitchToClaudeSubscription,
+ refreshServerSession,
+ retryLastError,
+ session,
+ sessionId,
+ ]);
+
const handleSilentStopContinue = useCallback(() => {
continueAfterSilentStop();
}, [continueAfterSilentStop]);
@@ -3256,6 +3315,11 @@ export function CCAgentSessionView({
deviceLinkDeviceId={remoteDeviceId}
modelId={session?.model}
providerId={session?.providerId}
+ onSwitchToClaudeSubscription={
+ canSwitchToClaudeSubscription
+ ? handleSwitchToClaudeSubscription
+ : undefined
+ }
silentEncryptedRetryEnabled={silentEncryptedRetryEnabled}
onForkStripEncrypted={ownsWindowRoute ? handleForkStripEncrypted : undefined}
forkStripEncryptedRunning={forkStripEncryptedRunning}
@@ -3301,6 +3365,9 @@ export function CCAgentSessionView({
deviceLinkDeviceId={remoteDeviceId}
modelId={session?.model}
providerId={session?.providerId}
+ onSwitchToClaudeSubscription={
+ canSwitchToClaudeSubscription ? handleSwitchToClaudeSubscription : undefined
+ }
silentEncryptedRetryEnabled={silentEncryptedRetryEnabled}
onForkStripEncrypted={ownsWindowRoute ? handleForkStripEncrypted : undefined}
forkStripEncryptedRunning={forkStripEncryptedRunning}
diff --git a/apps/desktop/src/renderer/hooks/useCCAgentChat.ts b/apps/desktop/src/renderer/hooks/useCCAgentChat.ts
index b1aaf7f06a..fb2e219bf0 100644
--- a/apps/desktop/src/renderer/hooks/useCCAgentChat.ts
+++ b/apps/desktop/src/renderer/hooks/useCCAgentChat.ts
@@ -157,7 +157,7 @@ interface UseCCAgentChatReturn {
/** Dismiss the error banner without retrying. */
clearError: () => void;
/** Retry the main-owned typed recovery target. */
- retryLastError: () => void;
+ retryLastError: () => Promise<void>;
/** silent-stop 耗尽横幅「继续」:清横幅并发隐藏续跑指令(充值守卫额度)。 */
continueAfterSilentStop: () => void;
/** F-CMD: Insert a local-only system card */
@@ -502,8 +502,8 @@ export function useCCAgentChat(
}, [sessionId]);
const retryLastError = useCallback(() => {
- if (!sessionId) return;
- makerChatStore.retryLastError(sessionId);
+ if (!sessionId) return Promise.resolve();
+ return makerChatStore.retryLastError(sessionId);
}, [sessionId]);
const insertSystemCard = useCallback(
diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.json
index 20354e3fba..839e10e8d4 100644
--- a/apps/desktop/src/renderer/i18n/locales/en/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json
@@ -5087,6 +5087,11 @@
"continueAfterResetTitle": "Create a one-time Automation to continue this task after usage resets",
"credentialSwitchBusy": "Another Codex task is still running, so the provider for this session can't be applied yet (the shared Codex process needs a restart). Retry after those tasks finish.",
"codexThreadStale": "Codex auth mode changed — this session can't continue. Start a new session to apply it.",
+ "claudeGatewayOpusPlanMismatch": "This Opus request went through XD Gateway, not your Claude.ai subscription. That gateway route rejected the model. Switch to your Claude.ai subscription and retry, or choose another model.",
+ "switchClaudeSubscription": "Switch to Claude.ai & Retry",
+ "switchClaudeSubscriptionTitle": "Switch this conversation to the Claude.ai subscription and retry",
+ "switchingClaudeSubscription": "Switching to Claude.ai…",
+ "claudeSubscriptionSwitchFailed": "Couldn’t switch to Claude.ai or retry this conversation: {{msg}}",
"budgetModelHint": "If this keeps failing, try switching to the standard GPT model.",
"codexAuthMissing": "Remote Codex hasn't been signed in yet (401 Unauthorized). Click \"Sync auth\" to push your local Codex credentials to the remote Cindy Codex home, then retry.",
"codexAuthMissingLocal": "Codex credentials missing or expired (401 Unauthorized). Re-login in {{appName}} Settings → Codex (the app-server will auto-restart on login), or run `codex login` in your terminal and toggle the auth mode in Settings once to restart the app-server. Then start a new session.",
diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.json
index d183cc17c8..dd6d20f871 100644
--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json
@@ -5086,6 +5086,11 @@
"continueAfterResetTitle": "利用上限のリセット後にこのタスクを続行する一回限りの自動化を作成",
"credentialSwitchBusy": "他の Codex タスクが実行中のため、この会話で選択したプロバイダーへまだ切り替えられません(共有 Codex プロセスの再起動が必要です)。他のタスクの終了後に「再試行」を押してください。",
"codexThreadStale": "Codex の認証モードが切り替わりました。この会話は続行できません。新しい会話を開始してください。",
+ "claudeGatewayOpusPlanMismatch": "この Opus リクエストは Claude.ai サブスクリプションではなく、XD Gateway 経由で送信され、このモデルが拒否されました。Claude.ai サブスクリプションに切り替えて再試行するか、別のモデルを選択してください。",
+ "switchClaudeSubscription": "Claude.ai に切り替えて再試行",
+ "switchClaudeSubscriptionTitle": "この会話を Claude.ai サブスクリプションに切り替えて再試行",
+ "switchingClaudeSubscription": "Claude.ai に切り替え中…",
+ "claudeSubscriptionSwitchFailed": "Claude.ai への切り替えまたはこの会話の再試行に失敗しました:{{msg}}",
"budgetModelHint": "繰り返し失敗する場合は、通常版 GPT モデルに切り替えてお試しください。",
"codexAuthMissing": "リモートの Codex がまだサインインしていません(401 Unauthorized)。「認証情報を同期」をクリックしてローカルの Codex 認証情報をリモートの Cindy Codex home にプッシュし、再試行してください。",
"codexAuthMissingLocal": "Codex 認証情報がないか期限切れです(401 Unauthorized)。{{appName}} Settings → Codex から再ログインする(ログイン時に app-server が自動再起動)か、ターミナルで `codex login` 実行後 Settings で認証モードを一度切り替えて app-server を再起動してから、新しい会話を開始してください。",
diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.json
index 1904c21f5b..64c3a7fb5b 100644
--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json
@@ -5086,6 +5086,11 @@
"continueAfterResetTitle": "사용량 제한 재설정 후 현재 작업을 계속할 일회성 자동화 만들기",
"credentialSwitchBusy": "다른 Codex 작업이 실행 중이어서 이 대화에서 선택한 제공자로 아직 전환할 수 없습니다(공유 Codex 프로세스 재시작 필요). 다른 작업이 끝난 후 ‘재시도’를 눌러 주세요.",
"codexThreadStale": "Codex 인증 모드가 변경되었습니다. 이 대화는 계속할 수 없습니다. 새 대화를 시작하세요.",
+ "claudeGatewayOpusPlanMismatch": "이 Opus 요청은 Claude.ai 구독이 아니라 XD Gateway를 통해 전송되었고, 해당 게이트웨이 경로에서 모델을 거부했습니다. Claude.ai 구독으로 전환해 다시 시도하거나 다른 모델을 선택하세요.",
+ "switchClaudeSubscription": "Claude.ai로 전환 후 재시도",
+ "switchClaudeSubscriptionTitle": "이 대화를 Claude.ai 구독으로 전환하고 다시 시도",
+ "switchingClaudeSubscription": "Claude.ai로 전환하는 중…",
+ "claudeSubscriptionSwitchFailed": "Claude.ai로 전환하거나 이 대화를 다시 시도할 수 없습니다: {{msg}}",
"budgetModelHint": "계속 실패하면 일반 GPT 모델로 전환해 보세요.",
"codexAuthMissing": "원격 Codex가 아직 로그인되지 않았습니다(401 Unauthorized). 「인증 동기화」를 클릭하여 로컬 Codex 자격 증명을 원격 Cindy Codex home으로 푸시한 후 다시 시도하세요.",
"codexAuthMissingLocal": "Codex 자격 증명이 없거나 만료되었습니다(401 Unauthorized). {{appName}} Settings → Codex에서 다시 로그인하거나(로그인 시 app-server가 자동 재시작) 터미널에서 `codex login` 실행 후 Settings에서 인증 모드를 한 번 전환하여 app-server를 재시작한 다음 새 대화를 시작하세요.",
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 c77ba1fd6a..c8a143d540 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
@@ -5086,6 +5086,11 @@
"continueAfterResetTitle": "创建一次性自动化,在用量恢复后继续当前任务",
"credentialSwitchBusy": "其他 Codex 任务正在运行,暂时无法按本对话选择的模型来源切换(需要重启共享的 Codex 后台进程)。等其他任务结束后点「重试」即可。",
"codexThreadStale": "Codex 鉴权模式已切换,当前对话无法继续 —— 请新建对话后生效。",
+ "claudeGatewayOpusPlanMismatch": "这次 Opus 请求实际走的是 XD Gateway,不是你的 Claude.ai 订阅;该网关路由拒绝了此模型。可切换到 Claude.ai 订阅后重试,或换一个模型。",
+ "switchClaudeSubscription": "切换到 Claude.ai 并重试",
+ "switchClaudeSubscriptionTitle": "把当前对话切换到 Claude.ai 订阅并重试",
+ "switchingClaudeSubscription": "正在切换到 Claude.ai…",
+ "claudeSubscriptionSwitchFailed": "无法切换到 Claude.ai 或重试当前对话:{{msg}}",
"budgetModelHint": "如果反复失败,可以切换到普通版 GPT 再试试。",
"codexAuthMissing": "远端 Codex 还没同步登录态(401 Unauthorized)。点击右侧「同步登录态」把本机 Codex 凭证推到远端 Cindy Codex home,然后重试发送。",
"codexAuthMissingLocal": "Codex 凭证缺失或失效(401 Unauthorized)。请在 {{appName}} Settings → Codex 重新登录(登录后会自动重启 Codex app-server),或在终端跑 `codex login` + 在 Settings 切换一次鉴权模式来重启 app-server,然后新建对话再发。",
diff --git a/apps/desktop/src/renderer/lib/makerChatStore.ts b/apps/desktop/src/renderer/lib/makerChatStore.ts
index 9c7fc2d715..45a8a2cb4c 100644
--- a/apps/desktop/src/renderer/lib/makerChatStore.ts
+++ b/apps/desktop/src/renderer/lib/makerChatStore.ts
@@ -7778,15 +7778,16 @@ function clearError(sessionId: string): void {
});
}
-function retryLastError(sessionId: string): void {
- if (!sessionId) return;
+function retryLastError(sessionId: string): Promise<void> {
+ if (!sessionId) return Promise.resolve();
// 续跑语义在 main:coordinator 判定失败 turn 已有 assistant 产出时,用共享英文
// 常量 CONTINUE_AFTER_ERROR_PROMPT 替代重发原文(shared/interruptedTurn.ts),
// renderer 不传文案、不做判定。
- makerApiFor(sessionId)
+ return makerApiFor(sessionId)
.input.retryLastError(sessionId)
- .then(applyInputProjection)
- .catch((err) => log.warn('retryLastError failed:', err));
+ .then((projection) => {
+ applyInputProjection(projection);
+ });
}
/**
diff --git a/apps/desktop/src/shared/__tests__/claudeGatewayError.test.ts b/apps/desktop/src/shared/__tests__/claudeGatewayError.test.ts
new file mode 100644
index 0000000000..44108802d0
--- /dev/null
+++ b/apps/desktop/src/shared/__tests__/claudeGatewayError.test.ts
@@ -0,0 +1,35 @@
+import { describe, expect, it } from 'vitest';
+
+import {
+ CLAUDE_GATEWAY_OPUS_PLAN_MISMATCH_REASON,
+ classifyClaudeGatewayError,
+ type ClaudeGatewayErrorContext,
+} from '../claudeGatewayError';
+
+const planError =
+ 'Claude Opus is not available with the Claude Pro plan. If you have updated your subscription plan recently, run /logout and /login for the plan to take effect.';
+
+function classify(overrides: Partial<ClaudeGatewayErrorContext> = {}) {
+ return classifyClaudeGatewayError({
+ modelId: 'claude-opus-5',
+ requestRoute: 'gateway',
+ status: 400,
+ error: planError,
+ ...overrides,
+ });
+}
+
+describe('classifyClaudeGatewayError', () => {
+ it('attributes the misleading Pro-plan error from the exact gateway Opus response', () => {
+ expect(classify()).toBe(CLAUDE_GATEWAY_OPUS_PLAN_MISMATCH_REASON);
+ });
+
+ it.each([
+ { label: 'Claude.ai subscription route', requestRoute: 'subscription' as const },
+ { label: 'non-400 response', status: 429 },
+ { label: 'non-Opus model', modelId: 'claude-sonnet-5' },
+ { label: 'unrelated error', error: 'model unavailable' },
+ ])('does not guess for $label', ({ label: _label, ...overrides }) => {
+ expect(classify(overrides)).toBeNull();
+ });
+});
diff --git a/apps/desktop/src/shared/claudeGatewayError.ts b/apps/desktop/src/shared/claudeGatewayError.ts
new file mode 100644
index 0000000000..003e81f1fc
--- /dev/null
+++ b/apps/desktop/src/shared/claudeGatewayError.ts
@@ -0,0 +1,34 @@
+/**
+ * Claude Code 会把部分上游 400 统一翻译成 Claude.ai 套餐提示。若请求实际走的是
+ * XD Gateway,这段提示里的 Pro/Max 判断并不属于用户的 Claude.ai 账号,不能原样
+ * 展示成“重新登录 Claude.ai”建议。
+ */
+
+export const CLAUDE_GATEWAY_OPUS_PLAN_MISMATCH_REASON = 'claude-gateway-opus-plan-mismatch';
+
+const CLAUDE_PRO_OPUS_ERROR = /Claude Opus is not available with the Claude Pro plan/i;
+
+export interface ClaudeGatewayErrorContext {
+ modelId: string;
+ requestRoute: 'gateway' | 'subscription';
+ status: number;
+ error: string;
+}
+
+/**
+ * 只按同一个 proxy 请求的精确路由与上游响应归因。会话 provider、最近路由或
+ * terminal event 到达时的活性状态都不是请求级证据,不能参与这个判定。
+ */
+export function classifyClaudeGatewayError(
+ context: ClaudeGatewayErrorContext,
+): typeof CLAUDE_GATEWAY_OPUS_PLAN_MISMATCH_REASON | null {
+ if (
+ context.requestRoute !== 'gateway' ||
+ context.status !== 400 ||
+ !context.modelId.startsWith('claude-opus-') ||
+ !CLAUDE_PRO_OPUS_ERROR.test(context.error)
+ ) {
+ return null;
+ }
+ return CLAUDE_GATEWAY_OPUS_PLAN_MISMATCH_REASON;
+}