|
| 1 | +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; |
| 2 | +import { markMcpLoopbackRequestStarted } from "../../gateway/mcp-http.loopback-runtime.js"; |
| 3 | +import type { getProcessSupervisor } from "../../process/supervisor/index.js"; |
| 4 | +import { |
| 5 | + buildClaudeLiveRunContext, |
| 6 | + buildPreparedCliRunContext, |
| 7 | + createCancelableLiveRunLifecycle, |
| 8 | + createClaudeInputStartedEvent, |
| 9 | + mockClaudeLiveRun, |
| 10 | +} from "../cli-runner.test-helpers.js"; |
| 11 | +import { |
| 12 | + restoreCliRunnerPrepareTestDeps, |
| 13 | + supervisorSpawnMock, |
| 14 | +} from "../cli-runner.test-support.js"; |
| 15 | +import { runClaudeTurn } from "./claude-live-session.js"; |
| 16 | +import { resetClaudeLiveSessionsForTest } from "./claude-live-session.test-support.js"; |
| 17 | +import { executePreparedCliRun } from "./execute.js"; |
| 18 | +import { cliBackendLog } from "./log.js"; |
| 19 | + |
| 20 | +type ProcessSupervisor = ReturnType<typeof getProcessSupervisor>; |
| 21 | +type SupervisorSpawnFn = ProcessSupervisor["spawn"]; |
| 22 | + |
| 23 | +function emitClaudeInputStarted(stdout: ((chunk: string) => void) | undefined, data: string): void { |
| 24 | + const event = createClaudeInputStartedEvent(data); |
| 25 | + if (event) { |
| 26 | + stdout?.(`${JSON.stringify(event)}\n`); |
| 27 | + } |
| 28 | +} |
| 29 | + |
| 30 | +function createCapturedLiveTurnRunner(options: { |
| 31 | + results: string[]; |
| 32 | + cleanup?: (runId: string) => Promise<void>; |
| 33 | +}) { |
| 34 | + const cancels: Array<ReturnType<typeof vi.fn>> = []; |
| 35 | + const captureKeys: string[] = []; |
| 36 | + let turnIndex = 0; |
| 37 | + supervisorSpawnMock.mockImplementation(async (...args: unknown[]) => { |
| 38 | + const spawnIndex = supervisorSpawnMock.mock.calls.length; |
| 39 | + const input = (args[0] ?? {}) as { onStdout?: (chunk: string) => void }; |
| 40 | + const lifecycle = createCancelableLiveRunLifecycle(); |
| 41 | + cancels.push(lifecycle.cancel); |
| 42 | + return { |
| 43 | + runId: `live-run-${spawnIndex}`, |
| 44 | + pid: 2345 + spawnIndex, |
| 45 | + startedAtMs: Date.now(), |
| 46 | + stdin: { |
| 47 | + write: vi.fn((dataValue: string, cb?: (err?: Error | null) => void) => { |
| 48 | + emitClaudeInputStarted(input.onStdout, dataValue); |
| 49 | + const result = options.results[turnIndex] ?? "ok"; |
| 50 | + turnIndex += 1; |
| 51 | + input.onStdout?.( |
| 52 | + [ |
| 53 | + JSON.stringify({ type: "system", subtype: "init", session_id: "live-session" }), |
| 54 | + JSON.stringify({ type: "result", session_id: "live-session", result }), |
| 55 | + ].join("\n") + "\n", |
| 56 | + ); |
| 57 | + cb?.(); |
| 58 | + }), |
| 59 | + end: vi.fn(), |
| 60 | + }, |
| 61 | + ...lifecycle, |
| 62 | + }; |
| 63 | + }); |
| 64 | + const runTurn = async (runId: string, args: string[], env: Record<string, string>) => { |
| 65 | + const context = buildClaudeLiveRunContext({ |
| 66 | + runId, |
| 67 | + backend: { |
| 68 | + resumeArgs: ["-p", "--output-format", "stream-json", "--resume", "{sessionId}"], |
| 69 | + }, |
| 70 | + mcpDeliveryCapture: true, |
| 71 | + }); |
| 72 | + const result = await runClaudeTurn({ |
| 73 | + context, |
| 74 | + args, |
| 75 | + env, |
| 76 | + prompt: "hi", |
| 77 | + useResume: args.some((entry) => entry.startsWith("--resume")), |
| 78 | + noOutputTimeoutMs: 1_000, |
| 79 | + getProcessSupervisor: () => ({ |
| 80 | + spawn: (spawnArgs: Parameters<SupervisorSpawnFn>[0]) => |
| 81 | + supervisorSpawnMock(spawnArgs) as ReturnType<SupervisorSpawnFn>, |
| 82 | + cancel: vi.fn(), |
| 83 | + cancelScope: vi.fn(), |
| 84 | + getRecord: vi.fn(), |
| 85 | + }), |
| 86 | + onAssistantDelta: () => {}, |
| 87 | + onMcpCaptureReady: (captureKey) => captureKeys.push(captureKey), |
| 88 | + cleanup: async () => { |
| 89 | + await options.cleanup?.(runId); |
| 90 | + }, |
| 91 | + }); |
| 92 | + return result.output.text; |
| 93 | + }; |
| 94 | + return { cancels, captureKeys, runTurn }; |
| 95 | +} |
| 96 | + |
| 97 | +beforeEach(() => { |
| 98 | + resetClaudeLiveSessionsForTest(); |
| 99 | + restoreCliRunnerPrepareTestDeps(); |
| 100 | + supervisorSpawnMock.mockClear(); |
| 101 | +}); |
| 102 | + |
| 103 | +afterEach(() => { |
| 104 | + vi.restoreAllMocks(); |
| 105 | + vi.useRealTimers(); |
| 106 | + resetClaudeLiveSessionsForTest(); |
| 107 | +}); |
| 108 | + |
| 109 | +describe("Claude live MCP capture lifetime", () => { |
| 110 | + it("reuses a captured Claude live process and capture key across resume turns", async () => { |
| 111 | + const logInfoSpy = vi.spyOn(cliBackendLog, "info").mockImplementation(() => undefined); |
| 112 | + const { cancels, captureKeys, runTurn } = createCapturedLiveTurnRunner({ |
| 113 | + results: ["first-ok", "resume-ok"], |
| 114 | + }); |
| 115 | + const env = { ANTHROPIC_BASE_URL: "https://one.example" }; |
| 116 | + const freshArgs = ["-p", "--output-format", "stream-json"]; |
| 117 | + const resumeArgs = ["-p", "--output-format", "stream-json", "--resume", "live-session"]; |
| 118 | + |
| 119 | + await expect(runTurn("run-live-fresh", freshArgs, env)).resolves.toBe("first-ok"); |
| 120 | + await expect(runTurn("run-live-resume", resumeArgs, env)).resolves.toBe("resume-ok"); |
| 121 | + |
| 122 | + expect(supervisorSpawnMock).toHaveBeenCalledOnce(); |
| 123 | + expect(cancels[0]).not.toHaveBeenCalled(); |
| 124 | + expect(captureKeys[0]).toEqual(expect.any(String)); |
| 125 | + expect(captureKeys).toEqual([captureKeys[0], captureKeys[0]]); |
| 126 | + expect( |
| 127 | + logInfoSpy.mock.calls |
| 128 | + .map(([message]) => message) |
| 129 | + .filter((message) => typeof message === "string" && message.includes("reason=restart")), |
| 130 | + ).toEqual([]); |
| 131 | + }); |
| 132 | + |
| 133 | + it("still restarts a captured Claude live process when resume identity changes", async () => { |
| 134 | + const logWarnSpy = vi.spyOn(cliBackendLog, "warn").mockImplementation(() => undefined); |
| 135 | + const { cancels, captureKeys, runTurn } = createCapturedLiveTurnRunner({ |
| 136 | + results: ["first-ok", "env-ok", "fresh-ok"], |
| 137 | + cleanup: async (runId) => { |
| 138 | + if (runId === "run-live-fresh") { |
| 139 | + throw new Error("captured cleanup failed"); |
| 140 | + } |
| 141 | + }, |
| 142 | + }); |
| 143 | + const freshArgs = ["-p", "--output-format", "stream-json"]; |
| 144 | + const resumeArgs = ["-p", "--output-format", "stream-json", "--resume", "live-session"]; |
| 145 | + |
| 146 | + await expect( |
| 147 | + runTurn("run-live-fresh", freshArgs, { ANTHROPIC_BASE_URL: "https://one.example" }), |
| 148 | + ).resolves.toBe("first-ok"); |
| 149 | + await expect( |
| 150 | + runTurn("run-live-env-change", resumeArgs, { ANTHROPIC_BASE_URL: "https://two.example" }), |
| 151 | + ).resolves.toBe("env-ok"); |
| 152 | + expect(supervisorSpawnMock).toHaveBeenCalledTimes(2); |
| 153 | + expect(cancels[0]).toHaveBeenCalledWith("manual-cancel"); |
| 154 | + expect(captureKeys[1]).not.toBe(captureKeys[0]); |
| 155 | + |
| 156 | + await expect( |
| 157 | + runTurn("run-live-fresh-retry", freshArgs, { ANTHROPIC_BASE_URL: "https://two.example" }), |
| 158 | + ).resolves.toBe("fresh-ok"); |
| 159 | + expect(supervisorSpawnMock).toHaveBeenCalledTimes(3); |
| 160 | + expect(cancels[1]).toHaveBeenCalledWith("manual-cancel"); |
| 161 | + expect(captureKeys[2]).not.toBe(captureKeys[1]); |
| 162 | + expect(logWarnSpy).toHaveBeenCalledWith( |
| 163 | + expect.stringContaining("Claude live session cleanup failed: captured cleanup failed"), |
| 164 | + ); |
| 165 | + }); |
| 166 | + |
| 167 | + it("fences a reused Claude live capture key between execute turns", async () => { |
| 168 | + const live = mockClaudeLiveRun(supervisorSpawnMock, { |
| 169 | + cancelable: true, |
| 170 | + onWrite: ({ data, emit, writeIndex }) => { |
| 171 | + if ((JSON.parse(data) as { type?: string }).type !== "user") { |
| 172 | + return; |
| 173 | + } |
| 174 | + emit([ |
| 175 | + { type: "system", subtype: "init", session_id: "captured-live" }, |
| 176 | + { |
| 177 | + type: "result", |
| 178 | + session_id: "captured-live", |
| 179 | + result: writeIndex === 0 ? "one" : "two", |
| 180 | + }, |
| 181 | + ]); |
| 182 | + }, |
| 183 | + }); |
| 184 | + const activateCapture = vi.fn<(captureKey: string) => void>(); |
| 185 | + const deactivateCapture = vi.fn<(captureKey: string) => void>(); |
| 186 | + const backend = { |
| 187 | + resumeArgs: ["-p", "--output-format", "stream-json", "--resume={sessionId}"], |
| 188 | + liveSession: "claude-stdio" as const, |
| 189 | + }; |
| 190 | + const buildContext = (prompt: string) => { |
| 191 | + const context = buildPreparedCliRunContext({ |
| 192 | + backend, |
| 193 | + prompt, |
| 194 | + mcpDeliveryCapture: true, |
| 195 | + }); |
| 196 | + context.preparedBackend.mcpClientGrantCapture = { |
| 197 | + activate: activateCapture, |
| 198 | + deactivate: deactivateCapture, |
| 199 | + }; |
| 200 | + return context; |
| 201 | + }; |
| 202 | + |
| 203 | + const first = await executePreparedCliRun(buildContext("first")); |
| 204 | + const second = await executePreparedCliRun(buildContext("second"), "captured-live"); |
| 205 | + |
| 206 | + expect(first.text).toBe("one"); |
| 207 | + expect(second.text).toBe("two"); |
| 208 | + expect(supervisorSpawnMock).toHaveBeenCalledOnce(); |
| 209 | + expect(live.lifecycle.cancel).not.toHaveBeenCalled(); |
| 210 | + const captureKey = activateCapture.mock.calls[0]?.[0]; |
| 211 | + expect(typeof captureKey).toBe("string"); |
| 212 | + expect(captureKey?.length).toBeGreaterThan(0); |
| 213 | + expect(activateCapture.mock.calls.map(([key]) => key)).toEqual([captureKey, captureKey]); |
| 214 | + expect(deactivateCapture.mock.calls.map(([key]) => key)).toEqual([captureKey, captureKey]); |
| 215 | + expect(deactivateCapture.mock.invocationCallOrder[0]).toBeLessThan( |
| 216 | + activateCapture.mock.invocationCallOrder[1]!, |
| 217 | + ); |
| 218 | + }); |
| 219 | + |
| 220 | + it("closes a captured Claude live process when MCP delivery capture cannot drain", async () => { |
| 221 | + const logInfoSpy = vi.spyOn(cliBackendLog, "info").mockImplementation(() => undefined); |
| 222 | + const live = mockClaudeLiveRun(supervisorSpawnMock, { |
| 223 | + cancelable: true, |
| 224 | + onWrite: ({ data, emit }) => { |
| 225 | + if ((JSON.parse(data) as { type?: string }).type !== "user") { |
| 226 | + return; |
| 227 | + } |
| 228 | + markMcpLoopbackRequestStarted(live.spawnInput.env?.OPENCLAW_MCP_CLI_CAPTURE_KEY); |
| 229 | + emit([ |
| 230 | + { type: "system", subtype: "init", session_id: "captured-drain" }, |
| 231 | + { type: "result", session_id: "captured-drain", result: "ok" }, |
| 232 | + ]); |
| 233 | + }, |
| 234 | + }); |
| 235 | + const context = buildClaudeLiveRunContext({ |
| 236 | + backend: { |
| 237 | + resumeArgs: ["-p", "--output-format", "stream-json", "--resume={sessionId}"], |
| 238 | + }, |
| 239 | + mcpDeliveryCapture: true, |
| 240 | + }); |
| 241 | + |
| 242 | + await expect(executePreparedCliRun(context)).rejects.toThrow( |
| 243 | + "CLI message tool call remained in flight after exit", |
| 244 | + ); |
| 245 | + expect(live.lifecycle.cancel).toHaveBeenCalledWith("manual-cancel"); |
| 246 | + expect( |
| 247 | + logInfoSpy.mock.calls |
| 248 | + .map(([message]) => message) |
| 249 | + .some( |
| 250 | + (message) => |
| 251 | + typeof message === "string" && message.includes("reason=mcp-capture-rotation"), |
| 252 | + ), |
| 253 | + ).toBe(true); |
| 254 | + }, 15_000); |
| 255 | +}); |
0 commit comments