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.
This commit is contained in:
yuez committed 2026-10-28 08:14:17 +08:00
1 parent b577e15f6d
commit 604fec5ea0
10 files changed
+560 -105

No files matched your search

+15 -14
View File
@@ -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 ? (
<span className="faint truncate" title={system.diskPath}>{system.diskPath}</span>
) : live;
const counts: Array<[string, string]> = [
[t("status.workspaces"), String(workspaceCount)],
@@ -91,7 +92,7 @@ export function MetricsBlock({
<div className="tile__bar">
<Meter value={cpu} label="CPU" />
</div>
<div className="tile__meta">{live}</div>
<div className="tile__meta">{cpuMeta}</div>
</div>
<div className="tile status-tile" data-res="mem">
@@ -100,7 +101,7 @@ export function MetricsBlock({
<div className="tile__bar">
<Meter value={mem} label={t("status.memory")} />
</div>
<div className="tile__meta">{live}</div>
<div className="tile__meta">{memMeta}</div>
</div>
<div className="tile status-tile" data-res="disk">
@@ -109,7 +110,7 @@ export function MetricsBlock({
<div className="tile__bar">
<Meter value={disk} label={t("status.disk")} />
</div>
<div className="tile__meta">{live}</div>
<div className="tile__meta">{diskMeta}</div>
</div>
<div className="tile status-tile" data-res="uptime">
+127 -68
View File
@@ -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<Set<string>>(
@@ -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 = <ErrorBlock message={error} onRetry={onRetry} />;
} else if (loading && providers.length === 0) {
body = <LoadingBlock rows={5} />;
} else if (
providers.length === 0 &&
(pendingReason === "no-instance" || pendingReason === "no-live-session")
) {
body = (
<StatusEmpty
icon="model"
title={t("status.modelsNoInstanceTitle", { defaultValue: "No live Neovim instance" })}
text={t("status.modelsNoInstanceText", {
defaultValue: "Open a session in any workspace",
})}
/>
);
} else if (pending && providers.length === 0) {
body = (
<section
aria-live="polite"
aria-label={t("status.modelsPendingTitle", { defaultValue: "Fetching models" })}
>
<LoadingBlock rows={5} />
<p className="faint">
{t("status.modelsPendingText", {
defaultValue: "Fetching the catalogue from a running Neovim",
})}
</p>
</section>
);
} else if (providers.length === 0) {
body = (
<>
<div className="model-search">
<Icon name="search" />
<Input
type="search"
className="model-search__input"
placeholder={t("status.modelSearchPlaceholder")}
aria-label={t("status.modelSearchAria")}
value={query}
onChange={(event) => setQuery(event.target.value)}
/>
</div>
<StatusEmpty icon="model" title={t("status.noModelsTitle")} text={t("status.noModelsText")} />
</>
);
} else {
body = (
<>
<div className="model-search">
<Icon name="search" />
<Input
type="search"
className="model-search__input"
placeholder={t("status.modelSearchPlaceholder")}
aria-label={t("status.modelSearchAria")}
value={query}
onChange={(event) => setQuery(event.target.value)}
/>
</div>
{groups.length === 0 ? (
<StatusEmpty icon="search" title={t("status.noModelsTitle")} text={t("status.noModelsText")} />
) : (
<div className="model-list">
{groups.map((group) => {
const expanded = Boolean(needle) || openProviders.has(group.provider);
return (
<div className={expanded ? "model-group open" : "model-group"} key={group.provider}>
<button
type="button"
className="model-group__head"
aria-expanded={expanded}
onClick={() => toggle(group.provider)}
>
<Icon name="chevron-right" />
<span className="model-provider truncate">{group.provider}</span>
<span className="model-count faint tabular">{group.models.length}</span>
<span className="spacer" />
</button>
{expanded ? (
<div className="model-group__body">
{group.models.map((model) => (
<div className="model-row" key={model.id}>
<span className="model-id mono truncate grow">{model.id}</span>
<span className="model-ctx faint tabular">
{formatContextWindow(model.contextWindow)}
</span>
{model.reasoning ? (
<Badge className="badge--outline">
{t("status.reasoning")}
</Badge>
) : null}
{group.provider === "cliproxyapi" ? (
<Badge>{t("status.scoped")}</Badge>
) : null}
</div>
))}
</div>
) : null}
</div>
);
})}
</div>
)}
</>
);
}
return (
<StatusCard title={t("status.models")} icon="model">
{error ? (
<ErrorBlock message={error} onRetry={onRetry} />
) : loading ? (
<LoadingBlock rows={5} />
) : (
<>
<div className="model-search">
<Icon name="search" />
<Input
type="search"
className="model-search__input"
placeholder={t("status.modelSearchPlaceholder")}
aria-label={t("status.modelSearchAria")}
value={query}
onChange={(event) => setQuery(event.target.value)}
/>
</div>
{providers.length === 0 ? (
<StatusEmpty icon="model" title={t("status.noModelsTitle")} text={t("status.noModelsText")} />
) : groups.length === 0 ? (
<StatusEmpty icon="search" title={t("status.noModelsTitle")} text={t("status.noModelsText")} />
) : (
<div className="model-list">
{groups.map((group) => {
const expanded = Boolean(needle) || openProviders.has(group.provider);
return (
<div className={expanded ? "model-group open" : "model-group"} key={group.provider}>
<button
type="button"
className="model-group__head"
aria-expanded={expanded}
onClick={() => toggle(group.provider)}
>
<Icon name="chevron-right" />
<span className="model-provider truncate">{group.provider}</span>
<span className="model-count faint tabular">{group.models.length}</span>
<span className="spacer" />
</button>
{expanded ? (
<div className="model-group__body">
{group.models.map((model) => (
<div className="model-row" key={model.id}>
<span className="model-id mono truncate grow">{model.id}</span>
<span className="model-ctx faint tabular">
{formatContextWindow(model.contextWindow)}
</span>
{model.reasoning ? (
<Badge className="badge--outline">
{t("status.reasoning")}
</Badge>
) : null}
{group.provider === "cliproxyapi" ? (
<Badge>{t("status.scoped")}</Badge>
) : null}
</div>
))}
</div>
) : null}
</div>
);
})}
</div>
)}
</>
)}
{body}
</StatusCard>
);
}
+49 -10
View File
@@ -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<DevicesRespons
return { devices: normalizeDevices(await apiRequest<unknown>("/api/v1/devices", { signal })) };
}
export async function fetchModels(workspaceId: string, signal?: AbortSignal): Promise<ModelsResponse> {
return apiRequest<ModelsResponse>(`/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<ModelsResponse> {
try {
const raw = await apiRequest<unknown>("/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<ModelsResponse>(`/api/v1/models?workspaceId=${encodeURIComponent(legacyWorkspaceId)}`, { signal });
}
throw error;
}
}
/**
@@ -154,6 +178,7 @@ export function useWorkspacesQuery() {
queryKey: ["workspaces"],
queryFn: async ({ signal }) => normalizeWorkspaces(await apiRequest<unknown>("/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<ModelsResponse>({
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;
},
});
}
+1 -1
View File
@@ -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]}`;
}
+29 -2
View File
@@ -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<DeviceInfo[]>("/api/v1/devices", { signal }),
revokeDevice: (deviceId: string, signal?: AbortSignal) =>
request<void>(`/api/v1/devices/${encodeURIComponent(deviceId)}`, { method: "DELETE", signal }),
models: (workspaceId: string, signal?: AbortSignal) =>
request<ModelInfo[]>(`/api/v1/models?workspaceId=${encodeURIComponent(workspaceId)}`, { signal }),
resources: (signal?: AbortSignal) => request<ResourcesResponse>("/api/v1/resources", { signal }),
diagnostics: (signal?: AbortSignal) => request<DiagnosticsResponse>("/api/v1/diagnostics", { signal }),
command: (body: { method: string; params?: Record<string, unknown>; sessionId?: string; clientRequestId?: string }, signal?: AbortSignal) =>
+6
View File
@@ -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.",
+6
View File
@@ -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": "在手机端扫码配对后,设备会显示在这里。",
+8 -6
View File
@@ -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() {
<div className="status-col">
<ModelsCard
providers={models.data?.providers ?? []}
loading={Boolean(modelsWorkspaceId) && models.isPending}
loading={models.isPending && models.data === undefined}
pending={models.data?.pending === true}
pendingReason={models.data?.pendingReason ?? null}
error={models.isError ? translatedError(models.error, "status.modelsError", t) : null}
onRetry={() => void models.refetch()}
/>