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(model-access): 智能体回合的 Key 失效上报不再占用新 Key 的触发机会

fmfsaisai38d5e7024a85
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/sessionEventPipeline.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/sessionEventPipeline.test.ts
index 7d63f4a41a..b750105b87 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/sessionEventPipeline.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/sessionEventPipeline.test.ts
@@ -13,6 +13,7 @@ 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';
+import { reportCindyGatewayKeyRejectedForCurrentKey } from '../../model-access/gatewayKeyRejection.js';
const effects = vi.hoisted(() => {
const calls: string[] = [];
@@ -34,6 +35,10 @@ vi.mock('../../maker-host/model-discovery/xai.js', () => ({
discardXaiModelsDiskCache: vi.fn(async () => {}),
}));
+// register.ts wires the agent-turn dependency to this current-key entry; assert against it.
+vi.mock('../../model-access/gatewayKeyRejection.js', () => ({
+ reportCindyGatewayKeyRejectedForCurrentKey: vi.fn(),
+}));
vi.mock('../../local-model-runtime/preflight.js', () => ({
ensureManagedOllamaReadyForSession: effects.fn('ensureManagedOllamaReadyForSession'),
}));
@@ -320,7 +325,7 @@ function harness() {
handleSilentStopTurnEnd: vi.fn(async () => {}),
isRemoteAuthRetryErrorEvent: vi.fn(() => false),
isGatewayProxyTokenRecoveryErrorEvent: vi.fn<(sessionId: string, event: AgentEvent) => boolean>(() => false),
- reportAgentCindyGatewayKeyRejected: vi.fn(),
+ reportAgentCindyGatewayKeyRejected: vi.mocked(reportCindyGatewayKeyRejectedForCurrentKey),
overflowSuppressedBroadcasts: new Map(),
handleAgentIslandEventAfterBroadcast: effects.fn('island'),
notifyGoalIdleAfterTurnSettled: vi.fn(() => {
@@ -694,6 +699,7 @@ describe('production Session event pipeline', () => {
['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();
+ h.deps.reportAgentCindyGatewayKeyRejected.mockClear();
// The production predicate, bound to this session's provider.
h.deps.isGatewayProxyTokenRecoveryErrorEvent.mockImplementation((_sessionId, value) =>
isGatewayProxyTokenRecoveryErrorEventForProvider(providerId, value));
@@ -703,11 +709,14 @@ describe('production Session event pipeline', () => {
reason: GATEWAY_PROXY_TOKEN_INVALID_REASON,
}));
expect(h.deps.reportAgentCindyGatewayKeyRejected).toHaveBeenCalledTimes(reports);
+ // Agents do not reveal the key they used: the current-key entry takes no key argument.
+ if (reports > 0) expect(h.deps.reportAgentCindyGatewayKeyRejected).toHaveBeenCalledWith();
} finally { await h.dispose(); }
});
it('does not report other Cindy AI turn failures or retryable key errors', async () => {
const h = harness();
+ h.deps.reportAgentCindyGatewayKeyRejected.mockClear();
h.deps.isGatewayProxyTokenRecoveryErrorEvent.mockImplementation((_sessionId, value) =>
isGatewayProxyTokenRecoveryErrorEventForProvider('xd', value));
try {
diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.ts
index 724b5eda8f..b3d072a5ea 100644
--- a/apps/desktop/src/main/maker-ipc/register.ts
+++ b/apps/desktop/src/main/maker-ipc/register.ts
@@ -1113,7 +1113,7 @@ import {
storeCustomProviderHeaders,
storeCustomProviderKey,
} from '../secrets/providerSecretStore.js';
-import { reportCindyGatewayKeyRejected } from '../model-access/gatewayKeyRejection.js';
+import { reportCindyGatewayKeyRejectedForCurrentKey } from '../model-access/gatewayKeyRejection.js';
import { isGatewayProxyTokenRecoveryErrorEventForProvider } from './gatewayProxyTokenRecovery.js';
import {
getSessionEffort,
@@ -4697,17 +4697,6 @@ 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 {
return isGatewayProxyTokenRecoveryErrorEventForProvider(getSessionProvider(sessionId), event);
}
@@ -5579,7 +5568,8 @@ const sessionEventDependencies: SessionEventDependencies = {
get handleAgentIslandEventAfterBroadcast() {
return handleAgentIslandEventAfterBroadcast;
},
- reportAgentCindyGatewayKeyRejected,
+ // 智能体不回报所用 Key:走「按当前 Key、不占用触发机会」的入口(见 gatewayKeyRejection.ts)。
+ reportAgentCindyGatewayKeyRejected: reportCindyGatewayKeyRejectedForCurrentKey,
get notifyGoalIdleAfterTurnSettled() {
return notifyGoalIdleAfterTurnSettled;
},
diff --git a/apps/desktop/src/main/model-access/__tests__/gatewayKeyRejection.test.ts b/apps/desktop/src/main/model-access/__tests__/gatewayKeyRejection.test.ts
index c096edc548..405270e47f 100644
--- a/apps/desktop/src/main/model-access/__tests__/gatewayKeyRejection.test.ts
+++ b/apps/desktop/src/main/model-access/__tests__/gatewayKeyRejection.test.ts
@@ -10,6 +10,7 @@ import {
createGatewayKeyRejectionReporter,
installCindyGatewayKeyRejectionReporter,
reportCindyGatewayKeyRejected,
+ reportCindyGatewayKeyRejectedForCurrentKey,
withCindyGatewayKeyRejectionReport,
type GatewayKeyRejectionDeps,
} from '../gatewayKeyRejection.js';
@@ -30,8 +31,10 @@ function harness(overrides: Partial<GatewayKeyRejectionDeps> = {}) {
log,
...overrides,
};
+ const reporter = createGatewayKeyRejectionReporter(deps);
return {
- report: createGatewayKeyRejectionReporter(deps),
+ report: reporter.reportUsedKey,
+ reportCurrent: reporter.reportCurrentKey,
requestSync: (overrides.requestSync as typeof requestSync | undefined) ?? requestSync,
log,
setCurrentKey: (key: string | null) => {
@@ -128,6 +131,76 @@ describe('createGatewayKeyRejectionReporter', () => {
});
});
+describe('reportCurrentKey (agent turns that do not reveal the key they used)', () => {
+ it('re-syncs without consuming the accurate report for the current key', () => {
+ const h = harness();
+ h.reportCurrent();
+ expect(h.requestSync).toHaveBeenCalledTimes(1);
+ // 未占用机会:同一把 Key 的准确上报仍可触发一次。
+ h.report(KEY_A);
+ expect(h.requestSync).toHaveBeenCalledTimes(2);
+ for (const call of [...h.log.info.mock.calls, ...h.log.warn.mock.calls]) {
+ expect(JSON.stringify(call)).not.toContain(KEY_A);
+ }
+ });
+
+ it('skips once the current key was already re-synced by an accurate report', () => {
+ const h = harness();
+ h.report(KEY_A);
+ expect(h.requestSync).toHaveBeenCalledTimes(1);
+ h.reportCurrent();
+ h.reportCurrent();
+ expect(h.requestSync).toHaveBeenCalledTimes(1);
+ });
+
+ it.each([
+ ['gateway capability is unavailable', { canUseCindyGateway: () => false }],
+ ['an account switch is pending', { isSessionBoundaryPending: () => true }],
+ ['the key was entered manually', { getCredentialSource: () => 'manual' as const }],
+ ['there is no current key', { readCurrentKey: () => null }],
+ ])('skips when %s', (_label, overrides) => {
+ const h = harness(overrides);
+ h.reportCurrent();
+ expect(h.requestSync).not.toHaveBeenCalled();
+ });
+
+ it('never lets stale agent failures consume a new key\'s single accurate trigger', () => {
+ const h = harness();
+ // 1. 准确上报 K1,触发同步。
+ h.report(KEY_A);
+ expect(h.requestSync).toHaveBeenCalledTimes(1);
+ // 2. 同步写入 K2。
+ h.setCurrentKey(KEY_B);
+ // 3. 仍带旧 Key 的智能体回合失败若干次:每次都同步,但不标记 K2。
+ h.reportCurrent();
+ h.reportCurrent();
+ h.reportCurrent();
+ expect(h.requestSync).toHaveBeenCalledTimes(4);
+ // 4. K2 真正失效时的准确上报仍触发一次。
+ h.report(KEY_B);
+ expect(h.requestSync).toHaveBeenCalledTimes(5);
+ h.report(KEY_B);
+ expect(h.requestSync).toHaveBeenCalledTimes(5);
+ });
+
+ it('swallows a rejected or throwing sync', async () => {
+ const requestSync = vi.fn(async () => {
+ throw new Error('network down');
+ });
+ const h = harness({ requestSync });
+ expect(() => h.reportCurrent()).not.toThrow();
+ await vi.waitFor(() => expect(h.log.warn).toHaveBeenCalledTimes(1));
+
+ const t = harness({
+ requestSync: () => {
+ throw new Error('sync unavailable');
+ },
+ });
+ expect(() => t.reportCurrent()).not.toThrow();
+ expect(t.log.warn).toHaveBeenCalledTimes(1);
+ });
+});
+
describe('reportCindyGatewayKeyRejected singleton', () => {
afterEach(() => installCindyGatewayKeyRejectionReporter(null));
@@ -135,11 +208,17 @@ describe('reportCindyGatewayKeyRejected singleton', () => {
expect(() => reportCindyGatewayKeyRejected(KEY_A)).not.toThrow();
});
- it('delegates to the installed reporter', () => {
- const reporter = vi.fn();
+ it('delegates both entries to the installed reporter', () => {
+ const reporter = { reportUsedKey: vi.fn(), reportCurrentKey: vi.fn() };
installCindyGatewayKeyRejectionReporter(reporter);
reportCindyGatewayKeyRejected(KEY_A);
- expect(reporter).toHaveBeenCalledWith(KEY_A);
+ reportCindyGatewayKeyRejectedForCurrentKey();
+ expect(reporter.reportUsedKey).toHaveBeenCalledWith(KEY_A);
+ expect(reporter.reportCurrentKey).toHaveBeenCalledTimes(1);
+ });
+
+ it('the current-key entry is a no-op before model-access installs a reporter', () => {
+ expect(() => reportCindyGatewayKeyRejectedForCurrentKey()).not.toThrow();
});
});
diff --git a/apps/desktop/src/main/model-access/gatewayKeyRejection.ts b/apps/desktop/src/main/model-access/gatewayKeyRejection.ts
index da47b4b4bd..b186382bfa 100644
--- a/apps/desktop/src/main/model-access/gatewayKeyRejection.ts
+++ b/apps/desktop/src/main/model-access/gatewayKeyRejection.ts
@@ -40,7 +40,17 @@ export interface GatewayKeyRejectionDeps {
};
}
-export type GatewayKeyRejectionReporter = (usedKey: string | null | undefined) => void;
+/**
+ * 上报器。两个入口共用同一份「已触发过的 Key 指纹」:
+ * - `reportUsedKey`:调用方知道请求实际携带的 Key(规则 A + 规则 B,触发即标记);
+ * - `reportCurrentKey`:调用方不知道用的是哪把 Key(智能体回合终态)。它只在当前 Key
+ * 尚未被准确上报触发过时同步,且**不标记**——否则旧 Key 进程(未重启的 Codex、老任务)
+ * 的迟到 401 会把新 Key 唯一的触发机会用掉,新 Key 真失效时准确上报反被忽略。
+ */
+export interface GatewayKeyRejectionReporter {
+ reportUsedKey(usedKey: string | null | undefined): void;
+ reportCurrentKey(): void;
+}
function keyFingerprint(key: string): string {
return createHash('sha256').update(key).digest('hex');
@@ -52,34 +62,53 @@ export function createGatewayKeyRejectionReporter(
): GatewayKeyRejectionReporter {
let lastTriggeredFingerprint: string | null = null;
- return (usedKey) => {
+ const warn = (prefix: string, error: unknown): void => {
+ deps.log?.warn(`${prefix}: ${error instanceof Error ? error.message : String(error)}`);
+ };
+
+ /** 共同的跳过条件;通过时返回本机当前 Key。 */
+ const currentServerKey = (): string | null => {
+ if (!deps.canUseCindyGateway()) return null;
+ if (deps.isSessionBoundaryPending()) return null;
+ if (deps.getCredentialSource() !== 'server') return null;
+ return deps.readCurrentKey() || null;
+ };
+
+ const triggerSync = (): void => {
+ deps.log?.info('Cindy AI key rejected by gateway, re-syncing credentials');
+ void deps.requestSync().catch((error: unknown) => {
+ warn('Cindy AI credentials re-sync after key rejection failed', error);
+ });
+ };
+
+ // 上报发生在各调用方的错误处理路径里,任何异常都不能改变调用方原有的失败语义。
+ const guarded = (run: () => void): void => {
try {
+ run();
+ } catch (error) {
+ warn('Cindy AI key rejection report failed', error);
+ }
+ };
+
+ return {
+ reportUsedKey: (usedKey) => guarded(() => {
if (!usedKey) return;
- if (!deps.canUseCindyGateway()) return;
- if (deps.isSessionBoundaryPending()) return;
- if (deps.getCredentialSource() !== 'server') return;
+ const currentKey = currentServerKey();
// 规则 A:只认本机当前这把 Key 的拒绝。
- if (deps.readCurrentKey() !== usedKey) return;
+ if (!currentKey || currentKey !== 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)
- }`,
- );
- }
+ triggerSync();
+ }),
+ reportCurrentKey: () => guarded(() => {
+ const currentKey = currentServerKey();
+ if (!currentKey) return;
+ // 当前 Key 已被准确上报同步过一次:不再重复请求(服务端故障时避免每个失败回合都打一次)。
+ if (keyFingerprint(currentKey) === lastTriggeredFingerprint) return;
+ triggerSync();
+ }),
};
}
@@ -98,7 +127,15 @@ export function installCindyGatewayKeyRejectionReporter(
* 初始化时(无凭据同步可触发)直接忽略。
*/
export function reportCindyGatewayKeyRejected(usedKey: string | null | undefined): void {
- installedReporter?.(usedKey);
+ installedReporter?.reportUsedKey(usedKey);
+}
+
+/**
+ * 不知道请求实际用哪把 Key 时的上报(智能体回合因 Key 失效终止)。按本机当前 Key 判断,
+ * 当前 Key 已被准确上报触发过则跳过;触发同步但不占用该 Key 的「只触发一次」机会。
+ */
+export function reportCindyGatewayKeyRejectedForCurrentKey(): void {
+ installedReporter?.reportCurrentKey();
}
/** 从请求头里取 `Authorization: Bearer <key>` 的 key;没有或格式不对返回 null。 */