|
| 1 | +import test, { after } from "node:test"; |
| 2 | +import assert from "node:assert/strict"; |
| 3 | +import { resolve as resolvePath } from "node:path"; |
| 4 | + |
| 5 | +// Stop fns for every "open" fake query, drained after the run so the dangling |
| 6 | +// consume() loops (and the process) can exit. |
| 7 | +const cleanups = []; |
| 8 | +after(() => { |
| 9 | + for (const stop of cleanups) stop(); |
| 10 | +}); |
| 11 | + |
| 12 | +// Unit tests for the ClaudeQuerySession adapter fixes. The class is exported |
| 13 | +// for testing and its constructor takes an injectable `queryFactory`, so these |
| 14 | +// drive the translation/permission/teardown logic with a fake Claude SDK query |
| 15 | +// and a mock ACP connection — no real SDK, no VM. |
| 16 | +const packageDir = resolvePath(import.meta.dirname, ".."); |
| 17 | +const { ClaudeQuerySession } = await import( |
| 18 | + resolvePath(packageDir, "dist", "adapter.js") |
| 19 | +); |
| 20 | + |
| 21 | +function makeConn(overrides = {}) { |
| 22 | + let closeConn; |
| 23 | + const closed = new Promise((r) => { |
| 24 | + closeConn = r; |
| 25 | + }); |
| 26 | + const updates = []; |
| 27 | + return { |
| 28 | + updates, |
| 29 | + closeConn: () => closeConn(), |
| 30 | + sessionUpdate: async (u) => { |
| 31 | + updates.push(u); |
| 32 | + }, |
| 33 | + requestPermission: async () => ({ |
| 34 | + outcome: { outcome: "selected", optionId: "allow_once" }, |
| 35 | + }), |
| 36 | + closed, |
| 37 | + ...overrides, |
| 38 | + }; |
| 39 | +} |
| 40 | + |
| 41 | +function makeQuery({ endImmediately = false } = {}) { |
| 42 | + let stop; |
| 43 | + const stopped = new Promise((r) => { |
| 44 | + stop = r; |
| 45 | + }); |
| 46 | + if (!endImmediately) cleanups.push(stop); |
| 47 | + return { |
| 48 | + setMcpServers: async () => {}, |
| 49 | + interrupt: async () => {}, |
| 50 | + setPermissionMode: async () => {}, |
| 51 | + async *[Symbol.asyncIterator]() { |
| 52 | + if (endImmediately) return; |
| 53 | + await stopped; // ends consume() when drained in `after` |
| 54 | + }, |
| 55 | + }; |
| 56 | +} |
| 57 | + |
| 58 | +function makeSession({ endImmediately = false, conn } = {}) { |
| 59 | + const c = conn ?? makeConn(); |
| 60 | + let capturedOptions; |
| 61 | + const queryFactory = (arg) => { |
| 62 | + capturedOptions = arg.options; |
| 63 | + return makeQuery({ endImmediately }); |
| 64 | + }; |
| 65 | + const sess = new ClaudeQuerySession( |
| 66 | + c, |
| 67 | + "sess-1", |
| 68 | + "/workspace", |
| 69 | + "default", |
| 70 | + { cwd: "/workspace", mcpServers: undefined }, |
| 71 | + "/usr/bin/claude", |
| 72 | + queryFactory, |
| 73 | + ); |
| 74 | + return { sess, conn: c, getOptions: () => capturedOptions }; |
| 75 | +} |
| 76 | + |
| 77 | +// ── Fix #5: input_json_delta maps to the correct tool by content-block index ── |
| 78 | +test("claude #5: partial tool input is attributed by content-block index, not insertion order", async () => { |
| 79 | + const { sess, conn } = makeSession(); |
| 80 | + sess.pendingTurn = { |
| 81 | + sawAssistantText: false, |
| 82 | + sawToolCall: false, |
| 83 | + resolve() {}, |
| 84 | + reject() {}, |
| 85 | + }; |
| 86 | + // A text block occupies content-block index 0; the tool_use block is index 1. |
| 87 | + await sess.handleStreamEvent({ |
| 88 | + event: { type: "content_block_delta", index: 0, delta: { type: "text_delta", text: "thinking..." } }, |
| 89 | + }); |
| 90 | + await sess.handleStreamEvent({ |
| 91 | + event: { |
| 92 | + type: "content_block_start", |
| 93 | + index: 1, |
| 94 | + content_block: { type: "tool_use", id: "tool-A", name: "Bash", input: {} }, |
| 95 | + }, |
| 96 | + }); |
| 97 | + await sess.handleStreamEvent({ |
| 98 | + event: { type: "content_block_delta", index: 1, delta: { type: "input_json_delta", partial_json: '{"command":"ls"}' } }, |
| 99 | + }); |
| 100 | + await sess.lastEmit; |
| 101 | + |
| 102 | + const toolUpdates = conn.updates |
| 103 | + .map((u) => u.update) |
| 104 | + .filter((u) => u?.sessionUpdate === "tool_call_update"); |
| 105 | + // With the old insertion-order lookup, findToolCallByIndex(1) on a 1-entry |
| 106 | + // map returns null and the partial input is silently dropped (no update). |
| 107 | + assert.equal(toolUpdates.length, 1, "expected exactly one tool_call_update for the partial input"); |
| 108 | + assert.equal(toolUpdates[0].toolCallId, "tool-A", "partial input must target the tool at block index 1"); |
| 109 | + assert.equal(toolUpdates[0].rawInput.partial_json, '{"command":"ls"}'); |
| 110 | +}); |
| 111 | + |
| 112 | +test("claude #5: two tool_use blocks at different indices each get their own partial input", async () => { |
| 113 | + const { sess, conn } = makeSession(); |
| 114 | + sess.pendingTurn = { sawAssistantText: false, sawToolCall: false, resolve() {}, reject() {} }; |
| 115 | + // index 0 = text, index 1 = toolA, index 2 = toolB |
| 116 | + await sess.handleStreamEvent({ event: { type: "content_block_delta", index: 0, delta: { type: "text_delta", text: "x" } } }); |
| 117 | + await sess.handleStreamEvent({ event: { type: "content_block_start", index: 1, content_block: { type: "tool_use", id: "tool-A", name: "Bash", input: {} } } }); |
| 118 | + await sess.handleStreamEvent({ event: { type: "content_block_start", index: 2, content_block: { type: "tool_use", id: "tool-B", name: "Read", input: {} } } }); |
| 119 | + await sess.handleStreamEvent({ event: { type: "content_block_delta", index: 2, delta: { type: "input_json_delta", partial_json: '{"path":"/a"}' } } }); |
| 120 | + await sess.handleStreamEvent({ event: { type: "content_block_delta", index: 1, delta: { type: "input_json_delta", partial_json: '{"command":"echo"}' } } }); |
| 121 | + await sess.lastEmit; |
| 122 | + |
| 123 | + const updates = conn.updates.map((u) => u.update).filter((u) => u?.sessionUpdate === "tool_call_update"); |
| 124 | + const byTool = Object.fromEntries(updates.map((u) => [u.toolCallId, u.rawInput.partial_json])); |
| 125 | + assert.equal(byTool["tool-B"], '{"path":"/a"}', "block index 2 → tool-B"); |
| 126 | + assert.equal(byTool["tool-A"], '{"command":"echo"}', "block index 1 → tool-A"); |
| 127 | +}); |
| 128 | + |
| 129 | +// ── Fix #1: permission handler is host-authoritative; no timer auto-resolve ── |
| 130 | +test("claude #1: permission handler returns the host's deny decision", async () => { |
| 131 | + const conn = makeConn({ |
| 132 | + requestPermission: async () => ({ outcome: { outcome: "selected", optionId: "reject_once" } }), |
| 133 | + }); |
| 134 | + const { getOptions } = makeSession({ conn }); |
| 135 | + const canUseTool = getOptions().canUseTool; |
| 136 | + const result = await canUseTool("Bash", { command: "rm -rf /" }, { toolUseID: "t1", title: "Bash", suggestions: [] }); |
| 137 | + assert.equal(result.behavior, "deny", "host reject must produce a deny"); |
| 138 | +}); |
| 139 | + |
| 140 | +test("claude #1: permission handler does NOT auto-resolve on a timer when the host is silent", async () => { |
| 141 | + let pendingResolve; |
| 142 | + const conn = makeConn({ |
| 143 | + // Never settles — simulates a host that hasn't answered yet. |
| 144 | + requestPermission: () => new Promise((r) => { |
| 145 | + pendingResolve = r; |
| 146 | + }), |
| 147 | + }); |
| 148 | + const { getOptions } = makeSession({ conn }); |
| 149 | + const canUseTool = getOptions().canUseTool; |
| 150 | + const handlerPromise = canUseTool("Bash", {}, { toolUseID: "t1", title: "Bash", suggestions: [] }); |
| 151 | + const timer = new Promise((r) => setTimeout(() => r("TIMER_WON"), 300)); |
| 152 | + const winner = await Promise.race([handlerPromise.then(() => "HANDLER_WON"), timer]); |
| 153 | + assert.equal(winner, "TIMER_WON", "handler must not auto-resolve before the host answers (no fail-open timer)"); |
| 154 | + // settle the pending request so the handler promise doesn't dangle |
| 155 | + pendingResolve({ outcome: { outcome: "selected", optionId: "reject_once" } }); |
| 156 | + await handlerPromise; |
| 157 | +}); |
| 158 | + |
| 159 | +// ── Fix #2: emit logs delivery failures (host-visible) and keeps the chain alive ── |
| 160 | +test("claude #2: a failed sessionUpdate is logged to stderr and the emit chain survives", async () => { |
| 161 | + let failNext = true; |
| 162 | + const delivered = []; |
| 163 | + const conn = makeConn({ |
| 164 | + sessionUpdate: async (u) => { |
| 165 | + if (failNext) { |
| 166 | + failNext = false; |
| 167 | + throw new Error("broken pipe"); |
| 168 | + } |
| 169 | + delivered.push(u); |
| 170 | + }, |
| 171 | + }); |
| 172 | + const { sess } = makeSession({ conn }); |
| 173 | + |
| 174 | + const writes = []; |
| 175 | + const orig = process.stderr.write; |
| 176 | + process.stderr.write = (s) => { |
| 177 | + writes.push(String(s)); |
| 178 | + return true; |
| 179 | + }; |
| 180 | + try { |
| 181 | + await sess.emit({ sessionUpdate: "agent_message_chunk", content: { type: "text", text: "a" } }); |
| 182 | + await sess.emit({ sessionUpdate: "agent_message_chunk", content: { type: "text", text: "b" } }); |
| 183 | + await sess.lastEmit; |
| 184 | + } finally { |
| 185 | + process.stderr.write = orig; |
| 186 | + } |
| 187 | + assert.ok( |
| 188 | + writes.some((w) => w.includes("failed to deliver session/update")), |
| 189 | + "a delivery failure must be written to stderr, not swallowed", |
| 190 | + ); |
| 191 | + assert.equal(delivered.length, 1, "the chain must survive the failure and deliver the next update"); |
| 192 | +}); |
| 193 | + |
| 194 | +// ── Fix #4: a dead reader marks the session closed so prompt() fails fast ── |
| 195 | +test("claude #4: once the query stream ends, prompt() fails fast instead of hanging", async () => { |
| 196 | + const { sess } = makeSession({ endImmediately: true }); |
| 197 | + await sess.reader; // wait for consume() to finish on the now-ended query |
| 198 | + await assert.rejects( |
| 199 | + sess.prompt({ prompt: [{ type: "text", text: "hi" }] }), |
| 200 | + /Session is closed/, |
| 201 | + "a prompt on a dead session must reject promptly, not hang", |
| 202 | + ); |
| 203 | +}); |
0 commit comments