Skip to content
Merged
36 changes: 36 additions & 0 deletions packages/cli/src/serve/scheduled-task-keepalive.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,12 @@ describe('scheduled-task keepalive', () => {
loadSession: async (req: { sessionId: string }) => {
loads.push(req.sessionId);
},
spawnOrAttach: async () => {
Comment thread
wenshao marked this conversation as resolved.
Resolved
throw new Error('spawnOrAttach not mocked');
Comment thread
wenshao marked this conversation as resolved.
Resolved
},
updateSessionMetadata: () => {
throw new Error('updateSessionMetadata not mocked');
},
};

beforeEach(async () => {
Expand Down Expand Up @@ -104,6 +110,12 @@ describe('scheduled-task keepalive', () => {
loadSession: async (req: { sessionId: string }) => {
loads.push(req.sessionId);
},
spawnOrAttach: async () => {
throw new Error('not mocked');
},
updateSessionMetadata: () => {
throw new Error('not mocked');
},
};
const ka = startScheduledTaskKeepalive({
bridge: guarded,
Expand Down Expand Up @@ -140,6 +152,12 @@ describe('scheduled-task keepalive', () => {
loadSession: async (req: { sessionId: string }) => {
loads.push(req.sessionId);
},
spawnOrAttach: async () => {
throw new Error('not mocked');
},
updateSessionMetadata: () => {
throw new Error('not mocked');
},
};
const ka = startScheduledTaskKeepalive({
bridge: reviving,
Expand Down Expand Up @@ -168,6 +186,12 @@ describe('scheduled-task keepalive', () => {
loads.push(req.sessionId);
if (req.sessionId === 'sess-1') throw new Error('transcript gone');
},
spawnOrAttach: async () => {
throw new Error('not mocked');
},
updateSessionMetadata: () => {
throw new Error('not mocked');
},
};
const ka = startScheduledTaskKeepalive({
bridge: reviving,
Expand All @@ -192,6 +216,12 @@ describe('scheduled-task keepalive', () => {
loads.push(req.sessionId);
throw new Error('transcript gone');
},
spawnOrAttach: async () => {
throw new Error('not mocked');
},
updateSessionMetadata: () => {
throw new Error('not mocked');
},
};
const ka = startScheduledTaskKeepalive({
bridge: reviving,
Expand Down Expand Up @@ -220,6 +250,12 @@ describe('scheduled-task keepalive', () => {
releaseLoad = resolve;
});
},
spawnOrAttach: async () => {
throw new Error('not mocked');
},
updateSessionMetadata: () => {
throw new Error('not mocked');
},
};
const ka = startScheduledTaskKeepalive({
bridge: reviving,
Expand Down
125 changes: 124 additions & 1 deletion packages/cli/src/serve/scheduled-task-keepalive.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,11 +28,16 @@
* gap is caught up when the session loads.
*/

import * as fsSync from 'node:fs';
import * as path from 'node:path';
import {
readCronTasks,
updateCronTasks,
getCronFilePath,
createDebugLogger,
type DurableCronTask,
} from '@qwen-code/qwen-code-core';
import { scheduledTaskSessionName } from './routes/scheduled-tasks.js';

const log = createDebugLogger('SCHED_KEEPALIVE');

Expand Down Expand Up @@ -62,14 +67,25 @@ function collectBoundSessionIds(tasks: readonly DurableCronTask[]): string[] {

/** The slice of the bridge the keepalive needs — narrowed for testability.
* `recordHeartbeat` keeps a live session resident; `loadSession` revives one
* the reaper already let go (a re-enabled task's session). */
* the reaper already let go (a re-enabled task's session). `spawnOrAttach`
* and `updateSessionMetadata` bind unbound durable tasks to dedicated
* sessions — the same flow the POST /scheduled-tasks route uses for
* UI-created tasks, applied retroactively to cron_create tool tasks. */
export interface KeepaliveBridge {
recordHeartbeat(sessionId: string): unknown;
loadSession(req: {
sessionId: string;
workspaceCwd: string;
historyReplay?: 'stream' | 'response';
}): Promise<unknown>;
spawnOrAttach(req: {
workspaceCwd: string;
sessionScope?: 'single' | 'thread';
}): Promise<{ sessionId: string }>;
updateSessionMetadata(
sessionId: string,
metadata: { displayName?: string },
): unknown;
}

/** Per-session revive-load timeout: a hung reload must not stall the sweep. */
Expand All @@ -79,6 +95,72 @@ const KEEPALIVE_REVIVE_TIMEOUT_MS = 30_000;
* every interval forever. */
const MAX_REVIVE_BACKOFF_MS = 30 * 60_000;

/**
* Bind unbound durable tasks to dedicated sessions, and rename bound
* sessions that don't yet have the ⏰ prefix. The cron_create tool leaves
* durable tasks unbound so they stay pickable by any lock owner (CLI/ACP
* /headless). In daemon mode this keepalive mints a dedicated session per
* task and names it — binding is a daemon-only concern.
*
* For unbound tasks: mints a dedicated session, names it `⏰ prompt`,
* writes sessionId to disk.
* For bound tasks without ⏰ name: renames the session to `⏰ prompt`.
*
* A Set tracks renamed sessions so we don't call updateSessionMetadata
* every tick. Best-effort — failures are logged and retried next tick.
*/
async function bindAndNameSessions(
bridge: KeepaliveBridge,
boundWorkspace: string,
tasks: readonly DurableCronTask[],
renamed: Set<string>,
): Promise<void> {
const unbound = tasks.filter((t) => !t.sessionId && t.enabled !== false);
const needsName = tasks.filter(
(t) => t.sessionId && t.enabled !== false && !renamed.has(t.sessionId),
);
Comment thread
wenshao marked this conversation as resolved.
Resolved

for (const task of unbound) {
try {
const { sessionId } = await bridge.spawnOrAttach({
Comment thread
wenshao marked this conversation as resolved.
Resolved
Comment thread
wenshao marked this conversation as resolved.
Resolved
Comment thread
wenshao marked this conversation as resolved.
Resolved
workspaceCwd: boundWorkspace,
Comment thread
wenshao marked this conversation as resolved.
Resolved
sessionScope: 'thread',
});
try {
bridge.updateSessionMetadata(sessionId, {
displayName: scheduledTaskSessionName(task.prompt),
Comment thread
wenshao marked this conversation as resolved.
Resolved
});
renamed.add(sessionId);
} catch {
// naming is non-critical — the session still fires correctly
Comment thread
wenshao marked this conversation as resolved.
Resolved
}
await updateCronTasks(boundWorkspace, (list) =>
Comment thread
wenshao marked this conversation as resolved.
Resolved
list.map((t) => (t.id === task.id ? { ...t, sessionId } : t)),
);
log.debug(
Comment thread
wenshao marked this conversation as resolved.
Resolved
'keepalive: bound task',
task.id,
'to dedicated session',
sessionId,
);
} catch (err) {
log.debug('keepalive: failed to bind task', task.id, err);
}
}

for (const task of needsName) {
const sessionId = task.sessionId!;
try {
bridge.updateSessionMetadata(sessionId, {
displayName: scheduledTaskSessionName(task.prompt),
});
renamed.add(sessionId);
} catch (err) {
log.debug('keepalive: failed to name session', sessionId, err);
}
}
}

export interface ScheduledTaskKeepalive {
/** Stops the periodic heartbeat. Idempotent. */
stop(): void;
Expand Down Expand Up @@ -113,6 +195,10 @@ export function startScheduledTaskKeepalive(
// the load's TRUE settlement, not the timeout.
const reviving = new Set<string>();

// Tracks sessions the keepalive has already named with ⏰ prefix,
// so updateSessionMetadata isn't called every tick.
const renamed = new Set<string>();

const tick = async (): Promise<void> => {
let tasks;
try {
Expand Down Expand Up @@ -187,6 +273,8 @@ export function startScheduledTaskKeepalive(
if (!live.has(id)) reviveState.delete(id);
}
}

await bindAndNameSessions(bridge, boundWorkspace, tasks, renamed);
};

// In-flight guard: a pass can outlast the interval (each revive awaits up to
Expand All @@ -204,12 +292,47 @@ export function startScheduledTaskKeepalive(
// The heartbeat alone must never hold the daemon process open.
timer.unref?.();

// Watch the tasks file so a newly created cron_create task is bound to a
// dedicated session immediately, not after the next interval. Same
// directory-watch + debounce pattern the scheduler uses.
let bindDebounce: ReturnType<typeof setTimeout> | undefined;
const cronFilePath = getCronFilePath(boundWorkspace);
const cronDir = path.dirname(cronFilePath);
const cronFileName = path.basename(cronFilePath);
let fileWatcher: ReturnType<typeof fsSync.watch> | undefined;
try {
fsSync.mkdirSync(cronDir, { recursive: true });
fileWatcher = fsSync.watch(
cronDir,
{ persistent: false },
(_event, filename) => {
if (filename && filename !== cronFileName) return;
if (bindDebounce) clearTimeout(bindDebounce);
bindDebounce = setTimeout(() => {
if (running) return;
running = true;
void tick().finally(() => {
running = false;
});
}, 500);
bindDebounce.unref?.();
},
);
fileWatcher.on('error', () => {
Comment thread
wenshao marked this conversation as resolved.
Resolved
// Watch errors are non-fatal — the interval timer still ticks.
});
} catch {
// Directory doesn't exist or can't be watched — interval timer still runs.
}

let stopped = false;
return {
stop: () => {
if (stopped) return;
stopped = true;
clearInterval(timer);
if (bindDebounce) clearTimeout(bindDebounce);
fileWatcher?.close();
},
tick,
};
Expand Down
1 change: 1 addition & 0 deletions packages/core/src/services/cronScheduler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1515,6 +1515,7 @@ function jobToDurableTask(job: CronJob): DurableCronTask {
recurring: job.recurring,
createdAt: job.createdAt,
lastFiredAt: job.lastFiredAt ?? null,
...(job.boundSessionId ? { sessionId: job.boundSessionId } : {}),
Comment thread
wenshao marked this conversation as resolved.
Resolved
};
}

Expand Down
4 changes: 2 additions & 2 deletions packages/web-shell/client/i18n.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2280,8 +2280,8 @@ const ZH: Messages = {
'scheduledTasks.save': '保存',
'scheduledTasks.saving': '保存中…',
'scheduledTasks.runHistory': (v) => `运行记录(${v?.count ?? 0})`,
'scheduledTasks.viewHistory': (v) => `查看历史(${v?.count ?? 0})`,
'scheduledTasks.viewHistoryEmpty': '查看历史',
'scheduledTasks.viewHistory': (v) => `查看对话(${v?.count ?? 0})`,
'scheduledTasks.viewHistoryEmpty': '查看对话',
'scheduledTasks.viewHistoryHint': '打开该任务的会话查看运行详情',
'scheduledTasks.runKind.catchUp': '补跑',
'scheduledTasks.runKind.manual': '手动',
Expand Down
Loading