Luigit
repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by admin

extensions/ephemlets/__tests__/contract.test.ts

Raw
import { readdir, readFile } from "node:fs/promises";
import { join } from "node:path";
import { fileURLToPath } from "node:url";
import {
	fauxAssistantMessage,
	fauxToolCall,
	getCurrentSystemPrompt,
	getCurrentTools,
} from "@earendil-works/pi-ai";
import { convertResponsesTools } from "@earendil-works/pi-ai/api/openai-responses-shared";
import {
	type AgentToolResult,
	createAgentSession,
	DefaultResourceLoader,
	type ExtensionUIContext,
	initTheme,
	SessionManager,
	SettingsManager,
} from "@earendil-works/pi-coding-agent";
import type { Component, TUI } from "@earendil-works/pi-tui";
import { Value } from "typebox/value";
import { afterEach, describe, expect, it, vi } from "vitest";
import {
	createPiSession,
	type PiSession,
} from "../../../test/fixture/create-pi-session.ts";
import type { EphemletParams } from "../runtime.ts";
import { icon } from "../src/look.ts";
import { REMOVED_INTERACTIVE_NOTICE } from "../src/store.ts";
import { plainTheme } from "./theme.ts";

let fixture: PiSession | undefined;
afterEach(async () => {
	await fixture?.dispose();
	fixture = undefined;
});
async function setup(debug = false) {
	fixture = await createPiSession({
		extensionPaths: [fileURLToPath(new URL("../index.ts", import.meta.url))],
		...(debug ? { env: { PI_EPHEMLETS_DEBUG: "1" } } : {}),
	});
	expect(fixture.errors).toEqual([]);
	await fixture.session.bindExtensions({
		mode: "tui",
		uiContext: {
			...fixture.session.extensionRunner.getUIContext(),
			custom: async () => undefined,
		} as ExtensionUIContext,
	});
	expect(fixture.session.getActiveToolNames()).toContain("ephemlet");
	const definition = fixture.extensions[0]!.tools.get("ephemlet")!.definition;
	expect(definition.annotations?.readOnlyHint).toBe(false);
	const session = fixture.session;
	const call = async (
		params: EphemletParams,
	): Promise<AgentToolResult<unknown>> =>
		definition.execute(
			"ephemlet-test",
			params,
			undefined,
			undefined,
			session.extensionRunner.createToolContext("ephemlet-test", undefined),
		);
	return { fixture, call, session, definition };
}
function data(result: AgentToolResult<unknown>): Record<string, unknown> {
	const content = result.content[0];
	if (content?.type !== "text") throw new Error("Missing text result");
	return JSON.parse(content.text) as Record<string, unknown>;
}

describe("ephemlets public Pi runtime", () => {
	it("declares ephemlet to the main model and handles a real tool turn", async () => {
		const { call, session, fixture } = await setup();
		fixture.setResponses([
			(context) => {
				expect(
					getCurrentTools(context.messages).map((tool) => tool.name),
				).toContain("ephemlet");
				return fauxAssistantMessage(
					fauxToolCall("ephemlet", {
						action: "put",
						title: "Progress",
						purpose: "Track actual work",
						source: "# Verified progress",
					}),
					{ stopReason: "toolUse" },
				);
			},
			fauxAssistantMessage("Report created"),
		]);
		await session.prompt("Create a living progress report");
		expect(data(await call({ action: "list" }))["ephemlets"]).toHaveLength(1);
	});
	it("declares only Markdown reports and declarative fields to providers", async () => {
		const { definition } = await setup();
		const declaration = convertResponsesTools([definition])[0]!;
		if (declaration.type !== "function")
			throw new Error("Expected function tool");
		const schema = declaration.parameters as {
			properties: Record<string, { anyOf?: { const?: string }[] }>;
		};
		expect(Object.keys(schema.properties).sort()).toEqual([
			"action",
			"expectedRevision",
			"fields",
			"id",
			"include",
			"purpose",
			"source",
			"timeoutMs",
			"title",
			"waitFor",
		]);
		expect(
			schema.properties["action"]?.anyOf?.map((item) => item.const),
		).toEqual(["put", "list", "get", "delete", "show", "hide", "wait"]);
		for (const params of [
			{ action: "put", title: "Report", source: "# Report" },
			{ action: "get", id: "x", include: [] },
			{ action: "get", id: "x", include: ["source", "view", "answers"] },
			{ action: "wait", id: "x", waitFor: ["why"], timeoutMs: 1000 },
			{
				action: "put",
				title: "Ask",
				source: "# Ask",
				fields: [{ id: "why", type: "text", label: "Why?", placeholder: "…" }],
			},
			{
				action: "put",
				title: "Plan",
				source: "# Plan",
				fields: [
					{
						id: "plan",
						type: "checklist",
						items: [{ id: "a", label: "A", checked: true }],
					},
				],
			},
		])
			expect(Value.Check(definition.parameters, params)).toBe(true);
		for (const params of [
			{ action: "build", brief: "x" },
			{
				action: "put",
				fields: [{ id: "f", type: "code", items: [{ id: "a", label: "A" }] }],
			},
			{
				action: "put",
				fields: [{ id: "f", type: "checklist", items: [] }],
			},
			{ action: "get", id: "x", include: ["state"] },
		])
			expect(Value.Check(definition.parameters, params)).toBe(false);
	});
	it("uses native sequential execution, structured outputs, and interactive exposure", async () => {
		const { call, definition } = await setup();
		expect(definition.exposure).toBe("model-only");
		expect(definition.executionMode).toBe("sequential");
		expect(definition.constrainedSampling).toEqual({
			type: "json_schema",
			strict: "prefer",
		});
		expect(definition.renderCall).toBeTypeOf("function");
		expect(definition.renderResult).toBeTypeOf("function");
		const checked = async (params: EphemletParams) => {
			const result = await call(params);
			expect(result.structuredContent).toEqual(data(result));
			expect(
				Value.Check(definition.outputSchema!, result.structuredContent),
			).toBe(true);
			return data(result);
		};
		const created = await checked({
			action: "put",
			title: "Report",
			purpose: "Track",
			source: "# Report",
		});
		const id = created["id"] as string;
		await checked({ action: "list" });
		await checked({ action: "get", id });
		await checked({ action: "get", id, include: [] });
		await checked({ action: "get", id, include: ["source", "view"] });
		await checked({ action: "get", id, include: ["answers"] });
		await checked({ action: "hide" });
		await checked({ action: "show", id });
		await checked({ action: "delete", id });
	});
	it("defaults purpose to title on creation and keeps it on update", async () => {
		const { call } = await setup();
		const created = data(
			await call({ action: "put", title: "Report", source: "# One" }),
		);
		expect(created).toMatchObject({ title: "Report", purpose: "Report" });
		const id = created["id"] as string;
		expect(
			data(
				await call({
					action: "put",
					title: "Blank purpose",
					purpose: " ",
					source: "# Two",
				}),
			),
		).toMatchObject({ purpose: "Blank purpose" });
		await call({
			action: "put",
			id,
			expectedRevision: 1,
			purpose: "Specific",
			source: "# Updated",
		});
		const renamed = data(
			await call({ action: "put", id, expectedRevision: 2, title: "Renamed" }),
		);
		expect(renamed).toMatchObject({
			title: "Renamed",
			purpose: "Specific",
			revision: 3,
		});
		expect(
			data(await call({ action: "get", id, include: ["source"] }))["source"],
		).toBe("# Updated");
		await expect(call({ action: "put", source: "x" })).rejects.toThrow(
			"title is required",
		);
		await expect(call({ action: "put", title: "Empty" })).rejects.toThrow(
			"source is required",
		);
		await expect(
			call({ action: "put", id, title: "Stale", source: "x" }),
		).rejects.toThrow("expectedRevision");
	});
	it("bounds default data reads and keeps persisted content out of automatic model context", async () => {
		const { call, session, fixture } = await setup();
		const oldSource = `private-original${"x".repeat(60000)}`;
		const newSource = `private-source${"y".repeat(60000)}`;
		const created = data(
			await call({
				action: "put",
				title: "Bounded",
				purpose: "p".repeat(4096),
				source: oldSource,
			}),
		);
		const id = created["id"] as string;
		await call({ action: "put", id, expectedRevision: 1, source: newSource });
		const summary = data(await call({ action: "get", id }));
		expect(summary).toMatchObject({ id, revision: 2 });
		expect(summary).not.toHaveProperty("source");
		expect(summary["purpose"]).toBe(`${"p".repeat(159)}…`);
		expect(JSON.stringify(summary).length).toBeLessThan(1000);
		const list = data(await call({ action: "list" }));
		expect(list).toEqual({ ephemlets: [summary] });
		expect(
			data(await call({ action: "get", id, include: ["source"] }))["source"],
		).toBe(newSource);
		fixture.setResponses([
			(context) => {
				const prompt = getCurrentSystemPrompt(context.messages);
				expect(prompt).toContain("You cannot see the panel");
				expect(prompt).toContain("only the highest revision counts");
				expect(prompt).toContain("say so in chat");
				const transcript = JSON.stringify(context.messages);
				for (const marker of ["private-original", "private-source"])
					expect(transcript).not.toContain(marker);
				return fauxAssistantMessage("OK");
			},
		]);
		await session.prompt("Continue the task");
	});
	it("hides tools and leaves session data untouched in non-TUI modes", async () => {
		const { call, fixture, session } = await setup();
		await call({
			action: "put",
			title: "Report",
			purpose: "Track",
			source: "# Report",
		});
		const before = session.sessionManager.getBranch().length;
		await session.bindExtensions({ mode: "print" });
		expect(
			fixture.extensions[0]!.tools.get("ephemlet")!.definition.exposure,
		).toBe("hidden");
		expect(session.getActiveToolNames()).not.toContain("ephemlet");
		const hidden = fixture.extensions[0]!.tools.get("ephemlet")!.definition;
		await expect(
			hidden.execute(
				"hidden",
				{ action: "list" },
				undefined,
				undefined,
				session.extensionRunner.createToolContext("hidden", undefined),
			),
		).rejects.toThrow("TUI");
		expect(session.sessionManager.getBranch().length).toBe(before);
	});
	it("registers tool/commands and persists reports through restore and deletion", async () => {
		const { call, session, fixture } = await setup();
		expect(fixture.extensions[0]!.commands.has("ephemlets")).toBe(true);
		const first = data(
			await call({
				action: "put",
				title: "Progress",
				purpose: "Track original request",
				source: "# Progress\n- Attempted\n- Verified",
			}),
		);
		const id = first["id"] as string;
		await call({ action: "hide" });
		await session.extensionRunner.emit({
			type: "session_start",
			reason: "resume",
		});
		expect(
			data(await call({ action: "get", id, include: ["source"] }))["source"],
		).toContain("Verified");
		expect(data(await call({ action: "list" }))["ephemlets"]).toHaveLength(1);
		await call({ action: "delete", id });
		await session.extensionRunner.emit({
			type: "session_start",
			reason: "resume",
		});
		expect(data(await call({ action: "list" }))["ephemlets"]).toEqual([]);
	});
	it("restores reports and legacy interactive records into a new Pi session", async () => {
		const { call, fixture } = await setup();
		const created = data(
			await call({
				action: "put",
				title: "Report",
				purpose: "Persist",
				source: "# Persisted",
			}),
		);
		await call({ action: "hide" });
		const manager = SessionManager.create(
			fixture.cwd,
			join(fixture.cwd, "saved-sessions"),
		);
		manager.appendMessage({
			role: "user",
			content: "Persistence fixture",
			timestamp: Date.now(),
		});
		for (const entry of fixture.session.sessionManager.getBranch())
			if (entry.type === "custom")
				manager.appendCustomEntry(entry.customType, entry.data);
		// Shape written by releases that still supported interactive ephemlets.
		manager.appendCustomEntry("ephemlets", {
			op: "put",
			ephemlet: {
				id: "legacy-native",
				title: "Counter",
				purpose: "Old native panel",
				kind: "interactive",
				revision: 2,
				status: "ready",
				source: "export default () => component",
				state: 7,
				error: null,
				jobId: null,
			},
		});
		manager.appendCustomEntry("ephemlets", {
			op: "state",
			id: "legacy-native",
			revision: 2,
			state: 8,
		});
		const path = manager.getSessionFile();
		if (!path) throw new Error("No persisted file");
		const settings = SettingsManager.inMemory({});
		const loader = new DefaultResourceLoader({
			cwd: fixture.cwd,
			agentDir: fixture.agentDir,
			settingsManager: settings,
			noExtensions: true,
			noSkills: true,
			noThemes: true,
			noPromptTemplates: true,
			noContextFiles: true,
			additionalExtensionPaths: [
				fileURLToPath(new URL("../index.ts", import.meta.url)),
			],
		});
		await loader.reload();
		const model = fixture.session.model;
		if (!model) throw new Error("Fixture model is unavailable");
		const { session: reopened } = await createAgentSession({
			cwd: fixture.cwd,
			modelRuntime: fixture.session.modelRuntime,
			model,
			settingsManager: settings,
			resourceLoader: loader,
			sessionManager: SessionManager.open(path),
		});
		try {
			await reopened.bindExtensions({
				mode: "tui",
				uiContext: {
					...fixture.session.extensionRunner.getUIContext(),
					custom: async () => undefined,
				} as ExtensionUIContext,
			});
			const tool = loader
				.getExtensions()
				.extensions[0]!.tools.get("ephemlet")!.definition;
			const get = async (id: unknown) =>
				data(
					await tool.execute(
						"restored",
						{ action: "get", id, include: ["source"] },
						undefined,
						undefined,
						reopened.extensionRunner.createToolContext("restored", undefined),
					),
				);
			expect(await get(created["id"])).toMatchObject({
				source: "# Persisted",
				revision: 1,
			});
			expect(await get("legacy-native")).toEqual({
				id: "legacy-native",
				title: "Counter",
				purpose: "Old native panel",
				revision: 2,
				source: REMOVED_INTERACTIVE_NOTICE,
			});
			const persisted = await readFile(path, "utf8");
			expect(persisted).toContain("export default () => component");
		} finally {
			await reopened.extensionRunner.emit({
				type: "session_shutdown",
				reason: "quit",
			});
			reopened.dispose();
		}
	});
	it("Save queues a snapshot follow-up without interrupting ongoing main-agent work", async () => {
		const { call, session, fixture } = await setup();
		let panel: Component | undefined;
		const tui = {
			terminal: { columns: 120, rows: 32 },
			requestRender() {},
			showOverlay(component: Component) {
				panel = component;
				return { hide() {}, setHidden() {}, focus() {} };
			},
		} as unknown as TUI;
		await session.bindExtensions({
			mode: "tui",
			uiContext: {
				...session.extensionRunner.getUIContext(),
				setWidget(_key: string, factory: unknown) {
					if (typeof factory === "function") factory(tui, plainTheme);
				},
			} as ExtensionUIContext,
		});
		const created = data(
			await call({
				action: "put",
				title: "Report",
				purpose: "Persist",
				source: "# Saved revision",
			}),
		);
		const id = created["id"] as string;
		await call({ action: "show", id });
		let release = () => {};
		const gate = new Promise<void>((resolve) => {
			release = resolve;
		});
		let started = false;
		let savePrompt = "";
		fixture.setResponses([
			async () => {
				started = true;
				await gate;
				return fauxAssistantMessage("Finished original work");
			},
			(context) => {
				const latest = context.messages
					.filter((message) => message.role === "user")
					.at(-1);
				savePrompt = JSON.stringify(latest?.content);
				return fauxAssistantMessage("Saved");
			},
		]);
		const running = session.prompt("Long-running work");
		try {
			await vi.waitFor(() => expect(started).toBe(true));
			if (!panel?.handleInput) throw new Error("Panel not mounted");
			panel.handleInput("\x13");
			await call({
				action: "put",
				id,
				expectedRevision: 1,
				source: "# Later revision",
			});
			expect(fixture.providerState.callCount).toBe(1);
			release();
			await running;
			await vi.waitFor(() =>
				expect(savePrompt).toContain("ephemlet-save-snapshot"),
			);
			expect(savePrompt).toContain("Saved revision");
			expect(savePrompt).not.toContain("Later revision");
		} finally {
			release();
			await running;
		}
	});
	it("lets the human tick checklist items and tells both sides who saw what", async () => {
		const { call, session } = await setup();
		initTheme("dark", false);
		let panel: Component | undefined;
		const tui = {
			terminal: { columns: 120, rows: 32 },
			requestRender() {},
			showOverlay(component: Component) {
				panel = component;
				return { hide() {}, setHidden() {}, focus() {} };
			},
		} as unknown as TUI;
		await session.bindExtensions({
			mode: "tui",
			uiContext: {
				...session.extensionRunner.getUIContext(),
				setWidget(_key: string, factory: unknown) {
					if (typeof factory === "function") factory(tui, plainTheme);
				},
			} as ExtensionUIContext,
		});
		const fields = [
			{
				id: "plan",
				type: "checklist" as const,
				label: "Plan",
				items: [
					{ id: "tests", label: "Write tests", checked: true },
					{ id: "docs", label: "Update docs" },
				],
			},
		];
		const id = data(
			await call({ action: "put", title: "Plan", source: "# Plan", fields }),
		)["id"] as string;
		await call({ action: "show", id });
		if (!panel?.handleInput) throw new Error("Panel not mounted");
		const frame = () => panel?.render(54).join("\n") ?? "";
		expect(frame()).toContain(`${icon("nerd", "checkOn")} Write tests`);
		expect(frame()).toContain(`${icon("nerd", "checkOff")} Update docs`);
		expect(data(await call({ action: "list" }))["ephemlets"]).toEqual([
			expect.not.objectContaining({ unseen: true }),
		]);
		panel.handleInput("\t");
		panel.handleInput(" ");
		expect(frame()).toContain(`${icon("nerd", "checkOff")} Write tests`);
		expect(frame()).toContain(`${icon("nerd", "unread")} unread`);
		expect(data(await call({ action: "list" }))["ephemlets"]).toEqual([
			expect.objectContaining({ unseen: true }),
		]);
		const read = data(await call({ action: "get", id, include: ["answers"] }));
		expect(read).not.toHaveProperty("unseen");
		expect(read["fields"]).toEqual([
			{
				id: "plan",
				type: "checklist",
				label: "Plan",
				items: [
					{ id: "tests", label: "Write tests", checked: false, by: "user" },
					{ id: "docs", label: "Update docs", checked: false, by: "agent" },
				],
			},
		]);
		expect(frame()).toContain(`${icon("nerd", "read")} read`);
		// The agent marking the item done again must not override the human.
		const kept = data(
			await call({
				action: "put",
				id,
				expectedRevision: 1,
				fields: [
					{
						...fields[0]!,
						items: [{ id: "tests", label: "Write tests", checked: true }],
					},
				],
			}),
		);
		expect(kept).not.toHaveProperty("droppedAnswers");
		expect(frame()).toContain(`${icon("nerd", "checkOff")} Write tests`);
		const dropped = data(
			await call({ action: "put", id, expectedRevision: 2, fields: [] }),
		);
		expect(dropped["droppedAnswers"]).toEqual(["plan"]);
		expect(frame()).not.toContain("Write tests");
	});
	it("delivers question answers by mode and marks them read when the model sees them", async () => {
		const { call, session, fixture } = await setup();
		initTheme("dark", false);
		let panel: Component | undefined;
		const notify = vi.fn();
		const tui = {
			terminal: { columns: 120, rows: 32 },
			requestRender() {},
			showOverlay(component: Component) {
				panel = component;
				return { hide() {}, setHidden() {}, focus() {} };
			},
		} as unknown as TUI;
		await session.bindExtensions({
			mode: "tui",
			uiContext: {
				...session.extensionRunner.getUIContext(),
				notify,
				setWidget(_key: string, factory: unknown) {
					if (typeof factory === "function") factory(tui, plainTheme);
				},
			} as ExtensionUIContext,
		});
		const fields = [
			{
				id: "approach",
				type: "choice" as const,
				options: [
					{ id: "a", label: "Alpha" },
					{ id: "b", label: "Beta" },
				],
			},
			{ id: "ship", type: "confirm" as const, label: "Ship it?" },
		];
		const id = data(
			await call({
				action: "put",
				title: "Decide",
				source: "# Decide",
				fields,
			}),
		)["id"] as string;
		await call({ action: "put", id, expectedRevision: 1, source: "# Again" });
		expect(notify.mock.calls).toEqual([
			['Ephemlet "Decide" needs your input · alt+e', "info"],
		]);
		await call({ action: "show", id });
		if (!panel?.handleInput) throw new Error("Panel not mounted");
		const frame = () => panel?.render(54).join("\n") ?? "";
		const contexts: string[] = [];
		fixture.setResponses([
			(context) => {
				contexts.push(JSON.stringify(context.messages));
				return fauxAssistantMessage("Noted the choice");
			},
			(context) => {
				contexts.push(JSON.stringify(context.messages));
				return fauxAssistantMessage("Shipping");
			},
		]);
		// next while idle: held without a turn; only the latest revision joins the next prompt.
		expect(frame()).toContain(`${icon("nerd", "radioOff")} Alpha`);
		panel.handleInput("\t");
		panel.handleInput(" ");
		await new Promise((resolve) => setTimeout(resolve, 1000));
		panel.handleInput("\t");
		panel.handleInput(" ");
		await new Promise((resolve) => setTimeout(resolve, 1000));
		expect(frame()).toContain(`${icon("nerd", "unread")} unread`);
		expect(fixture.providerState.callCount).toBe(0);
		expect(session.messages).not.toContainEqual(
			expect.objectContaining({ customType: "ephemlet-answer" }),
		);
		await session.prompt("Continue");
		expect(contexts[0]?.match(/<ephemlet-answers/g)).toHaveLength(1);
		expect(contexts[0]).toContain('\\"selected\\":[\\"b\\"]');
		expect(contexts[0]).toContain("answer revision 2");
		expect(frame()).toContain(`${icon("nerd", "read")} read`);
		expect(data(await call({ action: "list" }))["ephemlets"]).toEqual([
			expect.not.objectContaining({ unseen: true }),
		]);
		// now: an idle agent gets a new turn.
		panel.handleInput("\t");
		panel.handleInput(" ");
		await vi.waitFor(() => expect(fixture.providerState.callCount).toBe(2), {
			timeout: 3000,
		});
		await vi.waitFor(() =>
			expect(frame()).toContain(`${icon("nerd", "read")} read`),
		);
		expect(contexts[1]).toContain('\\"selected\\":[\\"yes\\"]');
		expect(contexts[1]).toContain("answer revision 3");
		expect(contexts[1]).toContain("only the highest revision is current");
	});
	it("steers a running agent with a next answer before its next model call, not the next prompt", async () => {
		const { call, session, fixture } = await setup();
		initTheme("dark", false);
		let panel: Component | undefined;
		const tui = {
			terminal: { columns: 120, rows: 32 },
			requestRender() {},
			showOverlay(component: Component) {
				panel = component;
				return { hide() {}, setHidden() {}, focus() {} };
			},
		} as unknown as TUI;
		await session.bindExtensions({
			mode: "tui",
			uiContext: {
				...session.extensionRunner.getUIContext(),
				setWidget(_key: string, factory: unknown) {
					if (typeof factory === "function") factory(tui, plainTheme);
				},
			} as ExtensionUIContext,
		});
		const id = data(
			await call({
				action: "put",
				title: "Pick",
				source: "# Pick",
				fields: [
					{
						id: "route",
						type: "choice",
						options: [
							{ id: "a", label: "Alpha" },
							{ id: "b", label: "Beta" },
						],
					},
				],
			}),
		)["id"] as string;
		await call({ action: "show", id });
		let release = () => {};
		const gate = new Promise<void>((resolve) => {
			release = resolve;
		});
		let started = false;
		let steered = "";
		fixture.setResponses([
			async () => {
				started = true;
				await gate;
				return fauxAssistantMessage("Still working");
			},
			(context) => {
				steered = JSON.stringify(context.messages);
				return fauxAssistantMessage("Taking Beta");
			},
		]);
		const running = session.prompt("Long-running work");
		try {
			await vi.waitFor(() => expect(started).toBe(true));
			if (!panel?.handleInput) throw new Error("Panel not mounted");
			panel.render(54);
			panel.handleInput("\x1b[Z");
			panel.handleInput(" ");
			expect(panel.render(54).join("\n")).toContain(
				`${icon("nerd", "radioOn")} Beta`,
			);
			await new Promise((resolve) => setTimeout(resolve, 1200));
			expect(fixture.providerState.callCount).toBe(1);
			expect(panel.render(54).join("\n")).toContain("sent");
			release();
			await running;
			await vi.waitFor(() =>
				expect(steered).toContain('\\"selected\\":[\\"b\\"]'),
			);
			expect(fixture.providerState.callCount).toBe(2);
		} finally {
			release();
			await running;
		}
	});

	it("steers a running agent with a now answer before its next model call", async () => {
		const { call, session, fixture } = await setup();
		initTheme("dark", false);
		let panel: Component | undefined;
		const tui = {
			terminal: { columns: 120, rows: 32 },
			requestRender() {},
			showOverlay(component: Component) {
				panel = component;
				return { hide() {}, setHidden() {}, focus() {} };
			},
		} as unknown as TUI;
		await session.bindExtensions({
			mode: "tui",
			uiContext: {
				...session.extensionRunner.getUIContext(),
				setWidget(_key: string, factory: unknown) {
					if (typeof factory === "function") factory(tui, plainTheme);
				},
			} as ExtensionUIContext,
		});
		const id = data(
			await call({
				action: "put",
				title: "Gate",
				source: "# Gate",
				fields: [{ id: "go", type: "confirm", label: "Proceed?" }],
			}),
		)["id"] as string;
		await call({ action: "show", id });
		let release = () => {};
		const gate = new Promise<void>((resolve) => {
			release = resolve;
		});
		let started = false;
		let steered = "";
		fixture.setResponses([
			async () => {
				started = true;
				await gate;
				return fauxAssistantMessage("Still working");
			},
			(context) => {
				steered = JSON.stringify(context.messages);
				return fauxAssistantMessage("Stopping as asked");
			},
		]);
		const running = session.prompt("Long-running work");
		try {
			await vi.waitFor(() => expect(started).toBe(true));
			if (!panel?.handleInput) throw new Error("Panel not mounted");
			expect(panel.render(54).join("\n")).toMatch(/Proceed\? +needs you/);
			panel.handleInput("\x1b[Z");
			panel.handleInput(" ");
			await new Promise((resolve) => setTimeout(resolve, 1200));
			expect(fixture.providerState.callCount).toBe(1);
			release();
			await running;
			await vi.waitFor(() =>
				expect(steered).toContain('\\"selected\\":[\\"no\\"]'),
			);
		} finally {
			release();
			await running;
		}
	});
	it("wait blocks only the tool call until the human answers and returns the answer", async () => {
		const { call, session, fixture } = await setup();
		initTheme("dark", false);
		let panel: Component | undefined;
		const notify = vi.fn();
		const tui = {
			terminal: { columns: 120, rows: 32 },
			requestRender() {},
			showOverlay(component: Component) {
				panel = component;
				return { hide() {}, setHidden() {}, focus() {} };
			},
		} as unknown as TUI;
		await session.bindExtensions({
			mode: "tui",
			uiContext: {
				...session.extensionRunner.getUIContext(),
				notify,
				setWidget(_key: string, factory: unknown) {
					if (typeof factory === "function") factory(tui, plainTheme);
				},
			} as ExtensionUIContext,
		});
		const id = data(
			await call({
				action: "put",
				title: "Ask",
				source: "# Ask",
				fields: [
					{ id: "why", type: "text", label: "Why?" },
					{ id: "go", type: "confirm", label: "Go?" },
				],
			}),
		)["id"] as string;
		await call({ action: "show", id });
		if (!panel?.handleInput) throw new Error("Panel not mounted");
		const frame = () => panel?.render(54).join("\n") ?? "";
		let settled = false;
		const waiting = call({ action: "wait", id, waitFor: ["why"] }).finally(
			() => {
				settled = true;
			},
		);
		await vi.waitFor(() => expect(frame()).toContain("agent waiting"));
		expect(notify).toHaveBeenCalledWith(
			'Ephemlet "Ask": the agent is waiting for your answer · alt+e',
			"info",
		);
		// Answering another field does not end the wait.
		panel.handleInput("\x1b[Z");
		panel.handleInput(" ");
		await new Promise((resolve) => setTimeout(resolve, 50));
		expect(settled).toBe(false);
		panel.handleInput("\x1b[Z");
		panel.handleInput("\x1b[Z");
		panel.handleInput("\r");
		for (const key of "Faster") panel.handleInput(key);
		panel.handleInput("\r");
		const answered = data(await waiting);
		expect(answered).toMatchObject({ id, timedOut: false });
		expect(answered).not.toHaveProperty("unseen");
		expect(
			data(await call({ action: "wait", id, waitFor: ["why"] })),
		).toMatchObject({ id, timedOut: false });
		expect(answered["fields"]).toEqual([
			expect.objectContaining({ id: "why", type: "text", text: "Faster" }),
			expect.objectContaining({ id: "go", type: "confirm" }),
		]);
		expect(frame()).not.toContain("agent waiting");
		expect(frame()).toContain(`${icon("nerd", "read")} read`);
		const current = data(await call({ action: "get", id }));
		await call({
			action: "put",
			id,
			expectedRevision: current["revision"] as number,
			fields: [
				{ id: "why", type: "text", label: "Why?" },
				{ id: "go", type: "confirm", label: "Go?" },
				{ id: "later", type: "text", label: "Later?" },
			],
		});
		expect(
			data(await call({ action: "wait", id, waitFor: ["why"] })),
		).toMatchObject({ timedOut: false });
		expect(
			data(
				await call({ action: "wait", id, waitFor: ["later"], timeoutMs: 20 }),
			),
		).toMatchObject({ timedOut: true });
		// The answer arrived as the tool result, so no answer message follows.
		await new Promise((resolve) => setTimeout(resolve, 1000));
		expect(fixture.providerState.callCount).toBe(0);
		expect(
			session.sessionManager
				.getBranch()
				.some(
					(entry) =>
						entry.type === "custom_message" &&
						entry.customType === "ephemlet-answer",
				),
		).toBe(false);
	});
	it("wait times out, honours abort, returns at once without open questions and rejects unknown fields", async () => {
		const { call, session, definition } = await setup();
		const id = data(
			await call({
				action: "put",
				title: "Ask",
				source: "# Ask",
				fields: [
					{ id: "go", type: "confirm", label: "Go?" },
					{ id: "plan", type: "checklist", items: [{ id: "a", label: "A" }] },
				],
			}),
		)["id"] as string;
		expect(
			data(await call({ action: "wait", id, timeoutMs: 30 })),
		).toMatchObject({ timedOut: true });
		const controller = new AbortController();
		const aborted = definition.execute(
			"wait-abort",
			{ action: "wait", id },
			controller.signal,
			undefined,
			session.extensionRunner.createToolContext("wait-abort", undefined),
		);
		controller.abort(new Error("Stopped by user"));
		await expect(aborted).rejects.toThrow("Stopped by user");
		await expect(
			call({ action: "wait", id, waitFor: ["missing"] }),
		).rejects.toThrow("Unknown field missing");
		const quiet = data(
			await call({
				action: "put",
				title: "Plan",
				source: "# Plan",
				fields: [
					{ id: "plan", type: "checklist", items: [{ id: "a", label: "A" }] },
				],
			}),
		)["id"] as string;
		expect(data(await call({ action: "wait", id: quiet }))).toMatchObject({
			timedOut: false,
		});
	});
	it("keeps creation quiet and does not steal selection", async () => {
		const { call, session } = await setup();
		const id = data(
			await call({ action: "put", title: "Quiet", source: "# First" }),
		)["id"] as string;
		const lastView = () =>
			session.sessionManager
				.getBranch()
				.filter(
					(entry) =>
						entry.type === "custom" &&
						entry.customType === "ephemlets" &&
						(entry.data as { op?: string })?.op === "view",
				)
				.at(-1);
		expect(lastView()).toMatchObject({
			data: { selected: id, visible: false },
		});
		await call({ action: "show", id });
		await call({ action: "put", title: "Background", source: "Second" });
		expect(lastView()).toMatchObject({ data: { selected: id, visible: true } });
		expect(data(await call({ action: "hide" }))).toMatchObject({
			visible: false,
			selected: id,
		});
	});
	it("respects explicit tool deactivation across TUI rebind", async () => {
		const { session } = await setup();
		session.setActiveToolsByName(
			session.getActiveToolNames().filter((name) => name !== "ephemlet"),
		);
		await session.bindExtensions({
			mode: "tui",
			uiContext: {
				...session.extensionRunner.getUIContext(),
				custom: async () => undefined,
			} as ExtensionUIContext,
		});
		expect(session.getActiveToolNames()).not.toContain("ephemlet");
	});
	it("enabled diagnostics use one owned writer and omit task content", async () => {
		const { call, fixture, session } = await setup(true);
		await call({
			action: "put",
			title: "private-marker-do-not-log",
			purpose: "private-marker-do-not-log",
			source: "private-marker-do-not-log",
		});
		await session.extensionRunner.emit({
			type: "session_shutdown",
			reason: "quit",
		});
		const directory = join(
			fixture.cwd,
			".test-state",
			"pi-ext",
			"debug",
			"ephemlets",
		);
		const files = await readdir(directory);
		expect(files).toHaveLength(1);
		const text = await readFile(join(directory, files[0]!), "utf8");
		const records = text
			.trim()
			.split("\n")
			.map((line) => JSON.parse(line));
		expect(records.map((record) => record.event)).toEqual([
			"session.start",
			"ephemlet.put",
			"session.shutdown",
		]);
		expect(text).not.toContain("private-marker-do-not-log");
	});
	it("has schema-bound diagnostics and defaults to no files", async () => {
		const { call, fixture } = await setup();
		await call({
			action: "put",
			title: "Report",
			purpose: "Report",
			source: "done",
		});
		expect(fixture.errors).toEqual([]);
		await expect(
			readdir(`${fixture.cwd}/.test-state/pi-ext/debug/ephemlets`),
		).rejects.toMatchObject({ code: "ENOENT" });
	});
});