forked from openclaw/openclaw
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtask-executor.test.ts
More file actions
865 lines (771 loc) · 28.1 KB
/
Copy pathtask-executor.test.ts
File metadata and controls
865 lines (771 loc) · 28.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
import { afterEach, describe, expect, it, vi } from "vitest";
import { resetAgentEventsForTest, resetAgentRunContextForTest } from "../infra/agent-events.js";
import { resetHeartbeatWakeStateForTests } from "../infra/heartbeat-wake.js";
import { resetSystemEventsForTest } from "../infra/system-events.js";
import { withStateDirEnv } from "../test-helpers/state-dir-env.js";
import {
getDetachedTaskLifecycleRuntime,
resetDetachedTaskLifecycleRuntimeForTests,
setDetachedTaskLifecycleRuntime,
} from "./detached-task-runtime.js";
import {
cancelFlowById,
cancelFlowByIdForOwner,
cancelDetachedTaskRunById,
completeTaskRunByRunId,
createQueuedTaskRun,
createRunningTaskRun,
failTaskRunByRunId,
recordTaskRunProgressByRunId,
retryBlockedFlowAsQueuedTaskRun,
runTaskInFlow,
runTaskInFlowForOwner,
setDetachedTaskDeliveryStatusByRunId,
startTaskRunByRunId,
} from "./task-executor.js";
import {
createManagedTaskFlow,
getTaskFlowById,
listTaskFlowRecords,
resetTaskFlowRegistryForTests,
} from "./task-flow-registry.js";
import {
setTaskRegistryDeliveryRuntimeForTests,
getTaskById,
findLatestTaskForFlowId,
findTaskByRunId,
resetTaskRegistryControlRuntimeForTests,
resetTaskRegistryDeliveryRuntimeForTests,
resetTaskRegistryForTests,
setTaskRegistryControlRuntimeForTests,
} from "./task-registry.js";
const ORIGINAL_STATE_DIR = process.env.OPENCLAW_STATE_DIR;
const hoisted = vi.hoisted(() => {
const sendMessageMock = vi.fn();
const cancelSessionMock = vi.fn();
const killSubagentRunAdminMock = vi.fn();
return {
sendMessageMock,
cancelSessionMock,
killSubagentRunAdminMock,
};
});
vi.mock("../acp/control-plane/manager.js", () => ({
getAcpSessionManager: () => ({
cancelSession: hoisted.cancelSessionMock,
}),
}));
vi.mock("../agents/subagent-control.js", () => ({
killSubagentRunAdmin: (params: unknown) => hoisted.killSubagentRunAdminMock(params),
}));
vi.mock("../utils/message-channel.js", () => ({
isDeliverableMessageChannel: (channel: string) => channel === "notifychat",
}));
async function withTaskExecutorStateDir(run: (stateDir: string) => Promise<void>): Promise<void> {
await withStateDirEnv("openclaw-task-executor-", async ({ stateDir }) => {
resetDetachedTaskLifecycleRuntimeForTests();
resetSystemEventsForTest();
resetHeartbeatWakeStateForTests();
resetAgentEventsForTest();
resetTaskRegistryDeliveryRuntimeForTests();
resetTaskRegistryControlRuntimeForTests();
resetAgentRunContextForTest();
resetTaskRegistryForTests({ persist: false });
resetTaskFlowRegistryForTests({ persist: false });
setTaskRegistryDeliveryRuntimeForTests({
sendMessage: hoisted.sendMessageMock,
});
setTaskRegistryControlRuntimeForTests({
getAcpSessionManager: () => ({
cancelSession: hoisted.cancelSessionMock,
}),
killSubagentRunAdmin: async (params) => hoisted.killSubagentRunAdminMock(params),
});
try {
await run(stateDir);
} finally {
resetSystemEventsForTest();
resetHeartbeatWakeStateForTests();
resetAgentEventsForTest();
resetTaskRegistryDeliveryRuntimeForTests();
resetTaskRegistryControlRuntimeForTests();
resetAgentRunContextForTest();
resetTaskRegistryForTests({ persist: false });
resetTaskFlowRegistryForTests({ persist: false });
}
});
}
function expectParentFlowId(task: { parentFlowId?: string }): string {
expect(task.parentFlowId).toMatch(
/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/u,
);
if (task.parentFlowId === undefined) {
throw new Error("Expected task parent flow id");
}
return task.parentFlowId;
}
function requireCreatedFlowTask(
result: ReturnType<typeof runTaskInFlow>,
): NonNullable<ReturnType<typeof runTaskInFlow>["task"]> {
if (!result.task) {
throw new Error("Expected TaskFlow child task to be created");
}
return result.task;
}
function expectCancelRequestedAt(value: unknown): number {
expect(typeof value).toBe("number");
if (typeof value !== "number") {
throw new Error("Expected numeric cancelRequestedAt");
}
expect(Number.isInteger(value)).toBe(true);
expect(value).toBeGreaterThan(0);
return value;
}
function createRunningAcpChildTaskRun(
overrides: Partial<Parameters<typeof createRunningTaskRun>[0]> = {},
) {
return createRunningTaskRun({
runtime: "acp",
ownerKey: "agent:main:main",
scopeKind: "session",
childSessionKey: "agent:codex:acp:child",
runId: "run-acp-child",
task: "Inspect a PR",
startedAt: 10,
deliveryStatus: "pending",
...overrides,
});
}
function spyOnRuntimeCancel() {
const defaultRuntime = getDetachedTaskLifecycleRuntime();
const cancelDetachedTaskRunByIdSpy = vi.fn(
(...args: Parameters<typeof defaultRuntime.cancelDetachedTaskRunById>) =>
defaultRuntime.cancelDetachedTaskRunById(...args),
);
setDetachedTaskLifecycleRuntime({
...defaultRuntime,
cancelDetachedTaskRunById: cancelDetachedTaskRunByIdSpy,
});
return cancelDetachedTaskRunByIdSpy;
}
function expectCancelledAcpChildTask(
child: ReturnType<typeof createRunningTaskRun>,
cancelled: { found?: boolean; cancelled?: boolean },
) {
expect(cancelled.found).toBe(true);
expect(cancelled.cancelled).toBe(true);
const task = getTaskById(child.taskId);
expect(task?.taskId).toBe(child.taskId);
expect(task?.status).toBe("cancelled");
expect(hoisted.cancelSessionMock).toHaveBeenCalledWith({
cfg: {} as never,
sessionKey: "agent:codex:acp:child",
reason: "task-cancel",
});
}
describe("task-executor", () => {
afterEach(() => {
if (ORIGINAL_STATE_DIR === undefined) {
delete process.env.OPENCLAW_STATE_DIR;
} else {
process.env.OPENCLAW_STATE_DIR = ORIGINAL_STATE_DIR;
}
resetSystemEventsForTest();
resetHeartbeatWakeStateForTests();
resetAgentEventsForTest();
resetTaskRegistryDeliveryRuntimeForTests();
resetTaskRegistryControlRuntimeForTests();
resetAgentRunContextForTest();
resetTaskRegistryForTests({ persist: false });
resetTaskFlowRegistryForTests({ persist: false });
hoisted.sendMessageMock.mockReset();
hoisted.cancelSessionMock.mockReset();
hoisted.killSubagentRunAdminMock.mockReset();
});
it("advances a queued run through start and completion", async () => {
await withTaskExecutorStateDir(async () => {
const created = createQueuedTaskRun({
runtime: "acp",
ownerKey: "agent:main:main",
scopeKind: "session",
childSessionKey: "agent:codex:acp:child",
runId: "run-executor-queued",
task: "Investigate issue",
});
expect(created.status).toBe("queued");
startTaskRunByRunId({
runId: "run-executor-queued",
startedAt: 100,
lastEventAt: 100,
eventSummary: "Started.",
});
completeTaskRunByRunId({
runId: "run-executor-queued",
endedAt: 250,
lastEventAt: 250,
terminalSummary: "Done.",
});
const task = getTaskById(created.taskId);
expect(task?.taskId).toBe(created.taskId);
expect(task?.status).toBe("succeeded");
expect(task?.startedAt).toBe(100);
expect(task?.endedAt).toBe(250);
expect(task?.terminalSummary).toBe("Done.");
});
});
it("records progress, failure, and delivery status through the executor", async () => {
await withTaskExecutorStateDir(async () => {
const created = createRunningTaskRun({
runtime: "subagent",
ownerKey: "agent:main:main",
scopeKind: "session",
childSessionKey: "agent:codex:subagent:child",
runId: "run-executor-fail",
task: "Write summary",
startedAt: 10,
});
recordTaskRunProgressByRunId({
runId: "run-executor-fail",
lastEventAt: 20,
progressSummary: "Collecting results",
eventSummary: "Collecting results",
});
failTaskRunByRunId({
runId: "run-executor-fail",
endedAt: 40,
lastEventAt: 40,
error: "tool failed",
});
setDetachedTaskDeliveryStatusByRunId({
runId: "run-executor-fail",
deliveryStatus: "failed",
});
const task = getTaskById(created.taskId);
expect(task?.taskId).toBe(created.taskId);
expect(task?.status).toBe("failed");
expect(task?.progressSummary).toBe("Collecting results");
expect(task?.error).toBe("tool failed");
expect(task?.deliveryStatus).toBe("failed");
});
});
it("persists explicit task kind metadata on created runs", async () => {
await withTaskExecutorStateDir(async () => {
const created = createRunningTaskRun({
runtime: "cli",
taskKind: "video_generation",
sourceId: "video_generate:openai",
ownerKey: "agent:main:main",
scopeKind: "session",
childSessionKey: "agent:main:main",
runId: "run-executor-kind",
task: "Generate lobster video",
startedAt: 10,
deliveryStatus: "not_applicable",
});
const task = getTaskById(created.taskId);
expect(task?.taskId).toBe(created.taskId);
expect(task?.taskKind).toBe("video_generation");
expect(task?.sourceId).toBe("video_generate:openai");
const found = findTaskByRunId("run-executor-kind");
expect(found?.taskId).toBe(created.taskId);
expect(found?.taskKind).toBe("video_generation");
});
});
it("auto-creates a one-task flow and keeps it synced with task status", async () => {
await withTaskExecutorStateDir(async () => {
const created = createRunningTaskRun({
runtime: "subagent",
ownerKey: "agent:main:main",
scopeKind: "session",
childSessionKey: "agent:codex:subagent:child",
runId: "run-executor-flow",
task: "Write summary",
startedAt: 10,
deliveryStatus: "pending",
});
const parentFlowId = expectParentFlowId(created);
const runningFlow = getTaskFlowById(parentFlowId);
expect(runningFlow?.flowId).toBe(parentFlowId);
expect(runningFlow?.ownerKey).toBe("agent:main:main");
expect(runningFlow?.status).toBe("running");
expect(runningFlow?.goal).toBe("Write summary");
expect(runningFlow?.notifyPolicy).toBe("done_only");
completeTaskRunByRunId({
runId: "run-executor-flow",
endedAt: 40,
lastEventAt: 40,
terminalSummary: "Done.",
});
const succeededFlow = getTaskFlowById(parentFlowId);
expect(succeededFlow?.flowId).toBe(parentFlowId);
expect(succeededFlow?.status).toBe("succeeded");
expect(succeededFlow?.endedAt).toBe(40);
expect(succeededFlow?.goal).toBe("Write summary");
expect(succeededFlow?.notifyPolicy).toBe("done_only");
});
});
it("does not auto-create one-task flows for non-returning bookkeeping runs", async () => {
await withTaskExecutorStateDir(async () => {
const created = createRunningTaskRun({
runtime: "cli",
ownerKey: "agent:main:main",
scopeKind: "session",
childSessionKey: "agent:main:main",
runId: "run-executor-cli",
task: "Foreground gateway run",
deliveryStatus: "not_applicable",
startedAt: 10,
});
expect(created.parentFlowId).toBeUndefined();
expect(listTaskFlowRecords()).toStrictEqual([]);
});
});
it("records blocked metadata on one-task flows and reuses the same flow for queued retries", async () => {
await withTaskExecutorStateDir(async () => {
const created = createRunningTaskRun({
runtime: "acp",
ownerKey: "agent:main:main",
scopeKind: "session",
requesterOrigin: {
channel: "notifychat",
to: "notifychat:123",
},
childSessionKey: "agent:codex:acp:child",
runId: "run-executor-blocked",
task: "Patch file",
startedAt: 10,
deliveryStatus: "pending",
});
completeTaskRunByRunId({
runId: "run-executor-blocked",
endedAt: 40,
lastEventAt: 40,
terminalOutcome: "blocked",
terminalSummary: "Writable session required.",
});
const blockedTask = getTaskById(created.taskId);
expect(blockedTask?.taskId).toBe(created.taskId);
expect(blockedTask?.status).toBe("succeeded");
expect(blockedTask?.terminalOutcome).toBe("blocked");
expect(blockedTask?.terminalSummary).toBe("Writable session required.");
const parentFlowId = expectParentFlowId(created);
const blockedFlow = getTaskFlowById(parentFlowId);
expect(blockedFlow?.flowId).toBe(parentFlowId);
expect(blockedFlow?.status).toBe("blocked");
expect(blockedFlow?.blockedTaskId).toBe(created.taskId);
expect(blockedFlow?.blockedSummary).toBe("Writable session required.");
expect(blockedFlow?.endedAt).toBe(40);
const retried = retryBlockedFlowAsQueuedTaskRun({
flowId: parentFlowId,
runId: "run-executor-retry",
childSessionKey: "agent:codex:acp:retry-child",
});
expect(retried.found).toBe(true);
expect(retried.retried).toBe(true);
if (!retried.retried) {
throw new Error("Expected blocked flow retry");
}
if (!retried.previousTask || !retried.task) {
throw new Error("Expected retry result payload");
}
expect(retried.previousTask.taskId).toBe(created.taskId);
expect(retried.task.parentFlowId).toBe(parentFlowId);
expect(retried.task.parentTaskId).toBe(created.taskId);
expect(retried.task.status).toBe("queued");
expect(retried.task.runId).toBe("run-executor-retry");
const queuedFlow = getTaskFlowById(parentFlowId);
expect(queuedFlow?.flowId).toBe(parentFlowId);
expect(queuedFlow?.status).toBe("queued");
expect(findLatestTaskForFlowId(parentFlowId)?.runId).toBe("run-executor-retry");
const original = findTaskByRunId("run-executor-blocked");
expect(original?.taskId).toBe(created.taskId);
expect(original?.status).toBe("succeeded");
expect(original?.terminalOutcome).toBe("blocked");
expect(original?.terminalSummary).toBe("Writable session required.");
});
});
it("cancels active tasks linked to a managed TaskFlow", async () => {
await withTaskExecutorStateDir(async () => {
hoisted.cancelSessionMock.mockResolvedValue(undefined);
const flow = createManagedTaskFlow({
ownerKey: "agent:main:main",
controllerId: "tests/managed-flow",
goal: "Inspect PR batch",
requesterOrigin: {
channel: "notifychat",
to: "notifychat:123",
},
});
const child = createRunningTaskRun({
runtime: "acp",
ownerKey: "agent:main:main",
scopeKind: "session",
parentFlowId: flow.flowId,
childSessionKey: "agent:codex:acp:child",
runId: "run-linear-cancel",
task: "Inspect a PR",
startedAt: 10,
deliveryStatus: "pending",
});
const cancelled = await cancelFlowById({
cfg: {} as never,
flowId: flow.flowId,
});
expect(cancelled.found).toBe(true);
expect(cancelled.cancelled).toBe(true);
const task = findTaskByRunId("run-linear-cancel");
expect(task?.taskId).toBe(child.taskId);
expect(task?.status).toBe("cancelled");
const cancelledFlow = getTaskFlowById(flow.flowId);
expect(cancelledFlow?.flowId).toBe(flow.flowId);
expect(cancelledFlow?.status).toBe("cancelled");
});
});
it("runs child tasks under managed TaskFlows", async () => {
await withTaskExecutorStateDir(async () => {
const flow = createManagedTaskFlow({
ownerKey: "agent:main:main",
controllerId: "tests/managed-flow",
goal: "Inspect PR batch",
requesterOrigin: {
channel: "notifychat",
to: "notifychat:123",
},
});
const created = runTaskInFlow({
flowId: flow.flowId,
runtime: "acp",
childSessionKey: "agent:codex:acp:child",
runId: "run-flow-child",
label: "Inspect a PR",
task: "Inspect a PR",
status: "running",
startedAt: 10,
lastEventAt: 10,
});
expect(created.found).toBe(true);
expect(created.created).toBe(true);
if (!created.created) {
throw new Error("Expected managed flow child task creation");
}
if (!created.task) {
throw new Error("Expected managed flow child task payload");
}
expect(created.task.parentFlowId).toBe(flow.flowId);
expect(created.task.ownerKey).toBe("agent:main:main");
expect(created.task.status).toBe("running");
expect(created.task.runId).toBe("run-flow-child");
const createdTask = requireCreatedFlowTask(created);
const task = getTaskById(createdTask.taskId);
expect(task?.parentFlowId).toBe(flow.flowId);
expect(task?.ownerKey).toBe("agent:main:main");
expect(task?.childSessionKey).toBe("agent:codex:acp:child");
});
});
it("refuses to add child tasks once cancellation is requested on a managed TaskFlow", async () => {
await withTaskExecutorStateDir(async () => {
const flow = createManagedTaskFlow({
ownerKey: "agent:main:main",
controllerId: "tests/managed-flow",
goal: "Protected flow",
});
const cancelled = await cancelFlowById({
cfg: {} as never,
flowId: flow.flowId,
});
expect(cancelled.found).toBe(true);
expect(cancelled.cancelled).toBe(true);
const created = runTaskInFlow({
flowId: flow.flowId,
runtime: "acp",
childSessionKey: "agent:codex:acp:child",
runId: "run-flow-after-cancel",
task: "Should be denied",
});
expect(created.found).toBe(true);
expect(created.created).toBe(false);
expect(created.reason).toBe("Flow cancellation has already been requested.");
});
});
it("sets cancel intent before child tasks settle and finalizes later", async () => {
await withTaskExecutorStateDir(async () => {
hoisted.cancelSessionMock.mockRejectedValue(new Error("still shutting down"));
const flow = createManagedTaskFlow({
ownerKey: "agent:main:main",
controllerId: "tests/managed-flow",
goal: "Long running batch",
});
const created = runTaskInFlow({
flowId: flow.flowId,
runtime: "acp",
childSessionKey: "agent:codex:acp:child",
runId: "run-flow-sticky-cancel",
task: "Inspect a PR",
status: "running",
startedAt: 10,
lastEventAt: 10,
});
const child = requireCreatedFlowTask(created);
const cancelled = await cancelFlowById({
cfg: {} as never,
flowId: flow.flowId,
});
expect(cancelled.found).toBe(true);
expect(cancelled.cancelled).toBe(false);
expect(cancelled.reason).toBe("One or more child tasks are still active.");
expect(cancelled.flow?.flowId).toBe(flow.flowId);
expect(cancelled.flow?.status).toBe("queued");
const cancelRequestedAt = expectCancelRequestedAt(cancelled.flow?.cancelRequestedAt);
failTaskRunByRunId({
runId: "run-flow-sticky-cancel",
endedAt: 50,
lastEventAt: 50,
error: "cancel completed later",
status: "cancelled",
});
const task = getTaskById(child.taskId);
expect(task?.taskId).toBe(child.taskId);
expect(task?.status).toBe("cancelled");
const cancelledFlow = getTaskFlowById(flow.flowId);
expect(cancelledFlow?.flowId).toBe(flow.flowId);
expect(cancelledFlow?.cancelRequestedAt).toBe(cancelRequestedAt);
expect(cancelledFlow?.status).toBe("cancelled");
expect(cancelledFlow?.endedAt).toBe(50);
});
});
it("denies cross-owner flow cancellation through the owner-scoped wrapper", async () => {
await withTaskExecutorStateDir(async () => {
const flow = createManagedTaskFlow({
ownerKey: "agent:main:main",
controllerId: "tests/managed-flow",
goal: "Protected flow",
});
const cancelled = await cancelFlowByIdForOwner({
cfg: {} as never,
flowId: flow.flowId,
callerOwnerKey: "agent:main:other",
});
expect(cancelled.found).toBe(false);
expect(cancelled.cancelled).toBe(false);
expect(cancelled.reason).toBe("Flow not found.");
const storedFlow = getTaskFlowById(flow.flowId);
expect(storedFlow?.flowId).toBe(flow.flowId);
expect(storedFlow?.status).toBe("queued");
});
});
it("denies cross-owner managed TaskFlow child spawning through the owner-scoped wrapper", async () => {
await withTaskExecutorStateDir(async () => {
const flow = createManagedTaskFlow({
ownerKey: "agent:main:main",
controllerId: "tests/managed-flow",
goal: "Protected flow",
});
const created = runTaskInFlowForOwner({
flowId: flow.flowId,
callerOwnerKey: "agent:main:other",
runtime: "acp",
childSessionKey: "agent:codex:acp:child",
runId: "run-flow-cross-owner",
task: "Should be denied",
});
expect(created.found).toBe(false);
expect(created.created).toBe(false);
expect(created.reason).toBe("Flow not found.");
expect(findLatestTaskForFlowId(flow.flowId)).toBeUndefined();
});
});
it("cancels active ACP child tasks", async () => {
await withTaskExecutorStateDir(async () => {
hoisted.cancelSessionMock.mockResolvedValue(undefined);
const child = createRunningAcpChildTaskRun({
runId: "run-linear-cancel",
});
const cancelled = await cancelDetachedTaskRunById({
cfg: {} as never,
taskId: child.taskId,
});
expectCancelledAcpChildTask(child, cancelled);
});
});
it("dispatches detached task cancellation through the registered runtime", async () => {
await withTaskExecutorStateDir(async () => {
hoisted.cancelSessionMock.mockResolvedValue(undefined);
const child = createRunningAcpChildTaskRun({
runId: "run-external-cancel",
});
const cancelDetachedTaskRunByIdSpy = spyOnRuntimeCancel();
const cancelled = await cancelDetachedTaskRunById({
cfg: {} as never,
taskId: child.taskId,
});
expect(cancelDetachedTaskRunByIdSpy).toHaveBeenCalledWith({
cfg: {} as never,
taskId: child.taskId,
});
expect(cancelled.found).toBe(true);
expect(cancelled.cancelled).toBe(true);
});
});
it("falls back to the legacy canceller when the registered runtime declines task ownership", async () => {
await withTaskExecutorStateDir(async () => {
hoisted.cancelSessionMock.mockResolvedValue(undefined);
const child = createRunningAcpChildTaskRun({
runId: "run-runtime-decline-cancel",
});
const cancelDetachedTaskRunByIdSpy = vi.fn(async () => ({
found: false,
cancelled: false,
reason: "not owned by runtime",
}));
setDetachedTaskLifecycleRuntime({
...getDetachedTaskLifecycleRuntime(),
cancelDetachedTaskRunById: cancelDetachedTaskRunByIdSpy,
});
const cancelled = await cancelDetachedTaskRunById({
cfg: {} as never,
taskId: child.taskId,
});
expect(cancelDetachedTaskRunByIdSpy).toHaveBeenCalledWith({
cfg: {} as never,
taskId: child.taskId,
});
expectCancelledAcpChildTask(child, cancelled);
});
});
it("does not fall back when the registered runtime claims task ownership", async () => {
await withTaskExecutorStateDir(async () => {
hoisted.cancelSessionMock.mockResolvedValue(undefined);
const child = createRunningAcpChildTaskRun({
runId: "run-runtime-owned-cancel",
});
const cancelDetachedTaskRunByIdSpy = vi.fn(async () => ({
found: true,
cancelled: false,
reason: "runtime refused cancel",
}));
setDetachedTaskLifecycleRuntime({
...getDetachedTaskLifecycleRuntime(),
cancelDetachedTaskRunById: cancelDetachedTaskRunByIdSpy,
});
const cancelled = await cancelDetachedTaskRunById({
cfg: {} as never,
taskId: child.taskId,
});
expect(cancelled.found).toBe(true);
expect(cancelled.cancelled).toBe(false);
expect(cancelled.reason).toBe("runtime refused cancel");
expect(cancelDetachedTaskRunByIdSpy).toHaveBeenCalledWith({
cfg: {} as never,
taskId: child.taskId,
});
const task = getTaskById(child.taskId);
expect(task?.taskId).toBe(child.taskId);
expect(task?.status).toBe("running");
expect(hoisted.cancelSessionMock).not.toHaveBeenCalled();
});
});
it("cancels active subagent child tasks", async () => {
await withTaskExecutorStateDir(async () => {
hoisted.killSubagentRunAdminMock.mockResolvedValue({
found: true,
killed: true,
});
const child = createRunningTaskRun({
runtime: "subagent",
ownerKey: "agent:main:main",
scopeKind: "session",
childSessionKey: "agent:codex:subagent:child",
runId: "run-subagent-cancel",
task: "Inspect a PR",
startedAt: 10,
deliveryStatus: "pending",
});
const cancelled = await cancelDetachedTaskRunById({
cfg: {} as never,
taskId: child.taskId,
});
expect(cancelled.found).toBe(true);
expect(cancelled.cancelled).toBe(true);
const task = getTaskById(child.taskId);
expect(task?.taskId).toBe(child.taskId);
expect(task?.status).toBe("cancelled");
expect(hoisted.killSubagentRunAdminMock).toHaveBeenCalledWith({
cfg: {} as never,
sessionKey: "agent:codex:subagent:child",
});
});
});
it("routes TaskFlow cancellation through the registered detached runtime", async () => {
await withTaskExecutorStateDir(async () => {
hoisted.cancelSessionMock.mockResolvedValue(undefined);
const flow = createManagedTaskFlow({
ownerKey: "agent:main:main",
controllerId: "tests/cancel-flow",
goal: "Cancel linked tasks",
});
const child = runTaskInFlow({
flowId: flow.flowId,
runtime: "acp",
childSessionKey: "agent:codex:acp:child",
runId: "run-flow-cancel-via-runtime",
task: "Cancel flow child",
status: "running",
startedAt: 10,
});
if (!child.created) {
throw new Error("expected child task creation to succeed");
}
const childTask = child.task;
if (!childTask) {
throw new Error("expected child task payload");
}
const cancelDetachedTaskRunByIdSpy = spyOnRuntimeCancel();
const cancelled = await cancelFlowById({
cfg: {} as never,
flowId: flow.flowId,
});
expect(cancelDetachedTaskRunByIdSpy).toHaveBeenCalledWith({
cfg: {} as never,
taskId: childTask.taskId,
});
expect(cancelled.found).toBe(true);
expect(cancelled.cancelled).toBe(true);
expect(cancelled.flow?.flowId).toBe(flow.flowId);
expect(cancelled.flow?.status).toBe("cancelled");
});
});
it("scopes run-id updates to the matching runtime and session", async () => {
await withTaskExecutorStateDir(async () => {
const victim = createRunningTaskRun({
runtime: "acp",
ownerKey: "agent:victim:main",
scopeKind: "session",
childSessionKey: "agent:victim:acp:child",
runId: "run-shared-executor-scope",
task: "Victim ACP task",
deliveryStatus: "pending",
});
const attacker = createRunningTaskRun({
runtime: "cli",
ownerKey: "agent:attacker:main",
scopeKind: "session",
childSessionKey: "agent:attacker:main",
runId: "run-shared-executor-scope",
task: "Attacker CLI task",
deliveryStatus: "not_applicable",
});
failTaskRunByRunId({
runId: "run-shared-executor-scope",
runtime: "cli",
sessionKey: "agent:attacker:main",
endedAt: 40,
lastEventAt: 40,
error: "attacker controlled error",
});
const attackerTask = getTaskById(attacker.taskId);
expect(attackerTask?.status).toBe("failed");
expect(attackerTask?.error).toBe("attacker controlled error");
expect(getTaskById(victim.taskId)?.status).toBe("running");
});
});
});