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): 为自动审核接入自定义辅助模型兜底 (#6228)

bobo6e50085770d4
diff --git a/apps/desktop/src/main/maker-host/__tests__/autoReviewModelRouter.test.ts b/apps/desktop/src/main/maker-host/__tests__/autoReviewModelRouter.test.ts
index 76f7b823df..e90a7713cb 100644
--- a/apps/desktop/src/main/maker-host/__tests__/autoReviewModelRouter.test.ts
+++ b/apps/desktop/src/main/maker-host/__tests__/autoReviewModelRouter.test.ts
@@ -1,10 +1,14 @@
import { afterEach, describe, expect, it, vi } from 'vitest';
+import { getAutoReviewDelegateHardCeilingMs } from '@cindy/maker-core';
import type { UtilityTextResult } from '../../../shared/utilityTextResult.js';
-import { DEDICATED_AUTO_REVIEW_CANDIDATES } from '../../utility-model/oneShotCandidates.js';
+import { DEDICATED_AUTO_REVIEW_CANDIDATES, type AutoReviewAuxiliaryFallback } from '../../utility-model/oneShotCandidates.js';
import {
AUTO_REVIEW_CANDIDATE_TIMEOUT_MS,
AUTO_REVIEW_CHAIN_TIMEOUT_MS,
+ AUTO_REVIEW_AUXILIARY_TIMEOUT_MS,
+ AUTO_REVIEW_TOTAL_TIMEOUT_MS,
+ AUTO_REVIEW_ROUTER_GUARD_TIMEOUT_MS,
createAutoReviewModelRouter,
} from '../auto-review-model-router.js';
@@ -55,6 +59,113 @@ afterEach(() => {
});
describe('dedicated Auto-review candidate policy', () => {
+ it('keeps both routing phases inside the host and core deadlines', () => {
+ expect(AUTO_REVIEW_TOTAL_TIMEOUT_MS).toBe(AUTO_REVIEW_CHAIN_TIMEOUT_MS + AUTO_REVIEW_AUXILIARY_TIMEOUT_MS);
+ expect(AUTO_REVIEW_ROUTER_GUARD_TIMEOUT_MS).toBeGreaterThan(AUTO_REVIEW_TOTAL_TIMEOUT_MS);
+ expect(AUTO_REVIEW_ROUTER_GUARD_TIMEOUT_MS).toBeLessThan(getAutoReviewDelegateHardCeilingMs());
+ });
+
+ it('preserves dedicated review when reading auxiliary settings fails', async () => {
+ const route = createAutoReviewModelRouter({
+ logger: logger(),
+ createAuxiliaryFallback: () => { throw new Error('settings unavailable'); },
+ requestCandidate: async (_prompt, candidate) => succeeded(candidate, '{"verdict":"allow"}'),
+ });
+ await expect(route('classify')).resolves.toBe('{"verdict":"allow"}');
+ });
+
+ it('uses the captured custom fallback only after all dedicated candidates fail', async () => {
+ const calls: string[] = [];
+ const fallback = vi.fn(async (_prompt, opts) => {
+ calls.push('custom');
+ expect(opts.validateResponse('not json')).toBe(false);
+ expect(opts.validateResponse('{"verdict":"ask"}')).toBe(true);
+ return succeeded(DEDICATED_AUTO_REVIEW_CANDIDATES[0], '{"verdict":"allow"}');
+ });
+ const capture = vi.fn(() => {
+ calls.push('capture');
+ return fallback;
+ });
+ const route = createAutoReviewModelRouter({
+ logger: logger(),
+ createAuxiliaryFallback: capture,
+ requestCandidate: async (_prompt, candidate) => {
+ calls.push(candidate.id);
+ return failed(candidate, 'http_error', 402);
+ },
+ });
+
+ await expect(route('classify')).resolves.toBe('{"verdict":"allow"}');
+ expect(calls).toEqual(['capture', 'cindy-gateway', 'chatgpt-nano', 'chatgpt-luna', 'custom']);
+ expect(fallback).toHaveBeenCalledTimes(1);
+ });
+
+ it.each(['allow', 'block', 'ask'])('stops on a valid dedicated %s decision', async (verdict) => {
+ const fallback = vi.fn();
+ const requestCandidate = vi.fn(async (_prompt, candidate) => succeeded(candidate, JSON.stringify({ verdict })));
+ const route = createAutoReviewModelRouter({
+ logger: logger(), requestCandidate, createAuxiliaryFallback: () => fallback,
+ });
+
+ await expect(route('classify')).resolves.toBe(JSON.stringify({ verdict }));
+ expect(requestCandidate).toHaveBeenCalledTimes(1);
+ expect(fallback).not.toHaveBeenCalled();
+ });
+
+ it.each(['malformed', 'throws', 'unavailable'])('returns unavailable when the custom fallback %s', async (failure) => {
+ const route = createAutoReviewModelRouter({
+ logger: logger(),
+ requestCandidate: async (_prompt, candidate) => failed(candidate, 'http_error', 402),
+ createAuxiliaryFallback: () => async () => {
+ if (failure === 'throws') throw new Error('private credential detail');
+ if (failure === 'unavailable') return { ok: false, reason: 'no_candidate', attempts: [] };
+ return succeeded(DEDICATED_AUTO_REVIEW_CANDIDATES[0], 'not a decision');
+ },
+ });
+ await expect(route('classify')).resolves.toBeNull();
+ });
+
+ it('reserves a full auxiliary budget after the dedicated phase exhausts its deadline', async () => {
+ vi.useFakeTimers();
+ const fallback = vi.fn<AutoReviewAuxiliaryFallback>(() => new Promise<UtilityTextResult>(() => undefined));
+ const route = createAutoReviewModelRouter({
+ logger: logger(),
+ candidates: Array.from({ length: 8 }, () => DEDICATED_AUTO_REVIEW_CANDIDATES[0]),
+ requestCandidate: () => new Promise<UtilityTextResult>(() => undefined),
+ createAuxiliaryFallback: () => fallback,
+ });
+ const pending = route('classify');
+ await vi.advanceTimersByTimeAsync(AUTO_REVIEW_CHAIN_TIMEOUT_MS);
+ expect(fallback).toHaveBeenCalledTimes(1);
+ const signal = fallback.mock.calls[0]![1].signal!;
+ await vi.advanceTimersByTimeAsync(AUTO_REVIEW_AUXILIARY_TIMEOUT_MS - 1);
+ expect(signal.aborted).toBe(false);
+ await vi.advanceTimersByTimeAsync(1);
+ await expect(pending).resolves.toBeNull();
+ expect(signal.aborted).toBe(true);
+ });
+
+ it('cancels an auxiliary request even if it ignores its abort signal', async () => {
+ const controller = new AbortController();
+ let started!: () => void;
+ const fallbackStarted = new Promise<void>((resolve) => { started = resolve; });
+ let signal!: AbortSignal;
+ const route = createAutoReviewModelRouter({
+ logger: logger(),
+ requestCandidate: async (_prompt, candidate) => failed(candidate, 'http_error', 402),
+ createAuxiliaryFallback: () => async (_prompt, opts) => {
+ signal = opts.signal!;
+ started();
+ return new Promise<UtilityTextResult>(() => undefined);
+ },
+ });
+ const pending = route('classify', controller.signal);
+ await fallbackStarted;
+ controller.abort();
+ await expect(pending).resolves.toBeNull();
+ expect(signal.aborted).toBe(true);
+ });
+
it('budgets exactly one full timeout per candidate plus a small margin', () => {
expect(AUTO_REVIEW_CHAIN_TIMEOUT_MS).toBe(
DEDICATED_AUTO_REVIEW_CANDIDATES.length * AUTO_REVIEW_CANDIDATE_TIMEOUT_MS + 4_000,
@@ -68,7 +179,7 @@ describe('dedicated Auto-review candidate policy', () => {
])).toEqual([
['xd', 'cindy/auto-review'],
['openai', 'gpt-5.4-nano'],
- ['openai', 'gpt-5.6-luna'],
+ ['openai', 'gpt-6-luna'],
]);
// Claude 订阅只供内置 Claude Code CLI 使用,不作为 Cindy 直连审阅的候选。
expect(JSON.stringify(DEDICATED_AUTO_REVIEW_CANDIDATES)).not.toMatch(
diff --git a/apps/desktop/src/main/maker-host/auto-review-model-router.ts b/apps/desktop/src/main/maker-host/auto-review-model-router.ts
index e228532d2f..a69986b7e1 100644
--- a/apps/desktop/src/main/maker-host/auto-review-model-router.ts
+++ b/apps/desktop/src/main/maker-host/auto-review-model-router.ts
@@ -4,22 +4,25 @@ import type { UtilityTextResult } from '../../shared/utilityTextResult.js';
import {
DEDICATED_AUTO_REVIEW_CANDIDATES,
requestDedicatedAutoReviewCandidateText,
+ type AutoReviewAuxiliaryFallback,
type DedicatedAutoReviewCandidate,
} from '../utility-model/oneShotCandidates.js';
+import { requestUtilityTextWithinTimeout } from '../utility-model/utilityTextTimeout.js';
import { parseAutoPermissionReviewDecision } from './auto-permission-reviewer.js';
export const AUTO_REVIEW_CANDIDATE_TIMEOUT_MS = 12_000;
/**
- * 整条链的预算 = 每个候选一次完整超时 + 4s 余量。按候选数推导:一个候选整段超时后先让给
+ * 内置链的预算 = 每个候选一次完整超时 + 4s 余量。按候选数推导:一个候选整段超时后先让给
* 下一个,而不是在原位重试吃掉后续候选的时间;兜底候选本机不可用(立即 no_candidate)时,
* 省下的预算留给超时候选在所有兜底之后再试一次。
*/
export const AUTO_REVIEW_CHAIN_TIMEOUT_MS =
DEDICATED_AUTO_REVIEW_CANDIDATES.length * AUTO_REVIEW_CANDIDATE_TIMEOUT_MS + 4_000;
-export const AUTO_REVIEW_ROUTER_GUARD_TIMEOUT_MS = AUTO_REVIEW_CHAIN_TIMEOUT_MS + 1_000;
+export const AUTO_REVIEW_AUXILIARY_TIMEOUT_MS = 40_000;
+export const AUTO_REVIEW_TOTAL_TIMEOUT_MS = AUTO_REVIEW_CHAIN_TIMEOUT_MS + AUTO_REVIEW_AUXILIARY_TIMEOUT_MS;
+export const AUTO_REVIEW_ROUTER_GUARD_TIMEOUT_MS = AUTO_REVIEW_TOTAL_TIMEOUT_MS + 1_000;
const AUTO_REVIEW_TRANSIENT_RETRY_ATTEMPTS = 2;
const AUTO_REVIEW_TRANSIENT_RETRY_BACKOFF_MS = 100;
-const AUTO_REVIEW_CANDIDATE_TIMEOUT = Symbol('auto-review-candidate-timeout');
interface AutoReviewModelRouterLogger {
debug(message: string, fields?: Record<string, unknown>): void;
@@ -34,6 +37,7 @@ interface AutoReviewModelRouterDeps {
candidate: DedicatedAutoReviewCandidate,
opts: { timeoutMs: number; signal?: AbortSignal },
) => Promise<UtilityTextResult>;
+ createAuxiliaryFallback?: () => AutoReviewAuxiliaryFallback | undefined;
parseDecision?: (text: string) => AutoReviewDecision | null;
now?: () => number;
sleep?: (ms: number, signal: AbortSignal) => Promise<void>;
@@ -100,42 +104,6 @@ function candidateTimeoutFailure(
};
}
-async function requestCandidateWithinTimeout(
- requestCandidate: NonNullable<AutoReviewModelRouterDeps['requestCandidate']>,
- prompt: string,
- candidate: DedicatedAutoReviewCandidate,
- timeoutMs: number,
- chainSignal: AbortSignal,
-): Promise<UtilityTextResult> {
- if (chainSignal.aborted) return candidateTimeoutFailure(candidate);
- const controller = new AbortController();
- let timeout: ReturnType<typeof setTimeout> | undefined;
- let abortFromChain: (() => void) | undefined;
- const cutoff = new Promise<typeof AUTO_REVIEW_CANDIDATE_TIMEOUT>((resolve) => {
- const abort = () => {
- controller.abort();
- resolve(AUTO_REVIEW_CANDIDATE_TIMEOUT);
- };
- abortFromChain = abort;
- if (chainSignal.aborted) abort();
- else chainSignal.addEventListener('abort', abort, { once: true });
- timeout = setTimeout(abort, timeoutMs);
- });
-
- try {
- const result = await Promise.race([
- requestCandidate(prompt, candidate, { timeoutMs, signal: controller.signal }),
- cutoff,
- ]);
- return result === AUTO_REVIEW_CANDIDATE_TIMEOUT
- ? candidateTimeoutFailure(candidate)
- : result;
- } finally {
- if (timeout) clearTimeout(timeout);
- if (abortFromChain) chainSignal.removeEventListener('abort', abortFromChain);
- }
-}
-
function safeFailureReason(result: UtilityTextResult): string {
if (result.ok) return 'none';
const failed = result.attempts.find((attempt) => attempt.status === 'failed');
@@ -148,7 +116,7 @@ interface PendingCandidateAttempt {
}
/**
- * Runs the dedicated Auto-review model chain once.
+ * Runs the dedicated Auto-review chain, then an explicitly customized auxiliary chain.
*
* Each candidate owns its HTTP timeout and receives the chain AbortSignal, and gets at most
* AUTO_REVIEW_TRANSIENT_RETRY_ATTEMPTS attempts. A transient failure is retried in place only
@@ -157,6 +125,8 @@ interface PendingCandidateAttempt {
* therefore cannot starve fallback or an earlier, higher-priority retry, and fallbacks that
* are unavailable locally (`no_candidate` returns immediately) do not waste the budget
* reserved for them.
+ * The auxiliary phase has its own bounded budget, shares parent cancellation, and
+ * cannot replace any valid dedicated decision (including block and ask).
*/
export function createAutoReviewModelRouter(
deps: AutoReviewModelRouterDeps,
@@ -169,12 +139,20 @@ export function createAutoReviewModelRouter(
return async (prompt, parentSignal) => {
const startedAt = now();
+ let auxiliaryFallback: AutoReviewAuxiliaryFallback | undefined;
+ try {
+ auxiliaryFallback = deps.createAuxiliaryFallback?.();
+ } catch {
+ deps.logger.warn('auto-review auxiliary fallback unavailable', { reason: 'configuration_unavailable' });
+ }
const deadlineAt = startedAt + AUTO_REVIEW_CHAIN_TIMEOUT_MS;
+ const totalTimeoutMs = auxiliaryFallback ? AUTO_REVIEW_TOTAL_TIMEOUT_MS : AUTO_REVIEW_CHAIN_TIMEOUT_MS;
+ const totalDeadlineAt = startedAt + totalTimeoutMs;
const controller = new AbortController();
const abortFromParent = () => controller.abort();
if (parentSignal?.aborted) abortFromParent();
else parentSignal?.addEventListener('abort', abortFromParent, { once: true });
- const deadline = setTimeout(() => controller.abort(), AUTO_REVIEW_CHAIN_TIMEOUT_MS);
+ const deadline = setTimeout(() => controller.abort(), totalTimeoutMs);
try {
const queue: PendingCandidateAttempt[] = candidates.map((candidate) => ({ candidate, attempt: 1 }));
@@ -198,12 +176,12 @@ export function createAutoReviewModelRouter(
const attemptStartedAt = now();
let result: UtilityTextResult;
try {
- result = await requestCandidateWithinTimeout(
- requestCandidate,
- prompt,
- candidate,
- Math.min(AUTO_REVIEW_CANDIDATE_TIMEOUT_MS, remainingMs),
+ const timeoutMs = Math.min(AUTO_REVIEW_CANDIDATE_TIMEOUT_MS, remainingMs);
+ result = await requestUtilityTextWithinTimeout(
+ (signal) => requestCandidate(prompt, candidate, { timeoutMs, signal }),
+ timeoutMs,
controller.signal,
+ () => candidateTimeoutFailure(candidate),
);
} catch {
// Credential refresh and catalog probes are runtime boundaries too. A thrown
@@ -211,6 +189,7 @@ export function createAutoReviewModelRouter(
result = candidateRequestFailure(candidate);
}
const durationMs = now() - attemptStartedAt;
+ if (controller.signal.aborted) break;
if (result.ok) {
const decision = parseDecision(result.text);
@@ -263,6 +242,39 @@ export function createAutoReviewModelRouter(
queue.push({ candidate, attempt: attempt + 1 });
}
}
+
+ if (auxiliaryFallback && !controller.signal.aborted) {
+ const timeoutMs = Math.min(AUTO_REVIEW_AUXILIARY_TIMEOUT_MS, totalDeadlineAt - now());
+ if (timeoutMs > 0) {
+ try {
+ const result = await requestUtilityTextWithinTimeout(
+ (signal) => auxiliaryFallback(prompt, {
+ timeoutMs: AUTO_REVIEW_CANDIDATE_TIMEOUT_MS,
+ signal,
+ validateResponse: (text) => parseDecision(text) !== null,
+ }),
+ timeoutMs,
+ controller.signal,
+ () => ({ ok: false, reason: 'timeout', attempts: [] }),
+ );
+ const decision = result.ok ? parseDecision(result.text) : null;
+ if (decision && !controller.signal.aborted) {
+ deps.logger.debug('auto-review auxiliary fallback completed', {
+ providerId: result.ok ? result.providerId : undefined,
+ model: result.ok ? result.model : undefined,
+ verdict: decision.verdict,
+ durationMs: now() - startedAt,
+ });
+ return JSON.stringify(decision);
+ }
+ deps.logger.warn('auto-review auxiliary fallback failed', {
+ reason: result.ok ? 'malformed_decision' : safeFailureReason(result),
+ });
+ } catch {
+ deps.logger.warn('auto-review auxiliary fallback failed', { reason: 'request_failed' });
+ }
+ }
+ }
} finally {
clearTimeout(deadline);
parentSignal?.removeEventListener('abort', abortFromParent);
diff --git a/apps/desktop/src/main/maker-host/index.ts b/apps/desktop/src/main/maker-host/index.ts
index db3e89bb58..f5b44b37ed 100644
--- a/apps/desktop/src/main/maker-host/index.ts
+++ b/apps/desktop/src/main/maker-host/index.ts
@@ -236,7 +236,7 @@ import { resolveDesktopClaudeSubagentModelAccess } from './subagent-model-access
import { claudeSubagentUsageBridge } from './claude-subagent-usage-bridge.js';
import { createAutoPermissionReviewer } from './auto-permission-reviewer.js';
import { createToolLoopReviewer } from './tool-loop-reviewer.js';
-import { requestUtilityText } from '../utility-model/oneShotCandidates.js';
+import { createCustomAutoReviewFallback, requestUtilityText } from '../utility-model/oneShotCandidates.js';
import {
AUTO_REVIEW_ROUTER_GUARD_TIMEOUT_MS,
createAutoReviewModelRouter,
@@ -428,6 +428,7 @@ export function setProviderAccessRuntimeRefreshListener(listener: (() => void) |
const requestAutoReviewText = createAutoReviewModelRouter({
logger: desktopMakerLogger,
+ createAuxiliaryFallback: createCustomAutoReviewFallback,
});
let autoReviewContextResolver: AutoReviewDelegate['prepareRequest'];
diff --git a/apps/desktop/src/main/utility-model/__tests__/oneShotCandidates.test.ts b/apps/desktop/src/main/utility-model/__tests__/oneShotCandidates.test.ts
index cbab2907e7..b2109009f4 100644
--- a/apps/desktop/src/main/utility-model/__tests__/oneShotCandidates.test.ts
+++ b/apps/desktop/src/main/utility-model/__tests__/oneShotCandidates.test.ts
@@ -1,4 +1,4 @@
-import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
const localReady = vi.hoisted(() => vi.fn(async () => {}));
vi.mock('../../local-model-runtime/preflight.js', () => ({ ensureManagedOllamaReadyForSession: localReady }));
@@ -49,10 +49,12 @@ vi.mock('../../maker-host/auth-adapters.js', () => ({
vi.mock('../../maker-host/anthropic-responses-bridge-host.js', () => ({
getChatgptBridgeAuth: vi.fn(),
+ getChatgptBridgeAuthForDispatch: vi.fn(),
}));
vi.mock('../../maker-host/grok-oauth-login.js', () => ({
getGrokAccessToken: vi.fn(),
+ getGrokOAuthCredentialGeneration: vi.fn(() => 0),
}));
vi.mock('../../maker-host/generic-oauth.js', () => ({
@@ -66,6 +68,7 @@ vi.mock('../../maker-host/active-catalog.js', () => ({
vi.mock('../../maker-host/provider-route.js', () => ({
isProviderRouteMutationInProgress: vi.fn(() => false),
+ getProviderRouteCredentialRevision: vi.fn(() => 0),
}));
vi.mock('../../maker-host/model-disable-store.js', () => ({
@@ -103,20 +106,22 @@ import { fetch as undiciFetch } from 'undici';
import { getAppCapabilities } from '../../appCapabilities.js';
import { readClaudeApiKey } from '../../maker-host/auth-adapters.js';
-import { getChatgptBridgeAuth } from '../../maker-host/anthropic-responses-bridge-host.js';
-import { getGrokAccessToken } from '../../maker-host/grok-oauth-login.js';
+import { getChatgptBridgeAuth, getChatgptBridgeAuthForDispatch } from '../../maker-host/anthropic-responses-bridge-host.js';
+import { getGrokAccessToken, getGrokOAuthCredentialGeneration } from '../../maker-host/grok-oauth-login.js';
import { readCachedGenericOAuthAccessToken } from '../../maker-host/generic-oauth.js';
import {
getActiveCatalog,
isXdGatewayPaymentRequiredRoute,
} from '../../maker-host/active-catalog.js';
import { readModelDisableOverrides } from '../../maker-host/model-disable-store.js';
-import { isProviderRouteMutationInProgress } from '../../maker-host/provider-route.js';
+import { getProviderRouteCredentialRevision, 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 { parseAutoPermissionReviewDecision } from '../../maker-host/auto-permission-reviewer.js';
import {
DEDICATED_AUTO_REVIEW_CANDIDATES,
+ createCustomAutoReviewFallback,
getUtilityTextCandidates,
isUtilityRoutePaymentRequired,
requestDedicatedAutoReviewCandidateText,
@@ -129,13 +134,17 @@ const getProfiles = vi.mocked(getUtilityModelChainProfiles);
const appCapabilities = vi.mocked(getAppCapabilities);
const readKey = vi.mocked(readClaudeApiKey);
const readCodexCreds = vi.mocked(getChatgptBridgeAuth);
+const readCodexDispatchAuth = vi.mocked(getChatgptBridgeAuthForDispatch);
+const codexAuthorizationCurrent = vi.fn((_providerId: string) => true);
const readGrokToken = vi.mocked(getGrokAccessToken);
+const grokCredentialGeneration = vi.mocked(getGrokOAuthCredentialGeneration);
const readGenericOAuthToken = vi.mocked(readCachedGenericOAuthAccessToken);
const fetchMock = vi.mocked(undiciFetch);
const activeCatalog = vi.mocked(getActiveCatalog);
const xdPaymentRequiredRoute = vi.mocked(isXdGatewayPaymentRequiredRoute);
const readDisableOverrides = vi.mocked(readModelDisableOverrides);
const providerRouteMutationInProgress = vi.mocked(isProviderRouteMutationInProgress);
+const providerRouteCredentialRevision = vi.mocked(getProviderRouteCredentialRevision);
const readCustomKey = vi.mocked(readCustomProviderKey);
const reportKeyRejected = vi.mocked(reportCindyGatewayKeyRejected);
@@ -158,9 +167,16 @@ describe('utility one-shot candidates', () => {
appCapabilities.mockReturnValue({ canUseCindyGateway: true } as never);
readKey.mockReturnValue(null);
readCodexCreds.mockRejectedValue(new Error('not authenticated'));
+ codexAuthorizationCurrent.mockReturnValue(true);
+ readCodexDispatchAuth.mockImplementation(async (providerId = 'openai') => ({
+ ...await (providerId === 'openai' ? readCodexCreds() : readCodexCreds(providerId)),
+ canDispatch: () => codexAuthorizationCurrent(providerId),
+ }));
readGrokToken.mockRejectedValue(new Error('not authenticated'));
+ grokCredentialGeneration.mockReturnValue(0);
readGenericOAuthToken.mockReturnValue(null);
providerRouteMutationInProgress.mockReturnValue(false);
+ providerRouteCredentialRevision.mockReturnValue(0);
readCustomKey.mockReturnValue(null);
readDisableOverrides.mockReturnValue({ disabledModels: {}, disabledProviders: {} });
activeCatalog.mockReturnValue({ providers: [] } as never);
@@ -185,6 +201,306 @@ describe('utility one-shot candidates', () => {
]);
});
+ describe('custom Auto-review fallback', () => {
+ const prompt = 'Review policy\n<review_input>\nuser request and action\n</review_input>';
+ const options = {
+ timeoutMs: 12_000,
+ validateResponse: (text: string) => parseAutoPermissionReviewDecision(text) !== null,
+ };
+ const response = (text: string) => ({
+ ok: true,
+ text: async () => JSON.stringify({ choices: [{ message: { content: text } }] }),
+ }) as never;
+
+ beforeEach(() => {
+ chainState.source = 'custom';
+ chainState.refs = ['cat:review-a:codex:small', 'cat:review-b:codex:small'];
+ activeCatalog.mockReturnValue({
+ providers: ['review-a', 'review-b'].map((id) => ({
+ id,
+ name: id,
+ source: 'user',
+ agents: ['codex'],
+ auth: { method: 'apiKey' },
+ routing: { codex: {
+ upstream: `https://${id}.example/v1`,
+ wireProtocol: 'openai-chat',
+ authStrategy: 'api-key-header',
+ } },
+ models: { codex: [{ id: 'small', name: 'Small', contextWindow: 100_000 }] },
+ })),
+ } as never);
+ readCustomKey.mockImplementation((id) => `${id}-secret`);
+ });
+
+ afterEach(() => { vi.useRealTimers(); });
+
+ it.each(['auto', 'env'] as const)('does not use a %s auxiliary chain', (source) => {
+ chainState.source = source;
+ expect(createCustomAutoReviewFallback()).toBeUndefined();
+ expect(fetchMock).not.toHaveBeenCalled();
+ expect(readCustomKey).not.toHaveBeenCalled();
+ });
+
+ it('validates each response and preserves exact route credentials and native system separation', async () => {
+ fetchMock.mockResolvedValueOnce(response('not JSON'));
+ fetchMock.mockResolvedValueOnce(response('{"verdict":"allow"}'));
+ const result = await createCustomAutoReviewFallback()!(prompt, options);
+
+ expect(result).toMatchObject({ ok: true, providerId: 'review-b', text: '{"verdict":"allow"}' });
+ expect(fetchMock.mock.calls.map(([url]) => url)).toEqual([
+ 'https://review-a.example/v1/chat/completions',
+ 'https://review-b.example/v1/chat/completions',
+ ]);
+ for (const [index, [, init]] of fetchMock.mock.calls.entries()) {
+ expect(init?.headers).toMatchObject({ Authorization: `Bearer review-${index === 0 ? 'a' : 'b'}-secret` });
+ const body = JSON.parse(String(init?.body));
+ expect(body).toMatchObject({
+ model: 'small', max_tokens: 384,
+ messages: [
+ { role: 'system', content: 'Review policy' },
+ { role: 'user', content: '<review_input>\nuser request and action\n</review_input>' },
+ ],
+ });
+ expect(body).not.toHaveProperty('tools');
+ expect(body).not.toHaveProperty('tool_choice');
+ }
+ });
+
+ it.each(['allow', 'block', 'ask'])('does not try another model after a valid %s', async (verdict) => {
+ fetchMock.mockResolvedValueOnce(response(JSON.stringify({ verdict })));
+ await expect(createCustomAutoReviewFallback()!(prompt, options)).resolves.toMatchObject({
+ ok: true, text: JSON.stringify({ verdict }), providerId: 'review-a',
+ });
+ expect(fetchMock).toHaveBeenCalledTimes(1);
+ });
+
+ it('preserves the decision budget instead of consuming it on optional chat thinking', async () => {
+ fetchMock.mockImplementation(async (_url, init) => {
+ const body = JSON.parse(String(init?.body));
+ // A thinking-enabled upstream consumes the short output cap on reasoning,
+ // then returns no final answer. Disabling thinking leaves room for JSON.
+ return response(body.thinking?.type === 'disabled' ? '{"verdict":"block"}' : '');
+ });
+
+ await expect(createCustomAutoReviewFallback()!(prompt, options)).resolves.toMatchObject({
+ ok: true, providerId: 'review-a', text: '{"verdict":"block"}',
+ });
+ expect(fetchMock).toHaveBeenCalledTimes(1);
+ expect(JSON.parse(String(fetchMock.mock.calls[0]?.[1]?.body))).toMatchObject({ max_tokens: 384 });
+ });
+
+ it('uses the supported low effort for a subscription Responses fallback', async () => {
+ chainState.refs = ['codex-gpt-5.4-nano'];
+ activeCatalog.mockReturnValue({ providers: [{
+ id: 'openai', name: 'OpenAI', source: 'builtin', agents: ['codex'],
+ auth: { method: 'oauth' },
+ routing: { codex: { upstream: 'https://chatgpt.example/backend-api/codex', authStrategy: 'oauth-passthrough' } },
+ models: { codex: [{ id: 'gpt-5.4-nano', name: 'Nano', contextWindow: 272_000 }] },
+ }] } as never);
+ readCodexCreds.mockResolvedValue({ accessToken: 'codex-token', accountId: 'account-1' });
+ fetchMock.mockResolvedValueOnce({
+ ok: true, text: async () => JSON.stringify({ output_text: '{"verdict":"ask"}' }),
+ } as never);
+
+ await expect(createCustomAutoReviewFallback()!(prompt, options)).resolves.toMatchObject({
+ ok: true, providerId: 'openai', text: '{"verdict":"ask"}',
+ });
+ const body = JSON.parse(String(fetchMock.mock.calls[0]?.[1]?.body));
+ expect(body).toMatchObject({ reasoning: { effort: 'low' } });
+ expect(body).not.toHaveProperty('thinking');
+ expect(body).not.toHaveProperty('tools');
+ });
+
+ it('does not expand an exhausted custom chain into defaults or the gateway', async () => {
+ readKey.mockReturnValue('gateway-key');
+ readCustomKey.mockReturnValue(null);
+ await expect(createCustomAutoReviewFallback()!(prompt, options)).resolves.toMatchObject({ ok: false });
+ expect(fetchMock).not.toHaveBeenCalled();
+ });
+
+ describe('subscription authorization', () => {
+ const providers = ['openai', 'openai-work', 'xai', 'xai-work'];
+ const configureSubscription = (providerId: string) => {
+ const openai = providerId.startsWith('openai');
+ const model = openai ? 'gpt-5.4-nano' : 'xai/grok-4.3';
+ chainState.refs = [`cat:${providerId}:codex:${model}`];
+ activeCatalog.mockReturnValue({ providers: [{
+ id: providerId, name: providerId, source: providerId.endsWith('-work') ? 'user' : 'builtin',
+ agents: ['codex'], auth: { method: 'oauth', native: openai ? 'codex' : 'xai' },
+ routing: { codex: { upstream: 'https://subscription.example/v1', authStrategy: 'provider-oauth-header' } },
+ models: { codex: [{ id: model, name: model, contextWindow: 272_000 }] },
+ }] } as never);
+ readCodexCreds.mockResolvedValue({ accessToken: 'selected-token', accountId: 'selected-account' });
+ readGrokToken.mockResolvedValue('selected-token');
+ };
+
+ it.each(providers)('discards a late allow after %s authorization changes, even with the same cached credentials', async (providerId) => {
+ configureSubscription(providerId);
+ fetchMock.mockResolvedValueOnce({
+ ok: true,
+ text: async () => {
+ // Logout/reconnect may leave the same token in a reader cache. The
+ // native authorization proof/generation must still invalidate it.
+ codexAuthorizationCurrent.mockImplementation((id) => id !== providerId);
+ grokCredentialGeneration.mockImplementation((id) => id === providerId ? 1 : 0);
+ return JSON.stringify({ output_text: '{"verdict":"allow"}' });
+ },
+ } as never);
+ await expect(createCustomAutoReviewFallback()!(prompt, options)).resolves.toMatchObject({ ok: false });
+ expect(fetchMock).toHaveBeenCalledTimes(1);
+ });
+
+ it.each(providers)('accepts %s decisions when only another subscription changes', async (providerId) => {
+ configureSubscription(providerId);
+ fetchMock.mockResolvedValueOnce({
+ ok: true,
+ text: async () => {
+ codexAuthorizationCurrent.mockImplementation((id) => id !== 'unrelated');
+ grokCredentialGeneration.mockImplementation((id) => id === 'unrelated' ? 1 : 0);
+ return JSON.stringify({ output_text: '{"verdict":"allow"}' });
+ },
+ } as never);
+ await expect(createCustomAutoReviewFallback()!(prompt, options)).resolves.toMatchObject({ ok: true, providerId });
+ });
+
+ it.each(['xai', 'xai-work'])('preserves an in-flight %s decision across ordinary access-token refresh', async (providerId) => {
+ configureSubscription(providerId);
+ fetchMock.mockResolvedValueOnce({
+ ok: true,
+ text: async () => {
+ readGrokToken.mockResolvedValue('refreshed-token');
+ return JSON.stringify({ output_text: '{"verdict":"ask"}' });
+ },
+ } as never);
+ await expect(createCustomAutoReviewFallback()!(prompt, options)).resolves.toMatchObject({ ok: true, providerId });
+ });
+ });
+
+ it('skips a disabled route and uses only the next selected route', async () => {
+ readDisableOverrides.mockReturnValue({ disabledModels: {}, disabledProviders: { 'review-a': true } });
+ fetchMock.mockResolvedValueOnce(response('{"verdict":"ask"}'));
+ await expect(createCustomAutoReviewFallback()!(prompt, options)).resolves.toMatchObject({
+ ok: true, providerId: 'review-b',
+ });
+ expect(fetchMock).toHaveBeenCalledTimes(1);
+ });
+
+ it.each([
+ ['provider', 'before dispatch'], ['model', 'before dispatch'],
+ ['provider', 'after dispatch'], ['model', 'after dispatch'],
+ ])('rejects a %s disabled %s instead of accepting its decision', async (kind, phase) => {
+ const disable = () => readDisableOverrides.mockReturnValue(kind === 'provider'
+ ? { disabledModels: {}, disabledProviders: { 'review-a': true } }
+ : { disabledModels: { 'review-a:small': true }, disabledProviders: {} });
+ fetchMock.mockResolvedValueOnce({
+ ok: true,
+ text: async () => {
+ if (phase === 'after dispatch') disable();
+ return JSON.stringify({ choices: [{ message: { content: '{"verdict":"allow"}' } }] });
+ },
+ } as never);
+ const fallback = createCustomAutoReviewFallback()!;
+ if (phase === 'before dispatch') disable();
+ await expect(fallback(prompt, options)).resolves.toMatchObject({ ok: false });
+ expect(fetchMock).toHaveBeenCalledTimes(phase === 'after dispatch' ? 1 : 0);
+ });
+
+ it.each(['owner', 'chain', 'boundary'])('rejects a stale %s captured before the dedicated phase', async (change) => {
+ const fallback = createCustomAutoReviewFallback()!;
+ if (change === 'owner') ownerState.key = 'owner-b';
+ if (change === 'chain') chainState.refs.reverse();
+ if (change === 'boundary') ownerState.pending = true;
+ await expect(fallback(prompt, options)).resolves.toMatchObject({ ok: false });
+ expect(fetchMock).not.toHaveBeenCalled();
+ });
+
+ it.each(['endpoint', 'headers', 'credential', 'recreated', 'mutation'])
+ ('rejects a provider %s change while dedicated candidates run', async (change) => {
+ const fallback = createCustomAutoReviewFallback()!;
+ const provider = getActiveCatalog().providers[0]!;
+ if (change === 'endpoint') provider.routing.codex!.upstream = 'https://replacement.example/v1';
+ if (change === 'headers') provider.routing.codex!.headerOverride = { 'X-Tenant': 'other-tenant' };
+ // Credential edits and delete/recreate commit monotonic revisions even
+ // when the provider id, endpoint and visible descriptors stay identical.
+ if (change === 'credential') providerRouteCredentialRevision.mockReturnValue(1);
+ if (change === 'recreated') providerRouteCredentialRevision.mockReturnValue(2);
+ if (change === 'mutation') providerRouteMutationInProgress.mockReturnValue(true);
+ await expect(fallback(prompt, options)).resolves.toMatchObject({ ok: false });
+ expect(fetchMock).not.toHaveBeenCalled();
+ });
+
+ it.each(['endpoint', 'credential'])('discards a valid late result after a provider %s change', async (change) => {
+ fetchMock.mockResolvedValueOnce({
+ ok: true,
+ text: async () => {
+ if (change === 'endpoint') getActiveCatalog().providers[0]!.routing.codex!.upstream = 'https://replacement.example/v1';
+ else providerRouteCredentialRevision.mockReturnValue(1);
+ return JSON.stringify({ choices: [{ message: { content: '{"verdict":"allow"}' } }] });
+ },
+ } as never);
+ await expect(createCustomAutoReviewFallback()!(prompt, options)).resolves.toMatchObject({ ok: false });
+ expect(fetchMock).toHaveBeenCalledTimes(1);
+ });
+
+ it('keeps unrelated provider changes and display metadata out of the routing identity', async () => {
+ const fallback = createCustomAutoReviewFallback()!;
+ getActiveCatalog().providers[0]!.name = 'Updated label';
+ providerRouteCredentialRevision.mockImplementation((id) => id === 'unrelated' ? 1 : 0);
+ readDisableOverrides.mockReturnValue({ disabledModels: { 'unrelated:small': true }, disabledProviders: { unrelated: true } });
+ fetchMock.mockResolvedValueOnce(response('{"verdict":"allow"}'));
+ await expect(fallback(prompt, options)).resolves.toMatchObject({ ok: true, providerId: 'review-a' });
+ expect(fetchMock).toHaveBeenCalledTimes(1);
+ });
+
+ it.each(['owner', 'chain'])('discards a response and stops the chain if the %s changes in flight', async (change) => {
+ fetchMock.mockResolvedValueOnce({
+ ok: true,
+ text: async () => {
+ if (change === 'owner') ownerState.key = 'owner-b';
+ else chainState.refs.reverse();
+ return JSON.stringify({ choices: [{ message: { content: '{"verdict":"allow"}' } }] });
+ },
+ } as never);
+ await expect(createCustomAutoReviewFallback()!(prompt, options)).resolves.toMatchObject({ ok: false });
+ expect(fetchMock).toHaveBeenCalledTimes(1);
+ });
+
+ it('bounds credential discovery per legacy profile and never dispatches the late request', async () => {
+ vi.useFakeTimers();
+ const customProviders = getActiveCatalog().providers;
+ activeCatalog.mockReturnValue({ providers: [
+ ...customProviders,
+ {
+ id: 'openai', name: 'OpenAI', source: 'builtin', agents: ['codex'],
+ auth: { method: 'oauth' },
+ routing: { codex: { upstream: 'https://chatgpt.example/backend-api/codex', authStrategy: 'oauth-passthrough' } },
+ models: { codex: [{ id: 'gpt-5.4-nano', name: 'Nano', contextWindow: 272_000 }] },
+ },
+ ] } as never);
+ chainState.refs = ['codex-gpt-5.4-nano', 'cat:review-b:codex:small'];
+ let finishAuth!: (value: { accessToken: string; accountId: string }) => void;
+ readCodexCreds.mockImplementationOnce(() => new Promise((resolve) => { finishAuth = resolve; }));
+ fetchMock.mockResolvedValueOnce(response('{"verdict":"allow"}'));
+
+ const pending = createCustomAutoReviewFallback()!(prompt, options);
+ await vi.advanceTimersByTimeAsync(options.timeoutMs);
+ await expect(pending).resolves.toMatchObject({ ok: true, providerId: 'review-b' });
+ finishAuth({ accessToken: 'late-token', accountId: 'account-1' });
+ await vi.advanceTimersByTimeAsync(1);
+ expect(fetchMock).toHaveBeenCalledTimes(1);
+ expect(fetchMock.mock.calls[0]?.[0]).toBe('https://review-b.example/v1/chat/completions');
+ });
+
+ it('does not dispatch any auxiliary route after cancellation', async () => {
+ const controller = new AbortController();
+ controller.abort();
+ await expect(createCustomAutoReviewFallback()!(prompt, { ...options, signal: controller.signal }))
+ .resolves.toMatchObject({ ok: false });
+ expect(fetchMock).not.toHaveBeenCalled();
+ });
+ });
+
it('skips unauthenticated codex and keeps configured LiteLLM when API key exists', async () => {
readKey.mockReturnValue('proxy-key');
@@ -2480,7 +2796,10 @@ describe('utility one-shot candidates', () => {
expect(fetchMock).not.toHaveBeenCalled();
});
- it('uses a supported ChatGPT subscription model with a tool-free Responses body', async () => {
+ it.each([
+ { candidateIndex: 1, model: 'gpt-5.4-nano' },
+ { candidateIndex: 2, model: 'gpt-6-luna' },
+ ])('uses $model with a tool-free subscription Responses body', async ({ candidateIndex, model }) => {
activeCatalog.mockReturnValue({
providers: [{
id: 'openai',
@@ -2495,7 +2814,7 @@ describe('utility one-shot candidates', () => {
},
},
models: {
- codex: [{ id: 'gpt-5.4-nano', name: 'Nano', contextWindow: 272_000 }],
+ codex: [{ id: model, name: model, contextWindow: 272_000 }],
},
}],
} as never);
@@ -2508,18 +2827,18 @@ describe('utility one-shot candidates', () => {
const result = await requestDedicatedAutoReviewCandidateText(
'Review policy\n<review_input>\nclassify\n</review_input>',
- DEDICATED_AUTO_REVIEW_CANDIDATES[1],
+ DEDICATED_AUTO_REVIEW_CANDIDATES[candidateIndex],
{ timeoutMs: 8_000 },
);
expect(result).toMatchObject({
ok: true,
providerId: 'openai',
- model: 'gpt-5.4-nano',
+ model,
});
const body = JSON.parse(String(fetchMock.mock.calls[0]?.[1]?.body)) as Record<string, unknown>;
expect(body).toMatchObject({
- model: 'gpt-5.4-nano',
+ model,
reasoning: { effort: 'low' },
instructions: 'Review policy',
input: [{ type: 'message', role: 'user', content: [{ type: 'input_text', text: '<review_input>\nclassify\n</review_input>' }] }],
@@ -2529,6 +2848,31 @@ describe('utility one-shot candidates', () => {
expect(body).not.toHaveProperty('parallel_tool_calls');
});
+ it('skips GPT-6 Luna when the subscription catalog only offers the previous Luna model', async () => {
+ activeCatalog.mockReturnValue({
+ providers: [{
+ id: 'openai',
+ agents: ['codex'],
+ routing: { codex: { upstream: 'https://chatgpt.example/backend-api/codex' } },
+ models: { codex: [{ id: 'gpt-5.6-luna' }] },
+ }],
+ } as never);
+
+ const result = await requestDedicatedAutoReviewCandidateText(
+ 'classify',
+ DEDICATED_AUTO_REVIEW_CANDIDATES[2],
+ { timeoutMs: 8_000 },
+ );
+
+ expect(result).toMatchObject({
+ ok: false,
+ reason: 'no_candidate',
+ attempts: [expect.objectContaining({ model: 'gpt-6-luna', reason: 'model_unavailable' })],
+ });
+ expect(readCodexCreds).not.toHaveBeenCalled();
+ expect(fetchMock).not.toHaveBeenCalled();
+ });
+
it('does not start OpenAI HTTP after credential refresh outlives the candidate', async () => {
activeCatalog.mockReturnValue({
providers: [{
diff --git a/apps/desktop/src/main/utility-model/oneShotCandidates.ts b/apps/desktop/src/main/utility-model/oneShotCandidates.ts
index 032ea90697..e9e417e24c 100644
--- a/apps/desktop/src/main/utility-model/oneShotCandidates.ts
+++ b/apps/desktop/src/main/utility-model/oneShotCandidates.ts
@@ -12,8 +12,8 @@ import { createLogger } from '../logger.js';
import { getAppCapabilities } from '../appCapabilities.js';
import { activeOwnerScopeKey, isAppSessionBoundaryPending } from '../appSessionState.js';
import { readClaudeApiKey } from '../maker-host/auth-adapters.js';
-import { getChatgptBridgeAuth } from '../maker-host/anthropic-responses-bridge-host.js';
-import { getGrokAccessToken } from '../maker-host/grok-oauth-login.js';
+import { getChatgptBridgeAuth, getChatgptBridgeAuthForDispatch } from '../maker-host/anthropic-responses-bridge-host.js';
+import { getGrokAccessToken, getGrokOAuthCredentialGeneration } from '../maker-host/grok-oauth-login.js';
import { readCachedGenericOAuthAccessToken } from '../maker-host/generic-oauth.js';
// undici 的 fetch,但 per-request 现取系统代理(裸 undici 不吃代理设置)。
import { outboundUndiciFetch as undiciFetch } from '../maker-host/outbound-fetch.js';
@@ -24,7 +24,7 @@ import {
} from '../maker-host/active-catalog.js';
import { readModelDisableOverrides } from '../maker-host/model-disable-store.js';
import { isModelDisabled, isProviderDisabled } from '@cindy/model-providers';
-import { isProviderRouteMutationInProgress } from '../maker-host/provider-route.js';
+import { getProviderRouteCredentialRevision, 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';
@@ -34,6 +34,7 @@ import { ensureManagedOllamaReadyForSession } from '../local-model-runtime/prefl
import { parseAuxiliaryModelRef, type ParsedAuxiliaryModelRef } from '../../shared/auxiliaryModelChain.js';
import { getUtilityModelChainProfiles } from './UtilityModelSelection.js';
import { getEffectiveAuxiliaryModelChain } from './resolveAuxiliaryModelChain.js';
+import { requestUtilityTextWithinTimeout } from './utilityTextTimeout.js';
import { getUtilityModelProfile, isUtilityModelProviderKind } from '../../shared/utilityModelProfiles.js';
import type { UtilityModelProfile, UtilityModelTransport } from '../../shared/utilityModelProfiles.js';
import type {
@@ -374,10 +375,9 @@ export async function requestExplicitUtilityText(
const DEDICATED_AUTO_REVIEW_MAX_TOKENS = 384;
/**
- * Auto-review 的封闭候选表。它刻意不接受调用方传 provider/model:待审内容只能
- * 发往 Cindy 托管网关或用户已连接的 OpenAI 订阅,不能跟随主会话落到 xAI、DeepSeek、
- * Kimi 或自定义 BYOM。Claude 订阅不在表内:它只供内置 Claude Code CLI 自己使用,
- * Cindy 的直连请求不得借用。
+ * Auto-review 第一阶段的封闭候选表,不跟随主会话的 provider/model。
+ * 全部不可用后,路由器才尝试用户明确自定义的辅助模型链;自动/环境变量辅助链不参与。
+ * Claude 订阅只供内置 Claude Code CLI 自己使用,Cindy 的直连请求不得借用。
*/
export const DEDICATED_AUTO_REVIEW_CANDIDATES = Object.freeze([
{
@@ -400,7 +400,7 @@ export const DEDICATED_AUTO_REVIEW_CANDIDATES = Object.freeze([
id: 'chatgpt-luna',
providerId: 'openai',
agentKind: 'codex',
- model: 'gpt-5.6-luna',
+ model: 'gpt-6-luna',
transport: 'codex-responses',
reasoningEffort: 'low',
},
@@ -415,6 +415,107 @@ export const DEDICATED_AUTO_REVIEW_CANDIDATES = Object.freeze([
export type DedicatedAutoReviewCandidate = (typeof DEDICATED_AUTO_REVIEW_CANDIDATES)[number];
+function splitAutoReviewPrompt(prompt: string): { systemPrompt?: string; evidence: string } {
+ // The reviewer escapes delimiters inside evidence. Keep Host rules on the native
+ // system channel, and action/user strings on the user channel for every candidate.
+ const boundary = prompt.indexOf('\n<review_input>\n');
+ return {
+ systemPrompt: boundary >= 0 ? prompt.slice(0, boundary) : undefined,
+ evidence: boundary >= 0 ? prompt.slice(boundary + 1) : prompt,
+ };
+}
+
+export type AutoReviewAuxiliaryFallback = (
+ prompt: string,
+ opts: { timeoutMs: number; signal?: AbortSignal; validateResponse: (text: string) => boolean },
+) => Promise<UtilityTextResult>;
+
+/** Capture explicit routing consent before the dedicated chain starts awaiting. */
+export function createCustomAutoReviewFallback(): AutoReviewAuxiliaryFallback | undefined {
+ const chain = getEffectiveAuxiliaryModelChain();
+ if (chain.source !== 'custom' || chain.refs.length === 0) return undefined;
+ const ownerScopeKey = activeOwnerScopeKey();
+ const chainSnapshot = stableSnapshot(chain);
+ const snapshotRoute = (route: UtilityTextDispatchRoute): string => {
+ const provider = getActiveCatalog().providers.find((item) => item.id === route.providerId);
+ return stableSnapshot({
+ source: provider?.source,
+ auth: provider?.auth,
+ routing: provider?.routing[route.agentKind],
+ disabled: isProviderModelRouteDisabled(route.providerId, route.model),
+ // The existing revision survives delete/recreate and covers secret-only edits.
+ credentialRevision: getProviderRouteCredentialRevision(route.providerId),
+ });
+ };
+ const routes = chain.refs.flatMap((ref) => {
+ const parsed = parseAuxiliaryModelRef(ref);
+ if (!parsed) return [];
+ const route = auxiliaryRefDispatchRoute(parsed);
+ return [{ route, snapshot: snapshotRoute(route) }];
+ });
+ const stillCurrent = (): boolean => !isAppSessionBoundaryPending()
+ && activeOwnerScopeKey() === ownerScopeKey
+ && stableSnapshot(getEffectiveAuxiliaryModelChain()) === chainSnapshot
+ && routes.every(({ route, snapshot }) =>
+ !isProviderRouteMutationInProgress(route.providerId) && snapshotRoute(route) === snapshot,
+ );
+
+ return async (prompt, opts) => {
+ const { systemPrompt, evidence } = splitAutoReviewPrompt(prompt);
+ const attempts: UtilityTextAttempt[] = [];
+ for (const ref of chain.refs) {
+ if (opts.signal?.aborted || !stillCurrent()) break;
+ const parsed = parseAuxiliaryModelRef(ref);
+ if (!parsed) continue;
+ const route = auxiliaryRefDispatchRoute(parsed);
+ const routing = getActiveCatalog().providers.find((provider) => provider.id === route.providerId)
+ ?.routing[route.agentKind];
+ const failure = (reason: 'timeout' | 'request_failed'): UtilityTextResult => ({
+ ok: false,
+ reason: reason === 'timeout' ? 'timeout' : 'all_candidates_failed',
+ attempts: [{
+ providerId: route.providerId,
+ model: route.model,
+ transport: route.agentKind === 'codex' && routing?.wireProtocol !== 'openai-chat'
+ ? 'codex-responses' : 'litellm-chat-completions',
+ status: 'failed',
+ reason,
+ }],
+ });
+ let result: UtilityTextResult;
+ try {
+ // Normalize legacy profiles into exact catalog HTTP routes too. Never call
+ // Agent.oneShot: approval must not start a development Agent or tool loop.
+ result = await requestUtilityTextWithinTimeout(
+ (signal) => requestExplicitUtilityText(evidence, {
+ ...route,
+ systemPrompt,
+ maxTokens: DEDICATED_AUTO_REVIEW_MAX_TOKENS,
+ timeoutMs: opts.timeoutMs,
+ signal,
+ reasoningEffort: 'low',
+ // Use the auxiliary transport's short-output policy: switch off optional
+ // thinking; Responses maps this to its supported low effort instead.
+ disableReasoning: true,
+ validateResponse: opts.validateResponse,
+ beforeDispatch: async () => !signal.aborted && stillCurrent(),
+ }),
+ opts.timeoutMs,
+ opts.signal,
+ () => failure('timeout'),
+ );
+ } catch {
+ // A credential/catalog failure must not bypass the next selected model.
+ result = failure('request_failed');
+ }
+ if (opts.signal?.aborted || !stillCurrent()) break;
+ if (result.ok) return result;
+ attempts.push(...result.attempts);
+ }
+ return failedChainResult(attempts);
+ };
+}
+
/**
* 执行一个专用 Auto-review 候选。
*
@@ -426,11 +527,7 @@ export async function requestDedicatedAutoReviewCandidateText(
candidate: DedicatedAutoReviewCandidate,
opts: { timeoutMs: number; signal?: AbortSignal },
): Promise<UtilityTextResult> {
- // The reviewer escapes delimiters inside evidence. Keep Host rules on the native
- // system channel, and action/user strings on the user channel for every candidate.
- const evidenceBoundary = prompt.indexOf('\n<review_input>\n');
- const systemPrompt = evidenceBoundary >= 0 ? prompt.slice(0, evidenceBoundary) : undefined;
- const evidence = evidenceBoundary >= 0 ? prompt.slice(evidenceBoundary + 1) : prompt;
+ const { systemPrompt, evidence } = splitAutoReviewPrompt(prompt);
const profile: UtilityModelProfile = {
id: candidate.providerId,
model: candidate.model,
@@ -1143,8 +1240,15 @@ async function requestBuiltinProviderText(
if (isOpenAiSubscriptionProvider(input.provider)) {
let creds: Awaited<ReturnType<typeof getChatgptBridgeAuth>>;
+ let credentialStillCurrent: (() => boolean) | undefined;
try {
- creds = await (input.provider.id === 'openai' ? getChatgptBridgeAuth() : getChatgptBridgeAuth(input.provider.id));
+ if (input.beforeDispatch) {
+ const auth = await getChatgptBridgeAuthForDispatch(input.provider.id);
+ creds = auth;
+ credentialStillCurrent = auth.canDispatch;
+ } else {
+ creds = await (input.provider.id === 'openai' ? getChatgptBridgeAuth() : getChatgptBridgeAuth(input.provider.id));
+ }
} catch {
return { ok: false, reason: 'no_candidate', attempts: [skippedAttempt(profile, 'not_authenticated')] };
}
@@ -1189,22 +1293,15 @@ async function requestBuiltinProviderText(
model: input.model,
})
: undefined,
- credentialStillCurrent: requestOpts?.beforeDispatch
- ? async () => {
- try {
- const current = await (input.provider.id === 'openai' ? getChatgptBridgeAuth() : getChatgptBridgeAuth(input.provider.id));
- return current.accountId === accountId && current.accessToken === creds.accessToken;
- } catch {
- return false;
- }
- }
- : undefined,
+ credentialStillCurrent: requestOpts?.beforeDispatch ? credentialStillCurrent : undefined,
routeStillCurrent: requestOpts?.beforeDispatch ? input.routeStillCurrent : undefined,
}),
}], prompt, [], input);
}
if (providerCatalogId(input.provider) === 'xai') {
+ const credentialGeneration = input.beforeDispatch
+ ? getGrokOAuthCredentialGeneration(input.provider.id) : undefined;
let accessToken: string;
try {
accessToken = await (input.provider.id === 'xai' ? getGrokAccessToken() : getGrokAccessToken(input.provider.id));
@@ -1240,8 +1337,12 @@ async function requestBuiltinProviderText(
: undefined,
credentialStillCurrent: requestOpts?.beforeDispatch
? async () => {
+ if (getGrokOAuthCredentialGeneration(input.provider.id) !== credentialGeneration) return false;
try {
- return (await (input.provider.id === 'xai' ? getGrokAccessToken() : getGrokAccessToken(input.provider.id))) === accessToken;
+ await (input.provider.id === 'xai' ? getGrokAccessToken() : getGrokAccessToken(input.provider.id));
+ // Token refresh stays within the same login. Logout/reconnect must
+ // invalidate the request even when a cached token is unchanged.
+ return getGrokOAuthCredentialGeneration(input.provider.id) === credentialGeneration;
} catch {
return false;
}
@@ -1757,6 +1858,12 @@ async function requestProviderHttpText(input: {
}
throw new UtilityTextExecutionError({ reason: 'empty_response' });
}
+ // A valid response cannot outlive the route or authorization that sent it.
+ // Recheck credentials and routing after the complete response, including retries.
+ if (
+ (input.credentialStillCurrent && !(await input.credentialStillCurrent()))
+ || (input.routeStillCurrent && !input.routeStillCurrent())
+ ) throw new UtilityTextExecutionError({ reason: 'request_failed' });
return text;
} catch (error) {
if (error instanceof UtilityTextExecutionError) throw error;
diff --git a/apps/desktop/src/main/utility-model/utilityTextTimeout.ts b/apps/desktop/src/main/utility-model/utilityTextTimeout.ts
new file mode 100644
index 0000000000..62dff029d5
--- /dev/null
+++ b/apps/desktop/src/main/utility-model/utilityTextTimeout.ts
@@ -0,0 +1,30 @@
+import type { UtilityTextResult } from '../../shared/utilityTextResult.js';
+
+const TIMEOUT = Symbol('utility-text-timeout');
+
+/** Include credential discovery in the budget, even when a transport ignores abort. */
+export async function requestUtilityTextWithinTimeout(
+ request: (signal: AbortSignal) => Promise<UtilityTextResult>,
+ timeoutMs: number,
+ parentSignal: AbortSignal | undefined,
+ timeoutFailure: () => UtilityTextResult,
+): Promise<UtilityTextResult> {
+ if (parentSignal?.aborted) return timeoutFailure();
+ const controller = new AbortController();
+ let abort!: () => void;
+ const cutoff = new Promise<typeof TIMEOUT>((resolve) => {
+ abort = () => {
+ controller.abort();
+ resolve(TIMEOUT);
+ };
+ });
+ parentSignal?.addEventListener('abort', abort, { once: true });
+ const timer = setTimeout(abort, timeoutMs);
+ try {
+ const result = await Promise.race([request(controller.signal), cutoff]);
+ return result === TIMEOUT || controller.signal.aborted ? timeoutFailure() : result;
+ } finally {
+ clearTimeout(timer);
+ parentSignal?.removeEventListener('abort', abort);
+ }
+}
diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.json
index 29d0366fd0..cfe5fa967e 100644
--- a/apps/desktop/src/renderer/i18n/locales/en/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json
@@ -4320,7 +4320,7 @@
"ariaLabel": "Choose the second fallback auxiliary model"
},
"emptySlot": "Not selected",
- "customHint": "A custom chain is tried in this order only. If none of them work, Cindy will not switch to another model.",
+ "customHint": "Models are tried in your chosen order and also back up Auto-review when its built-in models are unavailable. Selected providers receive review context: messages and references, task and action details (including blocked actions), identity and permissions, file paths, and operating system.",
"signInHint": "Sign in to Cindy to use the automatic recommendations. While signed out, choose a configured model from another provider under Custom.",
"chooseAgent": "Choose an Agent",
"backToAgents": "Back to Agent selection",
diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.json
index a3cfedc0ac..1a5ed30b4a 100644
--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json
@@ -4291,7 +4291,7 @@
"ariaLabel": "2 番目の予備補助モデルを選択"
},
"emptySlot": "未選択",
- "customHint": "カスタム後は選んだ順にだけ試します。どれも使えない場合、別のモデルへは切り替えません。",
+ "customHint": "選んだ順に試し、内蔵モデルが使えない場合は自動レビューにも使います。選択したプロバイダーに送るレビュー情報には、メッセージと引用内容、タスク・操作の詳細(ブロック済みの操作を含む)、依頼者の識別・権限情報、ファイルパス、OS が含まれます。",
"signInHint": "Cindy にログインすると自動おすすめを使えます。未ログイン時は「カスタム」で設定済みの他のプロバイダーのモデルを選択してください。",
"chooseAgent": "Agent を選択",
"backToAgents": "Agent の選択に戻る",
diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.json
index 70a398cc63..19e6a78633 100644
--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json
@@ -4291,7 +4291,7 @@
"ariaLabel": "두 번째 대체 보조 모델 선택"
},
"emptySlot": "선택 안 함",
- "customHint": "사용자 지정 후에는 선택한 순서대로만 시도합니다. 모두 사용할 수 없어도 다른 모델로 바꾸지 않습니다.",
+ "customHint": "선택한 순서대로 시도하며, 내장 모델을 사용할 수 없을 때는 자동 리뷰에도 사용합니다. 선택한 제공자에게 메시지와 참조 콘텐츠, 작업·동작의 상세 정보(차단된 동작 포함), 요청자의 신원과 권한, 파일 경로, 운영 체제를 포함한 리뷰 맥락이 전송됩니다.",
"signInHint": "Cindy에 로그인하면 자동 추천을 사용할 수 있습니다. 로그인하지 않은 상태에서는 「사용자 지정」에서 설정된 다른 제공자의 모델을 선택하세요.",
"chooseAgent": "Agent 선택",
"backToAgents": "Agent 선택으로 돌아가기",
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 9f64ca372a..fdaf47a5d2 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
@@ -4291,7 +4291,7 @@
"ariaLabel": "选择第二备选辅助模型"
},
"emptySlot": "未选择",
- "customHint": "自定义后只按你选的顺序尝试;都不可用时不会偷偷换成别的模型。",
+ "customHint": "轻量文本按所选顺序尝试;内置审核不可用时,也用于自动审核兜底。所选供应商会收到审核上下文,包括消息与引用内容、任务与操作详情及拦截记录、身份与权限、文件路径和操作系统。",
"signInHint": "登录 Cindy 后可使用自动推荐;未登录时请在自定义中选择已配置的其他供应商模型。",
"chooseAgent": "选择 Agent",
"backToAgents": "返回选择 Agent",
diff --git a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
index fa576e1ee5..cb02468c84 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
@@ -4291,7 +4291,7 @@
"ariaLabel": "選擇第二備選輔助模型"
},
"emptySlot": "未選擇",
- "customHint": "自訂後只按你選的順序嘗試;都無法使用時不會偷偷換成別的模型。",
+ "customHint": "輕量文字按所選順序嘗試;內建審核無法使用時,也用於自動審核備援。所選供應商會收到審核上下文,包括訊息與引用內容、任務與操作詳情及攔截記錄、身分與權限、檔案路徑和作業系統。",
"signInHint": "登入 Cindy 後可使用自動推薦;未登入時請在自訂中選擇已設定的其他供應商模型。",
"chooseAgent": "選擇 Agent",
"backToAgents": "返回選擇 Agent",
diff --git a/docs/dev-rules/maker-core-and-agent-behavior.md b/docs/dev-rules/maker-core-and-agent-behavior.md
index 4764976f88..22dbcd393f 100644
--- a/docs/dev-rules/maker-core-and-agent-behavior.md
+++ b/docs/dev-rules/maker-core-and-agent-behavior.md
@@ -445,6 +445,31 @@ sessionRunningRetry 就停。每次因 replacement 关闭而重新入队都计
该轮沿用的 generation 已记过上一轮的 `done`,唤醒轮自己的终止 error 不按「done 之后的迟到 error」过滤,
照常按失败收口(唤醒输出之前到达的迟到 error 仍过滤)。回归见 `session.origin.test.ts`。
+### Desktop Auto 审核的模型回退
+
+Desktop 的 Auto 审核先按固定顺序尝试 `cindy/auto-review`、内置 OpenAI 订阅的
+`gpt-5.4-nano`、`gpt-6-luna`。只有这些候选全部不可用、请求失败或输出无效时,才使用
+系统设置中用户明确自定义的辅助模型链,按已选顺序尝试最多 3 个模型;自动辅助链和
+环境变量辅助链不参与。任一候选返回有效的 `allow`、`block` 或 `ask` 后立即结束,
+不能为了争取放行而继续换模型。全部失败继续交回人工确认。
+
+自定义兜底复用辅助模型的精确目录路由、停用状态和凭证处理,以无工具的 HTTP 文本请求
+执行,不创建开发 Agent 或调用 CLI `oneShot`;Claude 订阅仍不可供 Cindy 直连借用。
+宿主规则走供应商原生 system/instructions 字段,审核上下文仅放在证据段,并复用同一
+严格判定解析器。设置说明须披露发往所选供应商的上下文范围:用户原话、引用内容、
+委派任务、此前被阻止的操作、发起者身份与权限、待审操作参数、工作区及可写/参考
+路径和操作系统;不能只列用户原话与操作参数,漏掉其余上下文。
+384 token 的短输出预算复用辅助模型的关闭可选思考策略;Messages/Chat 可关闭时关闭,
+Responses 沿用现有适配器的 `low` 档,不发送其不支持的思考关闭值。
+
+审核开始时绑定账号、自定义链及所选供应商路由与停用状态快照,并复用现有供应商变更代次校验,
+覆盖地址/鉴权配置、密钥修改和同 ID 删除重建。订阅请求同时绑定 OpenAI 原生授权凭证或
+xAI 登录代次,派发前与响应完成后均复查,订阅退出或换号后不得采纳旧判定。
+账号切换、配置变化、取消后不得继续派发旧请求或采纳迟到结果。
+每个候选最多 12 秒(含凭证发现),内置阶段预算 40 秒,
+自定义阶段另有最多 40 秒,共用取消信号。宿主守卫为 81 秒,必须小于 Core 的 delegate 硬上限。
+恢复辅助模型默认设置会移除自定义兜底,不扩展自动链,也不改写已有配置。
+
### Auto 模式的同范围自动跟进
用户授权完成一项工作时,可以通过定时任务在原目标与操作范围内继续跟进;延后执行、