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(scheduler): 无人值守拒绝计划审批后,run 结果里说明原因

Zhang Yunjinc4412b79e6c1
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/interactionRouter.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/interactionRouter.test.ts
index 752f95fc99..443e4d4260 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/interactionRouter.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/interactionRouter.test.ts
@@ -11,6 +11,7 @@ import {
type InteractionHandler,
} from '../interactionRouter';
import { beginUnattendedTurn } from '../../mcp-integrations/unattendedTurn';
+import { takeUnattendedPlanReviewDeclines } from '../../mcp-integrations/unattendedTurn';
function permission(requestId: string): InteractionRequest {
return {
@@ -62,6 +63,9 @@ describe('session interaction router', () => {
)).resolves.toEqual({
kind: 'plan_review', behavior: 'deny', dismissed: true, reason: 'unattended_scheduled_run',
});
+ // 拒绝要能被 run 结果引用,否则 plan 模式的定时任务看起来就像“什么也没做”。
+ expect(takeUnattendedPlanReviewDeclines(host.session.id)).toBe(1);
+ expect(takeUnattendedPlanReviewDeclines(host.session.id)).toBe(0);
expect(desktop).not.toHaveBeenCalled();
// Permissions keep their own card and timeout semantics.
await expect(requestHostInteraction(host.session, permission('perm-1'), new AbortController().signal))
diff --git a/apps/desktop/src/main/maker-ipc/interactionRouter.ts b/apps/desktop/src/main/maker-ipc/interactionRouter.ts
index 225a878268..0beae3b1d4 100644
--- a/apps/desktop/src/main/maker-ipc/interactionRouter.ts
+++ b/apps/desktop/src/main/maker-ipc/interactionRouter.ts
@@ -14,7 +14,10 @@ import type {
TurnPermissionOrigin,
} from '@cindy/maker-core';
import { createSharedPermission, type SharedPermission } from './sharedPermission';
-import { isUnattendedTurn } from '../mcp-integrations/unattendedTurn.js';
+import {
+ isUnattendedTurn,
+ noteUnattendedPlanReviewDeclined,
+} from '../mcp-integrations/unattendedTurn.js';
export type TurnOrigin = TurnPermissionOrigin;
@@ -208,6 +211,9 @@ class SessionInteractionRouter {
return { kind: 'ask_user_question', answers: {}, dismissed: true };
}
if (request.kind === 'plan_review') {
+ // Deny, not allow: plan mode means "act only after the owner approves".
+ // The runner surfaces this in the run result so the empty run is legible.
+ noteUnattendedPlanReviewDeclined(this.session.id);
return { kind: 'plan_review', behavior: 'deny', dismissed: true, reason: 'unattended_scheduled_run' };
}
}
diff --git a/apps/desktop/src/main/mcp-integrations/__tests__/unattendedTurn.test.ts b/apps/desktop/src/main/mcp-integrations/__tests__/unattendedTurn.test.ts
index 290b7d165a..e7314b0a2c 100644
--- a/apps/desktop/src/main/mcp-integrations/__tests__/unattendedTurn.test.ts
+++ b/apps/desktop/src/main/mcp-integrations/__tests__/unattendedTurn.test.ts
@@ -1,6 +1,11 @@
import { describe, expect, it } from 'vitest';
-import { beginUnattendedTurn, isUnattendedTurn } from '../unattendedTurn';
+import {
+ beginUnattendedTurn,
+ isUnattendedTurn,
+ noteUnattendedPlanReviewDeclined,
+ takeUnattendedPlanReviewDeclines,
+} from '../unattendedTurn';
describe('unattended turn marker', () => {
it('is turn scoped, ref counted and idempotent on release', () => {
@@ -25,4 +30,19 @@ describe('unattended turn marker', () => {
}
expect(isUnattendedTurn('a')).toBe(false);
});
+
+ it('records declined plan reviews once per run and starts each turn clean', () => {
+ const first = beginUnattendedTurn('p');
+ noteUnattendedPlanReviewDeclined('p');
+ noteUnattendedPlanReviewDeclined('p');
+ expect(takeUnattendedPlanReviewDeclines('p')).toBe(2);
+ expect(takeUnattendedPlanReviewDeclines('p')).toBe(0);
+ first();
+
+ // 上一轮没收口的记录不能带进下一轮。
+ noteUnattendedPlanReviewDeclined('p');
+ const second = beginUnattendedTurn('p');
+ expect(takeUnattendedPlanReviewDeclines('p')).toBe(0);
+ second();
+ });
});
diff --git a/apps/desktop/src/main/mcp-integrations/unattendedTurn.ts b/apps/desktop/src/main/mcp-integrations/unattendedTurn.ts
index ee9b53e1cc..8a141d5963 100644
--- a/apps/desktop/src/main/mcp-integrations/unattendedTurn.ts
+++ b/apps/desktop/src/main/mcp-integrations/unattendedTurn.ts
@@ -15,11 +15,20 @@
*/
const unattendedDepthBySession = new Map<string, number>();
+/**
+ * Plan reviews this turn had to decline because no one could approve them.
+ * Denying is right (plan mode means "act only after I approve"), but a run that
+ * silently produces a plan and executes nothing looks broken — the runner reads
+ * this once per run and says so in the run result.
+ */
+const declinedPlanReviewBySession = new Map<string, number>();
+
export function beginUnattendedTurn(sessionId: string): () => void {
- unattendedDepthBySession.set(
- sessionId,
- (unattendedDepthBySession.get(sessionId) ?? 0) + 1,
- );
+ const depth = (unattendedDepthBySession.get(sessionId) ?? 0) + 1;
+ unattendedDepthBySession.set(sessionId, depth);
+ // A turn starts with a clean record: an earlier fire that ended without
+ // finalizing must not leak its note into this run.
+ if (depth === 1) declinedPlanReviewBySession.delete(sessionId);
let released = false;
return () => {
if (released) return;
@@ -33,3 +42,17 @@ export function beginUnattendedTurn(sessionId: string): () => void {
export function isUnattendedTurn(sessionId: string): boolean {
return (unattendedDepthBySession.get(sessionId) ?? 0) > 0;
}
+
+export function noteUnattendedPlanReviewDeclined(sessionId: string): void {
+ declinedPlanReviewBySession.set(
+ sessionId,
+ (declinedPlanReviewBySession.get(sessionId) ?? 0) + 1,
+ );
+}
+
+/** Read-and-clear: the run reports the declines once, then the record is gone. */
+export function takeUnattendedPlanReviewDeclines(sessionId: string): number {
+ const count = declinedPlanReviewBySession.get(sessionId) ?? 0;
+ declinedPlanReviewBySession.delete(sessionId);
+ return count;
+}
diff --git a/apps/desktop/src/main/scheduler-host/__tests__/runnerQueuedDispatch.test.ts b/apps/desktop/src/main/scheduler-host/__tests__/runnerQueuedDispatch.test.ts
index d3e4e4c4ce..e4694786e5 100644
--- a/apps/desktop/src/main/scheduler-host/__tests__/runnerQueuedDispatch.test.ts
+++ b/apps/desktop/src/main/scheduler-host/__tests__/runnerQueuedDispatch.test.ts
@@ -120,6 +120,7 @@ import {
} from '../runner';
import { isHeadlessGhostSetupTurn } from '../../mcp-integrations/ghostSetupInteractionSurface';
import { isUnattendedTurn } from '../../mcp-integrations/unattendedTurn';
+import { noteUnattendedPlanReviewDeclined } from '../../mcp-integrations/unattendedTurn';
type SessionSendOptions = Parameters<Session['send']>[1];
type SessionStatus = Parameters<Parameters<Session['onStatusChange']>[0]>[0];
@@ -1008,6 +1009,29 @@ describe('MakerScheduleRunner queued dispatch (busy bound session)', () => {
},
);
+ it('reports a plan review it had to decline in the run result', async () => {
+ const harness = createSessionHarness(async () => ({ accepted: true }));
+ const queue = createQueueHarness({ busy: true });
+ const { runner } = createRunnerHarness(harness.session, queue.deps);
+
+ const fire = runner.fire(heartbeatSchedule(), createFireContext());
+ await vi.waitFor(() => expect(queue.enqueueCalls).toHaveLength(1));
+ await queue.accept();
+ await vi.waitFor(() => expect(harness.listenerCount()).toBe(1));
+ // 这轮在 plan 模式下被自动拒绝了一次计划审批。
+ noteUnattendedPlanReviewDeclined(SESSION_ID);
+ harness.emit({
+ type: 'text',
+ data: { text: 'plan: do the thing', isFinal: true },
+ source: 'claude-code',
+ });
+ harness.emit({ type: 'done', data: {}, source: 'claude-code' });
+
+ const result = await fire;
+ expect(result.resultText).toContain('plan: do the thing');
+ expect(result.resultText).toContain('[plan review declined]');
+ });
+
it('releases the unattended mark when the turn ends, not when the run finishing notifying', async () => {
const harness = createSessionHarness(async () => ({ accepted: true }));
const queue = createQueueHarness({ busy: true });
diff --git a/apps/desktop/src/main/scheduler-host/runner.ts b/apps/desktop/src/main/scheduler-host/runner.ts
index fb209ccabb..f5cbd1c054 100644
--- a/apps/desktop/src/main/scheduler-host/runner.ts
+++ b/apps/desktop/src/main/scheduler-host/runner.ts
@@ -118,7 +118,10 @@ import type { SchedulerDrizzleDb } from './storage';
import { backfillSessionMeta } from './runners/_shared';
import { buildSkipResultText, executePreRunHook, formatPreRunHookFailure } from './pre-run-hook';
import { beginHeadlessGhostSetupTurn } from '../mcp-integrations/ghostSetupInteractionSurface.js';
-import { beginUnattendedTurn } from '../mcp-integrations/unattendedTurn.js';
+import {
+ beginUnattendedTurn,
+ takeUnattendedPlanReviewDeclines,
+} from '../mcp-integrations/unattendedTurn.js';
import { terminalErrorText } from '../im/shared/turnRetryNotice.js';
import { isManagedScheduledTarget, restoreScheduledTarget } from './restore-target';
@@ -429,6 +432,13 @@ class RoutinePermissionMismatchError extends RoutineDispatchDeferredError {
*/
const PERSISTENT_PERMISSION_MISMATCH_FIRES = 3;
+/**
+ * Appended to the run result when a plan-mode fire had to decline its own plan
+ * review. Without it the run looks like it silently did nothing.
+ */
+const UNATTENDED_PLAN_REVIEW_DECLINED_NOTE =
+ '[plan review declined] This scheduled run is unattended, so its plan was not approved automatically and nothing was executed. The plan above is the result — approve it in the session to continue.';
+
/** An ordinary session was stopped before vendor dispatch; never retry it. */
class ScheduledDispatchStoppedError extends Error {}
@@ -3372,6 +3382,13 @@ export class MakerScheduleRunner implements ScheduleRunner {
assistantText: string,
finalTextMatchesStream: boolean,
): Promise<FireResult> {
+ const declinedPlanReviews = takeUnattendedPlanReviewDeclines(sessionId);
+ const streamedResultText = !runError && assistantText ? assistantText : undefined;
+ const resultText: string | undefined = runError
+ ? undefined
+ : declinedPlanReviews > 0
+ ? [streamedResultText?.trim(), UNATTENDED_PLAN_REVIEW_DECLINED_NOTE].filter(Boolean).join('\n\n')
+ : streamedResultText;
const finalRun: ScheduleRun = {
id: ctx.runId,
scheduleId: schedule.id,
@@ -3381,7 +3398,7 @@ export class MakerScheduleRunner implements ScheduleRunner {
status: runError ? 'failed' : 'success',
errorMsg: runError,
// 仅 success 时落库 — 失败 run 的部分输出意义不大,errorMsg 已经覆盖原因
- resultText: !runError && assistantText ? assistantText : undefined,
+ resultText,
};
// 静默 run:静默运行默认静默;若 agent 经 schedule_notify_current_run 主动上报,
// scheduler.isRunSilenced 会变回 false,这里照常通知。
@@ -3488,7 +3505,7 @@ export class MakerScheduleRunner implements ScheduleRunner {
}
if (runError) throw new Error(runError);
if (reportPersistFailed) throw new Error('Scheduled result could not be saved');
- return { sessionId, resultText: assistantText || undefined };
+ return { sessionId, resultText: resultText || undefined };
}
/**
@@ -3915,7 +3932,7 @@ function buildScheduledRunContextInstruction(
`firedAtUtc: ${new Date(ctx.firedAt).toISOString()}`,
`firedAtInScheduleTimezone: ${firedAtInScheduleTimezone}`,
'These timestamps identify when this run was triggered, not when a queued run started processing. Use the task instructions to determine the requested time range.',
- 'Unattended: nobody is watching this run. Do not call ask_user_question — decide with a stated default, finish the work, and list any open question in the final report.',
+ 'Unattended: nobody is watching this run. Do not call ask_user_question — decide with a stated default and list any open question in the final report. In plan mode the plan review cannot be approved automatically: put the plan in the final report and leave execution to the owner.',
...buildTeammateTurnAuthorityLine(schedule),
].join('\n');
}