import { useEffect, useRef, useState } from "react"; import ReactMarkdown from "react-markdown"; import type { ChatClientMessage, ChatConversation, ChatEvent } from "@shellbook/core"; import "./chat.css"; export interface ChatSocket { onopen: ((event: Event) => void) | null; onclose: ((event: CloseEvent) => void) | null; onerror: ((event: Event) => void) | null; onmessage: ((event: MessageEvent) => void) | null; send(text: string): void; close(): void; } const connectChat = (): ChatSocket => new WebSocket(`${location.protocol === "https:" ? "wss:" : "ws:"}//${location.host}/api/chat`); type Message = { role: "user" | "assistant" | "tool"; text: string; path?: string }; /** notebookPath and openNotebook use app paths (relative to notebooks/); the chat wire uses workspace paths. */ export function ChatPanel({ notebookPath, openNotebook, openTerminal, onClose, connect = connectChat }: { notebookPath?: string; openNotebook(path: string): void; openTerminal(): void; onClose?(): void; connect?: () => ChatSocket; }) { const [history, setHistory] = useState([]); const [selected, setSelected] = useState(""); const [messages, setMessages] = useState([]); const cache = useRef(new Map()); const selectedRef = useRef(""); const [text, setText] = useState(""); const [allowShell, setAllowShell] = useState(false); const [busy, setBusy] = useState(false); const [ready, setReady] = useState(false); const [error, setError] = useState(""); const [login, setLogin] = useState(false); const [summary, setSummary] = useState(""); const [attempt, setAttempt] = useState(0); const socket = useRef(); const end = useRef(null); useEffect(() => { end.current?.scrollIntoView?.({ block: "nearest" }); }, [messages]); useEffect(() => { let alive = true; let connection: ChatSocket; try { connection = connect(); socket.current = connection; } catch { setError("Cannot connect to chat."); return; } connection.onopen = () => { if (alive) { setReady(true); setError(""); } }; connection.onclose = connection.onerror = () => { if (alive) { setReady(false); setBusy(false); setError("Chat disconnected. The current turn was stopped. Reconnect to continue."); } }; connection.onmessage = ({ data }) => { if (!alive) return; let event: ChatEvent; try { event = JSON.parse(data); } catch { return; } if (event.type === "history") setHistory(event.conversations); if (event.type === "conversation") { selectedRef.current = event.conversation.id; setSelected(event.conversation.id); setHistory(previous => [...previous.filter(c => c.id !== event.conversation.id), event.conversation]); } if (event.type === "delta") setMessages(previous => { const last = previous.at(-1); return last?.role === "assistant" ? [...previous.slice(0, -1), { ...last, text: last.text + event.text }] : [...previous, { role: "assistant", text: event.text }]; }); if (event.type === "tool") setMessages(previous => [...previous, { role: "tool", text: `${["Edit", "Write", "MultiEdit"].includes(event.name) ? "Editing" : event.name} ${event.path ?? ""}`.trim(), path: event.path, }]); if (event.type === "error") { setBusy(false); setError(event.message); setLogin(event.code === "login" || event.code === "missing"); } if (event.type === "finished") { setBusy(false); setSummary(event.cancelled ? "Stopped" : `Finished${event.durationMs === undefined ? "" : ` in ${(event.durationMs / 1000).toFixed(1)}s`}${event.costUsd === undefined ? "" : ` · estimated $${event.costUsd.toFixed(4)}`}`); } }; return () => { alive = false; connection.close(); }; }, [connect, attempt]); useEffect(() => { if (selected) cache.current.set(selected, messages); }, [messages, selected]); function choose(id: string) { selectedRef.current = id; setSelected(id); setMessages(cache.current.get(id) ?? []); setError(""); setLogin(false); setSummary(""); setAllowShell(false); } function send(message: ChatClientMessage) { try { socket.current?.send(JSON.stringify(message)); } catch { setBusy(false); setError("Cannot send chat message. Reconnect to continue."); } } return