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

+115
View File
@@ -0,0 +1,115 @@
import type { Batch, Entry, SessionState, Subagent, TodoItem } from "@protocol/types";
import { emptySessionState } from "@/features/chat/session-state";
export function entryFixture(overrides: Partial<Entry> = {}): Entry {
return {
id: "e1",
role: "assistant",
ts: Date.now(),
blocks: [{ type: "text", text: "hello" }],
done: true,
...overrides,
};
}
export function subagentFixture(overrides: Partial<Subagent> = {}): Subagent {
return {
id: "sa1",
name: "researcher",
status: "active",
model: "claude-sonnet-4-5",
thinking: "low",
task: "Research the auth flow",
createdAt: Date.now() - 60_000,
lastActiveAt: Date.now() - 5_000,
...overrides,
};
}
export function todoFixture(): TodoItem[] {
return [
{ content: "Inspect callers", status: "completed" },
{ content: "Apply fix", status: "in_progress", activeForm: "Applying the fix" },
{ content: "Run tests", status: "pending" },
];
}
export function batchFixture(overrides: Partial<Batch> = {}): Batch {
return {
batchId: "b1",
status: "running",
items: [
{ ref: "0", name: "researcher", status: "ok" },
{ ref: "1", name: "writer", status: "failed", error: "boom" },
{ ref: "2", name: "tester", status: "running" },
],
...overrides,
};
}
export function sessionFixture(overrides: Partial<SessionState> = {}): SessionState {
return {
...emptySessionState({
sessionId: "s1",
workspaceId: "w1",
cwd: "/repo",
name: "Alpha",
status: "busy",
model: { provider: "anthropic", id: "claude-sonnet-4-5" },
thinking: "high",
}),
...overrides,
};
}
/** Snapshot carrying one of every stream block kind. */
export function fullStreamSession(): SessionState {
const now = Date.now();
const user = entryFixture({
id: "u1",
role: "user",
ts: now - 40_000,
blocks: [{ type: "text", text: "Fix the auth bug" }],
});
const assistant = entryFixture({
id: "a1",
role: "assistant",
ts: now - 30_000,
done: true,
blocks: [
{ type: "thinking", text: "Check every caller before editing" },
{ type: "text", text: "Looking at the auth path now." },
{
type: "tool",
toolCallId: "call_1",
name: "bash",
args: { command: "ls -la" },
state: "done",
durationMs: 1200,
output: { text: "a.txt\nb.txt" },
},
{
type: "tool",
toolCallId: "call_2",
name: "edit",
args: { path: "src/auth.ts", oldText: "a", newText: "b" },
state: "error",
durationMs: 300,
output: { text: "permission denied", isError: true },
},
],
});
const error = entryFixture({
id: "n1",
role: "notice",
ts: now - 20_000,
blocks: [{ type: "error", text: "agent aborted" }],
});
return sessionFixture({
entries: [user, assistant, error],
todos: todoFixture(),
batches: [batchFixture()],
subagents: [subagentFixture(), subagentFixture({ id: "sa2", name: "writer", status: "failed" })],
});
}
+94
View File
@@ -0,0 +1,94 @@
import type { AttentionItem } from "@protocol/types";
import { fireEvent, render, screen, waitFor } from "@testing-library/react";
import { beforeAll, describe, expect, it, vi } from "vitest";
import { setLanguage } from "@/lib/i18n";
import { AttentionDialog } from "@/features/chat/attention";
import { sessionFixture } from "./chat-fixtures";
beforeAll(async () => {
await setLanguage("en");
});
function attention(overrides: Partial<AttentionItem> = {}): AttentionItem {
return {
requestId: "att-1",
method: "select",
title: "Run this command?",
message: "Allow the pending tool call",
options: [
{ id: "allow-once", label: "Allow once" },
{ id: "deny", label: "Deny" },
],
timeoutSec: 10,
createdAt: Date.now(),
receivedAt: Date.now(),
...overrides,
};
}
describe("attention dialog", () => {
it("renders the request and responds with the chosen option", async () => {
const item = attention();
const onRespond = vi.fn();
render(
<AttentionDialog
session={sessionFixture({ attention: [item] })}
onRespond={onRespond}
onRemoteResolved={vi.fn()}
/>,
);
expect(await screen.findByText("Run this command?")).toBeInTheDocument();
fireEvent.click(screen.getByRole("button", { name: "Allow once" }));
expect(onRespond).toHaveBeenCalledWith(item, "allow-once");
});
it("closes and reports when another client resolves the request", async () => {
const item = attention();
const onRemoteResolved = vi.fn();
const { rerender } = render(
<AttentionDialog
session={sessionFixture({ attention: [item] })}
onRespond={vi.fn()}
onRemoteResolved={onRemoteResolved}
/>,
);
expect(await screen.findByText("Run this command?")).toBeInTheDocument();
expect(onRemoteResolved).not.toHaveBeenCalled();
rerender(
<AttentionDialog
session={sessionFixture({ attention: [] })}
onRespond={vi.fn()}
onRemoteResolved={onRemoteResolved}
/>,
);
await waitFor(() => expect(onRemoteResolved).toHaveBeenCalledWith("att-1"));
});
it("renders the diff review variant and sends the plugin's review JSON", async () => {
const item = attention({
method: "diff",
title: "Review the edit",
payload: {
files: [{ path: "src/auth.ts", before: "const a = 1;\n", after: "const a = 2;\n" }],
},
});
const onRespond = vi.fn();
render(
<AttentionDialog
session={sessionFixture({ attention: [item] })}
onRespond={onRespond}
onRemoteResolved={vi.fn()}
/>,
);
expect(await screen.findByText("src/auth.ts")).toBeInTheDocument();
fireEvent.click(screen.getByRole("button", { name: "Accept all" }));
expect(onRespond).toHaveBeenCalledTimes(1);
const response = onRespond.mock.calls[0]?.[1];
expect(typeof response).toBe("string");
expect(JSON.parse(String(response))).toEqual({ result: "Accepted" });
});
});
+135
View File
@@ -0,0 +1,135 @@
import { fireEvent, render, screen } from "@testing-library/react";
import { beforeAll, describe, expect, it, vi } from "vitest";
import { Composer } from "@/features/chat/composer";
import { chatCommands } from "@/features/chat/commands";
import { setLanguage } from "@/lib/i18n";
import { sessionFixture } from "./chat-fixtures";
beforeAll(async () => {
await setLanguage("en");
});
const MODELS = [
{
provider: "anthropic",
models: [{ id: "claude-sonnet-4-5" }, { id: "claude-haiku-4-5" }],
},
];
function renderComposer(session = sessionFixture()) {
const onSend = vi.fn();
const onAbort = vi.fn();
const onRemoveQueue = vi.fn();
const onSetSteer = vi.fn();
const onSetModel = vi.fn();
const onSetThinking = vi.fn();
const utils = render(
<Composer
session={session}
models={MODELS}
connected
onSend={onSend}
onAbort={onAbort}
onRemoveQueue={onRemoveQueue}
onSetSteer={onSetSteer}
onSetModel={onSetModel}
onSetThinking={onSetThinking}
/>,
);
return { ...utils, onSend, onAbort, onRemoveQueue, onSetSteer, onSetModel, onSetThinking };
}
describe("composer", () => {
it("sends on Enter and keeps Shift+Enter for a newline", () => {
const { onSend } = renderComposer();
const textarea = screen.getByRole("textbox", { name: "Message input" });
fireEvent.change(textarea, { target: { value: "hello" } });
fireEvent.keyDown(textarea, { key: "Enter", shiftKey: true });
expect(onSend).not.toHaveBeenCalled();
fireEvent.keyDown(textarea, { key: "Enter" });
expect(onSend).toHaveBeenCalledWith("hello", []);
expect(textarea).toHaveValue("");
});
it("turns the send button into an abort button while the session is busy", () => {
const session = sessionFixture({ status: "busy" });
const { onAbort, onSend } = renderComposer(session);
fireEvent.click(screen.getByRole("button", { name: "Abort" }));
expect(onAbort).toHaveBeenCalledTimes(1);
expect(onSend).not.toHaveBeenCalled();
});
it("renders queue chips with steer toggle and remove", () => {
const session = sessionFixture({
status: "idle",
queue: [{ id: "q1", text: "later please", steer: false }],
});
const { onRemoveQueue, onSetSteer } = renderComposer(session);
expect(screen.getByText("later please")).toBeInTheDocument();
fireEvent.click(screen.getByRole("checkbox", { name: "Steer" }));
expect(onSetSteer).toHaveBeenCalledWith("q1", true);
fireEvent.click(screen.getByRole("button", { name: "Remove queued message" }));
expect(onRemoveQueue).toHaveBeenCalledWith("q1");
});
it("builds the documented command payloads", () => {
expect(chatCommands.sendPrompt("s1", "hi")).toMatchObject({
method: "prompt.send",
sessionId: "s1",
params: { text: "hi", mode: "queue" },
});
expect(chatCommands.sendPrompt("s1", "hi", [{ mimeType: "image/png", data: "AAA" }])).toMatchObject({
params: { text: "hi", mode: "queue", images: [{ mimeType: "image/png", data: "AAA" }] },
});
expect(chatCommands.abort("s1")).toMatchObject({ method: "prompt.abort", sessionId: "s1" });
expect(chatCommands.removeQueued("s1", "q1")).toMatchObject({
method: "queue.remove",
params: { queueId: "q1" },
});
expect(chatCommands.setQueueSteer("s1", "q1", true)).toMatchObject({
method: "queue.setSteer",
params: { queueId: "q1", steer: true },
});
expect(chatCommands.setModel("s1", { provider: "anthropic", id: "m" })).toMatchObject({
method: "session.setModel",
params: { provider: "anthropic", id: "m" },
});
expect(chatCommands.setThinking("s1", "high")).toMatchObject({
method: "session.setThinking",
params: { level: "high" },
});
expect(chatCommands.respondAttention("s1", "att-1", "allow-once")).toMatchObject({
method: "attention.respond",
params: { requestId: "att-1", response: "allow-once" },
});
expect(
chatCommands.dispatchSubagent("s1", {
task: "do it",
name: "worker",
model: { provider: "anthropic", id: "m" },
thinking: "low",
wait: true,
cancelSiblingsOnFail: true,
}),
).toMatchObject({
method: "subagent.dispatch",
params: {
task: "do it",
name: "worker",
model: { provider: "anthropic", id: "m" },
thinking: "low",
wait: true,
cancelSiblingsOnFail: true,
},
});
expect(chatCommands.stopTask("s1", "t1")).toMatchObject({
method: "task.stop",
params: { taskId: "t1" },
});
});
});
+139
View File
@@ -0,0 +1,139 @@
import { describe, expect, it } from "vitest";
import {
mergeEntries,
normalizeEntriesPage,
prependUnique,
projectEntries,
} from "@/lib/entry-projection";
import { entryFixture } from "./chat-fixtures";
const TS = 1_733_234_400_000;
function rawEntries() {
return [
{
type: "message",
id: "u1",
timestamp: new Date(TS).toISOString(),
message: { role: "user", content: "hello", timestamp: TS },
},
{
type: "message",
id: "a1",
timestamp: new Date(TS + 1).toISOString(),
message: {
role: "assistant",
timestamp: TS + 1,
content: [
{ type: "thinking", thinking: "hmm" },
{ type: "text", text: "on it" },
{ type: "toolCall", id: "call_1", name: "bash", arguments: { command: "ls" } },
],
},
},
{
type: "message",
id: "tr1",
timestamp: new Date(TS + 2).toISOString(),
message: {
role: "toolResult",
timestamp: TS + 2,
toolCallId: "call_1",
toolName: "bash",
isError: false,
content: [{ type: "text", text: "file.txt" }],
},
},
{
type: "custom",
id: "todo1",
customType: "pi2-todo",
timestamp: new Date(TS + 3).toISOString(),
data: {
todos: [
{ content: "one", status: "completed" },
{ content: "two", status: "in_progress", activeForm: "doing two" },
],
},
},
];
}
describe("history entry projection", () => {
it("projects raw messages, folds tool results and keeps todo checkpoints", () => {
const entries = projectEntries(rawEntries());
expect(entries.map((entry) => entry.id)).toEqual(["u1", "a1", "todo1"]);
const assistant = entries[1];
expect(assistant?.blocks[0]).toEqual({ type: "thinking", text: "hmm" });
expect(assistant?.blocks[1]).toEqual({ type: "text", text: "on it" });
expect(assistant?.blocks[2]).toMatchObject({
type: "tool",
toolCallId: "call_1",
state: "done",
output: { text: "file.txt" },
});
const todo = entries[2];
expect(todo?.todo).toMatchObject({ completed: 1, total: 2 });
expect(todo?.todo?.items[1]).toMatchObject({ status: "in_progress", activeForm: "doing two" });
});
it("merges live entries by id (live wins) without dropping history", () => {
const history = [entryFixture({ id: "a", blocks: [{ type: "text", text: "old" }] })];
const live = [
entryFixture({ id: "a", blocks: [{ type: "text", text: "new" }] }),
entryFixture({ id: "b", blocks: [{ type: "text", text: "tail" }] }),
];
const merged = mergeEntries(history, live);
expect(merged.map((entry) => entry.id)).toEqual(["a", "b"]);
expect(merged[0]?.blocks[0]).toEqual({ type: "text", text: "new" });
});
it("prepends older pages without duplicating ids", () => {
const page2 = projectEntries([
{
type: "message",
id: "s02",
message: { role: "user", content: "b", timestamp: TS + 2 },
},
{
type: "message",
id: "s03",
message: { role: "user", content: "c", timestamp: TS + 3 },
},
]);
const page1 = projectEntries([
{
type: "message",
id: "s01",
message: { role: "user", content: "a", timestamp: TS + 1 },
},
{
type: "message",
id: "s02",
message: { role: "user", content: "b", timestamp: TS + 2 },
},
]);
const combined = prependUnique(page2, page1);
expect(combined.map((entry) => entry.id)).toEqual(["s01", "s02", "s03"]);
expect(new Set(combined.map((entry) => entry.id)).size).toBe(combined.length);
});
it("normalizes the entries page cursor", () => {
expect(
normalizeEntriesPage({
entries: [{ id: "e1" }, { id: "e2" }],
cursor: { before: "e1", hasMore: true },
bytes: 10,
}),
).toEqual({ entries: [{ id: "e1" }, { id: "e2" }], cursor: { before: "e1", hasMore: true } });
expect(
normalizeEntriesPage({ entries: [{ id: "e9" }], hasMore: true }).cursor,
).toEqual({ before: "e9", hasMore: true });
expect(normalizeEntriesPage({ entries: [] }).cursor).toEqual({ before: undefined, hasMore: false });
});
});
+152
View File
@@ -0,0 +1,152 @@
import { existsSync, readFileSync } from "node:fs";
import { join } from "node:path";
import process from "node:process";
import type { SessionEvent } from "@protocol/types";
import { describe, expect, it } from "vitest";
import { applySessionEvent, emptySessionState } from "@/features/chat/session-state";
function append(state: ReturnType<typeof emptySessionState>, event: SessionEvent) {
return applySessionEvent(state, event);
}
describe("canonical reducer integration", () => {
it("streams text deltas and lets authoritative message_end replace the block", () => {
let state = emptySessionState({ sessionId: "s1", workspaceId: "w1" });
state = append(state, { type: "agent_start", ts: 1 });
state = append(state, {
type: "message_start",
ts: 2,
message: { role: "assistant", content: [] },
});
state = append(state, {
type: "message_update",
ts: 3,
assistantMessageEvent: { type: "text_start", contentIndex: 0 },
});
state = append(state, {
type: "message_update",
ts: 4,
assistantMessageEvent: { type: "text_delta", contentIndex: 0, delta: "Hel" },
});
state = append(state, {
type: "message_update",
ts: 5,
assistantMessageEvent: { type: "text_delta", contentIndex: 0, delta: "lo" },
});
expect(state.status).toBe("busy");
expect(state.entries).toHaveLength(1);
expect(state.entries[0]?.blocks[0]).toEqual({ type: "text", text: "Hello" });
state = append(state, {
type: "message_end",
ts: 6,
message: {
role: "assistant",
content: [{ type: "text", text: "Hello world" }],
usage: { input: 10, output: 2, cacheRead: 0, cacheWrite: 0, cost: { total: 0.01 } },
},
});
expect(state.entries[0]?.blocks[0]).toEqual({ type: "text", text: "Hello world" });
expect(state.entries[0]?.done).toBe(true);
expect(state.usage).toMatchObject({ input: 10, output: 2, cost: 0.01 });
});
it("applies entry_appended for user messages and folds tool results into the tool block", () => {
const ts = Date.now();
let state = emptySessionState({ sessionId: "s1", workspaceId: "w1" });
state = append(state, {
type: "entry_appended",
ts,
entry: {
type: "message",
id: "u1",
timestamp: new Date(ts).toISOString(),
message: { role: "user", content: "please fix it", timestamp: ts },
},
});
expect(state.entries).toHaveLength(1);
expect(state.entries[0]).toMatchObject({ id: "u1", role: "user" });
state.entries.push({
id: "m1",
role: "assistant",
ts,
done: false,
blocks: [
{
type: "tool",
toolCallId: "call_9",
name: "bash",
state: "running",
},
],
});
state = append(state, {
type: "entry_appended",
ts: ts + 1,
entry: {
type: "message",
id: "tr1",
message: {
role: "toolResult",
toolCallId: "call_9",
toolName: "bash",
isError: false,
content: [{ type: "text", text: "ok" }],
},
},
});
const tool = state.entries.find((entry) => entry.id === "m1")?.blocks[0];
expect(tool).toMatchObject({ type: "tool", state: "done", output: { text: "ok" } });
});
it("deduplicates the same user entry arriving twice", () => {
const ts = Date.now();
const event: SessionEvent = {
type: "entry_appended",
ts,
entry: {
type: "message",
id: "u1",
message: { role: "user", content: "hello", timestamp: ts },
},
};
let state = emptySessionState({ sessionId: "s1", workspaceId: "w1" });
state = append(state, event);
state = append(state, { ...event, entry: { ...(event.entry as object), id: "u2" } });
expect(state.entries.filter((entry) => entry.role === "user")).toHaveLength(1);
});
it("replays the pi2d basic-turn fixture through the shared reducer", () => {
const fixture = join(process.cwd(), "..", "fixtures", "basic-turn", "events.jsonl");
if (!existsSync(fixture)) {
expect(true).toBe(true);
return;
}
const events = readFileSync(fixture, "utf8")
.split("\n")
.filter((line) => line.trim())
.map((line) => JSON.parse(line) as SessionEvent);
let state = emptySessionState({
sessionId: "basic-turn",
workspaceId: "ws-fixture",
cwd: "/repo",
});
for (const event of events) state = applySessionEvent(state, event);
const assistant = state.entries.find((entry) => entry.role === "assistant");
const tool = assistant?.blocks.find((block) => block.type === "tool");
expect(tool).toMatchObject({
type: "tool",
toolCallId: "call_1",
name: "bash",
state: "done",
output: { text: "a.txt\nb.txt" },
});
expect(state.status).toBe("idle");
});
});
+90
View File
@@ -0,0 +1,90 @@
import { fireEvent, render, screen } from "@testing-library/react";
import { beforeAll, describe, expect, it, vi } from "vitest";
import { setLanguage } from "@/lib/i18n";
import { MessageStream } from "@/features/chat/message-stream";
import { fullStreamSession } from "./chat-fixtures";
beforeAll(async () => {
await setLanguage("en");
});
function renderStream() {
const session = fullStreamSession();
const utils = render(
<MessageStream
session={session}
entries={session.entries}
hasMore={false}
loadingOlder={false}
error={null}
onLoadOlder={vi.fn()}
onRetry={vi.fn()}
onOpenSubagent={vi.fn()}
/>,
);
return { ...utils, session };
}
describe("chat message stream", () => {
it("renders user, assistant, thinking, tool, todo, batch and error blocks from a snapshot", () => {
renderStream();
expect(screen.getByText("Fix the auth bug")).toBeInTheDocument();
expect(screen.getByText("Fix the auth bug").closest("article")).toHaveClass("msg--user");
expect(screen.getByText("Looking at the auth path now.")).toBeInTheDocument();
expect(screen.getByText("Check every caller before editing")).toBeInTheDocument();
expect(screen.getByText("bash")).toBeInTheDocument();
expect(screen.getByText("edit")).toBeInTheDocument();
expect(screen.getByText("Todo · 1/3")).toBeInTheDocument();
expect(screen.getByText("Applying the fix")).toBeInTheDocument();
expect(screen.getByText("Apply fix")).toBeInTheDocument();
expect(screen.getByText("Batch dispatch · 2/3")).toBeInTheDocument();
expect(screen.getByText("writer")).toBeInTheDocument();
expect(screen.getByText("agent aborted")).toBeInTheDocument();
expect(screen.getByText("agent aborted").closest(".msg__error")).not.toBeNull();
});
it("expands a tool card to show output and an edit diff", () => {
renderStream();
const bashButton = screen.getByText("bash").closest("button");
expect(bashButton).not.toBeNull();
fireEvent.click(bashButton!);
expect(screen.getByText(/a\.txt/)).toBeInTheDocument();
expect(screen.getByText(/"command": "ls -la"/)).toBeInTheDocument();
const editButton = screen.getByText("edit").closest("button");
fireEvent.click(editButton!);
expect(screen.getByText("permission denied")).toBeInTheDocument();
expect(screen.getAllByText("src/auth.ts").length).toBeGreaterThan(0);
});
it("shows a streaming caret only for an unfinished assistant entry", () => {
const session = fullStreamSession();
session.entries = [
{
id: "a-live",
role: "assistant",
ts: Date.now(),
done: false,
blocks: [{ type: "text", text: "partial answer" }],
},
];
render(
<MessageStream
session={session}
entries={session.entries}
hasMore={false}
loadingOlder={false}
error={null}
onLoadOlder={vi.fn()}
onRetry={vi.fn()}
onOpenSubagent={vi.fn()}
/>,
);
expect(screen.getByText("partial answer")).toHaveClass("streaming");
});
});
+82
View File
@@ -0,0 +1,82 @@
import { fireEvent, render, screen, within } from "@testing-library/react";
import type { ComponentProps } from "react";
import { beforeAll, describe, expect, it, vi } from "vitest";
import { setLanguage } from "@/lib/i18n";
import { SessionTree } from "@/features/chat/session-tree";
import { sessionFixture, subagentFixture } from "./chat-fixtures";
beforeAll(async () => {
await setLanguage("en");
});
function renderTree(props: Partial<ComponentProps<typeof SessionTree>> = {}) {
const onSelectSession = vi.fn();
const onToggleCollapse = vi.fn();
const onToggleAll = vi.fn();
const sessions = props.sessions ?? [
sessionFixture({ sessionId: "s1", name: "Alpha", subagents: [subagentFixture()] }),
sessionFixture({ sessionId: "s2", name: "Beta", subagents: [] }),
];
const utils = render(
<SessionTree
sessions={sessions}
selectedId="s1"
filter=""
collapsed={{}}
connected
onFilter={vi.fn()}
onToggleCollapse={onToggleCollapse}
onToggleAll={onToggleAll}
onSelectSession={onSelectSession}
onNewSession={vi.fn()}
onRenameSession={vi.fn()}
onCloseSession={vi.fn()}
{...props}
/>,
);
return { ...utils, sessions, onSelectSession, onToggleCollapse, onToggleAll };
}
describe("session tree", () => {
it("selects a session and shows the nested subagent", () => {
const { onSelectSession } = renderTree();
fireEvent.click(screen.getByRole("button", { name: "Beta" }));
expect(onSelectSession).toHaveBeenCalledWith("s2");
expect(screen.getByText("researcher")).toBeInTheDocument();
expect(screen.getByText("claude-sonnet-4-5 · low")).toBeInTheDocument();
});
it("folds a parent without drawing vertical guides", () => {
const { onToggleCollapse, rerender, sessions } = renderTree();
const row = screen.getByRole("button", { name: "Alpha" });
fireEvent.click(within(row).getByLabelText("Collapse"));
expect(onToggleCollapse).toHaveBeenCalledWith("s1");
rerender(
<SessionTree
sessions={sessions}
selectedId="s1"
filter=""
collapsed={{ s1: true }}
onFilter={vi.fn()}
onToggleCollapse={vi.fn()}
onToggleAll={vi.fn()}
onSelectSession={vi.fn()}
onNewSession={vi.fn()}
onRenameSession={vi.fn()}
onCloseSession={vi.fn()}
/>,
);
expect(screen.queryByText("researcher")).not.toBeInTheDocument();
});
it("filters sessions by name and toggles all rows", () => {
const { onToggleAll } = renderTree({ filter: "Beta" });
expect(screen.queryByText("Alpha")).not.toBeInTheDocument();
expect(screen.getByText("Beta")).toBeInTheDocument();
fireEvent.click(screen.getByRole("button", { name: "Collapse or expand all" }));
expect(onToggleAll).toHaveBeenCalledTimes(1);
});
});
+124
View File
@@ -0,0 +1,124 @@
import { fireEvent, screen, waitFor, within } from "@testing-library/react";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { commandCalls, mockApi } from "./helpers/api-mock";
import { renderPage } from "./helpers/render-page";
import { setLanguage } from "@/lib/i18n";
import { ConnectPage } from "@/pages/connect";
const infoBody = {
v: 1,
daemonId: "daemon-1",
machineId: "machine-1",
platform: "linux",
capabilities: ["read", "steer"],
limits: {},
};
function routes() {
return [
{ path: "/connect", component: ConnectPage },
{ path: "/workspaces", component: () => <div>Workspaces destination</div> },
{ path: "/status", component: () => <div>Status destination</div> },
];
}
function redeemRoute() {
return {
method: "POST" as const,
path: "/api/v1/cmd",
handler: () => ({
body: {
accepted: true,
token: "pkt_test",
scopes: ["read", "steer"],
server: { name: "ThinkPad", hostname: "thinkpad" },
},
}),
};
}
beforeEach(async () => {
await setLanguage("en");
});
afterEach(() => {
vi.unstubAllGlobals();
});
describe("ConnectPage", () => {
it("validates host, port and token inline without calling the daemon", async () => {
const fetchMock = mockApi([redeemRoute()]);
await renderPage(routes(), "/connect", { paired: false });
const submit = screen.getByRole("button", { name: "Connect" });
fireEvent.click(submit);
expect(await screen.findByText("Enter the server address")).toBeInTheDocument();
fireEvent.change(screen.getByLabelText("Host"), { target: { value: "192.168.2.10" } });
fireEvent.change(screen.getByLabelText("Port"), { target: { value: "99999" } });
fireEvent.click(submit);
expect(await screen.findByText("Port must be 1–65535")).toBeInTheDocument();
fireEvent.change(screen.getByLabelText("Port"), { target: { value: "4321" } });
fireEvent.click(submit);
expect(await screen.findByText("Enter the pairing token")).toBeInTheDocument();
expect(commandCalls(fetchMock)).toHaveLength(0);
});
it("redeems a manual pairing, stores endpoint + token and redirects", async () => {
const fetchMock = mockApi([redeemRoute()]);
const { router } = await renderPage(routes(), "/connect", { paired: false });
fireEvent.change(screen.getByLabelText("Host"), { target: { value: "192.168.2.10" } });
fireEvent.change(screen.getByLabelText("Port"), { target: { value: "4321" } });
fireEvent.change(screen.getByPlaceholderText("Pairing token (pkt_…)"), {
target: { value: "ABCD-1234" },
});
fireEvent.change(screen.getByPlaceholderText("e.g. My browser"), {
target: { value: "My browser" },
});
fireEvent.click(screen.getByRole("button", { name: "Connect" }));
await waitFor(() =>
expect(localStorage.getItem("pi2-device-token")).toBe("Bearer pkt_test"),
);
expect(localStorage.getItem("pi2-endpoint")).toBe("http://192.168.2.10:4321");
expect(localStorage.getItem("pi2-connection")).toBe("paired");
const commands = commandCalls(fetchMock);
expect(commands).toHaveLength(1);
expect(commands[0]?.method).toBe("pair.redeem");
expect(commands[0]?.params).toMatchObject({
code: "ABCD-1234",
deviceName: "My browser",
});
await waitFor(() => expect(router.state.location.pathname).toBe("/workspaces"));
expect(await screen.findByText("Workspaces destination")).toBeInTheDocument();
});
it("shows the paired summary and clears storage on confirmed disconnect", async () => {
mockApi([{ path: "/api/v1/info", handler: () => ({ body: infoBody }) }]);
await renderPage(routes(), "/connect", {
paired: true,
storage: {
"pi2-device": "Test browser",
"pi2-endpoint": "http://192.168.2.10:4321",
},
});
expect(await screen.findByText("Current connection")).toBeInTheDocument();
expect(screen.getByText("Test browser")).toBeInTheDocument();
fireEvent.click(screen.getByRole("button", { name: "Disconnect" }));
const dialog = await screen.findByRole("dialog");
fireEvent.click(within(dialog).getByRole("button", { name: "Disconnect" }));
await waitFor(() => expect(localStorage.getItem("pi2-device-token")).toBeNull());
expect(localStorage.getItem("pi2-connection")).toBe("unpaired");
expect(await screen.findByRole("button", { name: "Scan to pair" })).toBeInTheDocument();
expect(screen.queryByText("Current connection")).not.toBeInTheDocument();
});
});
+74
View File
@@ -0,0 +1,74 @@
import { vi } from "vitest";
export interface MockRequest {
url: URL;
method: string;
body: unknown;
}
export interface MockReply {
status?: number;
body?: unknown;
}
export interface MockRoute {
method?: "GET" | "POST" | "DELETE" | "PUT";
path: string | RegExp;
handler: (request: MockRequest) => MockReply | Promise<MockReply>;
}
function matches(route: MockRoute, method: string, pathname: string): boolean {
if (route.method && route.method !== method) return false;
return typeof route.path === "string" ? route.path === pathname : route.path.test(pathname);
}
/**
* MSW-style fetch fake: a small route table instead of per-URL stubs.
* Unhandled requests fail loudly so a page cannot silently hit the network.
*/
export function mockApi(routes: MockRoute[]) {
const fetchMock = vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => {
const raw =
typeof input === "string" ? input : input instanceof URL ? input.toString() : input.url;
const url = new URL(raw, "http://localhost");
const method = (init?.method ?? "GET").toUpperCase();
let body: unknown;
if (typeof init?.body === "string") {
try {
body = JSON.parse(init.body);
} catch {
body = init.body;
}
}
const route = routes.find((candidate) => matches(candidate, method, url.pathname));
if (!route) throw new Error(`Unhandled request: ${method} ${url.pathname}`);
const reply = await route.handler({ url, method, body });
const status = reply.status ?? 200;
return new Response(status === 204 ? null : JSON.stringify(reply.body ?? {}), {
status,
headers: { "content-type": "application/json" },
});
});
vi.stubGlobal("fetch", fetchMock);
return fetchMock;
}
export interface CommandCall {
method: string;
params?: Record<string, unknown>;
}
/** Parse the recorded POST /api/v1/cmd bodies. */
export function commandCalls(fetchMock: ReturnType<typeof mockApi>): CommandCall[] {
return fetchMock.mock.calls
.filter(([input, init]) => {
const raw = typeof input === "string" ? input : input instanceof URL ? input.toString() : input.url;
const url = new URL(raw, "http://localhost");
return url.pathname === "/api/v1/cmd" && (init?.method ?? "GET").toUpperCase() === "POST";
})
.map(([, init]) => {
const parsed = JSON.parse(String(init?.body ?? "{}")) as CommandCall;
return parsed;
});
}
+75
View File
@@ -0,0 +1,75 @@
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import {
Outlet,
RouterProvider,
createMemoryHistory,
createRootRoute,
createRoute,
createRouter,
} from "@tanstack/react-router";
import { render } from "@testing-library/react";
import type { ComponentType } from "react";
import { useConnectionStore } from "@/stores/connection";
export interface TestRoute {
path: string;
component: ComponentType;
}
export interface RenderPageOptions {
paired?: boolean;
storage?: Record<string, string>;
}
/**
* Mount a page inside a minimal memory router + isolated QueryClient.
* The root renders an Outlet so each route component mounts without AppShell.
*/
export async function renderPage(
routes: TestRoute[],
initialPath: string,
options: RenderPageOptions = {},
) {
localStorage.clear();
if (options.paired ?? true) {
localStorage.setItem("pi2-connection", "paired");
localStorage.setItem("pi2-device-token", "test-token");
localStorage.setItem("pi2-endpoint", "http://127.0.0.1:4321");
localStorage.setItem("pi2-device", "Test browser");
localStorage.setItem("pi2-connected-at", String(Date.now()));
}
for (const [key, value] of Object.entries(options.storage ?? {})) localStorage.setItem(key, value);
useConnectionStore.getState().refreshFromStorage();
const rootRoute = createRootRoute({ component: () => <Outlet /> });
const routeTree = rootRoute.addChildren(
routes.map((route) =>
createRoute({
getParentRoute: () => rootRoute,
path: route.path,
component: () => <route.component />,
}),
),
);
const router = createRouter({
routeTree,
history: createMemoryHistory({ initialEntries: [initialPath] }),
defaultPreload: false,
});
const queryClient = new QueryClient({
defaultOptions: {
queries: { retry: false, gcTime: 0, staleTime: 0, refetchOnWindowFocus: false },
mutations: { retry: false },
},
});
const result = render(
<QueryClientProvider client={queryClient}>
<RouterProvider router={router} />
</QueryClientProvider>,
);
await router.load();
return { ...result, router, queryClient };
}
+142
View File
@@ -0,0 +1,142 @@
import { fireEvent, screen, waitFor, within } from "@testing-library/react";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { commandCalls, mockApi } from "./helpers/api-mock";
import { renderPage } from "./helpers/render-page";
import { setLanguage } from "@/lib/i18n";
import { StatusPage } from "@/pages/status";
const infoBody = {
v: 1,
daemonId: "daemon-1",
machineId: "machine-1",
platform: "linux",
capabilities: ["read", "steer"],
limits: { maxInstances: 5 },
};
const workspacesBody = [
{
workspaceId: "ws-1",
cwd: "/home/me/work",
name: "Work",
trusted: true,
exists: true,
sessionCount: 2,
liveCount: 1,
lastActiveAt: Date.now(),
instance: null,
},
];
const healthBody = {
ok: false,
checkedAt: Date.now(),
items: [
{ name: "plugin", ok: true, detail: "connected" },
{ name: "linsor", ok: false, detail: "degraded" },
],
};
const resourcesBody = {
instances: [
{
workspaceId: "ws-1",
instanceId: "instance-1",
nvimPid: 4242,
rssBytes: 512 * 1024 * 1024,
sessions: 2,
hasUI: true,
},
],
totalRssBytes: 512 * 1024 * 1024,
physicalMemoryBytes: 2048 * 1024 * 1024,
warn: true,
reason: "rss > soft limit",
};
const modelsBody = {
providers: [
{
provider: "anthropic",
models: [{ id: "claude-sonnet-4", contextWindow: 200_000, reasoning: true }],
},
],
};
function routes() {
return [
{ path: "/status", component: StatusPage },
{ path: "/connect", component: () => <div>Connect destination</div> },
{ path: "/workspaces", component: () => <div>Workspaces destination</div> },
];
}
function apiRoutes(devicesHandler = () => ({ body: { devices: devicesBody } })) {
return [
{ path: "/api/v1/info", handler: () => ({ body: infoBody }) },
{ path: "/api/v1/health", handler: () => ({ body: healthBody }) },
{ path: "/api/v1/resources", handler: () => ({ body: resourcesBody }) },
{ path: "/api/v1/workspaces", handler: () => ({ body: workspacesBody }) },
{ path: "/api/v1/models", handler: () => ({ body: modelsBody }) },
{ path: "/api/v1/devices", handler: devicesHandler },
{ method: "POST" as const, path: "/api/v1/cmd", handler: () => ({ body: { accepted: true } }) },
];
}
const devicesBody = [
{
id: "dev-1",
name: "Pixel",
kind: "phone",
scopes: ["read", "steer"],
lastActiveAt: Date.now() - 60_000,
revokedAt: null,
},
];
beforeEach(async () => {
await setLanguage("en");
});
afterEach(() => {
vi.unstubAllGlobals();
});
describe("StatusPage", () => {
it("renders server, health, resources, models and devices", async () => {
mockApi(apiRoutes());
await renderPage(routes(), "/status", { paired: true });
expect(await screen.findByText("Server info")).toBeInTheDocument();
expect(await screen.findByText("plugin")).toBeInTheDocument();
expect(screen.getByText("linsor")).toBeInTheDocument();
expect(screen.getByText("25%")).toBeInTheDocument();
expect(
screen.getByText("Memory is close to the soft limit; new instances may start slowly."),
).toBeInTheDocument();
expect(await screen.findByText("claude-sonnet-4")).toBeInTheDocument();
expect(screen.getByText("200k")).toBeInTheDocument();
expect(screen.getByText("reasoning")).toBeInTheDocument();
expect(await screen.findByText("Pixel")).toBeInTheDocument();
expect(screen.getByText("Paired devices")).toBeInTheDocument();
});
it("revokes a device only after the confirmation dialog", async () => {
const fetchMock = mockApi(apiRoutes());
await renderPage(routes(), "/status", { paired: true });
await screen.findByText("Pixel");
fireEvent.click(screen.getByRole("button", { name: "Revoke" }));
const dialog = await screen.findByRole("dialog");
expect(within(dialog).getByText('Revoke access for "Pixel"? The phone\'s next request will fail.')).toBeInTheDocument();
fireEvent.click(within(dialog).getByRole("button", { name: "Revoke" }));
await waitFor(() => expect(screen.queryByText("Pixel")).not.toBeInTheDocument());
const commands = commandCalls(fetchMock);
expect(commands).toHaveLength(1);
expect(commands[0]).toEqual({ method: "device.revoke", params: { deviceId: "dev-1" } });
});
});
+158
View File
@@ -0,0 +1,158 @@
import { fireEvent, screen, waitFor, within } from "@testing-library/react";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { commandCalls, mockApi } from "./helpers/api-mock";
import { renderPage } from "./helpers/render-page";
import { setLanguage } from "@/lib/i18n";
import type { WorkspaceInfo } from "@/lib/protocol";
import { WorkspacePage } from "@/pages/workspace";
import { WorkspacesPage } from "@/pages/workspaces";
const infoBody = {
v: 1,
daemonId: "daemon-1",
machineId: "machine-1",
platform: "linux",
capabilities: ["read", "steer"],
limits: { maxInstances: 5 },
};
function workspace(overrides: Partial<WorkspaceInfo> & Pick<WorkspaceInfo, "workspaceId" | "cwd" | "name">): WorkspaceInfo {
return {
trusted: true,
exists: true,
sessionCount: 0,
liveCount: 0,
lastActiveAt: 0,
instance: null,
...overrides,
};
}
function routes() {
return [
{ path: "/workspaces", component: WorkspacesPage },
{ path: "/chat", component: () => <div>Chat destination</div> },
{ path: "/status", component: () => <div>Status destination</div> },
];
}
beforeEach(async () => {
await setLanguage("en");
});
afterEach(() => {
vi.unstubAllGlobals();
});
describe("WorkspacesPage", () => {
it("sorts pinned workspaces first, then by lastActiveAt descending", async () => {
const items = [
workspace({ workspaceId: "ws-b", cwd: "/work/b", name: "Bravo", lastActiveAt: 3_000 }),
workspace({ workspaceId: "ws-a", cwd: "/work/a", name: "Alpha", pinned: true, lastActiveAt: 1_000 }),
workspace({ workspaceId: "ws-c", cwd: "/work/c", name: "Charlie", lastActiveAt: 2_000 }),
];
mockApi([
{ path: "/api/v1/info", handler: () => ({ body: infoBody }) },
{ path: "/api/v1/workspaces", handler: () => ({ body: items }) },
]);
const { container } = await renderPage(routes(), "/workspaces", { paired: true });
await screen.findByText("Bravo");
const names = [...container.querySelectorAll(".list-row__name")].map((node) => node.textContent);
expect(names).toEqual(["Alpha", "Bravo", "Charlie"]);
});
it("renders the empty state without a server picker", async () => {
mockApi([
{ path: "/api/v1/info", handler: () => ({ body: infoBody }) },
{ path: "/api/v1/workspaces", handler: () => ({ body: [] }) },
]);
await renderPage(routes(), "/workspaces", { paired: true });
expect(await screen.findByText("No workspaces yet")).toBeInTheDocument();
expect(screen.getAllByRole("button", { name: "Open new workspace" }).length).toBeGreaterThan(0);
expect(screen.queryByRole("combobox")).not.toBeInTheDocument();
});
it("shows an error state with retry when the list request fails", async () => {
let attempts = 0;
mockApi([
{ path: "/api/v1/info", handler: () => ({ body: infoBody }) },
{
path: "/api/v1/workspaces",
handler: () => {
attempts += 1;
return { status: 500, body: { error: { code: "E_INTERNAL", message: "boom" } } };
},
},
]);
await renderPage(routes(), "/workspaces", { paired: true });
expect(await screen.findByText("Could not load workspaces")).toBeInTheDocument();
expect(attempts).toBe(1);
fireEvent.click(screen.getByRole("button", { name: "Retry" }));
await waitFor(() => expect(attempts).toBe(2));
});
it("validates the path, then runs workspace.add + instance.ensure and navigates", async () => {
const base = [workspace({ workspaceId: "ws-old", cwd: "/work/old", name: "Old project" })];
let items = base;
const fetchMock = mockApi([
{ path: "/api/v1/info", handler: () => ({ body: infoBody }) },
{ path: "/api/v1/workspaces", handler: () => ({ body: items }) },
{
method: "POST",
path: "/api/v1/cmd",
handler: ({ body }) => {
const command = body as { method?: string };
if (command.method === "workspace.add") {
items = [...base, workspace({ workspaceId: "ws-new", cwd: "/work/new", name: "New project" })];
return { body: { accepted: true, workspaceId: "ws-new" } };
}
return { body: { accepted: true } };
},
},
]);
const { router } = await renderPage(routes(), "/workspaces", { paired: true });
await screen.findByText("Old project");
fireEvent.click(screen.getByRole("button", { name: "Open new workspace" }));
const dialog = await screen.findByRole("dialog");
fireEvent.click(within(dialog).getByRole("button", { name: "Open" }));
expect(await within(dialog).findByText("Enter a working directory path")).toBeInTheDocument();
expect(commandCalls(fetchMock)).toHaveLength(0);
fireEvent.change(within(dialog).getByLabelText("Path"), { target: { value: "/work/new" } });
fireEvent.change(within(dialog).getByLabelText("Display name"), { target: { value: "New project" } });
fireEvent.click(within(dialog).getByRole("button", { name: "Open" }));
await waitFor(() => expect(router.state.location.pathname).toBe("/chat"));
expect(router.state.location.href).toContain("workspace=ws-new");
const commands = commandCalls(fetchMock);
expect(commands.map((command) => command.method)).toEqual(["workspace.add", "instance.ensure"]);
expect(commands[1]?.params).toEqual({ workspaceId: "ws-new" });
expect(await screen.findByText("Chat destination")).toBeInTheDocument();
});
it("redirects /workspace/:workspaceId deep links into chat", async () => {
mockApi([{ path: "/api/v1/info", handler: () => ({ body: infoBody }) }]);
const { router } = await renderPage(
[
{ path: "/workspace/$workspaceId", component: WorkspacePage },
{ path: "/chat", component: () => <div>Chat destination</div> },
],
"/workspace/ws-42",
{ paired: true },
);
await waitFor(() => expect(router.state.location.pathname).toBe("/chat"));
expect(router.state.location.href).toContain("workspace=ws-42");
expect(await screen.findByText("Chat destination")).toBeInTheDocument();
});
});