feat(web): add notebook chat panel (#8)
This commit is contained in:
@@ -0,0 +1,97 @@
|
||||
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 };
|
||||
|
||||
export function ChatPanel({ notebookPath, openNotebook, openTerminal, connect = connectChat }: {
|
||||
notebookPath?: string; openNotebook(path: string): void; openTerminal(): void; connect?: () => ChatSocket;
|
||||
}) {
|
||||
const [history, setHistory] = useState<ChatConversation[]>([]);
|
||||
const [selected, setSelected] = useState("");
|
||||
const [messages, setMessages] = useState<Message[]>([]);
|
||||
const cache = useRef(new Map<string, Message[]>());
|
||||
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<ChatSocket>();
|
||||
const end = useRef<HTMLDivElement>(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 <aside className="chat-panel" aria-label="Chat panel">
|
||||
<h2>Chat with Claude</h2>
|
||||
<div className="actions"><button disabled={busy} onClick={() => choose("")}>New conversation</button>
|
||||
{!ready && <button onClick={() => setAttempt(n => n + 1)}>Reconnect chat</button>}</div>
|
||||
<label>Conversation history<select aria-label="Conversation history" disabled={busy} value={selected} onChange={e => choose(e.target.value)}>
|
||||
<option value="">New conversation</option>{[...history].reverse().map(c => <option key={c.id} value={c.id}>{c.title}</option>)}
|
||||
</select></label>
|
||||
<div className="chat-messages" role="log" aria-label="Chat messages" aria-live="polite">
|
||||
{!messages.length && <p>{selected ? "Continue this conversation. Earlier messages are retained by the Claude CLI; this view shows messages from this browser session." : "Ask Claude to create or edit a notebook. Do not send secrets."}</p>}
|
||||
{messages.map((m, i) => <div key={i} className={`chat-message ${m.role}`}>
|
||||
{m.role === "tool" ? <small>{m.text} {m.path && <button onClick={() => openNotebook(m.path!)}>Open notebook</button>}</small> : <><strong>{m.role === "user" ? "You" : "Claude"}</strong><ReactMarkdown>{m.text}</ReactMarkdown></>}
|
||||
</div>)}<div ref={end} />
|
||||
</div>
|
||||
{error && <p role="alert">{error}</p>}
|
||||
{login && <button onClick={openTerminal}>Open Terminal — run claude, then /login</button>}
|
||||
<p role="status">{busy ? "Claude is working…" : summary}</p>
|
||||
{!messages.length && <div className="actions">{["Create a notebook that…", "Add a check that…"].map(prompt => <button key={prompt} onClick={() => setText(prompt)}>{prompt}</button>)}</div>}
|
||||
<form onSubmit={e => { e.preventDefault(); if (!ready || busy || !text.trim()) return;
|
||||
setMessages(previous => [...previous, { role: "user", text }]); setBusy(true); setError(""); setLogin(false); setSummary("");
|
||||
send({ type: "send", conversationId: selectedRef.current || undefined, message: text, notebookPath, allowShell }); setText("");
|
||||
}}>
|
||||
<label>Message<textarea value={text} onChange={e => setText(e.target.value)} maxLength={32000} required rows={3} /></label>
|
||||
<label className="chat-shell"><input type="checkbox" checked={allowShell} disabled={busy} onChange={e => setAllowShell(e.target.checked)} />Allow Claude to run shell commands on the ShellBook server</label>
|
||||
<small>Off by default. Enabling this allows commands as the service user, including network access. File tools otherwise stay in the workspace.</small>
|
||||
<div className="actions"><button disabled={!ready || busy || !text.trim()}>Send</button>{busy && <button type="button" onClick={() => send({ type: "cancel" })}>Stop</button>}</div>
|
||||
</form>
|
||||
</aside>;
|
||||
}
|
||||
Reference in New Issue
Block a user