Skip to content
Merged
Show file tree
Hide file tree
Changes from 13 commits
Commits
Show all changes
18 commits
Select commit Hold shift + click to select a range
c16b4ea
feat(scheduled-tasks): allow creating a task with an existing session
yiliang114 Aug 17, 2026
08f54c3
Merge remote-tracking branch 'origin/main' into HEAD
yiliang114 Aug 17, 2026
a14a009
Merge branch 'main' into fix-8906-scheduled-task-existing-session
wenshao Aug 17, 2026
4d0ea79
fix(serve): harden scheduled-task session binding per bot review round 1
yiliang114 Aug 17, 2026
23cbd62
fix(serve): classify persisted-but-not-live sessions in task binding …
yiliang114 Aug 18, 2026
ca6a91d
fix(serve): gate scheduled-task delete teardown on session ownership
yiliang114 Aug 18, 2026
713029b
Merge branch 'main' into fix-8906-scheduled-task-existing-session
yiliang114 Aug 18, 2026
bf8b418
fix(serve): close session-binding races in scheduled-task create/reuse
yiliang114 Aug 18, 2026
9c4d756
fix(serve): keepalive must not tear down a session a committed task owns
yiliang114 Aug 18, 2026
e760806
fix(serve): serialize scheduled-task session teardown with reuse-crea…
yiliang114 Aug 19, 2026
d8b128b
fix(serve): extend scheduled-task session teardown serialization to r…
yiliang114 Aug 19, 2026
8b9116f
fix(scheduled-tasks): narrow existing session reuse
yiliang114 Aug 19, 2026
e2a8ce3
fix(scheduled-tasks): restore conversation-bound tasks
yiliang114 Aug 19, 2026
d561441
fix(scheduled-tasks): restore conversation runtime tasks
yiliang114 Aug 19, 2026
5adfabb
fix(scheduled-tasks): honor the session-management gate on the primar…
yiliang114 Aug 20, 2026
3385904
test(scheduled-tasks): isolate the Conversations runtime ownership re…
yiliang114 Aug 20, 2026
1bd85e5
test(scheduled-tasks): cover the ambiguous session-owner rejection path
yiliang114 Aug 20, 2026
9fb594c
Merge remote-tracking branch 'origin/main' into fix-8906-scheduled-ta…
yiliang114 Aug 20, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
316 changes: 314 additions & 2 deletions packages/cli/src/serve/routes/scheduled-tasks.test.ts

Large diffs are not rendered by default.

289 changes: 218 additions & 71 deletions packages/cli/src/serve/routes/scheduled-tasks.ts

Large diffs are not rendered by default.

71 changes: 71 additions & 0 deletions packages/cli/src/serve/run-qwen-serve.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,7 @@ import {
import { getDeferredRuntimeRequestTiming } from './server/request-helpers.js';
import type { WorkspaceFileSystemFactory } from './fs/workspace-file-system.js';
import { ConversationWorkspace } from './conversations/conversation-workspace.js';
import * as scheduledTaskKeepalive from './scheduled-task-keepalive.js';

const originalTestRuntimeDir = process.env['QWEN_RUNTIME_DIR'];
const isolatedTestRuntimeDir = fs.realpathSync(
Expand Down Expand Up @@ -489,6 +490,76 @@ function makeRuntimeBridge(): HttpAcpBridge {
} as unknown as HttpAcpBridge;
}

it('restores the Conversations runtime for a persisted scheduled task', async () => {
const workspace = fs.realpathSync(
fs.mkdtempSync(path.join(os.tmpdir(), 'qws-live-task-keepalive-')),
);
const liveConversationWorkspace = new ConversationWorkspace({
homeDir: workspace,
});
await liveConversationWorkspace.getRoot();
await qwenCore.updateCronTasks(liveConversationWorkspace.rootPath, () => [
{
id: 'live-task',
cron: '0 9 * * *',
prompt: 'p',
recurring: true,
createdAt: 1_700_000_000_000,
lastFiredAt: null,
sessionId: 'live-session',
sessionOwnedByTask: false,
},
]);
const startKeepalive = vi
.spyOn(scheduledTaskKeepalive, 'startScheduledTaskKeepalive')
.mockReturnValue({
stop: vi.fn(),
tick: vi.fn().mockResolvedValue(undefined),
});
vi.spyOn(acpBridge, 'createAcpSessionBridge').mockImplementation(
() =>
({
...makeRuntimeBridge(),
recordHeartbeat: vi.fn(),
resumeSession: vi.fn().mockResolvedValue({}),
setLiveScreenContextCaptureHandler: vi.fn(),
setLiveTaskToolRequestHandler: vi.fn(),
setLiveSpeakToUserHandler: vi.fn(),
}) as ReturnType<typeof acpBridge.createAcpSessionBridge>,
);
let handle: RunHandle | undefined;

try {
handle = await runQwenServe(
{
port: 0,
hostname: '127.0.0.1',
mode: 'http-bridge',
workspace,
maxSessions: 1,
serveWebShell: false,
},
{
bridge: makeRuntimeBridge(),
liveConversationWorkspace,
resolveOnListen: true,
},
Comment thread
yiliang114 marked this conversation as resolved.
Resolved
);
await handle.runtimeReady;
await vi.waitFor(() => {
expect(startKeepalive).toHaveBeenCalledWith(
expect.objectContaining({
boundWorkspace: liveConversationWorkspace.rootPath,
}),
);
});
} finally {
await handle?.close();
fs.rmSync(workspace, { recursive: true, force: true });
vi.restoreAllMocks();
}
});

function writeWebShellFixture(workspaceDir: string): string {
const shellDir = path.join(workspaceDir, 'web-shell');
fs.mkdirSync(path.join(shellDir, 'assets'), { recursive: true });
Expand Down
14 changes: 7 additions & 7 deletions packages/cli/src/serve/run-qwen-serve.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5553,13 +5553,6 @@ async function runQwenServeImpl(
} = { current: undefined };
const workspaceRuntimeRemoval = {
async runtimeAdded(runtimeAdded: WorkspaceRuntime): Promise<void> {
if (runtimeAdded.provenance === 'live-conversation') return;
channelWebhookEnvByWorkspace.set(
runtimeAdded.workspaceCwd,
workspaceRuntimeEffectiveEnv(runtimeAdded, daemonRuntimeBaseEnv),
);
channelWebhookConfigVersion += 1;
refreshChannelWebhookConfigs?.();
const app =
serveAppForRuntimeLifecycle.current ??
runtimeApp ??
Expand All @@ -5568,6 +5561,13 @@ async function runQwenServeImpl(
'startScheduledTaskKeepaliveForWorkspace'
] as ((runtime: WorkspaceRuntime) => void) | undefined;
startScheduledTaskKeepaliveForWorkspace?.(runtimeAdded);
if (runtimeAdded.provenance === 'live-conversation') return;
channelWebhookEnvByWorkspace.set(
runtimeAdded.workspaceCwd,
workspaceRuntimeEffectiveEnv(runtimeAdded, daemonRuntimeBaseEnv),
);
channelWebhookConfigVersion += 1;
refreshChannelWebhookConfigs?.();
if (!channelWorkerManager) return;
try {
if (runtimeAdded.trusted) {
Expand Down
7 changes: 6 additions & 1 deletion packages/cli/src/serve/scheduled-task-keepalive.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -698,9 +698,14 @@ describe('scheduled-task keepalive', () => {
expect(tasks[0]!.sessionId).toBe('new-sess-1');
});

it('renames a bound session without ⏰ prefix exactly once', async () => {
it('renames task-owned sessions once without renaming caller-owned ones', async () => {
await updateCronTasks(workspace, () => [
task({ id: 'bound-1', sessionId: 'existing-sess', prompt: 'lint' }),
task({
id: 'caller-bound',
sessionId: 'caller-sess',
sessionOwnedByTask: false,
}),
]);
const names: Array<[string, { displayName?: string }]> = [];
const naming = {
Expand Down
15 changes: 9 additions & 6 deletions packages/cli/src/serve/scheduled-task-keepalive.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,11 @@
*/

/**
* Keeps scheduled-task-owned sessions resident against the bridge's idle
* Keeps sessions bound to scheduled tasks resident against the bridge's idle
* reaper.
*
* A durable task created through the Web Shell management page is bound to a
* dedicated session and fires ONLY inside it (its transcript is the task's run
* session and fires ONLY inside it (its transcript is the task's run
* history). For that to keep happening the session must stay loaded so its
* in-child scheduler ticks — but a session with no client / SSE subscriber is
* closed by the bridge's idle reaper after the idle timeout, which would
Expand Down Expand Up @@ -50,7 +50,9 @@ const log = createDebugLogger('SCHED_KEEPALIVE');
* unbound, or a duplicate of one already collected. The heartbeat pass and the
* boot rehydrate share this so the "which sessions to keep resident" filter lives
* in exactly one place and can't drift between them. */
function collectBoundSessionIds(tasks: readonly DurableCronTask[]): string[] {
export function collectBoundSessionIds(
tasks: readonly DurableCronTask[],
): string[] {
const seen = new Set<string>();
const ids: string[] = [];
for (const task of tasks) {
Expand Down Expand Up @@ -113,14 +115,14 @@ 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
* task-owned 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`.
* For task-owned 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.
Expand All @@ -144,6 +146,7 @@ async function bindAndNameSessions(
const needsName = tasks.filter(
(t) =>
t.sessionId &&
t.sessionOwnedByTask !== false &&
t.enabled !== false &&
!taskHasLegacyCondition(t) &&
!renamed.has(t.sessionId),
Expand Down Expand Up @@ -498,7 +501,7 @@ export interface RehydrateResult {
}

/**
* Reloads every scheduled-task-owned session at daemon startup so its in-child
* Reloads every scheduled-task-bound session at daemon startup so its in-child
* scheduler re-arms after a restart — nothing rehydrates sessions on boot
* otherwise, so a bound task would sit dormant (its bound session dead, and the
* lock owner deliberately never fires a bound task) until something loaded it.
Expand Down
20 changes: 19 additions & 1 deletion packages/cli/src/serve/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import * as path from 'node:path';
import type { DaemonStatusProvider } from '@qwen-code/acp-bridge';
import {
hashDaemonWorkspace,
readCronTasks,
Storage,
type DurableCronTask,
} from '@qwen-code/qwen-code-core';
Expand Down Expand Up @@ -127,6 +128,7 @@ import { registerChannelNotifyRoutes } from './routes/channel-notify.js';
import { registerGoalsRoutes } from './routes/goals.js';
import { registerUsageStatsRoutes } from './routes/usage-stats.js';
import {
collectBoundSessionIds,
startScheduledTaskKeepalive,
rehydrateScheduledTaskSessions,
} from './scheduled-task-keepalive.js';
Expand Down Expand Up @@ -1470,6 +1472,22 @@ export function createServeApp(
if (liveVoiceEnabled) {
serveAppLifecycle.setBootStarter(startConversationRuntimeBoot);
}
if (deps.manageScheduledTaskSessions && deps.liveConversationWorkspace) {
void readCronTasks(deps.liveConversationWorkspace.rootPath)
.then((tasks) => {
if (collectBoundSessionIds(tasks).length > 0) {
Comment thread
yiliang114 marked this conversation as resolved.
Resolved
return startConversationRuntimeBoot();
}
return undefined;
})
.catch((error) => {
process.stderr.write(
`qwen serve: failed to restore the Conversations runtime for scheduled tasks: ${
error instanceof Error ? error.message : String(error)
}\n`,
);
});
}
const ensureConversationRuntimeWithLifecycle = async () => {
await serveAppLifecycle.startBoot(startConversationRuntimeBoot);
if (!liveRuntimeBootResult) {
Expand Down Expand Up @@ -2613,6 +2631,7 @@ export function createServeApp(
? workspaceRegistry.primaryEntry.current?.runtime
: undefined,
cleanupSession,
workspaceRegistry,
channelDeliveryAuthorizations: deps.channelDeliveryAuthorizations,
});

Expand Down Expand Up @@ -2715,7 +2734,6 @@ export function createServeApp(
// own cron file + bridge.
const keepaliveStops = new Map<string, () => void>();
const startKeepaliveForWorkspace = (runtime: WorkspaceRuntime) => {
if (runtime.provenance === 'live-conversation') return;
const trusted = runtime.primary
? isPrimaryWorkspaceTrusted()
: runtime.trusted;
Expand Down
10 changes: 10 additions & 0 deletions packages/core/src/services/cronTasksFile.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -215,6 +215,16 @@ describe('cronTasksFile', () => {
await expect(readCronTasks(tmpDir)).rejects.toThrow(/Invalid task entry/);
});

it('rejects a non-boolean session ownership marker', async () => {
await seedTasksFile(
tmpDir,
JSON.stringify([
{ ...makeTask(), sessionId: 'sess-1', sessionOwnedByTask: 'yes' },
]),
);
await expect(readCronTasks(tmpDir)).rejects.toThrow(/Invalid task entry/);
});

it('round-trips the optional runs history', async () => {
const task = makeTask({
lastFiredAt: 1718000300000,
Expand Down
14 changes: 8 additions & 6 deletions packages/core/src/services/cronTasksFile.ts
Original file line number Diff line number Diff line change
Expand Up @@ -101,14 +101,14 @@ export interface DurableCronTask {
*/
disabledByArchive?: boolean;
/**
* Id of the dedicated session this task is bound to. A task created through
* the Web Shell management page mints its own session and stores its id here;
* the task then fires ONLY inside that session (not via the shared per-project
* durable owner), so the session's transcript is the task's run history, and
* archiving/deleting that session stops the task. Absent on tool-created
* (`cron_create`) and legacy tasks, which keep the shared-owner firing model.
* Id of the session this task is bound to. The task fires only inside that
* session, so its transcript is the task's run history. Absent on unbound
* tool-created and legacy tasks, which use the shared durable owner.
*/
sessionId?: string;
/** False when the caller, rather than the task, owns the bound session.
* Absent means task-owned for backward compatibility. */
sessionOwnedByTask?: boolean;
delivery?: CronTaskDelivery;
/**
* Bounded, newest-last history of recent fires (capped at MAX_TASK_RUNS).
Expand Down Expand Up @@ -486,6 +486,8 @@ function isValidTask(value: unknown): value is DurableCronTask {
// would treat it as unbound, so a "bound" task would silently run unbound.
(obj['sessionId'] === undefined ||
(typeof obj['sessionId'] === 'string' && obj['sessionId'].length > 0)) &&
(obj['sessionOwnedByTask'] === undefined ||
typeof obj['sessionOwnedByTask'] === 'boolean') &&
Comment thread
yiliang114 marked this conversation as resolved.
Resolved
(obj['delivery'] === undefined || isValidDelivery(obj['delivery'])) &&
(obj['runs'] === undefined || isValidRuns(obj['runs']))
);
Expand Down
2 changes: 2 additions & 0 deletions packages/webui/src/daemon/workspace/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -272,6 +272,8 @@ export interface DaemonCreateScheduledTaskRequest {
recurring?: boolean;
/** Defaults to true. */
enabled?: boolean;
/** Reuse an existing live, idle session instead of creating one. */
sessionId?: string | null;
}

/** Partial update. `name: null` (or '') clears the name. Omitted fields are
Expand Down
Loading