Luigit
repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by admin

extensions/autopsy/site/app.js

Raw
const ui = Object.fromEntries(
	[...document.querySelectorAll("[id]")].map((node) => [node.id, node]),
);
const pageSize = 50;
const windowSize = 150;
let data = null;
let matchingEntries = [];
let windowEntries = [];
let windowStart = 0;
let previousCursor = null;
let nextCursor = null;
let generation = 0;
let pageController = null;
let metricsController = null;
let captureController = null;
let metricsComplete = false;
let capturesLoaded = false;
let historyError = null;
let searchTimer = null;
let scrollFrame = 0;
let pendingScope = true;
let windowScope = "";
const visibleRows = new Map();
const pinnedEntries = new Map();
const categories = [
	["Input", "input"],
	["Output", "output"],
	["Cache read", "cacheRead"],
	["Cache write", "cacheWrite"],
];
const known = (value) => typeof value === "number" && Number.isFinite(value);
const number = (value) => {
	if (!known(value)) return "Unknown";
	if (value !== 0 && Math.abs(value) < 1e-8) return value.toExponential(4);
	return value.toLocaleString(undefined, { maximumFractionDigits: 8 });
};
const dollars = (value) => (known(value) ? `$${number(value)}` : "Unknown");
const bytes = (value) => (known(value) ? `${number(value)} B` : "Unknown");
const duration = (value) =>
	known(value) ? `${number(value / 1000)} s` : "Unknown";
const timestamp = (value) =>
	typeof value === "string" && value.trim() ? Date.parse(value) : NaN;
const attributed = (value) => value || "Unattributed";

function element(tag, text, className) {
	const node = document.createElement(tag);
	if (text !== undefined) node.textContent = text;
	if (className) node.className = className;
	return node;
}

function displayTime(value) {
	const date = new Date(value);
	return Number.isNaN(date.getTime()) ? String(value) : date.toLocaleString();
}

function populateFilter(select, values, label) {
	const selected = select.value;
	select.replaceChildren(new Option(label, ""));
	for (const value of [...new Set(values)].sort()) {
		if (value) select.add(new Option(value, value));
	}
	if (
		selected &&
		![...select.options].some((option) => option.value === selected)
	)
		select.add(new Option(selected, selected));
	select.value = selected;
}

function renderMetadata() {
	ui.metadata.replaceChildren();
	for (const [label, value] of [
		["Name", data.name || "(Unnamed)"],
		["Session ID", data.sessionId],
		["Working directory", data.cwd],
		["Current leaf ID", data.leafId ?? "None"],
		["Snapshot generated", displayTime(data.generatedAt)],
	]) {
		ui.metadata.append(element("dt", label), element("dd", value));
	}
	ui.warnings.replaceChildren();
	if (data.warnings.length) {
		const box = element("div", undefined, "warnings");
		box.append(element("h3", "Warnings"));
		const list = element("ul");
		for (const warning of data.warnings) list.append(element("li", warning));
		box.append(list);
		ui.warnings.append(box);
	}
}

function sumKnown(entries, get) {
	let total = 0;
	let count = 0;
	for (const entry of entries) {
		const value = get(entry);
		if (known(value)) {
			total += value;
			count++;
		}
	}
	return { value: count ? total : null, count };
}

function table(caption, headings, rows) {
	const wrapper = element("div", undefined, "table-scroll");
	wrapper.tabIndex = 0;
	wrapper.setAttribute("role", "region");
	wrapper.setAttribute("aria-label", caption);
	const node = element("table");
	node.append(element("caption", caption));
	const head = element("thead");
	const tr = element("tr");
	for (const heading of headings) {
		const th = element("th", heading);
		th.scope = "col";
		tr.append(th);
	}
	head.append(tr);
	const body = element("tbody");
	for (const row of rows) {
		const line = element("tr");
		for (const [index, value] of row.entries()) {
			const cell = element(index === 0 ? "th" : "td");
			if (index === 0) cell.scope = "row";
			if (value instanceof Node) cell.append(value);
			else cell.textContent = String(value);
			line.append(cell);
		}
		body.append(line);
	}
	node.append(head, body);
	wrapper.append(node);
	return wrapper;
}

function disclosure(label, ...nodes) {
	const details = element("details", undefined, "dashboard-details");
	details.append(element("summary", label), ...nodes);
	return details;
}

async function openEntry(id) {
	ui["insights-panel"].close();
	if (pendingScope) return;
	if (!visibleRows.has(id) && pageController) {
		generation++;
		pageController.abort();
		pageController = null;
	}
	if (!visibleRows.has(id)) await loadPage("around", id);
	const details = visibleRows.get(id)?.node;
	if (!details) {
		showStatus("Entry is unavailable in this filtered history.");
		return;
	}
	details.open = true;
	details.querySelector("summary").focus();
	details.scrollIntoView({ block: "nearest" });
}

function entryButton(entry) {
	const button = element("button", entry.id, "entry-link");
	button.type = "button";
	button.dataset.entryId = entry.id;
	button.addEventListener("click", () => openEntry(entry.id));
	return button;
}

function renderUsage(entries) {
	const used = entries.filter((entry) => entry.usage != null);
	ui["usage-chart"].replaceChildren();
	if (!used.length) {
		ui["usage-chart"].append(
			element("p", "No reported usage for matching entries."),
		);
		return;
	}
	const totals = categories.map(([label, key]) => [
		label,
		sumKnown(entries, (entry) => entry.usage?.[key]).value,
	]);
	const max = Math.max(0, ...totals.map(([, value]) => value ?? 0));
	const list = element("ul", undefined, "chart");
	for (const [label, value] of totals) {
		const item = element("li");
		item.append(element("span", label), element("strong", number(value)));
		const track = element("span", undefined, "bar-track");
		track.setAttribute("aria-hidden", "true");
		const bar = element("span", undefined, "bar");
		bar.style.width = `${max > 0 ? Math.max(0, (value / max) * 100) : 0}%`;
		track.append(bar);
		item.append(track);
		list.append(item);
	}
	const total = sumKnown(entries, (entry) => entry.usage?.totalTokens).value;
	const cost = sumKnown(entries, (entry) => entry.usage?.cost).value;
	ui["usage-chart"].append(
		element(
			"p",
			`${used.length} matching entries report usage. Category values are shown separately; they may overlap.`,
		),
		list,
		element(
			"p",
			`Reported total tokens: ${number(total)} · Stored cost: ${dollars(cost)}`,
		),
	);
}

function renderTotals(entries) {
	const rows = [];
	const metrics = [
		...categories.map(([label, key]) => [
			`${label} tokens`,
			(entry) => entry.usage?.[key],
			number,
		]),
		["Reported total tokens", (entry) => entry.usage?.totalTokens, number],
		["Stored cost", (entry) => entry.usage?.cost, dollars],
		...categories.map(([label, key]) => [
			`Stored ${label.toLowerCase()} cost`,
			(entry) => entry.usage?.costBreakdown?.[key],
			dollars,
		]),
		[
			"Stored breakdown total",
			(entry) => entry.usage?.costBreakdown?.total,
			dollars,
		],
		[
			"Current catalog estimate",
			(entry) => entry.usage?.catalogCost?.total,
			dollars,
		],
		...categories.map(([label, key]) => [
			`Catalog ${label.toLowerCase()} estimate`,
			(entry) => entry.usage?.catalogCost?.[key],
			dollars,
		]),
		[
			"Reported duration sum (not session span)",
			(entry) => entry.metrics?.durationMs,
			duration,
		],
		["Text size", (entry) => entry.metrics?.textBytes, bytes],
		["Image size", (entry) => entry.metrics?.imageBytes, bytes],
		["Total content size", (entry) => entry.metrics?.totalBytes, bytes],
	];
	for (const [label, get, format] of metrics) {
		const total = sumKnown(entries, get);
		rows.push([
			label,
			format(total.value),
			`${total.count}/${entries.length} known`,
			entries.length - total.count,
		]);
	}
	const cards = element("div", undefined, "dashboard-cards");
	for (const [id, label, get, format] of [
		["stored-cost", "Stored cost", (entry) => entry.usage?.cost, dollars],
		[
			"catalog-cost",
			"Current catalog estimate",
			(entry) => entry.usage?.catalogCost?.total,
			dollars,
		],
		["tokens", "Reported tokens", (entry) => entry.usage?.totalTokens, number],
		[
			"duration",
			"Measured duration sum",
			(entry) => entry.metrics?.durationMs,
			duration,
		],
		[
			"size",
			"Recorded content size",
			(entry) => entry.metrics?.totalBytes,
			bytes,
		],
	]) {
		const total = sumKnown(entries, get);
		const card = element("div", undefined, "dashboard-card");
		card.dataset.metric = id;
		card.append(
			element("h4", label),
			element("strong", format(total.value), "card-value"),
			element(
				"small",
				`${total.count}/${entries.length} entries known`,
				"card-coverage",
			),
		);
		cards.append(card);
	}
	const totals = disclosure(
		"Detailed totals and cost breakdown",
		table(
			"Filtered totals",
			["Metric", "Known subtotal", "Coverage", "Unknown / not applicable"],
			rows,
		),
	);
	ui["dashboard-totals"].replaceChildren(
		cards,
		element(
			"p",
			"Partial totals sum known values only. Missing ≠ zero. Coverage includes all matching entries; fields may not apply to every entry. Measured durations can overlap, so their sum is not elapsed time.",
		),
		totals,
	);
	const sources = new Map();
	for (const entry of entries) {
		if (!entry.usage) continue;
		const source = entry.usage.costSource || "Unknown source";
		if (!sources.has(source)) sources.set(source, []);
		sources.get(source).push(entry);
	}
	totals.append(
		element(
			"p",
			"Stored costs retain their source: provider, recorded, or catalog fallback. Current catalog estimates use today's available prices, not historical billing. Missing catalog matches remain unknown.",
		),
		table(
			"Stored cost provenance",
			["Source", "Entries", "Known stored cost", "Cost coverage"],
			[...sources].map(([source, group]) => {
				const total = sumKnown(group, (entry) => entry.usage?.cost);
				return [
					source,
					group.length,
					dollars(total.value),
					`${total.count}/${group.length}`,
				];
			}),
		),
	);
}

function renderGroups(entries) {
	const details = disclosure("Totals by provider and model");
	ui["dashboard-groups"].replaceChildren(details);
	for (const key of ["provider", "model"]) {
		const groups = new Map();
		for (const entry of entries) {
			const name =
				key === "model"
					? JSON.stringify([entry.provider || null, entry.model || null])
					: entry.provider || null;
			if (!groups.has(name)) groups.set(name, []);
			groups.get(name).push(entry);
		}
		const rows = [...groups.values()].map((group) => {
			const first = group[0];
			const tokens = sumKnown(group, (entry) => entry.usage?.totalTokens);
			const stored = sumKnown(group, (entry) => entry.usage?.cost);
			const catalog = sumKnown(
				group,
				(entry) => entry.usage?.catalogCost?.total,
			);
			return [
				key === "model"
					? `${attributed(first.provider)} / ${attributed(first.model)}`
					: attributed(first.provider),
				group.length,
				number(tokens.value),
				`${tokens.count}/${group.length}`,
				dollars(stored.value),
				`${stored.count}/${group.length}`,
				dollars(catalog.value),
				`${catalog.count}/${group.length}`,
			];
		});
		details.append(
			table(
				`Totals by ${key}`,
				[
					key === "model" ? "Provider / model" : "Provider",
					"Entries",
					"Tokens",
					"Token coverage",
					"Stored USD",
					"Stored coverage",
					"Catalog USD",
					"Catalog coverage",
				],
				rows,
			),
		);
	}
}

function renderTimingAndSizes(entries) {
	const timed = entries.filter((entry) => known(timestamp(entry.timestamp)));
	const first = timed[0];
	const last = timed.at(-1);
	const span = timed.length
		? timestamp(last.timestamp) - timestamp(first.timestamp)
		: null;
	const gaps = [];
	for (let index = 1; index < timed.length; index++) {
		gaps.push({
			before: timed[index - 1],
			after: timed[index],
			value:
				timestamp(timed[index].timestamp) -
				timestamp(timed[index - 1].timestamp),
		});
	}
	gaps.sort((a, b) => b.value - a.value);
	ui["dashboard-timing"].replaceChildren(
		element("h3", "Time and gaps"),
		element(
			"p",
			`Filtered timestamp span: ${duration(span)} · ${first ? displayTime(first.timestamp) : "Unknown"} to ${last ? displayTime(last.timestamp) : "Unknown"}. Timestamp coverage: ${timed.length}/${entries.length}.`,
		),
		element(
			"p",
			"Span is first-to-last entry time, not model runtime. Reported durations can overlap. Gaps are adjacent timestamped matching entry differences, not inferred request durations; filtering can enlarge gaps.",
		),
		disclosure(
			"Largest timestamp gaps",
			table(
				"Largest timestamp gaps (up to 10)",
				["Following entry", "Previous entry", "Gap", "Following timestamp"],
				gaps
					.slice(0, 10)
					.map((gap) => [
						entryButton(gap.after),
						gap.before.id,
						duration(gap.value),
						displayTime(gap.after.timestamp),
					]),
			),
		),
	);
	const largest = entries
		.filter((entry) => known(entry.metrics?.totalBytes))
		.sort((a, b) => b.metrics.totalBytes - a.metrics.totalBytes)
		.slice(0, 10);
	ui["dashboard-sizes"].replaceChildren(
		disclosure(
			"Largest entries by content size",
			element(
				"p",
				"Content sizes count UTF-8 text/thinking/sections/summaries and decoded image bytes, not tool arguments, metadata, JSON file size, or context tokens. Unknown sizes remain unknown.",
			),
			table(
				"Largest entries by total content bytes (up to 10)",
				["Entry", "Text", "Images", "Total", "Image count"],
				largest.map((entry) => [
					entryButton(entry),
					bytes(entry.metrics.textBytes),
					bytes(entry.metrics.imageBytes),
					bytes(entry.metrics.totalBytes),
					number(entry.metrics?.imageCount),
				]),
			),
		),
	);
}

function svgElement(tag, attributes, text) {
	const node = document.createElementNS("http://www.w3.org/2000/svg", tag);
	for (const [key, value] of Object.entries(attributes))
		node.setAttribute(key, String(value));
	if (text !== undefined) node.textContent = text;
	return node;
}

function timeline(title, entries, series, format) {
	const section = element("section", undefined, "timeline");
	section.append(element("h4", title));
	const timed = entries.filter((entry) => known(timestamp(entry.timestamp)));
	const limit = Math.floor(200 / series.length);
	let eligibleCount = 0;
	const samples = series.map((item) => {
		const eligible = timed.filter((entry) => known(item.get(entry)));
		eligibleCount += eligible.length;
		const sampled =
			eligible.length <= limit
				? eligible
				: Array.from(
						{ length: limit },
						(_, index) =>
							eligible[
								Math.round((index * (eligible.length - 1)) / (limit - 1))
							],
					);
		return new Set(sampled);
	});
	const points = timed.filter((entry) =>
		samples.some((sample) => sample.has(entry)),
	);
	const values = points.map((entry) =>
		series.map((item, index) =>
			samples[index].has(entry) ? item.get(entry) : null,
		),
	);
	let max = 0;
	let min = 0;
	let count = 0;
	for (const row of values)
		for (const value of row)
			if (known(value)) {
				max = Math.max(max, value);
				min = Math.min(min, value);
				count++;
			}
	section.append(
		element(
			"p",
			`${timed.length} timestamped entries · ${points.length} sampled entry positions · ${count}/${eligibleCount} known values plotted. Each series samples only its known values. ${timed.length < entries.length ? `${entries.length - timed.length} entries lack valid timestamps.` : ""}`,
		),
	);
	const legend = element("ul", undefined, "timeline-legend");
	for (const [index, item] of series.entries())
		legend.append(element("li", item.label, `series-${index}`));
	section.append(legend);
	if (!count)
		section.append(
			element("p", "No known values at valid timestamps for this chart."),
		);
	else {
		const svg = svgElement("svg", {
			viewBox: "0 0 800 260",
			role: "group",
			"aria-label": `${title}. Horizontal axis: actual entry time. Vertical axis: ${format(min)} to ${format(max)}.`,
		});
		svg.append(svgElement("title", {}, title));
		svg.append(
			svgElement("path", { d: "M70 20 V210 H780", class: "timeline-axis" }),
		);
		const start = timestamp(timed[0].timestamp);
		const end = timestamp(timed.at(-1).timestamp);
		svg.append(
			svgElement("text", { x: 70, y: 235 }, displayTime(timed[0].timestamp)),
			svgElement(
				"text",
				{ x: 780, y: 252, "text-anchor": "end" },
				displayTime(timed.at(-1).timestamp),
			),
		);
		svg.append(
			svgElement("text", { x: 4, y: 20 }, format(max)),
			svgElement("text", { x: 4, y: 210 }, format(min)),
		);
		for (const [seriesIndex, item] of series.entries()) {
			for (const [index, entry] of points.entries()) {
				const value = values[index][seriesIndex];
				if (!known(value)) continue;
				const label = `${item.label}: ${format(value)} · ${displayTime(entry.timestamp)} · Entry ${entry.id}`;
				const point = svgElement("circle", {
					cx:
						start === end
							? 425
							: 70 +
								((timestamp(entry.timestamp) - start) / (end - start)) * 710,
					cy: max === min ? 115 : 210 - ((value - min) / (max - min)) * 190,
					r: 4,
					class: `timeline-point series-${seriesIndex}`,
					tabindex: 0,
					role: "button",
					"aria-label": label,
					"data-entry-id": entry.id,
				});
				point.append(svgElement("title", {}, label));
				point.addEventListener("click", () => openEntry(entry.id));
				point.addEventListener("keydown", (event) => {
					if (event.key === "Enter" || event.key === " ") {
						event.preventDefault();
						openEntry(entry.id);
					}
				});
				svg.append(point);
			}
		}
		const plot = element("div", undefined, "timeline-plot");
		plot.tabIndex = 0;
		plot.setAttribute("role", "region");
		plot.setAttribute(
			"aria-label",
			`${title} plot; scroll horizontally on small screens`,
		);
		plot.append(svg);
		section.append(plot);
	}
	const details = element("details");
	details.append(
		element("summary", "Accessible sampled chart data"),
		table(
			title,
			["Entry", "Timestamp", ...series.map((item) => item.label)],
			points.map((entry, index) => [
				entryButton(entry),
				displayTime(entry.timestamp),
				...values[index].map((value, seriesIndex) =>
					known(value)
						? format(value)
						: known(series[seriesIndex].get(entry))
							? "Not sampled"
							: "Unknown",
				),
			]),
		),
	);
	section.append(details);
	return section;
}

function renderTimelines(entries) {
	let stored = 0;
	let catalog = 0;
	let storedCount = 0;
	let catalogCount = 0;
	const cumulative = new Map();
	for (const entry of entries) {
		// Untimed entries cannot be located on an actual-time cumulative curve.
		if (!known(timestamp(entry.timestamp))) continue;
		if (known(entry.usage?.cost)) {
			stored += entry.usage.cost;
			storedCount++;
		}
		if (known(entry.usage?.catalogCost?.total)) {
			catalog += entry.usage.catalogCost.total;
			catalogCount++;
		}
		cumulative.set(entry.id, {
			stored: storedCount ? stored : null,
			catalog: catalogCount ? catalog : null,
		});
	}
	const charts = {
		cost: [
			"Cost per usage entry (USD)",
			[
				{ label: "Stored cost", get: (entry) => entry.usage?.cost },
				{
					label: "Current catalog estimate",
					get: (entry) => entry.usage?.catalogCost?.total,
				},
			],
			dollars,
		],
		cumulative: [
			"Cumulative known cost (USD, timestamped entries only)",
			[
				{
					label: "Stored cumulative",
					get: (entry) => cumulative.get(entry.id)?.stored,
				},
				{
					label: "Catalog cumulative",
					get: (entry) => cumulative.get(entry.id)?.catalog,
				},
			],
			dollars,
		],
		tokens: [
			"Reported tokens per entry",
			[
				...categories.map(([label, key]) => ({
					label,
					get: (entry) => entry.usage?.[key],
				})),
				{ label: "Reported total", get: (entry) => entry.usage?.totalTokens },
			],
			number,
		],
		duration: [
			"Measured duration per entry",
			[
				{
					label: "Model response",
					get: (entry) =>
						entry.role === "assistant" ? entry.metrics?.durationMs : null,
				},
				{
					label: "Tool execution",
					get: (entry) =>
						entry.role === "toolResult" ? entry.metrics?.durationMs : null,
				},
				{
					label: "Other recorded",
					get: (entry) =>
						entry.role !== "assistant" && entry.role !== "toolResult"
							? entry.metrics?.durationMs
							: null,
				},
			],
			duration,
		],
		size: [
			"Recorded content size per entry",
			[
				{ label: "Text", get: (entry) => entry.metrics?.textBytes },
				{ label: "Images", get: (entry) => entry.metrics?.imageBytes },
				{ label: "Total", get: (entry) => entry.metrics?.totalBytes },
			],
			bytes,
		],
	};
	const [title, series, format] =
		charts[ui["timeline-view"].value] ?? charts.cost;
	ui["dashboard-timelines"].replaceChildren(
		timeline(title, entries, series, format),
	);
}

function imageSummary(image, ordinal) {
	return `Image ${ordinal + 1} · ${image.mimeType} · ${bytes(image.bytes)} · ${known(image.width) && known(image.height) ? `${image.width} × ${image.height} px` : "Unknown dimensions"}`;
}

function imagePreview(entry, image, ordinal) {
	const viewer = element("details", undefined, "image-viewer");
	viewer.append(element("summary", imageSummary(image, ordinal)));
	viewer.dataset.imageIndex = String(image.index);
	viewer.dataset.imageOrdinal = String(ordinal);
	viewer.dataset.mimeType = image.mimeType;
	const content = element("div", undefined, "image-content");
	viewer.append(content);
	viewer.addEventListener("toggle", () => {
		content.replaceChildren();
		if (!viewer.open) return;
		const status = element("p", "Loading image…", "image-status");
		status.setAttribute("role", "status");
		const viewport = element("div", undefined, "image-viewport");
		const img = element("img");
		img.alt = `Session image ${ordinal + 1}`;
		img.loading = "lazy";
		img.decoding = "async";
		const zoom = element("button", "Show original size");
		zoom.type = "button";
		zoom.disabled = true;
		zoom.setAttribute("aria-pressed", "false");
		zoom.addEventListener("click", () => {
			const original = viewport.classList.toggle("image-original");
			zoom.setAttribute("aria-pressed", String(original));
			zoom.textContent = original ? "Show preview size" : "Show original size";
		});
		img.addEventListener("load", () => {
			status.textContent = `${img.naturalWidth} × ${img.naturalHeight} px`;
			zoom.disabled = false;
		});
		img.addEventListener("error", () => {
			status.textContent =
				"Image unavailable: unsupported, invalid, or exceeds preview limits (4 MiB, 16 Mi-pixels, 16384 px per side).";
		});
		viewport.append(img);
		content.append(status, zoom, viewport);
		img.src = `image/${encodeURIComponent(entry.id)}/${image.index}`;
	});
	return viewer;
}

// Each stream owns its partial DOM and cancellation; a retry starts from the beginning.
function detailStream(entryState, kind, root, status, retry) {
	let controller = null;
	let complete = false;
	let generation = 0;
	const start = async () => {
		if (!root.isConnected || controller || complete) return;
		const entry = entryState.current;
		const current = ++generation;
		controller = new AbortController();
		const signal = controller.signal;
		root.replaceChildren();
		retry.hidden = true;
		status.textContent = "Loading complete content…";
		let pre = kind === "json" ? element("pre", undefined, "json-code") : null;
		if (pre) root.append(pre);
		let inString = false;
		let escaped = false;
		let work = 0;
		let stringNode = null;
		let previousString = null;
		let tokenCount = 0;
		const appendPlain = (part) => {
			const next = part.match(/\S/u)?.[0];
			if (previousString && next) {
				if (next === ":") previousString.className = "json-key";
				previousString = null;
			}
			let cursor = 0;
			for (const match of part.matchAll(
				/-?\d+(?:\.\d+)?(?:[eE][+-]?\d+)?|\b(?:true|false|null)\b/gu,
			)) {
				if (++tokenCount > 10000) break;
				pre.append(document.createTextNode(part.slice(cursor, match.index)));
				pre.append(
					element(
						"span",
						match[0],
						/^(?:true|false|null)$/u.test(match[0])
							? "json-literal"
							: "json-number",
					),
				);
				cursor = match.index + match[0].length;
			}
			pre.append(document.createTextNode(part.slice(cursor)));
		};
		const appendJson = (text) => {
			// Highlight only a bounded prefix; all remaining content stays available.
			if (work >= 200000 || tokenCount >= 10000) {
				pre.append(document.createTextNode(text));
				return;
			}
			work += text.length;
			let cursor = 0;
			while (cursor < text.length) {
				if (inString) {
					const start = cursor;
					while (cursor < text.length) {
						const c = text[cursor++];
						if (escaped) escaped = false;
						else if (c === "\\") escaped = true;
						else if (c === '"') {
							inString = false;
							break;
						}
					}
					stringNode.append(document.createTextNode(text.slice(start, cursor)));
					if (!inString) {
						previousString = stringNode;
						stringNode = null;
					}
				} else {
					const quote = text.indexOf('"', cursor);
					const end = quote < 0 ? text.length : quote;
					appendPlain(text.slice(cursor, end));
					if (quote < 0) break;
					if (++tokenCount > 10000) {
						pre.append(document.createTextNode(text.slice(quote)));
						return;
					}
					previousString = null;
					stringNode = element("span", '"', "json-string");
					pre.append(stringNode);
					inString = true;
					escaped = false;
					cursor = quote + 1;
				}
			}
		};
		try {
			const response = await fetch(
				`entry/${encodeURIComponent(entry.id)}/${kind}`,
				{ cache: "no-store", referrerPolicy: "no-referrer", signal },
			);
			if (!response.ok) throw new Error(`HTTP ${response.status}`);
			if (!response.body) throw new Error("Streaming response unavailable");
			const reader = response.body.getReader();
			const decoder = new TextDecoder();
			let pending = "";
			let ended = false;
			let batch = 0;
			let lastYield = performance.now();
			let imageOrdinal = 0;
			while (!ended) {
				const { value, done } = await reader.read();
				if (signal.aborted || current !== generation) return;
				pending += decoder.decode(value, { stream: !done });
				if (done && pending.length) pending += "\n";
				for (
					let newline = pending.indexOf("\n");
					newline !== -1;
					newline = pending.indexOf("\n")
				) {
					if (newline > 1024 * 1024)
						throw new Error("Detail record exceeds buffer limit");
					const line = pending.slice(0, newline);
					pending = pending.slice(newline + 1);
					if (!line.trim()) continue;
					const event = JSON.parse(line);
					if (event.type === "end") {
						ended = true;
						break;
					}
					if (event.type === "error")
						throw new Error(event.message || "Stream failed");
					if (event.type === "text" && typeof event.text === "string") {
						if (kind === "json") appendJson(event.text);
						else {
							if (!pre) {
								pre = element("pre");
								root.append(pre);
							}
							pre.append(document.createTextNode(event.text));
						}
					} else if (
						kind === "text" &&
						event.type === "image" &&
						Number.isInteger(event.index) &&
						typeof event.mimeType === "string"
					) {
						pre = null;
						root.append(
							imagePreview(
								entry,
								{
									...entryState.current.images.find(
										(image) => image.index === event.index,
									),
									...event,
								},
								imageOrdinal++,
							),
						);
					} else throw new Error("Invalid detail record");
					status.textContent = "Loading… partial content shown.";
					if (++batch >= 64 || performance.now() - lastYield >= 8) {
						await new Promise((resolve) => setTimeout(resolve, 0));
						batch = 0;
						lastYield = performance.now();
					}
					if (signal.aborted || current !== generation) return;
				}
				if (pending.length > 1024 * 1024)
					throw new Error("Detail record exceeds buffer limit");
				if (done && !ended)
					throw new Error("Stream ended without completion record");
			}
			if (signal.aborted || current !== generation) return;
			complete = true;
			if (!root.childNodes.length) root.append(element("pre", "(No text)"));
			status.textContent = "";
			reader.cancel().catch(() => {});
		} catch (error) {
			if (!signal.aborted && current === generation) {
				controller.abort();
				status.textContent = `Load failed: ${error instanceof Error ? error.message : String(error)}. Partial content may be shown.`;
				retry.hidden = false;
			}
		} finally {
			if (current === generation) controller = null;
		}
	};
	retry.addEventListener("click", start);
	return {
		start,
		abort() {
			if (controller) {
				controller.abort();
				controller = null;
				generation++;
				status.textContent = "Loading stopped; partial content shown.";
				retry.hidden = false;
			}
		},
	};
}

function renderEntries() {
	if (!data) return;
	const visible = [
		...windowEntries.map((entry, index) => ({
			entry,
			index: windowStart + index,
		})),
	];
	for (const [id, pinned] of pinnedEntries) {
		if (windowEntries.some((entry) => entry.id === id))
			pinnedEntries.delete(id);
		else if (keepRow(visibleRows.get(id))) visible.push(pinned);
		else pinnedEntries.delete(id);
	}
	visible.sort((a, b) => a.index - b.index);
	const entries = visible.map((item) => item.entry);
	const ids = new Set(entries.map((entry) => entry.id));
	for (const [id, row] of visibleRows) {
		if (!ids.has(id)) {
			row.dispose();
			row.node.remove();
			visibleRows.delete(id);
		}
	}
	for (const [position, entry] of entries.entries()) {
		const signature = JSON.stringify([
			entry.id,
			entry.parentId,
			entry.role,
			entry.type,
			entry.timestamp,
			entry.text,
			entry.raw,
			entry.images.map((image) => [image.index, image.mimeType]),
			entry.toolNames,
			entry.provider,
			entry.model,
			entry.previewTruncated,
		]);
		let row = visibleRows.get(entry.id);
		if (row && row.signature !== signature) {
			row.dispose();
			row.node.remove();
			visibleRows.delete(entry.id);
			row = null;
		}
		if (row) {
			row.update(entry);
			row.branch.textContent = entry.onBranch ? "" : "Other branch";
			const at = ui.entries.children[position];
			if (at !== row.node) ui.entries.insertBefore(row.node, at || null);
			continue;
		}
		const details = element("details", undefined, "entry");
		details.dataset.entryId = entry.id;
		const summary = element("summary");
		const branch = element(
			"span",
			entry.onBranch ? "" : "Other branch",
			"entry-branch",
		);
		const heading = element("div", undefined, "entry-heading");
		const roles = {
			user: "You",
			assistant: "Assistant",
			system: "System",
			toolResult: "Tool",
		};
		const role = element(
			"strong",
			roles[entry.role] || entry.role || entry.type,
			"entry-role",
		);
		role.classList.toggle("assistant", entry.role === "assistant");
		role.classList.toggle("system", entry.role === "system");
		if (entry.toolNames.length)
			role.append(document.createTextNode(` · ${entry.toolNames.join(", ")}`));
		const time = element("time", undefined, "entry-time");
		const date = new Date(entry.timestamp);
		time.textContent = Number.isNaN(date.getTime())
			? "Unknown time"
			: date.toLocaleTimeString(undefined, {
					hour: "2-digit",
					minute: "2-digit",
				});
		time.dateTime = entry.timestamp;
		time.title = displayTime(entry.timestamp);
		const context = element("div", undefined, "entry-context");
		if (entry.role === "assistant" && entry.model)
			context.append(element("span", entry.model, "entry-model"));
		context.append(time, branch);
		heading.append(role, context);
		summary.append(heading);
		const preview = entry.text || "(No text)";
		const lines = preview.split("\n", 5);
		let short = lines.slice(0, 4).join("\n");
		const clipped = lines.length > 4 || short.length > 600;
		short = short.slice(0, 600);
		summary.append(element("span", short, "entry-preview"));
		summary.title =
			clipped || entry.previewTruncated ? "Open complete content" : "";
		details.append(summary);
		const body = element("div", undefined, "entry-body");
		const meta = element("dl", undefined, "entry-meta");
		const measurements = disclosure("Usage and size measurements");
		const entryState = { current: entry };
		let measuredSignature = "";
		const update = (nextEntry) => {
			entryState.current = nextEntry;
			const nextSignature = JSON.stringify([
				nextEntry.metrics,
				nextEntry.usage,
				nextEntry.images,
			]);
			if (nextSignature === measuredSignature) return;
			measuredSignature = nextSignature;
			const entry = nextEntry;
			meta.replaceChildren();
			for (const [label, value] of [
				["ID", entry.id],
				["Parent ID", entry.parentId ?? "None"],
				["Recorded at", displayTime(entry.timestamp)],
				["Tools", entry.toolNames.join(", ") || "None"],
				...(entry.provider || entry.usage
					? [["Provider", entry.provider || "Unknown identity"]]
					: []),
				...(entry.model || entry.usage
					? [["Model", entry.model || "Unknown identity"]]
					: []),
				["Reported duration", duration(entry.metrics?.durationMs)],
				["Content size", bytes(entry.metrics?.totalBytes)],
				["Stored cost", dollars(entry.usage?.cost)],
			])
				meta.append(element("dt", label), element("dd", value));
			const title = measurements.firstElementChild;
			measurements.replaceChildren(
				title,
				table(
					"Entry measurements",
					["Metric", "Value"],
					[
						[
							"Recorded request start",
							entry.metrics?.startedAt
								? displayTime(entry.metrics.startedAt)
								: "Unknown",
						],
						["Text bytes", bytes(entry.metrics?.textBytes)],
						["Image bytes", bytes(entry.metrics?.imageBytes)],
						["Images", number(entry.metrics?.imageCount)],
						...categories.map(([label, key]) => [
							`${label} tokens`,
							number(entry.usage?.[key]),
						]),
						["Reported total tokens", number(entry.usage?.totalTokens)],
						["Stored cost source", entry.usage?.costSource ?? "Unknown"],
						...categories.map(([label, key]) => [
							`Stored ${label.toLowerCase()} cost`,
							dollars(entry.usage?.costBreakdown?.[key]),
						]),
						[
							"Current catalog estimate (USD)",
							dollars(entry.usage?.catalogCost?.total),
						],
						...categories.map(([label, key]) => [
							`Catalog ${label.toLowerCase()} estimate`,
							dollars(entry.usage?.catalogCost?.[key]),
						]),
					],
				),
			);
			for (const viewer of body.querySelectorAll(".image-viewer")) {
				const image = entry.images.find(
					(item) => String(item.index) === viewer.dataset.imageIndex,
				) ?? { mimeType: viewer.dataset.mimeType };
				viewer.querySelector("summary").textContent = imageSummary(
					image,
					Number(viewer.dataset.imageOrdinal),
				);
			}
		};
		update(entry);
		const metadata = disclosure("Metadata", meta, measurements);
		metadata.classList.add("entry-metadata");
		const textRoot = element("div", undefined, "entry-full-text");
		const textStatus = element("p", "Not loaded.", "entry-load-status");
		textStatus.setAttribute("role", "status");
		const textRetry = element("button", "Retry text");
		textRetry.type = "button";
		textRetry.hidden = true;
		const textStream = detailStream(
			entryState,
			"text",
			textRoot,
			textStatus,
			textRetry,
		);
		body.append(textRoot, textStatus, textRetry, metadata);
		const raw = element("details", undefined, "entry-json");
		raw.append(
			element(
				"summary",
				"Entry JSON + provider metadata (signatures included)",
			),
		);
		const jsonStatus = element("p", "Not loaded.", "entry-load-status");
		jsonStatus.setAttribute("role", "status");
		const jsonRetry = element("button", "Retry JSON");
		jsonRetry.type = "button";
		jsonRetry.hidden = true;
		const jsonRoot = element("div");
		const jsonStream = detailStream(
			entryState,
			"json",
			jsonRoot,
			jsonStatus,
			jsonRetry,
		);
		raw.append(jsonStatus, jsonRetry, jsonRoot);
		raw.addEventListener("toggle", () => {
			if (raw.open && details.open) jsonStream.start();
			else jsonStream.abort();
		});
		body.append(raw);
		details.append(body);
		const dispose = () => {
			textStream.abort();
			jsonStream.abort();
			for (const viewer of body.querySelectorAll(".image-viewer")) {
				viewer.open = false;
				viewer.querySelector(".image-content")?.replaceChildren();
			}
		};
		details.addEventListener("toggle", () => {
			if (details.open) {
				textStream.start();
				if (raw.open) jsonStream.start();
			} else dispose();
		});
		visibleRows.set(entry.id, {
			node: details,
			signature,
			branch,
			dispose,
			update,
		});
		const at = ui.entries.children[position];
		ui.entries.insertBefore(details, at || null);
	}
}

function renderPrompt() {
	const snapshot = data.prompts.find(
		(prompt) => String(prompt.id) === ui["prompt-select"].value,
	);
	ui["prompt-empty"].hidden = data.prompts.length > 0;
	ui["prompt-select"].disabled = data.prompts.length === 0;
	ui["prompt-content"].hidden = !snapshot;
	ui["prompt-meta"].textContent = snapshot
		? `ID: ${snapshot.id} · Entry ID: ${snapshot.entryId ?? "None"} · ${displayTime(snapshot.timestamp)}`
		: "";
	ui["prompt-raw"].textContent = snapshot?.prompt ?? "";
	ui["prompt-grouped"].textContent = snapshot?.grouped ?? "";
}

function showStatus(message = "") {
	ui.status.textContent = message;
	ui.status.hidden = !message;
}

function queryParams() {
	const params = new URLSearchParams();
	for (const key of ["role", "type", "branch", "provider", "model", "order"]) {
		if (ui[key].value) params.set(key, ui[key].value);
	}
	if (ui.search.value) params.set("q", ui.search.value);
	for (const key of ["from", "to"]) {
		if (ui[key].value) params.set(key, new Date(ui[key].value).toISOString());
	}
	return params;
}

function keepRow(row) {
	if (!row) return false;
	const selection = window.getSelection();
	if (row.node.open || row.node.contains(document.activeElement)) return true;
	if (selection && !selection.isCollapsed) {
		for (let index = 0; index < selection.rangeCount; index++) {
			if (selection.getRangeAt(index).intersectsNode(row.node)) return true;
		}
	}
	return false;
}

function clearRows() {
	for (const row of visibleRows.values()) row.dispose();
	visibleRows.clear();
	pinnedEntries.clear();
	ui.entries.replaceChildren();
	windowEntries = [];
	windowStart = 0;
	previousCursor = null;
	nextCursor = null;
}

function viewportAnchor() {
	const top = ui.history.getBoundingClientRect().top;
	for (const row of visibleRows.values()) {
		const rect = row.node.getBoundingClientRect();
		if (rect.bottom > top && rect.top < top + ui.history.clientHeight)
			return { node: row.node, top: rect.top };
	}
	return null;
}

function retainReaders() {
	for (const [index, entry] of windowEntries.entries()) {
		if (keepRow(visibleRows.get(entry.id)))
			pinnedEntries.set(entry.id, { entry, index: windowStart + index });
	}
}

function renderHeader() {
	ui["session-name"].textContent = data.name || "(Unnamed session)";
	document.title = `${data.name || "Session"} · Autopsy`;
	const summary = data.summary;
	ui["entry-count"].textContent =
		`${number(summary.entries)} ${summary.entries === 1 ? "entry" : "entries"}`;
	ui["scope-cost"].hidden = summary.usageEntries === 0;
	ui["scope-tokens"].hidden = summary.usageEntries === 0;
	ui["scope-cost"].textContent = `${dollars(summary.storedCost)}`;
	ui["scope-cost"].title =
		`Stored USD cost · ${summary.storedCostKnown}/${summary.entries} entries known`;
	ui["scope-tokens"].textContent = `${number(summary.tokens)} tokens`;
	ui["scope-tokens"].title =
		`${summary.tokensKnown}/${summary.entries} entries known; reported usage, not context size`;
	renderMetadata();
	populateFilter(ui.role, data.facets.roles, "All roles");
	populateFilter(ui.type, data.facets.types, "All types");
	for (const key of ["provider", "model"]) {
		const select = ui[key];
		const selected = select.value;
		select.replaceChildren(new Option(`All ${key}s`, ""));
		for (const value of data.facets[`${key}s`])
			select.add(
				new Option(value || "Unknown identity", JSON.stringify(value)),
			);
		if (
			selected &&
			![...select.options].some((option) => option.value === selected)
		)
			select.add(
				new Option(JSON.parse(selected) || "Unknown identity", selected),
			);
		select.value = selected;
	}
}

function updateSentinels(direction = null) {
	for (const [side, key] of [
		["before", "start"],
		["after", "end"],
	]) {
		ui[`history-${key}`].classList.toggle("loading", direction === side);
		ui[`${key}-status`].textContent = direction === side ? "Loading…" : "";
	}
	if (!pageController && data && !nextCursor && !historyError)
		ui["end-status"].textContent = data.summary.entries
			? "End of history."
			: "No matching entries.";
	ui["history-retry"].hidden = !historyError;
	ui["history-more"].hidden = !nextCursor && !previousCursor;
	ui.history.setAttribute("aria-busy", String(Boolean(pageController)));
}

function visibleSentinel(id) {
	const root = ui.history.getBoundingClientRect();
	const rect = ui[id].getBoundingClientRect();
	return rect.bottom >= root.top - 120 && rect.top <= root.bottom + 120;
}

function schedulePump() {
	if (scrollFrame) return;
	scrollFrame = requestAnimationFrame(() => {
		scrollFrame = 0;
		if (pageController || historyError || pendingScope || !data) return;
		if (nextCursor && visibleSentinel("history-end")) void loadPage("after");
		else if (previousCursor && visibleSentinel("history-start"))
			void loadPage("before");
	});
}

function invalidateMetrics() {
	metricsController?.abort();
	metricsController = null;
	metricsComplete = false;
	matchingEntries = [];
	ui["metrics-content"].hidden = true;
	ui["metrics-status"].textContent = "";
	ui["metrics-retry"].hidden = true;
}

async function loadPage(direction, target) {
	if (pageController) return;
	const current = generation;
	const controller = new AbortController();
	pageController = controller;
	historyError = null;
	const cursor =
		target || (direction === "after" ? nextCursor : previousCursor);
	const params = queryParams();
	const scopeKey = params.toString();
	if (
		["before", "after", "around"].includes(direction) &&
		(pendingScope || scopeKey !== windowScope)
	) {
		pageController = null;
		return;
	}
	params.set("limit", String(pageSize));
	if (["after", "before", "around"].includes(direction)) {
		if (!cursor) {
			pageController = null;
			return;
		}
		params.set(direction, cursor);
	}
	updateSentinels(direction === "before" ? "before" : "after");
	ui.refresh.disabled = direction === "refresh";
	try {
		const response = await fetch(`data?${params}`, {
			cache: "no-store",
			referrerPolicy: "no-referrer",
			signal: controller.signal,
		});
		if (!response.ok) throw new Error(`HTTP ${response.status}`);
		const next = await response.json();
		if (controller.signal.aborted || current !== generation) return;
		const sameSession = data?.sessionId === next.sessionId;
		const unchanged =
			sameSession &&
			data.revision === next.revision &&
			windowScope === scopeKey;
		if (
			data &&
			!unchanged &&
			(direction === "before" ||
				direction === "after" ||
				direction === "around")
		) {
			showStatus(
				sameSession
					? "Session changed. Refresh to continue."
					: "Active session changed. Refresh to load it.",
			);
			throw new Error("History changed while loading");
		}
		const anchor = viewportAnchor();
		const oldHeight = ui.history.scrollHeight;
		if (!sameSession && data) {
			clearRows();
			showStatus("Active session changed.");
		} else if (
			data &&
			direction === "refresh" &&
			data.revision !== next.revision
		) {
			showStatus("Session updated.");
		} else showStatus();
		if (!unchanged) {
			invalidateMetrics();
			captureController?.abort();
			capturesLoaded = false;
		}
		if (direction === "refresh" && unchanged && windowEntries.length) {
			const updated = new Map(next.entries.map((entry) => [entry.id, entry]));
			windowEntries = windowEntries.map(
				(entry) => updated.get(entry.id) || entry,
			);
		} else {
			const extend = direction === "before" || direction === "after";
			if (unchanged) retainReaders();
			else pinnedEntries.clear();
			const indexed = new Map();
			if (extend)
				for (const [index, entry] of windowEntries.entries())
					indexed.set(entry.id, { entry, index: windowStart + index });
			for (const [index, entry] of next.entries.entries())
				indexed.set(entry.id, { entry, index: next.page.start + index });
			let merged = [...indexed.values()].sort((a, b) => a.index - b.index);
			// A tall viewport must fit before pruning; otherwise two visible sentinels
			// can page back and forth forever without ever filling the viewport.
			let smallestRow = Infinity;
			for (const row of visibleRows.values()) {
				if (row.node.open) continue;
				const height = row.node.getBoundingClientRect().height;
				if (height > 0) smallestRow = Math.min(smallestRow, height);
			}
			const capacity = Math.max(
				windowSize,
				Math.ceil(
					ui.history.clientHeight /
						(Number.isFinite(smallestRow) ? smallestRow : 44),
				) + pageSize,
			);
			if (merged.length > capacity)
				merged =
					direction === "before"
						? merged.slice(0, capacity)
						: merged.slice(-capacity);
			windowEntries = merged.map((item) => item.entry);
			windowStart = merged[0]?.index ?? next.page.start;
			previousCursor = windowStart > 0 ? windowEntries[0]?.id : null;
			nextCursor =
				windowStart + windowEntries.length < next.page.total
					? windowEntries.at(-1)?.id
					: null;
			if (
				extend &&
				(direction === "after" ? nextCursor : previousCursor) === cursor
			)
				throw new Error("History cursor did not advance");
		}
		const prompts = unchanged && capturesLoaded ? data.prompts : [];
		data = { ...next, prompts };
		if (!capturesLoaded) {
			ui["prompt-select"].replaceChildren();
			renderPrompt();
		}
		windowScope = scopeKey;
		pendingScope = false;
		renderHeader();
		renderEntries();
		if (direction === "refresh" && !unchanged) ui.history.scrollTop = 0;
		else if (anchor?.node.isConnected)
			ui.history.scrollTop +=
				anchor.node.getBoundingClientRect().top - anchor.top;
		else if (direction === "before")
			ui.history.scrollTop += ui.history.scrollHeight - oldHeight;
		if (ui["insights-panel"].open && !metricsComplete) void loadMetrics();
		if (ui.captures.open && ui["session-panel"].open && !capturesLoaded)
			void loadCaptures();
	} catch (error) {
		if (!controller.signal.aborted && current === generation) {
			historyError = { direction, target };
			showStatus(
				`History load failed: ${error instanceof Error ? error.message : String(error)}. Retry or Refresh.`,
			);
		}
	} finally {
		if (current === generation && pageController === controller) {
			pageController = null;
			ui.refresh.disabled = false;
			updateSentinels();
			schedulePump();
		}
	}
}

function reload(preserve = true) {
	const from = timestamp(ui.from.value);
	const to = timestamp(ui.to.value);
	const invalid = known(from) && known(to) && from > to;
	ui.to.setCustomValidity(invalid ? "To must be on or after From." : "");
	if (invalid) {
		ui.to.reportValidity();
		return;
	}
	generation++;
	pageController?.abort();
	pageController = null;
	metricsController?.abort();
	metricsController = null;
	captureController?.abort();
	captureController = null;
	historyError = null;
	// Catalog prices can change without changing the session revision.
	invalidateMetrics();
	if (!preserve || queryParams().toString() !== windowScope) {
		pendingScope = true;
		invalidateMetrics();
		clearRows();
		// Header totals must never describe the previous filter scope.
		ui["entry-count"].textContent = "";
		ui["scope-cost"].textContent = "";
		ui["scope-tokens"].textContent = "";
		ui.history.scrollTop = 0;
	}
	void loadPage("refresh");
}

function renderDashboard(entries) {
	renderUsage(entries);
	renderTotals(entries);
	renderGroups(entries);
	renderTimingAndSizes(entries);
	renderTimelines(entries);
}

async function loadMetrics() {
	if (!data || pendingScope || metricsController || metricsComplete) return;
	const current = generation;
	const controller = new AbortController();
	metricsController = controller;
	ui["metrics-content"].hidden = true;
	ui["metrics-retry"].hidden = true;
	ui["metrics-status"].textContent = "Loading full matching scope…";
	const entries = [];
	let reader;
	try {
		const response = await fetch(`metrics?${queryParams()}`, {
			cache: "no-store",
			referrerPolicy: "no-referrer",
			signal: controller.signal,
		});
		if (!response.ok) throw new Error(`HTTP ${response.status}`);
		if (!response.body) throw new Error("Streaming response unavailable");
		reader = response.body.getReader();
		const decoder = new TextDecoder();
		let pending = "";
		let ended = false;
		let lastYield = performance.now();
		while (!ended) {
			const { value, done } = await reader.read();
			if (controller.signal.aborted || current !== generation) return;
			pending += decoder.decode(value, { stream: !done });
			if (done && pending.length) pending += "\n";
			for (
				let newline = pending.indexOf("\n");
				newline !== -1;
				newline = pending.indexOf("\n")
			) {
				if (newline > 1024 * 1024)
					throw new Error("Metric record exceeds buffer limit");
				const line = pending.slice(0, newline);
				pending = pending.slice(newline + 1);
				if (!line.trim()) continue;
				const event = JSON.parse(line);
				if (event.type === "end") {
					ended = true;
					break;
				}
				if (event.type === "error")
					throw new Error(event.message || "Metrics stream failed");
				if (event.type !== "entry" || !event.entry?.id)
					throw new Error("Invalid metric record");
				entries.push(event.entry);
				if (performance.now() - lastYield >= 8) {
					await new Promise((resolve) => setTimeout(resolve, 0));
					lastYield = performance.now();
					if (controller.signal.aborted || current !== generation) return;
				}
			}
			if (pending.length > 1024 * 1024)
				throw new Error("Metric record exceeds buffer limit");
			if (done && !ended)
				throw new Error("Metrics stream ended without completion record");
		}
		if (controller.signal.aborted || current !== generation) return;
		// Dashboard gaps and cumulative costs are chronological, independent of transcript order.
		entries.sort((left, right) => {
			const a = timestamp(left.timestamp);
			const b = timestamp(right.timestamp);
			if (known(a) !== known(b)) return known(a) ? -1 : 1;
			return known(a) && known(b) ? a - b : 0;
		});
		matchingEntries = entries;
		metricsComplete = true;
		renderDashboard(entries);
		ui["metrics-content"].hidden = false;
		ui["metrics-status"].textContent =
			`${number(entries.length)} matching entries · complete scope`;
	} catch (error) {
		if (!controller.signal.aborted && current === generation) {
			ui["metrics-status"].textContent =
				`Metrics incomplete: ${error instanceof Error ? error.message : String(error)}. No partial totals shown.`;
			ui["metrics-retry"].hidden = false;
		}
	} finally {
		reader?.cancel().catch(() => {});
		if (metricsController === controller) metricsController = null;
	}
}

async function loadCaptures() {
	if (!data || capturesLoaded || captureController) return;
	const current = generation;
	const controller = new AbortController();
	captureController = controller;
	ui["capture-status"].textContent = "Loading captures…";
	ui["capture-retry"].hidden = true;
	try {
		const response = await fetch("prompts", {
			cache: "no-store",
			referrerPolicy: "no-referrer",
			signal: controller.signal,
		});
		if (!response.ok) throw new Error(`HTTP ${response.status}`);
		const prompts = await response.json();
		if (controller.signal.aborted || current !== generation) return;
		if (!Array.isArray(prompts)) throw new Error("Invalid captures response");
		data.prompts = prompts;
		capturesLoaded = true;
		const selected = ui["prompt-select"].value;
		ui["prompt-select"].replaceChildren(
			...prompts.map(
				(prompt) =>
					new Option(
						`#${prompt.id} · ${displayTime(prompt.timestamp)}`,
						String(prompt.id),
					),
			),
		);
		if (prompts.some((prompt) => String(prompt.id) === selected))
			ui["prompt-select"].value = selected;
		else ui["prompt-select"].selectedIndex = prompts.length - 1;
		renderPrompt();
		ui["capture-status"].textContent = "";
	} catch (error) {
		if (!controller.signal.aborted && current === generation) {
			ui["capture-status"].textContent =
				`Captures unavailable: ${error instanceof Error ? error.message : String(error)}`;
			ui["capture-retry"].hidden = false;
		}
	} finally {
		if (captureController === controller) captureController = null;
	}
}

for (const name of ["filters", "insights", "session"]) {
	ui[`${name}-button`].addEventListener("click", () => {
		ui[`${name}-panel`].showModal();
		if (name === "insights") void loadMetrics();
		if (name === "session" && ui.captures.open) void loadCaptures();
	});
}
for (const button of document.querySelectorAll("[data-close]"))
	button.addEventListener("click", () => button.closest("dialog").close());
ui["insights-panel"].addEventListener("close", () => {
	metricsController?.abort();
	metricsController = null;
});
ui["session-panel"].addEventListener("close", () => {
	captureController?.abort();
	captureController = null;
});
ui.refresh.addEventListener("click", () => {
	clearTimeout(searchTimer);
	reload();
});
for (const key of [
	"role",
	"type",
	"branch",
	"provider",
	"model",
	"from",
	"to",
	"order",
])
	ui[key].addEventListener("change", () => {
		clearTimeout(searchTimer);
		reload(false);
	});
ui.search.addEventListener("input", () => {
	clearTimeout(searchTimer);
	// Immediately reject stale responses and stop the cursor pump while typing.
	pendingScope = true;
	invalidateMetrics();
	generation++;
	pageController?.abort();
	pageController = null;
	metricsController?.abort();
	metricsController = null;
	searchTimer = setTimeout(() => reload(false), 180);
});
ui["reset-filters"].addEventListener("click", () => {
	for (const key of [
		"search",
		"role",
		"type",
		"provider",
		"model",
		"from",
		"to",
	])
		ui[key].value = "";
	ui.branch.value = "current";
	ui.order.value = "newest";
	clearTimeout(searchTimer);
	reload(false);
});
function systemInstructions() {
	for (const dialog of document.querySelectorAll("dialog[open]"))
		dialog.close();
	for (const key of ["search", "type", "provider", "model", "from", "to"])
		ui[key].value = "";
	if (![...ui.role.options].some((option) => option.value === "system"))
		ui.role.add(new Option("system", "system"));
	ui.role.value = "system";
	ui.branch.value = "all";
	clearTimeout(searchTimer);
	reload(false);
	ui.history.focus();
}
ui["system-instructions"].addEventListener("click", systemInstructions);
ui["session-system"].addEventListener("click", systemInstructions);
ui["timeline-view"].addEventListener("change", () => {
	if (metricsComplete) renderTimelines(matchingEntries);
});
ui["metrics-retry"].addEventListener("click", () => void loadMetrics());
ui["history-retry"].addEventListener("click", () => {
	const failed = historyError;
	if (failed) void loadPage(failed.direction, failed.target);
});
ui["history-more"].addEventListener("click", () => {
	if (nextCursor) void loadPage("after");
	else if (previousCursor) void loadPage("before");
});
ui["prompt-select"].addEventListener("change", renderPrompt);
ui.captures.addEventListener("toggle", () => {
	if (ui.captures.open) void loadCaptures();
});
ui["capture-retry"].addEventListener("click", () => void loadCaptures());
const themes = ["system", "light", "dark"];
let theme = "system";
ui.theme.addEventListener("click", () => {
	theme = themes[(themes.indexOf(theme) + 1) % themes.length];
	if (theme === "system")
		document.documentElement.removeAttribute("data-theme");
	else document.documentElement.dataset.theme = theme;
	ui.theme.setAttribute("aria-label", `Theme: ${theme}`);
	ui.theme.title = `Theme: ${theme}`;
});
const historyObserver = new IntersectionObserver(schedulePump, {
	root: ui.history,
	rootMargin: "120px",
});
historyObserver.observe(ui["history-start"]);
historyObserver.observe(ui["history-end"]);
ui.history.addEventListener("scroll", schedulePump, { passive: true });
window.addEventListener("resize", schedulePump);
window.addEventListener("pagehide", () => {
	generation++;
	pageController?.abort();
	metricsController?.abort();
	captureController?.abort();
	for (const row of visibleRows.values()) row.dispose();
	historyObserver.disconnect();
	cancelAnimationFrame(scrollFrame);
	clearTimeout(searchTimer);
});
reload();