Luigit
repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by admin

extensions/voice/__serial__/native-controller.test.ts

Raw
import { mkdtempSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import {
	buildSessionProjection,
	createEventBus,
	SessionManager,
} from "@earendil-works/pi-coding-agent";
import { afterEach, expect, it, vi } from "vitest";
import { VoiceController } from "../src/controller.ts";
import { VoiceHistory } from "../src/voice-history.ts";

const roots: string[] = [];
afterEach(() => {
	for (const root of roots.splice(0))
		rmSync(root, { recursive: true, force: true });
});
function fixture(id = "main") {
	const root = mkdtempSync(join(tmpdir(), "native-controller-"));
	roots.push(root);
	const send = vi.fn();
	const abort = vi.fn();
	const editor = vi.fn(() => {
		throw new Error("editor accessed");
	});
	const events = createEventBus();
	const controller = new VoiceController({
		sendUserMessage: send,
		events,
	} as never);
	const ctx = {
		cwd: root,
		isIdle: () => false,
		abort,
		ui: { setEditorText: editor, getEditorText: editor },
		sessionManager: {
			getSessionId: () => id,
			getSessionName: () => "",
			getBranch: (): any[] => [],
			buildSessionProjection: (): ReturnType<typeof buildSessionProjection> =>
				buildSessionProjection(ctx.sessionManager.getBranch()),
		},
	};
	controller.beginNative(ctx as never, {
		modelSetting: "auto",
		historyDirectory: root,
	});
	const tools = (controller as any).tools();
	const tool = (name: string) =>
		tools.find((entry: any) => entry.name === `voice_executor_${name}`);
	return { root, controller, tool, send, abort, editor, ctx, events };
}

function provideTaskSummaries(
	f: ReturnType<typeof fixture>,
	replies: string[],
): void {
	Reflect.set(f.ctx, "modelRegistry", {
		getAvailable: () => [{ provider: "test", id: "gpt-6-luna" }],
		streamSimple: () => ({
			result: async () => ({
				stopReason: "stop",
				content: [{ type: "text", text: replies.shift() ?? "SKIP" }],
			}),
		}),
	});
}

it("sends incremental context and suppresses unchanged facts, semantic SKIP and near-repeat speech", async () => {
	vi.useFakeTimers();
	vi.setSystemTime(0);
	const f = fixture();
	const replies = [
		"I’ve isolated why captions arrive late.",
		"SKIP",
		"I’ve isolated why the captions arrive late.",
		"I’ve made captions keep up with your speech.",
	];
	const stream = vi.fn((..._args: any[]) => ({
		result: async () => ({
			stopReason: "stop",
			content: [{ type: "text", text: replies.shift() }],
		}),
	}));
	Reflect.set(f.ctx, "modelRegistry", {
		getAvailable: () => [{ provider: "test", id: "gpt-6-luna" }],
		streamSimple: stream,
	});
	const statuses = () =>
		f.controller.nativeHistory().filter((entry) => entry.kind === "status");
	const tick = async () => {
		await vi.advanceTimersByTimeAsync(45_000);
		const started = f.controller.narrateExecutorProgress();
		await vi.advanceTimersByTimeAsync(0);
		return started;
	};
	try {
		await f.tool("dispatch").execute("1", { text: "Fix caption latency" });
		f.controller.onExecutorStart();
		f.controller.onExecutorMessageStart({
			role: "user",
			content: f.send.mock.calls[0]?.[0],
		});
		f.controller.onExecutorTool("read", "first", { path: "caption.ts" });
		expect(await tick()).toBe(true);
		expect(statuses()).toHaveLength(1);
		f.controller.turnBoundary(statuses()[0]!.id);
		expect(await tick()).toBe(false);
		expect(stream).toHaveBeenCalledTimes(1);
		f.controller.onExecutorTool("nu", "second", {
			command: "trace caption queue",
		});
		expect(await tick()).toBe(true);
		expect(statuses()).toHaveLength(1);
		expect(Reflect.get(f.controller, "boundaryReady")).toBe(true);
		const context = JSON.parse(stream.mock.calls[1]?.[1].messages[0].content);
		expect(context.previousUpdate).toBe(
			"I’ve isolated why captions arrive late.",
		);
		expect(context.changes.tool.name).toBe("nu");
		expect(context.changes.messages).toEqual([]);
		f.controller.onExecutorTool("edit", "third", { path: "caption.ts" });
		expect(await tick()).toBe(true);
		expect(statuses()).toHaveLength(1);
		f.controller.onExecutorTool("nu", "fourth", {
			command: "verify queue fix",
		});
		expect(await tick()).toBe(true);
		expect(statuses()).toHaveLength(2);
		expect(statuses()[1]?.text).toBe(
			"I’ve made captions keep up with your speech.",
		);
	} finally {
		f.controller.close();
		vi.useRealTimers();
	}
});

it("summarizes scoped real activity through the existing voice model with bounded, redacted context", async () => {
	vi.useFakeTimers();
	vi.setSystemTime(0);
	const f = fixture();
	const branch: any[] = [
		{
			type: "message",
			id: "old",
			message: {
				role: "assistant",
				content: [{ type: "text", text: "Unrelated old deployment" }],
			},
		},
	];
	vi.spyOn(f.ctx.sessionManager, "getBranch").mockImplementation(() => branch);
	let finish!: (value: any) => void;
	const answer = new Promise((resolve) => {
		finish = resolve;
	});
	const stream = vi.fn((..._args: any[]) => ({ result: () => answer }));
	Reflect.set(f.ctx, "modelRegistry", {
		getAvailable: () => [{ provider: "test", id: "gpt-6-luna" }],
		streamSimple: stream,
	});
	try {
		await f
			.tool("dispatch")
			.execute("1", { text: "Fix voice capture and run focused tests" });
		f.controller.onExecutorStart();
		f.controller.onExecutorMessageStart({
			role: "user",
			content: f.send.mock.calls[0]?.[0],
		});
		branch.push({
			type: "message",
			id: "current",
			message: {
				role: "assistant",
				content: [
					{
						type: "text",
						text: "Adjusted voice capture bounds; next verify focused tests.",
					},
				],
			},
		});
		f.controller.onExecutorMessageUpdate();
		f.controller.onExecutorTool("nu", "tests", {
			command: "mise run //:test -- extensions/voice",
			token: "fake-value",
		});
		f.controller.onExecutorToolEnd("tests", false, {
			content: [{ type: "text", text: "107 tests passed" }],
		});
		await vi.advanceTimersByTimeAsync(45_000);
		expect(f.controller.narrateExecutorProgress()).toBe(true);
		expect(f.controller.narrateExecutorProgress()).toBe(false);
		expect(
			f.controller.nativeHistory().some((entry) => entry.kind === "status"),
		).toBe(false);
		const input = JSON.parse(stream.mock.calls[0]?.[1].messages[0].content);
		expect(input.task).toContain("voice capture");
		expect(input.changes.tool.name).toBe("nu");
		expect(input.changes.tool.input).toContain("mise run //:test");
		expect(input.changes.tool.result).toContain("107 tests passed");
		expect(input.changes.tool.status).toBe("completed");
		expect(JSON.stringify(input)).not.toContain("Unrelated old deployment");
		expect(JSON.stringify(input)).not.toContain("fake-value");
		await vi.advanceTimersByTimeAsync(4_000);
		finish({
			stopReason: "stop",
			content: [
				{
					type: "text",
					text: "I’ve updated voice capture bounds and verified focused tests.",
				},
			],
		});
		await vi.advanceTimersByTimeAsync(0);
		const status = f.controller
			.nativeHistory()
			.find((entry) => entry.kind === "status");
		expect(status?.text).toBe(
			"I’ve updated voice capture bounds and verified focused tests.",
		);
		if (!status) throw new Error("Missing semantic status");
		f.controller.turnBoundary(status.id);
		f.controller.onExecutorTool("read", "next-tool");
		await vi.advanceTimersByTimeAsync(44_999);
		expect(f.controller.narrateExecutorProgress()).toBe(false);
		await vi.advanceTimersByTimeAsync(1);
		expect(f.controller.narrateExecutorProgress()).toBe(true);
	} finally {
		f.controller.close();
		vi.useRealTimers();
	}
});

it.each([
	"human",
	"question",
	"owner",
	"typed",
	"cancel",
	"busy",
	"stop",
] as const)(
	"discards semantic output and fallback after %s invalidates a pending summary",
	async (cause) => {
		vi.useFakeTimers();
		vi.setSystemTime(0);
		const f = fixture();
		let finish!: (value: any) => void;
		const answer = new Promise((resolve) => {
			finish = resolve;
		});
		const stream = vi.fn((..._args: any[]) => ({ result: () => answer }));
		Reflect.set(f.ctx, "modelRegistry", {
			getAvailable: () => [{ provider: "test", id: "gpt-6-luna" }],
			streamSimple: stream,
		});
		let idle = true;
		try {
			await f.tool("dispatch").execute("1", { text: "work" });
			f.controller.onExecutorStart();
			f.controller.onExecutorMessageStart({
				role: "user",
				content: f.send.mock.calls[0]?.[0],
			});
			await vi.advanceTimersByTimeAsync(45_000);
			expect(f.controller.narrateExecutorProgress(() => idle)).toBe(true);
			const signal = stream.mock.calls[0]?.[2].signal as AbortSignal;
			if (cause === "human") f.controller.onHumanSpeech(true);
			if (cause === "question") f.controller.onExecutorPromptStart("Question");
			if (cause === "typed")
				f.controller.onExecutorMessageStart({
					role: "user",
					content: "Typed takeover",
				});
			if (cause === "owner") {
				await f.tool("dispatch").execute("2", { text: "new work" });
				f.controller.onExecutorMessageStart({
					role: "user",
					content: f.send.mock.calls[1]?.[0],
				});
			}
			if (cause === "cancel") {
				const request = Reflect.get(f.controller, "executorRequests").get(
					Reflect.get(f.controller, "activeExecutorRequest"),
				);
				request.cancelRequested = true;
				Reflect.get(f.controller, "syncExecutorRequests").call(f.controller);
			}
			if (cause === "busy") idle = false;
			if (cause === "stop") f.controller.endNative();
			if (cause !== "busy") expect(signal.aborted).toBe(true);
			finish({
				stopReason: "stop",
				content: [
					{ type: "text", text: "An obsolete status must never be spoken." },
				],
			});
			await vi.advanceTimersByTimeAsync(6_000);
			expect(
				f.controller.nativeHistory().some((entry) => entry.kind === "status"),
			).toBe(false);
			expect(stream).toHaveBeenCalledOnce();
		} finally {
			f.controller.close();
			vi.useRealTimers();
		}
	},
);

it.each([
	"Bearer never-send-this",
	JSON.stringify({ ACCESS_KEY: "key-marker", SECRET_VALUE: "sec-marker" }),
])(
	"stays silent on summarizer failure and omits sensitive results: %s",
	async (resultText) => {
		vi.useFakeTimers();
		vi.setSystemTime(0);
		const f = fixture();
		let fail!: (error: Error) => void;
		const answer = new Promise((_resolve, reject) => {
			fail = reject;
		});
		const stream = vi.fn((..._args: any[]) => ({ result: () => answer }));
		Reflect.set(f.ctx, "modelRegistry", {
			getAvailable: () => [{ provider: "test", id: "gpt-6-luna" }],
			streamSimple: stream,
		});
		try {
			await f.tool("dispatch").execute("1", { text: "work" });
			f.controller.onExecutorStart();
			f.controller.onExecutorMessageStart({
				role: "user",
				content: f.send.mock.calls[0]?.[0],
			});
			f.controller.onExecutorTool("nu", "tool", {
				command: "API_KEY=do-not-send",
				query: "https://user:uri-password@example.invalid/",
			});
			f.controller.onExecutorToolEnd("tool", false, {
				content: [{ type: "text", text: resultText }],
			});
			await vi.advanceTimersByTimeAsync(45_000);
			f.controller.narrateExecutorProgress();
			const context = stream.mock.calls[0]?.[1].messages[0].content as string;
			expect(context).not.toContain("do-not-send");
			expect(context).not.toContain("never-send-this");
			expect(context).not.toContain("uri-password");
			expect(context).not.toContain("key-marker");
			expect(context).not.toContain("sec-marker");
			f.controller.onExecutorTool("edit", "new-tool", {
				path: "extensions/voice/src/native-call.ts",
			});
			fail(new Error("provider failed"));
			await vi.advanceTimersByTimeAsync(0);
			expect(
				f.controller.nativeHistory().find((entry) => entry.kind === "status")
					?.text,
			).toBeUndefined();
		} finally {
			f.controller.close();
			vi.useRealTimers();
		}
	},
);

it("stays silent when no semantic summarizer is available instead of narrating tool activity", async () => {
	vi.useFakeTimers();
	vi.setSystemTime(0);
	const f = fixture();
	try {
		await f.tool("dispatch").execute("1", { text: "Fix voice pauses" });
		f.controller.onExecutorStart();
		f.controller.onExecutorMessageStart({
			role: "user",
			content: f.send.mock.calls[0]?.[0],
		});
		for (const tool of ["read", "edit", "nu"]) {
			f.controller.onExecutorTool(tool, tool);
			await vi.advanceTimersByTimeAsync(45_000);
			expect(f.controller.narrateExecutorProgress()).toBe(false);
		}
		expect(
			f.controller.nativeHistory().filter((entry) => entry.kind === "status"),
		).toEqual([]);
	} finally {
		f.controller.close();
		vi.useRealTimers();
	}
});

it("captures rich activity only for started owned work during an active native call", async () => {
	const f = fixture();
	try {
		f.controller.onExecutorTool("nu", "unowned", {
			command: "ordinary command",
		});
		expect(Reflect.get(f.controller, "progressToolContext")).toBeUndefined();
		expect(Reflect.get(f.controller, "executor").tool).toBe("nu");
		await f.tool("dispatch").execute("1", { text: "work" });
		f.controller.onExecutorTool("nu", "queued", { command: "queued command" });
		expect(Reflect.get(f.controller, "progressToolContext")).toBeUndefined();
		f.controller.onExecutorMessageStart({
			role: "user",
			content: f.send.mock.calls[0]?.[0],
		});
		f.controller.onExecutorTool("nu", "owned", { command: "owned command" });
		expect(Reflect.get(f.controller, "progressToolContext")?.input).toContain(
			"owned command",
		);
		f.controller.endNative();
		f.controller.onExecutorToolEnd("owned", false, {
			content: [{ type: "text", text: "off-call result" }],
		});
		expect(Reflect.get(f.controller, "progressToolContext")).toBeUndefined();
		f.controller.onExecutorTool("edit", "off", { path: "ordinary.txt" });
		expect(Reflect.get(f.controller, "progressToolContext")).toBeUndefined();
		expect(Reflect.get(f.controller, "executor").tool).toBe("edit");
	} finally {
		f.controller.close();
	}
});

it("narrates only actual owned work at 45-second intervals with status history and matching boundaries", async () => {
	vi.useFakeTimers();
	vi.setSystemTime(0);
	const f = fixture();
	provideTaskSummaries(f, [
		"I’ve isolated why captions arrive late.",
		"I’ve made captions keep up with your speech.",
	]);
	try {
		Reflect.get(f.controller, "history").sessionManager.appendMessage({
			role: "user",
			content: "Please work on this.",
			timestamp: Date.now(),
		});
		await f.tool("dispatch").execute("1", { text: "work" });
		f.controller.onExecutorStart();
		await vi.advanceTimersByTimeAsync(60_000);
		expect(f.controller.narrateExecutorProgress()).toBe(false);
		f.controller.onExecutorMessageStart({
			role: "user",
			content: f.send.mock.calls[0]?.[0],
		});
		f.controller.onExecutorTool("edit", "tool-1");
		await vi.advanceTimersByTimeAsync(44_999);
		expect(f.controller.narrateExecutorProgress()).toBe(false);
		await vi.advanceTimersByTimeAsync(1);
		expect(f.controller.narrateExecutorProgress()).toBe(true);
		await vi.advanceTimersByTimeAsync(0);
		const first = f.controller
			.nativeHistory()
			.find((entry) => entry.kind === "status");
		expect(first).toMatchObject({
			role: "assistant",
			kind: "status",
			playback: "not-played",
			playedText: "",
			text: "I’ve isolated why captions arrive late.",
		});
		if (!first) throw new Error("Missing status");
		expect(f.controller.turnBoundary("stale-normal-turn")).toBe(false);
		expect(f.controller.narrateExecutorProgress()).toBe(false);
		f.controller.markNativePlayback(first.id, first.text);
		expect(
			f.controller.nativeHistory().find((entry) => entry.id === first.id)
				?.playback,
		).toBe("played");
		f.controller.turnBoundary(first.id);
		f.controller.onExecutorTool("read", "tool-2");
		await vi.advanceTimersByTimeAsync(44_999);
		expect(f.controller.narrateExecutorProgress()).toBe(false);
		await vi.advanceTimersByTimeAsync(1);
		expect(f.controller.narrateExecutorProgress()).toBe(true);
		await vi.advanceTimersByTimeAsync(0);
		const second = f.controller
			.nativeHistory()
			.filter((entry) => entry.kind === "status")
			.at(-1);
		expect(f.controller.turnBoundary(first.id)).toBe(false);
		f.controller.cancelNativeProgress();
		expect(
			f.controller.nativeHistory().find((entry) => entry.id === second?.id),
		).toMatchObject({ interrupted: true, playback: "not-played" });
		if (!second) throw new Error("Missing second status");
		f.controller.markNativePlayback(second.id, "Pi is still working.");
		expect(
			f.controller.nativeHistory().find((entry) => entry.id === second.id)
				?.playedText,
		).toBe("Pi is still working.");
		const reopened = new VoiceHistory(f.root, f.root, "main");
		expect(
			reopened.snapshot().find((entry) => entry.id === first.id)?.kind,
		).toBe("status");
	} finally {
		f.controller.close();
		vi.useRealTimers();
	}
});

it("suppresses status for human input, results, busy responses and questions; uses only correlated tool facts", async () => {
	vi.useFakeTimers();
	vi.setSystemTime(0);
	const f = fixture();
	provideTaskSummaries(f, [
		"I’ve found a blocker preventing the requested fix.",
	]);
	try {
		await f.tool("dispatch").execute("1", { text: "work" });
		f.controller.onExecutorStart();
		f.controller.onExecutorMessageStart({
			role: "user",
			content: f.send.mock.calls[0]?.[0],
		});
		await vi.advanceTimersByTimeAsync(45_000);
		for (const [key, value] of Object.entries({
			humanSpeaking: true,
			responsePending: true,
			draining: true,
			pendingSpeech: "human input",
			unadmittedInput: {
				ticket: 1,
				text: "awaiting admission",
				prompt: "prompt",
			},
			pendingResults: [{ text: "result" }],
			boundaryReady: false,
			nativePromptWaiting: true,
		})) {
			const before = Reflect.get(f.controller, key);
			Reflect.set(f.controller, key, value);
			expect(f.controller.narrateExecutorProgress()).toBe(false);
			Reflect.set(f.controller, key, before);
		}
		f.controller.onExecutorPromptStart("Approve a question?");
		expect(f.controller.narrateExecutorProgress()).toBe(false);
		f.controller.onExecutorPromptEnd();
		f.controller.onExecutorTool("ask_user_question", "ask");
		expect(f.controller.narrateExecutorProgress()).toBe(false);
		f.controller.onExecutorTool("nu", "current");
		f.controller.onExecutorToolEnd("stale-tool", true);
		expect(Reflect.get(f.controller, "progressToolContext")?.status).toBe(
			"running",
		);
		f.controller.onExecutorToolEnd("current", true);
		expect(f.controller.narrateExecutorProgress()).toBe(true);
		await vi.advanceTimersByTimeAsync(0);
		const status = f.controller
			.nativeHistory()
			.find((entry) => entry.kind === "status");
		expect(status?.text).toBe(
			"I’ve found a blocker preventing the requested fix.",
		);
		f.controller.onExecutorPromptStart("Pi approval");
		expect(f.controller.isNativeProgressCurrent(status?.id ?? "")).toBe(false);
		expect(
			f.controller.nativeHistory().find((entry) => entry.id === status?.id)
				?.interrupted,
		).toBe(true);
	} finally {
		f.controller.close();
		vi.useRealTimers();
	}
});

it("cancels status on settlement and delivers the real result instead of starving its boundary", async () => {
	vi.useFakeTimers();
	vi.setSystemTime(0);
	const f = fixture();
	provideTaskSummaries(f, ["I’ve isolated why captions arrive late."]);
	try {
		const prompt = vi.fn(async (_text: string) => {
			Reflect.get(f.controller, "consumeStructuredDelta").call(
				f.controller,
				Reflect.get(f.controller, "activeTurn"),
				JSON.stringify({
					heard: "",
					reply: "The work has settled.",
					hotwords: [],
				}),
			);
		});
		Reflect.set(f.controller, "ensureChild", async () => ({
			refreshContext: vi.fn(),
			setActiveToolsByName: vi.fn(),
			prompt,
		}));
		await f.tool("dispatch").execute("1", { text: "work" });
		f.controller.onExecutorStart();
		f.controller.onExecutorMessageStart({
			role: "user",
			content: f.send.mock.calls[0]?.[0],
		});
		await vi.advanceTimersByTimeAsync(45_000);
		expect(f.controller.narrateExecutorProgress()).toBe(true);
		await vi.advanceTimersByTimeAsync(0);
		const status = f.controller
			.nativeHistory()
			.find((entry) => entry.kind === "status");
		if (!status) throw new Error("Missing status");
		f.controller.onExecutorAgentEnd([]);
		expect(f.controller.isNativeProgressCurrent(status.id)).toBe(true);
		f.controller.onExecutorMessageEnd({
			role: "assistant",
			stopReason: "stop",
			content: "Finished the requested work.",
		});
		f.controller.onExecutorSettled();
		await vi.advanceTimersByTimeAsync(0);
		expect(f.controller.isNativeProgressCurrent(status.id)).toBe(false);
		expect(prompt).toHaveBeenCalledOnce();
		expect(prompt.mock.calls[0]?.[0]).toContain("work-result");
		expect(f.controller.turnBoundary(status.id)).toBe(false);
		expect(Reflect.get(f.controller, "boundaryReady")).toBe(false);
	} finally {
		f.controller.close();
		vi.useRealTimers();
	}
});

it("stops status on typed takeover, settlement and stop without claiming arbitrary tool labels", async () => {
	vi.useFakeTimers();
	vi.setSystemTime(0);
	const f = fixture();
	provideTaskSummaries(f, ["I’ve isolated why captions arrive late."]);
	try {
		await f.tool("dispatch").execute("1", { text: "work" });
		f.controller.onExecutorStart();
		f.controller.onExecutorMessageStart({
			role: "user",
			content: f.send.mock.calls[0]?.[0],
		});
		f.controller.onExecutorTool("approved_all_questions", "unknown");
		await vi.advanceTimersByTimeAsync(45_000);
		expect(f.controller.narrateExecutorProgress()).toBe(true);
		await vi.advanceTimersByTimeAsync(0);
		const status = f.controller
			.nativeHistory()
			.find((entry) => entry.kind === "status");
		expect(status?.text).toBe("I’ve isolated why captions arrive late.");
		f.controller.onExecutorMessageStart({
			role: "user",
			content: "typed takeover",
		});
		expect(f.controller.isNativeProgressCurrent(status?.id ?? "")).toBe(false);
		await vi.advanceTimersByTimeAsync(60_000);
		expect(f.controller.narrateExecutorProgress()).toBe(false);
		Reflect.set(f.controller, "ensureChild", () => new Promise(() => {}));
		f.controller.onExecutorSettled();
		expect(f.controller.narrateExecutorProgress()).toBe(false);
		f.controller.endNative();
		expect(f.controller.narrateExecutorProgress()).toBe(false);
	} finally {
		f.controller.close();
		vi.useRealTimers();
	}
});

it("keeps large native input intact through initialization and barge-in, with explicit sanity rejection", async () => {
	const f = fixture();
	let release!: (child: unknown) => void;
	const pending = new Promise((resolve) => {
		release = resolve;
	});
	const prompt = vi.fn(async (_text: string) => {});
	(f.controller as any).ensureChild = () => pending;
	try {
		const first = "a".repeat(100_000),
			second = "b".repeat(20_000);
		f.controller.receiveNative(first);
		f.controller.onHumanSpeech(true);
		f.controller.interruptNative(true);
		f.controller.receiveNative(second);
		release({ refreshContext: vi.fn(), setActiveToolsByName: vi.fn(), prompt });
		await new Promise((resolve) => setTimeout(resolve, 0));
		expect(prompt).toHaveBeenCalledOnce();
		expect(prompt.mock.calls[0]?.[0]).toContain(`${first}\n${second}`);
		expect(() => f.controller.receiveNative("x".repeat(100_001))).toThrow(
			"sanity bound",
		);
		Reflect.set(f.controller, "pendingSpeech", "p".repeat(1_000_000));
		expect(() => f.controller.receiveNative("overflow")).toThrow(
			"pending input exceeds sanity bound",
		);
		expect(Reflect.get(f.controller, "pendingSpeech")).toHaveLength(1_000_000);
	} finally {
		f.controller.close();
	}
});

it.each([
	["barge-in", false],
	["new-input", false],
	["barge-in", true],
	["new-input", true],
] as const)(
	"preserves unadmitted input exactly once on %s, admitted=%s",
	async (cause, admitted) => {
		const f = fixture();
		let rejectFirst: ((error: Error) => void) | undefined;
		const first = {
			refreshContext: vi.fn(),
			setActiveToolsByName: vi.fn(),
			dispose: vi.fn(),
			abort: vi.fn(async () => {
				rejectFirst?.(new Error("cancelled"));
			}),
			prompt: vi.fn((prompt: string) => {
				if (admitted) {
					(f.controller as any).onChildEvent(
						{
							type: "message_end",
							message: {
								role: "user",
								content: [{ type: "text", text: prompt }],
							},
						},
						first,
						(f.controller as any).generation,
					);
					(f.controller as any).history.sessionManager.appendMessage({
						role: "user",
						content: prompt,
						timestamp: Date.now(),
					});
				}
				return new Promise<void>((_resolve, reject) => {
					rejectFirst = reject;
				});
			}),
		};
		const replacement = {
			refreshContext: vi.fn(),
			setActiveToolsByName: vi.fn(),
			prompt: vi.fn(async (_prompt: string) => {}),
			abort: vi.fn(async () => {}),
			dispose: vi.fn(),
		};
		let starts = 0;
		(f.controller as any).ensureChild = async () => {
			const child = starts++ === 0 ? first : replacement;
			(f.controller as any).child = child;
			return child;
		};
		try {
			f.controller.receiveNative("original-monologue");
			await new Promise((resolve) => setTimeout(resolve, 0));
			if (cause === "barge-in") {
				f.controller.onHumanSpeech(true);
				f.controller.interruptNative(true);
			}
			f.controller.receiveNative("continuation");
			await new Promise((resolve) => setTimeout(resolve, 0));
			expect(replacement.prompt).toHaveBeenCalledOnce();
			const prompt = replacement.prompt.mock.calls[0]?.[0] ?? "";
			expect(prompt).toContain("continuation");
			if (admitted) expect(prompt).not.toContain("original-monologue");
			else expect(prompt).toContain("original-monologue\ncontinuation");
		} finally {
			f.controller.close();
		}
	},
);

it("explicit interruption still discards pending input", () => {
	const f = fixture();
	(f.controller as any).ensureChild = () => new Promise(() => {});
	try {
		f.controller.receiveNative("discard on explicit stop");
		f.controller.interruptNative();
		expect((f.controller as any).pendingSpeech).toBe("");
	} finally {
		f.controller.close();
	}
});

it("respects a different history root for the same executor identity, including after stop", async () => {
	const f = fixture();
	const active: unknown = Reflect.get(f.controller, "history");
	if (!(active instanceof VoiceHistory))
		throw new Error("Missing native history");
	active.update("a", "assistant", "Root A live reply");
	const directory = join(f.root, "other-history");
	const archived = new VoiceHistory(f.root, directory, "main");
	archived.sessionManager.appendMessage({
		role: "user",
		content: "hello",
		timestamp: Date.now(),
	});
	archived.update("b", "assistant", "Root B saved reply");
	const scope = {
		cwd: f.root,
		historyDirectory: directory,
		mainSessionId: "main",
	};
	expect(await f.controller.loadNativeHistory(scope)).toMatchObject([
		{ text: "Root B saved reply" },
	]);
	f.controller.endNative();
	expect(await f.controller.loadNativeHistory(scope)).toMatchObject([
		{ text: "Root B saved reply" },
	]);
	f.controller.close();
});

it("reloads native voice without a browser route", () => {
	const f = fixture();
	f.controller.endNative();
	expect(() =>
		f.controller.beginNative(f.ctx as never, {
			modelSetting: "auto",
			historyDirectory: f.root,
		}),
	).not.toThrow();
	expect((f.controller as any).open).toBeUndefined();
	expect((f.controller as any).hasOpenedBrowser).toBeUndefined();
	f.controller.dispose();
});

it("retires native voice despite an interrupted-history persistence failure", async () => {
	const f = fixture();
	(f.controller as any).ensureChild = async () => ({
		refreshContext: vi.fn(),
		setActiveToolsByName: vi.fn(),
		prompt: async () => {
			(f.controller as any).consumeStructuredDelta(
				(f.controller as any).activeTurn,
				JSON.stringify({ heard: "hello", reply: "Generated", hotwords: [] }),
			);
			await new Promise<void>(() => undefined);
		},
	});
	f.controller.receiveNative("hello");
	await new Promise((resolve) => setTimeout(resolve, 0));
	const write = vi
		.spyOn(VoiceHistory.prototype, "update")
		.mockImplementation(() => {
			throw new Error("disk full");
		});
	try {
		expect(() => f.controller.endNative()).not.toThrow();
		expect(f.controller.nativeSnapshot()).toMatchObject({
			status: "unavailable",
			error: expect.stringContaining("could not be saved"),
		});
	} finally {
		write.mockRestore();
		f.controller.close();
	}
});

it("streams through existing reply machinery, tracks only actual playback, disables notification tools", async () => {
	const f = fixture();
	const enabled = vi.fn();
	const child = {
		refreshContext: vi.fn(),
		setActiveToolsByName: enabled,
		compact: vi.fn(),
		prompt: vi.fn(async () => {
			(f.controller as any).consumeStructuredDelta(
				(f.controller as any).activeTurn,
				JSON.stringify({
					heard: "hello",
					reply: "Hello, more words.",
					hotwords: [],
				}),
			);
			const id = (f.controller as any).activeTurn.assistantId;
			f.controller.markNativePlayback(id, "Hello");
		}),
	};
	(f.controller as any).ensureChild = async () => child;
	f.controller.receiveNative("hello");
	await new Promise((resolve) => setTimeout(resolve, 0));
	const reply = f.controller
		.nativeHistory()
		.find((entry) => entry.role === "assistant");
	expect(reply).toMatchObject({
		text: "Hello, more words.",
		playedText: "Hello",
		playback: "partial",
	});
	expect(enabled.mock.calls[0]?.[0]).toContain("voice_executor_dispatch");
	f.controller.interruptNative();
	expect(
		f.controller.nativeHistory().find((entry) => entry.id === reply?.id)
			?.interrupted,
	).toBe(true);
	(f.controller as any).pendingResults.push({ text: "settled result" });
	f.controller.onEmptySpeechBoundary();
	await new Promise((resolve) => setTimeout(resolve, 0));
	expect(enabled.mock.calls.at(-1)?.[0]).toEqual([]);
	expect(f.editor).not.toHaveBeenCalled();
	f.controller.dispose();
});

it("queues unrelated dispatches, keeps receipts queued until matching lifecycle, preserves waiting jobs", async () => {
	const f = fixture();
	const first = await f.tool("dispatch").execute("1", { text: "one" });
	await f.tool("dispatch").execute("2", { text: "two" });
	expect(f.send).toHaveBeenCalledTimes(2);
	expect(f.send.mock.calls[0]?.[1]).toEqual({ deliverAs: "followUp" });
	expect(
		(f.controller as any).executor.entries.map((entry: any) => entry.status),
	).toEqual(["queued", "queued"]);
	f.controller.onExecutorMessageStart({
		role: "user",
		content: f.send.mock.calls[0]?.[0],
	});
	expect(
		(f.controller as any).executorRequests.get(first.details.id).status,
	).toBe("running");
	f.controller.onExecutorMessageEnd({
		role: "assistant",
		stopReason: "stop",
		content: "done",
	});
	(f.controller as any).boundaryReady = false;
	f.controller.onExecutorSettled();
	expect((f.controller as any).executorRequests.size).toBe(1);
	expect(f.editor).not.toHaveBeenCalled();
	f.controller.dispose();
});

it("explicit controls apply to typed work; settlement notifications are bounded", async () => {
	const f = fixture();
	f.controller.onExecutorMessageStart({ role: "user", content: "typed task" });
	expect(
		(await f.tool("steer").execute("s", { text: "change typed task" })).details
			.accepted,
	).toBe(true);
	expect(f.send.mock.calls.at(-1)?.[1]).toEqual({ deliverAs: "steer" });
	expect((await f.tool("cancel").execute("c", {})).details.scope).toBe(
		"session",
	);
	expect(f.abort).toHaveBeenCalledOnce();
	(f.controller as any).boundaryReady = false;
	for (let i = 0; i < 40; i++) {
		f.controller.onExecutorMessageStart({ role: "user", content: "typed" });
		f.controller.onExecutorMessageEnd({
			role: "assistant",
			stopReason: "stop",
			content: "typed result",
		});
		f.controller.onExecutorSettled();
	}
	expect((f.controller as any).pendingResults.length).toBeLessThanOrEqual(24);
	expect((f.controller as any).pendingResults.at(-1).text).toContain(
		"typed result",
	);
	f.controller.dispose();
});

it("derives cues from matching work, waiting input, and pending child initialization", async () => {
	const f = fixture();
	f.controller.onExecutorStart();
	expect(f.controller.nativeSnapshot().cueState).toBe("listening");
	const receipt = await f
		.tool("dispatch")
		.execute("dispatch", { text: "work" });
	expect(f.controller.nativeSnapshot().cueState).toBe("listening");
	f.controller.onExecutorMessageStart({
		role: "user",
		content: f.send.mock.calls[0]?.[0],
	});
	expect(f.controller.nativeSnapshot().cueState).toBe("working");
	f.controller.onExecutorPromptStart("Need confirmation");
	expect(f.controller.nativeSnapshot().cueState).toBe("listening");
	f.controller.onExecutorPromptEnd();
	expect(f.controller.nativeSnapshot().cueState).toBe("working");
	let release: (child: unknown) => void = () => undefined;
	(f.controller as any).ensureChild = () =>
		new Promise((resolve) => {
			release = resolve;
		});
	f.controller.receiveNative("hello");
	await new Promise((resolve) => setTimeout(resolve, 0));
	expect(f.controller.nativeSnapshot().cueState).toBe("thinking");
	f.controller.interruptNative();
	release({ prompt: vi.fn() });
	void receipt;
	f.controller.dispose();
});

it("fences a pending child initialization after session switch", async () => {
	const f = fixture();
	let release: (child: unknown) => void = () => undefined;
	const pending = new Promise((resolve) => {
		release = resolve;
	});
	(f.controller as any).ensureChild = () => pending;
	const prompt = vi.fn();
	f.controller.receiveNative("late initialization");
	f.controller.onExecutorSessionSwitch();
	release({ prompt });
	await new Promise((resolve) => setTimeout(resolve, 0));
	expect(prompt).not.toHaveBeenCalled();
	expect(f.send).not.toHaveBeenCalled();
	f.controller.dispose();
});

it.each(["hangup", "switch"])(
	"fences old controls after %s without aborting executor",
	async (action) => {
		const f = fixture();
		if (action === "switch") f.controller.onExecutorSessionSwitch();
		else f.controller.endNative();
		expect(
			(await f.tool("dispatch").execute("stale", { text: "must not run" }))
				.details.accepted,
		).toBe(false);
		expect(f.send).not.toHaveBeenCalled();
		expect(f.abort).not.toHaveBeenCalled();
		expect(() => f.controller.receiveNative("late speech")).toThrow();
		f.controller.dispose();
	},
);

it("blocks executor controls from notification turns and disables native bridge claiming", async () => {
	const f = fixture();
	const claims = vi.fn();
	f.events.on("pi-ext:ask:claim", claims);
	f.events.emit("pi-ext:ask:request", {
		version: 1,
		id: "q",
		sessionId: "main",
		toolCallId: "tool",
		questions: [
			{
				key: "db",
				header: "DB",
				question: "Which database?",
				multiSelect: false,
				options: [
					{ label: "SQLite", description: "local" },
					{ label: "Postgres", description: "server" },
				],
			},
		],
	});
	expect(claims).not.toHaveBeenCalled();
	(f.controller as any).activeTurn = { kind: "executor-result" };
	for (const name of ["dispatch", "steer", "cancel"])
		expect(
			(await f.tool(name).execute("n", { text: "no" })).details.accepted,
		).toBe(false);
	expect(f.send).not.toHaveBeenCalled();
	(f.controller as any).activeTurn = undefined;
	f.controller.dispose();
});

it("rebuilds a mechanical head from task/followups, pending questions, recent users and settled results", async () => {
	const f = fixture();
	await f.tool("dispatch").execute("one", { text: "Fix captions" });
	f.controller.onExecutorMessageStart({
		role: "user",
		content: f.send.mock.calls[0]?.[0],
	});
	await f.tool("steer").execute("two", { text: "Keep the call alive" });
	f.controller.onExecutorPromptStart("Approve caption change?");
	const history = Reflect.get(f.controller, "history") as VoiceHistory;
	history.update("latest-user", "user", "Do not restart my call.");
	Reflect.set(f.controller, "executorHistory", [
		{
			id: "settled",
			timestamp: "2026-10-21T12:00:00Z",
			role: "assistant",
			text: "Earlier checks passed.",
			outcome: "completed",
		},
	]);
	const child = { refreshContext: vi.fn() };
	Reflect.get(f.controller, "prepareChildContext").call(f.controller, child);
	const projected = JSON.stringify(
		history.sessionManager.buildSessionContext(),
	);
	expect(projected).toContain("Fix captions");
	expect(projected).toContain("Keep the call alive");
	expect(projected).toContain("Approve caption change?");
	expect(projected).toContain("Do not restart my call.");
	expect(projected).toContain("Earlier checks passed.");
	expect(child.refreshContext).toHaveBeenCalledOnce();
	f.controller.onExecutorPromptEnd();
	Reflect.get(f.controller, "prepareChildContext").call(f.controller, child);
	expect(
		JSON.stringify(history.sessionManager.buildSessionContext()),
	).not.toContain("Approve caption change?");
	f.controller.endNative();
});

it("recall respects SDK retry omissions and labels failed/aborted outcomes without replaying partial assertions", async () => {
	const f = fixture();
	const manager = SessionManager.inMemory();
	const answer = (text: string, stopReason: "stop" | "error" | "aborted") => ({
		role: "assistant" as const,
		api: "openai-responses" as const,
		provider: "test",
		model: "test",
		timestamp: 1,
		content: [{ type: "text" as const, text }],
		stopReason,
		usage: {
			input: 0,
			output: 0,
			cacheRead: 0,
			cacheWrite: 0,
			totalTokens: 0,
			cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
		},
	});
	manager.appendMessage({ role: "user", content: "Check", timestamp: 1 });
	const failed = manager.appendMessage(
		answer("unverified failure assertion", "error"),
	);
	manager.appendContextEdit(failed, null);
	const success = manager.appendMessage(answer("Verified result.", "stop"));
	const aborted = manager.appendMessage(
		answer("unverified interrupted assertion", "aborted"),
	);
	const tool = manager.appendMessage({
		role: "toolResult",
		toolCallId: "failed-read",
		toolName: "read",
		isError: true,
		content: [{ type: "text", text: "Read failed." }],
		timestamp: 1,
	});
	f.ctx.sessionManager.getBranch = () => manager.getBranch();
	f.ctx.sessionManager.buildSessionProjection = () =>
		manager.buildSessionProjection();
	f.controller.onExecutorSettled();
	const query = Reflect.get(f.controller, "tools")
		.call(f.controller)
		.find((entry: any) => entry.name === "voice_history_query");
	const result = (await query.execute("recall", { source: "executor" }))
		.details;
	expect(result.entries.map((entry: any) => entry.id)).not.toContain(failed);
	expect(
		result.entries.find((entry: any) => entry.id === success)?.outcome,
	).toBe("completed");
	expect(
		result.entries.find((entry: any) => entry.id === aborted)?.outcome,
	).toBe("aborted");
	expect(result.entries.find((entry: any) => entry.id === tool)?.outcome).toBe(
		"error",
	);
	expect(JSON.stringify(result)).not.toContain("unverified");
	expect(manager.getEntry(failed)).toBeDefined();
	f.controller.endNative();
});

it("history queries admit settled summaries/final tool results, not streaming assistant text or execution logs", async () => {
	const f = fixture();
	const query = Reflect.get(f.controller, "tools")
		.call(f.controller)
		.find((tool: any) => tool.name === "voice_history_query");
	f.ctx.sessionManager.getBranch = () =>
		[
			{
				id: "stream",
				type: "message",
				timestamp: "2026-10-21T12:00:00Z",
				message: {
					role: "assistant",
					stopReason: "pending",
					content: [{ type: "text", text: "unfinished words" }],
				},
			},
			{
				id: "log",
				type: "custom",
				customType: "tool-log",
				data: "raw execution log",
			},
			{
				id: "tool-result",
				type: "message",
				timestamp: "2026-10-21T12:01:00Z",
				message: {
					role: "toolResult",
					toolName: "read",
					content: [{ type: "text", text: "checked caption config" }],
				},
			},
			{
				id: "summary",
				type: "message",
				timestamp: "2026-10-21T12:02:00Z",
				message: {
					role: "assistant",
					stopReason: "stop",
					content: [{ type: "text", text: "caption config checked" }],
				},
			},
		].map((entry, index, entries) => ({
			...entry,
			parentId: entries[index - 1]?.id ?? null,
		}));
	f.controller.onExecutorMessageUpdate();
	expect(
		(await query.execute("before", { source: "executor" })).details.entries,
	).toEqual([]);
	f.controller.onExecutorSettled();
	const after = await query.execute("after", { source: "executor" });
	expect(after.details.entries.map((entry: any) => entry.id)).toEqual([
		"summary",
		"tool-result",
	]);
	expect(JSON.stringify(after)).not.toContain("unfinished words");
	expect(JSON.stringify(after)).not.toContain("raw execution log");
	f.controller.onExecutorSessionSwitch();
	expect(
		(await query.execute("stale", { source: "executor" })).details.accepted,
	).toBe(false);
});