import { type FormEvent, type KeyboardEvent, useEffect, useMemo, useRef, useState, } from "react"; import { EDITORS, type EditorId } from "@acme/contracts"; import { DEFAULT_MODEL, DEFAULT_REASONING, MODEL_OPTIONS, REASONING_OPTIONS, resolveModelSlug, } from "../model-logic"; import { derivePhase, deriveTimelineEntries, deriveWorkLogEntries, formatElapsed, formatTimestamp, readNativeApi, } from "../session-logic"; import { useStore } from "../store"; import ChatMarkdown from "./ChatMarkdown"; function formatMessageMeta(createdAt: string, duration: string | null): string { if (!duration) return formatTimestamp(createdAt); return `${formatTimestamp(createdAt)} • ${duration}`; } const FILE_MANAGER_LABEL = navigator.platform.includes("Mac") ? "Finder" : navigator.platform.includes("Win") ? "Explorer" : "Files"; function editorLabel(editor: (typeof EDITORS)[number]): string { return editor.command ? editor.label : FILE_MANAGER_LABEL; } const LAST_EDITOR_KEY = "codething:last-editor"; function statusLabel(phase: string): string { if (phase === "running") return "Thinking / working"; if (phase === "connecting") return "Connecting"; if (phase === "ready") return "Ready"; return "Disconnected"; } function workToneClass(tone: "thinking" | "tool" | "info" | "error"): string { if (tone === "error") return "text-rose-300/50"; if (tone === "tool") return "text-[#8a8a8a]"; if (tone === "thinking") return "text-[#707070]"; return "text-[#606060]"; } export default function ChatView() { const { state, dispatch } = useStore(); const api = useMemo(() => readNativeApi(), []); const [prompt, setPrompt] = useState(""); const [isSending, setIsSending] = useState(false); const [isConnecting, setIsConnecting] = useState(false); const [isModelMenuOpen, setIsModelMenuOpen] = useState(false); const [isEditorMenuOpen, setIsEditorMenuOpen] = useState(false); const [lastEditor, setLastEditor] = useState(() => { const stored = localStorage.getItem(LAST_EDITOR_KEY); return EDITORS.some((e) => e.id === stored) ? (stored as EditorId) : EDITORS[0].id; }); const [selectedEffort, setSelectedEffort] = useState(DEFAULT_REASONING); const [nowTick, setNowTick] = useState(() => Date.now()); const messagesEndRef = useRef(null); const textareaRef = useRef(null); const modelMenuRef = useRef(null); const editorMenuRef = useRef(null); const activeThread = state.threads.find((t) => t.id === state.activeThreadId); const activeProject = state.projects.find( (p) => p.id === activeThread?.projectId, ); const selectedModel = resolveModelSlug( activeThread?.model ?? activeProject?.model ?? DEFAULT_MODEL, ); const phase = derivePhase(activeThread?.session ?? null); const isWorking = phase === "running" || isSending || isConnecting; const activeTurnId = activeThread?.session?.activeTurnId; const nowIso = new Date(nowTick).toISOString(); const modelOptions = MODEL_OPTIONS; const workLogEntries = useMemo( () => deriveWorkLogEntries(activeThread?.events ?? [], activeTurnId), [activeThread?.events, activeTurnId], ); const assistantCompletionByItemId = useMemo(() => { const map = new Map(); const ordered = [...(activeThread?.events ?? [])].reverse(); for (const event of ordered) { if (event.method !== "item/completed") continue; if (!event.itemId) continue; map.set(event.itemId, event.createdAt); } return map; }, [activeThread?.events]); const timelineEntries = useMemo( () => deriveTimelineEntries( activeThread?.messages ?? [], isWorking ? workLogEntries : [], ), [activeThread?.messages, isWorking, workLogEntries], ); // Auto-scroll on new messages const messageCount = activeThread?.messages.length ?? 0; const workLogCount = workLogEntries.length; // biome-ignore lint/correctness/useExhaustiveDependencies: trigger on message count change useEffect(() => { messagesEndRef.current?.scrollIntoView({ behavior: "smooth" }); }, [messageCount]); // biome-ignore lint/correctness/useExhaustiveDependencies: auto-scroll while active work-log events stream in useEffect(() => { if (phase !== "running") return; messagesEndRef.current?.scrollIntoView({ behavior: "smooth" }); }, [phase, workLogCount]); // Auto-resize textarea // biome-ignore lint/correctness/useExhaustiveDependencies: trigger on prompt change useEffect(() => { const ta = textareaRef.current; if (!ta) return; ta.style.height = "auto"; ta.style.height = `${Math.min(ta.scrollHeight, 200)}px`; }, [prompt]); useEffect(() => { if (phase !== "running") return; const timer = window.setInterval(() => { setNowTick(Date.now()); }, 250); return () => { window.clearInterval(timer); }; }, [phase]); useEffect(() => { if (!isModelMenuOpen) return; const handleClickOutside = (event: MouseEvent) => { if (!modelMenuRef.current) return; if ( event.target instanceof Node && !modelMenuRef.current.contains(event.target) ) { setIsModelMenuOpen(false); } }; window.addEventListener("mousedown", handleClickOutside); return () => { window.removeEventListener("mousedown", handleClickOutside); }; }, [isModelMenuOpen]); useEffect(() => { if (!isEditorMenuOpen) return; const handleClickOutside = (event: MouseEvent) => { if (!editorMenuRef.current) return; if ( event.target instanceof Node && !editorMenuRef.current.contains(event.target) ) { setIsEditorMenuOpen(false); } }; window.addEventListener("mousedown", handleClickOutside); return () => { window.removeEventListener("mousedown", handleClickOutside); }; }, [isEditorMenuOpen]); // Cmd+O / Ctrl+O to open in last-used editor useEffect(() => { const handler = (e: globalThis.KeyboardEvent) => { if (e.key === "o" && (e.metaKey || e.ctrlKey) && !e.shiftKey) { if (api && activeProject) { e.preventDefault(); void api.shell.openInEditor(activeProject.cwd, lastEditor); } } }; window.addEventListener("keydown", handler); return () => window.removeEventListener("keydown", handler); }, [api, activeProject, lastEditor]); const openInEditor = (editorId: EditorId) => { if (!api || !activeProject) return; void api.shell.openInEditor(activeProject.cwd, editorId); setLastEditor(editorId); localStorage.setItem(LAST_EDITOR_KEY, editorId); setIsEditorMenuOpen(false); }; const ensureSession = async (): Promise => { if (!api || !activeThread || !activeProject) return null; if (activeThread.session && activeThread.session.status !== "closed") { return activeThread.session.sessionId; } setIsConnecting(true); try { const session = await api.providers.startSession({ provider: "codex", cwd: activeProject.cwd || undefined, model: selectedModel || undefined, }); dispatch({ type: "UPDATE_SESSION", threadId: activeThread.id, session, }); return session.sessionId; } catch (err) { dispatch({ type: "SET_ERROR", threadId: activeThread.id, error: err instanceof Error ? err.message : "Failed to connect.", }); return null; } finally { setIsConnecting(false); } }; const onSend = async (e: FormEvent) => { e.preventDefault(); if (!api || !activeThread || isSending || isConnecting) return; const trimmed = prompt.trim(); if (!trimmed) return; // Auto-title from first message if (activeThread.messages.length === 0) { const title = trimmed.length > 50 ? `${trimmed.slice(0, 50)}...` : trimmed; dispatch({ type: "SET_THREAD_TITLE", threadId: activeThread.id, title, }); } dispatch({ type: "SET_ERROR", threadId: activeThread.id, error: null, }); dispatch({ type: "PUSH_USER_MESSAGE", threadId: activeThread.id, id: crypto.randomUUID(), text: trimmed, }); setPrompt(""); const sessionId = await ensureSession(); if (!sessionId) return; setIsSending(true); try { await api.providers.sendTurn({ sessionId, input: trimmed, model: selectedModel || undefined, effort: selectedEffort || undefined, }); } catch (err) { dispatch({ type: "SET_ERROR", threadId: activeThread.id, error: err instanceof Error ? err.message : "Failed to send message.", }); } finally { setIsSending(false); } }; const onInterrupt = async () => { if (!api || !activeThread?.session) return; await api.providers.interruptTurn({ sessionId: activeThread.session.sessionId, turnId: activeThread.session.activeTurnId, }); }; const onModelSelect = (model: string) => { if (!activeThread) return; dispatch({ type: "SET_THREAD_MODEL", threadId: activeThread.id, model: resolveModelSlug(model), }); setIsModelMenuOpen(false); }; const onKeyDown = (e: KeyboardEvent) => { if (e.key === "Enter" && !e.shiftKey) { e.preventDefault(); void onSend(e as unknown as FormEvent); } }; // Empty state: no active thread if (!activeThread) { return (

Select a thread or create a new one to get started.

); } return (
{/* Top bar */}

{activeThread.title}

{activeProject && ( {activeProject.name} )}
{/* Status indicator */}
{(phase === "running" || phase === "connecting") && ( )} {statusLabel(phase)}
{/* Open in editor */} {activeProject && (
{isEditorMenuOpen && (
{EDITORS.map((editor) => ( ))}
)}
)} {/* Diff toggle */}
{/* Error banner */} {activeThread.error && (
{activeThread.error}
)} {/* Messages */}
{activeThread.messages.length === 0 && !isWorking ? (

Send a message to start the conversation.

) : (
{timelineEntries.map((timelineEntry) => timelineEntry.kind === "work" ? (

{timelineEntry.entry.detail ? ( <> {timelineEntry.entry.label} {timelineEntry.entry.detail} ) : ( timelineEntry.entry.label )}

) : (
{timelineEntry.message.role === "user" ? (
                          {timelineEntry.message.text}
                        

{formatTimestamp(timelineEntry.message.createdAt)}

) : (
{timelineEntry.message.streaming && (
Thinking
)}

{formatMessageMeta( timelineEntry.message.createdAt, timelineEntry.message.streaming ? formatElapsed( timelineEntry.message.createdAt, nowIso, ) : formatElapsed( timelineEntry.message.createdAt, assistantCompletionByItemId.get( timelineEntry.message.id, ), ), )}

)}
), )} {isWorking && (
)}
)}
{/* Input bar */}
{/* Textarea area */}