|
| 1 | +import fs from "node:fs"; |
| 2 | +import os from "node:os"; |
| 3 | +import path from "node:path"; |
| 4 | +import { Command } from "commander"; |
| 5 | +import { createDeferred } from "openclaw/plugin-sdk/extension-shared"; |
| 6 | +import { tempWorkspace } from "openclaw/plugin-sdk/temp-path"; |
| 7 | +import { afterEach, beforeEach, describe, expect, it, type MockInstance, vi } from "vitest"; |
| 8 | + |
| 9 | +const { sleepMock, historyMock } = vi.hoisted(() => ({ |
| 10 | + sleepMock: vi.fn(), |
| 11 | + historyMock: vi.fn(), |
| 12 | +})); |
| 13 | +vi.mock("../api.js", async (importOriginal) => ({ |
| 14 | + ...(await importOriginal<typeof import("../api.js")>()), |
| 15 | + sleep: sleepMock, |
| 16 | +})); |
| 17 | +vi.mock("./manager/store.js", async (importOriginal) => ({ |
| 18 | + ...(await importOriginal<typeof import("./manager/store.js")>()), |
| 19 | + getCallHistoryFromStore: historyMock, |
| 20 | +})); |
| 21 | + |
| 22 | +import { registerVoiceCallLogs } from "./cli-call-log.js"; |
| 23 | + |
| 24 | +describe("voice-call diagnostic stream ownership", () => { |
| 25 | + let workspace: Awaited<ReturnType<typeof tempWorkspace>>; |
| 26 | + let file: string; |
| 27 | + let output: Buffer[]; |
| 28 | + let stdout: MockInstance<typeof process.stdout.write>; |
| 29 | + const stopped = new Error("diagnostic test finished"); |
| 30 | + |
| 31 | + beforeEach(async () => { |
| 32 | + workspace = await tempWorkspace({ rootDir: os.tmpdir(), prefix: "voice-call-log-" }); |
| 33 | + file = await workspace.write("diagnostics.jsonl", ""); |
| 34 | + output = []; |
| 35 | + sleepMock.mockReset().mockRejectedValue(stopped); |
| 36 | + historyMock.mockReset().mockResolvedValue([]); |
| 37 | + stdout = vi.spyOn(process.stdout, "write").mockImplementation((chunk) => { |
| 38 | + output.push(Buffer.isBuffer(chunk) ? Buffer.from(chunk) : Buffer.from(String(chunk))); |
| 39 | + return true; |
| 40 | + }); |
| 41 | + }); |
| 42 | + |
| 43 | + afterEach(async () => { |
| 44 | + vi.restoreAllMocks(); |
| 45 | + await workspace.cleanup(); |
| 46 | + }); |
| 47 | + |
| 48 | + function command(...args: string[]) { |
| 49 | + const program = new Command(); |
| 50 | + registerVoiceCallLogs({ root: program, defaultFile: file, ensureHistoryStateRuntime() {} }); |
| 51 | + return program.parseAsync(args, { from: "user" }); |
| 52 | + } |
| 53 | + |
| 54 | + function text() { |
| 55 | + return Buffer.concat(output).toString("utf8"); |
| 56 | + } |
| 57 | + |
| 58 | + it.each(["tail", "latency"])( |
| 59 | + "preserves requested %s history beyond one megabyte without reading the whole file", |
| 60 | + async (mode) => { |
| 61 | + const records = [120, 240, 360].map((latency) => |
| 62 | + JSON.stringify({ metadata: { lastTurnLatencyMs: latency }, padding: "x".repeat(600_000) }), |
| 63 | + ); |
| 64 | + fs.writeFileSync(file, `${records.join("\n")}\n`); |
| 65 | + const readFile = vi.spyOn(fs, "readFileSync"); |
| 66 | + if (mode === "tail") { |
| 67 | + await expect(command("tail", "--since", "3")).rejects.toBe(stopped); |
| 68 | + expect(text()).toBe(`${records.join("\n")}\n`); |
| 69 | + } else { |
| 70 | + await command("latency", "--last", "3"); |
| 71 | + expect(JSON.parse(text())).toMatchObject({ |
| 72 | + recordsScanned: 3, |
| 73 | + turnLatency: { count: 3, avgMs: 240, minMs: 120, maxMs: 360 }, |
| 74 | + }); |
| 75 | + } |
| 76 | + expect(readFile.mock.calls.filter(([target]) => target === file)).toEqual([]); |
| 77 | + }, |
| 78 | + ); |
| 79 | + |
| 80 | + it("bounds follow reads while retaining every record and the unfinished suffix", async () => { |
| 81 | + const records = Array.from({ length: 2048 }, (_, seq) => |
| 82 | + JSON.stringify({ seq, text: "é".repeat(512) }), |
| 83 | + ); |
| 84 | + const read = vi.spyOn(fs, "readSync"); |
| 85 | + sleepMock |
| 86 | + .mockResolvedValueOnce(undefined) |
| 87 | + .mockImplementationOnce(async () => { |
| 88 | + fs.appendFileSync(file, `${records.join("\n")}\n{"seq":2048`); |
| 89 | + }) |
| 90 | + .mockImplementationOnce(async () => { |
| 91 | + fs.appendFileSync(file, "}\n"); |
| 92 | + }); |
| 93 | + await expect(command("tail", "--since", "0")).rejects.toBe(stopped); |
| 94 | + expect(text()).toBe(`${records.join("\n")}\n{"seq":2048}\n`); |
| 95 | + const requested = read.mock.calls.map(([, buffer]) => buffer.byteLength); |
| 96 | + expect(requested.length).toBeGreaterThan(0); |
| 97 | + expect(requested.every((length) => length <= 64 * 1024)).toBe(true); |
| 98 | + }); |
| 99 | + |
| 100 | + it("does not join a pending record to a larger replacement file", async () => { |
| 101 | + fs.writeFileSync(file, '{"seq":0}\n{"retired":'); |
| 102 | + const replacement = `${JSON.stringify({ seq: 1, text: "fresh".repeat(64) })}\n`; |
| 103 | + sleepMock.mockImplementationOnce(async () => { |
| 104 | + const next = await workspace.write("replacement.jsonl", replacement); |
| 105 | + fs.renameSync(next, file); |
| 106 | + }); |
| 107 | + await expect(command("tail", "--since", "1")).rejects.toBe(stopped); |
| 108 | + expect(text()).toBe(`{"seq":0}\n${replacement}`); |
| 109 | + }); |
| 110 | + |
| 111 | + it("stops producing until stdout drains", async () => { |
| 112 | + fs.writeFileSync(file, '{"seq":0}\n{"seq":1}\n'); |
| 113 | + const blocked = createDeferred<void>(); |
| 114 | + let rejectWrites = true; |
| 115 | + stdout.mockImplementation((chunk) => { |
| 116 | + output.push(Buffer.isBuffer(chunk) ? Buffer.from(chunk) : Buffer.from(String(chunk))); |
| 117 | + if (rejectWrites) { |
| 118 | + blocked.resolve(); |
| 119 | + return false; |
| 120 | + } |
| 121 | + return true; |
| 122 | + }); |
| 123 | + const running = command("tail", "--since", "2").catch((error: unknown) => error); |
| 124 | + await blocked.promise; |
| 125 | + try { |
| 126 | + expect(text()).not.toContain('"seq":1'); |
| 127 | + expect(sleepMock).not.toHaveBeenCalled(); |
| 128 | + } finally { |
| 129 | + rejectWrites = false; |
| 130 | + process.stdout.emit("drain"); |
| 131 | + expect(await running).toBe(stopped); |
| 132 | + } |
| 133 | + expect(text()).toBe('{"seq":0}\n{"seq":1}\n'); |
| 134 | + }); |
| 135 | + |
| 136 | + it("streams a large record across polls without breaking UTF-8 or dropping its prefix", async () => { |
| 137 | + const record = JSON.stringify({ text: "é".repeat(700_000) }); |
| 138 | + const bytes = Buffer.from(record); |
| 139 | + fs.writeFileSync(file, bytes.subarray(0, 600_001)); |
| 140 | + sleepMock.mockImplementationOnce(async () => { |
| 141 | + fs.appendFileSync(file, Buffer.concat([bytes.subarray(600_001), Buffer.from("\n")])); |
| 142 | + }); |
| 143 | + const read = vi.spyOn(fs, "readSync"); |
| 144 | + await expect(command("tail", "--since", "0")).rejects.toBe(stopped); |
| 145 | + expect(Buffer.concat(output)).toEqual(Buffer.concat([bytes, Buffer.from("\n")])); |
| 146 | + expect(read.mock.calls.every(([, buffer]) => buffer.byteLength <= 64 * 1024)).toBe(true); |
| 147 | + }); |
| 148 | + |
| 149 | + it("keeps latency record selection, envelopes, malformed JSON and final EOF semantics", async () => { |
| 150 | + fs.writeFileSync( |
| 151 | + file, |
| 152 | + [ |
| 153 | + '{"metadata":{"lastTurnLatencyMs":900}}', |
| 154 | + "", |
| 155 | + '{"call":{"metadata":{"lastTurnLatencyMs":100,"lastTurnListenWaitMs":20}}}', |
| 156 | + "invalid JSON", |
| 157 | + "null", |
| 158 | + '{"metadata":{"lastTurnLatencyMs":300,"lastTurnLatencyMs":200}}', |
| 159 | + ].join("\n"), |
| 160 | + ); |
| 161 | + await command("latency", "--last", "4"); |
| 162 | + expect(JSON.parse(text())).toMatchObject({ |
| 163 | + recordsScanned: 2, |
| 164 | + turnLatency: { count: 2, minMs: 100, maxMs: 200, avgMs: 150 }, |
| 165 | + listenWait: { count: 1, avgMs: 20 }, |
| 166 | + }); |
| 167 | + }); |
| 168 | + |
| 169 | + it("closes the active descriptor and stops when blocked stdout fails", async () => { |
| 170 | + fs.writeFileSync(file, '{"seq":0}\n'); |
| 171 | + const drainListeners = process.stdout.listenerCount("drain"); |
| 172 | + const blocked = createDeferred<void>(); |
| 173 | + const failed = new Error("output pipe failed"); |
| 174 | + stdout.mockImplementation(() => { |
| 175 | + blocked.resolve(); |
| 176 | + return false; |
| 177 | + }); |
| 178 | + const open = vi.spyOn(fs, "openSync"); |
| 179 | + const running = command("tail", "--since", "1").catch((error: unknown) => error); |
| 180 | + await blocked.promise; |
| 181 | + const index = open.mock.calls.findIndex(([target]) => target === file); |
| 182 | + const opened = open.mock.results[index]; |
| 183 | + if (opened?.type !== "return") { |
| 184 | + throw new Error("diagnostic command did not open its log"); |
| 185 | + } |
| 186 | + const fd = opened.value; |
| 187 | + expect(fs.fstatSync(fd).isFile()).toBe(true); |
| 188 | + process.stdout.emit("error", failed); |
| 189 | + expect(await running).toBe(failed); |
| 190 | + expect(() => fs.fstatSync(fd)).toThrow(); |
| 191 | + expect(sleepMock).not.toHaveBeenCalled(); |
| 192 | + expect(process.stdout.listenerCount("drain")).toBe(drainListeners); |
| 193 | + }); |
| 194 | + |
| 195 | + it("deduplicates retained SQLite snapshots without retaining retired history forever", async () => { |
| 196 | + file = path.join(workspace.dir, "calls.jsonl"); |
| 197 | + const first = { callId: "first", state: "completed" }; |
| 198 | + const second = { callId: "second", state: "completed" }; |
| 199 | + historyMock |
| 200 | + .mockResolvedValueOnce([first]) |
| 201 | + .mockResolvedValueOnce([first, second]) |
| 202 | + .mockResolvedValueOnce([second]) |
| 203 | + .mockResolvedValueOnce([first]) |
| 204 | + .mockResolvedValueOnce([first]); |
| 205 | + sleepMock |
| 206 | + .mockResolvedValueOnce(undefined) |
| 207 | + .mockResolvedValueOnce(undefined) |
| 208 | + .mockResolvedValueOnce(undefined); |
| 209 | + await expect(command("tail", "--since", "1")).rejects.toBe(stopped); |
| 210 | + expect( |
| 211 | + text() |
| 212 | + .trim() |
| 213 | + .split("\n") |
| 214 | + .map((line) => JSON.parse(line)), |
| 215 | + ).toEqual([first, second, first]); |
| 216 | + }); |
| 217 | +}); |
0 commit comments