Open History to see the last commit
1import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
2import * as NodeServices from "@effect/platform-node/NodeServices";
3import { assert, it } from "@effect/vitest";
4import {
5 CommandId,
6 EnvironmentId,
7 MessageId,
8 ProjectId,
9 ProviderDriverKind,
10 ProviderInstanceId,
11 ProviderThreadId,
12 ProviderTurnId,
13 ThreadId,
14 type OrchestrationV2DomainEvent,
15} from "@t3tools/contracts";
16import * as DateTime from "effect/DateTime";
17import * as Effect from "effect/Effect";
18import * as Fiber from "effect/Fiber";
19import * as Layer from "effect/Layer";
20import * as Queue from "effect/Queue";
21import * as Stream from "effect/Stream";
22import * as TestClock from "effect/testing/TestClock";
23
24import { ClaudeProviderCapabilitiesV2 } from "../orchestration-v2/Adapters/ClaudeAdapterV2.ts";
25import * as CommandReceiptStore from "../orchestration-v2/CommandReceiptStore.ts";
26import * as EffectWorker from "../orchestration-v2/EffectWorker.ts";
27import * as Orchestrator from "../orchestration-v2/Orchestrator.ts";
28import * as ProjectionStore from "../orchestration-v2/ProjectionStore.ts";
29import * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter";
30import * as ProviderAdapterRegistry from "../orchestration-v2/ProviderAdapterRegistry.ts";
31import * as ThreadLaunchService from "../orchestration-v2/ThreadLaunchService.ts";
32import * as UsageLimitRecoveryWorker from "../orchestration-v2/UsageLimitRecoveryWorker.ts";
33import * as GitVcsDriver from "../vcs/GitVcsDriver.ts";
34import * as ThreadManagementService from "../orchestration-v2/ThreadManagementService.ts";
35import * as ServerSettings from "../serverSettings.ts";
36import * as ProviderReplayHarness from "../orchestration-v2/testkit/ProviderReplayHarness.ts";
37import { checkpointWorkspace } from "@t3tools/provider-testing/replayWorkspace";
38import * as SqlitePersistence from "../persistence/Sqlite.ts";
39import * as ProjectService from "../project/ProjectService.ts";
40import * as ProviderRegistry from "../provider/ProviderRegistry.ts";
41import * as ScheduledTaskService from "../scheduledTasks/ScheduledTaskService.ts";
42import * as Scheduler from "../scheduling/Scheduler.ts";
43import * as SecretRequests from "../secrets/SecretRequests.ts";
44import * as RemoteDelegation from "../peer/RemoteDelegation.ts";
45import type { McpInvocationScope } from "./McpInvocationContext.ts";
46import * as OrchestratorMcpService from "./OrchestratorMcpService.ts";
47
48const driver = ProviderDriverKind.make("claudeAgent");
49const instanceId = ProviderInstanceId.make("claudeAgent");
50const modelSelection = { instanceId, model: "claude-test" };
51
52type StartedTurn = {
53 readonly turn: ProviderAdapter.ProviderAdapterV2TurnInput;
54 readonly events: Queue.Queue<ProviderAdapter.ProviderAdapterV2Event>;
55};
56
57const makeAdapter = (
58 cwd: string,
59 turns: Array<StartedTurn>,
60 interrupt: () => Effect.Effect<void>,
61) => {
62 const adapter: ProviderAdapter.ProviderAdapterV2["Service"] = {
63 instanceId,
64 driver,
65 getCapabilities: () => Effect.succeed(ClaudeProviderCapabilitiesV2),
66 planSelectionTransition: () => Effect.succeed({ type: "apply_on_next_turn" }),
67 openSession: (input) =>
68 Effect.gen(function* () {
69 const now = yield* DateTime.now;
70 const events = yield* Queue.unbounded<ProviderAdapter.ProviderAdapterV2Event>();
71 return {
72 instanceId,
73 driver,
74 providerSessionId: input.providerSessionId,
75 providerSession: {
76 id: input.providerSessionId,
77 driver,
78 providerInstanceId: instanceId,
79 status: "ready",
80 cwd,
81 model: modelSelection.model,
82 capabilities: ClaudeProviderCapabilitiesV2,
83 createdAt: now,
84 updatedAt: now,
85 lastError: null,
86 },
87 events: Stream.fromQueue(events),
88 ensureThread: ({ threadId }) =>
89 Effect.succeed({
90 id: ProviderThreadId.make(`provider-thread:${threadId}`),
91 driver,
92 providerInstanceId: instanceId,
93 providerSessionId: input.providerSessionId,
94 appThreadId: threadId,
95 ownerNodeId: null,
96 nativeThreadRef: { driver, nativeId: `native:${threadId}`, strength: "strong" },
97 nativeConversationHeadRef: null,
98 status: "idle",
99 firstRunOrdinal: null,
100 lastRunOrdinal: null,
101 handoffIds: [],
102 forkedFrom: null,
103 createdAt: now,
104 updatedAt: now,
105 }),
106 resumeThread: ({ providerThread }) => Effect.succeed(providerThread),
107 startTurn: (turn) =>
108 Effect.gen(function* () {
109 turns.push({ turn, events });
110 yield* Queue.offer(events, {
111 type: "provider_turn.updated",
112 driver,
113 providerTurn: {
114 id: ProviderTurnId.make(`provider-turn:${turn.attemptId}`),
115 providerThreadId: turn.providerThread.id,
116 nodeId: turn.rootNodeId,
117 runAttemptId: turn.attemptId,
118 nativeTurnRef: null,
119 ordinal: turn.providerTurnOrdinal,
120 status: "running",
121 startedAt: now,
122 completedAt: null,
123 },
124 });
125 }),
126 steerTurn: () => Effect.die("unused"),
127 interruptTurn: () => Effect.suspend(interrupt),
128 respondToRuntimeRequest: () => Effect.die("unused"),
129 readThreadSnapshot: () => Effect.die("unused"),
130 rollbackThread: () => Effect.die("unused"),
131 forkThread: () => Effect.die("unused"),
132 };
133 }),
134 };
135 return adapter;
136};
137
138const makeLayer = (
139 adapter: ProviderAdapter.ProviderAdapterV2["Service"],
140 sweeps: Map<string, Effect.Effect<void>>,
141) => {
142 const layerAdapters = ProviderAdapterRegistry.layerSingle(adapter);
143 const layerOrchestrator = ProviderReplayHarness.layerWithRegistry(
144 { name: "task-cancel-usage-limit" },
145 layerAdapters,
146 { runEffectWorker: false },
147 );
148 const layerOrchestration = Layer.merge(
149 layerOrchestrator,
150 ThreadManagementService.layer.pipe(
151 Layer.provide(layerOrchestrator),
152 Layer.provide(ServerSettings.layerTest()),
153 Layer.provide(CommandReceiptStore.layer.pipe(Layer.provide(SqlitePersistence.layerMemory))),
154 ),
155 );
156 const layerRecovery = UsageLimitRecoveryWorker.layer.pipe(
157 Layer.provide(
158 Layer.mergeAll(
159 Layer.succeed(Scheduler.Scheduler, {
160 register: <E, R>(name: string, work: Effect.Effect<void, E, R>) =>
161 Effect.gen(function* () {
162 const context = yield* Effect.context<R>();
163 sweeps.set(name, work.pipe(Effect.provideContext(context), Effect.orDie));
164 }),
165 }),
166 ProjectionStore.layer.pipe(Layer.provide(SqlitePersistence.layerMemory)),
167 ServerSettings.layerTest({ autoResumeLimitedThreads: true }),
168 ),
169 ),
170 );
171 const layerTest = Layer.merge(
172 OrchestratorMcpService.layer.pipe(
173 Layer.provide(Layer.mock(ThreadLaunchService.ThreadLaunchService)({})),
174 Layer.provide(Layer.mock(GitVcsDriver.GitVcsDriver)({})),
175 ),
176 layerRecovery,
177 ).pipe(
178 Layer.provideMerge(layerOrchestration),
179 Layer.provide(
180 Layer.mergeAll(
181 layerAdapters,
182 Layer.mock(ProviderRegistry.ProviderRegistry)({ getProviders: Effect.succeed([]) }),
183 Layer.mock(ProjectService.ProjectService)({}),
184 Layer.mock(SecretRequests.SecretRequests)({}),
185 Layer.mock(RemoteDelegation.RemoteDelegation)({}),
186 ServerSettings.layerTest(),
187 Layer.mock(ScheduledTaskService.ScheduledTaskService)({}),
188 NodeServices.layer,
189 NodeCrypto.layer,
190 ),
191 ),
192 );
193 return layerTest;
194};
195
196// A delegated child that fails on a usage limit is armed to continue at the reset.
197// Once its parent cancels the task, nothing is waiting for that continuation.
198it.effect.each([
199 { cancel: "after its limit", cancelStatus: "failed", resumed: false },
200 { cancel: "as its limit lands", cancelStatus: "cancel_requested", resumed: false },
201 { cancel: "never", cancelStatus: null, resumed: true },
202] as const)(
203 "a delegated child whose task is cancelled $cancel resumes at the reset: $resumed",
204 ({ cancel, cancelStatus, resumed }) =>
205 Effect.gen(function* () {
206 const cwd = yield* checkpointWorkspace("task-cancel-usage-limit");
207 // Set while the provider's usage-limit result is already on its way.
208 let limitInFlight: Effect.Effect<void> = Effect.void;
209 const turns: Array<StartedTurn> = [];
210 const adapter = makeAdapter(cwd, turns, () => limitInFlight);
211 const sweeps = new Map<string, Effect.Effect<void>>();
212 const layerTest = makeLayer(adapter, sweeps);
213
214 yield* Effect.gen(function* () {
215 const orchestrator = yield* Orchestrator.OrchestratorV2;
216 const worker = yield* EffectWorker.OrchestrationEffectWorkerV2;
217 const service = yield* OrchestratorMcpService.OrchestratorMcpService;
218 const sweep = Effect.andThen(
219 Effect.suspend(() => sweeps.get("usage-limit-recovery")!),
220 worker.drain(),
221 );
222 const parentThreadId = ThreadId.make("thread:task-cancel-limit-parent");
223 const watch = (predicate: (event: OrchestrationV2DomainEvent) => boolean) =>
224 orchestrator.streamDomainEvents.pipe(
225 Stream.filter(predicate),
226 Stream.take(1),
227 Stream.runDrain,
228 Effect.forkScoped,
229 );
230 const turnRunning = () =>
231 watch(
232 (event) => event.type === "provider-turn.updated" && event.payload.status === "running",
233 );
234 yield* orchestrator.dispatch({
235 type: "thread.create",
236 commandId: CommandId.make("create-parent"),
237 threadId: parentThreadId,
238 projectId: ProjectId.make("project:task-cancel-limit"),
239 title: "Parent",
240 modelSelection,
241 runtimeMode: "full-access",
242 interactionMode: "default",
243 branch: null,
244 worktreePath: cwd,
245 createdBy: "user",
246 creationSource: "web",
247 });
248 const parentRunning = yield* turnRunning();
249 yield* orchestrator.dispatch({
250 type: "message.dispatch",
251 commandId: CommandId.make("start-parent"),
252 threadId: parentThreadId,
253 messageId: MessageId.make("message:start-parent"),
254 text: "Delegate a review",
255 attachments: [],
256 dispatchMode: { type: "start_immediately" },
257 createdBy: "user",
258 creationSource: "web",
259 });
260 yield* worker.drain();
261 yield* Fiber.join(parentRunning);
262
263 const parentRun = (yield* orchestrator.getThreadProjection(parentThreadId)).runs[0]!;
264 const childRunning = yield* turnRunning();
265 yield* orchestrator.dispatch({
266 type: "delegated_task.request",
267 commandId: CommandId.make("delegate"),
268 parentThreadId,
269 parentRunId: parentRun.id,
270 parentNodeId: parentRun.rootNodeId!,
271 task: "Review the change",
272 modelSelection,
273 runtimeMode: "full-access",
274 interactionMode: "default",
275 completionWake: "always",
276 createdBy: "agent",
277 creationSource: "mcp",
278 });
279 yield* worker.drain();
280 yield* Fiber.join(childRunning);
281 const task = (yield* orchestrator.getThreadProjection(parentThreadId)).subagents[0]!;
282 const childThreadId = task.childThreadId!;
283 const child = turns.find((entry) => entry.turn.threadId === childThreadId)!;
284 const childTurn = (yield* orchestrator.getThreadProjection(childThreadId))
285 .providerTurns[0]!;
286
287 const scope: McpInvocationScope = {
288 environmentId: EnvironmentId.make("environment:task-cancel-limit"),
289 requestNamespace: "provider-session:task-cancel-limit",
290 thread: {
291 threadId: parentThreadId,
292 providerSessionId: "provider-session:task-cancel-limit",
293 providerInstanceId: instanceId,
294 },
295 client: undefined,
296 capabilities: new Set(["orchestration"]),
297 issuedAt: 1,
298 };
299 const cancelTask = Effect.gen(function* () {
300 const result = yield* service.cancelTask(scope, {
301 taskId: task.id,
302 clientRequestId: "cancel-task",
303 });
304 yield* worker.drain();
305 return result.status;
306 });
307
308 const now = yield* DateTime.now;
309 const childFailed = yield* watch(
310 (event) =>
311 event.type === "run.updated" &&
312 event.payload.id === child.turn.runId &&
313 event.payload.status === "failed",
314 );
315 const hitLimit = Effect.forEach(
316 [
317 {
318 type: "provider_turn.updated",
319 driver,
320 providerTurn: { ...childTurn, status: "failed", completedAt: now },
321 },
322 {
323 type: "turn.terminal",
324 driver,
325 providerThreadId: childTurn.providerThreadId,
326 providerTurnId: childTurn.id,
327 runOrdinal: child.turn.runOrdinal,
328 failureItemOrdinal: 1,
329 status: "failed",
330 failure: {
331 class: "usage_limit",
332 message: "Claude usage limit reached.",
333 code: null,
334 retryable: null,
335 resetAt: DateTime.formatIso(DateTime.add(now, { minutes: 1 })),
336 },
337 threadDisposition: "reusable",
338 },
339 ] satisfies ReadonlyArray<ProviderAdapter.ProviderAdapterV2Event>,
340 (event) => Queue.offer(child.events, event),
341 { discard: true },
342 );
343 let cancelled: string | null = null;
344 if (cancel === "as its limit lands") {
345 limitInFlight = hitLimit;
346 cancelled = yield* cancelTask;
347 } else {
348 yield* hitLimit;
349 }
350 yield* Fiber.join(childFailed);
351 yield* worker.drain();
352
353 // The sweep runs every few seconds, so it arms the child before a parent reacts.
354 yield* sweep;
355 if (cancel === "after its limit") cancelled = yield* cancelTask;
356 assert.equal(cancelled, cancelStatus);
357
358 yield* TestClock.adjust("1 minute");
359 yield* sweep;
360 const childAfter = yield* orchestrator.getThreadProjection(childThreadId);
361 assert.deepEqual(
362 childAfter.messages.flatMap((message) => (message.role === "user" ? [message.text] : [])),
363 resumed ? ["Review the change", "Continue where you left off."] : ["Review the change"],
364 );
365 }).pipe(Effect.provide(layerTest));
366 }),
367);
368
369// task_cancel promises to stop the task's queued turns in its child thread. A follow-up the
370// parent queued there with t3_thread_send is one of them, and a held leftover blocks
371// "Turn into project" as unfinished work.
372it.effect("task_cancel cancels the follow-up its parent queued in the child", () =>
373 Effect.gen(function* () {
374 const cwd = yield* checkpointWorkspace("task-cancel-queued-follow-up");
375 const turns: Array<StartedTurn> = [];
376 // Set once the child runs: the provider confirms Stop by ending its turn.
377 let onInterrupt: Effect.Effect<void> = Effect.void;
378 const layerTest = makeLayer(
379 makeAdapter(cwd, turns, () => onInterrupt),
380 new Map(),
381 );
382
383 yield* Effect.gen(function* () {
384 const orchestrator = yield* Orchestrator.OrchestratorV2;
385 const worker = yield* EffectWorker.OrchestrationEffectWorkerV2;
386 const service = yield* OrchestratorMcpService.OrchestratorMcpService;
387 const parentThreadId = ThreadId.make("thread:task-cancel-follow-up-parent");
388 const turnRunning = () =>
389 orchestrator.streamDomainEvents.pipe(
390 Stream.filter(
391 (event) => event.type === "provider-turn.updated" && event.payload.status === "running",
392 ),
393 Stream.take(1),
394 Stream.runDrain,
395 Effect.forkScoped,
396 );
397 yield* orchestrator.dispatch({
398 type: "thread.create",
399 commandId: CommandId.make("create-parent"),
400 threadId: parentThreadId,
401 projectId: ProjectId.make("project:task-cancel-follow-up"),
402 title: "Parent",
403 modelSelection,
404 runtimeMode: "full-access",
405 interactionMode: "default",
406 branch: null,
407 worktreePath: cwd,
408 createdBy: "user",
409 creationSource: "web",
410 });
411 const parentRunning = yield* turnRunning();
412 yield* orchestrator.dispatch({
413 type: "message.dispatch",
414 commandId: CommandId.make("start-parent"),
415 threadId: parentThreadId,
416 messageId: MessageId.make("message:start-parent"),
417 text: "Delegate a long task",
418 attachments: [],
419 dispatchMode: { type: "start_immediately" },
420 createdBy: "user",
421 creationSource: "web",
422 });
423 yield* worker.drain();
424 yield* Fiber.join(parentRunning);
425
426 const parentRun = (yield* orchestrator.getThreadProjection(parentThreadId)).runs[0]!;
427 const childRunning = yield* turnRunning();
428 yield* orchestrator.dispatch({
429 type: "delegated_task.request",
430 commandId: CommandId.make("delegate"),
431 parentThreadId,
432 parentRunId: parentRun.id,
433 parentNodeId: parentRun.rootNodeId!,
434 task: "Run sleep 150",
435 modelSelection,
436 runtimeMode: "full-access",
437 interactionMode: "default",
438 completionWake: "always",
439 createdBy: "agent",
440 creationSource: "mcp",
441 });
442 yield* worker.drain();
443 yield* Fiber.join(childRunning);
444 const task = (yield* orchestrator.getThreadProjection(parentThreadId)).subagents[0]!;
445 const childThreadId = task.childThreadId!;
446 const child = turns.find((entry) => entry.turn.threadId === childThreadId)!;
447 const childTurn = (yield* orchestrator.getThreadProjection(childThreadId)).providerTurns[0]!;
448 const now = yield* DateTime.now;
449 onInterrupt = Effect.forEach(
450 [
451 {
452 type: "provider_turn.updated",
453 driver,
454 providerTurn: { ...childTurn, status: "interrupted", completedAt: now },
455 },
456 {
457 type: "turn.terminal",
458 driver,
459 providerThreadId: childTurn.providerThreadId,
460 providerTurnId: childTurn.id,
461 runOrdinal: child.turn.runOrdinal,
462 status: "interrupted",
463 failure: null,
464 threadDisposition: "reusable",
465 },
466 ] satisfies ReadonlyArray<ProviderAdapter.ProviderAdapterV2Event>,
467 (event) => Queue.offer(child.events, event),
468 { discard: true },
469 );
470
471 const scope: McpInvocationScope = {
472 environmentId: EnvironmentId.make("environment:task-cancel-follow-up"),
473 requestNamespace: "provider-session:task-cancel-follow-up",
474 thread: {
475 threadId: parentThreadId,
476 providerSessionId: "provider-session:task-cancel-follow-up",
477 providerInstanceId: instanceId,
478 },
479 client: undefined,
480 capabilities: new Set(["orchestration"]),
481 issuedAt: 1,
482 };
483 const sent = yield* service.sendToThread(scope, {
484 threadId: childThreadId,
485 message: "Also check the logs",
486 mode: "queue",
487 clientRequestId: "queue-follow-up",
488 });
489 yield* worker.drain();
490 assert.equal(sent.status, "queued");
491
492 const cancelled = yield* service.cancelTask(scope, {
493 taskId: task.id,
494 clientRequestId: "cancel-task",
495 });
496 yield* worker.drain();
497 assert.equal(cancelled.status, "cancel_requested");
498
499 const childAfter = yield* orchestrator.getThreadProjection(childThreadId);
500 assert.equal(
501 childAfter.runs.find((run) => run.id === child.turn.runId)?.status,
502 "interrupted",
503 );
504 const followUp = childAfter.runs.find((run) => run.id === sent.runId)!;
505 assert.equal(followUp.status, "cancelled");
506 assert.isFalse(Orchestrator.threadHasUnfinishedWork(childAfter));
507 }).pipe(Effect.provide(layerTest));
508 }),
509);