|
| 1 | +import type { SDKMessage } from "@anthropic-ai/claude-agent-sdk"; |
| 2 | +import * as NodeServices from "@effect/platform-node/NodeServices"; |
| 3 | +import { assert, it } from "@effect/vitest"; |
| 4 | +import { |
| 5 | + ClaudeSettings, |
| 6 | + CommandId, |
| 7 | + MessageId, |
| 8 | + ProjectId, |
| 9 | + ProviderInstanceId, |
| 10 | + ThreadId, |
| 11 | + type OrchestrationV2DomainEvent, |
| 12 | +} from "@t3tools/contracts"; |
| 13 | +import * as Crypto from "effect/Crypto"; |
| 14 | +import * as Effect from "effect/Effect"; |
| 15 | +import * as Fiber from "effect/Fiber"; |
| 16 | +import * as FileSystem from "effect/FileSystem"; |
| 17 | +import * as Layer from "effect/Layer"; |
| 18 | +import * as Path from "effect/Path"; |
| 19 | +import * as Queue from "effect/Queue"; |
| 20 | +import * as Schema from "effect/Schema"; |
| 21 | +import * as Stream from "effect/Stream"; |
| 22 | +import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator"; |
| 23 | +import * as McpProviderSessions from "@t3tools/provider-core/server/McpProviderSessions"; |
| 24 | +import { checkpointWorkspace } from "@t3tools/provider-testing/replayWorkspace"; |
| 25 | +import * as ClaudeAdapterV2 from "./Adapters/ClaudeAdapterV2.ts"; |
| 26 | +import * as EffectWorker from "./EffectWorker.ts"; |
| 27 | +import * as EventSink from "./EventSink.ts"; |
| 28 | +import * as Orchestrator from "./Orchestrator.ts"; |
| 29 | +import * as ProviderAdapterRegistry from "./ProviderAdapterRegistry.ts"; |
| 30 | +import * as ProviderSessionManager from "./ProviderSessionManager.ts"; |
| 31 | +import * as ProviderReplayHarness from "./testkit/ProviderReplayHarness.ts"; |
| 32 | + |
| 33 | +const modelSelection = { |
| 34 | + instanceId: ProviderInstanceId.make("claudeAgent"), |
| 35 | + model: "claude-sonnet-4-6", |
| 36 | +}; |
| 37 | +const sessionId = "orphaned-subagent-session"; |
| 38 | +const decodeClaudeSettings = Schema.decodeEffect(ClaudeSettings); |
| 39 | +const frame = (value: unknown) => value as SDKMessage; |
| 40 | + |
| 41 | +// Only the SDK stream is replayed; adapter, session manager, ingestor, |
| 42 | +// orchestrator, and SQLite projections are the production ones. |
| 43 | +it.effect("settles a subagent the replacement Claude process reports stopped after resume", () => |
| 44 | + Effect.scoped( |
| 45 | + Effect.gen(function* () { |
| 46 | + const cwd = yield* checkpointWorkspace("claude-orphaned-subagent"); |
| 47 | + const processes: Array<Queue.Queue<SDKMessage>> = []; |
| 48 | + const adapter = yield* ClaudeAdapterV2.makeClaudeAdapterV2({ |
| 49 | + instanceId: modelSelection.instanceId, |
| 50 | + settings: yield* decodeClaudeSettings({}), |
| 51 | + environment: {}, |
| 52 | + attachmentsDir: cwd, |
| 53 | + fileSystem: yield* FileSystem.FileSystem, |
| 54 | + path: yield* Path.Path, |
| 55 | + crypto: yield* Crypto.Crypto, |
| 56 | + idAllocator: yield* IdAllocator.IdAllocatorV2, |
| 57 | + queryRunner: { |
| 58 | + allocateSessionId: Effect.succeed(sessionId), |
| 59 | + assertComplete: Effect.void, |
| 60 | + subagentLaunchToolUseId: () => Effect.succeed(null), |
| 61 | + open: () => |
| 62 | + Effect.gen(function* () { |
| 63 | + const messages = yield* Queue.unbounded<SDKMessage>(); |
| 64 | + processes.push(messages); |
| 65 | + return { |
| 66 | + messages: Stream.fromQueue(messages), |
| 67 | + offer: () => Effect.void, |
| 68 | + setModel: () => Effect.void, |
| 69 | + setPermissionMode: () => Effect.void, |
| 70 | + stopTask: () => Effect.void, |
| 71 | + interrupt: Effect.void, |
| 72 | + close: Queue.shutdown(messages), |
| 73 | + }; |
| 74 | + }), |
| 75 | + forkSession: () => Effect.die("unused forkSession"), |
| 76 | + }, |
| 77 | + }); |
| 78 | + yield* Effect.gen(function* () { |
| 79 | + const orchestrator = yield* Orchestrator.OrchestratorV2; |
| 80 | + const sink = yield* EventSink.EventSinkV2; |
| 81 | + const worker = yield* EffectWorker.OrchestrationEffectWorkerV2; |
| 82 | + const manager = yield* ProviderSessionManager.ProviderSessionManagerV2; |
| 83 | + const threadId = ThreadId.make("thread:orphaned-subagent"); |
| 84 | + // Subscribe before offering the frame so a fast commit is not missed. |
| 85 | + const awaitEvent = (predicate: (event: OrchestrationV2DomainEvent) => boolean) => |
| 86 | + Effect.gen(function* () { |
| 87 | + const afterSequence = yield* sink.latestSequence(); |
| 88 | + return yield* sink.stream({ afterSequence }).pipe( |
| 89 | + Stream.filter((stored) => predicate(stored.event)), |
| 90 | + Stream.take(1), |
| 91 | + Stream.runDrain, |
| 92 | + Effect.forkScoped, |
| 93 | + ); |
| 94 | + }); |
| 95 | + const sendMessage = (id: string) => |
| 96 | + orchestrator.dispatch({ |
| 97 | + type: "message.dispatch", |
| 98 | + commandId: CommandId.make(id), |
| 99 | + threadId, |
| 100 | + messageId: MessageId.make(id), |
| 101 | + text: "Continue.", |
| 102 | + attachments: [], |
| 103 | + dispatchMode: { type: "start_immediately" }, |
| 104 | + createdBy: "user", |
| 105 | + creationSource: "web", |
| 106 | + }); |
| 107 | + yield* orchestrator.dispatch({ |
| 108 | + type: "thread.create", |
| 109 | + commandId: CommandId.make("create"), |
| 110 | + threadId, |
| 111 | + projectId: ProjectId.make("project:orphaned-subagent"), |
| 112 | + title: "Orphaned subagent", |
| 113 | + modelSelection, |
| 114 | + runtimeMode: "full-access", |
| 115 | + interactionMode: "default", |
| 116 | + branch: null, |
| 117 | + worktreePath: cwd, |
| 118 | + createdBy: "user", |
| 119 | + creationSource: "web", |
| 120 | + }); |
| 121 | + yield* sendMessage("first"); |
| 122 | + yield* worker.drain(); |
| 123 | + const first = processes[0]!; |
| 124 | + const started = yield* awaitEvent( |
| 125 | + (event) => |
| 126 | + event.type === "subagent.updated" && |
| 127 | + event.payload.nativeTaskRef?.nativeId === "old-task", |
| 128 | + ); |
| 129 | + yield* Queue.offer( |
| 130 | + first, |
| 131 | + frame({ |
| 132 | + type: "system", |
| 133 | + subtype: "task_started", |
| 134 | + task_id: "old-task", |
| 135 | + tool_use_id: "old-tool", |
| 136 | + description: "Review recent changes", |
| 137 | + subagent_type: "general-purpose", |
| 138 | + is_backgrounded: true, |
| 139 | + task_type: "local_agent", |
| 140 | + prompt: "Review recent changes.", |
| 141 | + uuid: "old-task-started", |
| 142 | + session_id: sessionId, |
| 143 | + }), |
| 144 | + ); |
| 145 | + yield* Fiber.join(started); |
| 146 | + const firstTurnDone = yield* awaitEvent( |
| 147 | + (event) => event.type === "provider-turn.updated" && event.payload.status === "completed", |
| 148 | + ); |
| 149 | + yield* Queue.offer( |
| 150 | + first, |
| 151 | + frame({ |
| 152 | + type: "result", |
| 153 | + subtype: "success", |
| 154 | + uuid: "first-result", |
| 155 | + session_id: sessionId, |
| 156 | + is_error: false, |
| 157 | + num_turns: 1, |
| 158 | + result: "The review continues in the background.", |
| 159 | + stop_reason: "end_turn", |
| 160 | + permission_denials: [], |
| 161 | + duration_ms: 1, |
| 162 | + duration_api_ms: 1, |
| 163 | + total_cost_usd: 0, |
| 164 | + usage: { input_tokens: 1, output_tokens: 1 }, |
| 165 | + modelUsage: {}, |
| 166 | + }), |
| 167 | + ); |
| 168 | + yield* Fiber.join(firstTurnDone); |
| 169 | + yield* worker.drain(); |
| 170 | + const before = yield* orchestrator.getThreadProjection(threadId); |
| 171 | + const task = before.subagents.find( |
| 172 | + (entry) => entry.nativeTaskRef?.nativeId === "old-task", |
| 173 | + )!; |
| 174 | + assert.equal(task.status, "running"); |
| 175 | + |
| 176 | + // The replacement process starts with no record of the old task. |
| 177 | + yield* manager.release({ |
| 178 | + providerSessionId: before.providerSessions.at(-1)!.id, |
| 179 | + reason: "runtime_error", |
| 180 | + detail: "fixture process exited", |
| 181 | + }); |
| 182 | + yield* sendMessage("second"); |
| 183 | + yield* worker.drain(); |
| 184 | + assert.lengthOf(processes, 2); |
| 185 | + const second = processes[1]!; |
| 186 | + // A later frame's persisted item marks the notification as consumed. |
| 187 | + const consumed = yield* awaitEvent( |
| 188 | + (event) => |
| 189 | + event.type === "turn-item.updated" && |
| 190 | + event.payload.nativeItemRef?.nativeId === "barrier-tool", |
| 191 | + ); |
| 192 | + yield* Queue.offer( |
| 193 | + second, |
| 194 | + frame({ |
| 195 | + type: "system", |
| 196 | + subtype: "task_notification", |
| 197 | + task_id: "old-task", |
| 198 | + status: "stopped", |
| 199 | + reason: "worker_restart", |
| 200 | + summary: "Background agent didn't finish before the previous session ended", |
| 201 | + output_file: "", |
| 202 | + uuid: "old-task-stopped", |
| 203 | + session_id: sessionId, |
| 204 | + }), |
| 205 | + ); |
| 206 | + yield* Queue.offer( |
| 207 | + second, |
| 208 | + frame({ |
| 209 | + type: "assistant", |
| 210 | + uuid: "barrier", |
| 211 | + session_id: sessionId, |
| 212 | + parent_tool_use_id: null, |
| 213 | + message: { |
| 214 | + id: "barrier-message", |
| 215 | + role: "assistant", |
| 216 | + type: "message", |
| 217 | + model: modelSelection.model, |
| 218 | + content: [ |
| 219 | + { type: "tool_use", id: "barrier-tool", name: "Bash", input: { command: "true" } }, |
| 220 | + ], |
| 221 | + stop_reason: "tool_use", |
| 222 | + stop_sequence: null, |
| 223 | + usage: { input_tokens: 1, output_tokens: 1 }, |
| 224 | + }, |
| 225 | + }), |
| 226 | + ); |
| 227 | + yield* Fiber.join(consumed); |
| 228 | + |
| 229 | + const after = yield* orchestrator.getThreadProjection(threadId); |
| 230 | + const ended = after.subagents.find((entry) => entry.id === task.id)!; |
| 231 | + assert.equal(ended.status, "cancelled"); |
| 232 | + assert.equal(ended.runId, task.runId); |
| 233 | + assert.equal( |
| 234 | + ended.result, |
| 235 | + "Background agent didn't finish before the previous session ended", |
| 236 | + ); |
| 237 | + assert.equal(after.nodes.find((node) => node.id === task.id)?.status, "cancelled"); |
| 238 | + const item = after.turnItems.find( |
| 239 | + (entry) => entry.type === "subagent" && entry.subagentId === task.id, |
| 240 | + ); |
| 241 | + assert.equal(item?.status, "cancelled"); |
| 242 | + const child = yield* orchestrator.getThreadProjection(task.childThreadId!); |
| 243 | + const childRoots = child.nodes.filter((node) => node.kind === "root_turn"); |
| 244 | + assert.isAbove(childRoots.length, 0); |
| 245 | + assert.isTrue(childRoots.every((node) => node.status === "cancelled")); |
| 246 | + }).pipe( |
| 247 | + Effect.provide( |
| 248 | + ProviderReplayHarness.layerWithRegistry( |
| 249 | + { name: "claude-orphaned-subagent" }, |
| 250 | + ProviderAdapterRegistry.layerSingle(adapter), |
| 251 | + { runEffectWorker: false }, |
| 252 | + ), |
| 253 | + ), |
| 254 | + ); |
| 255 | + }).pipe( |
| 256 | + Effect.provide( |
| 257 | + Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer), |
| 258 | + ), |
| 259 | + ), |
| 260 | + ), |
| 261 | +); |
0 commit comments