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]}`;
}