import assert from "node:assert/strict";
import fsDefault, * as fs from "node:fs";
import { syncBuiltinESMExports } from "node:module";
import * as os from "node:os";
import * as path from "node:path";
import { describe, it } from "node:test";
import { Container, TuiAltScreen, TuiMainScreen, visibleWidth, type Component, type TuiMouseEvent, type MarkdownTheme } from "@earendil-works/pi-tui";
import { createEventBus } from "@earendil-works/pi-coding-agent";
import { registerInspector } from "../../src/api/inspectors.ts";
import { getInspectorPlugins, registerInspectorEventListener } from "../../src/inspectors/plugins.ts";
import { EXTERNAL_RUN_REGISTRY_KEY, EXTERNAL_RUN_REGISTRY_VERSION, registerExternalRun } from "../../src/api/external-runs.ts";
import { collectFleetSnapshot, openSubagentFleet, SubagentFleetComponent } from "../../src/tui/fleet.ts";
import { discardRunningForegroundRun, FOREGROUND_OWNER_EXITED_STOP_ERROR, persistForegroundRun, restoreForegroundRunHistory } from "../../src/runs/foreground/foreground-history.ts";
import { resetBootIdForTesting } from "../../src/runs/background/boot-id.ts";
import { currentPidNamespaceScope } from "../../src/runs/background/pid-namespace.ts";
import { inspectSubagentStatus } from "../../src/runs/background/run-status.ts";
import { spawnSync } from "node:child_process";
import { FLEET_STATUS_WIDGET_KEY } from "../../src/tui/fleet-status.ts";
import { setMainThinkingLevelSource } from "../../src/tui/running-tone.ts";
import { registerLivePromptAudit, rewritePromptWithGuidance } from "../../src/runs/foreground/prompt-audit.ts";
import { getArtifactPaths, getArtifactsDir, getProjectArtifactsDir } from "../../src/shared/artifacts.ts";
import type { HerdrClient } from "../../src/inspectors/herdr/client.ts";
import { createHerdrInspectorPlugin } from "../../src/inspectors/herdr/plugin.ts";
import type { ForegroundResumeRun, SubagentState } from "../../src/shared/types.ts";
import { fauxAssistantMessage } from "@earendil-works/pi-ai/providers/faux";
import { createAssistantMessageEventStream } from "@earendil-works/pi-ai";
import { updateActiveRunIndex } from "../../src/runs/background/active-run-index.ts";
import { encodeIndexSegment } from "../../src/runs/background/index-segment.ts";

function clearExternalRuns(): void {
	delete (globalThis as Record<PropertyKey, unknown>)[Symbol.for(EXTERNAL_RUN_REGISTRY_KEY)];
}

function foregroundHistoryFile(resultsDir: string, runId: string): string {
	return path.join(resultsDir, "foreground-history", `${encodeIndexSegment(runId)}.json`);
}

/** Writes a raw record as another Pi process, or an older version, would have left it. */
function writeForegroundHistoryFile(resultsDir: string, run: { runId: string }): void {
	fs.mkdirSync(path.join(resultsDir, "foreground-history"), { recursive: true });
	fs.writeFileSync(foregroundHistoryFile(resultsDir, run.runId), JSON.stringify(run), "utf-8");
}

function savedForegroundRuns(resultsDir: string): Map<string, ForegroundResumeRun> {
	const dir = path.join(resultsDir, "foreground-history");
	const files = fs.existsSync(dir) ? fs.readdirSync(dir) : [];
	return new Map(files.map((name) => JSON.parse(fs.readFileSync(path.join(dir, name), "utf-8")) as ForegroundResumeRun).map((run) => [run.runId, run]));
}

function stateForTest(): SubagentState {
	return {
		baseCwd: process.cwd(),
		currentSessionId: "session-current",
		asyncJobs: new Map(),
		foregroundRuns: new Map(),
		foregroundControls: new Map(),
		lastForegroundControlId: null,
		cleanupTimers: new Map(),
		lastUiContext: null,
		poller: null,
		completionSeen: new Map(),
		watcher: null,
		watcherRestartTimer: null,
		resultFileCoalescer: { schedule: () => false, clear: () => {} },
	};
}

function writeAsyncRun(root: string, input: {
	id: string;
	sessionId?: string;
	state?: "running" | "complete" | "failed";
	mode?: "single" | "parallel" | "workflow";
	lastUpdate?: number;
	startedAt?: number;
	agents?: string[];
	contexts?: Array<"fresh" | "fork">;
	models?: string[];
	thinking?: string[];
	descriptions?: string[];
	output?: string;
	transcript?: Array<Record<string, unknown>>;
}): string {
	const asyncDir = path.join(root, input.id);
	fs.mkdirSync(asyncDir, { recursive: true });
	const agents = input.agents ?? ["worker"];
	if (input.output !== undefined) fs.writeFileSync(path.join(asyncDir, "output-0.log"), input.output, "utf-8");
	const transcriptPath = input.transcript ? path.join(asyncDir, "transcript-0.jsonl") : undefined;
	if (transcriptPath && input.transcript) fs.writeFileSync(transcriptPath, `${input.transcript.map((record) => JSON.stringify(record)).join("\n")}\n`, "utf-8");
	const state = input.state ?? "running";
	fs.writeFileSync(path.join(asyncDir, "status.json"), JSON.stringify({
		runId: input.id,
		sessionId: input.sessionId ?? "session-current",
		mode: input.mode ?? (agents.length > 1 ? "parallel" : "single"),
		state,
		startedAt: input.startedAt ?? 100,
		lastUpdate: input.lastUpdate ?? 200,
		currentStep: 0,
		steps: agents.map((agent, index) => ({
			agent,
			...(input.contexts?.[index] ? { context: input.contexts[index] } : {}),
			...(input.models?.[index] ? { model: input.models[index] } : {}),
			...(input.thinking?.[index] ? { thinking: input.thinking[index] } : {}),
			...(input.descriptions?.[index] ? { description: input.descriptions[index] } : {}),
			status: input.state === "complete" ? "complete" : input.state === "failed" ? "failed" : index === 0 ? "running" : "pending",
			startedAt: 100,
			...(index === 0 ? { sessionFile: path.join(asyncDir, `${agent}.jsonl`), ...(transcriptPath ? { transcriptPath } : {}) } : {}),
		})),
		...(input.output !== undefined ? { outputFile: "output-0.log" } : {}),
	}, null, 2));
	updateActiveRunIndex(asyncDir, state);
	return asyncDir;
}

const theme = {
	fg: (_name: string, text: string) => text,
	bold: (text: string) => text,
	getThinkingBorderColor: (_level: string) => (text: string) => text,
};

const markdownTheme: MarkdownTheme = {
	heading: (text) => text,
	link: (text) => text,
	linkUrl: (text) => text,
	code: (text) => text,
	codeBlock: (text) => text,
	codeBlockBorder: (text) => text,
	quote: (text) => text,
	quoteBorder: (text) => text,
	hr: (text) => text,
	listBullet: (text) => text,
	bold: (text) => text,
	italic: (text) => text,
	strikethrough: (text) => text,
	underline: (text) => text,
};

describe("native subagent fleet", () => {
	it("rewrites an authored prompt from guidance without persistence", async () => {
		const calls: unknown[] = [];
		const streamFn = (_model: never, context: unknown) => {
			calls.push(context);
			const stream = createAssistantMessageEventStream();
			queueMicrotask(() => stream.push({ type: "done", reason: "stop", message: fauxAssistantMessage("Rewritten task", { stopReason: "stop" }) }));
			return stream;
		};
		const model = { provider: "faux", id: "rewrite", api: "faux", input: ["text"], reasoning: false, cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 }, contextWindow: 1000, maxTokens: 100 };
		const ctx = {
			model,
			signal: undefined,
			sessionManager: { getSessionId: () => "fleet-rewrite-session" },
			modelRegistry: {
				async getApiKeyAndHeaders() { return { ok: true as const, apiKey: "test" }; },
				streamSimple: streamFn,
			},
		} as never;
		const rewritten = await rewritePromptWithGuidance({
			ctx,
			authoredTask: "Original task",
			runtimeAdditions: "Runtime context",
			finalEffectivePrompt: "Runtime context\n\nOriginal task",
			guidance: "Make it narrower",
		});
		assert.equal(rewritten, "Rewritten task");
		assert.match(JSON.stringify(calls), /Original task/);
		assert.match(JSON.stringify(calls), /Make it narrower/);
	});

	it("collects current-session foreground and flattened async children", () => {
		const root = fs.mkdtempSync(path.join(os.tmpdir(), "pi-fleet-collect-"));
		try {
			writeAsyncRun(root, { id: "async-current", agents: ["worker", "reviewer"], output: "CURRENT OUTPUT" });
			writeAsyncRun(root, { id: "async-other", sessionId: "session-other", output: "OTHER OUTPUT" });
			const state = stateForTest();
			state.foregroundControls.set("foreground-live", {
				runId: "foreground-live",
				mode: "chain",
				startedAt: 10,
				updatedAt: 30,
				currentAgent: "scout",
				currentIndex: 1,
			});
			state.foregroundRuns!.set("foreground-recent", {
				runId: "foreground-recent",
				mode: "single",
				cwd: root,
				sessionId: "session-current",
				updatedAt: 20,
				children: [{ agent: "planner", index: 0, status: "completed", finalOutput: "PLAN COMPLETE" }],
			});
			state.foregroundRuns!.set("foreground-other", {
				runId: "foreground-other",
				mode: "single",
				cwd: root,
				sessionId: "session-other",
				updatedAt: 20,
				children: [{ agent: "outsider", index: 0, status: "completed" }],
			});

			const snapshot = collectFleetSnapshot(state, { asyncDirRoot: root, resultsDir: path.join(root, "results") });
			assert.deepEqual(snapshot.items.map((item) => item.key), [
				"foreground-active:foreground-live:1",
				"async:async-current:0",
				"async:async-current:1",
				"foreground-recent:foreground-recent:0",
			]);
			assert.equal(snapshot.error, undefined);
		} finally {
			fs.rmSync(root, { recursive: true, force: true });
		}
	});

	it("shows cached external jobs as display-only without reading paths or invoking controls", async () => {
		clearExternalRuns();
		registerExternalRun({
			id: "external-review",
			sessionId: "session-current",
			source: "interactive-shell",
			label: "Dependency review",
			state: "completed",
			startedAt: 100,
			updatedAt: 200,
			currentAction: "Inspecting package metadata",
			preview: "No dependency blockers found.",
			reportPath: "/outside/trusted/roots/report.md",
			transcriptPath: "/outside/trusted/roots/transcript.jsonl",
		});
		const state = stateForTest();
		const snapshot = collectFleetSnapshot(state);
		assert.equal(snapshot.error, undefined);
		assert.deepEqual(snapshot.items.map((item) => ({ key: item.key, kind: item.kind, agent: item.agent })), [{
			key: "external:external-review",
			kind: "external",
			agent: "Dependency review",
		}]);
		let steerCalls = 0;
		let stopCalls = 0;
		let inspectCalls = 0;
		const component = new SubagentFleetComponent(
			{ terminal: { rows: 32, columns: 120 }, requestRender() {} } as never,
			theme as never,
			state,
			() => {},
			{
				refreshMs: 60_000,
				markdownTheme,
				actions: {
					async steer() { steerCalls++; return { text: "unexpected" }; },
					stop() { stopCalls++; return { text: "unexpected" }; },
					async inspect() { inspectCalls++; return { text: "unexpected" }; },
				},
			},
		);
		try {
			const initial = component.render(120).join("\n");
			assert.match(initial, /Fleet inspector.*external display-only/);
			assert.match(initial, /Source: external · display-only/);
			assert.match(initial, /Owner: interactive-shell/);
			assert.match(initial, /Inspecting package metadata/);
			assert.match(initial, /Elapsed: 100ms/);
			assert.match(initial, /No dependency blockers found/);
			assert.match(initial, /Report path: \/outside\/trusted\/roots\/report\.md/);
			assert.match(initial, /Transcript path: \/outside\/trusted\/roots\/transcript\.jsonl/);
			assert.doesNotMatch(initial, /Herdr ·|steer ·|stop ·/);
			component.handleInput("H");
			assert.match(component.render(120).join("\n"), /display-only and have no inspector controls/);
			component.handleInput("s");
			assert.match(component.render(120).join("\n"), /display-only and remain controlled/);
			component.handleInput("D");
			assert.match(component.render(120).join("\n"), /display-only and remain controlled/);
			await new Promise((resolve) => setImmediate(resolve));
			assert.deepEqual({ steerCalls, stopCalls, inspectCalls }, { steerCalls: 0, stopCalls: 0, inspectCalls: 0 });
		} finally {
			component.dispose();
			clearExternalRuns();
		}
	});

	it("keeps running external elapsed time live when endedAt is present", () => {
		clearExternalRuns();
		try {
			const startedAt = Date.now() - 5_000;
			registerExternalRun({
				id: "external-running",
				sessionId: "session-current",
				source: "interactive-shell",
				label: "Running external job",
				state: "running",
				startedAt,
				updatedAt: startedAt + 100,
				endedAt: startedAt + 100,
			});
			const component = new SubagentFleetComponent(
				{ terminal: { rows: 32, columns: 120 }, requestRender() {} } as never,
				theme as never,
				stateForTest(),
				() => {},
				{ refreshMs: 60_000, markdownTheme },
			);
			try {
				const rendered = component.render(120).join("\n");
				assert.match(rendered, /Elapsed: 5\.0s/);
				assert.doesNotMatch(rendered, /Elapsed: 100ms/);
			} finally {
				component.dispose();
			}
		} finally {
			clearExternalRuns();
		}
	});

	it("ignores malformed cached external jobs while rendering Fleet", () => {
		clearExternalRuns();
		const warnings: string[] = [];
		const originalWarn = console.warn;
		console.warn = (message?: unknown) => warnings.push(String(message));
		(globalThis as Record<PropertyKey, unknown>)[Symbol.for(EXTERNAL_RUN_REGISTRY_KEY)] = {
			version: EXTERNAL_RUN_REGISTRY_VERSION,
			runs: new Map<string, unknown>([[
				"session-current\0bad",
				{ id: "bad", sessionId: "session-current", source: "tool", label: "Bad external", state: "running", startedAt: Number.NaN },
			]]),
		};
		const state = stateForTest();
		const component = new SubagentFleetComponent(
			{ terminal: { rows: 28, columns: 100 }, requestRender() {} } as never,
			theme as never,
			state,
			() => {},
			{ refreshMs: 60_000, markdownTheme },
		);
		try {
			const snapshot = collectFleetSnapshot(state);
			assert.equal(snapshot.error, undefined);
			assert.deepEqual(snapshot.items, []);
			assert.match(warnings[0]!, /Removed Malformed cached external run/);
			assert.match(component.render(100).join("\n"), /No current-session Fleet jobs/);
		} finally {
			console.warn = originalWarn;
			component.dispose();
			clearExternalRuns();
		}
	});

	it("does not crash Fleet render when live prompt audit stores a non-string authored task", () => {
		const state = stateForTest();
		const control = {
			runId: "bad-prompt-run",
			sessionId: "session-current",
			mode: "single" as const,
			startedAt: 10,
			updatedAt: 20,
			activeChildren: new Map([[0, { index: 0, agent: "worker", startedAt: 10, updatedAt: 20 }]]),
		};
		state.foregroundControls.set(control.runId, control);
		registerLivePromptAudit(control, 0, { nested: "task payload" } as unknown as string, "effective prompt");
		const component = new SubagentFleetComponent(
			{ terminal: { rows: 28, columns: 100 }, requestRender() {} } as never,
			theme as never,
			state,
			() => {},
			{ refreshMs: 60_000, markdownTheme },
		);
		try {
			assert.doesNotThrow(() => component.render(100));
			const rendered = component.render(100).join("\n");
			assert.doesNotMatch(rendered, /nested|task payload/);
			component.handleInput("p");
			assert.doesNotThrow(() => component.render(100));
			assert.match(component.render(100).join("\n"), /Selected prompt unavailable/);
		} finally {
			component.dispose();
		}
	});

	it("shows live prompt summaries and opens Prompt Audit with the authored prompt visible", async (t) => {
		// Frames are compared whole, and running rows show wall-clock elapsed time.
		t.mock.timers.enable({ apis: ["Date"], now: Date.now() });
		const sentinel = "PROMPT_AUDIT_SENTINEL_1021";
		const secondSentinel = "PROMPT_AUDIT_SECOND_CHILD";
		const state = stateForTest();
		const control = {
			runId: "prompt-run",
			sessionId: "session-current",
			mode: "parallel" as const,
			startedAt: 10,
			updatedAt: 20,
			activeChildren: new Map([
				[0, { index: 0, agent: "worker", startedAt: 10, updatedAt: 20 }],
				[1, { index: 1, agent: "reviewer", startedAt: 11, updatedAt: 21 }],
			]),
		};
		state.foregroundControls.set(control.runId, control);
		registerLivePromptAudit(control, 0, sentinel, `[Read from: context.md]\n\n${sentinel}\n\n---\nRuntime acceptance`, { rerun: { params: { agent: "worker", task: sentinel } } });
		registerLivePromptAudit(control, 1, secondSentinel, secondSentinel);
		assert.doesNotMatch(JSON.stringify(control), new RegExp(sentinel), "live prompts must not enter serializable Fleet state");
		const clipboardWrites: string[] = [];
		const redoCalls: Array<{ runId: string; index: number; guidance: string }> = [];
		const component = new SubagentFleetComponent(
			{ terminal: { rows: 28, columns: 100 }, requestRender() {} } as never,
			theme as never,
			state,
			() => {},
			{
				refreshMs: 60_000,
				markdownTheme,
				copyText: (text) => { clipboardWrites.push(text); },
				actions: {
					async steer() { return { text: "unused" }; },
					stop() { return { text: "unused" }; },
					async redoPrompt(input) {
						redoCalls.push(input);
						return { text: "Prompt redo started redo-run." };
					},
				},
			},
		);
		try {
			const initialRender = component.render(100).join("\n");
			assert.match(initialRender, new RegExp(`Task: ${sentinel}`));
			assert.match(initialRender, /Prompt audit: 2 live · 3 views · p opens/);
			component.handleInput("p");
			assert.doesNotMatch(component.render(100).join("\n"), /Prompt text hidden|Enter reveal|r hide/);
			assert.match(component.render(100).join("\n"), new RegExp(sentinel));
			const pointer: TuiMouseEvent = { type: "click", button: "left", x: 5, y: 4, screenX: 5, screenY: 4, width: 100, height: 23, shift: false, alt: false, ctrl: false };
			const promptFrame = component.render(100);
			assert.equal(component.handleMouse(pointer)?.handled, true);
			assert.deepEqual(component.render(100), promptFrame, "Prompt Audit owns roster clicks");
			component.handleInput("2");
			assert.match(component.render(100).join("\n"), /Read from: context\.md/);
			component.handleInput("3");
			assert.match(component.render(100).join("\n"), /Runtime acceptance/);
			component.handleInput("c");
			await new Promise((resolve) => setImmediate(resolve));
			assert.deepEqual(clipboardWrites, [`[Read from: context.md]\n\n${sentinel}\n\n---\nRuntime acceptance`]);
			assert.match(component.render(100).join("\n"), /Copied visible prompt view/);
			component.handleInput("g");
			const redoFrame = component.render(100);
			assert.equal(component.handleMouse({ ...pointer, type: "wheel", x: 70, wheelDelta: 5 })?.handled, true);
			assert.deepEqual(component.render(100), redoFrame, "redo draft owns wheel input");
			for (const char of "make narrower") component.handleInput(char);
			component.handleInput("\r");
			await new Promise((resolve) => setImmediate(resolve));
			assert.deepEqual(redoCalls, [{ runId: "prompt-run", index: 0, guidance: "make narrower", control }]);
			assert.match(component.render(100).join("\n"), /Prompt redo started redo-run/);
			component.handleInput("j");
			assert.match(component.render(100).join("\n"), /Selected: 2\/2/);
			assert.match(component.render(100).join("\n"), /Agent: reviewer/);
			assert.match(component.render(100).join("\n"), new RegExp(secondSentinel));
			component.handleInput("k");
			component.handleInput("1");
			assert.match(component.render(100).join("\n"), /Selected: 1\/2/);
			assert.match(component.render(100).join("\n"), /Agent: worker/);
			assert.match(component.render(100).join("\n"), new RegExp(sentinel));
			component.handleInput("\x1b");
			assert.match(component.render(100).join("\n"), /Prompt audit: 2 live · 3 views · p opens/);
		} finally {
			component.dispose();
		}
	});

	it("rejects Prompt Audit for a child owned by another session", () => {
		const state = stateForTest();
		const control = {
			runId: "other-run",
			sessionId: "session-other",
			mode: "single" as const,
			startedAt: 10,
			updatedAt: 20,
			activeChildren: new Map([[0, { index: 0, agent: "worker", startedAt: 10, updatedAt: 20 }]]),
		};
		state.foregroundControls.set(control.runId, control);
		registerLivePromptAudit(control, 0, "SECRET", "SECRET");
		const component = new SubagentFleetComponent(
			{ terminal: { rows: 28, columns: 100 }, requestRender() {} } as never,
			theme as never,
			state,
			() => {},
			{ refreshMs: 60_000, markdownTheme },
		);
		try {
			component.handleInput("p");
			const rendered = component.render(100).join("\n");
			assert.match(rendered, /Prompt Audit is available only/);
			assert.doesNotMatch(rendered, /SECRET/);
		} finally {
			component.dispose();
		}
	});

	it("keeps tracked missing-start rows stable across opposing heartbeat updates", () => {
		const state = stateForTest();
		state.fleetJobs = new Map();
		for (const [id, startedAt, status] of [
			["known", 100, "running"], ["unknown-b", undefined, "running"], ["unknown-a", undefined, "queued"],
		] as const) {
			state.fleetJobs.set(id, {
				asyncId: id, asyncDir: `/tmp/${id}`, sessionId: "session-current", status, startedAt,
			});
		}
		for (const direction of [1, -1]) {
			let heartbeat = 500;
			for (const job of state.fleetJobs.values()) job.updatedAt = heartbeat += direction * 10;
			const snapshot = collectFleetSnapshot(state);
			assert.equal(snapshot.error, undefined);
			assert.deepEqual(snapshot.items.map((item) => item.key), ["async:unknown-a", "async:unknown-b", "async:known"]);
			for (const item of snapshot.items) {
				const job = state.fleetJobs.get(item.runId)!;
				assert.equal(item.run?.startedAt, job.startedAt ?? job.updatedAt);
			}
		}
	});

	it("keeps tracked active workflows ahead of older failed terminal history", () => {
		const root = fs.mkdtempSync(path.join(os.tmpdir(), "pi-fleet-history-"));
		try {
			writeAsyncRun(root, { id: "older-failed", state: "failed", lastUpdate: 100 });
			writeAsyncRun(root, { id: "newer-complete", state: "complete", lastUpdate: 300 });
			const state = stateForTest();
			state.fleetJobs = new Map([["active-workflow", {
				asyncId: "active-workflow",
				asyncDir: path.join(root, "active-workflow"),
				sessionId: "session-current",
				status: "running",
				mode: "workflow",
				agents: ["worker"],
				startedAt: 100,
				updatedAt: 200,
			}]]);

			const snapshot = collectFleetSnapshot(state, { asyncDirRoot: root, resultsDir: path.join(root, "results") });
			assert.deepEqual(snapshot.items.map((item) => item.runId), ["active-workflow", "newer-complete", "older-failed"]);
		} finally {
			fs.rmSync(root, { recursive: true, force: true });
		}
	});

	it("bounds Fleet history status-file reads", () => {
		const root = fs.mkdtempSync(path.join(os.tmpdir(), "pi-fleet-bounded-history-"));
		try {
			for (let index = 0; index < 100; index++) {
				const asyncDir = writeAsyncRun(root, { id: `recent-${index}`, state: "complete", lastUpdate: index });
				fs.utimesSync(path.join(asyncDir, "status.json"), 1_000 + index, 1_000 + index);
			}
			const oldDir = writeAsyncRun(root, { id: "old-invalid", state: "failed", lastUpdate: 0 });
			fs.writeFileSync(path.join(oldDir, "status.json"), "{not-json", "utf8");
			fs.utimesSync(path.join(oldDir, "status.json"), 1, 1);

			const snapshot = collectFleetSnapshot(stateForTest(), { asyncDirRoot: root, resultsDir: path.join(root, "results") });
			assert.equal(snapshot.error, undefined);
			assert.equal(snapshot.items.length, 20);
			assert.ok(!snapshot.items.some((item) => item.runId === "old-invalid"));
		} finally {
			fs.rmSync(root, { recursive: true, force: true });
		}
	});

	it("shows async model and thinking metadata in the structured header", () => {
		const root = fs.mkdtempSync(path.join(os.tmpdir(), "pi-fleet-model-thinking-"));
		try {
			writeAsyncRun(root, {
				id: "model-thinking",
				state: "running",
				models: ["openai-codex/gpt-5.5"],
				thinking: ["high"],
			});
			const component = new SubagentFleetComponent(
				{ terminal: { rows: 32, columns: 100 }, requestRender() {} } as never,
				theme as never,
				stateForTest(),
				() => {},
				{ asyncDirRoot: root, resultsDir: path.join(root, "results"), refreshMs: 60_000, markdownTheme },
			);
			try {
				// The provider-qualified label wraps across rows in the 61-column detail pane, so
				// reassemble the detail column before asserting the model and thinking metadata.
				const detail = component.render(100)
					.map((line) => line.split("│")[2] ?? "")
					.join(" ")
					.replace(/\s+/g, " ");
				assert.ok(detail.includes("openai-codex/gpt-5.5 · thinking high"));
			} finally {
				component.dispose();
			}
		} finally {
			fs.rmSync(root, { recursive: true, force: true });
		}
	});

	it("names each async child's task on its roster row and keeps the run id in the detail header", (t) => {
		t.mock.timers.enable({ apis: ["Date"], now: Date.now() });
		const root = fs.mkdtempSync(path.join(os.tmpdir(), "pi-fleet-row-task-"));
		try {
			writeAsyncRun(root, {
				id: "row-task-run",
				agents: ["worker", "worker"],
				descriptions: [
					"Fix login bug",
					"Fix two Cycode Python SAST findings in entity-gov and add regression tests for both of the reported injection paths",
				],
			});
			const component = new SubagentFleetComponent({ terminal: { rows: 32, columns: 140 }, requestRender() {} } as never, theme as never, stateForTest(), () => {}, { asyncDirRoot: root, resultsDir: path.join(root, "results"), refreshMs: 60_000, markdownTheme });
			try {
				const lines = component.render(140);
				const roster = lines.map((line) => line.split("│")[1] ?? "");
				const short = roster.find((row) => row.includes("worker · Fix login bug"));
				const long = roster.find((row) => row.includes("worker · Fix two Cycode"));
				assert.ok(short, `short task row missing:\n${roster.join("\n")}`);
				assert.ok(long, `long task row missing:\n${roster.join("\n")}`);
				assert.ok(long.includes("..."), "a long task is cut to the row");
				assert.ok(!long.includes("injection paths"));
				assert.equal(visibleWidth(long), visibleWidth(short), "both rows keep the roster width");
				assert.ok(!short.includes("row-task"), "the row shows the task instead of the run id");
				assert.ok(lines.some((line) => (line.split("│")[2] ?? "").includes("row-task")), "the detail header still shows the run id");
			} finally { component.dispose(); }
		} finally { fs.rmSync(root, { recursive: true, force: true }); }
	});

	it("colors running Fleet rows by their child's recorded level, and whole runs by the main session's", () => {
		const root = fs.mkdtempSync(path.join(os.tmpdir(), "pi-fleet-levels-"));
		setMainThinkingLevelSource(() => "xhigh");
		try {
			writeAsyncRun(root, { id: "level-steps", state: "running", agents: ["scout", "reviewer"], thinking: ["high", "medium"], lastUpdate: 300 });
			writeAsyncRun(root, { id: "level-workflow", state: "running", mode: "workflow", agents: ["worker"], lastUpdate: 200 });
			const state = stateForTest();
			state.foregroundControls.set("level-foreground", { runId: "level-foreground", mode: "single", startedAt: 10, updatedAt: 400, currentAgent: "planner", currentIndex: 0, thinking: "max" });
			const tones = ["accent", ...["off", "minimal", "low", "medium", "high", "xhigh", "max"].map((level) => `thinking:${level}`)];
			const colored = (tone: string, text: string) => `\x1b[38;5;${Math.max(0, tones.indexOf(tone)) + 100}m${text}\x1b[39m`;
			const ansiTheme = {
				fg: (name: string, text: string) => colored(name, text),
				bold: (text: string) => text,
				getThinkingBorderColor: (level: string) => (text: string) => colored(`thinking:${level}`, text),
			};
			const component = new SubagentFleetComponent(
				{ terminal: { rows: 40, columns: 140 }, requestRender() {} } as never,
				ansiTheme as never,
				state,
				() => {},
				{ asyncDirRoot: root, resultsDir: path.join(root, "results"), refreshMs: 60_000, markdownTheme },
			);
			try {
				const lines = component.render(140);
				const plain = (line: string) => line.replace(/\x1b\[[0-9;]*m/g, "");
				const glyphTone = (label: string) => {
					const code = lines.find((line) => plain(line).includes(`\u25cf ${label}`))?.match(/\x1b\[38;5;(\d+)m\u25cf/)?.[1];
					return code === undefined ? undefined : tones[Number(code) - 100];
				};
				assert.equal(glyphTone("scout"), "thinking:high", "async step uses its recorded level");
				assert.equal(glyphTone("planner"), "thinking:max", "foreground child uses its recorded level");
				assert.equal(glyphTone("workflow"), "thinking:xhigh", "a whole workflow run uses the main level");
			} finally {
				component.dispose();
			}
		} finally {
			setMainThinkingLevelSource(() => undefined);
			fs.rmSync(root, { recursive: true, force: true });
		}
	});

	it("shows a scripted workflow as one fleet parent instead of unrelated children", () => {
		const root = fs.mkdtempSync(path.join(os.tmpdir(), "pi-fleet-workflow-parent-"));
		try {
			const state = stateForTest();
			const asyncDir = path.join(root, "workflow-1");
			fs.mkdirSync(asyncDir, { recursive: true });
			fs.writeFileSync(path.join(asyncDir, "status.json"), JSON.stringify({
				runId: "workflow-1",
				sessionId: "session-current",
				mode: "workflow",
				state: "running",
				startedAt: 10,
				lastUpdate: 20,
				steps: [
					{ agent: "scan", workflowKey: "scan", phase: "Plan", label: "Find seams", status: "completed", index: 0 },
					{ agent: "review", workflowKey: "review", phase: "Review", status: "running", index: 1, currentTool: "grep" },
				],
			}, null, 2));
			state.fleetJobs = new Map([["workflow-1", {
				asyncId: "workflow-1",
				asyncDir,
				sessionId: "session-current",
				status: "running",
				mode: "workflow",
				agents: ["scan", "review"],
				steps: [
					{ agent: "scan", workflowKey: "scan", status: "completed", index: 0 },
					{ agent: "review", workflowKey: "review", status: "running", index: 1 },
				],
				workflow: { trace: [], emits: ["reviewing"], console: [] },
				startedAt: 10,
				updatedAt: 20,
			}]]);

			const snapshot = collectFleetSnapshot(state);
			assert.deepEqual(snapshot.items.map((item) => item.key), ["async:workflow-1"]);
			assert.equal(snapshot.items[0]?.agent, "workflow");

			const component = new SubagentFleetComponent(
				{ terminal: { rows: 28, columns: 100 }, requestRender() {} } as never,
				theme as never,
				state,
				() => {},
				{ initialKey: "async:workflow-1", refreshMs: 60_000 },
			);
			try {
				const lines = component.render(120).join("\n");
				assert.match(lines, /Workflow progress:/);
				assert.match(lines, /Plan: scan · Find seams \(scan\) — completed/);
				assert.match(lines, /Review: review \(review\) — running · tool grep/);
			} finally {
				component.dispose();
			}
		} finally {
			fs.rmSync(root, { recursive: true, force: true });
		}
	});

	it("shows selectable workflow children only when multiple are live", async () => {
		const state = stateForTest();
		state.asyncJobs.set("workflow-1", {
			asyncId: "workflow-1",
			asyncDir: "/tmp/workflow-1",
			sessionId: "session-current",
			status: "running",
			mode: "workflow",
			startedAt: 10,
			updatedAt: 20,
		});
		state.asyncJobs.set("unrelated", {
			asyncId: "unrelated",
			asyncDir: "/tmp/unrelated",
			sessionId: "session-current",
			status: "running",
			mode: "single",
			startedAt: 5,
			updatedAt: 30,
		});
		state.foregroundControls.set("child-1", {
			runId: "child-1",
			parentWorkflowRunId: "workflow-1",
			workflowKey: "review",
			workflowSteeringDir: "/tmp/workflow-1/control/workflow-foreground/child-1",
			sessionId: "session-current",
			mode: "single",
			startedAt: 10,
			updatedAt: 20,
			activeChildren: new Map([[0, { index: 0, agent: "reviewer", startedAt: 10, updatedAt: 20 }]]),
		});
		assert.deepEqual(collectFleetSnapshot(state).items.map((item) => item.key), ["async:unrelated", "async:workflow-1"]);
		state.foregroundControls.get("child-1")!.activeChildren!.set(1, { index: 1, agent: "writer", startedAt: 11, updatedAt: 21 });
		assert.deepEqual(collectFleetSnapshot(state).items.map((item) => item.key), [
			"foreground-active:child-1:0",
			"foreground-active:child-1:1",
			"async:unrelated",
			"async:workflow-1",
		]);
		state.foregroundControls.get("child-1")!.activeChildren!.delete(1);
		state.foregroundControls.set("child-2", {
			runId: "child-2",
			parentWorkflowRunId: "workflow-1",
			workflowKey: "verify",
			workflowSteeringDir: "/tmp/workflow-1/control/workflow-foreground/child-2",
			sessionId: "session-current",
			mode: "single",
			startedAt: 11,
			updatedAt: 21,
			activeChildren: new Map([[0, { index: 0, agent: "verifier", startedAt: 11, updatedAt: 21 }]]),
		});
		const snapshot = collectFleetSnapshot(state);
		assert.deepEqual(snapshot.items.map((item) => item.key), [
			"foreground-active:child-1:0",
			"foreground-active:child-2:0",
			"async:unrelated",
			"async:workflow-1",
		]);
		const steerCalls: Array<{ runId: string; asyncDir: string; index?: number; message: string; mode: string }> = [];
		const inspectCalls: Array<{ runId: string; asyncDir: string; index?: number }> = [];
		const component = new SubagentFleetComponent(
			{ terminal: { rows: 28, columns: 100 }, requestRender() {} } as never,
			theme as never,
			state,
			() => {},
			{
				initialKey: "foreground-active:child-1:0",
				refreshMs: 60_000,
				actions: {
					async steer(input) { steerCalls.push(input); return { text: "Steering queued." }; },
					stop() { return { text: "unused" }; },
					async inspect(input) { inspectCalls.push(input); return { text: "Inspector opened." }; },
				},
			},
		);
		try {
			assert.ok(component.render(100).some((line) => line.includes("workflow")));
			component.handleInput("s");
			for (const char of "check the failure") component.handleInput(char);
			component.handleInput("\r");
			await new Promise((resolve) => setImmediate(resolve));
			assert.deepEqual(steerCalls, [{ runId: "child-1", asyncDir: "/tmp/workflow-1", index: 0, message: "check the failure", mode: "steer" }]);
			component.handleInput("H");
			await new Promise((resolve) => setImmediate(resolve));
			assert.deepEqual(inspectCalls, [{ runId: "workflow-1", asyncDir: "/tmp/workflow-1" }]);
		} finally {
			component.dispose();
		}
	});

	it("keeps every active async run ahead of the bounded recent-completion window", () => {
		const state = stateForTest();
		for (let index = 0; index < 22; index++) {
			state.fleetJobs ??= new Map();
			state.fleetJobs.set(`terminal-${index}`, {
				asyncId: `terminal-${index}`,
				asyncDir: path.join(os.tmpdir(), `missing-terminal-${index}`),
				sessionId: "session-current",
				status: "complete",
				mode: "single",
				agents: ["worker"],
				startedAt: index,
				updatedAt: index,
			});
		}
		state.fleetJobs!.set("active-old", {
			asyncId: "active-old",
			asyncDir: path.join(os.tmpdir(), "missing-active-old"),
			sessionId: "session-current",
			status: "running",
			mode: "single",
			agents: ["scout"],
			startedAt: 0,
			updatedAt: 0,
		});

		const snapshot = collectFleetSnapshot(state);
		assert.equal(snapshot.items.length, 21);
		assert.equal(snapshot.items[0]?.runId, "active-old");
		assert.equal(snapshot.items.find((item) => item.runId === "terminal-21")?.state, "complete");
		assert.ok(!snapshot.items.some((item) => item.runId === "terminal-0"));
	});

	it("orders active runs by start time so the roster stays stable while they emit", () => {
		const root = fs.mkdtempSync(path.join(os.tmpdir(), "pi-fleet-active-order-"));
		try {
			writeAsyncRun(root, { id: "worker-b", startedAt: 200, lastUpdate: 900 });
			writeAsyncRun(root, { id: "worker-a", startedAt: 100, lastUpdate: 500 });
			const state = stateForTest();
			const keys = () => collectFleetSnapshot(state, { asyncDirRoot: root, resultsDir: path.join(root, "results") }).items.map((item) => item.key);
			// First refresh: the run created first stays on top, even though worker-b emitted most recently.
			assert.deepEqual(keys(), ["async:worker-a:0", "async:worker-b:0"]);
			// Later activity on worker-b must not reorder the roster.
			writeAsyncRun(root, { id: "worker-b", startedAt: 200, lastUpdate: 1500 });
			assert.deepEqual(keys(), ["async:worker-a:0", "async:worker-b:0"]);
			// A run started later still lands after the earlier ones.
			writeAsyncRun(root, { id: "worker-c", startedAt: 300, lastUpdate: 300 });
			assert.deepEqual(keys(), ["async:worker-a:0", "async:worker-b:0", "async:worker-c:0"]);
		} finally {
			fs.rmSync(root, { recursive: true, force: true });
		}
	});

	it("accepts default Fleet navigation from Kitty CSI-u input", () => {
		const root = fs.mkdtempSync(path.join(os.tmpdir(), "pi-fleet-kitty-default-"));
		try {
			writeAsyncRun(root, { id: "newer", lastUpdate: 300 });
			writeAsyncRun(root, { id: "older", lastUpdate: 200 });
			const component = new SubagentFleetComponent(
				{ terminal: { rows: 28, columns: 100 }, requestRender() {} } as never,
				theme as never,
				stateForTest(),
				() => {},
				{ asyncDirRoot: root, resultsDir: path.join(root, "results"), refreshMs: 60_000 },
			);
			try {
				const selectedLine = () => component.render(100).find((line) => line.includes("›")) ?? "";
				assert.match(selectedLine(), /newer/);
				component.handleInput("\x1b[106;1u");
				assert.match(selectedLine(), /older/);
			} finally {
				component.dispose();
			}
		} finally {
			fs.rmSync(root, { recursive: true, force: true });
		}
	});

	it("uses custom Fleet keybindings without applying them inside modal text input", () => {
		const root = fs.mkdtempSync(path.join(os.tmpdir(), "pi-fleet-custom-keys-"));
		try {
			writeAsyncRun(root, { id: "newer", lastUpdate: 300 });
			writeAsyncRun(root, { id: "older", lastUpdate: 200 });
			const state = stateForTest();
			let closed = false;
			let inspectCalls = 0;
			const component = new SubagentFleetComponent(
				{ terminal: { rows: 28, columns: 100 }, requestRender() {} } as never,
				theme as never,
				state,
				() => { closed = true; },
				{
					asyncDirRoot: root,
					resultsDir: path.join(root, "results"),
					refreshMs: 60_000,
					fleetKeybindings: {
						selectDown: ["return"],
						selectUp: ["p"],
						steer: ["m"],
						close: ["z"],
					},
					actions: {
						async steer() { return { text: "unused" }; },
						stop() { return { text: "unused" }; },
						async inspect() { inspectCalls++; return { text: "unexpected" }; },
					},
				},
			);
			try {
				const selectedLine = () => component.render(100).find((line) => line.includes("›")) ?? "";
				assert.match(selectedLine(), /newer/);
				component.handleInput("j");
				assert.match(selectedLine(), /newer/, "default j should not move when selectDown is overridden");
				component.handleInput("\r");
				assert.match(selectedLine(), /older/, "custom Enter binding should move instead of opening Herdr");
				assert.equal(inspectCalls, 0);
				component.handleInput("p");
				assert.match(selectedLine(), /newer/);
				component.handleInput("m");
				component.handleInput("m");
				assert.ok(component.render(100).some((line) => line.includes("Steer message (steer): m")));
				component.handleInput("\x1b");
				component.handleInput("z");
				assert.equal(closed, true);
			} finally {
				component.dispose();
			}
		} finally {
			fs.rmSync(root, { recursive: true, force: true });
		}
	});

	it("restores current-session completed foreground history from the compact index", () => {
		const root = fs.mkdtempSync(path.join(os.tmpdir(), "pi-fleet-foreground-history-"));
		try {
			const resultsDir = path.join(root, "results");
			const cwd = path.join(root, "project");
			const artifactsRoot = getProjectArtifactsDir(cwd);
			fs.mkdirSync(artifactsRoot, { recursive: true });
			const outputPath = path.join(artifactsRoot, "outputs", "restored", "output.md");
			fs.mkdirSync(path.dirname(outputPath), { recursive: true });
			fs.writeFileSync(outputPath, "restored foreground output", "utf-8");

			const state = stateForTest();
			state.artifactDirPreference = "project";
			state.foregroundRuns!.set("restored", {
				runId: "restored",
				mode: "single",
				cwd,
				sessionId: "session-current",
				updatedAt: 200,
				children: [{ agent: "worker", index: 0, status: "completed", finalOutput: "do not persist this when an artifact exists", savedOutputPath: outputPath, resumeContract: { outputSchema: { type: "object" }, agentContract: { version: 1 }, acceptance: false, output: false, outputMode: "inline" }, extensionBindings: { "shepherd.dispatch/1": { role: "coder" } } }],
			});
			state.foregroundRuns!.set("other-session", {
				runId: "other-session",
				mode: "single",
				cwd,
				sessionId: "session-other",
				updatedAt: 300,
				children: [{ agent: "outsider", index: 0, status: "completed", savedOutputPath: outputPath }],
			});
			for (const run of state.foregroundRuns!.values()) persistForegroundRun(run, { resultsDir });
			if (process.platform !== "win32") assert.equal(fs.statSync(foregroundHistoryFile(resultsDir, "restored")).mode & 0o777, 0o600);

			const restored = stateForTest();
			restored.baseCwd = cwd;
			restored.artifactDirPreference = "project";
			assert.equal(restoreForegroundRunHistory(restored, { resultsDir }), 1);
			assert.deepEqual(restored.foregroundRuns?.get("restored")?.children[0]?.resumeContract, { outputSchema: { type: "object" }, agentContract: { version: 1 }, acceptance: false, output: false, outputMode: "inline" });
			assert.deepEqual(restored.foregroundRuns?.get("restored")?.children[0]?.extensionBindings, { "shepherd.dispatch/1": { role: "coder" } });
			const snapshot = collectFleetSnapshot(restored);
			assert.deepEqual(snapshot.items.map((item) => item.key), ["foreground-recent:restored:0"]);

			const component = new SubagentFleetComponent(
				{ terminal: { rows: 28, columns: 100 }, requestRender() {} } as never,
				theme as never,
				restored,
				() => {},
				{ refreshMs: 60_000 },
			);
			try {
				const lines = component.render(100);
				assert.ok(lines.some((line) => line.includes("restored foreground output")));
				assert.ok(!lines.some((line) => line.includes("do not persist")));
			} finally {
				component.dispose();
			}
		} finally {
			fs.rmSync(root, { recursive: true, force: true });
		}
	});

	it("does not restore nonterminal foreground history rows", () => {
		const root = fs.mkdtempSync(path.join(os.tmpdir(), "pi-fleet-foreground-terminal-"));
		try {
			const resultsDir = path.join(root, "results");
			// A running row without an owner pid cannot be judged, so it is never admitted.
			writeForegroundHistoryFile(resultsDir, { runId: "stale-running", mode: "single", cwd: root, sessionId: "session-current", updatedAt: 300, children: [{ agent: "worker", index: 0, status: "running", currentTool: "bash" }] });
			writeForegroundHistoryFile(resultsDir, { runId: "terminal", mode: "single", cwd: root, sessionId: "session-current", updatedAt: 200, children: [{ agent: "reviewer", index: 0, status: "completed", finalOutput: "done" }] });

			const restored = stateForTest();
			restored.baseCwd = root;
			assert.equal(restoreForegroundRunHistory(restored, { resultsDir }), 1);
			assert.deepEqual([...restored.foregroundRuns!.keys()], ["terminal"]);
			assert.deepEqual(collectFleetSnapshot(restored).items.map((item) => item.key), ["foreground-recent:terminal:0"]);

			fs.rmSync(foregroundHistoryFile(resultsDir, "stale-running"));
			persistForegroundRun({ runId: "stale-running", mode: "single", cwd: root, sessionId: "session-current", updatedAt: 400, children: [{ agent: "worker", index: 0, status: "running" }] }, { resultsDir });
			assert.deepEqual([...savedForegroundRuns(resultsDir).keys()], ["terminal"]);
		} finally {
			fs.rmSync(root, { recursive: true, force: true });
		}
	});

	it("keeps a running foreground record in the file and loads it as stopped only once its Pi process is gone", () => {
		const root = fs.mkdtempSync(path.join(os.tmpdir(), "pi-fleet-foreground-running-"));
		try {
			const resultsDir = path.join(root, "results");
			const sessionFile = path.join(root, "child-session.jsonl");
			fs.writeFileSync(sessionFile, "{}\n", "utf-8");
			const exited = spawnSync(process.execPath, ["-e", ""]).pid;
			assert.ok(exited);
			const running = (runId: string, owner: { pid: number; pidNamespaceScope?: string; bootId?: string }) => ({
				runId,
				mode: "single" as const,
				cwd: root,
				sessionId: "session-current",
				updatedAt: 100,
				parentWorkflowRunId: "workflow-parent",
				children: [{ agent: "worker", index: 0, status: "running" as const, activityState: "active" as const, currentTool: "bash", sessionFile, resumeContract: { outputMode: "inline" as const } }],
				owner: { pidNamespaceScope: currentPidNamespaceScope(), ...owner },
			});
			persistForegroundRun(running("owner-dead", { pid: exited }), { resultsDir });
			persistForegroundRun(running("owner-alive", { pid: process.pid, bootId: "boot-now" }), { resultsDir });
			// This test process is alive, so only the boot id can say this owner is gone.
			persistForegroundRun(running("owner-rebooted", { pid: process.pid, bootId: "boot-before" }), { resultsDir });
			persistForegroundRun(running("owner-other-namespace", { pid: exited, pidNamespaceScope: "pid:[container]" }), { resultsDir });
			assert.deepEqual([...savedForegroundRuns(resultsDir).values()].map((run) => [run.runId, run.children[0]?.status, run.owner !== undefined]).sort(), [
				["owner-alive", "running", true], ["owner-dead", "running", true], ["owner-other-namespace", "running", true], ["owner-rebooted", "running", true],
			]);

			const restored = stateForTest();
			restored.baseCwd = root;
			resetBootIdForTesting(() => "boot-now");
			try {
				assert.equal(restoreForegroundRunHistory(restored, { resultsDir }), 2);
			} finally {
				resetBootIdForTesting();
			}
			assert.deepEqual([...restored.foregroundRuns!.keys()].sort(), ["owner-dead", "owner-rebooted"]);
			const stopped = restored.foregroundRuns!.get("owner-dead")!;
			assert.deepEqual(stopped.children[0], { agent: "worker", index: 0, status: "stopped", exitCode: 1, error: FOREGROUND_OWNER_EXITED_STOP_ERROR, finalOutput: FOREGROUND_OWNER_EXITED_STOP_ERROR, sessionFile, resumeContract: { outputMode: "inline" } });
			assert.equal(stopped.owner, undefined);
			assert.equal(stopped.parentWorkflowRunId, "workflow-parent");
		} finally {
			fs.rmSync(root, { recursive: true, force: true });
		}
	});

	it("prunes the oldest final records beyond the cap, and a running record only once its owner is dead", () => {
		const root = fs.mkdtempSync(path.join(os.tmpdir(), "pi-fleet-foreground-prune-"));
		try {
			const resultsDir = path.join(root, "results");
			const exited = spawnSync(process.execPath, ["-e", ""]).pid;
			assert.ok(exited);
			const run = (runId: string, ownerPid?: number): ForegroundResumeRun => ({ runId, mode: "single", cwd: root, sessionId: "session-current", updatedAt: 100, ...(ownerPid ? { owner: { pid: ownerPid } } : {}), children: [{ agent: "worker", index: 0, status: ownerPid ? "running" : "completed" }] });
			// The two oldest files are running records: one whose owner is alive (its final save will
			// replace it later) and one left by a Pi process that died.
			for (const [index, [runId, ownerPid]] of ([["running-live", process.pid], ["running-dead", exited], ["final-1", undefined], ["final-2", undefined]] as const).entries()) {
				persistForegroundRun(run(runId, ownerPid), { resultsDir });
				fs.utimesSync(foregroundHistoryFile(resultsDir, runId), 1_000 + index, 1_000 + index);
			}
			persistForegroundRun(run("final-3"), { resultsDir, limit: 2 });
			assert.deepEqual([...savedForegroundRuns(resultsDir).keys()].sort(), ["final-2", "final-3", "running-live"]);
		} finally {
			fs.rmSync(root, { recursive: true, force: true });
		}
	});

	it("saves each foreground run to its own file without rewriting another process's record", () => {
		const root = fs.mkdtempSync(path.join(os.tmpdir(), "pi-fleet-foreground-own-file-"));
		try {
			const resultsDir = path.join(root, "results");
			const run = (runId: string, extra: Partial<ForegroundResumeRun> = {}): ForegroundResumeRun => ({ runId, mode: "single", cwd: root, sessionId: "session-current", updatedAt: 100, children: [{ agent: "worker", index: 0, status: "completed" }], ...extra });
			// Run A belongs to another Pi process: this process's state never held it.
			persistForegroundRun(run("run-a", { owner: { pid: process.pid + 1 }, children: [{ agent: "worker", index: 0, status: "running" }] }), { resultsDir });
			const fileA = foregroundHistoryFile(resultsDir, "run-a");
			fs.utimesSync(fileA, 1_000, 1_000);
			const bytesA = fs.readFileSync(fileA, "utf-8");
			persistForegroundRun(run("run-b"), { resultsDir });
			assert.equal(fs.readFileSync(fileA, "utf-8"), bytesA);
			assert.equal(fs.statSync(fileA).mtimeMs, 1_000_000, "run A's file was not rewritten");
			assert.deepEqual([...savedForegroundRuns(resultsDir).keys()].sort(), ["run-a", "run-b"]);
		} finally {
			fs.rmSync(root, { recursive: true, force: true });
		}
	});

	it("restores this session's saved runs, skips a corrupt file, and ignores and removes the old single history file", () => {
		const root = fs.mkdtempSync(path.join(os.tmpdir(), "pi-fleet-foreground-files-"));
		try {
			const resultsDir = path.join(root, "results");
			const run = (runId: string, sessionId: string) => ({ runId, mode: "single" as const, cwd: root, sessionId, updatedAt: 100, children: [{ agent: "worker", index: 0, status: "completed" as const }] });
			const legacyFile = path.join(resultsDir, "foreground-history.json");
			fs.mkdirSync(resultsDir, { recursive: true });
			fs.writeFileSync(legacyFile, JSON.stringify({ version: 1, runs: [run("legacy", "session-current")] }), "utf-8");
			persistForegroundRun(run("current", "session-current"), { resultsDir });
			persistForegroundRun(run("other-session", "session-other"), { resultsDir });
			fs.writeFileSync(path.join(resultsDir, "foreground-history", "corrupt.json"), "{not json", "utf-8");
			assert.equal(fs.existsSync(legacyFile), false);

			const restored = stateForTest();
			assert.equal(restoreForegroundRunHistory(restored, { resultsDir }), 1);
			assert.deepEqual([...restored.foregroundRuns!.keys()], ["current"]);
		} finally {
			fs.rmSync(root, { recursive: true, force: true });
		}
	});

	it("discards a running foreground record only while this process owns it", () => {
		const root = fs.mkdtempSync(path.join(os.tmpdir(), "pi-fleet-foreground-running-discard-"));
		try {
			const resultsDir = path.join(root, "results");
			const running = (runId: string, ownerPid: number) => ({ runId, mode: "single" as const, cwd: root, sessionId: "session-current", updatedAt: 100, owner: { pid: ownerPid }, children: [{ agent: "worker", index: 0, status: "running" as const }] });
			persistForegroundRun(running("threw", process.pid), { resultsDir });
			persistForegroundRun(running("other-owner", process.pid + 1), { resultsDir });
			discardRunningForegroundRun("threw", { resultsDir });
			discardRunningForegroundRun("other-owner", { resultsDir });
			assert.deepEqual([...savedForegroundRuns(resultsDir).keys()], ["other-owner"]);
		} finally {
			fs.rmSync(root, { recursive: true, force: true });
		}
	});

	it("shows a foreground child cut off by a Pi exit as interrupted, with its resume id only when a transcript exists", () => {
		const root = fs.mkdtempSync(path.join(os.tmpdir(), "pi-fleet-foreground-interrupted-"));
		try {
			const sessionFile = path.join(root, "child-session.jsonl");
			fs.writeFileSync(sessionFile, "{}\n", "utf-8");
			const state = stateForTest();
			state.baseCwd = root;
			const interrupted = (runId: string, extra: { sessionFile?: string } = {}) => ({ runId, mode: "single" as const, cwd: root, sessionId: state.currentSessionId!, updatedAt: 100, children: [{ agent: "worker", index: 0, status: "stopped" as const, exitCode: 1, error: FOREGROUND_OWNER_EXITED_STOP_ERROR, finalOutput: FOREGROUND_OWNER_EXITED_STOP_ERROR, ...extra }] });
			state.foregroundRuns!.set("run-interrupted", interrupted("run-interrupted", { sessionFile }));
			const statusText = (id: string) => {
				const status = inspectSubagentStatus({ id }, { asyncDirRoot: path.join(root, "runs"), resultsDir: path.join(root, "results"), state });
				return status.content[0]?.type === "text" ? status.content[0].text : "";
			};
			assert.match(statusText("run-interrupted"), /^1\. worker interrupted when Pi exited · resume run-interrupted, exit 1/m);
			const component = new SubagentFleetComponent({ terminal: { rows: 28, columns: 140 }, requestRender() {} } as never, theme as never, state, () => {}, { refreshMs: 60_000 });
			try {
				assert.ok(component.render(140).some((line) => line.includes("State: interrupted when Pi exited · resume run-interrupted")));
			} finally {
				component.dispose();
			}

			state.foregroundRuns!.set("run-no-transcript", interrupted("run-no-transcript"));
			assert.match(statusText("run-no-transcript"), /^1\. worker interrupted when Pi exited, exit 1/m);
		} finally {
			fs.rmSync(root, { recursive: true, force: true });
		}
	});

	it("does not restore or persist oversized foreground resume contracts", () => {
		const root = fs.mkdtempSync(path.join(os.tmpdir(), "pi-fleet-foreground-contract-bound-"));
		try {
			const resultsDir = path.join(root, "results");
			const oversized = (runId: string) => ({ runId, mode: "single" as const, cwd: root, sessionId: "session-current", updatedAt: 200, children: [{ agent: "worker", index: 0, status: "completed" as const, resumeContract: { outputSchema: { type: "object", description: "x".repeat(65 * 1024) } } }] });
			writeForegroundHistoryFile(resultsDir, oversized("saved-oversized"));

			const restored = stateForTest();
			assert.equal(restoreForegroundRunHistory(restored, { resultsDir }), 0);
			assert.equal(restored.foregroundRuns?.has("saved-oversized"), false);

			persistForegroundRun(oversized("oversized"), { resultsDir });
			assert.equal(fs.existsSync(foregroundHistoryFile(resultsDir, "oversized")), false);
		} finally {
			fs.rmSync(root, { recursive: true, force: true });
		}
	});

	it("keeps restored foreground rows when output artifacts are unavailable and bounds history", () => {
		const root = fs.mkdtempSync(path.join(os.tmpdir(), "pi-fleet-foreground-missing-"));
		try {
			const resultsDir = path.join(root, "results");
			const cwd = path.join(root, "project");
			const artifactsRoot = getProjectArtifactsDir(cwd);
			const state = stateForTest();
			state.artifactDirPreference = "project";
			for (let index = 0; index < 3; index++) {
				const outputPath = path.join(artifactsRoot, "outputs", `run-${index}`, "output.md");
				fs.mkdirSync(path.dirname(outputPath), { recursive: true });
				fs.writeFileSync(outputPath, `output ${index}`, "utf-8");
				state.foregroundRuns!.set(`run-${index}`, {
					runId: `run-${index}`,
					mode: "single",
					cwd,
					sessionId: "session-current",
					updatedAt: index,
					children: [{ agent: "worker", index: 0, status: "completed", savedOutputPath: outputPath }],
				});
			}
			for (const [index, run] of [...state.foregroundRuns!.values()].entries()) {
				persistForegroundRun(run, { resultsDir, limit: 2 });
				// Distinct mtimes in save order: the cap prunes the oldest file.
				fs.utimesSync(foregroundHistoryFile(resultsDir, run.runId), 1_000 + index, 1_000 + index);
			}
			assert.deepEqual([...savedForegroundRuns(resultsDir).keys()].sort(), ["run-1", "run-2"]);
			fs.rmSync(path.join(artifactsRoot, "outputs", "run-2", "output.md"), { force: true });

			const restored = stateForTest();
			restored.baseCwd = cwd;
			restored.artifactDirPreference = "project";
			assert.equal(restoreForegroundRunHistory(restored, { resultsDir, limit: 2 }), 2);
			assert.deepEqual([...restored.foregroundRuns!.keys()], ["run-2", "run-1"]);

			const component = new SubagentFleetComponent(
				{ terminal: { rows: 28, columns: 100 }, requestRender() {} } as never,
				theme as never,
				restored,
				() => {},
				{ initialKey: "foreground-recent:run-2:0", refreshMs: 60_000 },
			);
			try {
				assert.ok(component.render(100).some((line) => line.includes("output artifact unavailable")));
			} finally {
				component.dispose();
			}
		} finally {
			fs.rmSync(root, { recursive: true, force: true });
		}
	});

	it("uses the full 85% terminal-height budget for the inspector", () => {
		const component = new SubagentFleetComponent(
			{ terminal: { rows: 60, columns: 100 }, requestRender() {} } as never,
			theme as never,
			stateForTest(),
			() => {},
			{ refreshMs: 60_000 },
		);
		try {
			assert.equal(component.render(100).length, 51);
		} finally {
			component.dispose();
		}
	});

	it("renders selectable transcript detail and completed artifact paths within terminal width", () => {
		const root = fs.mkdtempSync(path.join(os.tmpdir(), "pi-fleet-render-"));
		try {
			const asyncDir = writeAsyncRun(root, { id: "async-finished", state: "complete", contexts: ["fork"], output: "FINAL ASYNC OUTPUT" });
			const state = stateForTest();
			let closed = false;
			let renderRequests = 0;
			const tui = { terminal: { rows: 32, columns: 100 }, requestRender: () => { renderRequests++; } };
			const component = new SubagentFleetComponent(
				tui as never,
				theme as never,
				state,
				() => { closed = true; },
				{ asyncDirRoot: root, resultsDir: path.join(root, "results"), refreshMs: 60_000 },
			);
			try {
				const lines = component.render(100);
				assert.ok(lines.some((line) => line.includes("FINAL ASYNC OUTPUT")));
				assert.ok(lines.some((line) => line.includes("worker") && line.includes("[fork]")));
				// The detail pane hard-wraps long paths at any character, so read it back as one string.
				const detail = lines.map((line) => (line.replace(/\x1b\[[0-9;]*m/g, "").split("│")[2] ?? "").trimEnd()).join("");
				assert.ok(detail.includes(path.join(asyncDir, "output-0.log")));
				assert.ok(detail.includes(path.join(asyncDir, "worker.jsonl")));
				for (const line of lines) assert.ok(visibleWidth(line) <= 100, `line exceeded width: ${line}`);
				tui.terminal.rows = 10;
				assert.ok(component.render(100).length <= 8, "short-terminal render should fit the overlay's 85% height cap");
				component.handleInput("\x1b[6~");
				component.handleInput("r");
				assert.equal(renderRequests, 1, "paging at the bottom is a no-op; refresh requests a render");
				component.handleInput("\x1b");
				assert.equal(closed, true);
			} finally {
				component.dispose();
			}
		} finally {
			fs.rmSync(root, { recursive: true, force: true });
		}
	});

	it("passes current-session trusted roots to async session transcript fallback", () => {
		const root = fs.mkdtempSync(path.join(os.tmpdir(), "pi-fleet-session-fallback-"));
		try {
			const asyncDir = writeAsyncRun(root, { id: "async-session-fallback" });
			const sessionFile = path.join(asyncDir, "worker.jsonl");
			fs.writeFileSync(sessionFile, `${JSON.stringify({ role: "assistant", content: "TRUSTED SESSION FALLBACK" })}\n`, "utf-8");
			const state = stateForTest();
			state.trustedSessionRoots = [asyncDir];
			const component = new SubagentFleetComponent(
				{ terminal: { rows: 32, columns: 100 }, requestRender() {} } as never,
				theme as never,
				state,
				() => {},
				{ asyncDirRoot: root, resultsDir: path.join(root, "results"), refreshMs: 60_000 },
			);
			try {
				const rendered = component.render(100).join("\n");
				assert.match(rendered, /TRUSTED SESSION FALLBACK/);
				assert.doesNotMatch(rendered, /without a trusted root|Session read failed/);
			} finally {
				component.dispose();
			}
		} finally {
			fs.rmSync(root, { recursive: true, force: true });
		}
	});

	it("previews an exact runtime-recorded workflow session under the Pi sessions base", () => {
		const root = fs.mkdtempSync(path.join(os.tmpdir(), "pi-fleet-recorded-session-"));
		try {
			const asyncDir = writeAsyncRun(root, { id: "async-recorded-session" });
			const sessionsBase = path.join(root, "sessions");
			const projectDir = path.join(sessionsBase, "project");
			fs.mkdirSync(projectDir, { recursive: true });
			const sessionFile = path.join(projectDir, "workflow-child.jsonl");
			fs.writeFileSync(sessionFile, `${JSON.stringify({ role: "assistant", content: "RECORDED WORKFLOW SESSION" })}\n`, "utf-8");
			const statusPath = path.join(asyncDir, "status.json");
			const status = JSON.parse(fs.readFileSync(statusPath, "utf-8")) as { sessionFile?: string; steps?: Array<{ sessionFile?: string; transcriptPath?: string }> };
			status.sessionFile = sessionFile;
			status.steps![0]!.sessionFile = sessionFile;
			delete status.steps![0]!.transcriptPath;
			fs.writeFileSync(statusPath, JSON.stringify(status, null, 2), "utf-8");

			const state = stateForTest();
			state.trustedSessionRoots = [];
			state.trustedSessionFileRoot = sessionsBase;
			const component = new SubagentFleetComponent(
				{ terminal: { rows: 32, columns: 100 }, requestRender() {} } as never,
				theme as never,
				state,
				() => {},
				{ asyncDirRoot: root, resultsDir: path.join(root, "results"), refreshMs: 60_000 },
			);
			try {
				const rendered = component.render(100).join("\n");
				assert.match(rendered, /RECORDED WORKFLOW SESSION/);
				assert.doesNotMatch(rendered, /without a trusted root|Session read failed/);
			} finally {
				component.dispose();
			}
		} finally {
			fs.rmSync(root, { recursive: true, force: true });
		}
	});

	it("selects rendered roster rows and consumes normalized output wheel input", (t) => {
		t.mock.timers.enable({ apis: ["Date"], now: Date.now() });
		const root = fs.mkdtempSync(path.join(os.tmpdir(), "pi-fleet-pointer-"));
		try {
			writeAsyncRun(root, { id: "pointer", agents: ["alpha", "beta"], transcript: [{ recordType: "message", role: "assistant", text: Array.from({ length: 200 }, (_, i) => `line ${i}`).join("\n") }] });
			const component = new SubagentFleetComponent({ terminal: { rows: 32, columns: 100 }, requestRender() {} } as never, theme as never, stateForTest(), () => {}, { asyncDirRoot: root, resultsDir: path.join(root, "results"), refreshMs: 60_000, markdownTheme });
			const event = (changes: Partial<TuiMouseEvent>): TuiMouseEvent => ({ type: "wheel", button: "none", x: 70, y: 10, screenX: 81, screenY: 15, width: 100, height: 27, shift: false, alt: false, ctrl: false, wheelDelta: -1, ...changes });
			try {
				const bottom = component.render(100);
				assert.equal((component as Component).handleMouse?.(event({}))?.handled, true, "output wheel must be owned");
				const wheel = component.render(100);
				assert.notDeepEqual(wheel, bottom);
				component.handleInput("J");
				assert.deepEqual(component.render(100), bottom);
				assert.equal((component as Component).handleMouse?.(event({ type: "click", button: "left", x: 5, y: 4 }))?.handled, true);
				const selected = component.render(100);
				assert.match(selected[1]!, /beta/);
				for (const outside of [{ x: 5, y: 4 }, { x: 50, y: 0 }]) {
					assert.equal((component as Component).handleMouse?.(event(outside))?.handled, true, "wheel outside the output pane must not reach the transcript");
					assert.deepEqual(component.render(100), selected);
				}
			} finally { component.dispose(); }
		} finally { fs.rmSync(root, { recursive: true, force: true }); }
	});

	it("hit-tests the rendered roster across refresh, removal, resize, blank rows, and unsupported pointers", () => {
		const state = stateForTest();
		for (let i = 0; i < 30; i++) state.foregroundControls.set(`run-${i}`, { runId: `run-${i}`, mode: "single", startedAt: i + 1, updatedAt: i + 1, currentAgent: `agent-${i}`, currentIndex: 0 });
		const terminal = { rows: 32, columns: 100 };
		const component = new SubagentFleetComponent({ terminal, requestRender() {} } as never, theme as never, state, () => {}, { refreshMs: 60_000, markdownTheme });
		const click = (changes: Partial<TuiMouseEvent> = {}) => component.handleMouse({ type: "click", button: "left", x: 5, y: 3, screenX: 40, screenY: 20, width: 100, height: 27, shift: false, alt: false, ctrl: false, ...changes });
		try {
			component.handleInput("\x1b[F");
			const rendered = component.render(100);
			const firstVisible = /agent-\d+/.exec(rendered[3]!)![0];
			for (const changes of [{ x: 0 }, { x: 37 }, { y: 2 }, { button: "right" as const }, { type: "drag" as const }, { shift: true }]) {
				assert.equal(click(changes), undefined);
				assert.match(component.render(100)[1]!, /agent-29/);
			}
			// Insert a row ahead of the rendered slice without rendering a replacement frame.
			state.foregroundControls.set("inserted", { runId: "inserted", mode: "single", startedAt: 0.5, updatedAt: 1, currentAgent: "inserted", currentIndex: 0 });
			component.handleInput("r");
			assert.equal(click()?.handled, true);
			assert.ok(component.render(100)[1]!.includes(firstVisible), "click resolves rendered key, not a refreshed row index");
			component.handleInput("\x1b[F");
			const lastFrame = component.render(100);
			const removedAgent = /agent-\d+/.exec(lastFrame[3]!)![0];
			state.foregroundControls.delete(removedAgent.replace("agent", "run"));
			component.handleInput("r");
			assert.equal(click(), undefined, "removed rendered keys are ignored");
			terminal.rows = 20;
			assert.equal(click(), undefined, "pre-resize hit regions cannot select");
			component.render(35);
			assert.equal(click({ width: 35 }), undefined);
			state.foregroundControls.clear();
			state.foregroundControls.set("only", { runId: "only", mode: "single", startedAt: 1, updatedAt: 1, currentAgent: "only", currentIndex: 0 });
			component.handleInput("r"); component.render(100);
			assert.equal(click({ y: 5 }), undefined, "blank roster rows are not targets");
		} finally { component.dispose(); }
	});

	it("routes fullscreen terminal mouse input through the host overlay and preserves regular keyboard navigation", (t) => {
		t.mock.timers.enable({ apis: ["Date"], now: Date.now() });
		const root = fs.mkdtempSync(path.join(os.tmpdir(), "pi-fleet-host-"));
		try {
			writeAsyncRun(root, { id: "host", agents: ["alpha", "beta"], transcript: [{ recordType: "message", role: "assistant", text: Array.from({ length: 200 }, (_, i) => `host line ${i}`).join("\n") }] });
			for (const fullscreen of [true, false]) {
				let input: (data: string) => void = () => {};
				const writes: string[] = [];
				const terminal = {
					rows: 40, columns: 120, kittyProtocolActive: false,
					start(handler: (data: string) => void) { input = handler; }, stop() {}, async drainInput() {},
					write(data: string) { writes.push(data); }, moveBy() {}, hideCursor() {}, showCursor() {},
					clearLine() {}, clearFromCursor() {}, clearScreen() {}, setTitle() {}, setProgress() {}, setProgramStatus() {},
				};
				const tui = fullscreen ? new TuiAltScreen(terminal, false, undefined, { mouse: true, wheelScrollLines: 1 }) : new TuiMainScreen(terminal);
				const component = new SubagentFleetComponent(tui, theme as never, stateForTest(), () => {}, { asyncDirRoot: root, resultsDir: path.join(root, "results"), refreshMs: 60_000, markdownTheme, actions: { async steer() { return { text: "steered" }; }, stop() { throw new Error("pointer must not activate stop"); } } });
				tui.addChild({ render: () => Array.from({ length: 200 }, (_, i) => `transcript ${i}`), invalidate() {} });
				tui.start();
				const overlay = tui.showOverlay(component, { width: 100, row: 2, col: 8 });
				try {
					tui.renderNow();
					const bottom = component.render(100);
					if (fullscreen && tui instanceof TuiAltScreen) {
						// The transcript starts following its bottom. Unhandled wheel input would fall back to
						// transcript scrolling, which clamps silently at either bound; move the transcript away
						// from both bounds first so fallback in either direction becomes observable.
						const endOffset = tui.viewportTop;
						tui.scrollBy(-10);
						tui.renderNow();
						const top = tui.viewportTop;
						assert.ok(top > 0, "setup must leave upward wheel-fallback room in the transcript");
						assert.ok(top < endOffset, "setup must leave downward wheel-fallback room in the transcript");
						const bounds = overlay.getBounds()!;
						const mouse = (button: number, x: number, y: number, release = false) => input(`\x1b[<${button};${bounds.col + x + 1};${bounds.row + y + 1}${release ? "m" : "M"}`);
						mouse(64, 70, 12);
						tui.renderNow();
						assert.notDeepEqual(component.render(100), bottom);
						assert.equal(tui.viewportTop, top);
						for (let i = 0; i < 230; i++) mouse(64, 70, 12);
						tui.renderNow();
						assert.equal(tui.viewportTop, top, "top limit must consume wheel");
						for (let i = 0; i < 230; i++) mouse(65, 70, 12);
						tui.renderNow();
						assert.equal(tui.viewportTop, top, "bottom limit must consume wheel");
						assert.deepEqual(component.render(100), bottom);
						mouse(0, 5, 4); mouse(0, 5, 4, true);
						tui.renderNow();
						assert.match(component.render(100)[1]!, /beta/);
						input("k"); tui.renderNow();
						input("D"); tui.renderNow();
						const modal = component.render(100);
						mouse(64, 70, 12); mouse(0, 5, 4); mouse(0, 5, 4, true);
						tui.renderNow();
						assert.deepEqual(component.render(100), modal);
						assert.equal(tui.viewportTop, top, "confirmation modal must not leak wheel input");
					} else {
						input("K"); tui.renderNow();
						assert.notDeepEqual(component.render(100), bottom);
						input("J"); tui.renderNow();
						assert.deepEqual(component.render(100), bottom);
						assert.ok(!writes.some((data) => /\x1b\[\?100[0236]h/.test(data)), "regular mode must not enable mouse tracking");
					}
				} finally { overlay.hide(); component.dispose(); tui.stop(); }
			}
		} finally { fs.rmSync(root, { recursive: true, force: true }); }
	});

	it("stays out of the way of an inline dialog that takes focus, then returns with its selection", () => {
		const state = stateForTest();
		for (const agent of ["alpha", "beta"]) state.foregroundControls.set(agent, { runId: agent, mode: "single", startedAt: 1, updatedAt: 1, currentAgent: agent, currentIndex: 0 });
		const writes: string[] = [];
		const terminal = {
			rows: 40, columns: 120, kittyProtocolActive: false,
			start(handler: (data: string) => void) { input = handler; }, stop() {}, async drainInput() {},
			write(data: string) { writes.push(data); }, moveBy() {}, hideCursor() {}, showCursor() {},
			clearLine() {}, clearFromCursor() {}, clearScreen() {}, setTitle() {}, setProgress() {}, setProgramStatus() {},
		};
		let input: (data: string) => void = () => {};
		const tui = new TuiMainScreen(terminal);
		let closed = 0;
		const editor: Component = { render: () => ["editor"], invalidate() {}, handleInput() {} };
		const promptKeys: string[] = [];
		const prompt: Component = { render: () => ["Allow bash? (y) yes (n) no · esc deny"], invalidate() {}, handleInput(data) { promptKeys.push(data); } };
		// Pi mounts inline dialogs in the editor slot: clear it, add the dialog, focus it, and swap back when done.
		const slot = new Container();
		slot.addChild(editor);
		tui.addChild(slot);
		tui.setFocus(editor);
		tui.start();
		// Like ctx.ui.custom: the fleet is built while the editor has focus, then shown as an overlay.
		const component = new SubagentFleetComponent(tui, theme as never, state, () => { closed++; }, { refreshMs: 60_000, markdownTheme });
		const overlay = tui.showOverlay(component, { width: 100, anchor: "center" });
		const frame = () => { writes.length = 0; tui.renderNow(); return writes.join(""); };
		try {
			assert.match(frame(), /Subagent fleet inspector/);
			// A fullscreen click on the editor focuses the fleet's own preFocus; no dialog opened, so stay drawn.
			tui.setFocus(editor);
			assert.match(component.render(100).join("\n"), /Subagent fleet inspector/);
			input("j");
			const selectedRow = component.render(100)[1]!;
			assert.match(selectedRow, /beta/);

			slot.clear(); slot.addChild(prompt); tui.setFocus(prompt);
			const covered = frame();
			assert.match(covered, /Allow bash\?/);
			assert.doesNotMatch(covered, /Subagent fleet inspector/);
			input("q"); input("\x1b");
			assert.deepEqual(promptKeys, ["q", "\x1b"]);
			assert.equal(closed, 0);

			slot.clear(); slot.addChild(editor); tui.setFocus(editor);
			assert.equal(overlay.isFocused(), true);
			assert.match(frame(), /Subagent fleet inspector/);
			assert.equal(component.render(100)[1], selectedRow);
			input("q");
			assert.equal(closed, 1);
		} finally { overlay.hide(); component.dispose(); tui.stop(); }
	});

	it("records long-transcript cache and render-request counters", (t) => {
		const root = fs.mkdtempSync(path.join(os.tmpdir(), "pi-fleet-counters-"));
		const original = fsDefault.openSync;
		let reads = 0;
		let requests = 0;
		let scans = 0;
		const readdir = fsDefault.readdirSync;
		try {
			writeAsyncRun(root, { id: "counters", transcript: [{ recordType: "message", role: "assistant", text: Array.from({ length: 1000 }, (_, i) => `detail ${i}`).join("\n") }] });
			const component = new SubagentFleetComponent({ terminal: { rows: 32, columns: 100 }, requestRender() { requests++; } } as never, theme as never, stateForTest(), () => {}, { asyncDirRoot: root, resultsDir: path.join(root, "results"), refreshMs: 60_000, markdownTheme });
			fsDefault.openSync = ((file: Parameters<typeof original>[0], ...args: unknown[]) => {
				if (String(file).endsWith("transcript-0.jsonl")) reads++;
				return (original as Function)(file, ...args);
			}) as typeof original;
			t.mock.method(fsDefault, "readdirSync", (...args: Parameters<typeof readdir>) => { scans++; return readdir(...args); });
			syncBuiltinESMExports();
			const start = performance.now();
			try {
				component.render(100);
				for (let i = 0; i < 20; i++) { component.handleInput("K"); component.render(100); }
				assert.equal(reads, 1);
				assert.equal(requests, 20);
				t.diagnostic(`1000 lines / 21 renders: transcript reads=${reads}, requests=${requests}, elapsed=${(performance.now() - start).toFixed(1)}ms`);
				for (let i = 0; i < 20; i++) {
					component.handleMouse({ type: "wheel", button: "none", x: 70, y: 12, screenX: 70, screenY: 12, width: 100, height: 27, shift: false, alt: false, ctrl: false, wheelDelta: -1 });
					component.render(100);
				}
				assert.equal(reads, 1, "pointer renders reuse the transcript cache");
				assert.equal(scans, 0, "pointer handling and rendering do not scan directories");
				assert.equal(requests, 40);
				t.diagnostic(`after 20 wheel movements: transcript reads=${reads}, directory scans=${scans}, requests=${requests}`);
			} finally { component.dispose(); }
		} finally { fsDefault.openSync = original; t.mock.restoreAll(); syncBuiltinESMExports(); fs.rmSync(root, { recursive: true, force: true }); }
	});

	it("renders structured tool activity and assistant Markdown when a child transcript is available", () => {
		const root = fs.mkdtempSync(path.join(os.tmpdir(), "pi-fleet-structured-"));
		try {
			const longResponse = `## Finding\n\n${Array.from({ length: 40 }, (_, index) => `detail ${index}`).join("\n")}\n\n\`\`\`ts\nconst fleet = true;\n\`\`\``;
			writeAsyncRun(root, {
				id: "async-structured",
				state: "complete",
				output: "RAW FALLBACK SHOULD NOT RENDER",
				transcript: [
					{ recordType: "message", sourceEventType: "initial_prompt", role: "user", text: "injected task" },
					{ recordType: "tool_start", toolName: "read", argsPreview: "src/tui/fleet.ts" },
					{ recordType: "tool_end", toolName: "read" },
					{ recordType: "message", role: "toolResult", text: "very large tool payload", message: { toolName: "read", isError: false } },
					{ recordType: "message", role: "assistant", model: "test-model", text: longResponse },
				],
			});
			const state = stateForTest();
			state.baseCwd = root;
			const component = new SubagentFleetComponent(
				{ terminal: { rows: 32, columns: 100 }, requestRender() {} } as never,
				theme as never,
				state,
				() => {},
				{ asyncDirRoot: root, resultsDir: path.join(root, "results"), refreshMs: 60_000, markdownTheme },
			);
			try {
				let lines = component.render(100);
				assert.ok(lines.some((line) => line.includes("Conversation") && line.includes("assistant response")));
				assert.ok(lines.some((line) => line.includes("const fleet = true;")));
				assert.ok(!lines.some((line) => line.includes("very large tool payload")));
				assert.ok(!lines.some((line) => line.includes("RAW FALLBACK SHOULD NOT RENDER")));
				const bottomLines = lines;
				const realDateNow = Date.now;
				const laterNow = realDateNow() + 2_000;
				Date.now = () => laterNow;
				try {
					component.handleInput("K");
					lines = component.render(100);
					assert.notDeepEqual(lines, bottomLines, "Shift+K should scroll the conversation up by one line");
					component.handleInput("J");
					lines = component.render(100);
					assert.deepEqual(lines, bottomLines, "Shift+J should scroll the conversation back down by one line");
				} finally {
					Date.now = realDateNow;
				}
				for (let page = 0; page < 4; page++) component.handleInput("\x1b[5~");
				lines = component.render(100);
				assert.ok(lines.some((line) => line.includes("Conversation") && line.includes("assistant response")), "the conversation header should remain pinned while scrolling");
				assert.ok(lines.some((line) => line.includes("✓ read") && line.includes("src/tui/fleet.ts")), "page up should reveal compact tool activity");
				assert.ok(lines.some((line) => line.includes("Assistant") && line.includes("test-model")), "page up should reveal the rendered assistant message header");
				for (const renderWidth of [60, 80, 100]) {
					for (const line of component.render(renderWidth)) {
						assert.ok(visibleWidth(line) <= renderWidth, `line exceeded ${renderWidth} columns: ${line}`);
					}
				}
			} finally {
				component.dispose();
			}
		} finally {
			fs.rmSync(root, { recursive: true, force: true });
		}
	});

	it("uses parent-tracked async state and cwd without rescanning status", () => {
		const root = fs.mkdtempSync(path.join(os.tmpdir(), "pi-fleet-async-cwd-"));
		try {
			const asyncDir = path.join(root, "async-custom-cwd");
			const customCwd = path.join(root, "custom-cwd");
			const artifactsRoot = getProjectArtifactsDir(customCwd);
			fs.mkdirSync(asyncDir, { recursive: true });
			fs.mkdirSync(artifactsRoot, { recursive: true });
			const transcriptPath = path.join(artifactsRoot, "async-custom-cwd_worker_transcript.jsonl");
			fs.writeFileSync(transcriptPath, `${JSON.stringify({ recordType: "message", role: "assistant", text: "Custom cwd async result" })}\n`, "utf-8");
			fs.writeFileSync(path.join(asyncDir, "status.json"), "{in-flight status", "utf-8");
			const state = stateForTest();
			state.baseCwd = path.join(root, "parent-cwd");
			state.artifactDirPreference = "project";
			state.asyncJobs.set("async-custom-cwd", {
				asyncId: "async-custom-cwd",
				asyncDir,
				cwd: customCwd,
				sessionId: "session-current",
				status: "running",
				mode: "single",
				startedAt: 100,
				updatedAt: 200,
				steps: [{ agent: "worker", index: 0, status: "running", transcriptPath }],
			});
			const component = new SubagentFleetComponent(
				{ terminal: { rows: 28, columns: 100 }, requestRender() {} } as never,
				theme as never,
				state,
				() => {},
				{ refreshMs: 60_000, markdownTheme },
			);
			try {
				assert.ok(component.render(100).some((line) => line.includes("Custom cwd async result")));
			} finally {
				component.dispose();
			}
		} finally {
			fs.rmSync(root, { recursive: true, force: true });
		}
	});

	it("toggles bounded tool output expansion with x and Ctrl+O", () => {
		const root = fs.mkdtempSync(path.join(os.tmpdir(), "pi-fleet-tool-toggle-"));
		try {
			writeAsyncRun(root, {
				id: "async-tools",
				state: "complete",
				transcript: [
					{ recordType: "tool_start", toolCallId: "read-1", toolName: "read", argsPreview: "src/a.ts", argsPayload: JSON.stringify({ path: "src/a.ts" }), ts: 1 },
					{ recordType: "tool_end", toolCallId: "read-1", toolName: "read", ts: 2 },
					{ recordType: "message", role: "toolResult", toolCallId: "read-1", toolName: "read", text: "alpha\nbeta\ngamma", isError: false, ts: 3 },
				],
			});
			const state = stateForTest();
			state.baseCwd = root;
			let renderRequests = 0;
			const component = new SubagentFleetComponent(
				{ terminal: { rows: 32, columns: 100 }, requestRender() { renderRequests++; } } as never,
				theme as never,
				state,
				() => {},
				{ asyncDirRoot: root, resultsDir: path.join(root, "results"), refreshMs: 60_000, markdownTheme },
			);
			try {
				let lines = component.render(100);
				assert.ok(lines.some((line) => line.includes("alpha beta gamma") && line.includes("x to expand")));
				component.handleInput("x");
				lines = component.render(100);
				assert.ok(lines.some((line) => line.includes("alpha") && !line.includes("beta")));
				assert.ok(lines.some((line) => line.includes("x to collapse")));
				component.handleInput("\x0f");
				lines = component.render(100);
				assert.ok(lines.some((line) => line.includes("alpha beta gamma") && line.includes("x to expand")));
				fs.appendFileSync(
					path.join(root, "async-tools", "transcript-0.jsonl"),
					`${JSON.stringify({ recordType: "message", role: "assistant", text: "Cache refreshed after append", ts: 4 })}\n`,
					"utf-8",
				);
				lines = component.render(100);
				assert.ok(lines.some((line) => line.includes("Cache refreshed after append")));
				assert.equal(renderRequests, 2);
			} finally {
				component.dispose();
			}
		} finally {
			fs.rmSync(root, { recursive: true, force: true });
		}
	});

	it("renders the selected foreground parallel child's structured transcript", () => {
		const root = fs.mkdtempSync(path.join(os.tmpdir(), "pi-fleet-foreground-"));
		try {
			const state = stateForTest();
			state.baseCwd = path.join(root, "parent-cwd");
			state.artifactDirPreference = "project";
			const effectiveCwd = path.join(root, "effective-cwd");
			const now = Date.now();
			state.foregroundControls.set("foreground-live", {
				runId: "foreground-live",
				mode: "parallel",
				startedAt: now - 1_000,
				updatedAt: now,
				cwd: effectiveCwd,
				currentAgent: "reviewer",
				currentIndex: 1,
				description: "Review the active task",
				activeChildren: new Map([
					[0, { index: 0, agent: "worker", description: "Implement the active task", startedAt: now - 900, updatedAt: now - 100, tokens: 120, model: "provider/live-model", thinking: "high" }],
					[1, { index: 1, agent: "reviewer", description: "Review the active task", startedAt: now - 800, updatedAt: now, tokens: 240 }],
				]),
			});
			const artifactsRoot = getProjectArtifactsDir(effectiveCwd);
			fs.mkdirSync(artifactsRoot, { recursive: true });
			const transcriptPath = getArtifactPaths(artifactsRoot, "foreground-live", "worker", 0).transcriptPath;
			fs.writeFileSync(transcriptPath, `${JSON.stringify({ recordType: "message", role: "assistant", model: "test-model", text: "**Worker live result**" })}\n`, "utf-8");
			const component = new SubagentFleetComponent(
				{ terminal: { rows: 28, columns: 90 }, requestRender() {} } as never,
				theme as never,
				state,
				() => {},
				{ initialKey: "foreground-active:foreground-live:0", refreshMs: 60_000, markdownTheme },
			);
			try {
				const lines = component.render(90);
				assert.ok(lines.some((line) => line.includes("worker")));
				assert.ok(lines.some((line) => line.includes("reviewer")));
				assert.ok(lines.some((line) => line.includes("foreground · live")));
				assert.ok(lines.some((line) => line.includes("provider/live-model · thinking high")));
				assert.ok(lines.every((line) => !line.includes("Implement the active task") && !line.includes("Review the active task")));
				assert.ok(lines.some((line) => line.includes("Conversation") && line.includes("assistant response")));
				assert.ok(lines.some((line) => line.includes("Worker live result")));
			} finally {
				component.dispose();
			}
		} finally {
			fs.rmSync(root, { recursive: true, force: true });
		}
	});

	it("renders configured session and temp transcripts for active foreground, completed foreground, and async children", () => {
		const root = fs.mkdtempSync(path.join(os.tmpdir(), "pi-fleet-artifact-roots-"));
		const createdTranscriptPaths: string[] = [];
		try {
			for (const preference of ["session", "temp"] as const) {
				const baseCwd = path.join(root, `${preference}-cwd`);
				const sessionFile = path.join(root, `${preference}-session`, "session.jsonl");
				const artifactsRoot = getArtifactsDir(sessionFile, baseCwd, preference);
				const prefix = `${path.basename(root)}-${preference}`;
				fs.mkdirSync(artifactsRoot, { recursive: true });
				const transcript = (runId: string, agent: string, index: number, text: string) => {
					const transcriptPath = getArtifactPaths(artifactsRoot, runId, agent, index).transcriptPath;
					fs.writeFileSync(transcriptPath, `${JSON.stringify({ recordType: "message", role: "assistant", text })}\n`, "utf-8");
					createdTranscriptPaths.push(transcriptPath);
					return transcriptPath;
				};

				const activeId = `${prefix}-active`;
				const recentId = `${prefix}-recent`;
				const asyncId = `${prefix}-async`;
				transcript(activeId, "worker", 0, `${preference} active foreground transcript`);
				const recentTranscript = transcript(recentId, "reviewer", 0, `${preference} completed foreground transcript`);
				const asyncTranscript = transcript(asyncId, "scout", 0, `${preference} async transcript`);

				const state = stateForTest();
				state.baseCwd = baseCwd;
				state.artifactDirPreference = preference;
				state.parentSessionFile = sessionFile;
				state.foregroundControls.set(activeId, {
					runId: activeId,
					mode: "single",
					cwd: baseCwd,
					startedAt: 100,
					updatedAt: 300,
					currentAgent: "worker",
					currentIndex: 0,
				});
				state.foregroundRuns!.set(recentId, {
					runId: recentId,
					mode: "single",
					cwd: baseCwd,
					sessionId: "session-current",
					updatedAt: 200,
					children: [{ agent: "reviewer", index: 0, status: "completed", transcriptPath: recentTranscript, model: "provider/recent-model", thinking: "xhigh" }],
				});
				state.asyncJobs.set(asyncId, {
					asyncId,
					asyncDir: path.join(root, `${preference}-async-run`),
					cwd: baseCwd,
					sessionId: "session-current",
					status: "complete",
					mode: "single",
					startedAt: 100,
					updatedAt: 250,
					steps: [{ agent: "scout", index: 0, status: "complete", transcriptPath: asyncTranscript }],
				});

				for (const [initialKey, expected] of [
					[`foreground-active:${activeId}:0`, `${preference} active foreground transcript`],
					[`foreground-recent:${recentId}:0`, `${preference} completed foreground transcript`],
					[`async:${asyncId}:0`, `${preference} async transcript`],
				] as const) {
					const component = new SubagentFleetComponent(
						{ terminal: { rows: 28, columns: 100 }, requestRender() {} } as never,
						theme as never,
						state,
						() => {},
						{ initialKey, refreshMs: 60_000, markdownTheme },
					);
					try {
						const lines = component.render(100);
						assert.ok(lines.some((line) => line.includes(expected)), `missing ${expected}`);
						if (initialKey.startsWith("foreground-recent:")) {
							assert.ok(lines.some((line) => line.includes("provider/recent-model · thinking xhigh")));
						}
					} finally {
						component.dispose();
					}
				}
			}
		} finally {
			for (const transcriptPath of createdTranscriptPaths) fs.rmSync(transcriptPath, { force: true });
			fs.rmSync(root, { recursive: true, force: true });
		}
	});

	it("shows disk-only current-session async runs when the overlay opens", async () => {
		const root = fs.mkdtempSync(path.join(os.tmpdir(), "pi-fleet-overlay-reconcile-"));
		try {
			writeAsyncRun(root, { id: "disk-only", agents: ["worker"] });
			const state = stateForTest();
			let rendered = "";
			const ctx = {
				hasUI: true,
				ui: {
					setWidget() {},
					async custom(factory: (tui: unknown, theme: unknown, keybindings: unknown, done: (result: undefined) => void) => SubagentFleetComponent) {
						const component = factory({ terminal: { rows: 32 }, requestRender() {} }, theme, undefined, () => {});
						try {
							rendered = component.render(100).join("\n");
						} finally {
							component.dispose();
						}
					},
				},
			};

			await openSubagentFleet(ctx as never, state, { asyncDirRoot: root, resultsDir: path.join(root, "results") });
			assert.match(rendered, /worker/);
		} finally {
			fs.rmSync(root, { recursive: true, force: true });
		}
	});

	it("focuses an external inspector registered after Fleet opens", async (t) => {
		const owner = { events: createEventBus() };
		t.after(registerInspectorEventListener(owner));
		const root = fs.mkdtempSync(path.join(os.tmpdir(), "pi-fleet-inspect-focus-"));
		try {
			const asyncDir = writeAsyncRun(root, { id: "run-focus", agents: ["worker"] });
			const state = stateForTest();
			state.asyncJobs.set("run-focus", {
				asyncId: "run-focus",
				asyncDir,
				status: "running",
				mode: "single",
				agents: ["worker"],
				startedAt: 100,
				updatedAt: 200,
			});
			const calls: string[][] = [];
			const client: HerdrClient = {
				run: async <T>(args: string[]) => {
					calls.push(args);
					if (args[0] === "--version") return { ok: true, data: "herdr 0.7.5" as T };
					if (args[0] === "pane" && args[1] === "split") return { ok: true, data: { pane: { pane_id: "w1:p9" } } as T };
					return { ok: true, data: {} as T };
				},
			};
			const ctx = {
				hasUI: true,
				ui: {
					setWidget() {},
					async custom(factory: (tui: unknown, theme: unknown, keybindings: unknown, done: (result: undefined) => void) => SubagentFleetComponent) {
						const component = factory({ terminal: { rows: 32, columns: 100 }, requestRender() {} }, theme, undefined, () => {});
						try {
							component.render(100);
							registerInspector(owner, { ...createHerdrInspectorPlugin({ client }), name: "test-host", available: () => true });
							component.handleInput("H");
							for (let attempt = 0; attempt < 500 && !calls.some((args) => args[0] === "pane" && args[1] === "split"); attempt++) {
								await new Promise((resolve) => setImmediate(resolve));
							}
						} finally {
							component.dispose();
						}
					},
				},
			};

			await openSubagentFleet(ctx as never, state, { asyncDirRoot: root, resultsDir: path.join(root, "results"), refreshMs: 60_000, inspectorPlugins: () => getInspectorPlugins(owner), inspectorEnv: {} });
			const split = calls.find((args) => args[0] === "pane" && args[1] === "split");
			assert.ok(split, `no pane split call: ${JSON.stringify(calls)}`);
			assert.deepEqual(split.slice(-1), ["--focus"]);
		} finally {
			fs.rmSync(root, { recursive: true, force: true });
		}
	});

	it("suppresses the status widget for the full inspector lifecycle", async () => {
		const state = stateForTest();
		let hidden = 0;
		let observedOpen = false;
		const ctx = {
			hasUI: true,
			ui: {
				setWidget(key: string, content: unknown) {
					assert.equal(key, FLEET_STATUS_WIDGET_KEY);
					assert.equal(content, undefined);
					hidden++;
				},
				async custom() {
					observedOpen = state.fleetInspectorOpen === true;
					throw new Error("overlay closed");
				},
			},
		};

		await assert.rejects(openSubagentFleet(ctx as never, state), /overlay closed/);
		assert.equal(hidden, 1);
		assert.equal(observedOpen, true);
		assert.equal(state.fleetInspectorOpen, false);
	});

	it("focuses the selected child and renders raw foreground model details", () => {
		const state = stateForTest();
		state.foregroundControls.set("run-worker", {
			runId: "run-worker",
			mode: "single",
			startedAt: 10,
			updatedAt: 20,
			currentAgent: "worker",
			currentIndex: 0,
			model: "provider/raw-model",
			thinking: "medium",
		});
		state.foregroundControls.set("run-reviewer", {
			runId: "run-reviewer",
			mode: "single",
			startedAt: 11,
			updatedAt: 21,
			currentAgent: "reviewer",
			currentIndex: 0,
		});
		state.foregroundRuns!.set("run-recent", {
			runId: "run-recent",
			mode: "single",
			cwd: process.cwd(),
			sessionId: "session-current",
			updatedAt: 19,
			children: [{ agent: "reviewer", index: 0, status: "completed", model: "provider/recent-raw-model", thinking: "xhigh" }],
		});
		const component = new SubagentFleetComponent(
			{ terminal: { rows: 28, columns: 90 }, requestRender() {} } as never,
			theme as never,
			state,
			() => {},
			{ initialKey: "foreground-active:run-worker:0", refreshMs: 60_000 },
		);
		try {
			const lines = component.render(90);
			const selectedLine = lines.find((line) => line.includes("›"));
			assert.ok(selectedLine?.includes("run-work"), `unexpected selected row: ${selectedLine}`);
			assert.ok(lines.some((line) => line.includes("Model: provider/raw-model · thinking medium")));
		} finally {
			component.dispose();
		}

		const recentComponent = new SubagentFleetComponent(
			{ terminal: { rows: 28, columns: 90 }, requestRender() {} } as never,
			theme as never,
			state,
			() => {},
			{ initialKey: "foreground-recent:run-recent:0", refreshMs: 60_000 },
		);
		try {
			assert.ok(recentComponent.render(90).some((line) => line.includes("Model: provider/recent-raw-model · thinking xhigh")));
		} finally {
			recentComponent.dispose();
		}
	});

	it("steers the selected async child with an inline message", async () => {
		const root = fs.mkdtempSync(path.join(os.tmpdir(), "pi-fleet-steer-"));
		try {
			const asyncDir = writeAsyncRun(root, { id: "async-steer", agents: ["worker", "reviewer"] });
			const state = stateForTest();
			const calls: Array<{ runId: string; asyncDir: string; index?: number; message: string; mode: string }> = [];
			const component = new SubagentFleetComponent(
				{ terminal: { rows: 28, columns: 100 }, requestRender() {} } as never,
				theme as never,
				state,
				() => {},
				{
					asyncDirRoot: root,
					resultsDir: path.join(root, "results"),
					initialKey: "async:async-steer:0",
					refreshMs: 60_000,
					actions: {
						async steer(input) {
							calls.push(input);
							return { text: "Steering queued." };
						},
						stop() {
							return { text: "unused" };
						},
					},
				},
			);
			try {
				component.handleInput("s");
				assert.ok(component.render(100).some((line) => line.includes("Steer message (steer):")));
				component.handleInput("\t");
				assert.ok(component.render(100).some((line) => line.includes("Steer message (follow_up):")));
				for (const char of "please continue") component.handleInput(char);
				component.handleInput("\r");
				await new Promise((resolve) => setImmediate(resolve));
				assert.deepEqual(calls, [{ runId: "async-steer", asyncDir, index: 0, message: "please continue", mode: "follow_up" }]);
				assert.ok(component.render(100).some((line) => line.includes("Steering queued.")));
			} finally {
				component.dispose();
			}
		} finally {
			fs.rmSync(root, { recursive: true, force: true });
		}
	});

	it("opens the selected async child in an inspector", async () => {
		const root = fs.mkdtempSync(path.join(os.tmpdir(), "pi-fleet-inspector-"));
		try {
			const asyncDir = writeAsyncRun(root, { id: "async-herdr" });
			const calls: Array<{ runId: string; asyncDir: string; index?: number }> = [];
			const component = new SubagentFleetComponent(
				{ terminal: { rows: 28, columns: 100 }, requestRender() {} } as never,
				theme as never,
				stateForTest(),
				() => {},
				{
					asyncDirRoot: root,
					resultsDir: path.join(root, "results"),
					refreshMs: 60_000,
					actions: {
						async steer() { return { text: "unused" }; },
						stop() { return { text: "unused" }; },
						async inspect(input) { calls.push(input); return { text: "Inspector opened." }; },
					},
				},
			);
			try {
				component.handleInput("\r");
				await new Promise((resolve) => setImmediate(resolve));
				assert.deepEqual(calls, [{ runId: "async-herdr", asyncDir, index: 0 }]);
				component.handleInput("H");
				await new Promise((resolve) => setImmediate(resolve));
				assert.deepEqual(calls, [
					{ runId: "async-herdr", asyncDir, index: 0 },
					{ runId: "async-herdr", asyncDir, index: 0 },
				]);
				assert.ok(component.render(100).some((line) => line.includes("Inspector opened.")));
			} finally {
				component.dispose();
			}
		} finally {
			fs.rmSync(root, { recursive: true, force: true });
		}
	});

	it("confirms stop for the selected async child before calling the action", async () => {
		const root = fs.mkdtempSync(path.join(os.tmpdir(), "pi-fleet-stop-"));
		try {
			const asyncDir = writeAsyncRun(root, { id: "async-stop" });
			const state = stateForTest();
			const calls: Array<{ runId: string; asyncDir: string; index?: number }> = [];
			let inspectCalls = 0;
			const component = new SubagentFleetComponent(
				{ terminal: { rows: 28, columns: 100 }, requestRender() {} } as never,
				theme as never,
				state,
				() => {},
				{
					asyncDirRoot: root,
					resultsDir: path.join(root, "results"),
					refreshMs: 60_000,
					fleetKeybindings: { stop: ["return"] },
					actions: {
						async steer() {
							return { text: "unused" };
						},
						stop(input) {
							calls.push(input);
							return { text: "Stop requested." };
						},
						async inspect() { inspectCalls++; return { text: "unexpected" }; },
					},
				},
			);
			try {
				component.handleInput("\r");
				assert.ok(component.render(100).some((line) => line.includes("Confirm stop for async run async-stop")));
				assert.equal(inspectCalls, 0);
				component.handleInput("n");
				assert.deepEqual(calls, []);
				component.handleInput("\r");
				component.handleInput("y");
				await new Promise((resolve) => setImmediate(resolve));
				assert.deepEqual(calls, [{ runId: "async-stop", asyncDir, index: 0 }]);
				assert.ok(component.render(100).some((line) => line.includes("Stop requested.")));
			} finally {
				component.dispose();
			}
		} finally {
			fs.rmSync(root, { recursive: true, force: true });
		}
	});

	it("explains unavailable controls for completed async children", () => {
		const root = fs.mkdtempSync(path.join(os.tmpdir(), "pi-fleet-unavailable-"));
		try {
			writeAsyncRun(root, { id: "async-complete", state: "complete" });
			const state = stateForTest();
			const component = new SubagentFleetComponent(
				{ terminal: { rows: 28, columns: 100 }, requestRender() {} } as never,
				theme as never,
				state,
				() => {},
				{
					asyncDirRoot: root,
					resultsDir: path.join(root, "results"),
					refreshMs: 60_000,
					actions: {
						async steer() {
							return { text: "unused" };
						},
						stop() {
							return { text: "unused" };
						},
					},
				},
			);
			try {
				component.handleInput("s");
				assert.ok(component.render(100).some((line) => line.includes("Selected child is complete")));
			} finally {
				component.dispose();
			}
		} finally {
			fs.rmSync(root, { recursive: true, force: true });
		}
	});

	it("periodically redraws only while the overlay remains open", (t) => {
		t.mock.timers.enable({ apis: ["setTimeout"] });
		const state = stateForTest();
		let renderRequests = 0;
		let closed = false;
		const tui = { terminal: { rows: 28, columns: 90 }, requestRender: () => { renderRequests++; } };
		const component = new SubagentFleetComponent(
			tui as never,
			theme as never,
			state,
			() => { closed = true; },
			{ refreshMs: 10 },
		);
		t.mock.timers.tick(249);
		assert.equal(renderRequests, 0, "refresh cadence is bounded away from a hot loop");
		t.mock.timers.tick(1);
		assert.equal(renderRequests, 1);
		component.handleInput("\x1b");
		assert.equal(closed, true);
		t.mock.timers.tick(1_000);
		assert.equal(renderRequests, 1, "closing cancels periodic redraws");

		const disposed = new SubagentFleetComponent(
			tui as never,
			theme as never,
			state,
			() => {},
			{ refreshMs: 250 },
		);
		disposed.dispose();
		t.mock.timers.tick(1_000);
		assert.equal(renderRequests, 1, "disposing cancels periodic redraws");
	});

	it("reuses an unchanged transcript across refresh ticks and rereads it when it changes", (t) => {
		const root = fs.mkdtempSync(path.join(os.tmpdir(), "pi-fleet-transcript-reuse-"));
		let transcriptOpens = 0;
		let failNextOpen = true;
		const openSync = fsDefault.openSync;
		t.mock.method(fsDefault, "openSync", (...args: Parameters<typeof fs.openSync>) => {
			if (path.basename(String(args[0])) === "transcript-0.jsonl") {
				transcriptOpens++;
				if (failNextOpen) {
					failNextOpen = false;
					throw Object.assign(new Error("too many open files"), { code: "EMFILE" });
				}
			}
			return openSync(...args);
		});
		syncBuiltinESMExports();
		t.mock.timers.enable({ apis: ["setTimeout"] });
		const asyncDir = writeAsyncRun(root, {
			id: "reuse-running",
			state: "running",
			transcript: [{ recordType: "message", role: "assistant", text: "first alpha answer" }],
		});
		const transcriptPath = path.join(asyncDir, "transcript-0.jsonl");
		const state = stateForTest();
		state.baseCwd = root;
		const component = new SubagentFleetComponent(
			{ terminal: { rows: 32, columns: 100 }, requestRender() {} } as never,
			theme as never,
			state,
			() => {},
			{ asyncDirRoot: root, resultsDir: path.join(root, "results"), refreshMs: 250, markdownTheme },
		);
		const tickAndRender = () => {
			t.mock.timers.tick(250);
			return component.render(100);
		};
		try {
			assert.ok(!component.render(100).some((line) => line.includes("first alpha answer")), "the first read fails");
			assert.ok(tickAndRender().some((line) => line.includes("first alpha answer")), "a failed read recovers on the next tick");
			for (let tick = 0; tick < 3; tick++) assert.ok(tickAndRender().some((line) => line.includes("first alpha answer")));
			assert.equal(transcriptOpens, 2, "an unchanged transcript is read once across refresh ticks");

			fs.appendFileSync(transcriptPath, `${JSON.stringify({ recordType: "message", role: "assistant", text: "second appended answer" })}\n`);
			assert.ok(tickAndRender().some((line) => line.includes("second appended answer")), "an append shows on the next tick");

			const fixedTime = new Date(1_700_000_000_000);
			fs.utimesSync(transcriptPath, fixedTime, fixedTime);
			tickAndRender();
			const before = fs.statSync(transcriptPath, { bigint: true });
			fs.writeFileSync(transcriptPath, fs.readFileSync(transcriptPath, "utf-8").replace("second appended answer", "second replaced answer"));
			fs.utimesSync(transcriptPath, fixedTime, fixedTime);
			const after = fs.statSync(transcriptPath, { bigint: true });
			assert.deepEqual([after.size, after.mtimeNs], [before.size, before.mtimeNs]);
			assert.ok(tickAndRender().some((line) => line.includes("second replaced answer")), "a same-size, same-mtime rewrite shows on the next tick");

			const opens = transcriptOpens;
			component.invalidate();
			component.render(100);
			component.handleInput("r");
			component.render(100);
			assert.equal(transcriptOpens, opens + 2, "host invalidation and the refresh key reread the transcript");
		} finally {
			component.dispose();
			t.mock.timers.reset();
			t.mock.restoreAll();
			syncBuiltinESMExports();
			fs.rmSync(root, { recursive: true, force: true });
		}
	});

	for (const malformedOnly of [false, true]) it(`reuses a readable transcript with no displayable events (${malformedOnly ? "only malformed records" : "user records only"})`, (t) => {
		const root = fs.mkdtempSync(path.join(os.tmpdir(), "pi-fleet-transcript-empty-"));
		let transcriptOpens = 0;
		const openSync = fsDefault.openSync;
		t.mock.method(fsDefault, "openSync", (...args: Parameters<typeof fs.openSync>) => {
			if (path.basename(String(args[0])) === "transcript-0.jsonl") transcriptOpens++;
			return openSync(...args);
		});
		syncBuiltinESMExports();
		t.mock.timers.enable({ apis: ["setTimeout"] });
		writeAsyncRun(root, {
			id: "user-only",
			state: "complete",
			transcript: Array.from({ length: 3 }, (_, index) => ({ recordType: "message", role: "user", text: `queued prompt ${index}` })),
		});
		if (malformedOnly) fs.writeFileSync(path.join(root, "user-only", "transcript-0.jsonl"), "not json\n[1]\n", "utf-8");
		const state = stateForTest();
		state.baseCwd = root;
		const component = new SubagentFleetComponent(
			{ terminal: { rows: 32, columns: 100 }, requestRender() {} } as never,
			theme as never,
			state,
			() => {},
			{ asyncDirRoot: root, resultsDir: path.join(root, "results"), refreshMs: 250, markdownTheme },
		);
		try {
			component.render(100);
			for (let tick = 0; tick < 3; tick++) {
				t.mock.timers.tick(250);
				component.render(100);
			}
			assert.equal(transcriptOpens, 1);
		} finally {
			component.dispose();
			t.mock.timers.reset();
			t.mock.restoreAll();
			syncBuiltinESMExports();
			fs.rmSync(root, { recursive: true, force: true });
		}
	});

	it("refreshes the roster while the overlay remains open", async () => {
		const root = fs.mkdtempSync(path.join(os.tmpdir(), "pi-fleet-refresh-"));
		try {
			const state = stateForTest();
			let renderRequests = 0;
			const tui = { terminal: { rows: 28, columns: 90 }, requestRender: () => { renderRequests++; } };
			const component = new SubagentFleetComponent(
				tui as never,
				theme as never,
				state,
				() => {},
				{ asyncDirRoot: root, resultsDir: path.join(root, "results"), refreshMs: 250 },
			);
			try {
				assert.ok(component.render(90).some((line) => line.includes("No tracked children")));
				const initialOutput = Array.from({ length: 40 }, (_, index) => `output line ${index}`).join("\n");
				const asyncDir = writeAsyncRun(root, { id: "appeared-live", output: initialOutput });
				await new Promise((resolve) => setTimeout(resolve, 275));
				let lines = component.render(90);
				assert.ok(lines.some((line) => line.includes("appeared")));
				assert.ok(lines.some((line) => line.includes("output line 39")));
				fs.appendFileSync(path.join(asyncDir, "output-0.log"), "\nLATEST LIVE OUTPUT", "utf-8");
				await new Promise((resolve) => setTimeout(resolve, 35));
				lines = component.render(90);
				assert.ok(lines.some((line) => line.includes("LATEST LIVE OUTPUT")), "live transcript should keep following new output");
				assert.ok(renderRequests > 0);
			} finally {
				component.dispose();
			}
		} finally {
			fs.rmSync(root, { recursive: true, force: true });
		}
	});

	it("selecting a child shows the bottom and reselecting returns there without per-child memory", () => {
		const root = fs.mkdtempSync(path.join(os.tmpdir(), "pi-fleet-select-follow-"));
		try {
			for (const id of ["alpha-run", "beta-run"]) {
				writeAsyncRun(root, {
					id,
					agents: [id.replace("-run", "")],
					transcript: [{ recordType: "message", role: "assistant", text: Array.from({ length: 200 }, (_, i) => `${id} line ${i}`).join("\n") }],
				});
			}
			const component = new SubagentFleetComponent(
				{ terminal: { rows: 32, columns: 100 }, requestRender() {} } as never,
				theme as never,
				stateForTest(),
				() => {},
				{ asyncDirRoot: root, resultsDir: path.join(root, "results"), refreshMs: 60_000, markdownTheme },
			);
			try {
				const opening = component.render(100);
				assert.ok(opening.some((line) => line.includes("alpha-run line 199")), "opening Fleet shows the newest output");
				assert.ok(!opening.some((line) => line.includes("alpha-run line 0")));
				for (let i = 0; i < 20; i++) component.handleInput("K");
				const scrolledAway = component.render(100);
				assert.notDeepEqual(scrolledAway, opening, "scrolling away must move the viewport");
				assert.ok(!scrolledAway.some((line) => line.includes("alpha-run line 199")));
				component.handleInput("j");
				const betaBottom = component.render(100);
				assert.ok(betaBottom.some((line) => line.includes("beta-run line 199")), "selecting a child shows its newest output");
				assert.ok(!betaBottom.some((line) => line.includes("beta-run line 0")));
				for (let i = 0; i < 20; i++) component.handleInput("K");
				const betaScrolled = component.render(100);
				assert.ok(!betaScrolled.some((line) => line.includes("beta-run line 199")));
				component.handleInput("k");
				const reselected = component.render(100);
				assert.ok(reselected.some((line) => line.includes("alpha-run line 199")), "reselecting returns to the bottom with no per-child memory");
			} finally {
				component.dispose();
			}
		} finally {
			fs.rmSync(root, { recursive: true, force: true });
		}
	});

	it("Prompt Audit opens at top, child and view changes reset top, and exiting resumes bottom follow", () => {
		const root = fs.mkdtempSync(path.join(os.tmpdir(), "pi-fleet-audit-follow-"));
		try {
			const state = stateForTest();
			state.baseCwd = root;
			state.artifactDirPreference = "project";
			const control = {
				runId: "audit-follow-run",
				sessionId: "session-current",
				mode: "parallel" as const,
				startedAt: 10,
				updatedAt: 20,
				activeChildren: new Map([
					[0, { index: 0, agent: "worker", startedAt: 10, updatedAt: 20 }],
					[1, { index: 1, agent: "reviewer", startedAt: 11, updatedAt: 21 }],
				]),
			};
			state.foregroundControls.set(control.runId, control);
			const artifactsRoot = getProjectArtifactsDir(root);
			for (const [agent, index] of [["worker", 0], ["reviewer", 1]] as const) {
				const lines = Array.from({ length: 200 }, (_, i) => `${agent} line ${i}`).join("\n");
				fs.mkdirSync(artifactsRoot, { recursive: true });
				fs.writeFileSync(getArtifactPaths(artifactsRoot, control.runId, agent, index).transcriptPath, `${JSON.stringify({ recordType: "message", role: "assistant", text: lines })}\n`);
			}
			const longLines = (prefix: string) => Array.from({ length: 60 }, (_, i) => `${prefix} ${i}`).join("\n");
			registerLivePromptAudit(control, 0, longLines("audit line"), `${longLines("audit line")}\n\n---\n${longLines("runtime line")}`);
			registerLivePromptAudit(control, 1, longLines("second audit line"), longLines("second audit line"));
			const component = new SubagentFleetComponent(
				{ terminal: { rows: 28, columns: 100 }, requestRender() {} } as never,
				theme as never,
				state,
				() => {},
				{ refreshMs: 60_000, markdownTheme },
			);
			try {
				const opening = component.render(100);
				assert.ok(opening.some((line) => line.includes("worker line 199")), "normal output follows the bottom before Prompt Audit");
				component.handleInput("p");
				const auditFrame = component.render(100);
				assert.ok(auditFrame.some((line) => line.includes("audit line 0")), "Prompt Audit opens at the top");
				assert.ok(!auditFrame.some((line) => line.includes("audit line 59")));
				// Scroll away from the top first: staying at the top would make the transition below
				// indistinguishable from preserving the existing offset.
				for (let i = 0; i < 20; i++) component.handleInput("J");
				const scrolledAudit = component.render(100);
				assert.ok(!scrolledAudit.some((line) => line.includes("audit line 0")), "scrolled away from the top before the view change");
				component.handleInput("2");
				const runtimeFrame = component.render(100);
				assert.ok(runtimeFrame.some((line) => line.includes("runtime line 0")), "view changes reset to the top");
				assert.ok(!runtimeFrame.some((line) => line.includes("runtime line 59")));
				component.handleInput("1");
				component.render(100);
				for (let i = 0; i < 20; i++) component.handleInput("J");
				const scrolledForChild = component.render(100);
				assert.ok(!scrolledForChild.some((line) => line.includes("audit line 0")), "scrolled away from the top before the child change");
				component.handleInput("j");
				const secondFrame = component.render(100);
				assert.ok(secondFrame.some((line) => line.includes("second audit line 0")), "child changes reset to the top");
				assert.ok(!secondFrame.some((line) => line.includes("second audit line 59")));
				component.handleInput("\x1b");
				const exited = component.render(100);
				assert.ok(exited.some((line) => line.includes("reviewer line 199")), "exiting Prompt Audit resumes normal output bottom follow");
				assert.ok(!exited.some((line) => line.includes("reviewer line 0")));
			} finally {
				component.dispose();
			}
		} finally {
			fs.rmSync(root, { recursive: true, force: true });
		}
	});
});
