Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(model-access): Cindy AI Key 被网关拒绝后主进程自动重新获取
fmfsaisai44e4d9a44fce
diff --git a/apps/desktop/src/main/bootstrap-electron.ts b/apps/desktop/src/main/bootstrap-electron.tsindex 95c3ac6508..3d2b6419c6 100644--- a/apps/desktop/src/main/bootstrap-electron.ts+++ b/apps/desktop/src/main/bootstrap-electron.ts@@ -1072,6 +1072,7 @@ import {refreshXdGatewayModels,} from './model-access/index.js';import { effectiveXdGatewayBaseUrl } from './model-access/effectiveEndpoint.js';+import { withCindyGatewayKeyRejectionReport } from './model-access/gatewayKeyRejection.js';import { isLocalDbOwnerCurrent } from './appSessionPolicy.js';import { getAppCapabilities, requireAppCapability } from './appCapabilities.js';import {@@ -1459,8 +1460,8 @@ function attemptStartEmbeddingHost(): void {// 函数形态:model-access 下发切换 endpoint 后,常驻的 embedding host 无需重启。gatewayBaseUrl: () => effectiveXdGatewayBaseUrl(),// /v1/embeddings 也要吃系统代理:裸全局 fetch 在「系统代理」模式下裸直连出网- // (见 maker-host/outbound-fetch.ts)。- fetchImpl: outboundFetch,+ // (见 maker-host/outbound-fetch.ts)。401 时按本次请求的 Key 上报 Cindy AI Key 失效。+ fetchImpl: withCindyGatewayKeyRejectionReport(outboundFetch),log: createSchedulerLogger('embeddingHost'),});} catch (err) {diff --git a/apps/desktop/src/main/cindy-media/__tests__/invocationService.test.ts b/apps/desktop/src/main/cindy-media/__tests__/invocationService.test.tsindex c197402a1d..4dad088621 100644--- a/apps/desktop/src/main/cindy-media/__tests__/invocationService.test.ts+++ b/apps/desktop/src/main/cindy-media/__tests__/invocationService.test.ts@@ -50,6 +50,7 @@ const mocks = vi.hoisted(() => ({prune: vi.fn(async () => undefined),rows: new Map<string, Record<string, unknown>>(),failRequestLog: false,+ reportKeyRejected: vi.fn(),}));vi.mock('../../authManager.js', () => ({@@ -68,6 +69,9 @@ vi.mock('../../appCapabilities.js', () => ({vi.mock('../../model-access/effectiveEndpoint.js', () => ({effectiveXdGatewayBaseUrl: () => 'https://gateway.example.com',}));+vi.mock('../../model-access/gatewayKeyRejection.js', () => ({+ reportCindyGatewayKeyRejected: mocks.reportKeyRejected,+}));vi.mock('../../secrets/providerSecretStore.js', () => ({getProviderSecretStore: () => ({ get: () => 'test-api-key' }),}));@@ -1527,6 +1531,34 @@ describe('Cindy Core media invocation state and security boundary', () => {expect(result.message).not.toContain(opaque);});+ it.each([+ [401, 1],+ [400, 0],+ [403, 0],+ ] as const)('网关 HTTP %s 时按 Cindy AI Key 失效上报 %s 次', async (status, reports) => {+ mocks.reportKeyRejected.mockClear();+ mocks.guide.mockResolvedValue(+ resolvedGuide(+ operation({+ mode: 'sync',+ media: [{ path: ['data'], encoding: 'base64', kind: 'image' }],+ }),+ ),+ );+ mocks.outboundFetch.mockResolvedValue(+ new Response(JSON.stringify({ message: 'rejected' }), { status }),+ );++ const result = await callCindyMedia({+ action: 'request',+ invocationId: await prepare(),+ body: { prompt: 'cat' },+ });+ expect(result).toMatchObject({ ok: false, errorCode: 'UPSTREAM_REJECTED' });+ expect(mocks.reportKeyRejected).toHaveBeenCalledTimes(reports);+ if (reports > 0) expect(mocks.reportKeyRejected).toHaveBeenCalledWith('test-api-key');+ });+it('受限网络未获批准时不下载,批准新 CDN 后不携带网关凭据', async () => {const urlOperation = operation({mode: 'sync',diff --git a/apps/desktop/src/main/cindy-media/invocationService.ts b/apps/desktop/src/main/cindy-media/invocationService.tsindex 26529b9897..ae1411640b 100644--- a/apps/desktop/src/main/cindy-media/invocationService.ts+++ b/apps/desktop/src/main/cindy-media/invocationService.ts@@ -22,6 +22,7 @@ import { ServerApiError } from '../serverApiClient.js';import { getCurrentDbClientUserId, getDbClient } from '../localDb/client/current.js';import type { DbClient } from '../localDb/client/DbClient.js';import { effectiveXdGatewayBaseUrl } from '../model-access/effectiveEndpoint.js';+import { reportCindyGatewayKeyRejected } from '../model-access/gatewayKeyRejection.js';import { outboundFetch } from '../maker-host/outbound-fetch.js';import {fetchMediaInvocationGuide,@@ -77,6 +78,8 @@ interface MediaConnection {headers?: Record<string, string>;assertCurrent?(): void;beforeSubmit?(): void;+ /** 上游以 401 拒绝时调用;只有携带 Cindy AI Key 的网关连接提供。 */+ onUnauthorized?(): void;}class MediaInvocationError extends Error {@@ -316,7 +319,7 @@ function resolveConnection(providerId: string): MediaConnection {) {throw new MediaInvocationError('CONNECTION_INVALID', 'Cindy AI endpoint 不合法');}- return { baseUrl, apiKey };+ return { baseUrl, apiKey, onUnauthorized: () => reportCindyGatewayKeyRejected(apiKey) };}function requestUrl(baseUrl: string, relativePath: string): string {@@ -519,6 +522,7 @@ async function dispatchRequest(input: {signal: controller.signal,});responseStatus = response.status;+ if (response.status === 401) input.connection.onUnauthorized?.();log.info('media request response', {...requestLog,status: response.status,diff --git a/apps/desktop/src/main/maker-ipc/__tests__/gatewayProxyTokenRecovery.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/gatewayProxyTokenRecovery.test.tsnew file mode 100644index 0000000000..9a48dfddc1--- /dev/null+++ b/apps/desktop/src/main/maker-ipc/__tests__/gatewayProxyTokenRecovery.test.ts@@ -0,0 +1,36 @@+import type { AgentEvent } from '@cindy/maker-core';+import { GATEWAY_PROXY_TOKEN_INVALID_REASON } from '@cindy/maker-shared/error-redaction';+import { describe, expect, it } from 'vitest';++import { isGatewayProxyTokenRecoveryErrorEventForProvider } from '../gatewayProxyTokenRecovery.js';++function errorEvent(data: Record<string, unknown>): AgentEvent {+ return { type: 'error', source: 'claude-code', data } as AgentEvent;+}++describe('isGatewayProxyTokenRecoveryErrorEventForProvider', () => {+ const tokenInvalid = errorEvent({ message: 'Authentication failed', reason: GATEWAY_PROXY_TOKEN_INVALID_REASON });++ it('matches terminal key failures on Cindy AI sessions, including legacy sessions without a provider', () => {+ expect(isGatewayProxyTokenRecoveryErrorEventForProvider('xd', tokenInvalid)).toBe(true);+ expect(isGatewayProxyTokenRecoveryErrorEventForProvider(null, tokenInvalid)).toBe(true);+ expect(isGatewayProxyTokenRecoveryErrorEventForProvider(undefined, tokenInvalid)).toBe(true);+ expect(isGatewayProxyTokenRecoveryErrorEventForProvider(+ 'xd',+ errorEvent({ message: 'Invalid proxy server token passed' }),+ )).toBe(true);+ });++ it('ignores other providers, other errors, retryable errors and non-error events', () => {+ expect(isGatewayProxyTokenRecoveryErrorEventForProvider('openai', tokenInvalid)).toBe(false);+ expect(isGatewayProxyTokenRecoveryErrorEventForProvider('xd', errorEvent({ message: 'Rate limited' }))).toBe(false);+ expect(isGatewayProxyTokenRecoveryErrorEventForProvider(+ 'xd',+ errorEvent({ reason: GATEWAY_PROXY_TOKEN_INVALID_REASON, isTerminal: false }),+ )).toBe(false);+ expect(isGatewayProxyTokenRecoveryErrorEventForProvider(+ 'xd',+ { type: 'done', source: 'claude-code', data: {} } as AgentEvent,+ )).toBe(false);+ });+});diff --git a/apps/desktop/src/main/maker-ipc/__tests__/sessionEventPipeline.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/sessionEventPipeline.test.tsindex 72438105d1..7d63f4a41a 100644--- a/apps/desktop/src/main/maker-ipc/__tests__/sessionEventPipeline.test.ts+++ b/apps/desktop/src/main/maker-ipc/__tests__/sessionEventPipeline.test.ts@@ -11,6 +11,8 @@ import { SessionTurnActivityTracker } from '../sessionTurnActivityTracker.js';import { ProductTurnWallClockTracker, ProductTurnUsageTargetTracker } from '../turnWallClock.js';import { ClaudeOutputLagTimingGuard } from '../../usage/modelUsageDelta.js';import { createWorkerTurnStartSequencer } from '../workerTurnStartSequencer.js';+import { isGatewayProxyTokenRecoveryErrorEventForProvider } from '../gatewayProxyTokenRecovery.js';+import { GATEWAY_PROXY_TOKEN_INVALID_REASON } from '@cindy/maker-shared/error-redaction';const effects = vi.hoisted(() => {const calls: string[] = [];@@ -317,7 +319,8 @@ function harness() {},handleSilentStopTurnEnd: vi.fn(async () => {}),isRemoteAuthRetryErrorEvent: vi.fn(() => false),- isGatewayProxyTokenRecoveryErrorEvent: vi.fn(() => false),+ isGatewayProxyTokenRecoveryErrorEvent: vi.fn<(sessionId: string, event: AgentEvent) => boolean>(() => false),+ reportAgentCindyGatewayKeyRejected: vi.fn(),overflowSuppressedBroadcasts: new Map(),handleAgentIslandEventAfterBroadcast: effects.fn('island'),notifyGoalIdleAfterTurnSettled: vi.fn(() => {@@ -684,6 +687,40 @@ describe('production Session event pipeline', () => {},);+ it.each([+ ['xd', 1],+ [null, 1],+ ['openai', 0],+ ['custom-provider', 0],+ ] as const)('reports a Cindy AI key rejection at turn end for provider %s (%s times)', async (providerId, reports) => {+ const h = harness();+ // The production predicate, bound to this session's provider.+ h.deps.isGatewayProxyTokenRecoveryErrorEvent.mockImplementation((_sessionId, value) =>+ isGatewayProxyTokenRecoveryErrorEventForProvider(providerId, value));+ try {+ h.emit(event('error', {+ message: 'Authentication failed',+ reason: GATEWAY_PROXY_TOKEN_INVALID_REASON,+ }));+ expect(h.deps.reportAgentCindyGatewayKeyRejected).toHaveBeenCalledTimes(reports);+ } finally { await h.dispose(); }+ });++ it('does not report other Cindy AI turn failures or retryable key errors', async () => {+ const h = harness();+ h.deps.isGatewayProxyTokenRecoveryErrorEvent.mockImplementation((_sessionId, value) =>+ isGatewayProxyTokenRecoveryErrorEventForProvider('xd', value));+ try {+ h.emit(event('error', { message: 'Rate limited' }));+ h.emit(event('error', {+ message: 'Authentication failed',+ reason: GATEWAY_PROXY_TOKEN_INVALID_REASON,+ isTerminal: false,+ }));+ expect(h.deps.reportAgentCindyGatewayKeyRejected).not.toHaveBeenCalled();+ } finally { await h.dispose(); }+ });+it('keeps a retryable error running without resetting persistence', async () => {const h = harness();h.activity.setSessionInTurn('task', true);diff --git a/apps/desktop/src/main/maker-ipc/gatewayProxyTokenRecovery.ts b/apps/desktop/src/main/maker-ipc/gatewayProxyTokenRecovery.tsnew file mode 100644index 0000000000..5da2761b10--- /dev/null+++ b/apps/desktop/src/main/maker-ipc/gatewayProxyTokenRecovery.ts@@ -0,0 +1,27 @@+import type { AgentEvent } from '@cindy/maker-core';+import {+ GATEWAY_PROXY_TOKEN_INVALID_REASON,+ isCindyGatewayProviderId,+ isGatewayProxyTokenInvalidError,+} from '@cindy/maker-shared/error-redaction';++import { isTerminalTurnErrorEvent } from './sessionTurnActivityTracker.js';++/**+ * 判定一个智能体事件是否为「回合因 Cindy AI Key 失效而终止」:终止型 error、会话走 Cindy+ * 网关(显式 `xd` 或旧会话未写 provider),且错误带网关代理 token 失效的结构化 reason 或文本。+ * register.ts 用它决定错误是否交给 renderer 自愈、是否落库,以及是否上报 Key 失效;+ * 抽成纯函数便于按供应商单测。+ */+export function isGatewayProxyTokenRecoveryErrorEventForProvider(+ providerId: string | null | undefined,+ event: AgentEvent,+): boolean {+ if (event.type !== 'error' || !isTerminalTurnErrorEvent(event)) return false;+ const data = event.data as { message?: unknown; reason?: unknown } | undefined;+ return (+ isCindyGatewayProviderId(providerId) &&+ (data?.reason === GATEWAY_PROXY_TOKEN_INVALID_REASON ||+ isGatewayProxyTokenInvalidError(typeof data?.message === 'string' ? data.message : ''))+ );+}diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.tsindex 3e55773f70..724b5eda8f 100644--- a/apps/desktop/src/main/maker-ipc/register.ts+++ b/apps/desktop/src/main/maker-ipc/register.ts@@ -157,12 +157,7 @@ import {type ProviderView,} from '@cindy/model-providers';import { createId } from '@paralleldrive/cuid2';-import {- GATEWAY_PROXY_TOKEN_INVALID_REASON,- isCindyGatewayProviderId,- isGatewayProxyTokenInvalidError,- redactSensitiveText,-} from '@cindy/maker-shared/error-redaction';+import { redactSensitiveText } from '@cindy/maker-shared/error-redaction';import { permissionModeOrAsk } from '@cindy/maker-shared/permission-mode';import {isProductTurnCompletionTailEvent,@@ -1118,6 +1113,8 @@ import {storeCustomProviderHeaders,storeCustomProviderKey,} from '../secrets/providerSecretStore.js';+import { reportCindyGatewayKeyRejected } from '../model-access/gatewayKeyRejection.js';+import { isGatewayProxyTokenRecoveryErrorEventForProvider } from './gatewayProxyTokenRecovery.js';import {getSessionEffort,getSessionFastMode,@@ -4700,14 +4697,19 @@ function isRemoteAuthRetryErrorEvent();}+/** 智能体不回报所用 Key:按本机当前保存的 Cindy AI Key 上报失效。 */+function reportAgentCindyGatewayKeyRejected(): void {+ try {+ reportCindyGatewayKeyRejected(readClaudeApiKey());+ } catch (error) {+ log.warn('Cindy AI key rejection report from agent turn failed', {+ error: error instanceof Error ? error.message : String(error),+ });+ }+}+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 : ''))- );+ return isGatewayProxyTokenRecoveryErrorEventForProvider(getSessionProvider(sessionId), event);}function handleAgentIslandInteractionAfterBroadcast(@@ -5577,6 +5579,7 @@ const sessionEventDependencies: SessionEventDependencies = {get handleAgentIslandEventAfterBroadcast() {return handleAgentIslandEventAfterBroadcast;},+ reportAgentCindyGatewayKeyRejected,get notifyGoalIdleAfterTurnSettled() {return notifyGoalIdleAfterTurnSettled;},diff --git a/apps/desktop/src/main/maker-ipc/sessionEventDelivery.ts b/apps/desktop/src/main/maker-ipc/sessionEventDelivery.tsindex 41392094ee..fa601d3a2f 100644--- a/apps/desktop/src/main/maker-ipc/sessionEventDelivery.ts+++ b/apps/desktop/src/main/maker-ipc/sessionEventDelivery.ts@@ -55,6 +55,11 @@ export interface DeliverSessionEventDeps {readonly refreshRemoteCodexMcpOnTurnSettledHolder: ((sessionId: string) => void) | null;readonly markTurnEndedAfterPersistDrain: (sessionId: string) => void;readonly gitSnapshotCoordinator: Pick<GitSnapshotCoordinator, 'onTurnEnd' | 'onTurnAbort'> | null;+ /**+ * 智能体回合因 Cindy AI Key 失效终止时调用(按本机当前 Key 上报,触发凭据重新同步)。+ * 智能体不会回报自己用的是哪把 Key。+ */+ readonly reportAgentCindyGatewayKeyRejected?: () => void;}export function deliverSessionEvent(@@ -77,6 +82,9 @@ export function deliverSessionEvent(} = prepared;let { persistId } = stream;const { resolvedContent } = stream;+ // 所有会话的终态事件都经过这里(不受 Agent Island 的会话过滤影响):回合因 Cindy AI+ // Key 失效结束时,让 model-access 重新拉取凭据。判定复用 isGatewayProxyTokenRecoveryErrorEvent。+ if (isGatewayProxyTokenRecovery) deps.reportAgentCindyGatewayKeyRejected?.();// 先 broadcast 保 UI 实时性,再 flush(flush 只入队、不阻塞)。// Keep the raw event for main-side coordination/persistence, but only// cross renderer/device-link boundaries with the redacted copy.diff --git a/apps/desktop/src/main/mcp-integrations/__tests__/cindyProxySearch.test.ts b/apps/desktop/src/main/mcp-integrations/__tests__/cindyProxySearch.test.tsindex f8d1b501e1..ca891f217a 100644--- a/apps/desktop/src/main/mcp-integrations/__tests__/cindyProxySearch.test.ts+++ b/apps/desktop/src/main/mcp-integrations/__tests__/cindyProxySearch.test.ts@@ -163,6 +163,28 @@ describe('cindyProxySearch', () => {expect(fetchImpl).not.toHaveBeenCalled();});+ it('网关 401 时上报本次请求携带的 Key,其他状态不上报', async () => {+ for (const [status, expectedReports] of [[401, 1], [403, 0], [429, 0], [200, 0]] as const) {+ const onKeyRejected = vi.fn();+ const service = createCindyProxySearchService({+ getBaseUrl: () => 'https://gateway.example.test',+ getApiKey: () => 'search-key-sent',+ onKeyRejected,+ fetchImpl: vi.fn(async () =>+ response(+ status === 200+ ? { content: [{ type: 'web_search_tool_result', content: [] }] }+ : { error: 'rejected' },+ { status },+ ),+ ) as unknown as typeof fetch,+ });+ await service.search({ query: 'Cindy', limit: 5 });+ expect(onKeyRejected).toHaveBeenCalledTimes(expectedReports);+ if (expectedReports > 0) expect(onKeyRejected).toHaveBeenCalledWith('search-key-sent');+ }+ });+it('归一化鉴权、额度、限流、服务不可用和非法响应错误', async () => {const cases = [{ status: 401, body: { error: 'insufficient scope' }, code: 'AUTH_REJECTED' },diff --git a/apps/desktop/src/main/mcp-integrations/cindyProxyMedia.ts b/apps/desktop/src/main/mcp-integrations/cindyProxyMedia.tsindex 2cf5751df3..b0721918d3 100644--- a/apps/desktop/src/main/mcp-integrations/cindyProxyMedia.ts+++ b/apps/desktop/src/main/mcp-integrations/cindyProxyMedia.ts@@ -12,6 +12,7 @@ import { createLogger } from '../logger.js';import { mediaErrorForLog } from '../cindy-media/mediaRequestLog.js';import { getProviderSecretStore } from '../secrets/providerSecretStore.js';import { effectiveXdGatewayBaseUrl } from '../model-access/effectiveEndpoint.js';+import { withCindyGatewayKeyRejectionReport } from '../model-access/gatewayKeyRejection.js';import { getAppCapabilities } from '../appCapabilities.js';const log = createLogger('art');@@ -26,6 +27,13 @@ function readApiKey(): string | null {return getProviderSecretStore().get('xd');}+/**+ * 注入给网关图像/视频后端的 fetch:行为与它们默认使用的全局 fetch 相同(调用时才取+ * 全局 fetch),只在响应 401 时按本次 Authorization 头里的 Key 上报 Cindy AI Key 失效。+ * 结果下载等不带该头的请求不会上报。+ */+const gatewayMediaFetch = withCindyGatewayKeyRejectionReport((input, init) => fetch(input, init));+function getGatewayBaseUrl(): string {// 与 key 同源的生效 endpoint(model-access 下发值优先,回落端点清单)。return effectiveXdGatewayBaseUrl();@@ -56,6 +64,7 @@ export function getCindyProxyMediaService(): CindyProxyMediaService {artService = createCindyProxyMediaService({imageApi: {getApiKey: readApiKey,+ fetchImplementation: gatewayMediaFetch,proxy: {baseUrl: getGatewayBaseUrl(),generatePath: '/v1/images/generations',@@ -82,6 +91,7 @@ function createGatewayVideoProviders(baseUrl: string) {createSeedanceProvider({baseUrl,getApiKey: readApiKey,+ fetchImplementation: gatewayMediaFetch,logger: log,}),// Seedance 2.5 是独立 provider(值域与 2.0 差太远,capabilities 是@@ -90,11 +100,13 @@ function createGatewayVideoProviders(baseUrl: string) {createSeedance25Provider({baseUrl,getApiKey: readApiKey,+ fetchImplementation: gatewayMediaFetch,logger: log,}),createHappyhorseProvider({baseUrl,getApiKey: readApiKey,+ fetchImplementation: gatewayMediaFetch,logger: log,}),];diff --git a/apps/desktop/src/main/mcp-integrations/cindyProxySearch.ts b/apps/desktop/src/main/mcp-integrations/cindyProxySearch.tsindex 7bcccfe96d..5dd2ff323b 100644--- a/apps/desktop/src/main/mcp-integrations/cindyProxySearch.ts+++ b/apps/desktop/src/main/mcp-integrations/cindyProxySearch.ts@@ -1,6 +1,7 @@import { getAppCapabilities } from '../appCapabilities.js';import { createLogger } from '../logger.js';import { effectiveXdGatewayBaseUrl } from '../model-access/effectiveEndpoint.js';+import { reportCindyGatewayKeyRejected } from '../model-access/gatewayKeyRejection.js';import { getProviderSecretStore } from '../secrets/providerSecretStore.js';import { outboundFetch } from '../maker-host/outbound-fetch.js';import {@@ -81,6 +82,8 @@ export interface CindyProxySearchDeps {getBaseUrl(): string;getApiKey(): string | null;fetchImpl: typeof fetch;+ /** 网关以 401 拒绝本次请求携带的 Cindy AI Key 时调用,入参为该 Key。 */+ onKeyRejected?(apiKey: string): void;timeoutMs?: number;log?: {info(message: string, meta?: Record<string, unknown>): void;@@ -469,6 +472,7 @@ export function createCindyProxySearchService(deps: CindyProxySearchDeps): Cindy}const latencyMs = Date.now() - startedAt;if (!response.ok) {+ if (response.status === 401) deps.onKeyRejected?.(apiKey);const failure = classifyHttpFailure(response.status, body);deps.log?.warn('cindy search request rejected', {logicalProvider: 'cindy',@@ -549,6 +553,7 @@ export function getCindyProxySearchService(): CindyProxySearchService {getApiKey: () =>getAppCapabilities().canUseCindyGateway ? getProviderSecretStore().get('xd') : null,fetchImpl: outboundFetch,+ onKeyRejected: reportCindyGatewayKeyRejected,log,});return service;diff --git a/apps/desktop/src/main/model-access/__tests__/gatewayKeyRejection.test.ts b/apps/desktop/src/main/model-access/__tests__/gatewayKeyRejection.test.tsnew file mode 100644index 0000000000..c096edc548--- /dev/null+++ b/apps/desktop/src/main/model-access/__tests__/gatewayKeyRejection.test.ts@@ -0,0 +1,211 @@+/**+ * gatewayKeyRejection 单测:Cindy AI Key 被网关 401 后的统一上报入口(依赖全注入)。+ * 覆盖:各「直接跳过」条件、规则 A(只认当前 Key)、规则 B(每把 Key 只触发一次)、+ * sync 失败不外冒、单例安装/卸载,以及 fetch 包装从 Authorization 头取 Key。+ */+import { afterEach, describe, expect, it, vi } from 'vitest';++import {+ bearerKeyFromHeaders,+ createGatewayKeyRejectionReporter,+ installCindyGatewayKeyRejectionReporter,+ reportCindyGatewayKeyRejected,+ withCindyGatewayKeyRejectionReport,+ type GatewayKeyRejectionDeps,+} from '../gatewayKeyRejection.js';++const KEY_A = 'sk-test-invalid-a';+const KEY_B = 'sk-test-invalid-b';++function harness(overrides: Partial<GatewayKeyRejectionDeps> = {}) {+ let currentKey: string | null = KEY_A;+ const requestSync = vi.fn(async () => undefined);+ const log = { info: vi.fn(), warn: vi.fn() };+ const deps: GatewayKeyRejectionDeps = {+ canUseCindyGateway: () => true,+ isSessionBoundaryPending: () => false,+ getCredentialSource: () => 'server',+ readCurrentKey: () => currentKey,+ requestSync,+ log,+ ...overrides,+ };+ return {+ report: createGatewayKeyRejectionReporter(deps),+ requestSync: (overrides.requestSync as typeof requestSync | undefined) ?? requestSync,+ log,+ setCurrentKey: (key: string | null) => {+ currentKey = key;+ },+ };+}++describe('createGatewayKeyRejectionReporter', () => {+ it('re-syncs once when the current server-issued key is rejected', () => {+ const h = harness();+ h.report(KEY_A);+ expect(h.requestSync).toHaveBeenCalledTimes(1);+ expect(h.log.info).toHaveBeenCalledWith('Cindy AI key rejected by gateway, re-syncing credentials');+ // 日志不得带 Key 本身。+ for (const call of [...h.log.info.mock.calls, ...h.log.warn.mock.calls]) {+ expect(JSON.stringify(call)).not.toContain(KEY_A);+ }+ });++ it.each([+ ['gateway capability is unavailable', { canUseCindyGateway: () => false }],+ ['an account switch is pending', { isSessionBoundaryPending: () => true }],+ ['the key was entered manually', { getCredentialSource: () => 'manual' as const }],+ ['the key has no source marker', { getCredentialSource: () => null }],+ ])('skips when %s', (_label, overrides) => {+ const h = harness(overrides);+ h.report(KEY_A);+ expect(h.requestSync).not.toHaveBeenCalled();+ });++ it.each([null, undefined, ''])('skips an empty used key (%s)', (usedKey) => {+ const h = harness();+ h.report(usedKey);+ expect(h.requestSync).not.toHaveBeenCalled();+ });++ it('ignores a rejection for a key that is no longer the stored key (rule A)', () => {+ const h = harness();+ h.setCurrentKey(KEY_B);+ h.report(KEY_A);+ expect(h.requestSync).not.toHaveBeenCalled();+ h.setCurrentKey(null);+ h.report(KEY_A);+ expect(h.requestSync).not.toHaveBeenCalled();+ });++ it('triggers once per key and again after the key changes (rule B)', () => {+ const h = harness();+ h.report(KEY_A);+ h.report(KEY_A);+ h.report(KEY_A);+ expect(h.requestSync).toHaveBeenCalledTimes(1);++ h.setCurrentKey(KEY_B);+ h.report(KEY_B);+ h.report(KEY_B);+ expect(h.requestSync).toHaveBeenCalledTimes(2);++ // 换回旧 Key 时与「上一次」不同,允许再触发。+ h.setCurrentKey(KEY_A);+ h.report(KEY_A);+ expect(h.requestSync).toHaveBeenCalledTimes(3);+ });++ it('does not remember a key whose report was skipped', () => {+ let pending = true;+ const h = harness({ isSessionBoundaryPending: () => pending });+ h.report(KEY_A);+ expect(h.requestSync).not.toHaveBeenCalled();+ pending = false;+ h.report(KEY_A);+ expect(h.requestSync).toHaveBeenCalledTimes(1);+ });++ it('swallows a rejected sync', async () => {+ const requestSync = vi.fn(async () => {+ throw new Error('network down');+ });+ const h = harness({ requestSync });+ expect(() => h.report(KEY_A)).not.toThrow();+ await vi.waitFor(() => expect(h.log.warn).toHaveBeenCalledTimes(1));+ });++ it('swallows a synchronously throwing dependency', () => {+ const h = harness({+ requestSync: () => {+ throw new Error('sync unavailable');+ },+ readCurrentKey: () => KEY_A,+ });+ expect(() => h.report(KEY_A)).not.toThrow();+ expect(h.log.warn).toHaveBeenCalledTimes(1);+ });+});++describe('reportCindyGatewayKeyRejected singleton', () => {+ afterEach(() => installCindyGatewayKeyRejectionReporter(null));++ it('is a no-op before model-access installs a reporter', () => {+ expect(() => reportCindyGatewayKeyRejected(KEY_A)).not.toThrow();+ });++ it('delegates to the installed reporter', () => {+ const reporter = vi.fn();+ installCindyGatewayKeyRejectionReporter(reporter);+ reportCindyGatewayKeyRejected(KEY_A);+ expect(reporter).toHaveBeenCalledWith(KEY_A);+ });+});++describe('bearerKeyFromHeaders', () => {+ it('reads bearer keys from every HeadersInit shape', () => {+ expect(bearerKeyFromHeaders({ Authorization: `Bearer ${KEY_A}` })).toBe(KEY_A);+ expect(bearerKeyFromHeaders({ authorization: `bearer ${KEY_A}` })).toBe(KEY_A);+ expect(bearerKeyFromHeaders(new Headers({ Authorization: `Bearer ${KEY_A}` }))).toBe(KEY_A);+ expect(bearerKeyFromHeaders([['Authorization', `Bearer ${KEY_A}`]])).toBe(KEY_A);+ });++ it('returns null without a bearer authorization header', () => {+ expect(bearerKeyFromHeaders(undefined)).toBeNull();+ expect(bearerKeyFromHeaders({ 'x-api-key': KEY_A })).toBeNull();+ expect(bearerKeyFromHeaders({ Authorization: `Basic ${KEY_A}` })).toBeNull();+ expect(bearerKeyFromHeaders({ Authorization: 'Bearer ' })).toBeNull();+ });+});++describe('withCindyGatewayKeyRejectionReport', () => {+ it('reports the bearer key of a 401 request and returns the response untouched', async () => {+ const response = new Response('denied', { status: 401 });+ const fetchImpl = vi.fn(async () => response) as unknown as typeof fetch;+ const report = vi.fn();+ const wrapped = withCindyGatewayKeyRejectionReport(fetchImpl, report);++ const result = await wrapped('https://gateway.invalid/v1/embeddings', {+ method: 'POST',+ headers: { Authorization: `Bearer ${KEY_A}` },+ });++ expect(result).toBe(response);+ expect(report).toHaveBeenCalledWith(KEY_A);+ expect(fetchImpl).toHaveBeenCalledWith('https://gateway.invalid/v1/embeddings', {+ method: 'POST',+ headers: { Authorization: `Bearer ${KEY_A}` },+ });+ });++ it('reads the key from a Request object', async () => {+ const fetchImpl = vi.fn(async () => new Response(null, { status: 401 })) as unknown as typeof fetch;+ const report = vi.fn();+ const wrapped = withCindyGatewayKeyRejectionReport(fetchImpl, report);+ await wrapped(new Request('https://gateway.invalid/v1/embeddings', {+ headers: { Authorization: `Bearer ${KEY_B}` },+ }));+ expect(report).toHaveBeenCalledWith(KEY_B);+ });++ it.each([200, 403, 500])('does not report HTTP %s', async (status) => {+ const fetchImpl = vi.fn(async () => new Response(null, { status })) as unknown as typeof fetch;+ const report = vi.fn();+ const wrapped = withCindyGatewayKeyRejectionReport(fetchImpl, report);+ await wrapped('https://gateway.invalid/v1/embeddings', {+ headers: { Authorization: `Bearer ${KEY_A}` },+ });+ expect(report).not.toHaveBeenCalled();+ });++ it('propagates network failures without reporting', async () => {+ const fetchImpl = vi.fn(async () => {+ throw new TypeError('fetch failed');+ }) as unknown as typeof fetch;+ const report = vi.fn();+ const wrapped = withCindyGatewayKeyRejectionReport(fetchImpl, report);+ await expect(wrapped('https://gateway.invalid/v1/embeddings')).rejects.toThrow('fetch failed');+ expect(report).not.toHaveBeenCalled();+ });+});diff --git a/apps/desktop/src/main/model-access/gatewayKeyRejection.ts b/apps/desktop/src/main/model-access/gatewayKeyRejection.tsnew file mode 100644index 0000000000..da47b4b4bd--- /dev/null+++ b/apps/desktop/src/main/model-access/gatewayKeyRejection.ts@@ -0,0 +1,142 @@+import { createHash } from 'node:crypto';++import type { ModelAccessCredentialSource } from '../../shared/modelAccess.js';++/**+ * gatewayKeyRejection.ts — Cindy AI Key 被网关拒绝(HTTP 401)后的统一上报入口。+ * ---------------------------------------------------------------------------+ * 服务端换发或撤销 Key 后,本机旧 Key 会被网关 401;服务端在客户端调用+ * `GET /api/model-access/credentials` 时会探测当前 Key,失效即签发新 Key。主进程各+ * 调用方(辅助模型、搜索、媒体、向量、额度、语音、智能体终态)在 401 时把**本次请求+ * 实际携带的 Key** 交给这里,由这里决定是否触发一次凭据同步。+ *+ * 规则刻意只有两条,不加冷却 / 退避 / 计时器:+ * - 规则 A:上报的 Key 必须等于本机当前保存的 Key——旧请求的迟到 401 不能为已换上的+ * 新 Key 再触发同步;+ * - 规则 B:每把 Key 只触发一次——内存只记上一次触发的 Key 的 SHA-256 指纹(不存明文),+ * 同一把 Key 的后续 401 全部忽略,换了 Key 之后才可能再次触发。+ * 同步用 `sync()` 而不是 `retry()`:它尊重 unsupported / disabled 终态,自带 single-flight+ * 与内部重试;失败沿用现有同步表现,这里不新增提示。+ *+ * 依赖全部注入(工厂函数),进程内单例由 model-access/index.ts 在 initModelAccess 时组装+ * 并安装。调用方从本文件导入 `reportCindyGatewayKeyRejected`,不直接依赖 index.ts——+ * 后者会拉入 maker-host 等整张主进程依赖图,不适合被底层网络模块反向导入。+ */++export interface GatewayKeyRejectionDeps {+ /** 当前会话是否允许使用 Cindy 网关(getAppCapabilities().canUseCindyGateway)。 */+ canUseCindyGateway(): boolean;+ /** 是否正处于账号切换边界(isAppSessionBoundaryPending)。 */+ isSessionBoundaryPending(): boolean;+ /** 本机 Key 的来源标记;只处理服务端下发('server')的 Key。 */+ getCredentialSource(): ModelAccessCredentialSource | null;+ /** 本机当前保存的 Cindy AI Key(providerSecretStore 'xd')。 */+ readCurrentKey(): string | null;+ /** 触发一次凭据同步(credentialsSync.sync())。 */+ requestSync(): Promise<unknown>;+ log?: {+ info(message: string): void;+ warn(message: string): void;+ };+}++export type GatewayKeyRejectionReporter = (usedKey: string | null | undefined) => void;++function keyFingerprint(key: string): string {+ return createHash('sha256').update(key).digest('hex');+}++/** 组装一个上报器;内存里只保留上一次已触发 Key 的指纹。 */+export function createGatewayKeyRejectionReporter(+ deps: GatewayKeyRejectionDeps,+): GatewayKeyRejectionReporter {+ let lastTriggeredFingerprint: string | null = null;++ return (usedKey) => {+ try {+ if (!usedKey) return;+ if (!deps.canUseCindyGateway()) return;+ if (deps.isSessionBoundaryPending()) return;+ if (deps.getCredentialSource() !== 'server') return;+ // 规则 A:只认本机当前这把 Key 的拒绝。+ if (deps.readCurrentKey() !== usedKey) return;+ // 规则 B:同一把 Key 只触发一次。+ const fingerprint = keyFingerprint(usedKey);+ if (fingerprint === lastTriggeredFingerprint) return;+ lastTriggeredFingerprint = fingerprint;+ deps.log?.info('Cindy AI key rejected by gateway, re-syncing credentials');+ void deps.requestSync().catch((error: unknown) => {+ deps.log?.warn(+ `Cindy AI credentials re-sync after key rejection failed: ${+ error instanceof Error ? error.message : String(error)+ }`,+ );+ });+ } catch (error) {+ // 上报发生在各调用方的错误处理路径里,任何异常都不能改变调用方原有的失败语义。+ deps.log?.warn(+ `Cindy AI key rejection report failed: ${+ error instanceof Error ? error.message : String(error)+ }`,+ );+ }+ };+}++let installedReporter: GatewayKeyRejectionReporter | null = null;++/** model-access/index.ts 初始化时安装进程内单例;传 null 卸载(仅测试复位用)。 */+export function installCindyGatewayKeyRejectionReporter(+ reporter: GatewayKeyRejectionReporter | null,+): void {+ installedReporter = reporter;+}++/**+ * 上报一次 Cindy 网关 401。只在三条同时成立时调用:请求发往 Cindy 网关、带的是+ * Cindy AI Key、响应 401。`usedKey` 传本次请求实际携带的 Key。model-access 尚未+ * 初始化时(无凭据同步可触发)直接忽略。+ */+export function reportCindyGatewayKeyRejected(usedKey: string | null | undefined): void {+ installedReporter?.(usedKey);+}++/** 从请求头里取 `Authorization: Bearer <key>` 的 key;没有或格式不对返回 null。 */+export function bearerKeyFromHeaders(headers: HeadersInit | undefined): string | null {+ if (!headers) return null;+ let value: string | null | undefined;+ if (typeof Headers !== 'undefined' && headers instanceof Headers) {+ value = headers.get('authorization');+ } else if (Array.isArray(headers)) {+ value = headers.find(([name]) => name.toLowerCase() === 'authorization')?.[1];+ } else {+ const record = headers as Record<string, string | undefined>;+ const name = Object.keys(record).find((key) => key.toLowerCase() === 'authorization');+ value = name ? record[name] : undefined;+ }+ const match = typeof value === 'string' ? /^Bearer\s+(.+)$/i.exec(value.trim()) : null;+ return match ? match[1].trim() || null : null;+}++/**+ * 给注入式 fetch 包一层:响应 401 时,用本次请求 Authorization 头里的 Bearer key 上报。+ * 只观察状态码,不读响应体、不改请求和响应;key 是否为 Cindy AI Key 由上报器按规则 A 判定。+ */+export function withCindyGatewayKeyRejectionReport(+ fetchImpl: typeof fetch,+ report: (usedKey: string | null) => void = reportCindyGatewayKeyRejected,+): typeof fetch {+ const wrapped = async (input: Parameters<typeof fetch>[0], init?: Parameters<typeof fetch>[1]) => {+ const response = await fetchImpl(input, init);+ if (response.status === 401) {+ const usedKey =+ bearerKeyFromHeaders(init?.headers)+ ?? (typeof Request !== 'undefined' && input instanceof Request+ ? bearerKeyFromHeaders(input.headers)+ : null);+ report(usedKey);+ }+ return response;+ };+ return wrapped as typeof fetch;+}diff --git a/apps/desktop/src/main/model-access/index.ts b/apps/desktop/src/main/model-access/index.tsindex d30b1be075..d3a6f745a7 100644--- a/apps/desktop/src/main/model-access/index.ts+++ b/apps/desktop/src/main/model-access/index.ts@@ -36,6 +36,11 @@ import {} from '../../shared/modelAccess.js';import { getModelAccessCredentialsStore } from './credentialsStore.js';import { getAppCapabilities } from '../appCapabilities.js';+import { isAppSessionBoundaryPending } from '../appSessionState.js';+import {+ createGatewayKeyRejectionReporter,+ installCindyGatewayKeyRejectionReporter,+} from './gatewayKeyRejection.js';import {createCredentialsSync,type CredentialsPayload,@@ -57,6 +62,7 @@ import {resetExecutableMediaModelCache,} from './mediaModels.js';export { isModelAccessReady } from './readiness.js';+export { reportCindyGatewayKeyRejected } from './gatewayKeyRejection.js';const log = createLogger('modelAccess');@@ -510,6 +516,18 @@ function mapServerError(err: unknown): never {*/export function initModelAccess(): void {const sync = getSync();+ // 主进程各调用方遇到 Cindy 网关 401 时经此重新拉取凭据(服务端会探测并换发失效 Key)。+ installCindyGatewayKeyRejectionReporter(createGatewayKeyRejectionReporter({+ canUseCindyGateway: () => getAppCapabilities().canUseCindyGateway,+ isSessionBoundaryPending: isAppSessionBoundaryPending,+ getCredentialSource: () => getModelAccessCredentialsStore().getSource(),+ readCurrentKey: () => getProviderSecretStore().get('xd'),+ requestSync: () => getSync().sync(),+ log: {+ info: (msg) => log.info(msg),+ warn: (msg) => log.warn(msg),+ },+ }));const byok = createByokRuntime(broadcastReferenceModelPricing,createByokCache(byokSnapshotSecretIo),@@ -603,6 +621,7 @@ export function resetModelAccessForTest(): void {app.removeListener('browser-window-focus', foregroundRefreshListener);foregroundRefreshListener = null;}+ installCindyGatewayKeyRejectionReporter(null);syncInstance = null;modelsSyncInflight = null;modelsSyncGen = -1;diff --git a/apps/desktop/src/main/usage/__tests__/claudeAccountUsageKeyRejection.test.ts b/apps/desktop/src/main/usage/__tests__/claudeAccountUsageKeyRejection.test.tsnew file mode 100644index 0000000000..0f20fa4d13--- /dev/null+++ b/apps/desktop/src/main/usage/__tests__/claudeAccountUsageKeyRejection.test.ts@@ -0,0 +1,99 @@+/**+ * 额度查询遇到 Cindy 网关 401 时上报 Cindy AI Key 失效(其余状态不上报)。+ * 只断言上报行为;配额解析契约见 claudeAccountUsageSource.test.ts。+ */+import { beforeEach, describe, expect, it, vi } from 'vitest';++const mocks = vi.hoisted(() => ({+ outboundFetch: vi.fn(),+ report: vi.fn(),+}));++vi.mock('electron', () => ({+ BrowserWindow: { getAllWindows: () => [] },+}));+vi.mock('../../authManager', () => ({+ getAuthState: () => ({+ mode: 'cloud',+ user: { id: 'user-1', membershipKind: 'org' },+ dataOwnerId: 'user-1',+ }),+}));+vi.mock('../../device-link/broadcast-tap.js', () => ({ tapWindowBroadcast: vi.fn() }));+vi.mock('../../logger', () => ({+ createLogger: () => ({ debug: vi.fn(), info: vi.fn(), warn: vi.fn(), error: vi.fn() }),+}));+vi.mock('../../maker-host/auth-adapters', () => ({+ readClaudeApiKey: () => 'usage-key-sent',+}));+vi.mock('../../maker-host/outbound-fetch', () => ({ outboundFetch: mocks.outboundFetch }));+vi.mock('../../maker-host/runtime-configs', () => ({+ claudeUpstreamEndpoint: () => 'https://gateway.test.invalid',+}));+vi.mock('../modelPricing', () => ({ getGatewayAccountCurrency: async () => 'USD' }));+vi.mock('../ledgerCurrency', () => ({ currentLedgerCurrency: () => 'USD' }));+vi.mock('../../model-access/gatewayKeyRejection', () => ({+ reportCindyGatewayKeyRejected: mocks.report,+}));++import { triggerClaudeAccountUsageRefresh } from '../claudeAccountUsage';++function jsonResponse(body: unknown, status = 200): Response {+ return new Response(JSON.stringify(body), { status });+}++describe('claudeAccountUsage Cindy AI key rejection', () => {+ beforeEach(() => {+ mocks.outboundFetch.mockReset();+ mocks.report.mockReset();+ });++ it('reports the sent key when user/info and daily/activity are rejected with 401', async () => {+ mocks.outboundFetch.mockImplementation(async () => jsonResponse({ error: 'invalid key' }, 401));++ await triggerClaudeAccountUsageRefresh(true);++ expect(mocks.outboundFetch).toHaveBeenCalledTimes(2);+ for (const call of mocks.outboundFetch.mock.calls) {+ expect(call[1]).toMatchObject({ headers: { Authorization: 'Bearer usage-key-sent' } });+ }+ expect(mocks.report).toHaveBeenCalledTimes(2);+ expect(mocks.report).toHaveBeenNthCalledWith(1, 'usage-key-sent');+ expect(mocks.report).toHaveBeenNthCalledWith(2, 'usage-key-sent');+ });++ it('reports only the endpoint that was rejected with 401', async () => {+ mocks.outboundFetch.mockImplementation(async (url: string) =>+ url.includes('/user/daily/activity')+ ? jsonResponse({ error: 'invalid key' }, 401)+ : jsonResponse({ spend: 1, max_budget: 10, budget_reset_at: null }),+ );++ await triggerClaudeAccountUsageRefresh(true);++ expect(mocks.report).toHaveBeenCalledTimes(1);+ expect(mocks.report).toHaveBeenCalledWith('usage-key-sent');+ });++ it.each([403, 500])('does not report HTTP %s', async (status) => {+ mocks.outboundFetch.mockImplementation(async () => jsonResponse({ error: 'nope' }, status));++ await triggerClaudeAccountUsageRefresh(true);++ expect(mocks.outboundFetch).toHaveBeenCalled();+ expect(mocks.report).not.toHaveBeenCalled();+ });++ it('does not report successful quota responses', async () => {+ mocks.outboundFetch.mockImplementation(async (url: string) =>+ url.includes('/user/daily/activity')+ ? jsonResponse({ results: [] })+ : jsonResponse({ spend: 1, max_budget: 10, budget_reset_at: null }),+ );++ await triggerClaudeAccountUsageRefresh(true);++ expect(mocks.outboundFetch).toHaveBeenCalledTimes(2);+ expect(mocks.report).not.toHaveBeenCalled();+ });+});diff --git a/apps/desktop/src/main/usage/claudeAccountUsage.ts b/apps/desktop/src/main/usage/claudeAccountUsage.tsindex 43f26d7bd0..d1fec0b434 100644--- a/apps/desktop/src/main/usage/claudeAccountUsage.ts+++ b/apps/desktop/src/main/usage/claudeAccountUsage.ts@@ -47,6 +47,7 @@ import { getAuthState } from '../authManager';import { tapWindowBroadcast } from '../device-link/broadcast-tap.js';import { createLogger } from '../logger';import { readClaudeApiKey } from '../maker-host/auth-adapters';+import { reportCindyGatewayKeyRejected } from '../model-access/gatewayKeyRejection';import { outboundFetch } from '../maker-host/outbound-fetch';import { claudeUpstreamEndpoint } from '../maker-host/runtime-configs';import { getGatewayAccountCurrency } from './modelPricing';@@ -149,6 +150,7 @@ async function fetchUserInfo(signal,});if (!res.ok) {+ if (res.status === 401) reportCindyGatewayKeyRejected(apiKey);log.debug(`user/info non-2xx: ${res.status}`);return null;}@@ -181,6 +183,7 @@ async function fetchTodayActivity({ headers: { Authorization: `Bearer ${apiKey}` }, signal },);if (!res.ok) {+ if (res.status === 401) reportCindyGatewayKeyRejected(apiKey);log.debug(`daily/activity non-2xx: ${res.status}`);return null;}diff --git a/apps/desktop/src/main/utility-model/__tests__/oneShotCandidates.test.ts b/apps/desktop/src/main/utility-model/__tests__/oneShotCandidates.test.tsindex 0429f69981..3a69dac581 100644--- a/apps/desktop/src/main/utility-model/__tests__/oneShotCandidates.test.ts+++ b/apps/desktop/src/main/utility-model/__tests__/oneShotCandidates.test.ts@@ -92,6 +92,10 @@ vi.mock('../../model-access/effectiveEndpoint.js', async () => {return { effectiveXdGatewayBaseUrl: () => TEST_XD_GATEWAY_BASE_URL };});+vi.mock('../../model-access/gatewayKeyRejection.js', () => ({+ reportCindyGatewayKeyRejected: vi.fn(),+}));+import type { Maker } from '@cindy/maker-core';import { DictationDictionaryAdvisor } from '@cindy/voice-input-core';import { DictionaryLearningTextModelClient } from '../../voice-input/DictionaryLearningTextModelClient.js';@@ -109,6 +113,7 @@ import {import { readModelDisableOverrides } from '../../maker-host/model-disable-store.js';import { isProviderRouteMutationInProgress } from '../../maker-host/provider-route.js';import { readCustomProviderKey } from '../../secrets/providerSecretStore.js';+import { reportCindyGatewayKeyRejected } from '../../model-access/gatewayKeyRejection.js';import { getUtilityModelChainProfiles } from '../UtilityModelSelection.js';import {DEDICATED_AUTO_REVIEW_CANDIDATES,@@ -132,6 +137,7 @@ const xdPaymentRequiredRoute = vi.mocked(isXdGatewayPaymentRequiredRoute);const readDisableOverrides = vi.mocked(readModelDisableOverrides);const providerRouteMutationInProgress = vi.mocked(isProviderRouteMutationInProgress);const readCustomKey = vi.mocked(readCustomProviderKey);+const reportKeyRejected = vi.mocked(reportCindyGatewayKeyRejected);function makerMock(authenticated: boolean): Maker {return {@@ -2977,4 +2983,142 @@ describe('utility one-shot candidates', () => {});expect(JSON.parse(String(fetchMock.mock.calls[0]?.[1]?.body))).not.toHaveProperty('thinking');});++ describe('Cindy AI key rejection reports', () => {+ const xdCatalog = {+ providers: [{+ id: 'xd',+ name: 'XD Gateway',+ source: 'builtin',+ agents: ['claude-code'],+ auth: { method: 'managed' },+ routing: {+ 'claude-code': { upstream: 'https://ignored.invalid', authStrategy: 'gateway-key' },+ },+ models: {+ 'claude-code': [{ id: 'gpt-5.5', name: 'GPT-5.5', contextWindow: 1_000_000 }],+ },+ }],+ };+ const unauthorized = () => ({+ ok: false,+ status: 401,+ body: { cancel: vi.fn(async () => undefined) },+ });++ it('reports the exact key sent by an explicit XD request rejected with 401', async () => {+ activeCatalog.mockReturnValue(xdCatalog as never);+ readKey.mockReturnValue('xd-key-sent');+ fetchMock.mockResolvedValueOnce(unauthorized() as never);++ const result = await requestUtilityText(makerMock(false), 'generate', {+ providerId: 'xd',+ agentKind: 'claude-code',+ model: 'gpt-5.5',+ });++ expect(result).toMatchObject({+ ok: false,+ attempts: [expect.objectContaining({ providerId: 'xd', reason: 'http_error', httpStatus: 401 })],+ });+ expect(fetchMock.mock.calls[0]?.[1]?.headers).toMatchObject({ Authorization: 'Bearer xd-key-sent' });+ expect(reportKeyRejected).toHaveBeenCalledTimes(1);+ expect(reportKeyRejected).toHaveBeenCalledWith('xd-key-sent');+ });++ it('does not report a successful XD request', async () => {+ activeCatalog.mockReturnValue(xdCatalog as never);+ readKey.mockReturnValue('xd-key-sent');+ fetchMock.mockResolvedValueOnce({+ ok: true,+ text: async () => JSON.stringify({ choices: [{ message: { content: 'script' } }] }),+ } as never);++ const result = await requestUtilityText(makerMock(false), 'generate', {+ providerId: 'xd',+ agentKind: 'claude-code',+ model: 'gpt-5.5',+ });++ expect(result).toMatchObject({ ok: true });+ expect(reportKeyRejected).not.toHaveBeenCalled();+ });++ it('does not report a non-401 XD failure', async () => {+ activeCatalog.mockReturnValue(xdCatalog as never);+ readKey.mockReturnValue('xd-key-sent');+ fetchMock.mockResolvedValueOnce({+ ok: false,+ status: 403,+ body: { cancel: vi.fn(async () => undefined) },+ } as never);++ await requestUtilityText(makerMock(false), 'generate', {+ providerId: 'xd',+ agentKind: 'claude-code',+ model: 'gpt-5.5',+ });++ expect(reportKeyRejected).not.toHaveBeenCalled();+ });++ it('does not report a 401 from another provider', async () => {+ activeCatalog.mockReturnValue({+ providers: [{+ id: 'tapsvc',+ name: 'Tap Service',+ source: 'user',+ agents: ['codex'],+ auth: { method: 'apiKey' },+ routing: { codex: { upstream: 'https://custom.example/v1', authStrategy: 'api-key-header' } },+ models: { codex: [{ id: 'custom-mini', name: 'Custom Mini', contextWindow: 100_000 }] },+ }],+ } as never);+ readCustomKey.mockReturnValue('custom-secret');+ readKey.mockReturnValue('xd-key-stored');+ fetchMock.mockResolvedValueOnce(unauthorized() as never);++ await requestUtilityText(makerMock(false), 'generate', {+ providerId: 'tapsvc',+ agentKind: 'codex',+ model: 'custom-mini',+ });++ expect(fetchMock).toHaveBeenCalledTimes(1);+ expect(reportKeyRejected).not.toHaveBeenCalled();+ });++ it('reports the key of an auxiliary-chain LiteLLM request rejected with 401', async () => {+ chainState.refs = ['litellm-gpt-5.4-mini'];+ readKey.mockReturnValue('proxy-key-sent');+ fetchMock.mockResolvedValueOnce(unauthorized() as never);++ const result = await requestUtilityText(makerMock(false), 'hello');++ expect(result).toMatchObject({+ ok: false,+ attempts: expect.arrayContaining([+ expect.objectContaining({ providerId: 'litellm-gpt-5.4-mini', httpStatus: 401 }),+ ]),+ });+ expect(reportKeyRejected).toHaveBeenCalledTimes(1);+ expect(reportKeyRejected).toHaveBeenCalledWith('proxy-key-sent');+ });++ it('reports the key of the cindy-gateway Auto-review candidate rejected with 401', async () => {+ readKey.mockReturnValue('review-key-sent');+ fetchMock.mockResolvedValueOnce(unauthorized() as never);++ const result = await requestDedicatedAutoReviewCandidateText(+ 'classify',+ DEDICATED_AUTO_REVIEW_CANDIDATES[0],+ { timeoutMs: 8_000 },+ );++ expect(result).toMatchObject({ ok: false });+ expect(fetchMock.mock.calls[0]?.[1]?.headers).toMatchObject({ Authorization: 'Bearer review-key-sent' });+ expect(reportKeyRejected).toHaveBeenCalledTimes(1);+ expect(reportKeyRejected).toHaveBeenCalledWith('review-key-sent');+ });+ });});diff --git a/apps/desktop/src/main/utility-model/oneShotCandidates.ts b/apps/desktop/src/main/utility-model/oneShotCandidates.tsindex 862ea6cdde..c26272804e 100644--- a/apps/desktop/src/main/utility-model/oneShotCandidates.ts+++ b/apps/desktop/src/main/utility-model/oneShotCandidates.ts@@ -27,6 +27,7 @@ import { isModelDisabled, isProviderDisabled } from '@cindy/model-providers';import { isProviderRouteMutationInProgress } from '../maker-host/provider-route.js';import { withOpenCodeGoSessionHeader } from '../maker-host/opencode-go-session.js';import { effectiveXdGatewayBaseUrl } from '../model-access/effectiveEndpoint.js';+import { reportCindyGatewayKeyRejected } from '../model-access/gatewayKeyRejection.js';import { readCustomProviderKey } from '../secrets/providerSecretStore.js';import { MANAGED_OLLAMA_PROVIDER_ID, isManagedSidecarProviderId } from '../../shared/localModelRuntime.js';import { ensureManagedOllamaReadyForSession } from '../local-model-runtime/preflight.js';@@ -471,6 +472,7 @@ export async function requestDedicatedAutoReviewCandidateText(maxTokens: DEDICATED_AUTO_REVIEW_MAX_TOKENS,timeoutMs: requestOpts?.timeoutMs ?? opts.timeoutMs,signal: requestOpts?.signal ?? opts.signal,+ onUnauthorized: () => reportCindyGatewayKeyRejected(apiKey),}),}], evidence, [], {maxTokens: DEDICATED_AUTO_REVIEW_MAX_TOKENS,@@ -1128,6 +1130,7 @@ async function requestBuiltinProviderText(? () => readClaudeApiKey() === apiKey && effectiveXdGatewayBaseUrl().trim() === baseUrl: undefined,routeStillCurrent: requestOpts?.beforeDispatch ? input.routeStillCurrent : undefined,+ onUnauthorized: () => reportCindyGatewayKeyRejected(apiKey),}),}], prompt, [], input);}@@ -1451,6 +1454,8 @@ async function requestLiteLlmText(input: {};let response = await send();if (!response.ok) {+ // This path always carries the Cindy AI key to the Cindy gateway.+ if (response.status === 401) reportCindyGatewayKeyRejected(input.apiKey);// Do not retain or log upstream response bodies: gateways may echo request// metadata, while the HTTP status is sufficient for user recovery.await response.body?.cancel().catch(() => undefined);@@ -1589,6 +1594,11 @@ async function requestProviderHttpText(input: {credentialStillCurrent?: () => boolean | Promise<boolean>;/** Synchronous catalog/override snapshot guard. */routeStillCurrent?: () => boolean;+ /**+ * Called when the final response is HTTP 401. Only the Cindy AI (xd) gateway branches+ * pass it, so a stale Cindy AI key can be re-synced; other providers keep plain 401s.+ */+ onUnauthorized?: () => void;}): Promise<string> {const controller = new AbortController();const timeoutMs = input.timeoutMs ?? 90_000;@@ -1705,6 +1715,7 @@ async function requestProviderHttpText(input: {minimalBody = true;}if (!response.ok) {+ if (response.status === 401) input.onUnauthorized?.();await response.body?.cancel().catch(() => undefined);throw new UtilityTextExecutionError({ reason: 'http_error', httpStatus: response.status });}diff --git a/apps/desktop/src/main/voice-input/LiteLlmTextModelClient.ts b/apps/desktop/src/main/voice-input/LiteLlmTextModelClient.tsindex 487dd472d1..2a94868d7d 100644--- a/apps/desktop/src/main/voice-input/LiteLlmTextModelClient.ts+++ b/apps/desktop/src/main/voice-input/LiteLlmTextModelClient.ts@@ -6,6 +6,7 @@ import { fetch as undiciFetch, type Agent, type Response as UndiciResponse } froimport type { TextModelClient } from '@cindy/voice-input-core';import { createLogger } from '../logger.js';+import { reportCindyGatewayKeyRejected } from '../model-access/gatewayKeyRejection.js';import { describeErrorWithCause, markRefinerModelOutputError } from './refinerErrorKind.js';import { createRefinerHttpDispatcher, resolveRefinerDispatcher } from './refinerHttpDispatcher.js';import { extractJsonStringFieldSnapshot } from './streamingJson.js';@@ -196,6 +197,10 @@ export class LiteLlmTextModelClient implements TextModelClient {if (response.status === 401 && this.requestTargetProvider) {await response.arrayBuffer().catch(() => undefined);response = await sendRequest(true);+ } else if (response.status === 401 && this.proxyApiKey) {+ // The proxy-key branch sends the Cindy AI key to the Cindy gateway; the+ // managed requestTargetProvider branch above uses Cindy voice tokens instead.+ reportCindyGatewayKeyRejected(this.proxyApiKey);}const headersAt = performance.now();armIdleTimeout('response body');diff --git a/apps/desktop/src/main/voice-input/LiteLlmTranscriptionProvider.ts b/apps/desktop/src/main/voice-input/LiteLlmTranscriptionProvider.tsindex 51db4e9ba9..01d6840f9a 100644--- a/apps/desktop/src/main/voice-input/LiteLlmTranscriptionProvider.ts+++ b/apps/desktop/src/main/voice-input/LiteLlmTranscriptionProvider.ts@@ -1,6 +1,7 @@import type { AsrEvent, AsrProvider } from '@cindy/voice-input-core';import { outboundFetch } from '../maker-host/outbound-fetch.js';+import { reportCindyGatewayKeyRejected } from '../model-access/gatewayKeyRejection.js';import { elevenLabsLanguageCode } from './language.js';type LiteLlmTranscriptionProviderOptions = {@@ -123,6 +124,8 @@ export async function transcribeLiteLlmAudioFile(input: LiteLlmAudioFileTranscri}if (!response.ok) {+ // proxyApiKey is the Cindy AI key sent to the Cindy gateway.+ if (response.status === 401) reportCindyGatewayKeyRejected(input.proxyApiKey);throw new Error(transcriptionErrorMessage(parsed, text, response.status));}diff --git a/apps/desktop/src/main/voice-input/RealtimeAsrWebSocketProvider.ts b/apps/desktop/src/main/voice-input/RealtimeAsrWebSocketProvider.tsindex 0f7ace4653..84599ba4b7 100644--- a/apps/desktop/src/main/voice-input/RealtimeAsrWebSocketProvider.ts+++ b/apps/desktop/src/main/voice-input/RealtimeAsrWebSocketProvider.ts@@ -29,6 +29,11 @@ export type RealtimeAsrWebSocketProviderOptions = {errorFallbackMessage?: string;/** Replace upstream application error text with errorFallbackMessage. */redactUpstreamErrors?: boolean;+ /**+ * Called with the token from accessTokenProvider when the WebSocket handshake is+ * rejected with HTTP 401. Only the Cindy AI key (gateway proxy) path passes it.+ */+ onAuthorizationRejected?: (accessToken: string) => void;};const OPENAI_REALTIME_TRANSCRIPTION_URL = 'wss://api.openai.com/v1/realtime?intent=transcription';@@ -627,6 +632,7 @@ export class RealtimeAsrWebSocketProvider implements AsrProvider {private readonly missingCredentialMessage: string;private readonly errorFallbackMessage: string;private readonly redactUpstreamErrors: boolean;+ private readonly onAuthorizationRejected?: (accessToken: string) => void;private socket?: WebSocket;private callback: (event: AsrEvent) => void = () => {};private connected = false;@@ -685,6 +691,7 @@ export class RealtimeAsrWebSocketProvider implements AsrProvider {constructor(options: RealtimeAsrWebSocketProviderOptions) {this.accessTokenProvider = options.accessTokenProvider;this.connectionProvider = options.connectionProvider;+ this.onAuthorizationRejected = options.onAuthorizationRejected;this.sourceLanguage = options.sourceLanguage ?? 'auto';this.model = options.model ?? OPENAI_REALTIME_WHISPER_MODEL;this.pcmSampleRate = options.pcmSampleRate ?? DEFAULT_REALTIME_PCM_SAMPLE_RATE;@@ -772,6 +779,7 @@ export class RealtimeAsrWebSocketProvider implements AsrProvider {this.socket = socket;this.attachSocketHandlers(socket);+ const onAuthorizationRejected = this.onAuthorizationRejected;await this.waitForSessionReady(socket, () => {socket.once('open', () => {this.connected = true;@@ -779,7 +787,9 @@ export class RealtimeAsrWebSocketProvider implements AsrProvider {this.startHealthLog();this.sendSessionUpdate();});- });+ }, dynamicConnection || !onAuthorizationRejected+ ? undefined+ : () => onAuthorizationRejected(accessToken));}private attachSocketHandlers(socket: WebSocket): void {@@ -839,7 +849,11 @@ export class RealtimeAsrWebSocketProvider implements AsrProvider {});}- private async waitForSessionReady(socket: WebSocket, begin: () => void): Promise<void> {+ private async waitForSessionReady(+ socket: WebSocket,+ begin: () => void,+ onUnauthorized?: () => void,+ ): Promise<void> {await new Promise<void>((resolve, reject) => {let settled = false;const cleanup = (): void => {@@ -882,6 +896,7 @@ export class RealtimeAsrWebSocketProvider implements AsrProvider {const onUnexpectedResponse = (_request: ClientRequest, response: IncomingMessage): void => {response.resume();const statusCode = response.statusCode ?? 'unknown';+ if (statusCode === 401) onUnauthorized?.();if (this.redactUpstreamErrors) {const statusSuffix = typeof statusCode === 'number' ? ` (HTTP ${statusCode})` : '';fail(new Error(`${this.errorFallbackMessage}${statusSuffix}`), true);diff --git a/apps/desktop/src/main/voice-input/__tests__/LiteLlmTextModelClient.test.ts b/apps/desktop/src/main/voice-input/__tests__/LiteLlmTextModelClient.test.tsindex f6bac17fe1..499dd814b5 100644--- a/apps/desktop/src/main/voice-input/__tests__/LiteLlmTextModelClient.test.ts+++ b/apps/desktop/src/main/voice-input/__tests__/LiteLlmTextModelClient.test.ts@@ -9,6 +9,11 @@ vi.mock('undici', async (importOriginal) => {};});+const reportKeyRejectedMock = vi.hoisted(() => vi.fn());+vi.mock('../../model-access/gatewayKeyRejection.js', () => ({+ reportCindyGatewayKeyRejected: reportKeyRejectedMock,+}));+import { LiteLlmTextModelClient } from '../LiteLlmTextModelClient.js';import { isRefinerModelOutputError } from '../refinerErrorKind.js';@@ -29,9 +34,39 @@ function chatCompletionSseChunk(content: string): string {describe('LiteLlmTextModelClient', () => {afterEach(() => {undiciFetchMock.mockReset();+ reportKeyRejectedMock.mockReset();vi.useRealTimers();});+ it('reports the Cindy AI key when the gateway proxy rejects it with HTTP 401', async () => {+ undiciFetchMock.mockResolvedValueOnce(new Response(JSON.stringify({+ error: { message: 'invalid key' },+ }), { status: 401 }));++ const client = new LiteLlmTextModelClient({+ proxyApiKey: 'proxy-key-sent',+ baseUrl: 'https://llm-proxy.example.com',+ });++ await expect(client.requestJson({ model: 'm', schemaName: 's', system: 'sys', user: {} }))+ .rejects.toThrow();+ expect(undiciFetchMock).toHaveBeenCalledTimes(1);+ expect(reportKeyRejectedMock).toHaveBeenCalledTimes(1);+ expect(reportKeyRejectedMock).toHaveBeenCalledWith('proxy-key-sent');+ });++ it('does not report non-401 proxy failures', async () => {+ undiciFetchMock.mockResolvedValueOnce(new Response('{}', { status: 403 }));+ const client = new LiteLlmTextModelClient({+ proxyApiKey: 'proxy-key-sent',+ baseUrl: 'https://llm-proxy.example.com',+ });++ await expect(client.requestJson({ model: 'm', schemaName: 's', system: 'sys', user: {} }))+ .rejects.toThrow();+ expect(reportKeyRejectedMock).not.toHaveBeenCalled();+ });+it('streams chat completion deltas, emits text snapshots, and reports usage', async () => {const usages: Array<{ promptTokens?: number; completionTokens?: number; cachedTokens?: number }> = [];const snapshots: string[] = [];@@ -258,6 +293,8 @@ describe('LiteLlmTextModelClient', () => {expect(undiciFetchMock.mock.calls[1]?.[1]).toMatchObject({headers: expect.objectContaining({ Authorization: 'Bearer fresh-token' }),});+ // Managed voice tokens are not Cindy AI keys.+ expect(reportKeyRejectedMock).not.toHaveBeenCalled();});it('uses stream-idle timeout instead of total request duration', async () => {diff --git a/apps/desktop/src/main/voice-input/__tests__/LiteLlmTranscriptionProvider.test.ts b/apps/desktop/src/main/voice-input/__tests__/LiteLlmTranscriptionProvider.test.tsindex 2f16e5eb62..5571aa798b 100644--- a/apps/desktop/src/main/voice-input/__tests__/LiteLlmTranscriptionProvider.test.ts+++ b/apps/desktop/src/main/voice-input/__tests__/LiteLlmTranscriptionProvider.test.ts@@ -5,6 +5,11 @@ vi.mock('../../maker-host/outbound-fetch.js', () => ({outboundFetch: (...args: unknown[]) => outboundFetchMock(...args),}));+const reportKeyRejectedMock = vi.hoisted(() => vi.fn());+vi.mock('../../model-access/gatewayKeyRejection.js', () => ({+ reportCindyGatewayKeyRejected: reportKeyRejectedMock,+}));+import {LiteLlmTranscriptionProvider,transcribeLiteLlmAudioFile,@@ -14,6 +19,22 @@ import type { AsrEvent } from '@cindy/voice-input-core';describe('LiteLlmTranscriptionProvider', () => {afterEach(() => {outboundFetchMock.mockReset();+ reportKeyRejectedMock.mockReset();+ });++ it.each([+ [401, 1],+ [403, 0],+ ] as const)('reports the sent Cindy AI key on HTTP %s only when unauthorized', async (status, reports) => {+ outboundFetchMock.mockResolvedValue(new Response(JSON.stringify({ detail: 'rejected' }), { status }));++ await expect(transcribeLiteLlmAudioFile({+ proxyApiKey: 'sk-sent',+ baseUrl: 'https://gateway.example',+ bytes: Buffer.from([1, 2, 3]),+ })).rejects.toThrow('rejected');+ expect(reportKeyRejectedMock).toHaveBeenCalledTimes(reports);+ if (reports > 0) expect(reportKeyRejectedMock).toHaveBeenCalledWith('sk-sent');});it('posts captured audio to LiteLLM using ElevenLabs Scribe v2', async () => {diff --git a/apps/desktop/src/main/voice-input/__tests__/RealtimeAsrWebSocketProvider.test.ts b/apps/desktop/src/main/voice-input/__tests__/RealtimeAsrWebSocketProvider.test.tsindex cee7add429..79a0e95db6 100644--- a/apps/desktop/src/main/voice-input/__tests__/RealtimeAsrWebSocketProvider.test.ts+++ b/apps/desktop/src/main/voice-input/__tests__/RealtimeAsrWebSocketProvider.test.ts@@ -325,6 +325,43 @@ describe('RealtimeAsrWebSocketProvider helpers', () => {}});+ it.each([+ [401, 1],+ [403, 0],+ ] as const)('reports the sent token on handshake HTTP %s only when unauthorized', async (status, reports) => {+ const server = new WebSocketServer({+ port: 0,+ verifyClient(_info, done) {+ done(false, status, 'Rejected');+ },+ });+ let provider: RealtimeAsrWebSocketProvider | undefined;+ const onAuthorizationRejected = vi.fn();++ try {+ await waitFor(() => server.address() !== null);+ const address = server.address();+ if (!address || typeof address === 'string') throw new Error('Expected local test server address.');++ provider = new RealtimeAsrWebSocketProvider({+ accessTokenProvider: async () => 'gateway-key-sent',+ realtimeUrl: `ws://127.0.0.1:${address.port}/v1/realtime`,+ model: 'gpt-realtime-whisper',+ providerKind: 'litellm-gpt-realtime-whisper',+ connectTimeoutMs: 2_000,+ onAuthorizationRejected,+ });+ provider.onEvent(() => {});++ await expect(provider.start()).rejects.toThrow(`HTTP ${status}`);+ expect(onAuthorizationRejected).toHaveBeenCalledTimes(reports);+ if (reports > 0) expect(onAuthorizationRejected).toHaveBeenCalledWith('gateway-key-sent');+ } finally {+ await provider?.stop();+ await new Promise<void>((resolve) => server.close(() => resolve()));+ }+ });+it('redacts custom handshake details while preserving the HTTP status for classification', async () => {const server = new WebSocketServer({port: 0,diff --git a/apps/desktop/src/main/voice-input/index.ts b/apps/desktop/src/main/voice-input/index.tsindex b89f9c8aa2..55e15e70d9 100644--- a/apps/desktop/src/main/voice-input/index.ts+++ b/apps/desktop/src/main/voice-input/index.ts@@ -38,6 +38,7 @@ import {desktopCodexAuthAdapter,readOwnerScopedXdGatewayKey,} from '../maker-host/auth-adapters.js';+import { reportCindyGatewayKeyRejected } from '../model-access/gatewayKeyRejection.js';import {activeOwnerScopeKey,getActiveAppSession,@@ -1760,12 +1761,16 @@ async function createVoiceInputProvider(}const { proxyApiKey, proxyBaseUrl } = readLiteLlmProxyConfig();if (!proxyApiKey || !proxyBaseUrl) throw new Error(profile.missingCredentialMessage);- return new RealtimeAsrWebSocketProvider(buildRealtimeAsrProviderOptions(- profile,- sourceLanguage,- () => Promise.resolve(proxyApiKey),- proxyBaseUrl,- ));+ return new RealtimeAsrWebSocketProvider({+ ...buildRealtimeAsrProviderOptions(+ profile,+ sourceLanguage,+ () => Promise.resolve(proxyApiKey),+ proxyBaseUrl,+ ),+ // 这条直连网关的 WebSocket 携带 Cindy AI Key;握手 401 时上报 Key 失效。+ onAuthorizationRejected: reportCindyGatewayKeyRejected,+ });}throw new Error(`Unsupported realtime ASR provider ${provider}.`);}