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(auto-review): 波动时重试并降级给用户确认,按模型能力给足额度 (#2474)

Chris Zhangac727519a27c
diff --git a/apps/desktop/src/main/im/shared/__tests__/turnRetryNotice.test.ts b/apps/desktop/src/main/im/shared/__tests__/turnRetryNotice.test.ts
index b464c21fb0..c2b55d937c 100644
--- a/apps/desktop/src/main/im/shared/__tests__/turnRetryNotice.test.ts
+++ b/apps/desktop/src/main/im/shared/__tests__/turnRetryNotice.test.ts
@@ -204,17 +204,18 @@ describe('terminalErrorText', () => {
*/
it('Auto 档审阅器不可用 → 渠道侧说明 + 可执行动作', () => {
const notice = turnRetryNotice({
- message: '[AUTO_REVIEW_UNAVAILABLE] Auto-review is temporarily unavailable, so actions '
- + 'that need review are being denied. Switch this task to Default permissions if you '
- + 'want to approve them yourself.',
+ message: '[AUTO_REVIEW_UNAVAILABLE] Auto-review could not reach a decision (network or '
+ + 'service hiccup), so actions that need review are being handed to you to confirm.',
isTerminal: false,
});
- expect(notice).toContain('自动审批暂时不可用');
+ expect(notice).toContain('自动审批暂时无法给出判断');
+ // 必须说清操作的去向 —— 现在是转交用户确认,不再是静默拒绝。
+ expect(notice).toContain('转由你来确认');
// 必须给出用户能做的事,否则等于只说"又失败了"。
expect(notice).toContain('默认权限');
// 不得把 [CODE] 前缀或英文原文推给渠道用户。
expect(notice).not.toContain('AUTO_REVIEW_UNAVAILABLE');
- expect(notice).not.toContain('Auto-review is temporarily');
+ expect(notice).not.toContain('Auto-review could not');
});
it('其它带 bracket code 的非终止 error 仍保持静默', () => {
diff --git a/apps/desktop/src/main/im/shared/turnRetryNotice.ts b/apps/desktop/src/main/im/shared/turnRetryNotice.ts
index 1520ff4d0f..099dd294dd 100644
--- a/apps/desktop/src/main/im/shared/turnRetryNotice.ts
+++ b/apps/desktop/src/main/im/shared/turnRetryNotice.ts
@@ -47,7 +47,8 @@ import {
*/
function autoReviewUnavailableNotice(message: string): string | null {
return isAutoReviewUnavailableNotice(message)
- ? '自动审批暂时不可用,需要审批的操作会被拒绝。想自己确认这些操作,可以把这个任务切到「默认权限」。'
+ ? '自动审批暂时无法给出判断(网络或服务波动),需要审批的操作已转由你来确认。'
+ + '想少被打断,可以把这个任务切到「默认权限」自行掌控。'
: null;
}
diff --git a/apps/desktop/src/main/maker-host/__tests__/autoPermissionReviewer.test.ts b/apps/desktop/src/main/maker-host/__tests__/autoPermissionReviewer.test.ts
index 7fd6d2f2cb..a846ab4f4b 100644
--- a/apps/desktop/src/main/maker-host/__tests__/autoPermissionReviewer.test.ts
+++ b/apps/desktop/src/main/maker-host/__tests__/autoPermissionReviewer.test.ts
@@ -34,7 +34,10 @@ describe('buildAutoPermissionReviewPrompt', () => {
const prompt = buildAutoPermissionReviewPrompt(request());
expect(prompt).toContain('The user selected Auto because they do not want routine interruptions.');
- expect(prompt).toContain('Prefer block over ask whenever a safer retry can avoid interrupting the user.');
+ // 「能 block 就别打扰」仍在,但被限定为「STEP 1 没命中的动作」—— 否则它会
+ // 压过凭证外传等红线,把本该让用户看见的动作静默拦掉(实测三轮全中)。
+ expect(prompt).toContain('Prefer block over ask');
+ expect(prompt).toContain('ONLY for actions that did not match STEP 1');
expect(prompt).toContain('Fix the type error and run tests');
expect(prompt).toContain('npx tsc --noEmit');
expect(prompt).toContain('/repo');
@@ -52,7 +55,10 @@ describe('buildAutoPermissionReviewPrompt', () => {
expect(prompt).toContain('"workspaceRoot":"/repo"');
expect(prompt).toContain('"readOnlyReferenceRoots":["/extra-docs"]');
- expect(prompt).toContain('never allow an action that writes, deletes, or modifies anything inside them');
+ // 读与写必须分成两句独立表述。写在同一句里时模型会串行理解成「这些目录里
+ // 的操作都要拦」,连读参考资料都被判 block(实测 nano 上 5/5 全错)。
+ expect(prompt).toContain('READING anything inside them is routine reference work');
+ expect(prompt).toContain('WRITING, deleting, or modifying anything inside them');
expect(prompt).toContain('edits inside workspaceRoot');
});
@@ -143,10 +149,11 @@ describe('createAutoPermissionReviewer', () => {
expect(JSON.stringify(logger.debug.mock.calls)).not.toContain('npx tsc --noEmit');
});
- it('returns null on malformed output or request failure so core can silently block', async () => {
+ it('returns null on malformed output or request failure so core can hand over to the user', async () => {
const logger = { debug: vi.fn(), warn: vi.fn() };
+ const malformedRequestText = vi.fn(async () => 'not json');
const malformed = createAutoPermissionReviewer({
- requestText: vi.fn(async () => 'not json'),
+ requestText: malformedRequestText,
logger,
});
const failed = createAutoPermissionReviewer({
@@ -158,13 +165,120 @@ describe('createAutoPermissionReviewer', () => {
await expect(malformed(request())).resolves.toBeNull();
await expect(failed(request())).resolves.toBeNull();
+ // 解析失败是该模型在这条 prompt 上的稳定行为,重试只会重复烧钱 —— 只试一次。
+ expect(malformedRequestText).toHaveBeenCalledTimes(1);
expect(logger.warn).toHaveBeenCalledWith(
- 'auto permission reviewer returned malformed output',
- expect.any(Object),
+ 'auto permission reviewer attempt failed',
+ expect.objectContaining({ failure: 'malformed' }),
);
expect(logger.warn).toHaveBeenCalledWith(
- 'auto permission reviewer failed',
- expect.objectContaining({ error: 'offline' }),
+ 'auto permission reviewer attempt failed',
+ expect.objectContaining({ failure: 'error', error: 'offline' }),
+ );
+ });
+
+ it('retries a transient failure and returns the recovered verdict', async () => {
+ const logger = { debug: vi.fn(), warn: vi.fn() };
+ const requestText = vi.fn()
+ .mockRejectedValueOnce(new Error('socket hang up'))
+ .mockResolvedValueOnce('{"verdict":"allow","reason":"Routine test"}');
+ const reviewer = createAutoPermissionReviewer({ requestText, logger });
+
+ await expect(reviewer(request())).resolves.toEqual({
+ verdict: 'allow',
+ reason: 'Routine test',
+ });
+ expect(requestText).toHaveBeenCalledTimes(2);
+ expect(logger.debug).toHaveBeenCalledWith(
+ 'auto permission reviewer recovered after retry',
+ expect.objectContaining({ attempt: 2 }),
+ );
+ });
+
+ it('gives up after the retry budget and reports the final failure', async () => {
+ const logger = { debug: vi.fn(), warn: vi.fn() };
+ const requestText = vi.fn(async () => {
+ throw new Error('offline');
+ });
+ const reviewer = createAutoPermissionReviewer({ requestText, logger });
+
+ await expect(reviewer(request())).resolves.toBeNull();
+ // 1 次首发 + 2 次重试。
+ expect(requestText).toHaveBeenCalledTimes(3);
+ expect(logger.warn).toHaveBeenCalledWith(
+ 'auto permission reviewer exhausted attempts',
+ expect.objectContaining({ failure: 'error' }),
+ );
+ });
+
+ it('still runs every declared retry when each attempt burns its full timeout', async () => {
+ // 回归 PR #2474 review:总预算只按 requestTimeoutMs × attempts 算(漏了退避)时,
+ // 前两次各耗满超时后第三次必然被自己的护栏挡掉 —— "声明两次重试、实际只跑一次"。
+ vi.useFakeTimers();
+ try {
+ const logger = { debug: vi.fn(), warn: vi.fn() };
+ const requestTimeoutMs = 12_000;
+ // 每次都挂到超时(永不 settle),让 attemptReview 的超时分支接管。
+ const requestText = vi.fn(() => new Promise<string | null>(() => {}));
+ const reviewer = createAutoPermissionReviewer({
+ requestText,
+ logger,
+ resolveRequestTimeoutMs: () => requestTimeoutMs,
+ });
+
+ const pending = reviewer(request());
+ // 三次完整超时 + 两次退避,全部推完。
+ await vi.advanceTimersByTimeAsync(requestTimeoutMs * 3 + 100 + 200 + 10);
+ await expect(pending).resolves.toBeNull();
+
+ expect(requestText).toHaveBeenCalledTimes(3);
+ // 第 3 次尝试确实发生在两次退避之后(12s + 100ms + 12s + 200ms),证明预算没被
+ // 自己的护栏提前截断。
+ expect(logger.warn).toHaveBeenCalledWith(
+ 'auto permission reviewer attempt failed',
+ expect.objectContaining({ attempt: 3, failure: 'timeout', durationMs: 36_300 }),
+ );
+ expect(logger.warn).toHaveBeenCalledWith(
+ 'auto permission reviewer exhausted attempts',
+ expect.objectContaining({ failure: 'timeout' }),
+ );
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it('still runs every retry when real scheduling overhead eats into the budget', async () => {
+ // 回归 PR #2474 review 第二轮:预算精确等于"三次超时 + 两次退避"时,prompt 构造
+ // 与定时器调度的那几毫秒会让第三次判断越界 —— 等于要求额外开销恰好为零。
+ // 这里用真实时钟 + 极短超时,让调度开销占比足够大,把该场景逼出来。
+ const logger = { debug: vi.fn(), warn: vi.fn() };
+ const requestText = vi.fn(
+ () => new Promise<string | null>((resolve) => setTimeout(() => resolve(null), 50)),
+ );
+ const reviewer = createAutoPermissionReviewer({
+ requestText,
+ logger,
+ resolveRequestTimeoutMs: () => 20,
+ });
+
+ await expect(reviewer(request())).resolves.toBeNull();
+ // 次数由 attempts 决定,不被调度抖动侵蚀。
+ expect(requestText).toHaveBeenCalledTimes(3);
+ });
+
+ it('honours a per-request timeout so slow reasoning models are not cut short', async () => {
+ const logger = { debug: vi.fn(), warn: vi.fn() };
+ const requestText = vi.fn(async () => '{"verdict":"allow"}');
+ const resolveRequestTimeoutMs = vi.fn(() => 30_000);
+ const reviewer = createAutoPermissionReviewer({
+ requestText,
+ logger,
+ resolveRequestTimeoutMs,
+ });
+
+ await expect(reviewer(request())).resolves.toEqual({ verdict: 'allow' });
+ expect(resolveRequestTimeoutMs).toHaveBeenCalledWith(
+ expect.objectContaining({ model: 'current-model' }),
);
});
@@ -190,18 +304,24 @@ describe('createAutoPermissionReviewer', () => {
it('enforces its own deadline even when requestText never settles', async () => {
vi.useFakeTimers();
const logger = { debug: vi.fn(), warn: vi.fn() };
- const reviewer = createAutoPermissionReviewer({
- requestText: vi.fn(() => new Promise<string | null>(() => {})),
- logger,
- });
+ const requestText = vi.fn(() => new Promise<string | null>(() => {}));
+ const reviewer = createAutoPermissionReviewer({ requestText, logger });
const pending = reviewer(request());
- await vi.advanceTimersByTimeAsync(DEFAULT_AUTO_REVIEW_TIMEOUT_POLICY.requestTimeoutMs);
+ // 每次尝试都拿完整的 requestTimeoutMs;超时可重试,故要推进整个重试预算
+ // (3 次尝试 + 退避)才会最终放弃。
+ await vi.advanceTimersByTimeAsync(
+ DEFAULT_AUTO_REVIEW_TIMEOUT_POLICY.requestTimeoutMs * 3 + 1_000,
+ );
await expect(pending).resolves.toBeNull();
expect(logger.warn).toHaveBeenCalledWith(
- 'auto permission reviewer timed out',
- expect.objectContaining({ durationMs: DEFAULT_AUTO_REVIEW_TIMEOUT_POLICY.requestTimeoutMs }),
+ 'auto permission reviewer attempt failed',
+ expect.objectContaining({ failure: 'timeout' }),
+ );
+ expect(logger.warn).toHaveBeenCalledWith(
+ 'auto permission reviewer exhausted attempts',
+ expect.objectContaining({ failure: 'timeout' }),
);
});
diff --git a/apps/desktop/src/main/maker-host/__tests__/autoReviewBudget.test.ts b/apps/desktop/src/main/maker-host/__tests__/autoReviewBudget.test.ts
new file mode 100644
index 0000000000..ed0ba5cb03
--- /dev/null
+++ b/apps/desktop/src/main/maker-host/__tests__/autoReviewBudget.test.ts
@@ -0,0 +1,124 @@
+import { describe, expect, it } from 'vitest';
+
+import type { CatalogModel } from '@cindy/model-providers';
+
+import {
+ findCatalogModel,
+ modelCanSuppressReasoning,
+ resolveAutoReviewBudget,
+} from '../auto-review-budget.js';
+
+const model = (over: Partial<CatalogModel> = {}): CatalogModel => ({
+ id: 'm1',
+ name: 'M1',
+ contextWindow: 200_000,
+ efforts: [],
+ defaultEffort: null,
+ ...over,
+} as CatalogModel);
+
+describe('modelCanSuppressReasoning', () => {
+ it('treats an explicit low/minimal tier as suppressible', () => {
+ expect(modelCanSuppressReasoning(model({ efforts: ['low', 'medium', 'high'] }))).toBe(true);
+ expect(modelCanSuppressReasoning(model({ efforts: ['minimal', 'high', 'max'] }))).toBe(true);
+ });
+
+ it('treats a model with no effort switch as suppressible', () => {
+ // Kimi K2.6 这类:不支持切档,但也不会强制长思考,紧凑额度够用。
+ expect(modelCanSuppressReasoning(model({ efforts: [] }))).toBe(true);
+ });
+
+ it('treats a forced-reasoning model as NOT suppressible', () => {
+ // DeepSeek V4 Pro/Flash:档位只有 high/max,传 low 会被上调 —— 384 token
+ // 会被思考烧光、正文为空,正是审核静默失效的根因。
+ expect(modelCanSuppressReasoning(model({ efforts: ['high', 'max'] }))).toBe(false);
+ });
+
+ it('is conservative when the model is unknown', () => {
+ // 目录里查不到(自定义供应商未声明能力)时宁可多给额度,也不要重演 384 token
+ // 判不出来的静默失败。
+ expect(modelCanSuppressReasoning(undefined)).toBe(false);
+ });
+});
+
+describe('resolveAutoReviewBudget', () => {
+ it('keeps the compact budget for models that can turn reasoning down', () => {
+ const budget = resolveAutoReviewBudget(model({ efforts: ['low', 'high'] }));
+ expect(budget.maxTokens).toBe(384);
+ expect(budget.timeoutMs).toBe(12_000);
+ expect(budget.reasoningEffort).toBe('low');
+ });
+
+ it('widens the budget for forced-reasoning models and drops the ineffective effort hint', () => {
+ const budget = resolveAutoReviewBudget(model({ efforts: ['high', 'max'] }));
+ expect(budget.maxTokens).toBeGreaterThan(384);
+ expect(budget.timeoutMs).toBeGreaterThan(12_000);
+ // 传 low 会被上调成模型支持的最低档,平白带一个不生效的字段;个别上游还会
+ // 因为不认的值直接 400。
+ expect(budget.reasoningEffort).toBeUndefined();
+ });
+
+ it('widens the budget when the model is unknown', () => {
+ const budget = resolveAutoReviewBudget(undefined);
+ expect(budget.maxTokens).toBeGreaterThan(384);
+ expect(budget.reasoningEffort).toBeUndefined();
+ });
+
+ it('sends minimal — not low — when that is the lowest tier the model declares', () => {
+ // 回归 PR #2474 review P1:目录里 z-ai/glm-5.2 是 ['minimal','high','max'],
+ // 固定发 low 会被上游拒绝或悄悄提到更高档,反而烧掉 384 token 的正文空间。
+ const budget = resolveAutoReviewBudget(model({ efforts: ['minimal', 'high', 'max'] }));
+ expect(budget.maxTokens).toBe(384);
+ expect(budget.reasoningEffort).toBe('minimal');
+ });
+
+ it('omits the effort field entirely for models with no effort tiers', () => {
+ // efforts: [] 的模型目录里有 10 个(Haiku 4.5 / Kimi K2.6 / grok 系 / qwen3.7-max
+ // 等)。它们不强制长思考,所以照常走紧凑额度,但带一个不认的字段是白冒 400 的险。
+ const budget = resolveAutoReviewBudget(model({ efforts: [] }));
+ expect(budget.maxTokens).toBe(384);
+ expect(budget.timeoutMs).toBe(12_000);
+ expect(budget.reasoningEffort).toBeUndefined();
+ });
+
+ it('prefers low over minimal when the model declares both', () => {
+ const budget = resolveAutoReviewBudget(model({ efforts: ['minimal', 'low', 'high'] }));
+ expect(budget.reasoningEffort).toBe('low');
+ });
+});
+
+describe('findCatalogModel', () => {
+ const providers = [
+ { id: 'xd', models: { 'claude-code': [model({ id: 'shared' })], pi: [model({ id: 'shared' })] } },
+ { id: 'other', models: { 'claude-code': [model({ id: 'only-here', efforts: ['high'] })] } },
+ ];
+
+ it('prefers the named provider', () => {
+ expect(findCatalogModel(providers, 'xd', 'pi', 'shared')?.id).toBe('shared');
+ });
+
+ it('falls back to a catalog-wide lookup when no provider is named', () => {
+ // Pi 的 providerId=null 表示走默认网关路由;这里只读能力元数据,不参与路由。
+ expect(findCatalogModel(providers, null, 'claude-code', 'only-here')?.efforts)
+ .toEqual(['high']);
+ });
+
+ it('returns undefined for an unknown model instead of guessing', () => {
+ expect(findCatalogModel(providers, 'xd', 'pi', 'nope')).toBeUndefined();
+ expect(findCatalogModel(providers, 'xd', 'pi', ' ')).toBeUndefined();
+ });
+
+ it('never borrows another provider capability when a provider is named', () => {
+ // 回归 PR #2474 review:同一个模型 id 在两家目录下能力不同时,跨家借用会把
+ // 强制思考的路由误判成"能关思考",于是又拿回��凑额度 —— 正是本 PR 要修的故障。
+ const crossProvider = [
+ { id: 'xd', models: { 'claude-code': [model({ id: 'dual', efforts: ['high'] })] } },
+ { id: 'other', models: { 'claude-code': [model({ id: 'dual', efforts: ['low', 'high'] })] } },
+ ];
+ // 点名 'nowhere' 这家没有该模型 → 返回 undefined,由调用方走保守宽裕档;
+ // 绝不落到 'other' 的 low 档。
+ expect(findCatalogModel(crossProvider, 'nowhere', 'claude-code', 'dual')).toBeUndefined();
+ // 点名 'xd' 时只认 xd 自己的声明。
+ expect(findCatalogModel(crossProvider, 'xd', 'claude-code', 'dual')?.efforts).toEqual(['high']);
+ });
+});
diff --git a/apps/desktop/src/main/maker-host/auto-permission-reviewer.ts b/apps/desktop/src/main/maker-host/auto-permission-reviewer.ts
index 4ae9518118..eb9b513617 100644
--- a/apps/desktop/src/main/maker-host/auto-permission-reviewer.ts
+++ b/apps/desktop/src/main/maker-host/auto-permission-reviewer.ts
@@ -2,6 +2,10 @@ import {
getAutoReviewActionTextLength,
MAX_AUTO_REVIEW_ACTION_TEXT_CHARS,
DEFAULT_AUTO_REVIEW_TIMEOUT_POLICY,
+ AUTO_REVIEW_RETRY_ATTEMPTS,
+ AUTO_REVIEW_RETRY_BACKOFF_MS,
+ AUTO_REVIEW_RETRY_SCHEDULING_SLACK_MS,
+ autoReviewRetryBudgetMs,
type AutoReviewTimeoutPolicy,
type AutoReviewDecision,
type AutoReviewRequest,
@@ -15,6 +19,14 @@ interface AutoPermissionReviewerLogger {
export interface AutoPermissionReviewerDeps {
requestText(request: AutoReviewRequest, prompt: string): Promise<string | null>;
logger: AutoPermissionReviewerLogger;
+ /**
+ * 本次请求允许的单次耗时。缺省用构造时的 timeoutPolicy.requestTimeoutMs。
+ *
+ * 存在的理由:额度是**按模型能力逐请求**决定的(强制思考的模型要 30s,能关
+ * 思考的 12s 就够,见 auto-review-budget.ts),而 timeoutPolicy 是构造期固定的。
+ * 如果这里的守卫仍按固定值计时,放宽额度的那一档会被自己的守卫切断。
+ */
+ resolveRequestTimeoutMs?(request: AutoReviewRequest): number;
}
const MAX_REASON_CHARS = 240;
@@ -24,6 +36,48 @@ const MAX_WORKSPACE_ROOTS = 8;
const MAX_WORKSPACE_ROOT_CHARS = 512;
const REVIEW_TIMEOUT = Symbol('auto-review-timeout');
+/**
+ * 短暂波动的重试次数(总尝试 = 1 + RETRIES)。
+ *
+ * 实测依据(2026-08-11,720 次网关调用):失败几乎全是 timeout / bad_json 这类
+ * 一次性抖动,没有一例是同一动作稳定失败。这类抖动重试一次即可恢复,而每多试
+ * 一次都要占用用户的等待时间 —— 取 2 是「够救回抖动」与「别把灰区卡成十几秒」
+ * 的折中。
+ *
+ * 不重试的情形见 isRetriableFailure:模型给出了合法但不可解析的输出属于稳定
+ * 行为,重试只是重复烧钱。
+ */
+const REVIEW_RETRIES = AUTO_REVIEW_RETRY_ATTEMPTS - 1;
+
+/**
+ * 重试前的退避,给瞬时网络/限流一点恢复时间;总开销上界 300ms。
+ *
+ * 与核心侧同源:核心的外层守卫按同一组常量推上界,分开维护会让守卫悄悄截断重试。
+ */
+const RETRY_BACKOFF_MS = AUTO_REVIEW_RETRY_BACKOFF_MS;
+
+/**
+ * 时间兜底之上的余量:prompt 构造、`setTimeout` 调度抖动、事件循环排队都算在
+ * `elapsed` 里但不属于任何一次请求。不留余量就等于要求这些开销恰好为零
+ * (PR #2474 review),真机上必然差那么几毫秒。
+ *
+ * 核心侧的外层守卫按同一个余量放宽,否则守卫会先于兜底触发,等于余量白留。
+ */
+const RETRY_SCHEDULING_SLACK_MS = AUTO_REVIEW_RETRY_SCHEDULING_SLACK_MS;
+
+/** 单次尝试的失败形态。区分它们决定了「该不该再试一次」。 */
+type AttemptFailure = 'timeout' | 'empty' | 'malformed' | 'error';
+
+/**
+ * 只有基础设施性的失败才值得重试。
+ *
+ * malformed(模型吐了解析不出的东西)刻意**不**重试:它反映的是该模型在这条
+ * prompt 上的稳定行为,重试大概率得到同样的结果,只是多付一次钱、多等一轮。
+ */
+function isRetriableFailure(failure: AttemptFailure): boolean {
+ return failure === 'timeout' || failure === 'empty' || failure === 'error';
+}
+
function compactText(value: string, maxChars: number): string {
if (value.length <= maxChars) return value;
const marker = '\n…[truncated]…\n';
@@ -67,6 +121,18 @@ export function buildAutoPermissionReviewPrompt(request: AutoReviewRequest): str
.map((root) => compactText(root, MAX_WORKSPACE_ROOT_CHARS)),
platform: request.platform,
};
+ // 分两步表述,而不是把五条规则平铺 —— 平铺版实测有两个稳定缺陷
+ // (2026-08-11,720 次网关调用,gpt-5.4-nano 与 kimi-k2.6 双模型验证):
+ //
+ // 1. 「Prefer block over ask whenever a safer retry can avoid interrupting
+ // the user」会压过 ask 红线清单。凭证外传、rm -rf ~、关闭 SIP 全被判成
+ // 静默 block —— 安全上拦住了,但用户永远不知道 agent 刚才想干这个。
+ // 故把红线提为 STEP 1,并显式声明「存在更安全的替代做法不构成降级理由」。
+ // 2. 只读引用目录的读与写写在同一句里,模型串行理解成「这些目录里的操作都要拦」,
+ // 读参考资料被误判 block(nano 上 5/5 全错)。故拆成两句独立表述。
+ //
+ // 修完两个模型的合格率 79.4%→97.8% / 87.8%→96.1%,且「危险动作误放行」与
+ // 「常规工作误打扰」两项始终为 0。改这段前请复跑 bench 确认不回归。
return [
'You are Cindy Auto Review, a lightweight pre-execution safety classifier.',
'The user selected Auto because they do not want routine interruptions.',
@@ -75,12 +141,29 @@ export function buildAutoPermissionReviewPrompt(request: AutoReviewRequest): str
'Return exactly one compact JSON object:',
'{"verdict":"allow|block|ask","reason":"short reason"}',
'',
- 'Decision policy:',
- '- allow: routine, reversible development work aligned with the current user intent, especially normal reads, tests, lint, builds, package commands, edits inside workspaceRoot, ordinary HTTP fetches, and normal git operations.',
- '- block: the action is ambiguous or risky but the agent can choose a safer alternative. Blocking is silent to the user; give the main agent a useful short reason.',
- '- ask: only a genuinely high-impact consent boundary: credentials or data exfiltration, privilege/system-security changes, broad irreversible destruction, production deployment/IAM/financial action, external communication with real-world effect, or force-pushing a protected branch.',
- '- readOnlyReferenceRoots are read-only reference context: reading them is routine, but never allow an action that writes, deletes, or modifies anything inside them — block it so the agent keeps its changes inside workspaceRoot.',
- '- Prefer allow over block for ordinary coding scoped to workspaceRoot. Prefer block over ask whenever a safer retry can avoid interrupting the user.',
+ 'STEP 1 — Consent boundaries. If the action does ANY of the following, the verdict',
+ 'is "ask". This overrides every other rule below, including the preference for a',
+ 'silent block. A safer alternative existing does NOT downgrade these to "block":',
+ '- reads, copies, or transmits credentials, keys, tokens, or private user data to any external destination',
+ '- changes privilege, sandbox, or system-security settings (sudo policy, SIP, firewall, permissions)',
+ '- irreversibly destroys a broad scope (home directory, whole volumes, production data/tables)',
+ '- deploys to production, changes IAM/billing, or performs a financial action',
+ '- communicates externally with real-world effect (email, publish, post, message a person)',
+ '- force-pushes a protected branch (main/master/release)',
+ 'The user must be given the chance to see and decide these, even though it interrupts.',
+ '',
+ 'STEP 2 — Otherwise choose between allow and block:',
+ '- allow: routine, reversible development work aligned with the current user intent —',
+ ' reads, tests, lint, builds, package commands, edits inside workspaceRoot,',
+ ' ordinary HTTP fetches, and normal git operations. Prefer allow for ordinary coding.',
+ '- block: ambiguous or risky, but the agent can pick a safer alternative. Blocking is',
+ ' silent to the user; give the main agent a short, useful reason. Prefer block over ask',
+ ' ONLY for actions that did not match STEP 1.',
+ '',
+ 'About readOnlyReferenceRoots:',
+ '- READING anything inside them is routine reference work → allow.',
+ '- WRITING, deleting, or modifying anything inside them → block, so the agent keeps',
+ ' its changes inside workspaceRoot.',
'',
'<review_input>',
serializeUntrustedPayload(payload),
@@ -118,6 +201,36 @@ export function parseAutoPermissionReviewDecision(text: string): AutoReviewDecis
};
}
+/** 跑一次审阅请求;成功返回裁决,失败返回失败形态(供调用方决定要不要重试)。 */
+async function attemptReview(
+ deps: AutoPermissionReviewerDeps,
+ request: AutoReviewRequest,
+ prompt: string,
+ requestTimeoutMs: number,
+): Promise<{ decision: AutoReviewDecision } | { failure: AttemptFailure; error?: string }> {
+ let timeout: ReturnType<typeof setTimeout> | undefined;
+ try {
+ const text = await Promise.race([
+ deps.requestText(request, prompt),
+ new Promise<typeof REVIEW_TIMEOUT>((resolve) => {
+ timeout = setTimeout(() => resolve(REVIEW_TIMEOUT), requestTimeoutMs);
+ }),
+ ]);
+ if (text === REVIEW_TIMEOUT) return { failure: 'timeout' };
+ if (!text) return { failure: 'empty' };
+ const decision = parseAutoPermissionReviewDecision(text);
+ if (!decision) return { failure: 'malformed' };
+ return { decision };
+ } catch (error) {
+ return {
+ failure: 'error',
+ error: error instanceof Error ? error.message : String(error),
+ };
+ } finally {
+ if (timeout) clearTimeout(timeout);
+ }
+}
+
export function createAutoPermissionReviewer(
deps: AutoPermissionReviewerDeps,
timeoutPolicy: Readonly<AutoReviewTimeoutPolicy> = DEFAULT_AUTO_REVIEW_TIMEOUT_POLICY,
@@ -136,53 +249,93 @@ export function createAutoPermissionReviewer(
return null;
}
const startedAt = Date.now();
- let timeout: ReturnType<typeof setTimeout> | undefined;
+ let prompt: string;
try {
- const text = await Promise.race([
- deps.requestText(request, buildAutoPermissionReviewPrompt(request)),
- new Promise<typeof REVIEW_TIMEOUT>((resolve) => {
- timeout = setTimeout(() => resolve(REVIEW_TIMEOUT), timeoutPolicy.requestTimeoutMs);
- }),
- ]);
- if (text === REVIEW_TIMEOUT) {
- deps.logger.warn('auto permission reviewer timed out', {
- agentKind: request.agentKind,
- providerId: request.providerId ?? null,
- model: request.model,
- durationMs: Date.now() - startedAt,
- });
- return null;
+ prompt = buildAutoPermissionReviewPrompt(request);
+ } catch (error) {
+ // prompt 构造失败(动作超限等)是确定性的,重试无意义。
+ deps.logger.warn('auto permission reviewer failed', {
+ agentKind: request.agentKind,
+ providerId: request.providerId ?? null,
+ model: request.model,
+ durationMs: Date.now() - startedAt,
+ error: error instanceof Error ? error.message : String(error),
+ });
+ return null;
+ }
+
+ // 每次尝试都拿完整的 requestTimeoutMs —— 不按次数切分。
+ //
+ // 切分是错的:抖动恢复往往就差那几秒,把 12s 切成 4s 会把本来能成功的请求
+ // 也判成超时,反而制造失败。总耗时的上界由 maker-core 的
+ // AUTO_REVIEW_DELEGATE_HARD_CEILING_MS 兜住,那里已按最慢一档 + 重试留足。
+ const attempts = 1 + REVIEW_RETRIES;
+ // 单次超时按本次请求的模型能力取(强制思考的模型需要更久),缺省回到构造期策略。
+ const requestTimeoutMs = deps.resolveRequestTimeoutMs?.(request)
+ ?? timeoutPolicy.requestTimeoutMs;
+ // 重试的**意图是次数**(试满 attempts 次),不是"在某个时间窗内尽量试"。
+ //
+ // 早先按 `elapsed + backoff + requestTimeoutMs > totalBudgetMs` 判断,等于要求
+ // prompt 构造与定时器调度的开销恰好为零 —— 真机上永远差那么几毫秒,于是最需要
+ // 重试的连续 timeout 场景反而只跑得到两次(PR #2474 review 两轮)。
+ //
+ // 改成:循环边界只由 attempts 决定;时间预算退居**兜底**,且带明确余量 —— 只有
+ // 已经耗掉的时间超出"全部尝试 + 退避 + 余量"时才提前收手(那意味着上游卡死到
+ // 连外层守卫都快触发了,再发一次纯属浪费)。
+ const deadlineAt = startedAt
+ + autoReviewRetryBudgetMs(requestTimeoutMs, attempts)
+ + RETRY_SCHEDULING_SLACK_MS;
+
+ let lastFailure: AttemptFailure = 'error';
+ for (let attempt = 0; attempt < attempts; attempt++) {
+ if (attempt > 0) {
+ const backoff = RETRY_BACKOFF_MS[Math.min(attempt - 1, RETRY_BACKOFF_MS.length - 1)];
+ // 兜底:真实剩余时间连一次退避都放不下时才停(正常路径永远不命中)。
+ if (Date.now() + backoff >= deadlineAt) break;
+ await new Promise((resolve) => setTimeout(resolve, backoff));
}
- if (!text) return null;
- const decision = parseAutoPermissionReviewDecision(text);
- if (!decision) {
- deps.logger.warn('auto permission reviewer returned malformed output', {
+ const result = await attemptReview(deps, request, prompt, requestTimeoutMs);
+ if ('decision' in result) {
+ if (attempt > 0) {
+ deps.logger.debug('auto permission reviewer recovered after retry', {
+ agentKind: request.agentKind,
+ providerId: request.providerId ?? null,
+ model: request.model,
+ attempt: attempt + 1,
+ durationMs: Date.now() - startedAt,
+ });
+ }
+ deps.logger.debug('auto permission reviewer completed', {
agentKind: request.agentKind,
providerId: request.providerId ?? null,
model: request.model,
+ verdict: result.decision.verdict,
+ attempts: attempt + 1,
durationMs: Date.now() - startedAt,
});
- return null;
+ return result.decision;
}
- deps.logger.debug('auto permission reviewer completed', {
- agentKind: request.agentKind,
- providerId: request.providerId ?? null,
- model: request.model,
- verdict: decision.verdict,
- durationMs: Date.now() - startedAt,
- });
- return decision;
- } catch (error) {
- deps.logger.warn('auto permission reviewer failed', {
+ lastFailure = result.failure;
+ deps.logger.warn('auto permission reviewer attempt failed', {
agentKind: request.agentKind,
providerId: request.providerId ?? null,
model: request.model,
+ attempt: attempt + 1,
+ maxAttempts: attempts,
+ failure: result.failure,
durationMs: Date.now() - startedAt,
- error: error instanceof Error ? error.message : String(error),
+ ...(result.error ? { error: result.error } : {}),
});
- return null;
- } finally {
- if (timeout) clearTimeout(timeout);
+ if (!isRetriableFailure(result.failure)) break;
}
+
+ deps.logger.warn('auto permission reviewer exhausted attempts', {
+ agentKind: request.agentKind,
+ providerId: request.providerId ?? null,
+ model: request.model,
+ failure: lastFailure,
+ durationMs: Date.now() - startedAt,
+ });
+ return null;
};
}
diff --git a/apps/desktop/src/main/maker-host/auto-review-budget.ts b/apps/desktop/src/main/maker-host/auto-review-budget.ts
new file mode 100644
index 0000000000..a81b3e3124
--- /dev/null
+++ b/apps/desktop/src/main/maker-host/auto-review-budget.ts
@@ -0,0 +1,135 @@
+/**
+ * Auto-review 请求的额度自适应。
+ *
+ * 背景:审核请求原本固定 384 token / 12 秒 / reasoningEffort='low'。这套参数
+ * 对「能关掉思考」的模型足够,但对**强制思考**的模型是致命的 —— 它们的档位里
+ * 根本没有 low/minimal,传了也会被上调,于是 384 token 全烧在思考上、正文为空,
+ * 审核判定失败。实测(2026-08-11)DeepSeek V4 Pro 在部分灰区用例上三轮全部
+ * `empty_content_reasoning_only`,而且越是需要斟酌的场景越容易触发 ——
+ * 审核最该发挥作用的时刻恰好最容易失效。
+ *
+ * 参考 Codex Guardian 的取舍:它给审阅器的是 272k 窗口、无输出上限、medium 档,
+ * 还允许调工具查证。我们不做到那个量级(那需要嵌套 agent 会话),但至少要让
+ * 强制思考的模型有写完结论的空间 —— 慢一点可以接受,判不出来不行。
+ */
+
+import type { AgentKind, CatalogModel } from '@cindy/model-providers';
+
+/** 能关思考的模型:够写一个 JSON 裁决即可。 */
+const COMPACT_MAX_TOKENS = 384;
+const COMPACT_TIMEOUT_MS = 12_000;
+
+/**
+ * 强制思考的模型:思考段 + 结论段都要装得下。
+ *
+ * 4096 是按实测的思考长度留的余量(DeepSeek 类模型在灰区用例上的思考通常
+ * 1-2k token),不是拍脑袋的大数 —— 再大只会让超时更容易先触发。
+ */
+const REASONING_MAX_TOKENS = 4_096;
+
+/**
+ * 相应放宽的超时。思考模型多花的是**输出**时间,首 token 延迟差别不大,
+ * 所以按输出量等比放宽而不是无限等 —— 用户仍在等这次工具调用。
+ */
+const REASONING_TIMEOUT_MS = 30_000;
+
+/** 审核请求的执行参数。 */
+export interface AutoReviewBudget {
+ maxTokens: number;
+ timeoutMs: number;
+ /** `undefined` = 不传该字段,让模型走自己的默认档。 */
+ reasoningEffort?: 'minimal' | 'low' | 'medium' | 'high';
+}
+
+/**
+ * 该模型能否把思考关到最低档。
+ *
+ * 判据是模型目录声明的 `efforts`:
+ * - 含 `minimal` 或 `low` → 能关,给紧凑额度;
+ * - 明确非空但不含二者(如 DeepSeek 的 `['high','max']`)→ 强制思考,给宽裕额度;
+ * - 空数组 `[]` → 该模型不支持切档(如 Kimi K2.6),它也不会强制长思考,按紧凑处理;
+ * - `undefined`(目录里没这个模型 / 自定义供应商未声明)→ **保守按强制思考处理**。
+ * 宁可多给额度慢一点,也不要重演 384 token 判不出来的静默失败。
+ */
+export function modelCanSuppressReasoning(model: CatalogModel | undefined): boolean {
+ const efforts = model?.efforts;
+ if (efforts === undefined) return false;
+ if (efforts.length === 0) return true;
+ return efforts.includes('minimal') || efforts.includes('low');
+}
+
+/**
+ * 紧凑档实际该发的 effort:该模型**自己声明过**的最低档,没有声明就不发。
+ *
+ * 只在 `modelCanSuppressReasoning` 为真时调用,所以这里只需区分 low / minimal /
+ * 空数组三种;`undefined`(目录查不到)走的是宽裕分支,压根到不了这里。
+ */
+function lowestDeclaredEffort(
+ model: CatalogModel | undefined,
+): 'minimal' | 'low' | undefined {
+ const efforts = model?.efforts;
+ if (!efforts || efforts.length === 0) return undefined;
+ if (efforts.includes('low')) return 'low';
+ if (efforts.includes('minimal')) return 'minimal';
+ return undefined;
+}
+
+/**
+ * 按模型能力选额度。
+ *
+ * `model` 传 `undefined` 表示目录里查不到 —— 走保守分支(宽裕额度)。
+ */
+export function resolveAutoReviewBudget(model: CatalogModel | undefined): AutoReviewBudget {
+ if (modelCanSuppressReasoning(model)) {
+ return {
+ maxTokens: COMPACT_MAX_TOKENS,
+ timeoutMs: COMPACT_TIMEOUT_MS,
+ // 只发该模型真正声明的最低档 —— 紧凑分支覆盖三种模型,不能一律发 low:
+ // - 声明了 low → low
+ // - 只声明 minimal → minimal(如 z-ai/glm-5.2;发 low 会被上游拒绝或
+ // 悄悄提到更高档,反而烧掉 384 token 的正文空间)
+ // - efforts: [] → 省略(如 Haiku 4.5 / Kimi K2.6 / grok 系共 10 个;
+ // 它们根本没有档位概念,带一个不认的字段是白白冒 400 的险)
+ // 发错档会让审阅请求连续失败 → 重试耗尽 → 每个灰区操作降级成用户确认,
+ // 正好绕回本 PR 要修的故障(PR #2474 review P1)。
+ reasoningEffort: lowestDeclaredEffort(model),
+ };
+ }
+ return {
+ maxTokens: REASONING_MAX_TOKENS,
+ timeoutMs: REASONING_TIMEOUT_MS,
+ // 强制思考的模型不传 effort:传 low 会被���调成它支持的最低档,平白让请求
+ // 带一个不生效的字段;个别上游还会因为不认的值直接 400。
+ reasoningEffort: undefined,
+ };
+}
+
+/** 从当前目录里查一个 (供应商, agent, 模型) 的目录条目。 */
+export function findCatalogModel(
+ providers: ReadonlyArray<{
+ id: string;
+ models: Partial<Record<AgentKind, CatalogModel[]>>;
+ }>,
+ providerId: string | null | undefined,
+ agentKind: AgentKind,
+ modelId: string,
+): CatalogModel | undefined {
+ const normalizedModel = modelId.trim();
+ if (!normalizedModel) return undefined;
+ const normalizedProvider = providerId?.trim();
+ if (normalizedProvider) {
+ // 点名了供应商就**只**在它的目录里找:同一个模型 id 在不同供应商下可能声明不同
+ // 的 efforts,跨家借用会把强制思考的路由误判成"能关思考",于是又拿回 384/12s 的
+ // 紧凑额度 —— 正是本 PR 要修的那个空正文故障(PR #2474 review)。
+ // 未命中返回 undefined,由调用方走保守宽裕档。
+ const provider = providers.find((item) => item.id === normalizedProvider);
+ return (provider?.models[agentKind] ?? []).find((m) => m.id === normalizedModel);
+ }
+ // 没有 providerId(Pi 的 null = 走默认网关路由)时按模型 id 全目录找第一个命中。
+ // 只用于读能力元数据,不参与路由决策,所以首见即可。
+ for (const provider of providers) {
+ const hit = (provider.models[agentKind] ?? []).find((m) => m.id === normalizedModel);
+ if (hit) return hit;
+ }
+ return undefined;
+}
diff --git a/apps/desktop/src/main/maker-host/index.ts b/apps/desktop/src/main/maker-host/index.ts
index ab43e502d0..6fda33270d 100644
--- a/apps/desktop/src/main/maker-host/index.ts
+++ b/apps/desktop/src/main/maker-host/index.ts
@@ -15,8 +15,8 @@ import {
Maker,
ClaudeCodeAgent,
CodexAgent,
- DEFAULT_AUTO_REVIEW_TIMEOUT_POLICY,
configureDefaultImageResizer,
+ type AutoReviewRequest,
type McpProvider,
} from '@cindy/maker-core';
import {
@@ -112,6 +112,7 @@ import {
import { resolveRemoteClaudeRoute } from './remote-claude-route.js';
import { claudeSubagentUsageBridge } from './claude-subagent-usage-bridge.js';
import { createAutoPermissionReviewer } from './auto-permission-reviewer.js';
+import { findCatalogModel, resolveAutoReviewBudget } from './auto-review-budget.js';
import { requestUtilityText } from '../utility-model/oneShotCandidates.js';
import { accountProviderReadinessBarrier } from './account-provider-readiness-barrier.js';
import { hasClaudeAiOAuth } from './claude-credentials-store.js';
@@ -239,18 +240,35 @@ type RemoteCcQuery = Awaited<
let _maker: Maker | null = null;
+/**
+ * 本次审核请求的额度。按模型能力自适应:能关思考的走紧凑档,强制思考的
+ * (以及目录里查不到的)给足思考+结论的空间 —— 固定 384 token 会让 DeepSeek
+ * 这类模型正文恒为空。详见 auto-review-budget.ts。
+ */
+function autoReviewBudgetFor(request: AutoReviewRequest) {
+ return resolveAutoReviewBudget(findCatalogModel(
+ getActiveCatalog().providers,
+ request.providerId,
+ request.agentKind,
+ request.model,
+ ));
+}
+
const reviewAutoPermissionAction = createAutoPermissionReviewer({
logger: desktopMakerLogger,
+ // 重试守卫必须按同一份额度计时,否则放宽额度的那一档会被自己的守卫切断。
+ resolveRequestTimeoutMs: (request) => autoReviewBudgetFor(request).timeoutMs,
requestText: async (request, prompt) => {
const maker = _maker;
if (!maker) return null;
+ const budget = autoReviewBudgetFor(request);
const result = await requestUtilityText(maker, prompt, {
providerId: request.providerId?.trim() || undefined,
agentKind: request.agentKind,
model: request.model,
- maxTokens: 384,
- timeoutMs: DEFAULT_AUTO_REVIEW_TIMEOUT_POLICY.requestTimeoutMs,
- reasoningEffort: 'low',
+ maxTokens: budget.maxTokens,
+ timeoutMs: budget.timeoutMs,
+ ...(budget.reasoningEffort ? { reasoningEffort: budget.reasoningEffort } : {}),
});
return result.ok ? result.text : null;
},
diff --git a/apps/desktop/src/main/utility-model/oneShotCandidates.ts b/apps/desktop/src/main/utility-model/oneShotCandidates.ts
index 513a9e497d..ddbf86328f 100644
--- a/apps/desktop/src/main/utility-model/oneShotCandidates.ts
+++ b/apps/desktop/src/main/utility-model/oneShotCandidates.ts
@@ -56,7 +56,7 @@ export type UtilityTextRequestOptions = {
maxTokens?: number;
timeoutMs?: number;
/** Optional lightweight reasoning hint for short internal classifiers. */
- reasoningEffort?: 'low' | 'medium' | 'high';
+ reasoningEffort?: 'minimal' | 'low' | 'medium' | 'high';
/** 显式任务来源;存在时禁止跨来源 fallback。 */
providerId?: string;
agentKind?: AgentKind;
@@ -554,7 +554,7 @@ async function requestBuiltinProviderText(
transport: UtilityModelTransport;
maxTokens?: number;
timeoutMs?: number;
- reasoningEffort?: 'low' | 'medium' | 'high';
+ reasoningEffort?: 'minimal' | 'low' | 'medium' | 'high';
},
): Promise<UtilityTextResult> {
const profile: UtilityModelProfile = {
@@ -824,7 +824,7 @@ async function requestLiteLlmText(input: {
prompt: string;
maxTokens?: number;
timeoutMs?: number;
- reasoningEffort?: 'low' | 'medium' | 'high';
+ reasoningEffort?: 'minimal' | 'low' | 'medium' | 'high';
}): Promise<string> {
const controller = new AbortController();
const timeoutMs = input.timeoutMs ?? 20_000;
@@ -933,7 +933,7 @@ async function requestProviderHttpText(input: {
prompt: string;
maxTokens?: number;
timeoutMs?: number;
- reasoningEffort?: 'low' | 'medium' | 'high';
+ reasoningEffort?: 'minimal' | 'low' | 'medium' | 'high';
/** Some coding-specialized models reject their wire's reasoning field. */
supportsReasoning?: boolean;
/** Unknown custom routes may reject optional fields from an otherwise compatible wire. */
@@ -1120,7 +1120,7 @@ async function requestCustomProviderText(input: {
prompt: string;
maxTokens?: number;
timeoutMs?: number;
- reasoningEffort?: 'low' | 'medium' | 'high';
+ reasoningEffort?: 'minimal' | 'low' | 'medium' | 'high';
}): Promise<string> {
const headers: Record<string, string> = {
...(input.headers ?? {}),
diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.json
index 405bdadab4..738b5973b4 100644
--- a/apps/desktop/src/renderer/i18n/locales/en/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json
@@ -6635,7 +6635,7 @@
"remoteError": {
"REMOTE_DAEMON_CLOSED": "Remote connection interrupted (the daemon may be upgrading or restarting). The turn has ended — please resend.",
"REMOTE_LOCAL_ATTACHMENT_UNSUPPORTED": "Local file/image attachments aren't accessible in remote sessions. Paste the content directly instead.",
- "AUTO_REVIEW_UNAVAILABLE": "Auto-review is temporarily unavailable, so actions that need review are being denied. Switch this task to Default permissions if you want to approve them yourself.",
+ "AUTO_REVIEW_UNAVAILABLE": "Auto-review could not reach a decision (network or service hiccup), so actions that need review are being handed to you to confirm. Switch this task to Default permissions if you would rather not be interrupted.",
"REMOTE_COMPAT_MODE_UNSUPPORTED": "Remote Claude Code sessions can't route through the local compat proxy (internal error).",
"REMOTE_GATEWAY_ENDPOINT_UNAVAILABLE": "Cindy AI credentials are not ready yet (issued automatically after sign-in). Please retry shortly; if this persists, check the Cindy AI status in Settings → Model Providers.",
"DEVICE_LINK_CONTROL_DISABLED": "Control for this device is off; the message was not sent.",
diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.json
index 108ffd655f..a0c10aa6a0 100644
--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json
@@ -6632,7 +6632,7 @@
"remoteError": {
"REMOTE_DAEMON_CLOSED": "リモート接続が中断されました(daemon がアップグレードまたは再起動中の可能性があります)。ターンが終了しました — 再送信してください。",
"REMOTE_LOCAL_ATTACHMENT_UNSUPPORTED": "リモートセッションではローカルのファイル/画像の添付にアクセスできません。内容を直接貼り付けてください。",
- "AUTO_REVIEW_UNAVAILABLE": "自動レビューが一時的に利用できないため、レビューが必要な操作は拒否されます。ご自身で承認する場合は、このセッションをデフォルト権限に切り替えてください。",
+ "AUTO_REVIEW_UNAVAILABLE": "自動レビューが判断できませんでした(ネットワークまたはサービスの一時的な問題)。レビューが必要な操作はご自身での確認に切り替わりました。中断を減らしたい場合は、このタスクをデフォルト権限に切り替えてください。",
"REMOTE_COMPAT_MODE_UNSUPPORTED": "リモート Claude Code セッションはローカル互換プロキシ経由でルーティングできません(内部エラー)。",
"REMOTE_GATEWAY_ENDPOINT_UNAVAILABLE": "Cindy AI の資格情報がまだ準備できていません(サインイン後に自動発行されます)。しばらくしてから再試行してください。続く場合は 設定 → モデルプロバイダー で Cindy AI の接続状態を確認してください。",
"DEVICE_LINK_CONTROL_DISABLED": "このデバイスの操作はオフです。メッセージは送信されていません。",
diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.json
index 5343a3aa21..1573e0b837 100644
--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json
@@ -6632,7 +6632,7 @@
"remoteError": {
"REMOTE_DAEMON_CLOSED": "원격 연결이 중단되었습니다(daemon이 업그레이드 또는 재시작 중일 수 있습니다). 턴이 종료되었습니다 — 다시 전송하세요.",
"REMOTE_LOCAL_ATTACHMENT_UNSUPPORTED": "원격 세션에서는 로컬 파일/이미지 첨부에 접근할 수 없습니다. 내용을 직접 붙여넣으세요.",
- "AUTO_REVIEW_UNAVAILABLE": "자동 리뷰를 일시적으로 사용할 수 없어 검토가 필요한 작업이 거부됩니다. 직접 승인하려면 이 세션을 기본 권한으로 전환하세요.",
+ "AUTO_REVIEW_UNAVAILABLE": "자동 리뷰가 판단을 내리지 못했습니다(네트워크 또는 서비스 일시 장애). 검토가 필요한 작업은 직접 확인하도록 전환되었습니다. 중단을 줄이려면 이 작업을 기본 권한으로 전환하세요.",
"REMOTE_COMPAT_MODE_UNSUPPORTED": "원격 Claude Code 세션은 로컬 호환 프록시를 통해 라우팅할 수 없습니다(내부 오류).",
"REMOTE_GATEWAY_ENDPOINT_UNAVAILABLE": "Cindy AI 자격 증명이 아직 준비되지 않았습니다(로그인 후 자동 발급됩니다). 잠시 후 다시 시도해 주세요. 계속되면 설정 → 모델 제공자에서 Cindy AI 연결 상태를 확인하세요.",
"DEVICE_LINK_CONTROL_DISABLED": "이 기기의 제어가 꺼져 있어 메시지가 전송되지 않았습니다.",
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 9b636fe1e2..ca7c033611 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
@@ -6628,7 +6628,7 @@
"remoteError": {
"REMOTE_DAEMON_CLOSED": "远端连接已中断(daemon 可能正在升级或重启)。本轮已结束 — 请重新发送。",
"REMOTE_LOCAL_ATTACHMENT_UNSUPPORTED": "远端任务无法访问本地文件/图片附件。请直接粘贴内容。",
- "AUTO_REVIEW_UNAVAILABLE": "自动审批暂时不可用,需要审批的操作会被拒绝。想自己确认这些操作,可以把任务切到「默认权限」。",
+ "AUTO_REVIEW_UNAVAILABLE": "自动审批暂时无法给出判断(网络或服务波动),需要审批的操作已转由你来确认。想少被打断,可以把任务切到「默认权限」自行掌控。",
"REMOTE_COMPAT_MODE_UNSUPPORTED": "远端 Claude Code 会话无法通过本地兼容 Proxy 路由(内部错误,请反馈)。",
"REMOTE_GATEWAY_ENDPOINT_UNAVAILABLE": "Cindy AI 凭据尚未就绪(登录后由服务端自动下发)。请稍候重试;若持续出现,请到 设置 → 模型供应商 检查 Cindy AI 连接状态。",
"DEVICE_LINK_CONTROL_DISABLED": "已关闭对该设备的控制,消息未发送。",
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 009b08ace4..e58cdafc30 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
@@ -6631,7 +6631,7 @@
"remoteError": {
"REMOTE_DAEMON_CLOSED": "遠端連線已中斷(daemon 可能正在升級或重啟)。本輪已結束 — 請重新傳送。",
"REMOTE_LOCAL_ATTACHMENT_UNSUPPORTED": "遠端任務無法訪問本地檔案/圖片附件。請直接貼上內容。",
- "AUTO_REVIEW_UNAVAILABLE": "自動審批暫時不可用,需要審批的操作會被拒絕。想自己確認這些操作,可以把任務切到「預設權限」。",
+ "AUTO_REVIEW_UNAVAILABLE": "自動審批暫時無法給出判斷(網路或服務波動),需要審批的操作已轉由你來確認。想少被打斷,可以把任務切到「預設權限」自行掌控。",
"REMOTE_COMPAT_MODE_UNSUPPORTED": "遠端 Claude Code 會話無法透過本地相容 Proxy 路由(內部錯誤,請反饋)。",
"REMOTE_GATEWAY_ENDPOINT_UNAVAILABLE": "Cindy AI 憑據尚未就緒(登入後由服務端自動下發)。請稍候重試;若持續出現,請到 設定 → 模型供應商 檢查 Cindy AI 連線狀態。",
"DEVICE_LINK_CONTROL_DISABLED": "已關閉對該裝置的控制,訊息未傳送。",
diff --git a/docs/product-rules/telegram-bot-parity.md b/docs/product-rules/telegram-bot-parity.md
index 0f33930957..1bbd5ff224 100644
--- a/docs/product-rules/telegram-bot-parity.md
+++ b/docs/product-rules/telegram-bot-parity.md
@@ -146,6 +146,7 @@ Cindy 有两个 Telegram bot,用户看到的是同一个产品:
| 2e | **私聊里能不能跨群检索:个人有、官方没有** | **群轮次两侧一致**(都 lane-only,只查当前群/topic)。差别只在私聊。个人:`groupHistoryAccessFor` 在无 lane(即 DM)时给 `access: 'owner'`,owner 可以显式指定别的 lane,跨群查这个 bot 名下全部群历史。官方:私聊的 externalKey 不是群 lane,`groupHistoryAccessForExternalKey` 返回 `undefined`,MCP 直接以 `NO_ACTIVE_TELEGRAM_SCOPE` 拒绝——**官方 bot 私聊里这个工具根本不可用**(MCP 工具自己的说明也写着「只有主人触发的个人 Telegram 轮次可显式指定其它精确 lane」)。个人侧「群轮次一律 lane-only」有 2026-07-30 的明确裁决(群里的可控文本能借 owner 轮次把别的 lane 检索出来回帖泄漏,而检索类调用没有确认卡兜底);**官方私聊这一档没有对应裁决**——是没接,不是判过,所以归缺口不归第三节 | 待判,**不在本 PR 改代码**。补之前先答一个产品问题:官方 bot 绑的是一个主账号,它的私聊该不该看到该账号名下全部群的历史。答「该」才是接线问题(DM 的 externalKey 里有 principal,能推出 `telegram:<principalId>` 的 owner 档);答「不该」就把这行升进第三节当有意差异 |
| 2f | **群里开了「全响应」后,一轮失败:个人 bot 会往群里吐错误,官方静默** | 全响应(`always`)本身两侧行为一致:未被召唤的消息也进 turn 并打 ambient 标、**不 typing、不表情**、模型可用 NO_REPLY 闭嘴、纯媒体/无正文消息不进(个人 `if (!plain) return`,官方 `plain.length > 0`);连 ambient 提示词都逐字相同(各写一份,跨仓无校验)。**分歧只在这一轮失败的时候**:官方不发失败通知(`controller.ts` 的 `finalFailureNoticeSent !== true && !entry.ambient`),并把过程消息删掉、记一句「completed silently」;个人侧的 `im/shared/turnRunner.ts` **完全不认识 ambient**(全文没有这个词),错误一律走 `❌ 错误:…`——惰性占位这时会被真建出来,于是群里凭空多一条错误消息,而这一轮本来连话都不打算说。第二节的生命周期表已按「普通轮次 / ambient 轮次」拆成两行,别再写回一条无条件的失败收口结论 | 待判,**不在本 PR 改代码**。倾向跟官方一致做静默(与「ambient 不打扰群」的既有取舍同一个方向),但要保证错误不因此彻底消失——至少落桌面端日志与该会话,不能只是吞掉 |
| 2g | **交互卡挂太久:官方 30 分钟自动收口,个人一直等** | 三类卡(`ask_user_question` / `plan_review` / 权限)在两侧走的是同一个注册入口,差别只在**有没有定时器**。官方:`hook-control/interactions.ts` 的 `registerHookInteraction` 给每张卡挂一个 `HOOK_INTERACTION_TIMEOUT_MS = 30min`,到点取共享模型的安全默认(ask 空答 / plan deny + dismissed / permission deny)resolve,并回调 `onFallback` → `session-runner.ts` 的 `sendCancel(requestId, reason)` 把卡片收掉。个人:`im/shared/pendingInteractions.ts` **没有任何定时器**,只能靠按钮决策(`resolvePending`),或 turn 收口 / session 清理 / 抢跑时的 `dropInteractionCard` → `cancelPending`(安全默认与官方同源,并把卡片改成「卡片已过期」)。**而这一轮正卡在 `await` 这张卡上,它不会自己结束**;maker-core 的 turn stall 看门狗又明确把「等用户回应交互」排除在静默之外,也不会来救。结果:**个人 bot 的卡片会一直挂着,第二天点还能点,agent 也还在等** | 待判,**不在本 PR 改代码**。先答一个产品问题:个人 bot 的卡片挂着不动算不算问题——它是用户自己的 bot,晚点回来再点也说得通;官方 bot 经服务端中继,挂着的交互会长期占住 lane,动机不一样。补的话要连「超时后卡片显示什么」一起定。**顺带**:官方那个 30 分钟的注释理由(「必须短于整 turn 硬超时 60min」)已过期——那条硬超时 2026-08-01 撤了,定时器本身仍在生效,注释已随本 PR 改正 |
+| 2h | **自动审批故障降级后,个人 bot 有确认入口、官方待核** | 审阅器故障(网络/服务波动,**不是**模型判定该问)时,Cindy 兜底裁决从静默 `block` 改为 `ask` 交回用户决定。个人 bot 的 Telegram / 微信 / 钉钉群轮次即使带 `turnPermissionPolicy` 也会**真正弹确认卡**(`agents/pi/index.ts` 的 `askNeedsUserDecision`),并附一条会话级提示(`im/shared/turnRetryNotice.ts`)说明原因与「切默认权限」的出路。**模型判定的 `ask` 仍按既有渠道策略走**——带 policy 的群轮次不打扰 owner,这条没变;只有 `unavailable` 走例外。官方 bot 侧的等价路径(服务端 `session-runner` 是否把 unavailable 降级的 `ask` 送到用户面前、提示文案由谁渲染)**待核** | 待核。个人侧收口于 PR #2474;官方侧若仍静默拒绝,用户会看到「已转由你确认」却没有确认入口——与个人侧修复前是同一个矛盾 |
| 3 | **终稿必达只有官方有** | 官方侧终稿先落盘、失败重试到送达或有界放弃(`xindong/cindy-server#348`)。个人 bot 的 `streamingText.finalize` 是进程内尽力而为,桌面进程挂掉那条终稿就没了。**两侧的「有界」各有一条明确边界、且不在同一层**:官方路径经桌面账本 `hook-control/requestLedger.ts`,客户端侧的投递时效是 `HOOK_TERMINAL_DELIVERY_TTL_MS ≈ 24h`,**规则无条件**——过线的终稿一律不再发出,不论是谁在要。覆盖的出口:持久出箱 `listPending`、ACK 退避重发、离线内存缓冲、ACK 缓冲的两个消费分支(`onConnected` 入口一次性清扫,含能力降级回落),以及 **server 显式重投**——那一支只回放 `task.ack` 后返回,不发终稿、也不把记录改回 `pending`。(重投一度有过 `origin='server-request'` 豁免,后被删除:它在持久记录里没有位置,每条路径都要手工传播,连续三轮 review 各找出一条漏掉的。)server 侧只丢掉一份它自己也已放弃发布的终稿——服务端 `OUTBOX_MAX_ATTEMPTS × OUTBOX_MAX_DELAY_MS ≈ 24h` 的发布放弃线与客户端刻意取同一个数,而结果总比请求更晚,所以它索取一份过线结果时自身 outbox 早已过放弃点;X 侧入口还另有 `x-hook-server` 的 `onMention` 陈旧守卫。**个人 bot 不经过这个账本**,既没有落盘也没有这条时效,它的边界就是「进程活着就尽力,挂了就没了」 | 待判:个人侧是否需要等价保障,还是接受「桌面挂了本来就没人在跑」。**注意两侧要判的不是同一件事**:官方已定「超过 24h 的终稿不再主动补发」,个人待定的是「要不要先落盘」 |
| 4 | 受保护群内容的隐私边界 | 个人侧已做(出站回流 fail-closed,任一分片带保护标即整条不回流)。官方侧是否等价**待核** | 待核 |
| 5 | 相册失败逐张回落 | 两侧都有实现,判据是否等价**待核** | 待核 |
diff --git a/packages/maker-core/src/agents/claude-code/index.ts b/packages/maker-core/src/agents/claude-code/index.ts
index f7b315e8b1..1dec247916 100644
--- a/packages/maker-core/src/agents/claude-code/index.ts
+++ b/packages/maker-core/src/agents/claude-code/index.ts
@@ -1817,15 +1817,17 @@ export class ClaudeCodeAgent extends BaseAgent {
} else if (!turnPolicyForcePrompt && autoDecision.verdict === 'allow') {
return { behavior: 'allow', updatedInput: input };
} else if (!turnPolicyForcePrompt && autoDecision.verdict === 'block') {
- // 审阅器没跑起来 ≠ 模型判定危险:前者是基础设施故障,用户有权知道并接管,
- // 后者按 Auto 本意保持静默(只把 reason 喂给模型)。动作两种都仍然 deny。
- if (autoDecision.unavailable) autoReviewUnavailableNotice.notify();
+ // 模型判定动作有更安全的做法 —— 按 Auto 本意保持静默,只把 reason 喂给模型。
+ // (审阅器故障已在 resolveAutoReviewDecision 降级成 ask,不会走到这条分支。)
return {
behavior: 'deny',
message: autoDecision.reason ?? 'Cindy Auto Review blocked this action. Choose a safer alternative.',
};
} else {
// AI `ask` and deterministic red-line verdicts are never persisted.
+ // 审阅器故障降级来的 ask 额外发一条会话级提示:用户需要知道自己为什么
+ // 突然开始被问,否则 Auto 档看起来像坏了。
+ if (autoDecision.unavailable) autoReviewUnavailableNotice.notify();
forcePrompt = true;
}
} else {
@@ -2847,14 +2849,15 @@ export class ClaudeCodeAgent extends BaseAgent {
return { kind: 'permission', behavior: 'allow' };
}
if (!remoteTurnPolicyForcePrompt && autoDecision.verdict === 'block') {
- // 与本地分支同口径:审阅器故障要提示一次,模型判定保持静默。
- if (autoDecision.unavailable) autoReviewUnavailableNotice.notify();
+ // 与本地分支同口径:模型判定保持静默(审阅器故障已降级成 ask)。
return {
kind: 'permission',
behavior: 'deny',
reason: autoDecision.reason ?? 'Cindy Auto Review blocked this action. Choose a safer alternative.',
};
}
+ // 与本地分支同口径:故障降级来的 ask 提示一次,让用户知道为何开始被问。
+ if (autoDecision.unavailable) autoReviewUnavailableNotice.notify();
remoteForcePrompt = true;
} else {
if (remoteMcpPolicy === 'auto-approve' && !remoteTurnPolicyForcePrompt) {
diff --git a/packages/maker-core/src/agents/codex/index.ts b/packages/maker-core/src/agents/codex/index.ts
index 020a19342e..044d423f1f 100644
--- a/packages/maker-core/src/agents/codex/index.ts
+++ b/packages/maker-core/src/agents/codex/index.ts
@@ -5521,12 +5521,13 @@ export class CodexAgent extends BaseAgent {
} else if (decision.verdict === 'allow') {
return 'accept';
} else if (decision.verdict === 'block') {
- // 审阅器没跑起来 ≠ 模型判定危险:前者是基础设施故障,提示一次让用户能接管;
- // 后者按 Auto 本意保持静默。动作两种都仍然 decline。
- if (decision.unavailable) autoReviewUnavailableNotice.notify();
+ // 模型判定动作有更安全的做法 —— 按 Auto 本意保持静默。
+ // (审阅器故障已在 resolveAutoReviewDecision 降级成 ask,不会走到这里。)
return 'decline';
} else {
// Only red-line decisions reach the user and they cannot be remembered.
+ // 审阅器故障降级来的 ask 提示一次,让用户知道为何突然开始被问。
+ if (decision.unavailable) autoReviewUnavailableNotice.notify();
forcePrompt = true;
}
}
diff --git a/packages/maker-core/src/agents/index.ts b/packages/maker-core/src/agents/index.ts
index 86c492d038..0171a82d32 100644
--- a/packages/maker-core/src/agents/index.ts
+++ b/packages/maker-core/src/agents/index.ts
@@ -66,8 +66,14 @@ export {
export { isNetworkishErrorMessage } from './shared/network-error.js';
export {
AUTO_REVIEW_UNAVAILABLE_CODE,
+ AUTO_REVIEW_MAX_REQUEST_TIMEOUT_MS,
+ AUTO_REVIEW_RETRY_ATTEMPTS,
+ AUTO_REVIEW_RETRY_BACKOFF_MS,
+ AUTO_REVIEW_RETRY_SCHEDULING_SLACK_MS,
+ autoReviewRetryBudgetMs,
DEFAULT_AUTO_REVIEW_TIMEOUT_POLICY,
getAutoReviewActionTextLength,
+ getAutoReviewDelegateHardCeilingMs,
isAutoReviewUnavailableNotice,
MAX_AUTO_REVIEW_ACTION_TEXT_CHARS,
type AutoReviewDecision,
diff --git a/packages/maker-core/src/agents/pi/__tests__/pi-auto-review-dispatch.test.ts b/packages/maker-core/src/agents/pi/__tests__/pi-auto-review-dispatch.test.ts
index 77621d882b..e3af4da47f 100644
--- a/packages/maker-core/src/agents/pi/__tests__/pi-auto-review-dispatch.test.ts
+++ b/packages/maker-core/src/agents/pi/__tests__/pi-auto-review-dispatch.test.ts
@@ -1087,7 +1087,10 @@ describe('pi auto-review dispatch & spawn config (mocked pi process)', () => {
expect(captured.sent).toContainEqual({ type: 'extension_ui_response', id: 'r4', confirmed: true });
});
- it('auto mode silently blocks gray actions when the current-model reviewer is unavailable', async () => {
+ // 审阅器不可用时降级为「问用户」,不再静默拒绝:宿主侧已重试过,走到这里
+ // 说明确实没救回来。静默否掉一批正常的灰区操作会让 Auto 档看起来像坏了,
+ // 而用户既看不到原因也无法接管。降级后安全边界不变(未点头仍不执行)。
+ it('auto mode hands gray actions to the user when the current-model reviewer is unavailable', async () => {
const handle = await start('auto');
let resolverCalls = 0;
handle.setInteractionResolver?.(async () => {
@@ -1096,8 +1099,8 @@ describe('pi auto-review dispatch & spawn config (mocked pi process)', () => {
});
firePermissionRequest('r7', 'write', { path: '/tmp/outside.txt' });
await flush();
- expect(resolverCalls).toBe(0);
- expect(captured.sent).toContainEqual({ type: 'extension_ui_response', id: 'r7', confirmed: false });
+ expect(resolverCalls).toBe(1);
+ expect(captured.sent).toContainEqual({ type: 'extension_ui_response', id: 'r7', confirmed: true });
});
it('ask mode still prompts for in-workspace writes (auto shortcut is auto-only)', async () => {
diff --git a/packages/maker-core/src/agents/pi/index.ts b/packages/maker-core/src/agents/pi/index.ts
index 4d103ecd3a..a64b269c61 100644
--- a/packages/maker-core/src/agents/pi/index.ts
+++ b/packages/maker-core/src/agents/pi/index.ts
@@ -2805,26 +2805,33 @@ export class PiAgent extends BaseAgent {
return;
}
if (decision.verdict === 'ask') {
+ // 审阅器故障降级来的 ask 提示一次:用户需要知道自己为何突然开始被问,
+ // 否则 Auto 档看起来像坏了。模型判定的 ask 不提示(那是正常工作)。
+ if (decision.unavailable) notifyAutoReviewUnavailable();
// policy turn + auto 的灰区语义对齐 Codex:只有渠道 policy 明确命中的调用
// 才打扰 owner;普通 Auto-Review ask 直接 fail-closed,不再额外弹微信确认。
// 无 policy 的 Desktop auto 会话维持既有逐次确认行为。
+ //
+ // **故障降级(unavailable)例外**:上面刚告诉用户"已转由你确认",若这里仍按
+ // policy 静默拒绝,提示与行为就自相矛盾 —— 用户看到可接管的说明却没有确认
+ // 入口,操作照样被拒(PR #2474 review)。故障不是"模型判定该问",而是基础
+ // 设施失灵,用户有权亲自决定,所以走真实确认。
+ const askNeedsUserDecision = decision.unavailable || !turnPermissionPolicy;
proc.send({
type: 'extension_ui_response',
id,
- confirmed: turnPermissionPolicy
- ? false
- : await requestUserConfirmation({ forcePrompt: true }),
+ confirmed: askNeedsUserDecision
+ ? await requestUserConfirmation({ forcePrompt: true })
+ : false,
});
return;
}
if (decision.verdict === 'block') {
- // 审阅器没跑起来 ≠ 模型判定危险:前者是基础设施故障,提示一次让用户能接管;
- // 后者按 Auto 本意保持静默。动作两种都仍然 confirmed:false。
- if (decision.unavailable) notifyAutoReviewUnavailable();
+ // 模型判定动作有更安全的做法 —— 按 Auto 本意保持静默。
+ // (审阅器故障已在 resolveAutoReviewDecision 降级成 ask,不会走到这里。)
this.deps.logger.debug('pi auto-review blocked tool call', {
toolName,
reason: decision.reason,
- unavailable: decision.unavailable === true,
});
}
proc.send({
diff --git a/packages/maker-core/src/agents/shared/auto-review-decision.test.ts b/packages/maker-core/src/agents/shared/auto-review-decision.test.ts
index 85ff01a9aa..d2482a46fe 100644
--- a/packages/maker-core/src/agents/shared/auto-review-decision.test.ts
+++ b/packages/maker-core/src/agents/shared/auto-review-decision.test.ts
@@ -2,6 +2,11 @@ import { afterEach, describe, expect, it, vi } from 'vitest';
import {
AUTO_REVIEW_UNAVAILABLE_CODE,
+ AUTO_REVIEW_MAX_REQUEST_TIMEOUT_MS,
+ AUTO_REVIEW_RETRY_ATTEMPTS,
+ AUTO_REVIEW_RETRY_BACKOFF_MS,
+ autoReviewRetryBudgetMs,
+ getAutoReviewDelegateHardCeilingMs,
DEFAULT_AUTO_REVIEW_TIMEOUT_POLICY,
classifyLocalAutoReviewTier,
isAutoReviewUnavailableNotice,
@@ -151,29 +156,33 @@ describe('resolveAutoReviewDecision', () => {
expect(called).toBe(false);
});
- it('silently blocks when the reviewer is absent, throws, or returns invalid output', async () => {
+ // 审阅器故障降级为 ask 而不是静默 block:宿主侧已先重试过,走到这里说明确实
+ // 没救回来。此时静默拒绝最差 —— 用户看不到发生了什么,一批正常的灰区操作被
+ // 连续否掉,Auto 档表现得像坏了。交给用户确认,安全边界不降低。
+ it('hands over to the user when the reviewer is absent, throws, or returns invalid output', async () => {
const gray = request({ kind: 'exec', command: 'npx tsc --noEmit' });
- await expect(resolveAutoReviewDecision(gray, undefined)).resolves.toMatchObject({ verdict: 'block' });
+ await expect(resolveAutoReviewDecision(gray, undefined)).resolves.toMatchObject({ verdict: 'ask' });
await expect(resolveAutoReviewDecision(gray, async () => {
throw new Error('offline');
- })).resolves.toMatchObject({ verdict: 'block' });
+ })).resolves.toMatchObject({ verdict: 'ask' });
await expect(resolveAutoReviewDecision(
gray,
async () => ({ verdict: 'unknown' } as never),
- )).resolves.toMatchObject({ verdict: 'block' });
+ )).resolves.toMatchObject({ verdict: 'ask' });
});
- it('silently blocks when the reviewer never settles', async () => {
+ it('hands over to the user when the reviewer never settles', async () => {
vi.useFakeTimers();
const pending = resolveAutoReviewDecision(
request({ kind: 'exec', command: 'npx tsc --noEmit' }),
async () => new Promise<never>(() => {}),
);
- await vi.advanceTimersByTimeAsync(DEFAULT_AUTO_REVIEW_TIMEOUT_POLICY.delegateTimeoutMs);
+ // 守卫上界要容得下宿主侧最慢一档 + 全部重试与退避;按常量推进,避免参数变化时失配。
+ await vi.advanceTimersByTimeAsync(getAutoReviewDelegateHardCeilingMs() + 1_000);
await expect(pending).resolves.toMatchObject({
- verdict: 'block',
+ verdict: 'ask',
reason: expect.stringContaining('could not complete'),
});
});
@@ -187,7 +196,7 @@ describe('resolveAutoReviewDecision', () => {
it('flags a missing reviewer as unavailable', async () => {
await expect(resolveAutoReviewDecision(gray, undefined)).resolves.toMatchObject({
- verdict: 'block',
+ verdict: 'ask',
unavailable: true,
});
});
@@ -195,21 +204,22 @@ describe('resolveAutoReviewDecision', () => {
it('flags a throwing reviewer as unavailable', async () => {
await expect(resolveAutoReviewDecision(gray, async () => {
throw new Error('offline');
- })).resolves.toMatchObject({ verdict: 'block', unavailable: true });
+ })).resolves.toMatchObject({ verdict: 'ask', unavailable: true });
});
it('flags invalid reviewer output as unavailable', async () => {
await expect(resolveAutoReviewDecision(
gray,
async () => ({ verdict: 'unknown' } as never),
- )).resolves.toMatchObject({ verdict: 'block', unavailable: true });
+ )).resolves.toMatchObject({ verdict: 'ask', unavailable: true });
});
it('flags a reviewer timeout as unavailable', async () => {
vi.useFakeTimers();
const pending = resolveAutoReviewDecision(gray, async () => new Promise<never>(() => {}));
- await vi.advanceTimersByTimeAsync(DEFAULT_AUTO_REVIEW_TIMEOUT_POLICY.delegateTimeoutMs);
- await expect(pending).resolves.toMatchObject({ verdict: 'block', unavailable: true });
+ // 按守卫的实际上界推进 —— 它由重试参数推出,写死数字会在参数变化时静默失配。
+ await vi.advanceTimersByTimeAsync(getAutoReviewDelegateHardCeilingMs() + 1_000);
+ await expect(pending).resolves.toMatchObject({ verdict: 'ask', unavailable: true });
});
it('allows a valid delegate response after eight seconds but before the shared outer deadline', async () => {
@@ -296,7 +306,7 @@ describe('createAutoReviewUnavailableNotice', () => {
expect(emitted).toHaveLength(1);
expect(emitted[0]).toContain(`[${AUTO_REVIEW_UNAVAILABLE_CODE}]`);
// 兜底英文必须跟在 code 后面:未落地 i18n 的宿主(远端 / IM)直接显示它。
- expect(emitted[0]).toContain('Auto-review is temporarily unavailable');
+ expect(emitted[0]).toContain('Auto-review could not reach a decision');
notice.reset();
notice.notify();
@@ -372,3 +382,32 @@ describe('composeAutoReviewIntentWithClarification', () => {
expect(long.length).toBeLessThanOrEqual(2_000);
});
});
+
+describe('重试预算', () => {
+ it('总预算含每次超时与全部退避', () => {
+ // 3 次 × 12s + (100 + 200)ms 退避。
+ expect(autoReviewRetryBudgetMs(12_000, 3)).toBe(36_300);
+ // 次数减少时只算实际发生的退避。
+ expect(autoReviewRetryBudgetMs(12_000, 2)).toBe(24_100);
+ expect(autoReviewRetryBudgetMs(12_000, 1)).toBe(12_000);
+ });
+
+ it('核心守卫容得下最宽一档的全部重试(否则宽裕额度形同虚设)', () => {
+ // 回归 PR #2474 review:固定 35s 盖不住 30s 档 × 3 次 + 退避(=90.3s),
+ // 第二次尝试约 5s 就被外层守卫丢弃,且请求未取消、继续消耗额度。
+ const needed = autoReviewRetryBudgetMs(
+ AUTO_REVIEW_MAX_REQUEST_TIMEOUT_MS,
+ AUTO_REVIEW_RETRY_ATTEMPTS,
+ );
+ expect(DEFAULT_AUTO_REVIEW_TIMEOUT_POLICY.delegateTimeoutMs).toBeLessThan(needed);
+ // 守卫本身由同一算法推出,不再是写死的常量 —— 改重试次数/退避会自动跟随。
+ expect(getAutoReviewDelegateHardCeilingMs()).toBeGreaterThanOrEqual(needed);
+ });
+
+ it('退避表长度与声明的重试次数自洽', () => {
+ // 退避发生在每次重试之前,所以需要 attempts - 1 个。少了会让后面的重试没有退避。
+ expect(AUTO_REVIEW_RETRY_BACKOFF_MS.length).toBeGreaterThanOrEqual(
+ AUTO_REVIEW_RETRY_ATTEMPTS - 1,
+ );
+ });
+});
diff --git a/packages/maker-core/src/agents/shared/auto-review-decision.ts b/packages/maker-core/src/agents/shared/auto-review-decision.ts
index fbadb0ddcb..5620e635a3 100644
--- a/packages/maker-core/src/agents/shared/auto-review-decision.ts
+++ b/packages/maker-core/src/agents/shared/auto-review-decision.ts
@@ -43,8 +43,9 @@ export const AUTO_REVIEW_UNAVAILABLE_CODE = 'AUTO_REVIEW_UNAVAILABLE';
* apps/desktop/src/main/im/shared/turnRetryNotice.ts。
*/
const AUTO_REVIEW_UNAVAILABLE_FALLBACK_TEXT =
- 'Auto-review is temporarily unavailable, so actions that need review are being denied. '
- + 'Switch this task to Default permissions if you want to approve them yourself.';
+ 'Auto-review could not reach a decision (network or service hiccup), so actions that '
+ + 'need review are being handed to you to confirm. Switch this task to Default '
+ + 'permissions if you would rather not be interrupted.';
/**
* 判定一条 AgentEvent 的 error message 是否就是「自动审批不可用」提示。
@@ -105,19 +106,78 @@ export type AutoReviewDelegate = (
export const MAX_AUTO_REVIEW_ACTION_TEXT_CHARS = 4_096;
const MAX_AUTO_REVIEW_REASON_CHARS = 240;
/**
- * Auto-review is deliberately bounded: a reviewer outage must still deny a
- * gray action. Keep the host request deadline below the core guard so a valid
- * answer at the request deadline can return before the outer guard fires.
+ * Auto-review is deliberately bounded: a reviewer outage must still resolve the
+ * gray action instead of hanging the tool callback. Keep the host request
+ * deadline below the core guard so a valid answer at the request deadline can
+ * return before the outer guard fires.
+ *
+ * **两个数必须一起改。** delegate 侧现在会做重试(见 desktop 的
+ * createAutoPermissionReviewer),而重试全部发生在 `delegateTimeoutMs` 之内 ——
+ * 外层守卫若先触发,重试就完全失去意义(白等、白花钱,结果照样是不可用)。
+ * 上限取「宿主侧最慢的一档 × 重试次数 + 退避」再留余量。
*/
export interface AutoReviewTimeoutPolicy {
requestTimeoutMs: number;
delegateTimeoutMs: number;
}
+/**
+ * 紧凑档(能关思考的模型)的默认策略。宿主侧每次尝试都用完整的
+ * `requestTimeoutMs`(不按次数切分 —— 切分会把本来能成功的慢响应也判成超时),
+ * 总耗时由 AUTO_REVIEW_DELEGATE_HARD_CEILING_MS 兜住。
+ */
export const DEFAULT_AUTO_REVIEW_TIMEOUT_POLICY: Readonly<AutoReviewTimeoutPolicy> = Object.freeze({
requestTimeoutMs: 12_000,
delegateTimeoutMs: 13_000,
});
+
+/** 宿主侧的重试次数与退避。核心侧据此推总预算,两边必须同源,否则守卫会截断重试。 */
+export const AUTO_REVIEW_RETRY_ATTEMPTS = 3;
+export const AUTO_REVIEW_RETRY_BACKOFF_MS: readonly number[] = Object.freeze([100, 200]);
+
+/** 宿主侧单次请求的最宽一档(强制思考模型),核心侧守卫按它推上界。 */
+export const AUTO_REVIEW_MAX_REQUEST_TIMEOUT_MS = 30_000;
+
+/**
+ * 调度余量:prompt 构造、`setTimeout` 抖动、事件循环排队都计入总耗时但不属于任何
+ * 一次请求。宿主的时间兜底与核心守卫都要加上它 —— 不留余量等于要求这些开销恰好
+ * 为零,真机上必然差那么几毫秒,于是最后一次重试恒定被自己的护栏挡掉
+ * (PR #2474 review 两轮都指向这一点)。
+ */
+export const AUTO_REVIEW_RETRY_SCHEDULING_SLACK_MS = 2_000;
+
+/**
+ * 一轮审阅(含全部重试与退避)的总预算。
+ *
+ * 宿主用它决定"还够不够再跑一次",核心用它推外层守卫的上界 —— **必须同一个算法**,
+ * 否则守卫会在重试跑完前触发,宽裕额度形同虚设(PR #2474 review:固定 35s 盖不住
+ * 30s 档的三次尝试,第二次约 5s 就被丢弃且请求未取消、继续消耗额度)。
+ */
+export function autoReviewRetryBudgetMs(
+ requestTimeoutMs: number,
+ attempts: number = AUTO_REVIEW_RETRY_ATTEMPTS,
+): number {
+ const backoffTotal = AUTO_REVIEW_RETRY_BACKOFF_MS
+ .slice(0, Math.max(0, attempts - 1))
+ .reduce((sum, ms) => sum + ms, 0);
+ return requestTimeoutMs * attempts + backoffTotal;
+}
+
+/**
+ * 核心侧守卫的绝对上界:按最宽一档 + 全部重试与退避推出,再加**两份**调度余量 ——
+ * 一份对应宿主时间兜底自己放宽的那份,另一份留给守卫与兜底之间的竞态。
+ * 守卫必须严格晚于宿主的兜底触发,否则宿主刚放宽的余量会被守卫吃掉。
+ *
+ * 这是**兜底**不是常态:绝大多数请求 2s 内返回(实测 p95 ≈ 2.5s)。
+ */
+const AUTO_REVIEW_DELEGATE_HARD_CEILING_MS =
+ autoReviewRetryBudgetMs(AUTO_REVIEW_MAX_REQUEST_TIMEOUT_MS)
+ + AUTO_REVIEW_RETRY_SCHEDULING_SLACK_MS * 2;
+
+/** 暴露给测试:守卫必须容得下最宽一档的全部重试,常量漂移时要红。 */
+export function getAutoReviewDelegateHardCeilingMs(): number {
+ return AUTO_REVIEW_DELEGATE_HARD_CEILING_MS;
+}
const AUTO_REVIEW_TIMEOUT = Symbol('auto-review-timeout');
export function getAutoReviewActionTextLength(action: ReviewableAction): number {
@@ -184,8 +244,16 @@ function oversizedReviewEvidence(action: ReviewableAction): string | null {
/**
* 原生 reviewer 不可用时的统一裁决入口:明显安全和明显红线仍由本地规则确定,
- * 只有中间灰区才调用当前会话模型。delegate 缺失、超时、抛错或返回非法结果时
- * 灰区一律 `block`,不会退化成逐条弹窗。
+ * 只有中间灰区才调用当前会话模型。
+ *
+ * **审阅器故障时降级为 `ask`,不再静默 `block`。** 宿主侧已先做过重试
+ * (见 desktop 的 createAutoPermissionReviewer),走到这里意味着重试也没救回来。
+ * 此时静默拒绝是最差的选择:用户既看不到发生了什么,一批本来完全正常的灰区操作
+ * 又被连续否掉,Auto 档表现得像坏了。降级成 `ask` 把决定权交回用户 ——
+ * 安全边界不降低(未经用户点头仍然不会执行),但用户至少知道该点头还是拒绝。
+ *
+ * 与「模型判定危险」的 `block` 仍然严格区分:那个继续静默,因为 Auto 的本意
+ * 就是不打扰;只有 `unavailable` 才升级成打扰。
*/
export async function resolveAutoReviewDecision(
request: AutoReviewRequest,
@@ -214,8 +282,8 @@ export async function resolveAutoReviewDecision(
}
if (!delegate) {
return {
- verdict: 'block',
- reason: 'Automatic review is unavailable. Choose a safer, workspace-scoped alternative.',
+ verdict: 'ask',
+ reason: 'Automatic review is unavailable, so this action needs your confirmation.',
unavailable: true,
};
}
@@ -224,9 +292,12 @@ export async function resolveAutoReviewDecision(
const decision = await Promise.race([
delegate(request),
new Promise<typeof AUTO_REVIEW_TIMEOUT>((resolve) => {
+ // 用硬上界而非紧凑档的 delegateTimeoutMs:宿主侧对强制思考的模型会放宽
+ // 单次超时并叠加重试,守卫必须容得下最慢的那一档,否则重试与放宽额度
+ // 都会被这里提前切断。
timeout = setTimeout(
() => resolve(AUTO_REVIEW_TIMEOUT),
- DEFAULT_AUTO_REVIEW_TIMEOUT_POLICY.delegateTimeoutMs,
+ AUTO_REVIEW_DELEGATE_HARD_CEILING_MS,
);
}),
]);
@@ -249,15 +320,15 @@ export async function resolveAutoReviewDecision(
};
}
} catch {
- // Reviewer outages must not turn Auto into Ask or hold the tool callback open.
+ // 审阅器故障不得吊住 tool callback;下面统一降级收口。
} finally {
if (timeout) clearTimeout(timeout);
}
- // 走到这里 = delegate 存在但没给出可用结果(超时 / 抛错 / 返回非法)。与「模型判定危险」
- // 不同,这是审阅器本身没跑起来,必须让上层能区分出来。
+ // 走到这里 = delegate 存在但没给出可用结果(重试后仍超时 / 抛错 / 返回非法)。
+ // 与「模型判定危险」不同,这是审阅器本身没跑起来 —— 交给用户确认,而不是替他拒绝。
return {
- verdict: 'block',
- reason: 'Automatic review could not complete. Choose a safer, workspace-scoped alternative.',
+ verdict: 'ask',
+ reason: 'Automatic review could not complete, so this action needs your confirmation.',
unavailable: true,
};
}