Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(scheduler): 修复 autoResume 后通知上下文丢失 (#2311)
Dashd903c36694a1
diff --git a/apps/desktop/src/main/scheduler-host/__tests__/runnerQueuedDispatch.test.ts b/apps/desktop/src/main/scheduler-host/__tests__/runnerQueuedDispatch.test.tsindex 6e1e401664..97e55226d3 100644--- a/apps/desktop/src/main/scheduler-host/__tests__/runnerQueuedDispatch.test.ts+++ b/apps/desktop/src/main/scheduler-host/__tests__/runnerQueuedDispatch.test.ts@@ -20,6 +20,7 @@ import { describe, expect, it, vi, beforeEach } from 'vitest';import { AcceptedCallbackDispatchCancelled } from '../../maker-ipc/acceptedCallbackRunner.js';import type { AgentEvent, Maker, Session, SessionSendResult } from '@cindy/maker-core';+import { SCHEDULER_RUN_ID_VENDOR_OPTION } from '@cindy/maker-scheduler';import type { FireContext, Logger, Notifier, Schedule, ScheduleRun } from '@cindy/maker-scheduler';const mocks = vi.hoisted(() => ({@@ -101,6 +102,8 @@ interface FakeSessionHarness {send: ReturnType<typeof vi.fn<SendImpl>>;setModel: ReturnType<typeof vi.fn>;setEffort: ReturnType<typeof vi.fn>;+ setVendorOptions: ReturnType<typeof vi.fn>;+ vendorOptions: Record<string, unknown>;emit(event: AgentEvent): void;listenerCount(): number;}@@ -112,6 +115,10 @@ function createSessionHarness(sendImpl: SendImpl): FakeSessionHarness {async (_model: string, _opts?: { providerId?: string | null }) => undefined,);const setEffort = vi.fn(async () => undefined);+ const vendorOptions: Record<string, unknown> = {};+ const setVendorOptions = vi.fn(async (patch: Record<string, unknown>) => {+ Object.assign(vendorOptions, patch);+ });const session = {id: SESSION_ID,agentKind: 'claude-code',@@ -120,6 +127,7 @@ function createSessionHarness(sendImpl: SendImpl): FakeSessionHarness {codexProxyActive: undefined,setModel,setEffort,+ setVendorOptions,send,onEvent(listener: (event: AgentEvent) => void) {listeners.push(listener);@@ -137,6 +145,8 @@ function createSessionHarness(sendImpl: SendImpl): FakeSessionHarness {send,setModel,setEffort,+ setVendorOptions,+ vendorOptions,emit(event: AgentEvent) {// 生产 Session 会给当前 schedule turn 的每个事件补 turnOrigin;fake 默认// 复刻该边界,个别归属测试可在 event 上显式覆盖为 user / 其它 run。@@ -380,6 +390,9 @@ describe('MakerScheduleRunner queued dispatch (busy bound session)', () => {// drain 派发 → runner 挂 turn 监听 → done 收尾。await queue.accept();+ expect(harness.setVendorOptions).toHaveBeenCalledWith({+ [SCHEDULER_RUN_ID_VENDOR_OPTION]: 'run-q1',+ });await vi.waitFor(() => expect(harness.listenerCount()).toBe(1));expect(isHeadlessGhostSetupTurn(SESSION_ID)).toBe(true);harness.emit({@@ -395,6 +408,10 @@ describe('MakerScheduleRunner queued dispatch (busy bound session)', () => {// listener 已摘干净,不泄漏。expect(harness.listenerCount()).toBe(0);expect(isHeadlessGhostSetupTurn(SESSION_ID)).toBe(false);+ expect(harness.setVendorOptions).toHaveBeenLastCalledWith({+ [SCHEDULER_RUN_ID_VENDOR_OPTION]: undefined,+ });+ expect(harness.vendorOptions[SCHEDULER_RUN_ID_VENDOR_OPTION]).toBeUndefined();// 收尾通知照常(未静默场景)。expect(latestNotifiedRun(notifier)).toMatchObject({ status: 'success' });});@@ -476,6 +493,8 @@ describe('MakerScheduleRunner queued dispatch (busy bound session)', () => {harness.emit({ type: 'done', data: {}, source: 'claude-code' });await Promise.resolve();expect(harness.listenerCount()).toBe(1);+ // autoResume 尚未结束时,权威 run context 必须继续留在 session 上。+ expect(harness.vendorOptions[SCHEDULER_RUN_ID_VENDOR_OPTION]).toBe('run-q1');autoResumePending = false;harness.emit({ type: 'text', data: { text: 'continued result', isFinal: true }, source: 'claude-code' });@@ -485,6 +504,7 @@ describe('MakerScheduleRunner queued dispatch (busy bound session)', () => {sessionId: SESSION_ID,resultText: 'continued result',});+ expect(harness.vendorOptions[SCHEDULER_RUN_ID_VENDOR_OPTION]).toBeUndefined();});it('ignores a delayed done while the same run still owns the auto-resume claim', async () => {diff --git a/apps/desktop/src/main/scheduler-host/__tests__/runnerSilentNotify.test.ts b/apps/desktop/src/main/scheduler-host/__tests__/runnerSilentNotify.test.tsindex bccd295572..1ba3e58325 100644--- a/apps/desktop/src/main/scheduler-host/__tests__/runnerSilentNotify.test.ts+++ b/apps/desktop/src/main/scheduler-host/__tests__/runnerSilentNotify.test.ts@@ -7,6 +7,7 @@ import type {SessionSendResult,} from '@cindy/maker-core';import type { Scheduler } from '@cindy/maker-scheduler';+import { SCHEDULER_RUN_ID_VENDOR_OPTION } from '@cindy/maker-scheduler';import type {FireContext,Logger,@@ -61,15 +62,20 @@ type SendImpl = (interface FakeSessionHarness {session: Session;+ vendorOptions: Record<string, unknown>;emit(event: AgentEvent): void;}function createSessionHarness(sendImpl: SendImpl): FakeSessionHarness {const listeners: Array<(event: AgentEvent) => void> = [];+ const vendorOptions: Record<string, unknown> = {};const session = {id: 'scheduler-session',agentKind: 'codex',send: vi.fn<SendImpl>(sendImpl),+ setVendorOptions: vi.fn(async (patch: Record<string, unknown>) => {+ Object.assign(vendorOptions, patch);+ }),onEvent(listener: (event: AgentEvent) => void) {listeners.push(listener);return vi.fn(() => {@@ -82,6 +88,7 @@ function createSessionHarness(sendImpl: SendImpl): FakeSessionHarness {return {session,+ vendorOptions,emit(event: AgentEvent) {for (const listener of [...listeners]) listener(event);},@@ -112,9 +119,9 @@ function baseSchedule(overrides: Partial<Schedule> = {}): Schedule {};}-function createFireContext(): FireContext {+function createFireContext(runId = 'run-1'): FireContext {return {- runId: 'run-1',+ runId,firedAt: 1_700_000_000_100,signal: new AbortController().signal,onSessionBound: vi.fn(async () => undefined),@@ -123,10 +130,14 @@ function createFireContext(): FireContext {function createRunnerHarness(session: Session,- opts: { silenced: boolean; abandoned?: boolean },+ opts: {+ silenced: boolean;+ abandoned?: boolean;+ notifyImpl?: Notifier['notify'];+ },) {const notifier: Notifier & { notify: ReturnType<typeof vi.fn> } = {- notify: vi.fn(async () => undefined),+ notify: vi.fn(opts.notifyImpl ?? (async () => undefined)),};const logger: Logger = { warn: vi.fn(), info: vi.fn(), debug: vi.fn(), error: vi.fn() };const maker = {@@ -195,6 +206,153 @@ describe('MakerScheduleRunner silent-run notification skip', () => {expect(notifier.notify).toHaveBeenCalledTimes(1);});+ it('scheduler turn 绑定 host-owned runId,收尾后清理', async () => {+ const h = createSessionHarness(acceptingSend());+ const { runner } = createRunnerHarness(h.session, { silenced: false });++ await fireToCompletion(runner, h);++ expect(h.session.setVendorOptions).toHaveBeenNthCalledWith(1, {+ [SCHEDULER_RUN_ID_VENDOR_OPTION]: 'run-1',+ });+ expect(h.session.setVendorOptions).toHaveBeenLastCalledWith({+ [SCHEDULER_RUN_ID_VENDOR_OPTION]: undefined,+ });+ expect(h.vendorOptions[SCHEDULER_RUN_ID_VENDOR_OPTION]).toBeUndefined();+ });++ it('context 写入失败时只回滚当前 owner generation', async () => {+ const h = createSessionHarness(acceptingSend());+ const setVendorOptions = h.session.setVendorOptions as ReturnType<typeof vi.fn>;+ setVendorOptions.mockImplementation(async (patch: Record<string, unknown>) => {+ Object.assign(h.vendorOptions, patch);+ if (patch[SCHEDULER_RUN_ID_VENDOR_OPTION] === 'run-1') {+ throw new Error('context write failed');+ }+ });+ const { runner } = createRunnerHarness(h.session, { silenced: false });++ await fireToCompletion(runner, h);++ expect(setVendorOptions).toHaveBeenNthCalledWith(1, {+ [SCHEDULER_RUN_ID_VENDOR_OPTION]: 'run-1',+ });+ expect(setVendorOptions).toHaveBeenNthCalledWith(2, {+ [SCHEDULER_RUN_ID_VENDOR_OPTION]: undefined,+ });+ expect(h.vendorOptions[SCHEDULER_RUN_ID_VENDOR_OPTION]).toBeUndefined();+ });++ it('旧 fire 收尾不能清掉同一 session 上较新的 run context', async () => {+ let resolveA!: () => void;+ let resolveB!: () => void;+ const notifyA = new Promise<void>((resolve) => {+ resolveA = resolve;+ });+ const notifyB = new Promise<void>((resolve) => {+ resolveB = resolve;+ });+ const h = createSessionHarness(acceptingSend());+ const { runner, notifier } = createRunnerHarness(h.session, {+ silenced: false,+ notifyImpl: async (_schedule, run) => (run.id === 'run-a' ? notifyA : notifyB),+ });++ const fireA = runner.fire(+ baseSchedule({ id: 'schedule-a' }),+ createFireContext('run-a'),+ );+ await vi.waitFor(() => expect(mocks.createMessage).toHaveBeenCalledTimes(1));+ h.emit({ type: 'done', data: {} });+ await vi.waitFor(() =>+ expect(notifier.notify).toHaveBeenCalledWith(+ expect.anything(),+ expect.objectContaining({ id: 'run-a' }),+ ),+ );++ // A's turn is done, but its fire is still finalizing notification work.+ // B is accepted on the same session before A's finally runs.+ const fireB = runner.fire(+ baseSchedule({ id: 'schedule-b' }),+ createFireContext('run-b'),+ );+ await vi.waitFor(() => expect(mocks.createMessage).toHaveBeenCalledTimes(2));+ h.emit({ type: 'done', data: {} });+ await vi.waitFor(() =>+ expect(notifier.notify).toHaveBeenCalledWith(+ expect.anything(),+ expect.objectContaining({ id: 'run-b' }),+ ),+ );+ expect(h.vendorOptions[SCHEDULER_RUN_ID_VENDOR_OPTION]).toBe('run-b');++ resolveA();+ await fireA;+ expect(h.vendorOptions[SCHEDULER_RUN_ID_VENDOR_OPTION]).toBe('run-b');++ resolveB();+ await fireB;+ expect(h.vendorOptions[SCHEDULER_RUN_ID_VENDOR_OPTION]).toBeUndefined();+ });++ it('新 fire 的 context 写入仍在 await 时,旧 fire 收尾也不能清掉它', async () => {+ let resolveNotifyA!: () => void;+ let releaseBindB!: () => void;+ const notifyA = new Promise<void>((resolve) => {+ resolveNotifyA = resolve;+ });+ const bindB = new Promise<void>((resolve) => {+ releaseBindB = resolve;+ });+ const h = createSessionHarness(acceptingSend());+ const setVendorOptions = h.session.setVendorOptions as ReturnType<typeof vi.fn>;+ setVendorOptions.mockImplementation(async (patch: Record<string, unknown>) => {+ Object.assign(h.vendorOptions, patch);+ if (patch[SCHEDULER_RUN_ID_VENDOR_OPTION] === 'run-b') await bindB;+ });+ const { runner, notifier } = createRunnerHarness(h.session, {+ silenced: false,+ notifyImpl: async (_schedule, run) => (run.id === 'run-a' ? notifyA : undefined),+ });++ const fireA = runner.fire(+ baseSchedule({ id: 'schedule-a' }),+ createFireContext('run-a'),+ );+ await vi.waitFor(() => expect(mocks.createMessage).toHaveBeenCalledTimes(1));+ h.emit({ type: 'done', data: {} });+ await vi.waitFor(() =>+ expect(notifier.notify).toHaveBeenCalledWith(+ expect.anything(),+ expect.objectContaining({ id: 'run-a' }),+ ),+ );++ const fireB = runner.fire(+ baseSchedule({ id: 'schedule-b' }),+ createFireContext('run-b'),+ );+ await vi.waitFor(() =>+ expect(setVendorOptions).toHaveBeenCalledWith({+ [SCHEDULER_RUN_ID_VENDOR_OPTION]: 'run-b',+ }),+ );++ // B already mutated the shared option but its async bind has not settled.+ // A's late finally must see B's owner generation and leave the value alone.+ expect(h.vendorOptions[SCHEDULER_RUN_ID_VENDOR_OPTION]).toBe('run-b');+ resolveNotifyA();+ await fireA;+ expect(h.vendorOptions[SCHEDULER_RUN_ID_VENDOR_OPTION]).toBe('run-b');++ releaseBindB();+ await vi.waitFor(() => expect(mocks.createMessage).toHaveBeenCalledTimes(2));+ h.emit({ type: 'done', data: {} });+ await fireB;+ expect(h.vendorOptions[SCHEDULER_RUN_ID_VENDOR_OPTION]).toBeUndefined();+ });+it('silentWhenIdle=true → 发送隐藏主动上报协议,落库仍保留原始 prompt', async () => {const h = createSessionHarness(acceptingSend());const { runner } = createRunnerHarness(h.session, { silenced: false });diff --git a/apps/desktop/src/main/scheduler-host/runner.ts b/apps/desktop/src/main/scheduler-host/runner.tsindex 892aafa5c7..843141049f 100644--- a/apps/desktop/src/main/scheduler-host/runner.ts+++ b/apps/desktop/src/main/scheduler-host/runner.ts@@ -42,6 +42,7 @@ import type {TurnContinuationState,} from '@cindy/maker-core';import { clampEffortToSupported } from '@cindy/model-providers';+import { SCHEDULER_RUN_ID_VENDOR_OPTION } from '@cindy/maker-scheduler';import type {Schedule,ScheduleRun,@@ -314,8 +315,19 @@ interface TurnCompletionWaiterOptions {requireTurnOrigin?: boolean;}+interface SchedulerRunContextOwner {+ session: Pick<Session, 'id' | 'setVendorOptions'>;+ runId: string;+}+export class MakerScheduleRunner implements ScheduleRunner {private scheduler: Scheduler | null = null;+ /**+ * The vendor option is a single session-level value, so a late finally from+ * an older fire must not clear a newer fire's binding. The map is the host's+ * ownership record for that value; it is deliberately not persisted.+ */+ private readonly schedulerRunContextOwners = new Map<string, SchedulerRunContextOwner>();constructor(private readonly deps: MakerScheduleRunnerDeps) {}@@ -324,6 +336,69 @@ export class MakerScheduleRunner implements ScheduleRunner {this.scheduler = scheduler;}+ /**+ * Keep the scheduler's authoritative run id in the host-owned session+ * context for the lifetime of the actual turn, including auto-resume+ * continuations. The normal session→run mapping remains the primary path;+ * this is the in-process fallback when that mapping is gone.+ */+ private async bindSchedulerRunContext(+ session: Pick<Session, 'id' | 'setVendorOptions'>,+ runId: string,+ holder: EphemeralSessionHolder,+ ): Promise<void> {+ if (typeof session.setVendorOptions !== 'function') return;+ const owner: SchedulerRunContextOwner = { session, runId };+ // Publish ownership before the async write starts. setVendorOptions mutates+ // the shared session context before its promise necessarily settles, so an+ // older fire must already see this generation and skip its late cleanup.+ this.schedulerRunContextOwners.set(session.id, owner);+ holder.schedulerRunContextOwner = owner;+ try {+ await session.setVendorOptions({ [SCHEDULER_RUN_ID_VENDOR_OPTION]: runId });+ } catch (err) {+ if (this.schedulerRunContextOwners.get(session.id) === owner) {+ this.schedulerRunContextOwners.delete(session.id);+ holder.schedulerRunContextOwner = undefined;+ try {+ await session.setVendorOptions({ [SCHEDULER_RUN_ID_VENDOR_OPTION]: undefined });+ } catch (rollbackErr) {+ this.deps.logger.warn?.('[runner] scheduler run context rollback failed (non-fatal)', {+ runId,+ error: rollbackErr instanceof Error ? rollbackErr.message : String(rollbackErr),+ });+ }+ }+ this.deps.logger.warn?.('[runner] scheduler run context bind failed (non-fatal)', {+ runId,+ error: err instanceof Error ? err.message : String(err),+ });+ }+ }++ private async clearSchedulerRunContext(holder: EphemeralSessionHolder): Promise<void> {+ const holderOwner = holder.schedulerRunContextOwner;+ holder.schedulerRunContextOwner = undefined;+ if (!holderOwner) return;+ const { session, runId } = holderOwner;+ if (typeof session.setVendorOptions !== 'function') return;+ const currentOwner = this.schedulerRunContextOwners.get(session.id);+ if (currentOwner !== holderOwner) {+ // Another fire now owns the shared session-level option. Do not let this+ // older fire erase the newer run's auto-resume context.+ return;+ }+ this.schedulerRunContextOwners.delete(session.id);+ try {+ await session.setVendorOptions({ [SCHEDULER_RUN_ID_VENDOR_OPTION]: undefined });+ } catch (err) {+ this.deps.logger.warn?.('[runner] scheduler run context clear failed (non-fatal)', {+ runId,+ error: err instanceof Error ? err.message : String(err),+ });+ }+ }+/*** 顺延本轮:返回 deferred FireResult(engine 据此撤销预插 run、不通知、把* nextFireAt 短延 RETRY_DELAY_MS 后重试)。reason 仅用于日志。@@ -406,6 +481,7 @@ export class MakerScheduleRunner implements ScheduleRunner {} finally {holder.releaseAgentSwitchLock?.();holder.releaseAgentSwitchLock = undefined;+ await this.clearSchedulerRunContext(holder);holder.headlessGhostSetupTurn?.close();if (holder.sessionId &&@@ -622,7 +698,7 @@ export class MakerScheduleRunner implements ScheduleRunner {}holder.releaseAgentSwitchLock?.();holder.releaseAgentSwitchLock = undefined;- return await this.fireHeartbeatViaQueue(schedule, ctx, sessionId, {+ return await this.fireHeartbeatViaQueue(schedule, ctx, sessionId, holder, {model: meta?.model,effort: meta?.effort,fastMode: meta?.fastMode,@@ -1118,6 +1194,7 @@ export class MakerScheduleRunner implements ScheduleRunner {schedule,ctx,session.id,+ holder,{model: session.model ?? model,effort: runtimeReconciledEffort,@@ -1273,6 +1350,10 @@ export class MakerScheduleRunner implements ScheduleRunner {// turn 误标成 headless;只在本轮 send 真正跨过接受边界后 acquire。// fire 已收口后才到达的迟发 callback 由 guard 拒绝,避免重新污染 session。if (!holder.headlessGhostSetupTurn?.markDispatched()) return;+ // Bind only after Session.send accepts this turn. A competing fire+ // rejected with SESSION_RUNNING must not overwrite the active run's+ // shared auto-resume context before it is rejected.+ await this.bindSchedulerRunContext(session, ctx.runId, holder);turnAccepted = true;// turn 已被会话接受 → 此刻才落定 sessionId → 本轮 runId 反向映射(供按// session 静默解析)。在 send 被接受这一刻写,被 SESSION_RUNNING 拒的并发 run@@ -1481,6 +1562,7 @@ export class MakerScheduleRunner implements ScheduleRunner {schedule: Schedule,ctx: FireContext,sessionId: string,+ holder: EphemeralSessionHolder,/** 绑定会话的当前路由基线(meta.model / meta.effort / sessions.provider_id)。 */routingBaseline: {model?: string;@@ -1499,6 +1581,7 @@ export class MakerScheduleRunner implements ScheduleRunner {schedule,ctx,sessionId,+ holder,routingBaseline,() => {// A cancelled queue item may still report a late accept after the@@ -1520,6 +1603,7 @@ export class MakerScheduleRunner implements ScheduleRunner {schedule: Schedule,ctx: FireContext,sessionId: string,+ holder: EphemeralSessionHolder,routingBaseline: {model?: string;effort?: string;@@ -1713,6 +1797,10 @@ export class MakerScheduleRunner implements ScheduleRunner {blockAcceptedDispatch(undefined, 'session unavailable for queued route sync');return;}+ // Only bind at the accepted→vendor-dispatch boundary. Binding while+ // the item is merely queued would let an unrelated interactive turn+ // observe this scheduler run id.+ await this.bindSchedulerRunContext(live, ctx.runId, holder);// 任务编辑器里选的 model/effort/来源在排队派发时刻热同步到会话(此回调// 运行于 vendor dispatch 之前,setModel 对本 turn 生效)—— 对齐直发路径// 的 4.4.1/4.4.2 语义,不让"任务改了模型且每轮都撞忙"的用户被静默忽略@@ -2514,6 +2602,8 @@ interface EphemeralSessionHolder {keepAlive?: boolean;/** heartbeat direct-send route lock; released immediately after Session.send settles. */releaseAgentSwitchLock?: () => void;+ /** unique ownership generation for the session-level scheduler run context. */+ schedulerRunContextOwner?: SchedulerRunContextOwner;}interface HeadlessGhostSetupTurnGuard {diff --git a/packages/lizi-mcps/src/__tests__/cindy_schedulerMcpServer.test.ts b/packages/lizi-mcps/src/__tests__/cindy_schedulerMcpServer.test.tsindex c125714409..97fd5c3ccb 100644--- a/packages/lizi-mcps/src/__tests__/cindy_schedulerMcpServer.test.ts+++ b/packages/lizi-mcps/src/__tests__/cindy_schedulerMcpServer.test.ts@@ -24,7 +24,7 @@ import { describe, it, expect, beforeEach, vi } from 'vitest';import { Client } from '@modelcontextprotocol/sdk/client/index.js';import { InMemoryTransport } from '@modelcontextprotocol/sdk/inMemory.js';-import { Scheduler } from '@cindy/maker-scheduler';+import { SCHEDULER_RUN_ID_VENDOR_OPTION, Scheduler } from '@cindy/maker-scheduler';import type {CreateScheduleInput,ListFilter,@@ -778,13 +778,16 @@ describe('schedule_silence_current_run — runId resolution branches', () => {function setup(opts: {sessionId?: string;inflightRunForSession?: string | undefined;- silenceReturns?: boolean;+ silenceReturns?: boolean | ((runId: string) => boolean);+ vendorRunId?: string;}) {const fake: FakeScheduler = {resolveInflightRunForSession: () => opts.inflightRunForSession,silenceRun: (runId: string) => {fake.silencedArg = runId;- return opts.silenceReturns ?? true;+ return typeof opts.silenceReturns === 'function'+ ? opts.silenceReturns(runId)+ : (opts.silenceReturns ?? true);},};const registry = new SchedulerToolRegistry();@@ -792,6 +795,9 @@ describe('schedule_silence_current_run — runId resolution branches', () => {agentKind: 'claude-code',workingDir: '/x',sessionId: opts.sessionId,+ vendorOptions: opts.vendorRunId+ ? { [SCHEDULER_RUN_ID_VENDOR_OPTION]: opts.vendorRunId }+ : undefined,};registerScheduleSilenceCurrentRunTool(registry,@@ -834,6 +840,31 @@ describe('schedule_silence_current_run — runId resolution branches', () => {expect(fake.silencedArg).toBeUndefined(); // 未尝试静默任何 run});+ it('session map 丢失 + host-owned runId 存在 → 静默权威 run', async () => {+ const { fake, registry } = setup({+ sessionId: 'sess-1',+ inflightRunForSession: undefined,+ vendorRunId: 'run-after-auto-resume',+ });+ const env = await callSilence(registry, { runId: 'run-incorrect' });+ expect(env.ok).toBe(true);+ expect(env.data).toMatchObject({ silenced: true, runId: 'run-after-auto-resume' });+ expect(fake.silencedArg).toBe('run-after-auto-resume');+ });++ it('host-owned runId 已过期 + session map 已恢复 → 回退到当前 run', async () => {+ const { fake, registry } = setup({+ sessionId: 'sess-1',+ inflightRunForSession: 'run-current',+ vendorRunId: 'run-stale',+ silenceReturns: (runId) => runId === 'run-current',+ });+ const env = await callSilence(registry, {});+ expect(env.ok).toBe(true);+ expect(env.data).toMatchObject({ silenced: true, runId: 'run-current' });+ expect(fake.silencedArg).toBe('run-current');+ });+it('sessionId 未知 + 传了 runId → 回退用该 runId 静默', async () => {const { fake, registry } = setup({ sessionId: undefined });const env = await callSilence(registry, { runId: 'run-fallback' });@@ -860,13 +891,16 @@ describe('schedule_notify_current_run — runId resolution branches', () => {function setup(opts: {sessionId?: string;inflightRunForSession?: string | undefined;- notifyReturns?: boolean;+ notifyReturns?: boolean | ((runId: string) => boolean);+ vendorRunId?: string;}) {const fake: FakeScheduler = {resolveInflightRunForSession: () => opts.inflightRunForSession,notifyRun: (runId: string) => {fake.notifiedArg = runId;- return opts.notifyReturns ?? true;+ return typeof opts.notifyReturns === 'function'+ ? opts.notifyReturns(runId)+ : (opts.notifyReturns ?? true);},};const registry = new SchedulerToolRegistry();@@ -874,6 +908,9 @@ describe('schedule_notify_current_run — runId resolution branches', () => {agentKind: 'claude-code',workingDir: '/x',sessionId: opts.sessionId,+ vendorOptions: opts.vendorRunId+ ? { [SCHEDULER_RUN_ID_VENDOR_OPTION]: opts.vendorRunId }+ : undefined,};registerScheduleNotifyCurrentRunTool(registry,@@ -914,6 +951,31 @@ describe('schedule_notify_current_run — runId resolution branches', () => {expect(fake.notifiedArg).toBeUndefined();});+ it('session map 丢失 + host-owned runId 存在 → 主动上报权威 run', async () => {+ const { fake, registry } = setup({+ sessionId: 'sess-1',+ inflightRunForSession: undefined,+ vendorRunId: 'run-after-auto-resume',+ });+ const env = await callNotify(registry, { runId: 'run-incorrect' });+ expect(env.ok).toBe(true);+ expect(env.data).toMatchObject({ notified: true, runId: 'run-after-auto-resume' });+ expect(fake.notifiedArg).toBe('run-after-auto-resume');+ });++ it('host-owned runId 已过期 + session map 已恢复 → 回退到当前 run', async () => {+ const { fake, registry } = setup({+ sessionId: 'sess-1',+ inflightRunForSession: 'run-current',+ vendorRunId: 'run-stale',+ notifyReturns: (runId) => runId === 'run-current',+ });+ const env = await callNotify(registry, {});+ expect(env.ok).toBe(true);+ expect(env.data).toMatchObject({ notified: true, runId: 'run-current' });+ expect(fake.notifiedArg).toBe('run-current');+ });+it('sessionId 未知 + 传了 runId → 回退用该 runId 主动上报', async () => {const { fake, registry } = setup({ sessionId: undefined });const env = await callNotify(registry, { runId: 'run-fallback' });diff --git a/packages/lizi-mcps/src/scheduler/_shared.ts b/packages/lizi-mcps/src/scheduler/_shared.tsindex 245d70f481..6fdaf3a3ef 100644--- a/packages/lizi-mcps/src/scheduler/_shared.ts+++ b/packages/lizi-mcps/src/scheduler/_shared.ts@@ -19,12 +19,49 @@* Implemented in errors.ts.*/-import { parseCron, type Scheduler } from '@cindy/maker-scheduler';+import {+ parseCron,+ SCHEDULER_RUN_ID_VENDOR_OPTION,+ type Scheduler,+} from '@cindy/maker-scheduler';import type { SchedulerToolResult } from '../cindy_schedulerToolRegistry.js';-import type { SchedulerMcpDeps } from '../types.js';+import type { LiziMcpSessionContext, SchedulerMcpDeps } from '../types.js';import { classifySchedulerError } from './errors.js';+/**+ * Resolve the possible owners of a scheduler MCP call in priority order.+ *+ * A completed run can leave a stale host-owned run id while a subsequent fire+ * is already mapped to the same session. Keep the host-owned id first for the+ * auto-resume case, but let callers try the live session mapping if that id is+ * no longer active.+ */+export function resolveSchedulerRunIdCandidates(+ scheduler: Pick<Scheduler, 'resolveInflightRunForSession'>,+ sessionContext: LiziMcpSessionContext | undefined,+ explicitRunId?: string,+): { sessionId?: string; runIds: string[] } {+ const sessionId = sessionContext?.sessionId;+ const hostOwnedRunId = sessionContext?.vendorOptions?.[SCHEDULER_RUN_ID_VENDOR_OPTION];+ const mappedRunId = sessionId+ ? scheduler.resolveInflightRunForSession(sessionId)+ : undefined;+ const runIds: string[] = [];++ if (typeof hostOwnedRunId === 'string' && hostOwnedRunId.length > 0) {+ runIds.push(hostOwnedRunId);+ }+ if (typeof mappedRunId === 'string' && mappedRunId.length > 0 && !runIds.includes(mappedRunId)) {+ runIds.push(mappedRunId);+ }+ if (!sessionId && runIds.length === 0 && explicitRunId) {+ runIds.push(explicitRunId);+ }++ return { sessionId, runIds };+}+/*** 校验 cronExpr / timezone 在工具层就合法。*diff --git a/packages/lizi-mcps/src/scheduler/notifyCurrentRun.ts b/packages/lizi-mcps/src/scheduler/notifyCurrentRun.tsindex c1facf9744..2e585e0b06 100644--- a/packages/lizi-mcps/src/scheduler/notifyCurrentRun.ts+++ b/packages/lizi-mcps/src/scheduler/notifyCurrentRun.ts@@ -7,7 +7,7 @@import { z } from 'zod';-import { withScheduler } from './_shared.js';+import { resolveSchedulerRunIdCandidates, withScheduler } from './_shared.js';import type { LiziMcpSessionContext, SchedulerMcpDeps } from '../types.js';import type { SchedulerToolRegistry } from '../cindy_schedulerToolRegistry.js';@@ -32,31 +32,24 @@ export function registerScheduleNotifyCurrentRunTool(},handler: async ({ runId }) =>withScheduler(deps, async (scheduler) => {- const sessionId = getSessionContext?.().sessionId;- let targetRunId: string | undefined;- if (sessionId) {- targetRunId = scheduler.resolveInflightRunForSession(sessionId);- if (!targetRunId) {- throw new Error(- 'in-flight run not found for current session — notify can only be called while this session has an automation run executing',- );- }- } else {- targetRunId = runId;- if (!targetRunId) {- throw new Error(- 'in-flight run not found: cannot resolve current session and no runId provided',- );+ const { sessionId, runIds } = resolveSchedulerRunIdCandidates(+ scheduler,+ getSessionContext?.(),+ runId,+ );+ for (const targetRunId of runIds) {+ if (scheduler.notifyRun(targetRunId)) {+ return { notified: true, runId: targetRunId };}}-- const ok = scheduler.notifyRun(targetRunId);- if (!ok) {+ if (sessionId) {throw new Error(- `in-flight run not found: ${targetRunId} — notify can only be called while this run is executing`,+ 'in-flight run not found for current session — notify can only be called while this session has an automation run executing',);}- return { notified: true, runId: targetRunId };+ throw new Error(+ `in-flight run not found: ${runIds[0] ?? 'unknown'} — notify can only be called while this run is executing`,+ );}),});}diff --git a/packages/lizi-mcps/src/scheduler/silenceCurrentRun.ts b/packages/lizi-mcps/src/scheduler/silenceCurrentRun.tsindex 3369ef707e..1c7ca3f2c2 100644--- a/packages/lizi-mcps/src/scheduler/silenceCurrentRun.ts+++ b/packages/lizi-mcps/src/scheduler/silenceCurrentRun.ts@@ -21,7 +21,7 @@import { z } from 'zod';-import { withScheduler } from './_shared.js';+import { resolveSchedulerRunIdCandidates, withScheduler } from './_shared.js';import type { LiziMcpSessionContext, SchedulerMcpDeps } from '../types.js';import type { SchedulerToolRegistry } from '../cindy_schedulerToolRegistry.js';@@ -46,34 +46,25 @@ export function registerScheduleSilenceCurrentRunTool(},handler: async ({ runId }) =>withScheduler(deps, async (scheduler) => {- // 优先按调用方 session 解析本轮 runId(忽略 agent 传入的 runId,杜绝传参漂移);- // 拿不到 sessionId(未绑定 session 的 codex 调用)才回退到显式 runId。- const sessionId = getSessionContext?.().sessionId;- let targetRunId: string | undefined;- if (sessionId) {- targetRunId = scheduler.resolveInflightRunForSession(sessionId);- if (!targetRunId) {- // 消息含 "not found" → classifySchedulerError 归为 NOT_FOUND- throw new Error(- 'in-flight run not found for current session — silence can only be called while this session has an automation run executing',- );- }- } else {- targetRunId = runId;- if (!targetRunId) {- throw new Error(- 'in-flight run not found: cannot resolve current session and no runId provided',- );+ const { sessionId, runIds } = resolveSchedulerRunIdCandidates(+ scheduler,+ getSessionContext?.(),+ runId,+ );+ for (const targetRunId of runIds) {+ if (scheduler.silenceRun(targetRunId)) {+ return { silenced: true, runId: targetRunId };}}-- const ok = scheduler.silenceRun(targetRunId);- if (!ok) {+ if (sessionId) {+ // 消息含 "not found" → classifySchedulerError 归为 NOT_FOUNDthrow new Error(- `in-flight run not found: ${targetRunId} — silence can only be called while this run is executing`,+ 'in-flight run not found for current session — silence can only be called while this session has an automation run executing',);}- return { silenced: true, runId: targetRunId };+ throw new Error(+ `in-flight run not found: ${runIds[0] ?? 'unknown'} — silence can only be called while this run is executing`,+ );}),});}diff --git a/packages/maker-scheduler/src/types.ts b/packages/maker-scheduler/src/types.tsindex d3b86455b5..50b08f2a1c 100644--- a/packages/maker-scheduler/src/types.ts+++ b/packages/maker-scheduler/src/types.ts@@ -5,6 +5,13 @@ export type ScheduleWorkspaceKind = 'project' | 'dialogue';export type ScheduleExecutionMode = 'agent' | 'script';export type ScriptCapability = 'jira.read' | 'jira.comment' | 'sessions.dispatch' | 'feishu.read';+/**+ * Host-owned session context key for the scheduler run currently dispatched+ * through a session. It is not exposed in the agent prompt; scheduler MCP+ * tools use it to recover the authoritative run during auto-resume.+ */+export const SCHEDULER_RUN_ID_VENDOR_OPTION = '__cindySchedulerRunId';+/** 一次调度执行由自动到点触发,还是由用户显式 runNow 触发。 */export type ScheduleFireSource = 'automatic' | 'run-now';