Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
fc51c3be37 | ||
|
|
7f9ce543d2 | ||
|
|
c08e0c7e94 | ||
|
|
2c44a19d57 | ||
|
|
e7ce064817 | ||
|
|
604fec5ea0 | ||
|
|
b577e15f6d | ||
|
|
22de7dcc9c | ||
|
|
88354ec078 |
No files matched your search
+29
-3
@@ -81,7 +81,7 @@ Plugin obligations:
|
||||
|
||||
| Endpoint | Notes |
|
||||
|---|---|
|
||||
| `GET /api/v1/info` | `{v, daemonId, machineId, platform, hostname, os, version, uptimeMs, pid, port, capabilities, limits}` |
|
||||
| `GET /api/v1/info` | `{v, daemonId, machineId, platform, hostname, os, version, uptimeMs, pid, port, capabilities, limits}`; additive `cpu`, `mem`, `disk` (integer percent, each omitted when unknown), `cpuCores`, `loadAvg` |
|
||||
| `GET /api/v1/health` | `{ok, items:[{name, ok, detail}]}` |
|
||||
| `GET /api/v1/workspaces` | `WorkspaceInfo[]` (registry + disk index + instance state) |
|
||||
| `GET /api/v1/workspaces/:id/sessions` | relayed `workspace.query{kind:"sessions"}` (row fields below) |
|
||||
@@ -91,8 +91,8 @@ Plugin obligations:
|
||||
| `POST /api/v1/pair` | **authenticated**; mints `{code, url, expiresAt, nonce, qr, bases}` |
|
||||
| `POST /api/v1/pair/redeem` | public + rate limited (`E_RATE_LIMITED`); `{code, kind, deviceName}` → `{token, device}` |
|
||||
| `GET /pair/:code` | public; `302 /connect?code=<code>&auto=1` (scanned links) |
|
||||
| `GET /api/v1/models?workspaceId=` | relayed to the instance |
|
||||
| `GET /api/v1/resources` | instances, sessions, RSS totals for the soft-limit notice |
|
||||
| `GET /api/v1/models?workspaceId=` | `workspaceId` optional; relayed when given, daemon-resolved when omitted (below) |
|
||||
| `GET /api/v1/resources` | instances, sessions, RSS totals for the soft-limit notice; additive `system` (below) |
|
||||
| `GET /api/v1/diagnostics` | connections, event rates, slow queries, instance table |
|
||||
|
||||
The entries read is the only query that is *about a session*. `workspaceId` from the
|
||||
@@ -103,6 +103,32 @@ does not know. A session that exists but has no JSONL yet (`pi` creates the file
|
||||
the first entry) answers an **empty page** (`{entries:[], cursor:{hasMore:false}}`),
|
||||
never an error: a new session has no history to fail on.
|
||||
|
||||
The `system` object on `GET /api/v1/resources` is additive (absent on daemons
|
||||
older than 0.1.5, so clients must tolerate its absence) and reports **host**
|
||||
figures sampled by the daemon itself:
|
||||
|
||||
| Field | Notes |
|
||||
|---|---|
|
||||
| `sampledAt` | epoch ms; a sample is cached ~1 s and shared across callers |
|
||||
| `cpuPercent` | integer 0–100, `null` on the first sample (it is a delta between two reads) |
|
||||
| `cpuCores` | logical core count |
|
||||
| `loadAvg` | 3-tuple `[1m, 5m, 15m]`, or `null` where the OS has no load average |
|
||||
| `memUsedBytes`, `memTotalBytes`, `memPercent` | **host** memory; `memPercent` is an integer. `totalRssBytes` stays the soft-limit input — it is instance RSS, not a host figure |
|
||||
| `diskPath` | the filesystem the sample describes: the daemon's state dir |
|
||||
| `diskUsedBytes`, `diskTotalBytes`, `diskPercent` | `diskPercent` integer, nullable; the byte counts are `null` when the stat fails |
|
||||
|
||||
`GET /api/v1/models` no longer requires `workspaceId`. With one, the read is
|
||||
relayed as before and may spawn that workspace's instance — the chat picker's
|
||||
path. Without one, the daemon never spawns: it scans only instances with status
|
||||
`ready`, relays `workspace.query{kind:"models"}` to the best candidate
|
||||
(falling through on failure or a pending answer), and answers 200
|
||||
`{providers, pending, workspaceId, pendingReason?}` where `pendingReason` is
|
||||
`fetching` | `no-instance` | `no-live-session`. The plugin contract underneath
|
||||
is lazy: the first `workspace.query{kind:"models"}` answers
|
||||
`{providers:[], pending:true}` while a cache fills asynchronously, and an
|
||||
instance without a live `pi` session can stay pending indefinitely — clients
|
||||
must poll while `pending` and bound that polling.
|
||||
|
||||
Workspace row (`GET /api/v1/workspaces`) — registry entry ∪ disk discovery ∪ live instance state. Every known workspace is returned; rows are never filtered, so `/workspace/<workspaceId>` deep links always resolve:
|
||||
|
||||
| Field | Notes |
|
||||
|
||||
+100
-38
@@ -3,72 +3,134 @@
|
||||
The Chat page's session list draws one small circle per row. Its meaning is **owned by
|
||||
pi2.nvim**, not by this daemon: the browser mirrors `:PiSessions`
|
||||
(`lua/pi/ui/sessions.lua` — `M.dot_hl`, `child_dot_hl`, `refresh_current_markers`,
|
||||
`format_line`, `lua/pi/ui/highlights.lua`). Change one side and the other must follow.
|
||||
`format_line`, `lua/pi/ui/highlights.lua`, `lua/pi/ui/tasks.lua`). Change one side and the
|
||||
other must follow.
|
||||
|
||||
Everything below is computed in `web/src/features/chat/session-state.ts`
|
||||
(`sessionDot` / `childSessionDot` / `subagentDot`, all returning a `DotView`) and rendered
|
||||
by `<StatusDot>` (`web/src/components/ui/status-dot.tsx`). The wire is untouched — the dot
|
||||
is a pure view of `SessionState`.
|
||||
(`sessionDot` / `childSessionDot` / `subagentDot`) and rendered by `<StatusDot>`
|
||||
(`web/src/components/ui/status-dot.tsx`). Each returns a `DotView`,
|
||||
`{ status: DotStatus; blink?: "fast" | "slow"; current?: boolean }`. The wire is untouched —
|
||||
the dot is a pure view of `SessionState`.
|
||||
|
||||
## Where the blink is decided
|
||||
|
||||
**Blinking is a property of the view (`DotView.blink`), never of the colour class and never
|
||||
of the DOM location.** Omitting `blink` means solid.
|
||||
|
||||
That rule exists because breaking it was the bug: keying the animation off the colour class
|
||||
plus a component scope (`html[data-pi-blink-fast="dim"] .tree-row .dot--ok`) made green blink
|
||||
only inside the session tree and sit steady elsewhere, `.dot--busy`/`.dot--err` blazed
|
||||
globally, `dot--steady` could not opt an `ok` dot out, and a failed task's `dot--err` blinked
|
||||
forever with nothing to acknowledge it.
|
||||
|
||||
The renderer adds `dot--blink-fast` or `dot--blink-slow` only when `blink` is set, and
|
||||
`app.css` has exactly two dim rules, with no colour or component scoping:
|
||||
|
||||
```css
|
||||
html[data-pi-blink-fast="dim"] .dot--blink-fast,
|
||||
html[data-pi-blink-slow="dim"] .dot--blink-slow { opacity: .35; }
|
||||
```
|
||||
|
||||
CSS therefore never decides *whether* a dot blinks, only *when* the shared clock dims it. A
|
||||
dot without `dot--blink-*` never animates. `dot--steady` is gone: to make a dot solid, omit
|
||||
`blink`. `DOT_CLASS` is colour-only. Server and health dots (topbar chip, nav rail, status
|
||||
page, workspace cards) carry no blink class at all.
|
||||
|
||||
## Parent rows (`sessionDot`)
|
||||
|
||||
Priority order, highest first:
|
||||
|
||||
| # | condition | class | visual |
|
||||
|---|---|---|---|
|
||||
| 1 | `status === "exited"` or `"interrupted"` | `dot--dead` | solid red, steady |
|
||||
| 2 | `flags.error` | `dot--err` | red, fast blink |
|
||||
| 3 | `flags.attention` or `attention.length > 0` | `dot--attention` | amber + ring, steady |
|
||||
| 4 | `flags.done` | `dot--ok` | green, fast blink |
|
||||
| 5 | `status === "busy"` | `dot--busy` | amber, fast blink |
|
||||
| 6 | `status === "compacting"` | `dot--compacting` | violet, slow blink |
|
||||
| 7 | anything else (`idle`, `starting`) | `dot--idle` | grey, steady |
|
||||
| # | condition | class | blink | visual |
|
||||
|---|---|---|---|---|
|
||||
| 1 | `status === "exited"` or `"interrupted"` | `dot--dead` | — | solid red |
|
||||
| 2 | `flags.error` | `dot--err` | fast | red |
|
||||
| 3 | `flags.attention` or `attention.length > 0` | `dot--attention` | — | amber + ring |
|
||||
| 4 | `flags.done` | `dot--ok` | fast | green |
|
||||
| 5 | `status === "busy"` | `dot--busy` | fast | amber |
|
||||
| 6 | `status === "compacting"` | `dot--compacting` | slow | violet |
|
||||
| 7 | anything else (`idle`, `starting`) | `dot--idle` | — | grey |
|
||||
|
||||
`interrupted` and `exited` share the top slot because the plugin has no `interrupted`: any
|
||||
non-running row is `exited`, and a dead row outranks its own unread flags.
|
||||
|
||||
## The "you are here" marker (`withCurrent`)
|
||||
|
||||
The row the console has open gets `dot--current` (blue) — the browser analogue of the
|
||||
plugin's current-tab marker (`refresh_current_markers`), which repaints the focused dot in the
|
||||
agent colour. It is suppressed whenever a notification colour applies (error / done /
|
||||
attention); idle and busy rows keep their rate and gain the class, a focused `compacting` row
|
||||
is painted `busy` + fast instead of half speed. `sessionStatusKey()` keeps the *text* label
|
||||
separate: `interrupted` reads "interrupted" even though its dot is the dead red.
|
||||
|
||||
## Sub-session rows (`childSessionDot`)
|
||||
|
||||
A separate matrix (`child_dot_hl`), not the parent's:
|
||||
|
||||
| condition | class |
|
||||
|---|---|
|
||||
| `status === "exited"` (the wire folds `dormant` into it) | `dot--exited` — hollow ring (the plugin's `◌`) |
|
||||
| `status === "interrupted"` | `dot--dead` |
|
||||
| `flags.error` | `dot--err`, plus `dot--steady` **while the row is viewed** |
|
||||
| `busy` or `compacting` | `dot--busy` (the plugin blinks both at the busy rate) |
|
||||
| anything else | `dot--idle` |
|
||||
| condition | class | blink |
|
||||
|---|---|---|
|
||||
| `status === "exited"` (the wire folds `dormant` into it) | `dot--exited` — hollow ring (the plugin's `◌`) | — |
|
||||
| `status === "interrupted"` | `dot--dead` | — |
|
||||
| `flags.error` | `dot--err` | solid **while viewed**, fast otherwise |
|
||||
| `busy` or `compacting` | `dot--busy` (the plugin blinks both at the busy rate) | fast |
|
||||
| anything else | `dot--idle` | — |
|
||||
|
||||
A child never shows `ok` or `attention`: the plugin forces `done = false` and
|
||||
`attention = 0` for children and surfaces completion/failure in the parent chat.
|
||||
|
||||
## Manifest-only subagents (`subagentDot`)
|
||||
|
||||
`active` → busy, `completed`/`dormant` → hollow, `failed` → err (steady when viewed),
|
||||
`interrupted` → dead, unknown → idle. A finished subagent is **hollow, not green** — the
|
||||
plugin shows a finished child as dormant `◌`.
|
||||
| status | class | blink |
|
||||
|---|---|---|
|
||||
| `active` | `dot--busy` | — |
|
||||
| `completed` / `dormant` | `dot--exited` (hollow) | — |
|
||||
| `failed` | `dot--err` | solid **when viewed**, fast otherwise |
|
||||
| `interrupted` | `dot--dead` | — |
|
||||
| unknown | `dot--idle` | — |
|
||||
|
||||
## The "you are here" marker
|
||||
A finished subagent is **hollow, not green** — the plugin shows a finished child as dormant
|
||||
`◌`. An `active` manifest row is amber but **solid**: a manifest entry that still has a live
|
||||
session is rendered as that session's row (which blinks while busy), so a manifest-only row is
|
||||
either a spawn in flight or stale, and nvim blinks neither — nothing would acknowledge it.
|
||||
|
||||
The row the console has open gets `dot--current` (blue) — the browser analogue of the
|
||||
plugin's current-tab marker, which repaints the focused dot in the agent colour. It is
|
||||
suppressed whenever a notification colour applies, and a focused `compacting` row blinks at
|
||||
the busy rate instead of half speed. `sessionStatusKey()` keeps the *text* label separate:
|
||||
`interrupted` reads "interrupted" even though its dot is the dead red.
|
||||
|
||||
## Task dots (`:PiTasks` parity)
|
||||
|
||||
`taskDotView` (exported by `session-tray.tsx`, reused by the task-output modal) is the one
|
||||
task matrix for the chat surfaces; the `/status` task card renders the same colours solid.
|
||||
Nothing ever acknowledges a task, so its terminal states are always solid — a failure must not
|
||||
blink forever.
|
||||
|
||||
| task status | class | blink |
|
||||
|---|---|---|
|
||||
| `running` | `dot--busy` | fast |
|
||||
| `completed` | `dot--ok` | — |
|
||||
| `failed` | `dot--err` | — |
|
||||
| `stopped` | `dot--attention` | — |
|
||||
|
||||
## The head dot agrees with its row
|
||||
|
||||
The stream-head dot renders the same `DotView` as the selected tree row —
|
||||
`sessionDot(active, { viewed: true })` — so one session can never show two different blink
|
||||
rates at once.
|
||||
|
||||
## `done` / `error` are unread markers, not states
|
||||
|
||||
The plugin raises `done` only for a session the user is **not** looking at, and
|
||||
`clear_flags` wipes `done`/`error` on `TabEnter`. `useSessionsStore.markSeen(sessionId)` is
|
||||
the browser's TabEnter: `pages/chat.tsx` calls it when the routed session carries either
|
||||
flag, so the session you open stops being green or red. The canonical reducer
|
||||
(`src/protocol/reducer.ts`) and `fixtures/` are deliberately untouched — this is a
|
||||
client-side view concern.
|
||||
the browser's TabEnter: `pages/chat.tsx` calls it when the routed session carries either flag,
|
||||
so the session you open stops being green or red — which is why a viewed child or subagent
|
||||
failure is solid while an unviewed one blinks. The canonical reducer (`src/protocol/reducer.ts`)
|
||||
and `fixtures/` are deliberately untouched: this is a client-side view concern.
|
||||
|
||||
## One clock for every dot
|
||||
|
||||
No dot animates itself. `web/src/lib/blink.ts` owns a single ref-counted 500ms interval
|
||||
that writes `data-pi-blink-fast` (`tick % 2`) and `data-pi-blink-slow`
|
||||
(`floor(tick / 2) % 2`) on `<html>`; `app.css` derives the dim phase from those attributes,
|
||||
so every dot in the app blinks in lockstep instead of drifting. `dot--steady` opts a dot
|
||||
out, and `prefers-reduced-motion: reduce` pins them all solid (the timer is never started).
|
||||
No dot animates itself. `web/src/lib/blink.ts` owns a single ref-counted 500ms interval that
|
||||
writes `data-pi-blink-fast` (`tick % 2`) and `data-pi-blink-slow` (`floor(tick / 2) % 2`) on
|
||||
`<html>`, so every blinking dot is in lockstep instead of drifting.
|
||||
`prefers-reduced-motion: reduce` pins both attributes `on` and never starts the timer.
|
||||
|
||||
## The contract is pinned
|
||||
|
||||
`web/tests/status-dot.blink-css.test.ts` loads the real stylesheets into jsdom and asserts that
|
||||
a colour-only dot stays solid in both clock phases and that placement (inside versus outside
|
||||
`.tree-row`) changes nothing. Add a case there before changing any blink behaviour.
|
||||
@@ -104,6 +104,7 @@ Per shot, all must pass:
|
||||
| `page-errors` | `0` | uncaught exceptions (`pageerror`) |
|
||||
| `api-errors` | `0` | no `/api/v1/*` response ≥ 400 — the fixture contract is complete |
|
||||
| `no-horizontal-overflow` | `scrollWidth ≤ clientWidth + 1` | no sideways scroll; the report lists the overflowing elements |
|
||||
| `control-font-size` | `≥16px` (380 px shots only) | a text control under 16px makes Mobile Safari zoom the page in on focus, and it never zooms back out; `app.css` owns the floor (`@media (hover: none), (max-width: 599px)`), `web/tests/mobile-controls.test.ts` pins it |
|
||||
| `no-tabbar` | `0 × .tabbar` | CHG-04/08: the bottom bar is gone, replaced by the rail + page pill |
|
||||
| `no-unexpected-modal` | `0 × .modal-backdrop` | the shot shows the page, not a dialog. Pending attention deliberately hangs off `s-attention`, not the session the matrix opens, because the attention modal is blocking and Escape-proof |
|
||||
| `connect-no-page-pill` / `connect-no-nav-item` | `0` each | `/connect` has no navigation chrome at all |
|
||||
@@ -246,6 +247,12 @@ state (`/sessions`) and the WS snapshot — so no web code calls them.
|
||||
外壳:`<600` 顶栏胶囊 + sheet,`600–839` 图标 rail,`≥840` 图标 sidebar(均为 56px)。
|
||||
Chat:`≥1100` 树 280px + 流,`1000–1099` 树 240px,`<1000` 单栏 + 树抽屉。阅读列 `--reading-max: 52rem`。
|
||||
|
||||
输入控件另有一条**不随断点走的最低字号**:`app.css` 在 `@media (hover: none), (max-width: 599px)` 里
|
||||
把所有 `input/select/textarea/[contenteditable]` 压到 16px。手机 Safari 的聚焦缩放由“控件字号 <16px”
|
||||
触发且不会自动退出,而设计里 `input` 继承 `--fs-body`(14px)、`.composer__ta` 是 15px,所以这条
|
||||
`!important` 兜底必须存在;`hover: none` 让横屏(宽于 600px)也被覆盖。桌面鼠标环境不受影响。
|
||||
`html { text-size-adjust: 100% }` 同时关掉旋转后的文字膨胀。
|
||||
|
||||
### 9.3 已知缺口
|
||||
|
||||
- `scripts/e2e/ui-e2e.mjs` 需要真 `pi` + nvim 才能跑;本轮只做了选择器适配,未在该环境回归。
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@yuez/pi2d",
|
||||
"version": "0.1.4",
|
||||
"version": "0.1.5",
|
||||
"type": "module",
|
||||
"license": "MIT",
|
||||
"description": "pi2 web console daemon (`pi2 daemon`): HTTP/WS gateway, workspace registry and instance supervisor for pi2.nvim",
|
||||
|
||||
@@ -333,6 +333,20 @@ async function collect(page) {
|
||||
dots: count(".dot"),
|
||||
modals: count(".modal-backdrop"),
|
||||
hasRoot: root !== null,
|
||||
// Smallest visible text-entry control. Mobile Safari zooms the page
|
||||
// in when one of these is under 16px and never zooms back out.
|
||||
minControlFont: (() => {
|
||||
const skip = new Set(["checkbox", "radio", "range", "file", "color", "hidden", "submit", "button", "reset"]);
|
||||
const sizes = [...document.querySelectorAll("input, select, textarea, [contenteditable='true']")]
|
||||
.filter((element) => {
|
||||
const rect = element.getBoundingClientRect();
|
||||
if (rect.width === 0 || rect.height === 0) return false;
|
||||
return !(element.tagName === "INPUT" && skip.has(element.type));
|
||||
})
|
||||
.map((element) => parseFloat(getComputedStyle(element).fontSize))
|
||||
.filter((size) => Number.isFinite(size));
|
||||
return sizes.length ? Math.min(...sizes) : null;
|
||||
})(),
|
||||
};
|
||||
});
|
||||
}
|
||||
@@ -452,6 +466,18 @@ async function shootPage(browser, { base, origin, page: spec, viewport, theme, i
|
||||
}),
|
||||
);
|
||||
checks.push(assert("no-tabbar", metrics.tabbar === 0, 0, metrics.tabbar));
|
||||
// Phone-width shots must keep every text control at ≥16px, otherwise
|
||||
// Mobile Safari scales the whole page on focus (app.css owns the floor).
|
||||
if (viewport.width < 600) {
|
||||
checks.push(
|
||||
assert(
|
||||
"control-font-size",
|
||||
metrics.minControlFont === null || metrics.minControlFont >= 16,
|
||||
">=16px",
|
||||
metrics.minControlFont,
|
||||
),
|
||||
);
|
||||
}
|
||||
// A stray overlay hides the page under a modal: the screenshots must show
|
||||
// the page, not a dialog nobody asked for.
|
||||
checks.push(assert("no-unexpected-modal", metrics.modals === 0, 0, metrics.modals));
|
||||
|
||||
@@ -16,6 +16,7 @@ import { join } from "node:path";
|
||||
import { loadConfig, type Config, type ConfigEnv } from "../config.js";
|
||||
import { dataDir, daemonSocketPath, daemonTokenPath, runtimeDir, stateDir } from "../core/paths.js";
|
||||
import type { Logger } from "../core/interfaces.js";
|
||||
import { createSysinfo } from "../core/sysinfo.js";
|
||||
import { AuthStore } from "../daemon/auth.js";
|
||||
import { InMemoryBus } from "../daemon/hub.js";
|
||||
import { startServer, type ServerDeps, type StartedServer } from "../daemon/server.js";
|
||||
@@ -144,6 +145,7 @@ export async function wireDaemon(options: WireOptions = {}): Promise<WiredDaemon
|
||||
machineId: options.machineId ?? machineIdFor(env.HOSTNAME ?? process.env.HOSTNAME ?? "localhost"),
|
||||
startedAt,
|
||||
now,
|
||||
sysinfo: createSysinfo({ now }),
|
||||
...(options.server?.heartbeatMs === undefined ? {} : { heartbeatMs: options.server.heartbeatMs }),
|
||||
...(options.server?.ws === undefined ? {} : { ws: options.server.ws }),
|
||||
};
|
||||
|
||||
@@ -31,6 +31,8 @@ export interface PluginConnection {
|
||||
): Promise<{ seq?: number; disposition?: string } & Record<string, unknown>>;
|
||||
subscribe(sessionId: string): void;
|
||||
unsubscribe(sessionId: string): void;
|
||||
/** Session IDs currently known by the plugin. */
|
||||
sessionIds(): string[];
|
||||
/** Last snapshot received for a session (render cache, may be undefined). */
|
||||
snapshot(sessionId: string): SessionState | undefined;
|
||||
/** Last seq received for a session. */
|
||||
|
||||
@@ -0,0 +1,301 @@
|
||||
/**
|
||||
* Host sysinfo sampler — CPU / memory / disk with injectable I/O.
|
||||
* Zero runtime dependencies; no OS calls at import time.
|
||||
*/
|
||||
import { statfs as nodeStatfs } from "node:fs/promises";
|
||||
import * as nodeOs from "node:os";
|
||||
import { readFile as nodeReadFile } from "node:fs/promises";
|
||||
import { stateDir } from "./paths.js";
|
||||
|
||||
/* ------------------------------------------------------------------ */
|
||||
/* Public types */
|
||||
/* ------------------------------------------------------------------ */
|
||||
|
||||
export interface CpuTimes {
|
||||
idle: number;
|
||||
total: number;
|
||||
}
|
||||
|
||||
export interface StatFsLike {
|
||||
bsize: number;
|
||||
blocks: number;
|
||||
bfree: number;
|
||||
}
|
||||
|
||||
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 SysinfoSampler {
|
||||
sample(): Promise<SystemStats>;
|
||||
}
|
||||
|
||||
export interface SysinfoDeps {
|
||||
now?: () => number;
|
||||
readFile?: (path: string) => Promise<string>;
|
||||
statfs?: (path: string) => Promise<StatFsLike>;
|
||||
cpus?: () => Array<{ times: { user: number; nice: number; sys: number; idle: number; irq: number } }>;
|
||||
totalmem?: () => number;
|
||||
freemem?: () => number;
|
||||
loadavg?: () => number[];
|
||||
platform?: NodeJS.Platform;
|
||||
diskPath?: string;
|
||||
cacheMs?: number;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ */
|
||||
/* Pure parsing helpers (exported for tests) */
|
||||
/* ------------------------------------------------------------------ */
|
||||
|
||||
/**
|
||||
* Parse /proc/meminfo text.
|
||||
* Tries MemAvailable; falls back to MemFree + Buffers + Cached.
|
||||
*/
|
||||
export function parseMeminfo(text: string): { totalBytes: number; availableBytes: number } | null {
|
||||
const kbOf = (label: string): number | null => {
|
||||
const m = new RegExp(`^${label}:\\s+(\\d+)\\s+kB`, "m").exec(text);
|
||||
return m ? Number(m[1]) * 1024 : null;
|
||||
};
|
||||
const total = kbOf("MemTotal");
|
||||
if (total === null) return null;
|
||||
|
||||
let available = kbOf("MemAvailable");
|
||||
if (available === null) {
|
||||
const free = kbOf("MemFree");
|
||||
const buffers = kbOf("Buffers") ?? 0;
|
||||
const cached = kbOf("Cached") ?? 0;
|
||||
if (free === null) return null;
|
||||
available = free + buffers + cached;
|
||||
}
|
||||
return { totalBytes: total, availableBytes: available };
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse the aggregate `cpu ` line from /proc/stat.
|
||||
* Returns cumulative idle and total jiffies.
|
||||
*/
|
||||
export function parseProcStat(text: string): CpuTimes | null {
|
||||
const m = /^cpu\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)/m.exec(text);
|
||||
if (!m) return null;
|
||||
const [, user, nice, sys, idle, iowait, irq, softirq] = m.map(Number);
|
||||
const idleTime = idle! + iowait!;
|
||||
const total = user! + nice! + sys! + idle! + iowait! + irq! + softirq!;
|
||||
return { idle: idleTime, total };
|
||||
}
|
||||
|
||||
/** Aggregate os.cpus() array into CpuTimes. */
|
||||
export function cpuTimesFromCpus(
|
||||
cpus: Array<{ times: { user: number; nice: number; sys: number; idle: number; irq: number } }>,
|
||||
): CpuTimes {
|
||||
let idle = 0;
|
||||
let total = 0;
|
||||
for (const cpu of cpus) {
|
||||
const t = cpu.times;
|
||||
idle += t.idle;
|
||||
total += t.user + t.nice + t.sys + t.idle + t.irq;
|
||||
}
|
||||
return { idle, total };
|
||||
}
|
||||
|
||||
/**
|
||||
* Derive CPU busy % from two successive CpuTimes snapshots.
|
||||
* Returns null on the first sample (prev === null) or when the delta is zero.
|
||||
*/
|
||||
export function cpuPercentBetween(prev: CpuTimes | null, next: CpuTimes): number | null {
|
||||
if (prev === null) return null;
|
||||
const totalDelta = next.total - prev.total;
|
||||
if (totalDelta <= 0) return null;
|
||||
const idleDelta = next.idle - prev.idle;
|
||||
const busy = 1 - idleDelta / totalDelta;
|
||||
return Math.min(100, Math.max(0, Math.round(busy * 100)));
|
||||
}
|
||||
|
||||
/**
|
||||
* Derive disk usage from a statfs result.
|
||||
* Returns null if blocks is 0 (pseudo-fs like tmpfs without a block count).
|
||||
*/
|
||||
export function diskFromStatfs(stats: StatFsLike): { totalBytes: number; usedBytes: number; percent: number } | null {
|
||||
const { bsize, blocks, bfree } = stats;
|
||||
if (![bsize, blocks, bfree].every((value) => Number.isFinite(value) && value >= 0)) return null;
|
||||
if (blocks <= 0 || bsize <= 0) return null;
|
||||
const totalBytes = blocks * bsize;
|
||||
if (!Number.isFinite(totalBytes)) return null;
|
||||
const rawUsedBytes = (blocks - bfree) * bsize;
|
||||
const usedBytes = Math.min(totalBytes, Math.max(0, Number.isFinite(rawUsedBytes) ? rawUsedBytes : 0));
|
||||
const percent = Math.min(100, Math.max(0, Math.round((usedBytes / totalBytes) * 100)));
|
||||
return { totalBytes, usedBytes, percent };
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ */
|
||||
/* Sampler factory */
|
||||
/* ------------------------------------------------------------------ */
|
||||
|
||||
export function createSysinfo(deps: SysinfoDeps = {}): SysinfoSampler {
|
||||
const now = deps.now ?? Date.now;
|
||||
const cacheMs = deps.cacheMs ?? 1000;
|
||||
const platform = deps.platform ?? process.platform;
|
||||
const diskPath = deps.diskPath ?? stateDir();
|
||||
|
||||
// I/O callables — real by default, injectable for tests
|
||||
const readFile = deps.readFile ?? ((path: string) => nodeReadFile(path, "utf8"));
|
||||
const statfsImpl = deps.statfs ?? ((path: string) => nodeStatfs(path) as Promise<StatFsLike>);
|
||||
const cpus = deps.cpus ?? (() => nodeOs.cpus());
|
||||
const totalmem = deps.totalmem ?? (() => nodeOs.totalmem());
|
||||
const freemem = deps.freemem ?? (() => nodeOs.freemem());
|
||||
const loadavg = deps.loadavg ?? (() => nodeOs.loadavg());
|
||||
|
||||
let prevCpuTimes: CpuTimes | null = null;
|
||||
let cachedResult: SystemStats | null = null;
|
||||
let cachedAt = -Infinity;
|
||||
let inFlight: Promise<SystemStats> | null = null;
|
||||
|
||||
async function doSample(): Promise<SystemStats> {
|
||||
const sampledAt = now();
|
||||
|
||||
// ── CPU ──────────────────────────────────────────────────────
|
||||
let nextCpuTimes: CpuTimes | null = null;
|
||||
if (platform === "linux") {
|
||||
try {
|
||||
const text = await readFile("/proc/stat");
|
||||
nextCpuTimes = parseProcStat(text);
|
||||
} catch {
|
||||
// fall through to os.cpus()
|
||||
}
|
||||
}
|
||||
if (nextCpuTimes === null) {
|
||||
try {
|
||||
nextCpuTimes = cpuTimesFromCpus(cpus());
|
||||
} catch {
|
||||
nextCpuTimes = null;
|
||||
}
|
||||
}
|
||||
const cpuPercent = nextCpuTimes !== null ? cpuPercentBetween(prevCpuTimes, nextCpuTimes) : null;
|
||||
if (nextCpuTimes !== null) prevCpuTimes = nextCpuTimes;
|
||||
|
||||
let cpuCores = 1;
|
||||
try {
|
||||
cpuCores = Math.max(1, cpus().length);
|
||||
} catch {
|
||||
// keep 1
|
||||
}
|
||||
|
||||
// ── loadAvg ──────────────────────────────────────────────────
|
||||
let loadAvgResult: [number, number, number] | null = null;
|
||||
if (platform !== "win32") {
|
||||
try {
|
||||
const raw = loadavg();
|
||||
if (raw.length >= 3) {
|
||||
loadAvgResult = [
|
||||
Math.round(raw[0]! * 100) / 100,
|
||||
Math.round(raw[1]! * 100) / 100,
|
||||
Math.round(raw[2]! * 100) / 100,
|
||||
];
|
||||
}
|
||||
} catch {
|
||||
loadAvgResult = null;
|
||||
}
|
||||
}
|
||||
|
||||
// ── Memory ───────────────────────────────────────────────────
|
||||
let memTotalBytes: number;
|
||||
let memUsedBytes: number;
|
||||
let parsed: { totalBytes: number; availableBytes: number } | null = null;
|
||||
if (platform === "linux") {
|
||||
try {
|
||||
const text = await readFile("/proc/meminfo");
|
||||
parsed = parseMeminfo(text);
|
||||
} catch {
|
||||
// fall through to os
|
||||
}
|
||||
}
|
||||
if (parsed !== null && Number.isFinite(parsed.totalBytes) && parsed.totalBytes >= 0 &&
|
||||
Number.isFinite(parsed.availableBytes) && parsed.availableBytes >= 0) {
|
||||
memTotalBytes = parsed.totalBytes;
|
||||
memUsedBytes = parsed.totalBytes - parsed.availableBytes;
|
||||
} else {
|
||||
let rawTotal = 0;
|
||||
let rawFree = 0;
|
||||
try {
|
||||
rawTotal = totalmem();
|
||||
} catch {
|
||||
// leave the total at zero
|
||||
}
|
||||
try {
|
||||
rawFree = freemem();
|
||||
} catch {
|
||||
// leave free memory at zero
|
||||
}
|
||||
memTotalBytes = Number.isFinite(rawTotal) && rawTotal >= 0 ? rawTotal : 0;
|
||||
const freeBytes = Number.isFinite(rawFree) && rawFree >= 0 ? rawFree : 0;
|
||||
memUsedBytes = memTotalBytes - freeBytes;
|
||||
}
|
||||
memUsedBytes = Math.min(memTotalBytes, Math.max(0, Number.isFinite(memUsedBytes) ? memUsedBytes : 0));
|
||||
const memPercent = memTotalBytes > 0
|
||||
? Math.min(100, Math.max(0, Math.round((memUsedBytes / memTotalBytes) * 100)))
|
||||
: 0;
|
||||
|
||||
// ── Disk ─────────────────────────────────────────────────────
|
||||
let diskUsedBytes: number | null = null;
|
||||
let diskTotalBytes: number | null = null;
|
||||
let diskPercent: number | null = null;
|
||||
try {
|
||||
const sf = await statfsImpl(diskPath);
|
||||
const result = diskFromStatfs(sf);
|
||||
if (result !== null) {
|
||||
diskUsedBytes = result.usedBytes;
|
||||
diskTotalBytes = result.totalBytes;
|
||||
diskPercent = result.percent;
|
||||
}
|
||||
} catch {
|
||||
// leave nulls
|
||||
}
|
||||
|
||||
return {
|
||||
sampledAt,
|
||||
cpuPercent,
|
||||
cpuCores,
|
||||
loadAvg: loadAvgResult,
|
||||
memUsedBytes,
|
||||
memTotalBytes,
|
||||
memPercent,
|
||||
diskPath,
|
||||
diskUsedBytes,
|
||||
diskTotalBytes,
|
||||
diskPercent,
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
async sample(): Promise<SystemStats> {
|
||||
const t = now();
|
||||
if (cachedResult !== null && t - cachedAt < cacheMs) {
|
||||
return cachedResult;
|
||||
}
|
||||
if (inFlight) return inFlight;
|
||||
inFlight = doSample().then(
|
||||
(result) => {
|
||||
cachedResult = result;
|
||||
cachedAt = now();
|
||||
inFlight = null;
|
||||
return result;
|
||||
},
|
||||
(err) => {
|
||||
inFlight = null;
|
||||
// should never throw, but just in case
|
||||
throw err;
|
||||
},
|
||||
);
|
||||
return inFlight;
|
||||
},
|
||||
};
|
||||
}
|
||||
+50
-9
@@ -1,5 +1,6 @@
|
||||
/** Hono application factory for the daemon HTTP surface. */
|
||||
import { existsSync, readFileSync } from "node:fs";
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { hostname as osHostname, platform as osPlatform, release as osRelease } from "node:os";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { Hono, type Context } from "hono";
|
||||
@@ -8,6 +9,7 @@ import type { Bus, InstanceManager, Logger, WorkspaceStore } from "../core/inter
|
||||
import { ERROR_CODES, errorBody } from "../protocol/errors.js";
|
||||
import { PROTOCOL_VERSION, type CommandRequest } from "../protocol/types.js";
|
||||
import type { Config } from "../config.js";
|
||||
import type { SysinfoSampler } from "../core/sysinfo.js";
|
||||
import { networkBases } from "../core/network.js";
|
||||
import { encodeQr, fitsQr } from "../core/qr.js";
|
||||
import type { AuthStore, DevicePublic } from "./auth.js";
|
||||
@@ -17,6 +19,7 @@ import { PairRateLimiter } from "./rate-limit.js";
|
||||
import { CommandRouter } from "./router.js";
|
||||
import { createSseHandler } from "./sse.js";
|
||||
import { serveStatic } from "./static.js";
|
||||
import { resolveModels, type ModelsCandidate } from "./models.js";
|
||||
|
||||
type Env = { Bindings: HttpBindings };
|
||||
|
||||
@@ -39,6 +42,7 @@ export interface AppDeps {
|
||||
startedAt?: number;
|
||||
now?: () => number;
|
||||
metrics?: () => DaemonMetrics;
|
||||
sysinfo?: SysinfoSampler;
|
||||
/** Redeem budget; injectable so tests can advance the clock. */
|
||||
pairLimiter?: PairRateLimiter;
|
||||
}
|
||||
@@ -191,8 +195,9 @@ export function createApp(deps: AppDeps): Hono<Env> {
|
||||
await next();
|
||||
});
|
||||
|
||||
app.get("/api/v1/info", (c) =>
|
||||
c.json({
|
||||
app.get("/api/v1/info", async (c) => {
|
||||
const system = await deps.sysinfo?.sample();
|
||||
return c.json({
|
||||
v: PROTOCOL_VERSION,
|
||||
daemonId: deps.daemonId,
|
||||
machineId: deps.machineId ?? deps.daemonId,
|
||||
@@ -207,8 +212,13 @@ export function createApp(deps: AppDeps): Hono<Env> {
|
||||
limits: config.limits,
|
||||
host: config.host,
|
||||
publicUrl: config.publicUrl,
|
||||
}),
|
||||
);
|
||||
cpuCores: system?.cpuCores,
|
||||
loadAvg: system?.loadAvg ?? null,
|
||||
...(typeof system?.cpuPercent === "number" ? { cpu: system.cpuPercent } : {}),
|
||||
...(typeof system?.memPercent === "number" ? { mem: system.memPercent } : {}),
|
||||
...(typeof system?.diskPercent === "number" ? { disk: system.diskPercent } : {}),
|
||||
});
|
||||
});
|
||||
|
||||
/**
|
||||
* Local-browser login handshake: loopback + the local CLI token only.
|
||||
@@ -310,10 +320,38 @@ export function createApp(deps: AppDeps): Hono<Env> {
|
||||
|
||||
app.get("/api/v1/models", async (c) => {
|
||||
const workspaceId = c.req.query("workspaceId");
|
||||
if (!workspaceId) throw DaemonError.badRequest("workspaceId is required");
|
||||
if (!workspaces.get(workspaceId)) throw DaemonError.notFound(`unknown workspace ${workspaceId}`);
|
||||
const ack = await router.relayWorkspaceQuery(workspaceId, "models");
|
||||
return json(200, ack);
|
||||
if (workspaceId) {
|
||||
if (!workspaces.get(workspaceId)) throw DaemonError.notFound(`unknown workspace ${workspaceId}`);
|
||||
const ack = await router.relayWorkspaceQuery(workspaceId, "models");
|
||||
return json(200, { ...ack, workspaceId });
|
||||
}
|
||||
const candidates: ModelsCandidate[] = instances.instanceStates().map((state) => ({
|
||||
workspaceId: state.workspaceId,
|
||||
status: state.status,
|
||||
startedAt: state.startedAt ?? 0,
|
||||
sessions: instances.get(state.workspaceId)?.sessionIds().length ?? 0,
|
||||
}));
|
||||
const resolution = await resolveModels({
|
||||
candidates,
|
||||
query: async (ws) => {
|
||||
const connection = instances.get(ws);
|
||||
if (connection === undefined) {
|
||||
throw new DaemonError(ERROR_CODES.INSTANCE_UNAVAILABLE, `no instance for workspace ${ws}`);
|
||||
}
|
||||
return (await connection.command(
|
||||
{ id: `req-${randomUUID()}`, method: "workspace.query", params: { kind: "models" } },
|
||||
2500,
|
||||
)) as unknown as Record<string, unknown>;
|
||||
},
|
||||
log: (event, detail) => deps.logger?.debug(event, detail),
|
||||
});
|
||||
const { providers, pending, workspaceId: resolvedWorkspaceId, pendingReason } = resolution;
|
||||
return c.json({
|
||||
providers,
|
||||
pending,
|
||||
workspaceId: resolvedWorkspaceId,
|
||||
...(pendingReason === undefined ? {} : { pendingReason }),
|
||||
});
|
||||
});
|
||||
|
||||
app.get("/api/v1/devices", (c) => c.json(auth.listDevices()));
|
||||
@@ -324,7 +362,10 @@ export function createApp(deps: AppDeps): Hono<Env> {
|
||||
return c.body(null, 204);
|
||||
});
|
||||
|
||||
app.get("/api/v1/resources", async (c) => c.json(await instances.resources()));
|
||||
app.get("/api/v1/resources", async (c) => {
|
||||
const [snapshot, system] = await Promise.all([instances.resources(), deps.sysinfo?.sample()]);
|
||||
return c.json(system === undefined ? snapshot : { ...snapshot, system });
|
||||
});
|
||||
|
||||
app.get("/api/v1/diagnostics", (c) => {
|
||||
const metrics = deps.metrics?.() ?? { connections: 0 };
|
||||
|
||||
@@ -0,0 +1,167 @@
|
||||
/**
|
||||
* Pure routing module for resolving the model catalogue without spawning Neovim.
|
||||
*
|
||||
* `resolveModels` picks the best ready workspace instance, queries it, and
|
||||
* falls through to the next candidate on failure or a pending answer.
|
||||
* No Node I/O, no unref'd timers, no imports from http.ts.
|
||||
*/
|
||||
|
||||
export interface ModelsCandidate {
|
||||
workspaceId: string;
|
||||
status: string;
|
||||
sessions: number;
|
||||
startedAt: number;
|
||||
}
|
||||
|
||||
export type ModelsPendingReason = "fetching" | "no-instance" | "no-live-session";
|
||||
|
||||
export interface ModelsResolution {
|
||||
providers: unknown[];
|
||||
pending: boolean;
|
||||
workspaceId: string | null;
|
||||
pendingReason?: ModelsPendingReason;
|
||||
attempted: string[];
|
||||
}
|
||||
|
||||
export interface ResolveModelsInput {
|
||||
candidates: ModelsCandidate[];
|
||||
preferredWorkspaceId?: string | null;
|
||||
query: (workspaceId: string) => Promise<Record<string, unknown>>;
|
||||
/** default 2500 */
|
||||
timeoutMs?: number;
|
||||
log?: (event: string, detail: Record<string, unknown>) => void;
|
||||
}
|
||||
|
||||
/**
|
||||
* Race `query(workspaceId)` against a timeout.
|
||||
* Always resolves — rejects are caught and re-thrown as Error.
|
||||
* Every timer is cleared in a finally block.
|
||||
*/
|
||||
function queryWithTimeout(
|
||||
query: (ws: string) => Promise<Record<string, unknown>>,
|
||||
workspaceId: string,
|
||||
timeoutMs: number,
|
||||
): Promise<Record<string, unknown>> {
|
||||
return new Promise<Record<string, unknown>>((resolve, reject) => {
|
||||
let timer: ReturnType<typeof setTimeout> | undefined;
|
||||
|
||||
const cleanup = () => {
|
||||
if (timer !== undefined) {
|
||||
clearTimeout(timer);
|
||||
timer = undefined;
|
||||
}
|
||||
};
|
||||
|
||||
timer = setTimeout(() => {
|
||||
timer = undefined;
|
||||
reject(new Error(`models query timed out after ${timeoutMs}ms`));
|
||||
}, timeoutMs);
|
||||
|
||||
Promise.resolve()
|
||||
.then(() => query(workspaceId))
|
||||
.then(
|
||||
(result) => {
|
||||
cleanup();
|
||||
resolve(result);
|
||||
},
|
||||
(err: unknown) => {
|
||||
cleanup();
|
||||
reject(err instanceof Error ? err : new Error(String(err)));
|
||||
},
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
export async function resolveModels(input: ResolveModelsInput): Promise<ModelsResolution> {
|
||||
const { candidates, preferredWorkspaceId, query, timeoutMs = 2500, log } = input;
|
||||
|
||||
// --- 1. Only ready candidates are eligible (no-spawn guarantee) ---
|
||||
const ready = candidates.filter((c) => c.status === "ready");
|
||||
|
||||
if (ready.length === 0) {
|
||||
return {
|
||||
providers: [],
|
||||
pending: true,
|
||||
workspaceId: preferredWorkspaceId ?? null,
|
||||
pendingReason: "no-instance",
|
||||
attempted: [],
|
||||
};
|
||||
}
|
||||
|
||||
// --- 2. Order: preferred first (if ready), then sessions desc, startedAt desc ---
|
||||
const preferred = preferredWorkspaceId != null
|
||||
? ready.find((c) => c.workspaceId === preferredWorkspaceId)
|
||||
: undefined;
|
||||
|
||||
const rest = ready
|
||||
.filter((c) => c.workspaceId !== preferred?.workspaceId)
|
||||
.sort((a, b) => b.sessions - a.sessions || b.startedAt - a.startedAt);
|
||||
|
||||
const ordered: ModelsCandidate[] = preferred ? [preferred, ...rest] : rest;
|
||||
|
||||
// Deduplicate (rule 7: never query the same workspace twice)
|
||||
const seen = new Set<string>();
|
||||
const queue: ModelsCandidate[] = [];
|
||||
for (const c of ordered) {
|
||||
if (!seen.has(c.workspaceId)) {
|
||||
seen.add(c.workspaceId);
|
||||
queue.push(c);
|
||||
}
|
||||
}
|
||||
|
||||
// --- 3. Query in order ---
|
||||
const attempted: string[] = [];
|
||||
|
||||
for (const candidate of queue) {
|
||||
const { workspaceId } = candidate;
|
||||
let ack: Record<string, unknown>;
|
||||
try {
|
||||
ack = await queryWithTimeout(query, workspaceId, timeoutMs);
|
||||
} catch (err) {
|
||||
attempted.push(workspaceId);
|
||||
log?.("models.candidate_failed", {
|
||||
workspaceId,
|
||||
error: err instanceof Error ? err.message : String(err),
|
||||
});
|
||||
continue;
|
||||
}
|
||||
|
||||
// --- 4. Success condition ---
|
||||
if (Array.isArray(ack["providers"]) && (ack["providers"] as unknown[]).length > 0 && ack["pending"] !== true) {
|
||||
return {
|
||||
providers: ack["providers"] as unknown[],
|
||||
pending: false,
|
||||
workspaceId,
|
||||
attempted,
|
||||
};
|
||||
}
|
||||
|
||||
// Not a success — counts as attempted
|
||||
attempted.push(workspaceId);
|
||||
log?.("models.candidate_failed", {
|
||||
workspaceId,
|
||||
reason: "pending-or-empty",
|
||||
pending: ack["pending"],
|
||||
providerCount: Array.isArray(ack["providers"]) ? (ack["providers"] as unknown[]).length : 0,
|
||||
});
|
||||
}
|
||||
|
||||
// --- 5. Nothing succeeded ---
|
||||
// pendingReason: fetching when any candidate had sessions > 0, else no-live-session
|
||||
const hasSessions = queue.some((c) => c.sessions > 0);
|
||||
|
||||
// Best workspaceId to surface: first attempted, else preferred, else best ready candidate
|
||||
const bestWorkspaceId =
|
||||
attempted[0] ??
|
||||
preferredWorkspaceId ??
|
||||
queue[0]?.workspaceId ??
|
||||
null;
|
||||
|
||||
return {
|
||||
providers: [],
|
||||
pending: true,
|
||||
workspaceId: bestWorkspaceId,
|
||||
pendingReason: hasSessions ? "fetching" : "no-live-session",
|
||||
attempted,
|
||||
};
|
||||
}
|
||||
@@ -102,6 +102,7 @@ export async function startServer(config: Config, deps: ServerDeps): Promise<Sta
|
||||
startedAt: deps.startedAt,
|
||||
now: deps.now,
|
||||
metrics: () => ({ connections: ws.connections(), eventsSent: ws.eventsSent() }),
|
||||
sysinfo: deps.sysinfo,
|
||||
});
|
||||
|
||||
let closing: Promise<void> | undefined;
|
||||
|
||||
@@ -0,0 +1,122 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
cpuPercentBetween,
|
||||
cpuTimesFromCpus,
|
||||
createSysinfo,
|
||||
diskFromStatfs,
|
||||
parseMeminfo,
|
||||
parseProcStat,
|
||||
} from "../../src/core/sysinfo.js";
|
||||
|
||||
const mem = (available = "MemAvailable: 512 kB") => `MemTotal: 1024 kB\n${available}\nMemFree: 128 kB\nBuffers: 64 kB\nCached: 128 kB\n`;
|
||||
const cpus = (user: number, idle: number) => [{ times: { user, nice: 0, sys: 0, idle, irq: 0 } }];
|
||||
|
||||
describe("sysinfo", () => {
|
||||
it("parses meminfo using MemAvailable and fallback fields", () => {
|
||||
expect(parseMeminfo(mem())).toEqual({ totalBytes: 1024 * 1024, availableBytes: 512 * 1024 });
|
||||
expect(parseMeminfo(mem("MemFree: 128 kB"))).toEqual({ totalBytes: 1024 * 1024, availableBytes: 320 * 1024 });
|
||||
expect(parseMeminfo("MemAvailable: 1 kB")).toBeNull();
|
||||
});
|
||||
|
||||
it("parses proc stat and aggregates cpu times", () => {
|
||||
expect(parseProcStat("cpu 10 2 3 40 5 6 7\ncpu0 1 0 0 1 0 0 0\n")).toEqual({ idle: 45, total: 73 });
|
||||
expect(cpuTimesFromCpus(cpus(10, 40))).toEqual({ idle: 40, total: 50 });
|
||||
});
|
||||
|
||||
it("calculates bounded CPU percentages", () => {
|
||||
expect(cpuPercentBetween(null, { idle: 1, total: 2 })).toBeNull();
|
||||
expect(cpuPercentBetween({ idle: 1, total: 2 }, { idle: 1, total: 2 })).toBeNull();
|
||||
expect(cpuPercentBetween({ idle: 10, total: 20 }, { idle: 5, total: 10 })).toBeNull();
|
||||
expect(cpuPercentBetween({ idle: 10, total: 20 }, { idle: 15, total: 30 })).toBe(50);
|
||||
expect(cpuPercentBetween({ idle: 10, total: 20 }, { idle: 0, total: 30 })).toBe(100);
|
||||
expect(cpuPercentBetween({ idle: 10, total: 20 }, { idle: 30, total: 30 })).toBe(0);
|
||||
});
|
||||
|
||||
it("calculates disk usage and handles null cases", () => {
|
||||
expect(diskFromStatfs({ bsize: 100, blocks: 10, bfree: 4 })).toEqual({ totalBytes: 1000, usedBytes: 600, percent: 60 });
|
||||
expect(diskFromStatfs({ bsize: 100, blocks: 0, bfree: 0 })).toBeNull();
|
||||
expect(diskFromStatfs({ bsize: 0, blocks: 10, bfree: 0 })).toBeNull();
|
||||
expect(diskFromStatfs({ bsize: Number.NaN, blocks: 10, bfree: 0 })).toBeNull();
|
||||
expect(diskFromStatfs({ bsize: 100, blocks: 10, bfree: 20 })).toEqual({
|
||||
totalBytes: 1000,
|
||||
usedBytes: 0,
|
||||
percent: 0,
|
||||
});
|
||||
expect(diskFromStatfs({ bsize: 100, blocks: 10, bfree: -1 })).toBeNull();
|
||||
});
|
||||
|
||||
it("clamps malformed memory sampler values", async () => {
|
||||
const result = await createSysinfo({
|
||||
now: () => 1,
|
||||
platform: "darwin",
|
||||
cpus: () => cpus(10, 10),
|
||||
totalmem: () => Number.NaN,
|
||||
freemem: () => Number.POSITIVE_INFINITY,
|
||||
loadavg: () => [0, 0, 0],
|
||||
statfs: async () => ({ bsize: 100, blocks: 10, bfree: 20 }),
|
||||
}).sample();
|
||||
expect(result.memTotalBytes).toBe(0);
|
||||
expect(result.memUsedBytes).toBe(0);
|
||||
expect(result.memPercent).toBe(0);
|
||||
expect(result.diskPercent).toBe(0);
|
||||
});
|
||||
|
||||
it("samples injected system data, caches, and expires", async () => {
|
||||
let clock = 1000;
|
||||
let reads = 0;
|
||||
let stats = 0;
|
||||
const sampler = createSysinfo({
|
||||
now: () => clock,
|
||||
platform: "linux",
|
||||
diskPath: "/test",
|
||||
readFile: async (path) => { reads++; return path === "/proc/stat" ? "cpu 10 0 0 10 0 0 0" : mem(); },
|
||||
statfs: async () => { stats++; return { bsize: 100, blocks: 10, bfree: 4 }; },
|
||||
cpus: () => cpus(10, 10),
|
||||
totalmem: () => 999,
|
||||
freemem: () => 1,
|
||||
loadavg: () => [1.234, 2.345, 3.456],
|
||||
cacheMs: 100,
|
||||
});
|
||||
const first = await sampler.sample();
|
||||
expect(first).toEqual({ sampledAt: 1000, cpuPercent: null, cpuCores: 1, loadAvg: [1.23, 2.35, 3.46], memUsedBytes: 512 * 1024, memTotalBytes: 1024 * 1024, memPercent: 50, diskPath: "/test", diskUsedBytes: 600, diskTotalBytes: 1000, diskPercent: 60 });
|
||||
await sampler.sample();
|
||||
expect(reads).toBe(2);
|
||||
expect(stats).toBe(1);
|
||||
clock = 1100;
|
||||
await sampler.sample();
|
||||
expect(reads).toBe(4);
|
||||
expect(stats).toBe(2);
|
||||
});
|
||||
|
||||
it("resolves when total memory probing throws", async () => {
|
||||
const sampler = createSysinfo({
|
||||
platform: "darwin",
|
||||
cpus: () => cpus(1, 1),
|
||||
totalmem: () => { throw new Error("totalmem unavailable"); },
|
||||
freemem: () => 25,
|
||||
statfs: async () => ({ bsize: 1, blocks: 1, bfree: 0 }),
|
||||
loadavg: () => [0, 0, 0],
|
||||
});
|
||||
await expect(sampler.sample()).resolves.toMatchObject({ memTotalBytes: 0, memUsedBytes: 0, memPercent: 0 });
|
||||
});
|
||||
|
||||
it("falls back and resolves I/O failures with null CPU and disk", async () => {
|
||||
const result = await createSysinfo({
|
||||
now: () => 1,
|
||||
platform: "linux",
|
||||
readFile: async () => { throw new Error("read"); },
|
||||
statfs: async () => { throw new Error("statfs"); },
|
||||
cpus: () => { throw new Error("cpu"); },
|
||||
totalmem: () => 0,
|
||||
freemem: () => 0,
|
||||
loadavg: () => { throw new Error("load"); },
|
||||
}).sample();
|
||||
expect(result.cpuPercent).toBeNull();
|
||||
expect(result.loadAvg).toBeNull();
|
||||
expect(result.diskUsedBytes).toBeNull();
|
||||
expect(result.diskTotalBytes).toBeNull();
|
||||
expect(result.diskPercent).toBeNull();
|
||||
expect(result.memTotalBytes).toBe(0);
|
||||
expect(result.memUsedBytes).toBe(0);
|
||||
});
|
||||
});
|
||||
@@ -65,6 +65,10 @@ export class FakeConnection implements PluginConnection {
|
||||
this.subscribed.delete(sessionId);
|
||||
}
|
||||
|
||||
sessionIds(): string[] {
|
||||
return [...this.snapshots.keys()];
|
||||
}
|
||||
|
||||
snapshot(sessionId: string): SessionState | undefined {
|
||||
return this.snapshots.get(sessionId);
|
||||
}
|
||||
|
||||
@@ -4,6 +4,7 @@ import { join } from "node:path";
|
||||
import { AuthStore } from "../../src/daemon/auth.js";
|
||||
import { startServer, type StartedServer } from "../../src/daemon/server.js";
|
||||
import type { Config, Limits } from "../../src/config.js";
|
||||
import type { SysinfoSampler, SystemStats } from "../../src/core/sysinfo.js";
|
||||
import type { WorkspaceInfo } from "../../src/protocol/types.js";
|
||||
import { FakeBus, FakeInstanceManager, FakeWorkspaceStore } from "./fakes.js";
|
||||
|
||||
@@ -31,6 +32,26 @@ export function testConfig(overrides: Partial<Config> = {}): Config {
|
||||
return { ...base, ...overrides, limits: { ...base.limits, ...(overrides.limits ?? {}) } };
|
||||
}
|
||||
|
||||
/** Deterministic fake sampler returned when no override is provided. */
|
||||
export const FAKE_SYSTEM_STATS: SystemStats = {
|
||||
sampledAt: 1_700_000_000_000,
|
||||
cpuPercent: 42,
|
||||
cpuCores: 4,
|
||||
loadAvg: [1.5, 1.2, 0.9],
|
||||
memUsedBytes: 4 * 1024 ** 3,
|
||||
memTotalBytes: 16 * 1024 ** 3,
|
||||
memPercent: 25,
|
||||
diskPath: "/tmp/pi2-test",
|
||||
diskUsedBytes: 50 * 1024 ** 3,
|
||||
diskTotalBytes: 200 * 1024 ** 3,
|
||||
diskPercent: 25,
|
||||
};
|
||||
|
||||
export function makeFakeSysinfoSampler(stats: Partial<SystemStats> = {}): SysinfoSampler {
|
||||
const merged: SystemStats = { ...FAKE_SYSTEM_STATS, ...stats };
|
||||
return { sample: async () => merged };
|
||||
}
|
||||
|
||||
export interface HarnessOptions {
|
||||
workspaces?: WorkspaceInfo[];
|
||||
seedInstances?: string[];
|
||||
@@ -45,6 +66,8 @@ export interface HarnessOptions {
|
||||
snapshotWaitMs?: number;
|
||||
measureBufferedAmount?: (socket: unknown) => number;
|
||||
};
|
||||
/** Override the sysinfo sampler; defaults to a deterministic fake (no real OS I/O). */
|
||||
sysinfo?: SysinfoSampler;
|
||||
}
|
||||
|
||||
export interface Harness {
|
||||
@@ -107,6 +130,7 @@ export async function createHarness(options: HarnessOptions = {}): Promise<Harne
|
||||
startedAt: Date.now(),
|
||||
heartbeatMs: options.heartbeatMs,
|
||||
ws: options.wsOverrides,
|
||||
sysinfo: options.sysinfo ?? makeFakeSysinfoSampler(),
|
||||
});
|
||||
|
||||
return {
|
||||
|
||||
@@ -275,6 +275,7 @@ describe("HTTP API", () => {
|
||||
expect(attention.status).toBe(200);
|
||||
const models = await fetch(`${h.url}/api/v1/models?workspaceId=ws-1`, authed());
|
||||
expect(models.status).toBe(200);
|
||||
expect(await models.json()).toEqual(expect.objectContaining({ workspaceId: "ws-1" }));
|
||||
expect(conn.commands.some((call) => call.method === "workspace.query" && call.params?.kind === "models")).toBe(
|
||||
true,
|
||||
);
|
||||
@@ -425,6 +426,51 @@ describe("HTTP API", () => {
|
||||
expect(res.status).toBe(401);
|
||||
});
|
||||
|
||||
it("includes injected system stats in resources", async () => {
|
||||
const custom = await createHarness({ sysinfo: (await import("./harness.js")).makeFakeSysinfoSampler({ cpuPercent: 42 }) });
|
||||
try {
|
||||
const customToken = custom.createToken();
|
||||
const response = await fetch(`${custom.url}/api/v1/resources`, {
|
||||
headers: { Authorization: `Bearer ${customToken}` },
|
||||
});
|
||||
expect(response.status).toBe(200);
|
||||
expect((await response.json()).system).toEqual(expect.objectContaining({ cpuPercent: 42 }));
|
||||
} finally {
|
||||
await custom.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
it("includes system stats in info", async () => {
|
||||
const response = await fetch(`${h.url}/api/v1/info`);
|
||||
expect(response.status).toBe(200);
|
||||
expect(await response.json()).toEqual(expect.objectContaining({
|
||||
cpuCores: 4,
|
||||
loadAvg: [1.5, 1.2, 0.9],
|
||||
cpu: 42,
|
||||
mem: 25,
|
||||
disk: 25,
|
||||
}));
|
||||
});
|
||||
|
||||
it("resolves bare models without spawning when no instance is ready", async () => {
|
||||
const bare = await createHarness();
|
||||
try {
|
||||
const bareToken = bare.createToken();
|
||||
const response = await fetch(`${bare.url}/api/v1/models`, {
|
||||
headers: { Authorization: `Bearer ${bareToken}` },
|
||||
});
|
||||
expect(response.status).toBe(200);
|
||||
const body = (await response.json()) as Record<string, unknown>;
|
||||
expect(body).toEqual({
|
||||
providers: [], pending: true, workspaceId: null, pendingReason: "no-instance",
|
||||
});
|
||||
expect(body).not.toHaveProperty("attempted");
|
||||
expect(bare.instances.ensureCalls).toEqual([]);
|
||||
} finally {
|
||||
await bare.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
it("redirects a scanned /pair/<code> link to the zero-input connect page", async () => {
|
||||
const res = await fetch(`${h.url}/pair/abcd2345`, { redirect: "manual" });
|
||||
expect(res.status).toBe(302);
|
||||
|
||||
@@ -0,0 +1,308 @@
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import { resolveModels, type ModelsCandidate } from "../../src/daemon/models.js";
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Helpers
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
function makeCandidate(
|
||||
workspaceId: string,
|
||||
opts: Partial<Omit<ModelsCandidate, "workspaceId">> = {},
|
||||
): ModelsCandidate {
|
||||
return {
|
||||
workspaceId,
|
||||
status: opts.status ?? "ready",
|
||||
sessions: opts.sessions ?? 1,
|
||||
startedAt: opts.startedAt ?? 1000,
|
||||
};
|
||||
}
|
||||
|
||||
function okQuery(providers: unknown[] = [{ id: "openai" }]) {
|
||||
return vi.fn((_ws: string) =>
|
||||
Promise.resolve({ providers, pending: false }),
|
||||
);
|
||||
}
|
||||
|
||||
function pendingQuery() {
|
||||
return vi.fn((_ws: string) =>
|
||||
Promise.resolve({ providers: [], pending: true }),
|
||||
);
|
||||
}
|
||||
|
||||
function rejectingQuery(msg = "connection refused") {
|
||||
return vi.fn((_ws: string) => Promise.reject(new Error(msg)));
|
||||
}
|
||||
|
||||
function hangingQuery() {
|
||||
return vi.fn((_ws: string) => new Promise<Record<string, unknown>>(() => undefined));
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Tests
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe("resolveModels", () => {
|
||||
// 1. Preferred-first ordering
|
||||
it("queries the preferred workspace first", async () => {
|
||||
const callOrder: string[] = [];
|
||||
const query = vi.fn((ws: string) => {
|
||||
callOrder.push(ws);
|
||||
// Only "ws-b" returns a real answer so we can verify ordering
|
||||
if (ws === "ws-b") return Promise.resolve({ providers: [{ id: "openai" }], pending: false });
|
||||
return Promise.resolve({ providers: [], pending: true });
|
||||
});
|
||||
|
||||
const candidates = [
|
||||
makeCandidate("ws-a", { sessions: 5, startedAt: 2000 }),
|
||||
makeCandidate("ws-b", { sessions: 1, startedAt: 1000 }),
|
||||
];
|
||||
|
||||
const result = await resolveModels({
|
||||
candidates,
|
||||
preferredWorkspaceId: "ws-b",
|
||||
query,
|
||||
});
|
||||
|
||||
expect(callOrder[0]).toBe("ws-b");
|
||||
expect(result.pending).toBe(false);
|
||||
expect(result.workspaceId).toBe("ws-b");
|
||||
});
|
||||
|
||||
// 2. Sessions desc then startedAt desc when no preferred
|
||||
it("orders by sessions desc, then startedAt desc when no preferred", async () => {
|
||||
const callOrder: string[] = [];
|
||||
const query = vi.fn((ws: string) => {
|
||||
callOrder.push(ws);
|
||||
return Promise.resolve({ providers: [], pending: true });
|
||||
});
|
||||
|
||||
const candidates = [
|
||||
makeCandidate("ws-low-old", { sessions: 1, startedAt: 500 }),
|
||||
makeCandidate("ws-low-new", { sessions: 1, startedAt: 2000 }),
|
||||
makeCandidate("ws-high", { sessions: 10, startedAt: 1000 }),
|
||||
];
|
||||
|
||||
await resolveModels({ candidates, query });
|
||||
|
||||
expect(callOrder).toEqual(["ws-high", "ws-low-new", "ws-low-old"]);
|
||||
});
|
||||
|
||||
// 3. Non-ready candidates are never queried
|
||||
it("never queries non-ready candidates", async () => {
|
||||
const query = vi.fn((_ws: string) =>
|
||||
Promise.resolve({ providers: [{ id: "x" }], pending: false }),
|
||||
);
|
||||
|
||||
const candidates = [
|
||||
makeCandidate("ws-starting", { status: "starting" }),
|
||||
makeCandidate("ws-stopped", { status: "stopped" }),
|
||||
makeCandidate("ws-ready", { status: "ready" }),
|
||||
];
|
||||
|
||||
const result = await resolveModels({ candidates, query });
|
||||
|
||||
expect(query).toHaveBeenCalledTimes(1);
|
||||
expect(query).toHaveBeenCalledWith("ws-ready");
|
||||
expect(result.pending).toBe(false);
|
||||
expect(result.workspaceId).toBe("ws-ready");
|
||||
});
|
||||
|
||||
// 4. Empty candidate list → no-instance
|
||||
it("returns no-instance when candidate list is empty", async () => {
|
||||
const query = vi.fn();
|
||||
|
||||
const result = await resolveModels({
|
||||
candidates: [],
|
||||
preferredWorkspaceId: "ws-x",
|
||||
query,
|
||||
});
|
||||
|
||||
expect(query).not.toHaveBeenCalled();
|
||||
expect(result).toEqual({
|
||||
providers: [],
|
||||
pending: true,
|
||||
workspaceId: "ws-x",
|
||||
pendingReason: "no-instance",
|
||||
attempted: [],
|
||||
});
|
||||
});
|
||||
|
||||
// 5. All ready + pending with sessions → fetching
|
||||
it("returns fetching when all candidates are pending and have sessions", async () => {
|
||||
const query = pendingQuery();
|
||||
const candidates = [
|
||||
makeCandidate("ws-a", { sessions: 2 }),
|
||||
makeCandidate("ws-b", { sessions: 3 }),
|
||||
];
|
||||
|
||||
const result = await resolveModels({ candidates, query });
|
||||
|
||||
expect(result.pending).toBe(true);
|
||||
expect(result.pendingReason).toBe("fetching");
|
||||
expect(result.attempted).toHaveLength(2);
|
||||
});
|
||||
|
||||
// 6. All ready + pending with zero sessions → no-live-session
|
||||
it("returns no-live-session when all candidates have zero sessions", async () => {
|
||||
const query = pendingQuery();
|
||||
const candidates = [
|
||||
makeCandidate("ws-a", { sessions: 0 }),
|
||||
makeCandidate("ws-b", { sessions: 0 }),
|
||||
];
|
||||
|
||||
const result = await resolveModels({ candidates, query });
|
||||
|
||||
expect(result.pending).toBe(true);
|
||||
expect(result.pendingReason).toBe("no-live-session");
|
||||
expect(result.attempted).toHaveLength(2);
|
||||
});
|
||||
|
||||
// 7. Rejecting candidate falls through and is listed in attempted
|
||||
it("falls through a rejecting candidate and records it in attempted", async () => {
|
||||
const query = vi.fn((ws: string) => {
|
||||
if (ws === "ws-bad") return Promise.reject(new Error("kaboom"));
|
||||
return Promise.resolve({ providers: [{ id: "anthropic" }], pending: false });
|
||||
});
|
||||
|
||||
const candidates = [
|
||||
makeCandidate("ws-bad", { sessions: 5, startedAt: 2000 }),
|
||||
makeCandidate("ws-good", { sessions: 1, startedAt: 1000 }),
|
||||
];
|
||||
|
||||
const result = await resolveModels({ candidates, query });
|
||||
|
||||
expect(result.pending).toBe(false);
|
||||
expect(result.workspaceId).toBe("ws-good");
|
||||
expect(result.attempted).toContain("ws-bad");
|
||||
expect(result.attempted).not.toContain("ws-good");
|
||||
});
|
||||
|
||||
// 8. Hanging candidate times out and falls through
|
||||
it("times out a hanging candidate and falls through to the next", async () => {
|
||||
const query = vi.fn((ws: string) => {
|
||||
if (ws === "ws-hang") return hangingQuery()(ws);
|
||||
return Promise.resolve({ providers: [{ id: "gemini" }], pending: false });
|
||||
});
|
||||
|
||||
const candidates = [
|
||||
makeCandidate("ws-hang", { sessions: 2, startedAt: 2000 }),
|
||||
makeCandidate("ws-ok", { sessions: 1, startedAt: 1000 }),
|
||||
];
|
||||
|
||||
const result = await resolveModels({
|
||||
candidates,
|
||||
query,
|
||||
timeoutMs: 30, // very small — should fire quickly
|
||||
});
|
||||
|
||||
expect(result.pending).toBe(false);
|
||||
expect(result.workspaceId).toBe("ws-ok");
|
||||
expect(result.attempted).toContain("ws-hang");
|
||||
}, 3000);
|
||||
|
||||
it("falls through when a candidate query throws synchronously", async () => {
|
||||
const query = vi.fn((ws: string) => {
|
||||
if (ws === "ws-bad") throw new Error("synchronous failure");
|
||||
return Promise.resolve({ providers: [{ id: "fallback" }], pending: false });
|
||||
});
|
||||
|
||||
const result = await resolveModels({
|
||||
candidates: [makeCandidate("ws-bad", { sessions: 2 }), makeCandidate("ws-good", { sessions: 1 })],
|
||||
query,
|
||||
});
|
||||
|
||||
expect(result.workspaceId).toBe("ws-good");
|
||||
expect(result.attempted).toEqual(["ws-bad"]);
|
||||
});
|
||||
|
||||
// 9. First non-pending non-empty answer wins; later candidates are not queried
|
||||
it("stops at the first successful answer and does not query later candidates", async () => {
|
||||
const query = vi.fn((ws: string) => {
|
||||
if (ws === "ws-a") return Promise.resolve({ providers: [{ id: "openai" }], pending: false });
|
||||
return Promise.resolve({ providers: [{ id: "should-not-appear" }], pending: false });
|
||||
});
|
||||
|
||||
const candidates = [
|
||||
makeCandidate("ws-a", { sessions: 2 }),
|
||||
makeCandidate("ws-b", { sessions: 1 }),
|
||||
];
|
||||
|
||||
const result = await resolveModels({ candidates, query });
|
||||
|
||||
expect(query).toHaveBeenCalledTimes(1);
|
||||
expect(query).toHaveBeenCalledWith("ws-a");
|
||||
expect(result.providers).toEqual([{ id: "openai" }]);
|
||||
expect(result.workspaceId).toBe("ws-a");
|
||||
});
|
||||
|
||||
// 10. Provider order inside the winning ack is preserved
|
||||
it("preserves provider order from the winning ack", async () => {
|
||||
const providers = [{ id: "z" }, { id: "a" }, { id: "m" }];
|
||||
const query = okQuery(providers);
|
||||
|
||||
const result = await resolveModels({
|
||||
candidates: [makeCandidate("ws-1")],
|
||||
query,
|
||||
});
|
||||
|
||||
expect(result.providers).toEqual(providers);
|
||||
});
|
||||
|
||||
// Extra: preferred workspace that is not ready is ignored (falls to ready pool)
|
||||
it("ignores a preferred workspace that is not ready", async () => {
|
||||
const query = okQuery();
|
||||
|
||||
const candidates = [
|
||||
makeCandidate("ws-preferred", { status: "starting" }),
|
||||
makeCandidate("ws-ready", { status: "ready" }),
|
||||
];
|
||||
|
||||
const result = await resolveModels({
|
||||
candidates,
|
||||
preferredWorkspaceId: "ws-preferred",
|
||||
query,
|
||||
});
|
||||
|
||||
expect(query).not.toHaveBeenCalledWith("ws-preferred");
|
||||
expect(query).toHaveBeenCalledWith("ws-ready");
|
||||
expect(result.pending).toBe(false);
|
||||
});
|
||||
|
||||
// Extra: log callback is called on failure
|
||||
it("calls the log callback when a candidate fails", async () => {
|
||||
const logs: { event: string; detail: Record<string, unknown> }[] = [];
|
||||
const log = vi.fn((event: string, detail: Record<string, unknown>) => {
|
||||
logs.push({ event, detail });
|
||||
});
|
||||
|
||||
const query = rejectingQuery("boom");
|
||||
const candidates = [makeCandidate("ws-fail")];
|
||||
|
||||
await resolveModels({ candidates, query, log });
|
||||
|
||||
expect(log).toHaveBeenCalledOnce();
|
||||
expect(logs[0]!.event).toBe("models.candidate_failed");
|
||||
expect(logs[0]!.detail["workspaceId"]).toBe("ws-fail");
|
||||
});
|
||||
|
||||
// Extra: no-instance returns null workspaceId when no preferred given
|
||||
it("returns null workspaceId when no candidates and no preferred", async () => {
|
||||
const result = await resolveModels({ candidates: [], query: vi.fn() });
|
||||
expect(result.workspaceId).toBeNull();
|
||||
expect(result.pendingReason).toBe("no-instance");
|
||||
});
|
||||
|
||||
// Extra: attempted list in fallback resolution uses first attempted ws
|
||||
it("uses the first attempted workspace as workspaceId in the fallback", async () => {
|
||||
const query = pendingQuery();
|
||||
const candidates = [
|
||||
makeCandidate("ws-first", { sessions: 3, startedAt: 2000 }),
|
||||
makeCandidate("ws-second", { sessions: 1, startedAt: 1000 }),
|
||||
];
|
||||
|
||||
const result = await resolveModels({ candidates, query });
|
||||
|
||||
expect(result.workspaceId).toBe("ws-first");
|
||||
expect(result.attempted).toEqual(["ws-first", "ws-second"]);
|
||||
});
|
||||
});
|
||||
@@ -3,6 +3,17 @@ import { cn } from "@/lib/utils";
|
||||
/** Status-dot vocabulary from the design's `:PiSessions` state matrix. */
|
||||
export type DotStatus = "busy" | "compacting" | "idle" | "ok" | "err" | "attention" | "exited" | "dead";
|
||||
|
||||
/**
|
||||
* Blink rate, in shared-clock phases (`web/src/lib/blink.ts`): `fast` follows
|
||||
* `data-pi-blink-fast` (500ms), `slow` follows `data-pi-blink-slow` (1000ms).
|
||||
*/
|
||||
export type BlinkRate = "fast" | "slow";
|
||||
|
||||
/**
|
||||
* Colour only. Whether a dot blinks is NOT encoded here: `dot--busy` is amber
|
||||
* whether it pulses (a running turn) or not (a startup `connecting` chip), so a
|
||||
* class-keyed dim rule cannot express the matrix. `blink` carries it instead.
|
||||
*/
|
||||
export const DOT_CLASS: Record<DotStatus, string> = {
|
||||
busy: "dot--busy",
|
||||
compacting: "dot--compacting",
|
||||
@@ -14,6 +25,11 @@ export const DOT_CLASS: Record<DotStatus, string> = {
|
||||
dead: "dot--dead",
|
||||
};
|
||||
|
||||
export const BLINK_CLASS: Record<BlinkRate, string> = {
|
||||
fast: "dot--blink-fast",
|
||||
slow: "dot--blink-slow",
|
||||
};
|
||||
|
||||
export type ServerStatus = "online" | "degraded" | "offline";
|
||||
|
||||
/** Server / connection status mapping (online → ok, degraded → attention, else exited). */
|
||||
@@ -27,20 +43,29 @@ export function serverDotClass(status: ServerStatus | string | null | undefined)
|
||||
|
||||
export interface StatusDotProps {
|
||||
status: DotStatus;
|
||||
/**
|
||||
* Blink rate decided by the *view* that owns the dot (`DotView.blink`), never
|
||||
* by the DOM location or the colour class. Omitted/`null` = solid.
|
||||
*/
|
||||
blink?: BlinkRate | null;
|
||||
title?: string;
|
||||
className?: string;
|
||||
/** Pin the dot solid (no blink) — nvim's "focused child error is steady red". */
|
||||
steady?: boolean;
|
||||
/** "You are here" overlay (nvim `PiSessionsListCurrent`, agent blue). */
|
||||
current?: boolean;
|
||||
/** Decorative by default; pass a title to expose the state to assistive tech. */
|
||||
"aria-hidden"?: boolean;
|
||||
}
|
||||
|
||||
export function StatusDot({ status, title, className, steady, current, ...rest }: StatusDotProps) {
|
||||
export function StatusDot({ status, blink, title, className, current, ...rest }: StatusDotProps) {
|
||||
return (
|
||||
<span
|
||||
className={cn("dot", DOT_CLASS[status], steady && "dot--steady", current && "dot--current", className)}
|
||||
className={cn(
|
||||
"dot",
|
||||
DOT_CLASS[status],
|
||||
blink ? BLINK_CLASS[blink] : null,
|
||||
current && "dot--current",
|
||||
className,
|
||||
)}
|
||||
title={title}
|
||||
aria-label={title}
|
||||
aria-hidden={title ? undefined : true}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
import { Icon } from "@/components/icons";
|
||||
import { StatusDot } from "@/components/ui/status-dot";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
import type { TrayTab } from "./store";
|
||||
@@ -80,7 +81,7 @@ export function HeadChips({
|
||||
>
|
||||
<Icon name="terminal" />
|
||||
<span className="head-chip__label">{t("chat.tabTasks")}</span>
|
||||
{running ? <span className="dot dot--busy" aria-hidden="true" /> : null}
|
||||
{running ? <StatusDot status="busy" blink="fast" /> : null}
|
||||
<span className="head-chip__count tabular">{taskCount}</span>
|
||||
</button>
|
||||
</div>
|
||||
|
||||
@@ -6,12 +6,14 @@ import { Button } from "@/components/ui/button";
|
||||
import { Modal } from "@/components/ui/dialog";
|
||||
import { KV } from "@/components/ui/kv";
|
||||
import { Spinner } from "@/components/ui/spinner";
|
||||
import { StatusDot } from "@/components/ui/status-dot";
|
||||
import { toast } from "@/components/ui/toast";
|
||||
import { ApiError, errorI18nKey } from "@/lib/api";
|
||||
import { chatCommands, runCommand } from "./commands";
|
||||
import type { ModelGroup } from "./data";
|
||||
import { withCurrentModel } from "./data";
|
||||
import { formatDuration, THINKING_LEVELS } from "./format";
|
||||
import { taskDotView } from "./session-tray";
|
||||
|
||||
function rec(value: unknown): Record<string, unknown> | undefined {
|
||||
return value && typeof value === "object" && !Array.isArray(value) ? (value as Record<string, unknown>) : undefined;
|
||||
@@ -259,6 +261,7 @@ export function TaskOutputModal({ open, session, task, onClose, onStop }: TaskOu
|
||||
if (!task) return null;
|
||||
const status = result?.status ?? task.status;
|
||||
const running = status === "running";
|
||||
const dot = taskDotView(status);
|
||||
const duration = result?.durationMs ?? (running ? Date.now() - task.startTime : (task.durationMs ?? 0));
|
||||
const exitCode = result?.exitCode !== undefined ? result.exitCode : (task.exitCode ?? null);
|
||||
const outputFile = result?.outputFile ?? task.outputFile;
|
||||
@@ -295,7 +298,7 @@ export function TaskOutputModal({ open, session, task, onClose, onStop }: TaskOu
|
||||
<div>
|
||||
<KV label={t("chat.status")}>
|
||||
<span className="row">
|
||||
<span className={`dot ${running ? "dot--busy" : status === "completed" ? "dot--ok" : status === "failed" ? "dot--err" : "dot--idle"}`} />
|
||||
<StatusDot status={dot.status} blink={dot.blink} />
|
||||
{t(`state.${status}`)}
|
||||
</span>
|
||||
</KV>
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { applyEvent, createReducer, type Reducer } from "@protocol/reducer";
|
||||
import type { Entry, ModelRef, SessionEvent, SessionState, ThinkingLevel } from "@protocol/types";
|
||||
import type { DotStatus } from "@/components/ui/status-dot";
|
||||
import type { BlinkRate, DotStatus } from "@/components/ui/status-dot";
|
||||
import { normalizeTodos, projectEntries, type ProjectedEntry } from "@/lib/entry-projection";
|
||||
|
||||
const EMPTY_USAGE = { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, cost: 0 };
|
||||
@@ -509,12 +509,14 @@ function attentionPending(state: SessionState): boolean {
|
||||
}
|
||||
|
||||
/**
|
||||
* A dot render decision: the base status plus the two overlay modifiers.
|
||||
* `steady` pins the dot solid, `current` paints the "you are here" overlay.
|
||||
* A dot render decision: the colour, its blink rate and the "you are here"
|
||||
* overlay. `blink` is the *only* place the animation is decided — the renderer
|
||||
* never infers it from the colour class or from where the dot is mounted — and
|
||||
* omitting it means the dot is solid.
|
||||
*/
|
||||
export interface DotView {
|
||||
status: DotStatus;
|
||||
steady?: boolean;
|
||||
blink?: BlinkRate;
|
||||
current?: boolean;
|
||||
}
|
||||
|
||||
@@ -531,7 +533,10 @@ function withCurrent(view: DotView, state: SessionState, viewed: boolean): DotVi
|
||||
// The plugin's `markable` is a positive list: only a live session carries the
|
||||
// marker, and a `compacting` one blinks at the busy rate under it.
|
||||
if (state.status !== "idle" && state.status !== "busy" && state.status !== "compacting") return view;
|
||||
return { current: true, status: state.status === "compacting" ? "busy" : view.status };
|
||||
// The rate follows the painted status, so a focused compacting row blinks at
|
||||
// the busy rate (fast) instead of half speed, exactly like the plugin.
|
||||
if (state.status === "compacting") return { current: true, status: "busy", blink: "fast" };
|
||||
return { ...view, current: true };
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -545,11 +550,11 @@ function parentDot(state: SessionState): DotView {
|
||||
// plugin every "not running" row is `exited` (sessions.lua:75-78), which is
|
||||
// why a dead row outranks its own unread error/attention/done flags.
|
||||
if (state.status === "exited" || state.status === "interrupted") return { status: "dead" };
|
||||
if (state.flags.error) return { status: "err" };
|
||||
if (state.flags.error) return { status: "err", blink: "fast" };
|
||||
if (attentionPending(state)) return { status: "attention" };
|
||||
if (state.flags.done) return { status: "ok" };
|
||||
if (state.status === "busy") return { status: "busy" };
|
||||
if (state.status === "compacting") return { status: "compacting" };
|
||||
if (state.flags.done) return { status: "ok", blink: "fast" };
|
||||
if (state.status === "busy") return { status: "busy", blink: "fast" };
|
||||
if (state.status === "compacting") return { status: "compacting", blink: "slow" };
|
||||
return { status: "idle" };
|
||||
}
|
||||
|
||||
@@ -569,8 +574,8 @@ export function sessionDot(state: SessionState, opts: { viewed?: boolean } = {})
|
||||
function childDot(state: SessionState, viewed: boolean): DotView {
|
||||
if (state.status === "exited") return { status: "exited" };
|
||||
if (state.status === "interrupted") return { status: "dead" };
|
||||
if (state.flags.error) return { status: "err", steady: viewed };
|
||||
if (state.status === "busy" || state.status === "compacting") return { status: "busy" };
|
||||
if (state.flags.error) return viewed ? { status: "err" } : { status: "err", blink: "fast" };
|
||||
if (state.status === "busy" || state.status === "compacting") return { status: "busy", blink: "fast" };
|
||||
return { status: "idle" };
|
||||
}
|
||||
|
||||
@@ -591,12 +596,18 @@ export function subagentDot(
|
||||
): DotView {
|
||||
switch (subagent.status) {
|
||||
case "active":
|
||||
// A manifest entry with a live session is rendered as *that* session
|
||||
// row, so this branch only ever sees a manifest nothing live owns (a
|
||||
// spawn in flight, or a stale entry). The plugin colours a child by its
|
||||
// live status (`sessions.lua` `append_child_row`) and blinks only the
|
||||
// live busy one, so the amber is informative but must stay solid —
|
||||
// nothing acknowledges a manifest blink and it would blink forever.
|
||||
return { status: "busy" };
|
||||
case "completed":
|
||||
case "dormant":
|
||||
return { status: "exited" };
|
||||
case "failed":
|
||||
return { status: "err", steady: opts.viewed === true };
|
||||
return opts.viewed === true ? { status: "err" } : { status: "err", blink: "fast" };
|
||||
case "interrupted":
|
||||
return { status: "dead" };
|
||||
default:
|
||||
|
||||
@@ -6,11 +6,12 @@ import { Icon } from "@/components/icons";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { Empty } from "@/components/ui/empty";
|
||||
import { Progress } from "@/components/ui/progress";
|
||||
import { StatusDot, type DotStatus } from "@/components/ui/status-dot";
|
||||
import { StatusDot } from "@/components/ui/status-dot";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
import { TodoList } from "./blocks";
|
||||
import { formatDuration } from "./format";
|
||||
import type { DotView } from "./session-state";
|
||||
import { subagentTitle } from "./session-title";
|
||||
import type { TrayTab } from "./store";
|
||||
|
||||
@@ -36,11 +37,19 @@ export interface SessionTrayProps {
|
||||
|
||||
const TABS: TrayTab[] = ["todo", "tasks"];
|
||||
|
||||
function taskDot(status: TaskItem["status"]): DotStatus {
|
||||
if (status === "running") return "busy";
|
||||
if (status === "completed") return "ok";
|
||||
if (status === "failed") return "err";
|
||||
return "idle";
|
||||
/**
|
||||
* `:PiTasks` (`lua/pi/ui/tasks.lua` `dot_hl`) parity, shared with the
|
||||
* task-output modal: only a *running* task blinks. A finished task is solid —
|
||||
* a `completed` green is not an unread notification, and a `failed` red has no
|
||||
* acknowledgement path, so blinking it would blink forever next to session dots
|
||||
* that the user has already seen.
|
||||
*/
|
||||
export function taskDotView(status: TaskItem["status"]): DotView {
|
||||
if (status === "running") return { status: "busy", blink: "fast" };
|
||||
if (status === "completed") return { status: "ok" };
|
||||
if (status === "failed") return { status: "err" };
|
||||
if (status === "stopped") return { status: "attention" };
|
||||
return { status: "idle" };
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -274,9 +283,10 @@ export function SessionTray({
|
||||
{tasks.map((task) => {
|
||||
const running = task.status === "running";
|
||||
const duration = running ? Date.now() - task.startTime : task.durationMs;
|
||||
const dot = taskDotView(task.status);
|
||||
return (
|
||||
<div key={task.id} className="task-row" data-task-id={task.id}>
|
||||
<StatusDot status={taskDot(task.status)} />
|
||||
<StatusDot status={dot.status} blink={dot.blink} />
|
||||
<button
|
||||
type="button"
|
||||
className="task-row__main"
|
||||
|
||||
@@ -213,7 +213,7 @@ export function SessionTree({
|
||||
aria-current={selected ? "true" : undefined}
|
||||
onClick={() => onSelectSession(session.sessionId)}
|
||||
>
|
||||
<StatusDot status={dot.status} steady={dot.steady} current={dot.current} />
|
||||
<StatusDot status={dot.status} blink={dot.blink} current={dot.current} />
|
||||
{title.spinner ? <SessionTitleSpinner /> : null}
|
||||
<span
|
||||
className={cn(
|
||||
@@ -280,7 +280,7 @@ export function SessionTree({
|
||||
data-sub-id={subagent.id}
|
||||
onClick={() => onSelectSubagent(session.sessionId, subagent.id)}
|
||||
>
|
||||
<StatusDot status={dot.status} steady={dot.steady} />
|
||||
<StatusDot status={dot.status} blink={dot.blink} />
|
||||
<span
|
||||
className={cn(
|
||||
"t-name truncate",
|
||||
|
||||
@@ -279,11 +279,7 @@ export function SubagentView({
|
||||
<span className="sub-back__label">{t("chat.subview.back")}</span>
|
||||
</button>
|
||||
<div className="stream-title">
|
||||
<StatusDot
|
||||
status={dot.status}
|
||||
steady={dot.steady}
|
||||
title={t(`state.${subagent.status}`)}
|
||||
/>
|
||||
<StatusDot status={dot.status} blink={dot.blink} title={t(`state.${subagent.status}`)} />
|
||||
<h2 className="stream-name truncate" tabIndex={-1} title={task ? `${name} · ${task}` : name}>
|
||||
{name}
|
||||
</h2>
|
||||
|
||||
@@ -188,7 +188,7 @@ export function Telemetry({ session, subagent, entries, className }: TelemetryPr
|
||||
data-testid="telemetry"
|
||||
>
|
||||
<span className={cn("telemetry__state", "sub-state", tone)} data-testid="telemetry-state">
|
||||
<StatusDot status={dot.status} steady={dot.steady} />
|
||||
<StatusDot status={dot.status} blink={dot.blink} />
|
||||
{t(`state.${subagent.status}`)}
|
||||
</span>
|
||||
{elapsed ? (
|
||||
|
||||
@@ -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">
|
||||
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
@@ -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;
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -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]}`;
|
||||
}
|
||||
|
||||
|
||||
@@ -8,11 +8,14 @@ import { ErrorBlock, LoadingBlock, StatusCard, StatusEmpty } from "./card-parts"
|
||||
|
||||
export type { StatusTask };
|
||||
|
||||
/** `:PiTasks` (`lua/pi/ui/tasks.lua` `dot_hl`) vocabulary — the same colours the
|
||||
* chat tray renders through `taskDotView`; this card just never blinks (a
|
||||
* monitoring report has no acknowledgement gesture). */
|
||||
const TASK_DOT: Record<string, DotStatus> = {
|
||||
running: "busy",
|
||||
completed: "ok",
|
||||
failed: "err",
|
||||
stopped: "exited",
|
||||
stopped: "attention",
|
||||
};
|
||||
|
||||
export interface TasksCardProps {
|
||||
|
||||
@@ -0,0 +1,56 @@
|
||||
import type { QueryClient } from "@tanstack/react-query";
|
||||
|
||||
import type { WorkspaceInfo } from "@/lib/protocol";
|
||||
import type { WsFrame } from "@/lib/ws";
|
||||
import { useWorkspacesStore } from "@/stores/workspaces";
|
||||
|
||||
/**
|
||||
* Validate and narrow a pushed `workspace_update` WS frame.
|
||||
* Never throws on hostile input (null, malformed envelopes, wrong types).
|
||||
*/
|
||||
export function parseWorkspaceUpdate(frame: WsFrame): WorkspaceInfo | null {
|
||||
if (!frame || typeof frame !== "object") return null;
|
||||
try {
|
||||
const payload = frame.payload;
|
||||
if (!payload || typeof payload !== "object" || Array.isArray(payload)) return null;
|
||||
const record = payload as Record<string, unknown>;
|
||||
if (typeof record.workspaceId !== "string" || record.workspaceId.trim() === "") {
|
||||
return null;
|
||||
}
|
||||
if (typeof record.cwd !== "string") {
|
||||
return null;
|
||||
}
|
||||
return payload as unknown as WorkspaceInfo;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function mergeRows(list: WorkspaceInfo[], info: WorkspaceInfo): WorkspaceInfo[] {
|
||||
const index = list.findIndex((w) => w.workspaceId === info.workspaceId);
|
||||
if (index === -1) return [...list, info];
|
||||
const next = list.slice();
|
||||
next[index] = info;
|
||||
return next;
|
||||
}
|
||||
|
||||
/**
|
||||
* Apply a live workspace update:
|
||||
* - replaces or appends in the ['workspaces'] cache
|
||||
* - replaces or appends in ['chat-workspaces'] cache only if already cached
|
||||
* - upserts in the zustand useWorkspacesStore
|
||||
* - invalidates ['health'] so the status page reflects instance state
|
||||
*/
|
||||
export function applyWorkspaceUpdate(queryClient: QueryClient, info: WorkspaceInfo): void {
|
||||
queryClient.setQueryData<WorkspaceInfo[]>(["workspaces"], (old) =>
|
||||
Array.isArray(old) ? mergeRows(old, info) : [info],
|
||||
);
|
||||
|
||||
queryClient.setQueryData<WorkspaceInfo[]>(["chat-workspaces"], (old) =>
|
||||
Array.isArray(old) ? mergeRows(old, info) : old,
|
||||
);
|
||||
|
||||
useWorkspacesStore.getState().upsert(info);
|
||||
|
||||
void queryClient.invalidateQueries({ queryKey: ["health"] });
|
||||
}
|
||||
+29
-2
@@ -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) =>
|
||||
|
||||
@@ -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.",
|
||||
|
||||
@@ -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": "在手机端扫码配对后,设备会显示在这里。",
|
||||
|
||||
+11
-2
@@ -126,6 +126,10 @@ function ChatExperience({ sessionId }: { sessionId?: string }) {
|
||||
if (!viewedSessionId || (!viewedDone && !viewedError)) return;
|
||||
useSessionsStore.getState().markSeen(viewedSessionId);
|
||||
}, [viewedSessionId, viewedDone, viewedError]);
|
||||
// The stream head shows the same session the selected tree row does, so it
|
||||
// renders that row's `DotView` (`viewed: true`) rather than re-deriving a
|
||||
// colour: one session must never show two different blink rates.
|
||||
const headDot = active ? sessionDot(active, { viewed: true }) : null;
|
||||
const history = useSessionHistory(
|
||||
active?.sessionId,
|
||||
active?.entries ?? NO_ENTRIES,
|
||||
@@ -544,8 +548,13 @@ function ChatExperience({ sessionId }: { sessionId?: string }) {
|
||||
</button>
|
||||
) : null}
|
||||
<div className="stream-title">
|
||||
{active ? (
|
||||
<StatusDot status={sessionDot(active).status} title={t(`state.${sessionStatusKey(active)}`)} />
|
||||
{active && headDot ? (
|
||||
<StatusDot
|
||||
status={headDot.status}
|
||||
blink={headDot.blink}
|
||||
current={headDot.current}
|
||||
title={t(`state.${sessionStatusKey(active)}`)}
|
||||
/>
|
||||
) : null}
|
||||
<h2 className="stream-name truncate" tabIndex={-1} ref={streamNameRef}>
|
||||
{active ? activeTitle?.text : (workspace?.name ?? t("nav.chat"))}
|
||||
|
||||
@@ -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()}
|
||||
/>
|
||||
|
||||
+27
-5
@@ -53,6 +53,8 @@
|
||||
* { margin: 0; }
|
||||
|
||||
html, body, #root { height: 100%; }
|
||||
/* No browser-side text inflation: rotating the phone must not resize the page. */
|
||||
html { -webkit-text-size-adjust: 100%; text-size-adjust: 100%; }
|
||||
body {
|
||||
font-family: var(--font-sans);
|
||||
font-size: var(--fs-body);
|
||||
@@ -387,13 +389,20 @@ code, pre { font-family: var(--font-mono); font-size: 0.875em; }
|
||||
.dot--dead { background: var(--err); }
|
||||
.dot--attention { background: var(--warn); box-shadow: 0 0 0 2px color-mix(in oklch, var(--warn) 22%, transparent); }
|
||||
.dot--exited { background: transparent; box-shadow: inset 0 0 0 1.5px var(--muted-foreground); }
|
||||
/* "You are here" (nvim `PiSessionsListCurrent`): agent blue wherever the dot is
|
||||
mounted, so the stream-head dot and its list row cannot disagree. Scoping this
|
||||
to `.tree-row` would leave the head's `dot--current` inert. */
|
||||
.dot--current { background: var(--info); }
|
||||
@keyframes pulse { 50% { opacity: .35; } }
|
||||
|
||||
/* Shared blink phase driven by html[data-pi-blink-*] attributes (single window clock) */
|
||||
html[data-pi-blink-fast="dim"] .dot--busy:not(.dot--steady),
|
||||
html[data-pi-blink-fast="dim"] .dot--err:not(.dot--steady),
|
||||
html[data-pi-blink-fast="dim"] .tree-row .dot--ok { opacity: .35; }
|
||||
html[data-pi-blink-slow="dim"] .dot--compacting:not(.dot--steady) { opacity: .35; }
|
||||
/* One blink contract. The <html> attributes are the shared clock (lib/blink.ts);
|
||||
whether a dot participates — and at which rate — is decided once, by the view
|
||||
that renders it (`DotView.blink` → `.dot--blink-fast` / `.dot--blink-slow`).
|
||||
Nothing here may key on a colour class or on a component wrapper: the same
|
||||
status must blink the same in the session list, the stream head, a task row
|
||||
or a dialog. A dot without a `dot--blink-*` class is solid. */
|
||||
html[data-pi-blink-fast="dim"] .dot--blink-fast,
|
||||
html[data-pi-blink-slow="dim"] .dot--blink-slow { opacity: .35; }
|
||||
|
||||
.chip {
|
||||
display: inline-flex; align-items: center; gap: var(--space-2);
|
||||
@@ -460,6 +469,19 @@ html[data-pi-blink-slow="dim"] .dot--compacting:not(.dot--steady) { opacity: .35
|
||||
.field .hint.is-err { color: var(--err); }
|
||||
.field--invalid .input, .field--invalid .textarea, .field--invalid .select { border-color: var(--err); }
|
||||
|
||||
/* ---------- touch: keep every text control at 16px ----------
|
||||
Focusing a text control smaller than 16px makes Mobile Safari zoom the visual
|
||||
viewport in, and it does not zoom back out when the keyboard closes — the
|
||||
page stays scaled for the rest of the session. Every control here is
|
||||
deliberately smaller (`input/select/textarea` inherit `--fs-body` 14px,
|
||||
`.composer__ta` is 15px), so the floor lives here once instead of in each
|
||||
component. `!important` because a bare element selector would lose the
|
||||
cascade to the one-class utilities that style those controls, and the rule
|
||||
keys on `hover: none` so landscape phones (well past 600px) are covered too. */
|
||||
@media (hover: none), (max-width: 599px) {
|
||||
input, select, textarea, [contenteditable="true"] { font-size: 16px !important; }
|
||||
}
|
||||
|
||||
/* ---------- tabs / progress / kv / misc ---------- */
|
||||
.tabs { display: flex; gap: var(--space-1); border-bottom: 1px solid var(--border-subtle); }
|
||||
.tab { padding: var(--space-2) var(--space-3); font-size: .875rem; font-weight: 550; color: var(--muted-foreground); border-bottom: 2px solid transparent; margin-bottom: -1px; }
|
||||
|
||||
@@ -446,10 +446,8 @@
|
||||
}
|
||||
|
||||
/* 状态圆点:由 <html> 根节点上的单一全局时钟驱动(data-pi-blink-* 属性,见 app.css 与 blink.ts),
|
||||
不再使用每个圆点独立的 CSS animation,避免相位漂移。当前聚焦会话叠加高亮背景。 */
|
||||
.tree-row .dot--current {
|
||||
background: var(--info);
|
||||
}
|
||||
不再使用每个圆点独立的 CSS animation,避免相位漂移。当前会话的蓝色标记在 app.css 的
|
||||
`.dot--current`(不按容器限定:流头圆点与列表行必须同色)。 */
|
||||
|
||||
/* 子会话 / 子代理行:更矮、更小、灰一档;状态只由圆点表达。 */
|
||||
.tree-row--sub .tree-row__main {
|
||||
|
||||
@@ -188,34 +188,55 @@ describe("session tree rows", () => {
|
||||
expect(s3Dot).toHaveClass("dot", "dot--ok");
|
||||
expect(s3Dot).not.toHaveClass("dot--current");
|
||||
|
||||
// 2. Child exited row renders hollow dot--exited (never dead red).
|
||||
// 2. Child exited row renders hollow dot--exited (never dead red, never blinking).
|
||||
const c1Dot = rowMain("c1").querySelector(".dot");
|
||||
expect(c1Dot).toHaveClass("dot", "dot--exited");
|
||||
expect(c1Dot).not.toHaveClass("dot--dead");
|
||||
expect(c1Dot).not.toHaveClass("dot--current");
|
||||
expect(c1Dot).not.toHaveClass("dot--blink-fast");
|
||||
|
||||
// 3. Child error row unselected renders dot--err without steady modifier.
|
||||
// 3. Child error row unselected renders dot--err + dot--blink-fast in the list.
|
||||
const c2DotUnselected = rowMain("c2").querySelector(".dot");
|
||||
expect(c2DotUnselected).toHaveClass("dot", "dot--err");
|
||||
expect(c2DotUnselected).not.toHaveClass("dot--steady");
|
||||
expect(c2DotUnselected).toHaveClass("dot", "dot--err", "dot--blink-fast");
|
||||
expect(c2DotUnselected).not.toHaveClass("dot--blink-slow");
|
||||
|
||||
// 4. Selected idle row renders dot--current (and dot--idle when done flag consumed).
|
||||
rerender(treeElement({ sessions, selectedId: "s2" }));
|
||||
const s2DotSelected = rowMain("s2").querySelector(".dot");
|
||||
expect(s2DotSelected).toHaveClass("dot", "dot--idle", "dot--current");
|
||||
expect(s2DotSelected).not.toHaveClass("dot--steady");
|
||||
// A focused idle session is solid.
|
||||
expect(s2DotSelected).not.toHaveClass("dot--blink-fast");
|
||||
expect(s2DotSelected).not.toHaveClass("dot--blink-slow");
|
||||
|
||||
// 5. Selected busy row renders dot--busy + dot--current.
|
||||
// 5. Selected busy row renders dot--busy + dot--current and keeps blinking.
|
||||
rerender(treeElement({ sessions, selectedId: "s4" }));
|
||||
const s4DotSelected = rowMain("s4").querySelector(".dot");
|
||||
expect(s4DotSelected).toHaveClass("dot", "dot--busy", "dot--current");
|
||||
expect(s4DotSelected).not.toHaveClass("dot--steady");
|
||||
expect(s4DotSelected).toHaveClass("dot--blink-fast");
|
||||
|
||||
// 6. Selected child with error renders dot--err + dot--steady.
|
||||
// 6. Selected child with error renders steady dot--err: viewed red is
|
||||
// acknowledged, so it carries NO blink class while the unselected
|
||||
// sibling above does.
|
||||
rerender(treeElement({ sessions, selectedId: "c2" }));
|
||||
const c2DotSelected = rowMain("c2").querySelector(".dot");
|
||||
expect(c2DotSelected).toHaveClass("dot", "dot--err", "dot--steady");
|
||||
expect(c2DotSelected).toHaveClass("dot", "dot--err");
|
||||
expect(c2DotSelected).not.toHaveClass("dot--blink-fast");
|
||||
expect(c2DotSelected).not.toHaveClass("dot--blink-slow");
|
||||
expect(c2DotSelected).not.toHaveClass("dot--current");
|
||||
|
||||
// 7. The regression: a `done` row blinks in the list. The old CSS keyed
|
||||
// the green animation on `.tree-row .dot--ok`, so it only pulsed here
|
||||
// and stayed solid everywhere else; the class must now be explicit.
|
||||
const s3DotFinal = rowMain("s3").querySelector(".dot");
|
||||
expect(s3DotFinal).toHaveClass("dot", "dot--ok");
|
||||
expect(s3DotFinal).toHaveClass("dot--blink-fast");
|
||||
expect(s3DotFinal).not.toHaveClass("dot--blink-slow");
|
||||
|
||||
// 8. An attention row never blinks (nothing to acknowledge twice).
|
||||
const s1DotFinal = rowMain("s1").querySelector(".dot");
|
||||
expect(s1DotFinal).toHaveClass("dot", "dot--attention");
|
||||
expect(s1DotFinal).not.toHaveClass("dot--blink-fast");
|
||||
expect(s1DotFinal).not.toHaveClass("dot--blink-slow");
|
||||
});
|
||||
|
||||
it("draws child rows as a single line without a child-count badge", () => {
|
||||
@@ -703,6 +724,19 @@ describe("chat session deep link", () => {
|
||||
expect(requestedUrls(fetchMock)).toContainEqual(
|
||||
expect.stringContaining("/api/v1/sessions/s2/entries"),
|
||||
);
|
||||
|
||||
// "One session, one blink": the stream head renders the same `DotView`
|
||||
// as the selected tree row (`sessionDot(active, { viewed: true })`), so
|
||||
// the colour, the blink rate and the current marker must agree. The bug
|
||||
// was that the list blinked while the head did not (or vice versa).
|
||||
const blinkClasses = (el: Element | null | undefined) =>
|
||||
["dot--blink-fast", "dot--blink-slow"].filter((cls) => el?.classList.contains(cls));
|
||||
const headDot = streamPane().querySelector(".stream-title .dot");
|
||||
const selectedRowDot = rowMain("s2").querySelector(".dot");
|
||||
expect(headDot).not.toBeNull();
|
||||
expect(headDot).toHaveClass("dot", "dot--busy", "dot--current");
|
||||
expect(blinkClasses(headDot)).toEqual(["dot--blink-fast"]);
|
||||
expect(blinkClasses(headDot)).toEqual(blinkClasses(selectedRowDot));
|
||||
});
|
||||
|
||||
it("keeps the first-session fallback for the /chat index", async () => {
|
||||
@@ -718,6 +752,13 @@ describe("chat session deep link", () => {
|
||||
expect(await screen.findByText("Alpha first message")).toBeInTheDocument();
|
||||
expect(screen.queryByTestId("session-not-found")).toBeNull();
|
||||
expect(streamPane().querySelector(".stream-name")).toHaveTextContent("Alpha");
|
||||
|
||||
// The same rule for a solid dot: an idle session is steady in the head
|
||||
// and in the list — no wrapper may add or remove a blink.
|
||||
const headDot = streamPane().querySelector(".stream-title .dot");
|
||||
expect(headDot).toHaveClass("dot", "dot--idle", "dot--current");
|
||||
expect(headDot).not.toHaveClass("dot--blink-fast");
|
||||
expect(headDot?.className).toBe(rowMain("s1").querySelector(".dot")?.className);
|
||||
});
|
||||
|
||||
it("renders a deep-linked hidden sub-session and offers the way back to its parent", async () => {
|
||||
|
||||
@@ -66,17 +66,35 @@ describe("StatusDot", () => {
|
||||
expect(container.firstElementChild).toHaveClass("dot", expected);
|
||||
});
|
||||
|
||||
it("applies dot--steady modifier when steady is true", () => {
|
||||
const { container } = render(<StatusDot status="err" steady={true} />);
|
||||
expect(container.firstElementChild).toHaveClass("dot", "dot--err", "dot--steady");
|
||||
it("applies the fast blink class only when blink='fast'", () => {
|
||||
const { container } = render(<StatusDot status="err" blink="fast" />);
|
||||
expect(container.firstElementChild).toHaveClass("dot", "dot--err", "dot--blink-fast");
|
||||
expect(container.firstElementChild).not.toHaveClass("dot--blink-slow");
|
||||
});
|
||||
|
||||
it("does not apply dot--steady when steady is false or omitted", () => {
|
||||
const { container: c1 } = render(<StatusDot status="err" steady={false} />);
|
||||
expect(c1.firstElementChild).not.toHaveClass("dot--steady");
|
||||
it("applies the slow blink class only when blink='slow'", () => {
|
||||
const { container } = render(<StatusDot status="compacting" blink="slow" />);
|
||||
expect(container.firstElementChild).toHaveClass("dot", "dot--compacting", "dot--blink-slow");
|
||||
expect(container.firstElementChild).not.toHaveClass("dot--blink-fast");
|
||||
});
|
||||
|
||||
const { container: c2 } = render(<StatusDot status="err" />);
|
||||
expect(c2.firstElementChild).not.toHaveClass("dot--steady");
|
||||
it("carries neither blink class when blink is omitted or null", () => {
|
||||
const { container: c1 } = render(<StatusDot status="err" />);
|
||||
expect(c1.firstElementChild).not.toHaveClass("dot--blink-fast");
|
||||
expect(c1.firstElementChild).not.toHaveClass("dot--blink-slow");
|
||||
|
||||
const { container: c2 } = render(<StatusDot status="err" blink={null} />);
|
||||
expect(c2.firstElementChild).not.toHaveClass("dot--blink-fast");
|
||||
expect(c2.firstElementChild).not.toHaveClass("dot--blink-slow");
|
||||
});
|
||||
|
||||
it("never encodes the blink in the colour class (a solid err dot is still dot--err)", () => {
|
||||
// The old bug: the animation was keyed on the colour class + the wrapper.
|
||||
const solid = render(<StatusDot status="err" />);
|
||||
const blinking = render(<StatusDot status="err" blink="fast" />);
|
||||
expect(solid.container.firstElementChild).toHaveClass("dot--err");
|
||||
expect(blinking.container.firstElementChild).toHaveClass("dot--err");
|
||||
expect(solid.container.firstElementChild).not.toHaveClass("dot--blink-fast");
|
||||
});
|
||||
|
||||
it("applies dot--current modifier when current is true", () => {
|
||||
@@ -92,14 +110,25 @@ describe("StatusDot", () => {
|
||||
expect(c2.firstElementChild).not.toHaveClass("dot--current");
|
||||
});
|
||||
|
||||
it("supports steady and current modifiers together", () => {
|
||||
const { container } = render(<StatusDot status="busy" steady current />);
|
||||
expect(container.firstElementChild).toHaveClass("dot", "dot--busy", "dot--steady", "dot--current");
|
||||
it("composes blink, current and a custom className", () => {
|
||||
const { container } = render(<StatusDot status="busy" blink="fast" current className="custom-dot" />);
|
||||
expect(container.firstElementChild).toHaveClass(
|
||||
"dot",
|
||||
"dot--busy",
|
||||
"dot--blink-fast",
|
||||
"dot--current",
|
||||
"custom-dot",
|
||||
);
|
||||
});
|
||||
|
||||
it("preserves custom className alongside modifiers", () => {
|
||||
const { container } = render(<StatusDot status="idle" steady current className="custom-dot" />);
|
||||
expect(container.firstElementChild).toHaveClass("dot", "dot--idle", "dot--steady", "dot--current", "custom-dot");
|
||||
it("composes a slow blink with the current marker", () => {
|
||||
const { container } = render(<StatusDot status="compacting" blink="slow" current />);
|
||||
expect(container.firstElementChild).toHaveClass(
|
||||
"dot",
|
||||
"dot--compacting",
|
||||
"dot--blink-slow",
|
||||
"dot--current",
|
||||
);
|
||||
});
|
||||
|
||||
it("exposes the state label when a title is provided", () => {
|
||||
|
||||
@@ -0,0 +1,79 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import appCss from "@/styles/app.css?raw";
|
||||
|
||||
/**
|
||||
* The mobile half of the "the console never scales itself" contract.
|
||||
*
|
||||
* Two browser behaviours make a phone render the console at the wrong scale,
|
||||
* both without any help from our CSS:
|
||||
*
|
||||
* 1. Mobile Safari zooms the visual viewport in when a focused text control
|
||||
* renders below 16px, and it never zooms back out — the page stays scaled
|
||||
* for the whole session. Every control we ship is smaller than that by
|
||||
* design (`input/select/textarea` inherit `--fs-body` 14px, `.composer__ta`
|
||||
* is 15px), so `app.css` has to raise a floor.
|
||||
* 2. Text autosizing inflates type when the device rotates to landscape.
|
||||
*
|
||||
* jsdom does not evaluate media queries for `getComputedStyle`, so the sheet is
|
||||
* read as text (the `?raw` idiom `tokens.test.ts` established).
|
||||
*/
|
||||
|
||||
function stripComments(source: string): string {
|
||||
return source.replace(/\/\*[\s\S]*?\*\//g, "");
|
||||
}
|
||||
|
||||
/** Every `@media (…) { … }` block in a sheet, as `{ condition, body }`. */
|
||||
function mediaBlocks(source: string): { condition: string; body: string }[] {
|
||||
const text = stripComments(source);
|
||||
const blocks: { condition: string; body: string }[] = [];
|
||||
const head = /@media([^{]+)\{/g;
|
||||
let match: RegExpExecArray | null;
|
||||
while ((match = head.exec(text))) {
|
||||
const condition = match[1] ?? "";
|
||||
const open = match.index + match[0].length - 1;
|
||||
let depth = 0;
|
||||
for (let i = open; i < text.length; i += 1) {
|
||||
if (text[i] === "{") depth += 1;
|
||||
if (text[i] === "}") {
|
||||
depth -= 1;
|
||||
if (depth === 0) {
|
||||
blocks.push({ condition, body: text.slice(open + 1, i) });
|
||||
head.lastIndex = i;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return blocks;
|
||||
}
|
||||
|
||||
const compact = (source: string) => source.replace(/\s+/g, " ").trim();
|
||||
|
||||
describe("mobile form controls", () => {
|
||||
const blocks = mediaBlocks(appCss);
|
||||
|
||||
it("keeps text controls at 16px on touch devices, not only on narrow ones", () => {
|
||||
const guarded = blocks.filter((block) => /font-size:\s*16px\s*!important/.test(compact(block.body)));
|
||||
expect(guarded.length, "no 16px control floor in app.css").toBeGreaterThan(0);
|
||||
for (const block of guarded) {
|
||||
for (const control of ["input", "select", "textarea", '[contenteditable="true"]']) {
|
||||
expect(compact(block.body), `${block.condition} misses ${control}`).toContain(control);
|
||||
}
|
||||
// Phones in landscape are wider than 600px and still zoom.
|
||||
expect(block.condition, "the floor must key on `hover: none`").toContain("hover: none");
|
||||
}
|
||||
});
|
||||
|
||||
it("leaves the desktop cascade alone", () => {
|
||||
for (const block of blocks) {
|
||||
if (!/font-size:\s*16px\s*!important/.test(compact(block.body))) continue;
|
||||
expect(block.condition).toMatch(/hover: none|max-width/);
|
||||
}
|
||||
});
|
||||
|
||||
it("opts out of mobile text autosizing", () => {
|
||||
expect(compact(appCss)).toMatch(/-webkit-text-size-adjust:\s*100%/);
|
||||
expect(compact(appCss)).toMatch(/[^-]text-size-adjust:\s*100%/);
|
||||
});
|
||||
});
|
||||
@@ -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: () => <div>connect</div> },
|
||||
];
|
||||
}
|
||||
|
||||
/** 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);
|
||||
});
|
||||
});
|
||||
+182
-71
@@ -9,6 +9,23 @@ import {
|
||||
subagentDot,
|
||||
} from "@/features/chat/session-state";
|
||||
|
||||
/**
|
||||
* The dot contract, in one place.
|
||||
*
|
||||
* `DotView` is the *only* decision about whether a dot blinks and at which
|
||||
* rate: `blink: "fast"` → `.dot--blink-fast`, `blink: "slow"` →
|
||||
* `.dot--blink-slow`, omitted → solid. The renderer never infers the animation
|
||||
* from the colour class or from where the dot is mounted (`status-dot.tsx`,
|
||||
* `app.css`), so every row below asserts the *whole* view with `toEqual` —
|
||||
* an unexpected `blink` is a failure, and a stray `steady` key can never come
|
||||
* back unnoticed.
|
||||
*
|
||||
* Regression this pins: `done` (green) used to blink only inside `.tree-row`
|
||||
* because the animation was keyed on `html[data-pi-blink-fast="dim"]
|
||||
* .tree-row .dot--ok`, while `.dot--busy`/`.dot--err` blazed globally and
|
||||
* `dot--steady` could not stop `ok` at all.
|
||||
*/
|
||||
|
||||
type SessionOverrides = Omit<Partial<SessionState>, "flags"> & {
|
||||
flags?: Partial<SessionFlags>;
|
||||
};
|
||||
@@ -44,58 +61,81 @@ describe("sessionDot (parent rows)", () => {
|
||||
describe("base status matrix", () => {
|
||||
it.each([
|
||||
{
|
||||
name: "exited -> dead",
|
||||
name: "exited -> dead, solid (a dead process does not blink)",
|
||||
state: makeSession({ status: "exited" }),
|
||||
expected: { status: "dead" },
|
||||
},
|
||||
{
|
||||
name: "error -> err",
|
||||
name: "error -> err, blinking fast",
|
||||
state: makeSession({ flags: { error: true } }),
|
||||
expected: { status: "err" },
|
||||
expected: { status: "err", blink: "fast" },
|
||||
},
|
||||
{
|
||||
name: "attention flag -> attention",
|
||||
name: "attention flag -> attention, solid",
|
||||
state: makeSession({ flags: { attention: true } }),
|
||||
expected: { status: "attention" },
|
||||
},
|
||||
{
|
||||
name: "attention array non-empty -> attention",
|
||||
name: "attention array non-empty -> attention, solid",
|
||||
state: makeSession({ attention: [{ id: "q1" } as any] }),
|
||||
expected: { status: "attention" },
|
||||
},
|
||||
{
|
||||
name: "done -> ok",
|
||||
name: "done -> ok, blinking fast (the green that used to be tree-scoped)",
|
||||
state: makeSession({ flags: { done: true } }),
|
||||
expected: { status: "ok" },
|
||||
expected: { status: "ok", blink: "fast" },
|
||||
},
|
||||
{
|
||||
name: "busy -> busy",
|
||||
name: "busy -> busy, blinking fast",
|
||||
state: makeSession({ status: "busy" }),
|
||||
expected: { status: "busy" },
|
||||
expected: { status: "busy", blink: "fast" },
|
||||
},
|
||||
{
|
||||
name: "compacting -> compacting",
|
||||
name: "compacting -> compacting, blinking slow",
|
||||
state: makeSession({ status: "compacting" }),
|
||||
expected: { status: "compacting" },
|
||||
expected: { status: "compacting", blink: "slow" },
|
||||
},
|
||||
{
|
||||
name: "interrupted -> dead",
|
||||
name: "interrupted -> dead, solid",
|
||||
state: makeSession({ status: "interrupted" }),
|
||||
expected: { status: "dead" },
|
||||
},
|
||||
{
|
||||
name: "starting -> idle",
|
||||
name: "starting -> idle, solid",
|
||||
state: makeSession({ status: "starting" }),
|
||||
expected: { status: "idle" },
|
||||
},
|
||||
{
|
||||
name: "idle -> idle",
|
||||
name: "idle -> idle, solid",
|
||||
state: makeSession({ status: "idle" }),
|
||||
expected: { status: "idle" },
|
||||
},
|
||||
])("$name", ({ state, expected }) => {
|
||||
expect(sessionDot(state)).toEqual(expected);
|
||||
});
|
||||
|
||||
it("compacting blinks at the slow rate, never at the busy rate, unviewed", () => {
|
||||
expect(sessionDot(makeSession({ status: "compacting" }))).toEqual({
|
||||
status: "compacting",
|
||||
blink: "slow",
|
||||
});
|
||||
expect(sessionDot(makeSession({ status: "compacting" })).blink).not.toBe("fast");
|
||||
});
|
||||
|
||||
it("exited and interrupted never blink (no acknowledgement path needed)", () => {
|
||||
expect(sessionDot(makeSession({ status: "exited" }))).toEqual({ status: "dead" });
|
||||
expect(sessionDot(makeSession({ status: "interrupted" }))).toEqual({ status: "dead" });
|
||||
for (const status of ["exited", "interrupted"] as const) {
|
||||
expect(sessionDot(makeSession({ status }))).not.toHaveProperty("blink");
|
||||
}
|
||||
});
|
||||
|
||||
it("attention never blinks, from the flag or the request array", () => {
|
||||
expect(sessionDot(makeSession({ flags: { attention: true } }))).toEqual({ status: "attention" });
|
||||
expect(sessionDot(makeSession({ attention: [{ id: "q1" } as any] }))).toEqual({
|
||||
status: "attention",
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("priority collisions (bug fixes: exited > error > attention > done > busy)", () => {
|
||||
@@ -103,7 +143,7 @@ describe("sessionDot (parent rows)", () => {
|
||||
const state = makeSession({
|
||||
flags: { error: true, attention: true },
|
||||
});
|
||||
expect(sessionDot(state)).toEqual({ status: "err" });
|
||||
expect(sessionDot(state)).toEqual({ status: "err", blink: "fast" });
|
||||
});
|
||||
|
||||
it("error beats attention (flags.error outranks populated attention array)", () => {
|
||||
@@ -111,7 +151,7 @@ describe("sessionDot (parent rows)", () => {
|
||||
flags: { error: true },
|
||||
attention: [{ id: "q1" } as any],
|
||||
});
|
||||
expect(sessionDot(state)).toEqual({ status: "err" });
|
||||
expect(sessionDot(state)).toEqual({ status: "err", blink: "fast" });
|
||||
});
|
||||
|
||||
it("exited beats error (status: exited outranks flags.error)", () => {
|
||||
@@ -125,9 +165,15 @@ describe("sessionDot (parent rows)", () => {
|
||||
it("interrupted is a dead process too (outranks error, attention and done)", () => {
|
||||
// The plugin has no `interrupted`: any "not running" row is `exited`
|
||||
// (sessions.lua:75-78), and `exited` sits at the top of dot_hl.
|
||||
expect(sessionDot(makeSession({ status: "interrupted", flags: { error: true } })).status).toBe("dead");
|
||||
expect(sessionDot(makeSession({ status: "interrupted", flags: { attention: true } })).status).toBe("dead");
|
||||
expect(sessionDot(makeSession({ status: "interrupted", flags: { done: true } })).status).toBe("dead");
|
||||
expect(sessionDot(makeSession({ status: "interrupted", flags: { error: true } }))).toEqual({
|
||||
status: "dead",
|
||||
});
|
||||
expect(sessionDot(makeSession({ status: "interrupted", flags: { attention: true } }))).toEqual({
|
||||
status: "dead",
|
||||
});
|
||||
expect(sessionDot(makeSession({ status: "interrupted", flags: { done: true } }))).toEqual({
|
||||
status: "dead",
|
||||
});
|
||||
// …and it never wears the blue current marker either.
|
||||
expect(sessionDot(makeSession({ status: "interrupted" }), { viewed: true })).toEqual({ status: "dead" });
|
||||
});
|
||||
@@ -152,7 +198,7 @@ describe("sessionDot (parent rows)", () => {
|
||||
status: "busy",
|
||||
flags: { done: true },
|
||||
});
|
||||
expect(sessionDot(state)).toEqual({ status: "ok" });
|
||||
expect(sessionDot(state)).toEqual({ status: "ok", blink: "fast" });
|
||||
});
|
||||
|
||||
it("exited beats attention (status: exited outranks flags.attention and attention array)", () => {
|
||||
@@ -168,7 +214,7 @@ describe("sessionDot (parent rows)", () => {
|
||||
const state = makeSession({
|
||||
flags: { error: true, done: true },
|
||||
});
|
||||
expect(sessionDot(state)).toEqual({ status: "err" });
|
||||
expect(sessionDot(state)).toEqual({ status: "err", blink: "fast" });
|
||||
});
|
||||
|
||||
it("attention beats busy (flags.attention outranks status: busy)", () => {
|
||||
@@ -178,38 +224,53 @@ describe("sessionDot (parent rows)", () => {
|
||||
});
|
||||
expect(sessionDot(state)).toEqual({ status: "attention" });
|
||||
});
|
||||
|
||||
it("a busy session keeps the fast rate (compacting never downgrades it)", () => {
|
||||
const state = makeSession({ status: "busy" });
|
||||
expect(sessionDot(state)).toEqual({ status: "busy", blink: "fast" });
|
||||
});
|
||||
});
|
||||
|
||||
describe("viewed overlay (you are here)", () => {
|
||||
it.each([
|
||||
{
|
||||
name: "idle -> current",
|
||||
name: "idle -> current, solid",
|
||||
state: makeSession({ status: "idle" }),
|
||||
expected: { status: "idle", current: true },
|
||||
},
|
||||
{
|
||||
name: "busy -> current (busy)",
|
||||
name: "busy -> current (busy), blinking fast",
|
||||
state: makeSession({ status: "busy" }),
|
||||
expected: { status: "busy", current: true },
|
||||
expected: { status: "busy", blink: "fast", current: true },
|
||||
},
|
||||
{
|
||||
name: "compacting -> current with status flipped to busy",
|
||||
name: "compacting -> current with status flipped to busy, blinking fast (not slow)",
|
||||
state: makeSession({ status: "compacting" }),
|
||||
expected: { status: "busy", current: true },
|
||||
expected: { status: "busy", blink: "fast", current: true },
|
||||
},
|
||||
])("$name", ({ state, expected }) => {
|
||||
expect(sessionDot(state, { viewed: true })).toEqual(expected);
|
||||
});
|
||||
|
||||
it("focused compacting blinks at the busy rate under the marker", () => {
|
||||
const viewed = sessionDot(makeSession({ status: "compacting" }), { viewed: true });
|
||||
expect(viewed).toEqual({ status: "busy", blink: "fast", current: true });
|
||||
// The unfocused row keeps the slow rate: the rate follows the view.
|
||||
expect(sessionDot(makeSession({ status: "compacting" }))).toEqual({
|
||||
status: "compacting",
|
||||
blink: "slow",
|
||||
});
|
||||
});
|
||||
|
||||
describe("no overlay when notification flags are set", () => {
|
||||
it("suppresses current overlay when error is set", () => {
|
||||
it("suppresses current overlay when error is set, but keeps the fast blink", () => {
|
||||
const state = makeSession({ status: "idle", flags: { error: true } });
|
||||
expect(sessionDot(state, { viewed: true })).toEqual({ status: "err" });
|
||||
expect(sessionDot(state, { viewed: true })).toEqual({ status: "err", blink: "fast" });
|
||||
});
|
||||
|
||||
it("suppresses current overlay when done is set", () => {
|
||||
it("suppresses current overlay when done is set, but keeps the fast blink", () => {
|
||||
const state = makeSession({ status: "idle", flags: { done: true } });
|
||||
expect(sessionDot(state, { viewed: true })).toEqual({ status: "ok" });
|
||||
expect(sessionDot(state, { viewed: true })).toEqual({ status: "ok", blink: "fast" });
|
||||
});
|
||||
|
||||
it("suppresses current overlay when flags.attention is set", () => {
|
||||
@@ -243,12 +304,12 @@ describe("sessionDot (parent rows)", () => {
|
||||
|
||||
it("does not apply current when viewed: false on busy", () => {
|
||||
const state = makeSession({ status: "busy" });
|
||||
expect(sessionDot(state, { viewed: false })).toEqual({ status: "busy" });
|
||||
expect(sessionDot(state, { viewed: false })).toEqual({ status: "busy", blink: "fast" });
|
||||
});
|
||||
|
||||
it("does not apply current or flip status when viewed: false on compacting", () => {
|
||||
const state = makeSession({ status: "compacting" });
|
||||
expect(sessionDot(state, { viewed: false })).toEqual({ status: "compacting" });
|
||||
expect(sessionDot(state, { viewed: false })).toEqual({ status: "compacting", blink: "slow" });
|
||||
});
|
||||
|
||||
it("does not apply current when opts is omitted", () => {
|
||||
@@ -257,55 +318,92 @@ describe("sessionDot (parent rows)", () => {
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("the view is the only animation decision (no `steady`, no colour-keyed blink)", () => {
|
||||
const samples: SessionState[] = [
|
||||
makeSession({ status: "idle" }),
|
||||
makeSession({ status: "busy" }),
|
||||
makeSession({ status: "compacting" }),
|
||||
makeSession({ status: "exited" }),
|
||||
makeSession({ status: "interrupted" }),
|
||||
makeSession({ status: "starting" }),
|
||||
makeSession({ flags: { error: true } }),
|
||||
makeSession({ flags: { done: true } }),
|
||||
makeSession({ flags: { attention: true } }),
|
||||
];
|
||||
|
||||
it.each(samples.map((state) => [state.status, state] as const))(
|
||||
"renders only status/blink/current keys for a %s session",
|
||||
(_status, state) => {
|
||||
for (const viewed of [false, true]) {
|
||||
const view = sessionDot(state, { viewed });
|
||||
const unexpected = Object.keys(view).filter(
|
||||
(key) => !["status", "blink", "current"].includes(key),
|
||||
);
|
||||
expect(unexpected, `unexpected DotView keys on ${state.status}`).toEqual([]);
|
||||
expect(view).not.toHaveProperty("steady");
|
||||
if (view.blink !== undefined) expect(["fast", "slow"]).toContain(view.blink);
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
it("a dot without a blink is solid", () => {
|
||||
expect(sessionDot(makeSession({ status: "idle" })).blink).toBeUndefined();
|
||||
expect(sessionDot(makeSession({ status: "starting" })).blink).toBeUndefined();
|
||||
expect(sessionDot(makeSession({ flags: { attention: true } })).blink).toBeUndefined();
|
||||
expect(sessionDot(makeSession({ status: "exited" })).blink).toBeUndefined();
|
||||
expect(sessionDot(makeSession({ status: "interrupted" })).blink).toBeUndefined();
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("childSessionDot (sub-session / tree depth > 0)", () => {
|
||||
describe("base status matrix", () => {
|
||||
it.each([
|
||||
{
|
||||
name: "exited -> exited (hollow ring)",
|
||||
name: "exited -> exited (hollow ring), solid",
|
||||
state: makeChild({ status: "exited" }),
|
||||
opts: undefined,
|
||||
expected: { status: "exited" },
|
||||
},
|
||||
{
|
||||
name: "interrupted -> dead",
|
||||
name: "interrupted -> dead, solid",
|
||||
state: makeChild({ status: "interrupted" }),
|
||||
opts: undefined,
|
||||
expected: { status: "dead" },
|
||||
},
|
||||
{
|
||||
name: "error with viewed -> { status: 'err', steady: true }",
|
||||
name: "error with viewed -> err, solid (acknowledged red)",
|
||||
state: makeChild({ flags: { error: true } }),
|
||||
opts: { viewed: true },
|
||||
expected: { status: "err", steady: true },
|
||||
expected: { status: "err" },
|
||||
},
|
||||
{
|
||||
name: "error without viewed (viewed: false) -> { status: 'err', steady: false } (blinking)",
|
||||
name: "error with viewed: false -> err, blinking fast",
|
||||
state: makeChild({ flags: { error: true } }),
|
||||
opts: { viewed: false },
|
||||
expected: { status: "err", steady: false },
|
||||
expected: { status: "err", blink: "fast" },
|
||||
},
|
||||
{
|
||||
name: "error without viewed (opts omitted) -> { status: 'err', steady: false } (blinking)",
|
||||
name: "error with opts omitted -> err, blinking fast",
|
||||
state: makeChild({ flags: { error: true } }),
|
||||
opts: undefined,
|
||||
expected: { status: "err", steady: false },
|
||||
expected: { status: "err", blink: "fast" },
|
||||
},
|
||||
{
|
||||
name: "busy -> busy",
|
||||
name: "busy -> busy, blinking fast",
|
||||
state: makeChild({ status: "busy" }),
|
||||
opts: undefined,
|
||||
expected: { status: "busy" },
|
||||
expected: { status: "busy", blink: "fast" },
|
||||
},
|
||||
{
|
||||
name: "compacting -> busy (NOT compacting)",
|
||||
name: "compacting -> busy (NOT compacting), blinking fast",
|
||||
state: makeChild({ status: "compacting" }),
|
||||
opts: undefined,
|
||||
expected: { status: "busy" },
|
||||
expected: { status: "busy", blink: "fast" },
|
||||
},
|
||||
{
|
||||
name: "idle -> idle",
|
||||
name: "idle -> idle, solid",
|
||||
state: makeChild({ status: "idle" }),
|
||||
opts: undefined,
|
||||
expected: { status: "idle" },
|
||||
@@ -313,28 +411,30 @@ describe("childSessionDot (sub-session / tree depth > 0)", () => {
|
||||
])("$name", ({ state, opts, expected }) => {
|
||||
expect(childSessionDot(state, opts)).toEqual(expected);
|
||||
});
|
||||
|
||||
it("a viewed failed child is steady red while the unviewed one blinks", () => {
|
||||
const viewed = childSessionDot(makeChild({ flags: { error: true } }), { viewed: true });
|
||||
const unviewed = childSessionDot(makeChild({ flags: { error: true } }));
|
||||
expect(viewed).toEqual({ status: "err" });
|
||||
expect(unviewed).toEqual({ status: "err", blink: "fast" });
|
||||
expect(viewed).not.toHaveProperty("blink");
|
||||
});
|
||||
});
|
||||
|
||||
describe("child never returns ok or attention", () => {
|
||||
it("returns idle instead of ok when flags.done is set on idle child", () => {
|
||||
const state = makeChild({ status: "idle", flags: { done: true } });
|
||||
const dot = childSessionDot(state);
|
||||
expect(dot.status).not.toBe("ok");
|
||||
expect(dot.status).toBe("idle");
|
||||
expect(childSessionDot(state)).toEqual({ status: "idle" });
|
||||
});
|
||||
|
||||
it("returns busy instead of ok when flags.done is set on busy child", () => {
|
||||
const state = makeChild({ status: "busy", flags: { done: true } });
|
||||
const dot = childSessionDot(state);
|
||||
expect(dot.status).not.toBe("ok");
|
||||
expect(dot.status).toBe("busy");
|
||||
expect(childSessionDot(state)).toEqual({ status: "busy", blink: "fast" });
|
||||
});
|
||||
|
||||
it("returns idle instead of attention when flags.attention is set on idle child", () => {
|
||||
const state = makeChild({ status: "idle", flags: { attention: true } });
|
||||
const dot = childSessionDot(state);
|
||||
expect(dot.status).not.toBe("attention");
|
||||
expect(dot.status).toBe("idle");
|
||||
expect(childSessionDot(state)).toEqual({ status: "idle" });
|
||||
});
|
||||
|
||||
it("returns idle instead of attention when attention array is populated on idle child", () => {
|
||||
@@ -342,9 +442,7 @@ describe("childSessionDot (sub-session / tree depth > 0)", () => {
|
||||
status: "idle",
|
||||
attention: [{ id: "q1" } as any],
|
||||
});
|
||||
const dot = childSessionDot(state);
|
||||
expect(dot.status).not.toBe("attention");
|
||||
expect(dot.status).toBe("idle");
|
||||
expect(childSessionDot(state)).toEqual({ status: "idle" });
|
||||
});
|
||||
|
||||
it("returns busy instead of attention when flags.attention is set on busy child", () => {
|
||||
@@ -353,9 +451,7 @@ describe("childSessionDot (sub-session / tree depth > 0)", () => {
|
||||
flags: { attention: true },
|
||||
attention: [{ id: "q1" } as any],
|
||||
});
|
||||
const dot = childSessionDot(state);
|
||||
expect(dot.status).not.toBe("attention");
|
||||
expect(dot.status).toBe("busy");
|
||||
expect(childSessionDot(state)).toEqual({ status: "busy", blink: "fast" });
|
||||
});
|
||||
|
||||
it("does not return ok or current when flags.done is set with viewed: true", () => {
|
||||
@@ -370,7 +466,7 @@ describe("childSessionDot (sub-session / tree depth > 0)", () => {
|
||||
});
|
||||
|
||||
describe("viewed overlay on child rows", () => {
|
||||
it("applies current overlay to idle child when viewed", () => {
|
||||
it("applies current overlay to idle child when viewed (still solid)", () => {
|
||||
const state = makeChild({ status: "idle" });
|
||||
expect(childSessionDot(state, { viewed: true })).toEqual({
|
||||
status: "idle",
|
||||
@@ -382,6 +478,7 @@ describe("childSessionDot (sub-session / tree depth > 0)", () => {
|
||||
const state = makeChild({ status: "busy" });
|
||||
expect(childSessionDot(state, { viewed: true })).toEqual({
|
||||
status: "busy",
|
||||
blink: "fast",
|
||||
current: true,
|
||||
});
|
||||
});
|
||||
@@ -390,6 +487,7 @@ describe("childSessionDot (sub-session / tree depth > 0)", () => {
|
||||
const state = makeChild({ status: "compacting" });
|
||||
expect(childSessionDot(state, { viewed: true })).toEqual({
|
||||
status: "busy",
|
||||
blink: "fast",
|
||||
current: true,
|
||||
});
|
||||
});
|
||||
@@ -407,25 +505,32 @@ describe("childSessionDot (sub-session / tree depth > 0)", () => {
|
||||
status: "dead",
|
||||
});
|
||||
});
|
||||
|
||||
it("does not apply current overlay to a failed child, and the error stays solid", () => {
|
||||
const state = makeChild({ flags: { error: true } });
|
||||
expect(childSessionDot(state, { viewed: true })).toEqual({ status: "err" });
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("subagentDot (manifest-only subagent tree rows)", () => {
|
||||
it.each([
|
||||
{
|
||||
name: "active -> busy",
|
||||
// A manifest-only entry has no live child (a live one renders as its
|
||||
// own session row), and nvim blinks only a live busy child: amber, solid.
|
||||
name: "active -> busy, solid",
|
||||
subagent: makeSubagent({ status: "active" }),
|
||||
opts: undefined,
|
||||
expected: { status: "busy" },
|
||||
},
|
||||
{
|
||||
name: "completed -> exited",
|
||||
name: "completed -> exited, solid",
|
||||
subagent: makeSubagent({ status: "completed" }),
|
||||
opts: undefined,
|
||||
expected: { status: "exited" },
|
||||
},
|
||||
{
|
||||
name: "dormant -> exited",
|
||||
name: "dormant -> exited, solid",
|
||||
subagent: makeSubagent({ status: "dormant" }),
|
||||
opts: undefined,
|
||||
expected: { status: "exited" },
|
||||
@@ -434,28 +539,28 @@ describe("subagentDot (manifest-only subagent tree rows)", () => {
|
||||
name: "failed with viewed -> steady err",
|
||||
subagent: makeSubagent({ status: "failed" }),
|
||||
opts: { viewed: true },
|
||||
expected: { status: "err", steady: true },
|
||||
expected: { status: "err" },
|
||||
},
|
||||
{
|
||||
name: "failed without viewed (viewed: false) -> blinking err",
|
||||
name: "failed with viewed: false -> blinking err",
|
||||
subagent: makeSubagent({ status: "failed" }),
|
||||
opts: { viewed: false },
|
||||
expected: { status: "err", steady: false },
|
||||
expected: { status: "err", blink: "fast" },
|
||||
},
|
||||
{
|
||||
name: "failed without viewed (opts omitted) -> blinking err",
|
||||
name: "failed with opts omitted -> blinking err",
|
||||
subagent: makeSubagent({ status: "failed" }),
|
||||
opts: undefined,
|
||||
expected: { status: "err", steady: false },
|
||||
expected: { status: "err", blink: "fast" },
|
||||
},
|
||||
{
|
||||
name: "interrupted -> dead",
|
||||
name: "interrupted -> dead, solid",
|
||||
subagent: makeSubagent({ status: "interrupted" }),
|
||||
opts: undefined,
|
||||
expected: { status: "dead" },
|
||||
},
|
||||
{
|
||||
name: "unknown status -> idle",
|
||||
name: "unknown status -> idle, solid",
|
||||
subagent: makeSubagent({ status: "unknown" as any }),
|
||||
opts: undefined,
|
||||
expected: { status: "idle" },
|
||||
@@ -463,6 +568,12 @@ describe("subagentDot (manifest-only subagent tree rows)", () => {
|
||||
])("$name", ({ subagent, opts, expected }) => {
|
||||
expect(subagentDot(subagent, opts)).toEqual(expected);
|
||||
});
|
||||
|
||||
it("a failed subagent stops blinking once it is the viewed child view", () => {
|
||||
const failed = makeSubagent({ status: "failed" });
|
||||
expect(subagentDot(failed, { viewed: true })).toEqual({ status: "err" });
|
||||
expect(subagentDot(failed)).toEqual({ status: "err", blink: "fast" });
|
||||
});
|
||||
});
|
||||
|
||||
describe("sessionStatusKey (stays distinct from dot)", () => {
|
||||
|
||||
@@ -0,0 +1,275 @@
|
||||
import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it } from "vitest";
|
||||
|
||||
import appCss from "@/styles/app.css?raw";
|
||||
import chatCss from "@/styles/pages/chat.css?raw";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
/**
|
||||
* The CSS half of the blink contract.
|
||||
*
|
||||
* `session-dot.test.ts` pins *which* dots ask to blink (`DotView.blink`);
|
||||
* this file pins that the stylesheet honours exactly that request and nothing
|
||||
* else. The bug it guards: the animation used to be keyed on the colour class
|
||||
* *and* on the component wrapper —
|
||||
*
|
||||
* html[data-pi-blink-fast="dim"] .tree-row .dot--ok { opacity: .35; }
|
||||
* .dot--busy { animation: … } /* global, unacknowledgeable *\/
|
||||
*
|
||||
* — so green blinked only in the session list, busy/err blazed everywhere, and
|
||||
* a dot could not opt out. The fix keeps exactly two dim rules, keyed on the
|
||||
* blink class alone.
|
||||
*
|
||||
* jsdom 30 runs a real specificity/attribute-selector cascade for
|
||||
* `getComputedStyle` against injected `<style>` sheets, so these assertions are
|
||||
* browser truth rather than a text grep. (The `@import`s are stripped because
|
||||
* jsdom cannot resolve them against `about:blank`; the imported token sheet
|
||||
* only supplies colours, never opacity.)
|
||||
*/
|
||||
|
||||
/** `@import "tailwindcss";` / `@import "./tokens.css";` — jsdom cannot fetch them. */
|
||||
function stripImports(source: string): string {
|
||||
return source.replace(/^[ \t]*@import[^;\n]*;[ \t]*$/gm, "");
|
||||
}
|
||||
|
||||
/** Whitespace-insensitive view of a sheet, for "the rule still says X" checks. */
|
||||
function compact(source: string): string {
|
||||
return source
|
||||
.replace(/\/\*[\s\S]*?\*\//g, "")
|
||||
.replace(/\s+/g, " ")
|
||||
.trim();
|
||||
}
|
||||
|
||||
function escapeRe(literal: string): string {
|
||||
return literal.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
||||
}
|
||||
|
||||
const DIM_FAST = 'html[data-pi-blink-fast="dim"]';
|
||||
const DIM_SLOW = 'html[data-pi-blink-slow="dim"]';
|
||||
|
||||
/** The two (and only two) dim selectors, exactly as they must read in `app.css`. */
|
||||
const BLINK_SELECTORS = `${DIM_FAST} .dot--blink-fast, ${DIM_SLOW} .dot--blink-slow`;
|
||||
|
||||
let style: HTMLStyleElement;
|
||||
let host: HTMLElement;
|
||||
|
||||
beforeAll(() => {
|
||||
style = document.createElement("style");
|
||||
style.textContent = `${stripImports(appCss)}\n${stripImports(chatCss)}`;
|
||||
document.head.appendChild(style);
|
||||
});
|
||||
|
||||
afterAll(() => {
|
||||
style.remove();
|
||||
});
|
||||
|
||||
beforeEach(() => {
|
||||
// Phase attributes are global state on the shared jsdom document; `blink.test.ts`
|
||||
// asserts on them and the suite runs with `isolate: false`, so start clean.
|
||||
clearPhases();
|
||||
host = document.createElement("div");
|
||||
host.className = "blink-css-host";
|
||||
document.body.appendChild(host);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
clearPhases();
|
||||
host.remove();
|
||||
});
|
||||
|
||||
function clearPhases(): void {
|
||||
document.documentElement.removeAttribute("data-pi-blink-fast");
|
||||
document.documentElement.removeAttribute("data-pi-blink-slow");
|
||||
}
|
||||
|
||||
function setPhase({ fast, slow }: { fast?: "on" | "dim"; slow?: "on" | "dim" } = {}): void {
|
||||
clearPhases();
|
||||
if (fast) document.documentElement.setAttribute("data-pi-blink-fast", fast);
|
||||
if (slow) document.documentElement.setAttribute("data-pi-blink-slow", slow);
|
||||
}
|
||||
|
||||
/**
|
||||
* Mount a dot the way `StatusDot` renders one (`cn("dot", DOT_CLASS[status],
|
||||
* BLINK_CLASS[blink])`), optionally inside `.tree-row` — the wrapper the old
|
||||
* rule scoped on.
|
||||
*/
|
||||
function mountDot(classes: string[], { inTreeRow = false }: { inTreeRow?: boolean } = {}): HTMLElement {
|
||||
const dot = document.createElement("span");
|
||||
dot.className = cn("dot", ...classes);
|
||||
if (inTreeRow) {
|
||||
const row = document.createElement("div");
|
||||
row.className = "tree-row";
|
||||
row.appendChild(dot);
|
||||
host.appendChild(row);
|
||||
} else {
|
||||
host.appendChild(dot);
|
||||
}
|
||||
return dot;
|
||||
}
|
||||
|
||||
/** Computed opacity, or `NaN` when the sheet never applies one. */
|
||||
function opacityOf(el: HTMLElement): number {
|
||||
return Number.parseFloat(getComputedStyle(el).opacity);
|
||||
}
|
||||
|
||||
const DIM = 0.35;
|
||||
const SOLID = 1;
|
||||
|
||||
describe("blink CSS: the stylesheet defines exactly one dim contract", () => {
|
||||
/** The single `data-pi-blink-*` rule, split into selector list and body. */
|
||||
function blinkRule() {
|
||||
const css = compact(appCss);
|
||||
const start = css.indexOf(DIM_FAST);
|
||||
expect(start, "missing the dim rule").toBeGreaterThanOrEqual(0);
|
||||
const open = css.indexOf("{", start);
|
||||
const close = css.indexOf("}", open);
|
||||
return {
|
||||
css,
|
||||
selectors: css.slice(start, open).trim(),
|
||||
body: css.slice(open + 1, close).trim(),
|
||||
};
|
||||
}
|
||||
|
||||
it("keeps the two blink rules verbatim in app.css (no silent rename)", () => {
|
||||
const { selectors, body } = blinkRule();
|
||||
expect(selectors).toBe(BLINK_SELECTORS);
|
||||
expect(body.replace(/\s+/g, "")).toBe("opacity:.35;");
|
||||
});
|
||||
|
||||
it("keys both dim rules on the blink class alone (no colour class, no wrapper)", () => {
|
||||
const { css, selectors } = blinkRule();
|
||||
// Exactly one rule mentions either clock attribute…
|
||||
expect(css.match(/data-pi-blink-fast="dim"/g)).toHaveLength(1);
|
||||
expect(css.match(/data-pi-blink-slow="dim"/g)).toHaveLength(1);
|
||||
// …and the blink classes exist nowhere else (a second, scoped rule would
|
||||
// show up as a third occurrence).
|
||||
expect(css.match(/\.dot--blink-(?:fast|slow)/g)).toHaveLength(2);
|
||||
expect(selectors).not.toMatch(/tree-row|session-list|\.dot--(?:ok|busy|err|attention|idle|compacting|dead|exited)/);
|
||||
});
|
||||
|
||||
it("leaves chat.css free of any dim rule (page CSS must not re-scope the blink)", () => {
|
||||
const css = compact(chatCss);
|
||||
expect(css).not.toContain("data-pi-blink");
|
||||
expect(css).not.toMatch(/\.dot--blink-(?:fast|slow)/);
|
||||
});
|
||||
|
||||
it("paints the current marker wherever the dot is mounted", () => {
|
||||
// The head dot and its list row must agree on the blue marker too, so
|
||||
// `.dot--current` may not be scoped to a wrapper either (jsdom cannot
|
||||
// resolve `var(--info)`, so this half has to read the sheet).
|
||||
expect(compact(appCss)).toMatch(/(?:^|[},\s])\.dot--current\s*\{[^}]*background:\s*var\(--info\)/);
|
||||
expect(compact(chatCss)).not.toMatch(/\.tree-row\s+\.dot--current/);
|
||||
});
|
||||
|
||||
it("no colour class owns an animation or an opacity any more", () => {
|
||||
const css = compact(appCss);
|
||||
// `@keyframes pulse` may stay for unrelated chrome, but a `.dot--*`
|
||||
// colour class may not animate or fade itself again.
|
||||
for (const selector of [".dot--busy", ".dot--ok", ".dot--err", ".dot--attention", ".dot--compacting"]) {
|
||||
const rule = new RegExp(`${escapeRe(selector)}\\s*\\{([^}]*)\\}`).exec(css);
|
||||
if (!rule) continue;
|
||||
expect(rule[1], selector).not.toMatch(/animation:|opacity:/);
|
||||
}
|
||||
expect(css).not.toMatch(/\.tree-row[^{,]*\.dot--(?:ok|busy|err)[^{]*\{[^}]*(?:opacity|animation)/);
|
||||
});
|
||||
});
|
||||
|
||||
describe("blink CSS: nothing blinks without a phase attribute", () => {
|
||||
it.each([
|
||||
["dot--blink-fast"],
|
||||
["dot--blink-slow"],
|
||||
["dot--ok", "dot--blink-fast"],
|
||||
["dot--compacting", "dot--blink-slow"],
|
||||
["dot--busy"],
|
||||
["dot--ok"],
|
||||
])("%s is solid", (...classes) => {
|
||||
setPhase();
|
||||
expect(opacityOf(mountDot(classes))).toBe(SOLID);
|
||||
expect(opacityOf(mountDot(classes, { inTreeRow: true }))).toBe(SOLID);
|
||||
});
|
||||
});
|
||||
|
||||
describe("blink CSS: data-pi-blink-fast='dim'", () => {
|
||||
it("dims .dot--blink-fast identically inside and outside .tree-row", () => {
|
||||
setPhase({ fast: "dim" });
|
||||
// The original bug in one line: the wrapper used to change the answer.
|
||||
const outside = opacityOf(mountDot(["dot--ok", "dot--blink-fast"]));
|
||||
const inside = opacityOf(mountDot(["dot--ok", "dot--blink-fast"], { inTreeRow: true }));
|
||||
expect(outside).toBe(DIM);
|
||||
expect(inside).toBe(DIM);
|
||||
});
|
||||
|
||||
it("dims every real fast-blink combination (ok / busy / err)", () => {
|
||||
setPhase({ fast: "dim" });
|
||||
for (const colour of ["dot--ok", "dot--busy", "dot--err"]) {
|
||||
expect(opacityOf(mountDot([colour, "dot--blink-fast"])), colour).toBe(DIM);
|
||||
expect(opacityOf(mountDot([colour, "dot--blink-fast"], { inTreeRow: true })), colour).toBe(DIM);
|
||||
}
|
||||
});
|
||||
|
||||
it("leaves .dot--blink-slow, and colour-only .dot--idle/.dot--ok/.dot--attention solid", () => {
|
||||
setPhase({ fast: "dim" });
|
||||
expect(opacityOf(mountDot(["dot--ok", "dot--blink-slow"]))).toBe(SOLID);
|
||||
expect(opacityOf(mountDot(["dot--compacting", "dot--blink-slow"]))).toBe(SOLID);
|
||||
for (const colour of ["dot--idle", "dot--ok", "dot--attention", "dot--compacting", "dot--exited", "dot--dead"]) {
|
||||
expect(opacityOf(mountDot([colour])), colour).toBe(SOLID);
|
||||
expect(opacityOf(mountDot([colour], { inTreeRow: true })), `${colour} in tree-row`).toBe(SOLID);
|
||||
}
|
||||
});
|
||||
|
||||
it("does not dim a dot that also carries dot--blink-slow at the fast-phase step", () => {
|
||||
// A dot only ever carries one rate (`DotView.blink` is a single value);
|
||||
// if both were present the fast clock would still win, which is why the
|
||||
// matrix must not emit both.
|
||||
setPhase({ fast: "dim", slow: "on" });
|
||||
expect(opacityOf(mountDot(["dot--busy", "dot--blink-fast", "dot--blink-slow"]))).toBe(DIM);
|
||||
});
|
||||
});
|
||||
|
||||
describe("blink CSS: data-pi-blink-slow='dim'", () => {
|
||||
it("dims .dot--blink-slow identically inside and outside .tree-row", () => {
|
||||
setPhase({ slow: "dim" });
|
||||
expect(opacityOf(mountDot(["dot--compacting", "dot--blink-slow"]))).toBe(DIM);
|
||||
expect(opacityOf(mountDot(["dot--compacting", "dot--blink-slow"], { inTreeRow: true }))).toBe(DIM);
|
||||
});
|
||||
|
||||
it("leaves every fast-blink and colour-only dot solid", () => {
|
||||
setPhase({ slow: "dim" });
|
||||
for (const classes of [
|
||||
["dot--ok", "dot--blink-fast"],
|
||||
["dot--busy", "dot--blink-fast"],
|
||||
["dot--err", "dot--blink-fast"],
|
||||
["dot--idle"],
|
||||
["dot--ok"],
|
||||
["dot--attention"],
|
||||
]) {
|
||||
expect(opacityOf(mountDot(classes)), classes.join(" ")).toBe(SOLID);
|
||||
expect(opacityOf(mountDot(classes, { inTreeRow: true })), `${classes.join(" ")} in tree-row`).toBe(SOLID);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("blink CSS: regression pin — the colour class alone can never blink", () => {
|
||||
// The old sheet animated `.dot--busy`/`.dot--err` globally and `.dot--ok`
|
||||
// inside `.tree-row`. A dot that asks for no blink must stay solid in every
|
||||
// phase, in every wrapper: no re-introduced tree-scoped green, no
|
||||
// forever-blinking red/green task dot.
|
||||
const colourOnly = ["dot--busy", "dot--err", "dot--ok", "dot--attention", "dot--idle"];
|
||||
|
||||
it.each(colourOnly)("%s stays solid across every phase and wrapper", (colour) => {
|
||||
for (const phase of [{}, { fast: "dim" as const }, { slow: "dim" as const }, { fast: "on" as const, slow: "on" as const }]) {
|
||||
setPhase(phase);
|
||||
expect(opacityOf(mountDot([colour])), `${colour} ${JSON.stringify(phase)}`).toBe(SOLID);
|
||||
expect(opacityOf(mountDot([colour], { inTreeRow: true })), `${colour} in tree-row`).toBe(SOLID);
|
||||
}
|
||||
});
|
||||
|
||||
it("the same colour blinks only when the view asked for it", () => {
|
||||
setPhase({ fast: "dim" });
|
||||
// `ok` (a done row) blinks *because* of dot--blink-fast, not because of
|
||||
// where it is mounted.
|
||||
expect(opacityOf(mountDot(["dot--ok"]))).toBe(SOLID);
|
||||
expect(opacityOf(mountDot(["dot--ok"], { inTreeRow: true }))).toBe(SOLID);
|
||||
expect(opacityOf(mountDot(["dot--ok", "dot--blink-fast"]))).toBe(DIM);
|
||||
expect(opacityOf(mountDot(["dot--ok", "dot--blink-fast"], { inTreeRow: true }))).toBe(DIM);
|
||||
});
|
||||
});
|
||||
@@ -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 });
|
||||
|
||||
@@ -0,0 +1,137 @@
|
||||
import { QueryClient } from "@tanstack/react-query";
|
||||
import i18n from "i18next";
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
import { applyWorkspaceUpdate, parseWorkspaceUpdate } from "@/features/workspaces/live";
|
||||
import { instanceState } from "@/features/workspaces/workspace-card";
|
||||
import { setLanguage } from "@/lib/i18n";
|
||||
import type { WorkspaceInfo } from "@/lib/protocol";
|
||||
import type { WsFrame } from "@/lib/ws";
|
||||
import { useWorkspacesStore } from "@/stores/workspaces";
|
||||
|
||||
function sampleWorkspace(overrides: Partial<WorkspaceInfo> & Pick<WorkspaceInfo, "workspaceId" | "cwd" | "name">): WorkspaceInfo {
|
||||
return {
|
||||
trusted: true,
|
||||
exists: true,
|
||||
sessionCount: 0,
|
||||
liveCount: 0,
|
||||
lastActiveAt: 0,
|
||||
instance: null,
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
describe("workspaces live updates", () => {
|
||||
beforeEach(async () => {
|
||||
await setLanguage("en");
|
||||
useWorkspacesStore.getState().reset();
|
||||
});
|
||||
|
||||
describe("parseWorkspaceUpdate", () => {
|
||||
it("rejects garbage input (null payload, missing workspaceId, empty workspaceId, missing cwd)", () => {
|
||||
expect(parseWorkspaceUpdate(null as unknown as WsFrame)).toBeNull();
|
||||
expect(parseWorkspaceUpdate(undefined as unknown as WsFrame)).toBeNull();
|
||||
expect(parseWorkspaceUpdate({} as WsFrame)).toBeNull();
|
||||
expect(parseWorkspaceUpdate({ type: "workspace_update" } as WsFrame)).toBeNull();
|
||||
expect(parseWorkspaceUpdate({ type: "workspace_update", payload: null as unknown as Record<string, unknown> })).toBeNull();
|
||||
expect(parseWorkspaceUpdate({ type: "workspace_update", payload: "not-an-object" as unknown as Record<string, unknown> })).toBeNull();
|
||||
expect(parseWorkspaceUpdate({ type: "workspace_update", payload: {} })).toBeNull();
|
||||
expect(parseWorkspaceUpdate({ type: "workspace_update", payload: { cwd: "/work" } })).toBeNull();
|
||||
expect(parseWorkspaceUpdate({ type: "workspace_update", payload: { workspaceId: "", cwd: "/work" } })).toBeNull();
|
||||
expect(parseWorkspaceUpdate({ type: "workspace_update", payload: { workspaceId: " ", cwd: "/work" } })).toBeNull();
|
||||
expect(parseWorkspaceUpdate({ type: "workspace_update", payload: { workspaceId: "ws-1" } })).toBeNull();
|
||||
expect(parseWorkspaceUpdate({ type: "workspace_update", payload: { workspaceId: "ws-1", cwd: 123 as unknown as string } })).toBeNull();
|
||||
});
|
||||
|
||||
it("accepts a real workspace row", () => {
|
||||
const row = sampleWorkspace({ workspaceId: "ws-1", cwd: "/work/1", name: "One" });
|
||||
const frame: WsFrame = {
|
||||
v: 1,
|
||||
type: "workspace_update",
|
||||
workspaceId: "ws-1",
|
||||
ts: 1000,
|
||||
payload: row as unknown as Record<string, unknown>,
|
||||
};
|
||||
|
||||
const parsed = parseWorkspaceUpdate(frame);
|
||||
expect(parsed).toEqual(row);
|
||||
});
|
||||
});
|
||||
|
||||
describe("applyWorkspaceUpdate", () => {
|
||||
it("replaces matching row in QueryClient ['workspaces'] cache and appends an unknown one", () => {
|
||||
const queryClient = new QueryClient();
|
||||
const initial1 = sampleWorkspace({ workspaceId: "ws-1", cwd: "/work/1", name: "One" });
|
||||
const initial2 = sampleWorkspace({ workspaceId: "ws-2", cwd: "/work/2", name: "Two" });
|
||||
queryClient.setQueryData<WorkspaceInfo[]>(["workspaces"], [initial1, initial2]);
|
||||
|
||||
// Replace matching row
|
||||
const updated1 = sampleWorkspace({ workspaceId: "ws-1", cwd: "/work/1", name: "One Updated", sessionCount: 5 });
|
||||
applyWorkspaceUpdate(queryClient, updated1);
|
||||
|
||||
const cachedAfterReplace = queryClient.getQueryData<WorkspaceInfo[]>(["workspaces"]);
|
||||
expect(cachedAfterReplace).toEqual([updated1, initial2]);
|
||||
|
||||
// Append unknown row
|
||||
const newRow3 = sampleWorkspace({ workspaceId: "ws-3", cwd: "/work/3", name: "Three" });
|
||||
applyWorkspaceUpdate(queryClient, newRow3);
|
||||
|
||||
const cachedAfterAppend = queryClient.getQueryData<WorkspaceInfo[]>(["workspaces"]);
|
||||
expect(cachedAfterAppend).toEqual([updated1, initial2, newRow3]);
|
||||
});
|
||||
|
||||
it("updates ['chat-workspaces'] only when cached and updates the zustand store", () => {
|
||||
const queryClient = new QueryClient();
|
||||
const row1 = sampleWorkspace({ workspaceId: "ws-1", cwd: "/work/1", name: "One" });
|
||||
const row2 = sampleWorkspace({ workspaceId: "ws-2", cwd: "/work/2", name: "Two" });
|
||||
|
||||
// ['chat-workspaces'] has cached data
|
||||
queryClient.setQueryData<WorkspaceInfo[]>(["chat-workspaces"], [row1]);
|
||||
|
||||
const updatedRow1 = sampleWorkspace({ workspaceId: "ws-1", cwd: "/work/1", name: "One Updated" });
|
||||
applyWorkspaceUpdate(queryClient, updatedRow1);
|
||||
|
||||
expect(queryClient.getQueryData<WorkspaceInfo[]>(["chat-workspaces"])).toEqual([updatedRow1]);
|
||||
expect(useWorkspacesStore.getState().items).toEqual([updatedRow1]);
|
||||
|
||||
// Add row2
|
||||
applyWorkspaceUpdate(queryClient, row2);
|
||||
expect(queryClient.getQueryData<WorkspaceInfo[]>(["chat-workspaces"])).toEqual([updatedRow1, row2]);
|
||||
expect(useWorkspacesStore.getState().items).toEqual([updatedRow1, row2]);
|
||||
});
|
||||
|
||||
it("invalidates ['health'] queries", () => {
|
||||
const queryClient = new QueryClient();
|
||||
const spy = vi.spyOn(queryClient, "invalidateQueries");
|
||||
const row = sampleWorkspace({ workspaceId: "ws-1", cwd: "/work/1", name: "One" });
|
||||
|
||||
applyWorkspaceUpdate(queryClient, row);
|
||||
|
||||
expect(spy).toHaveBeenCalledWith({ queryKey: ["health"] });
|
||||
});
|
||||
|
||||
it("maps a stopped row into the instance stopped label via instanceState()", () => {
|
||||
const stoppedRow = sampleWorkspace({
|
||||
workspaceId: "ws-stopped",
|
||||
cwd: "/work/stopped",
|
||||
name: "Stopped WS",
|
||||
instance: {
|
||||
workspaceId: "ws-stopped",
|
||||
instanceId: "inst-1",
|
||||
status: "stopped",
|
||||
nvimPid: 1234,
|
||||
pluginVersion: "0.1.1",
|
||||
hasUI: true,
|
||||
attachedClients: 0,
|
||||
listenAddr: "127.0.0.1:8888",
|
||||
startedAt: 1000,
|
||||
},
|
||||
});
|
||||
|
||||
const state = instanceState(stoppedRow);
|
||||
expect(state.status).toBe("exited");
|
||||
expect(state.labelKey).toBe("workspaces.instanceStopped");
|
||||
expect(i18n.t(state.labelKey)).toBe("Instance stopped");
|
||||
});
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user