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:
yuez committed 2026-10-21 13:32:34 +08:00
1 parent 2e5d6d5006
commit 721661177c
61 files changed
+10931 -355

No files matched your search

+304
View File
@@ -0,0 +1,304 @@
import type { Block, Entry, TodoItem } from "@protocol/types";
/** Raw pi session entries are JSONL records without a stable TypeScript type on the wire. */
export type RawEntry = Record<string, unknown>;
export interface ProjectedTodo {
items: TodoItem[];
completed: number;
total: number;
}
/** A projected history entry. `pi2-todo` checkpoints carry their block inline. */
export interface ProjectedEntry extends Entry {
todo?: ProjectedTodo;
}
export interface EntriesCursor {
before?: string;
hasMore: boolean;
}
export interface EntriesPage {
entries: RawEntry[];
cursor: EntriesCursor;
}
function rec(value: unknown): Record<string, unknown> | undefined {
return value && typeof value === "object" && !Array.isArray(value) ? (value as Record<string, unknown>) : undefined;
}
function arr(value: unknown): unknown[] {
return Array.isArray(value) ? value : [];
}
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;
}
function idOf(raw: unknown): string | undefined {
return str(rec(raw)?.id);
}
function timestampOf(raw: Record<string, unknown>, message?: Record<string, unknown>): number {
const fromMessage = num(message?.timestamp);
if (fromMessage !== undefined) return fromMessage;
const iso = str(raw.timestamp);
if (iso) {
const parsed = Date.parse(iso);
if (Number.isFinite(parsed)) return parsed;
}
return 0;
}
function textOfContent(content: unknown): string {
if (typeof content === "string") return content;
const parts: string[] = [];
for (const raw of arr(content)) {
const block = rec(raw);
if (block?.type === "text" && typeof block.text === "string") parts.push(block.text);
}
return parts.join("\n");
}
function imagesOf(content: unknown): Entry["images"] | undefined {
const images: { mimeType: string; data: string }[] = [];
for (const raw of arr(content)) {
const block = rec(raw);
if (block?.type === "image" && typeof block.data === "string" && typeof block.mimeType === "string") {
images.push({ mimeType: block.mimeType, data: block.data });
}
}
return images.length ? images : undefined;
}
function contentToBlocks(content: unknown): Block[] {
if (typeof content === "string") return [{ type: "text", text: content }];
const blocks: Block[] = [];
for (const raw of arr(content)) {
const block = rec(raw);
if (!block) continue;
switch (block.type) {
case "text":
blocks.push({ type: "text", text: str(block.text) ?? "" });
break;
case "thinking":
blocks.push({
type: "thinking",
text: str(block.thinking) ?? str(block.text) ?? "",
...(block.redacted === true ? { redacted: true } : {}),
});
break;
case "toolCall":
blocks.push({
type: "tool",
toolCallId: str(block.id) ?? `call_${blocks.length}`,
name: str(block.name) ?? "tool",
args: block.arguments,
state: "pending",
});
break;
case "error":
blocks.push({ type: "error", text: str(block.text) ?? str(block.error) ?? "error" });
break;
default:
break;
}
}
return blocks;
}
function applyToolResult(entries: ProjectedEntry[], message: Record<string, unknown>): boolean {
const toolCallId = str(message.toolCallId);
if (!toolCallId) return false;
for (const entry of entries) {
for (const block of entry.blocks) {
if (block.type !== "tool" || block.toolCallId !== toolCallId) continue;
block.output = {
text: textOfContent(message.content),
...(message.details !== undefined ? { details: message.details } : {}),
isError: message.isError === true,
};
block.state = message.isError === true ? "error" : "done";
return true;
}
}
return false;
}
function normalizeTodo(data: unknown): ProjectedTodo | undefined {
const record = rec(data);
if (!record) return undefined;
const items: TodoItem[] = arr(record.todos).map((raw) => {
const item = rec(raw) ?? {};
return {
content: str(item.content) ?? "",
status: item.status === "completed" || item.status === "in_progress" ? item.status : "pending",
...(typeof item.activeForm === "string" ? { activeForm: item.activeForm } : {}),
};
});
if (!items.length) return undefined;
const completed = num(record.completed) ?? items.filter((item) => item.status === "completed").length;
const total = num(record.total) ?? items.length;
return { items, completed, total };
}
/**
* Project raw pi session entries (message / toolResult / `pi2-todo` custom
* checkpoints) into the render `Entry` shape. Non-conversation entries
* (header, label, model_change, …) are ignored. Tool results are folded into
* the assistant tool block they belong to, exactly like the live reducer keeps
* execution state on the block.
*/
export function projectEntries(rawEntries: unknown[]): ProjectedEntry[] {
const out: ProjectedEntry[] = [];
let synthetic = 0;
for (const value of rawEntries) {
const raw = rec(value);
if (!raw) continue;
const type = str(raw.type);
if (type === "message") {
const message = rec(raw.message);
if (!message) continue;
const role = str(message.role);
const ts = timestampOf(raw, message);
const id = str(raw.id) ?? `raw-${synthetic++}`;
if (role === "user") {
const blocks = contentToBlocks(message.content);
const images = imagesOf(message.content);
out.push({ id, role: "user", ts, blocks, done: true, ...(images ? { images } : {}) });
continue;
}
if (role === "assistant") {
const blocks = contentToBlocks(message.content);
const stopReason = str(message.stopReason);
const errorMessage = str(message.errorMessage);
if (stopReason === "error" || stopReason === "aborted" || errorMessage) {
blocks.push({
type: "error",
text: errorMessage ?? `assistant ${stopReason ?? "error"}`,
});
}
out.push({ id, role: "assistant", ts, blocks, done: true });
continue;
}
if (role === "toolResult") {
if (applyToolResult(out, message)) continue;
const toolCallId = str(message.toolCallId) ?? `call_${synthetic++}`;
out.push({
id,
role: "assistant",
ts,
done: true,
blocks: [
{
type: "tool",
toolCallId,
name: str(message.toolName) ?? "tool",
state: message.isError === true ? "error" : "done",
output: {
text: textOfContent(message.content),
...(message.details !== undefined ? { details: message.details } : {}),
isError: message.isError === true,
},
},
],
});
continue;
}
continue;
}
if (type === "custom" && str(raw.customType) === "pi2-todo") {
const todo = normalizeTodo(raw.data);
if (!todo) continue;
out.push({
id: str(raw.id) ?? `raw-${synthetic++}`,
role: "system",
ts: timestampOf(raw),
blocks: [],
done: true,
todo,
});
continue;
}
if (type === "custom_message" && raw.display === true) {
out.push({
id: str(raw.id) ?? `raw-${synthetic++}`,
role: "assistant",
ts: timestampOf(raw),
blocks: contentToBlocks(raw.content),
done: true,
});
}
}
return out;
}
/** Live snapshot entries win over the same id from a historical page. */
export function mergeEntries(history: Entry[], live: Entry[]): Entry[] {
if (!history.length) return live;
if (!live.length) return history;
const liveById = new Map(live.map((entry) => [entry.id, entry]));
const merged: Entry[] = history.map((entry) => liveById.get(entry.id) ?? entry);
const historical = new Set(history.map((entry) => entry.id));
for (const entry of live) {
if (!historical.has(entry.id)) merged.push(entry);
}
return merged;
}
/** Prepend an older page while never duplicating an id already rendered. */
export function prependUnique(existing: Entry[], older: Entry[]): Entry[] {
const seen = new Set(existing.map((entry) => entry.id));
const fresh = older.filter((entry) => !seen.has(entry.id));
return fresh.length ? [...fresh, ...existing] : existing;
}
/** Normalize `{entries, cursor:{before,hasMore}}` (and older cursor spellings). */
export function normalizeEntriesPage(raw: unknown): EntriesPage {
const record = rec(raw);
const entries = (Array.isArray(raw) ? raw : arr(record?.entries ?? record?.items)).filter(
(entry): entry is RawEntry => !!rec(entry),
);
const cursor = rec(record?.cursor);
const next = rec(record?.nextCursor);
const explicitHasMore = cursor?.hasMore ?? record?.hasMore;
return {
entries,
cursor: {
before: str(cursor?.before) ?? str(record?.before) ?? str(next?.before) ?? idOf(entries[0]),
hasMore: explicitHasMore === true,
},
};
}
/** Extract the tail entries a snapshot may carry alongside the state. */
export function snapshotEntries(payload: unknown): RawEntry[] {
const record = rec(payload);
return arr(record?.entries).filter((entry): entry is RawEntry => !!rec(entry));
}
/** Normalize a todo list from a `pi2:todo` event or session state. */
export function normalizeTodos(value: unknown): TodoItem[] {
return arr(value).map((raw) => {
const item = rec(raw) ?? {};
return {
content: str(item.content) ?? "",
status: item.status === "completed" || item.status === "in_progress" ? item.status : "pending",
...(typeof item.activeForm === "string" ? { activeForm: item.activeForm } : {}),
};
});
}
+6 -303
View File
@@ -1,306 +1,9 @@
// synced from pi2d/src/protocol/types.ts — do not edit by hand; re-copy when the wire types change.
/**
* pi2 wire protocol — shared types.
* Re-export shim for the canonical wire protocol types.
*
* Three surfaces, one vocabulary:
* browser <-> daemon (HTTP + WS)
* plugin <-> daemon (JSONL over unix socket)
* daemon <-> plugin (same JSONL envelope, reversed direction)
*
* The plugin is the single source of truth for session state; the daemon only
* routes, the browser only renders.
* The single source of truth is `../src/protocol/types.ts` in the daemon
* package (aliased as `@protocol`). This module used to hold a hand-copied
* duplicate; it now only forwards so existing imports keep working while the
* browser and the daemon cannot drift apart.
*/
export const PROTOCOL_VERSION = 1;
export type ThinkingLevel = "off" | "minimal" | "low" | "medium" | "high" | "xhigh" | "max";
export type SessionStatus = "starting" | "busy" | "compacting" | "idle" | "exited" | "interrupted";
export type ClientKind = "nvim" | "web" | "cli" | "daemon" | "system";
export interface ClientRef {
clientId: string;
kind: ClientKind;
}
export interface ModelRef {
provider: string;
id: string;
}
export interface UsageTotals {
input: number;
output: number;
cacheRead: number;
cacheWrite: number;
cost: number;
}
export interface ContextUsage {
tokens: number;
window: number;
percent: number;
}
export interface ToolOutput {
text?: string;
details?: unknown;
isError?: boolean;
}
export type Block =
| { type: "text"; text: string }
| { type: "thinking"; text: string; redacted?: boolean }
| {
type: "tool";
toolCallId: string;
name: string;
args?: unknown;
output?: ToolOutput;
state: "pending" | "running" | "done" | "error";
durationMs?: number;
}
| { type: "error"; text: string };
export type EntryRole = "user" | "assistant" | "system" | "notice";
export interface Entry {
id: string;
role: EntryRole;
ts: number;
blocks: Block[];
done: boolean;
messageId?: string;
images?: { mimeType: string; data: string }[];
}
export interface TodoItem {
content: string;
status: "pending" | "in_progress" | "completed";
activeForm?: string;
}
export interface QueueItem {
id: string;
text: string;
steer: boolean;
}
export interface TaskItem {
id: string;
command: string;
status: "running" | "completed" | "failed" | "stopped";
startTime: number;
durationMs?: number;
exitCode?: number | null;
outputFile?: string;
}
export type BatchItemStatus = "queued" | "spawning" | "running" | "ok" | "failed" | "cancelled";
export interface BatchItem {
ref: string;
name?: string;
status: BatchItemStatus;
error?: string;
}
export interface BatchItemCounts {
total: number;
done: number;
ok: number;
failed: number;
cancelled: number;
running: number;
}
export interface Batch {
batchId: string;
status: "running" | "completed" | "partial" | "failed" | "cancelled";
items: BatchItem[];
summary?: BatchItemCounts;
}
export interface Subagent {
id: string;
name?: string;
status: "active" | "completed" | "failed" | "interrupted" | "dormant";
model?: string;
thinking?: ThinkingLevel;
task?: string;
createdAt?: number;
lastActiveAt?: number;
live?: boolean;
children?: Subagent[];
}
export interface AttentionOption {
id: string;
label: string;
}
export interface AttentionItem {
requestId: string;
method: string;
title?: string;
message?: string;
options?: AttentionOption[];
/** Free-form payload; `diff` requests carry `{files:[{path,before,after}]}`. */
payload?: unknown;
timeoutSec?: number;
createdAt: number;
receivedAt: number;
}
export interface SessionFlags {
attention: boolean;
done: boolean;
error: boolean;
}
export interface SessionState {
sessionId: string;
workspaceId: string;
cwd: string;
name: string | null;
status: SessionStatus;
flags: SessionFlags;
model: ModelRef | null;
thinking: ThinkingLevel | null;
usage: UsageTotals;
contextUsage: ContextUsage | null;
queue: QueueItem[];
todos: TodoItem[];
tasks: TaskItem[];
batches: Batch[];
subagents: Subagent[];
attention: AttentionItem[];
entries: Entry[];
}
/* ------------------------------------------------------------------ */
/* Events */
/* ------------------------------------------------------------------ */
/**
* Pi native events are relayed verbatim (`message_start`, `message_update`,
* `tool_execution_*`, `queue_update`, `agent_*`, `turn_*`, `compaction_*`,
* `session_info_changed`, `thinking_level_changed`, `entry_appended`).
*
* Derived events are prefixed `pi2:` and are computed by the plugin only.
*/
export type SessionEventType =
| "agent_start"
| "agent_end"
| "agent_settled"
| "turn_start"
| "turn_end"
| "message_start"
| "message_update"
| "message_end"
| "tool_execution_start"
| "tool_execution_update"
| "tool_execution_end"
| "queue_update"
| "session_info_changed"
| "thinking_level_changed"
| "entry_appended"
| "compaction_start"
| "compaction_end"
| "pi2:session"
| "pi2:todo"
| "pi2:batch"
| "pi2:task"
| "pi2:subagents"
| "pi2:attention_request"
| "pi2:attention_resolved"
| "pi2:process_exit"
| "pi2:error";
export interface SessionEvent {
type: SessionEventType | string;
ts: number;
[key: string]: unknown;
}
/* ------------------------------------------------------------------ */
/* Envelopes */
/* ------------------------------------------------------------------ */
export interface InstanceState {
workspaceId: string;
instanceId: string;
status: "starting" | "ready" | "degraded" | "stopping" | "stopped" | "unmanaged";
nvimPid: number | null;
pluginVersion: string | null;
hasUI: boolean;
attachedClients: number;
listenAddr: string | null;
startedAt: number | null;
reason?: string;
}
export interface WorkspaceInfo {
workspaceId: string;
cwd: string;
name: string;
alias?: string | null;
pinned?: boolean;
hidden?: boolean;
trusted: boolean;
exists: boolean;
/** Number of session files discovered on disk (header scan). */
sessionCount: number;
/** Number of live sessions reported by the instance, if any. */
liveCount: number;
lastActiveAt: number | null;
instance: InstanceState | null;
}
export type DaemonCommandMethod =
| "instance.ensure"
| "instance.shutdown"
| "workspace.add"
| "workspace.update"
| "workspace.remove"
| "workspace.refresh"
| "pair.create"
| "pair.redeem"
| "device.revoke"
| "session.create"
| "session.open"
| "session.close"
| "session.resume"
| "session.rename"
| "session.fork"
| "session.compact"
| "session.setModel"
| "session.setThinking"
| "session.hibernate"
| "prompt.send"
| "prompt.abort"
| "queue.remove"
| "queue.setSteer"
| "attention.respond"
| "subagent.dispatch"
| "subagent.stop"
| "subagent.steer"
| "subagent.read"
| "task.stop"
| "system.doctor"
| "system.shutdown";
export interface CommandRequest {
method: DaemonCommandMethod | string;
params?: Record<string, unknown>;
sessionId?: string;
clientRequestId?: string;
}
export interface ErrorBody {
code: string;
message: string;
retryable: boolean;
details?: Record<string, unknown>;
}
export * from "@protocol/types";