The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import type { SDKMessage, SDKUserMessage } from "@anthropic-ai/claude-agent-sdk"; |
| 2 | import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; |
| 3 | import * as NodeServices from "@effect/platform-node/NodeServices"; |
| 4 | import { assert, it } from "@effect/vitest"; |
| 5 | import { |
| 6 | ClaudeSettings, |
| 7 | CommandId, |
| 8 | EventId, |
| 9 | MessageId, |
| 10 | NodeId, |
| 11 | ProjectId, |
| 12 | ProviderInstanceId, |
| 13 | type RunId, |
| 14 | ScheduledTaskUpsertInput, |
| 15 | ThreadId, |
| 16 | type OrchestrationV2DomainEvent, |
| 17 | } from "@t3tools/contracts"; |
| 18 | import * as DateTime from "effect/DateTime"; |
| 19 | import * as Deferred from "effect/Deferred"; |
| 20 | import * as SecureRandom from "effect/crypto/SecureRandom"; |
| 21 | import * as Effect from "effect/Effect"; |
| 22 | import * as FileSystem from "effect/FileSystem"; |
| 23 | import * as Fiber from "effect/Fiber"; |
| 24 | import * as Layer from "effect/Layer"; |
| 25 | import * as Path from "effect/Path"; |
| 26 | import * as Queue from "effect/Queue"; |
| 27 | import * as Schema from "effect/Schema"; |
| 28 | import * as Stream from "effect/Stream"; |
| 29 | import * as ScheduledTaskService from "../scheduledTasks/ScheduledTaskService.ts"; |
| 30 | import * as ManagedPolicy from "../policy/ManagedPolicy.ts"; |
| 31 | import * as SecretRequests from "../secrets/SecretRequests.ts"; |
| 32 | import * as ManagedProjectFolders from "../project/ManagedProjectFolders.ts"; |
| 33 | import * as Scheduler from "../scheduling/Scheduler.ts"; |
| 34 | import * as SqlitePersistence from "../persistence/Sqlite.ts"; |
| 35 | import * as ClaudeAdapterV2 from "./Adapters/ClaudeAdapterV2.ts"; |
| 36 | import * as CommandReceiptStore from "./CommandReceiptStore.ts"; |
| 37 | import * as EffectWorker from "./EffectWorker.ts"; |
| 38 | import * as EventSink from "./EventSink.ts"; |
| 39 | import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator"; |
| 40 | import * as McpProviderSessions from "@t3tools/provider-core/server/McpProviderSessions"; |
| 41 | import * as ProviderContinuationRequests from "@t3tools/provider-core/server/ProviderContinuationRequests"; |
| 42 | import * as LegacyV1ThreadImporter from "./legacy/LegacyV1ThreadImporter.ts"; |
| 43 | import * as Orchestrator from "./Orchestrator.ts"; |
| 44 | import * as ProviderAdapterRegistry from "./ProviderAdapterRegistry.ts"; |
| 45 | import * as ThreadLaunchService from "./ThreadLaunchService.ts"; |
| 46 | import * as ThreadManagementService from "./ThreadManagementService.ts"; |
| 47 | import * as ServerSettings from "../serverSettings.ts"; |
| 48 | import * as ProviderReplayHarness from "./testkit/ProviderReplayHarness.ts"; |
| 49 | import { checkpointWorkspace } from "@t3tools/provider-testing/replayWorkspace"; |
| 50 | |
| 51 | const sessionId = "automatic-delivery-session"; |
| 52 | const settings = Schema.decodeSync(ClaudeSettings)({}); |
| 53 | const decodeScheduledTask = Schema.decodeEffect(ScheduledTaskUpsertInput); |
| 54 | const refusal = |
| 55 | "The user doesn't want to take this action right now. STOP what you are doing and wait for the user to tell you how to proceed."; |
| 56 | const statusIds = ["status-1", "status-2", "status-3", "status-4"]; |
| 57 | const modelSelection = { |
| 58 | instanceId: ProviderInstanceId.make("claudeAgent"), |
| 59 | model: "claude-sonnet-4-6", |
| 60 | }; |
| 61 | |
| 62 | function frame(value: unknown): SDKMessage { |
| 63 | return value as SDKMessage; |
| 64 | } |
| 65 | |
| 66 | const batch = frame({ |
| 67 | type: "assistant", |
| 68 | uuid: "batch", |
| 69 | session_id: sessionId, |
| 70 | parent_tool_use_id: null, |
| 71 | message: { |
| 72 | id: "tool-batch", |
| 73 | role: "assistant", |
| 74 | type: "message", |
| 75 | model: modelSelection.model, |
| 76 | content: [ |
| 77 | { type: "tool_use", id: "build", name: "Bash", input: { command: "make" } }, |
| 78 | ...statusIds.map((id) => ({ |
| 79 | type: "tool_use", |
| 80 | id, |
| 81 | name: "mcp__t3-code__task_status", |
| 82 | input: { taskId: id }, |
| 83 | })), |
| 84 | ], |
| 85 | stop_reason: "tool_use", |
| 86 | stop_sequence: null, |
| 87 | usage: { input_tokens: 1, output_tokens: 1 }, |
| 88 | }, |
| 89 | }); |
| 90 | |
| 91 | const toolResult = (id: string, cancelled: boolean) => |
| 92 | frame({ |
| 93 | type: "user", |
| 94 | uuid: `result-${id}`, |
| 95 | session_id: sessionId, |
| 96 | parent_tool_use_id: null, |
| 97 | message: { |
| 98 | role: "user", |
| 99 | content: [ |
| 100 | { |
| 101 | type: "tool_result", |
| 102 | tool_use_id: id, |
| 103 | is_error: cancelled, |
| 104 | content: cancelled ? refusal : id === "build" ? "build OK" : "Task completed normally", |
| 105 | }, |
| 106 | ], |
| 107 | }, |
| 108 | ...(cancelled ? { tool_result_meta: [{ id, non_execution_kind: "cancelled" }] } : {}), |
| 109 | }); |
| 110 | |
| 111 | const result = (uuid: string, aborted: boolean) => |
| 112 | frame({ |
| 113 | type: "result", |
| 114 | subtype: "success", |
| 115 | uuid, |
| 116 | session_id: sessionId, |
| 117 | is_error: false, |
| 118 | num_turns: 1, |
| 119 | result: "", |
| 120 | stop_reason: "end_turn", |
| 121 | terminal_reason: aborted ? "aborted_tools" : "completed", |
| 122 | permission_denials: [], |
| 123 | duration_ms: 1, |
| 124 | duration_api_ms: 1, |
| 125 | total_cost_usd: 0, |
| 126 | usage: { input_tokens: 1, output_tokens: 1 }, |
| 127 | modelUsage: {}, |
| 128 | }); |
| 129 | |
| 130 | const deliveries = [ |
| 131 | "child completion", |
| 132 | "scheduled message", |
| 133 | "user steering", |
| 134 | "promoted queued message", |
| 135 | ] as const; |
| 136 | |
| 137 | it.effect.each(deliveries)( |
| 138 | "delivers %s without Claude cancelling the pending tool calls in its batch", |
| 139 | (delivery) => |
| 140 | Effect.gen(function* () { |
| 141 | const cwd = yield* checkpointWorkspace("claude-automatic-delivery"); |
| 142 | const sdkMessages = yield* Queue.unbounded<SDKMessage>(); |
| 143 | const offers: SDKUserMessage[] = []; |
| 144 | const nativeQueue: SDKUserMessage[] = []; |
| 145 | // @effect-diagnostics-next-line abortControllerInEffect:off - The fake SDK interrupts its batch independently of the test fiber. |
| 146 | const batchAbort = new AbortController(); |
| 147 | const adapter = yield* ClaudeAdapterV2.makeClaudeAdapterV2({ |
| 148 | instanceId: modelSelection.instanceId, |
| 149 | settings, |
| 150 | environment: {}, |
| 151 | attachmentsDir: cwd, |
| 152 | fileSystem: yield* FileSystem.FileSystem, |
| 153 | path: yield* Path.Path, |
| 154 | random: yield* SecureRandom.SecureRandom, |
| 155 | idAllocator: yield* IdAllocator.IdAllocatorV2, |
| 156 | queryRunner: { |
| 157 | allocateSessionId: Effect.succeed(sessionId), |
| 158 | open: () => |
| 159 | Effect.succeed({ |
| 160 | messages: Stream.fromQueue(sdkMessages), |
| 161 | offer: (message) => |
| 162 | Effect.sync(() => { |
| 163 | offers.push(message); |
| 164 | nativeQueue.push(message); |
| 165 | // Claude Code 2.1.289 aborts on now-priority commands even while Bash blocks reads. |
| 166 | if (nativeQueue.some((command) => command.priority === "now")) { |
| 167 | batchAbort.abort({ kind: "interrupt" }); |
| 168 | } |
| 169 | }), |
| 170 | setModel: () => Effect.void, |
| 171 | applyFlagSettings: () => Effect.void, |
| 172 | setPermissionMode: () => Effect.void, |
| 173 | renameSession: () => Effect.void, |
| 174 | backgroundTasks: () => Effect.succeed(false), |
| 175 | mcpServerStatus: Effect.succeed([]), |
| 176 | readMcpResource: () => Effect.die("unexpected MCP resource read"), |
| 177 | callMcpTool: () => Effect.die("unexpected MCP tool call"), |
| 178 | mcpAuthenticate: () => Effect.die("unexpected MCP sign-in"), |
| 179 | mcpSubmitOAuthCallbackUrl: () => Effect.die("unexpected MCP sign-in"), |
| 180 | reconnectMcpServer: () => Effect.die("unexpected MCP reconnect"), |
| 181 | listPermissionRules: Effect.die("unexpected permission rules read"), |
| 182 | stopTask: () => Effect.void, |
| 183 | interrupt: Effect.die("automatic delivery must never interrupt"), |
| 184 | close: Effect.void, |
| 185 | }), |
| 186 | forkSession: () => Effect.die("unused"), |
| 187 | subagentLaunchToolUseId: () => Effect.succeed(null), |
| 188 | subagentModel: () => Effect.succeed(null), |
| 189 | assertComplete: Effect.void, |
| 190 | }, |
| 191 | }); |
| 192 | yield* Effect.gen(function* () { |
| 193 | const orchestrator = yield* Orchestrator.OrchestratorV2; |
| 194 | const worker = yield* EffectWorker.OrchestrationEffectWorkerV2; |
| 195 | const threadId = ThreadId.make("thread:automatic-delivery"); |
| 196 | const projectId = ProjectId.make("project:automatic-delivery"); |
| 197 | const watch = (predicate: (event: OrchestrationV2DomainEvent) => boolean) => |
| 198 | orchestrator.streamDomainEvents.pipe( |
| 199 | Stream.filter(predicate), |
| 200 | Stream.take(1), |
| 201 | Stream.runDrain, |
| 202 | Effect.forkScoped, |
| 203 | ); |
| 204 | yield* orchestrator.dispatch({ |
| 205 | type: "thread.create", |
| 206 | commandId: CommandId.make("create"), |
| 207 | threadId, |
| 208 | projectId, |
| 209 | title: "Automatic delivery", |
| 210 | modelSelection, |
| 211 | runtimeMode: "full-access", |
| 212 | interactionMode: "default", |
| 213 | branch: null, |
| 214 | worktreePath: cwd, |
| 215 | createdBy: "user", |
| 216 | creationSource: "web", |
| 217 | }); |
| 218 | const running = yield* watch( |
| 219 | (event) => event.type === "provider-turn.updated" && event.payload.status === "running", |
| 220 | ); |
| 221 | yield* orchestrator.dispatch({ |
| 222 | type: "message.dispatch", |
| 223 | commandId: CommandId.make("first"), |
| 224 | threadId, |
| 225 | messageId: MessageId.make("first"), |
| 226 | text: "Build and check all four tasks.", |
| 227 | attachments: [], |
| 228 | dispatchMode: { type: "start_immediately" }, |
| 229 | createdBy: "user", |
| 230 | creationSource: "web", |
| 231 | }); |
| 232 | yield* worker.drain(); |
| 233 | yield* Fiber.join(running); |
| 234 | const pending = yield* watch( |
| 235 | (event) => |
| 236 | event.type === "turn-item.updated" && |
| 237 | event.payload.nativeItemRef?.nativeId === "status-4", |
| 238 | ); |
| 239 | yield* Queue.offer(sdkMessages, batch); |
| 240 | yield* Fiber.join(pending); |
| 241 | const before = yield* orchestrator.getThreadProjection(threadId); |
| 242 | assert.equal(before.turnItems.filter((item) => item.status === "running").length, 5); |
| 243 | const parent = before.runs[0]!; |
| 244 | if (parent.rootNodeId === null) return yield* Effect.die("parent has no root node"); |
| 245 | const messageId = MessageId.make("automatic-notice"); |
| 246 | if (delivery === "child completion") { |
| 247 | const taskId = NodeId.make("completed-child"); |
| 248 | const now = yield* DateTime.now; |
| 249 | const sink = yield* EventSink.EventSinkV2; |
| 250 | yield* sink.write({ |
| 251 | events: [ |
| 252 | { |
| 253 | id: EventId.make("cohort"), |
| 254 | type: "run.updated", |
| 255 | threadId, |
| 256 | runId: parent.id, |
| 257 | occurredAt: now, |
| 258 | payload: { |
| 259 | ...parent, |
| 260 | delegatedCompletion: { |
| 261 | disposition: "open", |
| 262 | nextGeneration: 2, |
| 263 | delivery: { generation: 1, messageId, taskIds: [taskId] }, |
| 264 | }, |
| 265 | }, |
| 266 | }, |
| 267 | { |
| 268 | id: EventId.make("child"), |
| 269 | type: "subagent.updated", |
| 270 | threadId, |
| 271 | runId: parent.id, |
| 272 | nodeId: taskId, |
| 273 | occurredAt: now, |
| 274 | payload: { |
| 275 | id: taskId, |
| 276 | threadId, |
| 277 | runId: parent.id, |
| 278 | parentNodeId: parent.rootNodeId, |
| 279 | origin: "app_owned", |
| 280 | createdBy: "agent", |
| 281 | driver: ClaudeAdapterV2.CLAUDE_PROVIDER, |
| 282 | providerInstanceId: modelSelection.instanceId, |
| 283 | providerThreadId: null, |
| 284 | childThreadId: null, |
| 285 | nativeTaskRef: null, |
| 286 | prompt: "Background work", |
| 287 | title: "Child", |
| 288 | model: null, |
| 289 | completionWake: "always", |
| 290 | completionDelivery: { state: "claimed", observedByRunId: null }, |
| 291 | status: "completed", |
| 292 | result: "done", |
| 293 | startedAt: now, |
| 294 | completedAt: now, |
| 295 | updatedAt: now, |
| 296 | }, |
| 297 | }, |
| 298 | ], |
| 299 | }); |
| 300 | const command = { |
| 301 | type: "message.dispatch" as const, |
| 302 | commandId: CommandId.make("completion"), |
| 303 | threadId, |
| 304 | messageId, |
| 305 | text: "Child completed", |
| 306 | attachments: [], |
| 307 | dispatchMode: { type: "queue_after_active" as const }, |
| 308 | createdBy: "agent" as const, |
| 309 | creationSource: "server" as const, |
| 310 | delegatedCompletion: { parentRunId: parent.id, generation: 1, taskIds: [taskId] }, |
| 311 | }; |
| 312 | yield* orchestrator.dispatch(command); |
| 313 | yield* orchestrator.dispatch(command); |
| 314 | yield* orchestrator.recoverDelegatedTasks; |
| 315 | } else if (delivery === "scheduled message") { |
| 316 | yield* Effect.gen(function* () { |
| 317 | const service = yield* ScheduledTaskService.ScheduledTaskService; |
| 318 | const { task } = yield* service.upsert( |
| 319 | yield* decodeScheduledTask({ |
| 320 | title: "Status check", |
| 321 | prompt: "Check the four tasks.", |
| 322 | enabled: true, |
| 323 | schedule: { type: "interval", everyMs: 60_000 }, |
| 324 | projectId, |
| 325 | threadId, |
| 326 | workspaceStrategy: { type: "root" }, |
| 327 | modelSelection, |
| 328 | runtimeMode: "full-access", |
| 329 | interactionMode: "default", |
| 330 | }), |
| 331 | ); |
| 332 | const ran = yield* service.runNow({ id: task.id }); |
| 333 | assert.equal(ran.task.lastRunStatus, "succeeded"); |
| 334 | }).pipe( |
| 335 | Effect.provide( |
| 336 | ScheduledTaskService.layer.pipe( |
| 337 | Layer.provide(ThreadManagementService.layer), |
| 338 | Layer.provide(ServerSettings.layerTest()), |
| 339 | Layer.provide( |
| 340 | Layer.mock(LegacyV1ThreadImporter.LegacyV1ThreadImporter)({ |
| 341 | ensureTranscript: () => |
| 342 | Effect.succeed({ importedThreadCount: 0, importedMessageCount: 0 }), |
| 343 | }), |
| 344 | ), |
| 345 | Layer.provide(Layer.mock(ThreadLaunchService.ThreadLaunchService)({})), |
| 346 | Layer.provide(ManagedPolicy.layerTest()), |
| 347 | Layer.provide( |
| 348 | Layer.mock(ManagedProjectFolders.ManagedProjectFolders)({ |
| 349 | namedProjectsRoot: "/projects", |
| 350 | isScratchProject: () => Effect.succeed(false), |
| 351 | }), |
| 352 | ), |
| 353 | Layer.provide(Layer.mock(SecretRequests.SecretRequests)({})), |
| 354 | Layer.provide( |
| 355 | CommandReceiptStore.layer.pipe(Layer.provide(SqlitePersistence.layerMemory)), |
| 356 | ), |
| 357 | Layer.provide( |
| 358 | Layer.mergeAll(NodeCrypto.layer, Scheduler.layer, SqlitePersistence.layerMemory), |
| 359 | ), |
| 360 | ), |
| 361 | ), |
| 362 | ); |
| 363 | } else if (delivery === "user steering") { |
| 364 | yield* orchestrator.dispatch({ |
| 365 | type: "message.dispatch", |
| 366 | commandId: CommandId.make("steer"), |
| 367 | threadId, |
| 368 | messageId, |
| 369 | text: "Change direction now.", |
| 370 | attachments: [], |
| 371 | dispatchMode: { type: "steer_active", targetRunId: parent.id }, |
| 372 | createdBy: "user", |
| 373 | creationSource: "web", |
| 374 | }); |
| 375 | } else { |
| 376 | yield* orchestrator.dispatch({ |
| 377 | type: "message.dispatch", |
| 378 | commandId: CommandId.make("queue"), |
| 379 | threadId, |
| 380 | messageId, |
| 381 | text: "Change direction now.", |
| 382 | attachments: [], |
| 383 | dispatchMode: { type: "queue_after_active" }, |
| 384 | createdBy: "user", |
| 385 | creationSource: "web", |
| 386 | }); |
| 387 | const queuedRun = (yield* orchestrator.getThreadProjection(threadId)).runs[1]!; |
| 388 | yield* orchestrator.dispatch({ |
| 389 | type: "queued-message.promote-to-steer", |
| 390 | commandId: CommandId.make("promote"), |
| 391 | threadId, |
| 392 | queuedRunId: queuedRun.id, |
| 393 | targetRunId: parent.id, |
| 394 | }); |
| 395 | const promoted = yield* orchestrator.getThreadProjection(threadId); |
| 396 | assert.equal(promoted.runs.find((run) => run.id === queuedRun.id)?.status, "cancelled"); |
| 397 | assert.equal( |
| 398 | promoted.messages.find((message) => message.id === messageId)?.runId, |
| 399 | parent.id, |
| 400 | ); |
| 401 | const steer = promoted.turnItems.find( |
| 402 | (item) => item.type === "user_message" && item.messageId === messageId, |
| 403 | ); |
| 404 | assert.ok(steer?.type === "user_message"); |
| 405 | assert.equal(steer.inputIntent, "promoted_queued_to_steer"); |
| 406 | } |
| 407 | yield* worker.drain(); |
| 408 | const queuesBehindActiveTurn = delivery === "scheduled message"; |
| 409 | assert.equal(batchAbort.signal.aborted, false); |
| 410 | assert.lengthOf(offers, queuesBehindActiveTurn ? 1 : 2); |
| 411 | if (!queuesBehindActiveTurn) assert.equal(offers[1]?.priority, "next"); |
| 412 | const finished = yield* watch( |
| 413 | (event) => |
| 414 | event.type === "run.updated" && |
| 415 | event.payload.id === parent.id && |
| 416 | event.payload.status === "waiting", |
| 417 | ); |
| 418 | yield* Queue.offer(sdkMessages, toolResult("build", false)); |
| 419 | for (const id of statusIds) |
| 420 | yield* Queue.offer(sdkMessages, toolResult(id, batchAbort.signal.aborted)); |
| 421 | yield* Queue.offer( |
| 422 | sdkMessages, |
| 423 | delivery === "child completion" |
| 424 | ? frame({ ...result("completed", false), user_message_uuid: offers[1]!.uuid }) |
| 425 | : result("completed", false), |
| 426 | ); |
| 427 | yield* Fiber.join(finished); |
| 428 | yield* worker.drain(); |
| 429 | yield* orchestrator.resumeQueuedRuns; |
| 430 | yield* worker.drain(); |
| 431 | if (queuesBehindActiveTurn) { |
| 432 | const queued = (yield* orchestrator.getThreadProjection(threadId)).runs[1]!; |
| 433 | const noticeFinished = yield* watch( |
| 434 | (event) => |
| 435 | event.type === "run.updated" && |
| 436 | event.payload.id === queued.id && |
| 437 | event.payload.status === "waiting", |
| 438 | ); |
| 439 | yield* Queue.offer(sdkMessages, result("notice-completed", false)); |
| 440 | yield* Fiber.join(noticeFinished); |
| 441 | yield* worker.drain(); |
| 442 | } |
| 443 | const after = yield* orchestrator.getThreadProjection(threadId); |
| 444 | const reads = after.turnItems.filter((item) => |
| 445 | statusIds.includes(item.nativeItemRef?.nativeId ?? ""), |
| 446 | ); |
| 447 | assert.equal(reads.length, 4); |
| 448 | for (const read of reads) { |
| 449 | assert.equal(read.status, "completed"); |
| 450 | assert.equal(read.toolNonExecutionKind, undefined); |
| 451 | assert.equal(read.type === "dynamic_tool" && read.output === refusal, false); |
| 452 | } |
| 453 | assert.lengthOf(offers, 2); |
| 454 | assert.equal(offers.filter((offer) => offer.priority === "now").length, 0); |
| 455 | if (delivery === "child completion") { |
| 456 | assert.lengthOf(after.runs, 1); |
| 457 | assert.deepEqual( |
| 458 | after.messages |
| 459 | .filter((message) => message.id === messageId) |
| 460 | .map((message) => message.runId), |
| 461 | [parent.id], |
| 462 | ); |
| 463 | assert.equal(after.subagents[0]?.completionDelivery?.state, "delivered"); |
| 464 | } else if (queuesBehindActiveTurn) { |
| 465 | assert.lengthOf(after.runs, 2); |
| 466 | assert.equal( |
| 467 | after.messages.filter((message) => message.scheduledTaskId !== undefined).length, |
| 468 | 1, |
| 469 | ); |
| 470 | } |
| 471 | yield* orchestrator.recoverDelegatedTasks; |
| 472 | yield* orchestrator.resumeQueuedRuns; |
| 473 | yield* worker.drain(); |
| 474 | assert.equal(offers.length, 2); |
| 475 | }).pipe( |
| 476 | Effect.provide( |
| 477 | ProviderReplayHarness.layerWithRegistry( |
| 478 | { name: "claude-automatic-delivery" }, |
| 479 | ProviderAdapterRegistry.layerSingle(adapter), |
| 480 | { runEffectWorker: false }, |
| 481 | ), |
| 482 | ), |
| 483 | ); |
| 484 | }).pipe( |
| 485 | Effect.provide( |
| 486 | Layer.mergeAll( |
| 487 | IdAllocator.layer, |
| 488 | McpProviderSessions.layer, |
| 489 | NodeServices.layer, |
| 490 | NodeCrypto.layer, |
| 491 | ), |
| 492 | ), |
| 493 | ), |
| 494 | ); |
| 495 | |
| 496 | it.effect("applies an effort change to the running Claude query without waiting for a turn", () => |
| 497 | Effect.gen(function* () { |
| 498 | const cwd = yield* checkpointWorkspace("claude-live-effort"); |
| 499 | const sdkMessages = yield* Queue.unbounded<SDKMessage>(); |
| 500 | const flagSettings: unknown[] = []; |
| 501 | const adapter = yield* ClaudeAdapterV2.makeClaudeAdapterV2({ |
| 502 | instanceId: modelSelection.instanceId, |
| 503 | settings, |
| 504 | environment: {}, |
| 505 | attachmentsDir: cwd, |
| 506 | fileSystem: yield* FileSystem.FileSystem, |
| 507 | path: yield* Path.Path, |
| 508 | random: yield* SecureRandom.SecureRandom, |
| 509 | idAllocator: yield* IdAllocator.IdAllocatorV2, |
| 510 | queryRunner: { |
| 511 | allocateSessionId: Effect.succeed(sessionId), |
| 512 | open: () => |
| 513 | Effect.succeed({ |
| 514 | messages: Stream.fromQueue(sdkMessages), |
| 515 | offer: () => Effect.void, |
| 516 | setModel: () => Effect.void, |
| 517 | applyFlagSettings: (flags) => |
| 518 | Effect.sync(() => { |
| 519 | flagSettings.push(flags); |
| 520 | }), |
| 521 | setPermissionMode: () => Effect.void, |
| 522 | renameSession: () => Effect.void, |
| 523 | backgroundTasks: () => Effect.succeed(false), |
| 524 | mcpServerStatus: Effect.succeed([]), |
| 525 | readMcpResource: () => Effect.die("unexpected MCP resource read"), |
| 526 | callMcpTool: () => Effect.die("unexpected MCP tool call"), |
| 527 | mcpAuthenticate: () => Effect.die("unexpected MCP sign-in"), |
| 528 | mcpSubmitOAuthCallbackUrl: () => Effect.die("unexpected MCP sign-in"), |
| 529 | reconnectMcpServer: () => Effect.die("unexpected MCP reconnect"), |
| 530 | listPermissionRules: Effect.die("unexpected permission rules read"), |
| 531 | stopTask: () => Effect.void, |
| 532 | interrupt: Effect.die("an effort change must not interrupt the turn"), |
| 533 | close: Effect.void, |
| 534 | }), |
| 535 | forkSession: () => Effect.die("unused"), |
| 536 | subagentLaunchToolUseId: () => Effect.succeed(null), |
| 537 | subagentModel: () => Effect.succeed(null), |
| 538 | assertComplete: Effect.void, |
| 539 | }, |
| 540 | }); |
| 541 | yield* Effect.gen(function* () { |
| 542 | const orchestrator = yield* Orchestrator.OrchestratorV2; |
| 543 | const worker = yield* EffectWorker.OrchestrationEffectWorkerV2; |
| 544 | const threadId = ThreadId.make("thread:live-effort"); |
| 545 | const high = { ...modelSelection, options: [{ id: "effort", value: "high" }] }; |
| 546 | const running = yield* orchestrator.streamDomainEvents.pipe( |
| 547 | Stream.filter( |
| 548 | (event) => event.type === "provider-turn.updated" && event.payload.status === "running", |
| 549 | ), |
| 550 | Stream.take(1), |
| 551 | Stream.runDrain, |
| 552 | Effect.forkScoped, |
| 553 | ); |
| 554 | yield* orchestrator.dispatch({ |
| 555 | type: "thread.create", |
| 556 | commandId: CommandId.make("create"), |
| 557 | threadId, |
| 558 | projectId: ProjectId.make("project:live-effort"), |
| 559 | title: "Live effort", |
| 560 | modelSelection: high, |
| 561 | runtimeMode: "full-access", |
| 562 | interactionMode: "default", |
| 563 | branch: null, |
| 564 | worktreePath: cwd, |
| 565 | createdBy: "user", |
| 566 | creationSource: "web", |
| 567 | }); |
| 568 | yield* orchestrator.dispatch({ |
| 569 | type: "message.dispatch", |
| 570 | commandId: CommandId.make("first"), |
| 571 | threadId, |
| 572 | messageId: MessageId.make("first"), |
| 573 | text: "Keep working.", |
| 574 | attachments: [], |
| 575 | dispatchMode: { type: "start_immediately" }, |
| 576 | createdBy: "user", |
| 577 | creationSource: "web", |
| 578 | }); |
| 579 | yield* worker.drain(); |
| 580 | yield* Fiber.join(running); |
| 581 | assert.deepEqual(flagSettings, []); |
| 582 | |
| 583 | yield* orchestrator.dispatch({ |
| 584 | type: "thread.model-selection.set", |
| 585 | commandId: CommandId.make("medium"), |
| 586 | threadId, |
| 587 | modelSelection: { ...modelSelection, options: [{ id: "effort", value: "medium" }] }, |
| 588 | }); |
| 589 | yield* worker.drain(); |
| 590 | |
| 591 | assert.deepEqual(flagSettings, [{ effortLevel: "medium", fastMode: null, ultracode: null }]); |
| 592 | }).pipe( |
| 593 | Effect.provide( |
| 594 | ProviderReplayHarness.layerWithRegistry( |
| 595 | { name: "claude-live-effort" }, |
| 596 | ProviderAdapterRegistry.layerSingle(adapter), |
| 597 | { runEffectWorker: false }, |
| 598 | ), |
| 599 | ), |
| 600 | ); |
| 601 | }).pipe( |
| 602 | Effect.provide( |
| 603 | Layer.mergeAll( |
| 604 | IdAllocator.layer, |
| 605 | McpProviderSessions.layer, |
| 606 | NodeServices.layer, |
| 607 | NodeCrypto.layer, |
| 608 | ), |
| 609 | ), |
| 610 | ), |
| 611 | ); |
| 612 | |
| 613 | const renamedClaudeSessionTitles = (options: { readonly renameDuringStartup: boolean }) => |
| 614 | Effect.gen(function* () { |
| 615 | const cwd = yield* checkpointWorkspace("claude-live-rename"); |
| 616 | const sdkMessages = yield* Queue.unbounded<SDKMessage>(); |
| 617 | const renames: string[] = []; |
| 618 | const startupEntered = yield* Deferred.make<void>(); |
| 619 | const startupReleased = yield* Deferred.make<void>(); |
| 620 | const adapter = yield* ClaudeAdapterV2.makeClaudeAdapterV2({ |
| 621 | instanceId: modelSelection.instanceId, |
| 622 | settings, |
| 623 | environment: {}, |
| 624 | attachmentsDir: cwd, |
| 625 | fileSystem: yield* FileSystem.FileSystem, |
| 626 | path: yield* Path.Path, |
| 627 | random: yield* SecureRandom.SecureRandom, |
| 628 | idAllocator: yield* IdAllocator.IdAllocatorV2, |
| 629 | queryRunner: { |
| 630 | allocateSessionId: Effect.succeed(sessionId), |
| 631 | open: () => |
| 632 | Effect.succeed({ |
| 633 | messages: Stream.fromQueue(sdkMessages), |
| 634 | offer: () => Effect.void, |
| 635 | setModel: () => Effect.void, |
| 636 | applyFlagSettings: () => Effect.void, |
| 637 | setPermissionMode: () => Effect.void, |
| 638 | renameSession: (title) => |
| 639 | Effect.sync(() => { |
| 640 | renames.push(title); |
| 641 | }), |
| 642 | backgroundTasks: () => Effect.succeed(false), |
| 643 | mcpServerStatus: Effect.succeed([]), |
| 644 | readMcpResource: () => Effect.die("unexpected MCP resource read"), |
| 645 | callMcpTool: () => Effect.die("unexpected MCP tool call"), |
| 646 | mcpAuthenticate: () => Effect.die("unexpected MCP sign-in"), |
| 647 | mcpSubmitOAuthCallbackUrl: () => Effect.die("unexpected MCP sign-in"), |
| 648 | reconnectMcpServer: () => Effect.die("unexpected MCP reconnect"), |
| 649 | listPermissionRules: Effect.die("unexpected permission rules read"), |
| 650 | stopTask: () => Effect.void, |
| 651 | interrupt: Effect.die("a rename must not interrupt the turn"), |
| 652 | close: Effect.void, |
| 653 | }), |
| 654 | forkSession: () => Effect.die("unused"), |
| 655 | subagentLaunchToolUseId: () => Effect.succeed(null), |
| 656 | subagentModel: () => Effect.succeed(null), |
| 657 | assertComplete: Effect.void, |
| 658 | }, |
| 659 | }); |
| 660 | return yield* Effect.gen(function* () { |
| 661 | const orchestrator = yield* Orchestrator.OrchestratorV2; |
| 662 | const worker = yield* EffectWorker.OrchestrationEffectWorkerV2; |
| 663 | const threadId = ThreadId.make("thread:live-rename"); |
| 664 | const running = yield* orchestrator.streamDomainEvents.pipe( |
| 665 | Stream.filter( |
| 666 | (event) => event.type === "provider-turn.updated" && event.payload.status === "running", |
| 667 | ), |
| 668 | Stream.take(1), |
| 669 | Stream.runDrain, |
| 670 | Effect.forkScoped, |
| 671 | ); |
| 672 | yield* orchestrator.dispatch({ |
| 673 | type: "thread.create", |
| 674 | commandId: CommandId.make("create"), |
| 675 | threadId, |
| 676 | projectId: ProjectId.make("project:live-rename"), |
| 677 | title: "Seed title", |
| 678 | modelSelection, |
| 679 | runtimeMode: "full-access", |
| 680 | interactionMode: "default", |
| 681 | branch: null, |
| 682 | worktreePath: cwd, |
| 683 | createdBy: "user", |
| 684 | creationSource: "web", |
| 685 | }); |
| 686 | yield* orchestrator.dispatch({ |
| 687 | type: "message.dispatch", |
| 688 | commandId: CommandId.make("first"), |
| 689 | threadId, |
| 690 | messageId: MessageId.make("first"), |
| 691 | text: "Keep working.", |
| 692 | attachments: [], |
| 693 | dispatchMode: { type: "start_immediately" }, |
| 694 | createdBy: "user", |
| 695 | creationSource: "web", |
| 696 | }); |
| 697 | const rename = orchestrator.dispatch({ |
| 698 | type: "thread.metadata.update", |
| 699 | commandId: CommandId.make("rename"), |
| 700 | threadId, |
| 701 | title: "Renamed title", |
| 702 | }); |
| 703 | if (options.renameDuringStartup) { |
| 704 | const starting = yield* worker.drain().pipe(Effect.forkScoped); |
| 705 | yield* Deferred.await(startupEntered); |
| 706 | yield* rename; |
| 707 | yield* Deferred.succeed(startupReleased, undefined); |
| 708 | yield* Fiber.join(starting); |
| 709 | yield* Fiber.join(running); |
| 710 | } else { |
| 711 | yield* worker.drain(); |
| 712 | yield* Fiber.join(running); |
| 713 | assert.deepEqual(renames, []); |
| 714 | yield* rename; |
| 715 | } |
| 716 | yield* worker.drain(); |
| 717 | return renames; |
| 718 | }).pipe( |
| 719 | Effect.provide( |
| 720 | ProviderReplayHarness.layerWithRegistry( |
| 721 | { name: "claude-live-rename" }, |
| 722 | ProviderAdapterRegistry.layerSingle({ |
| 723 | ...adapter, |
| 724 | openSession: (input) => |
| 725 | options.renameDuringStartup |
| 726 | ? Deferred.succeed(startupEntered, undefined).pipe( |
| 727 | Effect.andThen(Deferred.await(startupReleased)), |
| 728 | Effect.andThen(adapter.openSession(input)), |
| 729 | ) |
| 730 | : adapter.openSession(input), |
| 731 | }), |
| 732 | { runEffectWorker: false }, |
| 733 | ), |
| 734 | ), |
| 735 | ); |
| 736 | }).pipe( |
| 737 | Effect.provide( |
| 738 | Layer.mergeAll( |
| 739 | IdAllocator.layer, |
| 740 | McpProviderSessions.layer, |
| 741 | NodeServices.layer, |
| 742 | NodeCrypto.layer, |
| 743 | ), |
| 744 | ), |
| 745 | ); |
| 746 | |
| 747 | it.effect("renames the running Claude session when the thread is renamed mid-turn", () => |
| 748 | Effect.gen(function* () { |
| 749 | assert.deepEqual(yield* renamedClaudeSessionTitles({ renameDuringStartup: false }), [ |
| 750 | "Renamed title", |
| 751 | ]); |
| 752 | }), |
| 753 | ); |
| 754 | |
| 755 | it.effect("renames the Claude session when the thread is renamed while it starts", () => |
| 756 | Effect.gen(function* () { |
| 757 | assert.deepEqual(yield* renamedClaudeSessionTitles({ renameDuringStartup: true }), [ |
| 758 | "Renamed title", |
| 759 | ]); |
| 760 | }), |
| 761 | ); |
| 762 | |
| 763 | const backgroundTaskStarted = (taskId: string) => |
| 764 | frame({ |
| 765 | type: "system", |
| 766 | subtype: "task_started", |
| 767 | task_id: taskId, |
| 768 | tool_use_id: `tool-${taskId}`, |
| 769 | description: "Background build", |
| 770 | is_backgrounded: true, |
| 771 | task_type: "local_bash", |
| 772 | uuid: `started-${taskId}`, |
| 773 | session_id: sessionId, |
| 774 | }); |
| 775 | |
| 776 | const backgroundTaskNotification = (taskId: string) => |
| 777 | frame({ |
| 778 | type: "system", |
| 779 | subtype: "task_notification", |
| 780 | task_id: taskId, |
| 781 | tool_use_id: `tool-${taskId}`, |
| 782 | status: "completed", |
| 783 | output_file: `/tmp/claude-replay/tasks/${taskId}.output`, |
| 784 | summary: `Background build ${taskId} completed`, |
| 785 | uuid: `notification-${taskId}`, |
| 786 | session_id: sessionId, |
| 787 | }); |
| 788 | |
| 789 | const wakeAssistant = (uuid: string) => |
| 790 | frame({ |
| 791 | type: "assistant", |
| 792 | uuid, |
| 793 | session_id: sessionId, |
| 794 | parent_tool_use_id: null, |
| 795 | message: { |
| 796 | id: `msg-${uuid}`, |
| 797 | role: "assistant", |
| 798 | type: "message", |
| 799 | model: modelSelection.model, |
| 800 | content: [{ type: "text", text: `Background build finished (${uuid}).` }], |
| 801 | stop_reason: null, |
| 802 | stop_sequence: null, |
| 803 | usage: { input_tokens: 1, output_tokens: 1 }, |
| 804 | }, |
| 805 | }); |
| 806 | |
| 807 | it.effect("offers a continuation for a later wake after a queued continuation is cancelled", () => |
| 808 | Effect.gen(function* () { |
| 809 | const cwd = yield* checkpointWorkspace("claude-cancelled-continuation"); |
| 810 | const sdkMessages = yield* Queue.unbounded<SDKMessage>(); |
| 811 | const processed = new WeakMap<SDKMessage, Deferred.Deferred<void>>(); |
| 812 | const offerAndWait = Effect.fnUntraced(function* (message: SDKMessage) { |
| 813 | const done = yield* Deferred.make<void>(); |
| 814 | processed.set(message, done); |
| 815 | yield* Queue.offer(sdkMessages, message); |
| 816 | yield* Deferred.await(done); |
| 817 | }); |
| 818 | const fileSystem = yield* FileSystem.FileSystem; |
| 819 | const path = yield* Path.Path; |
| 820 | const random = yield* SecureRandom.SecureRandom; |
| 821 | const idAllocator = yield* IdAllocator.IdAllocatorV2; |
| 822 | const continuations: ProviderContinuationRequests.ProviderContinuationRequest[] = []; |
| 823 | const services = |
| 824 | yield* Effect.context< |
| 825 | Effect.Services<ReturnType<typeof ClaudeAdapterV2.makeClaudeAdapterV2>> |
| 826 | >(); |
| 827 | const registry = ProviderAdapterRegistry.layerFromAdaptersEffect( |
| 828 | Effect.gen(function* () { |
| 829 | const requests = yield* ProviderContinuationRequests.ProviderContinuationRequests; |
| 830 | const adapter = yield* ClaudeAdapterV2.makeClaudeAdapterV2({ |
| 831 | instanceId: modelSelection.instanceId, |
| 832 | settings, |
| 833 | environment: {}, |
| 834 | attachmentsDir: cwd, |
| 835 | fileSystem, |
| 836 | path, |
| 837 | random, |
| 838 | idAllocator, |
| 839 | continuationRequests: { |
| 840 | offer: (request) => |
| 841 | Effect.sync(() => continuations.push(request)).pipe( |
| 842 | Effect.andThen(requests.offer(request)), |
| 843 | ), |
| 844 | }, |
| 845 | queryRunner: { |
| 846 | allocateSessionId: Effect.succeed(sessionId), |
| 847 | open: () => |
| 848 | Effect.succeed({ |
| 849 | // Resolve each frame's Deferred once the adapter pulls the next one. |
| 850 | messages: Stream.fromQueue(sdkMessages).pipe( |
| 851 | Stream.flatMap((message) => |
| 852 | Stream.make(message).pipe( |
| 853 | Stream.concat( |
| 854 | Stream.fromEffect( |
| 855 | Effect.suspend(() => { |
| 856 | const done = processed.get(message); |
| 857 | return done === undefined |
| 858 | ? Effect.void |
| 859 | : Deferred.succeed(done, undefined); |
| 860 | }), |
| 861 | ).pipe(Stream.drain), |
| 862 | ), |
| 863 | ), |
| 864 | ), |
| 865 | ), |
| 866 | offer: () => Effect.void, |
| 867 | setModel: () => Effect.void, |
| 868 | applyFlagSettings: () => Effect.void, |
| 869 | setPermissionMode: () => Effect.void, |
| 870 | renameSession: () => Effect.void, |
| 871 | backgroundTasks: () => Effect.succeed(false), |
| 872 | mcpServerStatus: Effect.succeed([]), |
| 873 | readMcpResource: () => Effect.die("unexpected MCP resource read"), |
| 874 | callMcpTool: () => Effect.die("unexpected MCP tool call"), |
| 875 | mcpAuthenticate: () => Effect.die("unexpected MCP sign-in"), |
| 876 | mcpSubmitOAuthCallbackUrl: () => Effect.die("unexpected MCP sign-in"), |
| 877 | reconnectMcpServer: () => Effect.die("unexpected MCP reconnect"), |
| 878 | listPermissionRules: Effect.die("unexpected permission rules read"), |
| 879 | stopTask: () => Effect.void, |
| 880 | interrupt: Effect.void, |
| 881 | close: Effect.void, |
| 882 | }), |
| 883 | forkSession: () => Effect.die("unused"), |
| 884 | subagentLaunchToolUseId: () => Effect.succeed(null), |
| 885 | subagentModel: () => Effect.succeed(null), |
| 886 | assertComplete: Effect.void, |
| 887 | }, |
| 888 | }).pipe(Effect.provideContext(services)); |
| 889 | return [adapter]; |
| 890 | }), |
| 891 | ); |
| 892 | yield* Effect.gen(function* () { |
| 893 | const orchestrator = yield* Orchestrator.OrchestratorV2; |
| 894 | const worker = yield* EffectWorker.OrchestrationEffectWorkerV2; |
| 895 | const threadId = ThreadId.make("thread:cancelled-continuation"); |
| 896 | const watch = (predicate: (event: OrchestrationV2DomainEvent) => boolean) => |
| 897 | orchestrator.streamDomainEvents.pipe( |
| 898 | Stream.filter(predicate), |
| 899 | Stream.take(1), |
| 900 | Stream.runDrain, |
| 901 | Effect.forkScoped, |
| 902 | ); |
| 903 | const runUpdated = (messageId: string, status: string) => |
| 904 | watch( |
| 905 | (event) => |
| 906 | event.type === "run.updated" && |
| 907 | event.payload.userMessageId === messageId && |
| 908 | event.payload.status === status, |
| 909 | ); |
| 910 | // A user turn that leaves a background task running when it ends. |
| 911 | const userTurnWithBackgroundTask = Effect.fnUntraced(function* (id: string, taskId: string) { |
| 912 | const running = yield* runUpdated(id, "running"); |
| 913 | yield* orchestrator.dispatch({ |
| 914 | type: "message.dispatch", |
| 915 | commandId: CommandId.make(id), |
| 916 | threadId, |
| 917 | messageId: MessageId.make(id), |
| 918 | text: "Run the build in the background.", |
| 919 | attachments: [], |
| 920 | dispatchMode: { type: "start_immediately" }, |
| 921 | createdBy: "user", |
| 922 | creationSource: "web", |
| 923 | }); |
| 924 | yield* worker.drain(); |
| 925 | yield* Fiber.join(running); |
| 926 | const waiting = yield* runUpdated(id, "waiting"); |
| 927 | yield* Queue.offer(sdkMessages, backgroundTaskStarted(taskId)); |
| 928 | yield* Queue.offer(sdkMessages, result(`result-${id}`, false)); |
| 929 | yield* Fiber.join(waiting); |
| 930 | }); |
| 931 | yield* orchestrator.dispatch({ |
| 932 | type: "thread.create", |
| 933 | commandId: CommandId.make("create"), |
| 934 | threadId, |
| 935 | projectId: ProjectId.make("project:cancelled-continuation"), |
| 936 | title: "Cancelled continuation", |
| 937 | modelSelection, |
| 938 | runtimeMode: "full-access", |
| 939 | interactionMode: "default", |
| 940 | branch: null, |
| 941 | worktreePath: cwd, |
| 942 | createdBy: "user", |
| 943 | creationSource: "web", |
| 944 | }); |
| 945 | |
| 946 | // The first run is still finalizing when its background task wakes Claude. |
| 947 | yield* userTurnWithBackgroundTask("first", "build-1"); |
| 948 | const queued = yield* watch( |
| 949 | (event) => event.type === "run.created" && event.payload.status === "queued", |
| 950 | ); |
| 951 | yield* offerAndWait(backgroundTaskNotification("build-1")); |
| 952 | yield* offerAndWait(wakeAssistant("wake-1")); |
| 953 | yield* Fiber.join(queued); |
| 954 | assert.lengthOf(continuations, 1); |
| 955 | const continuationRun = (yield* orchestrator.getThreadProjection(threadId)).runs.find( |
| 956 | (run) => run.status === "queued", |
| 957 | ); |
| 958 | assert.ok(continuationRun !== undefined); |
| 959 | yield* orchestrator.dispatch({ |
| 960 | type: "queued-run.cancel", |
| 961 | commandId: CommandId.make("cancel"), |
| 962 | threadId, |
| 963 | runId: continuationRun.id, |
| 964 | }); |
| 965 | yield* offerAndWait(result("wake-1-result", false)); |
| 966 | yield* worker.drain(); |
| 967 | yield* orchestrator.resumeQueuedRuns; |
| 968 | yield* worker.drain(); |
| 969 | const idle = yield* orchestrator.getThreadProjection(threadId); |
| 970 | assert.equal(idle.runs.find((run) => run.id === continuationRun.id)?.status, "cancelled"); |
| 971 | assert.isFalse(idle.runs.some((run) => run.status === "queued")); |
| 972 | |
| 973 | yield* userTurnWithBackgroundTask("second", "build-2"); |
| 974 | yield* worker.drain(); |
| 975 | // The second user run has completed, so this continuation starts without queueing. |
| 976 | const isContinuationRun = (event: OrchestrationV2DomainEvent, type: string, status: string) => |
| 977 | (event.type === "run.created" || event.type === "run.updated") && |
| 978 | event.type === type && |
| 979 | event.payload.status === status && |
| 980 | event.payload.userMessageId !== MessageId.make("first") && |
| 981 | event.payload.userMessageId !== MessageId.make("second"); |
| 982 | const secondCreated = yield* watch((event) => |
| 983 | isContinuationRun(event, "run.created", "starting"), |
| 984 | ); |
| 985 | const secondRunning = yield* watch((event) => |
| 986 | isContinuationRun(event, "run.updated", "running"), |
| 987 | ); |
| 988 | yield* offerAndWait(backgroundTaskNotification("build-2")); |
| 989 | yield* offerAndWait(wakeAssistant("wake-2")); |
| 990 | assert.lengthOf( |
| 991 | continuations, |
| 992 | 2, |
| 993 | "the wake after a cancelled queued continuation must offer a new continuation", |
| 994 | ); |
| 995 | yield* Fiber.join(secondCreated); |
| 996 | yield* worker.drain(); |
| 997 | yield* Fiber.join(secondRunning); |
| 998 | const secondContinuation = (yield* orchestrator.getThreadProjection(threadId)).runs.find( |
| 999 | (run) => run.status === "running", |
| 1000 | ); |
| 1001 | assert.ok(secondContinuation !== undefined); |
| 1002 | const secondWaiting = yield* watch( |
| 1003 | (event) => |
| 1004 | event.type === "run.updated" && |
| 1005 | event.payload.id === secondContinuation.id && |
| 1006 | event.payload.status === "waiting", |
| 1007 | ); |
| 1008 | yield* offerAndWait(result("wake-2-result", false)); |
| 1009 | yield* Fiber.join(secondWaiting); |
| 1010 | yield* worker.drain(); |
| 1011 | const settled = yield* orchestrator.getThreadProjection(threadId); |
| 1012 | assert.equal( |
| 1013 | settled.runs.find((run) => run.id === secondContinuation.id)?.status, |
| 1014 | "completed", |
| 1015 | ); |
| 1016 | assert.deepEqual( |
| 1017 | settled.turnItems.flatMap((item) => |
| 1018 | item.runId === secondContinuation.id && item.type === "assistant_message" |
| 1019 | ? [item.text] |
| 1020 | : [], |
| 1021 | ), |
| 1022 | ["Background build finished (wake-2)."], |
| 1023 | "the continuation must carry only its own wake's output", |
| 1024 | ); |
| 1025 | assert.lengthOf(continuations, 2, "two wakes must offer exactly two continuations"); |
| 1026 | }).pipe( |
| 1027 | Effect.provide( |
| 1028 | ProviderReplayHarness.layerWithRegistry( |
| 1029 | { name: "claude-cancelled-continuation" }, |
| 1030 | registry, |
| 1031 | { runEffectWorker: false, runContinuationWorker: true }, |
| 1032 | ), |
| 1033 | ), |
| 1034 | ); |
| 1035 | }).pipe( |
| 1036 | Effect.provide( |
| 1037 | Layer.mergeAll( |
| 1038 | IdAllocator.layer, |
| 1039 | McpProviderSessions.layer, |
| 1040 | NodeServices.layer, |
| 1041 | NodeCrypto.layer, |
| 1042 | ), |
| 1043 | ), |
| 1044 | ), |
| 1045 | ); |
| 1046 | |
| 1047 | // A steer Claude never read runs as the next turn, between the messages sent before and after |
| 1048 | // it, even when they share a millisecond and the later one picks another model. |
| 1049 | it.effect.each([ |
| 1050 | "Claude cancels it twice", |
| 1051 | "the Claude process exits", |
| 1052 | "the server restarts", |
| 1053 | "Claude cancels it and the user stops", |
| 1054 | ] as const)("handles an unread steer when %s", (outcome) => |
| 1055 | Effect.gen(function* () { |
| 1056 | const cwd = yield* checkpointWorkspace("claude-unread-steer"); |
| 1057 | const sdkMessages = yield* Queue.unbounded<SDKMessage>(); |
| 1058 | const offers: SDKUserMessage[] = []; |
| 1059 | const adapter = yield* ClaudeAdapterV2.makeClaudeAdapterV2({ |
| 1060 | instanceId: modelSelection.instanceId, |
| 1061 | settings, |
| 1062 | environment: {}, |
| 1063 | attachmentsDir: cwd, |
| 1064 | fileSystem: yield* FileSystem.FileSystem, |
| 1065 | path: yield* Path.Path, |
| 1066 | random: yield* SecureRandom.SecureRandom, |
| 1067 | idAllocator: yield* IdAllocator.IdAllocatorV2, |
| 1068 | queryRunner: { |
| 1069 | allocateSessionId: Effect.succeed(sessionId), |
| 1070 | open: () => |
| 1071 | Effect.succeed({ |
| 1072 | messages: Stream.fromQueue(sdkMessages), |
| 1073 | offer: (message) => Effect.sync(() => void offers.push(message)), |
| 1074 | setModel: () => Effect.void, |
| 1075 | applyFlagSettings: () => Effect.void, |
| 1076 | setPermissionMode: () => Effect.void, |
| 1077 | renameSession: () => Effect.void, |
| 1078 | backgroundTasks: () => Effect.succeed(false), |
| 1079 | mcpServerStatus: Effect.succeed([]), |
| 1080 | readMcpResource: () => Effect.die("unexpected MCP resource read"), |
| 1081 | callMcpTool: () => Effect.die("unexpected MCP tool call"), |
| 1082 | mcpAuthenticate: () => Effect.die("unexpected MCP sign-in"), |
| 1083 | mcpSubmitOAuthCallbackUrl: () => Effect.die("unexpected MCP sign-in"), |
| 1084 | reconnectMcpServer: () => Effect.die("unexpected MCP reconnect"), |
| 1085 | listPermissionRules: Effect.die("unexpected permission rules read"), |
| 1086 | stopTask: () => Effect.void, |
| 1087 | interrupt: Queue.shutdown(sdkMessages), |
| 1088 | close: Effect.void, |
| 1089 | }), |
| 1090 | forkSession: () => Effect.die("unused"), |
| 1091 | subagentLaunchToolUseId: () => Effect.succeed(null), |
| 1092 | subagentModel: () => Effect.succeed(null), |
| 1093 | assertComplete: Effect.void, |
| 1094 | }, |
| 1095 | }); |
| 1096 | yield* Effect.gen(function* () { |
| 1097 | const orchestrator = yield* Orchestrator.OrchestratorV2; |
| 1098 | const worker = yield* EffectWorker.OrchestrationEffectWorkerV2; |
| 1099 | const threadId = ThreadId.make("thread:unread-steer"); |
| 1100 | const steerId = MessageId.make("steer"); |
| 1101 | const watch = (predicate: (event: OrchestrationV2DomainEvent) => boolean) => |
| 1102 | orchestrator.streamDomainEvents.pipe( |
| 1103 | Stream.filter(predicate), |
| 1104 | Stream.take(1), |
| 1105 | Stream.runDrain, |
| 1106 | Effect.forkScoped, |
| 1107 | ); |
| 1108 | const settled = (runId: RunId, status: "waiting") => |
| 1109 | watch( |
| 1110 | (event) => |
| 1111 | event.type === "run.updated" && |
| 1112 | event.payload.id === runId && |
| 1113 | event.payload.status === status, |
| 1114 | ); |
| 1115 | const pending = () => |
| 1116 | watch( |
| 1117 | (event) => |
| 1118 | event.type === "turn-item.updated" && |
| 1119 | event.payload.type === "user_message" && |
| 1120 | event.payload.messageId === steerId && |
| 1121 | event.payload.status === "pending", |
| 1122 | ); |
| 1123 | const answer = (offer: SDKUserMessage) => |
| 1124 | Queue.offer( |
| 1125 | sdkMessages, |
| 1126 | frame({ |
| 1127 | ...(result(`result-${offer.uuid}`, false) as object), |
| 1128 | user_message_uuid: offer.uuid, |
| 1129 | }), |
| 1130 | ); |
| 1131 | const cancel = (offer: SDKUserMessage) => |
| 1132 | Queue.offer( |
| 1133 | sdkMessages, |
| 1134 | frame({ |
| 1135 | type: "command_lifecycle", |
| 1136 | command_uuid: offer.uuid, |
| 1137 | state: "cancelled", |
| 1138 | uuid: `cancelled-${offer.uuid}`, |
| 1139 | session_id: sessionId, |
| 1140 | }), |
| 1141 | ); |
| 1142 | const offeredText = (offer: SDKUserMessage | undefined) => |
| 1143 | JSON.stringify(offer?.message.content ?? null); |
| 1144 | const queued = Effect.map(orchestrator.getThreadProjection(threadId), (projection) => |
| 1145 | projection.runs |
| 1146 | .filter((run) => run.status === "queued") |
| 1147 | .toSorted( |
| 1148 | (left, right) => |
| 1149 | (left.queuePosition ?? left.ordinal) - (right.queuePosition ?? right.ordinal), |
| 1150 | ), |
| 1151 | ); |
| 1152 | const queuedOrder = Effect.map(queued, (runs) => |
| 1153 | runs.map((run) => [run.userMessageId, run.queueHeld === true]), |
| 1154 | ); |
| 1155 | yield* orchestrator.dispatch({ |
| 1156 | type: "thread.create", |
| 1157 | commandId: CommandId.make("create"), |
| 1158 | threadId, |
| 1159 | projectId: ProjectId.make("project:unread-steer"), |
| 1160 | title: "Unread steer", |
| 1161 | modelSelection, |
| 1162 | runtimeMode: "full-access", |
| 1163 | interactionMode: "default", |
| 1164 | branch: null, |
| 1165 | worktreePath: cwd, |
| 1166 | createdBy: "user", |
| 1167 | creationSource: "web", |
| 1168 | }); |
| 1169 | const running = yield* watch( |
| 1170 | (event) => event.type === "provider-turn.updated" && event.payload.status === "running", |
| 1171 | ); |
| 1172 | const send = ( |
| 1173 | id: string, |
| 1174 | dispatchMode: |
| 1175 | | { readonly type: "start_immediately" | "queue_after_active" } |
| 1176 | | { readonly type: "steer_active"; readonly targetRunId: RunId }, |
| 1177 | model?: string, |
| 1178 | ) => |
| 1179 | orchestrator.dispatch({ |
| 1180 | type: "message.dispatch", |
| 1181 | commandId: CommandId.make(id), |
| 1182 | threadId, |
| 1183 | messageId: MessageId.make(id), |
| 1184 | text: `Message ${id}`, |
| 1185 | attachments: [], |
| 1186 | ...(model === undefined ? {} : { modelSelection: { ...modelSelection, model } }), |
| 1187 | dispatchMode, |
| 1188 | createdBy: "user", |
| 1189 | creationSource: "web", |
| 1190 | }); |
| 1191 | yield* send("first", { type: "start_immediately" }); |
| 1192 | yield* worker.drain(); |
| 1193 | yield* Fiber.join(running); |
| 1194 | const parent = (yield* orchestrator.getThreadProjection(threadId)).runs[0]!; |
| 1195 | yield* send("before", { type: "queue_after_active" }); |
| 1196 | const unread = yield* pending(); |
| 1197 | yield* send("steer", { type: "steer_active", targetRunId: parent.id }); |
| 1198 | yield* worker.drain(); |
| 1199 | yield* Fiber.join(unread); |
| 1200 | yield* send("after", { type: "queue_after_active" }, "claude-opus-4-1"); |
| 1201 | assert.deepEqual( |
| 1202 | offers.map((offer) => offer.priority), |
| 1203 | [undefined, "next"], |
| 1204 | ); |
| 1205 | |
| 1206 | if (outcome === "Claude cancels it twice") { |
| 1207 | const ended = yield* settled(parent.id, "waiting"); |
| 1208 | const nextRunning = yield* watch( |
| 1209 | (event) => |
| 1210 | event.type === "provider-turn.updated" && |
| 1211 | event.payload.status === "running" && |
| 1212 | event.payload.runAttemptId !== parent.activeAttemptId, |
| 1213 | ); |
| 1214 | yield* answer(offers[0]!); |
| 1215 | yield* cancel(offers[1]!); |
| 1216 | yield* Fiber.join(ended); |
| 1217 | yield* worker.drain(); |
| 1218 | yield* Fiber.join(nextRunning); |
| 1219 | // The older message runs first; the steer waits right behind it on its own model. |
| 1220 | const behind = yield* queued; |
| 1221 | assert.deepEqual( |
| 1222 | behind.map((run) => run.userMessageId), |
| 1223 | [steerId, MessageId.make("after")], |
| 1224 | ); |
| 1225 | assert.deepEqual(behind[0]?.modelSelection, modelSelection); |
| 1226 | assert.include(offeredText(offers[2]), "Message before"); |
| 1227 | // Promoted into that run, Claude drops it again; it is queued again, then reaches Claude. |
| 1228 | const before = (yield* orchestrator.getThreadProjection(threadId)).runs.find( |
| 1229 | (run) => run.userMessageId === MessageId.make("before"), |
| 1230 | )!; |
| 1231 | yield* orchestrator.dispatch({ |
| 1232 | type: "queued-message.promote-to-steer", |
| 1233 | commandId: CommandId.make("promote"), |
| 1234 | threadId, |
| 1235 | queuedRunId: behind[0]!.id, |
| 1236 | targetRunId: before.id, |
| 1237 | }); |
| 1238 | yield* worker.drain(); |
| 1239 | assert.equal(offers[3]?.priority, "next"); |
| 1240 | const beforeEnded = yield* settled(before.id, "waiting"); |
| 1241 | yield* answer(offers[2]!); |
| 1242 | yield* cancel(offers[3]!); |
| 1243 | yield* Fiber.join(beforeEnded); |
| 1244 | yield* worker.drain(); |
| 1245 | assert.deepEqual(yield* queuedOrder, [[MessageId.make("after"), false]]); |
| 1246 | assert.equal(offers.length, 5); |
| 1247 | assert.equal(offers[4]?.priority, undefined); |
| 1248 | assert.include(offeredText(offers[4]), "Message steer"); |
| 1249 | return; |
| 1250 | } |
| 1251 | |
| 1252 | if (outcome === "the Claude process exits") { |
| 1253 | const requeued = yield* watch( |
| 1254 | (event) => |
| 1255 | event.type === "run.updated" && |
| 1256 | event.payload.userMessageId === steerId && |
| 1257 | event.payload.status === "queued", |
| 1258 | ); |
| 1259 | yield* Queue.shutdown(sdkMessages); |
| 1260 | yield* Fiber.join(requeued); |
| 1261 | yield* worker.drain(); |
| 1262 | // The provider failure holds the queue, the follow-up included, until someone resumes it. |
| 1263 | assert.deepEqual(yield* queuedOrder, [ |
| 1264 | [MessageId.make("before"), true], |
| 1265 | [steerId, true], |
| 1266 | [MessageId.make("after"), true], |
| 1267 | ]); |
| 1268 | assert.equal(offers.length, 2); |
| 1269 | return; |
| 1270 | } |
| 1271 | |
| 1272 | if (outcome === "Claude cancels it and the user stops") { |
| 1273 | yield* cancel(offers[1]!); |
| 1274 | const dropped = yield* watch( |
| 1275 | (event) => |
| 1276 | event.type === "turn-item.updated" && |
| 1277 | event.payload.type === "user_message" && |
| 1278 | event.payload.messageId === steerId && |
| 1279 | event.payload.status === "cancelled", |
| 1280 | ); |
| 1281 | yield* orchestrator.dispatch({ |
| 1282 | type: "run.interrupt", |
| 1283 | commandId: CommandId.make("stop"), |
| 1284 | threadId, |
| 1285 | runId: parent.id, |
| 1286 | holdQueue: true, |
| 1287 | }); |
| 1288 | yield* worker.drain(); |
| 1289 | yield* Fiber.join(dropped); |
| 1290 | const after = yield* orchestrator.getThreadProjection(threadId); |
| 1291 | assert.equal( |
| 1292 | after.turnItems.find((item) => item.type === "user_message" && item.messageId === steerId) |
| 1293 | ?.status, |
| 1294 | "cancelled", |
| 1295 | ); |
| 1296 | assert.isTrue( |
| 1297 | after.turnItems.some( |
| 1298 | (item) => item.type === "system_notice" && item.message?.includes("Message steer"), |
| 1299 | ), |
| 1300 | ); |
| 1301 | assert.deepEqual(yield* queuedOrder, [ |
| 1302 | [MessageId.make("before"), true], |
| 1303 | [MessageId.make("after"), true], |
| 1304 | ]); |
| 1305 | return; |
| 1306 | } |
| 1307 | |
| 1308 | // Recovery cancels the run, holds the queue and leaves the unread steer pending. |
| 1309 | const projection = yield* orchestrator.getThreadProjection(threadId); |
| 1310 | const now = yield* DateTime.now; |
| 1311 | yield* (yield* EventSink.EventSinkV2).write({ |
| 1312 | commandId: CommandId.make("command:runtime-reconcile:startup:unread-steer"), |
| 1313 | events: projection.runs.map((run, index) => ({ |
| 1314 | id: EventId.make(`recovered-run-${index}`), |
| 1315 | type: "run.updated" as const, |
| 1316 | threadId, |
| 1317 | runId: run.id, |
| 1318 | occurredAt: now, |
| 1319 | payload: |
| 1320 | run.id === parent.id |
| 1321 | ? { ...run, status: "cancelled" as const, completedAt: now } |
| 1322 | : { ...run, queueHeld: true }, |
| 1323 | })), |
| 1324 | }); |
| 1325 | yield* orchestrator.recoverDelegatedTasks; |
| 1326 | yield* worker.drain(); |
| 1327 | assert.deepEqual(yield* queuedOrder, [ |
| 1328 | [MessageId.make("before"), true], |
| 1329 | [steerId, true], |
| 1330 | [MessageId.make("after"), true], |
| 1331 | ]); |
| 1332 | assert.equal(offers.length, 2); |
| 1333 | }).pipe( |
| 1334 | Effect.provide( |
| 1335 | ProviderReplayHarness.layerWithRegistry( |
| 1336 | { name: "claude-unread-steer" }, |
| 1337 | ProviderAdapterRegistry.layerSingle(adapter), |
| 1338 | { runEffectWorker: false }, |
| 1339 | ), |
| 1340 | ), |
| 1341 | ); |
| 1342 | }).pipe( |
| 1343 | Effect.provide( |
| 1344 | Layer.mergeAll( |
| 1345 | IdAllocator.layer, |
| 1346 | McpProviderSessions.layer, |
| 1347 | NodeServices.layer, |
| 1348 | NodeCrypto.layer, |
| 1349 | ), |
| 1350 | ), |
| 1351 | ), |
| 1352 | ); |