Merge branch 't3/claude-chat-panel'
# Conflicts: # .agents/mind/gotchas.md # packages/core/src/protocol.ts
This commit is contained in:
@@ -34,6 +34,7 @@ import type { Api } from "./api";
|
||||
import { emptySession, eventReducer, stepKey } from "./events";
|
||||
import { ParamsForm } from "./ParamsForm";
|
||||
import { StepCard } from "./StepCard";
|
||||
import { ChatPanel } from "./ChatPanel";
|
||||
const TerminalSlot = lazy(() =>
|
||||
import("./TerminalSlot").then((module) => ({ default: module.TerminalSlot })),
|
||||
);
|
||||
@@ -61,6 +62,7 @@ export function App({ api }: { api: Api }) {
|
||||
const [values, setValues] = useState<ParamValues>({});
|
||||
const [edit, setEdit] = useState(false);
|
||||
const [terminal, setTerminal] = useState(false);
|
||||
const [chat, setChat] = useState(false);
|
||||
const [terminalOpened, setTerminalOpened] = useState(false);
|
||||
const [conflict, setConflict] = useState(false);
|
||||
const [error, setError] = useState("");
|
||||
@@ -338,7 +340,7 @@ export function App({ api }: { api: Api }) {
|
||||
</main>
|
||||
);
|
||||
return (
|
||||
<div className={`app ${terminal ? "with-terminal" : ""}`}>
|
||||
<div className={`app ${terminal || chat ? "with-terminal" : ""}`}>
|
||||
<aside className="sidebar">
|
||||
<h1>
|
||||
ShellBook<span>RUNBOOKS</span>
|
||||
@@ -378,6 +380,7 @@ export function App({ api }: { api: Api }) {
|
||||
{page === "Hosts" && <p>Host management will appear here.</p>}
|
||||
<div hidden={page !== "Notebooks"}>
|
||||
<div className="toolbar">
|
||||
<button aria-expanded={chat} onClick={() => { setChat(!chat); setTerminal(false); }}>Chat</button>
|
||||
<span>{doc?.notebook.title ?? "Loading workspace…"}</span>
|
||||
<button onClick={() => setEdit(!edit)}>
|
||||
{edit ? "Close editor" : "Edit Markdown"}
|
||||
@@ -386,6 +389,7 @@ export function App({ api }: { api: Api }) {
|
||||
aria-expanded={terminal}
|
||||
onClick={() => {
|
||||
setTerminalOpened(true);
|
||||
setChat(false);
|
||||
setTerminal(!terminal);
|
||||
}}
|
||||
>
|
||||
@@ -500,6 +504,9 @@ export function App({ api }: { api: Api }) {
|
||||
)}
|
||||
</div>
|
||||
</main>
|
||||
{chat && <ChatPanel notebookPath={doc?.path} openNotebook={path => {
|
||||
if (!dirty || window.confirm("Discard unsaved edits?")) void load(path);
|
||||
}} openTerminal={() => { setChat(false); setTerminalOpened(true); setTerminal(true); }} />}
|
||||
{terminalOpened && (
|
||||
<Suspense fallback={<p>Loading terminal...</p>}>
|
||||
<TerminalSlot collapsed={!terminal} />
|
||||
|
||||
@@ -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>;
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
.chat-panel { position: sticky; top: 0; height: 100vh; min-width: 0; display: flex; flex-direction: column; gap: .6rem; padding: 1rem; border-left: 1px solid #64748b; box-sizing: border-box; }
|
||||
.chat-panel h2, .chat-panel p { margin: .25rem 0; }
|
||||
.chat-panel select, .chat-panel textarea { width: 100%; box-sizing: border-box; }
|
||||
.chat-panel label { display: block; }
|
||||
.chat-messages { flex: 1; min-height: 120px; overflow-y: auto; overflow-wrap: anywhere; }
|
||||
.chat-messages pre { overflow-x: auto; }
|
||||
.chat-message { padding: .6rem 0; border-bottom: 1px solid #64748b55; }
|
||||
.chat-message.user { opacity: .85; }
|
||||
.chat-shell { margin-top: .5rem; }
|
||||
.chat-panel form { flex-shrink: 0; }
|
||||
@media (max-width: 900px) { .chat-panel { position: static; grid-column: 1 / -1; height: min(800px, 100dvh); } }
|
||||
@media (max-width: 580px) { .with-terminal { display: block; } .chat-panel { padding: .7rem; } }
|
||||
@@ -0,0 +1,49 @@
|
||||
import { act, fireEvent, render, screen } from "@testing-library/react";
|
||||
import { expect, it, vi } from "vitest";
|
||||
import { ChatPanel, type ChatSocket } from "../ChatPanel";
|
||||
import type { ChatEvent } from "@shellbook/core";
|
||||
|
||||
function setup() {
|
||||
const socket: ChatSocket = { onopen: null, onclose: null, onerror: null, onmessage: null, send: vi.fn(), close: vi.fn() };
|
||||
const openNotebook = vi.fn(), openTerminal = vi.fn();
|
||||
const view = render(<ChatPanel notebookPath="notebooks/current.md" connect={() => socket} openNotebook={openNotebook} openTerminal={openTerminal} />);
|
||||
act(() => socket.onopen?.(new Event("open")));
|
||||
const emit = (event: ChatEvent) => act(() => socket.onmessage?.({ data: JSON.stringify(event) } as MessageEvent));
|
||||
return { socket, emit, openNotebook, openTerminal, ...view };
|
||||
}
|
||||
it("sends notebook context, defaults shell off, streams Markdown, opens edited notebooks and stops", () => {
|
||||
const { socket, emit, openNotebook } = setup();
|
||||
fireEvent.change(screen.getByLabelText("Message"), { target: { value: "Create nginx" } });
|
||||
fireEvent.click(screen.getByRole("button", { name: "Send" }));
|
||||
expect(socket.send).toHaveBeenCalledWith(JSON.stringify({ type: "send", message: "Create nginx", notebookPath: "notebooks/current.md", allowShell: false }));
|
||||
emit({ type: "delta", text: "Hello **" }); emit({ type: "delta", text: "world**" });
|
||||
expect(screen.getByText("world").tagName).toBe("STRONG");
|
||||
emit({ type: "tool", name: "Edit", path: "notebooks/nginx.md" });
|
||||
fireEvent.click(screen.getByText("Open notebook")); expect(openNotebook).toHaveBeenCalledWith("notebooks/nginx.md");
|
||||
fireEvent.click(screen.getByText("Stop")); expect(socket.send).toHaveBeenLastCalledWith('{"type":"cancel"}');
|
||||
emit({ type: "finished", durationMs: 1000, costUsd: .01 }); expect(screen.getByRole("status")).toHaveTextContent("Finished in 1.0s");
|
||||
});
|
||||
it("offers terminal login recovery and closes the socket on unmount", () => {
|
||||
const { emit, openTerminal, unmount, socket } = setup();
|
||||
emit({ type: "error", code: "login", message: "Please log in" });
|
||||
fireEvent.click(screen.getByRole("button", { name: /Open Terminal/ })); expect(openTerminal).toHaveBeenCalledOnce();
|
||||
expect(screen.getByRole("alert")).toHaveTextContent("Please log in");
|
||||
unmount(); expect(socket.close).toHaveBeenCalledOnce();
|
||||
});
|
||||
it("resumes history, enables shell explicitly and resets it for new conversations", () => {
|
||||
const { emit, socket } = setup();
|
||||
emit({ type: "history", conversations: [{ id: "saved", title: "Earlier notebook", createdAt: "now", updatedAt: "now" }] });
|
||||
fireEvent.change(screen.getByLabelText("Conversation history"), { target: { value: "saved" } });
|
||||
fireEvent.click(screen.getByLabelText(/Allow Claude/));
|
||||
fireEvent.click(screen.getByText("Add a check that…"));
|
||||
fireEvent.click(screen.getByRole("button", { name: "Send" }));
|
||||
expect(JSON.parse((socket.send as ReturnType<typeof vi.fn>).mock.calls[0]![0])).toMatchObject({ conversationId: "saved", allowShell: true });
|
||||
expect(screen.getByText("New conversation", { selector: "button" })).toBeDisabled();
|
||||
emit({ type: "finished" }); fireEvent.click(screen.getByText("New conversation", { selector: "button" }));
|
||||
expect(screen.getByLabelText(/Allow Claude/)).not.toBeChecked();
|
||||
});
|
||||
it("handles a disconnect and disables sending", () => {
|
||||
const { socket } = setup(); act(() => socket.onclose?.(new CloseEvent("close")));
|
||||
expect(screen.getByRole("alert")).toHaveTextContent("disconnected");
|
||||
expect(screen.getByRole("button", { name: "Reconnect chat" })).toBeInTheDocument();
|
||||
});
|
||||
Reference in New Issue
Block a user