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): 向模型提供本轮定时任务触发时间 (#4338)

Dashc63d86168e3d
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 fd65048cfb..389e61566f 100644
--- a/apps/desktop/src/main/scheduler-host/__tests__/runnerQueuedDispatch.test.ts
+++ b/apps/desktop/src/main/scheduler-host/__tests__/runnerQueuedDispatch.test.ts
@@ -7,8 +7,9 @@
* 可删除),drain 派发(onAccepted)后沿用既有 run 结果捕获/通知链路。
*
* 覆盖:
- * - 撞忙 → enqueuePrompt(text 带静默协议后缀 / persistedContent 是原始 prompt /
- * origin=scheduler),不直发 session.send、不自行 createMessage
+ * - 撞忙 → enqueuePrompt(text 带 firedAt 上下文和静默协议后缀 /
+ * persistedContent 是原始 prompt / origin=scheduler),不直发 session.send、
+ * 不自行 createMessage
* - accepted → 等 turn done → success run 带 resultText
* - 同 schedule 已有排队项 → 顺延(deferred),不重复入队
* - 排队项被丢弃(用户删除)→ run 以含 aborted 的错误收尾
@@ -321,7 +322,8 @@ function createQueueHarness(opts: {
if (opts.enqueueRetry) return { retry: true as const };
if (opts.enqueueDuplicate) return { duplicate: true as const };
enqueueCalls.push(req);
- if (opts.acceptBeforeEnqueueResolves) await req.onAccepted({ permissionMode: 'ask', planMode: false });
+ if (opts.acceptBeforeEnqueueResolves)
+ await req.onAccepted({ permissionMode: 'ask', planMode: false });
return { clientId: `client-${enqueueCalls.length}` };
}),
removeQueuedPrompt: (sessionId, clientId) => {
@@ -452,34 +454,72 @@ describe('MakerScheduleRunner queued dispatch (busy bound session)', () => {
mocks.setSessionProvider.mockImplementationOnce((_sessionId, providerId) => {
mocks.getSessionProvider.mockReturnValue(providerId);
});
- const providers: ProviderView[] = [{
- id: 'selected', name: 'Selected', connected: true, agents: ['pi'],
- source: 'user', auth: { method: 'apiKey' },
- routing: { pi: { upstream: 'https://selected.invalid/v1', authStrategy: 'none', wireProtocol: 'openai-responses' } },
- models: { pi: [{ id: 'shared-model', name: 'Shared', mode: 'chat', contextWindow: 128_000, efforts: ['high'],
- defaultEffort: 'high', supportsFastMode: false }] },
- }];
- const resolveModelSelection = vi.fn<NonNullable<MakerScheduleRunnerDeps['resolveModelSelection']>>(
- async (choice) => resolveScheduledModelSelection(choice, providers),
- );
+ const providers: ProviderView[] = [
+ {
+ id: 'selected',
+ name: 'Selected',
+ connected: true,
+ agents: ['pi'],
+ source: 'user',
+ auth: { method: 'apiKey' },
+ routing: {
+ pi: {
+ upstream: 'https://selected.invalid/v1',
+ authStrategy: 'none',
+ wireProtocol: 'openai-responses',
+ },
+ },
+ models: {
+ pi: [
+ {
+ id: 'shared-model',
+ name: 'Shared',
+ mode: 'chat',
+ contextWindow: 128_000,
+ efforts: ['high'],
+ defaultEffort: 'high',
+ supportsFastMode: false,
+ },
+ ],
+ },
+ },
+ ];
+ const resolveModelSelection = vi.fn<
+ NonNullable<MakerScheduleRunnerDeps['resolveModelSelection']>
+ >(async (choice) => resolveScheduledModelSelection(choice, providers));
const checkModelRoute = vi.fn<NonNullable<MakerScheduleRunnerDeps['checkModelRoute']>>(
async () => ({ kind: 'pass' }),
);
const queue = createQueueHarness({ busy: false });
const { runner, maker, notifier } = createRunnerHarness(h.session, queue.deps, {
- resolveModelSelection, checkModelRoute,
+ resolveModelSelection,
+ checkModelRoute,
});
vi.mocked(maker.isSessionAlive).mockReturnValue(false);
- const schedule = heartbeatSchedule({ targetSessionId: undefined, workingDir: '/work',
- agentKind: 'pi', modelAgentKind: 'pi', model: 'shared-model', fastMode: true });
+ const schedule = heartbeatSchedule({
+ targetSessionId: undefined,
+ workingDir: '/work',
+ agentKind: 'pi',
+ modelAgentKind: 'pi',
+ model: 'shared-model',
+ fastMode: true,
+ });
const saved = structuredClone(schedule);
const fire = runner.fire(schedule, createFireContext());
const result = fire.catch((error: unknown) => error);
await vi.waitFor(() => expect(queue.enqueueCalls).toHaveLength(1));
- expect(resolveModelSelection).toHaveBeenCalledWith(expect.objectContaining({ providerId: null }));
- expect(maker.createSession).toHaveBeenCalledWith(expect.objectContaining({
- agentKind: 'pi', model: 'shared-model', providerId: 'selected', effort: 'high', fastMode: false,
- }));
+ expect(resolveModelSelection).toHaveBeenCalledWith(
+ expect.objectContaining({ providerId: null }),
+ );
+ expect(maker.createSession).toHaveBeenCalledWith(
+ expect.objectContaining({
+ agentKind: 'pi',
+ model: 'shared-model',
+ providerId: 'selected',
+ effort: 'high',
+ fastMode: false,
+ }),
+ );
// A fresh handle was already created on this route. The store and queue
// baseline must agree before acceptance checks for credential changes.
expect(mocks.setSessionProvider).toHaveBeenLastCalledWith(SESSION_ID, 'selected');
@@ -490,7 +530,9 @@ describe('MakerScheduleRunner queued dispatch (busy bound session)', () => {
expect(checkModelRoute).toHaveBeenLastCalledWith('pi', 'shared-model', 'selected');
expect(mocks.setSessionProvider).toHaveBeenLastCalledWith(SESSION_ID, 'selected');
expect(mocks.backfillSessionMeta.mock.calls.at(-1)?.[2]).toMatchObject({
- providerId: 'selected', effort: 'high', fastMode: false,
+ providerId: 'selected',
+ effort: 'high',
+ fastMode: false,
});
await vi.waitFor(() => expect(h.listenerCount()).toBe(1));
h.emit({ type: 'done', data: {}, source: 'pi' });
@@ -512,31 +554,50 @@ describe('MakerScheduleRunner queued dispatch (busy bound session)', () => {
const queue = createQueueHarness({ busy: false });
const release = vi.fn();
const { runner, maker } = createRunnerHarness(h.session, queue.deps, {
- metaModel: 'shared-model', metaEffort: 'ultra', metaFastMode: true,
+ metaModel: 'shared-model',
+ metaEffort: 'ultra',
+ metaFastMode: true,
availableModels: [{ id: 'shared-model', efforts: ['low'], defaultEffort: 'low' }],
- acquirePendingAgentSwitch: async () => ({ release, selection: {
- model: 'shared-model', providerId: 'selected', ...axes,
- } }),
+ acquirePendingAgentSwitch: async () => ({
+ release,
+ selection: {
+ model: 'shared-model',
+ providerId: 'selected',
+ ...axes,
+ },
+ }),
+ });
+ const schedule = heartbeatSchedule({
+ agentKind: axes.agentKind,
+ modelAgentKind: axes.agentKind,
+ model: 'shared-model',
+ effort: 'ultra',
+ fastMode: true,
});
- const schedule = heartbeatSchedule({ agentKind: axes.agentKind, modelAgentKind: axes.agentKind,
- model: 'shared-model', effort: 'ultra', fastMode: true });
const saved = structuredClone(schedule);
const fire = runner.fire(schedule, createFireContext());
await vi.waitFor(() => expect(queue.enqueueCalls).toHaveLength(1));
expect(release).toHaveBeenCalledTimes(1);
- expect(maker.createSession).toHaveBeenCalledWith(expect.objectContaining({
- effort: axes.effort ?? undefined, fastMode: axes.fastMode, providerId: 'selected',
- }));
+ expect(maker.createSession).toHaveBeenCalledWith(
+ expect.objectContaining({
+ effort: axes.effort ?? undefined,
+ fastMode: axes.fastMode,
+ providerId: 'selected',
+ }),
+ );
h.setEffort.mockClear();
mocks.setSessionFastMode.mockClear();
await queue.accept();
- if (axes.agentKind === 'pi') expect(mocks.setSessionFastMode).toHaveBeenLastCalledWith(SESSION_ID, axes.fastMode);
+ if (axes.agentKind === 'pi')
+ expect(mocks.setSessionFastMode).toHaveBeenLastCalledWith(SESSION_ID, axes.fastMode);
else expect(setFastMode).toHaveBeenLastCalledWith(axes.fastMode);
expect(mocks.setSessionEffort).toHaveBeenLastCalledWith(SESSION_ID, axes.effort);
if (axes.effort) expect(h.setEffort).toHaveBeenLastCalledWith(axes.effort);
else expect(h.setEffort).not.toHaveBeenCalled();
expect(mocks.backfillSessionMeta.mock.calls.at(-1)?.[2]).toMatchObject({
- effort: axes.effort ?? undefined, fastMode: axes.fastMode, providerId: 'selected',
+ effort: axes.effort ?? undefined,
+ fastMode: axes.fastMode,
+ providerId: 'selected',
});
await vi.waitFor(() => expect(h.listenerCount()).toBe(1));
h.emit({ type: 'done', data: {}, source: 'pi' });
@@ -545,20 +606,37 @@ describe('MakerScheduleRunner queued dispatch (busy bound session)', () => {
});
it.each(['harness-changed', 'effort-failed', 'fast-failed'] as const)(
- 'blocks queued dispatch if the resolved selection cannot be honored (%s)', async (failure) => {
+ 'blocks queued dispatch if the resolved selection cannot be honored (%s)',
+ async (failure) => {
const h = createSessionHarness(async () => ({ accepted: true }));
const setFastMode = vi.fn(async () => {});
Object.assign(h.session, { agentKind: 'codex', model: 'shared-model', setFastMode });
mocks.getSessionProvider.mockReturnValue('selected');
const queue = createQueueHarness({ busy: false });
const { runner } = createRunnerHarness(h.session, queue.deps, {
- metaModel: 'shared-model', metaEffort: 'high',
- acquirePendingAgentSwitch: async () => ({ release: vi.fn(), selection: {
- agentKind: 'codex', model: 'shared-model', providerId: 'selected', effort: 'high', fastMode: false,
- } }),
+ metaModel: 'shared-model',
+ metaEffort: 'high',
+ acquirePendingAgentSwitch: async () => ({
+ release: vi.fn(),
+ selection: {
+ agentKind: 'codex',
+ model: 'shared-model',
+ providerId: 'selected',
+ effort: 'high',
+ fastMode: false,
+ },
+ }),
});
- const fire = runner.fire(heartbeatSchedule({ agentKind: 'codex', modelAgentKind: 'codex',
- model: 'shared-model', effort: 'ultra', fastMode: true }), createFireContext());
+ const fire = runner.fire(
+ heartbeatSchedule({
+ agentKind: 'codex',
+ modelAgentKind: 'codex',
+ model: 'shared-model',
+ effort: 'ultra',
+ fastMode: true,
+ }),
+ createFireContext(),
+ );
const result = fire.catch((error: unknown) => error);
await vi.waitFor(() => expect(queue.enqueueCalls).toHaveLength(1));
if (failure === 'harness-changed') Object.assign(h.session, { agentKind: 'pi' });
@@ -571,37 +649,58 @@ describe('MakerScheduleRunner queued dispatch (busy bound session)', () => {
},
);
- it.each(['permission', 'plan', 'switching', 'missing', 'replaced'])('defers queued routine acceptance after %s changes and runs with a fresh snapshot', async (change) => {
- const h = createSessionHarness(async () => ({ accepted: true }));
- const queue = createQueueHarness({ busy: true });
- const f = createRunnerHarness(h.session, queue.deps);
- const ctx = { ...createFireContext(), deferToCaller: true };
- const fire = f.runner.fire(heartbeatSchedule({ source: 'bot', manual: true }), ctx);
- await vi.waitFor(() => expect(queue.enqueueCalls).toHaveLength(1));
- const queuedPermissions = { permissionMode: change === 'permission' || change === 'replaced' ? 'bypassPermissions' : 'ask', planMode: false };
- const currentPlan = change === 'plan';
- mocks.getSessionFsSnapshot.mockResolvedValue(change === 'missing' ? null : { permissionMode: 'ask', planModeEnabled: currentPlan });
- if (change === 'switching') Object.assign(h.session, { stablePermissionModeState: null });
- let acceptedSession = h;
- if (change === 'replaced') {
- acceptedSession = createSessionHarness(async () => ({ accepted: true }));
- f.replaceLiveSession(acceptedSession.session);
- }
- await queue.accept(queuedPermissions);
- expect(await fire).toMatchObject({ deferred: true });
- expect(acceptedSession.session.abort).toHaveBeenCalledOnce();
- expect(ctx.onTurnActive).not.toHaveBeenCalled();
- expect(f.notifier.notify).not.toHaveBeenCalled();
- expect(acceptedSession.listenerCount()).toBe(0);
-
- Object.assign(acceptedSession.session, { stablePermissionModeState: { mode: 'ask', generation: 1 } });
- mocks.getSessionFsSnapshot.mockResolvedValue({ permissionMode: 'ask', planModeEnabled: currentPlan });
- const retry = f.runner.fire(heartbeatSchedule({ source: 'bot', manual: true }), { ...createFireContext(), deferToCaller: true });
- await vi.waitFor(() => expect(queue.enqueueCalls).toHaveLength(2));
- await queue.accept({ permissionMode: 'ask', planMode: currentPlan });
- acceptedSession.emit({ type: 'done', data: {}, turnOrigin: SCHEDULER_TURN_ORIGIN } as AgentEvent);
- expect(await retry).not.toMatchObject({ deferred: true });
- });
+ it.each(['permission', 'plan', 'switching', 'missing', 'replaced'])(
+ 'defers queued routine acceptance after %s changes and runs with a fresh snapshot',
+ async (change) => {
+ const h = createSessionHarness(async () => ({ accepted: true }));
+ const queue = createQueueHarness({ busy: true });
+ const f = createRunnerHarness(h.session, queue.deps);
+ const ctx = { ...createFireContext(), deferToCaller: true };
+ const fire = f.runner.fire(heartbeatSchedule({ source: 'bot', manual: true }), ctx);
+ await vi.waitFor(() => expect(queue.enqueueCalls).toHaveLength(1));
+ const queuedPermissions = {
+ permissionMode:
+ change === 'permission' || change === 'replaced' ? 'bypassPermissions' : 'ask',
+ planMode: false,
+ };
+ const currentPlan = change === 'plan';
+ mocks.getSessionFsSnapshot.mockResolvedValue(
+ change === 'missing' ? null : { permissionMode: 'ask', planModeEnabled: currentPlan },
+ );
+ if (change === 'switching') Object.assign(h.session, { stablePermissionModeState: null });
+ let acceptedSession = h;
+ if (change === 'replaced') {
+ acceptedSession = createSessionHarness(async () => ({ accepted: true }));
+ f.replaceLiveSession(acceptedSession.session);
+ }
+ await queue.accept(queuedPermissions);
+ expect(await fire).toMatchObject({ deferred: true });
+ expect(acceptedSession.session.abort).toHaveBeenCalledOnce();
+ expect(ctx.onTurnActive).not.toHaveBeenCalled();
+ expect(f.notifier.notify).not.toHaveBeenCalled();
+ expect(acceptedSession.listenerCount()).toBe(0);
+
+ Object.assign(acceptedSession.session, {
+ stablePermissionModeState: { mode: 'ask', generation: 1 },
+ });
+ mocks.getSessionFsSnapshot.mockResolvedValue({
+ permissionMode: 'ask',
+ planModeEnabled: currentPlan,
+ });
+ const retry = f.runner.fire(heartbeatSchedule({ source: 'bot', manual: true }), {
+ ...createFireContext(),
+ deferToCaller: true,
+ });
+ await vi.waitFor(() => expect(queue.enqueueCalls).toHaveLength(2));
+ await queue.accept({ permissionMode: 'ask', planMode: currentPlan });
+ acceptedSession.emit({
+ type: 'done',
+ data: {},
+ turnOrigin: SCHEDULER_TURN_ORIGIN,
+ } as AgentEvent);
+ expect(await retry).not.toMatchObject({ deferred: true });
+ },
+ );
it('defers a queued routine when its live session disappears before acceptance', async () => {
const h = createSessionHarness(async () => ({ accepted: true }));
@@ -634,63 +733,71 @@ describe('MakerScheduleRunner queued dispatch (busy bound session)', () => {
expect(f.notifier.notify).not.toHaveBeenCalled();
});
- it.each(['user', 'bot'] as const)('%s enqueues without direct send and preserves routine plan mode', async (source) => {
- const harness = createSessionHarness(async () => ({ accepted: true }));
- const queue = createQueueHarness({ busy: true });
- const { runner, notifier } = createRunnerHarness(harness.session, queue.deps);
+ it.each(['user', 'bot'] as const)(
+ '%s enqueues without direct send and preserves routine plan mode',
+ async (source) => {
+ const harness = createSessionHarness(async () => ({ accepted: true }));
+ const queue = createQueueHarness({ busy: true });
+ const { runner, notifier } = createRunnerHarness(harness.session, queue.deps);
- const firePromise = runner.fire(heartbeatSchedule({ source }), createFireContext());
+ const firePromise = runner.fire(heartbeatSchedule({ source }), createFireContext());
- // 入队参数:发送正文带静默协议后缀,落库/展示用原始 prompt,origin=scheduler。
- await vi.waitFor(() => expect(queue.enqueueCalls.length).toBe(1));
- const req = queue.enqueueCalls[0]!;
- expect(req.sessionId).toBe(SESSION_ID);
- expect(req.text).toContain('PR #971 heartbeat prompt');
- expect(req.text).toContain('[Silent scheduled run]');
- expect(req.inheritTargetPlanMode).toBe(source === 'bot' ? true : undefined);
- expect(req.persistedContent).toContain('PR #971 heartbeat prompt');
- if (source === 'user') expect(req.persistedContent).toBe('PR #971 heartbeat prompt');
- else expect(req.persistedContent).not.toBe('PR #971 heartbeat prompt');
- expect(req.origin).toEqual({
- kind: 'scheduler',
- scheduleId: 'schedule-hb',
- scheduleName: 'PR #971 心跳',
- runId: 'run-q1',
- });
- // 不直发、不自行落库(coordinator drain 负责)。
- expect(harness.send).not.toHaveBeenCalled();
- expect(mocks.createMessage).not.toHaveBeenCalled();
- // 排队等待仍属于当前 Desktop turn,不能被未来的 scheduler turn
- // 提前标成 headless,否则当前 turn 的插件设置卡会被错误抑制。
- expect(isHeadlessGhostSetupTurn(SESSION_ID)).toBe(false);
+ // 入队参数:发送正文带 firedAt 上下文与静默协议后缀,落库/展示用原始
+ // prompt,origin=scheduler。
+ await vi.waitFor(() => expect(queue.enqueueCalls.length).toBe(1));
+ const req = queue.enqueueCalls[0]!;
+ 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('firedAtEpochMs: 1700000000100');
+ expect(req.text).toContain('firedAtUtc: 2023-11-14T22:13:20.100Z');
+ expect(req.text).toContain('firedAtInScheduleTimezone: 2023-11-15T06:13:20[Asia/Hong_Kong]');
+ expect(req.text).toContain('[Silent scheduled run]');
+ expect(req.inheritTargetPlanMode).toBe(source === 'bot' ? true : undefined);
+ expect(req.persistedContent).toContain('PR #971 heartbeat prompt');
+ if (source === 'user') expect(req.persistedContent).toBe('PR #971 heartbeat prompt');
+ else expect(req.persistedContent).not.toBe('PR #971 heartbeat prompt');
+ expect(req.origin).toEqual({
+ kind: 'scheduler',
+ scheduleId: 'schedule-hb',
+ scheduleName: 'PR #971 心跳',
+ runId: 'run-q1',
+ });
+ // 不直发、不自行落库(coordinator drain 负责)。
+ expect(harness.send).not.toHaveBeenCalled();
+ expect(mocks.createMessage).not.toHaveBeenCalled();
+ // 排队等待仍属于当前 Desktop turn,不能被未来的 scheduler turn
+ // 提前标成 headless,否则当前 turn 的插件设置卡会被错误抑制。
+ expect(isHeadlessGhostSetupTurn(SESSION_ID)).toBe(false);
- // 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({
- type: 'text',
- data: { text: 'heartbeat summary', isFinal: true },
- source: 'claude-code',
- });
- harness.emit({ type: 'done', data: {}, source: 'claude-code' });
+ // 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({
+ type: 'text',
+ data: { text: 'heartbeat summary', isFinal: true },
+ source: 'claude-code',
+ });
+ harness.emit({ type: 'done', data: {}, source: 'claude-code' });
- const result = await firePromise;
- expect(result.sessionId).toBe(SESSION_ID);
- expect(result.resultText).toBe('heartbeat summary');
- // 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' });
- });
+ const result = await firePromise;
+ expect(result.sessionId).toBe(SESSION_ID);
+ expect(result.resultText).toBe('heartbeat summary');
+ // 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' });
+ },
+ );
it('ignores events from a user turn or a different scheduler run', async () => {
const harness = createSessionHarness(async () => ({ accepted: true }));
@@ -1451,19 +1558,22 @@ describe('MakerScheduleRunner queued dispatch (busy bound session)', () => {
expect(harness.send).not.toHaveBeenCalled();
});
- it.each([false, true])('manual busy dispatch defers only when the caller owns retries: %s', async (deferToCaller) => {
- const harness = createSessionHarness(async () => ({ accepted: true }));
- const queue = createQueueHarness({ busy: true, hasQueued: true });
- const { runner } = createRunnerHarness(harness.session, queue.deps);
- const result = runner.fire(
- heartbeatSchedule({ manual: true, source: 'bot' }),
- { ...createFireContext(), deferToCaller },
- );
- if (deferToCaller) await expect(result).resolves.toMatchObject({ deferred: true });
- else await expect(result).rejects.toThrow('HEARTBEAT_ALREADY_QUEUED');
- expect(queue.enqueueCalls).toHaveLength(0);
- expect(harness.send).not.toHaveBeenCalled();
- });
+ it.each([false, true])(
+ 'manual busy dispatch defers only when the caller owns retries: %s',
+ async (deferToCaller) => {
+ const harness = createSessionHarness(async () => ({ accepted: true }));
+ const queue = createQueueHarness({ busy: true, hasQueued: true });
+ const { runner } = createRunnerHarness(harness.session, queue.deps);
+ const result = runner.fire(heartbeatSchedule({ manual: true, source: 'bot' }), {
+ ...createFireContext(),
+ deferToCaller,
+ });
+ if (deferToCaller) await expect(result).resolves.toMatchObject({ deferred: true });
+ else await expect(result).rejects.toThrow('HEARTBEAT_ALREADY_QUEUED');
+ expect(queue.enqueueCalls).toHaveLength(0);
+ expect(harness.send).not.toHaveBeenCalled();
+ },
+ );
it('settles the run as aborted-style failure when the queued prompt is discarded', async () => {
const harness = createSessionHarness(async () => ({ accepted: true }));
@@ -1820,7 +1930,9 @@ describe('MakerScheduleRunner queued dispatch (busy bound session)', () => {
await vi.waitFor(() => expect(queue.enqueueCalls.length).toBe(1));
await queue.accept();
- await expect(firePromise).rejects.toThrow(/requires SuperGrok \(xAI\) or an explicitly selected custom source/);
+ await expect(firePromise).rejects.toThrow(
+ /requires SuperGrok \(xAI\) or an explicitly selected custom source/,
+ );
await expect(firePromise).rejects.not.toThrow(/disabled in settings/);
await expect(firePromise).rejects.toThrow(/\(exclusive-source-unavailable\)/);
});
diff --git a/apps/desktop/src/main/scheduler-host/__tests__/runnerSilentNotify.test.ts b/apps/desktop/src/main/scheduler-host/__tests__/runnerSilentNotify.test.ts
index 1ba3e58325..3d3f07a4f1 100644
--- a/apps/desktop/src/main/scheduler-host/__tests__/runnerSilentNotify.test.ts
+++ b/apps/desktop/src/main/scheduler-host/__tests__/runnerSilentNotify.test.ts
@@ -1,19 +1,9 @@
import { describe, expect, it, vi, beforeEach } from 'vitest';
-import type {
- AgentEvent,
- Maker,
- Session,
- SessionSendResult,
-} from '@cindy/maker-core';
+import type { AgentEvent, Maker, Session, 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,
- Notifier,
- Schedule,
-} from '@cindy/maker-scheduler';
+import type { FireContext, Logger, Notifier, Schedule } from '@cindy/maker-scheduler';
const mocks = vi.hoisted(() => ({
createMessage: vi.fn(),
@@ -166,10 +156,7 @@ function acceptingSend(): SendImpl {
};
}
-async function fireToCompletion(
- runner: MakerScheduleRunner,
- h: FakeSessionHarness,
-): Promise<void> {
+async function fireToCompletion(runner: MakerScheduleRunner, h: FakeSessionHarness): Promise<void> {
const firePromise = runner.fire(baseSchedule(), createFireContext());
await vi.waitFor(() => {
expect(mocks.createMessage).toHaveBeenCalled();
@@ -258,10 +245,7 @@ describe('MakerScheduleRunner silent-run notification skip', () => {
notifyImpl: async (_schedule, run) => (run.id === 'run-a' ? notifyA : notifyB),
});
- const fireA = runner.fire(
- baseSchedule({ id: 'schedule-a' }),
- createFireContext('run-a'),
- );
+ 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(() =>
@@ -273,10 +257,7 @@ describe('MakerScheduleRunner silent-run notification skip', () => {
// 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'),
- );
+ 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(() =>
@@ -316,10 +297,7 @@ describe('MakerScheduleRunner silent-run notification skip', () => {
notifyImpl: async (_schedule, run) => (run.id === 'run-a' ? notifyA : undefined),
});
- const fireA = runner.fire(
- baseSchedule({ id: 'schedule-a' }),
- createFireContext('run-a'),
- );
+ 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(() =>
@@ -329,10 +307,7 @@ describe('MakerScheduleRunner silent-run notification skip', () => {
),
);
- const fireB = runner.fire(
- baseSchedule({ id: 'schedule-b' }),
- createFireContext('run-b'),
- );
+ const fireB = runner.fire(baseSchedule({ id: 'schedule-b' }), createFireContext('run-b'));
await vi.waitFor(() =>
expect(setVendorOptions).toHaveBeenCalledWith({
[SCHEDULER_RUN_ID_VENDOR_OPTION]: 'run-b',
@@ -353,14 +328,11 @@ describe('MakerScheduleRunner silent-run notification skip', () => {
expect(h.vendorOptions[SCHEDULER_RUN_ID_VENDOR_OPTION]).toBeUndefined();
});
- it('silentWhenIdle=true → 发送隐藏主动上报协议,落库仍保留原始 prompt', async () => {
+ it('每轮发送权威 firedAt 上下文,静默任务再追加主动上报协议,落库仍保留原始 prompt', async () => {
const h = createSessionHarness(acceptingSend());
const { runner } = createRunnerHarness(h.session, { silenced: false });
- const firePromise = runner.fire(
- baseSchedule({ silentWhenIdle: true }),
- createFireContext(),
- );
+ const firePromise = runner.fire(baseSchedule({ silentWhenIdle: true }), createFireContext());
await vi.waitFor(() => {
expect(mocks.createMessage).toHaveBeenCalled();
});
@@ -371,6 +343,14 @@ describe('MakerScheduleRunner silent-run notification skip', () => {
content: string;
};
expect(sent.content.startsWith('check the PR status')).toBe(true);
+ expect(sent.content).toContain('[Scheduled run context]');
+ expect(sent.content).toContain('firedAtEpochMs: 1700000000100');
+ expect(sent.content).toContain('firedAtUtc: 2023-11-14T22:13:20.100Z');
+ expect(sent.content).toContain('firedAtInScheduleTimezone: 2023-11-15T06:13:20[Asia/Shanghai]');
+ expect(sent.content).toContain(
+ 'Use the task instructions to determine the requested time range.',
+ );
+ expect(sent.content).not.toContain('outside this run');
expect(sent.content).toContain('schedule_notify_current_run');
expect(sent.content).toContain('Successful runs do not notify by default');
expect(sent.content).toContain('call_tool');
@@ -380,7 +360,7 @@ describe('MakerScheduleRunner silent-run notification skip', () => {
expect(body.content).toBe('check the PR status');
});
- it('silentWhenIdle=false → prompt 原样,不注入协议', async () => {
+ it('silentWhenIdle=false → 仍注入 firedAt 上下文,但不注入静默协议', async () => {
const h = createSessionHarness(acceptingSend());
const { runner } = createRunnerHarness(h.session, { silenced: false });
@@ -389,7 +369,44 @@ describe('MakerScheduleRunner silent-run notification skip', () => {
const sent = (h.session.send as ReturnType<typeof vi.fn>).mock.calls[0][0] as {
content: string;
};
- expect(sent.content).toBe('check the PR status');
+ expect(sent.content.startsWith('check the PR status')).toBe(true);
+ expect(sent.content).toContain('[Scheduled run context]');
+ expect(sent.content).toContain('firedAtEpochMs: 1700000000100');
+ expect(sent.content).not.toContain('[Silent scheduled run]');
+ const [, body] = mocks.createMessage.mock.calls[0];
+ expect(body.content).toBe('check the PR status');
+ });
+
+ it('successive runs retain their own trigger time across Auckland DST and a UTC date boundary', async () => {
+ const h = createSessionHarness(acceptingSend());
+ const { runner } = createRunnerHarness(h.session, { silenced: false });
+ const schedule = baseSchedule({
+ timezone: 'Pacific/Auckland',
+ prompt: 'Find appointments for the next seven days',
+ });
+ const cases = [
+ ['2026-09-26T12:00:00.000Z', '2026-09-27T00:00:00[Pacific/Auckland]'],
+ ['2026-09-26T13:59:59.123Z', '2026-09-27T01:59:59[Pacific/Auckland]'],
+ ['2026-09-26T14:00:00.456Z', '2026-09-27T03:00:00[Pacific/Auckland]'],
+ ];
+ for (const [index, [utc, local]] of cases.entries()) {
+ const fire = runner.fire(schedule, {
+ ...createFireContext(`run-${index}`),
+ firedAt: Date.parse(utc),
+ });
+ await vi.waitFor(() => expect(mocks.createMessage).toHaveBeenCalledTimes(index + 1));
+ h.emit({ type: 'done', data: {} });
+ await fire;
+ const sent = (h.session.send as ReturnType<typeof vi.fn>).mock.calls[index][0] as {
+ content: string;
+ };
+ expect(sent.content).toContain(`firedAtEpochMs: ${Date.parse(utc)}`);
+ expect(sent.content).toContain(`firedAtUtc: ${utc}`);
+ expect(sent.content).toContain(`firedAtInScheduleTimezone: ${local}`);
+ expect(sent.content.startsWith(schedule.prompt)).toBe(true);
+ expect(sent.content).not.toContain('authoritative endpoint');
+ expect(mocks.createMessage.mock.calls[index][1].content).toBe(schedule.prompt);
+ }
});
it('failed + silenced → 仍然通知(fail-safe,异常必须可见)', async () => {
@@ -450,7 +467,10 @@ describe('MakerScheduleRunner silent-run notification skip', () => {
// 投递卡住:此刻若还没认领,就存在竞态窗口
let releaseNotify!: () => void;
notifier.notify.mockImplementationOnce(
- () => new Promise<void>((resolve) => { releaseNotify = resolve; }),
+ () =>
+ new Promise<void>((resolve) => {
+ releaseNotify = resolve;
+ }),
);
const firePromise = runner.fire(baseSchedule(), ctx);
diff --git a/apps/desktop/src/main/scheduler-host/runner.ts b/apps/desktop/src/main/scheduler-host/runner.ts
index a7848cd6ec..851cd1ccb3 100644
--- a/apps/desktop/src/main/scheduler-host/runner.ts
+++ b/apps/desktop/src/main/scheduler-host/runner.ts
@@ -1,4 +1,8 @@
-import { ScheduledModelSelectionBusyError, type ScheduledModelSelection, type ScheduledModelSelectionLease } from '../maker-ipc/scheduledModelSelection';
+import {
+ ScheduledModelSelectionBusyError,
+ type ScheduledModelSelection,
+ type ScheduledModelSelectionLease,
+} from '../maker-ipc/scheduledModelSelection';
import { UI_ACTION_TRIGGER_PREFIX } from '../../shared/interruptedTurn.js';
import { routinePermissionSnapshot } from './routinePermission.js';
/**
@@ -63,7 +67,11 @@ import type {
} from '@cindy/maker-scheduler';
import { createMessage } from '../localDb/ipc/messages.js';
-import { getSessionRowSnapshot, getSessionFsSnapshot, touchUserSendInDb } from '../localDb/ipc/sessions.js';
+import {
+ getSessionRowSnapshot,
+ getSessionFsSnapshot,
+ touchUserSendInDb,
+} from '../localDb/ipc/sessions.js';
import {
getSessionProvider,
setSessionProvider,
@@ -210,7 +218,10 @@ export interface SchedulerQueueDeps {
persistedContent: string;
inheritTargetPlanMode?: boolean;
origin: { kind: 'scheduler'; scheduleId: string; scheduleName: string; runId: string };
- onAccepted: (queuedPermissions?: { permissionMode?: string; planMode?: boolean }) => void | Promise<void>;
+ onAccepted: (queuedPermissions?: {
+ permissionMode?: string;
+ planMode?: boolean;
+ }) => void | Promise<void>;
onAcceptedRollback?: () => void | Promise<void>;
onDiscarded?: () => void;
}): Promise<{ clientId: string } | { duplicate: true } | { retry: true }>;
@@ -224,11 +235,7 @@ export interface SchedulerQueueDeps {
/** 普通聊天自动续跑是否已接管当前 scheduler run。 */
isAutoResumePending?: (sessionId: string, runId: string) => boolean;
/** 已接管的续跑最终仍失败(含补发未 dispatch / Stop / clear)。 */
- onAutoResumeFailed?: (
- sessionId: string,
- runId: string,
- listener: () => void,
- ) => () => void;
+ onAutoResumeFailed?: (sessionId: string, runId: string, listener: () => void) => () => void;
/** Schedule pause/delete:撤销仍属于该 run 的退避或派发前隐藏续跑。 */
cancelAutoResume?: (sessionId: string, runId: string) => void;
}
@@ -244,7 +251,11 @@ export interface MakerScheduleRunnerDeps {
* 锁住 heartbeat session、落实 deferred switch 并 bootstrap 新 live session。
* runner 在 Session.send 返回后 release。
*/
- acquirePendingAgentSwitch?: (sessionId: string, signal?: AbortSignal, selection?: ScheduledModelSelection) => Promise<(() => void) | ScheduledModelSelectionLease>;
+ acquirePendingAgentSwitch?: (
+ sessionId: string,
+ signal?: AbortSignal,
+ selection?: ScheduledModelSelection,
+ ) => Promise<(() => void) | ScheduledModelSelectionLease>;
/** Resolve the same provider-specific snapshot for fresh explicit choices. */
resolveModelSelection?: (selection: ScheduledModelSelection) => Promise<ScheduledModelSelection>;
/** 新建可见会话落库后通知本机窗口与 device-link 列表订阅者。 */
@@ -672,11 +683,16 @@ export class MakerScheduleRunner implements ScheduleRunner {
// 直发路径不经过 makerSendTransaction。先落实 pending switch,再读取 meta/row,
// 才能让本轮 createSession 与 send 都指向切换后的 live engine。
throwIfFireAborted(ctx.signal, 'credential switch setup');
- const selection: ScheduledModelSelection | undefined = schedule.modelAgentKind && schedule.model?.trim()
- ? { agentKind: schedule.modelAgentKind, model: schedule.model,
- providerId: schedule.providerId?.trim() || null,
- effort: (schedule.effort as Effort | undefined) ?? null, fastMode: schedule.fastMode === true }
- : undefined;
+ const selection: ScheduledModelSelection | undefined =
+ schedule.modelAgentKind && schedule.model?.trim()
+ ? {
+ agentKind: schedule.modelAgentKind,
+ model: schedule.model,
+ providerId: schedule.providerId?.trim() || null,
+ effort: (schedule.effort as Effort | undefined) ?? null,
+ fastMode: schedule.fastMode === true,
+ }
+ : undefined;
if (selection && this.deps.schedulerQueue?.isSessionBusy(sessionId)) {
return this.failOrDeferSessionRunning(schedule, ctx, sessionId, true);
}
@@ -689,11 +705,17 @@ export class MakerScheduleRunner implements ScheduleRunner {
: this.deps.acquirePendingAgentSwitch?.(sessionId, ctx.signal));
holder.releaseAgentSwitchLock = typeof lease === 'function' ? lease : lease?.release;
if (selection) {
- if (!lease || typeof lease === 'function') throw new Error('Scheduled model selection was not resolved');
+ if (!lease || typeof lease === 'function')
+ throw new Error('Scheduled model selection was not resolved');
resolvedSelection = lease.selection;
- schedule = { ...schedule, agentKind: resolvedSelection.agentKind,
- model: resolvedSelection.model, providerId: resolvedSelection.providerId ?? undefined,
- effort: resolvedSelection.effort ?? undefined, fastMode: resolvedSelection.fastMode };
+ schedule = {
+ ...schedule,
+ agentKind: resolvedSelection.agentKind,
+ model: resolvedSelection.model,
+ providerId: resolvedSelection.providerId ?? undefined,
+ effort: resolvedSelection.effort ?? undefined,
+ fastMode: resolvedSelection.fastMode,
+ };
}
} catch (error) {
if (error instanceof ScheduledModelSelectionBusyError) {
@@ -864,9 +886,11 @@ export class MakerScheduleRunner implements ScheduleRunner {
// 都空时按 agentKind 兜底 (与 renderer schedulerFallbackModel 同源),
// 不留空字符串 — UI picker 显示 placeholder。
// 普通 schedule 沿用既有默认权限;伙伴例行任务继承当前伙伴的权限和计划模式。
- const effectiveAgentKind = resolvedSelection?.agentKind ?? (isHeartbeat
- ? (heartbeatAgentKind ?? schedule.agentKind)
- : (schedule.modelAgentKind ?? schedule.agentKind));
+ const effectiveAgentKind =
+ resolvedSelection?.agentKind ??
+ (isHeartbeat
+ ? (heartbeatAgentKind ?? schedule.agentKind)
+ : (schedule.modelAgentKind ?? schedule.agentKind));
const rawModel = schedule.model?.trim()
? schedule.model
: isHeartbeat
@@ -887,10 +911,8 @@ export class MakerScheduleRunner implements ScheduleRunner {
} | null = null;
if (!modelHint && effectiveAgentKind === 'pi') {
dynamicDefaultRoute =
- (await this.deps.resolveDefaultModelRoute?.(
- effectiveAgentKind,
- defaultRouteProviderId,
- )) ?? null;
+ (await this.deps.resolveDefaultModelRoute?.(effectiveAgentKind, defaultRouteProviderId)) ??
+ null;
} else if (shouldMaterializeFreshClaudeProvider) {
dynamicDefaultRoute =
(await this.deps.resolveDefaultModelRoute?.(
@@ -918,7 +940,8 @@ export class MakerScheduleRunner implements ScheduleRunner {
const materializedDefaultProviderId = shouldMaterializeFreshClaudeProvider
? (dynamicDefaultRoute?.providerId ?? null)
: null;
- let routinePermissions = schedule.source === 'bot' ? await this.readRoutinePermissions(sessionId) : null;
+ let routinePermissions =
+ schedule.source === 'bot' ? await this.readRoutinePermissions(sessionId) : null;
if (schedule.source === 'bot' && !routinePermissions)
return this.deferFire(schedule, sessionId, 'routine-permission-unavailable');
// fastMode 对 Codex / Pi 生效(claude-code agent 忽略此字段);Claude 恒不传,
@@ -951,16 +974,25 @@ export class MakerScheduleRunner implements ScheduleRunner {
}
}
if (!isHeartbeat && schedule.modelAgentKind && !resolvedSelection) {
- if (!this.deps.resolveModelSelection) throw new Error('Scheduled model selection is not available');
+ if (!this.deps.resolveModelSelection)
+ throw new Error('Scheduled model selection is not available');
resolvedSelection = await this.deps.resolveModelSelection({
- agentKind: effectiveAgentKind, model, providerId: createProviderId,
- effort: (schedule.effort as Effort | undefined) ?? null, fastMode: fastMode === true,
+ agentKind: effectiveAgentKind,
+ model,
+ providerId: createProviderId,
+ effort: (schedule.effort as Effort | undefined) ?? null,
+ fastMode: fastMode === true,
});
createProviderId = resolvedSelection.providerId;
fastMode = resolvedSelection.fastMode;
- schedule = { ...schedule, agentKind: resolvedSelection.agentKind,
- model: resolvedSelection.model, providerId: resolvedSelection.providerId ?? undefined,
- effort: resolvedSelection.effort ?? undefined, fastMode: resolvedSelection.fastMode };
+ schedule = {
+ ...schedule,
+ agentKind: resolvedSelection.agentKind,
+ model: resolvedSelection.model,
+ providerId: resolvedSelection.providerId ?? undefined,
+ effort: resolvedSelection.effort ?? undefined,
+ fastMode: resolvedSelection.fastMode,
+ };
}
// issue #456:未门控入口(定时任务 fire)按所选模型自报的 supported efforts 把 effort
// clamp 到最高兼容档,避免把模型不支持的档(如 gpt-5.5 + max/ultra)透给上游被拒。
@@ -968,16 +1000,13 @@ export class MakerScheduleRunner implements ScheduleRunner {
// 只影响本次 fire 的运行值(该模型日后支持该档时自动生效)。直发 / 排队两路径共用
// reconcileEffortForModel(见其注释),口径一致;lookup 失败不阻断 headless 运行。
if (resolvedSelection && createProviderId !== resolvedSelection.providerId) {
- throw new Error('Scheduled model route changed after selection; retry with the current catalog');
+ throw new Error(
+ 'Scheduled model route changed after selection; retry with the current catalog',
+ );
}
let reconciledEffort = resolvedSelection
- ? resolvedSelection.effort ?? undefined
- : this.reconcileEffortForModel(
- effectiveAgentKind,
- model,
- schedule.effort,
- schedule.id,
- );
+ ? (resolvedSelection.effort ?? undefined)
+ : this.reconcileEffortForModel(effectiveAgentKind, model, schedule.effort, schedule.id);
// 隐式改道后的来源级 reconcile(PR #744 review 第二十七轮):上面的 clamp 用的是
// merged capability,分辨不出来源差异 —— 改道后的落地拷贝 effort 支持可能更窄、
// 可能不支持 Fast,原样透传会被上游拒。按 (verdict.providerId, model) 的拷贝重查:
@@ -1145,7 +1174,8 @@ export class MakerScheduleRunner implements ScheduleRunner {
throwIfFireAborted(ctx.signal, 'session creation');
if (schedule.source === 'bot') {
routinePermissions = await this.readRoutinePermissions(sessionId);
- if (!routinePermissions) return this.deferFire(schedule, sessionId, 'routine-permission-unavailable');
+ if (!routinePermissions)
+ return this.deferFire(schedule, sessionId, 'routine-permission-unavailable');
throwIfFireAborted(ctx.signal, 'session creation');
}
let session: Awaited<ReturnType<Maker['createSession']>>;
@@ -1249,7 +1279,7 @@ export class MakerScheduleRunner implements ScheduleRunner {
throw new Error('Scheduled model selection did not reach the live session');
}
const desiredEffort = resolvedSelection
- ? resolvedSelection.effort ?? undefined
+ ? (resolvedSelection.effort ?? undefined)
: schedule.effort || heartbeatEffort;
// runtimeModel===model 且未走 follow(desiredEffort===schedule.effort)时直接复用上方
// createSession 已算好的 reconciledEffort,不重复 lookup / 不重复打 reconcile 日志。
@@ -1281,7 +1311,8 @@ export class MakerScheduleRunner implements ScheduleRunner {
// 仅当 fresh 且要落的档 == createSession 已应用的档时,setEffort 只是幂等兜底,失败可照常落库。
if (reusedLiveSession || runtimeReconciledEffort !== reconciledEffort)
effortSwitchApplied = false;
- if (resolvedSelection) throw new Error('Scheduled effort selection could not be applied', { cause: err });
+ if (resolvedSelection)
+ throw new Error('Scheduled effort selection could not be applied', { cause: err });
this.deps.logger.warn?.('[runner] heartbeat setEffort failed (non-fatal)', err);
}
}
@@ -1463,11 +1494,10 @@ export class MakerScheduleRunner implements ScheduleRunner {
// 6. send 并在 onAccepted 中落库 user prompt(不要 close session)。
// onAccepted 失败表示产品层输入没有完成接受,必须按 pre-dispatch failure 收口,
// 不继续等待 terminal event,避免无人值守 run 永久挂起。
- // 静默运行:成功 run 默认已由 scheduler 标记为静默;这里只给 agent 一条隐藏协议,
- // 告知"有事才主动上报"。落库仍保留用户原始 prompt,避免运行历史暴露工具协议。
- const promptToSend = schedule.silentWhenIdle
- ? `${schedule.prompt}${buildSilentRunInstruction()}`
- : schedule.prompt;
+ // 每轮都把 ctx.firedAt 作为隐藏运行上下文交给 agent,避免模型拿会话 current_date
+ // 覆盖调度器已经落定的时间窗口。静默协议按任务配置追加;落库仍只保留用户原始
+ // prompt,避免运行历史暴露宿主协议。
+ const promptToSend = buildScheduledRunPrompt(schedule, ctx);
let sendError: string | undefined;
const sendContext = buildSchedulerSendContext(schedule, ctx, session.id);
const sendLogBase = {
@@ -1521,7 +1551,10 @@ export class MakerScheduleRunner implements ScheduleRunner {
`schedule route unavailable: ${describeModelRouteRejection(verdict.reason, runtimeModel, dispatchProviderId)} (${verdict.reason}, revalidated before dispatch)`,
);
}
- if (verdict.kind === 'reroute' && shouldApplyExclusiveProviderRerouteLive(dispatchProviderId)) {
+ if (
+ verdict.kind === 'reroute' &&
+ shouldApplyExclusiveProviderRerouteLive(dispatchProviderId)
+ ) {
// 晚到的隐式改道(createSession 之后目录才变)跨凭证形态时不能只热换
// provider store:进程是旧凭证形态 spawn 的,热换后这次 send 仍用旧凭证
// 下单或直接鉴权失败。需要关会话重建的组合按明确错误失败收口 —— 下一轮
@@ -1595,7 +1628,10 @@ export class MakerScheduleRunner implements ScheduleRunner {
await createMessage(session.id, {
clientId: randomUUID(),
role: 'user',
- content: schedule.source === 'bot' ? `${UI_ACTION_TRIGGER_PREFIX}${schedule.prompt}` : schedule.prompt,
+ content:
+ schedule.source === 'bot'
+ ? `${UI_ACTION_TRIGGER_PREFIX}${schedule.prompt}`
+ : schedule.prompt,
agentMeta: { origin },
});
} catch (err) {
@@ -1861,9 +1897,7 @@ export class MakerScheduleRunner implements ScheduleRunner {
): Promise<FireResult> {
const sq = this.deps.schedulerQueue;
if (!sq) throw new Error('fireHeartbeatViaQueue requires schedulerQueue dep');
- const promptToSend = schedule.silentWhenIdle
- ? `${schedule.prompt}${buildSilentRunInstruction()}`
- : schedule.prompt;
+ const promptToSend = buildScheduledRunPrompt(schedule, ctx);
const origin = {
kind: 'scheduler',
scheduleId: schedule.id,
@@ -1980,7 +2014,10 @@ export class MakerScheduleRunner implements ScheduleRunner {
sessionId,
text: promptToSend,
...(schedule.source === 'bot' ? { inheritTargetPlanMode: true } : {}),
- persistedContent: schedule.source === 'bot' ? `${UI_ACTION_TRIGGER_PREFIX}${schedule.prompt}` : schedule.prompt,
+ persistedContent:
+ schedule.source === 'bot'
+ ? `${UI_ACTION_TRIGGER_PREFIX}${schedule.prompt}`
+ : schedule.prompt,
origin,
onAccepted: async (queuedPermissions) => {
dispatched = true;
@@ -2036,10 +2073,12 @@ export class MakerScheduleRunner implements ScheduleRunner {
return;
}
if (!live) {
- const message = 'queued heartbeat live session unavailable before route sync and vendor dispatch';
- const unavailable = schedule.source === 'bot'
- ? new RoutineDispatchDeferredError(message)
- : new Error(message);
+ const message =
+ 'queued heartbeat live session unavailable before route sync and vendor dispatch';
+ const unavailable =
+ schedule.source === 'bot'
+ ? new RoutineDispatchDeferredError(message)
+ : new Error(message);
failAfterAccept(unavailable);
failDispatch(unavailable);
blockAcceptedDispatch(undefined, 'session unavailable for queued route sync');
@@ -2085,11 +2124,16 @@ export class MakerScheduleRunner implements ScheduleRunner {
}
if (schedule.source === 'bot') {
const permissions = await this.readRoutinePermissions(sessionId, live);
- if (!permissions || this.deps.maker.getSession(sessionId) !== live ||
+ if (
+ !permissions ||
+ this.deps.maker.getSession(sessionId) !== live ||
live.stablePermissionModeState?.mode !== permissions.permissionMode ||
queuedPermissions?.permissionMode !== permissions.permissionMode ||
- queuedPermissions?.planMode !== permissions.planMode) {
- const error = new RoutineDispatchDeferredError('Queued routine permissions changed before dispatch');
+ queuedPermissions?.planMode !== permissions.planMode
+ ) {
+ const error = new RoutineDispatchDeferredError(
+ 'Queued routine permissions changed before dispatch',
+ );
failAfterAccept(error);
failDispatch(error);
blockAcceptedDispatch(live, 'routine permissions changed');
@@ -2097,7 +2141,9 @@ export class MakerScheduleRunner implements ScheduleRunner {
}
}
if (ctx.canDispatch && !ctx.canDispatch()) {
- const error = new RoutineDispatchDeferredError('Routine revision changed before dispatch');
+ const error = new RoutineDispatchDeferredError(
+ 'Routine revision changed before dispatch',
+ );
failAfterAccept(error);
failDispatch(error);
blockAcceptedDispatch(live, 'routine revision changed');
@@ -2369,8 +2415,12 @@ export class MakerScheduleRunner implements ScheduleRunner {
}
const nextProviderId = applyProviderId ?? currentProviderId;
const resolvedSelection = baseline.resolvedSelection;
- if (resolvedSelection && (live.agentKind !== resolvedSelection.agentKind ||
- targetModel !== resolvedSelection.model || nextProviderId !== resolvedSelection.providerId)) {
+ if (
+ resolvedSelection &&
+ (live.agentKind !== resolvedSelection.agentKind ||
+ targetModel !== resolvedSelection.model ||
+ nextProviderId !== resolvedSelection.providerId)
+ ) {
throw new QueuedRouteDisabledError('Scheduled model route changed before queued dispatch');
}
if (
@@ -2397,8 +2447,7 @@ export class MakerScheduleRunner implements ScheduleRunner {
nextModel: live.model,
currentCodexProxyActive: live.codexProxyActive,
currentCodexThreadModelProviderId: live.codexThreadModelProviderId,
- currentCodexCindyRemoteCompactionCompatible:
- live.codexCindyRemoteCompactionCompatible,
+ currentCodexCindyRemoteCompactionCompatible: live.codexCindyRemoteCompactionCompatible,
})
) {
throw new QueuedCodexThreadIdentityMismatchError(
@@ -2415,12 +2464,13 @@ export class MakerScheduleRunner implements ScheduleRunner {
nextModel: targetModel,
currentCodexProxyActive: live.codexProxyActive,
currentCodexThreadModelProviderId: live.codexThreadModelProviderId,
- currentCodexCindyRemoteCompactionCompatible:
- live.codexCindyRemoteCompactionCompatible,
+ currentCodexCindyRemoteCompactionCompatible: live.codexCindyRemoteCompactionCompatible,
})
) {
if (resolvedSelection) {
- throw new QueuedRouteDisabledError('Scheduled model route requires rebuilding before queued dispatch');
+ throw new QueuedRouteDisabledError(
+ 'Scheduled model route requires rebuilding before queued dispatch',
+ );
}
// 早退 = 本轮沿用 live 当前路由派发:这条保留路由自己也要过停用裁决 ——
// 目标来源启用但需要凭证切换、而**当前**来源在排队等待期间被停用时,不裁决
@@ -2449,7 +2499,8 @@ export class MakerScheduleRunner implements ScheduleRunner {
return;
}
if (
- (await live.requiresModelSwitchRebuild?.(targetModel, { providerId: nextProviderId })) === true
+ (await live.requiresModelSwitchRebuild?.(targetModel, { providerId: nextProviderId })) ===
+ true
) {
// onAccepted 正运行在 coordinator 的 vendor-dispatch 边界,不能在这里关闭并替换
// live Session。明确中止本轮;recurring 的下一次 fire 会在空闲直发路径 cold resume。
@@ -2525,16 +2576,13 @@ export class MakerScheduleRunner implements ScheduleRunner {
// 遵循「follow 且当前值不可知 → 不动 effort」(PR #479 review「Re-read effort before following
// queued sessions」)。显式 effort 才是权威意图,按实际运行模型 clamp 后下发。
if (resolvedSelection && runtimeModel !== resolvedSelection.model) {
- throw new QueuedRouteDisabledError('Scheduled model selection did not reach the queued session');
+ throw new QueuedRouteDisabledError(
+ 'Scheduled model selection did not reach the queued session',
+ );
}
const reconciledEffort = resolvedSelection
- ? resolvedSelection.effort ?? undefined
- : this.reconcileEffortForModel(
- live.agentKind,
- runtimeModel,
- schedule.effort,
- schedule.id,
- );
+ ? (resolvedSelection.effort ?? undefined)
+ : this.reconcileEffortForModel(live.agentKind, runtimeModel, schedule.effort, schedule.id);
// 显式 effort 存在即下发,不靠 `!== baseline.effort` 判断:baseline.effort 是 enqueue 时刻快照,
// 且上一次 fire 可能已把它 backfill 成 clamp 后的值 —— 若据此判"未变"而 skip,当用户在排队期间
// 把 live effort 调低时,这一 turn 会跑用户的低档而非 schedule 的显式档。setEffort 幂等,显式档
@@ -2547,7 +2595,10 @@ export class MakerScheduleRunner implements ScheduleRunner {
await live.setEffort(reconciledEffort as Effort);
} catch (err) {
effortApplied = false;
- if (resolvedSelection) throw new QueuedRouteDisabledError('Scheduled effort selection could not be applied', { cause: err });
+ if (resolvedSelection)
+ throw new QueuedRouteDisabledError('Scheduled effort selection could not be applied', {
+ cause: err,
+ });
this.deps.logger.warn?.('[runner] queued heartbeat setEffort failed (non-fatal)', err);
}
}
@@ -2558,7 +2609,9 @@ export class MakerScheduleRunner implements ScheduleRunner {
try {
await live.setFastMode(resolvedSelection.fastMode);
} catch (err) {
- throw new QueuedRouteDisabledError('Scheduled Fast selection could not be applied', { cause: err });
+ throw new QueuedRouteDisabledError('Scheduled Fast selection could not be applied', {
+ cause: err,
+ });
}
}
// applyProviderId = 裁决后的落地来源:显式来源(通过裁决)或隐式默认被停用时的
@@ -2569,7 +2622,12 @@ export class MakerScheduleRunner implements ScheduleRunner {
if (live.agentKind === 'pi') {
setSessionFastMode(live.id, baseline.fastMode === true);
}
- if (resolvedSelection || (modelChanged && modelApplied) || (effortChanged && effortApplied) || applyProviderId) {
+ if (
+ resolvedSelection ||
+ (modelChanged && modelApplied) ||
+ (effortChanged && effortApplied) ||
+ applyProviderId
+ ) {
await backfillSessionMeta(
this.deps.getDb(),
live.id,
@@ -2701,10 +2759,7 @@ export class MakerScheduleRunner implements ScheduleRunner {
}
};
const isCurrentAutoResumePending = (): boolean =>
- this.deps.schedulerQueue?.isAutoResumePending?.(
- sessionId,
- options.origin.runId,
- ) === true;
+ this.deps.schedulerQueue?.isAutoResumePending?.(sessionId, options.origin.runId) === true;
const clearSessionListeners = (): void => {
pendingContinuationUnsub?.();
pendingContinuationUnsub = undefined;
@@ -2807,9 +2862,10 @@ export class MakerScheduleRunner implements ScheduleRunner {
const isSilentStopDone =
(ev.data as { silentStop?: boolean } | null | undefined)?.silentStop === true;
const continuationId = ev.turnContinuationId;
- const continuationState = continuationId === undefined
- ? null
- : owner.beginTurnContinuationWait?.(continuationId) ?? null;
+ const continuationState =
+ continuationId === undefined
+ ? null
+ : (owner.beginTurnContinuationWait?.(continuationId) ?? null);
if (continuationState === 'cancelled') {
// Provider already observed an explicit stop/teardown. Session
// gets a separate ordered boundary; this run can settle now.
@@ -2955,6 +3011,50 @@ export class MakerScheduleRunner implements ScheduleRunner {
}
}
+function buildScheduledRunPrompt(schedule: Schedule, ctx: FireContext): string {
+ return `${schedule.prompt}${buildScheduledRunContextInstruction(schedule, ctx)}${
+ schedule.silentWhenIdle ? buildSilentRunInstruction() : ''
+ }`;
+}
+
+/**
+ * 每次 fire 注入的权威时间上下文。UI / DB 仍展示用户原始 prompt;这里只让 agent
+ * 明确知道本轮 run.firedAt;具体查询时间范围仍由任务 prompt 决定。
+ * 采用 epoch ms + UTC ISO,避免 UTC 日期与任务时区的壁钟日期被直接比较。
+ */
+function buildScheduledRunContextInstruction(
+ schedule: Pick<Schedule, 'timezone'>,
+ ctx: Pick<FireContext, 'firedAt'>,
+): string {
+ const zonedParts = Object.fromEntries(
+ new Intl.DateTimeFormat('en-US', {
+ timeZone: schedule.timezone,
+ year: 'numeric',
+ month: '2-digit',
+ day: '2-digit',
+ hour: '2-digit',
+ minute: '2-digit',
+ second: '2-digit',
+ hourCycle: 'h23',
+ })
+ .formatToParts(ctx.firedAt)
+ .filter((part) => part.type !== 'literal')
+ .map((part) => [part.type, part.value]),
+ );
+ const hour = zonedParts.hour === '24' ? '00' : zonedParts.hour;
+ const firedAtInScheduleTimezone = `${zonedParts.year}-${zonedParts.month}-${zonedParts.day}T${hour}:${zonedParts.minute}:${zonedParts.second}[${schedule.timezone}]`;
+ return [
+ '',
+ '',
+ '---',
+ '[Scheduled run context]',
+ `firedAtEpochMs: ${ctx.firedAt}`,
+ `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.',
+ ].join('\n');
+}
+
/**
* 静默运行任务在每次 fire 时由 runner 追加到模型输入末尾的隐藏协议。UI / DB
* 仍展示用户原始 prompt。注意:这是 per-fire user message suffix,不是系统提示词