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

+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 };
}