Skip to content

Commit 34348d8

Browse files
authored
fix(cron): link active tasks to execution transcripts (#117679)
* fix(cron): link tasks to execution sessions Fixes #117678 * fix(tasks): preserve canonical cron cancellation state
1 parent 35e4563 commit 34348d8

9 files changed

Lines changed: 196 additions & 83 deletions

‎src/cron/service/task-runs.test.ts‎

Lines changed: 124 additions & 47 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@ import {
2424
tryFinishCronTaskRun,
2525
tryFinishCronTaskRunWithoutHistory,
2626
} from "./task-runs.js";
27+
import { executeJobCoreWithTimeout } from "./timer-job-runner.js";
2728

2829
function createCronServiceState(
2930
params: Parameters<typeof createCronServiceStateBase>[0],
@@ -113,25 +114,11 @@ describe("cron task run terminal records", () => {
113114
);
114115
});
115116

116-
it("uses the scoped owner for a current-session task run", async () => {
117+
it("seeds main transcript links only for system events and clears an unused link", async () => {
117118
await withOpenClawTestState(
118-
{ layout: "state-only", prefix: "openclaw-cron-current-task-owner-" },
119+
{ layout: "state-only", prefix: "openclaw-cron-main-task-session-" },
119120
async () => {
120121
resetTaskRegistryForTests();
121-
const job = {
122-
id: "current-task-owner",
123-
name: "current task owner",
124-
agentId: " ",
125-
sessionKey: "agent:ops:main",
126-
sessionTarget: "current",
127-
wakeMode: "next-heartbeat",
128-
payload: { kind: "systemEvent", text: "work" },
129-
schedule: { kind: "every", everyMs: 60_000 },
130-
state: {},
131-
createdAtMs: 100,
132-
updatedAtMs: 100,
133-
enabled: true,
134-
} satisfies CronJob;
135122
const state = createCronServiceState({
136123
storePath: "/tmp/jobs.json",
137124
cronEnabled: true,
@@ -140,64 +127,154 @@ describe("cron task run terminal records", () => {
140127
requestHeartbeat: vi.fn(),
141128
runIsolatedAgentJob: vi.fn(async () => ({ status: "ok" as const })),
142129
});
143-
144-
expect(tryCreateCronTaskRun({ state, job, startedAt: 1_500 })).toBeTruthy();
145-
146-
expect(
130+
const createMainJob = (id: string, payload: CronJob["payload"]): CronJob => ({
131+
id,
132+
name: id,
133+
agentId: "ops",
134+
sessionTarget: "main",
135+
wakeMode: "next-heartbeat",
136+
payload,
137+
schedule: { kind: "every", everyMs: 60_000 },
138+
state: {},
139+
createdAtMs: 100,
140+
updatedAtMs: 100,
141+
enabled: true,
142+
});
143+
const systemEventJob = createMainJob("main-system-event", {
144+
kind: "systemEvent",
145+
text: "work",
146+
});
147+
const jobs = [
148+
systemEventJob,
149+
createMainJob("main-script", { kind: "script", script: "return {}" }),
150+
createMainJob("main-heartbeat", { kind: "heartbeat" }),
151+
];
152+
const runIds = jobs.map((job) => tryCreateCronTaskRun({ state, job, startedAt: 1_500 }));
153+
const childSessionKey = (job: CronJob) =>
147154
listTaskRegistryRecordsByRuntimeSourceIdFromSqlite({
148155
runtime: "cron",
149156
sourceId: job.id,
150-
}),
151-
).toEqual([
152-
expect.objectContaining({
153-
agentId: "ops",
154-
childSessionKey: "agent:ops:cron:current-task-owner",
155-
}),
156-
]);
157+
})[0]?.childSessionKey;
158+
159+
expect(childSessionKey(systemEventJob)).toBe("agent:ops:cron:main-system-event:run:1500");
160+
expect(childSessionKey(jobs[1]!)).toBeUndefined();
161+
expect(childSessionKey(jobs[2]!)).toBeUndefined();
162+
163+
tryFinishCronTaskRunWithoutHistory(state, {
164+
taskRunId: runIds[0],
165+
status: "skipped",
166+
endedAt: 1_501,
167+
});
168+
expect(childSessionKey(systemEventJob)).toBeUndefined();
157169
},
158170
);
159171
});
160172

161-
it("uses the scoped owner for an isolated task run", async () => {
173+
it.each([
174+
{
175+
label: "current",
176+
id: "current-task-owner",
177+
agentId: " ",
178+
sessionTarget: "current" as const,
179+
timeoutSeconds: 0,
180+
initialSessionKey: undefined,
181+
executionSessionKey: "agent:ops:cron:current-task-owner:run:session-1",
182+
},
183+
{
184+
label: "isolated with creator source",
185+
id: "isolated-task-owner",
186+
agentId: " ",
187+
sessionTarget: "isolated" as const,
188+
timeoutSeconds: undefined,
189+
initialSessionKey: undefined,
190+
executionSessionKey: "agent:ops:cron:isolated-task-owner:run:session-1",
191+
},
192+
{
193+
label: "custom session target",
194+
id: "custom-task-owner",
195+
agentId: "ops",
196+
sessionTarget: "session:agent:ops:telegram:group:target" as const,
197+
timeoutSeconds: 0,
198+
initialSessionKey: undefined,
199+
executionSessionKey: "agent:ops:telegram:group:target",
200+
},
201+
])("uses the authoritative $label execution transcript", async (testCase) => {
162202
await withOpenClawTestState(
163-
{ layout: "state-only", prefix: "openclaw-cron-isolated-scoped-owner-" },
203+
{ layout: "state-only", prefix: `openclaw-cron-${testCase.id}-` },
164204
async () => {
165205
resetTaskRegistryForTests();
166-
const job = {
167-
id: "isolated-scoped-owner",
168-
name: "isolated scoped owner",
169-
agentId: " ",
170-
sessionKey: "agent:ops:main",
171-
sessionTarget: "isolated",
206+
let resolveStarted!: () => void;
207+
let resolveRun!: () => void;
208+
const started = new Promise<void>((resolve) => {
209+
resolveStarted = resolve;
210+
});
211+
const runPending = new Promise<void>((resolve) => {
212+
resolveRun = resolve;
213+
});
214+
const job: CronJob = {
215+
id: testCase.id,
216+
name: testCase.label,
217+
agentId: testCase.agentId,
218+
sessionKey: "agent:ops:telegram:group:creator",
219+
sessionTarget: testCase.sessionTarget,
172220
wakeMode: "next-heartbeat",
173-
payload: { kind: "agentTurn", message: "work" },
221+
payload: {
222+
kind: "agentTurn",
223+
message: "work",
224+
...(testCase.timeoutSeconds !== undefined
225+
? { timeoutSeconds: testCase.timeoutSeconds }
226+
: {}),
227+
},
174228
schedule: { kind: "every", everyMs: 60_000 },
175229
state: {},
176230
createdAtMs: 100,
177231
updatedAtMs: 100,
178232
enabled: true,
179-
} satisfies CronJob;
233+
};
180234
const state = createCronServiceState({
181235
storePath: "/tmp/jobs.json",
182236
cronEnabled: true,
183237
log: { debug: vi.fn(), info: vi.fn(), warn: vi.fn(), error: vi.fn() },
184238
enqueueSystemEvent: vi.fn(),
185239
requestHeartbeat: vi.fn(),
186-
runIsolatedAgentJob: vi.fn(async () => ({ status: "ok" as const })),
240+
runIsolatedAgentJob: vi.fn(async ({ onExecutionStarted }) => {
241+
onExecutionStarted?.({
242+
jobId: job.id,
243+
agentId: "ops",
244+
sessionId: "session-1",
245+
sessionKey: testCase.executionSessionKey,
246+
phase: "runner_entered",
247+
});
248+
resolveStarted();
249+
await runPending;
250+
return {
251+
status: "ok" as const,
252+
sessionId: "session-1",
253+
sessionKey: testCase.executionSessionKey,
254+
};
255+
}),
187256
});
188257

189-
expect(tryCreateCronTaskRun({ state, job, startedAt: 1_500 })).toBeTruthy();
190-
expect(
258+
const taskRunId = tryCreateCronTaskRun({ state, job, startedAt: 1_500 });
259+
expect(taskRunId).toBeTruthy();
260+
const taskRecords = () =>
191261
listTaskRegistryRecordsByRuntimeSourceIdFromSqlite({
192262
runtime: "cron",
193263
sourceId: job.id,
194-
}),
195-
).toEqual([
196-
expect.objectContaining({
197-
agentId: "ops",
198-
childSessionKey: "agent:ops:main",
199-
}),
200-
]);
264+
});
265+
expect(taskRecords()).toHaveLength(1);
266+
expect(taskRecords()[0]?.agentId).toBe("ops");
267+
expect(taskRecords()[0]?.childSessionKey).toBe(testCase.initialSessionKey);
268+
269+
const runPromise = executeJobCoreWithTimeout(state, job, { runId: taskRunId });
270+
try {
271+
await started;
272+
expect(taskRecords()[0]?.agentId).toBe("ops");
273+
expect(taskRecords()[0]?.childSessionKey).toBe(testCase.executionSessionKey);
274+
} finally {
275+
resolveRun();
276+
await runPromise;
277+
}
201278
},
202279
);
203280
});

‎src/cron/service/task-runs.ts‎

Lines changed: 32 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,7 @@
11
/** Detached task-ledger integration for cron runs. */
22
import { randomUUID } from "node:crypto";
33
import { normalizeOptionalLowercaseString } from "@openclaw/normalization-core/string-coerce";
4-
import {
5-
normalizeAgentId,
6-
parseAgentSessionKey,
7-
resolveAgentIdFromSessionKey,
8-
} from "../../routing/session-key.js";
4+
import { normalizeAgentId, resolveAgentIdFromSessionKey } from "../../routing/session-key.js";
95
import { resolveCronJobEffectiveAgentId } from "../agent-id.js";
106
import { isCronTimeoutErrorText } from "../execution-error-constants.js";
117

@@ -19,15 +15,16 @@ function requireCronAgentId(agentId: string | undefined): string {
1915
function resolveCurrentDefaultAgentId(state: CronServiceState): string | undefined {
2016
return state.deps.resolveDefaultAgentId?.() ?? state.deps.defaultAgentId;
2117
}
18+
import { CRON_TASK_KIND } from "../../tasks/cron-task-contract.js";
2219
import {
2320
createRunningTaskRun,
2421
finalizeTaskRunById,
2522
finalizeTaskRunByRunId,
2623
findTaskByRunId,
2724
listTaskRecordsUnsorted,
25+
recordTaskRunProgressByRunId,
2826
} from "../../tasks/task-executor.js";
2927
import type { JsonValue, TaskRecord, TaskStatus } from "../../tasks/task-registry.types.js";
30-
import { resolveCronAgentSessionKey } from "../isolated-agent/session-key.js";
3128
import { createCronExecutionId } from "../run-id.js";
3229
import type { CronRunLogEntry } from "../run-log-types.js";
3330
import { cronStoreKey } from "../store/key.js";
@@ -72,36 +69,40 @@ function resolveCronTaskChildSessionKey(params: {
7269
job: CronJob;
7370
startedAt: number;
7471
}): string | undefined {
75-
const explicitAgentId = params.job.agentId?.trim() || undefined;
76-
if (params.job.sessionTarget === "main") {
72+
if (params.job.sessionTarget === "main" && params.job.payload.kind === "systemEvent") {
7773
return resolveMainSessionCronRunSessionKey(
7874
params.job,
7975
params.startedAt,
8076
resolveCurrentDefaultAgentId(params.state),
8177
);
8278
}
83-
if (params.job.sessionTarget === "current") {
84-
const scopedAgentId = parseAgentSessionKey(params.job.sessionKey)?.agentId;
85-
return resolveCronAgentSessionKey({
86-
sessionKey: `cron:${params.job.id}`,
87-
agentId: requireCronAgentId(
88-
explicitAgentId ?? scopedAgentId ?? resolveCurrentDefaultAgentId(params.state),
89-
),
90-
});
91-
}
92-
const explicitSessionKey = params.job.sessionKey?.trim();
93-
if (explicitSessionKey) {
94-
// Explicit session bindings must win over generated cron session keys so
95-
// task drill-down opens the same transcript the cron run actually used.
96-
return explicitSessionKey;
79+
// Agent turns publish their exact transcript key after setup. This also
80+
// avoids inventing links for headless command/script/heartbeat work.
81+
return undefined;
82+
}
83+
84+
/** Updates an active cron task with the exact transcript identity reported by its runner. */
85+
export function tryUpdateCronTaskRunSession(
86+
state: CronServiceState,
87+
taskRunId: string | undefined,
88+
sessionKey: string | undefined,
89+
): void {
90+
const childSessionKey = sessionKey?.trim();
91+
if (!taskRunId || !childSessionKey) {
92+
return;
9793
}
98-
if (params.job.sessionTarget !== "isolated") {
99-
return undefined;
94+
try {
95+
const updated = recordTaskRunProgressByRunId({
96+
runId: taskRunId,
97+
runtime: "cron",
98+
childSessionKey,
99+
});
100+
if (updated.length === 0) {
101+
state.deps.log.warn({ runId: taskRunId }, "cron: task ledger session was not updated");
102+
}
103+
} catch (error) {
104+
state.deps.log.warn({ runId: taskRunId, error }, "cron: failed to update task ledger session");
100105
}
101-
return resolveCronAgentSessionKey({
102-
sessionKey: `cron:${params.job.id}`,
103-
agentId: resolveCronJobEffectiveAgentId(params.job, resolveCurrentDefaultAgentId(params.state)),
104-
});
105106
}
106107

107108
/** Creates a best-effort detached task row keyed to the persisted execution start. */
@@ -237,6 +238,7 @@ function tryCreateCronTaskRunRecord(params: {
237238
: undefined;
238239
const task = createRunningTaskRun({
239240
runtime: "cron",
241+
taskKind: CRON_TASK_KIND,
240242
sourceId: params.jobId,
241243
ownerKey: "",
242244
scopeKind: "system",
@@ -287,6 +289,7 @@ export function tryFinishCronTaskRunWithoutHistory(
287289
endedAt: number;
288290
summary?: string;
289291
childSessionKey?: string;
292+
sessionKey?: string;
290293
},
291294
): void {
292295
if (!result.taskRunId) {
@@ -307,7 +310,7 @@ export function tryFinishCronTaskRunWithoutHistory(
307310
lastEventAt: result.endedAt,
308311
error,
309312
terminalSummary: result.summary,
310-
childSessionKey: result.childSessionKey,
313+
childSessionKey: result.childSessionKey ?? result.sessionKey ?? null,
311314
});
312315
} catch (cause) {
313316
state.deps.log.warn(

‎src/cron/service/timer-job-runner.ts‎

Lines changed: 14 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@ import {
1818
timeoutErrorMessage,
1919
} from "./execution-errors.js";
2020
import type { CronServiceState } from "./state.js";
21+
import { tryUpdateCronTaskRunSession } from "./task-runs.js";
2122
import { resolveCronJobTimeoutMs } from "./timeout-policy.js";
2223
import {
2324
type IsolatedAgentSetupTimeoutSignal,
@@ -95,6 +96,9 @@ export async function executeJobCoreWithTimeout(
9596
onCancel: () => resolveOperatorCancellation?.(operatorCancellationMarker),
9697
})
9798
: undefined;
99+
const recordTaskExecutionStart = (info?: CronAgentExecutionStarted) => {
100+
tryUpdateCronTaskRunSession(state, opts?.runId, info?.sessionKey);
101+
};
98102
const jobTimeoutMs = resolveCronJobTimeoutMs(job);
99103
try {
100104
if (typeof jobTimeoutMs !== "number") {
@@ -108,13 +112,17 @@ export async function executeJobCoreWithTimeout(
108112
activeExecution = { ...activeExecution, ...info };
109113
}
110114
};
115+
const noteExecutionStarted = (info?: CronAgentExecutionStarted) => {
116+
accumulateExecution(info);
117+
recordTaskExecutionStart(info);
118+
};
111119
const corePromise = executeJobCore(state, job, runAbortController.signal, {
112120
activeJobMarker: opts?.activeJobMarker,
113121
owningCronLaneTaskMarker: opts?.owningCronLaneTaskMarker,
114122
streamBatch: opts?.streamBatch,
115123
streamScheduleKey: opts?.streamScheduleKey,
116124
streamSourceIdentity: opts?.streamSourceIdentity,
117-
onExecutionStarted: accumulateExecution,
125+
onExecutionStarted: noteExecutionStarted,
118126
onExecutionPhase: accumulateExecution,
119127
});
120128
trackActiveCronTaskRunSettlement(corePromise);
@@ -166,13 +174,17 @@ export async function executeJobCoreWithTimeout(
166174
}
167175
watchdog.noteLaneWait();
168176
};
177+
const noteRunnerStarted = (info?: CronAgentExecutionStarted) => {
178+
watchdog.noteRunnerStarted(info);
179+
recordTaskExecutionStart(info);
180+
};
169181
const corePromise = executeJobCore(state, job, runAbortController.signal, {
170182
activeJobMarker: opts?.activeJobMarker,
171183
owningCronLaneTaskMarker: opts?.owningCronLaneTaskMarker,
172184
streamBatch: opts?.streamBatch,
173185
streamScheduleKey: opts?.streamScheduleKey,
174186
streamSourceIdentity: opts?.streamSourceIdentity,
175-
onExecutionStarted: deferTimeoutUntilExecutionStart ? watchdog.noteRunnerStarted : undefined,
187+
onExecutionStarted: deferTimeoutUntilExecutionStart ? noteRunnerStarted : undefined,
176188
onExecutionPhase: deferTimeoutUntilExecutionStart ? watchdog.notePhase : undefined,
177189
onLaneWait: deferTimeoutUntilExecutionStart ? noteLaneState : undefined,
178190
});

0 commit comments

Comments
 (0)