Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(scheduler): 定时任务里的提问不再挂死整轮
Zhang Yunjin7d78aa0100b3
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/interactionRouter.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/interactionRouter.test.tsindex 9ad27f777f..752f95fc99 100644--- a/apps/desktop/src/main/maker-ipc/__tests__/interactionRouter.test.ts+++ b/apps/desktop/src/main/maker-ipc/__tests__/interactionRouter.test.ts@@ -10,6 +10,7 @@ import {noteInteractionRouteSteer,type InteractionHandler,} from '../interactionRouter';+import { beginUnattendedTurn } from '../../mcp-integrations/unattendedTurn';function permission(requestId: string): InteractionRequest {return {@@ -44,6 +45,33 @@ function makeSession() {}describe('session interaction router', () => {+ it('resolves questions and plan reviews for an unattended scheduled turn instead of opening a card', async () => {+ const host = makeSession();+ const desktop = vi.fn<InteractionHandler>(async (): Promise<InteractionDecision> => ({+ kind: 'permission', behavior: 'allow',+ }));+ installDesktopInteractionHandler(host.session, desktop);+ const release = beginUnattendedTurn(host.session.id);+ try {+ await expect(requestHostInteraction(host.session, ask('ask-1'), new AbortController().signal))+ .resolves.toEqual({ kind: 'ask_user_question', answers: {}, dismissed: true });+ await expect(requestHostInteraction(+ host.session,+ { kind: 'plan_review', requestId: 'plan-1', plan: 'do it' } as InteractionRequest,+ new AbortController().signal,+ )).resolves.toEqual({+ kind: 'plan_review', behavior: 'deny', dismissed: true, reason: 'unattended_scheduled_run',+ });+ expect(desktop).not.toHaveBeenCalled();+ // Permissions keep their own card and timeout semantics.+ await expect(requestHostInteraction(host.session, permission('perm-1'), new AbortController().signal))+ .resolves.toMatchObject({ kind: 'permission', behavior: 'allow' });+ expect(desktop).toHaveBeenCalledOnce();+ } finally {+ release();+ }+ });+it('routes Host download permissions through the active channel without replacing the listener', async () => {const host = makeSession();const desktop = vi.fn<InteractionHandler>((_request, shared) => shared!.result);diff --git a/apps/desktop/src/main/maker-ipc/interactionRouter.ts b/apps/desktop/src/main/maker-ipc/interactionRouter.tsindex 9d735c70bf..225a878268 100644--- a/apps/desktop/src/main/maker-ipc/interactionRouter.ts+++ b/apps/desktop/src/main/maker-ipc/interactionRouter.ts@@ -14,6 +14,7 @@ import type {TurnPermissionOrigin,} from '@cindy/maker-core';import { createSharedPermission, type SharedPermission } from './sharedPermission';+import { isUnattendedTurn } from '../mcp-integrations/unattendedTurn.js';export type TurnOrigin = TurnPermissionOrigin;@@ -199,6 +200,17 @@ class SessionInteractionRouter {if (this.pending.has(request.requestId)) {return safeDecision(request, 'duplicate_request_id');}+ // Scheduled fires have no one to answer. Resolve as a system dismissal+ // instead of opening a card nothing can resolve: ask/plan deliberately have+ // no timeout, so the run would otherwise hang until the 60min stall guard.+ if (isUnattendedTurn(this.session.id)) {+ if (request.kind === 'ask_user_question') {+ return { kind: 'ask_user_question', answers: {}, dismissed: true };+ }+ if (request.kind === 'plan_review') {+ return { kind: 'plan_review', behavior: 'deny', dismissed: true, reason: 'unattended_scheduled_run' };+ }+ }const active = this.activeRoute;if (request.kind === 'permission' && active?.route.sourceDescription) {diff --git a/apps/desktop/src/main/mcp-integrations/__tests__/unattendedTurn.test.ts b/apps/desktop/src/main/mcp-integrations/__tests__/unattendedTurn.test.tsnew file mode 100644index 0000000000..290b7d165a--- /dev/null+++ b/apps/desktop/src/main/mcp-integrations/__tests__/unattendedTurn.test.ts@@ -0,0 +1,28 @@+import { describe, expect, it } from 'vitest';++import { beginUnattendedTurn, isUnattendedTurn } from '../unattendedTurn';++describe('unattended turn marker', () => {+ it('is turn scoped, ref counted and idempotent on release', () => {+ expect(isUnattendedTurn('s')).toBe(false);+ const first = beginUnattendedTurn('s');+ const second = beginUnattendedTurn('s');+ expect(isUnattendedTurn('s')).toBe(true);+ first();+ expect(isUnattendedTurn('s')).toBe(true);+ second();+ expect(isUnattendedTurn('s')).toBe(false);+ first();+ expect(isUnattendedTurn('s')).toBe(false);+ });++ it('keeps sessions independent', () => {+ const release = beginUnattendedTurn('a');+ try {+ expect(isUnattendedTurn('b')).toBe(false);+ } finally {+ release();+ }+ expect(isUnattendedTurn('a')).toBe(false);+ });+});diff --git a/apps/desktop/src/main/mcp-integrations/unattendedTurn.ts b/apps/desktop/src/main/mcp-integrations/unattendedTurn.tsnew file mode 100644index 0000000000..ee9b53e1cc--- /dev/null+++ b/apps/desktop/src/main/mcp-integrations/unattendedTurn.ts@@ -0,0 +1,35 @@+/**+ * Marks one agent turn whose only requester is a timer.+ *+ * A scheduled fire has nobody in the loop, and the interaction layer is+ * deliberately unbounded for human decisions: ask_user_question / plan_review+ * cards get no timeout (see PERMISSION_INTERACTION_TIMEOUT_MS) and the session+ * turn watchdog suspends while `pendingInteractions > 0`. A question asked from+ * a scheduled turn therefore waits forever, and the only backstop left is the+ * 60min run-level stall guard, which kills the run and leaves the turn with no+ * final answer at all.+ *+ * Turn-scoped and ref-counted for the same reason as+ * beginHeadlessGhostSetupTurn: scheduler runs reuse live Desktop and teammate+ * sessions, and later user-driven turns must go back to interactive.+ */+const unattendedDepthBySession = new Map<string, number>();++export function beginUnattendedTurn(sessionId: string): () => void {+ unattendedDepthBySession.set(+ sessionId,+ (unattendedDepthBySession.get(sessionId) ?? 0) + 1,+ );+ let released = false;+ return () => {+ if (released) return;+ released = true;+ const next = (unattendedDepthBySession.get(sessionId) ?? 1) - 1;+ if (next > 0) unattendedDepthBySession.set(sessionId, next);+ else unattendedDepthBySession.delete(sessionId);+ };+}++export function isUnattendedTurn(sessionId: string): boolean {+ return (unattendedDepthBySession.get(sessionId) ?? 0) > 0;+}diff --git a/apps/desktop/src/main/scheduler-host/__tests__/runnerQueuedDispatch.test.ts b/apps/desktop/src/main/scheduler-host/__tests__/runnerQueuedDispatch.test.tsindex 9010f838c4..d3e4e4c4ce 100644--- a/apps/desktop/src/main/scheduler-host/__tests__/runnerQueuedDispatch.test.ts+++ b/apps/desktop/src/main/scheduler-host/__tests__/runnerQueuedDispatch.test.ts@@ -119,6 +119,7 @@ import {type SchedulerQueueDeps,} from '../runner';import { isHeadlessGhostSetupTurn } from '../../mcp-integrations/ghostSetupInteractionSurface';+import { isUnattendedTurn } from '../../mcp-integrations/unattendedTurn';type SessionSendOptions = Parameters<Session['send']>[1];type SessionStatus = Parameters<Parameters<Session['onStatusChange']>[0]>[0];@@ -947,6 +948,7 @@ describe('MakerScheduleRunner queued dispatch (busy bound session)', () => {expect(req.sessionId).toBe(SESSION_ID);expect(req.text).toContain('PR #971 heartbeat prompt');expect(req.text).toContain('[Scheduled run context]');+ expect(req.text).toContain('Unattended: nobody is watching this run. Do not call ask_user_question');expect(req.text).toContain('\nschedule: 「PR #971 心跳」(schedule_id: schedule-hb)\nfiredAtEpochMs: 1700000000100',);@@ -972,6 +974,7 @@ describe('MakerScheduleRunner queued dispatch (busy bound session)', () => {// 排队等待仍属于当前 Desktop turn,不能被未来的 scheduler turn// 提前标成 headless,否则当前 turn 的插件设置卡会被错误抑制。expect(isHeadlessGhostSetupTurn(SESSION_ID)).toBe(false);+ expect(isUnattendedTurn(SESSION_ID)).toBe(false);// drain 派发 → runner 挂 turn 监听 → done 收尾。await queue.accept();@@ -980,6 +983,8 @@ describe('MakerScheduleRunner queued dispatch (busy bound session)', () => {});await vi.waitFor(() => expect(harness.listenerCount()).toBe(1));expect(isHeadlessGhostSetupTurn(SESSION_ID)).toBe(true);+ // 无人值守标记与 headless 同时生效:本轮的任何提问都按系统收口处理。+ expect(isUnattendedTurn(SESSION_ID)).toBe(true);harness.emit({type: 'text',data: { text: 'heartbeat summary', isFinal: true },@@ -993,6 +998,7 @@ describe('MakerScheduleRunner queued dispatch (busy bound session)', () => {// listener 已摘干净,不泄漏。expect(harness.listenerCount()).toBe(0);expect(isHeadlessGhostSetupTurn(SESSION_ID)).toBe(false);+ expect(isUnattendedTurn(SESSION_ID)).toBe(false);expect(harness.setVendorOptions).toHaveBeenLastCalledWith({[SCHEDULER_RUN_ID_VENDOR_OPTION]: undefined,});@@ -1002,6 +1008,32 @@ describe('MakerScheduleRunner queued dispatch (busy bound session)', () => {},);+ 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 });+ const { runner, notifier } = createRunnerHarness(harness.session, queue.deps);+ let releaseNotify!: () => void;+ const notifyGate = new Promise<void>((resolve) => { releaseNotify = resolve; });+ notifier.notify.mockImplementation(async () => { await notifyGate; });++ 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));+ expect(isUnattendedTurn(SESSION_ID)).toBe(true);++ // turn 结束(done)后会话立刻可接用户下一条消息,而 run 还在等通知落地。+ harness.emit({ type: 'done', data: {}, source: 'claude-code' });+ await vi.waitFor(() => expect(isUnattendedTurn(SESSION_ID)).toBe(false));+ // ghost-setup 标记仍按 fire 生命周期存在,两者互不影响。+ expect(isHeadlessGhostSetupTurn(SESSION_ID)).toBe(true);++ releaseNotify();+ await fire;+ expect(isHeadlessGhostSetupTurn(SESSION_ID)).toBe(false);+ expect(isUnattendedTurn(SESSION_ID)).toBe(false);+ });+it.each(['result', 'finalText'].flatMap((field) =>['none', 'partial', 'matching'].map((stream) => ({ field, stream })),diff --git a/apps/desktop/src/main/scheduler-host/runner.ts b/apps/desktop/src/main/scheduler-host/runner.tsindex 3b7a96f524..fb209ccabb 100644--- a/apps/desktop/src/main/scheduler-host/runner.ts+++ b/apps/desktop/src/main/scheduler-host/runner.ts@@ -118,6 +118,7 @@ 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 { terminalErrorText } from '../im/shared/turnRetryNotice.js';import { isManagedScheduledTarget, restoreScheduledTarget } from './restore-target';@@ -446,6 +447,12 @@ interface TurnCompletionWaiterOptions {origin: { kind: 'scheduler'; scheduleId: string; scheduleName: string; runId: string };/** Coordinator queue path has authoritative per-turn origins; direct fallback keeps legacy compatibility. */requireTurnOrigin?: boolean;+ /**+ * Turn-scoped marks that must stop applying the moment this turn ends — not+ * when the fire settles. The session accepts a user message again at `done`,+ * while finalize may still be saving the report or waiting on a notification.+ */+ onTurnSettled?: () => void;}interface SchedulerRunContextOwner {@@ -782,6 +789,8 @@ export class MakerScheduleRunner implements ScheduleRunner {// native context intact until an actual next send chooses its target model.await this.clearSchedulerRunContext(holder);holder.headlessGhostSetupTurn?.close();+ holder.releaseUnattendedTurn?.();+ holder.releaseUnattendedTurn = undefined;if (holder.sessionId &&!holder.keepAlive &&@@ -1577,7 +1586,7 @@ export class MakerScheduleRunner implements ScheduleRunner {// 登记,后续任何 throw 都能被收尾。holder.sessionId = session.id;holder.keepAlive = isHeartbeat || !!schedule.persistentSession;- holder.headlessGhostSetupTurn = createHeadlessGhostSetupTurnGuard(session.id);+ holder.headlessGhostSetupTurn = createHeadlessGhostSetupTurnGuard(session.id, holder);// 4.4.1 heartbeat 模型 / effort 同步:schedule 上的选择与绑定 session 当前值// 不一致时,把改动推给 session 运行时。必须显式 setModel / setEffort ——@@ -1915,6 +1924,7 @@ export class MakerScheduleRunner implements ScheduleRunner {} as const;const waiter = this.createTurnCompletionWaiter(session, {onProgress: ctx.onProgress, onQueueWaitStart: ctx.onQueueWaitStart, endQueueWait: ctx.endQueueWait, origin,+ onTurnSettled: () => holder.releaseUnattendedTurn?.(),});const turnFinished = waiter.turnFinished;@@ -2382,7 +2392,9 @@ export class MakerScheduleRunner implements ScheduleRunner {// runner has already settled. Do not acquire a marker that no// remaining finally block could release.if (headlessTurn.closed || headlessTurn.release) return;- headlessTurn.release = beginHeadlessGhostSetupTurn(sessionId);+ const marks = beginScheduledTurnMarkers(sessionId);+ headlessTurn.release = marks.release;+ holder.releaseUnattendedTurn = marks.releaseTurn;},options,);@@ -2728,6 +2740,7 @@ export class MakerScheduleRunner implements ScheduleRunner {endQueueWait: ctx.endQueueWait,origin,requireTurnOrigin: true,+ onTurnSettled: () => holder.releaseUnattendedTurn?.(),});}// 与直发路径 onAccepted 的簿记对齐(落库/基线钩子除外,见方法头注释)。@@ -3538,6 +3551,9 @@ export class MakerScheduleRunner implements ScheduleRunner {currentSession = null;};const cleanup = (): void => {+ // Turn-scoped host marks end with the turn, before the run finalizes:+ // the session can already accept the next user message here.+ options.onTurnSettled?.();if (quotaWaiting) {quotaWaiting = false;options.endQueueWait?.(false);@@ -3899,6 +3915,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.',...buildTeammateTurnAuthorityLine(schedule),].join('\n');}@@ -3979,6 +3996,12 @@ interface EphemeralSessionHolder {releaseAgentSwitchLock?: () => void;/** unique ownership generation for the session-level scheduler run context. */schedulerRunContextOwner?: SchedulerRunContextOwner;+ /**+ * Releases the turn-scoped unattended mark. Called when the turn settles (the+ * session can accept the next user message there) and again from the fire's+ * finally as a safety net; releasing twice is a no-op.+ */+ releaseUnattendedTurn?: () => void;}interface HeadlessGhostSetupTurnGuard {@@ -3990,13 +4013,54 @@ interface HeadlessGhostSetupTurnGuard {close(): void;}-function createHeadlessGhostSetupTurnGuard(sessionId: string): HeadlessGhostSetupTurnGuard {+/**+ * Surface marks for one dispatched scheduler turn. Acquired together because the+ * queued path and the direct path acquire them at different call sites; keeping+ * them in one helper stops them from diverging again.+ *+ * The unattended mark matters because ask_user_question / plan_review cards have+ * no timeout by design (nobody is watching a scheduled fire). Without it the run+ * parks on an unanswerable card until the 60min stall guard.+ *+ * The two halves have different lifetimes: ghost-setup suppression belongs to the+ * fire, the unattended mark must die with the turn — the session accepts a user+ * message at `done` while the run is still saving its report or notifying.+ */+function beginScheduledTurnMarkers(sessionId: string): {+ release: () => void;+ releaseTurn: () => void;+} {+ const releaseGhostSetup = beginHeadlessGhostSetupTurn(sessionId);+ const releaseUnattended = beginUnattendedTurn(sessionId);+ let turnReleased = false;+ const releaseTurn = (): void => {+ if (turnReleased) return;+ turnReleased = true;+ releaseUnattended();+ };+ return {+ releaseTurn,+ release: () => {+ releaseGhostSetup();+ releaseTurn();+ },+ };+}++function createHeadlessGhostSetupTurnGuard(+ sessionId: string,+ holder: EphemeralSessionHolder,+): HeadlessGhostSetupTurnGuard {let closed = false;let release: (() => void) | undefined;return {markDispatched() {if (closed) return false;- release ??= beginHeadlessGhostSetupTurn(sessionId);+ if (!release) {+ const marks = beginScheduledTurnMarkers(sessionId);+ release = marks.release;+ holder.releaseUnattendedTurn = marks.releaseTurn;+ }return true;},close() {