The best way to control Claude Code, Codex and more from any computer or phone
| 1 | // @effect-diagnostics nodeBuiltinImport:off -- the fake CLI and its leftover child are real processes. |
| 2 | import * as ClaudeSdk from "@anthropic-ai/claude-agent-sdk"; |
| 3 | import * as NodeChildProcess from "node:child_process"; |
| 4 | import * as NodeEvents from "node:events"; |
| 5 | import * as NodeFS from "node:fs"; |
| 6 | import * as NodeOS from "node:os"; |
| 7 | import * as NodePath from "node:path"; |
| 8 | import * as NodeStream from "node:stream"; |
| 9 | import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; |
| 10 | import * as NodeServices from "@effect/platform-node/NodeServices"; |
| 11 | import { assert, describe, it } from "@effect/vitest"; |
| 12 | import { ProviderSessionId, ThreadId } from "@t3tools/contracts"; |
| 13 | import * as Effect from "effect/Effect"; |
| 14 | import * as Exit from "effect/Exit"; |
| 15 | import * as Deferred from "effect/Deferred"; |
| 16 | import * as Fiber from "effect/Fiber"; |
| 17 | import * as FileSystem from "effect/FileSystem"; |
| 18 | import * as Layer from "effect/Layer"; |
| 19 | import * as Path from "effect/Path"; |
| 20 | import * as Stream from "effect/Stream"; |
| 21 | import * as TestClock from "effect/testing/TestClock"; |
| 22 | import { vi } from "vite-plus/test"; |
| 23 | |
| 24 | import * as HostProcess from "@t3tools/shared/HostProcess"; |
| 25 | import { AgentScope } from "@t3tools/shared/AgentScope"; |
| 26 | import { ProviderEventLoggers } from "@t3tools/provider-core/server/ProviderEventLoggers"; |
| 27 | import { makeProviderFailure } from "@t3tools/provider-core/server/failure"; |
| 28 | import { signalProcessGroup } from "@t3tools/provider-core/server/processGroup"; |
| 29 | import * as PortScanner from "../../preview/PortScanner.ts"; |
| 30 | import { |
| 31 | ClaudeAgentSdkQueryRunner, |
| 32 | type ClaudeAgentSdkQueryOpenInput, |
| 33 | layerQueryRunner, |
| 34 | makeClaudeDescendantTracker, |
| 35 | spawnClaudeProcessGroup, |
| 36 | } from "./ClaudeAdapterV2.ts"; |
| 37 | |
| 38 | vi.mock("@anthropic-ai/claude-agent-sdk", { spy: true }); |
| 39 | |
| 40 | const FORK_SESSION_ID = "11111111-1111-4111-8111-111111111111"; |
| 41 | |
| 42 | const sessionEntry = (uuid: string, parentUuid: string | null, message: unknown) => ({ |
| 43 | type: parentUuid === null ? "user" : "assistant", |
| 44 | uuid, |
| 45 | parentUuid, |
| 46 | sessionId: FORK_SESSION_ID, |
| 47 | cwd: "/repo", |
| 48 | isSidechain: false, |
| 49 | timestamp: "2026-10-01T00:00:00.000Z", |
| 50 | message, |
| 51 | }); |
| 52 | |
| 53 | const writeClaudeSession = Effect.fnUntraced(function* ( |
| 54 | configDir: string, |
| 55 | entries: ReadonlyArray<unknown> = [ |
| 56 | sessionEntry("aaaaaaaa-0000-4000-8000-000000000001", null, { role: "user", content: "hello" }), |
| 57 | sessionEntry("aaaaaaaa-0000-4000-8000-000000000002", "aaaaaaaa-0000-4000-8000-000000000001", { |
| 58 | role: "assistant", |
| 59 | content: [{ type: "text", text: "hi" }], |
| 60 | }), |
| 61 | ], |
| 62 | ) { |
| 63 | const fileSystem = yield* FileSystem.FileSystem; |
| 64 | const path = yield* Path.Path; |
| 65 | const projectDir = path.join(configDir, "projects", "-repo"); |
| 66 | yield* fileSystem.makeDirectory(projectDir, { recursive: true }); |
| 67 | yield* fileSystem.writeFileString( |
| 68 | path.join(projectDir, `${FORK_SESSION_ID}.jsonl`), |
| 69 | entries.map((line) => JSON.stringify(line)).join("\n"), |
| 70 | ); |
| 71 | return projectDir; |
| 72 | }); |
| 73 | |
| 74 | const forkRunnerLayer = layerQueryRunner.pipe( |
| 75 | Layer.provide(PortScanner.layerTest), |
| 76 | Layer.provide(Layer.succeed(ProviderEventLoggers, { native: undefined, canonical: undefined })), |
| 77 | ); |
| 78 | |
| 79 | it.effect("forks a session stored under the instance's own CLAUDE_CONFIG_DIR", () => |
| 80 | Effect.scoped( |
| 81 | Effect.gen(function* () { |
| 82 | const fileSystem = yield* FileSystem.FileSystem; |
| 83 | const path = yield* Path.Path; |
| 84 | const configDir = yield* fileSystem.makeTempDirectoryScoped({ |
| 85 | prefix: "t3-claude-fork-config-", |
| 86 | }); |
| 87 | const projectDir = yield* writeClaudeSession(configDir); |
| 88 | const hostConfigDir = (yield* HostProcess.Environment).CLAUDE_CONFIG_DIR; |
| 89 | const inProcessFork = vi.spyOn(ClaudeSdk, "forkSession"); |
| 90 | yield* Effect.addFinalizer(() => Effect.sync(() => inProcessFork.mockRestore())); |
| 91 | |
| 92 | const runner = yield* ClaudeAgentSdkQueryRunner; |
| 93 | const forked = yield* runner.forkSession({ |
| 94 | sessionId: FORK_SESSION_ID, |
| 95 | options: { dir: "/repo" }, |
| 96 | environment: { ...process.env, CLAUDE_CONFIG_DIR: configDir }, |
| 97 | threadId: ThreadId.make("thread-fork-config-dir"), |
| 98 | providerSessionId: ProviderSessionId.make("session-fork-config-dir"), |
| 99 | }); |
| 100 | |
| 101 | assert.notEqual(forked.sessionId, FORK_SESSION_ID); |
| 102 | const transcript = yield* fileSystem.readFileString( |
| 103 | path.join(projectDir, `${forked.sessionId}.jsonl`), |
| 104 | ); |
| 105 | assert.include(transcript, '"content":"hello"'); |
| 106 | assert.include(transcript, '"text":"hi"'); |
| 107 | const inheritedHead = transcript |
| 108 | .trim() |
| 109 | .split("\n") |
| 110 | .findLast((line) => line.includes('"type":"assistant"')) |
| 111 | ?.match(/"uuid"\s*:\s*"([^"]+)"/)?.[1]; |
| 112 | assert.isString(inheritedHead); |
| 113 | assert.equal(forked.headMessageId, inheritedHead); |
| 114 | assert.equal((yield* HostProcess.Environment).CLAUDE_CONFIG_DIR, hostConfigDir); |
| 115 | assert.equal(inProcessFork.mock.calls.length, 0); |
| 116 | }).pipe(Effect.provide(forkRunnerLayer)), |
| 117 | ).pipe(Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))), |
| 118 | ); |
| 119 | it.effect("forked Claude sessions keep their compaction chain", () => |
| 120 | Effect.scoped( |
| 121 | Effect.gen(function* () { |
| 122 | const fileSystem = yield* FileSystem.FileSystem; |
| 123 | const path = yield* Path.Path; |
| 124 | const configDir = yield* fileSystem.makeTempDirectoryScoped({ |
| 125 | prefix: "t3-claude-fork-compact-", |
| 126 | }); |
| 127 | const uuid = (n: number) => `bbbbbbbb-0000-4000-8000-00000000000${n}`; |
| 128 | const turn = (id: number, parent: string | null, role: "user" | "assistant") => ({ |
| 129 | ...sessionEntry(uuid(id), parent, { |
| 130 | role, |
| 131 | content: role === "user" ? `question ${id}` : [{ type: "text", text: `answer ${id}` }], |
| 132 | }), |
| 133 | type: role, |
| 134 | }); |
| 135 | const projectDir = yield* writeClaudeSession(configDir, [ |
| 136 | turn(1, null, "user"), |
| 137 | turn(2, uuid(1), "assistant"), |
| 138 | turn(3, uuid(2), "user"), |
| 139 | turn(4, uuid(3), "assistant"), |
| 140 | { |
| 141 | ...sessionEntry(uuid(5), null, undefined), |
| 142 | type: "system", |
| 143 | subtype: "compact_boundary", |
| 144 | content: "Conversation compacted", |
| 145 | logicalParentUuid: uuid(4), |
| 146 | compactMetadata: { |
| 147 | trigger: "manual", |
| 148 | preTokens: 19979, |
| 149 | preservedSegment: { headUuid: uuid(3), anchorUuid: uuid(6), tailUuid: uuid(4) }, |
| 150 | preservedMessages: { |
| 151 | anchorUuid: uuid(6), |
| 152 | uuids: [uuid(3), uuid(4)], |
| 153 | allUuids: [uuid(3), uuid(4)], |
| 154 | }, |
| 155 | postTokens: 3589, |
| 156 | }, |
| 157 | }, |
| 158 | { |
| 159 | ...turn(6, uuid(5), "user"), |
| 160 | isCompactSummary: true, |
| 161 | isVisibleInTranscriptOnly: true, |
| 162 | }, |
| 163 | turn(7, uuid(4), "user"), |
| 164 | turn(8, uuid(7), "assistant"), |
| 165 | ]); |
| 166 | |
| 167 | const runner = yield* ClaudeAgentSdkQueryRunner; |
| 168 | const forked = yield* runner.forkSession({ |
| 169 | sessionId: FORK_SESSION_ID, |
| 170 | options: { dir: "/repo" }, |
| 171 | environment: { ...process.env, CLAUDE_CONFIG_DIR: configDir }, |
| 172 | threadId: ThreadId.make("thread-fork-compaction"), |
| 173 | providerSessionId: ProviderSessionId.make("session-fork-compaction"), |
| 174 | }); |
| 175 | |
| 176 | const entries: ReadonlyArray<{ |
| 177 | readonly uuid?: string; |
| 178 | readonly subtype?: string; |
| 179 | readonly compactMetadata?: { |
| 180 | readonly preservedSegment: Record<"headUuid" | "anchorUuid" | "tailUuid", string>; |
| 181 | readonly preservedMessages: { |
| 182 | readonly anchorUuid: string; |
| 183 | readonly uuids: string[]; |
| 184 | readonly allUuids: string[]; |
| 185 | }; |
| 186 | }; |
| 187 | }> = (yield* fileSystem.readFileString(path.join(projectDir, `${forked.sessionId}.jsonl`))) |
| 188 | .trim() |
| 189 | .split("\n") |
| 190 | .map((line) => JSON.parse(line)); |
| 191 | const forkedUuids = new Set(entries.map((entry) => entry.uuid)); |
| 192 | const boundary = entries.find((entry) => entry.subtype === "compact_boundary"); |
| 193 | assert.isDefined(boundary?.compactMetadata); |
| 194 | const { preservedSegment, preservedMessages } = boundary!.compactMetadata!; |
| 195 | const danglingRefs = [ |
| 196 | ...Object.values(preservedSegment), |
| 197 | preservedMessages.anchorUuid, |
| 198 | ...preservedMessages.uuids, |
| 199 | ...preservedMessages.allUuids, |
| 200 | ].filter((ref) => !forkedUuids.has(ref)); |
| 201 | assert.deepEqual(danglingRefs, [], "compaction refs missing from the forked transcript"); |
| 202 | }).pipe(Effect.provide(forkRunnerLayer)), |
| 203 | ).pipe(Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))), |
| 204 | ); |
| 205 | |
| 206 | const realQueryRunner = layerQueryRunner.pipe( |
| 207 | Layer.provide(PortScanner.layerTest), |
| 208 | Layer.provide( |
| 209 | Layer.succeed(ProviderEventLoggers, { |
| 210 | native: undefined, |
| 211 | canonical: undefined, |
| 212 | }), |
| 213 | ), |
| 214 | Layer.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)), |
| 215 | ); |
| 216 | |
| 217 | const resumedMcpQueryInput = { |
| 218 | threadId: ThreadId.make("thread-restart-registration"), |
| 219 | providerSessionId: ProviderSessionId.make("session-restart-registration"), |
| 220 | options: { |
| 221 | resume: FORK_SESSION_ID, |
| 222 | model: "claude-sonnet-4-6", |
| 223 | tools: [], |
| 224 | permissionMode: "default", |
| 225 | mcpServers: { |
| 226 | "t3-code": { |
| 227 | type: "http", |
| 228 | url: "http://localhost:3773/mcp", |
| 229 | headers: { Authorization: "Bearer test-mcp-credential" }, |
| 230 | }, |
| 231 | }, |
| 232 | }, |
| 233 | } satisfies ClaudeAgentSdkQueryOpenInput; |
| 234 | |
| 235 | it.effect("resumes a session whose history exceeds the status-probe output limit", () => |
| 236 | Effect.gen(function* () { |
| 237 | const fileSystem = yield* FileSystem.FileSystem; |
| 238 | const configDir = yield* fileSystem.makeTempDirectoryScoped({ |
| 239 | prefix: "t3-claude-large-history-", |
| 240 | }); |
| 241 | yield* writeClaudeSession(configDir, [ |
| 242 | sessionEntry("aaaaaaaa-0000-4000-8000-000000000001", null, { |
| 243 | role: "user", |
| 244 | content: "x".repeat(9 * 1024 * 1024), |
| 245 | }), |
| 246 | ]); |
| 247 | const querySpy = vi |
| 248 | .spyOn(ClaudeSdk, "query") |
| 249 | .mockImplementation(() => ({ close: vi.fn() }) as unknown as ClaudeSdk.Query); |
| 250 | yield* Effect.addFinalizer(() => Effect.sync(() => querySpy.mockRestore())); |
| 251 | const runner = yield* ClaudeAgentSdkQueryRunner; |
| 252 | const { mcpServers: _mcpServers, ...options } = resumedMcpQueryInput.options; |
| 253 | const session = yield* runner.open({ |
| 254 | ...resumedMcpQueryInput, |
| 255 | resume: true, |
| 256 | options: { ...options, cwd: "/repo", env: { ...process.env, CLAUDE_CONFIG_DIR: configDir } }, |
| 257 | }); |
| 258 | yield* Effect.addFinalizer(() => session.close.pipe(Effect.orDie)); |
| 259 | assert.equal(querySpy.mock.calls.length, 1); |
| 260 | assert.equal(querySpy.mock.calls[0]?.[0].options?.resume, FORK_SESSION_ID); |
| 261 | }).pipe(Effect.provide(Layer.merge(realQueryRunner, NodeServices.layer))), |
| 262 | ); |
| 263 | |
| 264 | it.effect("reopens a stalled MCP registration before delivering the resumed prompt", () => |
| 265 | Effect.gen(function* () { |
| 266 | const registrationStarted = Promise.withResolvers<void>(); |
| 267 | const disposalStarted = Promise.withResolvers<void>(); |
| 268 | const finishDisposal = Promise.withResolvers<void>(); |
| 269 | const prompts: AsyncIterable<ClaudeSdk.SDKUserMessage>[] = []; |
| 270 | const firstClose = vi.fn(); |
| 271 | const secondClose = vi.fn(); |
| 272 | const firstRegistration = vi.fn(() => { |
| 273 | registrationStarted.resolve(); |
| 274 | return new Promise<ClaudeSdk.McpSetServersResult>(() => {}); |
| 275 | }); |
| 276 | const secondRegistration = vi.fn(async () => ({ |
| 277 | added: ["t3-code"], |
| 278 | removed: [], |
| 279 | errors: {}, |
| 280 | })); |
| 281 | const querySpy = vi.spyOn(ClaudeSdk, "query").mockImplementation(({ prompt }) => { |
| 282 | assert.notTypeOf(prompt, "string"); |
| 283 | if (typeof prompt === "string") throw new Error("Expected streaming input"); |
| 284 | prompts.push(prompt); |
| 285 | return { |
| 286 | initializationResult: async () => ({}), |
| 287 | setMcpServers: prompts.length === 1 ? firstRegistration : secondRegistration, |
| 288 | close: prompts.length === 1 ? firstClose : secondClose, |
| 289 | [Symbol.asyncDispose]: async () => { |
| 290 | firstClose(); |
| 291 | disposalStarted.resolve(); |
| 292 | await finishDisposal.promise; |
| 293 | }, |
| 294 | } as unknown as ClaudeSdk.Query; |
| 295 | }); |
| 296 | yield* Effect.addFinalizer(() => Effect.sync(() => querySpy.mockRestore())); |
| 297 | const runner = yield* ClaudeAgentSdkQueryRunner; |
| 298 | const opening = yield* runner.open(resumedMcpQueryInput).pipe(Effect.forkChild); |
| 299 | yield* Effect.promise(() => registrationStarted.promise); |
| 300 | yield* TestClock.adjust("90 seconds"); |
| 301 | yield* Effect.promise(() => disposalStarted.promise); |
| 302 | assert.equal(querySpy.mock.calls.length, 1); |
| 303 | finishDisposal.resolve(); |
| 304 | const session = yield* Fiber.join(opening); |
| 305 | yield* Effect.addFinalizer(() => session.close.pipe(Effect.orDie)); |
| 306 | |
| 307 | assert.equal(firstClose.mock.calls.length, 1); |
| 308 | assert.equal(secondClose.mock.calls.length, 0); |
| 309 | assert.equal(querySpy.mock.calls.length, 2); |
| 310 | for (const [call] of querySpy.mock.calls) { |
| 311 | assert.equal(call.options?.resume, FORK_SESSION_ID); |
| 312 | assert.isUndefined(call.options?.mcpServers); |
| 313 | } |
| 314 | assert.deepEqual(secondRegistration.mock.calls, [[resumedMcpQueryInput.options.mcpServers]]); |
| 315 | const message = { |
| 316 | type: "user", |
| 317 | message: { role: "user", content: "Continue where you left off." }, |
| 318 | parent_tool_use_id: null, |
| 319 | session_id: FORK_SESSION_ID, |
| 320 | } satisfies ClaudeSdk.SDKUserMessage; |
| 321 | yield* session.offer(message); |
| 322 | assert.isTrue((yield* Effect.promise(() => prompts[0]![Symbol.asyncIterator]().next())).done); |
| 323 | const delivered = yield* Effect.promise(() => prompts[1]![Symbol.asyncIterator]().next()); |
| 324 | assert.deepEqual(delivered.value, message); |
| 325 | assert.isFalse(delivered.done); |
| 326 | }).pipe(Effect.provide(realQueryRunner)), |
| 327 | ); |
| 328 | |
| 329 | it.effect.each([ |
| 330 | { case: "a readable rule list", errors: undefined, readable: true }, |
| 331 | { case: "a settings file Claude skipped", errors: [{ file: "settings.json" }], readable: false }, |
| 332 | { case: "a reply without a rule list", response: {}, readable: false }, |
| 333 | ])("reads Claude's permission rules only when no settings file was skipped: $case", (testCase) => |
| 334 | Effect.gen(function* () { |
| 335 | const rules = [{ behavior: "deny" as const, rule: "mcp__probe__redeploy" }]; |
| 336 | const querySpy = vi.spyOn(ClaudeSdk, "query").mockImplementation( |
| 337 | () => |
| 338 | ({ |
| 339 | close: vi.fn(), |
| 340 | request: async () => ({ |
| 341 | response: |
| 342 | "response" in testCase |
| 343 | ? testCase.response |
| 344 | : { state: { rules, errors: testCase.errors } }, |
| 345 | }), |
| 346 | }) as unknown as ClaudeSdk.Query, |
| 347 | ); |
| 348 | yield* Effect.addFinalizer(() => Effect.sync(() => querySpy.mockRestore())); |
| 349 | const runner = yield* ClaudeAgentSdkQueryRunner; |
| 350 | const { mcpServers: _mcpServers, ...options } = resumedMcpQueryInput.options; |
| 351 | const session = yield* runner.open({ ...resumedMcpQueryInput, options }); |
| 352 | yield* Effect.addFinalizer(() => session.close.pipe(Effect.orDie)); |
| 353 | const exit = yield* Effect.exit(session.listPermissionRules); |
| 354 | if (testCase.readable) assert.deepEqual(exit, Exit.succeed(rules)); |
| 355 | else assert.isTrue(Exit.isFailure(exit)); |
| 356 | }).pipe(Effect.provide(realQueryRunner)), |
| 357 | ); |
| 358 | |
| 359 | it.effect.each([true, false])("only retries after confirmed process exit: %s", (exits) => |
| 360 | Effect.gen(function* () { |
| 361 | const registrationStarted = Promise.withResolvers<void>(); |
| 362 | const cleanupProgress = Promise.withResolvers<"kill" | "retry">(); |
| 363 | const events = new NodeEvents.EventEmitter(); |
| 364 | const stdin = new NodeStream.PassThrough(); |
| 365 | const stdout = new NodeStream.PassThrough(); |
| 366 | const child = { |
| 367 | stdin, |
| 368 | stdout, |
| 369 | killed: false, |
| 370 | exitCode: null, |
| 371 | kill: vi.fn(() => { |
| 372 | cleanupProgress.resolve("kill"); |
| 373 | return true; |
| 374 | }), |
| 375 | on: events.on.bind(events), |
| 376 | once: events.once.bind(events), |
| 377 | off: events.off.bind(events), |
| 378 | } satisfies ClaudeSdk.SpawnedProcess; |
| 379 | const signal = yield* Effect.abortSignal; |
| 380 | const disposed = vi.fn(async () => {}); |
| 381 | const querySpy = vi.spyOn(ClaudeSdk, "query").mockImplementation(({ options }) => { |
| 382 | const first = querySpy.mock.calls.length === 1; |
| 383 | if (first) { |
| 384 | options?.spawnClaudeCodeProcess?.({ command: "claude", args: [], env: {}, signal }); |
| 385 | } else { |
| 386 | cleanupProgress.resolve("retry"); |
| 387 | } |
| 388 | return { |
| 389 | initializationResult: async () => ({}), |
| 390 | setMcpServers: () => { |
| 391 | registrationStarted.resolve(); |
| 392 | return first |
| 393 | ? new Promise<ClaudeSdk.McpSetServersResult>(() => {}) |
| 394 | : Promise.resolve({ added: ["t3-code"], removed: [], errors: {} }); |
| 395 | }, |
| 396 | close: vi.fn(), |
| 397 | [Symbol.asyncDispose]: disposed, |
| 398 | } as unknown as ClaudeSdk.Query; |
| 399 | }); |
| 400 | yield* Effect.addFinalizer(() => |
| 401 | Effect.sync(() => { |
| 402 | querySpy.mockRestore(); |
| 403 | stdin.destroy(); |
| 404 | stdout.destroy(); |
| 405 | }), |
| 406 | ); |
| 407 | const runner = yield* ClaudeAgentSdkQueryRunner; |
| 408 | const opening = yield* runner |
| 409 | .open({ |
| 410 | ...resumedMcpQueryInput, |
| 411 | options: { ...resumedMcpQueryInput.options, spawnClaudeCodeProcess: () => child }, |
| 412 | }) |
| 413 | .pipe(Effect.exit, Effect.forkChild); |
| 414 | yield* Effect.promise(() => registrationStarted.promise); |
| 415 | yield* TestClock.adjust("90 seconds"); |
| 416 | |
| 417 | assert.equal(yield* Effect.promise(() => cleanupProgress.promise), "kill"); |
| 418 | assert.equal(querySpy.mock.calls.length, 1); |
| 419 | assert.deepEqual(child.kill.mock.calls, [["SIGKILL"]]); |
| 420 | if (exits) events.emit("exit", null, "SIGKILL"); |
| 421 | else yield* TestClock.adjust("10 seconds"); |
| 422 | const result = yield* Fiber.join(opening); |
| 423 | assert.equal(Exit.isSuccess(result), exits); |
| 424 | if (Exit.isSuccess(result)) yield* result.value.close; |
| 425 | assert.equal(querySpy.mock.calls.length, exits ? 2 : 1); |
| 426 | assert.equal(disposed.mock.calls.length, 1); |
| 427 | }).pipe(Effect.provide(realQueryRunner)), |
| 428 | ); |
| 429 | |
| 430 | it.effect("stops retrying MCP registration after two timeouts and reports the cause", () => |
| 431 | Effect.gen(function* () { |
| 432 | const firstRegistration = Promise.withResolvers<void>(); |
| 433 | const secondRegistration = Promise.withResolvers<void>(); |
| 434 | const disposed = vi.fn(async () => {}); |
| 435 | const querySpy = vi.spyOn(ClaudeSdk, "query").mockImplementation(() => { |
| 436 | const started = querySpy.mock.calls.length === 1 ? firstRegistration : secondRegistration; |
| 437 | return { |
| 438 | initializationResult: async () => ({}), |
| 439 | setMcpServers: () => { |
| 440 | started.resolve(); |
| 441 | return new Promise<ClaudeSdk.McpSetServersResult>(() => {}); |
| 442 | }, |
| 443 | [Symbol.asyncDispose]: disposed, |
| 444 | } as unknown as ClaudeSdk.Query; |
| 445 | }); |
| 446 | yield* Effect.addFinalizer(() => Effect.sync(() => querySpy.mockRestore())); |
| 447 | const runner = yield* ClaudeAgentSdkQueryRunner; |
| 448 | const opening = yield* runner.open(resumedMcpQueryInput).pipe(Effect.result, Effect.forkChild); |
| 449 | yield* Effect.promise(() => firstRegistration.promise); |
| 450 | yield* TestClock.adjust("90 seconds"); |
| 451 | yield* Effect.promise(() => secondRegistration.promise); |
| 452 | yield* TestClock.adjust("90 seconds"); |
| 453 | const result = yield* Fiber.join(opening); |
| 454 | |
| 455 | assert.equal(result._tag, "Failure"); |
| 456 | if (result._tag !== "Failure") return; |
| 457 | assert.equal(querySpy.mock.calls.length, 2); |
| 458 | assert.equal(disposed.mock.calls.length, 2); |
| 459 | assert.equal( |
| 460 | makeProviderFailure({ |
| 461 | cause: { _tag: "ProviderAdapterTurnStartError", cause: result.failure }, |
| 462 | }).message, |
| 463 | "Claude timed out while registering its MCP tools. Retry the turn; if it keeps failing, check Claude and the server logs.", |
| 464 | ); |
| 465 | }).pipe(Effect.provide(realQueryRunner)), |
| 466 | ); |
| 467 | |
| 468 | it.effect("cancels a stalled registration without retrying or retaining its prompt queue", () => |
| 469 | Effect.gen(function* () { |
| 470 | const registrationStarted = Promise.withResolvers<void>(); |
| 471 | const disposed = vi.fn(async () => {}); |
| 472 | const querySpy = vi.spyOn(ClaudeSdk, "query").mockImplementation( |
| 473 | () => |
| 474 | ({ |
| 475 | initializationResult: async () => ({}), |
| 476 | setMcpServers: () => { |
| 477 | registrationStarted.resolve(); |
| 478 | return new Promise<ClaudeSdk.McpSetServersResult>(() => {}); |
| 479 | }, |
| 480 | [Symbol.asyncDispose]: disposed, |
| 481 | }) as unknown as ClaudeSdk.Query, |
| 482 | ); |
| 483 | yield* Effect.addFinalizer(() => Effect.sync(() => querySpy.mockRestore())); |
| 484 | const runner = yield* ClaudeAgentSdkQueryRunner; |
| 485 | const opening = yield* runner.open(resumedMcpQueryInput).pipe(Effect.forkChild); |
| 486 | yield* Effect.promise(() => registrationStarted.promise); |
| 487 | yield* Fiber.interrupt(opening); |
| 488 | |
| 489 | assert.equal(querySpy.mock.calls.length, 1); |
| 490 | assert.equal(disposed.mock.calls.length, 1); |
| 491 | const prompt = querySpy.mock.calls[0]![0].prompt; |
| 492 | if (typeof prompt === "string") throw new Error("Expected streaming input"); |
| 493 | assert.isTrue((yield* Effect.promise(() => prompt[Symbol.asyncIterator]().next())).done); |
| 494 | }).pipe(Effect.provide(realQueryRunner)), |
| 495 | ); |
| 496 | |
| 497 | it.effect("retries a fresh session once after MCP registration times out", () => |
| 498 | Effect.gen(function* () { |
| 499 | const registrationStarted = Promise.withResolvers<void>(); |
| 500 | const disposed = vi.fn(async () => {}); |
| 501 | const querySpy = vi.spyOn(ClaudeSdk, "query").mockImplementation(() => { |
| 502 | const first = querySpy.mock.calls.length === 1; |
| 503 | return { |
| 504 | initializationResult: async () => ({}), |
| 505 | setMcpServers: () => { |
| 506 | registrationStarted.resolve(); |
| 507 | return first |
| 508 | ? new Promise<ClaudeSdk.McpSetServersResult>(() => {}) |
| 509 | : Promise.resolve({ added: ["t3-code"], removed: [], errors: {} }); |
| 510 | }, |
| 511 | close: vi.fn(), |
| 512 | [Symbol.asyncDispose]: disposed, |
| 513 | } as unknown as ClaudeSdk.Query; |
| 514 | }); |
| 515 | yield* Effect.addFinalizer(() => Effect.sync(() => querySpy.mockRestore())); |
| 516 | const runner = yield* ClaudeAgentSdkQueryRunner; |
| 517 | const { resume, ...options } = resumedMcpQueryInput.options; |
| 518 | const opening = yield* runner |
| 519 | .open({ |
| 520 | ...resumedMcpQueryInput, |
| 521 | options: { ...options, sessionId: resume }, |
| 522 | }) |
| 523 | .pipe(Effect.result, Effect.forkChild); |
| 524 | yield* Effect.promise(() => registrationStarted.promise); |
| 525 | yield* TestClock.adjust("90 seconds"); |
| 526 | const result = yield* Fiber.join(opening); |
| 527 | |
| 528 | assert.equal(result._tag, "Success"); |
| 529 | if (result._tag === "Success") yield* result.success.close; |
| 530 | assert.equal(querySpy.mock.calls.length, 2); |
| 531 | assert.equal(disposed.mock.calls.length, 1); |
| 532 | // A fresh ID may already have a transcript, so the retry must not open it as fresh again. |
| 533 | const retry = querySpy.mock.calls[1]![0].options; |
| 534 | assert.isFalse(retry?.sessionId === resume && retry?.resume === undefined); |
| 535 | }).pipe(Effect.provide(realQueryRunner)), |
| 536 | ); |
| 537 | |
| 538 | it.effect.each([ |
| 539 | ["opens after a slow CLI boot", "120 seconds", true], |
| 540 | ["times out a CLI that never boots", "5 minutes", false], |
| 541 | ] as const)("%s", ([, bootWait, boots]) => |
| 542 | Effect.gen(function* () { |
| 543 | const attempts = [Promise.withResolvers<void>(), Promise.withResolvers<void>()]; |
| 544 | const booted = Promise.withResolvers<void>(); |
| 545 | const querySpy = vi.spyOn(ClaudeSdk, "query").mockImplementation(() => { |
| 546 | const waiting = attempts[querySpy.mock.calls.length - 1]!; |
| 547 | return { |
| 548 | initializationResult: () => { |
| 549 | waiting.resolve(); |
| 550 | return booted.promise; |
| 551 | }, |
| 552 | // The CLI answers control requests only after it has booted. |
| 553 | setMcpServers: async () => { |
| 554 | waiting.resolve(); |
| 555 | await booted.promise; |
| 556 | return { added: ["t3-code"], removed: [], errors: {} }; |
| 557 | }, |
| 558 | close: vi.fn(), |
| 559 | [Symbol.asyncDispose]: async () => {}, |
| 560 | } as unknown as ClaudeSdk.Query; |
| 561 | }); |
| 562 | yield* Effect.addFinalizer(() => Effect.sync(() => querySpy.mockRestore())); |
| 563 | const runner = yield* ClaudeAgentSdkQueryRunner; |
| 564 | const { resume, ...options } = resumedMcpQueryInput.options; |
| 565 | const opening = yield* runner |
| 566 | .open({ ...resumedMcpQueryInput, options: { ...options, sessionId: resume } }) |
| 567 | .pipe(Effect.result, Effect.forkChild); |
| 568 | yield* Effect.promise(() => attempts[0]!.promise); |
| 569 | yield* TestClock.adjust(bootWait); |
| 570 | if (boots) booted.resolve(); |
| 571 | else { |
| 572 | yield* Effect.promise(() => attempts[1]!.promise); |
| 573 | yield* TestClock.adjust(bootWait); |
| 574 | } |
| 575 | const result = yield* Fiber.join(opening); |
| 576 | |
| 577 | assert.equal(result._tag, boots ? "Success" : "Failure"); |
| 578 | assert.equal(querySpy.mock.calls.length, boots ? 1 : 2); |
| 579 | if (result._tag === "Success") yield* result.success.close; |
| 580 | else |
| 581 | assert.equal( |
| 582 | makeProviderFailure({ |
| 583 | cause: { _tag: "ProviderAdapterTurnStartError", cause: result.failure }, |
| 584 | }).message, |
| 585 | "Claude timed out while starting up. Retry the turn; if it keeps failing, check Claude and the server logs.", |
| 586 | ); |
| 587 | }).pipe(Effect.provide(realQueryRunner)), |
| 588 | ); |
| 589 | |
| 590 | function fakeClaudeCli(script: string): string { |
| 591 | const dir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-claude-cli-")); |
| 592 | const cli = NodePath.join(dir, "claude"); |
| 593 | NodeFS.writeFileSync(cli, `#!/bin/sh\n${script}\n`, { mode: 0o755 }); |
| 594 | return cli; |
| 595 | } |
| 596 | |
| 597 | const openFakeCli = (cli: string) => |
| 598 | Effect.gen(function* () { |
| 599 | const runner = yield* ClaudeAgentSdkQueryRunner; |
| 600 | return yield* runner.open({ |
| 601 | threadId: ThreadId.make("thread-fake-cli"), |
| 602 | providerSessionId: ProviderSessionId.make("session-fake-cli"), |
| 603 | options: { |
| 604 | sessionId: "native-session-fake-cli", |
| 605 | model: "claude-sonnet-4-6", |
| 606 | tools: [], |
| 607 | permissionMode: "default", |
| 608 | pathToClaudeCodeExecutable: cli, |
| 609 | }, |
| 610 | }); |
| 611 | }); |
| 612 | |
| 613 | describe.skipIf(HostProcess.Platform.defaultValue() === "win32")("Claude CLI process", () => { |
| 614 | // The leftover child holds a FIFO open; its death produces EOF without polling. |
| 615 | it.effect("stops what the CLI left running when the session closes", () => |
| 616 | Effect.gen(function* () { |
| 617 | const cli = fakeClaudeCli( |
| 618 | [ |
| 619 | 'dir=$(dirname "$0")', |
| 620 | 'sleep 600 > "$dir/alive" &', |
| 621 | 'echo $! > "$dir/leftover.pid"', |
| 622 | "cat > /dev/null", |
| 623 | ].join("\n"), |
| 624 | ); |
| 625 | const dir = NodePath.dirname(cli); |
| 626 | NodeChildProcess.execFileSync("mkfifo", [NodePath.join(dir, "alive")]); |
| 627 | yield* Effect.addFinalizer(() => |
| 628 | Effect.sync(() => { |
| 629 | try { |
| 630 | process.kill(Number(NodeFS.readFileSync(NodePath.join(dir, "leftover.pid"), "utf8"))); |
| 631 | } catch {} |
| 632 | NodeFS.rmSync(dir, { recursive: true, force: true }); |
| 633 | }), |
| 634 | ); |
| 635 | const alive = NodeFS.createReadStream(NodePath.join(dir, "alive")); |
| 636 | const leftoverStarted = new Promise<void>((resolve) => alive.once("open", () => resolve())); |
| 637 | const leftoverStopped = new Promise<void>((resolve) => alive.once("close", () => resolve())); |
| 638 | alive.resume(); |
| 639 | |
| 640 | const stopped = yield* Deferred.make<string>(); |
| 641 | const session = yield* openFakeCli(cli).pipe( |
| 642 | Effect.provide( |
| 643 | realQueryRunner.pipe( |
| 644 | Layer.provide( |
| 645 | Layer.succeed(AgentScope, { |
| 646 | ...AgentScope.defaultValue(), |
| 647 | wrap: ({ command, args }) => |
| 648 | Effect.succeed({ command, args, unit: "t3code-claude-test.scope" }), |
| 649 | stop: (unit) => Deferred.succeed(stopped, unit).pipe(Effect.asVoid), |
| 650 | }), |
| 651 | ), |
| 652 | ), |
| 653 | ), |
| 654 | ); |
| 655 | yield* Effect.promise(() => leftoverStarted); |
| 656 | yield* session.close; |
| 657 | yield* Effect.promise(() => leftoverStopped); |
| 658 | assert.strictEqual(yield* Deferred.await(stopped), "t3code-claude-test.scope"); |
| 659 | }), |
| 660 | ); |
| 661 | |
| 662 | // The default AgentScope is what macOS gets: no systemd scope to catch a job outside the CLI's group. |
| 663 | it.effect("stops a job the CLI started in its own process group when the session closes", () => |
| 664 | Effect.gen(function* () { |
| 665 | const cli = fakeClaudeCli( |
| 666 | [ |
| 667 | 'dir=$(dirname "$0")', |
| 668 | `perl -e 'setpgrp(0, 0); exec @ARGV' sleep 600 > "$dir/alive" &`, |
| 669 | 'echo $! > "$dir/leftover.pid"', |
| 670 | "cat > /dev/null", |
| 671 | ].join("\n"), |
| 672 | ); |
| 673 | const dir = NodePath.dirname(cli); |
| 674 | NodeChildProcess.execFileSync("mkfifo", [NodePath.join(dir, "alive")]); |
| 675 | yield* Effect.addFinalizer(() => |
| 676 | Effect.sync(() => { |
| 677 | try { |
| 678 | process.kill(Number(NodeFS.readFileSync(NodePath.join(dir, "leftover.pid"), "utf8"))); |
| 679 | } catch {} |
| 680 | NodeFS.rmSync(dir, { recursive: true, force: true }); |
| 681 | }), |
| 682 | ); |
| 683 | const alive = NodeFS.createReadStream(NodePath.join(dir, "alive")); |
| 684 | const leftoverStarted = new Promise<void>((resolve) => alive.once("open", () => resolve())); |
| 685 | const leftoverStopped = new Promise<void>((resolve) => alive.once("close", () => resolve())); |
| 686 | alive.resume(); |
| 687 | |
| 688 | const session = yield* openFakeCli(cli).pipe(Effect.provide(realQueryRunner)); |
| 689 | yield* Effect.promise(() => leftoverStarted); |
| 690 | yield* session.close; |
| 691 | yield* Effect.promise(() => leftoverStopped); |
| 692 | }), |
| 693 | ); |
| 694 | |
| 695 | // Live clock: the job is found by polling while the CLI runs, and the CLI exits on its own. |
| 696 | it.live("stops a job the CLI started in its own process group when the CLI exits", () => |
| 697 | Effect.gen(function* () { |
| 698 | const cli = fakeClaudeCli( |
| 699 | [ |
| 700 | 'dir=$(dirname "$0")', |
| 701 | `perl -e 'setpgrp(0, 0); exec @ARGV' sleep 600 > "$dir/alive" &`, |
| 702 | 'echo $! > "$dir/leftover.pid"', |
| 703 | "sleep 3", |
| 704 | ].join("\n"), |
| 705 | ); |
| 706 | const dir = NodePath.dirname(cli); |
| 707 | NodeChildProcess.execFileSync("mkfifo", [NodePath.join(dir, "alive")]); |
| 708 | yield* Effect.addFinalizer(() => |
| 709 | Effect.sync(() => { |
| 710 | try { |
| 711 | process.kill(Number(NodeFS.readFileSync(NodePath.join(dir, "leftover.pid"), "utf8"))); |
| 712 | } catch {} |
| 713 | NodeFS.rmSync(dir, { recursive: true, force: true }); |
| 714 | }), |
| 715 | ); |
| 716 | const alive = NodeFS.createReadStream(NodePath.join(dir, "alive")); |
| 717 | const leftoverStopped = new Promise<void>((resolve) => alive.once("close", () => resolve())); |
| 718 | alive.resume(); |
| 719 | |
| 720 | yield* openFakeCli(cli).pipe(Effect.provide(realQueryRunner)); |
| 721 | yield* Effect.promise(() => leftoverStopped); |
| 722 | }), |
| 723 | ); |
| 724 | |
| 725 | const processRow = (pid: number, ppid: number, startedSecond: number) => ({ |
| 726 | pid, |
| 727 | ppid, |
| 728 | pgid: pid, |
| 729 | started: `Sun Nov 15 10:00:0${startedSecond} 2026`, |
| 730 | }); |
| 731 | const byNumber = (left: number, right: number) => left - right; |
| 732 | |
| 733 | it.effect( |
| 734 | "keeps only the descendants the CLI still has running, however many jobs it ran", |
| 735 | () => { |
| 736 | let table: ReadonlyArray<ReturnType<typeof processRow>> = []; |
| 737 | const tracker = makeClaudeDescendantTracker( |
| 738 | 1000, |
| 739 | Effect.sync(() => table), |
| 740 | ); |
| 741 | const jobs = (poll: number) => [0, 1, 2, 3].map((job) => 1100 + poll * 4 + job); |
| 742 | return Effect.gen(function* () { |
| 743 | for (let poll = 0; poll < 50; poll++) { |
| 744 | table = [ |
| 745 | processRow(1000, 10, 0), |
| 746 | processRow(1001, 1000, 0), |
| 747 | // A job that outlives the shell that started it is re-parented. |
| 748 | ...(poll === 0 ? [processRow(1003, 1000, 0)] : []), |
| 749 | processRow(1002, poll === 0 ? 1003 : 1, 0), |
| 750 | ...jobs(poll).map((pid) => processRow(pid, 1001, 1)), |
| 751 | ]; |
| 752 | yield* tracker.refresh; |
| 753 | // A failed `ps` reads as no rows. |
| 754 | table = []; |
| 755 | yield* tracker.refresh; |
| 756 | } |
| 757 | assert.strictEqual(tracker.tracked.size, 6); |
| 758 | assert.deepStrictEqual( |
| 759 | [...tracker.tracked.values()].map((row) => row.pid).toSorted(byNumber), |
| 760 | [1001, 1002, ...jobs(49)], |
| 761 | ); |
| 762 | }); |
| 763 | }, |
| 764 | ); |
| 765 | |
| 766 | it.effect( |
| 767 | "stops at exit only what the CLI left running, never a process that took a job's pid", |
| 768 | () => { |
| 769 | const orphan = processRow(1300, 1, 1); |
| 770 | // Unrelated processes take both finished jobs' pids, one in the second its job started. |
| 771 | const unrelated = [processRow(1100, 1, 2), processRow(1200, 1, 1)]; |
| 772 | const tables = [ |
| 773 | [ |
| 774 | processRow(1000, 10, 0), |
| 775 | processRow(1001, 1000, 0), |
| 776 | processRow(1100, 1001, 1), |
| 777 | processRow(1200, 1001, 1), |
| 778 | processRow(1300, 1001, 1), |
| 779 | ], |
| 780 | [processRow(1000, 10, 0), orphan], |
| 781 | [processRow(1000, 10, 0), ...unrelated, orphan], |
| 782 | [...unrelated, orphan], |
| 783 | ]; |
| 784 | const tracker = makeClaudeDescendantTracker( |
| 785 | 1000, |
| 786 | Effect.sync(() => tables.shift() ?? []), |
| 787 | ); |
| 788 | return Effect.gen(function* () { |
| 789 | yield* tracker.refresh; |
| 790 | yield* tracker.refresh; |
| 791 | yield* tracker.refresh; |
| 792 | assert.deepStrictEqual( |
| 793 | (yield* tracker.leftovers).map((row) => row.pid), |
| 794 | [1300], |
| 795 | ); |
| 796 | }); |
| 797 | }, |
| 798 | ); |
| 799 | |
| 800 | // The poll and a session close read the table independently. The older table still lists a |
| 801 | // re-parented job and the child it just started; the newer one lists a job started since. |
| 802 | it.effect( |
| 803 | "stops at exit what the poll and a session close found, reading at the same time", |
| 804 | () => { |
| 805 | type Table = ReadonlyArray<ReturnType<typeof processRow>>; |
| 806 | const cli = processRow(1000, 10, 0); |
| 807 | const olderReadStarted = Deferred.makeUnsafe<void>(); |
| 808 | const olderRead = Deferred.makeUnsafe<Table>(); |
| 809 | let read: Effect.Effect<Table> = Effect.succeed([ |
| 810 | cli, |
| 811 | processRow(1001, 1000, 0), |
| 812 | processRow(1100, 1001, 1), |
| 813 | ]); |
| 814 | const tracker = makeClaudeDescendantTracker( |
| 815 | 1000, |
| 816 | Effect.suspend(() => read), |
| 817 | ); |
| 818 | return Effect.gen(function* () { |
| 819 | yield* tracker.refresh; |
| 820 | read = Deferred.succeed(olderReadStarted, undefined).pipe( |
| 821 | Effect.andThen(Deferred.await(olderRead)), |
| 822 | ); |
| 823 | const older = yield* tracker.refresh.pipe(Effect.forkChild); |
| 824 | yield* Deferred.await(olderReadStarted); |
| 825 | read = Effect.succeed([cli, processRow(1200, 1, 1), processRow(1300, 1000, 2)]); |
| 826 | const newer = yield* tracker.refresh.pipe(Effect.forkChild({ startImmediately: true })); |
| 827 | yield* Deferred.succeed(olderRead, [ |
| 828 | cli, |
| 829 | processRow(1100, 1, 1), |
| 830 | processRow(1200, 1100, 1), |
| 831 | ]); |
| 832 | yield* Fiber.join(older); |
| 833 | yield* Fiber.join(newer); |
| 834 | read = Effect.succeed([processRow(1200, 1, 1), processRow(1300, 1, 2)]); |
| 835 | assert.deepStrictEqual( |
| 836 | (yield* tracker.leftovers).map((row) => row.pid).toSorted(byNumber), |
| 837 | [1200, 1300], |
| 838 | ); |
| 839 | }); |
| 840 | }, |
| 841 | ); |
| 842 | |
| 843 | const rootRefusal = |
| 844 | "--dangerously-skip-permissions cannot be used with root/sudo privileges for security reasons"; |
| 845 | |
| 846 | const startupFailureMessage = (stderr: string) => |
| 847 | Effect.gen(function* () { |
| 848 | const cli = fakeClaudeCli(`printf '%s\\n' '${stderr}' >&2\nexit 1`); |
| 849 | yield* Effect.addFinalizer(() => |
| 850 | Effect.sync(() => NodeFS.rmSync(NodePath.dirname(cli), { recursive: true, force: true })), |
| 851 | ); |
| 852 | const session = yield* openFakeCli(cli); |
| 853 | const exit = yield* Stream.runDrain(session.messages).pipe(Effect.exit); |
| 854 | assert.isTrue(Exit.isFailure(exit)); |
| 855 | return Exit.isFailure(exit) |
| 856 | ? makeProviderFailure({ cause: exit.cause, class: "transport_error" }).message |
| 857 | : ""; |
| 858 | }); |
| 859 | |
| 860 | // Startup stderr can carry paths, tokens, or settings, so only the known |
| 861 | // refusal reaches the failure the client shows. |
| 862 | it.effect("keeps other startup stderr out of the turn failure", () => |
| 863 | Effect.gen(function* () { |
| 864 | const surrounded = yield* startupFailureMessage( |
| 865 | `token=sk-private-123\n${rootRefusal}\nat /home/private/settings.json`, |
| 866 | ); |
| 867 | assert.include(surrounded, rootRefusal); |
| 868 | assert.notInclude(surrounded, "sk-private-123"); |
| 869 | assert.notInclude(surrounded, "/home/private"); |
| 870 | |
| 871 | const unknown = yield* startupFailureMessage("token=sk-private-123"); |
| 872 | assert.notInclude(unknown, "sk-private-123"); |
| 873 | // The exit status carries no private text and tells the user the CLI itself died. |
| 874 | assert.include(unknown, "Claude Code process exited with code 1"); |
| 875 | |
| 876 | const missingConversation = yield* startupFailureMessage( |
| 877 | "No conversation found with session ID: sk-private-123", |
| 878 | ); |
| 879 | assert.include(missingConversation, "could not find this conversation"); |
| 880 | assert.notInclude(missingConversation, "sk-private-123"); |
| 881 | }).pipe(Effect.provide(realQueryRunner)), |
| 882 | ); |
| 883 | |
| 884 | // What Claude Code writes when the session store behind --resume is gone. |
| 885 | it.effect("names a resumed conversation Claude Code cannot find", () => |
| 886 | Effect.gen(function* () { |
| 887 | const missing = "No conversation found with session ID: native-session-fake-cli"; |
| 888 | const result = JSON.stringify({ |
| 889 | type: "result", |
| 890 | subtype: "error_during_execution", |
| 891 | is_error: true, |
| 892 | num_turns: 0, |
| 893 | duration_ms: 0, |
| 894 | duration_api_ms: 0, |
| 895 | total_cost_usd: 0, |
| 896 | usage: {}, |
| 897 | modelUsage: {}, |
| 898 | permission_denials: [], |
| 899 | errors: [missing], |
| 900 | session_id: "native-session-fake-cli", |
| 901 | uuid: "00000000-0000-4000-8000-000000000000", |
| 902 | }); |
| 903 | const cli = fakeClaudeCli( |
| 904 | `printf '%s\\n' '${result}'\nprintf '%s\\n' '${missing}' >&2\nexit 1`, |
| 905 | ); |
| 906 | yield* Effect.addFinalizer(() => |
| 907 | Effect.sync(() => NodeFS.rmSync(NodePath.dirname(cli), { recursive: true, force: true })), |
| 908 | ); |
| 909 | const session = yield* openFakeCli(cli); |
| 910 | const exit = yield* Stream.runDrain(session.messages).pipe(Effect.exit); |
| 911 | assert.isTrue(Exit.isFailure(exit)); |
| 912 | if (Exit.isFailure(exit)) { |
| 913 | assert.include( |
| 914 | makeProviderFailure({ cause: exit.cause, class: "transport_error" }).message, |
| 915 | "could not find this conversation", |
| 916 | ); |
| 917 | } |
| 918 | }).pipe(Effect.provide(realQueryRunner)), |
| 919 | ); |
| 920 | |
| 921 | // The CLI keeps running its turn after its pipes close, so a server that |
| 922 | // crashed would leave it working next to the session it resumes. |
| 923 | it.effect("stops the CLI when the server that started it goes away", () => |
| 924 | Effect.gen(function* () { |
| 925 | const cli = fakeClaudeCli(['dir=$(dirname "$0")', 'sleep 600 > "$dir/alive"'].join("\n")); |
| 926 | const dir = NodePath.dirname(cli); |
| 927 | NodeChildProcess.execFileSync("mkfifo", [NodePath.join(dir, "alive")]); |
| 928 | const child = spawnClaudeProcessGroup({ |
| 929 | command: cli, |
| 930 | args: [], |
| 931 | cwd: dir, |
| 932 | env: process.env, |
| 933 | // @effect-diagnostics-next-line abortControllerInEffect:off - This crash fixture closes pipes itself; aborting on test teardown raises an unrelated process error. |
| 934 | signal: new AbortController().signal, |
| 935 | }) as NodeChildProcess.ChildProcess; |
| 936 | yield* Effect.addFinalizer(() => |
| 937 | Effect.sync(() => { |
| 938 | try { |
| 939 | signalProcessGroup(child.pid ?? 0, "SIGKILL"); |
| 940 | } catch {} |
| 941 | NodeFS.rmSync(dir, { recursive: true, force: true }); |
| 942 | }), |
| 943 | ); |
| 944 | const alive = NodeFS.createReadStream(NodePath.join(dir, "alive")); |
| 945 | const turnStarted = new Promise<void>((resolve) => alive.once("open", () => resolve())); |
| 946 | const turnStopped = new Promise<void>((resolve) => alive.once("close", () => resolve())); |
| 947 | alive.resume(); |
| 948 | yield* Effect.promise(() => turnStarted); |
| 949 | |
| 950 | // A dying server's descriptors close; the kernel would do this for it. |
| 951 | for (const pipe of child.stdio) pipe?.destroy(); |
| 952 | yield* Effect.promise(() => turnStopped); |
| 953 | }), |
| 954 | ); |
| 955 | |
| 956 | // A native cwd makes libuv wait for chdir, which a hung mount stalls with the whole server. |
| 957 | it.effect("enters the cwd in the child, so a missing one fails the CLI and not the spawn", () => |
| 958 | Effect.gen(function* () { |
| 959 | const cli = fakeClaudeCli('pwd -P > "$(dirname "$0")/cwd"'); |
| 960 | const dir = NodePath.dirname(cli); |
| 961 | const workspace = NodePath.join(dir, "work space"); |
| 962 | NodeFS.mkdirSync(workspace); |
| 963 | yield* Effect.addFinalizer(() => |
| 964 | Effect.sync(() => NodeFS.rmSync(dir, { recursive: true, force: true })), |
| 965 | ); |
| 966 | const exitCode = (cwd: string) => |
| 967 | Effect.promise( |
| 968 | () => |
| 969 | new Promise<number | null>((resolve) => |
| 970 | spawnClaudeProcessGroup({ |
| 971 | command: cli, |
| 972 | args: [], |
| 973 | cwd, |
| 974 | env: process.env, |
| 975 | signal: new AbortController().signal, |
| 976 | }).once("exit", resolve), |
| 977 | ), |
| 978 | ); |
| 979 | assert.equal(yield* exitCode(workspace), 0); |
| 980 | assert.equal( |
| 981 | NodeFS.readFileSync(NodePath.join(dir, "cwd"), "utf8"), |
| 982 | `${NodeFS.realpathSync(workspace)}\n`, |
| 983 | ); |
| 984 | assert.equal(yield* exitCode(NodePath.join(dir, "missing")), 125); |
| 985 | }), |
| 986 | ); |
| 987 | |
| 988 | // A restarted server reaps recorded CLIs, so a CLI must never run before its record exists. |
| 989 | it.effect("records the CLI before it runs and forgets it once it exits", () => |
| 990 | Effect.gen(function* () { |
| 991 | const cli = fakeClaudeCli( |
| 992 | ['dir=$(dirname "$0")', 'printf \'%s %s\' "$$" "$(cat "$dir/record")" > "$dir/seen"'].join( |
| 993 | "\n", |
| 994 | ), |
| 995 | ); |
| 996 | const dir = NodePath.dirname(cli); |
| 997 | NodeChildProcess.execFileSync("mkfifo", [NodePath.join(dir, "seen")]); |
| 998 | yield* Effect.addFinalizer(() => |
| 999 | Effect.sync(() => NodeFS.rmSync(dir, { recursive: true, force: true })), |
| 1000 | ); |
| 1001 | const forgotten = yield* Deferred.make<void>(); |
| 1002 | let registered = 0; |
| 1003 | spawnClaudeProcessGroup( |
| 1004 | { |
| 1005 | command: cli, |
| 1006 | args: [], |
| 1007 | cwd: dir, |
| 1008 | env: process.env, |
| 1009 | // @effect-diagnostics-next-line abortControllerInEffect:off - The CLI exits on its own. |
| 1010 | signal: new AbortController().signal, |
| 1011 | }, |
| 1012 | undefined, |
| 1013 | undefined, |
| 1014 | undefined, |
| 1015 | (pid) => { |
| 1016 | registered = pid; |
| 1017 | NodeFS.writeFileSync(NodePath.join(dir, "record"), String(pid)); |
| 1018 | return () => Deferred.doneUnsafe(forgotten, Effect.void); |
| 1019 | }, |
| 1020 | ); |
| 1021 | const seen = yield* Effect.promise(() => |
| 1022 | NodeFS.promises.readFile(NodePath.join(dir, "seen"), "utf8"), |
| 1023 | ); |
| 1024 | assert.equal(seen, `${registered} ${registered}`); |
| 1025 | yield* Deferred.await(forgotten); |
| 1026 | }), |
| 1027 | ); |
| 1028 | |
| 1029 | it.effect("marks the CLI's jobs with its thread and counts it as an agent until it exits", () => { |
| 1030 | let runningAgents = 0; |
| 1031 | let releaseAgent!: () => void; |
| 1032 | const agentReleased = new Promise<void>((resolve) => (releaseAgent = resolve)); |
| 1033 | const runner = layerQueryRunner.pipe( |
| 1034 | Layer.provide( |
| 1035 | Layer.mock(PortScanner.PortDiscovery)({ |
| 1036 | trackAgent: () => { |
| 1037 | runningAgents += 1; |
| 1038 | return () => { |
| 1039 | runningAgents -= 1; |
| 1040 | releaseAgent(); |
| 1041 | }; |
| 1042 | }, |
| 1043 | }), |
| 1044 | ), |
| 1045 | Layer.provide( |
| 1046 | Layer.succeed(ProviderEventLoggers, { native: undefined, canonical: undefined }), |
| 1047 | ), |
| 1048 | Layer.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)), |
| 1049 | ); |
| 1050 | return Effect.gen(function* () { |
| 1051 | const cli = fakeClaudeCli( |
| 1052 | [ |
| 1053 | 'dir=$(dirname "$0")', |
| 1054 | `printf '%s' "$${PortScanner.AGENT_THREAD_ENV}" > "$dir/thread"`, |
| 1055 | "cat > /dev/null", |
| 1056 | ].join("\n"), |
| 1057 | ); |
| 1058 | const dir = NodePath.dirname(cli); |
| 1059 | NodeChildProcess.execFileSync("mkfifo", [NodePath.join(dir, "thread")]); |
| 1060 | yield* Effect.addFinalizer(() => |
| 1061 | Effect.sync(() => NodeFS.rmSync(dir, { recursive: true, force: true })), |
| 1062 | ); |
| 1063 | const threadRead = new Promise<string>((resolve) => { |
| 1064 | let thread = ""; |
| 1065 | NodeFS.createReadStream(NodePath.join(dir, "thread"), "utf8") |
| 1066 | .on("data", (chunk) => (thread += chunk)) |
| 1067 | .once("end", () => resolve(thread)); |
| 1068 | }); |
| 1069 | |
| 1070 | const session = yield* openFakeCli(cli); |
| 1071 | assert.equal(yield* Effect.promise(() => threadRead), "thread-fake-cli"); |
| 1072 | assert.equal(runningAgents, 1); |
| 1073 | yield* session.close; |
| 1074 | yield* Effect.promise(() => agentReleased); |
| 1075 | assert.equal(runningAgents, 0); |
| 1076 | }).pipe(Effect.provide(runner)); |
| 1077 | }); |
| 1078 | }); |