Luigit
repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by admin

extensions/autopsy/__tests__/details.test.ts

Raw
import { describe, expect, it } from "vitest";
import { entryDetailEvents } from "../details.ts";
import type { EntryDetailEvent } from "../src/types.ts";

async function collect(entry: unknown, view: "text" | "json") {
	const events: EntryDetailEvent[] = [];
	let text = "";
	for await (const event of entryDetailEvents(entry, view)) {
		events.push(event);
		if (event.type === "text") {
			expect(event.text.length).toBeLessThanOrEqual(8192);
			// Each event must survive independent UTF-8 transport.
			expect(Buffer.from(event.text).toString()).toBe(event.text);
			text += event.text;
		}
	}
	return { events, text };
}

describe("complete entry details", () => {
	it("roundtrips large strings, escaped keys, opaque signatures and repeated references", async () => {
		const repeated = { value: "shared" };
		const entry = {
			message: {
				content: [
					{
						type: "text",
						text: `${"a".repeat(8191)}🦊${'tail\n\t"\\'.repeat(20000)}[truncated]`,
					},
				],
				signature: "opaque".repeat(30000),
			},
			'key"\n\\🦊': repeated,
			unknown: repeated,
		};
		const result = await collect(entry, "json");
		expect(JSON.parse(result.text)).toEqual(entry);
		expect(result.events.at(-1)).toEqual({ type: "end" });
		const readable = await collect(entry, "text");
		expect(readable.text).toBe(entry.message.content[0]?.text);
		expect(readable.text).not.toContain(entry.message.signature);
	});

	it("preserves wide arrays and deeply nested data without recursive traversal", async () => {
		const wide = Array.from({ length: 5000 }, (_, index) => index);
		let deep: unknown = "bottom";
		for (let index = 0; index < 12000; index++) deep = [deep];
		const result = await collect({ wide, deep }, "json");
		const decoded = JSON.parse(result.text);
		expect(decoded.wide).toEqual(wide);
		let value = decoded.deep;
		for (let index = 0; index < 12000; index++) value = value[0];
		expect(value).toBe("bottom");
		expect(result.events.at(-1)?.type).toBe("end");
	});

	it("streams complete known prose and arguments with lazy images at original indices", async () => {
		const content = [
			{ type: "text", text: "full".repeat(40000) },
			{ type: "thinking", thinking: "reasoning", thinkingSignature: "opaque" },
			{
				type: "toolCall",
				name: "run",
				arguments: { full: "args".repeat(40000) },
			},
			...Array.from({ length: 2100 }, () => ({ type: "text", text: "" })),
			{ type: "image", mimeType: "image/png", data: "secret-image-bytes" },
		];
		const entry = {
			message: { sections: { rules: "system section" }, content },
		};
		const result = await collect(entry, "text");
		expect(result.text).toContain("system section");
		expect(result.text).toContain("full".repeat(40000));
		expect(result.text).toContain("[Thinking]\nreasoning");
		expect(result.text).toContain(
			JSON.stringify({ full: "args".repeat(40000) }, null, 2),
		);
		expect(result.text).not.toContain("opaque");
		expect(result.text).not.toContain("secret-image-bytes");
		expect(result.events.filter((event) => event.type === "image")).toEqual([
			{ type: "image", index: 2103, mimeType: "image/png" },
		]);
		const json = await collect(entry, "json");
		const image = JSON.parse(json.text).message.content[2103];
		expect(image.data).toContain("on demand");
		expect(json.text).not.toContain("secret-image-bytes");
	});

	it("renders bash, summaries and unknown schemas without preview clipping", async () => {
		const output = "output".repeat(30000);
		expect(
			(await collect({ message: { command: "cmd", output } }, "text")).text,
		).toBe(`cmd\n${output}`);
		expect((await collect({ summary: output }, "text")).text).toBe(output);
		const unknown = { unknown: { payload: output } };
		expect(JSON.parse((await collect(unknown, "text")).text)).toEqual(unknown);
	});

	it("fails unsupported and cyclic ephemeral data explicitly without signaling completion", async () => {
		const cycle: Record<string, unknown> = { prefix: "readable" };
		cycle["self"] = cycle;
		let invoked = false;
		const accessor = Object.defineProperty({}, "value", {
			enumerable: true,
			get() {
				invoked = true;
				throw new Error("PRIVATE SOURCE ERROR");
			},
		});
		for (const value of [cycle, accessor, { value: 1n }, new Date()]) {
			const result = await collect(value, "json");
			expect(result.events.at(-1)?.type).toBe("error");
			expect(result.events.some((event) => event.type === "end")).toBe(false);
			expect(JSON.stringify(result.events)).not.toContain(
				"PRIVATE SOURCE ERROR",
			);
		}
		expect(invoked).toBe(false);
	});

	it("matches stored JSON semantics for absent fields and non-finite numbers", async () => {
		const entry = {
			absent: undefined,
			values: [undefined, Number.NaN, Infinity],
			negativeZero: -0,
		};
		const result = await collect(entry, "json");
		expect(JSON.parse(result.text)).toEqual(JSON.parse(JSON.stringify(entry)));
		expect(result.events.at(-1)?.type).toBe("end");
		for (const content of [
			"base instructions",
			[{ type: "text", text: "base instructions" }],
		]) {
			const system = await collect(
				{
					message: {
						role: "system",
						content,
						sections: { rules: "rule body", removed: null },
					},
				},
				"text",
			);
			expect(system.text).toContain("base instructions");
			expect(system.text).toContain("[Section rules]\nrule body");
			expect(system.text).toContain("[Section removed]\n[removed]");
		}
	});

	it("does not invoke toJSON and preserves its data when JSON-compatible", async () => {
		const entry = {
			toJSON: "stored field",
			nested: { type: "image", data: "bytes", signature: "keep" },
		};
		const result = await collect(entry, "json");
		expect(JSON.parse(result.text)).toEqual({
			toJSON: "stored field",
			nested: {
				type: "image",
				data: "[image data: available on demand]",
				signature: "keep",
			},
		});
	});

	it("yields to the event loop and can cancel before traversing later source fields", async () => {
		let reached = false;
		const entry = { content: "a".repeat(2 * 1024 * 1024) };
		Object.defineProperty(entry, "later", {
			enumerable: true,
			get() {
				reached = true;
				return "later";
			},
		});
		const iterator = entryDetailEvents(entry, "json");
		let ticked = false;
		const tick = new Promise<void>((resolve) =>
			setImmediate(() => {
				ticked = true;
				resolve();
			}),
		);
		for (let count = 0; count < 100; count++) await iterator.next();
		expect(ticked).toBe(true);
		await iterator.return(undefined);
		expect((await iterator.next()).done).toBe(true);
		await tick;
		expect(reached).toBe(false);
	});
});