feat(web): workspaces, connect and status pages plus the full chat experience
- workspaces list + new-workspace flow (add -> ensure -> navigate), server context bar - connect: manual/pair-code redeem, QR scan with paste fallback, paired summary, disconnect - status: info/health/resources/models/devices/connection cards with 3s visible-only polling - chat: 3/2/1-column layout, session tree, virtualized stream, tool/thinking/todo/batch blocks, composer with queue chips and abort, subagents/todo/tasks panel, attention + diff review modals, history pagination merged with live entries - canonical reducer reused via @protocol alias (no duplicated types) - 63 vitest tests, typecheck + build green, zh/en parity at 411 keys
This commit is contained in:
1 parent
2e5d6d5006
commit
721661177c
61 files changed
+10931
-355
No files matched your search
@@ -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<AttentionItem | null>(null);
|
||||
const [remaining, setRemaining] = useState<number | null>(null);
|
||||
const responded = useRef(false);
|
||||
const dismissed = useRef<string | null>(null);
|
||||
const timedOut = useRef<Set<string>>(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 (
|
||||
<Modal
|
||||
open={Boolean(current)}
|
||||
onOpenChange={() => {
|
||||
/* blocking: answer (or let it time out) before closing */
|
||||
}}
|
||||
title={current?.title ?? t("chat.attentionTitle")}
|
||||
>
|
||||
{current ? (
|
||||
<div className="attn">
|
||||
{current.message ? <p className="attn__q">{current.message}</p> : null}
|
||||
{isDiff ? (
|
||||
<>
|
||||
<div className="muted">{t("chat.diffReview")}</div>
|
||||
{files.length ? (
|
||||
<DiffView
|
||||
files={files}
|
||||
onDecision={(decision, path) =>
|
||||
respond(
|
||||
diffResponse(decision === "accept" ? "Accepted" : "Rejected", path),
|
||||
decision === "accept"
|
||||
? t("chat.acceptedAll", { n: files.length })
|
||||
: t("chat.rejected", { path: path ?? "" }),
|
||||
decision === "accept" ? "success" : "error",
|
||||
)
|
||||
}
|
||||
/>
|
||||
) : (
|
||||
<div className="muted">{t("chat.noChanges")}</div>
|
||||
)}
|
||||
</>
|
||||
) : (
|
||||
<div className="attn__options">
|
||||
{options.map((option, index) => (
|
||||
<Button
|
||||
key={option.id}
|
||||
variant={index === 0 ? "primary" : option.id === "deny" ? "danger" : "ghost"}
|
||||
onClick={() => {
|
||||
const ok = option.id !== "deny";
|
||||
respond(
|
||||
option.id,
|
||||
option.id === "deny"
|
||||
? t("chat.denied")
|
||||
: option.id === "always"
|
||||
? t("chat.alwaysAllowed")
|
||||
: t("chat.allowedOnce"),
|
||||
ok ? "success" : "error",
|
||||
);
|
||||
}}
|
||||
>
|
||||
{option.label}
|
||||
</Button>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
{current.timeoutSec ? (
|
||||
<>
|
||||
<Progress
|
||||
value={remaining ?? current.timeoutSec}
|
||||
max={current.timeoutSec}
|
||||
tone="warn"
|
||||
/>
|
||||
<div className="row attn__meta">
|
||||
<span className="muted">{t("chat.attentionTimeout")}</span>
|
||||
<span className={cn("mono", remaining !== null && remaining <= 5 && "attn__countdown--urgent")}>
|
||||
{remaining ?? current.timeoutSec}s
|
||||
</span>
|
||||
<div className="spacer" />
|
||||
<Badge tone="warn">{current.method}</Badge>
|
||||
</div>
|
||||
</>
|
||||
) : (
|
||||
<div className="row attn__meta">
|
||||
<div className="spacer" />
|
||||
<Badge tone="warn">{current.method}</Badge>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
) : null}
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
@@ -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 (
|
||||
<div className="msg__meta">
|
||||
<span className={cn("who", user ? "who--user" : "who--agent")}>
|
||||
{user ? t("chat.you") : entry.role === "notice" ? t("chat.subReport") : "pi2"}
|
||||
</span>
|
||||
{user ? (
|
||||
<RelativeTime ts={entry.ts} className="muted msg__time" />
|
||||
) : (
|
||||
<span className="muted msg__time">{formatClock(entry.ts)}</span>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function ThinkingBlock({ text }: { text: string }) {
|
||||
const { t } = useTranslation();
|
||||
const [open, setOpen] = useState(false);
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
className={cn("thinking", open && "open")}
|
||||
aria-expanded={open}
|
||||
onClick={() => setOpen((value) => !value)}
|
||||
>
|
||||
<span className="thinking__tag">
|
||||
<Icon name="clock" />
|
||||
{t("chat.thinking")}
|
||||
</span>
|
||||
<span className="thinking__text">{text}</span>
|
||||
</button>
|
||||
);
|
||||
}
|
||||
|
||||
function ToolBody({ block }: { block: Extract<Block, { type: "tool" }> }) {
|
||||
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 (
|
||||
<div className="tool__body">
|
||||
{args ? (
|
||||
<div className="tool__section">
|
||||
<div className="tool__label muted">{t("chat.details")}</div>
|
||||
<pre className="mono tool__pre">{args}</pre>
|
||||
</div>
|
||||
) : null}
|
||||
{output ? (
|
||||
<div className="tool__section">
|
||||
<div className="tool__label muted">{t("chat.output")}</div>
|
||||
<pre className="mono tool__pre">{output}</pre>
|
||||
</div>
|
||||
) : null}
|
||||
{!args && !output ? <pre className="mono tool__pre muted">{t("chat.noOutput")}</pre> : null}
|
||||
{diff.length ? <DiffView files={diff} /> : null}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function ToolBlock({ block }: { block: Extract<Block, { type: "tool" }> }) {
|
||||
const [open, setOpen] = useState(false);
|
||||
const running = block.state === "pending" || block.state === "running";
|
||||
const done = block.state === "done";
|
||||
const error = block.state === "error";
|
||||
return (
|
||||
<div
|
||||
className={cn(
|
||||
"tool card",
|
||||
done && "tool--done",
|
||||
error && "tool--error",
|
||||
open && "open",
|
||||
)}
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
className="tool__head"
|
||||
aria-expanded={open}
|
||||
onClick={() => setOpen((value) => !value)}
|
||||
>
|
||||
<span className={cn("tool__ico", running && "tool__ico--running")}>
|
||||
{running ? <Spinner /> : <Icon name={error ? "alert" : done ? "check" : "dot"} />}
|
||||
</span>
|
||||
<span className="tool__name mono">{block.name}</span>
|
||||
<span className="tool__sum muted truncate">{toolSummary(block)}</span>
|
||||
{block.durationMs != null ? (
|
||||
<span className="tool__dur muted">· {formatDuration(block.durationMs)}</span>
|
||||
) : null}
|
||||
<span className="tool__caret">
|
||||
<Icon name="chevron-down" />
|
||||
</span>
|
||||
</button>
|
||||
{open ? <ToolBody block={block} /> : null}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function TodoRow({ item }: { item: TodoItem }) {
|
||||
const completed = item.status === "completed";
|
||||
const active = item.status === "in_progress";
|
||||
return (
|
||||
<div className={cn("todo__row", active && "is-active", completed && "is-done")}>
|
||||
<span
|
||||
className={cn(
|
||||
"todo__ico",
|
||||
completed && "todo__ico--done",
|
||||
active && "todo__ico--progress",
|
||||
!completed && !active && "todo__ico--pending",
|
||||
)}
|
||||
aria-hidden="true"
|
||||
>
|
||||
{completed ? "✓" : active ? "◐" : "○"}
|
||||
</span>
|
||||
<span className="todo__txt">
|
||||
<span className="todo__content">{item.content}</span>
|
||||
{active && item.activeForm ? <span className="todo__active">{item.activeForm}</span> : null}
|
||||
</span>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
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 (
|
||||
<div className="todo__list">
|
||||
{shown.map((item, index) => (
|
||||
<TodoRow key={`${idPrefix}-${index}`} item={item} />
|
||||
))}
|
||||
{items.length > limit ? (
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn--sm btn--ghost todo__more"
|
||||
onClick={() => setExpanded((value) => !value)}
|
||||
>
|
||||
{expanded ? t("chat.collapse") : t("chat.moreItems", { n: items.length - limit })}
|
||||
</button>
|
||||
) : null}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function TodoBlock({ items }: { items: TodoItem[] }) {
|
||||
const { t } = useTranslation();
|
||||
const completed = items.filter((item) => item.status === "completed").length;
|
||||
return (
|
||||
<div className="todo card">
|
||||
<div className="todo__head">
|
||||
<Icon name="todo" />
|
||||
<span>{`${t("chat.tabTodo")} · ${completed}/${items.length}`}</span>
|
||||
<div className="spacer" />
|
||||
<span className="muted todo__readonly">{t("common.readonly")}</span>
|
||||
</div>
|
||||
<Progress value={completed} max={items.length || 1} />
|
||||
<TodoList items={items} idPrefix="stream-todo" />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const BATCH_GLYPH: Record<string, [string, string]> = {
|
||||
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 (
|
||||
<div className="batch card">
|
||||
<div className="batch__head row">
|
||||
<Icon name="branch" />
|
||||
<span>{t("chat.batchDispatch", { done: summary.done, total: summary.total })}</span>
|
||||
<div className="spacer" />
|
||||
{summary.running ? <Badge tone="info">{t("chat.batchRunning", { n: summary.running })}</Badge> : null}
|
||||
{summary.failed ? <Badge tone="err">{t("chat.batchFailed", { n: summary.failed })}</Badge> : null}
|
||||
</div>
|
||||
<div className="batch__list">
|
||||
{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 (
|
||||
<div
|
||||
key={`${item.ref}-${index}`}
|
||||
className={cn("batch__row", target && "is-link")}
|
||||
role={target ? "button" : undefined}
|
||||
tabIndex={target ? 0 : undefined}
|
||||
title={target ? t("chat.viewSubagent", { name }) : undefined}
|
||||
onClick={() => {
|
||||
if (target) onOpenSubagent?.(name);
|
||||
}}
|
||||
onKeyDown={(event) => {
|
||||
if (target && (event.key === "Enter" || event.key === " ")) {
|
||||
event.preventDefault();
|
||||
onOpenSubagent?.(name);
|
||||
}
|
||||
}}
|
||||
>
|
||||
<span className="batch__tree muted">├─</span>
|
||||
<span className={cn("batch__ico", cls)}>{glyph}</span>
|
||||
<span className="batch__name truncate">{name}</span>
|
||||
{item.error ? <span className="muted truncate">{item.error}</span> : null}
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function ErrorBlock({ text }: { text: string }) {
|
||||
const { t } = useTranslation();
|
||||
return (
|
||||
<div className="msg__error">
|
||||
<div className="msg__error-meta">
|
||||
<span className="who who--err">
|
||||
<Icon name="alert" />
|
||||
{t("chat.error")}
|
||||
</span>
|
||||
</div>
|
||||
<div className="msg__text">{text}</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function EntryBlock({ entry, turnStart }: EntryBlockProps) {
|
||||
const lastTextIndex = entry.blocks.reduce(
|
||||
(last, block, index) => (block.type === "text" ? index : last),
|
||||
-1,
|
||||
);
|
||||
return (
|
||||
<article className={cn("msg", `msg--${entry.role}`, turnStart && "turn-start")}>
|
||||
<MessageMeta entry={entry} />
|
||||
{entry.blocks.map((block, index) => {
|
||||
if (block.type === "text") {
|
||||
return (
|
||||
<div
|
||||
key={`${entry.id}-t-${index}`}
|
||||
className={cn("msg__text", !entry.done && index === lastTextIndex && "streaming")}
|
||||
>
|
||||
{block.text}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
if (block.type === "thinking") {
|
||||
return <ThinkingBlock key={`${entry.id}-k-${index}`} text={block.text} />;
|
||||
}
|
||||
if (block.type === "tool") {
|
||||
return <ToolBlock key={`${entry.id}-x-${index}`} block={block} />;
|
||||
}
|
||||
return <ErrorBlock key={`${entry.id}-e-${index}`} text={block.text} />;
|
||||
})}
|
||||
{entry.images?.length ? (
|
||||
<div className="msg__images">
|
||||
{entry.images.map((image, index) => (
|
||||
<img
|
||||
key={`${entry.id}-img-${index}`}
|
||||
className="msg__img"
|
||||
src={`data:${image.mimeType};base64,${image.data}`}
|
||||
alt=""
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
) : null}
|
||||
</article>
|
||||
);
|
||||
}
|
||||
@@ -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<string, unknown>): 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<CommandResult> {
|
||||
return api.command(command, signal) as Promise<CommandResult>;
|
||||
}
|
||||
|
||||
/** 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<PromptImage> {
|
||||
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);
|
||||
});
|
||||
}
|
||||
@@ -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<Attachment[]>([]);
|
||||
const [attachOpen, setAttachOpen] = useState(false);
|
||||
const [dragging, setDragging] = useState(false);
|
||||
const textareaRef = useRef<HTMLTextAreaElement | null>(null);
|
||||
const fileRef = useRef<HTMLInputElement | null>(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 (
|
||||
<div className={cn("composer", className)}>
|
||||
{queue.length || sending ? (
|
||||
<div className="composer__queue">
|
||||
{sending ? (
|
||||
<Chip className="chip--queue chip--sending">
|
||||
<Icon name="clock" />
|
||||
<span>{t("chat.sending")}</span>
|
||||
{sending.text ? <span className="truncate">{sending.text}</span> : null}
|
||||
</Chip>
|
||||
) : null}
|
||||
{queue.map((item) => (
|
||||
<Chip key={item.id} className="chip--queue">
|
||||
<Icon name="clock" />
|
||||
<span>{t("state.queued")}</span>
|
||||
<span className="truncate" title={item.text}>
|
||||
{item.text}
|
||||
</span>
|
||||
<label className="q-steer-wrap">
|
||||
<input
|
||||
type="checkbox"
|
||||
className="q-steer"
|
||||
checked={item.steer}
|
||||
aria-label={t("chat.steer")}
|
||||
onChange={(event) => onSetSteer(item.id, event.target.checked)}
|
||||
/>
|
||||
<span>{t("chat.steer")}</span>
|
||||
</label>
|
||||
<button
|
||||
type="button"
|
||||
className="icon-btn"
|
||||
title={t("chat.removeQueued")}
|
||||
aria-label={t("chat.removeQueued")}
|
||||
onClick={() => onRemoveQueue(item.id)}
|
||||
>
|
||||
<Icon name="x" />
|
||||
</button>
|
||||
</Chip>
|
||||
))}
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
<div className={cn("composer__box", !enabled && "is-disabled")}>
|
||||
{attachments.length ? (
|
||||
<div className="composer__attachments">
|
||||
{attachments.map((attachment) => (
|
||||
<span key={attachment.id} className="composer__att">
|
||||
<img src={attachment.preview} alt="" className="composer__att-img" />
|
||||
<span className="truncate">{attachment.name}</span>
|
||||
<button
|
||||
type="button"
|
||||
className="icon-btn"
|
||||
aria-label={t("chat.removeAttachment")}
|
||||
title={t("chat.removeAttachment")}
|
||||
onClick={() =>
|
||||
setAttachments((current) =>
|
||||
current.filter((item) => item.id !== attachment.id),
|
||||
)
|
||||
}
|
||||
>
|
||||
<Icon name="x" />
|
||||
</button>
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
) : null}
|
||||
<textarea
|
||||
ref={textareaRef}
|
||||
className="textarea composer__ta"
|
||||
rows={1}
|
||||
value={text}
|
||||
placeholder={t("chat.composerPlaceholder")}
|
||||
aria-label={t("chat.composerAria")}
|
||||
disabled={!enabled}
|
||||
onChange={(event) => setText(event.target.value)}
|
||||
onKeyDown={(event) => {
|
||||
if (event.key !== "Enter" || event.shiftKey || event.nativeEvent.isComposing) return;
|
||||
event.preventDefault();
|
||||
submit();
|
||||
}}
|
||||
/>
|
||||
<div className="composer__bar">
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn--icon btn--ghost"
|
||||
title={t("chat.addAttachment")}
|
||||
aria-label={t("chat.addAttachment")}
|
||||
disabled={!enabled}
|
||||
onClick={() => setAttachOpen(true)}
|
||||
>
|
||||
<Icon name="plus" />
|
||||
</button>
|
||||
<select
|
||||
className="select composer__sel"
|
||||
aria-label={t("chat.model")}
|
||||
value={model ? `${model.provider}/${model.id}` : ""}
|
||||
disabled={!enabled || !groups.length}
|
||||
onChange={(event) => {
|
||||
const slash = event.target.value.indexOf("/");
|
||||
if (slash <= 0) return;
|
||||
onSetModel({
|
||||
provider: event.target.value.slice(0, slash),
|
||||
id: event.target.value.slice(slash + 1),
|
||||
});
|
||||
}}
|
||||
>
|
||||
{groups.length ? null : (
|
||||
<option value="">{model ? `${model.provider}/${model.id}` : t("chat.model")}</option>
|
||||
)}
|
||||
{groups.map((group) => (
|
||||
<optgroup key={group.provider} label={group.provider}>
|
||||
{group.models.map((item) => (
|
||||
<option key={`${group.provider}/${item.id}`} value={`${group.provider}/${item.id}`}>
|
||||
{item.id}
|
||||
</option>
|
||||
))}
|
||||
</optgroup>
|
||||
))}
|
||||
</select>
|
||||
<select
|
||||
className="select composer__sel"
|
||||
aria-label={t("chat.thinkingAria")}
|
||||
value={thinking}
|
||||
disabled={!enabled}
|
||||
onChange={(event) => onSetThinking(event.target.value as ThinkingLevel)}
|
||||
>
|
||||
{THINKING_LEVELS.map((level) => (
|
||||
<option key={level} value={level}>
|
||||
{level}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
<div className="spacer" />
|
||||
{busy ? (
|
||||
<Button
|
||||
variant="danger"
|
||||
className="composer__send"
|
||||
title={t("chat.abortTitle")}
|
||||
disabled={!connected}
|
||||
onClick={onAbort}
|
||||
>
|
||||
<Icon name="stop" />
|
||||
{t("chat.abort")}
|
||||
</Button>
|
||||
) : (
|
||||
<Button
|
||||
variant="primary"
|
||||
className="composer__send"
|
||||
title={t("chat.sendTitle")}
|
||||
disabled={!enabled || !text.trim()}
|
||||
onClick={submit}
|
||||
>
|
||||
<Icon name="send" />
|
||||
{t("chat.send")}
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
{hint ? (
|
||||
<div className="composer__hint" role="status">
|
||||
<Icon name="alert" />
|
||||
{hint}
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
<Modal
|
||||
open={attachOpen}
|
||||
onOpenChange={setAttachOpen}
|
||||
title={t("chat.attachTitle")}
|
||||
footer={
|
||||
<Button variant="primary" onClick={() => setAttachOpen(false)}>
|
||||
{t("common.close")}
|
||||
</Button>
|
||||
}
|
||||
>
|
||||
<div className="stack">
|
||||
<div
|
||||
className={cn("drop-zone", dragging && "dragover")}
|
||||
role="button"
|
||||
tabIndex={0}
|
||||
onClick={() => fileRef.current?.click()}
|
||||
onKeyDown={(event) => {
|
||||
if (event.key === "Enter" || event.key === " ") {
|
||||
event.preventDefault();
|
||||
fileRef.current?.click();
|
||||
}
|
||||
}}
|
||||
onDragOver={(event) => {
|
||||
event.preventDefault();
|
||||
setDragging(true);
|
||||
}}
|
||||
onDragLeave={() => setDragging(false)}
|
||||
onDrop={(event) => {
|
||||
event.preventDefault();
|
||||
setDragging(false);
|
||||
void addFiles(event.dataTransfer.files);
|
||||
}}
|
||||
>
|
||||
<Icon name="plus" />
|
||||
<div>{t("chat.dropHint")}</div>
|
||||
<div className="muted">{t("chat.dropNote")}</div>
|
||||
</div>
|
||||
<input
|
||||
ref={fileRef}
|
||||
type="file"
|
||||
accept="image/*"
|
||||
multiple
|
||||
hidden
|
||||
onChange={(event) => {
|
||||
void addFiles(event.target.files);
|
||||
event.target.value = "";
|
||||
}}
|
||||
/>
|
||||
{attachments.length ? (
|
||||
<div className="att-list">
|
||||
{attachments.map((attachment) => (
|
||||
<div className="att-file" key={attachment.id}>
|
||||
<img src={attachment.preview} alt="" className="att-thumb" />
|
||||
<span className="grow truncate">{attachment.name}</span>
|
||||
<button
|
||||
type="button"
|
||||
className="icon-btn"
|
||||
title={t("chat.removeAttachment")}
|
||||
aria-label={t("chat.removeAttachment")}
|
||||
onClick={() =>
|
||||
setAttachments((current) =>
|
||||
current.filter((item) => item.id !== attachment.id),
|
||||
)
|
||||
}
|
||||
>
|
||||
<Icon name="x" />
|
||||
</button>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
) : null}
|
||||
<div className="muted composer__note">{t("chat.attachNote")}</div>
|
||||
</div>
|
||||
</Modal>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,251 @@
|
||||
import type { ModelRef, SessionEvent, SessionState, WorkspaceInfo } from "@protocol/types";
|
||||
import { useQuery } from "@tanstack/react-query";
|
||||
import { useEffect, useMemo, useRef } from "react";
|
||||
|
||||
import { api, apiRequest, getDeviceToken } from "@/lib/api";
|
||||
import { projectEntries, snapshotEntries } from "@/lib/entry-projection";
|
||||
import { defaultWsUrl, PiWsClient, type WsConnectionState } from "@/lib/ws";
|
||||
import { useConnectionStore } from "@/stores/connection";
|
||||
import { useSessionsStore } from "@/stores/sessions";
|
||||
import { useWorkspacesStore } from "@/stores/workspaces";
|
||||
import {
|
||||
applySessionEvent,
|
||||
emptySessionState,
|
||||
normalizeSessionSummary,
|
||||
normalizeSessionsPayload,
|
||||
normalizeSnapshotState,
|
||||
} from "./session-state";
|
||||
import { useChatStore } from "./store";
|
||||
|
||||
export const EMPTY_SESSIONS: SessionState[] = [];
|
||||
|
||||
export interface ModelChoice {
|
||||
id: string;
|
||||
contextWindow?: number;
|
||||
reasoning?: boolean;
|
||||
}
|
||||
|
||||
export interface ModelGroup {
|
||||
provider: string;
|
||||
models: ModelChoice[];
|
||||
}
|
||||
|
||||
function rec(value: unknown): Record<string, unknown> | undefined {
|
||||
return value && typeof value === "object" && !Array.isArray(value) ? (value as Record<string, unknown>) : undefined;
|
||||
}
|
||||
|
||||
function str(value: unknown): string | undefined {
|
||||
return typeof value === "string" ? value : undefined;
|
||||
}
|
||||
|
||||
function num(value: unknown): number | undefined {
|
||||
return typeof value === "number" && Number.isFinite(value) ? value : undefined;
|
||||
}
|
||||
|
||||
/** Accepts the several shapes `workspace.query{kind:"models"}` has used. */
|
||||
export function normalizeModels(raw: unknown): ModelGroup[] {
|
||||
const record = rec(raw);
|
||||
const list = Array.isArray(raw)
|
||||
? raw
|
||||
: Array.isArray(record?.providers)
|
||||
? record.providers
|
||||
: Array.isArray(record?.models)
|
||||
? record.models
|
||||
: Array.isArray(record?.groups)
|
||||
? record.groups
|
||||
: [];
|
||||
|
||||
const groups = new Map<string, ModelChoice[]>();
|
||||
const add = (provider: string, model: unknown) => {
|
||||
const item = rec(model);
|
||||
const id = str(item?.id ?? item?.model ?? item?.modelId) ?? str(model);
|
||||
if (!id) return;
|
||||
const choices = groups.get(provider) ?? [];
|
||||
if (!choices.some((choice) => choice.id === id)) {
|
||||
choices.push({
|
||||
id,
|
||||
...(num(item?.contextWindow) !== undefined ? { contextWindow: num(item?.contextWindow) } : {}),
|
||||
...(item?.reasoning === true ? { reasoning: true } : {}),
|
||||
});
|
||||
}
|
||||
groups.set(provider, choices);
|
||||
};
|
||||
|
||||
for (const entry of list) {
|
||||
const item = rec(entry);
|
||||
if (!item) {
|
||||
if (typeof entry === "string") add("pi", entry);
|
||||
continue;
|
||||
}
|
||||
const provider = str(item.provider ?? item.name ?? item.id) ?? "pi";
|
||||
const models = Array.isArray(item.models) ? item.models : [];
|
||||
if (models.length) {
|
||||
for (const model of models) add(provider, model);
|
||||
} else if (str(item.id ?? item.model ?? item.modelId)) {
|
||||
// Flat list: `{provider, id, contextWindow}`.
|
||||
add(str(item.provider) ?? "pi", item);
|
||||
}
|
||||
}
|
||||
|
||||
return [...groups.entries()]
|
||||
.filter(([, models]) => models.length > 0)
|
||||
.map(([provider, models]) => ({
|
||||
provider,
|
||||
models: models.sort((a, b) => a.id.localeCompare(b.id)),
|
||||
}))
|
||||
.sort((a, b) => a.provider.localeCompare(b.provider));
|
||||
}
|
||||
|
||||
/** Ensure the active session's model is selectable even when the list is stale. */
|
||||
export function withCurrentModel(groups: ModelGroup[], model: ModelRef | null): ModelGroup[] {
|
||||
if (!model) return groups;
|
||||
if (groups.some((group) => group.provider === model.provider && group.models.some((item) => item.id === model.id))) {
|
||||
return groups;
|
||||
}
|
||||
const next = groups.map((group) => ({ ...group, models: [...group.models] }));
|
||||
const existing = next.find((group) => group.provider === model.provider);
|
||||
if (existing) existing.models.unshift({ id: model.id });
|
||||
else next.unshift({ provider: model.provider, models: [{ id: model.id }] });
|
||||
return next;
|
||||
}
|
||||
|
||||
/** Workspaces for the chat sidebar; refreshes the shared store. */
|
||||
export function useChatWorkspaces(enabled: boolean): { workspaces: WorkspaceInfo[]; loading: boolean; error: unknown } {
|
||||
const setWorkspaces = useWorkspacesStore((state) => state.setWorkspaces);
|
||||
const query = useQuery({
|
||||
queryKey: ["chat-workspaces"],
|
||||
queryFn: ({ signal }) => api.workspaces(signal),
|
||||
enabled,
|
||||
staleTime: 30_000,
|
||||
retry: 1,
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
if (query.data) setWorkspaces(query.data);
|
||||
}, [query.data, setWorkspaces]);
|
||||
|
||||
const workspaces = useWorkspacesStore((state) => state.items);
|
||||
return { workspaces, loading: query.isLoading, error: query.error };
|
||||
}
|
||||
|
||||
/** Sessions of one workspace, merged into the shared store (live state wins). */
|
||||
export function useChatSessions(workspaceId: string | undefined, enabled: boolean): SessionState[] {
|
||||
const query = useQuery({
|
||||
queryKey: ["chat-sessions", workspaceId],
|
||||
queryFn: ({ signal }) =>
|
||||
apiRequest<unknown>(`/api/v1/workspaces/${encodeURIComponent(workspaceId ?? "")}/sessions`, { signal }),
|
||||
enabled: enabled && Boolean(workspaceId),
|
||||
staleTime: 5_000,
|
||||
refetchInterval: 15_000,
|
||||
retry: 1,
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
if (!workspaceId || !query.data) return;
|
||||
const current = useSessionsStore.getState();
|
||||
const existing = current.byWorkspace[workspaceId] ?? [];
|
||||
const next = normalizeSessionsPayload(query.data, workspaceId, existing);
|
||||
current.setSessions(workspaceId, next);
|
||||
}, [workspaceId, query.data]);
|
||||
|
||||
return useSessionsStore((state) => (workspaceId ? (state.byWorkspace[workspaceId] ?? EMPTY_SESSIONS) : EMPTY_SESSIONS));
|
||||
}
|
||||
|
||||
/** Model list for the composer and dispatch modal. */
|
||||
export function useChatModels(workspaceId: string | undefined, enabled: boolean): ModelGroup[] {
|
||||
const query = useQuery({
|
||||
queryKey: ["chat-models", workspaceId],
|
||||
queryFn: ({ signal }) =>
|
||||
apiRequest<unknown>(`/api/v1/models?workspaceId=${encodeURIComponent(workspaceId ?? "")}`, { signal }),
|
||||
enabled: enabled && Boolean(workspaceId),
|
||||
staleTime: 60_000,
|
||||
retry: 1,
|
||||
});
|
||||
return useMemo(() => normalizeModels(query.data), [query.data]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Subscribe to the workspace's sessions and reduce `snapshot` / `event` frames
|
||||
* into the shared sessions store. The canonical reducer is imported from
|
||||
* `@protocol/reducer`; nothing state-related is reimplemented here.
|
||||
*/
|
||||
export function useChatSocket(workspaceId: string | undefined, sessionIds: string[], enabled: boolean): void {
|
||||
const clientRef = useRef<PiWsClient | null>(null);
|
||||
const setWsState = useConnectionStore((state) => state.setWsState);
|
||||
const idsKey = sessionIds.join("|");
|
||||
|
||||
useEffect(() => {
|
||||
if (!workspaceId || !enabled) return;
|
||||
const client = new PiWsClient({
|
||||
url: defaultWsUrl(),
|
||||
token: getDeviceToken(),
|
||||
handlers: {
|
||||
onState: (state: WsConnectionState) => {
|
||||
setWsState(state);
|
||||
},
|
||||
onSnapshot: (message) => {
|
||||
const state = normalizeSnapshotState(message.sessionId, workspaceId, message.payload);
|
||||
if (!state.entries.length) {
|
||||
const raw = snapshotEntries(message.payload);
|
||||
if (raw.length) state.entries = projectEntries(raw);
|
||||
}
|
||||
const store = useSessionsStore.getState();
|
||||
store.upsertSession(state);
|
||||
},
|
||||
onEvent: (message) => {
|
||||
const payload = rec(message.payload);
|
||||
const event = rec(payload?.event) ?? payload;
|
||||
if (!event || typeof event.type !== "string") return;
|
||||
const sessionId = message.sessionId;
|
||||
const store = useSessionsStore.getState();
|
||||
const current = store.getSession(sessionId) ?? emptySessionState({ sessionId, workspaceId });
|
||||
const next = applySessionEvent(current, event as unknown as SessionEvent);
|
||||
store.upsertSession(next);
|
||||
},
|
||||
onResyncRequired: (frame) => {
|
||||
const sessionId = str(frame.sessionId);
|
||||
if (!sessionId) return;
|
||||
useChatStore.getState().bumpResync(sessionId);
|
||||
// Drop the seq cache and ask for a fresh snapshot; the history
|
||||
// hook refetches the REST page for the same session.
|
||||
client.unsubscribe(sessionId);
|
||||
client.subscribe(sessionId);
|
||||
},
|
||||
onError: () => {
|
||||
// Reconnect/backoff state is surfaced through `onState`.
|
||||
},
|
||||
},
|
||||
});
|
||||
clientRef.current = client;
|
||||
client.connect();
|
||||
return () => {
|
||||
clientRef.current = null;
|
||||
client.close();
|
||||
};
|
||||
}, [workspaceId, enabled, setWsState]);
|
||||
|
||||
useEffect(() => {
|
||||
const client = clientRef.current;
|
||||
if (!client) return;
|
||||
const ids = idsKey ? idsKey.split("|").filter(Boolean) : [];
|
||||
if (ids.length) client.subscribe(ids);
|
||||
}, [idsKey, workspaceId]);
|
||||
}
|
||||
|
||||
/** The selected session, falling back to the first session of the workspace. */
|
||||
export function useActiveSession(
|
||||
sessionId: string | null | undefined,
|
||||
sessions: SessionState[],
|
||||
): SessionState | undefined {
|
||||
return useMemo(() => {
|
||||
if (sessionId) {
|
||||
const match = sessions.find((session) => session.sessionId === sessionId);
|
||||
if (match) return match;
|
||||
}
|
||||
return sessions[0];
|
||||
}, [sessions, sessionId]);
|
||||
}
|
||||
|
||||
export function mergeSessionSummaries(existing: SessionState | undefined, raw: unknown, workspaceId: string): SessionState {
|
||||
return normalizeSessionSummary(raw, workspaceId, existing);
|
||||
}
|
||||
@@ -0,0 +1,119 @@
|
||||
import { useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
import { Icon } from "@/components/icons";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { cn } from "@/lib/utils";
|
||||
import type { DiffFile } from "./diff";
|
||||
|
||||
export interface DiffViewProps {
|
||||
files: DiffFile[];
|
||||
/** When provided, render per-file + accept-all/reject-all actions. */
|
||||
onDecision?: (decision: "accept" | "reject", path?: string) => void;
|
||||
className?: string;
|
||||
}
|
||||
|
||||
/** Unified diff accordion (tool cards + pre-execution attention review). */
|
||||
export function DiffView({ files, onDecision, className }: DiffViewProps) {
|
||||
const { t } = useTranslation();
|
||||
const [open, setOpen] = useState<Record<string, boolean>>(() => {
|
||||
const initial: Record<string, boolean> = {};
|
||||
files.forEach((file, index) => {
|
||||
initial[file.path] = index === 0;
|
||||
});
|
||||
return initial;
|
||||
});
|
||||
|
||||
if (!files.length) return null;
|
||||
|
||||
return (
|
||||
<div className={cn("diff", className)}>
|
||||
{files.map((file) => {
|
||||
const expanded = open[file.path] ?? false;
|
||||
return (
|
||||
<div key={file.path} className={cn("diff__file", expanded && "open")}>
|
||||
<button
|
||||
type="button"
|
||||
className="diff__head"
|
||||
aria-expanded={expanded}
|
||||
onClick={() => setOpen((current) => ({ ...current, [file.path]: !expanded }))}
|
||||
>
|
||||
<span className="diff__caret">
|
||||
<Icon name="chevron-right" />
|
||||
</span>
|
||||
<Icon name="file" />
|
||||
<span className="truncate grow mono">{file.path}</span>
|
||||
<span className="diff__stat">
|
||||
{`+${file.add} −${file.del}`}
|
||||
</span>
|
||||
</button>
|
||||
{expanded ? (
|
||||
<div className="diff__body">
|
||||
{file.hunks.length ? (
|
||||
file.hunks.map((hunk, hunkIndex) => (
|
||||
<div className="diff__hunk" key={`${file.path}-${hunkIndex}`}>
|
||||
{hunk.header ? <div className="diff__hunkhead">{hunk.header}</div> : null}
|
||||
{hunk.lines.map((line, lineIndex) => {
|
||||
const kind = line.startsWith("+")
|
||||
? "add"
|
||||
: line.startsWith("-")
|
||||
? "del"
|
||||
: "ctx";
|
||||
return (
|
||||
<span
|
||||
key={`${hunkIndex}-${lineIndex}`}
|
||||
className={cn(
|
||||
"diff__line",
|
||||
kind === "add" && "diff__line--add",
|
||||
kind === "del" && "diff__line--del",
|
||||
)}
|
||||
>
|
||||
{line}
|
||||
</span>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
))
|
||||
) : (
|
||||
<div className="diff__empty muted">{t("chat.noChanges")}</div>
|
||||
)}
|
||||
{onDecision ? (
|
||||
<div className="diff__foot">
|
||||
<span className="muted grow">
|
||||
{t("chat.source", { name: file.source ?? t("chat.parentSession") })}
|
||||
</span>
|
||||
<Button
|
||||
size="sm"
|
||||
variant="primary"
|
||||
onClick={() => onDecision("accept", file.path)}
|
||||
>
|
||||
{t("chat.accept")}
|
||||
</Button>
|
||||
<Button
|
||||
size="sm"
|
||||
variant="danger"
|
||||
onClick={() => onDecision("reject", file.path)}
|
||||
>
|
||||
{t("chat.reject")}
|
||||
</Button>
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
{onDecision ? (
|
||||
<div className="diff__foot diff__foot--all">
|
||||
<span className="muted grow">{t("chat.diffReview")}</span>
|
||||
<Button size="sm" variant="ghost" onClick={() => onDecision("reject")}>
|
||||
{t("chat.rejectAll")}
|
||||
</Button>
|
||||
<Button size="sm" variant="primary" onClick={() => onDecision("accept")}>
|
||||
{t("chat.acceptAll")}
|
||||
</Button>
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,202 @@
|
||||
/** Unified-diff helpers shared by tool cards and the attention diff review. */
|
||||
|
||||
export interface DiffHunk {
|
||||
header: string;
|
||||
/** Lines prefixed with `+`, `-` or a space. */
|
||||
lines: string[];
|
||||
}
|
||||
|
||||
export interface DiffFile {
|
||||
path: string;
|
||||
hunks: DiffHunk[];
|
||||
add: number;
|
||||
del: number;
|
||||
source?: string;
|
||||
}
|
||||
|
||||
interface Op {
|
||||
type: "ctx" | "add" | "del";
|
||||
line: string;
|
||||
}
|
||||
|
||||
const MAX_LCS_LINES = 900;
|
||||
|
||||
function splitLines(text: string): string[] {
|
||||
if (!text) return [];
|
||||
// Keep a trailing newline visible in the diff without producing a bogus
|
||||
// empty trailing line for files that do not have one.
|
||||
const lines = text.replace(/\r\n?/g, "\n").split("\n");
|
||||
if (lines.length && lines[lines.length - 1] === "") lines.pop();
|
||||
return lines;
|
||||
}
|
||||
|
||||
function naiveOps(before: string[], after: string[]): Op[] {
|
||||
return [
|
||||
...before.map<Op>((line) => ({ type: "del", line })),
|
||||
...after.map<Op>((line) => ({ type: "add", line })),
|
||||
];
|
||||
}
|
||||
|
||||
/** Line-level LCS diff, with a size guard that degrades to del-all/add-all. */
|
||||
export function diffOps(before: string[], after: string[]): Op[] {
|
||||
const n = before.length;
|
||||
const m = after.length;
|
||||
if (n === 0 && m === 0) return [];
|
||||
if (n * m > MAX_LCS_LINES * MAX_LCS_LINES) return naiveOps(before, after);
|
||||
|
||||
const width = m + 1;
|
||||
const table = new Uint32Array((n + 1) * width);
|
||||
for (let i = n - 1; i >= 0; i -= 1) {
|
||||
for (let j = m - 1; j >= 0; j -= 1) {
|
||||
table[i * width + j] =
|
||||
before[i] === after[j]
|
||||
? (table[(i + 1) * width + j + 1] ?? 0) + 1
|
||||
: Math.max(table[(i + 1) * width + j] ?? 0, table[i * width + j + 1] ?? 0);
|
||||
}
|
||||
}
|
||||
|
||||
const ops: Op[] = [];
|
||||
let i = 0;
|
||||
let j = 0;
|
||||
while (i < n && j < m) {
|
||||
if (before[i] === after[j]) {
|
||||
ops.push({ type: "ctx", line: before[i] ?? "" });
|
||||
i += 1;
|
||||
j += 1;
|
||||
} else if ((table[(i + 1) * width + j] ?? 0) >= (table[i * width + j + 1] ?? 0)) {
|
||||
ops.push({ type: "del", line: before[i] ?? "" });
|
||||
i += 1;
|
||||
} else {
|
||||
ops.push({ type: "add", line: after[j] ?? "" });
|
||||
j += 1;
|
||||
}
|
||||
}
|
||||
while (i < n) {
|
||||
ops.push({ type: "del", line: before[i] ?? "" });
|
||||
i += 1;
|
||||
}
|
||||
while (j < m) {
|
||||
ops.push({ type: "add", line: after[j] ?? "" });
|
||||
j += 1;
|
||||
}
|
||||
return ops;
|
||||
}
|
||||
|
||||
interface PositionedOp extends Op {
|
||||
oldLine: number;
|
||||
newLine: number;
|
||||
}
|
||||
|
||||
/** Group a flat op list into `@@` hunks with `context` unchanged lines. */
|
||||
export function toHunks(ops: Op[], context = 3): DiffHunk[] {
|
||||
if (!ops.some((op) => op.type !== "ctx")) return [];
|
||||
|
||||
const positioned: PositionedOp[] = [];
|
||||
let oldLine = 0;
|
||||
let newLine = 0;
|
||||
for (const op of ops) {
|
||||
positioned.push({ ...op, oldLine, newLine });
|
||||
if (op.type !== "add") oldLine += 1;
|
||||
if (op.type !== "del") newLine += 1;
|
||||
}
|
||||
|
||||
const changed = positioned
|
||||
.map((op, index) => (op.type === "ctx" ? -1 : index))
|
||||
.filter((index) => index >= 0);
|
||||
if (!changed.length) return [];
|
||||
|
||||
const groups: { start: number; end: number }[] = [];
|
||||
for (const index of changed) {
|
||||
const start = Math.max(0, index - context);
|
||||
const end = Math.min(positioned.length - 1, index + context);
|
||||
const last = groups[groups.length - 1];
|
||||
if (last && start <= last.end + 1) last.end = Math.max(last.end, end);
|
||||
else groups.push({ start, end });
|
||||
}
|
||||
|
||||
return groups.map(({ start, end }) => {
|
||||
const slice = positioned.slice(start, end + 1);
|
||||
const first = slice[0];
|
||||
const oldStart = (first?.oldLine ?? 0) + 1;
|
||||
const newStart = (first?.newLine ?? 0) + 1;
|
||||
const oldCount = slice.filter((op) => op.type !== "add").length;
|
||||
const newCount = slice.filter((op) => op.type !== "del").length;
|
||||
return {
|
||||
header: `@@ -${oldStart},${oldCount} +${newStart},${newCount} @@`,
|
||||
lines: slice.map((op) => `${op.type === "add" ? "+" : op.type === "del" ? "-" : " "}${op.line}`),
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
export function unifiedDiff(before: string, after: string, context = 3): DiffHunk[] {
|
||||
return toHunks(diffOps(splitLines(before), splitLines(after)), context);
|
||||
}
|
||||
|
||||
export function statsOf(hunks: DiffHunk[]): { add: number; del: number } {
|
||||
let add = 0;
|
||||
let del = 0;
|
||||
for (const hunk of hunks) {
|
||||
for (const line of hunk.lines) {
|
||||
if (line.startsWith("+")) add += 1;
|
||||
else if (line.startsWith("-")) del += 1;
|
||||
}
|
||||
}
|
||||
return { add, del };
|
||||
}
|
||||
|
||||
export function fileDiff(path: string, before: string, after: string, source?: string): DiffFile {
|
||||
const hunks = unifiedDiff(before, after);
|
||||
const stats = statsOf(hunks);
|
||||
return { path, hunks, add: stats.add, del: stats.del, ...(source ? { source } : {}) };
|
||||
}
|
||||
|
||||
function rec(value: unknown): Record<string, unknown> | undefined {
|
||||
return value && typeof value === "object" && !Array.isArray(value) ? (value as Record<string, unknown>) : undefined;
|
||||
}
|
||||
|
||||
function str(value: unknown): string | undefined {
|
||||
return typeof value === "string" ? value : undefined;
|
||||
}
|
||||
|
||||
function num(value: unknown): number | undefined {
|
||||
return typeof value === "number" && Number.isFinite(value) ? value : undefined;
|
||||
}
|
||||
|
||||
/** `attention_request{method:"diff"}` payload → files (also accepts `hunks`). */
|
||||
export function diffFilesFromPayload(payload: unknown): DiffFile[] {
|
||||
const record = rec(payload);
|
||||
const list = Array.isArray(payload) ? payload : Array.isArray(record?.files) ? record.files : [];
|
||||
const files: DiffFile[] = [];
|
||||
for (const raw of list) {
|
||||
const file = rec(raw);
|
||||
if (!file) continue;
|
||||
const path = str(file.path ?? file.file) ?? "file";
|
||||
const rawHunks = Array.isArray(file.hunks) ? file.hunks : [];
|
||||
let hunks: DiffHunk[] = [];
|
||||
if (rawHunks.length) {
|
||||
hunks = rawHunks.map((value) => {
|
||||
const hunk = rec(value) ?? {};
|
||||
const lines = Array.isArray(hunk.lines) ? hunk.lines.map((line) => String(line)) : [];
|
||||
return { header: str(hunk.header) ?? "", lines };
|
||||
});
|
||||
} else if (typeof file.before === "string" || typeof file.after === "string") {
|
||||
hunks = unifiedDiff(str(file.before) ?? "", str(file.after) ?? "");
|
||||
} else if (typeof file.diff === "string") {
|
||||
hunks = [
|
||||
{
|
||||
header: "",
|
||||
lines: file.diff.split("\n").filter((line) => line !== ""),
|
||||
},
|
||||
];
|
||||
}
|
||||
const stats = statsOf(hunks);
|
||||
files.push({
|
||||
path,
|
||||
hunks,
|
||||
add: num(file.add) ?? stats.add,
|
||||
del: num(file.del) ?? stats.del,
|
||||
...(str(file.source ?? file.agent) ? { source: str(file.source ?? file.agent) } : {}),
|
||||
});
|
||||
}
|
||||
return files;
|
||||
}
|
||||
@@ -0,0 +1,117 @@
|
||||
import type { Block, ThinkingLevel } from "@protocol/types";
|
||||
|
||||
export const THINKING_LEVELS: ThinkingLevel[] = ["off", "minimal", "low", "medium", "high", "xhigh", "max"];
|
||||
|
||||
const clockFormatters = new Map<string, Intl.DateTimeFormat>();
|
||||
|
||||
/** Wall-clock label used in message metadata (`HH:MM`). */
|
||||
export function formatClock(ts: number): string {
|
||||
if (!Number.isFinite(ts) || ts <= 0) return "—";
|
||||
const locale = typeof document !== "undefined" && document.documentElement.lang ? document.documentElement.lang : "en-US";
|
||||
let formatter = clockFormatters.get(locale);
|
||||
if (!formatter) {
|
||||
formatter = new Intl.DateTimeFormat(locale, { hour: "2-digit", minute: "2-digit" });
|
||||
clockFormatters.set(locale, formatter);
|
||||
}
|
||||
return formatter.format(new Date(ts));
|
||||
}
|
||||
|
||||
/** Compact duration (`350ms`, `1.2s`, `2m 05s`) matching `App.fmt.dur`. */
|
||||
export function formatDuration(ms: number | null | undefined): string {
|
||||
if (ms == null || !Number.isFinite(ms) || ms < 0) return "—";
|
||||
if (ms < 1_000) return `${Math.round(ms)}ms`;
|
||||
if (ms < 60_000) {
|
||||
const seconds = ms / 1_000;
|
||||
return `${seconds < 10 ? seconds.toFixed(1) : Math.round(seconds)}s`;
|
||||
}
|
||||
const minutes = Math.floor(ms / 60_000);
|
||||
const seconds = Math.round((ms % 60_000) / 1_000);
|
||||
return `${minutes}m ${String(seconds).padStart(2, "0")}s`;
|
||||
}
|
||||
|
||||
export function truncate(value: string, max = 120): string {
|
||||
const clean = value.replace(/\s+/g, " ").trim();
|
||||
if (clean.length <= max) return clean;
|
||||
return `${clean.slice(0, Math.max(0, max - 1))}…`;
|
||||
}
|
||||
|
||||
function argsOf(block: Block): Record<string, unknown> {
|
||||
if (block.type !== "tool" || !block.args || typeof block.args !== "object") return {};
|
||||
return block.args as Record<string, unknown>;
|
||||
}
|
||||
|
||||
function firstString(args: Record<string, unknown>, keys: string[]): string | undefined {
|
||||
for (const key of keys) {
|
||||
const value = args[key];
|
||||
if (typeof value === "string" && value.trim()) return value;
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
/** One-line tool summary (path/command/pattern) for the collapsed card. */
|
||||
export function toolSummary(block: Extract<Block, { type: "tool" }>): string {
|
||||
const args = argsOf(block);
|
||||
const named =
|
||||
firstString(args, ["command", "cmd", "path", "file_path", "filePath", "pattern", "query", "url", "task"]) ??
|
||||
firstString(args, ["description", "prompt"]);
|
||||
if (named) return truncate(named);
|
||||
const output = block.output?.text;
|
||||
if (output) return truncate(output);
|
||||
return "";
|
||||
}
|
||||
|
||||
export function toolArgsText(block: Extract<Block, { type: "tool" }>): string {
|
||||
if (!block.args || typeof block.args !== "object") return "";
|
||||
try {
|
||||
return JSON.stringify(block.args, null, 2);
|
||||
} catch {
|
||||
return String(block.args);
|
||||
}
|
||||
}
|
||||
|
||||
export function toolOutputText(block: Extract<Block, { type: "tool" }>): string {
|
||||
const output = block.output;
|
||||
if (!output) return "";
|
||||
if (typeof output.text === "string" && output.text.trim()) return output.text;
|
||||
if (output.details !== undefined) {
|
||||
try {
|
||||
return JSON.stringify(output.details, null, 2);
|
||||
} catch {
|
||||
return String(output.details);
|
||||
}
|
||||
}
|
||||
return "";
|
||||
}
|
||||
|
||||
export interface ToolDiffSource {
|
||||
path: string;
|
||||
before: string;
|
||||
after: string;
|
||||
}
|
||||
|
||||
/** Best-effort before/after extraction for edit-style tool arguments. */
|
||||
export function toolDiffSource(block: Extract<Block, { type: "tool" }>): ToolDiffSource | null {
|
||||
const args = argsOf(block);
|
||||
const details = block.output?.details;
|
||||
const path =
|
||||
firstString(args, ["path", "file_path", "filePath", "file", "filename"]) ??
|
||||
(details && typeof details === "object"
|
||||
? firstString(details as Record<string, unknown>, ["path", "file_path", "file"])
|
||||
: undefined);
|
||||
if (!path) return null;
|
||||
const before = firstString(args, ["oldText", "old_string", "oldString", "before", "original"]);
|
||||
const after = firstString(args, ["newText", "new_string", "newString", "after", "content", "replacement"]);
|
||||
if (before === undefined && after === undefined) return null;
|
||||
return { path, before: before ?? "", after: after ?? "" };
|
||||
}
|
||||
|
||||
export function blocksText(blocks: Block[]): string {
|
||||
return blocks
|
||||
.map((block) => {
|
||||
if (block.type === "text" || block.type === "error") return block.text;
|
||||
if (block.type === "thinking") return block.text;
|
||||
return "";
|
||||
})
|
||||
.filter(Boolean)
|
||||
.join("\n\n");
|
||||
}
|
||||
@@ -0,0 +1,129 @@
|
||||
import type { Entry } from "@protocol/types";
|
||||
import { useCallback, useEffect } from "react";
|
||||
|
||||
import { apiRequest, ApiError } from "@/lib/api";
|
||||
import { mergeEntries, normalizeEntriesPage, projectEntries } from "@/lib/entry-projection";
|
||||
import { EMPTY_HISTORY, useChatStore, type HistoryState } from "./store";
|
||||
|
||||
export const HISTORY_PAGE_SIZE = 50;
|
||||
|
||||
export interface FetchedPage {
|
||||
entries: ReturnType<typeof projectEntries>;
|
||||
cursor: { before?: string; hasMore: boolean };
|
||||
}
|
||||
|
||||
/** `GET /api/v1/sessions/:sid/entries?before=&limit=` → raw pi entries + cursor. */
|
||||
export async function fetchEntriesPage(
|
||||
sessionId: string,
|
||||
before?: string,
|
||||
limit = HISTORY_PAGE_SIZE,
|
||||
signal?: AbortSignal,
|
||||
): Promise<FetchedPage> {
|
||||
const query = new URLSearchParams({ limit: String(limit) });
|
||||
if (before) query.set("before", before);
|
||||
const raw = await apiRequest<unknown>(
|
||||
`/api/v1/sessions/${encodeURIComponent(sessionId)}/entries?${query.toString()}`,
|
||||
{ signal },
|
||||
);
|
||||
const page = normalizeEntriesPage(raw);
|
||||
return { entries: projectEntries(page.entries), cursor: page.cursor };
|
||||
}
|
||||
|
||||
/** Monotonic guard so a stale page (session switch / resync) cannot win. */
|
||||
let requestCounter = 0;
|
||||
const latestRequest = new Map<string, number>();
|
||||
|
||||
function nextRequest(sessionId: string): number {
|
||||
const seq = ++requestCounter;
|
||||
latestRequest.set(sessionId, seq);
|
||||
return seq;
|
||||
}
|
||||
|
||||
function isCurrent(sessionId: string, seq: number): boolean {
|
||||
return latestRequest.get(sessionId) === seq;
|
||||
}
|
||||
|
||||
export interface SessionHistory {
|
||||
entries: Entry[];
|
||||
history: HistoryState;
|
||||
hasMore: boolean;
|
||||
loadingOlder: boolean;
|
||||
loadingInitial: boolean;
|
||||
error: string | null;
|
||||
loadOlder: () => void;
|
||||
retry: () => void;
|
||||
}
|
||||
|
||||
/**
|
||||
* Historical pages merged with the live snapshot entries (live wins by id).
|
||||
* Paging is backwards (`before` cursor) and dedupes by entry id.
|
||||
*/
|
||||
export function useSessionHistory(
|
||||
sessionId: string | null | undefined,
|
||||
liveEntries: Entry[],
|
||||
enabled = true,
|
||||
): SessionHistory {
|
||||
const history = useChatStore((state) =>
|
||||
sessionId ? (state.history[sessionId] ?? EMPTY_HISTORY) : EMPTY_HISTORY,
|
||||
);
|
||||
|
||||
const token = history.resyncToken;
|
||||
useEffect(() => {
|
||||
if (!sessionId || !enabled) return;
|
||||
const current = useChatStore.getState().history[sessionId] ?? EMPTY_HISTORY;
|
||||
if (current.loaded || current.loadingInitial) return;
|
||||
|
||||
const seq = nextRequest(sessionId);
|
||||
useChatStore.getState().beginInitial(sessionId);
|
||||
void fetchEntriesPage(sessionId)
|
||||
.then((page) => {
|
||||
if (!isCurrent(sessionId, seq)) return;
|
||||
useChatStore.getState().receiveInitial(sessionId, page.entries, page.cursor);
|
||||
})
|
||||
.catch((error: unknown) => {
|
||||
if (!isCurrent(sessionId, seq)) return;
|
||||
const message = error instanceof ApiError ? error.code : error instanceof Error ? error.message : String(error);
|
||||
useChatStore.getState().historyError(sessionId, message);
|
||||
});
|
||||
// `token` is the resync generation; `sessionId`/`enabled` gate loading.
|
||||
}, [sessionId, enabled, token]);
|
||||
|
||||
const loadOlder = useCallback(() => {
|
||||
if (!sessionId) return;
|
||||
const current = useChatStore.getState().history[sessionId] ?? EMPTY_HISTORY;
|
||||
if (current.loadingOlder || current.loadingInitial) return;
|
||||
const before = current.cursor?.before;
|
||||
if (!current.cursor?.hasMore || !before) return;
|
||||
|
||||
const seq = nextRequest(sessionId);
|
||||
useChatStore.getState().beginOlder(sessionId);
|
||||
void fetchEntriesPage(sessionId, before)
|
||||
.then((page) => {
|
||||
if (!isCurrent(sessionId, seq)) return;
|
||||
useChatStore.getState().receiveOlder(sessionId, page.entries, page.cursor);
|
||||
})
|
||||
.catch((error: unknown) => {
|
||||
if (!isCurrent(sessionId, seq)) return;
|
||||
const message = error instanceof ApiError ? error.code : error instanceof Error ? error.message : String(error);
|
||||
useChatStore.getState().historyError(sessionId, message);
|
||||
});
|
||||
}, [sessionId]);
|
||||
|
||||
const retry = useCallback(() => {
|
||||
if (!sessionId) return;
|
||||
const current = useChatStore.getState().history[sessionId] ?? EMPTY_HISTORY;
|
||||
if (current.loaded) loadOlder();
|
||||
else useChatStore.getState().bumpResync(sessionId);
|
||||
}, [loadOlder, sessionId]);
|
||||
|
||||
return {
|
||||
entries: mergeEntries(history.entries, liveEntries),
|
||||
history,
|
||||
hasMore: history.cursor?.hasMore === true && Boolean(history.cursor?.before),
|
||||
loadingOlder: history.loadingOlder,
|
||||
loadingInitial: history.loadingInitial,
|
||||
error: history.error,
|
||||
loadOlder,
|
||||
retry,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,133 @@
|
||||
import type { CSSProperties, ReactNode } from "react";
|
||||
import { useCallback } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
export interface ChatLayoutProps {
|
||||
tree: ReactNode;
|
||||
stream: ReactNode;
|
||||
panel: ReactNode;
|
||||
treeOpen: boolean;
|
||||
panelOpen: boolean;
|
||||
treeCollapsed: boolean;
|
||||
treeWidth: number;
|
||||
panelWidth: number;
|
||||
onWidths: (widths: { treeWidth?: number; panelWidth?: number }) => void;
|
||||
onCloseDrawers: () => void;
|
||||
className?: string;
|
||||
}
|
||||
|
||||
const TREE_MIN = 220;
|
||||
const TREE_MAX = 460;
|
||||
const PANEL_MIN = 260;
|
||||
const PANEL_MAX = 520;
|
||||
|
||||
function clamp(value: number, min: number, max: number): number {
|
||||
return Math.min(max, Math.max(min, value));
|
||||
}
|
||||
|
||||
/**
|
||||
* Three-column chat grid with resizable dividers.
|
||||
* ≥840: tree | stream | panel; 600–839: tree | stream (panel drawer);
|
||||
* <600: single column with tree/panel drawers.
|
||||
*/
|
||||
export function ChatLayout({
|
||||
tree,
|
||||
stream,
|
||||
panel,
|
||||
treeOpen,
|
||||
panelOpen,
|
||||
treeCollapsed,
|
||||
treeWidth,
|
||||
panelWidth,
|
||||
onWidths,
|
||||
onCloseDrawers,
|
||||
className,
|
||||
}: ChatLayoutProps) {
|
||||
const { t } = useTranslation();
|
||||
const startResize = useCallback(
|
||||
(which: "tree" | "panel", event: React.PointerEvent<HTMLDivElement>) => {
|
||||
event.preventDefault();
|
||||
const startX = event.clientX;
|
||||
const startWidth = which === "tree" ? treeWidth : panelWidth;
|
||||
const move = (moveEvent: PointerEvent) => {
|
||||
const delta = which === "tree" ? moveEvent.clientX - startX : startX - moveEvent.clientX;
|
||||
if (which === "tree") onWidths({ treeWidth: clamp(startWidth + delta, TREE_MIN, TREE_MAX) });
|
||||
else onWidths({ panelWidth: clamp(startWidth + delta, PANEL_MIN, PANEL_MAX) });
|
||||
};
|
||||
const up = () => {
|
||||
window.removeEventListener("pointermove", move);
|
||||
window.removeEventListener("pointerup", up);
|
||||
};
|
||||
window.addEventListener("pointermove", move);
|
||||
window.addEventListener("pointerup", up, { once: true });
|
||||
},
|
||||
[onWidths, panelWidth, treeWidth],
|
||||
);
|
||||
|
||||
const nudge = useCallback(
|
||||
(which: "tree" | "panel", delta: number) => {
|
||||
if (which === "tree") onWidths({ treeWidth: clamp(treeWidth + delta, TREE_MIN, TREE_MAX) });
|
||||
else onWidths({ panelWidth: clamp(panelWidth + delta, PANEL_MIN, PANEL_MAX) });
|
||||
},
|
||||
[onWidths, panelWidth, treeWidth],
|
||||
);
|
||||
|
||||
const separator = (which: "tree" | "panel") => (
|
||||
<div
|
||||
role="separator"
|
||||
aria-orientation="vertical"
|
||||
aria-label={which === "tree" ? t("chat.resizeTree") : t("chat.resizePanel")}
|
||||
tabIndex={0}
|
||||
className={cn("resize-handle", which === "tree" ? "resize-handle--tree" : "resize-handle--panel")}
|
||||
onPointerDown={(event) => startResize(which, event)}
|
||||
onDoubleClick={() => {
|
||||
if (which === "tree") onWidths({ treeWidth: 300 });
|
||||
else onWidths({ panelWidth: 340 });
|
||||
}}
|
||||
onKeyDown={(event) => {
|
||||
if (event.key === "ArrowLeft") {
|
||||
event.preventDefault();
|
||||
nudge(which, -16);
|
||||
} else if (event.key === "ArrowRight") {
|
||||
event.preventDefault();
|
||||
nudge(which, 16);
|
||||
}
|
||||
}}
|
||||
/>
|
||||
);
|
||||
|
||||
const style = {
|
||||
"--tree-w": `${treeWidth}px`,
|
||||
"--panel-w": `${panelWidth}px`,
|
||||
} as CSSProperties;
|
||||
|
||||
return (
|
||||
<div
|
||||
className={cn(
|
||||
"chat-page",
|
||||
treeOpen && "tree-open",
|
||||
panelOpen && "panel-open",
|
||||
treeCollapsed && "tree-collapsed",
|
||||
className,
|
||||
)}
|
||||
style={style}
|
||||
>
|
||||
<aside className="tree-pane">
|
||||
{tree}
|
||||
</aside>
|
||||
{separator("tree")}
|
||||
<section className="stream-pane">{stream}</section>
|
||||
{separator("panel")}
|
||||
<aside className="panel-pane">{panel}</aside>
|
||||
<button
|
||||
type="button"
|
||||
className="drawer-backdrop"
|
||||
aria-label={t("common.close")}
|
||||
tabIndex={treeOpen || panelOpen ? 0 : -1}
|
||||
onClick={onCloseDrawers}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,278 @@
|
||||
import type { Batch, Entry, SessionState, Subagent, TodoItem } from "@protocol/types";
|
||||
import { useVirtualizer } from "@tanstack/react-virtual";
|
||||
import { useCallback, useLayoutEffect, useRef, useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
import { Icon } from "@/components/icons";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Empty } from "@/components/ui/empty";
|
||||
import { Spinner } from "@/components/ui/spinner";
|
||||
import type { ProjectedEntry } from "@/lib/entry-projection";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { BatchBlock, EntryBlock, TodoBlock } from "./blocks";
|
||||
import { findSubagent } from "./session-state";
|
||||
|
||||
/** Below this many items the DOM list is cheaper than virtualizer bookkeeping. */
|
||||
export const VIRTUALIZE_THRESHOLD = 30;
|
||||
|
||||
export type StreamItem =
|
||||
| { kind: "entry"; key: string; entry: Entry; turnStart: boolean }
|
||||
| { kind: "todo"; key: string; todos: TodoItem[] }
|
||||
| { kind: "batch"; key: string; batch: Batch };
|
||||
|
||||
/**
|
||||
* Combine entry-backed messages with the session-level panels (todo, batches)
|
||||
* into one ordered stream. Historical `pi2-todo` checkpoints stay inline; when
|
||||
* history has none, the current todo list is appended as a live block.
|
||||
*/
|
||||
export function buildStreamItems(session: SessionState, entries: Entry[]): StreamItem[] {
|
||||
const items: StreamItem[] = [];
|
||||
let hasTodoEntry = false;
|
||||
entries.forEach((entry, index) => {
|
||||
const projectedTodo = (entry as ProjectedEntry).todo;
|
||||
if (projectedTodo) {
|
||||
hasTodoEntry = true;
|
||||
items.push({ kind: "todo", key: `todo:${entry.id}`, todos: projectedTodo.items });
|
||||
return;
|
||||
}
|
||||
const previous = index > 0 ? entries[index - 1] : undefined;
|
||||
const turnStart = index === 0 || entry.role === "user" || previous?.role === "user";
|
||||
items.push({ kind: "entry", key: `entry:${entry.id}`, entry, turnStart });
|
||||
});
|
||||
if (!hasTodoEntry && session.todos.length) {
|
||||
items.push({ kind: "todo", key: `todo:${session.sessionId}`, todos: session.todos });
|
||||
}
|
||||
for (const batch of session.batches) {
|
||||
items.push({ kind: "batch", key: `batch:${batch.batchId}`, batch });
|
||||
}
|
||||
return items;
|
||||
}
|
||||
|
||||
export interface MessageStreamProps {
|
||||
session: SessionState;
|
||||
entries: Entry[];
|
||||
hasMore: boolean;
|
||||
loadingOlder: boolean;
|
||||
error: string | null;
|
||||
onLoadOlder: () => void;
|
||||
onRetry: () => void;
|
||||
onOpenSubagent: (subagent: Subagent) => void;
|
||||
className?: string;
|
||||
}
|
||||
|
||||
export function MessageStream({
|
||||
session,
|
||||
entries,
|
||||
hasMore,
|
||||
loadingOlder,
|
||||
error,
|
||||
onLoadOlder,
|
||||
onRetry,
|
||||
onOpenSubagent,
|
||||
className,
|
||||
}: MessageStreamProps) {
|
||||
const { t } = useTranslation();
|
||||
const items = buildStreamItems(session, entries);
|
||||
const scrollRef = useRef<HTMLDivElement | null>(null);
|
||||
const [following, setFollowing] = useState(true);
|
||||
const followingRef = useRef(true);
|
||||
const [showTop, setShowTop] = useState(false);
|
||||
const pendingPrepend = useRef<number | null>(null);
|
||||
const loadRequested = useRef(false);
|
||||
const rafRef = useRef<number | null>(null);
|
||||
|
||||
const setFollow = useCallback((value: boolean) => {
|
||||
followingRef.current = value;
|
||||
setFollowing(value);
|
||||
}, []);
|
||||
|
||||
const virtualize = items.length >= VIRTUALIZE_THRESHOLD;
|
||||
const virtualizer = useVirtualizer({
|
||||
count: items.length,
|
||||
getScrollElement: () => scrollRef.current,
|
||||
estimateSize: () => 120,
|
||||
overscan: 8,
|
||||
getItemKey: (index) => items[index]?.key ?? index,
|
||||
});
|
||||
|
||||
const scrollToBottom = useCallback((smooth = false) => {
|
||||
const element = scrollRef.current;
|
||||
if (!element) return;
|
||||
if (typeof element.scrollTo === "function") {
|
||||
element.scrollTo({ top: element.scrollHeight, behavior: smooth ? "smooth" : "auto" });
|
||||
} else {
|
||||
element.scrollTop = element.scrollHeight;
|
||||
}
|
||||
}, []);
|
||||
|
||||
// Streaming keeps the DOM height changing; stay pinned while following.
|
||||
useLayoutEffect(() => {
|
||||
if (!followingRef.current) return;
|
||||
if (rafRef.current != null) cancelAnimationFrame(rafRef.current);
|
||||
rafRef.current = requestAnimationFrame(() => {
|
||||
rafRef.current = requestAnimationFrame(() => {
|
||||
rafRef.current = null;
|
||||
if (followingRef.current) scrollToBottom(false);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
useLayoutEffect(() => {
|
||||
const element = scrollRef.current;
|
||||
const previous = pendingPrepend.current;
|
||||
if (previous != null && element) {
|
||||
element.scrollTop += element.scrollHeight - previous;
|
||||
pendingPrepend.current = null;
|
||||
}
|
||||
if (!loadingOlder) loadRequested.current = false;
|
||||
}, [items.length, loadingOlder]);
|
||||
|
||||
const handleScroll = useCallback(() => {
|
||||
const element = scrollRef.current;
|
||||
if (!element) return;
|
||||
const distance = element.scrollHeight - element.scrollTop - element.clientHeight;
|
||||
setFollow(distance < 80);
|
||||
setShowTop(element.scrollTop > 400);
|
||||
if (element.scrollTop < 120 && hasMore && !loadingOlder && !loadRequested.current) {
|
||||
loadRequested.current = true;
|
||||
pendingPrepend.current = element.scrollHeight;
|
||||
onLoadOlder();
|
||||
}
|
||||
}, [hasMore, loadingOlder, onLoadOlder, setFollow]);
|
||||
|
||||
const openByName = useCallback(
|
||||
(name: string) => {
|
||||
const subagent = findSubagent(session.subagents, (candidate) => candidate.name === name);
|
||||
if (subagent) onOpenSubagent(subagent);
|
||||
},
|
||||
[onOpenSubagent, session.subagents],
|
||||
);
|
||||
|
||||
const canOpen = useCallback(
|
||||
(name: string) => Boolean(findSubagent(session.subagents, (candidate) => candidate.name === name)),
|
||||
[session.subagents],
|
||||
);
|
||||
|
||||
const renderItem = useCallback(
|
||||
(item: StreamItem) => {
|
||||
switch (item.kind) {
|
||||
case "entry":
|
||||
return <EntryBlock entry={item.entry} turnStart={item.turnStart} />;
|
||||
case "todo":
|
||||
return <TodoBlock items={item.todos} />;
|
||||
case "batch":
|
||||
return <BatchBlock batch={item.batch} onOpenSubagent={openByName} canOpen={canOpen} />;
|
||||
}
|
||||
},
|
||||
[canOpen, openByName],
|
||||
);
|
||||
|
||||
const status = (
|
||||
<div className="stream-status-row">
|
||||
{loadingOlder ? (
|
||||
<span className="muted stream-status">
|
||||
<Spinner /> {t("chat.loadingOlder")}
|
||||
</span>
|
||||
) : hasMore ? (
|
||||
<button type="button" className="stream-older muted" onClick={onLoadOlder}>
|
||||
{t("chat.loadOlder")}
|
||||
</button>
|
||||
) : null}
|
||||
{error ? (
|
||||
<span className="stream-status stream-status--err">
|
||||
<span>{t("chat.historyError")}</span>
|
||||
<Button size="sm" onClick={onRetry}>
|
||||
{t("common.retry")}
|
||||
</Button>
|
||||
</span>
|
||||
) : null}
|
||||
</div>
|
||||
);
|
||||
|
||||
const body = items.length ? (
|
||||
virtualize ? (
|
||||
<div
|
||||
className="stream-list stream-list--virtual"
|
||||
style={{ height: `${virtualizer.getTotalSize()}px` }}
|
||||
>
|
||||
{virtualizer.getVirtualItems().map((virtualItem) => {
|
||||
const item = items[virtualItem.index];
|
||||
if (!item) return null;
|
||||
return (
|
||||
<div
|
||||
key={item.key}
|
||||
data-index={virtualItem.index}
|
||||
ref={(node) => {
|
||||
virtualizer.measureElement(node);
|
||||
}}
|
||||
className={cn("stream-item", item.kind === "entry" && item.turnStart && "turn-start")}
|
||||
style={{ transform: `translateY(${virtualItem.start}px)` }}
|
||||
>
|
||||
{renderItem(item)}
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
) : (
|
||||
<div className="stream-list">
|
||||
{items.map((item) => (
|
||||
<div
|
||||
className={cn("stream-item", item.kind === "entry" && item.turnStart && "turn-start")}
|
||||
key={item.key}
|
||||
>
|
||||
{renderItem(item)}
|
||||
</div>
|
||||
))}
|
||||
<div className="stream-end" />
|
||||
</div>
|
||||
)
|
||||
) : (
|
||||
<Empty
|
||||
className="stream-empty"
|
||||
icon={<Icon name="chat" />}
|
||||
title={t("chat.emptyTitle")}
|
||||
description={t("chat.emptyText")}
|
||||
/>
|
||||
);
|
||||
|
||||
return (
|
||||
<div className={cn("stream-body", className)}>
|
||||
<div
|
||||
ref={scrollRef}
|
||||
className="stream-scroll"
|
||||
role="log"
|
||||
aria-live="polite"
|
||||
aria-label={t("chat.streamAria")}
|
||||
onScroll={handleScroll}
|
||||
>
|
||||
{status}
|
||||
{body}
|
||||
</div>
|
||||
<div className="stream-fab">
|
||||
<button
|
||||
type="button"
|
||||
className={cn("fab fab--top", showTop && "is-visible")}
|
||||
title={t("chat.toTop")}
|
||||
onClick={() => {
|
||||
scrollRef.current?.scrollTo({ top: 0, behavior: "smooth" });
|
||||
setFollow(false);
|
||||
setShowTop(false);
|
||||
}}
|
||||
>
|
||||
{t("chat.top")}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className={cn("fab fab--latest", !following && "is-visible")}
|
||||
title={t("chat.backToLatest")}
|
||||
onClick={() => {
|
||||
setFollow(true);
|
||||
scrollToBottom(true);
|
||||
}}
|
||||
>
|
||||
{t("chat.latest")}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,557 @@
|
||||
import type { Entry, ModelRef, SessionState, Subagent, TaskItem, ThinkingLevel } from "@protocol/types";
|
||||
import { useEffect, useMemo, useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
import { RelativeTime } from "@/components/shared/relative-time";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Modal } from "@/components/ui/dialog";
|
||||
import { KV } from "@/components/ui/kv";
|
||||
import { Spinner } from "@/components/ui/spinner";
|
||||
import { toast } from "@/components/ui/toast";
|
||||
import { projectEntries } from "@/lib/entry-projection";
|
||||
import { EntryBlock } from "./blocks";
|
||||
import { chatCommands, runCommand } from "./commands";
|
||||
import type { ModelGroup } from "./data";
|
||||
import { withCurrentModel } from "./data";
|
||||
import { formatDuration, THINKING_LEVELS } from "./format";
|
||||
import { flattenSubagents } from "./session-state";
|
||||
|
||||
/* ------------------------------------------------------------------ */
|
||||
/* dispatch */
|
||||
/* ------------------------------------------------------------------ */
|
||||
|
||||
export interface DispatchInput {
|
||||
task: string;
|
||||
name?: string;
|
||||
model?: ModelRef;
|
||||
thinking?: ThinkingLevel;
|
||||
wait?: boolean;
|
||||
cancelSiblingsOnFail?: boolean;
|
||||
}
|
||||
|
||||
export interface DispatchModalProps {
|
||||
open: boolean;
|
||||
session: SessionState;
|
||||
models: ModelGroup[];
|
||||
onClose: () => void;
|
||||
onDispatch: (input: DispatchInput) => void | Promise<void>;
|
||||
}
|
||||
|
||||
export function DispatchModal({ open, session, models, onClose, onDispatch }: DispatchModalProps) {
|
||||
const { t } = useTranslation();
|
||||
const groups = withCurrentModel(models, session.model);
|
||||
const [task, setTask] = useState("");
|
||||
const [name, setName] = useState("");
|
||||
const [modelValue, setModelValue] = useState("");
|
||||
const [thinking, setThinking] = useState<ThinkingLevel>("low");
|
||||
const [wait, setWait] = useState(false);
|
||||
const [cancelSiblings, setCancelSiblings] = useState(true);
|
||||
const [busy, setBusy] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) return;
|
||||
const first = groups[0]?.provider && groups[0]?.models[0] ? `${groups[0].provider}/${groups[0].models[0].id}` : "";
|
||||
setModelValue(session.model ? `${session.model.provider}/${session.model.id}` : first);
|
||||
}, [open, session.model, groups]);
|
||||
|
||||
function parseModel(): ModelRef | undefined {
|
||||
const slash = modelValue.indexOf("/");
|
||||
if (slash <= 0) return undefined;
|
||||
return { provider: modelValue.slice(0, slash), id: modelValue.slice(slash + 1) };
|
||||
}
|
||||
|
||||
async function submit() {
|
||||
if (!task.trim()) {
|
||||
toast.error(t("chat.taskRequired"));
|
||||
return;
|
||||
}
|
||||
setBusy(true);
|
||||
try {
|
||||
await onDispatch({
|
||||
task: task.trim(),
|
||||
...(name.trim() ? { name: name.trim() } : {}),
|
||||
...(parseModel() ? { model: parseModel() } : {}),
|
||||
thinking,
|
||||
wait,
|
||||
cancelSiblingsOnFail: cancelSiblings,
|
||||
});
|
||||
setTask("");
|
||||
setName("");
|
||||
onClose();
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Modal
|
||||
open={open}
|
||||
onOpenChange={(next) => {
|
||||
if (!next) onClose();
|
||||
}}
|
||||
title={t("chat.dispatchTitle")}
|
||||
footer={
|
||||
<>
|
||||
<Button variant="ghost" onClick={onClose}>
|
||||
{t("common.cancel")}
|
||||
</Button>
|
||||
<Button variant="primary" onClick={() => void submit()} disabled={busy}>
|
||||
{t("chat.dispatch")}
|
||||
</Button>
|
||||
</>
|
||||
}
|
||||
>
|
||||
<div className="field">
|
||||
<label htmlFor="dispatch-task">{t("chat.taskLabel")}</label>
|
||||
<textarea
|
||||
id="dispatch-task"
|
||||
className="textarea"
|
||||
rows={3}
|
||||
value={task}
|
||||
placeholder={t("chat.taskPlaceholder")}
|
||||
onChange={(event) => setTask(event.target.value)}
|
||||
/>
|
||||
</div>
|
||||
<div className="field">
|
||||
<label htmlFor="dispatch-name">{t("chat.nameLabel")}</label>
|
||||
<input
|
||||
id="dispatch-name"
|
||||
className="input"
|
||||
value={name}
|
||||
placeholder={t("chat.subagentNamePlaceholder")}
|
||||
onChange={(event) => setName(event.target.value)}
|
||||
/>
|
||||
</div>
|
||||
<div className="field">
|
||||
<label htmlFor="dispatch-model">{t("chat.modelLabel")}</label>
|
||||
<select
|
||||
id="dispatch-model"
|
||||
className="select"
|
||||
value={modelValue}
|
||||
onChange={(event) => setModelValue(event.target.value)}
|
||||
>
|
||||
{groups.map((group) => (
|
||||
<optgroup key={group.provider} label={group.provider}>
|
||||
{group.models.map((item) => (
|
||||
<option key={`${group.provider}/${item.id}`} value={`${group.provider}/${item.id}`}>
|
||||
{item.id}
|
||||
</option>
|
||||
))}
|
||||
</optgroup>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
<div className="field">
|
||||
<label htmlFor="dispatch-thinking">{t("chat.thinkingAria")}</label>
|
||||
<select
|
||||
id="dispatch-thinking"
|
||||
className="select"
|
||||
value={thinking}
|
||||
onChange={(event) => setThinking(event.target.value as ThinkingLevel)}
|
||||
>
|
||||
{THINKING_LEVELS.map((level) => (
|
||||
<option key={level} value={level}>
|
||||
{level}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
<div className="field">
|
||||
<label className="check-row">
|
||||
<input type="checkbox" checked={wait} onChange={(event) => setWait(event.target.checked)} />
|
||||
{t("chat.waitLabel")}
|
||||
</label>
|
||||
</div>
|
||||
<div className="field">
|
||||
<label className="check-row">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={cancelSiblings}
|
||||
onChange={(event) => setCancelSiblings(event.target.checked)}
|
||||
/>
|
||||
{t("chat.cancelSiblingsLabel")}
|
||||
</label>
|
||||
</div>
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ */
|
||||
/* subagent conversation (read-only tail + steer) */
|
||||
/* ------------------------------------------------------------------ */
|
||||
|
||||
const SUB_BADGE: Record<Subagent["status"], { tone: "info" | "ok" | "err" | "warn" | "default"; key: string }> = {
|
||||
active: { tone: "info", key: "active" },
|
||||
completed: { tone: "ok", key: "completed" },
|
||||
failed: { tone: "err", key: "failed" },
|
||||
interrupted: { tone: "warn", key: "interrupted" },
|
||||
dormant: { tone: "default", key: "dormant" },
|
||||
};
|
||||
|
||||
const SUB_DOT: Record<Subagent["status"], string> = {
|
||||
active: "dot--busy",
|
||||
completed: "dot--ok",
|
||||
failed: "dot--err",
|
||||
interrupted: "dot--attention",
|
||||
dormant: "dot--exited",
|
||||
};
|
||||
|
||||
function statusTail(subagent: Subagent, t: (key: string) => string): Entry[] {
|
||||
const ts = subagent.lastActiveAt ?? subagent.createdAt ?? Date.now();
|
||||
if (subagent.status === "failed") {
|
||||
return [{ id: `preview-${subagent.id}-err`, role: "notice", ts, done: true, blocks: [{ type: "error", text: t("chat.previewFailed") }] }];
|
||||
}
|
||||
if (subagent.status === "interrupted") {
|
||||
return [{ id: `preview-${subagent.id}-int`, role: "assistant", ts, done: true, blocks: [{ type: "text", text: t("chat.previewInterrupted") }] }];
|
||||
}
|
||||
if (subagent.status === "completed") {
|
||||
return [{ id: `preview-${subagent.id}-done`, role: "assistant", ts, done: true, blocks: [{ type: "text", text: t("chat.previewCompleted") }] }];
|
||||
}
|
||||
if (subagent.status === "dormant") {
|
||||
return [{ id: `preview-${subagent.id}-dorm`, role: "assistant", ts, done: true, blocks: [{ type: "text", text: t("chat.previewDormant") }] }];
|
||||
}
|
||||
return [];
|
||||
}
|
||||
|
||||
export interface SubagentModalProps {
|
||||
open: boolean;
|
||||
session: SessionState;
|
||||
subagent: Subagent | null;
|
||||
onClose: () => void;
|
||||
onBack: () => void;
|
||||
onSteer: (subagent: Subagent, message: string) => void;
|
||||
}
|
||||
|
||||
export function SubagentModal({ open, session, subagent, onClose, onBack, onSteer }: SubagentModalProps) {
|
||||
const { t } = useTranslation();
|
||||
const [steer, setSteer] = useState("");
|
||||
const [tail, setTail] = useState<Entry[] | null>(null);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const badge = subagent ? (SUB_BADGE[subagent.status] ?? { tone: "default" as const, key: subagent.status }) : null;
|
||||
|
||||
useEffect(() => {
|
||||
if (!open || !subagent) return;
|
||||
setTail(null);
|
||||
setLoading(true);
|
||||
const target = subagent.name ?? subagent.id;
|
||||
void runCommand(chatCommands.readSubagent(session.sessionId, target))
|
||||
.then((response) => {
|
||||
const raw = response as Record<string, unknown>;
|
||||
const entries = Array.isArray(raw.entries)
|
||||
? raw.entries
|
||||
: Array.isArray(raw.messages)
|
||||
? raw.messages
|
||||
: [];
|
||||
if (entries.length) setTail(projectEntries(entries));
|
||||
else setTail(statusTail(subagent, t));
|
||||
})
|
||||
.catch(() => {
|
||||
if (subagent) setTail(statusTail(subagent, t));
|
||||
})
|
||||
.finally(() => setLoading(false));
|
||||
}, [open, session.sessionId, subagent, t]);
|
||||
|
||||
const feed = useMemo(() => {
|
||||
if (!subagent) return [];
|
||||
if (tail && tail.length) return tail;
|
||||
return [
|
||||
{
|
||||
id: `preview-${subagent.id}-task`,
|
||||
role: "user" as const,
|
||||
ts: subagent.createdAt ?? Date.now(),
|
||||
done: true,
|
||||
blocks: [{ type: "text" as const, text: subagent.task ?? t("chat.task") }],
|
||||
},
|
||||
...statusTail(subagent, t),
|
||||
];
|
||||
}, [subagent, t, tail]);
|
||||
|
||||
const children = subagent ? flattenSubagents(subagent.children) : [];
|
||||
|
||||
function sendSteer() {
|
||||
if (!steer.trim()) {
|
||||
toast.error(t("chat.steerRequired"));
|
||||
return;
|
||||
}
|
||||
if (subagent) onSteer(subagent, steer.trim());
|
||||
setSteer("");
|
||||
}
|
||||
|
||||
return (
|
||||
<Modal
|
||||
open={open}
|
||||
onOpenChange={(next) => {
|
||||
if (!next) onClose();
|
||||
}}
|
||||
title={t("chat.subagentTitle", { name: subagent?.name ?? subagent?.id ?? "" })}
|
||||
size="wide"
|
||||
footer={
|
||||
<>
|
||||
<Button variant="ghost" onClick={onClose}>
|
||||
{t("common.close")}
|
||||
</Button>
|
||||
<Button variant="primary" onClick={onBack}>
|
||||
{t("chat.backToParent")}
|
||||
</Button>
|
||||
</>
|
||||
}
|
||||
>
|
||||
{subagent ? (
|
||||
<div className="sub-preview">
|
||||
<div className="row">
|
||||
<span className={`dot ${SUB_DOT[subagent.status] ?? "dot--exited"}`} />
|
||||
{badge ? <Badge tone={badge.tone}>{t(`state.${badge.key}`)}</Badge> : null}
|
||||
<span className="muted mono truncate">{subagent.id}</span>
|
||||
</div>
|
||||
<div>
|
||||
<KV label={t("chat.task")}>{subagent.task ?? "—"}</KV>
|
||||
<KV label={t("chat.model")} mono>
|
||||
{subagent.model ?? "—"}
|
||||
{subagent.thinking ? ` · ${subagent.thinking}` : ""}
|
||||
</KV>
|
||||
<KV label={t("status.created")}>
|
||||
<RelativeTime ts={subagent.createdAt} />
|
||||
</KV>
|
||||
<KV label={t("status.lastActive")}>
|
||||
<RelativeTime ts={subagent.lastActiveAt} />
|
||||
</KV>
|
||||
</div>
|
||||
{children.length ? (
|
||||
<div className="stack">
|
||||
<div className="muted">{t("chat.currentSubagents", { n: children.length })}</div>
|
||||
{children.map(({ subagent: child, depth }) => (
|
||||
<div
|
||||
key={child.id}
|
||||
className="sub-item sub-item--nested"
|
||||
style={{ marginLeft: `${depth * 16}px` }}
|
||||
>
|
||||
<span className={`dot ${SUB_DOT[child.status] ?? "dot--exited"}`} />
|
||||
<span className="sub-item__main">
|
||||
<span className="sub-item__name truncate">{child.name ?? child.id}</span>
|
||||
<span className="sub-item__meta muted truncate">{child.model ?? "—"}</span>
|
||||
</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
) : null}
|
||||
<div className="sub-preview__feed" aria-label={t("chat.preview")}>
|
||||
{loading ? (
|
||||
<div className="row muted">
|
||||
<Spinner /> {t("chat.loading")}
|
||||
</div>
|
||||
) : (
|
||||
feed.map((entry) => <EntryBlock key={entry.id} entry={entry} />)
|
||||
)}
|
||||
</div>
|
||||
<div className="muted sub-preview__note">{t("chat.previewNote")}</div>
|
||||
<div className="row sub-steer">
|
||||
<input
|
||||
className="input"
|
||||
value={steer}
|
||||
placeholder={t("chat.steerPlaceholder")}
|
||||
aria-label={t("chat.steer")}
|
||||
onChange={(event) => setSteer(event.target.value)}
|
||||
onKeyDown={(event) => {
|
||||
if (event.key === "Enter" && !event.nativeEvent.isComposing) {
|
||||
event.preventDefault();
|
||||
sendSteer();
|
||||
}
|
||||
}}
|
||||
/>
|
||||
<Button size="sm" onClick={sendSteer}>
|
||||
{t("chat.steer")}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
) : null}
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ */
|
||||
/* task output */
|
||||
/* ------------------------------------------------------------------ */
|
||||
|
||||
function fakePid(task: TaskItem): number {
|
||||
let hash = 0;
|
||||
for (const char of task.id) hash = (hash * 31 + char.charCodeAt(0)) % 100_000;
|
||||
return 10_000 + (hash % 8_000);
|
||||
}
|
||||
|
||||
export interface TaskOutputModalProps {
|
||||
open: boolean;
|
||||
session: SessionState;
|
||||
task: TaskItem | null;
|
||||
onClose: () => void;
|
||||
onStop: (task: TaskItem) => void;
|
||||
}
|
||||
|
||||
export function TaskOutputModal({ open, session, task, onClose, onStop }: TaskOutputModalProps) {
|
||||
const { t } = useTranslation();
|
||||
const [output, setOutput] = useState<string | null>(null);
|
||||
const [loading, setLoading] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
if (!open || !task) return;
|
||||
setOutput(null);
|
||||
setLoading(true);
|
||||
void runCommand(chatCommands.taskOutput(session.sessionId, task.id))
|
||||
.then((response) => {
|
||||
const record = response as Record<string, unknown>;
|
||||
const text =
|
||||
typeof record.output === "string"
|
||||
? record.output
|
||||
: typeof record.text === "string"
|
||||
? record.text
|
||||
: typeof record.data === "string"
|
||||
? record.data
|
||||
: null;
|
||||
setOutput(text);
|
||||
})
|
||||
.catch(() => setOutput(null))
|
||||
.finally(() => setLoading(false));
|
||||
}, [open, session.sessionId, task]);
|
||||
|
||||
if (!task) return null;
|
||||
const running = task.status === "running";
|
||||
const duration = running ? Date.now() - task.startTime : (task.durationMs ?? 0);
|
||||
|
||||
return (
|
||||
<Modal
|
||||
open={open}
|
||||
onOpenChange={(next) => {
|
||||
if (!next) onClose();
|
||||
}}
|
||||
title={t("chat.taskOutput", { id: task.id })}
|
||||
footer={
|
||||
<>
|
||||
{running ? (
|
||||
<Button variant="danger" onClick={() => onStop(task)}>
|
||||
{t("common.stop")}
|
||||
</Button>
|
||||
) : null}
|
||||
<Button variant="primary" onClick={onClose}>
|
||||
{t("common.close")}
|
||||
</Button>
|
||||
</>
|
||||
}
|
||||
>
|
||||
<div className="stack">
|
||||
<pre className="mono tool__pre">{loading ? t("chat.loading") : (output ?? t("chat.noOutput"))}</pre>
|
||||
{task.outputFile ? <div className="muted mono truncate">{task.outputFile}</div> : null}
|
||||
<div>
|
||||
<KV label="pid" mono>
|
||||
{fakePid(task)}
|
||||
</KV>
|
||||
<KV label={t("chat.status")}>
|
||||
<span className="row">
|
||||
<span className={`dot ${running ? "dot--busy" : task.status === "completed" ? "dot--ok" : task.status === "failed" ? "dot--err" : "dot--idle"}`} />
|
||||
{t(`state.${task.status}`)}
|
||||
</span>
|
||||
</KV>
|
||||
<KV label={t("chat.duration")}>{formatDuration(duration)}</KV>
|
||||
<KV label="exit code" mono>
|
||||
{task.exitCode == null ? "—" : task.exitCode}
|
||||
</KV>
|
||||
<KV label={t("chat.command")} mono>
|
||||
{task.command}
|
||||
</KV>
|
||||
</div>
|
||||
{running ? (
|
||||
<div className="row muted">
|
||||
<Spinner /> {t("chat.taskRunning")}
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ */
|
||||
/* rename */
|
||||
/* ------------------------------------------------------------------ */
|
||||
|
||||
export interface RenameDialogProps {
|
||||
open: boolean;
|
||||
title: string;
|
||||
initial: string;
|
||||
hint?: string;
|
||||
onClose: () => void;
|
||||
onSave: (value: string) => void | Promise<void>;
|
||||
}
|
||||
|
||||
export function RenameDialog({ open, title, initial, hint, onClose, onSave }: RenameDialogProps) {
|
||||
const { t } = useTranslation();
|
||||
const [value, setValue] = useState(initial);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [busy, setBusy] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
if (open) {
|
||||
setValue(initial);
|
||||
setError(null);
|
||||
}
|
||||
}, [open, initial]);
|
||||
|
||||
async function save() {
|
||||
const trimmed = value.trim();
|
||||
if (!trimmed) {
|
||||
setError(t("chat.nameRequired"));
|
||||
return;
|
||||
}
|
||||
setBusy(true);
|
||||
try {
|
||||
await onSave(trimmed);
|
||||
onClose();
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Modal
|
||||
open={open}
|
||||
onOpenChange={(next) => {
|
||||
if (!next) onClose();
|
||||
}}
|
||||
title={title}
|
||||
footer={
|
||||
<>
|
||||
<Button variant="ghost" onClick={onClose}>
|
||||
{t("common.cancel")}
|
||||
</Button>
|
||||
<Button variant="primary" onClick={() => void save()} disabled={busy}>
|
||||
{t("common.save")}
|
||||
</Button>
|
||||
</>
|
||||
}
|
||||
>
|
||||
<div className="field">
|
||||
<label htmlFor="rename-input">{t("chat.name")}</label>
|
||||
<input
|
||||
id="rename-input"
|
||||
className="input"
|
||||
value={value}
|
||||
onChange={(event) => {
|
||||
setValue(event.target.value);
|
||||
setError(null);
|
||||
}}
|
||||
onKeyDown={(event) => {
|
||||
if (event.key === "Enter") {
|
||||
event.preventDefault();
|
||||
void save();
|
||||
}
|
||||
}}
|
||||
/>
|
||||
{error ? (
|
||||
<div className="hint is-err" role="alert">
|
||||
{error}
|
||||
</div>
|
||||
) : hint ? (
|
||||
<div className="hint">{hint}</div>
|
||||
) : null}
|
||||
</div>
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,356 @@
|
||||
import { applyEvent, createReducer, type Reducer } from "@protocol/reducer";
|
||||
import type { Entry, ModelRef, SessionEvent, SessionState, ThinkingLevel } from "@protocol/types";
|
||||
import type { DotStatus } from "@/components/ui/status-dot";
|
||||
import { normalizeTodos, projectEntries, type ProjectedEntry } from "@/lib/entry-projection";
|
||||
|
||||
const EMPTY_USAGE = { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, cost: 0 };
|
||||
|
||||
function rec(value: unknown): Record<string, unknown> | undefined {
|
||||
return value && typeof value === "object" && !Array.isArray(value) ? (value as Record<string, unknown>) : undefined;
|
||||
}
|
||||
|
||||
function arr<T>(value: unknown): T[] {
|
||||
return Array.isArray(value) ? (value as T[]) : [];
|
||||
}
|
||||
|
||||
function str(value: unknown): string | undefined {
|
||||
return typeof value === "string" ? value : undefined;
|
||||
}
|
||||
|
||||
function num(value: unknown): number | undefined {
|
||||
return typeof value === "number" && Number.isFinite(value) ? value : undefined;
|
||||
}
|
||||
|
||||
const STATUSES = new Set(["starting", "busy", "compacting", "idle", "exited", "interrupted"]);
|
||||
const THINKING = new Set(["off", "minimal", "low", "medium", "high", "xhigh", "max"]);
|
||||
|
||||
export interface EmptySessionInput {
|
||||
sessionId: string;
|
||||
workspaceId?: string;
|
||||
cwd?: string;
|
||||
name?: string | null;
|
||||
status?: SessionState["status"];
|
||||
model?: ModelRef | null;
|
||||
thinking?: ThinkingLevel | null;
|
||||
}
|
||||
|
||||
export function emptySessionState(input: EmptySessionInput): SessionState {
|
||||
return {
|
||||
sessionId: input.sessionId,
|
||||
workspaceId: input.workspaceId ?? "",
|
||||
cwd: input.cwd ?? "",
|
||||
name: input.name ?? null,
|
||||
status: input.status ?? "idle",
|
||||
flags: { attention: false, done: false, error: false },
|
||||
model: input.model ?? null,
|
||||
thinking: input.thinking ?? null,
|
||||
usage: { ...EMPTY_USAGE },
|
||||
contextUsage: null,
|
||||
queue: [],
|
||||
todos: [],
|
||||
tasks: [],
|
||||
batches: [],
|
||||
subagents: [],
|
||||
attention: [],
|
||||
entries: [],
|
||||
};
|
||||
}
|
||||
|
||||
export function cloneSessionState(state: SessionState): SessionState {
|
||||
if (typeof structuredClone === "function") return structuredClone(state);
|
||||
return JSON.parse(JSON.stringify(state)) as SessionState;
|
||||
}
|
||||
|
||||
export function normalizeModelRef(value: unknown): ModelRef | null {
|
||||
if (typeof value === "string") {
|
||||
const slash = value.indexOf("/");
|
||||
return slash > 0
|
||||
? { provider: value.slice(0, slash), id: value.slice(slash + 1) }
|
||||
: { provider: "pi", id: value };
|
||||
}
|
||||
const record = rec(value);
|
||||
const provider = str(record?.provider);
|
||||
const id = str(record?.id ?? record?.model ?? record?.modelId);
|
||||
if (id) return { provider: provider ?? "pi", id };
|
||||
return null;
|
||||
}
|
||||
|
||||
/** Rebuild the reducer bookkeeping a snapshot does not carry. */
|
||||
export function reducerForState(state: SessionState): Reducer {
|
||||
const reducer = createReducer({
|
||||
sessionId: state.sessionId,
|
||||
workspaceId: state.workspaceId,
|
||||
cwd: state.cwd,
|
||||
name: state.name,
|
||||
status: state.status,
|
||||
model: state.model,
|
||||
thinking: state.thinking,
|
||||
});
|
||||
reducer.state = state;
|
||||
let nextEntry = 1;
|
||||
let assistantEntryId: string | null = null;
|
||||
let userEntryId: string | null = null;
|
||||
for (const entry of state.entries) {
|
||||
const match = /^m(\d+)$/.exec(entry.id);
|
||||
if (match?.[1]) nextEntry = Math.max(nextEntry, Number(match[1]) + 1);
|
||||
if (entry.role === "assistant") assistantEntryId = entry.id;
|
||||
if (entry.role === "user") userEntryId = entry.id;
|
||||
entry.blocks.forEach((block, index) => {
|
||||
if (block.type === "tool") reducer.ctx.toolBlocks.set(block.toolCallId, { entryId: entry.id, index });
|
||||
});
|
||||
}
|
||||
reducer.ctx.nextEntry = nextEntry;
|
||||
reducer.ctx.assistantEntryId = assistantEntryId;
|
||||
reducer.ctx.userEntryId = userEntryId;
|
||||
return reducer;
|
||||
}
|
||||
|
||||
function entryText(entry: Entry): string {
|
||||
return entry.blocks
|
||||
.map((block) => (block.type === "text" || block.type === "error" ? block.text : block.type === "thinking" ? block.text : ""))
|
||||
.join("\n");
|
||||
}
|
||||
|
||||
function isDuplicateEntry(entries: Entry[], candidate: Entry): boolean {
|
||||
const text = entryText(candidate);
|
||||
const recent = entries.slice(-8);
|
||||
return recent.some(
|
||||
(entry) =>
|
||||
entry.role === candidate.role &&
|
||||
Math.abs(entry.ts - candidate.ts) < 5_000 &&
|
||||
entryText(entry).trim() === text.trim(),
|
||||
);
|
||||
}
|
||||
|
||||
function patchToolResult(state: SessionState, raw: Record<string, unknown>): boolean {
|
||||
const toolCallId = str(raw.toolCallId);
|
||||
if (!toolCallId) return false;
|
||||
for (const entry of state.entries) {
|
||||
for (const block of entry.blocks) {
|
||||
if (block.type !== "tool" || block.toolCallId !== toolCallId) continue;
|
||||
block.state = raw.isError === true ? "error" : "done";
|
||||
block.output = {
|
||||
text: contentText(raw.content),
|
||||
...(raw.details !== undefined ? { details: raw.details } : {}),
|
||||
isError: raw.isError === true,
|
||||
};
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
function contentText(content: unknown): string {
|
||||
if (typeof content === "string") return content;
|
||||
const parts: string[] = [];
|
||||
for (const item of arr<Record<string, unknown>>(content)) {
|
||||
if (item.type === "text" && typeof item.text === "string") parts.push(item.text);
|
||||
}
|
||||
return parts.join("\n");
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle `entry_appended`. The canonical reducer relays pi's streaming
|
||||
* `message_*` events but does not project this authoritative history record, so
|
||||
* the browser applies it here (user messages arrive this way; we never insert a
|
||||
* local user message).
|
||||
*/
|
||||
function applyEntryAppended(state: SessionState, rawEntry: unknown): void {
|
||||
const raw = rec(rawEntry);
|
||||
if (!raw) return;
|
||||
const type = str(raw.type);
|
||||
|
||||
if (type === "custom" && str(raw.customType) === "pi2-todo") {
|
||||
const todos = normalizeTodos(rec(raw.data)?.todos);
|
||||
if (todos.length) state.todos = todos;
|
||||
}
|
||||
|
||||
if (type === "message") {
|
||||
const message = rec(raw.message);
|
||||
if (message?.role === "toolResult" && patchToolResult(state, message)) return;
|
||||
if (message?.role === "assistant") {
|
||||
// Streaming message_* events already own the assistant entry; the
|
||||
// raw append would re-introduce a second copy.
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
const [projected] = projectEntries([raw]);
|
||||
if (!projected) return;
|
||||
if (isDuplicateEntry(state.entries, projected)) return;
|
||||
state.entries = [...state.entries, projected];
|
||||
}
|
||||
|
||||
/** Apply one live session event to an immutable copy of the render state. */
|
||||
export function applySessionEvent(state: SessionState, event: SessionEvent): SessionState {
|
||||
const next = cloneSessionState(state);
|
||||
const normalized: SessionEvent = { ...event, ts: typeof event.ts === "number" ? event.ts : Date.now() };
|
||||
|
||||
if (normalized.type === "entry_appended") {
|
||||
applyEntryAppended(next, normalized.entry);
|
||||
return next;
|
||||
}
|
||||
|
||||
applyEvent(reducerForState(next), normalized);
|
||||
return next;
|
||||
}
|
||||
|
||||
/** Enrich a snapshot with its separately-carried entry tail. */
|
||||
export function normalizeSnapshotState(sessionId: string, workspaceId: string, payload: unknown): SessionState {
|
||||
const record = rec(payload);
|
||||
const candidate = rec(record?.state) ?? record ?? {};
|
||||
const base = emptySessionState({
|
||||
sessionId,
|
||||
workspaceId: str(candidate.workspaceId) ?? workspaceId,
|
||||
cwd: str(candidate.cwd) ?? "",
|
||||
});
|
||||
const state: SessionState = {
|
||||
...base,
|
||||
...candidate,
|
||||
sessionId,
|
||||
workspaceId: str(candidate.workspaceId) ?? workspaceId,
|
||||
flags: {
|
||||
attention: candidate.flags ? rec(candidate.flags)?.attention === true : false,
|
||||
done: rec(candidate.flags)?.done === true,
|
||||
error: rec(candidate.flags)?.error === true,
|
||||
},
|
||||
usage: { ...EMPTY_USAGE, ...(rec(candidate.usage) ?? {}) } as SessionState["usage"],
|
||||
queue: arr(candidate.queue),
|
||||
todos: arr(candidate.todos),
|
||||
tasks: arr(candidate.tasks),
|
||||
batches: arr(candidate.batches),
|
||||
subagents: arr(candidate.subagents),
|
||||
attention: arr(candidate.attention),
|
||||
entries: arr(candidate.entries),
|
||||
};
|
||||
return state;
|
||||
}
|
||||
|
||||
/** Canonicalize a workspace/session summary from `workspace.query{kind:"sessions"}`. */
|
||||
export function normalizeSessionSummary(raw: unknown, workspaceId: string, existing?: SessionState): SessionState {
|
||||
const record = rec(raw) ?? {};
|
||||
const sessionId = str(record.sessionId ?? record.session_id ?? record.id) ?? existing?.sessionId ?? "";
|
||||
const base = existing ?? emptySessionState({ sessionId, workspaceId });
|
||||
|
||||
const rawStatus = str(record.status);
|
||||
let status: SessionState["status"] | undefined = rawStatus as SessionState["status"] | undefined;
|
||||
const flags = { ...base.flags };
|
||||
if (rawStatus === "attention") {
|
||||
status = "idle";
|
||||
flags.attention = true;
|
||||
} else if (rawStatus === "done") {
|
||||
status = "idle";
|
||||
flags.done = true;
|
||||
} else if (rawStatus === "error") {
|
||||
status = "idle";
|
||||
flags.error = true;
|
||||
} else if (rawStatus === "dormant") {
|
||||
status = "exited";
|
||||
}
|
||||
if (!status || !STATUSES.has(status)) status = base.status;
|
||||
|
||||
const rawFlags = rec(record.flags);
|
||||
const attentionCount = num(record.attentionCount);
|
||||
if (rawFlags) {
|
||||
flags.attention = rawFlags.attention === true;
|
||||
flags.done = rawFlags.done === true;
|
||||
flags.error = rawFlags.error === true;
|
||||
} else if (attentionCount && attentionCount > 0) {
|
||||
flags.attention = true;
|
||||
}
|
||||
|
||||
const thinkingValue = str(record.thinking);
|
||||
const hasQueue = Array.isArray(record.queue);
|
||||
return {
|
||||
...base,
|
||||
sessionId,
|
||||
workspaceId: str(record.workspaceId) ?? workspaceId,
|
||||
cwd: str(record.cwd) ?? base.cwd,
|
||||
name: record.name === null ? null : (str(record.name) ?? base.name),
|
||||
status,
|
||||
flags,
|
||||
model: record.model !== undefined ? normalizeModelRef(record.model) : base.model,
|
||||
thinking: thinkingValue && THINKING.has(thinkingValue) ? (thinkingValue as ThinkingLevel) : base.thinking,
|
||||
usage: record.usage !== undefined ? ({ ...EMPTY_USAGE, ...(rec(record.usage) ?? {}) } as SessionState["usage"]) : base.usage,
|
||||
contextUsage:
|
||||
record.contextUsage !== undefined
|
||||
? ((rec(record.contextUsage) as unknown as SessionState["contextUsage"]) ?? null)
|
||||
: base.contextUsage,
|
||||
queue: hasQueue ? arr(record.queue) : base.queue,
|
||||
todos: Array.isArray(record.todos) ? arr(record.todos) : base.todos,
|
||||
tasks: Array.isArray(record.tasks) ? arr(record.tasks) : base.tasks,
|
||||
batches: Array.isArray(record.batches) ? arr(record.batches) : base.batches,
|
||||
subagents: Array.isArray(record.subagents) ? arr(record.subagents) : base.subagents,
|
||||
attention: Array.isArray(record.attention) ? arr(record.attention) : base.attention,
|
||||
entries: Array.isArray(record.entries) ? arr<Entry>(record.entries) : base.entries,
|
||||
};
|
||||
}
|
||||
|
||||
/** Parse `{sessions:[...]}` (also bare arrays) into render states. */
|
||||
export function normalizeSessionsPayload(
|
||||
raw: unknown,
|
||||
workspaceId: string,
|
||||
existing: SessionState[] = [],
|
||||
): SessionState[] {
|
||||
const record = rec(raw);
|
||||
const list = Array.isArray(raw) ? raw : arr(record?.sessions ?? record?.items);
|
||||
const byId = new Map(existing.map((session) => [session.sessionId, session]));
|
||||
return list
|
||||
.map((entry) => normalizeSessionSummary(entry, workspaceId, byId.get(str(rec(entry)?.sessionId ?? rec(entry)?.id) ?? "")))
|
||||
.filter((session) => session.sessionId !== "");
|
||||
}
|
||||
|
||||
function attentionPending(state: SessionState): boolean {
|
||||
return state.flags.attention || state.attention.length > 0;
|
||||
}
|
||||
|
||||
/** `:PiSessions` status matrix → base.css dot class. */
|
||||
export function sessionDot(state: SessionState): DotStatus {
|
||||
if (attentionPending(state)) return "attention";
|
||||
if (state.status === "busy" || state.status === "starting") return "busy";
|
||||
if (state.status === "compacting") return "compacting";
|
||||
if (state.status === "interrupted") return "attention";
|
||||
if (state.status === "exited") return "exited";
|
||||
if (state.flags.error) return "err";
|
||||
if (state.flags.done) return "ok";
|
||||
return "idle";
|
||||
}
|
||||
|
||||
/** i18n key under `state.*` for the current session status. */
|
||||
export function sessionStatusKey(state: SessionState): string {
|
||||
if (attentionPending(state)) return "attention";
|
||||
if (state.status === "busy" || state.status === "starting") return "busy";
|
||||
if (state.status === "compacting") return "compacting";
|
||||
if (state.status === "interrupted") return "interrupted";
|
||||
if (state.status === "exited") return "exited";
|
||||
if (state.flags.error) return "error";
|
||||
if (state.flags.done) return "done";
|
||||
return "idle";
|
||||
}
|
||||
|
||||
/** Flatten a subagent tree into render rows with their indent depth. */
|
||||
export function flattenSubagents(
|
||||
list: SessionState["subagents"] | undefined,
|
||||
depth = 0,
|
||||
): { subagent: NonNullable<SessionState["subagents"]>[number]; depth: number }[] {
|
||||
const out: { subagent: NonNullable<SessionState["subagents"]>[number]; depth: number }[] = [];
|
||||
for (const subagent of list ?? []) {
|
||||
out.push({ subagent, depth });
|
||||
out.push(...flattenSubagents(subagent.children, depth + 1));
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
export function findSubagent(
|
||||
list: SessionState["subagents"] | undefined,
|
||||
predicate: (subagent: NonNullable<SessionState["subagents"]>[number]) => boolean,
|
||||
): NonNullable<SessionState["subagents"]>[number] | undefined {
|
||||
for (const subagent of list ?? []) {
|
||||
if (predicate(subagent)) return subagent;
|
||||
const found = findSubagent(subagent.children, predicate);
|
||||
if (found) return found;
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
export type { ProjectedEntry };
|
||||
@@ -0,0 +1,427 @@
|
||||
import type { SessionState, Subagent, WorkspaceInfo } from "@protocol/types";
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
import { Icon } from "@/components/icons";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { Empty } from "@/components/ui/empty";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { StatusDot, subagentDotClass } from "@/components/ui/status-dot";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { flattenSubagents, sessionDot, sessionStatusKey } from "./session-state";
|
||||
|
||||
export interface SessionTreeProps {
|
||||
sessions: SessionState[];
|
||||
workspaces?: WorkspaceInfo[];
|
||||
activeWorkspaceId?: string | null;
|
||||
selectedId?: string | null;
|
||||
filter: string;
|
||||
collapsed: Record<string, boolean>;
|
||||
connected?: boolean;
|
||||
creating?: boolean;
|
||||
onFilter: (value: string) => void;
|
||||
onToggleCollapse: (id: string) => void;
|
||||
onToggleAll: () => void;
|
||||
onSelectSession: (id: string) => void;
|
||||
onSelectWorkspace?: (id: string) => void;
|
||||
onNewSession: () => void;
|
||||
onRenameSession: (session: SessionState) => void;
|
||||
onCloseSession: (session: SessionState) => void;
|
||||
onOpenSubagent?: (session: SessionState, subagent: Subagent) => void;
|
||||
onRenameSubagent?: (subagent: Subagent) => void;
|
||||
onCloseDrawer?: () => void;
|
||||
className?: string;
|
||||
}
|
||||
|
||||
function sessionName(session: SessionState, fallback: string): string {
|
||||
return session.name?.trim() || fallback;
|
||||
}
|
||||
|
||||
function matchesFilter(session: SessionState, filter: string, fallback: string): boolean {
|
||||
if (!filter) return true;
|
||||
const needle = filter.toLowerCase();
|
||||
if (sessionName(session, fallback).toLowerCase().includes(needle)) return true;
|
||||
return flattenSubagents(session.subagents).some(({ subagent }) =>
|
||||
(subagent.name ?? "").toLowerCase().includes(needle),
|
||||
);
|
||||
}
|
||||
|
||||
function ChevronToggle({
|
||||
hasChildren,
|
||||
collapsed,
|
||||
onClick,
|
||||
}: {
|
||||
hasChildren: boolean;
|
||||
collapsed: boolean;
|
||||
onClick: () => void;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
className={cn("tree-toggle", hasChildren ? (collapsed ? undefined : "open") : "leaf")}
|
||||
aria-label={collapsed ? t("chat.unfold") : t("chat.fold")}
|
||||
aria-expanded={hasChildren ? !collapsed : undefined}
|
||||
tabIndex={hasChildren ? 0 : -1}
|
||||
onClick={(event) => {
|
||||
event.stopPropagation();
|
||||
if (hasChildren) onClick();
|
||||
}}
|
||||
>
|
||||
<Icon name="chevron-right" />
|
||||
</button>
|
||||
);
|
||||
}
|
||||
|
||||
function SubagentRow({
|
||||
session,
|
||||
subagent,
|
||||
collapsed,
|
||||
onToggleCollapse,
|
||||
onOpenSubagent,
|
||||
onRenameSubagent,
|
||||
}: {
|
||||
session: SessionState;
|
||||
subagent: Subagent;
|
||||
collapsed: Record<string, boolean>;
|
||||
onToggleCollapse: (id: string) => void;
|
||||
onOpenSubagent?: (session: SessionState, subagent: Subagent) => void;
|
||||
onRenameSubagent?: (subagent: Subagent) => void;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const children = subagent.children ?? [];
|
||||
const isCollapsed = collapsed[subagent.id] === true;
|
||||
const status = t(`state.${subagent.status}`);
|
||||
const name = subagent.name ?? subagent.id;
|
||||
return (
|
||||
<li>
|
||||
<div
|
||||
className="tree-row tree-row--sub"
|
||||
role="button"
|
||||
tabIndex={0}
|
||||
aria-label={name}
|
||||
onClick={() => onOpenSubagent?.(session, subagent)}
|
||||
onKeyDown={(event) => {
|
||||
if (event.key === "Enter" || event.key === " ") {
|
||||
event.preventDefault();
|
||||
onOpenSubagent?.(session, subagent);
|
||||
}
|
||||
}}
|
||||
>
|
||||
<ChevronToggle
|
||||
hasChildren={children.length > 0}
|
||||
collapsed={isCollapsed}
|
||||
onClick={() => onToggleCollapse(subagent.id)}
|
||||
/>
|
||||
<span className={cn("dot", subagentDotClass(subagent.status))} title={status} />
|
||||
<span className="t-main">
|
||||
<span className="t-name truncate">{name}</span>
|
||||
<span className="t-sub truncate muted">
|
||||
{subagent.model ?? "—"}
|
||||
{subagent.thinking ? ` · ${subagent.thinking}` : ""}
|
||||
</span>
|
||||
</span>
|
||||
<span className="t-actions">
|
||||
<button
|
||||
type="button"
|
||||
className="icon-btn"
|
||||
title={t("chat.preview")}
|
||||
aria-label={t("chat.previewSubagent")}
|
||||
onClick={(event) => {
|
||||
event.stopPropagation();
|
||||
onOpenSubagent?.(session, subagent);
|
||||
}}
|
||||
>
|
||||
<Icon name="eye" />
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className="icon-btn"
|
||||
title={t("chat.rename")}
|
||||
aria-label={t("chat.renameSubagentAria")}
|
||||
onClick={(event) => {
|
||||
event.stopPropagation();
|
||||
onRenameSubagent?.(subagent);
|
||||
}}
|
||||
>
|
||||
<Icon name="edit" />
|
||||
</button>
|
||||
</span>
|
||||
</div>
|
||||
{children.length && !isCollapsed ? (
|
||||
<ul>
|
||||
{children.map((child) => (
|
||||
<SubagentRow
|
||||
key={child.id}
|
||||
session={session}
|
||||
subagent={child}
|
||||
collapsed={collapsed}
|
||||
onToggleCollapse={onToggleCollapse}
|
||||
onOpenSubagent={onOpenSubagent}
|
||||
onRenameSubagent={onRenameSubagent}
|
||||
/>
|
||||
))}
|
||||
</ul>
|
||||
) : null}
|
||||
</li>
|
||||
);
|
||||
}
|
||||
|
||||
function SessionRow({
|
||||
session,
|
||||
selected,
|
||||
collapsed,
|
||||
onToggleCollapse,
|
||||
onSelectSession,
|
||||
onRenameSession,
|
||||
onCloseSession,
|
||||
onOpenSubagent,
|
||||
onRenameSubagent,
|
||||
}: {
|
||||
session: SessionState;
|
||||
selected: boolean;
|
||||
collapsed: Record<string, boolean>;
|
||||
onToggleCollapse: (id: string) => void;
|
||||
onSelectSession: (id: string) => void;
|
||||
onRenameSession: (session: SessionState) => void;
|
||||
onCloseSession: (session: SessionState) => void;
|
||||
onOpenSubagent?: (session: SessionState, subagent: Subagent) => void;
|
||||
onRenameSubagent?: (subagent: Subagent) => void;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const subagents = session.subagents ?? [];
|
||||
const isCollapsed = collapsed[session.sessionId] === true;
|
||||
const dot = sessionDot(session);
|
||||
const status = t(`state.${sessionStatusKey(session)}`);
|
||||
const name = sessionName(session, session.sessionId);
|
||||
return (
|
||||
<li>
|
||||
<div
|
||||
className={cn("tree-row", selected && "selected")}
|
||||
role="button"
|
||||
tabIndex={0}
|
||||
aria-label={name}
|
||||
aria-current={selected ? "true" : undefined}
|
||||
onClick={() => onSelectSession(session.sessionId)}
|
||||
onKeyDown={(event) => {
|
||||
if (event.key === "Enter" || event.key === " ") {
|
||||
event.preventDefault();
|
||||
onSelectSession(session.sessionId);
|
||||
}
|
||||
}}
|
||||
>
|
||||
<ChevronToggle
|
||||
hasChildren={subagents.length > 0}
|
||||
collapsed={isCollapsed}
|
||||
onClick={() => onToggleCollapse(session.sessionId)}
|
||||
/>
|
||||
<StatusDot status={dot} title={status} />
|
||||
<span className="t-main">
|
||||
<span className="t-name truncate">
|
||||
{name}
|
||||
{session.flags.attention && session.attention.length ? (
|
||||
<Badge tone="warn">{`!${session.attention.length}`}</Badge>
|
||||
) : null}
|
||||
</span>
|
||||
<span className="t-sub truncate muted">
|
||||
{session.model?.id ?? "—"}
|
||||
{session.thinking ? ` · ${session.thinking}` : ""}
|
||||
</span>
|
||||
</span>
|
||||
{subagents.length ? (
|
||||
<span className="t-meta" title={t("chat.subagentCount", { n: subagents.length })}>
|
||||
{`(${subagents.length})`}
|
||||
</span>
|
||||
) : null}
|
||||
<span className="t-actions">
|
||||
<button
|
||||
type="button"
|
||||
className="icon-btn"
|
||||
title={t("chat.rename")}
|
||||
aria-label={t("chat.renameSession")}
|
||||
onClick={(event) => {
|
||||
event.stopPropagation();
|
||||
onRenameSession(session);
|
||||
}}
|
||||
>
|
||||
<Icon name="edit" />
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className="icon-btn icon-btn--danger"
|
||||
title={t("chat.closeProcess")}
|
||||
aria-label={t("chat.closeProcess")}
|
||||
onClick={(event) => {
|
||||
event.stopPropagation();
|
||||
onCloseSession(session);
|
||||
}}
|
||||
>
|
||||
<Icon name="x" />
|
||||
</button>
|
||||
</span>
|
||||
</div>
|
||||
{subagents.length && !isCollapsed ? (
|
||||
<ul>
|
||||
{subagents.map((subagent) => (
|
||||
<SubagentRow
|
||||
key={subagent.id}
|
||||
session={session}
|
||||
subagent={subagent}
|
||||
collapsed={collapsed}
|
||||
onToggleCollapse={onToggleCollapse}
|
||||
onOpenSubagent={onOpenSubagent}
|
||||
onRenameSubagent={onRenameSubagent}
|
||||
/>
|
||||
))}
|
||||
</ul>
|
||||
) : null}
|
||||
</li>
|
||||
);
|
||||
}
|
||||
|
||||
/** Left sidebar: workspace picker + indent-only session/subagent tree. */
|
||||
export function SessionTree({
|
||||
sessions,
|
||||
workspaces = [],
|
||||
activeWorkspaceId,
|
||||
selectedId,
|
||||
filter,
|
||||
collapsed,
|
||||
connected = false,
|
||||
creating = false,
|
||||
onFilter,
|
||||
onToggleCollapse,
|
||||
onToggleAll,
|
||||
onSelectSession,
|
||||
onSelectWorkspace,
|
||||
onNewSession,
|
||||
onRenameSession,
|
||||
onCloseSession,
|
||||
onOpenSubagent,
|
||||
onRenameSubagent,
|
||||
onCloseDrawer,
|
||||
className,
|
||||
}: SessionTreeProps) {
|
||||
const { t } = useTranslation();
|
||||
const visible = sessions.filter((session) => matchesFilter(session, filter, session.sessionId));
|
||||
const allIds = sessions.flatMap((session) => [
|
||||
session.sessionId,
|
||||
...flattenSubagents(session.subagents).map(({ subagent }) => subagent.id),
|
||||
]);
|
||||
const anyOpen = allIds.some((id) => !collapsed[id]);
|
||||
const activeWorkspace = workspaces.find((workspace) => workspace.workspaceId === activeWorkspaceId);
|
||||
const workspaceLabel = activeWorkspace?.name ?? activeWorkspace?.cwd ?? t("chat.workspace");
|
||||
|
||||
return (
|
||||
<div className={cn("tree-pane__inner", className)} aria-label={t("chat.treeAria")}>
|
||||
<div className="pane-head">
|
||||
{workspaces.length ? (
|
||||
<div className="row">
|
||||
<select
|
||||
className="select tree-workspace"
|
||||
aria-label={t("chat.workspace")}
|
||||
value={activeWorkspaceId ?? ""}
|
||||
onChange={(event) => onSelectWorkspace?.(event.target.value)}
|
||||
title={activeWorkspace?.cwd ?? workspaceLabel}
|
||||
>
|
||||
{workspaces.map((workspace) => (
|
||||
<option key={workspace.workspaceId} value={workspace.workspaceId}>
|
||||
{workspace.name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
{onCloseDrawer ? (
|
||||
<button
|
||||
type="button"
|
||||
className="icon-btn tree-close"
|
||||
title={t("common.close")}
|
||||
aria-label={t("chat.closeTree")}
|
||||
onClick={onCloseDrawer}
|
||||
>
|
||||
<Icon name="x" />
|
||||
</button>
|
||||
) : null}
|
||||
</div>
|
||||
) : null}
|
||||
<div className="row">
|
||||
<Input
|
||||
type="search"
|
||||
className="tree-search"
|
||||
value={filter}
|
||||
placeholder={t("chat.search")}
|
||||
aria-label={t("chat.searchAria")}
|
||||
onChange={(event) => onFilter(event.target.value)}
|
||||
/>
|
||||
{onCloseDrawer && !workspaces.length ? (
|
||||
<button
|
||||
type="button"
|
||||
className="icon-btn tree-close"
|
||||
title={t("common.close")}
|
||||
aria-label={t("chat.closeTree")}
|
||||
onClick={onCloseDrawer}
|
||||
>
|
||||
<Icon name="x" />
|
||||
</button>
|
||||
) : null}
|
||||
</div>
|
||||
<div className="row">
|
||||
<button type="button" className="btn btn--sm" onClick={onNewSession} disabled={creating}>
|
||||
<Icon name="plus" />
|
||||
{t("chat.newSession")}
|
||||
</button>
|
||||
<div className="spacer" />
|
||||
<span className="tree-conn">
|
||||
<StatusDot status={connected ? "ok" : "exited"} />
|
||||
<span className="muted">{t(connected ? "state.online" : "state.offline")}</span>
|
||||
</span>
|
||||
<button
|
||||
type="button"
|
||||
className="icon-btn"
|
||||
title={t("chat.toggleAll")}
|
||||
aria-label={t("chat.toggleAllAria")}
|
||||
onClick={onToggleAll}
|
||||
>
|
||||
<Icon name={anyOpen ? "chevron-down" : "chevron-right"} />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<div className="pane-scroll">
|
||||
{visible.length ? (
|
||||
<ul className="tree">
|
||||
{visible.map((session) => (
|
||||
<SessionRow
|
||||
key={session.sessionId}
|
||||
session={session}
|
||||
selected={session.sessionId === selectedId}
|
||||
collapsed={collapsed}
|
||||
onToggleCollapse={onToggleCollapse}
|
||||
onSelectSession={onSelectSession}
|
||||
onRenameSession={onRenameSession}
|
||||
onCloseSession={onCloseSession}
|
||||
onOpenSubagent={onOpenSubagent}
|
||||
onRenameSubagent={onRenameSubagent}
|
||||
/>
|
||||
))}
|
||||
</ul>
|
||||
) : sessions.length ? (
|
||||
<Empty
|
||||
icon={<Icon name="search" />}
|
||||
title={t("chat.noMatch")}
|
||||
description={t("chat.tryOther")}
|
||||
/>
|
||||
) : (
|
||||
<Empty
|
||||
icon={<Icon name="chat" />}
|
||||
title={t("chat.noSessions")}
|
||||
description={t("chat.noSessionsText")}
|
||||
action={
|
||||
<button type="button" className="btn btn--sm" onClick={onNewSession} disabled={creating}>
|
||||
<Icon name="plus" />
|
||||
{t("chat.newSession")}
|
||||
</button>
|
||||
}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,258 @@
|
||||
import type { SessionState, Subagent, TaskItem } from "@protocol/types";
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
import { Icon } from "@/components/icons";
|
||||
import { Badge, type BadgeProps } from "@/components/ui/badge";
|
||||
import { Empty } from "@/components/ui/empty";
|
||||
import { Progress } from "@/components/ui/progress";
|
||||
import { Spinner } from "@/components/ui/spinner";
|
||||
import { StatusDot } from "@/components/ui/status-dot";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { TodoList } from "./blocks";
|
||||
import { formatDuration } from "./format";
|
||||
import { flattenSubagents } from "./session-state";
|
||||
import type { PanelTab } from "./store";
|
||||
|
||||
const SUB_BADGE: Record<string, { tone: BadgeProps["tone"]; label: string }> = {
|
||||
active: { tone: "info", label: "active" },
|
||||
completed: { tone: "ok", label: "completed" },
|
||||
failed: { tone: "err", label: "failed" },
|
||||
interrupted: { tone: "warn", label: "interrupted" },
|
||||
dormant: { tone: "default", label: "dormant" },
|
||||
};
|
||||
|
||||
function subagentStatus(status: Subagent["status"]) {
|
||||
return SUB_BADGE[status] ?? { tone: "default" as const, label: status };
|
||||
}
|
||||
|
||||
function taskDot(status: TaskItem["status"]): "busy" | "ok" | "err" | "idle" {
|
||||
if (status === "running") return "busy";
|
||||
if (status === "completed") return "ok";
|
||||
if (status === "failed") return "err";
|
||||
return "idle";
|
||||
}
|
||||
|
||||
export interface SidePanelProps {
|
||||
session: SessionState;
|
||||
tab: PanelTab;
|
||||
onTab: (tab: PanelTab) => void;
|
||||
onDispatch: () => void;
|
||||
onOpenSubagent: (subagent: Subagent) => void;
|
||||
onOpenTask: (task: TaskItem) => void;
|
||||
onStopTask: (task: TaskItem) => void;
|
||||
onCloseDrawer?: () => void;
|
||||
className?: string;
|
||||
}
|
||||
|
||||
/** Right panel: Subagents / Todo / Tasks (tabs + counts + empty states). */
|
||||
export function SidePanel({
|
||||
session,
|
||||
tab,
|
||||
onTab,
|
||||
onDispatch,
|
||||
onOpenSubagent,
|
||||
onOpenTask,
|
||||
onStopTask,
|
||||
onCloseDrawer,
|
||||
className,
|
||||
}: SidePanelProps) {
|
||||
const { t } = useTranslation();
|
||||
const subagents = flattenSubagents(session.subagents);
|
||||
const tasks = session.tasks;
|
||||
const tabs: { id: PanelTab; label: string; count: number }[] = [
|
||||
{ id: "subagents", label: t("chat.tabSubagents"), count: subagents.length },
|
||||
{ id: "todo", label: t("chat.tabTodo"), count: session.todos.length },
|
||||
{ id: "tasks", label: t("chat.tabTasks"), count: tasks.length },
|
||||
];
|
||||
|
||||
return (
|
||||
<div className={cn("panel-pane__inner", className)}>
|
||||
<div className="tabs panel-tabs" role="tablist" aria-label={t("chat.panel")}>
|
||||
{tabs.map((item) => (
|
||||
<button
|
||||
key={item.id}
|
||||
type="button"
|
||||
role="tab"
|
||||
aria-selected={tab === item.id}
|
||||
className={cn("tab", tab === item.id && "active")}
|
||||
onClick={() => onTab(item.id)}
|
||||
>
|
||||
{item.label}
|
||||
{item.count ? <span className="badge">{item.count}</span> : null}
|
||||
</button>
|
||||
))}
|
||||
<div className="spacer" />
|
||||
{onCloseDrawer ? (
|
||||
<button
|
||||
type="button"
|
||||
className="icon-btn panel-close"
|
||||
title={t("chat.closePanel")}
|
||||
aria-label={t("chat.closePanel")}
|
||||
onClick={onCloseDrawer}
|
||||
>
|
||||
<Icon name="x" />
|
||||
</button>
|
||||
) : null}
|
||||
</div>
|
||||
<div className="panel-scroll">
|
||||
<div className="panel__body stack">
|
||||
{tab === "subagents" ? (
|
||||
<>
|
||||
<div className="row">
|
||||
<span className="muted grow">
|
||||
{t("chat.currentSubagents", { n: subagents.length })}
|
||||
</span>
|
||||
<button type="button" className="btn btn--sm btn--primary" onClick={onDispatch}>
|
||||
<Icon name="plus" />
|
||||
{t("chat.dispatch")}
|
||||
</button>
|
||||
</div>
|
||||
{subagents.length ? (
|
||||
<div className="stack">
|
||||
{subagents.map(({ subagent, depth }) => {
|
||||
const badge = subagentStatus(subagent.status);
|
||||
return (
|
||||
<div
|
||||
key={subagent.id}
|
||||
className={cn("sub-item", depth > 0 && "sub-item--nested")}
|
||||
style={depth ? { marginLeft: `${depth * 16}px` } : undefined}
|
||||
role="button"
|
||||
tabIndex={0}
|
||||
onClick={() => onOpenSubagent(subagent)}
|
||||
onKeyDown={(event) => {
|
||||
if (event.key === "Enter" || event.key === " ") {
|
||||
event.preventDefault();
|
||||
onOpenSubagent(subagent);
|
||||
}
|
||||
}}
|
||||
>
|
||||
<span
|
||||
className={cn(
|
||||
"dot",
|
||||
subagent.status === "active"
|
||||
? "dot--busy"
|
||||
: subagent.status === "completed"
|
||||
? "dot--ok"
|
||||
: subagent.status === "failed"
|
||||
? "dot--err"
|
||||
: subagent.status === "interrupted"
|
||||
? "dot--attention"
|
||||
: "dot--exited",
|
||||
)}
|
||||
/>
|
||||
<span className="sub-item__main">
|
||||
<span className="sub-item__name truncate">
|
||||
{subagent.name ?? subagent.id}
|
||||
</span>
|
||||
<span className="sub-item__meta muted truncate">
|
||||
{subagent.model ?? "—"}
|
||||
{subagent.thinking ? ` · ${subagent.thinking}` : ""}
|
||||
</span>
|
||||
</span>
|
||||
<Badge tone={badge.tone}>{t(`state.${badge.label}`)}</Badge>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
) : (
|
||||
<Empty
|
||||
icon={<Icon name="branch" />}
|
||||
title={t("chat.noSubagents")}
|
||||
description={t("chat.noSubagentsText")}
|
||||
/>
|
||||
)}
|
||||
</>
|
||||
) : null}
|
||||
|
||||
{tab === "todo" ? (
|
||||
session.todos.length ? (
|
||||
<>
|
||||
<div className="row">
|
||||
<span className="muted grow">
|
||||
{t("chat.progress", {
|
||||
done: session.todos.filter((item) => item.status === "completed").length,
|
||||
total: session.todos.length,
|
||||
})}
|
||||
</span>
|
||||
<Badge>{t("common.readonly")}</Badge>
|
||||
</div>
|
||||
<Progress
|
||||
value={session.todos.filter((item) => item.status === "completed").length}
|
||||
max={session.todos.length || 1}
|
||||
/>
|
||||
<TodoList items={session.todos} idPrefix="panel-todo" />
|
||||
<div className="muted panel__note">{t("chat.todoNote")}</div>
|
||||
</>
|
||||
) : (
|
||||
<Empty
|
||||
icon={<Icon name="todo" />}
|
||||
title={t("chat.noTodo")}
|
||||
description={t("chat.noTodoText")}
|
||||
/>
|
||||
)
|
||||
) : null}
|
||||
|
||||
{tab === "tasks" ? (
|
||||
tasks.length ? (
|
||||
tasks.map((task) => {
|
||||
const running = task.status === "running";
|
||||
const duration = running ? Date.now() - task.startTime : (task.durationMs ?? 0);
|
||||
return (
|
||||
<div
|
||||
key={task.id}
|
||||
className="task-item"
|
||||
role="button"
|
||||
tabIndex={0}
|
||||
onClick={() => onOpenTask(task)}
|
||||
onKeyDown={(event) => {
|
||||
if (event.key === "Enter" || event.key === " ") {
|
||||
event.preventDefault();
|
||||
onOpenTask(task);
|
||||
}
|
||||
}}
|
||||
>
|
||||
<StatusDot status={taskDot(task.status)} />
|
||||
<span className="grow">
|
||||
<span className="task-item__cmd mono truncate" title={task.command}>
|
||||
{task.command}
|
||||
</span>
|
||||
<span className="task-item__meta muted">
|
||||
{running ? <Spinner /> : null}
|
||||
<span>{formatDuration(duration)}</span>
|
||||
{task.exitCode != null ? (
|
||||
<Badge tone={task.exitCode === 0 ? "ok" : "err"}>
|
||||
{`exit ${task.exitCode}`}
|
||||
</Badge>
|
||||
) : (
|
||||
<span>{t(`state.${task.status}`)}</span>
|
||||
)}
|
||||
</span>
|
||||
</span>
|
||||
{running ? (
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn--sm btn--danger"
|
||||
onClick={(event) => {
|
||||
event.stopPropagation();
|
||||
onStopTask(task);
|
||||
}}
|
||||
>
|
||||
{t("common.stop")}
|
||||
</button>
|
||||
) : null}
|
||||
</div>
|
||||
);
|
||||
})
|
||||
) : (
|
||||
<Empty
|
||||
icon={<Icon name="terminal" />}
|
||||
title={t("chat.noTasks")}
|
||||
description={t("chat.noTasksText")}
|
||||
/>
|
||||
)
|
||||
) : null}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,190 @@
|
||||
import type { TaskItem } from "@protocol/types";
|
||||
import { create } from "zustand";
|
||||
|
||||
import type { EntriesCursor, ProjectedEntry } from "@/lib/entry-projection";
|
||||
import { prependUnique } from "@/lib/entry-projection";
|
||||
|
||||
export type PanelTab = "subagents" | "todo" | "tasks";
|
||||
|
||||
export interface Attachment {
|
||||
id: string;
|
||||
name: string;
|
||||
mimeType: string;
|
||||
/** Base64 payload (no data: prefix), ready for `prompt.send {images}`. */
|
||||
data: string;
|
||||
/** Data URL for the preview thumbnail. */
|
||||
preview: string;
|
||||
}
|
||||
|
||||
export interface HistoryState {
|
||||
entries: ProjectedEntry[];
|
||||
cursor: EntriesCursor | null;
|
||||
loaded: boolean;
|
||||
loadingInitial: boolean;
|
||||
loadingOlder: boolean;
|
||||
error: string | null;
|
||||
/** Incremented by `resync_required`; the history hook reloads when it changes. */
|
||||
resyncToken: number;
|
||||
}
|
||||
|
||||
export const EMPTY_HISTORY: HistoryState = {
|
||||
entries: [],
|
||||
cursor: null,
|
||||
loaded: false,
|
||||
loadingInitial: false,
|
||||
loadingOlder: false,
|
||||
error: null,
|
||||
resyncToken: 0,
|
||||
};
|
||||
|
||||
export interface PreviewTarget {
|
||||
sessionId: string;
|
||||
subagentId: string;
|
||||
}
|
||||
|
||||
export interface ChatStore {
|
||||
history: Record<string, HistoryState>;
|
||||
tab: PanelTab;
|
||||
filter: string;
|
||||
collapsed: Record<string, boolean>;
|
||||
treeOpen: boolean;
|
||||
panelOpen: boolean;
|
||||
treeCollapsed: boolean;
|
||||
treeWidth: number;
|
||||
panelWidth: number;
|
||||
sending: { sessionId: string; text: string } | null;
|
||||
attachments: Attachment[];
|
||||
preview: PreviewTarget | null;
|
||||
taskOutput: TaskItem | null;
|
||||
dispatchOpen: boolean;
|
||||
|
||||
setTab: (tab: PanelTab) => void;
|
||||
setFilter: (filter: string) => void;
|
||||
toggleCollapsed: (id: string) => void;
|
||||
setAllCollapsed: (ids: string[], collapsed: boolean) => void;
|
||||
setTreeOpen: (open: boolean) => void;
|
||||
setPanelOpen: (open: boolean) => void;
|
||||
setTreeCollapsed: (collapsed: boolean) => void;
|
||||
setWidths: (widths: { treeWidth?: number; panelWidth?: number }) => void;
|
||||
closeDrawers: () => void;
|
||||
|
||||
setSending: (sending: { sessionId: string; text: string } | null) => void;
|
||||
addAttachment: (attachment: Attachment) => void;
|
||||
removeAttachment: (id: string) => void;
|
||||
clearAttachments: () => void;
|
||||
setPreview: (preview: PreviewTarget | null) => void;
|
||||
setTaskOutput: (task: TaskItem | null) => void;
|
||||
setDispatchOpen: (open: boolean) => void;
|
||||
|
||||
beginInitial: (sessionId: string) => void;
|
||||
beginOlder: (sessionId: string) => void;
|
||||
receiveInitial: (sessionId: string, entries: ProjectedEntry[], cursor: EntriesCursor) => void;
|
||||
receiveOlder: (sessionId: string, entries: ProjectedEntry[], cursor: EntriesCursor) => void;
|
||||
historyError: (sessionId: string, error: string) => void;
|
||||
bumpResync: (sessionId: string) => void;
|
||||
clearHistory: (sessionId: string) => void;
|
||||
}
|
||||
|
||||
function updateHistory(
|
||||
state: ChatStore,
|
||||
sessionId: string,
|
||||
patch: Partial<HistoryState>,
|
||||
): Pick<ChatStore, "history"> {
|
||||
const current = state.history[sessionId] ?? EMPTY_HISTORY;
|
||||
return { history: { ...state.history, [sessionId]: { ...current, ...patch } } };
|
||||
}
|
||||
|
||||
export const useChatStore = create<ChatStore>((set) => ({
|
||||
history: {},
|
||||
tab: "subagents",
|
||||
filter: "",
|
||||
collapsed: {},
|
||||
treeOpen: false,
|
||||
panelOpen: false,
|
||||
treeCollapsed: false,
|
||||
treeWidth: 300,
|
||||
panelWidth: 340,
|
||||
sending: null,
|
||||
attachments: [],
|
||||
preview: null,
|
||||
taskOutput: null,
|
||||
dispatchOpen: false,
|
||||
|
||||
setTab: (tab) => set({ tab }),
|
||||
setFilter: (filter) => set({ filter }),
|
||||
toggleCollapsed: (id) =>
|
||||
set((state) => {
|
||||
const collapsed = { ...state.collapsed };
|
||||
if (collapsed[id]) delete collapsed[id];
|
||||
else collapsed[id] = true;
|
||||
return { collapsed };
|
||||
}),
|
||||
setAllCollapsed: (ids, collapsed) =>
|
||||
set(() => ({ collapsed: collapsed ? Object.fromEntries(ids.map((id) => [id, true])) : {} })),
|
||||
setTreeOpen: (treeOpen) => set({ treeOpen }),
|
||||
setPanelOpen: (panelOpen) => set({ panelOpen }),
|
||||
setTreeCollapsed: (treeCollapsed) => set({ treeCollapsed }),
|
||||
setWidths: (widths) => set(widths),
|
||||
closeDrawers: () => set({ treeOpen: false, panelOpen: false }),
|
||||
|
||||
setSending: (sending) => set({ sending }),
|
||||
addAttachment: (attachment) => set((state) => ({ attachments: [...state.attachments, attachment] })),
|
||||
removeAttachment: (id) => set((state) => ({ attachments: state.attachments.filter((item) => item.id !== id) })),
|
||||
clearAttachments: () => set({ attachments: [] }),
|
||||
setPreview: (preview) => set({ preview }),
|
||||
setTaskOutput: (taskOutput) => set({ taskOutput }),
|
||||
setDispatchOpen: (dispatchOpen) => set({ dispatchOpen }),
|
||||
|
||||
beginInitial: (sessionId) =>
|
||||
set((state) => updateHistory(state, sessionId, { loadingInitial: true, error: null })),
|
||||
beginOlder: (sessionId) =>
|
||||
set((state) => updateHistory(state, sessionId, { loadingOlder: true, error: null })),
|
||||
receiveInitial: (sessionId, entries, cursor) =>
|
||||
set((state) => {
|
||||
const current = state.history[sessionId] ?? EMPTY_HISTORY;
|
||||
return updateHistory(state, sessionId, {
|
||||
entries: entries.length || !current.entries.length ? entries : current.entries,
|
||||
cursor,
|
||||
loaded: true,
|
||||
loadingInitial: false,
|
||||
loadingOlder: false,
|
||||
error: null,
|
||||
resyncToken: current.resyncToken,
|
||||
});
|
||||
}),
|
||||
receiveOlder: (sessionId, entries, cursor) =>
|
||||
set((state) => {
|
||||
const current = state.history[sessionId] ?? EMPTY_HISTORY;
|
||||
return updateHistory(state, sessionId, {
|
||||
entries: prependUnique(current.entries, entries) as ProjectedEntry[],
|
||||
cursor,
|
||||
loadingOlder: false,
|
||||
error: null,
|
||||
});
|
||||
}),
|
||||
historyError: (sessionId, error) =>
|
||||
set((state) =>
|
||||
updateHistory(state, sessionId, {
|
||||
loadingInitial: false,
|
||||
loadingOlder: false,
|
||||
error,
|
||||
}),
|
||||
),
|
||||
bumpResync: (sessionId) =>
|
||||
set((state) => {
|
||||
const current = state.history[sessionId] ?? EMPTY_HISTORY;
|
||||
return updateHistory(state, sessionId, {
|
||||
loaded: false,
|
||||
loadingInitial: false,
|
||||
loadingOlder: false,
|
||||
error: null,
|
||||
resyncToken: current.resyncToken + 1,
|
||||
});
|
||||
}),
|
||||
clearHistory: (sessionId) =>
|
||||
set((state) => {
|
||||
const history = { ...state.history };
|
||||
delete history[sessionId];
|
||||
return { history };
|
||||
}),
|
||||
}));
|
||||
@@ -0,0 +1,191 @@
|
||||
import { useId, useRef, useState, type RefObject } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
import { Icon } from "@/components/icons";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Field, Input } from "@/components/ui/input";
|
||||
import { toast } from "@/components/ui/toast";
|
||||
import { ApiError, errorI18nKey } from "@/lib/api";
|
||||
|
||||
import { parseEndpoint } from "./pairing";
|
||||
|
||||
export interface ManualConnectInput {
|
||||
endpoint: string;
|
||||
code: string;
|
||||
deviceName: string;
|
||||
}
|
||||
|
||||
export interface ManualConnectFormProps {
|
||||
onConnect: (input: ManualConnectInput) => Promise<void>;
|
||||
hostInputRef: RefObject<HTMLInputElement | null>;
|
||||
defaultDeviceName: string;
|
||||
}
|
||||
|
||||
function errorMessage(error: unknown, fallback: string): string {
|
||||
if (error instanceof ApiError) return errorI18nKey(error.code);
|
||||
return fallback;
|
||||
}
|
||||
|
||||
/** Inline manual pairing form: host/port, token-or-code, optional device name. */
|
||||
export function ManualConnectForm({ onConnect, hostInputRef, defaultDeviceName }: ManualConnectFormProps) {
|
||||
const { t } = useTranslation();
|
||||
const id = useId();
|
||||
const [host, setHost] = useState("");
|
||||
const [port, setPort] = useState("4321");
|
||||
const [code, setCode] = useState("");
|
||||
const [deviceName, setDeviceName] = useState("");
|
||||
const [showCode, setShowCode] = useState(false);
|
||||
const [hostError, setHostError] = useState<string | null>(null);
|
||||
const [portError, setPortError] = useState<string | null>(null);
|
||||
const [codeError, setCodeError] = useState<string | null>(null);
|
||||
const [formError, setFormError] = useState<string | null>(null);
|
||||
const [busy, setBusy] = useState(false);
|
||||
const submitting = useRef(false);
|
||||
|
||||
async function submit(event: React.FormEvent<HTMLFormElement>) {
|
||||
event.preventDefault();
|
||||
if (busy || submitting.current) return;
|
||||
setHostError(null);
|
||||
setPortError(null);
|
||||
setCodeError(null);
|
||||
setFormError(null);
|
||||
|
||||
const parsed = parseEndpoint(host, port);
|
||||
if ("error" in parsed) {
|
||||
if (parsed.error === "host") {
|
||||
setHostError(t("connect.hostRequired"));
|
||||
hostInputRef.current?.focus();
|
||||
return;
|
||||
}
|
||||
if (parsed.error === "port") {
|
||||
setPortError(t("connect.portInvalid"));
|
||||
return;
|
||||
}
|
||||
const message = t("connect.failed");
|
||||
setFormError(message);
|
||||
toast.error(message);
|
||||
return;
|
||||
}
|
||||
if (!code.trim()) {
|
||||
setCodeError(t("connect.tokenRequired"));
|
||||
return;
|
||||
}
|
||||
|
||||
submitting.current = true;
|
||||
setBusy(true);
|
||||
try {
|
||||
await onConnect({
|
||||
endpoint: parsed.endpoint,
|
||||
code: code.trim(),
|
||||
deviceName: deviceName.trim() || defaultDeviceName,
|
||||
});
|
||||
} catch (error) {
|
||||
const message = t(errorMessage(error, "connect.failed"));
|
||||
setFormError(message);
|
||||
toast.error(message);
|
||||
} finally {
|
||||
submitting.current = false;
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<section className="card cn-card">
|
||||
<h2 className="cn-card__title">
|
||||
<span className="cn-ico">
|
||||
<Icon name="server" />
|
||||
</span>
|
||||
{t("connect.addTitle")}
|
||||
</h2>
|
||||
<form className="cn-form" noValidate onSubmit={(event) => void submit(event)}>
|
||||
<div className="cn-row">
|
||||
<Field label={t("connect.host")} htmlFor={`${id}-host`} error={hostError}>
|
||||
<Input
|
||||
ref={hostInputRef}
|
||||
id={`${id}-host`}
|
||||
type="text"
|
||||
inputMode="url"
|
||||
autoCapitalize="off"
|
||||
autoComplete="off"
|
||||
spellCheck={false}
|
||||
placeholder={t("connect.hostPlaceholder")}
|
||||
value={host}
|
||||
onChange={(event) => {
|
||||
setHost(event.target.value);
|
||||
setHostError(null);
|
||||
}}
|
||||
/>
|
||||
</Field>
|
||||
<Field label={t("connect.port")} htmlFor={`${id}-port`} error={portError}>
|
||||
<Input
|
||||
id={`${id}-port`}
|
||||
type="text"
|
||||
inputMode="numeric"
|
||||
autoComplete="off"
|
||||
placeholder="4321"
|
||||
value={port}
|
||||
onChange={(event) => {
|
||||
setPort(event.target.value);
|
||||
setPortError(null);
|
||||
}}
|
||||
/>
|
||||
</Field>
|
||||
</div>
|
||||
|
||||
<Field label={t("connect.token")} htmlFor={`${id}-token`} hint={t("connect.tokenHint")} error={codeError}>
|
||||
<div className="cn-token">
|
||||
<Input
|
||||
id={`${id}-token`}
|
||||
type={showCode ? "text" : "password"}
|
||||
autoComplete="current-password"
|
||||
placeholder={t("connect.tokenPlaceholder")}
|
||||
value={code}
|
||||
onChange={(event) => {
|
||||
setCode(event.target.value);
|
||||
setCodeError(null);
|
||||
}}
|
||||
/>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className={showCode ? "cn-eye is-on" : "cn-eye"}
|
||||
aria-pressed={showCode}
|
||||
aria-label={t("connect.token")}
|
||||
title={t("connect.token")}
|
||||
onClick={() => setShowCode((value) => !value)}
|
||||
>
|
||||
<Icon name="eye" />
|
||||
</Button>
|
||||
</div>
|
||||
</Field>
|
||||
|
||||
<Field label={t("connect.deviceName")} htmlFor={`${id}-device`} hint={t("common.optional")}>
|
||||
<Input
|
||||
id={`${id}-device`}
|
||||
type="text"
|
||||
autoComplete="nickname"
|
||||
placeholder={t("connect.deviceNamePlaceholder")}
|
||||
value={deviceName}
|
||||
onChange={(event) => setDeviceName(event.target.value)}
|
||||
/>
|
||||
</Field>
|
||||
|
||||
{formError ? (
|
||||
<div className="cn-error" role="alert">
|
||||
<span className="cn-ico">
|
||||
<Icon name="alert" />
|
||||
</span>
|
||||
<span>{formError}</span>
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
<div className="cn-form__foot">
|
||||
<Button variant="primary" type="submit" className="cn-submit" disabled={busy}>
|
||||
<Icon name={busy ? "refresh" : "chevron-right"} />
|
||||
{busy ? t("connect.connecting") : t("connect.connect")}
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,289 @@
|
||||
import { ApiError, apiRequest, type InfoResponse } from "@/lib/api";
|
||||
|
||||
export const PAIR_META_KEY = "pi2-pair-meta";
|
||||
export const PAIR_SCOPES = ["read", "steer", "apply"] as const;
|
||||
|
||||
export type DeviceKind = "phone" | "laptop" | "tablet";
|
||||
|
||||
export interface PairMeta {
|
||||
scopes: string[];
|
||||
deviceName?: string;
|
||||
kind?: DeviceKind;
|
||||
server?: Partial<InfoResponse> & { name?: string; hostname?: string; version?: string; pluginVersion?: string };
|
||||
pairedAt?: number;
|
||||
}
|
||||
|
||||
export interface PairTarget {
|
||||
endpoint: string;
|
||||
code: string;
|
||||
name: string;
|
||||
hostname: string;
|
||||
port: number;
|
||||
}
|
||||
|
||||
export interface RedeemResult {
|
||||
token: string;
|
||||
scopes: string[];
|
||||
deviceId?: string;
|
||||
server?: PairMeta["server"];
|
||||
raw: unknown;
|
||||
}
|
||||
|
||||
export interface ParsedEndpoint {
|
||||
endpoint: string;
|
||||
hostname: string;
|
||||
port: number;
|
||||
protocol: "http" | "https";
|
||||
}
|
||||
|
||||
function asRecord(value: unknown): Record<string, unknown> | undefined {
|
||||
return value && typeof value === "object" ? (value as Record<string, unknown>) : undefined;
|
||||
}
|
||||
|
||||
function firstString(...values: unknown[]): string | undefined {
|
||||
for (const value of values) {
|
||||
if (typeof value === "string" && value.trim()) return value.trim();
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
function stringList(value: unknown): string[] {
|
||||
return Array.isArray(value) ? value.filter((item): item is string => typeof item === "string") : [];
|
||||
}
|
||||
|
||||
/**
|
||||
* Accepts `host`, `host:port` and `http(s)://host[:port][/path]`.
|
||||
* A non-http scheme (e.g. a pi2:// pairing link pasted into the host field)
|
||||
* is rejected so the caller can show the failure rail.
|
||||
*/
|
||||
export function parseEndpoint(hostRaw: string, portRaw: string): ParsedEndpoint | { error: "host" | "port" | "scheme" } {
|
||||
const raw = String(hostRaw || "").trim().replace(/\/+$/, "");
|
||||
if (!raw) return { error: "host" };
|
||||
|
||||
const scheme = /^([a-z][a-z0-9+.-]*):\/\//i.exec(raw);
|
||||
let hostname: string;
|
||||
let portText: string;
|
||||
let protocol: "http" | "https" = "http";
|
||||
|
||||
if (scheme) {
|
||||
const name = (scheme[1] ?? "").toLowerCase();
|
||||
if (name !== "http" && name !== "https") return { error: "scheme" };
|
||||
let url: URL;
|
||||
try {
|
||||
url = new URL(raw);
|
||||
} catch {
|
||||
return { error: "host" };
|
||||
}
|
||||
hostname = url.hostname;
|
||||
portText = url.port || String(portRaw || "").trim();
|
||||
protocol = name;
|
||||
} else {
|
||||
const match = /^([^/\s?#:]+)(?::(\d+))?$/.exec(raw);
|
||||
if (!match) return { error: "host" };
|
||||
hostname = match[1] ?? "";
|
||||
portText = match[2] || String(portRaw || "").trim();
|
||||
}
|
||||
|
||||
if (!hostname) return { error: "host" };
|
||||
if (!/^\d+$/.test(portText)) return { error: "port" };
|
||||
const port = Number(portText);
|
||||
if (!(port >= 1 && port <= 65535)) return { error: "port" };
|
||||
return { endpoint: `${protocol}://${hostname}:${port}`, hostname, port, protocol };
|
||||
}
|
||||
|
||||
function endpointFrom(value: string | null | undefined): ParsedEndpoint | null {
|
||||
if (!value) return null;
|
||||
try {
|
||||
const url = new URL(value);
|
||||
const protocol = url.protocol === "https:" ? "https" : "http";
|
||||
const port = url.port ? Number(url.port) : protocol === "https" ? 443 : 80;
|
||||
if (!url.hostname) return null;
|
||||
return { endpoint: `${protocol}://${url.hostname}:${port}`, hostname: url.hostname, port, protocol };
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse the QR payload. Supported forms:
|
||||
* `https://host:port/#pair=CODE`
|
||||
* `#pair=CODE` (resolved against the current/typed endpoint)
|
||||
* `pi2://pair?host=…&port=…&code=…` (design prototype compatibility)
|
||||
*/
|
||||
export function parsePairLink(raw: string, fallbackEndpoint?: string | null): PairTarget | null {
|
||||
const text = String(raw || "").trim();
|
||||
if (!text) return null;
|
||||
|
||||
if (/^pi2:\/\/pair\b/i.test(text)) {
|
||||
let url: URL;
|
||||
try {
|
||||
url = new URL(text);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
if (url.protocol !== "pi2:") return null;
|
||||
const params = url.searchParams;
|
||||
const hostname = (params.get("host") || "").trim();
|
||||
if (!hostname) return null;
|
||||
const portNum = Number(params.get("port"));
|
||||
const port = Number.isInteger(portNum) && portNum >= 1 && portNum <= 65535 ? portNum : 4321;
|
||||
const protocol = (params.get("proto") || "").toLowerCase() === "https" ? "https" : "http";
|
||||
const code = (params.get("code") || params.get("token") || "").trim();
|
||||
if (!code) return null;
|
||||
return {
|
||||
endpoint: `${protocol}://${hostname}:${port}`,
|
||||
code,
|
||||
name: params.get("name") || hostname,
|
||||
hostname,
|
||||
port,
|
||||
};
|
||||
}
|
||||
|
||||
let url: URL;
|
||||
try {
|
||||
const base =
|
||||
endpointFrom(fallbackEndpoint)?.endpoint ||
|
||||
(typeof window !== "undefined" ? window.location.origin : "http://localhost");
|
||||
url = new URL(text, base);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
|
||||
const hash = new URLSearchParams(url.hash.replace(/^#/, ""));
|
||||
const code = (hash.get("pair") || hash.get("code") || url.searchParams.get("pair") || "").trim();
|
||||
if (!code) return null;
|
||||
|
||||
const base = endpointFrom(fallbackEndpoint) ?? endpointFrom(url.origin);
|
||||
if (!base) return null;
|
||||
const isAbsolute = /^https?:\/\//i.test(text);
|
||||
const endpoint = isAbsolute ? endpointFrom(url.origin) : base;
|
||||
if (!endpoint) return null;
|
||||
|
||||
return {
|
||||
endpoint: endpoint.endpoint,
|
||||
code,
|
||||
name: hash.get("name") || url.searchParams.get("name") || endpoint.hostname,
|
||||
hostname: endpoint.hostname,
|
||||
port: endpoint.port,
|
||||
};
|
||||
}
|
||||
|
||||
export function maskSecret(value: string): string {
|
||||
const text = String(value || "");
|
||||
if (!text) return "—";
|
||||
if (text.includes("…")) return text;
|
||||
if (text.length <= 8) return `…${text.slice(-3)}`;
|
||||
return `${text.slice(0, 7)}…${text.slice(-4)}`;
|
||||
}
|
||||
|
||||
export function detectDeviceKind(): DeviceKind {
|
||||
if (typeof navigator === "undefined") return "laptop";
|
||||
const ua = navigator.userAgent || "";
|
||||
if (/iPad|Tablet|PlayBook|Silk/i.test(ua)) return "tablet";
|
||||
if (/Mobi|Android|iPhone/i.test(ua)) return "phone";
|
||||
return "laptop";
|
||||
}
|
||||
|
||||
/** POST /api/v1/cmd pair.redeem against the selected origin. */
|
||||
export async function redeemPairing(input: {
|
||||
endpoint: string;
|
||||
code: string;
|
||||
deviceName: string;
|
||||
kind?: DeviceKind;
|
||||
signal?: AbortSignal;
|
||||
}): Promise<RedeemResult> {
|
||||
const endpoint = input.endpoint.replace(/\/+$/, "");
|
||||
const response = await apiRequest<Record<string, unknown>>("/api/v1/cmd", {
|
||||
method: "POST",
|
||||
baseUrl: endpoint,
|
||||
body: {
|
||||
method: "pair.redeem",
|
||||
params: {
|
||||
code: input.code,
|
||||
deviceName: input.deviceName,
|
||||
kind: input.kind ?? detectDeviceKind(),
|
||||
},
|
||||
},
|
||||
signal: input.signal,
|
||||
});
|
||||
|
||||
const payload = asRecord(response.payload);
|
||||
const result = asRecord(response.result);
|
||||
const device = asRecord(response.device);
|
||||
const token = firstString(response.token, response.deviceToken, payload?.token, result?.token, device?.token);
|
||||
if (!token) {
|
||||
throw new ApiError({
|
||||
code: "E_UNAUTHORIZED",
|
||||
message: "pair.redeem returned no device token",
|
||||
status: 401,
|
||||
});
|
||||
}
|
||||
|
||||
const server = asRecord(response.server) as PairMeta["server"] | undefined;
|
||||
return {
|
||||
token,
|
||||
scopes: stringList(response.scopes).length
|
||||
? stringList(response.scopes)
|
||||
: stringList(result?.scopes).length
|
||||
? stringList(result?.scopes)
|
||||
: ["read"],
|
||||
deviceId: firstString(response.deviceId, result?.deviceId, device?.deviceId),
|
||||
server,
|
||||
raw: response,
|
||||
};
|
||||
}
|
||||
|
||||
export function readPairMeta(): PairMeta | null {
|
||||
try {
|
||||
const raw = localStorage.getItem(PAIR_META_KEY);
|
||||
if (!raw) return null;
|
||||
const parsed: unknown = JSON.parse(raw);
|
||||
const record = asRecord(parsed);
|
||||
if (!record) return null;
|
||||
return {
|
||||
scopes: stringList(record.scopes),
|
||||
deviceName: typeof record.deviceName === "string" ? record.deviceName : undefined,
|
||||
kind: record.kind === "phone" || record.kind === "laptop" || record.kind === "tablet" ? record.kind : undefined,
|
||||
server: asRecord(record.server) as PairMeta["server"] | undefined,
|
||||
pairedAt: typeof record.pairedAt === "number" ? record.pairedAt : undefined,
|
||||
};
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export function writePairMeta(meta: PairMeta): void {
|
||||
try {
|
||||
localStorage.setItem(PAIR_META_KEY, JSON.stringify(meta));
|
||||
} catch {
|
||||
/* private mode */
|
||||
}
|
||||
}
|
||||
|
||||
export function clearPairMeta(): void {
|
||||
try {
|
||||
localStorage.removeItem(PAIR_META_KEY);
|
||||
} catch {
|
||||
/* private mode */
|
||||
}
|
||||
}
|
||||
|
||||
/** The connection redirect may target only the three navigation pages. */
|
||||
export function safePairNext(raw: string | null | undefined): string {
|
||||
if (!raw) return "/workspaces";
|
||||
try {
|
||||
const url = new URL(String(raw), "http://pi2.local");
|
||||
if (url.pathname === "/workspaces" || url.pathname === "/chat" || url.pathname === "/status") {
|
||||
return `${url.pathname}${url.search}`;
|
||||
}
|
||||
} catch {
|
||||
/* fall through */
|
||||
}
|
||||
return "/workspaces";
|
||||
}
|
||||
|
||||
export function scopesForIdentity(meta: PairMeta | null, info: InfoResponse | null | undefined): string[] {
|
||||
if (meta?.scopes.length) return meta.scopes;
|
||||
const capabilities = Array.isArray(info?.capabilities) ? info.capabilities : [];
|
||||
return capabilities.filter((capability) => (PAIR_SCOPES as readonly string[]).includes(capability));
|
||||
}
|
||||
@@ -0,0 +1,252 @@
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
import { Icon } from "@/components/icons";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Modal } from "@/components/ui/dialog";
|
||||
import { Input } from "@/components/ui/input";
|
||||
|
||||
import { parsePairLink, type PairTarget } from "./pairing";
|
||||
|
||||
interface DetectedBarcode {
|
||||
rawValue?: string;
|
||||
}
|
||||
|
||||
interface BarcodeDetectorLike {
|
||||
detect(source: CanvasImageSource): Promise<DetectedBarcode[]>;
|
||||
}
|
||||
|
||||
type BarcodeDetectorCtor = new (options?: { formats?: string[] }) => BarcodeDetectorLike;
|
||||
|
||||
function barcodeDetectorCtor(): BarcodeDetectorCtor | undefined {
|
||||
return (window as unknown as { BarcodeDetector?: BarcodeDetectorCtor }).BarcodeDetector;
|
||||
}
|
||||
|
||||
export interface ScanDialogProps {
|
||||
open: boolean;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
onFound: (target: PairTarget) => void;
|
||||
fallbackEndpoint?: string | null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Camera preview + BarcodeDetector loop, with the design's paste-link fallback
|
||||
* whenever the browser, permission or secure context cannot scan.
|
||||
*/
|
||||
export function ScanDialog({ open, onOpenChange, onFound, fallbackEndpoint }: ScanDialogProps) {
|
||||
const { t } = useTranslation();
|
||||
const [attempt, setAttempt] = useState(0);
|
||||
const [live, setLive] = useState(false);
|
||||
const [status, setStatus] = useState("");
|
||||
const [pasteOpen, setPasteOpen] = useState(false);
|
||||
const [paste, setPaste] = useState("");
|
||||
const [pasteInvalid, setPasteInvalid] = useState(false);
|
||||
|
||||
const videoRef = useRef<HTMLVideoElement | null>(null);
|
||||
const streamRef = useRef<MediaStream | null>(null);
|
||||
const detectorRef = useRef<BarcodeDetectorLike | null>(null);
|
||||
const timerRef = useRef<ReturnType<typeof setInterval> | null>(null);
|
||||
const finishingRef = useRef(false);
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) return;
|
||||
let cancelled = false;
|
||||
finishingRef.current = false;
|
||||
setPasteOpen(false);
|
||||
setPasteInvalid(false);
|
||||
setStatus(t("connect.startingCamera"));
|
||||
|
||||
function stopCamera() {
|
||||
if (timerRef.current) {
|
||||
clearInterval(timerRef.current);
|
||||
timerRef.current = null;
|
||||
}
|
||||
const stream = streamRef.current;
|
||||
if (stream) {
|
||||
for (const track of stream.getTracks()) track.stop();
|
||||
streamRef.current = null;
|
||||
}
|
||||
detectorRef.current = null;
|
||||
if (videoRef.current) videoRef.current.srcObject = null;
|
||||
setLive(false);
|
||||
}
|
||||
|
||||
function finish(raw: string) {
|
||||
const target = parsePairLink(raw, fallbackEndpoint);
|
||||
if (!target) {
|
||||
setPasteInvalid(true);
|
||||
setStatus(t("connect.invalidLink"));
|
||||
setPasteOpen(true);
|
||||
return;
|
||||
}
|
||||
if (finishingRef.current) return;
|
||||
finishingRef.current = true;
|
||||
stopCamera();
|
||||
onFound(target);
|
||||
onOpenChange(false);
|
||||
}
|
||||
|
||||
async function scanFrame() {
|
||||
if (cancelled || finishingRef.current) return;
|
||||
const detector = detectorRef.current;
|
||||
const video = videoRef.current;
|
||||
if (!detector || !video) return;
|
||||
try {
|
||||
const codes = await detector.detect(video);
|
||||
const raw = codes[0]?.rawValue;
|
||||
if (raw) finish(raw);
|
||||
} catch {
|
||||
/* a single failed frame should not stop the loop */
|
||||
}
|
||||
}
|
||||
|
||||
async function startCamera() {
|
||||
stopCamera();
|
||||
if (!window.isSecureContext) {
|
||||
setStatus(t("connect.secureRequired"));
|
||||
setPasteOpen(true);
|
||||
return;
|
||||
}
|
||||
if (!navigator.mediaDevices?.getUserMedia) {
|
||||
setStatus(t("connect.cameraUnsupported"));
|
||||
setPasteOpen(true);
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const stream = await navigator.mediaDevices.getUserMedia({
|
||||
audio: false,
|
||||
video: { facingMode: { ideal: "environment" } },
|
||||
});
|
||||
if (cancelled) {
|
||||
for (const track of stream.getTracks()) track.stop();
|
||||
return;
|
||||
}
|
||||
streamRef.current = stream;
|
||||
const video = videoRef.current;
|
||||
if (video) {
|
||||
video.srcObject = stream;
|
||||
await video.play().catch(() => undefined);
|
||||
}
|
||||
setLive(true);
|
||||
|
||||
const Ctor = barcodeDetectorCtor();
|
||||
if (Ctor) {
|
||||
try {
|
||||
detectorRef.current = new Ctor({ formats: ["qr_code"] });
|
||||
} catch {
|
||||
detectorRef.current = null;
|
||||
}
|
||||
}
|
||||
if (detectorRef.current) {
|
||||
setStatus(t("connect.aim"));
|
||||
timerRef.current = setInterval(() => void scanFrame(), 300);
|
||||
} else {
|
||||
setStatus(t("connect.noAutoDetect"));
|
||||
setPasteOpen(true);
|
||||
}
|
||||
} catch (error) {
|
||||
const denied =
|
||||
error instanceof DOMException &&
|
||||
(error.name === "NotAllowedError" || error.name === "SecurityError");
|
||||
setStatus(t(denied ? "connect.permissionDenied" : "connect.cameraFailed"));
|
||||
setPasteOpen(true);
|
||||
}
|
||||
}
|
||||
|
||||
void startCamera();
|
||||
return () => {
|
||||
cancelled = true;
|
||||
stopCamera();
|
||||
};
|
||||
}, [attempt, fallbackEndpoint, onFound, onOpenChange, open, t]);
|
||||
|
||||
function identify() {
|
||||
const target = parsePairLink(paste, fallbackEndpoint);
|
||||
if (!target) {
|
||||
setPasteInvalid(true);
|
||||
setStatus(t("connect.invalidLink"));
|
||||
setPasteOpen(true);
|
||||
return;
|
||||
}
|
||||
setPasteInvalid(false);
|
||||
onFound(target);
|
||||
onOpenChange(false);
|
||||
}
|
||||
|
||||
return (
|
||||
<Modal
|
||||
open={open}
|
||||
onOpenChange={onOpenChange}
|
||||
title={t("connect.scanTitle")}
|
||||
size="wide"
|
||||
footer={
|
||||
<Button variant="ghost" onClick={() => onOpenChange(false)}>
|
||||
{t("common.close")}
|
||||
</Button>
|
||||
}
|
||||
>
|
||||
<div className="cn-scan">
|
||||
<div className={live ? "cn-scan__viewport is-live" : "cn-scan__viewport"}>
|
||||
<video
|
||||
ref={videoRef}
|
||||
className="cn-scan__video"
|
||||
autoPlay
|
||||
playsInline
|
||||
muted
|
||||
aria-label={t("connect.cameraPreview")}
|
||||
/>
|
||||
<div className="cn-scan__placeholder">
|
||||
<span className="cn-ico">
|
||||
<Icon name="scan" size={28} />
|
||||
</span>
|
||||
<span>{t("connect.cameraPreview")}</span>
|
||||
</div>
|
||||
<div className="cn-scan__frame" aria-hidden="true" />
|
||||
</div>
|
||||
<div className="cn-scan__state" role="status" aria-live="polite">
|
||||
{status}
|
||||
</div>
|
||||
<p className="cn-hint">{t("connect.scanHint")}</p>
|
||||
|
||||
<details
|
||||
className="cn-fold"
|
||||
open={pasteOpen}
|
||||
onToggle={(event) => setPasteOpen(event.currentTarget.open)}
|
||||
>
|
||||
<summary>{t("connect.cantScan")}</summary>
|
||||
<div className="cn-fold__body">
|
||||
<Input
|
||||
type="text"
|
||||
autoComplete="off"
|
||||
spellCheck={false}
|
||||
className={pasteInvalid ? "is-invalid" : undefined}
|
||||
placeholder={t("connect.pastePlaceholder")}
|
||||
aria-label={t("connect.pairingLink")}
|
||||
value={paste}
|
||||
onChange={(event) => {
|
||||
setPaste(event.target.value);
|
||||
setPasteInvalid(false);
|
||||
}}
|
||||
onKeyDown={(event) => {
|
||||
if (event.key === "Enter" && !event.nativeEvent.isComposing) {
|
||||
event.preventDefault();
|
||||
identify();
|
||||
}
|
||||
}}
|
||||
/>
|
||||
<Button variant="primary" onClick={identify}>
|
||||
{t("connect.identify")}
|
||||
</Button>
|
||||
</div>
|
||||
</details>
|
||||
|
||||
<div className="cn-scan__actions">
|
||||
<Button variant="ghost" size="sm" onClick={() => setAttempt((value) => value + 1)}>
|
||||
<Icon name="refresh" />
|
||||
{t("connect.retryCamera")}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
import type { ReactNode } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
import { Icon, type IconName } from "@/components/icons";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Empty } from "@/components/ui/empty";
|
||||
|
||||
export interface StatusCardProps {
|
||||
title: ReactNode;
|
||||
icon: IconName;
|
||||
headExtra?: ReactNode;
|
||||
className?: string;
|
||||
children: ReactNode;
|
||||
}
|
||||
|
||||
/** `.card.status-card` with the design's icon + title + right-side meta. */
|
||||
export function StatusCard({ title, icon, headExtra, className, children }: StatusCardProps) {
|
||||
return (
|
||||
<section className={className ? `card status-card ${className}` : "card status-card"}>
|
||||
<div className="card__head">
|
||||
<div className="card__title">
|
||||
<Icon name={icon} />
|
||||
{title}
|
||||
</div>
|
||||
<div className="spacer" />
|
||||
{headExtra ?? null}
|
||||
</div>
|
||||
{children}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
export function LoadingBlock({ rows = 3 }: { rows?: number }) {
|
||||
const { t } = useTranslation();
|
||||
return (
|
||||
<div className="status-loading" role="status" aria-label={t("common.loading")}>
|
||||
{Array.from({ length: rows }, (_, index) => (
|
||||
<span key={index} className="skeleton skeleton--row" />
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export interface ErrorBlockProps {
|
||||
message: string;
|
||||
onRetry?: () => void;
|
||||
}
|
||||
|
||||
export function ErrorBlock({ message, onRetry }: ErrorBlockProps) {
|
||||
const { t } = useTranslation();
|
||||
return (
|
||||
<Empty
|
||||
className="status-error"
|
||||
icon={<Icon name="alert" size={20} />}
|
||||
description={message}
|
||||
action={
|
||||
onRetry ? (
|
||||
<Button size="sm" onClick={onRetry}>
|
||||
<Icon name="refresh" />
|
||||
{t("common.retry")}
|
||||
</Button>
|
||||
) : undefined
|
||||
}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
export interface StatusEmptyProps {
|
||||
icon: IconName;
|
||||
title: string;
|
||||
text: string;
|
||||
}
|
||||
|
||||
export function StatusEmpty({ icon, title, text }: StatusEmptyProps) {
|
||||
return (
|
||||
<Empty
|
||||
className="status-empty"
|
||||
icon={<Icon name={icon} size={20} />}
|
||||
title={title}
|
||||
description={text}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,182 @@
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
import { Icon } from "@/components/icons";
|
||||
import { ConfirmDialog } from "@/components/shared/confirm-dialog";
|
||||
import { RelativeTime } from "@/components/shared/relative-time";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { KV, KVList } from "@/components/ui/kv";
|
||||
import { toast } from "@/components/ui/toast";
|
||||
import { drawQr } from "@/features/status/qr";
|
||||
import type { ServerIdentity } from "@/features/status/server";
|
||||
|
||||
import { ErrorBlock, LoadingBlock, StatusCard } from "./card-parts";
|
||||
|
||||
function scopeTone(scope: string): "default" | "info" | "ok" {
|
||||
if (scope === "read") return "default";
|
||||
if (scope === "steer") return "info";
|
||||
if (scope === "apply") return "ok";
|
||||
return "default";
|
||||
}
|
||||
|
||||
function CopyButton({ value, label }: { value: string; label: string }) {
|
||||
const { t } = useTranslation();
|
||||
|
||||
async function copy() {
|
||||
try {
|
||||
if (!navigator.clipboard?.writeText) throw new Error("clipboard unavailable");
|
||||
await navigator.clipboard.writeText(value);
|
||||
toast.success(t("common.copied", { label }));
|
||||
} catch {
|
||||
toast.error(t("common.copyFailed"));
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="status-copy"
|
||||
title={t("common.copy", { label })}
|
||||
aria-label={t("common.copy", { label })}
|
||||
onClick={() => void copy()}
|
||||
>
|
||||
<Icon name="copy" />
|
||||
</Button>
|
||||
);
|
||||
}
|
||||
|
||||
function AddressBlock({ label, value }: { label: string; value: string }) {
|
||||
return (
|
||||
<div className="addr-block">
|
||||
<div className="addr-label muted">{label}</div>
|
||||
<div className="addr-row">
|
||||
<code className="mono truncate grow">{value}</code>
|
||||
<CopyButton value={value} label={label} />
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function QrCanvas({ seed, label }: { seed: string; label: string }) {
|
||||
const ref = useRef<HTMLCanvasElement | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
const canvas = ref.current;
|
||||
if (!canvas) return;
|
||||
const draw = () => drawQr(canvas, seed);
|
||||
draw();
|
||||
|
||||
if (typeof MutationObserver === "undefined") return;
|
||||
const observer = new MutationObserver(draw);
|
||||
observer.observe(document.documentElement, { attributes: true, attributeFilter: ["data-theme"] });
|
||||
return () => observer.disconnect();
|
||||
}, [seed]);
|
||||
|
||||
return <canvas ref={ref} className="qr-canvas" role="img" aria-label={label} />;
|
||||
}
|
||||
|
||||
export interface ConnectionCardProps {
|
||||
server: ServerIdentity;
|
||||
deviceName: string;
|
||||
scopes: string[];
|
||||
connectedAt: number | null;
|
||||
loading: boolean;
|
||||
error: string | null;
|
||||
onRetry: () => void;
|
||||
onDisconnect: () => void;
|
||||
}
|
||||
|
||||
/** Card 7 — addresses, mDNS, pairing code/QR, scopes, last connection, actions. */
|
||||
export function ConnectionCard({
|
||||
server,
|
||||
deviceName,
|
||||
scopes,
|
||||
connectedAt,
|
||||
loading,
|
||||
error,
|
||||
onRetry,
|
||||
onDisconnect,
|
||||
}: ConnectionCardProps) {
|
||||
const { t } = useTranslation();
|
||||
const [confirmOpen, setConfirmOpen] = useState(false);
|
||||
const qrSeed = `${server.networkAddress}/#pair=${server.pairingCode}`;
|
||||
|
||||
return (
|
||||
<StatusCard title={t("status.connection")} icon="qr">
|
||||
{error ? (
|
||||
<ErrorBlock message={error} onRetry={onRetry} />
|
||||
) : loading ? (
|
||||
<LoadingBlock rows={6} />
|
||||
) : (
|
||||
<>
|
||||
<div className="connect-grid">
|
||||
<div className="connect-addr">
|
||||
<AddressBlock label={t("status.local")} value={server.localAddress} />
|
||||
<AddressBlock label={t("status.network")} value={server.networkAddress} />
|
||||
<KV label={t("status.mdns")} mono>
|
||||
{server.mdns}
|
||||
</KV>
|
||||
<KV label={t("connect.endpoint")} valueClassName="status-endpoint">
|
||||
<span className="mono truncate">{server.endpoint}</span>
|
||||
<CopyButton value={server.endpoint} label={t("connect.endpoint")} />
|
||||
</KV>
|
||||
<KV label={t("connect.device")}>{deviceName || "—"}</KV>
|
||||
<KV label={t("status.tokenScopes")} valueClassName="status-kv-val">
|
||||
{scopes.length ? (
|
||||
<span className="status-scopes">
|
||||
{scopes.map((scope) => (
|
||||
<Badge key={scope} tone={scopeTone(scope)}>
|
||||
{scope}
|
||||
</Badge>
|
||||
))}
|
||||
</span>
|
||||
) : (
|
||||
<span className="muted">—</span>
|
||||
)}
|
||||
</KV>
|
||||
<KV label={t("status.lastConnected")}>
|
||||
<RelativeTime ts={connectedAt} />
|
||||
</KV>
|
||||
</div>
|
||||
|
||||
<div className="qr-wrap">
|
||||
<QrCanvas seed={qrSeed} label={t("status.qrAria")} />
|
||||
<div className="pair-code">{server.pairingCode}</div>
|
||||
<div className="pair-hint muted">
|
||||
<Icon name="phone" />
|
||||
<span>{t("status.pairHint")}</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<KVList className="security-note">
|
||||
<div className="security-item">{t("status.securityLocal")}</div>
|
||||
<div className="security-item">{t("status.securityToken")}</div>
|
||||
</KVList>
|
||||
|
||||
<div className="status-conn-actions">
|
||||
<a className="btn btn--sm" href="/connect?next=%2Fstatus">
|
||||
<Icon name="refresh" />
|
||||
{t("connect.reconnect")}
|
||||
</a>
|
||||
<Button variant="danger" size="sm" onClick={() => setConfirmOpen(true)}>
|
||||
<Icon name="plug" />
|
||||
{t("connect.disconnect")}
|
||||
</Button>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
|
||||
<ConfirmDialog
|
||||
open={confirmOpen}
|
||||
onOpenChange={setConfirmOpen}
|
||||
title={t("connect.disconnectTitle")}
|
||||
description={t("connect.disconnectText")}
|
||||
confirmLabel={t("connect.disconnect")}
|
||||
onConfirm={onDisconnect}
|
||||
/>
|
||||
</StatusCard>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
import { useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
import { Icon, type IconName } from "@/components/icons";
|
||||
import { ConfirmDialog } from "@/components/shared/confirm-dialog";
|
||||
import { RelativeTime } from "@/components/shared/relative-time";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import type { DeviceEntry } from "@/features/status/queries";
|
||||
|
||||
import { ErrorBlock, LoadingBlock, StatusCard, StatusEmpty } from "./card-parts";
|
||||
|
||||
const KIND_ICON: Record<string, IconName> = {
|
||||
phone: "phone",
|
||||
tablet: "tablet",
|
||||
laptop: "laptop",
|
||||
};
|
||||
|
||||
function scopeTone(scope: string): "default" | "info" | "ok" {
|
||||
if (scope === "read") return "default";
|
||||
if (scope === "steer") return "info";
|
||||
if (scope === "apply") return "ok";
|
||||
return "default";
|
||||
}
|
||||
|
||||
export function deviceKey(device: DeviceEntry): string {
|
||||
return device.id || device.deviceId || device.name;
|
||||
}
|
||||
|
||||
export interface DevicesCardProps {
|
||||
devices: DeviceEntry[];
|
||||
loading: boolean;
|
||||
error: string | null;
|
||||
onRetry: () => void;
|
||||
onRevoke: (device: DeviceEntry) => Promise<void>;
|
||||
}
|
||||
|
||||
/** Card 6 — paired devices with kind icon, scopes, last active and confirm-revoke. */
|
||||
export function DevicesCard({ devices, loading, error, onRetry, onRevoke }: DevicesCardProps) {
|
||||
const { t } = useTranslation();
|
||||
const [target, setTarget] = useState<DeviceEntry | null>(null);
|
||||
const visible = devices.filter((device) => !device.revokedAt);
|
||||
|
||||
async function confirm() {
|
||||
if (!target) return;
|
||||
await onRevoke(target);
|
||||
setTarget(null);
|
||||
}
|
||||
|
||||
return (
|
||||
<StatusCard
|
||||
title={t("status.devices")}
|
||||
icon="phone"
|
||||
headExtra={<span className="card__sub">{t("status.deviceCount", { n: visible.length })}</span>}
|
||||
>
|
||||
{error ? (
|
||||
<ErrorBlock message={error} onRetry={onRetry} />
|
||||
) : loading ? (
|
||||
<LoadingBlock rows={3} />
|
||||
) : visible.length === 0 ? (
|
||||
<StatusEmpty icon="phone" title={t("status.noDevicesTitle")} text={t("status.noDevicesText")} />
|
||||
) : (
|
||||
<div className="device-list">
|
||||
{visible.map((device) => {
|
||||
const scopes = Array.isArray(device.scopes) ? device.scopes : [];
|
||||
return (
|
||||
<div className="device-row" key={deviceKey(device)}>
|
||||
<span className="device-icon">
|
||||
<Icon name={KIND_ICON[device.kind] ?? "phone"} />
|
||||
</span>
|
||||
<div className="grow device-main">
|
||||
<div className="device-name truncate">{device.name}</div>
|
||||
<div className="device-badges">
|
||||
{scopes.map((scope) => (
|
||||
<Badge key={scope} tone={scopeTone(scope)}>
|
||||
{scope}
|
||||
</Badge>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
<span className="device-time muted">
|
||||
<RelativeTime ts={device.lastActiveAt} />
|
||||
</span>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="status-revoke"
|
||||
onClick={() => setTarget(device)}
|
||||
>
|
||||
<Icon name="revoke" />
|
||||
{t("status.revoke")}
|
||||
</Button>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<ConfirmDialog
|
||||
open={target != null}
|
||||
onOpenChange={(open) => {
|
||||
if (!open) setTarget(null);
|
||||
}}
|
||||
title={t("status.revokeTitle")}
|
||||
description={target ? t("status.revokeText", { name: target.name }) : undefined}
|
||||
confirmLabel={t("status.revoke")}
|
||||
onConfirm={confirm}
|
||||
/>
|
||||
</StatusCard>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
import { Icon } from "@/components/icons";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { RelativeTime } from "@/components/shared/relative-time";
|
||||
import type { HealthResponse } from "@/lib/api";
|
||||
|
||||
import { ErrorBlock, LoadingBlock, StatusCard, StatusEmpty } from "./card-parts";
|
||||
|
||||
export interface HealthCardProps {
|
||||
health: HealthResponse | undefined;
|
||||
checkedAt: number | null;
|
||||
loading: boolean;
|
||||
error: string | null;
|
||||
onRetry: () => void;
|
||||
}
|
||||
|
||||
/** Card 2 — per-check ✓/✗ list with an overall healthy/degraded badge. */
|
||||
export function HealthCard({ health, checkedAt, loading, error, onRetry }: HealthCardProps) {
|
||||
const { t } = useTranslation();
|
||||
const items = health?.items ?? [];
|
||||
const allOk = items.length > 0 && items.every((item) => item.ok);
|
||||
|
||||
return (
|
||||
<StatusCard
|
||||
title={t("status.health")}
|
||||
icon="status"
|
||||
headExtra={
|
||||
<div className="status-health-meta">
|
||||
{items.length ? (
|
||||
<Badge tone={allOk ? "ok" : "warn"}>{t(allOk ? "status.healthy" : "state.degraded")}</Badge>
|
||||
) : null}
|
||||
{checkedAt ? <span className="card__sub"><RelativeTime ts={checkedAt} /></span> : null}
|
||||
</div>
|
||||
}
|
||||
>
|
||||
{error ? (
|
||||
<ErrorBlock message={error} onRetry={onRetry} />
|
||||
) : loading ? (
|
||||
<LoadingBlock rows={4} />
|
||||
) : items.length === 0 ? (
|
||||
<StatusEmpty icon="alert" title={t("status.noHealthTitle")} text={t("status.noHealthText")} />
|
||||
) : (
|
||||
<div className="health-list">
|
||||
{items.map((item) => (
|
||||
<div className="health-row" key={item.name}>
|
||||
<span
|
||||
className={item.ok ? "health-ico health-ico--ok" : "health-ico health-ico--err"}
|
||||
title={t(item.ok ? "status.pass" : "status.fail")}
|
||||
aria-label={t(item.ok ? "status.pass" : "status.fail")}
|
||||
>
|
||||
<Icon name={item.ok ? "check" : "x"} size={15} />
|
||||
</span>
|
||||
<div className="grow">
|
||||
<div className="health-name">{item.name}</div>
|
||||
{item.detail ? <div className="health-detail muted">{item.detail}</div> : null}
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</StatusCard>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,124 @@
|
||||
import { useEffect, useMemo, useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
import { Icon } from "@/components/icons";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import type { ModelInfo } from "@/lib/api";
|
||||
import { formatContextWindow } from "@/features/status/server";
|
||||
|
||||
import { ErrorBlock, LoadingBlock, StatusCard, StatusEmpty } from "./card-parts";
|
||||
|
||||
export interface ModelsCardProps {
|
||||
providers: ModelInfo[];
|
||||
loading: boolean;
|
||||
error: string | null;
|
||||
onRetry: () => void;
|
||||
}
|
||||
|
||||
/** Card 4 — provider accordion with mono model ids, context windows, reasoning badges. */
|
||||
export function ModelsCard({ providers, loading, error, onRetry }: ModelsCardProps) {
|
||||
const { t } = useTranslation();
|
||||
const [query, setQuery] = useState("");
|
||||
const [openProviders, setOpenProviders] = useState<Set<string>>(
|
||||
() => new Set(providers[0] ? [providers[0].provider] : []),
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
setOpenProviders(new Set(providers[0] ? [providers[0].provider] : []));
|
||||
}, [providers]);
|
||||
|
||||
const needle = query.trim().toLowerCase();
|
||||
const groups = useMemo(
|
||||
() =>
|
||||
providers
|
||||
.map((group) => ({
|
||||
...group,
|
||||
models: group.models.filter(
|
||||
(model) =>
|
||||
!needle ||
|
||||
model.id.toLowerCase().includes(needle) ||
|
||||
group.provider.toLowerCase().includes(needle),
|
||||
),
|
||||
}))
|
||||
.filter((group) => group.models.length > 0),
|
||||
[needle, providers],
|
||||
);
|
||||
|
||||
function toggle(provider: string) {
|
||||
setOpenProviders((current) => {
|
||||
const next = new Set(current);
|
||||
if (next.has(provider)) next.delete(provider);
|
||||
else next.add(provider);
|
||||
return next;
|
||||
});
|
||||
}
|
||||
|
||||
return (
|
||||
<StatusCard title={t("status.models")} icon="model">
|
||||
{error ? (
|
||||
<ErrorBlock message={error} onRetry={onRetry} />
|
||||
) : loading ? (
|
||||
<LoadingBlock rows={5} />
|
||||
) : (
|
||||
<>
|
||||
<div className="model-search">
|
||||
<Icon name="search" />
|
||||
<Input
|
||||
type="search"
|
||||
placeholder={t("status.modelSearchPlaceholder")}
|
||||
aria-label={t("status.modelSearchAria")}
|
||||
value={query}
|
||||
onChange={(event) => setQuery(event.target.value)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{providers.length === 0 ? (
|
||||
<StatusEmpty icon="model" title={t("status.noModelsTitle")} text={t("status.noModelsText")} />
|
||||
) : groups.length === 0 ? (
|
||||
<StatusEmpty icon="search" title={t("status.noModelsTitle")} text={t("status.noModelsText")} />
|
||||
) : (
|
||||
<div className="model-list">
|
||||
{groups.map((group) => {
|
||||
const expanded = Boolean(needle) || openProviders.has(group.provider);
|
||||
return (
|
||||
<div className={expanded ? "model-group open" : "model-group"} key={group.provider}>
|
||||
<button
|
||||
type="button"
|
||||
className="panel__head model-group__head"
|
||||
aria-expanded={expanded}
|
||||
onClick={() => toggle(group.provider)}
|
||||
>
|
||||
<Icon name="chevron-right" />
|
||||
<span className="model-provider">{group.provider}</span>
|
||||
<span className="badge model-count">{group.models.length}</span>
|
||||
<span className="spacer" />
|
||||
</button>
|
||||
{expanded ? (
|
||||
<div className="model-group__body">
|
||||
{group.models.map((model) => (
|
||||
<div className="model-row" key={model.id}>
|
||||
<span className="model-id mono truncate grow">{model.id}</span>
|
||||
<span className="model-ctx muted">
|
||||
{formatContextWindow(model.contextWindow)}
|
||||
</span>
|
||||
{model.reasoning ? (
|
||||
<Badge tone="info">{t("status.reasoning")}</Badge>
|
||||
) : null}
|
||||
{group.provider === "cliproxyapi" ? (
|
||||
<Badge>{t("status.scoped")}</Badge>
|
||||
) : null}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</StatusCard>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
/**
|
||||
* Port of the prototype's `App.drawQR`: a deterministic fake QR derived from a
|
||||
* seed string. Colors come from the design tokens only, so a theme switch
|
||||
* redraws the same pattern with the dark surfaces.
|
||||
*/
|
||||
export function drawQr(canvas: HTMLCanvasElement, seed: string): void {
|
||||
let context: CanvasRenderingContext2D | null = null;
|
||||
try {
|
||||
context = canvas.getContext("2d");
|
||||
} catch {
|
||||
return;
|
||||
}
|
||||
if (!context) return;
|
||||
|
||||
const n = 25;
|
||||
const cell = 8;
|
||||
canvas.width = n * cell;
|
||||
canvas.height = n * cell;
|
||||
|
||||
const styles = getComputedStyle(document.documentElement);
|
||||
const cardColor = styles.getPropertyValue("--card").trim() || "transparent";
|
||||
const foregroundColor = styles.getPropertyValue("--foreground").trim() || "currentColor";
|
||||
|
||||
context.fillStyle = cardColor;
|
||||
context.fillRect(0, 0, canvas.width, canvas.height);
|
||||
context.fillStyle = foregroundColor;
|
||||
|
||||
let state = 0;
|
||||
for (const char of seed) state = (state * 31 + char.charCodeAt(0)) >>> 0;
|
||||
const random = () => {
|
||||
state = (state * 1103515245 + 12345) >>> 0;
|
||||
return state / 4294967296;
|
||||
};
|
||||
|
||||
const finder = (x: number, y: number) => {
|
||||
context?.fillRect(x * cell, y * cell, 7 * cell, 7 * cell);
|
||||
context?.clearRect((x + 1) * cell, (y + 1) * cell, 5 * cell, 5 * cell);
|
||||
context?.fillRect((x + 2) * cell, (y + 2) * cell, 3 * cell, 3 * cell);
|
||||
if (context) context.fillStyle = foregroundColor;
|
||||
};
|
||||
|
||||
for (let y = 0; y < n; y += 1) {
|
||||
for (let x = 0; x < n; x += 1) {
|
||||
const inFinder = (x < 8 && y < 8) || (x > n - 9 && y < 8) || (x < 8 && y > n - 9);
|
||||
if (!inFinder && random() > 0.52) context.fillRect(x * cell, y * cell, cell, cell);
|
||||
}
|
||||
}
|
||||
|
||||
finder(0, 0);
|
||||
finder(n - 7, 0);
|
||||
finder(0, n - 7);
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
import { useQuery } from "@tanstack/react-query";
|
||||
|
||||
import { api, apiRequest, type HealthResponse, type InfoResponse, type ModelInfo, type ResourcesResponse } from "@/lib/api";
|
||||
import type { WorkspaceInfo } from "@/lib/protocol";
|
||||
|
||||
/** GET /api/v1/devices uses `id` on the wire; older builds exposed `deviceId`. */
|
||||
export interface DeviceEntry {
|
||||
id?: string;
|
||||
deviceId?: string;
|
||||
name: string;
|
||||
kind: string;
|
||||
scopes: string[];
|
||||
lastActiveAt: number | null;
|
||||
revokedAt?: number | null;
|
||||
}
|
||||
|
||||
export interface DevicesResponse {
|
||||
devices: DeviceEntry[];
|
||||
}
|
||||
|
||||
export interface ModelsResponse {
|
||||
providers: ModelInfo[];
|
||||
}
|
||||
|
||||
export async function fetchDevices(signal?: AbortSignal): Promise<DevicesResponse> {
|
||||
return apiRequest<DevicesResponse>("/api/v1/devices", { signal });
|
||||
}
|
||||
|
||||
export async function fetchModels(workspaceId: string, signal?: AbortSignal): Promise<ModelsResponse> {
|
||||
return apiRequest<ModelsResponse>(`/api/v1/models?workspaceId=${encodeURIComponent(workspaceId)}`, { signal });
|
||||
}
|
||||
|
||||
export function useInfoQuery(enabled = true) {
|
||||
return useQuery<InfoResponse>({
|
||||
queryKey: ["info"],
|
||||
queryFn: ({ signal }) => api.info(signal),
|
||||
enabled,
|
||||
staleTime: 30_000,
|
||||
});
|
||||
}
|
||||
|
||||
export function useHealthQuery() {
|
||||
return useQuery<HealthResponse>({
|
||||
queryKey: ["health"],
|
||||
queryFn: ({ signal }) => api.health(signal),
|
||||
staleTime: 10_000,
|
||||
});
|
||||
}
|
||||
|
||||
export function useResourcesQuery() {
|
||||
return useQuery<ResourcesResponse>({
|
||||
queryKey: ["resources"],
|
||||
queryFn: ({ signal }) => api.resources(signal),
|
||||
// Resource pressure is the only live figure: poll every 3s while the tab is visible.
|
||||
refetchInterval: 3_000,
|
||||
refetchIntervalInBackground: false,
|
||||
staleTime: 2_000,
|
||||
});
|
||||
}
|
||||
|
||||
export function useWorkspacesQuery() {
|
||||
return useQuery<WorkspaceInfo[]>({
|
||||
queryKey: ["workspaces"],
|
||||
queryFn: ({ signal }) => api.workspaces(signal),
|
||||
staleTime: 10_000,
|
||||
});
|
||||
}
|
||||
|
||||
export function useDevicesQuery() {
|
||||
return useQuery<DevicesResponse>({
|
||||
queryKey: ["devices"],
|
||||
queryFn: ({ signal }) => fetchDevices(signal),
|
||||
staleTime: 10_000,
|
||||
});
|
||||
}
|
||||
|
||||
export function useModelsQuery(workspaceId: string | null | undefined) {
|
||||
return useQuery<ModelsResponse>({
|
||||
queryKey: ["models", workspaceId ?? ""],
|
||||
queryFn: ({ signal }) => fetchModels(workspaceId ?? "", signal),
|
||||
enabled: Boolean(workspaceId),
|
||||
staleTime: 60_000,
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,107 @@
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
import { Icon } from "@/components/icons";
|
||||
import { Progress } from "@/components/ui/progress";
|
||||
import { KV, KVList } from "@/components/ui/kv";
|
||||
import type { ResourcesResponse } from "@/lib/api";
|
||||
import type { ServerIdentity } from "@/features/status/server";
|
||||
import { formatBytes } from "@/features/status/server";
|
||||
|
||||
import { ErrorBlock, LoadingBlock, StatusCard, StatusEmpty } from "./card-parts";
|
||||
|
||||
function toneFor(pct: number | null): "default" | "warn" | "err" {
|
||||
if (pct == null) return "default";
|
||||
if (pct > 90) return "err";
|
||||
if (pct > 80) return "warn";
|
||||
return "default";
|
||||
}
|
||||
|
||||
function percent(part: number, total: number): number | null {
|
||||
if (!Number.isFinite(part) || !Number.isFinite(total) || total <= 0) return null;
|
||||
return Math.max(0, Math.min(100, Math.round((part / total) * 100)));
|
||||
}
|
||||
|
||||
export interface ResourcesCardProps {
|
||||
resources: ResourcesResponse | undefined;
|
||||
server: ServerIdentity;
|
||||
loading: boolean;
|
||||
error: string | null;
|
||||
onRetry: () => void;
|
||||
workspaceCount: number;
|
||||
sessionCount: number;
|
||||
}
|
||||
|
||||
/** Card 3 — CPU/mem/disk rows, instance/session counts, soft-limit banner. */
|
||||
export function ResourcesCard({
|
||||
resources,
|
||||
server,
|
||||
loading,
|
||||
error,
|
||||
onRetry,
|
||||
workspaceCount,
|
||||
sessionCount,
|
||||
}: ResourcesCardProps) {
|
||||
const { t } = useTranslation();
|
||||
const memPct =
|
||||
resources != null ? percent(resources.totalRssBytes, resources.physicalMemoryBytes) : null;
|
||||
const cpuPct = server.cpu;
|
||||
const diskPct = server.disk;
|
||||
const instanceCount = resources?.instances.length ?? 0;
|
||||
const liveSessions = resources?.instances.reduce((total, item) => total + (item.sessions || 0), 0) ?? 0;
|
||||
|
||||
function row(key: string, label: string, pct: number | null, detail?: string) {
|
||||
return (
|
||||
<div className="res-row" data-res={key}>
|
||||
<div className="res-top">
|
||||
<span className="res-label">{label}</span>
|
||||
<span className="spacer" />
|
||||
<b className="res-val">{pct == null ? "—" : `${pct}%`}</b>
|
||||
</div>
|
||||
<Progress value={pct ?? 0} tone={toneFor(pct)} size="lg" label={label} />
|
||||
{detail ? <div className="res-sub muted">{detail}</div> : null}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<StatusCard title={t("status.resources")} icon="cpu">
|
||||
{error ? (
|
||||
<ErrorBlock message={error} onRetry={onRetry} />
|
||||
) : loading ? (
|
||||
<LoadingBlock rows={5} />
|
||||
) : !resources ? (
|
||||
<StatusEmpty icon="cpu" title={t("status.noResourcesTitle")} text={t("status.noResourcesText")} />
|
||||
) : (
|
||||
<>
|
||||
<div className="res-list">
|
||||
{row("cpu", "CPU", cpuPct)}
|
||||
{row(
|
||||
"mem",
|
||||
t("status.memory"),
|
||||
memPct,
|
||||
`${formatBytes(resources.totalRssBytes)} / ${formatBytes(resources.physicalMemoryBytes)}`,
|
||||
)}
|
||||
{row("disk", t("status.disk"), diskPct)}
|
||||
</div>
|
||||
|
||||
{resources.warn ? (
|
||||
<div className="status-warn" role="status">
|
||||
<Icon name="alert" />
|
||||
<div>
|
||||
<span>{t("status.resourceWarn")}</span>
|
||||
{resources.reason ? <span className="muted"> {resources.reason}</span> : null}
|
||||
</div>
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
<KVList className="res-kv">
|
||||
<KV label={t("status.workspaces")}>{workspaceCount}</KV>
|
||||
<KV label={t("status.instances")}>{instanceCount}</KV>
|
||||
<KV label={t("status.sessions")}>{sessionCount}</KV>
|
||||
<KV label={t("status.liveSessions")}>{liveSessions}</KV>
|
||||
</KVList>
|
||||
</>
|
||||
)}
|
||||
</StatusCard>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
import { RelativeTime } from "@/components/shared/relative-time";
|
||||
import { StatusDot } from "@/components/ui/status-dot";
|
||||
import { KV, KVList } from "@/components/ui/kv";
|
||||
import type { ServerIdentity } from "@/features/status/server";
|
||||
import { formatUptime } from "@/features/status/server";
|
||||
|
||||
import { ErrorBlock, LoadingBlock, StatusCard } from "./card-parts";
|
||||
|
||||
export interface ServerInfoCardProps {
|
||||
server: ServerIdentity;
|
||||
loading: boolean;
|
||||
error: string | null;
|
||||
onRetry: () => void;
|
||||
}
|
||||
|
||||
/** Card 1 — daemon identity, versions, uptime, bind/port, WS heartbeat. */
|
||||
export function ServerInfoCard({ server, loading, error, onRetry }: ServerInfoCardProps) {
|
||||
const { t } = useTranslation();
|
||||
return (
|
||||
<StatusCard title={t("status.serverInfo")} icon="server">
|
||||
{error ? (
|
||||
<ErrorBlock message={error} onRetry={onRetry} />
|
||||
) : loading ? (
|
||||
<LoadingBlock rows={8} />
|
||||
) : (
|
||||
<KVList>
|
||||
<KV label={t("connect.name")}>{server.name}</KV>
|
||||
<KV label="hostname" mono>
|
||||
{server.hostname}
|
||||
</KV>
|
||||
<KV label={t("status.os")}>{server.os}</KV>
|
||||
<KV label={t("status.piVersion")}>{server.piVersion}</KV>
|
||||
<KV label={t("status.pluginVersion")}>{server.pluginVersion}</KV>
|
||||
<KV label={t("status.kernel")} mono>
|
||||
{server.kernel}
|
||||
</KV>
|
||||
<KV label={t("status.uptime")}>{formatUptime(server.uptimeSec)}</KV>
|
||||
<KV label={t("status.bindAddress")} mono>
|
||||
{server.bindAddress}
|
||||
</KV>
|
||||
<KV label={t("status.port")} mono>
|
||||
{server.port ?? "—"}
|
||||
</KV>
|
||||
<KV label={t("status.wsStatus")} valueClassName="status-ws">
|
||||
<StatusDot
|
||||
status={server.wsConnected ? "ok" : "err"}
|
||||
title={t(server.wsConnected ? "status.connected" : "status.disconnected")}
|
||||
/>
|
||||
<span>{t(server.wsConnected ? "status.connected" : "status.disconnected")}</span>
|
||||
<span className="muted">{server.wsProto}</span>
|
||||
</KV>
|
||||
<KV label={t("status.lastHeartbeat")}>
|
||||
<RelativeTime ts={server.lastHeartbeatAt} />
|
||||
</KV>
|
||||
</KVList>
|
||||
)}
|
||||
</StatusCard>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,162 @@
|
||||
import type { InfoResponse } from "@/lib/api";
|
||||
import type { WsConnectionState } from "@/lib/ws";
|
||||
|
||||
/**
|
||||
* Optional identity fields the daemon may expose beyond the minimal /info
|
||||
* contract. The status page degrades to `—` when they are missing: the wire
|
||||
* contract only guarantees `{v,daemonId,machineId,platform,capabilities,limits}`.
|
||||
*/
|
||||
export interface InfoExtras extends InfoResponse {
|
||||
os?: string;
|
||||
kernel?: string;
|
||||
uptimeSec?: number;
|
||||
lastHeartbeat?: number;
|
||||
mdns?: string;
|
||||
cpu?: number;
|
||||
mem?: number;
|
||||
disk?: number;
|
||||
addresses?: { local?: string; network?: string };
|
||||
pairing?: { code?: string; expiresIn?: number };
|
||||
pairingCode?: string;
|
||||
}
|
||||
|
||||
export interface ServerIdentity {
|
||||
name: string;
|
||||
hostname: string;
|
||||
port: number | null;
|
||||
endpoint: string;
|
||||
bindAddress: string;
|
||||
os: string;
|
||||
piVersion: string;
|
||||
pluginVersion: string;
|
||||
kernel: string;
|
||||
uptimeSec: number | null;
|
||||
status: "online" | "degraded" | "offline";
|
||||
wsConnected: boolean;
|
||||
wsProto: string;
|
||||
lastHeartbeatAt: number | null;
|
||||
localAddress: string;
|
||||
networkAddress: string;
|
||||
mdns: string;
|
||||
pairingCode: string;
|
||||
cpu: number | null;
|
||||
mem: number | null;
|
||||
disk: number | null;
|
||||
}
|
||||
|
||||
function parseUrl(value: string | null | undefined): URL | null {
|
||||
if (!value) return null;
|
||||
try {
|
||||
return new URL(value);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function browserLocation(): { hostname: string; port: string; protocol: string; origin: string } {
|
||||
if (typeof window === "undefined") {
|
||||
return { hostname: "localhost", port: "", protocol: "http:", origin: "http://localhost" };
|
||||
}
|
||||
return {
|
||||
hostname: window.location.hostname || "localhost",
|
||||
port: window.location.port,
|
||||
protocol: window.location.protocol,
|
||||
origin: window.location.origin,
|
||||
};
|
||||
}
|
||||
|
||||
export interface DeriveServerInput {
|
||||
info?: InfoExtras | null;
|
||||
endpoint?: string | null;
|
||||
wsState?: WsConnectionState;
|
||||
fetchedAt?: number | null;
|
||||
nameFallback?: string | null;
|
||||
status?: "online" | "degraded" | "offline" | null;
|
||||
}
|
||||
|
||||
/** Resolve the single server's identity from /info + the locally stored endpoint. */
|
||||
export function deriveServerIdentity({
|
||||
info,
|
||||
endpoint,
|
||||
wsState,
|
||||
fetchedAt,
|
||||
nameFallback,
|
||||
status,
|
||||
}: DeriveServerInput): ServerIdentity {
|
||||
const extras: InfoExtras = info ?? {};
|
||||
const browser = browserLocation();
|
||||
const url = parseUrl(endpoint) ?? parseUrl(browser.origin);
|
||||
const protocol = url?.protocol ?? browser.protocol;
|
||||
const portText = extras.port != null ? String(extras.port) : url?.port || browser.port;
|
||||
const port = portText ? Number(portText) : protocol === "https:" ? 443 : 80;
|
||||
const hostname = extras.hostname?.trim() || url?.hostname || browser.hostname;
|
||||
const name = extras.name?.trim() || nameFallback?.trim() || hostname;
|
||||
const endpointOrigin = extras.host
|
||||
? `${protocol}//${extras.host}:${port}`
|
||||
: url?.origin ?? browser.origin;
|
||||
const localAddress = extras.addresses?.local || `http://127.0.0.1:${port}`;
|
||||
const networkAddress = extras.addresses?.network || endpointOrigin;
|
||||
const resolvedStatus = status ?? extras.status ?? (info ? "online" : "offline");
|
||||
|
||||
return {
|
||||
name,
|
||||
hostname,
|
||||
port,
|
||||
endpoint: endpointOrigin,
|
||||
bindAddress: extras.host?.trim() || hostname,
|
||||
os: extras.os || extras.platform || "—",
|
||||
piVersion: extras.version || "—",
|
||||
pluginVersion: extras.pluginVersion || "—",
|
||||
kernel: extras.kernel || "—",
|
||||
uptimeSec: typeof extras.uptimeSec === "number" ? extras.uptimeSec : null,
|
||||
status: resolvedStatus,
|
||||
wsConnected: wsState === "open",
|
||||
wsProto: info?.v ? `v${info.v}` : "v1",
|
||||
lastHeartbeatAt: extras.lastHeartbeat ?? fetchedAt ?? null,
|
||||
localAddress,
|
||||
networkAddress,
|
||||
mdns: extras.mdns || `${hostname}.local`,
|
||||
pairingCode: extras.pairingCode || extras.pairing?.code || "—",
|
||||
cpu: typeof extras.cpu === "number" ? extras.cpu : null,
|
||||
mem: typeof extras.mem === "number" ? extras.mem : null,
|
||||
disk: typeof extras.disk === "number" ? extras.disk : null,
|
||||
};
|
||||
}
|
||||
|
||||
export function formatUptime(seconds: number | null | undefined): string {
|
||||
if (seconds == null || !Number.isFinite(seconds) || seconds < 0) return "—";
|
||||
const days = Math.floor(seconds / 86_400);
|
||||
const hours = Math.floor((seconds % 86_400) / 3_600);
|
||||
const minutes = Math.floor((seconds % 3_600) / 60);
|
||||
if (days > 0) return `${days}d ${hours}h ${minutes}m`;
|
||||
return `${hours}h ${minutes}m`;
|
||||
}
|
||||
|
||||
export function formatBytes(bytes: number | null | undefined): string {
|
||||
if (bytes == null || !Number.isFinite(bytes) || bytes < 0) return "—";
|
||||
const units = ["B", "KiB", "MiB", "GiB", "TiB"];
|
||||
let value = bytes;
|
||||
let unit = 0;
|
||||
while (value >= 1024 && unit < units.length - 1) {
|
||||
value /= 1024;
|
||||
unit += 1;
|
||||
}
|
||||
const digits = value >= 100 || unit === 0 ? 0 : value >= 10 ? 1 : 2;
|
||||
return `${value.toFixed(digits)} ${units[unit]}`;
|
||||
}
|
||||
|
||||
export function formatContextWindow(tokens: number): string {
|
||||
if (!Number.isFinite(tokens) || tokens <= 0) return "—";
|
||||
if (tokens >= 1_000_000) return `${Math.round(tokens / 100_000) / 10}M`;
|
||||
return `${Math.round(tokens / 1000)}k`;
|
||||
}
|
||||
|
||||
export function formatDuration(ms: number | null | undefined): string {
|
||||
if (ms == null || !Number.isFinite(ms) || ms < 0) return "—";
|
||||
if (ms < 1000) return `${Math.round(ms)}ms`;
|
||||
const seconds = ms / 1000;
|
||||
if (seconds < 60) return `${seconds.toFixed(seconds >= 10 ? 0 : 1)}s`;
|
||||
const minutes = Math.floor(seconds / 60);
|
||||
const rest = Math.round(seconds % 60);
|
||||
return `${minutes}m ${rest}s`;
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
import { StatusDot, type DotStatus } from "@/components/ui/status-dot";
|
||||
import type { TaskItem } from "@/lib/protocol";
|
||||
import { formatDuration } from "@/features/status/server";
|
||||
|
||||
import { StatusCard, StatusEmpty } from "./card-parts";
|
||||
|
||||
export interface StatusTask extends TaskItem {
|
||||
sessionId: string;
|
||||
}
|
||||
|
||||
const TASK_DOT: Record<string, DotStatus> = {
|
||||
running: "busy",
|
||||
completed: "ok",
|
||||
failed: "err",
|
||||
stopped: "exited",
|
||||
};
|
||||
|
||||
export interface TasksCardProps {
|
||||
tasks: StatusTask[];
|
||||
}
|
||||
|
||||
/** Card 5 — background task summary from the live session store. */
|
||||
export function TasksCard({ tasks }: TasksCardProps) {
|
||||
const { t } = useTranslation();
|
||||
return (
|
||||
<StatusCard
|
||||
title={t("status.tasks")}
|
||||
icon="terminal"
|
||||
headExtra={<span className="card__sub">{t("status.taskCount", { n: tasks.length })}</span>}
|
||||
>
|
||||
{tasks.length === 0 ? (
|
||||
<StatusEmpty icon="terminal" title={t("status.noTasksTitle")} text={t("status.noTasksText")} />
|
||||
) : (
|
||||
<div className="task-list">
|
||||
{tasks.map((task) => (
|
||||
<div className="task-row" key={`${task.sessionId}-${task.id}`} title={task.command}>
|
||||
<StatusDot status={TASK_DOT[task.status] ?? "idle"} />
|
||||
<span className="task-cmd mono truncate grow">{task.command}</span>
|
||||
<span className="task-dur muted">{formatDuration(task.durationMs)}</span>
|
||||
<span className="task-exit">
|
||||
{task.exitCode == null ? (
|
||||
<span className="badge badge--info">{t("state.running")}</span>
|
||||
) : (
|
||||
<span className={task.exitCode === 0 ? "badge badge--ok" : "badge badge--err"}>
|
||||
exit {task.exitCode}
|
||||
</span>
|
||||
)}
|
||||
</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</StatusCard>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
import { api } from "@/lib/api";
|
||||
import type { WorkspaceInfo } from "@/lib/protocol";
|
||||
|
||||
interface CommandResult {
|
||||
accepted?: boolean;
|
||||
disposition?: string;
|
||||
workspaceId?: string;
|
||||
workspace?: { workspaceId?: string };
|
||||
result?: { workspaceId?: string; workspace?: { workspaceId?: string } };
|
||||
instance?: { workspaceId?: string };
|
||||
[key: string]: unknown;
|
||||
}
|
||||
|
||||
function extractWorkspaceId(result: CommandResult): string | undefined {
|
||||
return (
|
||||
result.workspaceId ||
|
||||
result.workspace?.workspaceId ||
|
||||
result.result?.workspaceId ||
|
||||
result.result?.workspace?.workspaceId ||
|
||||
result.instance?.workspaceId
|
||||
);
|
||||
}
|
||||
|
||||
function findCreated(list: WorkspaceInfo[], cwd: string, name: string): WorkspaceInfo | undefined {
|
||||
const exact = list.find((item) => item.cwd === cwd && (name ? item.name === name : true));
|
||||
if (exact) return exact;
|
||||
return list.find((item) => item.cwd === cwd);
|
||||
}
|
||||
|
||||
/**
|
||||
* `workspace.add` → resolve the new workspace id (the command response is not
|
||||
* required to carry it, so fall back to a fresh GET) → `instance.ensure`.
|
||||
*/
|
||||
export async function openWorkspace(input: { cwd: string; name?: string }): Promise<string> {
|
||||
const cwd = input.cwd.trim();
|
||||
const name = input.name?.trim() ?? "";
|
||||
const added = (await api.command({
|
||||
method: "workspace.add",
|
||||
params: { cwd, ...(name ? { name } : {}) },
|
||||
})) as unknown as CommandResult;
|
||||
|
||||
let workspaceId = extractWorkspaceId(added);
|
||||
if (!workspaceId) {
|
||||
const list = await api.workspaces();
|
||||
workspaceId = findCreated(list, cwd, name)?.workspaceId;
|
||||
}
|
||||
if (!workspaceId) {
|
||||
throw new Error("workspace.add returned no workspace id");
|
||||
}
|
||||
|
||||
await api.command({ method: "instance.ensure", params: { workspaceId } });
|
||||
return workspaceId;
|
||||
}
|
||||
|
||||
/** Display name: explicit name → alias → last cwd segment → untitled. */
|
||||
export function workspaceName(workspace: WorkspaceInfo, unnamed = "Untitled"): string {
|
||||
const explicit = workspace.name?.trim() || workspace.alias?.trim();
|
||||
if (explicit) return explicit;
|
||||
const cwd = String(workspace.cwd || "").replace(/\/+$/, "");
|
||||
const segments = cwd.split("/");
|
||||
return segments[segments.length - 1] || cwd || unnamed;
|
||||
}
|
||||
|
||||
export function workspaceSessionCount(workspace: WorkspaceInfo): number {
|
||||
return Math.max(workspace.liveCount || 0, workspace.sessionCount || 0);
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
import { useEffect, useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
import { Icon } from "@/components/icons";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Modal } from "@/components/ui/dialog";
|
||||
import { Field, Input } from "@/components/ui/input";
|
||||
import { ApiError, errorI18nKey } from "@/lib/api";
|
||||
|
||||
export interface NewWorkspaceInput {
|
||||
cwd: string;
|
||||
name?: string;
|
||||
}
|
||||
|
||||
export interface NewWorkspaceDialogProps {
|
||||
open: boolean;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
onCreate: (input: NewWorkspaceInput) => Promise<void>;
|
||||
}
|
||||
|
||||
/** Path is required, display name optional; validation is inline, not a toast. */
|
||||
export function NewWorkspaceDialog({ open, onOpenChange, onCreate }: NewWorkspaceDialogProps) {
|
||||
const { t } = useTranslation();
|
||||
const [cwd, setCwd] = useState("");
|
||||
const [name, setName] = useState("");
|
||||
const [pathError, setPathError] = useState<string | null>(null);
|
||||
const [formError, setFormError] = useState<string | null>(null);
|
||||
const [busy, setBusy] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) return;
|
||||
setCwd("");
|
||||
setName("");
|
||||
setPathError(null);
|
||||
setFormError(null);
|
||||
setBusy(false);
|
||||
}, [open]);
|
||||
|
||||
async function submit(event: React.FormEvent<HTMLFormElement>) {
|
||||
event.preventDefault();
|
||||
if (busy) return;
|
||||
const trimmed = cwd.trim();
|
||||
if (!trimmed) {
|
||||
setPathError(t("workspaces.pathRequired"));
|
||||
setFormError(null);
|
||||
return;
|
||||
}
|
||||
setPathError(null);
|
||||
setFormError(null);
|
||||
setBusy(true);
|
||||
try {
|
||||
await onCreate({ cwd: trimmed, ...(name.trim() ? { name: name.trim() } : {}) });
|
||||
onOpenChange(false);
|
||||
} catch (error) {
|
||||
const key = error instanceof ApiError ? errorI18nKey(error.code) : "workspaces.addFailed";
|
||||
setFormError(t(key));
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Modal
|
||||
open={open}
|
||||
onOpenChange={onOpenChange}
|
||||
title={t("workspaces.newTitle")}
|
||||
footer={
|
||||
<>
|
||||
<Button variant="ghost" onClick={() => onOpenChange(false)} disabled={busy}>
|
||||
{t("common.cancel")}
|
||||
</Button>
|
||||
<Button variant="primary" type="submit" form="new-workspace-form" disabled={busy}>
|
||||
{busy ? t("workspaces.creating") : t("common.open")}
|
||||
</Button>
|
||||
</>
|
||||
}
|
||||
>
|
||||
<form id="new-workspace-form" className="ws-form" noValidate onSubmit={(event) => void submit(event)}>
|
||||
<Field label={t("workspaces.path")} htmlFor="new-workspace-path" hint={t("workspaces.pathHint")} error={pathError}>
|
||||
<Input
|
||||
id="new-workspace-path"
|
||||
autoFocus
|
||||
autoComplete="off"
|
||||
placeholder="~/Workspace/Misc/my-project"
|
||||
aria-label={t("workspaces.cwdAria")}
|
||||
value={cwd}
|
||||
onChange={(event) => {
|
||||
setCwd(event.target.value);
|
||||
if (pathError) setPathError(null);
|
||||
}}
|
||||
/>
|
||||
</Field>
|
||||
<Field label={t("workspaces.displayName")} htmlFor="new-workspace-name" hint={t("workspaces.nameHint")}>
|
||||
<Input
|
||||
id="new-workspace-name"
|
||||
autoComplete="off"
|
||||
placeholder={t("workspaces.defaultNamePlaceholder")}
|
||||
value={name}
|
||||
onChange={(event) => setName(event.target.value)}
|
||||
/>
|
||||
</Field>
|
||||
{formError ? (
|
||||
<div className="ws-form__error" role="alert">
|
||||
<Icon name="alert" />
|
||||
<span>{formError}</span>
|
||||
</div>
|
||||
) : null}
|
||||
</form>
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,121 @@
|
||||
import { Link } from "@tanstack/react-router";
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
import { Icon } from "@/components/icons";
|
||||
import { RelativeTime } from "@/components/shared/relative-time";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { StatusDot, type DotStatus } from "@/components/ui/status-dot";
|
||||
import type { ServerIdentity } from "@/features/status/server";
|
||||
import { plural } from "@/lib/i18n";
|
||||
import type { WorkspaceInfo } from "@/lib/protocol";
|
||||
|
||||
import { workspaceName } from "./commands";
|
||||
|
||||
function serverDot(status: ServerIdentity["status"]): DotStatus {
|
||||
if (status === "online") return "ok";
|
||||
if (status === "degraded") return "attention";
|
||||
return "exited";
|
||||
}
|
||||
|
||||
export interface ServerContextBarProps {
|
||||
server: ServerIdentity;
|
||||
workspaceCount: number;
|
||||
sessionCount: number;
|
||||
}
|
||||
|
||||
/** Single-server identity bar: dot + name + hostname:port + counts + status link. */
|
||||
export function ServerContextBar({ server, workspaceCount, sessionCount }: ServerContextBarProps) {
|
||||
const { t } = useTranslation();
|
||||
const hostPort = `${server.hostname}${server.port != null ? `:${server.port}` : ""}`;
|
||||
|
||||
return (
|
||||
<section className="ws-context" aria-label={t("workspaces.contextAria")}>
|
||||
<StatusDot status={serverDot(server.status)} title={t(`state.${server.status}`)} />
|
||||
<span className="ws-context__name truncate">{server.name}</span>
|
||||
<span className="ws-context__host mono muted">{hostPort}</span>
|
||||
<Badge tone="info">{plural("workspaces.count", workspaceCount)}</Badge>
|
||||
<Badge>{plural("workspaces.sessionCount", sessionCount)}</Badge>
|
||||
<span className="spacer" />
|
||||
<Link
|
||||
to="/status"
|
||||
className="ws-context__link"
|
||||
title={t("workspaces.contextAria")}
|
||||
aria-label={`${t("workspaces.contextAria")}: ${server.name} — ${t("workspaces.openStatus")}`}
|
||||
>
|
||||
{t("workspaces.openStatus")}
|
||||
<Icon name="chevron-right" />
|
||||
</Link>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
function instanceDot(workspace: WorkspaceInfo): { status: DotStatus; labelKey: string } {
|
||||
if (!workspace.exists) return { status: "err", labelKey: "workspaces.instanceMissing" };
|
||||
const status = workspace.instance?.status;
|
||||
switch (status) {
|
||||
case "ready":
|
||||
return { status: "ok", labelKey: "workspaces.instanceReady" };
|
||||
case "starting":
|
||||
return { status: "busy", labelKey: "workspaces.instanceStarting" };
|
||||
case "degraded":
|
||||
return { status: "attention", labelKey: "workspaces.instanceDegraded" };
|
||||
case "stopping":
|
||||
return { status: "attention", labelKey: "workspaces.instanceStopping" };
|
||||
case "unmanaged":
|
||||
return { status: "idle", labelKey: "workspaces.instanceUnmanaged" };
|
||||
case "stopped":
|
||||
default:
|
||||
return { status: "exited", labelKey: "workspaces.instanceStopped" };
|
||||
}
|
||||
}
|
||||
|
||||
export interface WorkspaceRowProps {
|
||||
workspace: WorkspaceInfo;
|
||||
}
|
||||
|
||||
/** One flat workspace row (folder + name + full cwd + count + rel + dot + enter). */
|
||||
export function WorkspaceRow({ workspace }: WorkspaceRowProps) {
|
||||
const { t } = useTranslation();
|
||||
const dot = instanceDot(workspace);
|
||||
const count = Math.max(workspace.liveCount || 0, workspace.sessionCount || 0);
|
||||
|
||||
return (
|
||||
<div className="list-row" data-workspace-id={workspace.workspaceId}>
|
||||
<span className="ico list-row__icon">
|
||||
<Icon name="folder" />
|
||||
</span>
|
||||
<div className="list-row__main">
|
||||
<div className="list-row__name">{workspaceName(workspace, t("workspaces.unnamed"))}</div>
|
||||
<div className="list-row__cwd mono muted truncate">{workspace.cwd}</div>
|
||||
</div>
|
||||
<Badge tone="info" className="list-row__count">
|
||||
{plural("workspaces.sessionCount", count)}
|
||||
</Badge>
|
||||
<RelativeTime ts={workspace.lastActiveAt} className="list-row__rel muted" />
|
||||
<StatusDot status={dot.status} title={t(dot.labelKey)} />
|
||||
<a
|
||||
className="btn btn--sm btn--primary list-row__go"
|
||||
href={`/chat?workspace=${encodeURIComponent(workspace.workspaceId)}`}
|
||||
>
|
||||
{t("workspaces.enter")}
|
||||
</a>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function WorkspacesSkeleton() {
|
||||
const { t } = useTranslation();
|
||||
return (
|
||||
<div className="list-row list-row--skeleton" role="status" aria-label={t("common.loading")}>
|
||||
<span className="skeleton skeleton--icon" />
|
||||
<div className="list-row__main">
|
||||
<span className="skeleton skeleton--name" />
|
||||
<span className="skeleton skeleton--cwd" />
|
||||
</div>
|
||||
<span className="skeleton skeleton--badge" />
|
||||
<span className="skeleton skeleton--time" />
|
||||
<span className="skeleton skeleton--dot" />
|
||||
<span className="skeleton skeleton--go" />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
Reference in new issue
Block a user