From 604fec5ea0ea7024fab63c143567c4752ccd8c1e Mon Sep 17 00:00:00 2001 From: yuez Date: Wed, 28 Oct 2026 08:14:17 +0800 Subject: [PATCH] feat(web): read host stats and the bare models endpoint on the status page The metrics tiles now prefer the daemon's own sample (`resources.system`, then `info.cpu/mem/disk`) over the old RSS-over-physical-memory guess, and each tile gained the detail that makes the number actionable: cores and 1-minute load, used/total bytes, the filesystem the disk figure describes. The models card stops asking for a workspace it does not have. It calls the bare endpoint (no spawn), polls every 1.5 s while the plugin's cache is still filling (bounded to 12 rounds), and tells the three empty states apart instead of showing one generic "no models": still fetching, no live instance, no live session. With no workspace to key on, `fetchModels` also tolerates a legacy daemon that requires the parameter, retrying with the first visible workspace. Smaller fixes that fell out of the same read: `formatBytes` printed "4.00 GiB" for a whole number of GiB, and the workspaces query now polls every 5 s only while the socket is down, so a dropped connection still refreshes the page. --- web/src/features/status/metrics-block.tsx | 29 +-- web/src/features/status/models-card.tsx | 195 +++++++++------ web/src/features/status/queries.ts | 59 ++++- web/src/features/status/server.ts | 2 +- web/src/lib/api.ts | 31 ++- web/src/locales/en.json | 6 + web/src/locales/zh.json | 6 + web/src/pages/status.tsx | 14 +- web/tests/models-card.test.tsx | 276 ++++++++++++++++++++++ web/tests/status-page.test.tsx | 47 +++- 10 files changed, 560 insertions(+), 105 deletions(-) create mode 100644 web/tests/models-card.test.tsx diff --git a/web/src/features/status/metrics-block.tsx b/web/src/features/status/metrics-block.tsx index 44b9b39..865e73e 100644 --- a/web/src/features/status/metrics-block.tsx +++ b/web/src/features/status/metrics-block.tsx @@ -3,7 +3,7 @@ import { useTranslation } from "react-i18next"; import { Icon } from "@/components/icons"; import { RelativeTime } from "@/components/shared/relative-time"; import type { ResourcesResponse } from "@/lib/api"; -import { formatUptime, type ServerIdentity } from "@/features/status/server"; +import { formatBytes, formatUptime, type ServerIdentity } from "@/features/status/server"; import { ErrorBlock } from "./card-parts"; @@ -61,17 +61,18 @@ export function MetricsBlock({ onRetry, }: MetricsBlockProps) { const { t } = useTranslation(); - const cpu = percent(server.cpu); - // `/info` may not carry a memory percentage; `/resources` gives RSS and the - // physical total, so derive the ratio instead of showing "—". - const mem = - server.mem != null - ? percent(server.mem) - : resources && resources.physicalMemoryBytes > 0 - ? percent((resources.totalRssBytes / resources.physicalMemoryBytes) * 100) - : null; - const disk = percent(server.disk); + const system = resources?.system; + const cpu = percent(system?.cpuPercent ?? server.cpu); + const mem = percent(system?.memPercent ?? server.mem); + const disk = percent(system?.diskPercent ?? server.disk); const live = t("status.live", { defaultValue: "Live" }); + const cpuMeta = system + ? `${system.cpuCores} ${t("status.cores")}${system.loadAvg ? ` · ${t("status.load")} ${system.loadAvg[0].toFixed(2)}` : ""}` + : live; + const memMeta = system ? `${formatBytes(system.memUsedBytes)} / ${formatBytes(system.memTotalBytes)}` : live; + const diskMeta = system ? ( + {system.diskPath} + ) : live; const counts: Array<[string, string]> = [ [t("status.workspaces"), String(workspaceCount)], @@ -91,7 +92,7 @@ export function MetricsBlock({
-
{live}
+
{cpuMeta}
@@ -100,7 +101,7 @@ export function MetricsBlock({
-
{live}
+
{memMeta}
@@ -109,7 +110,7 @@ export function MetricsBlock({
-
{live}
+
{diskMeta}
diff --git a/web/src/features/status/models-card.tsx b/web/src/features/status/models-card.tsx index a9133ca..1d09c89 100644 --- a/web/src/features/status/models-card.tsx +++ b/web/src/features/status/models-card.tsx @@ -1,10 +1,11 @@ -import { useEffect, useMemo, useState } from "react"; +import { type ReactNode, 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 type { ModelsResponse } from "@/features/status/queries"; import { formatContextWindow } from "@/features/status/server"; import { ErrorBlock, LoadingBlock, StatusCard, StatusEmpty } from "./card-parts"; @@ -14,10 +15,12 @@ export interface ModelsCardProps { loading: boolean; error: string | null; onRetry: () => void; + pending?: boolean; + pendingReason?: ModelsResponse["pendingReason"] | null; } /** Card 4 — provider accordion with mono model ids, context windows, reasoning badges. */ -export function ModelsCard({ providers, loading, error, onRetry }: ModelsCardProps) { +export function ModelsCard({ providers, loading, error, onRetry, pending, pendingReason }: ModelsCardProps) { const { t } = useTranslation(); const [query, setQuery] = useState(""); const [openProviders, setOpenProviders] = useState>( @@ -54,74 +57,130 @@ export function ModelsCard({ providers, loading, error, onRetry }: ModelsCardPro }); } + // State machine: + // 1. error → ErrorBlock + // 2. loading with no data yet → LoadingBlock (initial fetch in progress) + // 3. providers empty + no-instance or no-live-session → StatusEmpty + // (checked before the generic pending hint: those reasons are also pending) + // 4. pending fetch with no providers yet → LoadingBlock + aria-live pending hint (NOT an error) + // 5. providers empty otherwise → search bar + StatusEmpty (no-models copy) + // 6. providers present → search input + provider accordion + let body: ReactNode; + + if (error) { + body = ; + } else if (loading && providers.length === 0) { + body = ; + } else if ( + providers.length === 0 && + (pendingReason === "no-instance" || pendingReason === "no-live-session") + ) { + body = ( + + ); + } else if (pending && providers.length === 0) { + body = ( +
+ +

+ {t("status.modelsPendingText", { + defaultValue: "Fetching the catalogue from a running Neovim", + })} +

+
+ ); + } else if (providers.length === 0) { + body = ( + <> +
+ + setQuery(event.target.value)} + /> +
+ + + ); + } else { + body = ( + <> +
+ + setQuery(event.target.value)} + /> +
+ + {groups.length === 0 ? ( + + ) : ( +
+ {groups.map((group) => { + const expanded = Boolean(needle) || openProviders.has(group.provider); + return ( +
+ + {expanded ? ( +
+ {group.models.map((model) => ( +
+ {model.id} + + {formatContextWindow(model.contextWindow)} + + {model.reasoning ? ( + + {t("status.reasoning")} + + ) : null} + {group.provider === "cliproxyapi" ? ( + {t("status.scoped")} + ) : null} +
+ ))} +
+ ) : null} +
+ ); + })} +
+ )} + + ); + } + return ( - {error ? ( - - ) : loading ? ( - - ) : ( - <> -
- - setQuery(event.target.value)} - /> -
- - {providers.length === 0 ? ( - - ) : groups.length === 0 ? ( - - ) : ( -
- {groups.map((group) => { - const expanded = Boolean(needle) || openProviders.has(group.provider); - return ( -
- - {expanded ? ( -
- {group.models.map((model) => ( -
- {model.id} - - {formatContextWindow(model.contextWindow)} - - {model.reasoning ? ( - - {t("status.reasoning")} - - ) : null} - {group.provider === "cliproxyapi" ? ( - {t("status.scoped")} - ) : null} -
- ))} -
- ) : null} -
- ); - })} -
- )} - - )} + {body}
); } diff --git a/web/src/features/status/queries.ts b/web/src/features/status/queries.ts index 393b1aa..14c9d03 100644 --- a/web/src/features/status/queries.ts +++ b/web/src/features/status/queries.ts @@ -6,9 +6,11 @@ import { type HealthResponse, type InfoResponse, type ModelInfo, + type ModelsResponse, type ResourcesResponse, } from "@/lib/api"; import type { SessionState, TaskItem, WorkspaceInfo } from "@/lib/protocol"; +import { useConnectionStore } from "@/stores/connection"; /** * `GET /api/v1/devices` answers a **bare array** (`auth.listDevices()`); older @@ -31,9 +33,13 @@ export interface DevicesResponse { devices: DeviceEntry[]; } -export interface ModelsResponse { - providers: ModelInfo[]; -} +/** + * `GET /api/v1/models` answer. The plugin answers `pending: true` on the first + * call (it kicks off `get_available_models`) and fills `providers` later, so a + * client must poll until `pending` is false. The BARE endpoint never spawns a + * Neovim — it scans ready instances only. + */ +export type { ModelsResponse } from "@/lib/api"; /** Accept the daemon's bare device array and the legacy `{devices:[…]}` envelope. */ export function normalizeDevices(payload: unknown): DeviceEntry[] { @@ -46,8 +52,26 @@ export async function fetchDevices(signal?: AbortSignal): Promise("/api/v1/devices", { signal })) }; } -export async function fetchModels(workspaceId: string, signal?: AbortSignal): Promise { - return apiRequest(`/api/v1/models?workspaceId=${encodeURIComponent(workspaceId)}`, { signal }); +/** + * `GET /api/v1/models` — the BARE endpoint: no workspaceId, no spawn. + * Legacy tolerance: a bare array payload normalises to `{providers, pending:false}`. + */ +export async function fetchModels(legacyWorkspaceId?: string | null, signal?: AbortSignal): Promise { + try { + const raw = await apiRequest("/api/v1/models", { signal }); + if (Array.isArray(raw)) return { providers: raw as ModelInfo[], pending: false }; + return raw as ModelsResponse; + } catch (error) { + if ( + legacyWorkspaceId && + error instanceof Error && + "code" in error && + ["E_BAD_REQUEST", "E_NOT_FOUND", "E_METHOD_NOT_ALLOWED"].includes(String((error as { code?: unknown }).code)) + ) { + return apiRequest(`/api/v1/models?workspaceId=${encodeURIComponent(legacyWorkspaceId)}`, { signal }); + } + throw error; + } } /** @@ -154,6 +178,7 @@ export function useWorkspacesQuery() { queryKey: ["workspaces"], queryFn: async ({ signal }) => normalizeWorkspaces(await apiRequest("/api/v1/workspaces", { signal })), staleTime: 10_000, + refetchInterval: () => (useConnectionStore.getState().wsState === "open" ? false : 5_000), }); } @@ -203,11 +228,25 @@ export function useWorkspaceSessionsQueries(workspaceIds: string[], enabled = tr }); } -export function useModelsQuery(workspaceId: string | null | undefined) { +/** + * `GET /api/v1/models` — BARE endpoint, no workspaceId, never spawns. + * Polls every 1500 ms while `pending === true` (up to 12 rounds), then stops. + */ +export function useModelsQuery(legacyWorkspaceId?: string | null, enabled = true) { return useQuery({ - queryKey: ["models", workspaceId ?? ""], - queryFn: ({ signal }) => fetchModels(workspaceId ?? "", signal), - enabled: Boolean(workspaceId), - staleTime: 60_000, + queryKey: ["models"], + queryFn: ({ signal }) => fetchModels(legacyWorkspaceId, signal), + enabled, + staleTime: 30_000, + retry: 1, + refetchInterval: (query) => { + if ( + query.state.data?.pending === true && + (query.state.dataUpdateCount ?? 0) < 12 + ) { + return 1500; + } + return false; + }, }); } diff --git a/web/src/features/status/server.ts b/web/src/features/status/server.ts index eed21e4..d2bc7bd 100644 --- a/web/src/features/status/server.ts +++ b/web/src/features/status/server.ts @@ -204,7 +204,7 @@ export function formatBytes(bytes: number | null | undefined): string { value /= 1024; unit += 1; } - const digits = value >= 100 || unit === 0 ? 0 : value >= 10 ? 1 : 2; + const digits = Number.isInteger(value) || value >= 100 || unit === 0 ? 0 : value >= 10 ? 1 : 2; return `${value.toFixed(digits)} ${units[unit]}`; } diff --git a/web/src/lib/api.ts b/web/src/lib/api.ts index 8b85304..79599b1 100644 --- a/web/src/lib/api.ts +++ b/web/src/lib/api.ts @@ -257,6 +257,12 @@ export interface InfoResponse { /** Additive identity fields (daemon ≥ 0.2): OS label and process uptime. */ os?: string; uptimeMs?: number; + /** Resource percentages from newer daemons (0..100). */ + cpu?: number; + mem?: number; + disk?: number; + cpuCores?: number; + loadAvg?: [number, number, number] | null; /** Daemon does not send status today; resolveServerStatus() is the authority (a newer daemon may still send it as an override). */ status?: "online" | "degraded" | "offline"; } @@ -289,10 +295,33 @@ export interface ModelInfo { models: { id: string; contextWindow: number; reasoning: boolean }[]; } +export interface ModelsResponse { + providers: ModelInfo[]; + pending?: boolean; + workspaceId?: string | null; + pendingReason?: "fetching" | "no-instance" | "no-live-session"; +} + +export interface SystemStats { + sampledAt: number; + cpuPercent: number | null; + cpuCores: number; + loadAvg: [number, number, number] | null; + memUsedBytes: number; + memTotalBytes: number; + memPercent: number; + diskPath: string; + diskUsedBytes: number | null; + diskTotalBytes: number | null; + diskPercent: number | null; +} + export interface ResourcesResponse { instances: { workspaceId: string; instanceId: string; nvimPid: number | null; rssBytes: number | null; sessions: number; hasUI: boolean }[]; totalRssBytes: number; physicalMemoryBytes: number; + /** Absent on daemons < 0.1.5. */ + system?: SystemStats; warn: boolean; reason?: string; } @@ -340,8 +369,6 @@ export const api = { devices: (signal?: AbortSignal) => request("/api/v1/devices", { signal }), revokeDevice: (deviceId: string, signal?: AbortSignal) => request(`/api/v1/devices/${encodeURIComponent(deviceId)}`, { method: "DELETE", signal }), - models: (workspaceId: string, signal?: AbortSignal) => - request(`/api/v1/models?workspaceId=${encodeURIComponent(workspaceId)}`, { signal }), resources: (signal?: AbortSignal) => request("/api/v1/resources", { signal }), diagnostics: (signal?: AbortSignal) => request("/api/v1/diagnostics", { signal }), command: (body: { method: string; params?: Record; sessionId?: string; clientRequestId?: string }, signal?: AbortSignal) => diff --git a/web/src/locales/en.json b/web/src/locales/en.json index e8ab7ad..504f945 100644 --- a/web/src/locales/en.json +++ b/web/src/locales/en.json @@ -563,6 +563,8 @@ "status.bindAddress": "Bind address", "status.connected": "Connected", "status.connection": "Connection", + "status.cores": "cores", + "status.load": "load", "status.created": "Created", "status.deviceCount": "{n}", "status.devices": "Paired devices", @@ -593,6 +595,10 @@ "status.modelSearchPlaceholder": "Search models or providers…", "status.models": "Models & providers", "status.modelsError": "Failed to load models", + "status.modelsPendingTitle": "Loading models", + "status.modelsPendingText": "Fetching the catalogue from a running Neovim…", + "status.modelsNoInstanceTitle": "No live Neovim instance", + "status.modelsNoInstanceText": "Open a session in any workspace, then retry to load the catalogue.", "status.network": "Network", "status.networkAddress": "Network address", "status.noDevicesText": "Devices appear here after pairing from the phone.", diff --git a/web/src/locales/zh.json b/web/src/locales/zh.json index ac20be1..7bac24a 100644 --- a/web/src/locales/zh.json +++ b/web/src/locales/zh.json @@ -563,6 +563,8 @@ "status.bindAddress": "绑定地址", "status.connected": "已连接", "status.connection": "连接信息", + "status.cores": "核心", + "status.load": "负载", "status.created": "创建", "status.deviceCount": "{n} 台", "status.devices": "已配对设备", @@ -593,6 +595,10 @@ "status.modelSearchPlaceholder": "搜索模型或 provider…", "status.models": "模型与 Provider", "status.modelsError": "加载模型列表失败", + "status.modelsPendingTitle": "正在加载模型", + "status.modelsPendingText": "正在从运行中的 Neovim 获取模型目录…", + "status.modelsNoInstanceTitle": "没有运行中的 Neovim 实例", + "status.modelsNoInstanceText": "在任意工作区打开一个会话后重试,即可加载模型目录。", "status.network": "Network", "status.networkAddress": "Network 地址", "status.noDevicesText": "在手机端扫码配对后,设备会显示在这里。", diff --git a/web/src/pages/status.tsx b/web/src/pages/status.tsx index f22504a..4825020 100644 --- a/web/src/pages/status.tsx +++ b/web/src/pages/status.tsx @@ -73,14 +73,14 @@ export function StatusPage() { const pairCode = usePairCodeQuery(paired); const workspaces = workspacesQuery.data ?? []; - // Counters, the models probe and the task list only consider the rows the - // workspace-noise policy keeps in the default view: a ghost or a /tmp - // scratch dir must not become the "first workspace" used for `/models`. + // Counters and the task list only consider the rows the workspace-noise + // policy keeps in the default view. const { primary: visibleWorkspaces } = partitionWorkspaces(workspaces); const workspaceCount = visibleWorkspaces.length; const sessionCount = visibleWorkspaces.reduce((total, workspace) => total + (workspace.sessionCount || 0), 0); - const modelsWorkspaceId = visibleWorkspaces[0]?.workspaceId ?? null; - const models = useModelsQuery(modelsWorkspaceId); + // Models: use the bare /api/v1/models endpoint — the daemon scans ready + // instances without spawning, so we never get E_INSTANCE_STARTING here. + const models = useModelsQuery(visibleWorkspaces[0]?.workspaceId ?? null, paired); const meta = useMemo(() => readPairMeta(), []); @@ -221,7 +221,9 @@ export function StatusPage() {
void models.refetch()} /> diff --git a/web/tests/models-card.test.tsx b/web/tests/models-card.test.tsx new file mode 100644 index 0000000..9be2cdf --- /dev/null +++ b/web/tests/models-card.test.tsx @@ -0,0 +1,276 @@ +import { screen, waitFor } from "@testing-library/react"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; + +import { mockApi, type MockRoute } from "./helpers/api-mock"; +import { renderPage } from "./helpers/render-page"; + +import { setLanguage } from "@/lib/i18n"; +import { StatusPage } from "@/pages/status"; + +// ── minimal stubs for every endpoint the StatusPage touches ────────────────── + +const infoBody = { + v: 1, + daemonId: "daemon-1", + hostname: "box", + version: "0.1.0", + platform: "linux", +}; + +const healthBody = { + ok: true, + checkedAt: Date.now(), + items: [{ name: "plugin", ok: true, detail: "connected" }], +}; + +const resourcesBody = { + instances: [], + totalRssBytes: 0, + physicalMemoryBytes: 1024 * 1024 * 1024, + warn: false, +}; + +const workspacesBody = [ + { + workspaceId: "ws-1", + cwd: "/home/me/work", + name: "Work", + trusted: true, + exists: true, + sessionCount: 1, + liveCount: 1, + lastActiveAt: Date.now(), + instance: { workspaceId: "ws-1", status: "ready", pid: 1234, since: Date.now() }, + }, +]; + +const devicesBody: unknown[] = []; +const pairBody = { + accepted: true, + code: "XYZW9999", + url: "http://127.0.0.1:4321/pair/XYZW9999", + expiresAt: Date.now() + 9 * 60_000, + nonce: "nonce-x", + bases: [], +}; + +const SESSIONS_PATH = /^\/api\/v1\/workspaces\/[^/]+\/sessions$/; + +/** Build a full route table, merging caller overrides in front. */ +function apiRoutes(overrides: MockRoute[] = []): MockRoute[] { + const base: MockRoute[] = [ + { 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: SESSIONS_PATH, handler: () => ({ body: { sessions: [] } }) }, + { path: "/api/v1/models", handler: () => ({ body: { providers: [], pending: false } }) }, + { path: "/api/v1/devices", handler: () => ({ body: devicesBody }) }, + { method: "POST" as const, path: "/api/v1/pair", handler: () => ({ body: pairBody }) }, + ]; + const overridePaths = overrides.map((r) => r.path); + return [...overrides, ...base.filter((r) => !overridePaths.includes(r.path))]; +} + +function routes() { + return [ + { path: "/status", component: StatusPage }, + { path: "/connect", component: () =>
connect
}, + ]; +} + +/** Return the `.status-card` whose heading contains the given text. */ +function modelsCard(): HTMLElement { + const heading = screen.getByText("Models & providers"); + const root = heading.closest(".status-card"); + if (!(root instanceof HTMLElement)) throw new Error("Models & providers card not found"); + return root; +} + +beforeEach(async () => { + await setLanguage("en"); +}); + +afterEach(() => { + vi.unstubAllGlobals(); +}); + +describe("ModelsCard via StatusPage", () => { + it("(a) pending + empty providers → loading block visible, pending copy present, no error block", async () => { + mockApi( + apiRoutes([ + { + path: "/api/v1/models", + handler: () => ({ + body: { providers: [], pending: true, pendingReason: "fetching" }, + }), + }, + ]), + ); + + await renderPage(routes(), "/status", { paired: true }); + // Wait for the page to settle so the models query fires. + await screen.findByText("Models & providers"); + + const card = modelsCard(); + + // Must show the loading skeleton (aria role="status"). + await waitFor(() => { + expect(card.querySelector('[role="status"]')).not.toBeNull(); + }); + + // The aria-live pending region must be present and contain the pending copy. + await waitFor(() => { + expect(card.querySelector('[aria-live="polite"]')).not.toBeNull(); + }); + await waitFor(() => { + expect(card).toHaveTextContent("Fetching the catalogue from a running Neovim"); + }); + + // Must NOT render an error block (no .status-error). + expect(card.querySelector(".status-error")).toBeNull(); + }); + + it( + "(b) providers returned → provider row, model id, context window and badges render", + async () => { + mockApi( + apiRoutes([ + { + path: "/api/v1/models", + handler: () => ({ + body: { + providers: [ + { + provider: "cliproxyapi", + models: [ + { + id: "gemini-3.8-flash-high", + contextWindow: 1_000_000, + reasoning: true, + }, + ], + }, + ], + pending: false, + workspaceId: "ws-1", + }, + }), + }, + ]), + ); + + await renderPage(routes(), "/status", { paired: true }); + await screen.findByText("Models & providers"); + + const card = modelsCard(); + + // Provider name visible. + await waitFor(() => { + expect(card).toHaveTextContent("cliproxyapi"); + }); + + // Model id visible. + expect(card).toHaveTextContent("gemini-3.8-flash-high"); + + // Context window formatted (1 000 000 → "1M" or "1000K" depending on formatter). + await waitFor(() => { + expect(card.querySelector(".model-ctx")).not.toBeNull(); + const ctx = card.querySelector(".model-ctx")?.textContent ?? ""; + expect(ctx.length).toBeGreaterThan(0); + }); + + // Reasoning badge. + expect(card).toHaveTextContent("reasoning"); + + // Scoped badge (cliproxyapi provider). + expect(card).toHaveTextContent("scoped"); + }, + ); + + it("(c) pending:true + pendingReason:no-instance → no-instance empty state", async () => { + mockApi( + apiRoutes([ + { + path: "/api/v1/models", + handler: () => ({ + body: { providers: [], pending: true, pendingReason: "no-instance" }, + }), + }, + ]), + ); + + await renderPage(routes(), "/status", { paired: true }); + await screen.findByText("Models & providers"); + + const card = modelsCard(); + + await waitFor(() => { + expect(card).toHaveTextContent("No live Neovim instance"); + }); + expect(card).toHaveTextContent("Open a session in any workspace"); + + // Not an error block. + expect(card.querySelector(".status-error")).toBeNull(); + }); + + it("(d) failed request → ErrorBlock with error message and retry button triggers refetch", async () => { + let callCount = 0; + // useModelsQuery retries once on its own, so a single 500 is not the + // click. Keep failing until the button is pressed. + let allowSuccess = false; + mockApi( + apiRoutes([ + { + path: "/api/v1/models", + handler: () => { + callCount += 1; + if (!allowSuccess) { + return { status: 500, body: { code: "E_INTERNAL", message: "server exploded" } }; + } + return { + body: { + providers: [ + { + provider: "anthropic", + models: [{ id: "claude-opus-4", contextWindow: 200_000, reasoning: false }], + }, + ], + pending: false, + }, + }; + }, + }, + ]), + ); + + await renderPage(routes(), "/status", { paired: true }); + await screen.findByText("Models & providers"); + + const card = modelsCard(); + + // Error block must appear. The query retries once (~1s) before it settles. + await waitFor( + () => { + expect(card.querySelector(".status-error")).not.toBeNull(); + }, + { timeout: 4_000 }, + ); + + // Retry button must be present. + const retryBtn = card.querySelector("button"); + expect(retryBtn).not.toBeNull(); + + // Click retry → next fetch succeeds → providers appear. + allowSuccess = true; + retryBtn!.click(); + + await waitFor( + () => { + expect(card).toHaveTextContent("anthropic"); + }, + { timeout: 4_000 }, + ); + expect(callCount).toBeGreaterThanOrEqual(2); + }); +}); diff --git a/web/tests/status-page.test.tsx b/web/tests/status-page.test.tsx index c90d64e..025b5a6 100644 --- a/web/tests/status-page.test.tsx +++ b/web/tests/status-page.test.tsx @@ -62,6 +62,19 @@ const resourcesBody = { ], totalRssBytes: 512 * 1024 * 1024, physicalMemoryBytes: 2048 * 1024 * 1024, + system: { + sampledAt: Date.now(), + cpuPercent: 37, + cpuCores: 8, + loadAvg: [1.23, 0.98, 0.75], + memUsedBytes: 4 * 1024 * 1024 * 1024, + memTotalBytes: 16 * 1024 * 1024 * 1024, + memPercent: 61, + diskPath: "/var/lib/pi2", + diskUsedBytes: 82 * 1024 * 1024 * 1024, + diskTotalBytes: 100 * 1024 * 1024 * 1024, + diskPercent: 82, + }, warn: true, reason: "rss > soft limit", }; @@ -242,10 +255,15 @@ describe("StatusPage", () => { } // cpu / mem / disk carry the 3px meter, uptime does not. expect(document.querySelectorAll(".meter")).toHaveLength(3); - // 512 MiB of 2 GiB RSS → the memory ratio the daemon does not send directly. - await waitFor(() => - expect(document.querySelector('.status-tile[data-res="mem"] .tile__value')).toHaveTextContent("25%"), - ); + await waitFor(() => { + expect(document.querySelector('.status-tile[data-res="cpu"] .tile__value')).toHaveTextContent("37%"); + expect(document.querySelector('.status-tile[data-res="mem"] .tile__value')).toHaveTextContent("61%"); + expect(document.querySelector('.status-tile[data-res="disk"] .tile__value')).toHaveTextContent("82%"); + }); + expect(document.querySelector('.status-tile[data-res="mem"] .tile__meta')).toHaveTextContent("4 GiB / 16 GiB"); + expect(document.querySelector('.status-tile[data-res="disk"] .tile__meta')).toHaveTextContent("/var/lib/pi2"); + expect(document.querySelector('.status-tile[data-res="cpu"] .tile__meta')).toHaveTextContent("8"); + expect(document.querySelector('.status-tile[data-res="cpu"] .tile__meta')).toHaveTextContent("1.23"); expect(document.querySelector('.status-tile[data-res="uptime"] .tile__value')).toHaveTextContent("2h 5m"); const counts = document.querySelector(".status-counts"); @@ -257,6 +275,27 @@ describe("StatusPage", () => { expect(primaries()).toHaveLength(0); }); + it("does not derive memory percent from RSS on old daemons", async () => { + mockApi( + apiRoutes([ + { + path: "/api/v1/resources", + handler: () => ({ + body: { + ...resourcesBody, + system: undefined, + }, + }), + }, + ]), + ); + await renderPage(routes(), "/status", { paired: true }); + await screen.findByText("Server info"); + await waitFor(() => + expect(document.querySelector('.status-tile[data-res="mem"] .tile__value')).toHaveTextContent("—"), + ); + }); + it("puts info + health and models + tasks into two columns, with devices and connection full width", async () => { mockApi(apiRoutes()); await renderPage(routes(), "/status", { paired: true });