Skip to content

Never stop coding. Free MIT AI gateway: one endpoint, 375 providers (150+ free), 1,400+ models Kimi, Claude, GPT, Gemini, GLM, DeepSeek, MiniMax. Works with Claude Code, Codex, Cursor, OpenCode, Cline & Copilot. Quota-aware auto-fallback, RTK+Caveman compression saves 15-95% tokens, MCP/A2A, Desktop/PWA. Built by 900+ contributors

test(inspector): unit tests for F4 inspector core (7 specs)

diegosouzapw75b3e916bcca
diff --git a/tests/unit/inspector-buffer.test.ts b/tests/unit/inspector-buffer.test.ts
new file mode 100644
index 0000000000..455715a95c
--- /dev/null
+++ b/tests/unit/inspector-buffer.test.ts
@@ -0,0 +1,204 @@
+import test from "node:test";
+import assert from "node:assert/strict";
+import { TrafficBuffer } from "../../src/mitm/inspector/buffer.ts";
+import type {
+ InterceptedRequest,
+ WsEvent,
+} from "../../src/mitm/inspector/types.ts";
+
+function makeReq(overrides: Partial<InterceptedRequest> = {}): InterceptedRequest {
+ return {
+ id: overrides.id ?? `id-${Math.random().toString(36).slice(2, 10)}`,
+ source: "agent-bridge",
+ timestamp: new Date().toISOString(),
+ method: "POST",
+ host: "api.openai.com",
+ path: "/v1/chat/completions",
+ requestHeaders: {},
+ requestBody: JSON.stringify({
+ messages: [
+ { role: "system", content: "You are an assistant." },
+ { role: "user", content: "Hi" },
+ ],
+ }),
+ requestSize: 0,
+ responseHeaders: {},
+ responseBody: null,
+ responseSize: 0,
+ status: 200,
+ ...overrides,
+ };
+}
+
+test("push appends entries and auto-applies detectedKind=llm", () => {
+ const buf = new TrafficBuffer(10);
+ const r = makeReq({ id: "r1" });
+ buf.push(r);
+ const got = buf.get("r1");
+ assert.ok(got);
+ assert.equal(got.detectedKind, "llm");
+});
+
+test("push auto-computes contextKey from system prompt", () => {
+ const buf = new TrafficBuffer(10);
+ const r = makeReq({ id: "r1" });
+ buf.push(r);
+ const got = buf.get("r1");
+ assert.ok(got);
+ assert.ok(got.contextKey);
+ assert.match(got.contextKey!, /^[0-9a-f]{12}$/);
+});
+
+test("push does not override an existing contextKey", () => {
+ const buf = new TrafficBuffer(10);
+ const r = makeReq({ id: "r1", contextKey: "preexisting1" });
+ buf.push(r);
+ const got = buf.get("r1");
+ assert.equal(got!.contextKey, "preexisting1");
+});
+
+test("push truncates large requestBody with marker", () => {
+ // 1 KiB so cap is hit reliably; override env via fresh buffer w/ explicit byte cap
+ const big = "a".repeat(3000);
+ const buf = new TrafficBuffer(10, 1024); // 1 KiB max body
+ buf.push(makeReq({ id: "r1", requestBody: big }));
+ const got = buf.get("r1");
+ assert.ok(got);
+ assert.ok(got.requestBody!.length > 1024); // marker increases length slightly
+ assert.match(got.requestBody!, /truncated for performance/);
+});
+
+test("push rotates oldest when over maxSize", () => {
+ const buf = new TrafficBuffer(3, 1024);
+ buf.push(makeReq({ id: "a" }));
+ buf.push(makeReq({ id: "b" }));
+ buf.push(makeReq({ id: "c" }));
+ buf.push(makeReq({ id: "d" }));
+ assert.equal(buf.size(), 3);
+ assert.equal(buf.get("a"), null);
+ assert.ok(buf.get("d"));
+});
+
+test("update replaces existing entry by id and broadcasts update", () => {
+ const buf = new TrafficBuffer(5);
+ buf.push(makeReq({ id: "r1" }));
+ const events: WsEvent[] = [];
+ const off = buf.subscribe((e) => events.push(e));
+ // initial snapshot received
+ buf.update("r1", makeReq({ id: "r1", status: 500, responseBody: "err" }));
+ off();
+ const got = buf.get("r1");
+ assert.equal(got!.status, 500);
+ const updates = events.filter((e) => e.type === "update");
+ assert.equal(updates.length, 1);
+});
+
+test("update is a no-op when id is unknown", () => {
+ const buf = new TrafficBuffer(5);
+ buf.update("missing", makeReq({ id: "missing" }));
+ assert.equal(buf.size(), 0);
+});
+
+test("list applies filters by source, host, status, profile, agent, sessionId", () => {
+ const buf = new TrafficBuffer(20);
+ buf.push(makeReq({ id: "a", host: "api.openai.com", source: "agent-bridge", agent: "codex" }));
+ buf.push(
+ makeReq({
+ id: "b",
+ host: "random.example.com",
+ source: "http-proxy",
+ requestBody: JSON.stringify({ name: "not-llm" }),
+ detectedKind: "app",
+ })
+ );
+ buf.push(
+ makeReq({
+ id: "c",
+ host: "api.anthropic.com",
+ source: "custom-host",
+ status: 500,
+ sessionId: "00000000-0000-0000-0000-000000000000",
+ })
+ );
+
+ assert.equal(buf.list({ profile: "llm" }).length, 2);
+ assert.equal(buf.list({ source: "http-proxy" }).length, 1);
+ assert.equal(buf.list({ host: "api.openai.com" }).length, 1);
+ assert.equal(buf.list({ status: "5xx" }).length, 1);
+ assert.equal(buf.list({ agent: "codex" }).length, 1);
+ assert.equal(
+ buf.list({ sessionId: "00000000-0000-0000-0000-000000000000" }).length,
+ 1
+ );
+ assert.equal(buf.list({ profile: "custom" }).length, 1);
+ assert.equal(buf.list({ profile: "all" }).length, 3);
+});
+
+test("clear empties the buffer and broadcasts a clear event", () => {
+ const buf = new TrafficBuffer(5);
+ buf.push(makeReq({ id: "a" }));
+ buf.push(makeReq({ id: "b" }));
+ const events: WsEvent[] = [];
+ const off = buf.subscribe((e) => events.push(e));
+ buf.clear();
+ off();
+ assert.equal(buf.size(), 0);
+ assert.ok(events.some((e) => e.type === "clear"));
+});
+
+test("subscribe immediately delivers a snapshot of the current buffer", () => {
+ const buf = new TrafficBuffer(5);
+ buf.push(makeReq({ id: "a" }));
+ buf.push(makeReq({ id: "b" }));
+ const events: WsEvent[] = [];
+ const off = buf.subscribe((e) => events.push(e));
+ off();
+ assert.equal(events.length, 1);
+ assert.equal(events[0].type, "snapshot");
+ if (events[0].type === "snapshot") {
+ assert.equal(events[0].data.length, 2);
+ }
+});
+
+test("subscribe returns an unsubscribe function", () => {
+ const buf = new TrafficBuffer(5);
+ const fn = (_e: WsEvent): void => {};
+ const off = buf.subscribe(fn);
+ assert.equal(buf.subscriberCount(), 1);
+ off();
+ assert.equal(buf.subscriberCount(), 0);
+});
+
+test("broadcast survives a throwing subscriber", () => {
+ const buf = new TrafficBuffer(5);
+ buf.subscribe(() => {
+ throw new Error("subscriber crash");
+ });
+ let okCount = 0;
+ buf.subscribe(() => {
+ okCount += 1;
+ });
+ buf.push(makeReq({ id: "a" }));
+ // 1 snapshot from second subscribe + 1 new event from push
+ assert.ok(okCount >= 1);
+});
+
+test("broadcasts new event with the pushed request", () => {
+ const buf = new TrafficBuffer(5);
+ const events: WsEvent[] = [];
+ buf.subscribe((e) => events.push(e));
+ buf.push(makeReq({ id: "evt" }));
+ const news = events.filter((e) => e.type === "new");
+ assert.equal(news.length, 1);
+ if (news[0].type === "new") {
+ assert.equal(news[0].data.id, "evt");
+ }
+});
+
+test("body cap applies to responseBody as well", () => {
+ const buf = new TrafficBuffer(5, 100);
+ const r = makeReq({ id: "r", responseBody: "x".repeat(500) });
+ buf.push(r);
+ const got = buf.get("r");
+ assert.match(got!.responseBody!, /truncated for performance/);
+});
diff --git a/tests/unit/inspector-conversation-normalizer.test.ts b/tests/unit/inspector-conversation-normalizer.test.ts
new file mode 100644
index 0000000000..51ed564a52
--- /dev/null
+++ b/tests/unit/inspector-conversation-normalizer.test.ts
@@ -0,0 +1,189 @@
+import test from "node:test";
+import assert from "node:assert/strict";
+import { normalizeConversation } from "../../src/mitm/inspector/conversationNormalizer.ts";
+import type { InterceptedRequest } from "../../src/mitm/inspector/types.ts";
+
+function makeReq(overrides: Partial<InterceptedRequest> = {}): InterceptedRequest {
+ return {
+ id: "test-id",
+ source: "agent-bridge",
+ timestamp: new Date().toISOString(),
+ method: "POST",
+ host: "api.openai.com",
+ path: "/v1/chat/completions",
+ requestHeaders: {},
+ requestBody: null,
+ requestSize: 0,
+ responseHeaders: {},
+ responseBody: null,
+ responseSize: 0,
+ status: 200,
+ detectedKind: "llm",
+ ...overrides,
+ };
+}
+
+test("returns null for non-llm requests", () => {
+ const req = makeReq({ detectedKind: "app" });
+ assert.equal(normalizeConversation(req), null);
+});
+
+test("returns null when request body cannot yield turns", () => {
+ const req = makeReq({ requestBody: JSON.stringify({ foo: "bar" }) });
+ assert.equal(normalizeConversation(req), null);
+});
+
+test("normalizes OpenAI request with system + user messages", () => {
+ const req = makeReq({
+ requestBody: JSON.stringify({
+ messages: [
+ { role: "system", content: "You are helpful." },
+ { role: "user", content: "Hello!" },
+ ],
+ }),
+ });
+ const conv = normalizeConversation(req);
+ assert.ok(conv);
+ assert.equal(conv.request.length, 2);
+ assert.equal(conv.request[0].role, "system");
+ assert.equal(conv.request[0].blocks[0].type, "text");
+ assert.equal(conv.request[1].role, "user");
+});
+
+test("normalizes OpenAI assistant tool_calls into tool_use blocks", () => {
+ const req = makeReq({
+ requestBody: JSON.stringify({
+ messages: [
+ {
+ role: "assistant",
+ content: null,
+ tool_calls: [
+ {
+ id: "call-1",
+ function: { name: "get_weather", arguments: '{"city":"SP"}' },
+ },
+ ],
+ },
+ ],
+ }),
+ });
+ const conv = normalizeConversation(req);
+ assert.ok(conv);
+ const blocks = conv.request[0].blocks;
+ assert.equal(blocks.length, 1);
+ assert.equal(blocks[0].type, "tool_use");
+ const tu = blocks[0] as { type: "tool_use"; id: string; name: string; input: unknown };
+ assert.equal(tu.id, "call-1");
+ assert.equal(tu.name, "get_weather");
+ assert.deepEqual(tu.input, { city: "SP" });
+});
+
+test("normalizes OpenAI tool role into tool_result", () => {
+ const req = makeReq({
+ requestBody: JSON.stringify({
+ messages: [
+ { role: "tool", tool_call_id: "call-1", content: "sunny" },
+ ],
+ }),
+ });
+ const conv = normalizeConversation(req);
+ assert.ok(conv);
+ assert.equal(conv.request[0].role, "tool");
+ const blk = conv.request[0].blocks[0] as { type: "tool_result"; tool_use_id: string };
+ assert.equal(blk.type, "tool_result");
+ assert.equal(blk.tool_use_id, "call-1");
+});
+
+test("normalizes Anthropic request with top-level system + tool_use response", () => {
+ const req = makeReq({
+ host: "api.anthropic.com",
+ path: "/v1/messages",
+ requestBody: JSON.stringify({
+ system: "Be terse.",
+ messages: [{ role: "user", content: "hi" }],
+ }),
+ responseBody: JSON.stringify({
+ content: [
+ { type: "text", text: "Hello." },
+ { type: "tool_use", id: "tu1", name: "lookup", input: { q: "x" } },
+ ],
+ }),
+ });
+ const conv = normalizeConversation(req);
+ assert.ok(conv);
+ assert.equal(conv.request[0].role, "system");
+ assert.equal(conv.response.length, 1);
+ assert.equal(conv.response[0].role, "assistant");
+ assert.equal(conv.response[0].blocks.length, 2);
+ assert.equal(conv.response[0].blocks[0].type, "text");
+ assert.equal(conv.response[0].blocks[1].type, "tool_use");
+});
+
+test("normalizes Gemini request contents + functionCall response", () => {
+ const req = makeReq({
+ host: "generativelanguage.googleapis.com",
+ path: "/v1beta/models/gemini-pro:generateContent",
+ requestBody: JSON.stringify({
+ systemInstruction: { parts: [{ text: "sys" }] },
+ contents: [
+ { role: "user", parts: [{ text: "hi" }] },
+ {
+ role: "model",
+ parts: [{ functionCall: { name: "fn", args: { a: 1 } } }],
+ },
+ ],
+ }),
+ responseBody: JSON.stringify({
+ candidates: [
+ {
+ content: {
+ parts: [{ text: "Hello from gemini" }],
+ },
+ },
+ ],
+ }),
+ });
+ const conv = normalizeConversation(req);
+ assert.ok(conv);
+ assert.equal(conv.request[0].role, "system");
+ // user + assistant (model -> assistant)
+ assert.equal(conv.request[1].role, "user");
+ assert.equal(conv.request[2].role, "assistant");
+ const tu = conv.request[2].blocks[0] as { type: string; name: string };
+ assert.equal(tu.type, "tool_use");
+ assert.equal(tu.name, "fn");
+ assert.equal(conv.response[0].role, "assistant");
+ assert.equal((conv.response[0].blocks[0] as { text: string }).text, "Hello from gemini");
+});
+
+test("propagates contextKey from request", () => {
+ const req = makeReq({
+ contextKey: "abc123def456",
+ requestBody: JSON.stringify({
+ messages: [{ role: "user", content: "hi" }],
+ }),
+ });
+ const conv = normalizeConversation(req);
+ assert.ok(conv);
+ assert.equal(conv.contextKey, "abc123def456");
+});
+
+test("parses SSE response to extract OpenAI delta", () => {
+ const sse = [
+ `data: {"choices":[{"delta":{"role":"assistant","content":"Hello"}}]}`,
+ "",
+ `data: {"choices":[{"delta":{"content":" world"}}]}`,
+ "",
+ "data: [DONE]",
+ "",
+ ].join("\n");
+ const req = makeReq({
+ requestBody: JSON.stringify({ messages: [{ role: "user", content: "hi" }] }),
+ responseHeaders: { "content-type": "text/event-stream" },
+ responseBody: sse,
+ });
+ const conv = normalizeConversation(req);
+ assert.ok(conv);
+ assert.ok(conv.response.length >= 1);
+ assert.equal(conv.response[0].role, "assistant");
+});
diff --git a/tests/unit/inspector-har-export.test.ts b/tests/unit/inspector-har-export.test.ts
new file mode 100644
index 0000000000..50c6c5ec82
--- /dev/null
+++ b/tests/unit/inspector-har-export.test.ts
@@ -0,0 +1,128 @@
+import test from "node:test";
+import assert from "node:assert/strict";
+import { toHar } from "../../src/lib/inspector/harExport.ts";
+import type { InterceptedRequest } from "../../src/mitm/inspector/types.ts";
+
+function makeReq(overrides: Partial<InterceptedRequest> = {}): InterceptedRequest {
+ return {
+ id: "00000000-0000-4000-8000-000000000001",
+ source: "agent-bridge",
+ timestamp: "2026-05-27T12:00:00.000Z",
+ method: "POST",
+ host: "api.openai.com",
+ path: "/v1/chat/completions",
+ requestHeaders: { "content-type": "application/json" },
+ requestBody: '{"model":"gpt-4"}',
+ requestSize: 17,
+ responseHeaders: { "content-type": "application/json" },
+ responseBody: '{"ok":true}',
+ responseSize: 11,
+ status: 200,
+ totalLatencyMs: 200,
+ upstreamLatencyMs: 150,
+ ...overrides,
+ };
+}
+
+test("produces HAR v1.2 with creator + entries", () => {
+ const har = toHar([makeReq()]);
+ assert.equal(har.log.version, "1.2");
+ assert.ok(har.log.creator.name.includes("OmniRoute"));
+ assert.equal(har.log.entries.length, 1);
+});
+
+test("entry fields match the spec", () => {
+ const har = toHar([makeReq()]);
+ const e = har.log.entries[0];
+ assert.equal(e.startedDateTime, "2026-05-27T12:00:00.000Z");
+ assert.equal(e.time, 200);
+ assert.equal(e.request.method, "POST");
+ assert.equal(e.request.url, "https://api.openai.com/v1/chat/completions");
+ assert.equal(e.request.httpVersion, "HTTP/1.1");
+ assert.equal(e.request.bodySize, 17);
+ assert.ok(e.request.postData);
+ assert.equal(e.request.postData?.mimeType, "application/json");
+ assert.equal(e.response.status, 200);
+ assert.equal(e.response.content.size, 11);
+ assert.equal(e.response.content.text, '{"ok":true}');
+ assert.equal(e.timings.send, 0);
+ assert.equal(e.timings.wait, 150);
+ assert.equal(e.timings.receive, 50);
+});
+
+test("Bearer tokens in headers are masked", () => {
+ const req = makeReq({
+ requestHeaders: {
+ "content-type": "application/json",
+ authorization: "Bearer sk-supersecretvalueabc1234567890XYZ",
+ },
+ });
+ const har = toHar([req]);
+ const authHeader = har.log.entries[0].request.headers.find(
+ (h) => h.name === "authorization"
+ );
+ assert.ok(authHeader);
+ // Either Bearer regex (authorization:\sBearer prefix) or sk-/long-token regex must mask the value
+ assert.ok(!authHeader.value.includes("supersecretvalueabc1234567890XYZ"));
+ assert.ok(authHeader.value.includes("…") || authHeader.value.includes("***"));
+});
+
+test("sk- keys in bodies are masked", () => {
+ const req = makeReq({
+ requestBody: '{"key":"sk-abcdef1234567890ABCDEF"}',
+ });
+ const har = toHar([req]);
+ const body = har.log.entries[0].request.postData?.text ?? "";
+ assert.ok(!body.includes("sk-abcdef1234567890ABCDEF"));
+ assert.match(body, /sk-abc/);
+});
+
+test("preserves _source custom property", () => {
+ const har = toHar([
+ makeReq({ source: "http-proxy" }),
+ makeReq({ id: "00000000-0000-4000-8000-000000000002", source: "system-proxy" }),
+ ]);
+ assert.equal(har.log.entries[0]._source, "http-proxy");
+ assert.equal(har.log.entries[1]._source, "system-proxy");
+});
+
+test("preserves _detectedKind / _contextKey / _agent / _sessionId / _note", () => {
+ const har = toHar([
+ makeReq({
+ agent: "claude",
+ detectedKind: "llm",
+ contextKey: "abc123",
+ sessionId: "00000000-0000-4000-8000-000000000099",
+ note: "TLS tunnel",
+ }),
+ ]);
+ const e = har.log.entries[0];
+ assert.equal(e._agent, "claude");
+ assert.equal(e._detectedKind, "llm");
+ assert.equal(e._contextKey, "abc123");
+ assert.equal(e._sessionId, "00000000-0000-4000-8000-000000000099");
+ assert.equal(e._note, "TLS tunnel");
+ assert.equal(e._omniRouteId, "00000000-0000-4000-8000-000000000001");
+});
+
+test("handles in-flight / error status without throwing", () => {
+ const har = toHar([
+ makeReq({ status: "in-flight", responseBody: null }),
+ makeReq({ id: "x", status: "error", responseBody: null, error: "boom" }),
+ ]);
+ assert.equal(har.log.entries[0].response.status, 0);
+ assert.equal(har.log.entries[0].response.statusText, "in-flight");
+ assert.equal(har.log.entries[1].response.statusText, "error");
+});
+
+test("CONNECT-style path renders pseudo-URL", () => {
+ const har = toHar([
+ makeReq({
+ method: "CONNECT",
+ host: "api.example.com",
+ path: ":443",
+ responseBody: null,
+ }),
+ ]);
+ assert.equal(har.log.entries[0].request.url, "https://api.example.com:443");
+});
diff --git a/tests/unit/inspector-http-proxy.test.ts b/tests/unit/inspector-http-proxy.test.ts
new file mode 100644
index 0000000000..bc39b3697b
--- /dev/null
+++ b/tests/unit/inspector-http-proxy.test.ts
@@ -0,0 +1,142 @@
+import test from "node:test";
+import assert from "node:assert/strict";
+import http from "node:http";
+import net from "node:net";
+import { startHttpProxyServer } from "../../src/mitm/inspector/httpProxyServer.ts";
+import { globalTrafficBuffer } from "../../src/mitm/inspector/buffer.ts";
+
+async function withUpstream(
+ handler: (req: http.IncomingMessage, res: http.ServerResponse) => void
+): Promise<{ port: number; close: () => Promise<void> }> {
+ const server = http.createServer(handler);
+ await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", () => resolve()));
+ const addr = server.address();
+ const port = typeof addr === "object" && addr ? addr.port : 0;
+ return {
+ port,
+ close: () => new Promise<void>((res) => server.close(() => res())),
+ };
+}
+
+async function withTcpServer(): Promise<{ port: number; close: () => Promise<void> }> {
+ const server = net.createServer((socket) => {
+ socket.on("data", () => {
+ socket.end("ok");
+ });
+ });
+ await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", () => resolve()));
+ const addr = server.address();
+ const port = typeof addr === "object" && addr ? addr.port : 0;
+ return {
+ port,
+ close: () => new Promise<void>((res) => server.close(() => res())),
+ };
+}
+
+function sendThroughProxy(
+ proxyPort: number,
+ upstreamPort: number,
+ method = "GET"
+): Promise<{ status: number; body: string }> {
+ return new Promise((resolve, reject) => {
+ const req = http.request(
+ {
+ host: "127.0.0.1",
+ port: proxyPort,
+ method,
+ path: `http://127.0.0.1:${upstreamPort}/test`,
+ headers: { host: `127.0.0.1:${upstreamPort}` },
+ },
+ (res) => {
+ const chunks: Buffer[] = [];
+ res.on("data", (c) => chunks.push(c));
+ res.on("end", () =>
+ resolve({ status: res.statusCode ?? 0, body: Buffer.concat(chunks).toString("utf8") })
+ );
+ }
+ );
+ req.once("error", reject);
+ req.end();
+ });
+}
+
+function sendConnect(proxyPort: number, target: string): Promise<number> {
+ return new Promise((resolve, reject) => {
+ const socket = net.connect(proxyPort, "127.0.0.1");
+ socket.once("error", reject);
+ socket.once("connect", () => {
+ socket.write(`CONNECT ${target} HTTP/1.1\r\nHost: ${target}\r\n\r\n`);
+ });
+ socket.once("data", (chunk) => {
+ const line = chunk.toString("utf8").split("\r\n")[0];
+ const m = line.match(/HTTP\/1\.1\s+(\d+)/);
+ socket.end();
+ resolve(m ? Number(m[1]) : 0);
+ });
+ });
+}
+
+test("HTTP direct passes through and records buffer entry", async () => {
+ globalTrafficBuffer.clear();
+ const upstream = await withUpstream((_req, res) => {
+ res.writeHead(200, { "content-type": "text/plain" });
+ res.end("hello");
+ });
+ const proxy = await startHttpProxyServer(0);
+ try {
+ const sizeBefore = globalTrafficBuffer.size();
+ const { status, body } = await sendThroughProxy(proxy.port, upstream.port);
+ assert.equal(status, 200);
+ assert.equal(body, "hello");
+ // give buffer.update a tick (it runs inside async path)
+ await new Promise((r) => setTimeout(r, 30));
+ assert.ok(globalTrafficBuffer.size() > sizeBefore);
+ const entry = globalTrafficBuffer.list().at(-1);
+ assert.ok(entry);
+ assert.equal(entry.source, "http-proxy");
+ assert.equal(entry.method, "GET");
+ assert.equal(entry.status, 200);
+ assert.match(entry.responseBody ?? "", /hello/);
+ } finally {
+ await proxy.stop();
+ await upstream.close();
+ }
+});
+
+test("CONNECT tunnel returns 200 and records metadata-only entry", async () => {
+ globalTrafficBuffer.clear();
+ const tcp = await withTcpServer();
+ const proxy = await startHttpProxyServer(0);
+ try {
+ const sizeBefore = globalTrafficBuffer.size();
+ const status = await sendConnect(proxy.port, `127.0.0.1:${tcp.port}`);
+ assert.equal(status, 200);
+ await new Promise((r) => setTimeout(r, 30));
+ assert.ok(globalTrafficBuffer.size() > sizeBefore);
+ const entry = globalTrafficBuffer.list().at(-1);
+ assert.ok(entry);
+ assert.equal(entry.method, "CONNECT");
+ assert.equal(entry.source, "http-proxy");
+ assert.equal(entry.responseBody, null);
+ assert.match(entry.note ?? "", /TLS tunnel/);
+ } finally {
+ await proxy.stop();
+ await tcp.close();
+ }
+});
+
+test("EADDRINUSE rejects with code", async () => {
+ const first = await startHttpProxyServer(0);
+ try {
+ await assert.rejects(
+ () => startHttpProxyServer(first.port),
+ (err: NodeJS.ErrnoException) => {
+ assert.ok(err);
+ assert.equal(err.code, "EADDRINUSE");
+ return true;
+ }
+ );
+ } finally {
+ await first.stop();
+ }
+});
diff --git a/tests/unit/inspector-llm-metadata.test.ts b/tests/unit/inspector-llm-metadata.test.ts
new file mode 100644
index 0000000000..babb1f14c5
--- /dev/null
+++ b/tests/unit/inspector-llm-metadata.test.ts
@@ -0,0 +1,153 @@
+import test from "node:test";
+import assert from "node:assert/strict";
+import { extractLlmMetadata } from "../../src/mitm/inspector/llmMetadataExtractor.ts";
+import type { InterceptedRequest } from "../../src/mitm/inspector/types.ts";
+
+function makeReq(overrides: Partial<InterceptedRequest> = {}): InterceptedRequest {
+ return {
+ id: "test",
+ source: "agent-bridge",
+ timestamp: new Date().toISOString(),
+ method: "POST",
+ host: "api.openai.com",
+ path: "/v1/chat/completions",
+ requestHeaders: {},
+ requestBody: null,
+ requestSize: 0,
+ responseHeaders: {},
+ responseBody: null,
+ responseSize: 0,
+ status: 200,
+ detectedKind: "llm",
+ ...overrides,
+ };
+}
+
+test("returns null for non-llm requests", () => {
+ const req = makeReq({ detectedKind: "app" });
+ assert.equal(extractLlmMetadata(req), null);
+});
+
+test("infers provider=openai from host", () => {
+ const req = makeReq({
+ requestBody: JSON.stringify({ model: "gpt-4", messages: [] }),
+ });
+ const meta = extractLlmMetadata(req);
+ assert.ok(meta);
+ assert.equal(meta.provider, "openai");
+ assert.equal(meta.apiKind, "chat.completions");
+ assert.equal(meta.model, "gpt-4");
+});
+
+test("infers provider=anthropic + apiKind=messages", () => {
+ const req = makeReq({
+ host: "api.anthropic.com",
+ path: "/v1/messages",
+ requestBody: JSON.stringify({ model: "claude-3", messages: [{}, {}] }),
+ });
+ const meta = extractLlmMetadata(req);
+ assert.ok(meta);
+ assert.equal(meta.provider, "anthropic");
+ assert.equal(meta.apiKind, "messages");
+ assert.equal(meta.messages, 2);
+});
+
+test("infers provider=gemini", () => {
+ const req = makeReq({
+ host: "generativelanguage.googleapis.com",
+ path: "/v1beta/models/gemini-pro:generateContent",
+ requestBody: JSON.stringify({ contents: [{}, {}, {}] }),
+ });
+ const meta = extractLlmMetadata(req);
+ assert.ok(meta);
+ assert.equal(meta.provider, "gemini");
+ assert.equal(meta.messages, 3);
+});
+
+test("extracts model from response body when missing in request", () => {
+ const req = makeReq({
+ requestBody: JSON.stringify({ messages: [] }),
+ responseBody: JSON.stringify({ model: "gpt-4-turbo", choices: [] }),
+ });
+ const meta = extractLlmMetadata(req);
+ assert.ok(meta);
+ assert.equal(meta.model, "gpt-4-turbo");
+});
+
+test("extracts tokensIn/tokensOut from prompt_tokens/completion_tokens", () => {
+ const req = makeReq({
+ requestBody: JSON.stringify({ model: "gpt-4", messages: [] }),
+ responseBody: JSON.stringify({
+ usage: { prompt_tokens: 10, completion_tokens: 25 },
+ }),
+ });
+ const meta = extractLlmMetadata(req);
+ assert.ok(meta);
+ assert.equal(meta.tokensIn, 10);
+ assert.equal(meta.tokensOut, 25);
+});
+
+test("extracts tokensIn/tokensOut from input_tokens/output_tokens (Anthropic)", () => {
+ const req = makeReq({
+ host: "api.anthropic.com",
+ path: "/v1/messages",
+ requestBody: JSON.stringify({ model: "claude-3", messages: [] }),
+ responseBody: JSON.stringify({
+ usage: { input_tokens: 50, output_tokens: 100 },
+ }),
+ });
+ const meta = extractLlmMetadata(req);
+ assert.ok(meta);
+ assert.equal(meta.tokensIn, 50);
+ assert.equal(meta.tokensOut, 100);
+});
+
+test("extracts tokens from Gemini usageMetadata", () => {
+ const req = makeReq({
+ host: "generativelanguage.googleapis.com",
+ path: "/v1beta/models/gemini-pro:generateContent",
+ requestBody: JSON.stringify({ contents: [] }),
+ responseBody: JSON.stringify({
+ usageMetadata: { promptTokenCount: 7, candidatesTokenCount: 14 },
+ }),
+ });
+ const meta = extractLlmMetadata(req);
+ assert.ok(meta);
+ assert.equal(meta.tokensIn, 7);
+ assert.equal(meta.tokensOut, 14);
+});
+
+test("flags streamed=true on SSE content-type", () => {
+ const req = makeReq({
+ requestBody: JSON.stringify({ model: "gpt-4", messages: [] }),
+ responseHeaders: { "content-type": "text/event-stream" },
+ responseBody: "data: {}\n",
+ });
+ const meta = extractLlmMetadata(req);
+ assert.ok(meta);
+ assert.equal(meta.streamed, true);
+});
+
+test("returns null fields when no info available", () => {
+ const req = makeReq({
+ host: "unknown.example.com",
+ path: "/v1/messages",
+ requestBody: JSON.stringify({ messages: [] }),
+ });
+ const meta = extractLlmMetadata(req);
+ assert.ok(meta);
+ assert.equal(meta.provider, null);
+ assert.equal(meta.tokensIn, null);
+ assert.equal(meta.tokensOut, null);
+ assert.equal(meta.costEstimateUsd, null);
+});
+
+test("captures mappedTo from request override", () => {
+ const req = makeReq({
+ mappedModel: "gpt-4o",
+ requestBody: JSON.stringify({ model: "gpt-3.5", messages: [] }),
+ });
+ const meta = extractLlmMetadata(req);
+ assert.ok(meta);
+ assert.equal(meta.mappedTo, "gpt-4o");
+});
diff --git a/tests/unit/inspector-sse-merger.test.ts b/tests/unit/inspector-sse-merger.test.ts
new file mode 100644
index 0000000000..10f8b996fb
--- /dev/null
+++ b/tests/unit/inspector-sse-merger.test.ts
@@ -0,0 +1,210 @@
+import test from "node:test";
+import assert from "node:assert/strict";
+import {
+ detectApiFormat,
+ mergeStream,
+ parseSseStream,
+ rebuildAnthropic,
+ rebuildGemini,
+ rebuildOpenAI,
+ type SseEvent,
+} from "../../src/mitm/inspector/sseMerger.ts";
+
+function jsonChunks(payloads: unknown[]): SseEvent[] {
+ return payloads.map((p) => ({ data: JSON.stringify(p), json: p }));
+}
+
+test("detectApiFormat — message_start → anthropic", () => {
+ const chunks = jsonChunks([
+ { type: "message_start", message: { id: "msg_1" } },
+ ]);
+ assert.equal(detectApiFormat(chunks), "anthropic");
+});
+
+test("detectApiFormat — content_block_delta → anthropic", () => {
+ const chunks = jsonChunks([
+ { type: "content_block_delta", index: 0, delta: { type: "text_delta", text: "Hi" } },
+ ]);
+ assert.equal(detectApiFormat(chunks), "anthropic");
+});
+
+test("detectApiFormat — choices[].delta → openai", () => {
+ const chunks = jsonChunks([
+ { choices: [{ index: 0, delta: { content: "Hi" } }] },
+ ]);
+ assert.equal(detectApiFormat(chunks), "openai");
+});
+
+test("detectApiFormat — candidates → gemini", () => {
+ const chunks = jsonChunks([
+ { candidates: [{ content: { parts: [{ text: "Hello" }] } }] },
+ ]);
+ assert.equal(detectApiFormat(chunks), "gemini");
+});
+
+test("detectApiFormat — no JSON chunks → unknown", () => {
+ assert.equal(detectApiFormat([{ data: "weird non-json" }]), "unknown");
+});
+
+test("rebuildAnthropic — concat text_delta by index", () => {
+ const chunks = jsonChunks([
+ { type: "message_start", message: { id: "msg_1" } },
+ { type: "content_block_start", index: 0, content_block: { type: "text" } },
+ { type: "content_block_delta", index: 0, delta: { type: "text_delta", text: "Hello" } },
+ { type: "content_block_delta", index: 0, delta: { type: "text_delta", text: " world" } },
+ { type: "content_block_stop", index: 0 },
+ { type: "message_delta", delta: { stop_reason: "end_turn" }, usage: { output_tokens: 7 } },
+ ]);
+ const merged = rebuildAnthropic(chunks);
+ assert.equal(merged.format, "anthropic");
+ const msg = merged.message as { content: Array<{ text: string }>; stop_reason: string; usage: { output_tokens: number } };
+ assert.equal(msg.content[0].text, "Hello world");
+ assert.equal(msg.stop_reason, "end_turn");
+ assert.equal(msg.usage.output_tokens, 7);
+});
+
+test("rebuildAnthropic — input_json_delta merges and JSON.parses", () => {
+ const chunks = jsonChunks([
+ { type: "message_start", message: {} },
+ {
+ type: "content_block_start",
+ index: 0,
+ content_block: { type: "tool_use", id: "tu_1", name: "search" },
+ },
+ { type: "content_block_delta", index: 0, delta: { type: "input_json_delta", partial_json: '{"q":' } },
+ { type: "content_block_delta", index: 0, delta: { type: "input_json_delta", partial_json: '"hi"}' } },
+ { type: "content_block_stop", index: 0 },
+ ]);
+ const merged = rebuildAnthropic(chunks);
+ const msg = merged.message as { content: Array<{ type: string; input: { q: string }; name: string }> };
+ assert.equal(msg.content[0].type, "tool_use");
+ assert.equal(msg.content[0].name, "search");
+ assert.deepEqual(msg.content[0].input, { q: "hi" });
+});
+
+test("rebuildAnthropic — thinking_delta accumulates", () => {
+ const chunks = jsonChunks([
+ { type: "content_block_start", index: 0, content_block: { type: "thinking" } },
+ { type: "content_block_delta", index: 0, delta: { type: "thinking_delta", thinking: "I am " } },
+ { type: "content_block_delta", index: 0, delta: { type: "thinking_delta", thinking: "thinking..." } },
+ ]);
+ const merged = rebuildAnthropic(chunks);
+ const msg = merged.message as { content: Array<{ thinking: string }> };
+ assert.equal(msg.content[0].thinking, "I am thinking...");
+});
+
+test("rebuildOpenAI — concat delta.content per choice index", () => {
+ const chunks = jsonChunks([
+ { id: "c1", model: "gpt-4", choices: [{ index: 0, delta: { role: "assistant", content: "Hel" } }] },
+ { choices: [{ index: 0, delta: { content: "lo" }, finish_reason: null }] },
+ { choices: [{ index: 0, delta: {}, finish_reason: "stop" }] },
+ { usage: { prompt_tokens: 3, completion_tokens: 1 } },
+ ]);
+ const merged = rebuildOpenAI(chunks);
+ assert.equal(merged.format, "openai");
+ const msg = merged.message as {
+ id: string;
+ model: string;
+ choices: Array<{ message: { content: string; role: string }; finish_reason: string }>;
+ usage: { prompt_tokens: number };
+ };
+ assert.equal(msg.id, "c1");
+ assert.equal(msg.model, "gpt-4");
+ assert.equal(msg.choices[0].message.content, "Hello");
+ assert.equal(msg.choices[0].message.role, "assistant");
+ assert.equal(msg.choices[0].finish_reason, "stop");
+ assert.equal(msg.usage.prompt_tokens, 3);
+});
+
+test("rebuildOpenAI — merges tool_calls per (choice, tool) index", () => {
+ const chunks = jsonChunks([
+ {
+ choices: [
+ {
+ index: 0,
+ delta: {
+ tool_calls: [{ index: 0, id: "tc_1", type: "function", function: { name: "search", arguments: '{"q":' } }],
+ },
+ },
+ ],
+ },
+ {
+ choices: [
+ {
+ index: 0,
+ delta: {
+ tool_calls: [{ index: 0, function: { arguments: '"hi"}' } }],
+ },
+ },
+ ],
+ },
+ ]);
+ const merged = rebuildOpenAI(chunks);
+ const msg = merged.message as {
+ choices: Array<{
+ message: {
+ tool_calls: Array<{ id: string; function: { name: string; arguments: string } }>;
+ };
+ }>;
+ };
+ assert.equal(msg.choices[0].message.tool_calls[0].id, "tc_1");
+ assert.equal(msg.choices[0].message.tool_calls[0].function.name, "search");
+ assert.equal(msg.choices[0].message.tool_calls[0].function.arguments, '{"q":"hi"}');
+});
+
+test("rebuildGemini — merges parts across candidates", () => {
+ const chunks = jsonChunks([
+ { candidates: [{ content: { parts: [{ text: "Hello " }] } }] },
+ { candidates: [{ content: { parts: [{ text: "world" }] } }] },
+ { usageMetadata: { promptTokenCount: 2, candidatesTokenCount: 2 } },
+ ]);
+ const merged = rebuildGemini(chunks);
+ assert.equal(merged.format, "gemini");
+ const msg = merged.message as {
+ candidates: Array<{ content: { parts: Array<{ text: string }> } }>;
+ usageMetadata: { promptTokenCount: number };
+ };
+ assert.equal(msg.candidates[0].content.parts.length, 2);
+ assert.equal(msg.candidates[0].content.parts[0].text, "Hello ");
+ assert.equal(msg.candidates[0].content.parts[1].text, "world");
+ assert.equal(msg.usageMetadata.promptTokenCount, 2);
+});
+
+test("mergeStream — unknown format returns raw fallback (no crash)", () => {
+ const chunks: SseEvent[] = [
+ { data: "garbage" },
+ { data: "{}", json: { foo: 1 } },
+ ];
+ const merged = mergeStream(chunks);
+ assert.equal(merged.format, "unknown");
+ assert.ok(Array.isArray(merged.raw));
+ assert.equal(merged.raw!.length, 2);
+});
+
+test("parseSseStream — parses event/data blocks separated by blank lines", () => {
+ const raw =
+ "event: foo\ndata: 1\n\n" +
+ 'data: {"x":1}\n\n' +
+ "data: [DONE]\n\n";
+ const events = parseSseStream(raw);
+ assert.equal(events.length, 3);
+ assert.equal(events[0].event, "foo");
+ assert.deepEqual(events[1].json, { x: 1 });
+ assert.equal(events[2].data, "[DONE]");
+});
+
+test("parseSseStream — keeps raw data when JSON parse fails", () => {
+ const events = parseSseStream("data: {not-json\n\n");
+ assert.equal(events.length, 1);
+ assert.equal(events[0].data, "{not-json");
+ assert.equal(events[0].json, undefined);
+});
+
+test("mergeStream — dispatches by detected format", () => {
+ const anth = mergeStream(jsonChunks([{ type: "message_start", message: {} }]));
+ assert.equal(anth.format, "anthropic");
+ const oai = mergeStream(jsonChunks([{ choices: [{ delta: { content: "x" } }] }]));
+ assert.equal(oai.format, "openai");
+ const gem = mergeStream(jsonChunks([{ candidates: [{ content: { parts: [{ text: "x" }] } }] }]));
+ assert.equal(gem.format, "gemini");
+});
diff --git a/tests/unit/inspector-system-proxy.test.ts b/tests/unit/inspector-system-proxy.test.ts
new file mode 100644
index 0000000000..cc033f38d2
--- /dev/null
+++ b/tests/unit/inspector-system-proxy.test.ts
@@ -0,0 +1,224 @@
+import test from "node:test";
+import assert from "node:assert/strict";
+import os from "node:os";
+import {
+ __setExec,
+ apply,
+ revert,
+ type ExecFileFn,
+} from "../../src/mitm/inspector/systemProxyConfig.ts";
+
+interface Call {
+ file: string;
+ args: string[];
+}
+
+function makeRecorder(stdoutByCmd: Record<string, string> = {}): {
+ calls: Call[];
+ exec: ExecFileFn;
+} {
+ const calls: Call[] = [];
+ const exec: ExecFileFn = async (file, args) => {
+ calls.push({ file, args });
+ const key = `${file} ${args.join(" ")}`;
+ for (const [pattern, out] of Object.entries(stdoutByCmd)) {
+ if (key.includes(pattern)) return { stdout: out, stderr: "" };
+ }
+ return { stdout: "", stderr: "" };
+ };
+ return { calls, exec };
+}
+
+test("macOS apply uses execFile array-form and captures previous state", async (t) => {
+ const orig = os.platform;
+ (os as { platform: () => NodeJS.Platform }).platform = () => "darwin" as NodeJS.Platform;
+ t.after(() => {
+ (os as { platform: () => NodeJS.Platform }).platform = orig;
+ });
+
+ const { calls, exec } = makeRecorder({
+ "-getwebproxy Wi-Fi": "Enabled: Yes\nServer: 10.0.0.1\nPort: 8888\n",
+ "-getsecurewebproxy Wi-Fi": "Enabled: No\nServer:\nPort: 0\n",
+ });
+ const restore = __setExec(exec);
+ t.after(restore);
+
+ const result = await apply(8080);
+ assert.equal(result.platform, "macos");
+ // All calls must use array args, never a single shell string
+ for (const c of calls) {
+ assert.ok(Array.isArray(c.args));
+ // file is bare command name, no spaces / pipes / redirects
+ assert.ok(!c.file.includes(" "));
+ assert.ok(!c.file.includes(";"));
+ assert.ok(!c.file.includes("|"));
+ }
+ const setCall = calls.find((c) => c.args.includes("-setwebproxy"));
+ assert.ok(setCall);
+ assert.deepEqual(setCall.args, ["-setwebproxy", "Wi-Fi", "127.0.0.1", "8080"]);
+ const prev = result.previousState as { platform: string; http: { enabled: boolean } };
+ assert.equal(prev.platform, "macos");
+ assert.equal(prev.http.enabled, true);
+});
+
+test("macOS revert restores prior server when http was enabled", async (t) => {
+ const orig = os.platform;
+ (os as { platform: () => NodeJS.Platform }).platform = () => "darwin" as NodeJS.Platform;
+ t.after(() => {
+ (os as { platform: () => NodeJS.Platform }).platform = orig;
+ });
+
+ const { calls, exec } = makeRecorder();
+ const restore = __setExec(exec);
+ t.after(restore);
+
+ await revert({
+ platform: "macos",
+ service: "Wi-Fi",
+ http: { enabled: true, host: "10.0.0.1", port: "8888" },
+ https: { enabled: false, host: "", port: "" },
+ });
+ const restoreCall = calls.find((c) => c.args.includes("-setwebproxy"));
+ assert.ok(restoreCall);
+ assert.deepEqual(restoreCall.args, ["-setwebproxy", "Wi-Fi", "10.0.0.1", "8888"]);
+ // https disabled previously → revert should turn it off
+ const offCall = calls.find((c) => c.args.includes("-setsecurewebproxystate"));
+ assert.ok(offCall);
+ assert.deepEqual(offCall.args, ["-setsecurewebproxystate", "Wi-Fi", "off"]);
+});
+
+test("Linux apply uses gsettings with array args", async (t) => {
+ const orig = os.platform;
+ (os as { platform: () => NodeJS.Platform }).platform = () => "linux" as NodeJS.Platform;
+ t.after(() => {
+ (os as { platform: () => NodeJS.Platform }).platform = orig;
+ });
+
+ const { calls, exec } = makeRecorder({
+ "get org.gnome.system.proxy mode": "'none'\n",
+ "get org.gnome.system.proxy.http host": "''\n",
+ });
+ const restore = __setExec(exec);
+ t.after(restore);
+
+ const result = await apply(9090);
+ assert.equal(result.platform, "linux");
+ const setMode = calls.find(
+ (c) => c.args[0] === "set" && c.args[1] === "org.gnome.system.proxy" && c.args[2] === "mode"
+ );
+ assert.ok(setMode);
+ assert.deepEqual(setMode.args, ["set", "org.gnome.system.proxy", "mode", "manual"]);
+ const setHost = calls.find(
+ (c) =>
+ c.args[0] === "set" &&
+ c.args[1] === "org.gnome.system.proxy.http" &&
+ c.args[2] === "host"
+ );
+ assert.ok(setHost);
+ assert.deepEqual(setHost.args, ["set", "org.gnome.system.proxy.http", "host", "127.0.0.1"]);
+ // port string is passed as own arg (no shell interpolation)
+ const setPort = calls.find(
+ (c) =>
+ c.args[0] === "set" &&
+ c.args[1] === "org.gnome.system.proxy.http" &&
+ c.args[2] === "port"
+ );
+ assert.ok(setPort);
+ assert.equal(setPort.args[3], "9090");
+});
+
+test("Linux revert restores recorded gnomeMode", async (t) => {
+ const orig = os.platform;
+ (os as { platform: () => NodeJS.Platform }).platform = () => "linux" as NodeJS.Platform;
+ t.after(() => {
+ (os as { platform: () => NodeJS.Platform }).platform = orig;
+ });
+
+ const { calls, exec } = makeRecorder();
+ const restore = __setExec(exec);
+ t.after(restore);
+
+ await revert({
+ platform: "linux",
+ gnomeMode: "'auto'",
+ httpHost: "old.host",
+ httpPort: "1234",
+ httpsHost: "",
+ httpsPort: "",
+ });
+ const restoreMode = calls.find(
+ (c) => c.args[0] === "set" && c.args[1] === "org.gnome.system.proxy" && c.args[2] === "mode"
+ );
+ assert.ok(restoreMode);
+ assert.equal(restoreMode.args[3], "'auto'");
+});
+
+test("Windows apply passes proxyArg as single arg, no shell interpolation", async (t) => {
+ const orig = os.platform;
+ (os as { platform: () => NodeJS.Platform }).platform = () => "win32" as NodeJS.Platform;
+ t.after(() => {
+ (os as { platform: () => NodeJS.Platform }).platform = orig;
+ });
+
+ const { calls, exec } = makeRecorder({
+ "winhttp show proxy": "Direct access (no proxy server).",
+ });
+ const restore = __setExec(exec);
+ t.after(restore);
+
+ const result = await apply(7777);
+ assert.equal(result.platform, "windows");
+ const setCall = calls.find((c) => c.args.join(" ") === "winhttp set proxy 127.0.0.1:7777");
+ assert.ok(setCall);
+ assert.equal(setCall.file, "netsh");
+ // Argument is one literal token — no embedded spaces, semicolons, pipes
+ const proxyArg = setCall.args[setCall.args.length - 1];
+ assert.equal(proxyArg, "127.0.0.1:7777");
+});
+
+test("Windows revert calls netsh winhttp reset proxy", async (t) => {
+ const orig = os.platform;
+ (os as { platform: () => NodeJS.Platform }).platform = () => "win32" as NodeJS.Platform;
+ t.after(() => {
+ (os as { platform: () => NodeJS.Platform }).platform = orig;
+ });
+
+ const { calls, exec } = makeRecorder();
+ const restore = __setExec(exec);
+ t.after(restore);
+
+ await revert({ platform: "windows", netshOutput: "" });
+ const resetCall = calls.find((c) => c.args.join(" ") === "winhttp reset proxy");
+ assert.ok(resetCall);
+});
+
+test("apply throws sanitized error when exec fails", async (t) => {
+ const orig = os.platform;
+ (os as { platform: () => NodeJS.Platform }).platform = () => "darwin" as NodeJS.Platform;
+ t.after(() => {
+ (os as { platform: () => NodeJS.Platform }).platform = orig;
+ });
+
+ const exec: ExecFileFn = async () => {
+ throw new Error("ENOENT: /usr/bin/networksetup");
+ };
+ const restore = __setExec(exec);
+ t.after(restore);
+
+ await assert.rejects(() => apply(8080), (err: Error) => {
+ // sanitizeErrorMessage strips paths; assert we still get an Error
+ assert.ok(err instanceof Error);
+ assert.ok(err.message.length > 0);
+ return true;
+ });
+});
+
+test("revert no-ops for unknown platform payload", async (t) => {
+ const { calls, exec } = makeRecorder();
+ const restore = __setExec(exec);
+ t.after(restore);
+
+ await revert(null);
+ await revert({ platform: "freebsd" });
+ assert.equal(calls.length, 0);
+});