A personal assistant that lives on your desktop, remembers what matters, and can use your Mac for you.
TypeScript
feat(ui): add chat, ask cards, recovery prompt, and floating Dot surfaces
Alan Buscagliaf871c011ef2e
diff --git a/packages/ui/src/App.tsx b/packages/ui/src/App.tsxnew file mode 100644index 0000000..c5c640f--- /dev/null+++ b/packages/ui/src/App.tsx@@ -0,0 +1,104 @@+import { useEffect, useState } from "react";+import { type ConnectionInfo, tokenFromLocation } from "./client.ts";+import { ChatSurface } from "./components/ChatSurface.tsx";+import { DotSurface } from "./components/DotSurface.tsx";+import {+ connectionInfo,+ hidePanel,+ inDesktop,+ onDesktopEvent,+ setDotState,+ startDragging,+ togglePanel,+} from "./desktop.ts";+import { useDot } from "./useDot.ts";++type Surface = "dot" | "panel" | "web";++function currentSurface(): Surface {+ const surface = new URLSearchParams(window.location.search).get("surface");+ return surface === "dot" || surface === "panel" ? surface : "web";+}++function browserConnection(): ConnectionInfo | undefined {+ const token = tokenFromLocation(window.location, window.sessionStorage, (url) =>+ window.history.replaceState(null, "", url),+ );+ if (!token) return undefined;+ const daemon = import.meta.env.VITE_DAEMON_ORIGIN as string | undefined;+ const base = daemon ? new URL(daemon) : window.location;+ const protocol = base.protocol === "https:" ? "wss:" : "ws:";+ return { url: `${protocol}//${base.host}/ws`, token };+}++export function App() {+ const surface = currentSurface();+ const [info, setInfo] = useState<ConnectionInfo | undefined>(undefined);+ const [missingToken, setMissingToken] = useState(false);+ const [focusKey, setFocusKey] = useState(0);+ const { state, send, dismiss } = useDot(info);++ useEffect(() => {+ if (inDesktop()) {+ connectionInfo().then(setInfo, () => setMissingToken(true));+ return;+ }+ const found = browserConnection();+ if (found) setInfo(found);+ else setMissingToken(true);+ }, []);++ useEffect(() => {+ if (surface === "dot") setDotState(state.agentState);+ }, [surface, state.agentState]);++ useEffect(() => {+ if (surface !== "panel") return;+ const subscriptions = [+ onDesktopEvent("dot://new-conversation", () => send({ type: "new_conversation" })),+ onDesktopEvent("dot://panel-shown", () => setFocusKey((k) => k + 1)),+ ];+ const onKey = (event: KeyboardEvent) => {+ if (event.key === "Escape") hidePanel();+ };+ window.addEventListener("keydown", onKey);+ return () => {+ window.removeEventListener("keydown", onKey);+ for (const s of subscriptions) void s.then((unlisten) => unlisten());+ };+ }, [surface, send]);++ useEffect(() => {+ document.documentElement.dataset.surface = surface;+ }, [surface]);++ if (surface === "dot") {+ return (+ <DotSurface+ agentState={state.agentState}+ connected={state.connection === "open"}+ toggle={togglePanel}+ startDrag={() => void startDragging()}+ />+ );+ }+ if (missingToken) {+ return (+ <div className="chat chat-web">+ <div className="status" role="status">+ Open the link the assistant printed when it started; it includes your access key.+ </div>+ </div>+ );+ }+ return (+ <ChatSurface+ variant={surface === "panel" ? "panel" : "web"}+ state={state}+ send={send}+ dismiss={dismiss}+ focusKey={focusKey}+ {...(surface === "panel" ? { onHide: hidePanel } : {})}+ />+ );+}diff --git a/packages/ui/src/client.ts b/packages/ui/src/client.tsnew file mode 100644index 0000000..e9972b9--- /dev/null+++ b/packages/ui/src/client.ts@@ -0,0 +1,120 @@+import { type ClientMessage, CloseCode, PROTOCOL_VERSION, type ServerMessage } from "@gentle-dot/protocol";+import type { ConnectionStatus } from "./store.ts";++export interface ConnectionInfo {+ url: string;+ token: string;+ webUrl?: string;+}++interface ClientHandlers {+ onStatus: (status: ConnectionStatus) => void;+ onMessage: (message: ServerMessage) => void;+ WebSocketImpl?: typeof WebSocket;+}++const BACKOFF_MS = [500, 1000, 2000, 5000];+const TOKEN_KEY = "gentle-dot-token";++/** One WebSocket session with the daemon: hello, reconnect with backoff, and history refresh. */+export class DotClient {+ private socket: WebSocket | undefined;+ private ready = false;+ private stopped = false;+ private attempts = 0;+ private retryTimer: ReturnType<typeof setTimeout> | undefined;+ private readonly info: ConnectionInfo;+ private readonly handlers: ClientHandlers;++ constructor(info: ConnectionInfo, handlers: ClientHandlers) {+ this.info = info;+ this.handlers = handlers;+ }++ start(): void {+ this.stopped = false;+ this.connect();+ }++ stop(): void {+ this.stopped = true;+ clearTimeout(this.retryTimer);+ this.socket?.close();+ }++ send(message: ClientMessage): boolean {+ if (!this.ready || !this.socket || this.socket.readyState !== 1) return false;+ this.socket.send(JSON.stringify(message));+ return true;+ }++ private connect(): void {+ const Impl = this.handlers.WebSocketImpl ?? WebSocket;+ const socket = new Impl(this.info.url);+ this.socket = socket;+ this.ready = false;+ this.handlers.onStatus("connecting");+ socket.onopen = () => {+ socket.send(JSON.stringify({ type: "hello", token: this.info.token, protocol: PROTOCOL_VERSION }));+ };+ socket.onmessage = (event: MessageEvent) => {+ let message: ServerMessage;+ try {+ message = JSON.parse(String(event.data)) as ServerMessage;+ } catch {+ return;+ }+ this.handlers.onMessage(message);+ if (message.type === "ready") {+ this.ready = true;+ this.attempts = 0;+ this.handlers.onStatus("open");+ this.send({ type: "get_history" });+ this.send({ type: "list_conversations" });+ }+ };+ socket.onclose = (event: CloseEvent) => {+ if (socket !== this.socket) return;+ this.ready = false;+ if (event.code === CloseCode.unauthorized) {+ this.handlers.onStatus("unauthorized");+ return;+ }+ this.handlers.onStatus("closed");+ if (this.stopped) return;+ const delay = BACKOFF_MS[Math.min(this.attempts, BACKOFF_MS.length - 1)] ?? 5000;+ this.attempts += 1;+ this.retryTimer = setTimeout(() => this.connect(), delay);+ };+ }+}++interface LocationLike {+ hash: string;+ pathname: string;+ search: string;+}++interface StorageLike {+ getItem(key: string): string | null;+ setItem(key: string, value: string): void;+}++/**+ * The browser receives the token once in the URL fragment (`#token=…`), keeps it+ * in session storage, and removes it from the address bar.+ */+export function tokenFromLocation(+ location: LocationLike,+ storage: StorageLike,+ replaceUrl: (url: string) => void,+): string | undefined {+ const match = /(?:^#|&)token=([^&]+)/.exec(location.hash);+ if (match?.[1]) {+ const token = decodeURIComponent(match[1]);+ storage.setItem(TOKEN_KEY, token);+ replaceUrl(`${location.pathname}${location.search}`);+ return token;+ }+ return storage.getItem(TOKEN_KEY) ?? undefined;+}diff --git a/packages/ui/src/components/AskCard.tsx b/packages/ui/src/components/AskCard.tsxnew file mode 100644index 0000000..bec623a--- /dev/null+++ b/packages/ui/src/components/AskCard.tsx@@ -0,0 +1,66 @@+import type { Ask } from "@gentle-dot/protocol";+import { useState } from "react";+import type { Send } from "./types.ts";++export function AskCard({ ask, send }: { ask: Ask; send: Send }) {+ const [value, setValue] = useState(ask.prefill ?? "");+ const answer = (fields: { value?: string; confirmed?: boolean; cancelled?: boolean }) =>+ send({ type: "ui_response", requestId: ask.requestId, ...fields });++ return (+ <section className="ask-card" aria-label="The assistant needs your answer">+ <p className="ask-title">{ask.title}</p>+ {ask.message ? <p className="ask-message">{ask.message}</p> : null}+ {ask.method === "select" ? (+ <div className="ask-options">+ {(ask.options ?? []).map((option) => (+ <button key={option} type="button" onClick={() => answer({ value: option })}>+ {option}+ </button>+ ))}+ </div>+ ) : null}+ {ask.method === "confirm" ? (+ <div className="ask-options">+ <button type="button" className="primary" onClick={() => answer({ confirmed: true })}>+ Yes+ </button>+ <button type="button" onClick={() => answer({ confirmed: false })}>+ No+ </button>+ </div>+ ) : null}+ {ask.method === "input" || ask.method === "editor" ? (+ <form+ className="ask-form"+ onSubmit={(event) => {+ event.preventDefault();+ answer({ value });+ }}+ >+ {ask.method === "editor" ? (+ <textarea+ aria-label={ask.title}+ rows={6}+ value={value}+ onChange={(event) => setValue(event.target.value)}+ />+ ) : (+ <input+ aria-label={ask.title}+ placeholder={ask.placeholder ?? ""}+ value={value}+ onChange={(event) => setValue(event.target.value)}+ />+ )}+ <button type="submit" className="primary">+ Send answer+ </button>+ </form>+ ) : null}+ <button type="button" className="ask-skip" onClick={() => answer({ cancelled: true })}>+ Skip+ </button>+ </section>+ );+}diff --git a/packages/ui/src/components/ChatSurface.tsx b/packages/ui/src/components/ChatSurface.tsxnew file mode 100644index 0000000..80fc3ff--- /dev/null+++ b/packages/ui/src/components/ChatSurface.tsx@@ -0,0 +1,138 @@+import { useState } from "react";+import { activeTitle, type DotState, isBusy } from "../store.ts";+import { AskCard } from "./AskCard.tsx";+import { Composer } from "./Composer.tsx";+import { MessageList } from "./MessageList.tsx";+import { newRequestId, type Send } from "./types.ts";++interface ChatSurfaceProps {+ variant: "web" | "panel";+ state: DotState;+ send: Send;+ dismiss: (id: number) => void;+ onHide?: () => void;+ focusKey?: number;+}++const CONTINUE_TEXT = "Continue where you left off.";++function statusText(state: DotState): string | undefined {+ if (state.connection === "unauthorized") {+ return "This link is not valid anymore. Please open the link the assistant printed when it started.";+ }+ if (state.connection === "closed") return "Reconnecting to the assistant…";+ if (state.connection === "connecting") return "Connecting…";+ if (state.agentState === "restarting") return "The assistant is restarting…";+ if (state.agentState === "starting") return "Starting the assistant…";+ return undefined;+}++export function ChatSurface({ variant, state, send, dismiss, onHide, focusKey }: ChatSurfaceProps) {+ const [showConversations, setShowConversations] = useState(false);+ const status = statusText(state);+ const ready =+ state.connection === "open" && state.agentState !== "restarting" && state.agentState !== "starting";++ return (+ <div className={`chat chat-${variant}`} data-state={state.agentState}>+ <header className="chat-header" data-tauri-drag-region={variant === "panel" ? "" : undefined}>+ <span className={`state-dot state-${state.agentState}`} aria-hidden="true" />+ <h1>{activeTitle(state)}</h1>+ <button+ type="button"+ className="icon"+ aria-label="Conversations"+ aria-expanded={showConversations}+ onClick={() => {+ if (!showConversations) send({ type: "list_conversations" });+ setShowConversations(!showConversations);+ }}+ >+ ☰+ </button>+ <button+ type="button"+ className="icon"+ aria-label="New conversation"+ disabled={!ready}+ onClick={() => {+ setShowConversations(false);+ send({ type: "new_conversation" });+ }}+ >+ ++ </button>+ {onHide ? (+ <button type="button" className="icon" aria-label="Hide" onClick={onHide}>+ –+ </button>+ ) : null}+ </header>++ {showConversations ? (+ <nav className="conversations" aria-label="Earlier conversations">+ {state.conversations.length === 0 ? <p className="muted">No conversations yet.</p> : null}+ {state.conversations.map((conversation) => (+ <button+ key={conversation.id}+ type="button"+ className={conversation.id === state.conversationId ? "active" : ""}+ onClick={() => {+ setShowConversations(false);+ if (conversation.id !== state.conversationId) {+ send({ type: "open_conversation", conversationId: conversation.id });+ }+ }}+ >+ <span>{conversation.title}</span>+ <time dateTime={conversation.updatedAt}>+ {new Date(conversation.updatedAt).toLocaleString()}+ </time>+ </button>+ ))}+ </nav>+ ) : null}++ {status ? (+ <div className="status" role="status">+ {status}+ </div>+ ) : null}++ <main className="chat-body">+ <MessageList messages={state.messages} />+ {state.interrupted ? (+ <div className="interrupted">+ <p>I was interrupted. Continue?</p>+ <button+ type="button"+ className="primary"+ disabled={!ready}+ onClick={() => send({ type: "send", text: CONTINUE_TEXT, requestId: newRequestId() })}+ >+ Continue+ </button>+ </div>+ ) : null}+ {state.asks.map((ask) => (+ <AskCard key={ask.requestId} ask={ask} send={send} />+ ))}+ </main>++ {state.notices.length > 0 ? (+ <div className="notices">+ {state.notices.map((notice) => (+ <div key={notice.id} className={`notice notice-${notice.level}`}>+ <span>{notice.message}</span>+ <button type="button" aria-label="Dismiss" onClick={() => dismiss(notice.id)}>+ ×+ </button>+ </div>+ ))}+ </div>+ ) : null}++ <Composer busy={isBusy(state.agentState)} disabled={!ready} send={send} focusKey={focusKey} />+ </div>+ );+}diff --git a/packages/ui/src/components/Composer.tsx b/packages/ui/src/components/Composer.tsxnew file mode 100644index 0000000..beddab9--- /dev/null+++ b/packages/ui/src/components/Composer.tsx@@ -0,0 +1,67 @@+import { type KeyboardEvent, useEffect, useRef, useState } from "react";+import { newRequestId, type Send } from "./types.ts";++interface ComposerProps {+ busy: boolean;+ disabled: boolean;+ send: Send;+ /** Changes to this value move focus to the text box. */+ focusKey?: number;+}++export function Composer({ busy, disabled, send, focusKey }: ComposerProps) {+ const [text, setText] = useState("");+ const box = useRef<HTMLTextAreaElement>(null);++ useEffect(() => {+ if (focusKey !== undefined) box.current?.focus();+ }, [focusKey]);++ function submit() {+ const value = text.trim();+ if (!value || disabled) return;+ send({ type: "send", text: value, requestId: newRequestId() });+ setText("");+ }++ function onKeyDown(event: KeyboardEvent<HTMLTextAreaElement>) {+ if (event.key === "Enter" && !event.shiftKey && !event.nativeEvent.isComposing) {+ event.preventDefault();+ submit();+ }+ }++ return (+ <form+ className="composer"+ onSubmit={(event) => {+ event.preventDefault();+ submit();+ }}+ >+ <textarea+ ref={box}+ aria-label="Message"+ placeholder={busy ? "Add to what I'm doing…" : "Ask me anything…"}+ rows={1}+ value={text}+ disabled={disabled}+ onChange={(event) => setText(event.target.value)}+ onKeyDown={onKeyDown}+ />+ {busy ? (+ <button type="button" className="composer-stop" onClick={() => send({ type: "abort" })}>+ Stop+ </button>+ ) : null}+ <button+ type="submit"+ className="composer-send"+ disabled={disabled || text.trim() === ""}+ aria-label="Send"+ >+ ↑+ </button>+ </form>+ );+}diff --git a/packages/ui/src/components/DotSurface.tsx b/packages/ui/src/components/DotSurface.tsxnew file mode 100644index 0000000..79991d6--- /dev/null+++ b/packages/ui/src/components/DotSurface.tsx@@ -0,0 +1,66 @@+import type { AgentState } from "@gentle-dot/protocol";+import { useRef } from "react";++const LABELS: Record<AgentState, string> = {+ starting: "starting",+ idle: "ready",+ thinking: "thinking",+ working: "working",+ needs_you: "needs your answer",+ restarting: "restarting",+ error: "unavailable",+};++const DRAG_THRESHOLD_PX = 3;++interface DotSurfaceProps {+ agentState: AgentState;+ connected: boolean;+ toggle: () => void;+ startDrag: () => void;+}++/** The collapsed, always-on-top orb. A click opens the panel; a drag moves the window. */+export function DotSurface({ agentState, connected, toggle, startDrag }: DotSurfaceProps) {+ const press = useRef<{ x: number; y: number; dragging: boolean } | undefined>(undefined);+ const state = connected ? agentState : "restarting";++ return (+ <button+ type="button"+ className={`dot dot-${state}`}+ aria-label={`Gentle Dot: ${LABELS[state]}`}+ onPointerDown={(event) => {+ if (event.button !== 0) return;+ press.current = { x: event.clientX, y: event.clientY, dragging: false };+ }}+ onPointerMove={(event) => {+ const p = press.current;+ if (!p || p.dragging) return;+ if (Math.hypot(event.clientX - p.x, event.clientY - p.y) > DRAG_THRESHOLD_PX) {+ p.dragging = true;+ startDrag();+ }+ }}+ onPointerUp={() => {+ const p = press.current;+ press.current = undefined;+ if (p && !p.dragging) toggle();+ }}+ onKeyDown={(event) => {+ if (event.key === "Enter" || event.key === " ") {+ event.preventDefault();+ toggle();+ }+ }}+ >+ <span className="dot-core" aria-hidden="true" />+ <span className="dot-orbit" aria-hidden="true" />+ {state === "needs_you" ? (+ <span className="dot-badge" aria-hidden="true">+ !+ </span>+ ) : null}+ </button>+ );+}diff --git a/packages/ui/src/components/MessageList.tsx b/packages/ui/src/components/MessageList.tsxnew file mode 100644index 0000000..68b4cd8--- /dev/null+++ b/packages/ui/src/components/MessageList.tsx@@ -0,0 +1,87 @@+import type { Activity, ActivityKind } from "@gentle-dot/protocol";+import { useEffect, useRef, useState } from "react";+import Markdown from "react-markdown";+import remarkGfm from "remark-gfm";+import type { ChatMessage } from "../store.ts";++const VERBS: Record<ActivityKind, [string, string, string]> = {+ read: ["Read", "file", "files"],+ edit: ["Edited", "file", "files"],+ run: ["Ran", "command", "commands"],+ search: ["Searched", "time", "times"],+ memory: ["Used memory", "time", "times"],+ delegate: ["Asked", "helper", "helpers"],+ other: ["Did", "step", "steps"],+};++/** "Read 2 files · Ran 1 command" */+export function summarize(activities: Activity[]): string {+ const counts = new Map<ActivityKind, number>();+ for (const activity of activities) counts.set(activity.kind, (counts.get(activity.kind) ?? 0) + 1);+ return [...counts]+ .map(([kind, count]) => {+ const [verb, one, many] = VERBS[kind];+ return `${verb} ${count} ${count === 1 ? one : many}`;+ })+ .join(" · ");+}++function Activities({ activities }: { activities: Activity[] }) {+ const [open, setOpen] = useState(false);+ const running = activities.find((a) => a.status === "running");+ return (+ <div className="activities">+ <button+ type="button"+ className="activities-summary"+ aria-expanded={open}+ onClick={() => setOpen(!open)}+ >+ <span className={running ? "pulse" : ""} aria-hidden="true" />+ {running ? running.title : summarize(activities)}+ </button>+ {open ? (+ <ul>+ {activities.map((a) => (+ <li key={a.id} className={`activity activity-${a.status}`}>+ {a.title}+ </li>+ ))}+ </ul>+ ) : null}+ </div>+ );+}++export function MessageList({ messages }: { messages: ChatMessage[] }) {+ const end = useRef<HTMLDivElement>(null);+ const last = messages.at(-1);+ // biome-ignore lint/correctness/useExhaustiveDependencies: scroll whenever the visible content grows+ useEffect(() => {+ end.current?.scrollIntoView?.({ block: "end" });+ }, [messages.length, last?.text, last?.activities.length]);++ if (messages.length === 0) {+ return (+ <div className="empty">+ <p>Hi! What can I do for you?</p>+ </div>+ );+ }+ return (+ <div className="messages" aria-live="polite">+ {messages.map((message) => (+ <article key={message.id} className={`message message-${message.role}`}>+ {message.activities.length > 0 ? <Activities activities={message.activities} /> : null}+ {message.text ? (+ <div className="message-body">+ <Markdown remarkPlugins={[remarkGfm]}>{message.text}</Markdown>+ </div>+ ) : null}+ {message.streaming ? <span className="caret" aria-hidden="true" /> : null}+ </article>+ ))}+ <div ref={end} />+ </div>+ );+}diff --git a/packages/ui/src/components/types.ts b/packages/ui/src/components/types.tsnew file mode 100644index 0000000..88ce358--- /dev/null+++ b/packages/ui/src/components/types.ts@@ -0,0 +1,7 @@+import type { ClientMessage } from "@gentle-dot/protocol";++export type Send = (message: ClientMessage) => void;++export function newRequestId(): string {+ return crypto.randomUUID();+}diff --git a/packages/ui/src/desktop.ts b/packages/ui/src/desktop.tsnew file mode 100644index 0000000..fa92d58--- /dev/null+++ b/packages/ui/src/desktop.ts@@ -0,0 +1,36 @@+import type { AgentState } from "@gentle-dot/protocol";+import { invoke, isTauri } from "@tauri-apps/api/core";+import type { ConnectionInfo } from "./client.ts";++/** Bridge to the Tauri shell (docs/design.md §9). Every call is a no-op in the browser. */+export const inDesktop = (): boolean => isTauri();++export function connectionInfo(): Promise<ConnectionInfo> {+ return invoke<ConnectionInfo>("connection_info");+}++export function togglePanel(): void {+ void invoke("toggle_panel");+}++export function hidePanel(): void {+ if (inDesktop()) void invoke("hide_panel");+}++export function setDotState(state: AgentState): void {+ if (inDesktop()) void invoke("set_dot_state", { state });+}++export async function startDragging(): Promise<void> {+ const { getCurrentWindow } = await import("@tauri-apps/api/window");+ await getCurrentWindow().startDragging();+}++export async function onDesktopEvent(+ name: "dot://new-conversation" | "dot://panel-shown",+ handler: () => void,+) {+ if (!inDesktop()) return () => {};+ const { listen } = await import("@tauri-apps/api/event");+ return listen(name, handler);+}diff --git a/packages/ui/src/main.tsx b/packages/ui/src/main.tsxindex 3669bd0..db71587 100644--- a/packages/ui/src/main.tsx+++ b/packages/ui/src/main.tsx@@ -1,11 +1,13 @@import { StrictMode } from "react";import { createRoot } from "react-dom/client";+import { App } from "./App.tsx";+import "./styles.css";const root = document.getElementById("root");if (root) {createRoot(root).render(<StrictMode>- <p>Gentle Dot</p>+ <App /></StrictMode>,);}diff --git a/packages/ui/src/store.ts b/packages/ui/src/store.tsnew file mode 100644index 0000000..e4e4ec1--- /dev/null+++ b/packages/ui/src/store.ts@@ -0,0 +1,156 @@+import type { Activity, AgentState, Ask, ConversationSummary, ServerMessage } from "@gentle-dot/protocol";++export type ConnectionStatus = "connecting" | "open" | "closed" | "unauthorized";++export interface ChatMessage {+ id: string;+ role: "user" | "assistant";+ text: string;+ streaming: boolean;+ activities: Activity[];+}++export interface Notice {+ id: number;+ level: "info" | "warning" | "error";+ message: string;+}++export interface DotState {+ connection: ConnectionStatus;+ agentState: AgentState;+ conversationId?: string;+ model?: string;+ messages: ChatMessage[];+ asks: Ask[];+ conversations: ConversationSummary[];+ interrupted: boolean;+ notices: Notice[];+}++export type DotAction =+ | { type: "server"; message: ServerMessage }+ | { type: "connection"; status: ConnectionStatus }+ | { type: "dismiss"; id: number };++export const initialState: DotState = {+ connection: "connecting",+ agentState: "starting",+ messages: [],+ asks: [],+ conversations: [],+ interrupted: false,+ notices: [],+};++let nextNotice = 0;++export function reduce(state: DotState, action: DotAction): DotState {+ switch (action.type) {+ case "connection":+ return {+ ...state,+ connection: action.status,+ messages: action.status === "open" ? state.messages : state.messages.map(stopStreaming),+ };+ case "dismiss":+ return { ...state, notices: state.notices.filter((n) => n.id !== action.id) };+ case "server":+ return reduceServer(state, action.message);+ }+}++function reduceServer(state: DotState, message: ServerMessage): DotState {+ switch (message.type) {+ case "ready":+ return {+ ...state,+ agentState: message.agentState,+ conversationId: message.conversationId ?? state.conversationId,+ model: message.model ?? state.model,+ };+ case "agent_state":+ return { ...state, agentState: message.state };+ case "user_message":+ return {+ ...state,+ interrupted: false,+ messages: [+ ...state.messages,+ { id: message.messageId, role: "user", text: message.text, streaming: false, activities: [] },+ ],+ };+ case "message_delta":+ return updateAssistant(state, message.messageId, (m) => ({+ ...m,+ text: m.text + message.delta,+ streaming: true,+ }));+ case "message_done":+ return updateAssistant(state, message.messageId, (m) => ({+ ...m,+ text: message.text,+ streaming: false,+ }));+ case "activity":+ return updateAssistant(state, message.messageId, (m) => {+ const index = m.activities.findIndex((a) => a.id === message.activity.id);+ const activities =+ index < 0+ ? [...m.activities, message.activity]+ : m.activities.map((a, i) => (i === index ? message.activity : a));+ return { ...m, activities };+ });+ case "ask":+ if (state.asks.some((a) => a.requestId === message.ask.requestId)) return state;+ return { ...state, asks: [...state.asks, message.ask] };+ case "ask_resolved":+ return { ...state, asks: state.asks.filter((a) => a.requestId !== message.requestId) };+ case "history":+ return {+ ...state,+ interrupted: false,+ conversationId: message.conversationId ?? state.conversationId,+ messages: message.messages.map((m) => ({ ...m, streaming: false })),+ };+ case "conversations":+ return {+ ...state,+ conversations: message.conversations,+ conversationId: message.activeId ?? state.conversationId,+ };+ case "interrupted":+ return { ...state, interrupted: true };+ case "toast":+ return addNotice(state, message.level, message.message);+ case "error":+ return addNotice(state, "error", message.message);+ }+}++function updateAssistant(state: DotState, id: string, update: (m: ChatMessage) => ChatMessage): DotState {+ const index = state.messages.findIndex((m) => m.id === id);+ if (index < 0) {+ const created: ChatMessage = { id, role: "assistant", text: "", streaming: false, activities: [] };+ return { ...state, messages: [...state.messages, update(created)] };+ }+ return { ...state, messages: state.messages.map((m, i) => (i === index ? update(m) : m)) };+}++function addNotice(state: DotState, level: Notice["level"], message: string): DotState {+ if (!message) return state;+ return { ...state, notices: [...state.notices.slice(-4), { id: ++nextNotice, level, message }] };+}++function stopStreaming(message: ChatMessage): ChatMessage {+ return message.streaming ? { ...message, streaming: false } : message;+}++/** Conversation title for the header. */+export function activeTitle(state: DotState): string {+ return state.conversations.find((c) => c.id === state.conversationId)?.title ?? "New conversation";+}++export function isBusy(state: AgentState): boolean {+ return state === "thinking" || state === "working" || state === "needs_you";+}diff --git a/packages/ui/src/styles.css b/packages/ui/src/styles.cssnew file mode 100644index 0000000..b20c03d--- /dev/null+++ b/packages/ui/src/styles.css@@ -0,0 +1,564 @@+:root {+ --bg: #0e0f13;+ --surface: rgba(28, 30, 38, 0.72);+ --surface-solid: #1c1e26;+ --raised: rgba(255, 255, 255, 0.06);+ --line: rgba(255, 255, 255, 0.09);+ --text: #ecedef;+ --muted: #8a8f98;+ --accent: #7c5cff;+ --accent-soft: rgba(124, 92, 255, 0.18);+ --amber: #f5a524;+ --danger: #f0506e;+ --radius: 20px;+ --ease: cubic-bezier(0.2, 0.8, 0.2, 1);+ color-scheme: dark light;+ font:+ 14px / 20px -apple-system,+ BlinkMacSystemFont,+ "SF Pro Text",+ "Segoe UI",+ system-ui,+ sans-serif;+ color: var(--text);+ -webkit-font-smoothing: antialiased;+}++@media (prefers-color-scheme: light) {+ :root {+ --bg: #f5f5f8;+ --surface: rgba(255, 255, 255, 0.78);+ --surface-solid: #ffffff;+ --raised: rgba(0, 0, 0, 0.04);+ --line: rgba(0, 0, 0, 0.08);+ --text: #17181c;+ --muted: #6b7079;+ --accent-soft: rgba(124, 92, 255, 0.12);+ }+}++* {+ box-sizing: border-box;+}++html,+body,+#root {+ height: 100%;+ margin: 0;+}++body {+ background: var(--bg);+}++html[data-surface="dot"] body,+html[data-surface="panel"] body {+ background: transparent;+ overflow: hidden;+}++button,+input,+textarea {+ font: inherit;+ color: inherit;+}++button {+ cursor: pointer;+ border: 1px solid var(--line);+ background: var(--raised);+ border-radius: 10px;+ padding: 6px 12px;+ transition: background 120ms var(--ease);+}++button:hover:not(:disabled) {+ background: var(--accent-soft);+}++button:disabled {+ opacity: 0.45;+ cursor: default;+}++button.primary {+ background: var(--accent);+ border-color: var(--accent);+ color: #fff;+}++button.icon {+ border: none;+ background: none;+ width: 30px;+ height: 30px;+ padding: 0;+ border-radius: 8px;+ color: var(--muted);+}++:focus-visible {+ outline: 2px solid var(--accent);+ outline-offset: 2px;+}++/* ---------- Dot ---------- */++.dot {+ position: relative;+ width: 56px;+ height: 56px;+ padding: 0;+ border: none;+ border-radius: 50%;+ background: radial-gradient(circle at 35% 30%, #a48bff, var(--accent) 55%, #4b2fd1);+ box-shadow: 0 0 0 0 var(--accent-soft);+ user-select: none;+ -webkit-user-select: none;+}++.dot:hover:not(:disabled) {+ background: radial-gradient(circle at 35% 30%, #b39dff, var(--accent) 55%, #4b2fd1);+}++.dot-core {+ position: absolute;+ inset: 18px;+ border-radius: 50%;+ background: rgba(255, 255, 255, 0.85);+}++.dot-orbit {+ position: absolute;+ inset: 6px;+ border-radius: 50%;+}++.dot-idle {+ animation: breathe 3.2s var(--ease) infinite;+}++.dot-thinking .dot-orbit::after {+ content: "";+ position: absolute;+ top: -2px;+ left: 50%;+ width: 6px;+ height: 6px;+ margin-left: -3px;+ border-radius: 50%;+ background: #fff;+}++.dot-thinking .dot-orbit {+ animation: orbit 1.2s linear infinite;+}++.dot-working {+ animation: pulse 1s var(--ease) infinite;+}++.dot-needs_you {+ box-shadow: 0 0 0 3px var(--amber);+}++.dot-restarting,+.dot-starting {+ filter: grayscale(1);+ opacity: 0.7;+}++.dot-error {+ box-shadow: 0 0 0 3px var(--danger);+}++.dot-badge {+ position: absolute;+ top: -2px;+ right: -2px;+ width: 18px;+ height: 18px;+ border-radius: 50%;+ background: var(--amber);+ color: #1a1200;+ font-size: 12px;+ font-weight: 700;+ line-height: 18px;+}++@keyframes breathe {+ 50% {+ box-shadow: 0 0 0 6px var(--accent-soft);+ }+}++@keyframes orbit {+ to {+ transform: rotate(360deg);+ }+}++@keyframes pulse {+ 50% {+ transform: scale(0.94);+ }+}++/* ---------- Chat ---------- */++.chat {+ display: flex;+ flex-direction: column;+ height: 100%;+ position: relative;+}++.chat-panel {+ background: var(--surface);+ border: 1px solid var(--line);+ border-radius: var(--radius);+ overflow: hidden;+ backdrop-filter: blur(24px) saturate(1.4);+ -webkit-backdrop-filter: blur(24px) saturate(1.4);+}++.chat-web {+ max-width: 760px;+ margin: 0 auto;+}++.chat-header {+ display: flex;+ align-items: center;+ gap: 6px;+ padding: 12px 12px 10px 16px;+ border-bottom: 1px solid var(--line);+}++.chat-header h1 {+ flex: 1;+ margin: 0;+ font-size: 14px;+ font-weight: 600;+ white-space: nowrap;+ overflow: hidden;+ text-overflow: ellipsis;+}++.state-dot {+ width: 8px;+ height: 8px;+ border-radius: 50%;+ background: var(--muted);+}++.state-idle {+ background: #3ecf8e;+}++.state-thinking,+.state-working {+ background: var(--accent);+ animation: pulse 1s var(--ease) infinite;+}++.state-needs_you {+ background: var(--amber);+}++.state-error {+ background: var(--danger);+}++.conversations {+ position: absolute;+ top: 52px;+ left: 8px;+ right: 8px;+ z-index: 2;+ max-height: 60%;+ overflow: auto;+ padding: 6px;+ background: var(--surface-solid);+ border: 1px solid var(--line);+ border-radius: 14px;+ box-shadow: 0 12px 32px rgba(0, 0, 0, 0.35);+}++.conversations button {+ display: flex;+ flex-direction: column;+ align-items: flex-start;+ width: 100%;+ border: none;+ background: none;+ text-align: left;+}++.conversations button.active {+ background: var(--accent-soft);+}++.conversations time,+.muted {+ color: var(--muted);+ font-size: 12px;+ line-height: 16px;+}++.status {+ margin: 10px 12px 0;+ padding: 8px 12px;+ border-radius: 10px;+ background: var(--raised);+ color: var(--muted);+ font-size: 12px;+ line-height: 16px;+}++.chat-body {+ flex: 1;+ overflow-y: auto;+ padding: 12px 16px;+}++.empty {+ height: 100%;+ display: grid;+ place-items: center;+ color: var(--muted);+}++.message {+ margin: 0 0 12px;+}++.message-user {+ display: flex;+ justify-content: flex-end;+}++.message-user .message-body {+ max-width: 85%;+ padding: 8px 12px;+ border-radius: 14px 14px 4px 14px;+ background: var(--accent);+ color: #fff;+}++.message-body > :first-child {+ margin-top: 0;+}++.message-body > :last-child {+ margin-bottom: 0;+}++.message-body pre {+ overflow-x: auto;+ padding: 10px 12px;+ border-radius: 10px;+ background: var(--raised);+ font:+ 12px / 18px "SF Mono",+ ui-monospace,+ Menlo,+ monospace;+}++.message-body code {+ font-family: "SF Mono", ui-monospace, Menlo, monospace;+ font-size: 12px;+}++.message-body a {+ color: var(--accent);+}++.caret {+ display: inline-block;+ width: 7px;+ height: 14px;+ margin-left: 2px;+ background: var(--accent);+ animation: blink 1s steps(2) infinite;+ vertical-align: text-bottom;+}++@keyframes blink {+ 50% {+ opacity: 0;+ }+}++.activities {+ margin-bottom: 6px;+}++.activities-summary {+ display: inline-flex;+ align-items: center;+ gap: 8px;+ padding: 3px 10px;+ border-radius: 999px;+ color: var(--muted);+ font-size: 12px;+ line-height: 16px;+}++.activities-summary .pulse {+ width: 6px;+ height: 6px;+ border-radius: 50%;+ background: var(--accent);+ animation: pulse 1s var(--ease) infinite;+}++.activities ul {+ margin: 6px 0 0;+ padding-left: 18px;+ color: var(--muted);+ font-size: 12px;+}++.activity-failed {+ color: var(--danger);+}++.ask-card,+.interrupted {+ margin: 4px 0 12px;+ padding: 12px;+ border-radius: 14px;+ border: 1px solid var(--amber);+ background: rgba(245, 165, 36, 0.08);+}++.interrupted {+ display: flex;+ align-items: center;+ justify-content: space-between;+ gap: 12px;+ border-color: var(--line);+ background: var(--raised);+}++.interrupted p,+.ask-title {+ margin: 0;+ font-weight: 600;+}++.ask-message {+ margin: 4px 0 0;+ color: var(--muted);+}++.ask-options,+.ask-form {+ display: flex;+ flex-wrap: wrap;+ gap: 8px;+ margin-top: 10px;+}++.ask-form input,+.ask-form textarea {+ flex: 1 1 100%;+ padding: 8px 10px;+ border-radius: 10px;+ border: 1px solid var(--line);+ background: var(--raised);+}++.ask-skip {+ margin-top: 8px;+ border: none;+ background: none;+ padding: 0;+ color: var(--muted);+ font-size: 12px;+}++.notices {+ display: flex;+ flex-direction: column;+ gap: 6px;+ padding: 0 12px 8px;+}++.notice {+ display: flex;+ align-items: center;+ justify-content: space-between;+ gap: 8px;+ padding: 8px 12px;+ border-radius: 10px;+ background: var(--raised);+ font-size: 12px;+}++.notice-error {+ background: rgba(240, 80, 110, 0.14);+}++.notice-warning {+ background: rgba(245, 165, 36, 0.14);+}++.notice button {+ border: none;+ background: none;+ padding: 0 4px;+}++.composer {+ display: flex;+ align-items: flex-end;+ gap: 8px;+ margin: 0 12px 12px;+ padding: 8px 8px 8px 14px;+ border-radius: 16px;+ border: 1px solid var(--line);+ background: var(--raised);+}++.composer textarea {+ flex: 1;+ resize: none;+ max-height: 160px;+ field-sizing: content;+ padding: 6px 0;+ border: none;+ background: none;+ outline: none;+}++.composer-send {+ width: 32px;+ height: 32px;+ padding: 0;+ border-radius: 50%;+ background: var(--accent);+ border-color: var(--accent);+ color: #fff;+ font-weight: 700;+}++.composer-stop {+ height: 32px;+ border-radius: 999px;+}++@media (prefers-reduced-motion: reduce) {+ *,+ *::before,+ *::after {+ /* biome-ignore lint/complexity/noImportantStyles: reduced motion must override every animation */+ animation: none !important;+ /* biome-ignore lint/complexity/noImportantStyles: reduced motion must override every transition */+ transition: none !important;+ }+}diff --git a/packages/ui/src/useDot.ts b/packages/ui/src/useDot.tsnew file mode 100644index 0000000..c9d79c7--- /dev/null+++ b/packages/ui/src/useDot.ts@@ -0,0 +1,38 @@+import type { ClientMessage } from "@gentle-dot/protocol";+import { useCallback, useEffect, useReducer, useRef } from "react";+import { type ConnectionInfo, DotClient } from "./client.ts";+import { initialState, reduce } from "./store.ts";++/** Connects to the daemon once `info` is known and exposes the reduced state. */+export function useDot(info: ConnectionInfo | undefined) {+ const [state, dispatch] = useReducer(reduce, initialState);+ const client = useRef<DotClient | undefined>(undefined);++ useEffect(() => {+ if (!info) return;+ const c = new DotClient(info, {+ onStatus: (status) => dispatch({ type: "connection", status }),+ onMessage: (message) => dispatch({ type: "server", message }),+ });+ client.current = c;+ c.start();+ return () => c.stop();+ }, [info]);++ const send = useCallback((message: ClientMessage) => {+ if (!client.current?.send(message)) {+ dispatch({+ type: "server",+ message: {+ type: "error",+ code: "offline",+ message: "Not connected yet. Try again in a moment.",+ seq: 0,+ },+ });+ }+ }, []);+ const dismiss = useCallback((id: number) => dispatch({ type: "dismiss", id }), []);++ return { state, send, dismiss };+}diff --git a/packages/ui/test/client.test.ts b/packages/ui/test/client.test.tsnew file mode 100644index 0000000..f71ed15--- /dev/null+++ b/packages/ui/test/client.test.ts@@ -0,0 +1,122 @@+import type { ServerMessage } from "@gentle-dot/protocol";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { DotClient, tokenFromLocation } from "../src/client.ts";+import type { ConnectionStatus } from "../src/store.ts";++class FakeSocket {+ static all: FakeSocket[] = [];+ readyState = 0;+ sent: unknown[] = [];+ onopen: (() => void) | null = null;+ onmessage: ((event: { data: string }) => void) | null = null;+ onclose: ((event: { code: number }) => void) | null = null;+ readonly url: string;+ constructor(url: string) {+ this.url = url;+ FakeSocket.all.push(this);+ }+ send(data: string) {+ this.sent.push(JSON.parse(data));+ }+ close() {+ this.readyState = 3;+ }+ open() {+ this.readyState = 1;+ this.onopen?.();+ }+ receive(message: { type: ServerMessage["type"]; [key: string]: unknown }) {+ this.onmessage?.({ data: JSON.stringify({ seq: 1, ...message }) });+ }+ drop(code = 1006) {+ this.readyState = 3;+ this.onclose?.({ code });+ }+}++function makeClient() {+ const statuses: ConnectionStatus[] = [];+ const messages: ServerMessage[] = [];+ const client = new DotClient(+ { url: "ws://127.0.0.1:4317/ws", token: "secret" },+ {+ onStatus: (s) => statuses.push(s),+ onMessage: (m) => messages.push(m),+ WebSocketImpl: FakeSocket as unknown as typeof WebSocket,+ },+ );+ return { client, statuses, messages };+}++beforeEach(() => {+ FakeSocket.all = [];+ vi.useFakeTimers();+});+afterEach(() => vi.useRealTimers());++describe("DotClient", () => {+ it("says hello with the token, then asks for history and conversations once ready", () => {+ const { client, statuses, messages } = makeClient();+ client.start();+ const socket = FakeSocket.all[0];+ socket?.open();+ expect(socket?.sent).toEqual([{ type: "hello", token: "secret", protocol: 1 }]);+ socket?.receive({ type: "ready", agentState: "idle" });+ expect(statuses.at(-1)).toBe("open");+ expect(messages.map((m) => m.type)).toEqual(["ready"]);+ expect(socket?.sent.slice(1)).toEqual([{ type: "get_history" }, { type: "list_conversations" }]);+ });++ it("reconnects with backoff after a drop", () => {+ const { client, statuses } = makeClient();+ client.start();+ FakeSocket.all[0]?.open();+ FakeSocket.all[0]?.receive({ type: "ready", agentState: "idle" });+ FakeSocket.all[0]?.drop();+ expect(statuses.at(-1)).toBe("closed");+ vi.advanceTimersByTime(499);+ expect(FakeSocket.all).toHaveLength(1);+ vi.advanceTimersByTime(1);+ expect(FakeSocket.all).toHaveLength(2);+ });++ it("stops retrying when the token is rejected", () => {+ const { client, statuses } = makeClient();+ client.start();+ FakeSocket.all[0]?.open();+ FakeSocket.all[0]?.drop(4401);+ vi.advanceTimersByTime(60_000);+ expect(FakeSocket.all).toHaveLength(1);+ expect(statuses.at(-1)).toBe("unauthorized");+ });++ it("reports whether a message could be sent", () => {+ const { client } = makeClient();+ client.start();+ expect(client.send({ type: "abort" })).toBe(false);+ FakeSocket.all[0]?.open();+ FakeSocket.all[0]?.receive({ type: "ready", agentState: "idle" });+ expect(client.send({ type: "abort" })).toBe(true);+ });+});++describe("tokenFromLocation", () => {+ it("reads the token from the fragment, stores it, and removes it from the address", () => {+ const storage = new Map<string, string>();+ const replace = vi.fn();+ const token = tokenFromLocation(+ { hash: "#token=abc", pathname: "/", search: "" },+ { getItem: (k) => storage.get(k) ?? null, setItem: (k, v) => storage.set(k, v) },+ replace,+ );+ expect(token).toBe("abc");+ expect(storage.get("gentle-dot-token")).toBe("abc");+ expect(replace).toHaveBeenCalledWith("/");+ const again = tokenFromLocation(+ { hash: "", pathname: "/", search: "" },+ { getItem: (k) => storage.get(k) ?? null, setItem: (k, v) => storage.set(k, v) },+ replace,+ );+ expect(again).toBe("abc");+ });+});diff --git a/packages/ui/test/components.test.tsx b/packages/ui/test/components.test.tsxnew file mode 100644index 0000000..6e75815--- /dev/null+++ b/packages/ui/test/components.test.tsx@@ -0,0 +1,177 @@+import type { ClientMessage } from "@gentle-dot/protocol";+import { fireEvent, render, screen } from "@testing-library/react";+import userEvent from "@testing-library/user-event";+import { describe, expect, it, vi } from "vitest";+import { AskCard } from "../src/components/AskCard.tsx";+import { ChatSurface } from "../src/components/ChatSurface.tsx";+import { Composer } from "../src/components/Composer.tsx";+import { MessageList } from "../src/components/MessageList.tsx";+import { type DotState, initialState } from "../src/store.ts";++function state(overrides: Partial<DotState> = {}): DotState {+ return { ...initialState, connection: "open", agentState: "idle", ...overrides };+}++describe("Composer", () => {+ it("sends on Enter and keeps a new line on Shift+Enter", async () => {+ const send = vi.fn<(message: ClientMessage) => void>();+ render(<Composer busy={false} disabled={false} send={send} />);+ const box = screen.getByRole("textbox", { name: "Message" });+ await userEvent.type(box, "first line{Shift>}{Enter}{/Shift}second{Enter}");+ expect(send).toHaveBeenCalledTimes(1);+ const sent = send.mock.calls[0]?.[0];+ expect(sent).toMatchObject({ type: "send", text: "first line\nsecond" });+ expect(sent && "requestId" in sent && sent.requestId).toBeTruthy();+ expect(box).toHaveValue("");+ });++ it("does not send blank text", async () => {+ const send = vi.fn();+ render(<Composer busy={false} disabled={false} send={send} />);+ await userEvent.type(screen.getByRole("textbox", { name: "Message" }), " {Enter}");+ expect(send).not.toHaveBeenCalled();+ });++ it("offers Stop while the assistant works", async () => {+ const send = vi.fn();+ render(<Composer busy disabled={false} send={send} />);+ await userEvent.click(screen.getByRole("button", { name: "Stop" }));+ expect(send).toHaveBeenCalledWith({ type: "abort" });+ });+});++describe("AskCard", () => {+ it("answers a select with the chosen option", async () => {+ const send = vi.fn();+ render(+ <AskCard+ ask={{ requestId: "q1", method: "select", title: "Pick a color", options: ["Red", "Blue"] }}+ send={send}+ />,+ );+ expect(screen.getByText("Pick a color")).toBeInTheDocument();+ await userEvent.click(screen.getByRole("button", { name: "Blue" }));+ expect(send).toHaveBeenCalledWith({ type: "ui_response", requestId: "q1", value: "Blue" });+ });++ it("answers a confirm with yes or no", async () => {+ const send = vi.fn();+ render(+ <AskCard+ ask={{ requestId: "q2", method: "confirm", title: "Proceed?", message: "It is safe" }}+ send={send}+ />,+ );+ expect(screen.getByText("It is safe")).toBeInTheDocument();+ await userEvent.click(screen.getByRole("button", { name: "No" }));+ expect(send).toHaveBeenCalledWith({ type: "ui_response", requestId: "q2", confirmed: false });+ });++ it("answers an input with typed text and can be dismissed", async () => {+ const send = vi.fn();+ render(+ <AskCard+ ask={{ requestId: "q3", method: "input", title: "Your name", placeholder: "Name" }}+ send={send}+ />,+ );+ await userEvent.type(screen.getByPlaceholderText("Name"), "Ada");+ await userEvent.click(screen.getByRole("button", { name: "Send answer" }));+ expect(send).toHaveBeenCalledWith({ type: "ui_response", requestId: "q3", value: "Ada" });+ await userEvent.click(screen.getByRole("button", { name: "Skip" }));+ expect(send).toHaveBeenLastCalledWith({ type: "ui_response", requestId: "q3", cancelled: true });+ });+});++describe("MessageList", () => {+ it("renders Markdown and summarizes activities", async () => {+ render(+ <MessageList+ messages={[+ { id: "u1", role: "user", text: "check it", streaming: false, activities: [] },+ {+ id: "m1",+ role: "assistant",+ text: "All **good**",+ streaming: false,+ activities: [+ { id: "a", kind: "read", title: "Reading a.md", status: "done" },+ { id: "b", kind: "read", title: "Reading b.md", status: "done" },+ { id: "c", kind: "run", title: "Running a command", status: "failed" },+ ],+ },+ ]}+ />,+ );+ expect(screen.getByText("good").tagName).toBe("STRONG");+ const summary = screen.getByRole("button", { name: /Read 2 files · Ran 1 command/ });+ await userEvent.click(summary);+ expect(screen.getByText("Reading b.md")).toBeInTheDocument();+ });+});++describe("ChatSurface", () => {+ it("shows the interruption prompt and continues", async () => {+ const send = vi.fn();+ render(<ChatSurface variant="web" state={state({ interrupted: true })} send={send} dismiss={vi.fn()} />);+ expect(screen.getByText("I was interrupted. Continue?")).toBeInTheDocument();+ await userEvent.click(screen.getByRole("button", { name: "Continue" }));+ expect(send).toHaveBeenCalledWith(+ expect.objectContaining({ type: "send", text: "Continue where you left off." }),+ );+ });++ it("starts a new conversation and opens an earlier one", async () => {+ const send = vi.fn();+ render(+ <ChatSurface+ variant="web"+ state={state({+ conversationId: "b.jsonl",+ conversations: [+ { id: "b.jsonl", title: "Current", updatedAt: "2026-10-08T10:00:00.000Z" },+ { id: "a.jsonl", title: "Trip plan", updatedAt: "2026-10-07T10:00:00.000Z" },+ ],+ })}+ send={send}+ dismiss={vi.fn()}+ />,+ );+ expect(screen.getByRole("heading", { name: "Current" })).toBeInTheDocument();+ await userEvent.click(screen.getByRole("button", { name: "New conversation" }));+ expect(send).toHaveBeenCalledWith({ type: "new_conversation" });+ await userEvent.click(screen.getByRole("button", { name: "Conversations" }));+ await userEvent.click(screen.getByRole("button", { name: /Trip plan/ }));+ expect(send).toHaveBeenCalledWith({ type: "open_conversation", conversationId: "a.jsonl" });+ });++ it("explains a lost connection and a rejected token", () => {+ const { rerender } = render(+ <ChatSurface variant="web" state={state({ connection: "closed" })} send={vi.fn()} dismiss={vi.fn()} />,+ );+ expect(screen.getByRole("status")).toHaveTextContent("Reconnecting");+ rerender(+ <ChatSurface+ variant="web"+ state={state({ connection: "unauthorized" })}+ send={vi.fn()}+ dismiss={vi.fn()}+ />,+ );+ expect(screen.getByRole("status")).toHaveTextContent("open the link the assistant printed");+ });++ it("shows notices that can be dismissed", () => {+ const dismiss = vi.fn();+ render(+ <ChatSurface+ variant="web"+ state={state({ notices: [{ id: 7, level: "error", message: "That did not work." }] })}+ send={vi.fn()}+ dismiss={dismiss}+ />,+ );+ fireEvent.click(screen.getByRole("button", { name: "Dismiss" }));+ expect(dismiss).toHaveBeenCalledWith(7);+ });+});diff --git a/packages/ui/test/dot.test.tsx b/packages/ui/test/dot.test.tsxnew file mode 100644index 0000000..0e397da--- /dev/null+++ b/packages/ui/test/dot.test.tsx@@ -0,0 +1,42 @@+import { fireEvent, render, screen } from "@testing-library/react";+import { describe, expect, it, vi } from "vitest";+import { DotSurface } from "../src/components/DotSurface.tsx";++function setup(agentState: Parameters<typeof DotSurface>[0]["agentState"] = "idle") {+ const toggle = vi.fn();+ const startDrag = vi.fn();+ render(<DotSurface agentState={agentState} connected toggle={toggle} startDrag={startDrag} />);+ return { toggle, startDrag, dot: screen.getByRole("button") };+}++describe("DotSurface", () => {+ it("opens the panel on click", () => {+ const { toggle, startDrag, dot } = setup();+ fireEvent.pointerDown(dot, { clientX: 10, clientY: 10, button: 0 });+ fireEvent.pointerUp(dot, { clientX: 11, clientY: 10, button: 0 });+ expect(toggle).toHaveBeenCalledTimes(1);+ expect(startDrag).not.toHaveBeenCalled();+ });++ it("drags instead of opening when the pointer moves", () => {+ const { toggle, startDrag, dot } = setup();+ fireEvent.pointerDown(dot, { clientX: 10, clientY: 10, button: 0 });+ fireEvent.pointerMove(dot, { clientX: 20, clientY: 18, button: 0 });+ fireEvent.pointerUp(dot, { clientX: 20, clientY: 18, button: 0 });+ expect(startDrag).toHaveBeenCalledTimes(1);+ expect(toggle).not.toHaveBeenCalled();+ });++ it("opens from the keyboard", () => {+ const { toggle, dot } = setup();+ fireEvent.keyDown(dot, { key: "Enter" });+ expect(toggle).toHaveBeenCalledTimes(1);+ });++ it("shows the state and a badge when the assistant needs the user", () => {+ const { dot } = setup("needs_you");+ expect(dot).toHaveAccessibleName("Gentle Dot: needs your answer");+ expect(dot).toHaveClass("dot-needs_you");+ expect(screen.getByText("!")).toBeInTheDocument();+ });+});diff --git a/packages/ui/test/setup.ts b/packages/ui/test/setup.tsindex f149f27..0ecbed3 100644--- a/packages/ui/test/setup.ts+++ b/packages/ui/test/setup.ts@@ -1 +1,5 @@import "@testing-library/jest-dom/vitest";+import { cleanup } from "@testing-library/react";+import { afterEach } from "vitest";++afterEach(() => cleanup());diff --git a/packages/ui/test/store.test.ts b/packages/ui/test/store.test.tsnew file mode 100644index 0000000..a64a53e--- /dev/null+++ b/packages/ui/test/store.test.ts@@ -0,0 +1,115 @@+import type { ServerMessage, ServerPayload } from "@gentle-dot/protocol";+import { describe, expect, it } from "vitest";+import { type DotState, initialState, reduce } from "../src/store.ts";++let seq = 0;+function apply(state: DotState, ...payloads: ServerPayload[]): DotState {+ return payloads.reduce(+ (s, p) => reduce(s, { type: "server", message: { ...p, seq: ++seq } as ServerMessage }),+ state,+ );+}++describe("reduce", () => {+ it("records ready, connection, and agent state", () => {+ let s = reduce(initialState, { type: "connection", status: "open" });+ s = apply(s, { type: "ready", agentState: "idle", conversationId: "a.jsonl", model: "Fake" });+ expect(s).toMatchObject({+ connection: "open",+ agentState: "idle",+ conversationId: "a.jsonl",+ model: "Fake",+ });+ s = apply(s, { type: "agent_state", state: "thinking" });+ expect(s.agentState).toBe("thinking");+ });++ it("streams an assistant message and replaces it with the final text", () => {+ const s = apply(+ initialState,+ { type: "user_message", messageId: "u1", text: "hi" },+ { type: "message_delta", messageId: "m2", delta: "Hel" },+ { type: "message_delta", messageId: "m2", delta: "lo" },+ );+ expect(s.messages.map((m) => [m.role, m.text, m.streaming])).toEqual([+ ["user", "hi", false],+ ["assistant", "Hello", true],+ ]);+ const done = apply(s, { type: "message_done", messageId: "m2", text: "Hello!" });+ expect(done.messages[1]).toMatchObject({ text: "Hello!", streaming: false });+ });++ it("attaches activities to their message and updates them in place", () => {+ const running = { id: "t1", kind: "read" as const, title: "Reading a.md", status: "running" as const };+ let s = apply(initialState, { type: "activity", messageId: "m1", activity: running });+ expect(s.messages[0]).toMatchObject({ role: "assistant", text: "", activities: [running] });+ s = apply(s, { type: "activity", messageId: "m1", activity: { ...running, status: "done" } });+ expect(s.messages[0]?.activities).toEqual([{ ...running, status: "done" }]);+ });++ it("adds and resolves asks", () => {+ const ask = { requestId: "q1", method: "confirm" as const, title: "Proceed?" };+ let s = apply(initialState, { type: "ask", ask }, { type: "ask", ask });+ expect(s.asks).toEqual([ask]);+ s = apply(s, { type: "ask_resolved", requestId: "q1" });+ expect(s.asks).toEqual([]);+ });++ it("replaces messages with history and clears the interruption", () => {+ let s = apply(+ initialState,+ { type: "user_message", messageId: "u1", text: "old" },+ { type: "interrupted" },+ );+ expect(s.interrupted).toBe(true);+ s = apply(s, {+ type: "history",+ conversationId: "b.jsonl",+ messages: [{ id: "h1", role: "user", text: "new", activities: [] }],+ });+ expect(s.messages.map((m) => m.text)).toEqual(["new"]);+ expect(s).toMatchObject({ conversationId: "b.jsonl", interrupted: false });+ });++ it("clears the interruption when a new user message arrives", () => {+ const s = apply(+ initialState,+ { type: "interrupted" },+ { type: "user_message", messageId: "u1", text: "go" },+ );+ expect(s.interrupted).toBe(false);+ });++ it("keeps conversations and the active id", () => {+ const s = apply(initialState, {+ type: "conversations",+ conversations: [{ id: "a.jsonl", title: "A", updatedAt: "2026-10-08T00:00:00.000Z" }],+ activeId: "a.jsonl",+ });+ expect(s.conversations).toHaveLength(1);+ expect(s.conversationId).toBe("a.jsonl");+ });++ it("queues toasts and errors, and dismisses them by id", () => {+ let s = apply(+ initialState,+ { type: "toast", level: "warning", message: "Careful" },+ { type: "error", code: "x", message: "Nope" },+ );+ expect(s.notices.map((n) => [n.level, n.message])).toEqual([+ ["warning", "Careful"],+ ["error", "Nope"],+ ]);+ s = reduce(s, { type: "dismiss", id: s.notices[0]?.id ?? -1 });+ expect(s.notices.map((n) => n.message)).toEqual(["Nope"]);+ });++ it("stops streaming when the connection drops", () => {+ const s = reduce(apply(initialState, { type: "agent_state", state: "thinking" }), {+ type: "connection",+ status: "closed",+ });+ expect(s.connection).toBe("closed");+ expect(s.messages.every((m) => !m.streaming)).toBe(true);+ });+});