Skip to content

Record your screen, ship a demo. Free and open-source, GPU-accelerated, no watermarks, no subscriptions. Windows, macOS, Linux. Actively maintained.

56.6 KB
Raw Blame
import { ArrowLeft, Check, Loader2, Square, X } from "lucide-react";
import { useCallback, useEffect, useRef, useState } from "react";
import { createPortal } from "react-dom";
import { toast } from "sonner";
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
import { Tooltip } from "@/components/ui/tooltip";
import { useEditorDialogActions, useEditorDialogSection } from "@/contexts/EditorDialogsContext";
import { useScopedT } from "@/contexts/I18nContext";
import {
	applyAgentDocumentIfCurrent,
	runAgentTurn,
} from "@/lib/ai-edition/store/agentDocumentApply";
import { useProjectStore } from "@/lib/ai-edition/store/projectStore";
import { useChatPromptBus } from "@/lib/ai-edition/store/useChatPromptBus";
import { nativeBridgeClient } from "@/native/client";
import type {
	AiEditionChatEvent,
	AiEditionLlmConfig,
	AiEditionToolCallSummary,
} from "@/native/contracts";
import {
	getReasoningEffortLabel,
	getReasoningEffortOptions,
	PROVIDER_DEFINITIONS,
	type ReasoningEffort,
} from "../../../electron/ai-edition/provider-registry";
import { ChatWelcome } from "./ChatWelcome";
import { canSendChat } from "./chatAvailability";
import { adoptStoredUserMessage } from "./chatTranscript";
import { ChatHistoryModal } from "./Modals";
import styles from "./NewEditorShell.module.css";
import { useChatBudget } from "./useChatBudget";

interface ChatDisplayMessage {
	stopped?: boolean;
	id?: string;
	role: string;
	content: string;
	/** ISO timestamp, as the main process stores it; formatted only where it is drawn (#1134). */
	time?: string;
	toolCalls?: AiEditionToolCallSummary[];
	// ponytail: axcut parity — non-null on user messages that have a
	// rewind-able document snapshot, so the per-message ↩ button shows.
	checkpointId?: string | null;
	// ponytail: when an assistant message carries the model's reasoning trace
	// (Anthropic/MiniMax thinking), the chat renders it as a collapsible block
	// above the answer. Ephemeral — only present for the turn that streamed it;
	// reloading a session won't show past traces.
	thinking?: string;
}

/** A message's clock time; a stored value that is no date is shown as stored. */
function formatMessageTime(time: string): string {
	const date = new Date(time);
	return Number.isNaN(date.getTime()) ? time : date.toLocaleTimeString();
}

// Quick-access model picker anchored to the composer's model pill — mirrors
// axcut's LlmPopover in "models"/"providers" mode (a lightweight popover, not
// the full AI-settings modal). "Provider settings…" in the providers screen
// is the escape hatch into that full modal (same one the header gear opens),
// matching axcut's `openProviderSettings` from its popover's providers screen.
function ModelQuickPopover({
	anchorRect,
	llmConfig,
	connectedProviders,
	onClose,
	onConfigChange,
	onOpenFullSettings,
}: {
	anchorRect: { left: number; bottom: number; maxHeight: number };
	llmConfig: AiEditionLlmConfig;
	connectedProviders: string[];
	onClose: () => void;
	onConfigChange: () => void;
	onOpenFullSettings: () => void;
}) {
	const t = useScopedT("editor");
	const tc = useScopedT("common");
	const [screen, setScreen] = useState<"models" | "providers">("models");
	const [browseProviderId, setBrowseProviderId] = useState(llmConfig.provider);
	const [models, setModels] = useState<string[]>([]);
	const [modelsLoading, setModelsLoading] = useState(false);
	const [modelsError, setModelsError] = useState<string | null>(null);
	const [search, setSearch] = useState("");
	const [busy, setBusy] = useState(false);

	const browseDef = PROVIDER_DEFINITIONS.find((d) => d.id === browseProviderId);

	useEffect(() => {
		if (screen !== "models" || !browseProviderId) return;
		let cancelled = false;
		setModelsLoading(true);
		setModelsError(null);
		void nativeBridgeClient.aiEdition
			.llmListProviderModels(browseProviderId)
			.then((result) => {
				if (cancelled) return;
				setModels(result.models);
				setModelsError(result.error ?? null);
			})
			.catch((err) => {
				if (cancelled) return;
				setModels([]);
				setModelsError(err instanceof Error ? err.message : String(err));
			})
			.finally(() => {
				if (!cancelled) setModelsLoading(false);
			});
		return () => {
			cancelled = true;
		};
	}, [screen, browseProviderId]);

	const selectModel = async (nextModel: string) => {
		setBusy(true);
		try {
			const result = await nativeBridgeClient.aiEdition.llmSetConfig({
				...llmConfig,
				provider: browseProviderId,
				model: nextModel,
			});
			if (result.success) {
				onConfigChange();
				onClose();
			} else {
				setModelsError(result.error ?? t("chat.selectModelFailed"));
			}
		} finally {
			setBusy(false);
		}
	};

	const filteredModels = search.trim()
		? models.filter((candidate) => candidate.toLowerCase().includes(search.trim().toLowerCase()))
		: models;

	return createPortal(
		<div
			role="dialog"
			aria-modal="true"
			style={{ position: "fixed", inset: 0, zIndex: 999 }}
			onMouseDown={(event) => {
				if (event.target === event.currentTarget) onClose();
			}}
		>
			<section
				style={{
					position: "fixed",
					left: anchorRect.left,
					bottom: anchorRect.bottom,
					width: 320,
					maxHeight: anchorRect.maxHeight,
					display: "flex",
					flexDirection: "column",
					background: "var(--surface)",
					border: "1px solid var(--border)",
					borderRadius: 12,
					boxShadow: "var(--elev-pop)",
					zIndex: 1000,
					overflow: "hidden",
				}}
			>
				<div
					style={{
						display: "flex",
						alignItems: "center",
						justifyContent: "space-between",
						padding: "10px 12px",
						borderBottom: "1px solid var(--border-soft)",
					}}
				>
					<button
						type="button"
						onClick={() => setScreen(screen === "models" ? "providers" : "models")}
						style={{
							display: "flex",
							alignItems: "center",
							gap: 6,
							background: "transparent",
							border: "none",
							color: "var(--fg-2)",
							cursor: "pointer",
							fontSize: 13,
							padding: 0,
						}}
					>
						<ArrowLeft size={16} />
						{screen === "models" ? t("chat.changeProvider") : t("chat.back")}
					</button>
					<button
						type="button"
						onClick={onClose}
						aria-label={tc("actions.close")}
						className={styles.iconBtn}
					>
						<X size={16} />
					</button>
				</div>
				<div style={{ overflowY: "auto", padding: 10, minHeight: 0, flex: 1 }}>
					{screen === "models" ? (
						<>
							<div style={{ marginBottom: 8 }}>
								<div style={{ fontWeight: 600, fontSize: 13 }}>
									{browseDef?.label ?? browseProviderId}
								</div>
								<div style={{ fontSize: 12, color: "var(--muted)" }}>
									{t("chat.currentModel")}{" "}
									{browseProviderId === llmConfig.provider
										? llmConfig.model
										: (browseDef?.defaultModel ?? t("chat.notSelected"))}
								</div>
							</div>
							<input
								value={search}
								onChange={(e) => setSearch(e.target.value)}
								placeholder={modelsLoading ? t("chat.loadingModels") : t("chat.searchModels")}
								disabled={modelsLoading || !models.length}
								className={styles.control}
								style={{ width: "100%", marginBottom: 8 }}
							/>
							{!models.length ? (
								<div style={{ fontSize: 12, color: "var(--muted)", padding: "8px 0" }}>
									{modelsLoading
										? t("chat.loadingModels")
										: modelsError
											? t("chat.fetchModelsFailed", { error: modelsError })
											: t("chat.noModelsAvailable")}
								</div>
							) : (
								<div>
									{filteredModels.map((candidate) => (
										<button
											key={candidate}
											type="button"
											disabled={busy}
											onClick={() => void selectModel(candidate)}
											style={{
												display: "flex",
												alignItems: "center",
												justifyContent: "space-between",
												width: "100%",
												padding: "7px 8px",
												border: "none",
												borderRadius: "var(--r-sm)",
												background:
													candidate === llmConfig.model && browseProviderId === llmConfig.provider
														? "var(--accent-soft)"
														: "transparent",
												color: "var(--fg)",
												cursor: "pointer",
												fontSize: 13,
												marginBottom: 2,
											}}
										>
											{candidate}
											{candidate === llmConfig.model && browseProviderId === llmConfig.provider ? (
												<Check size={12} />
											) : null}
										</button>
									))}
									{filteredModels.length === 0 ? (
										<div style={{ fontSize: 12, color: "var(--muted)" }}>
											{t("chat.noModelsMatch")}
										</div>
									) : null}
								</div>
							)}
						</>
					) : (
						<>
							{connectedProviders.map((providerId) => {
								const def = PROVIDER_DEFINITIONS.find((d) => d.id === providerId);
								if (!def) return null;
								return (
									<button
										key={providerId}
										type="button"
										onClick={() => {
											setBrowseProviderId(providerId);
											setScreen("models");
										}}
										style={{
											display: "flex",
											flexDirection: "column",
											alignItems: "flex-start",
											width: "100%",
											padding: "8px 10px",
											border: "none",
											borderRadius: "var(--r-sm)",
											background:
												providerId === browseProviderId ? "var(--accent-soft)" : "transparent",
											color: "var(--fg)",
											cursor: "pointer",
											marginBottom: 4,
										}}
									>
										<strong style={{ fontSize: 13 }}>{def.label}</strong>
										<span style={{ fontSize: 12, color: "var(--muted)" }}>
											{providerId === llmConfig.provider ? llmConfig.model : def.defaultModel}
										</span>
									</button>
								);
							})}
							{connectedProviders.length === 0 ? (
								<div style={{ fontSize: 12, color: "var(--muted)", marginBottom: 8 }}>
									{t("chat.noProvidersConnected")}
								</div>
							) : null}
							<button
								type="button"
								onClick={() => {
									onClose();
									onOpenFullSettings();
								}}
								className={`${styles.btn} ${styles.btnSecondary}`}
								style={{ width: "100%", marginTop: 6 }}
							>
								{t("chat.providerSettings")}
							</button>
						</>
					)}
				</div>
			</section>
		</div>,
		document.body,
	);
}

// ponytail: collapsible block that renders a model's reasoning trace (the
// streaming text from Anthropic/MiniMax `thinking` blocks). Default state is
// the last ~240 chars of the trace, clamped to two lines — the latest
// reasoning the model produced. Clicking the header toggles into "solid" mode
// (full text, scrollable). Used both while the reasoning is still streaming
// (so the user sees the model is alive) and on the completed message (so the
// trace is still there to revisit, collapsed by default).
const THINKING_PREVIEW_TAIL_CHARS = 240;
function ThinkingBlock({
	text,
	expanded,
	onToggle,
	label,
}: {
	text: string;
	expanded: boolean;
	onToggle: () => void;
	label: string;
}) {
	const preview =
		text.length > THINKING_PREVIEW_TAIL_CHARS
			? `…${text.slice(-THINKING_PREVIEW_TAIL_CHARS)}`
			: text;
	return (
		<button
			type="button"
			onClick={onToggle}
			aria-expanded={expanded}
			style={{
				display: "block",
				width: "100%",
				textAlign: "left",
				background: "transparent",
				border: "1px solid var(--border-soft)",
				borderRadius: "var(--r-sm)",
				padding: "6px 8px",
				marginBottom: 4,
				color: expanded ? "var(--fg-2)" : "var(--muted)",
				font: "400 12px/1.5 var(--font-body)",
				cursor: "pointer",
			}}
		>
			<div
				style={{
					display: "flex",
					alignItems: "center",
					gap: 4,
					marginBottom: expanded ? 4 : 0,
					color: "var(--muted)",
					font: "600 12px/1.3 var(--font-body)",
				}}
			>
				<svg
					width={10}
					height={10}
					viewBox="0 0 24 24"
					fill="none"
					stroke="currentColor"
					strokeWidth="2"
					strokeLinecap="round"
					strokeLinejoin="round"
					style={{
						transform: expanded ? "rotate(90deg)" : "rotate(0deg)",
						transition: "transform 120ms ease",
						flex: "0 0 auto",
					}}
					aria-hidden="true"
				>
					<polyline points="9 6 15 12 9 18" />
				</svg>
				<span>{label}</span>
			</div>
			{expanded ? (
				<div
					style={{
						maxHeight: 220,
						overflow: "auto",
						whiteSpace: "pre-wrap",
						wordBreak: "break-word",
						font: "400 12px/1.5 var(--font-body)",
					}}
				>
					{text}
				</div>
			) : (
				<div
					style={{
						display: "-webkit-box",
						WebkitLineClamp: 2,
						WebkitBoxOrient: "vertical",
						overflow: "hidden",
						whiteSpace: "pre-wrap",
						wordBreak: "break-word",
					}}
				>
					{preview}
				</div>
			)}
		</button>
	);
}

export function ChatStripPanel() {
	const t = useScopedT("editor");
	const tc = useScopedT("common");
	// The Auto-enhance confirmation is timeline-owned copy, fired from here —
	// see the prompt-bus effect below.
	const tTimeline = useScopedT("timeline");
	const projectId = useProjectStore((s) => s.projectId);
	const [messages, setMessages] = useState<ChatDisplayMessage[]>([]);
	const [input, setInput] = useState("");
	const [busy, setBusy] = useState(false);
	const [stopping, setStopping] = useState(false);
	const [liveText, setLiveText] = useState("");
	const latestRunIdRef = useRef<string | null>(null);
	const runRef = useRef<{
		id: string;
		projectId: string;
		sessionId: string | null;
		stopping: boolean;
		thinking: string;
	} | null>(null);
	const viewRef = useRef({ projectId, sessionId: null as string | null });
	const [llmConfig, setLlmConfig] = useState<AiEditionLlmConfig | null>(null);
	// The dialog itself is mounted in App.tsx so the app menu can reach it from every mode
	// (issue #420); this panel only asks for it to be opened, and watches it close.
	const dialogSection = useEditorDialogSection();
	const { openDialog } = useEditorDialogActions();
	const providerSettingsOpen = dialogSection === "providers";
	const openProviderSettings = useCallback(() => openDialog("providers"), [openDialog]);
	const [chatsOpen, setChatsOpen] = useState(false);
	const [sessions, setSessions] = useState<
		Array<{ id: string; title: string; messageCount: number; createdAt: string }>
	>([]);
	const [activeSessionId, setActiveSessionId] = useState<string | null>(null);
	// Mirror in a ref so refreshSessions can read the current selection without
	// listing activeSessionId in its deps — otherwise refreshSessions is recreated
	// on every selection change, which re-runs the project effect below (with
	// preferFirst=true) and forces the selection back to list[0]. That feedback
	// loop is what made "new conversation" jump to the oldest chat instead of the
	// freshly-created empty one.
	const activeSessionIdRef = useRef<string | null>(activeSessionId);
	activeSessionIdRef.current = activeSessionId;
	viewRef.current = { projectId, sessionId: activeSessionId };
	const scrollRef = useRef<HTMLDivElement | null>(null);
	// ponytail: live reasoning trace for the in-flight turn. Reset at send()
	// start; deltas append through the chat-event subscription; once the run
	// resolves we copy it onto the assistant message and clear it.
	const [thinkingText, setThinkingText] = useState("");
	const [thinkingExpanded, setThinkingExpanded] = useState(false);

	// Per-message expand state for completed turns. Using a Set keeps the
	// default-collapsed preview lightweight and the click-to-expand obvious.
	const [thinkingExpandedIds, setThinkingExpandedIds] = useState<Set<string>>(() => new Set());
	const [reasoningOpen, setReasoningOpen] = useState(false);
	const [reasoningBusy, setReasoningBusy] = useState(false);
	// null until the first llmGetSnapshot() lands: "unknown", not "none".
	const [connectedProviders, setConnectedProviders] = useState<string[] | null>(null);
	// unknown ≠ none; see chatAvailability.ts.
	const canChat = canSendChat(llmConfig, connectedProviders);
	const sendDisabled = busy || !input.trim() || !canChat;
	const [modelPopoverOpen, setModelPopoverOpen] = useState(false);
	const modelButtonRef = useRef<HTMLButtonElement | null>(null);
	const [modelPopoverRect, setModelPopoverRect] = useState<{
		left: number;
		bottom: number;
		maxHeight: number;
	} | null>(null);

	const refreshLlm = useCallback(async () => {
		try {
			const snap = await nativeBridgeClient.aiEdition.llmGetSnapshot();
			setLlmConfig(snap.config);
			setConnectedProviders(snap.connectedProviders);
		} catch {
			// ponytail: silent
		}
	}, []);

	const refreshSessions = useCallback(async (pid: string, preferFirst = false) => {
		try {
			const list = await nativeBridgeClient.aiEdition.chatListSessions(pid);
			if (viewRef.current.projectId !== pid) return;
			setSessions(list);
			if (list.length === 0) {
				setActiveSessionId(null);
				setMessages([]);
				return;
			}
			if (preferFirst || !list.some((s) => s.id === activeSessionIdRef.current)) {
				setActiveSessionId(list[0].id);
			}
		} catch {
			// ponytail: silent — shim mode or missing project
		}
	}, []);

	// On mount, and again every time the provider dialog closes. Connecting a provider there is
	// what makes the composer usable here and what fills the model pill, and the dialog no
	// longer hangs off this component, so there is no onClose to do it from. "Not open" covers
	// both events at once, which is why there is no ref here watching for the falling edge.
	useEffect(() => {
		if (!providerSettingsOpen) void refreshLlm();
	}, [providerSettingsOpen, refreshLlm]);

	const abandonRun = useCallback(() => {
		const run = runRef.current;
		if (!run) return;
		runRef.current = null;
		if (run.sessionId) {
			void nativeBridgeClient.aiEdition
				.chatCancel(run.projectId, run.sessionId, run.id)
				.catch(() => undefined);
		}
	}, []);

	useEffect(() => {
		const unsubscribe = window.electronAPI.onAiEditionChatEvent((event: AiEditionChatEvent) => {
			const run = runRef.current;
			if (
				!run ||
				event.runId !== run.id ||
				event.projectId !== run.projectId ||
				event.sessionId !== run.sessionId
			)
				return;
			if (
				viewRef.current.projectId !== run.projectId ||
				viewRef.current.sessionId !== run.sessionId
			)
				return;
			if (event.kind === "thinking") {
				run.thinking += event.delta;
				setThinkingText(run.thinking);
			} else if (event.kind === "text") setLiveText((prev) => prev + event.delta);
		});
		return () => {
			unsubscribe();
			abandonRun();
		};
	}, [abandonRun]);

	useEffect(() => {
		const run = runRef.current;
		if (run && (run.projectId !== projectId || run.sessionId !== activeSessionId)) {
			abandonRun();
			setBusy(false);
			setStopping(false);
			setThinkingText("");
			setLiveText("");
		}
	}, [projectId, activeSessionId, abandonRun]);

	const stop = async () => {
		const run = runRef.current;
		if (!run || run.stopping) return;
		run.stopping = true;
		setStopping(true);
		if (!run.sessionId) return; // session creation is still pending; send() will stop there.
		try {
			await nativeBridgeClient.aiEdition.chatCancel(run.projectId, run.sessionId, run.id);
		} catch (error) {
			if (runRef.current !== run) return;
			run.stopping = false;
			setStopping(false);
			toast.error(t("chat.stopFailed"), {
				description: error instanceof Error ? error.message : String(error),
			});
		}
	};

	useEffect(() => {
		if (!projectId) {
			setSessions([]);
			setActiveSessionId(null);
			setMessages([]);
			return;
		}
		void refreshSessions(projectId, true);
	}, [projectId, refreshSessions]);

	useEffect(() => {
		if (!projectId || !activeSessionId) {
			setMessages([]);
			return;
		}
		let disposed = false;
		void (async () => {
			try {
				const session = await nativeBridgeClient.aiEdition.chatSelectSession(
					projectId,
					activeSessionId,
				);
				if (
					disposed ||
					runRef.current ||
					viewRef.current.projectId !== projectId ||
					viewRef.current.sessionId !== activeSessionId
				)
					return;
				if (session) {
					setMessages(
						session.messages.map((m) => ({
							id: m.id,
							role: m.role,
							content: m.content,
							time: m.createdAt,
							toolCalls: m.toolCalls,
							checkpointId: m.checkpointId ?? null,
							stopped: m.stopped,
						})),
					);
				} else {
					setMessages([]);
				}
			} catch {
				// ponytail: silent — shim mode
			}
		})();
		return () => {
			disposed = true;
		};
	}, [projectId, activeSessionId]);

	useEffect(() => {
		scrollRef.current?.scrollTo({ top: scrollRef.current.scrollHeight, behavior: "smooth" });
	});

	const send = async (overrideText?: string) => {
		const text = (overrideText ?? input).trim();
		if (!projectId || !text || busy || runRef.current) return;
		// ponytail: nothing to talk to. Bounce to the settings modal instead of
		// firing a doomed request. The composer is disabled in this state too,
		// but Auto-enhance calls send() directly and Enter can slip through.
		if (!canChat) {
			toast.error(t("chat.composerDisabledNoProvider"));
			openProviderSettings();
			return;
		}
		const run = {
			id: crypto.randomUUID(),
			projectId,
			sessionId: activeSessionId,
			stopping: false,
			thinking: "",
		};
		runRef.current = run;
		latestRunIdRef.current = run.id;
		const isCurrent = () =>
			runRef.current === run &&
			viewRef.current.projectId === projectId &&
			viewRef.current.sessionId === run.sessionId;
		setInput("");
		setBusy(true);
		setStopping(false);
		setLiveText("");
		// ponytail: prepare the live reasoning-trace accumulator. Late events
		// from a previous run (or from another panel/window) won't match this
		// sessionId and are dropped by the subscription above.
		setThinkingText("");
		setThinkingExpanded(false);

		// ponytail: pre-seed the user message so the rewind ↩ button is
		// available before the server confirms. Mirrors axcut's
		// `before-message` checkpoint that runChat records in chat-service.
		const optimisticUserId = `local_${Date.now()}_u`;
		setMessages((prev) => [
			...prev,
			{
				id: optimisticUserId,
				role: "user",
				content: text,
				time: new Date().toISOString(),
				checkpointId: optimisticUserId,
			},
		]);
		try {
			// Mirror axcut's `getOrCreateSession`: the composer works with zero
			// setup, so the first message on a project with no sessions yet
			// silently starts one instead of no-op'ing.
			let sessionId = activeSessionId;
			if (!sessionId) {
				const created = await nativeBridgeClient.aiEdition.chatCreateSession(projectId);
				sessionId = created.id;
				if (!isCurrent()) return;
				if (run.stopping) {
					setMessages((prev) => prev.filter((message) => message.id !== optimisticUserId));
					setInput(text);
					return;
				}
				run.sessionId = sessionId;
				viewRef.current.sessionId = sessionId;
				setSessions((prev) => [...prev, created]);
				setActiveSessionId(sessionId);
			}
			if (!isCurrent() || run.stopping) return;
			run.sessionId = sessionId;
			// Capture the document and its revision together before awaiting the turn.
			// Stop returns the completed tools' aggregate too: commit it once so the
			// entire turn has one save and one undo step, regardless of tool count.
			const { result, applyDocument } = await runAgentTurn((documentSnapshot) =>
				nativeBridgeClient.aiEdition.chatRun(projectId, sessionId, text, documentSnapshot, run.id),
			);
			if (!isCurrent()) return;
			if (result.document) {
				const applyEdits = async (options?: { ignoreConflict?: boolean }) => {
					try {
						const applied = await applyDocument(options);
						if (applied === "save-failed") toast.error(t("chat.applyEditsFailed"));
						return applied;
					} catch (error) {
						toast.error(t("chat.applyEditsFailed"), {
							description: error instanceof Error ? error.message : String(error),
						});
						return "malformed" as const;
					}
				};
				const applied = await applyEdits();
				if (!isCurrent()) return;
				if (applied === "conflict")
					toast.warning(t("chat.agentEditConflict"), {
						duration: Number.POSITIVE_INFINITY,
						action: {
							label: t("chat.applyAnyway"),
							onClick: () => {
								if (
									latestRunIdRef.current !== run.id ||
									viewRef.current.projectId !== projectId ||
									viewRef.current.sessionId !== sessionId
								)
									return;
								void applyEdits({ ignoreConflict: true });
							},
						},
					});
			}
			setMessages((prev) => adoptStoredUserMessage(prev, optimisticUserId, result));
			// A rewind confirmation opened during the turn names the message too. Stored without a
			// checkpoint, the message has nothing to rewind to and the confirmation closes.
			const storedId = result.userMessageId;
			if (storedId) {
				setRewindFor((open) =>
					open?.messageId !== optimisticUserId
						? open
						: result.userMessageCheckpointId
							? { ...open, messageId: storedId }
							: null,
				);
			}
			const assistant = result.assistantMessage;
			if (result.success && assistant) {
				setMessages((prev) => [
					...prev,
					{
						role: "assistant",
						content: assistant.content,
						stopped: assistant.stopped,
						time: new Date().toISOString(),
						toolCalls: assistant.toolCalls,
						// ponytail: snapshot the live reasoning trace onto the
						// finished message so it can be revisited (collapsed by
						// default, click-to-expand) instead of vanishing. The
						// live accumulator is cleared in `finally`.
						thinking: run.thinking || undefined,
					},
				]);
				void refreshSessions(projectId);
			} else {
				toast.error(result.error ?? t("chat.chatFailed"));
			}
		} catch (err) {
			if (!isCurrent()) return;
			toast.error(t("chat.chatFailed"), {
				description: err instanceof Error ? err.message : String(err),
			});
		} finally {
			if (isCurrent()) {
				runRef.current = null;
				setBusy(false);
				setStopping(false);
				setThinkingText("");
				setLiveText("");
				setThinkingExpanded(false);
			}
		}
	};

	// Auto-send a prompt handed over by another part of the UI (e.g. the
	// timeline's Auto-enhance → "Smart zooms + cuts with AI"). Routes through
	// the normal send() so sessions/checkpoints/rewind all keep working; the
	// message shows in the composer's history exactly as if typed.
	// The confirmation toast lives here because only this side knows the prompt
	// was taken — send() bounces it to the settings modal with no provider.
	// ponytail: one producer today, so the toast copy is assumed to be its own.
	// A second producer needs the bus to carry its confirmation string.
	const pendingPrompt = useChatPromptBus((s) => s.pending);
	const consumePrompt = useChatPromptBus((s) => s.consume);
	// biome-ignore lint/correctness/useExhaustiveDependencies: send() is intentionally not a dep (recreated each render); consume() clears `pending` so this fires once per queued prompt.
	useEffect(() => {
		if (!pendingPrompt || !projectId || busy) return;
		consumePrompt();
		if (canChat) toast.success(tTimeline("toolbar.aiEnhanceRequested"));
		void send(pendingPrompt);
	}, [pendingPrompt, projectId, busy, consumePrompt, canChat, tTimeline]);

	// ponytail: per-user-message rewind. Pops a confirmation popover, then
	// asks the main process to roll the session + document back to the
	// snapshot taken right before the user hit Send. axcut parity.
	const [rewindFor, setRewindFor] = useState<{
		messageId: string;
		anchor: { left: number; bottom: number } | null;
	} | null>(null);
	const confirmRewind = useCallback(
		async (messageId: string) => {
			if (!projectId || !activeSessionId) return;
			try {
				const result = await nativeBridgeClient.aiEdition.chatRewind(
					projectId,
					activeSessionId,
					messageId,
				);
				if (!result.success) {
					toast.error(result.error ?? t("chat.rewindFailed"));
					setRewindFor(null);
					return;
				}
				const doc = (result as { document?: unknown }).document;
				// No `expectedRevision`: a rewind REPLACES whatever is live, which is what the
				// confirmation dialog now says out loud -- including any manual edit made since.
				if (doc) await applyAgentDocumentIfCurrent(doc);
				setMessages(
					result.messages.map((m) => ({
						id: m.id,
						role: m.role,
						content: m.content,
						time: m.createdAt,
						toolCalls: m.toolCalls,
						checkpointId: m.checkpointId ?? null,
						stopped: m.stopped,
					})),
				);
				setInput(result.prompt);
				toast.success(t("chat.rewoundSuccess"));
			} catch (err) {
				toast.error(t("chat.rewindFailed"), {
					description: err instanceof Error ? err.message : String(err),
				});
			} finally {
				setRewindFor(null);
			}
		},
		[projectId, activeSessionId, t],
	);

	useEffect(() => {
		if (!rewindFor) return;
		const handlePointerDown = (event: PointerEvent) => {
			const target = event.target instanceof Element ? event.target : null;
			if (target?.closest("[data-rewind-confirmation], [data-rewind-trigger]")) {
				return;
			}
			setRewindFor(null);
		};
		const handleKeyDown = (event: KeyboardEvent) => {
			if (event.key === "Escape") setRewindFor(null);
		};
		globalThis.document.addEventListener("pointerdown", handlePointerDown);
		globalThis.document.addEventListener("keydown", handleKeyDown);
		return () => {
			globalThis.document.removeEventListener("pointerdown", handlePointerDown);
			globalThis.document.removeEventListener("keydown", handleKeyDown);
		};
	}, [rewindFor]);

	const modelLabel = llmConfig ? llmConfig.model : t("chat.configureModel");
	const providerSupportsReasoning = Boolean(
		llmConfig &&
			PROVIDER_DEFINITIONS.find((d) => d.id === llmConfig.provider)?.supportsReasoningEffort,
	);
	const currentReasoningEffort: ReasoningEffort =
		(llmConfig?.reasoningEffort as ReasoningEffort | undefined) ?? "medium";
	const reasoningLabel =
		providerSupportsReasoning && llmConfig
			? getReasoningEffortLabel(llmConfig.provider, currentReasoningEffort)
			: null;

	const selectReasoningEffort = useCallback(
		async (effort: ReasoningEffort) => {
			if (!llmConfig) return;
			setReasoningBusy(true);
			try {
				const result = await nativeBridgeClient.aiEdition.llmSetConfig({
					...llmConfig,
					reasoningEffort: effort,
				});
				if (result.success) {
					setLlmConfig({ ...llmConfig, reasoningEffort: effort });
					setReasoningOpen(false);
				} else {
					toast.error(result.error ?? t("chat.reasoningEffortUpdateFailed"));
				}
			} catch (err) {
				toast.error(t("chat.reasoningEffortUpdateFailed"), {
					description: err instanceof Error ? err.message : String(err),
				});
			} finally {
				setReasoningBusy(false);
			}
		},
		[llmConfig, t],
	);

	const toggleModelPopoverOpen = useCallback(() => {
		// Mirrors axcut's providerButtonRef handler: with no provider configured
		// yet there's nothing to quick-pick a model from, so go straight to the
		// full settings modal (the "providers" screen) instead of toggling a
		// popover that would render empty.
		if (!llmConfig) {
			openProviderSettings();
			return;
		}
		setModelPopoverOpen((wasOpen) => {
			if (!wasOpen) {
				const rect = modelButtonRef.current?.getBoundingClientRect();
				if (rect) {
					// The popover opens upward from the pill and can hold a long,
					// scrollable model list — cap its height to the space actually
					// available above the button so it never overflows off the top
					// of the window (only "bottom" is set; nothing clamps "top").
					setModelPopoverRect({
						left: rect.left,
						bottom: window.innerHeight - rect.top + 4,
						maxHeight: Math.max(160, rect.top - 12),
					});
				}
			}
			return !wasOpen;
		});
	}, [llmConfig, openProviderSettings]);

	// Escape closes the model quick-pick and hands focus back to its pill (#1039). On the document,
	// as the dialogs do (Modals.tsx), so it is heard from the search field too, and it goes no
	// further, so nothing else bound to it acts on the same press.
	useEffect(() => {
		if (!modelPopoverOpen) return;
		const onKeyDown = (event: KeyboardEvent) => {
			if (event.key !== "Escape") return;
			event.preventDefault();
			event.stopPropagation();
			// The rewind confirmation, open above it, takes this press: one Escape, one layer.
			if (rewindFor) return;
			setModelPopoverOpen(false);
			modelButtonRef.current?.focus();
		};
		document.addEventListener("keydown", onKeyDown);
		return () => document.removeEventListener("keydown", onKeyDown);
	}, [modelPopoverOpen, rewindFor]);

	// Prefer the main process's estimate of the windowed history it actually sends, so
	// manual compaction can shrink this meter while the complete transcript remains
	// visible. The renderer estimate is only shown until the first answer arrives --
	// including in web builds, where the shim answers with its own transcript estimate
	// rather than leaving the fallback in place.
	const budget = useChatBudget({ projectId, sessionId: activeSessionId, messages });

	const [compactNowPending, setCompactNowPending] = useState(false);
	const compactNow = useCallback(async () => {
		if (!projectId || !activeSessionId || compactNowPending) return;
		setCompactNowPending(true);
		try {
			const result = await nativeBridgeClient.aiEdition.chatCompact(projectId, activeSessionId);
			if (!result) {
				toast.info(t("chat.notEnoughHistory"));
				return;
			}
			setMessages(
				result.session.messages.map((m) => ({
					id: m.id,
					role: m.role,
					content: m.content,
					time: m.createdAt,
					toolCalls: m.toolCalls,
					checkpointId: m.checkpointId ?? null,
					stopped: m.stopped,
				})),
			);
			toast.success(t("chat.compactedSuccess"));
		} catch (err) {
			toast.error(t("chat.compactFailed"), {
				description: err instanceof Error ? err.message : String(err),
			});
		} finally {
			setCompactNowPending(false);
		}
	}, [projectId, activeSessionId, compactNowPending, t]);

	const newChat = useCallback(async () => {
		if (!projectId) return;
		try {
			const created = await nativeBridgeClient.aiEdition.chatCreateSession(projectId);
			setSessions((prev) => [...prev, created]);
			setActiveSessionId(created.id);
			setMessages([]);
		} catch (err) {
			toast.error(t("chat.createSessionFailed"), {
				description: err instanceof Error ? err.message : String(err),
			});
		}
	}, [projectId, t]);

	const selectSession = useCallback((id: string) => {
		setActiveSessionId(id);
	}, []);

	const handleDelete = useCallback(
		async (id: string) => {
			if (!projectId) return;
			try {
				const res = await nativeBridgeClient.aiEdition.chatDeleteSession(projectId, id);
				if (!res.success) return;
				setSessions((prev) => prev.filter((s) => s.id !== id));
				if (activeSessionId === id) {
					setActiveSessionId(null);
					setMessages([]);
				}
			} catch (err) {
				toast.error(t("chat.deleteSessionFailed"), {
					description: err instanceof Error ? err.message : String(err),
				});
			}
		},
		[projectId, activeSessionId, t],
	);

	const handleRename = useCallback(
		async (id: string, title: string) => {
			if (!projectId) return;
			const trimmed = title.trim();
			if (!trimmed) return;
			try {
				const updated = await nativeBridgeClient.aiEdition.chatRenameSession(
					projectId,
					id,
					trimmed,
				);
				if (updated) {
					setSessions((prev) => prev.map((s) => (s.id === id ? updated : s)));
				}
			} catch (err) {
				toast.error(t("chat.renameSessionFailed"), {
					description: err instanceof Error ? err.message : String(err),
				});
			}
		},
		[projectId, t],
	);

	// ponytail: inline session rename. Click the title to edit, Enter saves,
	// Escape cancels, blur saves when the value is non-empty (axcut parity).
	const [editingSessionId, setEditingSessionId] = useState<string | null>(null);
	const [editingTitle, setEditingTitle] = useState("");
	const editingInputRef = useRef<HTMLInputElement | null>(null);
	const beginEditTitle = useCallback((id: string, currentTitle: string) => {
		setEditingSessionId(id);
		setEditingTitle(currentTitle);
	}, []);
	const cancelEditTitle = useCallback(() => {
		setEditingSessionId(null);
		setEditingTitle("");
	}, []);
	const commitEditTitle = useCallback(
		async (id: string) => {
			const next = editingTitle.trim();
			if (!next) {
				cancelEditTitle();
				return;
			}
			setEditingSessionId(null);
			await handleRename(id, next);
		},
		[editingTitle, handleRename, cancelEditTitle],
	);

	return (
		<aside className={styles.panel}>
			<div className={styles.panelHeader}>
				<div className={styles.chatStrip}>
					<div className={styles.chatStripRow}>
						<span
							className={styles.ctxPill}
							title={t("chat.contextTooltip", {
								usedTokens: budget.usedTokens,
								budgetTokens: budget.budgetTokens,
							})}
						>
							<span className={styles.d} aria-hidden />
							{t("chat.contextPercent", { percent: Math.min(100, Math.round(budget.ratio * 100)) })}
						</span>
						<span className={styles.stripActions}>
							{/* `aria-disabled`, not `disabled`, so the tooltip still opens on a greyed button. */}
							<Tooltip content={t("chat.compactContext")}>
								<button
									type="button"
									aria-label={t("chat.compactContext")}
									className={styles.iconBtn}
									onClick={
										!activeSessionId || compactNowPending ? undefined : () => void compactNow()
									}
									aria-disabled={!activeSessionId || compactNowPending || undefined}
								>
									<svg
										width={14}
										height={14}
										viewBox="0 0 24 24"
										fill="none"
										stroke="currentColor"
										strokeWidth="2"
										strokeLinecap="round"
										strokeLinejoin="round"
										aria-hidden="true"
									>
										<path d="M8 4l4 4 4-4" />
										<path d="M8 20l4-4 4 4" />
										<path d="M6 12h12" />
									</svg>
								</button>
							</Tooltip>
							<Tooltip content={t("chat.aiSettings")}>
								<button
									type="button"
									aria-label={t("chat.aiSettings")}
									onClick={openProviderSettings}
								>
									<svg
										width={14}
										height={14}
										viewBox="0 0 24 24"
										fill="none"
										stroke="currentColor"
										strokeWidth="2"
										strokeLinecap="round"
										strokeLinejoin="round"
									>
										<circle cx="12" cy="12" r="3" />
										<path d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 0 1 0 2.83 2 2 0 0 1-2.83 0l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-4 0v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 0 1-2.83 0 2 2 0 0 1 0-2.83l.06-.06a1.65 1.65 0 0 0 .33-1.82 1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1 0-4h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 0 1 0-2.83 2 2 0 0 1 2.83 0l.06.06a1.65 1.65 0 0 0 1.82.33H9a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 4 0v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 0 1 2.83 0 2 2 0 0 1 0 2.83l-.06.06a1.65 1.65 0 0 0-.33 1.82V9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 0 4h-.09a1.65 1.65 0 0 0-1.51 1z" />
									</svg>
								</button>
							</Tooltip>
							<Tooltip content={t("chat.history")}>
								<button
									type="button"
									aria-label={t("chat.history")}
									onClick={() => setChatsOpen(true)}
								>
									<svg
										width={14}
										height={14}
										viewBox="0 0 24 24"
										fill="none"
										stroke="currentColor"
										strokeWidth="2"
										strokeLinecap="round"
										strokeLinejoin="round"
									>
										<path d="M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8" />
										<path d="M3 3v5h5" />
										<path d="M12 7v5l4 2" />
									</svg>
								</button>
							</Tooltip>
							<Tooltip content={t("chat.newConversation")}>
								<button type="button" aria-label={t("chat.newConversation")} onClick={newChat}>
									<svg
										width={14}
										height={14}
										viewBox="0 0 24 24"
										fill="none"
										stroke="currentColor"
										strokeWidth="2"
										strokeLinecap="round"
										strokeLinejoin="round"
									>
										<path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z" />
										<path d="M12 7v6" />
										<path d="M9 10h6" />
									</svg>
								</button>
							</Tooltip>
						</span>
					</div>
				</div>

				{activeSessionId ? (
					<div
						style={{
							display: "flex",
							alignItems: "center",
							justifyContent: "space-between",
							gap: 8,
							padding: "6px var(--sp-3)",
							borderTop: "1px solid var(--border-soft)",
							background: "var(--surface-warm)",
						}}
					>
						{editingSessionId === activeSessionId ? (
							<input
								ref={editingInputRef}
								type="text"
								autoFocus
								value={editingTitle}
								onChange={(event) => setEditingTitle(event.target.value)}
								onFocus={(event) => event.currentTarget.select()}
								onBlur={() => {
									if (editingSessionId) void commitEditTitle(editingSessionId);
								}}
								onKeyDown={(event) => {
									if (event.key === "Enter") {
										event.preventDefault();
										if (editingSessionId) void commitEditTitle(editingSessionId);
									} else if (event.key === "Escape") {
										event.preventDefault();
										cancelEditTitle();
									}
								}}
								style={{
									font: "500 12px/1.3 var(--font-body)",
									color: "var(--fg)",
									background: "var(--surface)",
									border: "1px solid var(--accent)",
									borderRadius: "var(--r-sm)",
									padding: "2px 6px",
									flex: 1,
									minWidth: 0,
								}}
							/>
						) : (
							<span
								style={{
									font: "500 12px/1.3 var(--font-body)",
									color: "var(--fg-2)",
									overflow: "hidden",
									textOverflow: "ellipsis",
									whiteSpace: "nowrap",
									flex: 1,
									cursor: "text",
								}}
								title={t("chat.clickToRename")}
								onClick={() => {
									const current = sessions.find((s) => s.id === activeSessionId);
									if (current) beginEditTitle(activeSessionId, current.title);
								}}
							>
								{sessions.find((s) => s.id === activeSessionId)?.title ??
									t("chat.untitledConversation")}
							</span>
						)}
						<Tooltip content={t("chat.renameConversation")}>
							<button
								type="button"
								aria-label={t("chat.renameConversation")}
								aria-disabled={editingSessionId === activeSessionId || undefined}
								onClick={() => {
									if (editingSessionId === activeSessionId) return;
									const current = sessions.find((s) => s.id === activeSessionId);
									if (current) beginEditTitle(activeSessionId, current.title);
								}}
								className={styles.iconBtn}
							>
								<svg
									width={14}
									height={14}
									viewBox="0 0 24 24"
									fill="none"
									stroke="currentColor"
									strokeWidth="2"
									strokeLinecap="round"
									strokeLinejoin="round"
								>
									<path d="M12 20h9" />
									<path d="M16.5 3.5a2.12 2.12 0 0 1 3 3L7 19l-4 1 1-4z" />
								</svg>
							</button>
						</Tooltip>
						<Tooltip content={t("chat.deleteConversation")}>
							<button
								type="button"
								aria-label={t("chat.deleteConversation")}
								onClick={() => {
									const current = sessions.find((s) => s.id === activeSessionId);
									if (!current) return;
									if (
										window.confirm(t("chat.confirmDeleteConversation", { title: current.title }))
									) {
										void handleDelete(activeSessionId);
									}
								}}
								className={styles.iconBtn}
							>
								<svg
									width={14}
									height={14}
									viewBox="0 0 24 24"
									fill="none"
									stroke="currentColor"
									strokeWidth="2"
									strokeLinecap="round"
									strokeLinejoin="round"
								>
									<polyline points="3 6 5 6 21 6" />
									<path d="M19 6l-1 14a2 2 0 0 1-2 2H8a2 2 0 0 1-2-2L5 6" />
									<path d="M10 11v6" />
									<path d="M14 11v6" />
									<path d="M9 6V4a1 1 0 0 1 1-1h4a1 1 0 0 1 1 1v2" />
								</svg>
							</button>
						</Tooltip>
					</div>
				) : null}
			</div>

			<div className={styles.panelBody} ref={scrollRef}>
				{!canChat && messages.length === 0 ? (
					<ChatWelcome onOpenProviderSettings={openProviderSettings} />
				) : messages.length === 0 ? (
					<p
						style={{
							font: "400 12px var(--font-body)",
							color: "var(--muted)",
							padding: "24px var(--sp-4)",
							textAlign: "center",
							lineHeight: 1.5,
						}}
					>
						{t("chat.emptyState")}
					</p>
				) : (
					<>
						{messages.map((m, i) => (
							<div className={styles.msg} key={i}>
								<div className={styles.msgHead}>
									<span className={styles.msgAuthor}>
										{m.role === "user" ? t("chat.authorUser") : t("chat.authorAssistant")}
									</span>
									{m.time ? (
										<span
											className="right"
											style={{
												font: "500 11px/1 var(--font-body)",
												fontVariantNumeric: "tabular-nums",
												color: "var(--muted)",
											}}
										>
											{formatMessageTime(m.time)}
										</span>
									) : null}
								</div>
								{m.thinking && m.role !== "user" ? (
									<ThinkingBlock
										text={m.thinking}
										expanded={m.id !== undefined && thinkingExpandedIds.has(m.id)}
										onToggle={() => {
											if (!m.id) return;
											setThinkingExpandedIds((prev) => {
												const next = new Set(prev);
												if (next.has(m.id!)) {
													next.delete(m.id!);
												} else {
													next.add(m.id!);
												}
												return next;
											});
										}}
										label={t("chat.thinking")}
									/>
								) : null}
								<div
									className={
										m.role === "user"
											? `${styles.msgBubble} ${styles.msgBubbleUser}`
											: styles.msgBubble
									}
								>
									{m.content}
								</div>
								<div
									style={{
										display: "flex",
										alignItems: "center",
										gap: 4,
										marginTop: 4,
										justifyContent: "flex-end",
									}}
								>
									{m.role === "user" && m.checkpointId ? (
										// The name stays "Rewind to this message"; the tip adds what it does, which
										// only the confirmation dialog said before.
										<Tooltip content={t("chat.rewindTip")}>
											<button
												type="button"
												data-rewind-trigger="true"
												aria-label={t("chat.rewindToMessage")}
												aria-expanded={rewindFor?.messageId === m.id}
												onClick={(event) => {
													const rect = event.currentTarget.getBoundingClientRect();
													setRewindFor({
														messageId: m.id ?? "",
														anchor: {
															left: rect.left + rect.width / 2,
															bottom: window.innerHeight - rect.top + 6,
														},
													});
												}}
												className={styles.iconBtn}
											>
												<svg
													width={14}
													height={14}
													viewBox="0 0 24 24"
													fill="none"
													stroke="currentColor"
													strokeWidth="2"
													strokeLinecap="round"
													strokeLinejoin="round"
												>
													<path d="M3 7v6h6" />
													<path d="M21 17a9 9 0 0 0-15-6.7L3 13" />
												</svg>
											</button>
										</Tooltip>
									) : null}
									<Tooltip content={t("chat.copyMessage")}>
										<button
											type="button"
											aria-label={t("chat.copyMessage")}
											onClick={() => {
												// Electron denies the renderer's navigator clipboard write
												// (issue #738), so the write crosses to main when the
												// bridge offers it; the navigator path remains for
												// shim/web contexts without the bridge.
												const bridge = window.electronAPI?.copyToClipboard;
												const write = bridge
													? bridge(m.content)
													: navigator.clipboard.writeText(m.content);
												void write.then(
													() => toast.success(t("chat.copiedToClipboard")),
													() => toast.error(t("chat.copyFailed")),
												);
											}}
											className={styles.iconBtn}
										>
											<svg
												width={14}
												height={14}
												viewBox="0 0 24 24"
												fill="none"
												stroke="currentColor"
												strokeWidth="2"
												strokeLinecap="round"
												strokeLinejoin="round"
											>
												<rect x="9" y="9" width="13" height="13" rx="2" />
												<path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1" />
											</svg>
										</button>
									</Tooltip>
								</div>
								{m.stopped ? (
									<div role="status" className={styles.msgText}>
										{t("chat.stopped")}
									</div>
								) : null}
								{m.toolCalls?.length ? (
									<div style={{ marginTop: 4, display: "flex", flexDirection: "column", gap: 2 }}>
										{m.toolCalls.map((call, j) => (
											<div
												key={j}
												style={{
													font: "500 12px/1.5 var(--font-body)",
													color: "var(--success)",
												}}
											>
												{t("chat.appliedPrefix")} {call.summary}
											</div>
										))}
									</div>
								) : null}
							</div>
						))}
						{busy ? (
							<div className={styles.msg} aria-live="polite">
								<div className={styles.msgHead}>
									<span className={styles.msgAuthor}>{t("chat.authorAssistant")}</span>
								</div>
								{liveText ? <div className={styles.msgText}>{liveText}</div> : null}
								{stopping ? <div role="status">{t("chat.stopping")}</div> : null}
								{thinkingText ? (
									<div
										style={{
											display: "flex",
											alignItems: "flex-start",
											gap: 6,
										}}
									>
										<Loader2
											size={12}
											className="animate-spin"
											style={{
												marginTop: 10,
												flex: "0 0 auto",
												color: "var(--muted)",
											}}
										/>
										<div style={{ flex: 1, minWidth: 0 }}>
											<ThinkingBlock
												text={thinkingText}
												expanded={thinkingExpanded}
												onToggle={() => setThinkingExpanded((v) => !v)}
												label={t("chat.thinking")}
											/>
										</div>
									</div>
								) : (
									<div
										className={styles.msgBubble}
										style={{ color: "var(--muted)", fontStyle: "italic" }}
									>
										<Loader2
											size={12}
											className="animate-spin"
											style={{ marginRight: 6, verticalAlign: "middle" }}
										/>
										{t("chat.thinking")}
									</div>
								)}
							</div>
						) : null}
					</>
				)}
			</div>

			<div className={styles.chatInput}>
				<textarea
					placeholder={
						canChat ? t("chat.composerPlaceholder") : t("chat.composerDisabledNoProvider")
					}
					value={input}
					disabled={!canChat}
					onChange={(e) => setInput(e.target.value)}
					onKeyDown={(e) => {
						if (e.key === "Enter" && !e.shiftKey) {
							e.preventDefault();
							void send();
						}
					}}
				/>
				<div className={styles.actions}>
					<button
						ref={modelButtonRef}
						type="button"
						className={styles.modelPicker}
						aria-label={t("chat.modelLabel")}
						aria-haspopup="menu"
						aria-expanded={modelPopoverOpen}
						onClick={toggleModelPopoverOpen}
					>
						<svg
							width={12}
							height={12}
							viewBox="0 0 24 24"
							fill="none"
							stroke="currentColor"
							strokeWidth="2"
							strokeLinecap="round"
							strokeLinejoin="round"
						>
							<line x1="3" y1="6" x2="21" y2="6" />
							<line x1="3" y1="12" x2="21" y2="12" />
							<line x1="3" y1="18" x2="21" y2="18" />
						</svg>
						{/* Mono is for the model ID; the "set one up" prompt is words. */}
						<span style={llmConfig ? undefined : { fontFamily: "var(--font-body)" }}>
							{modelLabel}
						</span>
					</button>
					{reasoningLabel ? (
						// The shared popover, for its Escape and outside click (#1039); Escape goes no
						// further, so nothing else bound to it acts on the same press.
						<Popover open={reasoningOpen} onOpenChange={setReasoningOpen}>
							<PopoverTrigger asChild>
								<button
									type="button"
									className={styles.reasoningBtn}
									aria-label={t("chat.reasoningEffortLabel")}
									aria-haspopup="menu"
									aria-expanded={reasoningOpen}
								>
									<span className={styles.chip}>
										<span className={styles.d} />
										{reasoningLabel}
									</span>
								</button>
							</PopoverTrigger>
							<PopoverContent
								side="top"
								align="start"
								animated={false}
								className="w-auto border-0 bg-transparent p-0 shadow-none"
								onEscapeKeyDown={(event) => event.stopPropagation()}
							>
								<div
									role="menu"
									style={{
										minWidth: 160,
										background: "var(--surface)",
										border: "1px solid var(--border)",
										borderRadius: "var(--r-md)",
										boxShadow: "var(--elev-pop)",
										padding: 4,
									}}
								>
									{getReasoningEffortOptions(llmConfig?.provider ?? "").map((option) => (
										<button
											type="button"
											key={option}
											role="menuitem"
											disabled={reasoningBusy}
											onClick={() => void selectReasoningEffort(option)}
											style={{
												display: "flex",
												alignItems: "center",
												justifyContent: "space-between",
												gap: 8,
												width: "100%",
												padding: "6px 10px",
												border: "none",
												background:
													option === currentReasoningEffort ? "var(--accent-soft)" : "transparent",
												color: "var(--fg)",
												borderRadius: "var(--r-sm)",
												cursor: "pointer",
												fontSize: 13,
											}}
										>
											{getReasoningEffortLabel(llmConfig?.provider ?? "", option)}
											{option === currentReasoningEffort ? <Check size={12} /> : null}
										</button>
									))}
								</div>
							</PopoverContent>
						</Popover>
					) : null}
					{modelPopoverOpen && modelPopoverRect && llmConfig ? (
						<ModelQuickPopover
							anchorRect={modelPopoverRect}
							llmConfig={llmConfig}
							connectedProviders={connectedProviders ?? []}
							onClose={() => setModelPopoverOpen(false)}
							onConfigChange={() => void refreshLlm()}
							onOpenFullSettings={openProviderSettings}
						/>
					) : null}
					{/* `aria-disabled`, not `disabled`: this is where "Set up a provider" is said, and a
					    natively disabled button takes no pointer events, so nothing could show it. */}
					{busy ? (
						<Tooltip content={stopping ? t("chat.stopping") : t("chat.stop")} side="top">
							<button
								type="button"
								className={styles.sendBtn}
								aria-label={t("chat.stop")}
								aria-disabled={stopping || undefined}
								onClick={stopping ? undefined : () => void stop()}
							>
								<Square size={14} fill="currentColor" />
							</button>
						</Tooltip>
					) : (
						<Tooltip
							content={canChat ? t("chat.send") : t("chat.composerDisabledNoProvider")}
							shortcut={canChat ? "Enter" : undefined}
						>
							<button
								type="button"
								className={styles.sendBtn}
								aria-label={t("chat.send")}
								aria-disabled={sendDisabled || undefined}
								onClick={sendDisabled ? undefined : () => void send()}
							>
								<svg
									width={14}
									height={14}
									viewBox="0 0 24 24"
									fill="none"
									stroke="currentColor"
									strokeWidth="2"
									strokeLinecap="round"
									strokeLinejoin="round"
								>
									<path d="M3.714 3.048a.498.498 0 0 0-.683.627l2.843 7.627a2 2 0 0 1 0 1.396l-2.843 7.627a.498.498 0 0 0 .683.627l18-8.5a.5.5 0 0 0 0-.904Z" />
									<path d="M6 12h16" />
								</svg>
							</button>
						</Tooltip>
					)}
				</div>
			</div>
			<ChatHistoryModal
				open={chatsOpen}
				onClose={() => setChatsOpen(false)}
				sessions={sessions}
				activeSessionId={activeSessionId}
				onSelect={selectSession}
				onNew={newChat}
			/>
			{rewindFor && rewindFor.anchor
				? createPortal(
						<div
							data-rewind-confirmation="true"
							role="dialog"
							aria-label={t("chat.rewindConfirmTitle")}
							style={{
								position: "fixed",
								left: rewindFor.anchor.left - 130,
								bottom: rewindFor.anchor.bottom,
								width: 260,
								background: "var(--surface)",
								border: "1px solid var(--border)",
								borderRadius: 12,
								boxShadow: "var(--elev-pop)",
								padding: 12,
								zIndex: 1000,
							}}
						>
							<strong style={{ display: "block", marginBottom: 4 }}>
								{t("chat.rewindConfirmTitle")}
							</strong>
							<p
								style={{
									font: "400 12px/1.4 var(--font-body)",
									color: "var(--muted)",
									margin: "0 0 8px",
								}}
							>
								{t("chat.rewindConfirmBody")}
							</p>
							<div style={{ display: "flex", justifyContent: "flex-end", gap: 6 }}>
								<button
									type="button"
									onClick={() => setRewindFor(null)}
									className={`${styles.btn} ${styles.btnSecondary}`}
								>
									{tc("actions.cancel")}
								</button>
								<button
									type="button"
									onClick={() => void confirmRewind(rewindFor.messageId)}
									className={`${styles.btn} ${styles.btnPrimary}`}
								>
									{t("chat.rewindConfirm")}
								</button>
							</div>
						</div>,
						document.body,
					)
				: null}
		</aside>
	);
}