@@ -24,6 +24,7 @@ import {
2424 tryFinishCronTaskRun,
2525 tryFinishCronTaskRunWithoutHistory,
2626} from "./task-runs.js";
27+ import { executeJobCoreWithTimeout } from "./timer-job-runner.js";
2728
2829function 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 });
0 commit comments