Files
ShellBook/apps/web/src/ChatPanel.tsx
T
Florian Schmidt e38f9c453c feat(web): rework layout and quality of life (#12)
- App shell: top bar with connection state and Chat/Terminal toggles,
  per-column scrolling, sidebar only on the Notebooks page.
- Hash routes (#/notebooks/<path>, #/hosts, #/settings) so reloads and
  links keep the open notebook and page.
- Parameters sit beside the notebook on wide screens, collapsible, with
  missing-count summary and Reset; non-secret values are remembered per
  notebook in localStorage (secrets and undeclared names never stored).
- Sticky notebook header with breadcrumbs, check summary and run-all;
  Ctrl/Cmd+S saves the Markdown draft.
- Step cards show target, one deduplicated hint for missing values and
  copy feedback.
- Shared Dialog, Menu and CopyButton components; notebook and host
  actions move into menus and modal dialogs.
- Hosts page as a compact list; Settings split into cards with sign out
  for this browser.
2026-11-16 12:32:01 +01:00

104 lines
7.2 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
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<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 side-panel" aria-label="Chat panel">
<header className="panel-header">
<h2>Chat with Claude</h2>
<span className="spacer" />
{!ready && <button onClick={() => setAttempt(n => n + 1)}>Reconnect chat</button>}
<button disabled={busy} onClick={() => choose("")}>New conversation</button>
{onClose && <button className="icon" aria-label="Close chat" onClick={onClose}>×</button>}
</header>
{notebookPath && <p className="muted">About: <code>{notebookPath}</code></p>}
<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!.replace(/^notebooks\//, ""))}>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: notebookPath && `notebooks/${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>;
}