feat(web): React 19 + Vite + Tailwind v4 + shadcn foundation

- design tokens ported verbatim from the product design, data-theme light/dark
- app shell: topbar, sidebar/rail/tabbar responsive nav, lang + theme menus
- ui primitives (button/card/badge/dot/chip/tabs/dialog/sheet/toast/kv/seg/progress)
- api client, reconnecting ws client, zustand stores, route guard to /connect
- full zh/en dictionaries (key parity test), 32 vitest specs, dist committed
This commit is contained in:
yuez committed 2026-10-21 11:33:36 +08:00
1 parent 4e98ef8658
commit 5b55e622ea
63 files changed
+8466

No files matched your search

+76
View File
@@ -0,0 +1,76 @@
import { render, screen } from "@testing-library/react";
import { describe, expect, it } from "vitest";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Card, CardSub, CardTitle } from "@/components/ui/card";
import { StatusDot } from "@/components/ui/status-dot";
describe("Button", () => {
it("renders the base class and default variant", () => {
render(<Button>Open</Button>);
const button = screen.getByRole("button", { name: "Open" });
expect(button).toHaveClass("btn");
expect(button).toHaveAttribute("type", "button");
});
it("applies variant and size classes", () => {
render(
<Button variant="primary" size="sm">
Save
</Button>,
);
expect(screen.getByRole("button", { name: "Save" })).toHaveClass("btn", "btn--primary", "btn--sm");
});
it("supports disabled state", () => {
render(<Button disabled>Stop</Button>);
expect(screen.getByRole("button", { name: "Stop" })).toBeDisabled();
});
});
describe("Card", () => {
it("renders the card surface with title/sub", () => {
render(
<Card>
<CardTitle>Server info</CardTitle>
<CardSub>hostname</CardSub>
</Card>,
);
expect(screen.getByText("Server info").closest(".card")).toBeInTheDocument();
expect(screen.getByText("Server info")).toHaveClass("card__title");
expect(screen.getByText("hostname")).toHaveClass("card__sub");
});
it("renders the hover variant", () => {
const { container } = render(<Card hover>hover</Card>);
expect(container.firstElementChild).toHaveClass("card", "card--hover");
});
});
describe("StatusDot", () => {
it.each([
["busy", "dot--busy"],
["compacting", "dot--compacting"],
["idle", "dot--idle"],
["ok", "dot--ok"],
["err", "dot--err"],
["attention", "dot--attention"],
["exited", "dot--exited"],
] as const)("maps %s to %s", (status, expected) => {
const { container } = render(<StatusDot status={status} />);
expect(container.firstElementChild).toHaveClass("dot", expected);
});
it("exposes the state label when a title is provided", () => {
render(<StatusDot status="ok" title="Online" />);
expect(screen.getByLabelText("Online")).toHaveAttribute("title", "Online");
});
});
describe("Badge", () => {
it("maps semantic tones", () => {
const { container } = render(<Badge tone="warn">degraded</Badge>);
expect(container.firstElementChild).toHaveClass("badge", "badge--warn");
});
});
+101
View File
@@ -0,0 +1,101 @@
import { describe, expect, it } from "vitest";
import en from "@/locales/en.json";
import zh from "@/locales/zh.json";
type Catalog = Record<string, string>;
function flatten(value: unknown, prefix = ""): Record<string, string> {
if (!value || typeof value !== "object") return {};
const out: Record<string, string> = {};
for (const [key, child] of Object.entries(value as Record<string, unknown>)) {
const path = prefix ? `${prefix}.${key}` : key;
if (typeof child === "string") out[path] = child;
else if (child && typeof child === "object") Object.assign(out, flatten(child, path));
}
return out;
}
const zhFlat = flatten(zh as Catalog);
const enFlat = flatten(en as Catalog);
describe("i18n catalogs", () => {
it("have identical key sets", () => {
const zhKeys = new Set(Object.keys(zhFlat));
const enKeys = new Set(Object.keys(enFlat));
expect([...zhKeys].filter((key) => !enKeys.has(key))).toEqual([]);
expect([...enKeys].filter((key) => !zhKeys.has(key))).toEqual([]);
expect(zhKeys.size).toBeGreaterThan(300);
console.log(`i18n key parity: ${zhKeys.size} zh / ${enKeys.size} en`);
});
it("have a non-empty string for every key", () => {
for (const [key, value] of Object.entries(zhFlat)) {
expect(typeof value, key).toBe("string");
expect(value.length, key).toBeGreaterThan(0);
}
for (const [key, value] of Object.entries(enFlat)) {
expect(typeof value, key).toBe("string");
expect(value.length, key).toBeGreaterThan(0);
}
});
it("covers every prototype namespace", () => {
for (const prefix of [
"common.",
"shell.",
"language.",
"nav.",
"time.",
"state.",
"connect.",
"workspaces.",
"status.",
"chat.",
]) {
expect(Object.keys(zhFlat).some((key) => key.startsWith(prefix)), prefix).toBe(true);
expect(Object.keys(enFlat).some((key) => key.startsWith(prefix)), prefix).toBe(true);
}
// The prototype's English plural variants are mirrored in zh for parity.
for (const key of [
"workspaces.count.one",
"workspaces.count.other",
"workspaces.sessionCount.one",
"workspaces.sessionCount.other",
]) {
expect(zhFlat[key], key).toBeTruthy();
expect(enFlat[key], key).toBeTruthy();
}
});
it("keeps the copy contract for key shell strings", () => {
expect(zhFlat["nav.workspaces"]).toBe("工作空间");
expect(enFlat["nav.workspaces"]).toBe("Workspaces");
expect(zhFlat["connect.title"]).toBe("连接 pi2 服务器");
expect(enFlat["status.title"]).toBe("Server status");
expect(zhFlat["chat.tabSubagents"]).toBe("子代理");
expect(enFlat["chat.tabTodo"]).toBe("Todo");
});
});
describe("i18n runtime", () => {
it("interpolates single-brace params and switches languages", async () => {
const { default: i18n, plural, setLanguage } = await import("@/lib/i18n");
await setLanguage("zh");
expect(i18n.t("time.minutesAgo", { n: 3 })).toBe("3 分钟前");
expect(i18n.t("shell.serverChip", { name: "ThinkPad" })).toBe("服务器:ThinkPad,查看状态");
await setLanguage("en");
expect(i18n.t("time.minutesAgo", { n: 3 })).toBe("3m ago");
expect(i18n.t("shell.serverChip", { name: "ThinkPad" })).toBe("Server: ThinkPad, view status");
await setLanguage("zh");
expect(plural("workspaces.count", 2)).toBe("2 个工作空间");
expect(plural("workspaces.sessionCount", 1)).toBe("1 个会话");
await setLanguage("en");
expect(plural("workspaces.count", 2)).toBe("2 workspaces");
expect(plural("workspaces.count", 1)).toBe("1 workspace");
});
});
+25
View File
@@ -0,0 +1,25 @@
import { describe, expect, it } from "vitest";
import { connectHref, safeNext } from "@/lib/routing";
describe("safeNext", () => {
it("keeps whitelisted navigation routes with their query", () => {
expect(safeNext("/workspaces")).toBe("/workspaces");
expect(safeNext("/status?tab=devices")).toBe("/status?tab=devices");
expect(safeNext("/chat/01a15368")).toBe("/chat/01a15368");
expect(safeNext("/workspace/ws-pi2?x=1")).toBe("/workspace/ws-pi2?x=1");
});
it("falls back for unknown or unsafe targets", () => {
expect(safeNext(undefined)).toBe("/workspaces");
expect(safeNext("/servers")).toBe("/workspaces");
expect(safeNext("/connect")).toBe("/workspaces");
expect(safeNext("javascript:alert(1)")).toBe("/workspaces");
expect(safeNext("https://evil.example/not-a-page")).toBe("/workspaces");
});
it("builds an encoded connect redirect", () => {
expect(connectHref("/chat/01a1?tab=todo")).toBe("/connect?next=%2Fchat%2F01a1%3Ftab%3Dtodo");
expect(connectHref("/nope")).toBe("/connect?next=%2Fworkspaces");
});
});
+39
View File
@@ -0,0 +1,39 @@
import "@testing-library/jest-dom/vitest";
import { cleanup } from "@testing-library/react";
import { afterEach, vi } from "vitest";
afterEach(() => {
cleanup();
localStorage.clear();
document.documentElement.removeAttribute("data-theme");
});
// next-themes / responsive helpers expect these in jsdom.
if (!window.matchMedia) {
Object.defineProperty(window, "matchMedia", {
writable: true,
value: vi.fn().mockImplementation((query: string) => ({
matches: false,
media: query,
onchange: null,
addListener: vi.fn(),
removeListener: vi.fn(),
addEventListener: vi.fn(),
removeEventListener: vi.fn(),
dispatchEvent: vi.fn(),
})),
});
}
if (!globalThis.ResizeObserver) {
class ResizeObserverStub {
observe() {}
unobserve() {}
disconnect() {}
}
globalThis.ResizeObserver = ResizeObserverStub;
}
if (!Element.prototype.scrollIntoView) {
Element.prototype.scrollIntoView = vi.fn();
}
+144
View File
@@ -0,0 +1,144 @@
import { describe, expect, it } from "vitest";
import appCss from "@/styles/app.css?raw";
import tokensCss from "@/styles/tokens.css?raw";
function block(source: string, selector: string): string {
const start = source.indexOf(selector);
expect(start, `missing selector ${selector}`).toBeGreaterThanOrEqual(0);
const open = source.indexOf("{", start);
let depth = 0;
for (let i = open; i < source.length; i += 1) {
if (source[i] === "{") depth += 1;
if (source[i] === "}") {
depth -= 1;
if (depth === 0) return source.slice(open + 1, i);
}
}
throw new Error(`unclosed block ${selector}`);
}
function customProps(source: string): Record<string, string> {
const props: Record<string, string> = {};
for (const match of source.matchAll(/--([\w-]+)\s*:\s*([^;]+);/g)) {
const name = match[1];
const value = match[2];
if (name && value) props[name] = value.trim();
}
return props;
}
describe("design tokens", () => {
const light = customProps(block(tokensCss, ":root"));
const dark = customProps(block(tokensCss, 'html[data-theme="dark"]'));
it("defines the contract's semantic token names in :root", () => {
for (const name of [
"background",
"foreground",
"card",
"card-foreground",
"popover",
"muted",
"muted-foreground",
"accent",
"primary",
"primary-foreground",
"secondary",
"destructive",
"border",
"input",
"ring",
"sidebar",
"sidebar-foreground",
"sidebar-accent",
"role-user",
"role-agent",
"role-thinking",
"role-error",
"ok",
"warn",
"err",
"info",
"radius-sm",
"radius",
"radius-lg",
"space-1",
"space-8",
"font-sans",
"font-mono",
"topbar-h",
"sidebar-w",
"rail-w",
"tabbar-h",
]) {
expect(light[name], `--${name}`).toBeTruthy();
}
});
it("overrides the same surfaces in the dark data-theme block", () => {
expect(light.background).toBe("oklch(0.985 0.004 90)");
expect(dark.background).toBe("oklch(0.145 0.008 60)");
expect(light.foreground).not.toBe(dark.foreground);
for (const name of ["background", "foreground", "card", "muted", "muted-foreground", "primary", "border", "input", "ok", "warn", "role-user", "role-agent", "role-thinking"]) {
expect(dark[name], `--${name} dark override`).toBeTruthy();
}
// Dark borders are translucent white per the contract.
expect(dark.border).toContain("oklch(1 0 0");
});
it("maps every semantic token to a Tailwind color utility", () => {
const theme = block(appCss, "@theme inline");
const mapped = customProps(theme);
const expected: Record<string, string> = {
"color-background": "--background",
"color-foreground": "--foreground",
"color-card": "--card",
"color-card-foreground": "--card-foreground",
"color-popover": "--popover",
"color-muted": "--muted",
"color-muted-foreground": "--muted-foreground",
"color-accent": "--accent",
"color-primary": "--primary",
"color-primary-foreground": "--primary-foreground",
"color-secondary": "--secondary",
"color-destructive": "--destructive",
"color-border": "--border",
"color-input": "--input",
"color-ring": "--ring",
"color-sidebar": "--sidebar",
"color-sidebar-foreground": "--sidebar-foreground",
"color-sidebar-accent": "--sidebar-accent",
"color-role-user": "--role-user",
"color-role-agent": "--role-agent",
"color-role-thinking": "--role-thinking",
"color-role-error": "--role-error",
"color-ok": "--ok",
"color-warn": "--warn",
"color-err": "--err",
"color-info": "--info",
};
for (const [utility, token] of Object.entries(expected)) {
expect(mapped[utility], `--${utility}`).toBe(`var(${token})`);
}
expect(appCss).toContain("@custom-variant dark");
});
it("switches computed values with data-theme", () => {
const style = document.createElement("style");
style.textContent = tokensCss;
document.head.appendChild(style);
document.documentElement.dataset.theme = "light";
expect(getComputedStyle(document.documentElement).getPropertyValue("--background").trim()).toBe(
"oklch(0.985 0.004 90)",
);
document.documentElement.dataset.theme = "dark";
expect(getComputedStyle(document.documentElement).getPropertyValue("--background").trim()).toBe(
"oklch(0.145 0.008 60)",
);
style.remove();
});
});
+194
View File
@@ -0,0 +1,194 @@
import { afterEach, describe, expect, it, vi } from "vitest";
import { PiWsClient, type WebSocketLike, type WsFrame } from "@/lib/ws";
class FakeSocket implements WebSocketLike {
readyState = 0;
sent: WsFrame[] = [];
closed = false;
onopen: ((event: unknown) => void) | null = null;
onmessage: ((event: { data: unknown }) => void) | null = null;
onclose: ((event: { code?: number; reason?: string }) => void) | null = null;
onerror: ((event: unknown) => void) | null = null;
send(data: string): void {
this.sent.push(JSON.parse(data) as WsFrame);
}
close(): void {
this.closed = true;
this.readyState = 3;
this.onclose?.({ code: 1000, reason: "closed" });
}
open(): void {
this.readyState = 1;
this.onopen?.({});
}
receive(frame: Record<string, unknown>): void {
this.onmessage?.({ data: JSON.stringify(frame) });
}
serverClose(code = 1006): void {
this.readyState = 3;
this.onclose?.({ code });
}
frames(type: string): WsFrame[] {
return this.sent.filter((frame) => frame.type === type);
}
}
function createClient(token = "pkt_test") {
const sockets: FakeSocket[] = [];
const states: string[] = [];
const snapshots: unknown[] = [];
const events: unknown[] = [];
const client = new PiWsClient({
url: "ws://127.0.0.1:7676/api/v1/ws",
token,
heartbeatMs: 0,
socketFactory: () => {
const socket = new FakeSocket();
sockets.push(socket);
return socket;
},
handlers: {
onState: (state) => states.push(state),
onSnapshot: (snapshot) => snapshots.push(snapshot),
onEvent: (event) => events.push(event),
},
});
return { client, sockets, states, snapshots, events };
}
afterEach(() => {
vi.useRealTimers();
});
describe("PiWsClient", () => {
it("sends the auth frame first, then flushes subscriptions on hello_ack", () => {
vi.useFakeTimers();
const { client, sockets, states } = createClient();
client.connect();
expect(sockets).toHaveLength(1);
expect(states).toEqual(["connecting"]);
const socket = sockets[0]!;
socket.open();
expect(states).toEqual(["connecting", "authenticating"]);
expect(socket.sent[0]).toEqual({ v: 1, type: "auth", payload: { token: "pkt_test" } });
// Queued before authentication.
client.subscribe("s1");
expect(socket.frames("subscribe")).toHaveLength(0);
socket.receive({ v: 1, type: "hello_ack" });
expect(client.getState()).toBe("open");
expect(socket.frames("subscribe")).toEqual([
{ v: 1, type: "subscribe", payload: { sessionIds: ["s1"] } },
]);
});
it("reconnects with exponential backoff and resumes with sinceSeq", () => {
vi.useFakeTimers();
const { client, sockets, states, snapshots } = createClient();
client.connect();
sockets[0]!.open();
sockets[0]!.receive({ type: "hello_ack" });
client.subscribe(["s1"]);
sockets[0]!.receive({ type: "snapshot", sessionId: "s1", epoch: "e1", seq: 10, payload: { ok: true } });
expect(client.getLastSeq("s1")).toBe(10);
expect(snapshots).toHaveLength(1);
sockets[0]!.serverClose(1006);
expect(client.getState()).toBe("reconnecting");
vi.advanceTimersByTime(199);
expect(sockets).toHaveLength(1);
vi.advanceTimersByTime(1);
expect(sockets).toHaveLength(2);
sockets[1]!.open();
expect(sockets[1]!.sent[0]?.type).toBe("auth");
sockets[1]!.receive({ type: "hello_ack" });
expect(client.getState()).toBe("open");
expect(sockets[1]!.frames("subscribe")).toEqual([
{ v: 1, type: "subscribe", payload: { sessionIds: ["s1"], sinceSeq: { s1: 10 } } },
]);
// A successful hello_ack resets the backoff, so the next retry is 200ms again.
sockets[1]!.serverClose(1006);
vi.advanceTimersByTime(199);
expect(sockets).toHaveLength(2);
vi.advanceTimersByTime(1);
expect(sockets).toHaveLength(3);
expect(states).toContain("authenticating");
});
it("tracks event seq and ignores duplicates", () => {
vi.useFakeTimers();
const { client, sockets, events } = createClient();
client.connect();
sockets[0]!.open();
sockets[0]!.receive({ type: "hello_ack" });
client.subscribe("s1");
sockets[0]!.receive({ type: "snapshot", sessionId: "s1", seq: 4, payload: {} });
sockets[0]!.receive({ type: "event", sessionId: "s1", seq: 5, payload: { kind: "a" } });
sockets[0]!.receive({ type: "event", sessionId: "s1", seq: 5, payload: { kind: "duplicate" } });
sockets[0]!.receive({ type: "event", sessionId: "s1", seq: 6, payload: { kind: "b" } });
expect(client.getLastSeq("s1")).toBe(6);
expect(events).toHaveLength(2);
});
it("clears the resume cursor on resync_required", () => {
vi.useFakeTimers();
const { client, sockets } = createClient();
client.connect();
sockets[0]!.open();
sockets[0]!.receive({ type: "hello_ack" });
client.subscribe("s1");
sockets[0]!.receive({ type: "snapshot", sessionId: "s1", epoch: "e1", seq: 10, payload: {} });
sockets[0]!.receive({ type: "resync_required", sessionId: "s1" });
expect(client.getLastSeq("s1")).toBeUndefined();
expect(client.getEpoch("s1")).toBeUndefined();
});
it("stops reconnecting after close()", () => {
vi.useFakeTimers();
const { client, sockets } = createClient();
client.connect();
sockets[0]!.open();
sockets[0]!.receive({ type: "hello_ack" });
client.close();
expect(client.getState()).toBe("closed");
expect(sockets[0]!.closed).toBe(true);
vi.advanceTimersByTime(10_000);
expect(sockets).toHaveLength(1);
});
it("caps backoff at maxBackoffMs", () => {
vi.useFakeTimers();
const sockets: FakeSocket[] = [];
const client = new PiWsClient({
url: "ws://x",
token: "t",
heartbeatMs: 0,
initialBackoffMs: 200,
maxBackoffMs: 500,
socketFactory: () => {
const socket = new FakeSocket();
sockets.push(socket);
return socket;
},
});
client.connect();
// Fail four times without authenticating.
for (let i = 0; i < 4; i += 1) {
sockets[i]!.serverClose(1006);
vi.advanceTimersByTime(500);
}
expect(sockets.length).toBe(5);
});
});