diff --git a/web/src/features/chat/attention.tsx b/web/src/features/chat/attention.tsx new file mode 100644 index 0000000..7af8db4 --- /dev/null +++ b/web/src/features/chat/attention.tsx @@ -0,0 +1,188 @@ +import type { AttentionItem, SessionState } from "@protocol/types"; +import { useEffect, useMemo, useRef, useState } from "react"; +import { useTranslation } from "react-i18next"; + +import { Badge } from "@/components/ui/badge"; +import { Button } from "@/components/ui/button"; +import { Modal } from "@/components/ui/dialog"; +import { Progress } from "@/components/ui/progress"; +import { toast } from "@/components/ui/toast"; +import { cn } from "@/lib/utils"; +import { diffFilesFromPayload } from "./diff"; +import { DiffView } from "./diff-view"; + +export interface AttentionDialogProps { + session: SessionState; + onRespond: (item: AttentionItem, response: unknown) => void; + /** Fired when the request vanished because another client answered it. */ + onRemoteResolved: (requestId: string) => void; +} + +function diffResponse(result: "Accepted" | "Rejected", path?: string): string { + return JSON.stringify({ result, ...(path ? { path } : {}) }); +} + +/** + * Blocking extension attention request. + * + * One dialog per session: title/options/countdown, or the pre-execution diff + * review variant. A request resolved by another client disappears from + * `session.attention` (reducer) and we close immediately + toast. + */ +export function AttentionDialog({ session, onRespond, onRemoteResolved }: AttentionDialogProps) { + const { t } = useTranslation(); + const [current, setCurrent] = useState(null); + const [remaining, setRemaining] = useState(null); + const responded = useRef(false); + const dismissed = useRef(null); + const timedOut = useRef>(new Set()); + + useEffect(() => { + const next = session.attention[0] ?? null; + if (next && dismissed.current === next.requestId) return; + if (next) { + if (!current || current.requestId !== next.requestId) { + responded.current = false; + setCurrent(next); + } + return; + } + if (current) { + if (!responded.current) onRemoteResolved(current.requestId); + responded.current = false; + dismissed.current = null; + setCurrent(null); + } + }, [session.attention, current, onRemoteResolved]); + + useEffect(() => { + const timeoutSec = current?.timeoutSec; + if (!current || !timeoutSec) { + setRemaining(null); + return; + } + const item = current; + const deadline = item.receivedAt + timeoutSec * 1_000; + const tick = () => { + const left = Math.max(0, Math.ceil((deadline - Date.now()) / 1_000)); + setRemaining(left); + if (left <= 0 && !timedOut.current.has(item.requestId)) { + timedOut.current.add(item.requestId); + responded.current = true; + dismissed.current = item.requestId; + setCurrent(null); + toast.error(t("chat.attentionTimedOut")); + } + }; + tick(); + const timer = setInterval(tick, 500); + return () => clearInterval(timer); + }, [current, t]); + + const files = useMemo(() => diffFilesFromPayload(current?.payload), [current]); + const isDiff = current?.method === "diff" || files.length > 0; + + function respond(response: unknown, message: string, kind: "success" | "error" | "info" = "success") { + if (!current) return; + responded.current = true; + onRespond(current, response); + if (kind === "error") toast.error(message); + else if (kind === "info") toast.info(message); + else toast.success(message); + } + + const options = current?.options?.length + ? current.options + : current?.method === "confirm" + ? [ + { id: "confirm", label: t("chat.allowOnce") }, + { id: "deny", label: t("chat.deny") }, + ] + : [ + { id: "allow-once", label: t("chat.allowOnce") }, + { id: "always", label: t("chat.always") }, + { id: "deny", label: t("chat.deny") }, + ]; + + return ( + { + /* blocking: answer (or let it time out) before closing */ + }} + title={current?.title ?? t("chat.attentionTitle")} + > + {current ? ( +
+ {current.message ?

{current.message}

: null} + {isDiff ? ( + <> +
{t("chat.diffReview")}
+ {files.length ? ( + + respond( + diffResponse(decision === "accept" ? "Accepted" : "Rejected", path), + decision === "accept" + ? t("chat.acceptedAll", { n: files.length }) + : t("chat.rejected", { path: path ?? "" }), + decision === "accept" ? "success" : "error", + ) + } + /> + ) : ( +
{t("chat.noChanges")}
+ )} + + ) : ( +
+ {options.map((option, index) => ( + + ))} +
+ )} + {current.timeoutSec ? ( + <> + +
+ {t("chat.attentionTimeout")} + + {remaining ?? current.timeoutSec}s + +
+ {current.method} +
+ + ) : ( +
+
+ {current.method} +
+ )} +
+ ) : null} + + ); +} diff --git a/web/src/features/chat/blocks.tsx b/web/src/features/chat/blocks.tsx new file mode 100644 index 0000000..3101032 --- /dev/null +++ b/web/src/features/chat/blocks.tsx @@ -0,0 +1,334 @@ +import type { Batch, Block, Entry, TodoItem } from "@protocol/types"; +import { useState } from "react"; +import { useTranslation } from "react-i18next"; + +import { Icon } from "@/components/icons"; +import { RelativeTime } from "@/components/shared/relative-time"; +import { Badge } from "@/components/ui/badge"; +import { Progress } from "@/components/ui/progress"; +import { Spinner } from "@/components/ui/spinner"; +import { cn } from "@/lib/utils"; +import { fileDiff } from "./diff"; +import { DiffView } from "./diff-view"; +import { + formatClock, + formatDuration, + toolArgsText, + toolDiffSource, + toolOutputText, + toolSummary, +} from "./format"; + +export interface EntryBlockProps { + entry: Entry; + turnStart?: boolean; +} + +function MessageMeta({ entry }: { entry: Entry }) { + const { t } = useTranslation(); + const user = entry.role === "user"; + return ( +
+ + {user ? t("chat.you") : entry.role === "notice" ? t("chat.subReport") : "pi2"} + + {user ? ( + + ) : ( + {formatClock(entry.ts)} + )} +
+ ); +} + +function ThinkingBlock({ text }: { text: string }) { + const { t } = useTranslation(); + const [open, setOpen] = useState(false); + return ( + + ); +} + +function ToolBody({ block }: { block: Extract }) { + const { t } = useTranslation(); + const args = toolArgsText(block); + const output = toolOutputText(block); + const source = toolDiffSource(block); + const diff = source ? [fileDiff(source.path, source.before, source.after)] : []; + return ( +
+ {args ? ( +
+
{t("chat.details")}
+
{args}
+
+ ) : null} + {output ? ( +
+
{t("chat.output")}
+
{output}
+
+ ) : null} + {!args && !output ?
{t("chat.noOutput")}
: null} + {diff.length ? : null} +
+ ); +} + +export function ToolBlock({ block }: { block: Extract }) { + const [open, setOpen] = useState(false); + const running = block.state === "pending" || block.state === "running"; + const done = block.state === "done"; + const error = block.state === "error"; + return ( +
+ + {open ? : null} +
+ ); +} + +function TodoRow({ item }: { item: TodoItem }) { + const completed = item.status === "completed"; + const active = item.status === "in_progress"; + return ( +
+ + + {item.content} + {active && item.activeForm ? {item.activeForm} : null} + +
+ ); +} + +export interface TodoListProps { + items: TodoItem[]; + limit?: number; + idPrefix: string; +} + +export function TodoList({ items, limit = 5, idPrefix }: TodoListProps) { + const { t } = useTranslation(); + const [expanded, setExpanded] = useState(false); + const shown = expanded ? items : items.slice(0, limit); + return ( +
+ {shown.map((item, index) => ( + + ))} + {items.length > limit ? ( + + ) : null} +
+ ); +} + +export function TodoBlock({ items }: { items: TodoItem[] }) { + const { t } = useTranslation(); + const completed = items.filter((item) => item.status === "completed").length; + return ( +
+
+ + {`${t("chat.tabTodo")} · ${completed}/${items.length}`} +
+ {t("common.readonly")} +
+ + +
+ ); +} + +const BATCH_GLYPH: Record = { + ok: ["✓", "batch__ico--ok"], + failed: ["✗", "batch__ico--err"], + cancelled: ["⊘", "batch__ico--muted"], + running: ["◐", "batch__ico--warn"], + spawning: ["◐", "batch__ico--warn"], + queued: ["·", "batch__ico--muted"], +}; + +function batchSummary(batch: Batch) { + const items = batch.items ?? []; + if (batch.summary) return batch.summary; + const counts = { total: items.length, done: 0, ok: 0, failed: 0, cancelled: 0, running: 0 }; + for (const item of items) { + if (item.status === "ok") { + counts.ok += 1; + counts.done += 1; + } else if (item.status === "failed") { + counts.failed += 1; + counts.done += 1; + } else if (item.status === "cancelled") { + counts.cancelled += 1; + counts.done += 1; + } else { + counts.running += 1; + } + } + return counts; +} + +export interface BatchBlockProps { + batch: Batch; + onOpenSubagent?: (name: string) => void; + canOpen?: (name: string) => boolean; +} + +export function BatchBlock({ batch, onOpenSubagent, canOpen }: BatchBlockProps) { + const { t } = useTranslation(); + const summary = batchSummary(batch); + const items = batch.items ?? []; + return ( +
+
+ + {t("chat.batchDispatch", { done: summary.done, total: summary.total })} +
+ {summary.running ? {t("chat.batchRunning", { n: summary.running })} : null} + {summary.failed ? {t("chat.batchFailed", { n: summary.failed })} : null} +
+
+ {items.map((item, index) => { + const name = item.name ?? item.ref ?? String(index); + const target = Boolean(canOpen?.(name)); + const [glyph, cls] = BATCH_GLYPH[item.status] ?? ["·", "batch__ico--muted"]; + return ( +
{ + if (target) onOpenSubagent?.(name); + }} + onKeyDown={(event) => { + if (target && (event.key === "Enter" || event.key === " ")) { + event.preventDefault(); + onOpenSubagent?.(name); + } + }} + > + ├─ + {glyph} + {name} + {item.error ? {item.error} : null} +
+ ); + })} +
+
+ ); +} + +function ErrorBlock({ text }: { text: string }) { + const { t } = useTranslation(); + return ( +
+
+ + + {t("chat.error")} + +
+
{text}
+
+ ); +} + +export function EntryBlock({ entry, turnStart }: EntryBlockProps) { + const lastTextIndex = entry.blocks.reduce( + (last, block, index) => (block.type === "text" ? index : last), + -1, + ); + return ( +
+ + {entry.blocks.map((block, index) => { + if (block.type === "text") { + return ( +
+ {block.text} +
+ ); + } + if (block.type === "thinking") { + return ; + } + if (block.type === "tool") { + return ; + } + return ; + })} + {entry.images?.length ? ( +
+ {entry.images.map((image, index) => ( + + ))} +
+ ) : null} +
+ ); +} diff --git a/web/src/features/chat/commands.ts b/web/src/features/chat/commands.ts new file mode 100644 index 0000000..a40f7fd --- /dev/null +++ b/web/src/features/chat/commands.ts @@ -0,0 +1,128 @@ +import type { CommandRequest, ModelRef, ThinkingLevel } from "@protocol/types"; +import { api } from "@/lib/api"; + +export interface PromptImage { + mimeType: string; + data: string; +} + +export interface ChatCommand extends CommandRequest { + method: string; +} + +function requestId(): string | undefined { + try { + if (typeof crypto !== "undefined" && typeof crypto.randomUUID === "function") return crypto.randomUUID(); + } catch { + /* older browsers */ + } + return undefined; +} + +function command(method: string, sessionId: string | undefined, params?: Record): ChatCommand { + const clientRequestId = requestId(); + return { + method, + ...(sessionId ? { sessionId } : {}), + ...(params ? { params } : {}), + ...(clientRequestId ? { clientRequestId } : {}), + }; +} + +/** + * Command payload builders for `POST /api/v1/cmd`. + * + * Parameter names follow the daemon/plugin contract + * (`docs/protocol.md`, design `explore/web-server-round2-contract.md` §4). + */ +export const chatCommands = { + sendPrompt: (sessionId: string, text: string, images: PromptImage[] = []): ChatCommand => + command("prompt.send", sessionId, { + text, + mode: "queue", + ...(images.length ? { images } : {}), + }), + + abort: (sessionId: string): ChatCommand => command("prompt.abort", sessionId, {}), + + removeQueued: (sessionId: string, queueId: string): ChatCommand => command("queue.remove", sessionId, { queueId }), + + setQueueSteer: (sessionId: string, queueId: string, steer: boolean): ChatCommand => + command("queue.setSteer", sessionId, { queueId, steer }), + + setModel: (sessionId: string, model: ModelRef): ChatCommand => + command("session.setModel", sessionId, { provider: model.provider, id: model.id }), + + setThinking: (sessionId: string, level: ThinkingLevel): ChatCommand => + command("session.setThinking", sessionId, { level }), + + renameSession: (sessionId: string, name: string): ChatCommand => command("session.rename", sessionId, { name }), + + closeSession: (sessionId: string): ChatCommand => command("session.close", sessionId, { mode: "close" }), + + createSession: (workspaceId: string): ChatCommand => command("session.create", undefined, { workspaceId }), + + respondAttention: (sessionId: string, requestIdValue: string, response: unknown): ChatCommand => + command("attention.respond", sessionId, { requestId: requestIdValue, response }), + + dispatchSubagent: ( + sessionId: string, + input: { + task: string; + name?: string; + model?: ModelRef; + thinking?: ThinkingLevel; + wait?: boolean; + cancelSiblingsOnFail?: boolean; + }, + ): ChatCommand => + command("subagent.dispatch", sessionId, { + task: input.task, + ...(input.name ? { name: input.name } : {}), + ...(input.model ? { model: input.model } : {}), + ...(input.thinking ? { thinking: input.thinking } : {}), + ...(input.wait !== undefined ? { wait: input.wait } : {}), + ...(input.cancelSiblingsOnFail !== undefined + ? { cancelSiblingsOnFail: input.cancelSiblingsOnFail } + : {}), + }), + + steerSubagent: (sessionId: string, target: string, message: string): ChatCommand => + command("subagent.steer", sessionId, { target, message }), + + readSubagent: (sessionId: string, target: string): ChatCommand => + command("subagent.read", sessionId, { target }), + + stopTask: (sessionId: string, taskId: string): ChatCommand => command("task.stop", sessionId, { taskId }), + + taskOutput: (sessionId: string, taskId: string): ChatCommand => command("task.output", sessionId, { taskId }), +}; + +export type CommandResult = { accepted?: boolean; disposition?: string; [key: string]: unknown }; + +/** Execute one command; errors surface as `ApiError` with a stable code. */ +export async function runCommand(command: ChatCommand, signal?: AbortSignal): Promise { + return api.command(command, signal) as Promise; +} + +/** Response value for the diff-review attention variant (matches the plugin's JSON payload). */ +export function diffResponse(result: "Accepted" | "Rejected"): string { + return JSON.stringify({ result }); +} + +export function promptImage(file: File): Promise { + return new Promise((resolve, reject) => { + const reader = new FileReader(); + reader.onerror = () => reject(reader.error ?? new Error("cannot read file")); + reader.onload = () => { + const result = String(reader.result ?? ""); + const comma = result.indexOf(","); + if (comma < 0) { + reject(new Error("cannot read file")); + return; + } + resolve({ mimeType: file.type || "image/png", data: result.slice(comma + 1) }); + }; + reader.readAsDataURL(file); + }); +} diff --git a/web/src/features/chat/composer.tsx b/web/src/features/chat/composer.tsx new file mode 100644 index 0000000..3024afa --- /dev/null +++ b/web/src/features/chat/composer.tsx @@ -0,0 +1,356 @@ +import type { ModelRef, SessionState, ThinkingLevel } from "@protocol/types"; +import { useEffect, useLayoutEffect, useRef, useState } from "react"; +import { useTranslation } from "react-i18next"; + +import { Icon } from "@/components/icons"; +import { Button } from "@/components/ui/button"; +import { Chip } from "@/components/ui/chip"; +import { Modal } from "@/components/ui/dialog"; +import { toast } from "@/components/ui/toast"; +import { cn } from "@/lib/utils"; +import { promptImage, type PromptImage } from "./commands"; +import type { ModelGroup } from "./data"; +import { withCurrentModel } from "./data"; +import { THINKING_LEVELS } from "./format"; +import type { Attachment } from "./store"; + +export interface ComposerProps { + session: SessionState | null; + models: ModelGroup[]; + connected: boolean; + paired?: boolean; + sending?: { text: string } | null; + onSend: (text: string, images: PromptImage[]) => void; + onAbort: () => void; + onRemoveQueue: (id: string) => void; + onSetSteer: (id: string, steer: boolean) => void; + onSetModel: (model: ModelRef) => void; + onSetThinking: (level: ThinkingLevel) => void; + disabled?: boolean; + className?: string; +} + +function attachmentId(file: File): string { + return `${file.name}-${file.size}-${Date.now()}-${Math.random().toString(36).slice(2, 7)}`; +} + +/** Bottom composer: auto-growing textarea, queue chips, model/thinking, send/abort. */ +export function Composer({ + session, + models, + connected, + paired = true, + sending, + onSend, + onAbort, + onRemoveQueue, + onSetSteer, + onSetModel, + onSetThinking, + disabled = false, + className, +}: ComposerProps) { + const { t } = useTranslation(); + const [text, setText] = useState(""); + const [attachments, setAttachments] = useState([]); + const [attachOpen, setAttachOpen] = useState(false); + const [dragging, setDragging] = useState(false); + const textareaRef = useRef(null); + const fileRef = useRef(null); + + const enabled = Boolean(session) && connected && !disabled; + const busy = session ? session.status === "busy" || session.status === "compacting" : false; + const queue = session?.queue ?? []; + const model = session?.model ?? null; + const thinking = session?.thinking ?? "off"; + const groups = withCurrentModel(models, model); + const hint = !paired ? t("chat.unpairedHint") : !connected ? t("chat.offlineHint") : null; + + useLayoutEffect(() => { + const element = textareaRef.current; + if (!element) return; + element.style.height = "auto"; + const max = 5 * 24; + element.style.height = `${Math.min(element.scrollHeight, max)}px`; + element.style.overflowY = element.scrollHeight > max ? "auto" : "hidden"; + }, [text]); + + useEffect(() => { + if (!enabled) return; + textareaRef.current?.focus({ preventScroll: true }); + }, [enabled]); + + function submit() { + const trimmed = text.trim(); + if (!trimmed || !enabled) return; + const images = attachments.map(({ mimeType, data }) => ({ mimeType, data })); + setText(""); + setAttachments([]); + onSend(trimmed, images); + } + + async function addFiles(files: FileList | File[] | null) { + if (!files) return; + for (const file of Array.from(files)) { + if (!file.type.startsWith("image/")) continue; + try { + const image = await promptImage(file); + setAttachments((current) => [ + ...current, + { + id: attachmentId(file), + name: file.name, + mimeType: image.mimeType, + data: image.data, + preview: `data:${image.mimeType};base64,${image.data}`, + }, + ]); + toast(t("chat.attachmentAdded", { name: file.name })); + } catch { + toast.error(t("chat.attachmentFailed", { name: file.name })); + } + } + } + + return ( +
+ {queue.length || sending ? ( +
+ {sending ? ( + + + {t("chat.sending")} + {sending.text ? {sending.text} : null} + + ) : null} + {queue.map((item) => ( + + + {t("state.queued")} + + {item.text} + + + + + ))} +
+ ) : null} + +
+ {attachments.length ? ( +
+ {attachments.map((attachment) => ( + + + {attachment.name} + + + ))} +
+ ) : null} +