|
| 1 | +/** Claude live session: base64 image payloads in tool_result lines are metered as stubs. */ |
| 2 | +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; |
| 3 | +import { |
| 4 | + setDiagnosticsEnabledForProcess, |
| 5 | + waitForDiagnosticEventsDrained, |
| 6 | +} from "../../infra/diagnostic-events.js"; |
| 7 | +import { |
| 8 | + resetDiagnosticRunActivityForTest, |
| 9 | + startDiagnosticRunActivityTracking, |
| 10 | +} from "../../logging/diagnostic-run-activity.js"; |
| 11 | +import type { getProcessSupervisor } from "../../process/supervisor/index.js"; |
| 12 | +import type { CliToolResultDelta } from "../cli-output.js"; |
| 13 | +import { |
| 14 | + restoreCliRunnerPrepareTestDeps, |
| 15 | + supervisorSpawnMock, |
| 16 | +} from "../cli-runner.test-support.js"; |
| 17 | +import { runClaudeLiveSessionTurn } from "./claude-live-session.js"; |
| 18 | +import { resetClaudeLiveSessionsForTest } from "./claude-live-session.test-support.js"; |
| 19 | +import { setCliRunnerExecuteTestDeps } from "./execute.test-support.js"; |
| 20 | +import { writeCliSystemPromptFile } from "./helpers.js"; |
| 21 | +import type { PreparedCliRunContext } from "./types.js"; |
| 22 | + |
| 23 | +vi.mock("../../plugin-sdk/anthropic-cli.js", () => ({ |
| 24 | + CLAUDE_CLI_BACKEND_ID: "claude-cli", |
| 25 | + isClaudeCliProvider: (providerId: string) => providerId === "claude-cli", |
| 26 | +})); |
| 27 | + |
| 28 | +type ProcessSupervisor = ReturnType<typeof getProcessSupervisor>; |
| 29 | +type SupervisorSpawnFn = ProcessSupervisor["spawn"]; |
| 30 | + |
| 31 | +beforeEach(() => { |
| 32 | + setDiagnosticsEnabledForProcess(true); |
| 33 | + resetDiagnosticRunActivityForTest(); |
| 34 | + startDiagnosticRunActivityTracking(); |
| 35 | + resetClaudeLiveSessionsForTest(); |
| 36 | + restoreCliRunnerPrepareTestDeps(); |
| 37 | + setCliRunnerExecuteTestDeps({ writeCliSystemPromptFile }); |
| 38 | + supervisorSpawnMock.mockClear(); |
| 39 | +}); |
| 40 | + |
| 41 | +afterEach(async () => { |
| 42 | + vi.restoreAllMocks(); |
| 43 | + vi.useRealTimers(); |
| 44 | + resetDiagnosticRunActivityForTest(); |
| 45 | + resetClaudeLiveSessionsForTest(); |
| 46 | + await waitForDiagnosticEventsDrained(); |
| 47 | +}); |
| 48 | + |
| 49 | +function buildPreparedCliRunContext(params: { |
| 50 | + runId: string; |
| 51 | + sessionId?: string; |
| 52 | + sessionKey?: string; |
| 53 | +}): PreparedCliRunContext { |
| 54 | + const backend = { |
| 55 | + command: "claude", |
| 56 | + args: ["-p", "--output-format", "stream-json"], |
| 57 | + output: "jsonl" as const, |
| 58 | + input: "stdin" as const, |
| 59 | + modelArg: "--model", |
| 60 | + sessionArgs: ["--session-id", "{sessionId}"], |
| 61 | + sessionMode: "always" as const, |
| 62 | + systemPromptFileArg: "--append-system-prompt-file", |
| 63 | + systemPromptWhen: "first" as const, |
| 64 | + serialize: true, |
| 65 | + liveSession: "claude-stdio" as const, |
| 66 | + }; |
| 67 | + return { |
| 68 | + params: { |
| 69 | + sessionId: params.sessionId ?? "s-img", |
| 70 | + sessionKey: params.sessionKey ?? "agent:main:img", |
| 71 | + sessionFile: "/tmp/session.jsonl", |
| 72 | + workspaceDir: "/tmp", |
| 73 | + prompt: "hi", |
| 74 | + provider: "claude-cli", |
| 75 | + model: "sonnet", |
| 76 | + timeoutMs: 60_000, |
| 77 | + runId: params.runId, |
| 78 | + }, |
| 79 | + started: Date.now(), |
| 80 | + workspaceDir: "/tmp", |
| 81 | + backendResolved: { |
| 82 | + id: "claude-cli", |
| 83 | + config: backend, |
| 84 | + bundleMcp: true, |
| 85 | + pluginId: "anthropic", |
| 86 | + }, |
| 87 | + preparedBackend: { |
| 88 | + backend, |
| 89 | + env: {}, |
| 90 | + }, |
| 91 | + reusableCliSession: { mode: "none" }, |
| 92 | + hadSessionFile: false, |
| 93 | + contextEngineConfig: {}, |
| 94 | + modelId: "sonnet", |
| 95 | + normalizedModel: "sonnet", |
| 96 | + systemPrompt: "You are a helpful assistant.", |
| 97 | + systemPromptReport: {} as PreparedCliRunContext["systemPromptReport"], |
| 98 | + bootstrapPromptWarningLines: [], |
| 99 | + authEpochVersion: 2, |
| 100 | + }; |
| 101 | +} |
| 102 | + |
| 103 | +function getProcessSupervisorForTest() { |
| 104 | + return { |
| 105 | + spawn: (params: Parameters<SupervisorSpawnFn>[0]) => |
| 106 | + supervisorSpawnMock(params) as ReturnType<SupervisorSpawnFn>, |
| 107 | + cancel: vi.fn(), |
| 108 | + cancelScope: vi.fn(), |
| 109 | + getRecord: vi.fn(), |
| 110 | + }; |
| 111 | +} |
| 112 | + |
| 113 | +function installLiveStdoutDriver(): { |
| 114 | + cancel: ReturnType<typeof vi.fn>; |
| 115 | + userInputUuids: string[]; |
| 116 | + stdout: { |
| 117 | + emit: (chunk: string) => void; |
| 118 | + waitReady: () => Promise<void>; |
| 119 | + }; |
| 120 | +} { |
| 121 | + let stdoutListener: ((chunk: string) => void) | undefined; |
| 122 | + const cancel = vi.fn(); |
| 123 | + const userInputUuids: string[] = []; |
| 124 | + let markReady: (() => void) | undefined; |
| 125 | + const ready = new Promise<void>((resolve) => { |
| 126 | + markReady = resolve; |
| 127 | + }); |
| 128 | + const stdin = { |
| 129 | + write: vi.fn((data: string, cb?: (err?: Error | null) => void) => { |
| 130 | + const parsed = JSON.parse(data) as { type?: string; uuid?: string }; |
| 131 | + if (parsed.type === "user" && typeof parsed.uuid === "string") { |
| 132 | + userInputUuids.push(parsed.uuid); |
| 133 | + stdoutListener?.( |
| 134 | + jsonl([{ type: "command_lifecycle", command_uuid: parsed.uuid, state: "started" }]), |
| 135 | + ); |
| 136 | + } |
| 137 | + cb?.(); |
| 138 | + markReady?.(); |
| 139 | + }), |
| 140 | + end: vi.fn(), |
| 141 | + }; |
| 142 | + supervisorSpawnMock.mockImplementation(async (...args: unknown[]) => { |
| 143 | + const input = (args[0] ?? {}) as { onStdout?: (chunk: string) => void }; |
| 144 | + stdoutListener = input.onStdout; |
| 145 | + return { |
| 146 | + runId: "live-img-run", |
| 147 | + pid: 4242, |
| 148 | + startedAtMs: Date.now(), |
| 149 | + stdin, |
| 150 | + wait: vi.fn(() => new Promise(() => {})), |
| 151 | + cancel, |
| 152 | + }; |
| 153 | + }); |
| 154 | + return { |
| 155 | + cancel, |
| 156 | + userInputUuids, |
| 157 | + stdout: { |
| 158 | + emit: (chunk: string) => { |
| 159 | + stdoutListener?.(chunk); |
| 160 | + }, |
| 161 | + waitReady: () => ready, |
| 162 | + }, |
| 163 | + }; |
| 164 | +} |
| 165 | + |
| 166 | +function jsonl(lines: unknown[]): string { |
| 167 | + return lines.map((line) => JSON.stringify(line)).join("\n") + "\n"; |
| 168 | +} |
| 169 | + |
| 170 | +function startLiveTurn(params: { |
| 171 | + runId: string; |
| 172 | + onToolResult?: (delta: CliToolResultDelta) => void; |
| 173 | +}) { |
| 174 | + const context = buildPreparedCliRunContext({ runId: params.runId }); |
| 175 | + return runClaudeLiveSessionTurn({ |
| 176 | + context, |
| 177 | + args: context.preparedBackend.backend.args ?? [], |
| 178 | + env: {}, |
| 179 | + prompt: "hi", |
| 180 | + useResume: false, |
| 181 | + noOutputTimeoutMs: 5_000, |
| 182 | + getProcessSupervisor: getProcessSupervisorForTest, |
| 183 | + onAssistantDelta: () => {}, |
| 184 | + onToolResult: params.onToolResult, |
| 185 | + cleanup: async () => {}, |
| 186 | + }); |
| 187 | +} |
| 188 | + |
| 189 | +function imageToolResultLine(params: { |
| 190 | + toolCallId: string; |
| 191 | + base64: string; |
| 192 | +}): Record<string, unknown> { |
| 193 | + return { |
| 194 | + type: "user", |
| 195 | + session_id: "live-img", |
| 196 | + message: { |
| 197 | + role: "user", |
| 198 | + content: [ |
| 199 | + { |
| 200 | + type: "tool_result", |
| 201 | + tool_use_id: params.toolCallId, |
| 202 | + content: [ |
| 203 | + { |
| 204 | + type: "image", |
| 205 | + source: { |
| 206 | + type: "base64", |
| 207 | + media_type: "image/jpeg", |
| 208 | + data: params.base64, |
| 209 | + }, |
| 210 | + }, |
| 211 | + ], |
| 212 | + }, |
| 213 | + ], |
| 214 | + }, |
| 215 | + }; |
| 216 | +} |
| 217 | + |
| 218 | +describe("claude live session image payload metering", () => { |
| 219 | + it("completes a photo-heavy turn instead of tripping the raw-chars output cap", async () => { |
| 220 | + const driver = installLiveStdoutDriver(); |
| 221 | + const resultPromise = startLiveTurn({ runId: "run-img-over-cap" }); |
| 222 | + await driver.stdout.waitReady(); |
| 223 | + |
| 224 | + // Three tool_result lines carrying ~3 MiB of base64 image data each: the |
| 225 | + // turn-level raw-chars cap is 8 MiB, so without stub metering the turn |
| 226 | + // would abort with "Claude CLI turn output exceeded limit". Lines are |
| 227 | + // emitted one per chunk, as the CLI writes them; a single multi-MiB chunk |
| 228 | + // would instead trip the pending-line buffer cap. |
| 229 | + const bigImage = "A".repeat(3 * 1024 * 1024); |
| 230 | + for (const line of [ |
| 231 | + { type: "system", subtype: "init", session_id: "live-img" }, |
| 232 | + { |
| 233 | + type: "assistant", |
| 234 | + session_id: "live-img", |
| 235 | + message: { |
| 236 | + role: "assistant", |
| 237 | + content: [{ type: "text", text: "Reading photos." }], |
| 238 | + }, |
| 239 | + }, |
| 240 | + imageToolResultLine({ toolCallId: "tool-img-1", base64: bigImage }), |
| 241 | + imageToolResultLine({ toolCallId: "tool-img-2", base64: bigImage }), |
| 242 | + imageToolResultLine({ toolCallId: "tool-img-3", base64: bigImage }), |
| 243 | + { |
| 244 | + type: "assistant", |
| 245 | + session_id: "live-img", |
| 246 | + message: { |
| 247 | + role: "assistant", |
| 248 | + content: [{ type: "text", text: "Summarized the photos." }], |
| 249 | + }, |
| 250 | + }, |
| 251 | + { |
| 252 | + type: "result", |
| 253 | + subtype: "success", |
| 254 | + session_id: "live-img", |
| 255 | + result: "Summarized the photos.", |
| 256 | + stop_reason: "end_turn", |
| 257 | + }, |
| 258 | + ]) { |
| 259 | + driver.stdout.emit(`${JSON.stringify(line)}\n`); |
| 260 | + } |
| 261 | + |
| 262 | + const result = await resultPromise; |
| 263 | + expect(result.output.text).toContain("Summarized the photos."); |
| 264 | + expect(driver.cancel).not.toHaveBeenCalled(); |
| 265 | + }); |
| 266 | + |
| 267 | + it("feeds the streaming parser stubbed image payloads instead of raw base64", async () => { |
| 268 | + const driver = installLiveStdoutDriver(); |
| 269 | + const onToolResult = vi.fn(); |
| 270 | + const resultPromise = startLiveTurn({ runId: "run-img-stub", onToolResult }); |
| 271 | + await driver.stdout.waitReady(); |
| 272 | + |
| 273 | + const bigImage = "A".repeat(1024 * 1024); |
| 274 | + driver.stdout.emit( |
| 275 | + jsonl([ |
| 276 | + { type: "system", subtype: "init", session_id: "live-img" }, |
| 277 | + imageToolResultLine({ toolCallId: "tool-img-stub", base64: bigImage }), |
| 278 | + { |
| 279 | + type: "assistant", |
| 280 | + session_id: "live-img", |
| 281 | + message: { |
| 282 | + role: "assistant", |
| 283 | + content: [{ type: "text", text: "Done." }], |
| 284 | + }, |
| 285 | + }, |
| 286 | + { |
| 287 | + type: "result", |
| 288 | + subtype: "success", |
| 289 | + session_id: "live-img", |
| 290 | + result: "Done.", |
| 291 | + stop_reason: "end_turn", |
| 292 | + }, |
| 293 | + ]), |
| 294 | + ); |
| 295 | + |
| 296 | + await resultPromise; |
| 297 | + const delta = onToolResult.mock.calls[0]?.[0]; |
| 298 | + expect(delta).toMatchObject({ toolCallId: "tool-img-stub" }); |
| 299 | + const blocks = delta?.result as Array<Record<string, unknown>>; |
| 300 | + expect(Array.isArray(blocks)).toBe(true); |
| 301 | + const source = blocks[0]?.source as Record<string, unknown> | undefined; |
| 302 | + expect(source?.data).toBe(`[image: ${bigImage.length} base64 chars omitted]`); |
| 303 | + }); |
| 304 | +}); |
0 commit comments