17 Commits
Author SHA1 Message Date
yuez 1664227c3b chore: release 0.1.4 2026-10-27 19:21:49 +08:00
yuez dcbda60165 docs: write down the session dot contract
The dot is a view of the plugin, and it drifted once already because the rule
lived only in code. docs/session-dot.md now records the parent/sub-session/
subagent matrices, the current marker, the unread-flag lifetime and the single
blink clock, with the pi2.nvim functions each rule mirrors.
2026-10-27 19:18:07 +08:00
yuez 668f77bf51 fix(web): a dead process outranks its own unread flags
Review caught two holes in the previous commit.

interrupted was ranked below error/attention/done, so an interrupted session
with a stale error flag still blinked red, one with pending attention still
wore the amber dot, and one with a done flag still turned green. In the
plugin there is no interrupted at all: any non-running row is exited
(sessions.lua:75-78) and exited sits at the top of dot_hl. interrupted now
shares that slot.

The subagent tables were not actually consolidated: subagent-view.tsx and
telemetry.tsx each kept their own SUB_DOT, still painting interrupted amber
and completed green. All three now go through subagentDot(); in a subagent
view the row is the one you have open, so a failed child is steady red there.
2026-10-27 19:13:35 +08:00
yuez b6335a21a4 docs(protocol): document the session list ordering contract
Sessions rows now document `tabRank`, the console's ranking rule, which
parts are console-side determinism rather than :PiSessions behaviour, and
the remaining gaps (history parent retained, manifest existence not
consulted, child ownership without conversation_epoch).
2026-10-27 19:08:47 +08:00
yuez 2712c6c76c test(web): pin the :PiSessions session ordering
Covers root ranking by tab/tabRank (including a child-view parent inheriting
its viewing child's tab and a lineage taking its earliest slot), the root
tie-break chain, sibling order by createdAt desc + id asc, the manifest
entry winning the sort key over the row, cycle/duplicate/self-parent safety
and determinism under input shuffles.
2026-10-27 19:08:47 +08:00
yuez 37941aea19 feat(web): order the chat session list like :PiSessions
The sidebar rendered whatever order the plugin payload happened to carry
(disk mtime desc, then Lua hash order). It now mirrors pi2.nvim:

- roots ranked by the tab's visual position (`tabRank`, falling back to the
  `tab` handle), a lineage occupying the earliest tab it occupies;
- siblings (real sub-session rows and manifest subagents merged into one list)
  by `createdAt` desc with the id as tie-break, a session row inheriting its
  manifest entry's `createdAt`, matching `manifest.lua`;
- deterministic code-unit comparisons plus a root tie-break chain, so WS
  arrivals and payload order can no longer shuffle rows.

`session-order.ts` is the single owner of the rule; the tree model renders it
and the /chat index default is the sidebar's top root.
2026-10-27 19:08:47 +08:00
yuez 92f844d694 feat(protocol): carry tab, tabRank, createdAt and lastActiveAt on SessionState
List metadata the web console needs to order the chat session list like
pi2.nvim's :PiSessions: the tab handle, its 1-based visual tabline position,
and the creation/last-activity timestamps. Never emitted by the reducer; the
web normalizer and the sessions store preserve them across snapshot and live
event updates.
2026-10-27 19:08:47 +08:00
yuez c4d0057b0b test(web): pin the dot matrix, the shared blink clock and markSeen
sessionDot had no test at all, which is how its priority order drifted away
from the plugin. session-dot.test.ts locks the whole matrix: the parent
order (exited > error > attention > done > busy > compacting > idle), every
collision that used to be wrong, the viewed -> current overlay, the separate
child matrix (steady red while viewed, never green, never attention) and the
subagent table.

blink.test.ts covers the one shared clock: phase lockstep, ref counting
(two subscribers, one interval), idempotent unsubscribe, and
prefers-reduced-motion pinning the dots solid.

chat.tree.test.tsx grows up from "a .dot exists" to the actual classes;
sessions-store.test.ts covers markSeen; components.test.tsx covers the dead
status and the steady/current modifiers.

Also makes the current-tab overlay a positive check (idle | busy |
compacting), matching the plugin markable list: a session that has not
reported a status yet ("starting") no longer claims the blue marker.
2026-10-27 19:00:26 +08:00
yuez bf01fd549d fix(web): rebuild the session dot matrix from pi2.nvim
The Chat session list dot did not follow the plugin it mirrors
(:PiSessions in pi2.nvim, lua/pi/ui/sessions.lua). Four things were wrong:

- priority: attention outranked error and exited; the plugin order is
  exited > error > attention > done > busy > compacting > idle.
- interrupted wore the attention amber, the same colour as "waiting for you";
  it is a dead process, so it takes the solid exited red (dot--dead).
- exited and dormant were collapsed into the hollow grey ring; a dead parent
  is the solid red one, the hollow ring is the dormant sub-session.
- sub-sessions reused the parent matrix. They now follow child_dot_hl: a
  failed child is steady red while you are looking at it and blinking red
  while you are not, busy/compacting blink at the busy rate, and a child
  never shows green (the plugin forces done=false there).

The current-tab marker (PiSessionsListCurrent) was missing entirely: the row
the console has open now carries dot--current, steady on idle and blinking
on busy, and never on top of a notification colour - same guard as
refresh_current_markers. It is the browser analogue of the focused nvim tab,
so no wire change is needed.

Also drops the unreachable sessionDotClass() dead code, whose second mapping
was the reason the divergence went unnoticed, and consolidates the three
subagent dot tables into subagentDot().

Unread notifications now expire like the plugin's: done/error are unread
markers, not states (on_agent_end only raises done for a tab that is not
current, clear_flags wipes both on TabEnter). The store gained markSeen(),
called when the routed session carries done/error, so a session you open
stops being green or red. The canonical reducer and fixtures/ are untouched:
this is a client-side view concern.
2026-10-27 18:43:13 +08:00
yuez 81e7f96a64 feat(web): drive every status dot from one shared blink clock
Each dot used its own CSS animation ("pulse" in app.css, "tree-dot-blink" in
chat.css), so dots drifted out of phase and the tree looked noisy. One
ref-counted 500ms clock in lib/blink.ts now writes data-pi-blink-fast and
data-pi-blink-slow on <html>, and CSS derives the dim phase from those
attributes: one timer for the whole app, no React re-renders, and
prefers-reduced-motion pins every dot solid.
2026-10-27 18:42:54 +08:00
yuez 48411dccd2 feat(cli): add stop command to shut down running daemon 2026-10-27 18:37:21 +08:00
yuez 2b8171cc37 test(web): lock the server chip's status and version fallbacks
Assert the chip renders `dot--idle` / Unknown for the initial `unknown` store
value, and that a bogus `status` carried by a `server` override can no longer
override the store's `online` verdict.
2026-10-27 18:07:16 +08:00
yuez 611c405439 fix(web): read the live server status in the page sheet
The navigation sheet took its status from `server.status` on the cached /info
payload, which stays `"online"` (or `"offline"` once stored) regardless of the
live probe, and rendered an empty version when `pluginVersion` was "". Use the
connection store's `serverStatus` and fall back through `version` with `||`, and
cover both the localized status fact and the empty-`pluginVersion` path.
2026-10-27 18:07:16 +08:00
yuez ec80ee4bab fix(web): stop doubling the dot modifier on the status page head
`serverDotClass()` already returns the full `dot--<status>` class, but the head
fed it to a `DotStatus` prop that prepends `dot--` again, so the dot never
matched a status color. Strip the prefix and assert the concrete class
(`dot--attention` / `dot--ok`) in the page tests instead of just the size.
2026-10-27 18:07:11 +08:00
yuez f549045ed2 fix(web): degrade server status when the /health probe fails
`resolveServerStatus` only degraded on `healthOk === false`, so a /health
request that errored outright (network error, 5xx) left the console claiming
"online" off a cached /info. Add `healthError` as its own step, ahead of the
subsystem check, and feed `health.isError` from the shell, the status page and
the workspaces page so all three derive a single verdict.
2026-10-27 18:07:04 +08:00
yuez 5139adf915 perf(web): optimize vitest performance and add testing guide 2026-10-27 17:30:40 +08:00
yuez e910e75849 feat: session-scoped entries query, session title tree and message stream updates 2026-10-27 17:30:28 +08:00
68 changed files with 4423 additions and 286 deletions

No files matched your search

+2
View File
@@ -67,8 +67,10 @@ owner/repo/workflow filename, not the npm name).
| Doc | Contents |
|---|---|
| `docs/protocol.md` | the browser ↔ daemon ↔ plugin wire contract |
| `docs/session-dot.md` | the session-list status dot: the `:PiSessions` matrix, the unread flags, the one blink clock |
| `docs/deployment.md` | env vars, runtime files, ports, auth, services, troubleshooting |
| `docs/e2e.md` | scenario ids, isolation, skip conditions, report paths |
| `docs/testing.md` | test architecture, performance tuning, hybrid core CPU guidelines |
| `docs/releasing.md` | npm Trusted Publishing, the bootstrap phases, verification |
| `README.md` | install paths, `:PiWeb`, binding & pairing |
| `.agents/skills/release/` | how to cut and verify a release |
+6
View File
@@ -44,6 +44,7 @@ Then:
```bash
pi2 daemon # foreground; the plugin/browser needs this running
pi2 stop # stop a running daemon (or: pi2 daemon stop)
pi2 install-service --write # or run it at login: systemd --user / launchd
pi2 status # daemon + instances + health
pi2 doctor # node/nvim/pi/curl/plugin/runtime/web-dist/protocol checks
@@ -114,6 +115,11 @@ pnpm dev # daemon on 127.0.0.1:7676 (tsx watch)
pnpm --dir web dev # vite dev server on :5173, proxying /api and /ws to the daemon
```
The dev proxy presents the daemon's own `Origin`, so the :5173 server needs no `PI2_ORIGINS`
(the daemon's allowlist is derived from its port). Sign in to :5173 once by opening
`http://localhost:5173/#t=<token>` with the fragment from `pnpm exec tsx src/cli/pi2.ts open --print`;
`localStorage` is per origin, so the :7676 session does not carry over.
`pnpm build` → `dist/`, `pnpm build:web` → `web/dist/`. The published tarball ships both, so
`pi2 daemon` serves the web console from its own package with no extra step.
+15
View File
@@ -275,6 +275,21 @@ The daemon is dispatched *inside* `pi2` (`src/cli/pi2.ts` → `src/cli/daemon.ts
it is not a separate executable, nothing is re-exec'd, and there is no detaching
mode. Flags, stdout contract and startup order: [§3](#3-running-the-daemon).
### 8.0b `pi2 stop` / `pi2 daemon stop`
```bash
pi2 stop # stop a running daemon (SIGTERM, waits up to 5s)
pi2 daemon stop # alias for `pi2 stop`
pi2 stop --force # escalate to SIGKILL if SIGTERM times out
pi2 stop -t 10 # wait up to 10 seconds before failing / escalating
```
Locates the running daemon via `<runtime>/daemon.json` (or `daemon.lock`), verifies
that the PID belongs to this boot, sends `SIGTERM`, and waits for the process to exit.
If the daemon was already dead (stale lock/json), it cleans up the stale files and reports
that no daemon is running. With `--force`, it escalates to `SIGKILL` if the daemon does not
exit within the timeout.
### 8.1 `pi2 attach [path]`
```bash
+32 -3
View File
@@ -63,6 +63,8 @@ The plugin dials the daemon (`<runtime>/d.sock`), sends `hello` first.
{"v":1,"type":"sub.unsubscribe","sessionId":"s1"}
{"v":1,"type":"instance.shutdown","payload":{"mode":"drain"}}
{"v":1,"type":"workspace.query","id":"req-2","payload":{"kind":"sessions"}}
// a session-scoped read keeps the sid on the envelope (see §3.1 entries)
{"v":1,"type":"workspace.query","id":"req-3","sessionId":"s1","payload":{"kind":"entries","limit":50}}
```
Plugin obligations:
@@ -83,7 +85,7 @@ Plugin obligations:
| `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) |
| `GET /api/v1/sessions/:sid/entries?before=&limit=` | relayed; plugin paginates |
| `GET /api/v1/sessions/:sid/entries?before=&limit=&workspaceId=&sessionFile=` | relayed `workspace.query{kind:"entries"}`; plugin paginates |
| `GET /api/v1/attention?workspaceId=` | pending attention for one workspace |
| `GET /api/v1/devices` | paired devices (daemon-owned; `{id, name, kind, createdAt, lastSeenAt, revokedAt}`) |
| `POST /api/v1/pair` | **authenticated**; mints `{code, url, expiresAt, nonce, qr, bases}` |
@@ -93,6 +95,14 @@ Plugin obligations:
| `GET /api/v1/resources` | instances, sessions, RSS totals for the soft-limit notice |
| `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
caller routes it (a disk-only row has no live owner); the `sid` always travels on the
record envelope, so the plugin resolves the session — and its file — from its own
registry. `sessionFile` is an optional fallback for a session the receiving instance
does not know. A session that exists but has no JSONL yet (`pi` creates the file with
the first entry) answers an **empty page** (`{entries:[], cursor:{hasMore:false}}`),
never an error: a new session has no history to fail on.
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 |
@@ -125,13 +135,31 @@ Session row (`GET /api/v1/workspaces/:id/sessions`) — a subset of `SessionStat
| Field | Notes |
|---|---|
| `sessionId`, `sessionFile?`, `name?`, `cwd?`, `timestamp?`, `modified?`, `firstMessage?` | identity + disk projection |
| `tab?`, `live?` | live projection |
| `tab?` | live projection of `Session.attached_tab`; present ⇒ this row is an nvim tab |
| `tabRank?` | live projection: 1-based visual position of `tab` in `nvim_list_tabpages()`; absent on plugins that predate it |
| `live?` | live projection: the session's `pi --mode rpc` process runs (a detached sub-session is live without a `tab`) |
| `status?` | live status when `live` (`busy`, `compacting`, `idle`, `exited`); otherwise the child's manifest status (`dormant`, `done`, `error`, `interrupted`, `exited`). Absent on a non-live root. |
| `model?`, `thinking?` | per-session model pin; the child's manifest thinking level |
| `visible: boolean` | always present; the plugin's `:PiSessions` visibility decision |
| `parentId?: string` | sub-session rows only: the parent session id (normally present in the same list) |
| `task?`, `agentSpawned?`, `reported?` | sub-session rows only, carried through from the spawn request |
| `createdAt?`, `lastActiveAt?` | epoch ms; ordering/aging hints, never required |
| `createdAt?`, `lastActiveAt?` | epoch ms; optional ordering/aging hints — the console degrades gracefully when they are absent |
The console mirrors `:PiSessions` ordering: roots are ranked by `tabRank` (1-based visual position) and fall back to the `tab` handle (where handle order diverges after `:tabmove` or mid-tabline insertions), with a lineage placed at the earliest tab slot of the root and all its descendants. Tab-less roots are placed last (rank `+Infinity`); note that `:PiSessions` never renders a tab-less root at all, and the console retains one only when it serves as the parent row of a live child-view tab (or an orphan). Ties among roots are broken deterministically by `createdAt` desc, `lastActiveAt` desc, `sessionId` asc — this tie-break chain is a console-side determinism rule rather than `:PiSessions` behaviour. Siblings are ordered by `createdAt` desc then id asc (matching `manifest.lua`'s `created_at` desc + `_id` asc), with child session rows inheriting the same-id manifest entry's `createdAt`.
The list is a union of every session JSONL the workspace has on disk and its live
sessions, so a client must not assume every row is an nvim tab. A row carrying
`tab` is a tab; a tab-less root row is *history* — it has no live owner, and a
command routed to it answers `E_SESSION_NOT_FOUND`. A client that mirrors the
nvim session list renders the tab-backed component: the rows with a `tab` plus
every row linked to them through `parentId` in either direction (their
sub-sessions, and the parent row when a tab is in a child view). That approximates
`:PiSessions` (`Sessions.list()` plus children); pi2 web applies this filter in
`web/src/features/chat/session-state.ts` (`tabSessionRows`). Known gaps from nvim:
a history parent row with no live owner is kept; manifest-entry existence is not
consulted; and child ownership across a lineage with two live roots is decided by
`parentId` alone (nvim also uses `conversation_epoch`). A history row is a
`session.resume` target, never a prompt target.
Sub-session rows sit in the same flat list as their parent: build the tree from `parentId`
(an unknown `parentId`, or one whose row was pruned, promotes the row to a root so a row is
@@ -204,6 +232,7 @@ interface SessionState {
parentId?: string | null; // null = root (client-side only; the plugin omits the field)
visible?: boolean; // plugin `:PiSessions` visibility decision
task?: string; // subagent task description from the spawn request
firstMessage?: string | null; // first user message of the session file (provisional title)
}
type Block =
+74
View File
@@ -0,0 +1,74 @@
# The session-list status dot
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.
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`.
## 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 |
`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.
## 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` |
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 `◌`.
## The "you are here" marker
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.
## `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.
## 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).
+87
View File
@@ -0,0 +1,87 @@
# Testing & Performance Guide
This document describes the testing architecture for `pi2d` (both daemon and web console),
along with performance tuning strategies for local development and CI.
---
## 1. Test Architecture
The repository maintains two independent test suites across two lockfiles:
| Scope | Path | Runner | Environment | Isolation | Focus |
|---|---|---|---|---|---|
| **Daemon** | `test/` | Vitest (root) | `node` | per-file forks | CLI, routing, auth, instances, IPC, protocol conformance |
| **Web Console** | `web/tests/` | Vitest (web) | `jsdom` | shared worker (`isolate: false`) | React 19 UI, pages, TanStack router/query, token contracts |
---
## 2. Web Test Performance & CPU Optimization
Web unit tests use React 19, `@testing-library/react` and `jsdom`.
### 2.1 The DOM Isolation Overhead (`isolate: false`)
* **Problem**: By default, Vitest destroys and rebuilds a clean DOM environment for every single test file. In a suite with 35+ test files, recreating `jsdom` accounted for **52% of total CPU tracking time** (~240s CPU time per run).
* **Optimization**: Set `isolate: false` in `web/vite.config.ts`.
- Environment instances are reused across files within each worker.
- Test files maintain clean state using standard teardown hooks in `tests/setup.ts` (`cleanup()`, `localStorage.clear()`, theme reset).
- **Result**: Wall clock time drops by ~37%, and total CPU time is reduced by ~40% with 100% test pass rate.
### 2.2 Worker Concurrency on Hybrid Core Architectures
* On modern CPUs with Performance and Efficient cores (e.g., Intel 12th+ Gen like i7-12700H with 6P + 8E cores):
- Vitest defaults to spawning workers matching total logical threads (e.g. 20 workers).
- This saturates E-cores, leading to high thermal throttling, CPU lockup, and system unresponsiveness.
- **Recommendation for heavy multi-tasking / laptops**:
```bash
pnpm --dir web exec vitest run --maxWorkers=6
```
Confining workers to P-core count keeps tests fast while leaving headroom for Neovim and the desktop compositor.
### 2.3 JSDOM Stubs vs. Virtual Console Noise
* `jsdom` includes incomplete stubs (e.g., `window.scrollTo` and `HTMLCanvasElement.getContext`) that write noisy "Not implemented" warnings to stderr on every call.
* These stubs are explicitly overridden in `web/tests/setup.ts`:
```typescript
if (typeof window !== "undefined") {
window.scrollTo = vi.fn();
}
if (typeof HTMLCanvasElement !== "undefined") {
HTMLCanvasElement.prototype.getContext = vi.fn();
}
```
This eliminates thousands of lines of terminal I/O overhead and keeps test logs readable.
### 2.4 Why JSDOM over Happy-DOM
* While `happy-dom` is slightly faster, real-world evaluation in `pi2-web` revealed subtle incompatibilities with TanStack Router navigation microtasks and React 19 asynchronous `act(...)` scheduling (causing failures in `ConnectPage` and `StatusPage`).
* We retain `jsdom` with `isolate: false` to preserve 100% browser behavior fidelity while achieving near-identical speed.
### 2.5 Timeout Defensive Line
* Set `testTimeout: 15000` in `web/vite.config.ts` to prevent transient timeouts when the host CPU is under heavy background load.
---
## 3. Daily Development Workflow
### 3.1 Incremental Test Runs (Recommended)
Avoid running all 35+ tests on every keystroke. Run only what changed:
```bash
# Run only test files related to uncommitted git changes
pnpm --dir web exec vitest run --changed
# Run a specific test file
pnpm --dir web exec vitest run tests/chat.composer.test.tsx
```
### 3.2 Watch Mode
Vitest's HMR-powered watch mode tracks module dependency graphs and re-runs only the affected test tree:
```bash
pnpm --dir web test
```
### 3.3 Pre-commit Full Gate
Before submitting or tagging releases, run the comprehensive verification chain:
```bash
pnpm typecheck && pnpm test && pnpm --dir web typecheck && pnpm --dir web exec vitest run
```
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@yuez/pi2d",
"version": "0.1.3",
"version": "0.1.4",
"type": "module",
"license": "MIT",
"description": "pi2 web console daemon (`pi2 daemon`): HTTP/WS gateway, workspace registry and instance supervisor for pi2.nvim",
+4 -8
View File
@@ -174,20 +174,16 @@ pass "GET /api/v1/workspaces without a token -> 401"
expect_status 401 GET /api/v1/workspaces -H "authorization: Bearer deadbeef"
pass "GET /api/v1/workspaces with a bogus token -> 401"
printf '==> stopping pi2 daemon (SIGTERM)\n'
kill -TERM "$DAEMON_PID"
for _ in $(seq 1 100); do
kill -0 "$DAEMON_PID" 2>/dev/null || break
sleep 0.05
done
kill -0 "$DAEMON_PID" 2>/dev/null && fail "pi2 daemon did not exit within 5s of SIGTERM"
printf '==> stopping pi2 daemon (pi2 stop)\n'
PI2_RUNTIME_DIR="$TMP/run" node "$ROOT/dist/cli/pi2.js" stop
pass "pi2 stop executed cleanly"
set +e
wait "$DAEMON_PID"
EXIT_CODE=$?
set -e
[[ "$EXIT_CODE" -eq 0 ]] || fail "pi2 daemon exited with code $EXIT_CODE"
pass "SIGTERM -> clean exit (code 0)"
pass "daemon process -> clean exit (code 0)"
[[ ! -f "$LOCK" ]] || fail "daemon.lock was not removed on shutdown"
pass "daemon.lock removed"
+57 -11
View File
@@ -26,6 +26,7 @@ import { readDaemonJson, type DaemonLock } from "./lock.js";
import { cliTokenPath, readCliToken } from "./token.js";
import {
boolFlag,
CliError,
errorMessage,
formatBytes,
formatTable,
@@ -44,11 +45,17 @@ import {
type ServicePlatform,
} from "./service.js";
import { diagnose, formatReport, reportToJson, type DoctorReport } from "./doctor.js";
import { runStop, STOP_USAGE, type StopOptions } from "./stop.js";
export { CliError } from "./util.js";
export { runStop, STOP_USAGE, type StopOptions } from "./stop.js";
export const USAGE = `pi2 — pi2 client
Usage:
pi2 daemon [start] [options] run the web-console daemon (foreground)
pi2 daemon stop [options] stop the running daemon
pi2 stop [options] stop the running daemon (alias for daemon stop)
pi2 attach [path] attach nvim to the workspace instance, else open nvim
pi2 status [--json] daemon info, instances, resources, health
pi2 open [--print] [--no-browser] open the web console signed in (local only)
@@ -58,6 +65,8 @@ Usage:
pi2 uninstall-service [--dry-run|--write] remove the unit
pi2 --version | --help
\`pi2 stop\` / \`pi2 daemon stop\` flags: -f, --force sends SIGKILL if the daemon
does not exit in time; -t, --timeout <sec> configures the wait timeout (default 5s).
\`pi2 open\` flags: --print prints the URL only; --no-browser prints it instead
of launching a browser (--print implies --no-browser).
\`pi2 pairing\` flags: --base <url> pins the link to one of the addresses the
@@ -69,17 +78,6 @@ The daemon endpoint comes from $PI2_RUNTIME_DIR/daemon.json (port) and
$PI2_RUNTIME_DIR/cli.token (local admin token). Start it with \`pi2 daemon\`.
See docs/deployment.md.`;
/** A user-facing failure: printed as-is, exits with `code`. */
export class CliError extends Error {
readonly code: number;
constructor(message: string, code = 1) {
super(message);
this.name = "CliError";
this.code = code;
}
}
export interface Endpoint {
baseUrl: string;
token: string;
@@ -635,6 +633,44 @@ export function runUninstallService(options: ServiceCommandOptions): number {
return 0;
}
async function handleStop(argv: readonly string[], options: Pi2Options, out: (line: string) => void): Promise<number> {
const parsed = parseArgs(argv, {
values: ["--timeout", "-t"],
booleans: ["--force", "--help"],
aliases: { "-h": "--help", "-f": "--force", "-t": "--timeout" },
});
if (boolFlag(parsed.flags, "--help")) {
out(STOP_USAGE);
return 0;
}
if (parsed.positionals.length > 0) {
throw new UsageError(`unexpected argument "${parsed.positionals[0]}"`, STOP_USAGE);
}
let timeoutSec: number | undefined;
const timeout = stringFlag(parsed.flags, "--timeout");
if (timeout !== undefined) {
if (!/^\d+$/.test(timeout.trim())) {
throw new UsageError(`--timeout must be a positive integer, got "${timeout}"`, STOP_USAGE);
}
const val = Number(timeout);
if (!Number.isSafeInteger(val) || val <= 0) {
throw new UsageError(`--timeout must be a positive integer, got "${timeout}"`, STOP_USAGE);
}
timeoutSec = val;
}
const runner = options.stopRunner ?? runStop;
return await runner({
runtime: options.runtime,
force: boolFlag(parsed.flags, "--force"),
...(timeoutSec === undefined ? {} : { timeoutSec }),
print: out,
...(options.isPidAlive === undefined ? {} : { isPidAlive: options.isPidAlive }),
...(options.kill === undefined ? {} : { kill: options.kill }),
...(options.sleep === undefined ? {} : { sleep: options.sleep }),
...(options.removeFile === undefined ? {} : { unlink: options.removeFile }),
});
}
// ---------------------------------------------------------------------------
// main
// ---------------------------------------------------------------------------
@@ -654,6 +690,10 @@ export interface Pi2Options {
runtime?: string;
/** Injected `pi2 daemon` runner (defaults to `src/cli/daemon.ts:main`). */
daemonMain?: (argv: readonly string[], io: { out: (line: string) => void; err: (line: string) => void }) => Promise<number>;
stopRunner?: (options: StopOptions) => Promise<number>;
isPidAlive?: (pid: number) => boolean;
kill?: (pid: number, signal: NodeJS.Signals) => void;
sleep?: (ms: number) => Promise<void>;
}
export async function main(argv: readonly string[], options: Pi2Options = {}): Promise<number> {
@@ -673,12 +713,18 @@ export async function main(argv: readonly string[], options: Pi2Options = {}): P
try {
switch (command) {
case "daemon": {
if (rest[0] === "stop") {
return await handleStop(rest.slice(1), options, out);
}
// `pi2 daemon` and `pi2 daemon start` are the same thing; the
// optional `start` word is consumed here so the daemon parser
// only ever sees flags.
const argv = rest[0] === "start" ? rest.slice(1) : rest;
return await (options.daemonMain ?? runDaemonMain)(argv, { out, err });
}
case "stop": {
return await handleStop(rest, options, out);
}
case "attach": {
const parsed = parseArgs(rest, { booleans: ["--help"], aliases: { "-h": "--help" } });
if (boolFlag(parsed.flags, "--help")) {
+159
View File
@@ -0,0 +1,159 @@
/**
* `pi2 stop` / `pi2 daemon stop` — stop a running pi2 web-console daemon.
*
* Locates the daemon via `<runtime>/daemon.json` (or `daemon.lock`), verifies
* the PID belongs to this boot, sends SIGTERM, and waits for it to exit.
* If --force is passed and SIGTERM times out, escalates to SIGKILL.
*/
import { rmSync } from "node:fs";
import { resolve } from "node:path";
import { runtimeDir } from "../core/paths.js";
import {
assessLock,
DAEMON_JSON_FILE,
LOCK_FILE,
readBootId,
readDaemonJson,
readLockFile,
isPidAlive as defaultIsPidAlive,
type DaemonLock,
} from "./lock.js";
import { CliError, errorMessage } from "./util.js";
export const STOP_USAGE = `pi2 stop — stop a running pi2 daemon
Usage:
pi2 stop [options]
pi2 daemon stop [options]
Options:
-f, --force force kill with SIGKILL if the daemon does not stop in time
-t, --timeout <sec> seconds to wait for the daemon to exit (default: 5)
-h, --help print this help and exit
Environment:
PI2_RUNTIME_DIR directory holding daemon.json and daemon.lock`;
export interface StopOptions {
runtime?: string;
force?: boolean;
timeoutSec?: number;
print?: (line: string) => void;
readDaemonJson?: (path: string) => DaemonLock | undefined;
readLockFile?: (path: string) => DaemonLock | undefined;
isPidAlive?: (pid: number) => boolean;
bootId?: () => string;
kill?: (pid: number, signal: NodeJS.Signals) => void;
sleep?: (ms: number) => Promise<void>;
unlink?: (path: string) => void;
now?: () => number;
}
export async function runStop(options: StopOptions = {}): Promise<number> {
const print = options.print ?? ((line: string) => process.stdout.write(`${line}\n`));
const runtime = options.runtime ?? runtimeDir();
const daemonJsonPath = resolve(runtime, DAEMON_JSON_FILE);
const lockPath = resolve(runtime, LOCK_FILE);
const readJson = options.readDaemonJson ?? readDaemonJson;
const readLock = options.readLockFile ?? readLockFile;
const lock = readJson(daemonJsonPath) ?? readLock(lockPath);
if (lock === undefined) {
throw new CliError(`no running pi2 daemon (${daemonJsonPath} missing)`);
}
const checkAlive = options.isPidAlive ?? defaultIsPidAlive;
const getBootId = options.bootId ?? readBootId;
const staleness = assessLock(lock, { isPidAlive: checkAlive, bootId: getBootId });
const doUnlink = options.unlink ?? ((p: string) => rmSync(p, { force: true }));
if (!staleness.live) {
doUnlink(daemonJsonPath);
doUnlink(lockPath);
throw new CliError(`no running pi2 daemon (cleaned up stale lock for pid ${lock.pid})`);
}
const killFn = options.kill ?? ((pid: number, sig: NodeJS.Signals) => process.kill(pid, sig));
const sleepFn = options.sleep ?? ((ms: number) => new Promise((res) => setTimeout(res, ms)));
const nowFn = options.now ?? Date.now;
const timeoutSec = options.timeoutSec ?? 5;
const timeoutMs = timeoutSec * 1000;
try {
killFn(lock.pid, "SIGTERM");
} catch (error) {
const err = error as NodeJS.ErrnoException;
if (err.code === "ESRCH") {
doUnlink(daemonJsonPath);
doUnlink(lockPath);
print(`pi2 daemon (pid ${lock.pid}) stopped`);
return 0;
}
if (err.code === "EPERM") {
throw new CliError(`failed to stop pi2 daemon (pid ${lock.pid}): permission denied`);
}
throw new CliError(`failed to stop pi2 daemon (pid ${lock.pid}): ${errorMessage(error)}`);
}
const pollIntervalMs = 50;
const deadline = nowFn() + timeoutMs;
let exited = false;
while (nowFn() < deadline) {
if (!checkAlive(lock.pid)) {
exited = true;
break;
}
await sleepFn(Math.min(pollIntervalMs, Math.max(1, deadline - nowFn())));
}
if (!exited && !checkAlive(lock.pid)) {
exited = true;
}
if (exited) {
doUnlink(daemonJsonPath);
doUnlink(lockPath);
print(`pi2 daemon (pid ${lock.pid}) stopped`);
return 0;
}
if (options.force === true) {
try {
killFn(lock.pid, "SIGKILL");
} catch (error) {
const err = error as NodeJS.ErrnoException;
if (err.code !== "ESRCH") {
if (err.code === "EPERM") {
throw new CliError(`failed to kill pi2 daemon (pid ${lock.pid}): permission denied`);
}
throw new CliError(`failed to kill pi2 daemon (pid ${lock.pid}): ${errorMessage(error)}`);
}
}
const killDeadline = nowFn() + 1000;
while (nowFn() < killDeadline) {
if (!checkAlive(lock.pid)) {
exited = true;
break;
}
await sleepFn(50);
}
if (!exited && !checkAlive(lock.pid)) {
exited = true;
}
if (!exited) {
throw new CliError(`pi2 daemon (pid ${lock.pid}) could not be killed with SIGKILL`);
}
doUnlink(daemonJsonPath);
doUnlink(lockPath);
print(`pi2 daemon (pid ${lock.pid}) killed with SIGKILL`);
return 0;
}
throw new CliError(`pi2 daemon (pid ${lock.pid}) did not stop within ${timeoutSec}s; use --force to kill`);
}
+11
View File
@@ -13,6 +13,17 @@ export class UsageError extends Error {
}
}
/** A user-facing failure: printed as-is, exits with `code`. */
export class CliError extends Error {
readonly code: number;
constructor(message: string, code = 1) {
super(message);
this.name = "CliError";
this.code = code;
}
}
export type FlagValue = string | boolean;
export interface FlagSpec {
+8 -7
View File
@@ -287,15 +287,16 @@ export function createApp(deps: AppDeps): Hono<Env> {
if (before !== undefined) params.before = before;
const limit = Number(c.req.query("limit"));
if (Number.isFinite(limit) && limit > 0) params.limit = Math.min(500, Math.floor(limit));
const workspaceId = c.req.query("workspaceId");
const sessionFile = c.req.query("sessionFile");
if (sessionFile) params.sessionFile = sessionFile;
const ack = workspaceId
? await router.relayWorkspaceQuery(workspaceId, "entries", params)
: await router.relaySessionQuery(c.req.param("sid"), "workspace.query", {
...params,
kind: "entries",
});
// `workspaceId` only routes the read (a disk-only row has no live owner);
// the sid still rides along so the plugin can answer from its registry.
const ack = await router.relaySessionQuery(
c.req.param("sid"),
"workspace.query",
{ ...params, kind: "entries" },
c.req.query("workspaceId"),
);
return json(200, ack);
});
+16 -2
View File
@@ -124,13 +124,27 @@ export class CommandRouter {
return this.relay(workspaceId, undefined, "workspace.query", { ...params, kind });
}
/** Relayed read used by `GET /sessions/:sid/entries`. */
/**
* Relayed read used by `GET /sessions/:sid/entries`.
*
* The sid travels on the envelope even when `workspaceIdHint` routes the read
* to an instance that does not own the session (a disk-only row): the plugin
* resolves the file from its registry, so `params.sessionFile` is a fallback,
* never a requirement. Dropping the sid here forced every workspace-scoped
* read to carry a session file, which a session does not have before its
* first entry is persisted.
*/
async relaySessionQuery(
sessionId: string,
method: string,
params: Record<string, unknown> = {},
workspaceIdHint?: string,
): Promise<Record<string, unknown>> {
const workspaceId = this.resolveWorkspace(sessionId, params);
const hint =
typeof workspaceIdHint === "string" && workspaceIdHint !== ""
? { workspaceId: workspaceIdHint }
: {};
const workspaceId = this.resolveWorkspace(sessionId, { ...params, ...hint });
return this.relay(workspaceId, sessionId, method, params);
}
+25
View File
@@ -199,6 +199,31 @@ export interface SessionState {
visible?: boolean;
/** List metadata only: the subagent task description carried by the list row. Never emitted by the reducer. */
task?: string;
/**
* List metadata only: the first user message of the session file, carried by
* the list row's disk projection. The web client shows it as the provisional
* display name while the session has no name of its own (pi2.nvim's
* `first_message` fallback). Never emitted by the reducer.
*/
firstMessage?: string | null;
/**
* List metadata only: the live projection of `Session.attached_tab`; positive
* finite number marks an nvim tab handle. Never emitted by the reducer.
*/
tab?: number | null;
/**
* List metadata only: the 1-based visual tabline position of `tab` in
* `nvim_list_tabpages()`. Absent on older plugins. Never emitted by the reducer.
*/
tabRank?: number | null;
/**
* List metadata only: creation timestamp in epoch ms. Never emitted by the reducer.
*/
createdAt?: number | null;
/**
* List metadata only: last active timestamp in epoch ms. Never emitted by the reducer.
*/
lastActiveAt?: number | null;
}
/* ------------------------------------------------------------------ */
+59
View File
@@ -658,4 +658,63 @@ describe("pi2 main", () => {
checks: [{ name: "node", status: "fail", detail: "v18.0.0" }],
});
});
it("prints stop usage for `stop --help` and `daemon stop --help`", async () => {
const out1: string[] = [];
const code1 = await main(["stop", "--help"], { out: (line) => out1.push(line) });
expect(code1).toBe(0);
expect(out1.join("\n")).toContain("pi2 stop [options]");
expect(out1.join("\n")).toContain("-f, --force");
const out2: string[] = [];
const code2 = await main(["daemon", "stop", "--help"], { out: (line) => out2.push(line) });
expect(code2).toBe(0);
expect(out2.join("\n")).toContain("pi2 stop [options]");
});
it("routes `stop` and `daemon stop` to stopRunner with parsed flags", async () => {
const calls: unknown[] = [];
const code1 = await main(["stop", "--force", "-t", "10"], {
stopRunner: async (opts) => {
calls.push(opts);
return 0;
},
});
expect(code1).toBe(0);
expect(calls[0]).toMatchObject({ force: true, timeoutSec: 10 });
calls.length = 0;
const code2 = await main(["daemon", "stop", "-f"], {
stopRunner: async (opts) => {
calls.push(opts);
return 0;
},
});
expect(code2).toBe(0);
expect(calls[0]).toMatchObject({ force: true });
});
it("rejects invalid arguments for `stop` with exit 2", async () => {
const err: string[] = [];
const code1 = await main(["stop", "extra"], { err: (line) => err.push(line) });
expect(code1).toBe(2);
expect(err[0]).toContain('unexpected argument "extra"');
err.length = 0;
const code2 = await main(["stop", "--timeout", "nope"], { err: (line) => err.push(line) });
expect(code2).toBe(2);
expect(err[0]).toContain("--timeout must be a positive integer");
});
it("reports missing daemon on `stop` with exit 1", async () => {
const err: string[] = [];
const code = await main(["stop"], {
err: (line) => err.push(line),
stopRunner: async () => {
throw new CliError("no running pi2 daemon");
},
});
expect(code).toBe(1);
expect(err[0]).toBe("pi2: no running pi2 daemon");
});
});
+192
View File
@@ -0,0 +1,192 @@
import { describe, expect, it } from "vitest";
import { runStop, type StopOptions } from "../../src/cli/stop.js";
import { CliError } from "../../src/cli/util.js";
import type { DaemonLock } from "../../src/cli/lock.js";
function mockLock(overrides: Partial<DaemonLock> = {}): DaemonLock {
return {
pid: 12345,
bootId: "boot-1",
port: 7676,
daemonId: "d-test-1",
startedAt: 1700000000000,
protocolVersion: 1,
...overrides,
};
}
describe("runStop", () => {
it("throws CliError when neither daemon.json nor daemon.lock exists", async () => {
await expect(
runStop({
readDaemonJson: () => undefined,
readLockFile: () => undefined,
}),
).rejects.toThrow("no running pi2 daemon");
});
it("cleans up stale lock and throws CliError when PID is dead", async () => {
const unlinked: string[] = [];
const lock = mockLock({ pid: 99999 });
await expect(
runStop({
readDaemonJson: () => lock,
isPidAlive: () => false,
bootId: () => "boot-1",
unlink: (p) => unlinked.push(p),
}),
).rejects.toThrow("no running pi2 daemon (cleaned up stale lock for pid 99999)");
expect(unlinked.length).toBe(2);
});
it("cleans up stale lock and throws CliError when bootId has changed", async () => {
const unlinked: string[] = [];
const lock = mockLock({ pid: 12345, bootId: "boot-old" });
await expect(
runStop({
readDaemonJson: () => lock,
isPidAlive: () => true,
bootId: () => "boot-new",
unlink: (p) => unlinked.push(p),
}),
).rejects.toThrow("no running pi2 daemon (cleaned up stale lock for pid 12345)");
expect(unlinked.length).toBe(2);
});
it("sends SIGTERM, waits for daemon to exit, and returns 0", async () => {
const signals: { pid: number; signal: NodeJS.Signals }[] = [];
const lines: string[] = [];
const unlinked: string[] = [];
let alive = true;
const code = await runStop({
readDaemonJson: () => mockLock({ pid: 12345 }),
isPidAlive: () => alive,
bootId: () => "boot-1",
kill: (pid, sig) => {
signals.push({ pid, signal: sig });
alive = false;
},
print: (line) => lines.push(line),
unlink: (p) => unlinked.push(p),
sleep: async () => {},
});
expect(code).toBe(0);
expect(signals).toEqual([{ pid: 12345, signal: "SIGTERM" }]);
expect(lines).toEqual(["pi2 daemon (pid 12345) stopped"]);
expect(unlinked.length).toBe(2);
});
it("handles ESRCH on SIGTERM cleanly as stopped", async () => {
const lines: string[] = [];
const unlinked: string[] = [];
const esrch = new Error("kill ESRCH") as NodeJS.ErrnoException;
esrch.code = "ESRCH";
const code = await runStop({
readDaemonJson: () => mockLock({ pid: 12345 }),
isPidAlive: () => true,
bootId: () => "boot-1",
kill: () => {
throw esrch;
},
print: (line) => lines.push(line),
unlink: (p) => unlinked.push(p),
});
expect(code).toBe(0);
expect(lines).toEqual(["pi2 daemon (pid 12345) stopped"]);
expect(unlinked.length).toBe(2);
});
it("throws CliError when SIGTERM fails with EPERM", async () => {
const eperm = new Error("kill EPERM") as NodeJS.ErrnoException;
eperm.code = "EPERM";
await expect(
runStop({
readDaemonJson: () => mockLock({ pid: 12345 }),
isPidAlive: () => true,
bootId: () => "boot-1",
kill: () => {
throw eperm;
},
}),
).rejects.toThrow("failed to stop pi2 daemon (pid 12345): permission denied");
});
it("throws CliError when daemon does not exit within timeout without force", async () => {
let fakeTime = 1000;
await expect(
runStop({
readDaemonJson: () => mockLock({ pid: 12345 }),
isPidAlive: () => true,
bootId: () => "boot-1",
kill: () => {},
timeoutSec: 1,
now: () => fakeTime,
sleep: async (ms) => {
fakeTime += ms;
},
}),
).rejects.toThrow("pi2 daemon (pid 12345) did not stop within 1s; use --force to kill");
});
it("escalates to SIGKILL with --force when SIGTERM times out", async () => {
const signals: { pid: number; signal: NodeJS.Signals }[] = [];
const lines: string[] = [];
const unlinked: string[] = [];
let fakeTime = 1000;
let killedWithSigkill = false;
const code = await runStop({
readDaemonJson: () => mockLock({ pid: 12345 }),
isPidAlive: () => !killedWithSigkill,
bootId: () => "boot-1",
kill: (pid, sig) => {
signals.push({ pid, signal: sig });
if (sig === "SIGKILL") killedWithSigkill = true;
},
force: true,
timeoutSec: 1,
now: () => fakeTime,
sleep: async (ms) => {
fakeTime += ms;
},
print: (line) => lines.push(line),
unlink: (p) => unlinked.push(p),
});
expect(code).toBe(0);
expect(signals).toEqual([
{ pid: 12345, signal: "SIGTERM" },
{ pid: 12345, signal: "SIGKILL" },
]);
expect(lines).toEqual(["pi2 daemon (pid 12345) killed with SIGKILL"]);
expect(unlinked.length).toBe(2);
});
it("throws CliError if daemon still alive after SIGKILL", async () => {
let fakeTime = 1000;
await expect(
runStop({
readDaemonJson: () => mockLock({ pid: 12345 }),
isPidAlive: () => true,
bootId: () => "boot-1",
kill: () => {},
force: true,
timeoutSec: 1,
now: () => fakeTime,
sleep: async (ms) => {
fakeTime += ms;
},
}),
).rejects.toThrow("pi2 daemon (pid 12345) could not be killed with SIGKILL");
});
});
+24
View File
@@ -266,6 +266,9 @@ describe("HTTP API", () => {
(call) => call.method === "workspace.query" && call.params?.kind === "entries",
);
expect(entryCall?.params).toEqual({ before: "e9", limit: 25, kind: "entries" });
// The routed sid rides on the envelope so the plugin can resolve the
// session file itself (no `sessionFile` guarantee on the wire).
expect(entryCall?.sessionId).toBe("s1");
expect((await entries.json()) as { entries: unknown[] }).toHaveProperty("entries");
const attention = await fetch(`${h.url}/api/v1/attention?workspaceId=ws-1`, authed());
@@ -277,6 +280,27 @@ describe("HTTP API", () => {
);
});
it("routes a disk-only session's entries through workspaceId but keeps the sid", async () => {
// A row from disk discovery is not owned by the live instance, so the
// workspace hint is what routes it -- and the sid must survive that.
h.instances.sessionOwners.delete("s1");
conn.commandHandler = async () =>
({ seq: 1, disposition: "started", entries: [] }) as never;
const res = await fetch(
`${h.url}/api/v1/sessions/disk-1/entries?limit=5&workspaceId=ws-1&sessionFile=${encodeURIComponent(
"/tmp/disk-1.jsonl",
)}`,
authed(),
);
expect(res.status).toBe(200);
const call = conn.commands.find(
(entry) => entry.method === "workspace.query" && entry.params?.kind === "entries",
);
expect(call?.sessionId).toBe("disk-1");
expect(call?.params).toEqual({ limit: 5, sessionFile: "/tmp/disk-1.jsonl", kind: "entries" });
});
it("returns resources and diagnostics", async () => {
h.instances.resourcesValue = {
instances: [
+25
View File
@@ -0,0 +1,25 @@
# pi2-web
React port of the pi2 web UI prototype, built into `web/dist` and served statically by `pi2 daemon`.
## Development
```bash
# Start dev server with proxy to daemon (:7676)
pnpm --dir web dev
# Typecheck
pnpm --dir web typecheck
# Run test suite
pnpm --dir web exec vitest run
# Run only changed tests or specific file
pnpm --dir web exec vitest run --changed
pnpm --dir web exec vitest run tests/chat.composer.test.tsx
# Watch mode
pnpm --dir web test
```
For performance tuning, concurrency settings, and DOM environment details, see [docs/testing.md](../docs/testing.md).
+17
View File
@@ -8,6 +8,8 @@ import { PagePill } from "@/components/shared/page-pill";
import { PrefsMenu } from "@/components/shared/prefs-menu";
import { ServerChip } from "@/components/shared/server-chip";
import { clearPairMeta } from "@/features/connect/pairing";
import { useHealthQuery } from "@/features/status/queries";
import { resolveServerStatus } from "@/features/status/server";
import { api, getDeviceToken, onUnauthorized } from "@/lib/api";
import { CONNECT_PATH, safeNext } from "@/lib/routing";
import { defaultWsUrl, PiWsClient, type WsConnectionState } from "@/lib/ws";
@@ -99,6 +101,7 @@ export function AppShell() {
const href = useRouterState({ select: (state) => state.location.href });
const paired = useConnectionStore((state) => state.paired);
const setServer = useConnectionStore((state) => state.setServer);
const setServerStatus = useConnectionStore((state) => state.setServerStatus);
const wsState = useConnectionStore((state) => state.wsState);
const setWsState = useConnectionStore((state) => state.setWsState);
const disconnect = useConnectionStore((state) => state.disconnect);
@@ -116,11 +119,25 @@ export function AppShell() {
staleTime: 30_000,
retry: 1,
});
const health = useHealthQuery(paired && !isConnect);
const healthOk = health.data?.ok ?? (health.data ? health.data.items.every((item) => item.ok) : undefined);
useEffect(() => {
if (info.data) setServer(info.data);
}, [info.data, setServer]);
useEffect(() => {
setServerStatus(
resolveServerStatus({
paired,
info: info.data,
infoError: info.isError,
healthError: health.isError,
healthOk,
}),
);
}, [health.isError, healthOk, info.data, info.isError, paired, setServerStatus]);
useEffect(() => {
document.body.dataset.page = page;
}, [page]);
@@ -5,6 +5,7 @@ import { useTranslation } from "react-i18next";
import { Icon, type IconName } from "@/components/icons";
import { NAV } from "@/components/shared/nav-list";
import { sessionTitle } from "@/features/chat/session-title";
import { cn } from "@/lib/utils";
import { useSessionsStore } from "@/stores/sessions";
import { useWorkspacesStore } from "@/stores/workspaces";
@@ -76,7 +77,10 @@ export function CommandPalette({ open, onOpenChange }: CommandPaletteProps) {
id: `session-${session.sessionId}`,
group: groupSessions,
icon: "chat",
label: session.name ?? session.sessionId,
label: sessionTitle(session, {
unnamed: t("chat.sessionUnnamed"),
subagentUnnamed: t("chat.subagentUnnamed"),
}).text,
hint: t(`state.${session.status}`),
keywords: `${session.sessionId} ${session.model?.id ?? ""} ${session.cwd}`,
href: `/chat/${encodeURIComponent(session.sessionId)}`,
+2 -2
View File
@@ -57,10 +57,10 @@ export interface NavListProps {
export function NavList({ variant, page }: NavListProps) {
const { t } = useTranslation();
const server = useConnectionStore((state) => state.server);
const status = useConnectionStore((state) => state.serverStatus);
const status = server?.status ?? "offline";
const name = server?.name ?? "pi2.nvim";
const version = server?.pluginVersion ?? server?.version ?? "";
const version = server?.pluginVersion || server?.version || "";
const serverTip = t("shell.railServerTip", { name, status: t(`state.${status}`), version });
const connectTip = t("shell.connection");
+3 -2
View File
@@ -32,10 +32,11 @@ export function PageSheet({ open, onOpenChange, page, onSearch, returnFocusTo }:
const workspaces = useWorkspacesStore((state) => state.items);
const byWorkspace = useSessionsStore((state) => state.byWorkspace);
const server = useConnectionStore((state) => state.server);
const serverStatus = useConnectionStore((s) => s.serverStatus);
const sessionCount = Object.values(byWorkspace).reduce((total, list) => total + list.length, 0);
const status = server?.status ?? "unknown";
const version = server?.pluginVersion ?? server?.version ?? "";
const status = serverStatus;
const version = server?.pluginVersion || server?.version || "";
function fact(key: NavKey): string {
if (key === "workspaces") return t("shell.pageFactWorkspaces", { n: workspaces.length });
+1 -1
View File
@@ -18,12 +18,12 @@ export interface ServerChipProps {
export function ServerChip({ server: override, className }: ServerChipProps) {
const { t } = useTranslation();
const stored = useConnectionStore((state) => state.server);
const status = useConnectionStore((state) => state.serverStatus);
const server = override ?? stored;
const name = server?.name ?? "pi2.nvim";
const hostname =
server?.hostname ?? (typeof window !== "undefined" ? window.location.hostname || "localhost" : "localhost");
const status = server?.status ?? "offline";
const dot = serverDotClass(status);
const dotStatus = dot.replace("dot--", "") as "ok" | "attention" | "exited" | "idle";
+8 -47
View File
@@ -1,7 +1,7 @@
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";
export type DotStatus = "busy" | "compacting" | "idle" | "ok" | "err" | "attention" | "exited" | "dead";
export const DOT_CLASS: Record<DotStatus, string> = {
busy: "dot--busy",
@@ -11,6 +11,7 @@ export const DOT_CLASS: Record<DotStatus, string> = {
err: "dot--err",
attention: "dot--attention",
exited: "dot--exited",
dead: "dot--dead",
};
export type ServerStatus = "online" | "degraded" | "offline";
@@ -24,62 +25,22 @@ export function serverDotClass(status: ServerStatus | string | null | undefined)
return DOT_CLASS.idle;
}
export type SubagentStatus = "active" | "completed" | "failed" | "interrupted" | "dormant";
export function subagentDotClass(status: SubagentStatus | string): string {
switch (status) {
case "active":
return DOT_CLASS.busy;
case "completed":
return DOT_CLASS.ok;
case "failed":
return DOT_CLASS.err;
case "interrupted":
return DOT_CLASS.attention;
case "dormant":
return DOT_CLASS.exited;
default:
return DOT_CLASS.idle;
}
}
export type SessionStatus = "starting" | "busy" | "compacting" | "idle" | "exited" | "interrupted" | "attention" | "done" | "error";
export function sessionDotClass(status: SessionStatus | string): string {
switch (status) {
case "busy":
case "starting":
return DOT_CLASS.busy;
case "compacting":
return DOT_CLASS.compacting;
case "interrupted":
case "attention":
return DOT_CLASS.attention;
case "done":
return DOT_CLASS.ok;
case "error":
return DOT_CLASS.err;
case "exited":
return DOT_CLASS.exited;
case "idle":
return DOT_CLASS.idle;
default:
return DOT_CLASS.idle;
}
}
export interface StatusDotProps {
status: DotStatus;
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, ...rest }: StatusDotProps) {
export function StatusDot({ status, title, className, steady, current, ...rest }: StatusDotProps) {
return (
<span
className={cn("dot", DOT_CLASS[status], className)}
className={cn("dot", DOT_CLASS[status], steady && "dot--steady", current && "dot--current", className)}
title={title}
aria-label={title}
aria-hidden={title ? undefined : true}
+20 -12
View File
@@ -14,7 +14,9 @@ import {
normalizeSessionSummary,
normalizeSessionsPayload,
normalizeSnapshotState,
tabSessionRows,
} from "./session-state";
import { firstRootSession } from "./session-order";
import { setSessionMeta } from "./history";
import { migrateSessionId } from "./migration";
import { useChatStore } from "./store";
@@ -148,7 +150,13 @@ export interface ChatSessions {
refetch: () => void;
}
/** Sessions of one workspace, merged into the shared store (live state wins). */
/**
* Sessions of one workspace, merged into the shared store (live state wins).
*
* "Sessions" here means the nvim tab set — `tab`-backed rows plus the sessions
* linked to them through `parentId` (see `tabSessionRows`). The plugin's list
* also carries every JSONL on disk, which is history, not a tab.
*/
export function useChatSessions(workspaceId: string | undefined, enabled: boolean): ChatSessions {
const query = useQuery({
queryKey: ["chat-sessions", workspaceId],
@@ -162,18 +170,18 @@ export function useChatSessions(workspaceId: string | undefined, enabled: boolea
useEffect(() => {
if (!workspaceId || !query.data) return;
const raw = query.data as { sessions?: Array<{ sessionId?: unknown; sessionFile?: unknown }> } | undefined;
for (const row of raw?.sessions ?? []) {
if (typeof row?.sessionId === "string") {
setSessionMeta(row.sessionId, {
workspaceId,
sessionFile: typeof row.sessionFile === "string" ? row.sessionFile : undefined,
});
}
// The payload is the union of the workspace's JSONL history and its live
// sessions; the console renders the nvim tab set only, so a historical
// row can never look like a tab (and never receives a prompt).
const rows = tabSessionRows(query.data);
for (const row of rows) {
const sessionId = str(row.sessionId) ?? str(row.session_id) ?? str(row.id);
if (!sessionId) continue;
setSessionMeta(sessionId, { workspaceId, sessionFile: str(row.sessionFile) });
}
const current = useSessionsStore.getState();
const existing = current.byWorkspace[workspaceId] ?? [];
const next = normalizeSessionsPayload(query.data, workspaceId, existing);
const next = normalizeSessionsPayload(rows, workspaceId, existing);
current.setSessions(workspaceId, next);
}, [workspaceId, query.data]);
@@ -323,7 +331,7 @@ export interface SessionLookup {
* A non-empty `sessionId` that the loaded list does not contain resolves to
* `undefined` — falling back to `sessions[0]` would silently show a different
* session for an unknown deep link. The first-session fallback stays for the
* `/chat` index (no id), which means "the workspace's most recent root session"
* `/chat` index (no id), which means "the sidebar's top row: the root in canonical order"
* (a sub-session row is never the index default).
*
* @param sessionId Route session id (`undefined` on `/chat`).
@@ -336,7 +344,7 @@ export function useSessionLookup(
loaded: boolean,
): SessionLookup {
return useMemo(() => {
if (!sessionId) return { session: sessions.find((session) => !session.parentId) ?? sessions[0], missing: false };
if (!sessionId) return { session: firstRootSession(sessions), missing: false };
const match = sessions.find((session) => session.sessionId === sessionId);
if (match) return { session: match, missing: false };
return { session: undefined, missing: loaded };
+22 -9
View File
@@ -34,17 +34,25 @@ export function remapSessionMeta(from: string, to: string): void {
if (meta) sessionMeta.set(to, { ...sessionMeta.get(to), ...meta });
}
/** `GET /api/v1/sessions/:sid/entries?before=&limit=&workspaceId=&sessionFile=` → raw pi entries + cursor. */
/**
* `GET /api/v1/sessions/:sid/entries?before=&limit=&workspaceId=&sessionFile=` → raw pi entries + cursor.
*
* `workspaceId` is the caller's routing hint (the page knows the workspace it is
* showing): the daemon needs it to reach the right instance for a row that is
* not live, and it must not depend on the list effect having filled
* `sessionMeta` first. `sessionFile` stays metadata-driven — it is a fallback
* for the plugin, which resolves the file from the session id itself.
*/
export async function fetchEntriesPage(
sessionId: string,
before?: string,
limit = HISTORY_PAGE_SIZE,
signal?: AbortSignal,
options: { before?: string; limit?: number; signal?: AbortSignal; workspaceId?: string } = {},
): Promise<FetchedPage> {
const { before, limit = HISTORY_PAGE_SIZE, signal, workspaceId } = options;
const query = new URLSearchParams({ limit: String(limit) });
if (before) query.set("before", before);
const meta = sessionMeta.get(sessionId);
if (meta?.workspaceId) query.set("workspaceId", meta.workspaceId);
const routedWorkspace = workspaceId ?? meta?.workspaceId;
if (routedWorkspace) query.set("workspaceId", routedWorkspace);
if (meta?.sessionFile) query.set("sessionFile", meta.sessionFile);
const raw = await apiRequest<unknown>(
`/api/v1/sessions/${encodeURIComponent(sessionId)}/entries?${query.toString()}`,
@@ -82,11 +90,16 @@ export interface SessionHistory {
/**
* Historical pages merged with the live snapshot entries (live wins by id).
* Paging is backwards (`before` cursor) and dedupes by entry id.
*
* `workspaceId` is the routing hint for the entries relay (see
* `fetchEntriesPage`); it is nullable because `/chat` can render before a
* workspace is resolved.
*/
export function useSessionHistory(
sessionId: string | null | undefined,
liveEntries: Entry[],
enabled = true,
workspaceId?: string | null,
): SessionHistory {
const history = useChatStore((state) =>
sessionId ? (state.history[sessionId] ?? EMPTY_HISTORY) : EMPTY_HISTORY,
@@ -100,7 +113,7 @@ export function useSessionHistory(
const seq = nextRequest(sessionId);
useChatStore.getState().beginInitial(sessionId);
void fetchEntriesPage(sessionId)
void fetchEntriesPage(sessionId, { workspaceId: workspaceId ?? undefined })
.then((page) => {
if (!isCurrent(sessionId, seq)) return;
useChatStore.getState().receiveInitial(sessionId, page.entries, page.cursor);
@@ -111,7 +124,7 @@ export function useSessionHistory(
useChatStore.getState().historyError(sessionId, message);
});
// `token` is the resync generation; `sessionId`/`enabled` gate loading.
}, [sessionId, enabled, token]);
}, [sessionId, enabled, token, workspaceId]);
const loadOlder = useCallback(() => {
if (!sessionId) return;
@@ -122,7 +135,7 @@ export function useSessionHistory(
const seq = nextRequest(sessionId);
useChatStore.getState().beginOlder(sessionId);
void fetchEntriesPage(sessionId, before)
void fetchEntriesPage(sessionId, { before, workspaceId: workspaceId ?? undefined })
.then((page) => {
if (!isCurrent(sessionId, seq)) return;
useChatStore.getState().receiveOlder(sessionId, page.entries, page.cursor);
@@ -132,7 +145,7 @@ export function useSessionHistory(
const message = error instanceof ApiError ? error.code : error instanceof Error ? error.message : String(error);
useChatStore.getState().historyError(sessionId, message);
});
}, [sessionId]);
}, [sessionId, workspaceId]);
const retry = useCallback(() => {
if (!sessionId) return;
+65 -6
View File
@@ -1,6 +1,6 @@
import type { Batch, Entry, QueueItem, SessionState, Subagent, TodoItem } from "@protocol/types";
import { useVirtualizer } from "@tanstack/react-virtual";
import { useCallback, useLayoutEffect, useRef, useState } from "react";
import { useCallback, useEffect, useLayoutEffect, useRef, useState } from "react";
import { useTranslation } from "react-i18next";
import { Icon } from "@/components/icons";
@@ -121,18 +121,50 @@ export function MessageStream({
const queued = allItems.filter((item) => item.kind === "queued");
const steerAll = steerAllOf(session.queue);
const scrollRef = useRef<HTMLDivElement | null>(null);
const listRef = useRef<HTMLDivElement | null>(null);
const [following, setFollowing] = useState(true);
const followingRef = useRef(true);
const pendingPrepend = useRef<number | null>(null);
const loadRequested = useRef(false);
const rafRef = useRef<number | null>(null);
/** Last observed `scrollTop`, so only an *upward* move counts as "stop following". */
const lastTopRef = useRef<number | null>(null);
/** Explicit scroll input (wheel / touch / keys / pointer drag) is the only way to stop following. */
const userInputRef = useRef(false);
const inputTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
/** A smooth FAB scroll is in flight; instant pins would fight it. */
const smoothUntilRef = useRef(0);
const setFollow = useCallback((value: boolean) => {
followingRef.current = value;
setFollowing(value);
}, []);
/**
* Mark an explicit user scroll. `following` must never be cleared by content
* growth: the virtualizer measures real item heights after its estimated
* pass, so `scrollHeight` jumps while the view sits still — treating that
* as a user scroll froze the stream one or more screens above the newest
* entry (the stream then looked stuck at an old message).
*/
const markScrollInput = useCallback(() => {
userInputRef.current = true;
if (inputTimerRef.current) clearTimeout(inputTimerRef.current);
inputTimerRef.current = setTimeout(() => {
inputTimerRef.current = null;
userInputRef.current = false;
}, 500);
}, []);
useEffect(
() => () => {
if (inputTimerRef.current) clearTimeout(inputTimerRef.current);
},
[],
);
const virtualize = items.length >= VIRTUALIZE_THRESHOLD;
const hasItems = items.length > 0;
const virtualizer = useVirtualizer({
count: items.length,
getScrollElement: () => scrollRef.current,
@@ -153,7 +185,7 @@ export function MessageStream({
// Streaming keeps the DOM height changing; stay pinned while following.
useLayoutEffect(() => {
if (!followingRef.current) return;
if (!followingRef.current || Date.now() < smoothUntilRef.current) return;
if (rafRef.current != null) cancelAnimationFrame(rafRef.current);
rafRef.current = requestAnimationFrame(() => {
rafRef.current = requestAnimationFrame(() => {
@@ -163,6 +195,20 @@ export function MessageStream({
});
});
// A one-shot rAF after render lands short of the end: the virtualizer reports
// real heights only after its estimated pass, and images/tool output load
// later still. Observe the list so every real height change re-pins while
// the user is following.
useEffect(() => {
const list = listRef.current;
if (!list || typeof ResizeObserver === "undefined") return;
const observer = new ResizeObserver(() => {
if (followingRef.current && Date.now() >= smoothUntilRef.current) scrollToBottom(false);
});
observer.observe(list);
return () => observer.disconnect();
}, [scrollToBottom, virtualize, hasItems]);
useLayoutEffect(() => {
const element = scrollRef.current;
const previous = pendingPrepend.current;
@@ -176,9 +222,16 @@ export function MessageStream({
const handleScroll = useCallback(() => {
const element = scrollRef.current;
if (!element) return;
const distance = element.scrollHeight - element.scrollTop - element.clientHeight;
setFollow(distance < 80);
if (element.scrollTop < 120 && hasMore && !loadingOlder && !loadRequested.current) {
const top = element.scrollTop;
const previous = lastTopRef.current;
lastTopRef.current = top;
const distance = element.scrollHeight - top - element.clientHeight;
// Re-arm at the bottom. Only explicit input that actually moved the view
// *up* may stop following — growth-driven scroll positions (virtualizer
// measurements, streamed text, late images) must never freeze the pin.
if (distance < 80) setFollow(true);
else if (userInputRef.current && (previous === null || top < previous - 2)) setFollow(false);
if (top < 120 && hasMore && !loadingOlder && !loadRequested.current) {
loadRequested.current = true;
pendingPrepend.current = element.scrollHeight;
onLoadOlder();
@@ -268,6 +321,7 @@ export function MessageStream({
{items.length ? (
virtualize ? (
<div
ref={listRef}
className="stream-list stream-inner stream-list--virtual"
style={{ height: `${virtualizer.getTotalSize()}px` }}
>
@@ -290,7 +344,7 @@ export function MessageStream({
})}
</div>
) : (
<div className="stream-list stream-inner">
<div ref={listRef} className="stream-list stream-inner">
{items.map((item) => (
<div className={itemClassName(item)} key={item.key}>
{renderItem(item)}
@@ -329,6 +383,10 @@ export function MessageStream({
aria-live="polite"
aria-label={t("chat.streamAria")}
onScroll={handleScroll}
onWheel={markScrollInput}
onTouchMove={markScrollInput}
onKeyDown={markScrollInput}
onPointerDown={markScrollInput}
>
{status}
{body}
@@ -342,6 +400,7 @@ export function MessageStream({
title={t("chat.backToLatest")}
onClick={() => {
setFollow(true);
smoothUntilRef.current = Date.now() + 700;
scrollToBottom(true);
}}
>
+224
View File
@@ -0,0 +1,224 @@
import type { SessionState } from "@protocol/types";
/**
* Canonical ordering for workspace session trees in the pi2d web console.
*
* Rules taken from pi2.nvim:
* - Root order: visual tabline position of live attached tabs (`lua/pi/sessions/manager.lua`).
* A lineage occupies the earliest tab slot of the root and all its descendants (`lua/pi/ui/sessions.lua`),
* so in a child view the parent row occupies that tab's slot.
* - Sibling order: children of the same parent (merged real child session rows and
* synthetic manifest subagents) are sorted by `createdAt` DESC (missing last),
* tie-break `id` ASC (`lua/pi/subsessions/manifest.lua`). Real session rows win over
* same-id subagents, but inherit the manifest entry's `createdAt`.
*
* Console-side determinism & edge-case additions:
* - Tie-break chain: `createdAt` DESC (missing last) → `lastActiveAt` DESC (missing last) →
* `sessionId` ASC (plain code-unit comparison). In Neovim each session has at most one
* attached tab and ranks are distinct, so it needs no tie-break; the console defines this
* chain to ensure total, deterministic ordering across WS arrivals.
* - Tab-less roots: Neovim's `Sessions.list()` excludes detached/tab-less sessions entirely.
* The console keeps a tab-less root when it is the parent of a live child-view tab (or
* an orphaned/promoted row); assigning it rank `+Infinity` (placed last) is a console rule.
* - Rank unit: rows prefer `tabRank` (1-based visual tabline position in `nvim_list_tabpages()`),
* falling back to `tab` (creation-ordered tab handle). Handle order diverges from visual order
* after `:tabmove` or mid-tabline insertions (`:PiNewTab` from tab 1).
* - Comparisons are plain code-unit `<`/`>` (never `localeCompare`) and numeric for
* timestamps, guaranteeing total, deterministic ordering.
*/
export interface SiblingItem {
createdAt?: number | null;
id: string;
}
/**
* Effective parent id: the parent must exist in `index`, must not point to
* itself, and must not form a parent-pointer cycle. Any invalid parent promotes
* the session to a root so a row is never lost.
*/
export function effectiveParentOf(session: SessionState, index: Map<string, SessionState>): string | null {
const parentId = session.parentId ?? null;
if (!parentId || parentId === session.sessionId || !index.has(parentId)) return null;
const seen = new Set<string>([session.sessionId]);
let cursor: string | null = parentId;
while (cursor) {
if (seen.has(cursor)) return null;
seen.add(cursor);
const next: string | null = index.get(cursor)?.parentId ?? null;
if (!next || next === cursor) break;
cursor = next;
}
return parentId;
}
/**
* Sibling comparator: `createdAt` DESC (missing last), tie-break `id` ASC.
* Comparisons are plain string `<`/`>` (never `localeCompare`).
*/
export function compareSiblings(a: SiblingItem, b: SiblingItem): number {
const ca = typeof a.createdAt === "number" && Number.isFinite(a.createdAt) ? a.createdAt : null;
const cb = typeof b.createdAt === "number" && Number.isFinite(b.createdAt) ? b.createdAt : null;
if (ca !== null && cb !== null) {
if (ca !== cb) return cb - ca;
} else if (ca !== null) {
return -1;
} else if (cb !== null) {
return 1;
}
if (a.id < b.id) return -1;
if (a.id > b.id) return 1;
return 0;
}
function positiveNum(value: unknown): number | undefined {
return typeof value === "number" && Number.isFinite(value) && value > 0 ? value : undefined;
}
/**
* Tab position rank for a single row: prefer visual tabline rank (`tabRank`, 1-based
* position in `nvim_list_tabpages()`), fall back to tab handle (`tab`, creation-ordered).
* Visual rank reflects `:tabmove` and mid-tabline insertions; handle is legacy fallback.
*/
function rowTabRank(session: SessionState): number | undefined {
return positiveNum(session.tabRank) ?? positiveNum(session.tab);
}
/**
* Calculate the rank of a root session: the earliest tab position occupied across
* its whole lineage (root itself and all descendants), or `Infinity` if tab-less.
* pi2.nvim places a lineage at its earliest live tab slot (`lua/pi/ui/sessions.lua`).
*/
function rootRank(session: SessionState, childSessions: Map<string | null, SessionState[]>): number {
const ownRank = rowTabRank(session);
let minTab = Infinity;
const visited = new Set<string>([session.sessionId]);
const stack = [...(childSessions.get(session.sessionId) ?? [])];
while (stack.length > 0) {
const child = stack.pop()!;
if (visited.has(child.sessionId)) continue;
visited.add(child.sessionId);
const childRank = rowTabRank(child);
if (childRank !== undefined && childRank < minTab) {
minTab = childRank;
}
for (const grandchild of childSessions.get(child.sessionId) ?? []) {
stack.push(grandchild);
}
}
return Math.min(ownRank ?? Infinity, minTab);
}
/**
* Compare two root sessions:
* 1. `rank` ASC
* 2. `createdAt` DESC (missing last)
* 3. `lastActiveAt` DESC (missing last)
* 4. `sessionId` ASC (code-unit comparison)
*/
function compareRoots(
a: SessionState,
b: SessionState,
rankA: number,
rankB: number,
): number {
if (rankA !== rankB) {
return rankA - rankB;
}
const ca = typeof a.createdAt === "number" && Number.isFinite(a.createdAt) ? a.createdAt : null;
const cb = typeof b.createdAt === "number" && Number.isFinite(b.createdAt) ? b.createdAt : null;
if (ca !== null && cb !== null) {
if (ca !== cb) return cb - ca;
} else if (ca !== null) {
return -1;
} else if (cb !== null) {
return 1;
}
const la = typeof a.lastActiveAt === "number" && Number.isFinite(a.lastActiveAt) ? a.lastActiveAt : null;
const lb = typeof b.lastActiveAt === "number" && Number.isFinite(b.lastActiveAt) ? b.lastActiveAt : null;
if (la !== null && lb !== null) {
if (la !== lb) return lb - la;
} else if (la !== null) {
return -1;
} else if (lb !== null) {
return 1;
}
if (a.sessionId < b.sessionId) return -1;
if (a.sessionId > b.sessionId) return 1;
return 0;
}
/**
* Flatten sessions into canonical document order:
* Each root (Rule 1: rank ASC, createdAt DESC, lastActiveAt DESC, sessionId ASC)
* followed by its subtree in Rule 3 sibling order (createdAt DESC, id ASC).
*
* Input is deduped by `sessionId` (first wins) and cycle-guarded.
*/
export function orderSessions(sessions: readonly SessionState[]): SessionState[] {
const index = new Map<string, SessionState>();
const deduped: SessionState[] = [];
for (const session of sessions) {
if (!session.sessionId || index.has(session.sessionId)) continue;
index.set(session.sessionId, session);
deduped.push(session);
}
if (deduped.length === 0) return [];
const childSessions = new Map<string | null, SessionState[]>();
for (const session of deduped) {
const parentId = effectiveParentOf(session, index);
const list = childSessions.get(parentId);
if (list) list.push(session);
else childSessions.set(parentId, [session]);
}
const roots = [...(childSessions.get(null) ?? [])];
const ranks = new Map<string, number>();
for (const root of roots) {
ranks.set(root.sessionId, rootRank(root, childSessions));
}
roots.sort((a, b) => compareRoots(a, b, ranks.get(a.sessionId)!, ranks.get(b.sessionId)!));
for (const [parentId, children] of childSessions.entries()) {
if (parentId === null) continue;
children.sort((a, b) =>
compareSiblings(
{ createdAt: a.createdAt, id: a.sessionId },
{ createdAt: b.createdAt, id: b.sessionId },
),
);
}
const result: SessionState[] = [];
const visited = new Set<string>();
function appendSubtree(session: SessionState) {
if (visited.has(session.sessionId)) return;
visited.add(session.sessionId);
result.push(session);
const children = childSessions.get(session.sessionId) ?? [];
for (const child of children) {
appendSubtree(child);
}
}
for (const root of roots) {
appendSubtree(root);
}
return result;
}
/**
* Return the top root session of the sidebar (for the `/chat` index default).
*/
export function firstRootSession(sessions: readonly SessionState[]): SessionState | undefined {
const ordered = orderSessions(sessions);
if (ordered.length === 0) return undefined;
const index = new Map(ordered.map((s) => [s.sessionId, s]));
return ordered.find((s) => effectiveParentOf(s, index) === null) ?? ordered[0];
}
+235 -10
View File
@@ -35,6 +35,10 @@ export interface EmptySessionInput {
parentId?: string | null;
visible?: boolean;
task?: string;
tab?: number | null;
tabRank?: number | null;
createdAt?: number | null;
lastActiveAt?: number | null;
}
export function emptySessionState(input: EmptySessionInput): SessionState {
@@ -62,6 +66,10 @@ export function emptySessionState(input: EmptySessionInput): SessionState {
...(input.parentId !== undefined ? { parentId: input.parentId } : {}),
...(input.visible !== undefined ? { visible: input.visible } : {}),
...(input.task !== undefined ? { task: input.task } : {}),
...(input.tab !== undefined ? { tab: input.tab } : {}),
...(input.tabRank !== undefined ? { tabRank: input.tabRank } : {}),
...(input.createdAt !== undefined ? { createdAt: input.createdAt } : {}),
...(input.lastActiveAt !== undefined ? { lastActiveAt: input.lastActiveAt } : {}),
};
}
@@ -235,6 +243,48 @@ export function applySessionEvent(state: SessionState, event: SessionEvent): Ses
return next;
}
function positiveNum(value: unknown): number | undefined {
return typeof value === "number" && Number.isFinite(value) && value > 0 ? value : undefined;
}
function epochMs(value: unknown): number | undefined {
if (typeof value === "number" && Number.isFinite(value)) return value;
if (typeof value === "string") {
const parsed = Date.parse(value);
if (Number.isFinite(parsed)) return parsed;
}
return undefined;
}
function summaryTab(record: Record<string, unknown>, base?: SessionState): number | null {
if (!("tab" in record) && !("attached_tab" in record)) return base?.tab ?? null;
const raw = record.tab !== undefined ? record.tab : record.attached_tab;
if (raw === undefined) return base?.tab ?? null;
if (raw === null) return null;
return positiveNum(raw) ?? null;
}
function summaryTabRank(record: Record<string, unknown>, base?: SessionState): number | null {
if (!("tabRank" in record) && !("tab_rank" in record)) return base?.tabRank ?? null;
const raw = record.tabRank !== undefined ? record.tabRank : record.tab_rank;
if (raw === undefined) return base?.tabRank ?? null;
if (raw === null) return null;
return positiveNum(raw) ?? null;
}
function summaryEpoch(
record: Record<string, unknown>,
camelKey: string,
snakeKey: string,
fallback?: number | null,
): number | null {
if (!(camelKey in record) && !(snakeKey in record)) return fallback ?? null;
const raw = record[camelKey] !== undefined ? record[camelKey] : record[snakeKey];
if (raw === undefined) return fallback ?? null;
if (raw === null) return null;
return epochMs(raw) ?? null;
}
/** `parentId` as carried by a list row: string → value, explicit null → `null`. */
function summaryParentId(record: Record<string, unknown>, base: SessionState): string | null {
if (!("parentId" in record) && !("parent_id" in record)) return base.parentId ?? null;
@@ -260,6 +310,10 @@ export function normalizeSnapshotState(
const parentId = str(candidate.parentId ?? candidate.parent_id) ?? existing?.parentId ?? null;
const visible = typeof candidate.visible === "boolean" ? candidate.visible : (existing?.visible ?? true);
const task = str(candidate.task) ?? existing?.task;
const tab = summaryTab(candidate, existing);
const tabRank = summaryTabRank(candidate, existing);
const createdAt = summaryEpoch(candidate, "createdAt", "created_at", existing?.createdAt ?? null);
const lastActiveAt = summaryEpoch(candidate, "lastActiveAt", "last_active_at", existing?.lastActiveAt ?? null);
const state: SessionState = {
...base,
...candidate,
@@ -268,6 +322,10 @@ export function normalizeSnapshotState(
parentId,
visible,
...(task !== undefined ? { task } : {}),
tab,
tabRank,
createdAt,
lastActiveAt,
flags: {
attention: candidate.flags ? rec(candidate.flags)?.attention === true : false,
done: rec(candidate.flags)?.done === true,
@@ -321,6 +379,10 @@ export function normalizeSessionSummary(raw: unknown, workspaceId: string, exist
const thinkingValue = str(record.thinking);
const hasQueue = Array.isArray(record.queue);
const task = str(record.task) ?? base.task;
// Provisional display name: the list row's disk projection of the session's
// first user message (pi2.nvim's `first_message` fallback). Absent means
// "not carried", `null` means "there is none".
const firstMessage = record.firstMessage === null ? null : str(record.firstMessage);
return {
...base,
sessionId,
@@ -346,9 +408,88 @@ export function normalizeSessionSummary(raw: unknown, workspaceId: string, exist
parentId: summaryParentId(record, base),
visible: typeof record.visible === "boolean" ? record.visible : base.visible,
...(task !== undefined ? { task } : {}),
...(firstMessage !== undefined ? { firstMessage } : {}),
tab: summaryTab(record, base),
tabRank: summaryTabRank(record, base),
createdAt: summaryEpoch(record, "createdAt", "created_at", base.createdAt),
lastActiveAt: summaryEpoch(record, "lastActiveAt", "last_active_at", base.lastActiveAt),
};
}
/** `sessionId` of a raw list row (`sessionId` is the wire field; aliases are tolerated). */
function rawSessionId(row: Record<string, unknown>): string {
return str(row.sessionId) ?? str(row.session_id) ?? str(row.id) ?? "";
}
/** `parentId` of a raw list row; `null` means a root. */
function rawParentId(row: Record<string, unknown>): string | null {
return str(row.parentId) ?? str(row.parent_id) ?? null;
}
/** A row is a tab when the plugin's live projection carries `attached_tab`. */
function hasTab(row: Record<string, unknown>): boolean {
return typeof row.tab === "number" && Number.isFinite(row.tab) && row.tab > 0;
}
/**
* Restrict a `workspace.query{kind:"sessions"}` payload to the sessions nvim's
* list renders.
*
* The plugin answers with the union of the workspace's session JSONL files on
* disk (`History.list()`) and its live sessions, so a tab-less root row is
* *history*, not a tab: it has no live owner and a command routed to it answers
* `E_SESSION_NOT_FOUND`. nvim's `:PiSessions` is `Sessions.list()` — the
* sessions attached to a tabpage — plus their children, and `tab` is the live
* projection of `Session.attached_tab`.
*
* So keep the connected component (through `parentId`, in both directions) of
* every row that carries a `tab`: the tabs themselves, the sub-sessions below
* them, and the parent row when a tab is in a child view. Everything else is
* disk history and stays out of the console (it is a `session.resume` target,
* never a prompt target).
*/
export function tabSessionRows(raw: unknown): Record<string, unknown>[] {
const record = rec(raw);
const list = Array.isArray(raw) ? raw : arr(record?.sessions ?? record?.items);
const rows: Record<string, unknown>[] = [];
for (const entry of list) {
const row = rec(entry);
if (row) rows.push(row);
}
// Parent links both ways; a duplicate id (a list race) keeps its first row.
const parentOf = new Map<string, string>();
const childrenOf = new Map<string, string[]>();
for (const row of rows) {
const id = rawSessionId(row);
if (id === "" || parentOf.has(id)) continue;
const parentId = rawParentId(row);
parentOf.set(id, parentId ?? "");
if (parentId !== null && parentId !== "") {
const siblings = childrenOf.get(parentId);
if (siblings) siblings.push(id);
else childrenOf.set(parentId, [id]);
}
}
const keep = new Set<string>();
const stack: string[] = [];
for (const row of rows) {
const id = rawSessionId(row);
if (id !== "" && hasTab(row)) stack.push(id);
}
while (stack.length > 0) {
const id = stack.pop();
if (id === undefined || keep.has(id)) continue;
keep.add(id);
const parentId = parentOf.get(id);
if (parentId) stack.push(parentId);
for (const childId of childrenOf.get(id) ?? []) stack.push(childId);
}
return rows.filter((row) => keep.has(rawSessionId(row)));
}
/** Parse `{sessions:[...]}` (also bare arrays) into render states. */
export function normalizeSessionsPayload(
raw: unknown,
@@ -367,16 +508,100 @@ function attentionPending(state: SessionState): boolean {
return state.flags.attention || state.attention.length > 0;
}
/** `:PiSessions` status matrix → base.css dot class. */
export function sessionDot(state: SessionState): DotStatus {
if (attentionPending(state)) return "attention";
if (state.status === "busy" || state.status === "starting") return "busy";
if (state.status === "compacting") return "compacting";
if (state.status === "interrupted") return "attention";
if (state.status === "exited") return "exited";
if (state.flags.error) return "err";
if (state.flags.done) return "ok";
return "idle";
/**
* A dot render decision: the base status plus the two overlay modifiers.
* `steady` pins the dot solid, `current` paints the "you are here" overlay.
*/
export interface DotView {
status: DotStatus;
steady?: boolean;
current?: boolean;
}
/**
* The current-tab marker: `:PiSessions` paints the dot of the session its tab is
* showing in agent blue, steady while idle and blinking while busy, and never on
* top of a notification colour (`dot_hl` outranks it — see
* `refresh_current_markers`). The browser's analogue is the row the user has
* open. A focused `compacting` session blinks at the busy rate, not half speed.
*/
function withCurrent(view: DotView, state: SessionState, viewed: boolean): DotView {
if (!viewed) return view;
if (state.flags.error || state.flags.done || attentionPending(state)) return view;
// 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 };
}
/**
* `:PiSessions` parent row matrix (`dot_hl`, priority order): exited > error >
* attention > done > busy > compacting > idle. `interrupted` is the wire's
* "the process died badly" — it shares the exited red with `exited`, never the
* attention amber (`sessionStatusKey` still labels it "interrupted").
*/
function parentDot(state: SessionState): DotView {
// `interrupted` sits with `exited`: both mean the process is gone, and in the
// 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 (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" };
return { status: "idle" };
}
/** `:PiSessions` → dot for a parent (depth 0) session row. */
export function sessionDot(state: SessionState, opts: { viewed?: boolean } = {}): DotView {
return withCurrent(parentDot(state), state, opts.viewed === true);
}
/**
* `:PiSessions` sub-session matrix (`child_dot_hl`) — deliberately not the
* parent's: an exited/dormant child is the hollow `◌` (never the exited red), a
* failed child is steady red while you are looking at it and blinking red while
* you are not, and `busy`/`compacting` share the busy amber at the busy rate.
* A child never shows `ok` or `attention`: the plugin forces `done = false` and
* `attention = 0` there, surfacing both in the parent chat instead.
*/
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" };
return { status: "idle" };
}
/** `:PiSessions` → dot for a sub-session (depth > 0) row. */
export function childSessionDot(state: SessionState, opts: { viewed?: boolean } = {}): DotView {
const viewed = opts.viewed === true;
return withCurrent(childDot(state, viewed), state, viewed);
}
/**
* `:PiSessions` → dot for a manifest-only subagent row. A `completed` subagent is
* the hollow dot, not a green one: the plugin shows a finished child as dormant
* `◌` and keeps green for "a turn finished while you were elsewhere" on parents.
*/
export function subagentDot(
subagent: SessionState["subagents"][number],
opts: { viewed?: boolean } = {},
): DotView {
switch (subagent.status) {
case "active":
return { status: "busy" };
case "completed":
case "dormant":
return { status: "exited" };
case "failed":
return { status: "err", steady: opts.viewed === true };
case "interrupted":
return { status: "dead" };
default:
return { status: "idle" };
}
}
/** i18n key under `state.*` for the current session status. */
@@ -0,0 +1,37 @@
import { useEffect, useState } from "react";
/**
* pi2.nvim's auto-title spinner (`lua/pi/ui/sessions.lua`): 10 braille frames
* ticked every 120 ms and rendered as a *prefix* before the name — never in
* place of it. It only runs while the backend generates a title; the row's own
* text stays static (pi2.nvim animates nothing else in `:PiSessions`).
*
* `prefers-reduced-motion: reduce` freezes it on the first frame: the state is
* still visible, only the motion stops.
*/
const SPINNER_FRAMES = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"];
const SPINNER_INTERVAL_MS = 120;
export interface SessionTitleSpinnerProps {
/** Hidden from assistive tech: the row's name already carries the state. */
className?: string;
}
export function SessionTitleSpinner({ className = "t-spinner" }: SessionTitleSpinnerProps) {
const [frame, setFrame] = useState(0);
useEffect(() => {
if (typeof window === "undefined") return;
if (window.matchMedia?.("(prefers-reduced-motion: reduce)").matches) return;
const timer = window.setInterval(() => {
setFrame((current) => (current + 1) % SPINNER_FRAMES.length);
}, SPINNER_INTERVAL_MS);
return () => window.clearInterval(timer);
}, []);
return (
<span className={className} aria-hidden="true">
{SPINNER_FRAMES[frame]}
</span>
);
}
+91
View File
@@ -0,0 +1,91 @@
/**
* Session / sub-session display titles — the web port of pi2.nvim's
* `:PiSessions` name resolution (`lua/pi/ui/sessions.lua`, `resolve_name`).
*
* Rules (in this order, each guarded by a trim + non-empty check):
*
* 1. the session's own name (`session.name`, set by the user or the backend's
* auto-title extension);
* 2. while the backend is *generating* a title, the provisional placeholder —
* never the first message: pi2.nvim keeps the label on `(unnamed)` so the
* row makes one visible change (placeholder → title), not two;
* 3. the first user message (`session.firstMessage`, the list row's disk
* projection) as the provisional label;
* 4. the `(unnamed)` placeholder.
*
* Sub-sessions resolve `name` → the task prompt (first 40 characters, the same
* cut as `pi/subsessions/manifest.lua FALLBACK_NAME_CHARS`) → `sub-session`.
*
* **Never returns an id.** A session id is an identity (`data-session-id`,
* hrefs, RPC targets), not a label — pi2.nvim shows `(unnamed)` instead.
*
* Pure and React-free so the state machine is unit-testable without a DOM.
*/
export interface SessionTitleInput {
name?: string | null;
firstMessage?: string | null;
/**
* Reserved: the plugin's `pi-title` extension status (the auto-title
* extension's `setStatus` while it generates a name) is not relayed to the
* browser yet — `docs/protocol.md` has no field for it. When it lands, the
* row's spinner switches on with no change here.
*/
titleGenerating?: boolean;
}
export interface SessionTitlePhrases {
/** `t("chat.sessionUnnamed")` — the pi2.nvim `(unnamed)` literal. */
unnamed: string;
/** `t("chat.subagentUnnamed")` — the pi2.nvim `sub-session` fallback. */
subagentUnnamed: string;
}
export type SessionTitleKind = "name" | "first-message" | "task" | "generating" | "unnamed";
export interface SessionTitle {
/** What the row renders. Never an id. */
text: string;
kind: SessionTitleKind;
/** Placeholder text (`(unnamed)` / `sub-session`) rather than data. */
provisional: boolean;
/** Render the braille spinner prefix (pi2.nvim: prefix, never a replacement). */
spinner: boolean;
}
/** Task characters kept when deriving a sub-session name (`Manifest.fallback_name`). */
export const FALLBACK_NAME_CHARS = 40;
export function sessionTitle(input: SessionTitleInput, phrases: SessionTitlePhrases): SessionTitle {
const name = trim(input?.name);
if (name) return { text: name, kind: "name", provisional: false, spinner: false };
if (input?.titleGenerating === true) {
// pi2.nvim suppresses the first-message fallback while titling.
return { text: phrases.unnamed, kind: "generating", provisional: true, spinner: true };
}
const firstMessage = trim(input?.firstMessage);
if (firstMessage) return { text: firstMessage, kind: "first-message", provisional: false, spinner: false };
return { text: phrases.unnamed, kind: "unnamed", provisional: true, spinner: false };
}
export function subagentTitle(
input: Pick<SessionTitleInput, "name"> & { task?: string | null },
phrases: SessionTitlePhrases,
): SessionTitle {
const name = trim(input?.name);
if (name) return { text: name, kind: "name", provisional: false, spinner: false };
const task = trim(input?.task);
if (task) {
return { text: task.slice(0, FALLBACK_NAME_CHARS), kind: "task", provisional: true, spinner: false };
}
return { text: phrases.subagentUnnamed, kind: "unnamed", provisional: true, spinner: false };
}
function trim(value: string | null | undefined): string {
return typeof value === "string" ? value.trim() : "";
}
+12 -4
View File
@@ -11,6 +11,7 @@ import { cn } from "@/lib/utils";
import { TodoList } from "./blocks";
import { formatDuration } from "./format";
import { subagentTitle } from "./session-title";
import type { TrayTab } from "./store";
import "@/styles/pages/chat-tray.css";
@@ -71,9 +72,16 @@ export function SessionTray({
const tabsRef = useRef<HTMLDivElement | null>(null);
const [entered, setEntered] = useState(false);
const title = subagent
? t("chat.subview.trayTitle", { name: subagent.name ?? subagent.id })
: t("chat.trayTitle");
// The tray names the subagent it is scoped to; a nameless subagent is
// labelled by its task prompt, never by its id (pi2.nvim parity).
const subagentName = subagent
? subagentTitle(subagent, {
unnamed: t("chat.sessionUnnamed"),
subagentUnnamed: t("chat.subagentUnnamed"),
}).text
: "";
const title = subagent ? t("chat.subview.trayTitle", { name: subagentName }) : t("chat.trayTitle");
// Enter animation: flip `is-open` on the frame after the node is painted.
useEffect(() => {
@@ -185,7 +193,7 @@ export function SessionTray({
<p className="tray-scope" data-testid="tray-scope">
<span className="tray-scope__label">
{subagent
? t("chat.trayScopeSubagent", { name: subagent.name ?? subagent.id })
? t("chat.trayScopeSubagent", { name: subagentName })
: t("chat.trayScopeSession")}
</span>
{subagent ? <span className="tray-scope__note">{t("chat.trayScopeNote")}</span> : null}
+70 -47
View File
@@ -1,5 +1,8 @@
import type { SessionState, Subagent } from "@protocol/types";
import { compareSiblings, effectiveParentOf, orderSessions } from "./session-order";
import { sessionTitle, subagentTitle } from "./session-title";
/**
* The session tree the sidebar renders: workspace sessions nest under their
* `parentId` (sub-sessions are separate rows of the same REST list), and a
@@ -145,12 +148,19 @@ function containsNode(node: TreeNode, id: string): boolean {
return node.children.some((child) => containsNode(child, id));
}
/**
* English search phrases: the model is React-free, so it must not depend on
* i18n. Searching matches the rendered label *and* the raw id, which keeps a
* session findable even though an id is never displayed as its title.
*/
const SEARCH_PHRASES = { unnamed: "(unnamed)", subagentUnnamed: "sub-session" };
function sessionLabel(session: SessionState): string {
return session.name?.trim() || session.sessionId;
return sessionTitle(session, SEARCH_PHRASES).text;
}
function subagentLabel(subagent: Subagent): string {
return subagent.name?.trim() || subagent.id;
return subagentTitle(subagent, SEARCH_PHRASES).text;
}
/** Search matches the session/subagent name or its model id (prototype behaviour). */
@@ -159,34 +169,13 @@ function matches(label: string, model: string | undefined, needle: string): bool
return label.toLowerCase().includes(needle) || (model ?? "").toLowerCase().includes(needle);
}
/**
* The parent a row is grouped under, or `null` when it is a root.
*
* A `parentId` that is not in the list is promoted to a root (a filtered-out
* parent must never lose its children), and a cycle is cut by rendering every
* member of the cycle as a root.
*/
function effectiveParent(session: SessionState, index: Map<string, SessionState>): string | null {
const parentId = session.parentId ?? null;
if (!parentId || parentId === session.sessionId || !index.has(parentId)) return null;
const seen = new Set<string>([session.sessionId]);
let cursor: string | null = parentId;
while (cursor) {
if (seen.has(cursor)) return null;
seen.add(cursor);
const next: string | null = index.get(cursor)?.parentId ?? null;
if (!next || next === cursor) break;
cursor = next;
}
return parentId;
}
/**
* Build the render tree for one workspace.
*
* Input order is preserved (never sorted): root sessions and siblings keep the
* order the list delivered; a session's synthetic subagent rows follow its real
* child sessions, in manifest order.
* Input is put into canonical order first (roots by tab rank asc, siblings by
* createdAt desc then id asc, per pi2.nvim `:PiSessions`), and only then grouped:
* a session's real child sessions and synthetic manifest subagent rows are merged
* into one sorted sibling list (real child sessions win over same-id subagents).
*/
export function buildSessionTreeView(
sessions: SessionState[],
@@ -197,19 +186,18 @@ export function buildSessionTreeView(
const selectedId = options.selectedId ?? null;
const needle = (options.filter ?? "").trim().toLowerCase();
const ordered = orderSessions(sessions);
const index = new Map<string, SessionState>();
for (const session of sessions) {
// Duplicate ids (a list/payload race) must not render twice or key twice.
if (!index.has(session.sessionId)) index.set(session.sessionId, session);
for (const session of ordered) {
index.set(session.sessionId, session);
}
let hiddenByPolicy = 0;
// Children grouped by their effective parent, in list order.
// Children grouped by their effective parent, in canonical order.
const childSessions = new Map<string | null, SessionState[]>();
for (const session of sessions) {
if (index.get(session.sessionId) !== session) continue;
const parentId = effectiveParent(session, index);
for (const session of ordered) {
const parentId = effectiveParentOf(session, index);
const siblings = childSessions.get(parentId);
if (siblings) siblings.push(session);
else childSessions.set(parentId, [session]);
@@ -225,7 +213,13 @@ export function buildSessionTreeView(
* active lens > plugin policy > "an kept descendant needs the ancestor".
*/
function keepSession(session: SessionState, childCount: number): boolean {
if (needle !== "") return matches(sessionLabel(session), session.model?.id, needle) || childCount > 0;
if (needle !== "") {
return (
matches(sessionLabel(session), session.model?.id, needle) ||
session.sessionId.toLowerCase().includes(needle) ||
childCount > 0
);
}
if (selectedId !== null && session.sessionId === selectedId) return true;
if (activeOnly && !isSessionActive(session)) return childCount > 0;
if (session.visible === false) return showHidden || childCount > 0;
@@ -237,16 +231,42 @@ export function buildSessionTreeView(
const nextPath = new Set(path).add(session.sessionId);
const children: TreeNode[] = [];
let hiddenCount = 0;
for (const child of childSessions.get(session.sessionId) ?? []) {
const node = buildSessionNode(child, depth + 1, nextPath);
if (node) children.push(node);
else if (activeOnly && needle === "" && child.visible !== false) hiddenCount += 1;
}
for (const subagent of session.subagents ?? []) {
const node = buildSubagentNode(session, subagent, depth + 1, nextPath);
if (node) children.push(node);
else if (activeOnly && needle === "" && !isSubagentActive(subagent) && subagent.visible !== false) {
hiddenCount += 1;
type SiblingCandidate =
| { kind: "session"; session: SessionState; id: string; createdAt?: number | null }
| { kind: "subagent"; subagent: Subagent; id: string; createdAt?: number | null };
const manifestById = new Map((session.subagents ?? []).map((s) => [s.id, s]));
const candidates: SiblingCandidate[] = [
...(childSessions.get(session.sessionId) ?? []).map((child) => ({
kind: "session" as const,
session: child,
id: child.sessionId,
createdAt: manifestById.get(child.sessionId)?.createdAt ?? child.createdAt,
})),
...(session.subagents ?? [])
.filter((subagent) => !index.has(subagent.id))
.map((subagent) => ({
kind: "subagent" as const,
subagent,
id: subagent.id,
createdAt: subagent.createdAt,
})),
];
candidates.sort(compareSiblings);
for (const candidate of candidates) {
if (candidate.kind === "session") {
const node = buildSessionNode(candidate.session, depth + 1, nextPath);
if (node) children.push(node);
else if (activeOnly && needle === "" && candidate.session.visible !== false) hiddenCount += 1;
} else {
const node = buildSubagentNode(session, candidate.subagent, depth + 1, nextPath);
if (node) children.push(node);
else if (activeOnly && needle === "" && !isSubagentActive(candidate.subagent) && candidate.subagent.visible !== false) {
hiddenCount += 1;
}
}
}
if (!keepSession(session, children.length)) {
@@ -284,7 +304,8 @@ export function buildSessionTreeView(
const nextPath = new Set(path).add(subagent.id);
const children: TreeNode[] = [];
let hiddenCount = 0;
for (const child of subagent.children ?? []) {
const subChildren = [...(subagent.children ?? [])].sort(compareSiblings);
for (const child of subChildren) {
const node = buildSubagentNode(session, child, depth + 1, nextPath);
if (node) children.push(node);
else if (activeOnly && needle === "" && !isSubagentActive(child) && child.visible !== false) {
@@ -298,7 +319,9 @@ export function buildSessionTreeView(
showHidden ||
selectedId === subagent.id ||
children.length > 0 ||
(needle !== "" && matches(subagentLabel(subagent), subagent.model, needle));
(needle !== "" &&
(matches(subagentLabel(subagent), subagent.model, needle) ||
subagent.id.toLowerCase().includes(needle)));
if (!keep) {
if (needle === "") hiddenByPolicy += 1;
return null;
+42 -10
View File
@@ -4,10 +4,12 @@ import { useTranslation } from "react-i18next";
import { Icon } from "@/components/icons";
import { Empty } from "@/components/ui/empty";
import { StatusDot, subagentDotClass } from "@/components/ui/status-dot";
import { StatusDot } from "@/components/ui/status-dot";
import { cn } from "@/lib/utils";
import { SessionRowMenu } from "./session-row-menu";
import { flattenSubagents, sessionDot } from "./session-state";
import { childSessionDot, flattenSubagents, sessionDot, subagentDot } from "./session-state";
import { sessionTitle, subagentTitle } from "./session-title";
import { SessionTitleSpinner } from "./session-title-spinner";
import {
buildSessionTreeView,
treeNodeId,
@@ -104,6 +106,11 @@ export function SessionTree({
const [wsMenuOpen, setWsMenuOpen] = useState(false);
const [rowMenu, setRowMenu] = useState<{ session: SessionState; anchor: HTMLElement } | null>(null);
const anchorRef = useRef<HTMLElement | null>(null);
// pi2.nvim's `(unnamed)` / `sub-session` placeholders, in the active locale.
const titlePhrases = useMemo(
() => ({ unnamed: t("chat.sessionUnnamed"), subagentUnnamed: t("chat.subagentUnnamed") }),
[t],
);
const view = useMemo(
() =>
@@ -171,8 +178,13 @@ export function SessionTree({
function renderSessionRow(node: SessionTreeNode) {
const session = node.session;
const selected = session.sessionId === selectedId;
const dot =
node.depth > 0
? childSessionDot(session, { viewed: selected })
: sessionDot(session, { viewed: selected });
const menuOpen = rowMenu?.session.sessionId === session.sessionId;
const name = session.name?.trim() || session.sessionId;
// A row is never labelled with its id (pi2.nvim shows `(unnamed)`).
const title = sessionTitle(session, titlePhrases);
const attention = session.attention.length;
return (
<div
@@ -197,12 +209,21 @@ export function SessionTree({
<button
type="button"
className="tree-row__main"
title={rowTitle([name, session.model?.id, session.thinking])}
title={rowTitle([title.text, session.model?.id, session.thinking])}
aria-current={selected ? "true" : undefined}
onClick={() => onSelectSession(session.sessionId)}
>
<StatusDot status={sessionDot(session)} />
<span className="t-name truncate">{name}</span>
<StatusDot status={dot.status} steady={dot.steady} current={dot.current} />
{title.spinner ? <SessionTitleSpinner /> : null}
<span
className={cn(
"t-name truncate",
title.kind === "unnamed" && "is-unnamed",
title.kind === "generating" && "is-generating",
)}
>
{title.text}
</span>
{attention > 0 ? <span className="t-attn">{`!${attention}`}</span> : null}
</button>
<button
@@ -227,9 +248,12 @@ export function SessionTree({
function renderSubagentRow(node: SubagentTreeNode) {
const { session, subagent } = node;
const viewing = subagent.id === activeSubagentId;
const name = subagent.name?.trim() || subagent.id;
const dot = subagentDot(subagent, { viewed: viewing });
// Sub-session rows resolve name → task prompt (40 chars) → `sub-session`;
// the id stays an identity, never a label.
const title = subagentTitle(subagent, titlePhrases);
// Status is carried by the dot only; text goes to title/aria-label.
const label = rowTitle([name, subagent.model, subagent.thinking, t(`state.${subagent.status}`)]);
const label = rowTitle([title.text, subagent.model, subagent.thinking, t(`state.${subagent.status}`)]);
return (
<div
className={cn(
@@ -256,8 +280,16 @@ export function SessionTree({
data-sub-id={subagent.id}
onClick={() => onSelectSubagent(session.sessionId, subagent.id)}
>
<span className={cn("dot", subagentDotClass(subagent.status))} aria-hidden="true" />
<span className="t-name truncate">{name}</span>
<StatusDot status={dot.status} steady={dot.steady} />
<span
className={cn(
"t-name truncate",
title.kind === "unnamed" && "is-unnamed",
title.kind === "generating" && "is-generating",
)}
>
{title.text}
</span>
{node.hiddenCount > 0 ? (
<span className="t-hidden tabular" title={t("chat.hiddenSubs", { n: node.hiddenCount })}>
{`+${node.hiddenCount}`}
+16 -11
View File
@@ -4,7 +4,7 @@ import { useTranslation } from "react-i18next";
import { Icon } from "@/components/icons";
import { Empty } from "@/components/ui/empty";
import { StatusDot, type DotStatus } from "@/components/ui/status-dot";
import { StatusDot } from "@/components/ui/status-dot";
import { toast } from "@/components/ui/toast";
import { cn } from "@/lib/utils";
@@ -12,20 +12,14 @@ import { EntryBlock } from "./blocks";
import { Composer } from "./composer";
import type { ModelGroup } from "./data";
import { HeadChips } from "./head-chips";
import { subagentDot } from "./session-state";
import { subagentTitle } from "./session-title";
import type { TrayTab } from "./store";
import "@/styles/pages/chat-telemetry.css";
type ToolBlock = Extract<Block, { type: "tool" }>;
const SUB_DOT: Record<Subagent["status"], DotStatus> = {
active: "busy",
completed: "ok",
failed: "err",
interrupted: "attention",
dormant: "exited",
};
function str(value: unknown): string | undefined {
return typeof value === "string" && value.trim() ? value.trim() : undefined;
}
@@ -185,7 +179,10 @@ export function SubagentView({
className,
}: SubagentViewProps) {
const { t } = useTranslation();
const name = subagent.name?.trim() || subagent.id;
const name = subagentTitle(subagent, {
unnamed: t("chat.sessionUnnamed"),
subagentUnnamed: t("chat.subagentUnnamed"),
}).text;
const task = subagent.task?.trim() || "";
// `live` is authoritative when present; the status is the fallback.
const isLive = subagent.live === true || subagent.status === "active";
@@ -246,6 +243,10 @@ export function SubagentView({
.catch(() => undefined);
}
// The child view is the session you are looking at, so its unread markers are
// already consumed (`viewed: true`) — a failed child is steady red here.
const dot = subagentDot(subagent, { viewed: true });
return (
<div
className={cn("subagent-view", "subagent-view--child", className)}
@@ -278,7 +279,11 @@ export function SubagentView({
<span className="sub-back__label">{t("chat.subview.back")}</span>
</button>
<div className="stream-title">
<StatusDot status={SUB_DOT[subagent.status]} title={t(`state.${subagent.status}`)} />
<StatusDot
status={dot.status}
steady={dot.steady}
title={t(`state.${subagent.status}`)}
/>
<h2 className="stream-name truncate" tabIndex={-1} title={task ? `${name} · ${task}` : name}>
{name}
</h2>
+6 -9
View File
@@ -2,10 +2,12 @@ import type { ContextUsage, Entry, SessionState, Subagent, UsageTotals } from "@
import { useEffect, useState } from "react";
import { useTranslation } from "react-i18next";
import { StatusDot } from "@/components/ui/status-dot";
import { plural } from "@/lib/i18n";
import { cn } from "@/lib/utils";
import { formatDuration } from "./format";
import { subagentDot } from "./session-state";
import { synthesizeSubagentTimeline } from "./subagent-view";
import "@/styles/pages/chat-telemetry.css";
@@ -24,14 +26,6 @@ const SUB_TONE: Record<Subagent["status"], string> = {
dormant: "is-idle",
};
const SUB_DOT: Record<Subagent["status"], string> = {
active: "dot--busy",
completed: "dot--ok",
failed: "dot--err",
interrupted: "dot--attention",
dormant: "dot--exited",
};
export interface TelemetryCounts {
/** `role === "user"` entries in the view's timeline. */
turns: number;
@@ -175,6 +169,9 @@ export function Telemetry({ session, subagent, entries, className }: TelemetryPr
if (subagent) {
const timeline = synthesizeSubagentTimeline(subagent, entries);
// The subagent view is the session you have open: its unread markers are
// already consumed, so a failed child is steady red here.
const dot = subagentDot(subagent, { viewed: true });
const { turns, tools } = countTelemetry(timeline);
const created = subagent.createdAt;
const end = ticking ? now : (subagent.lastActiveAt ?? created);
@@ -191,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">
<span className={cn("dot", SUB_DOT[subagent.status])} aria-hidden="true" />
<StatusDot status={dot.status} steady={dot.steady} />
{t(`state.${subagent.status}`)}
</span>
{elapsed ? (
+2 -1
View File
@@ -122,10 +122,11 @@ export function useInfoQuery(enabled = true) {
});
}
export function useHealthQuery() {
export function useHealthQuery(enabled = true) {
return useQuery<HealthResponse>({
queryKey: ["health"],
queryFn: ({ signal }) => api.health(signal),
enabled,
staleTime: 10_000,
});
}
+43 -2
View File
@@ -1,6 +1,47 @@
import type { InfoResponse } from "@/lib/api";
import type { WsConnectionState } from "@/lib/ws";
export type ServerStatusValue = "online" | "degraded" | "offline" | "unknown";
export interface ServerStatusInput {
/** The browser holds a paired device (localStorage `pi2-connection`). */
paired: boolean;
/** Cached `GET /api/v1/info` payload, or `null`/`undefined` before the first success. */
info?: InfoResponse | null;
/** The /info query failed (network error or non-2xx). */
infoError?: boolean;
/** The /health query failed (network error or non-2xx) while the daemon responds. */
healthError?: boolean;
/** `GET /api/v1/health` → `ok`, `null`/`undefined` while unknown. */
healthOk?: boolean | null;
}
/** Resolve the server status the UI may trust; never the wire's absent `status` field. */
export function resolveServerStatus(input: ServerStatusInput): ServerStatusValue {
// 1. Unpaired clients cannot reach a server session.
if (!input.paired) {
return "offline";
}
// 2. The /info probe failed (network error or non-2xx) — daemon is unreachable.
if (input.infoError) {
return "offline";
}
// 3. /health probe failed (network error or 5xx) while the daemon answers.
if (input.healthError) {
return "degraded";
}
// 4. /health reported a degraded subsystem while the daemon itself responds.
if (input.healthOk === false) {
return "degraded";
}
// 5. Cached or freshly fetched /info payload is present and healthy.
if (input.info != null) {
return "online";
}
// 6. First probe is still in flight — do not flash offline.
return "unknown";
}
/**
* Optional identity fields the daemon may expose beyond the minimal /info
* contract (`{v,daemonId,machineId,platform,hostname,os,version,uptimeMs,
@@ -36,7 +77,7 @@ export interface ServerIdentity {
uptimeSec: number | null;
uptimeMs: number | null;
pid: number | null;
status: "online" | "degraded" | "offline";
status: ServerStatusValue;
wsConnected: boolean;
wsProto: string;
lastHeartbeatAt: number | null;
@@ -85,7 +126,7 @@ export interface DeriveServerInput {
wsState?: WsConnectionState;
fetchedAt?: number | null;
nameFallback?: string | null;
status?: "online" | "degraded" | "offline" | null;
status?: ServerStatusValue | null;
}
/** Resolve the single server's identity from /info + the locally stored endpoint. */
+1
View File
@@ -257,6 +257,7 @@ export interface InfoResponse {
/** Additive identity fields (daemon ≥ 0.2): OS label and process uptime. */
os?: string;
uptimeMs?: number;
/** Daemon does not send status today; resolveServerStatus() is the authority (a newer daemon may still send it as an override). */
status?: "online" | "degraded" | "offline";
}
+79
View File
@@ -0,0 +1,79 @@
export const BLINK_MS = 500;
let subscribers = 0;
let timerId: number | null = null;
let tick = 0;
function updateDom(fast: "on" | "dim", slow: "on" | "dim"): void {
if (typeof document === "undefined" || !document.documentElement) return;
document.documentElement.setAttribute("data-pi-blink-fast", fast);
document.documentElement.setAttribute("data-pi-blink-slow", slow);
}
function clearDom(): void {
if (typeof document === "undefined" || !document.documentElement) return;
document.documentElement.removeAttribute("data-pi-blink-fast");
document.documentElement.removeAttribute("data-pi-blink-slow");
}
function syncDomForTick(t: number): void {
const fast = t % 2 === 0 ? "on" : "dim";
const slow = Math.floor(t / 2) % 2 === 0 ? "on" : "dim";
updateDom(fast, slow);
}
export function blinkTick(): number {
return tick;
}
export function startBlinkClock(): () => void {
subscribers++;
if (subscribers === 1) {
tick = 0;
const prefersReducedMotion =
typeof window !== "undefined" &&
typeof window.matchMedia === "function" &&
window.matchMedia("(prefers-reduced-motion: reduce)").matches;
if (prefersReducedMotion) {
updateDom("on", "on");
} else {
syncDomForTick(tick);
if (typeof window !== "undefined") {
timerId = window.setInterval(() => {
tick++;
syncDomForTick(tick);
}, BLINK_MS);
}
}
}
let unsubscribed = false;
return () => {
if (unsubscribed) return;
unsubscribed = true;
subscribers--;
if (subscribers <= 0) {
subscribers = 0;
if (timerId !== null) {
window.clearInterval(timerId);
timerId = null;
}
tick = 0;
clearDom();
}
};
}
export function resetBlinkClock(): void {
subscribers = 0;
if (timerId !== null) {
window.clearInterval(timerId);
timerId = null;
}
tick = 0;
clearDom();
}
+2
View File
@@ -209,6 +209,7 @@
"chat.sendFailed": "Send failed: {error}",
"chat.sendTitle": "Send (Enter)",
"chat.sending": "Sending…",
"chat.sessionUnnamed": "(unnamed)",
"chat.sessions": "Sessions",
"chat.shell.command": "Command",
"chat.shell.copyCommand": "Copy command",
@@ -256,6 +257,7 @@
"chat.subagentCount": "{n} subagents",
"chat.subagentFilter": "Subagent filter",
"chat.subagentName": "Subagent name",
"chat.subagentUnnamed": "sub-session",
"chat.subagentNamePlaceholder": "e.g. ui-research",
"chat.subview.back": "Parent",
"chat.subview.backTo": "Back to {name}",
+2
View File
@@ -209,6 +209,7 @@
"chat.sendFailed": "发送失败:{error}",
"chat.sendTitle": "发送(Enter)",
"chat.sending": "发送中…",
"chat.sessionUnnamed": "(未命名)",
"chat.sessions": "会话",
"chat.shell.command": "命令",
"chat.shell.copyCommand": "复制命令",
@@ -256,6 +257,7 @@
"chat.subagentCount": "{n} 个子代理",
"chat.subagentFilter": "子代理筛选",
"chat.subagentName": "子代理名称",
"chat.subagentUnnamed": "子会话",
"chat.subagentNamePlaceholder": "例如 ui-research",
"chat.subview.back": "父级",
"chat.subview.backTo": "返回 {name}",
+4 -1
View File
@@ -1,13 +1,14 @@
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { RouterProvider } from "@tanstack/react-router";
import { ThemeProvider } from "next-themes";
import { StrictMode } from "react";
import { StrictMode, useEffect } from "react";
import { createRoot } from "react-dom/client";
import "@/styles/app.css";
import "@/lib/i18n";
import { Toaster } from "@/components/ui/toast";
import { startBlinkClock } from "@/lib/blink";
import { consumeHandoff } from "@/lib/handoff";
import { router } from "@/router";
import { useConnectionStore } from "@/stores/connection";
@@ -23,6 +24,8 @@ const queryClient = new QueryClient({
});
function App() {
useEffect(() => startBlinkClock(), []);
return (
<StrictMode>
<ThemeProvider
+39 -9
View File
@@ -39,6 +39,7 @@ import { MessageStream } from "@/features/chat/message-stream";
import { onSessionMigration, replaceChatUrl } from "@/features/chat/migration";
import { DispatchModal, RenameDialog, TaskOutputModal, type DispatchInput } from "@/features/chat/modals";
import { SessionTray } from "@/features/chat/session-tray";
import { sessionTitle } from "@/features/chat/session-title";
import {
findSubagent,
flattenSubagents,
@@ -115,9 +116,36 @@ function ChatExperience({ sessionId }: { sessionId?: string }) {
sessions,
sessionsQuery.loaded,
);
const history = useSessionHistory(active?.sessionId, active?.entries ?? NO_ENTRIES, paired);
// `:PiSessions` TabEnter: the routed session is in view, so its unread
// notifications are consumed — the plugin clears `done`/`error` when the user
// enters the tab and only raises `done` for a session that is not current.
const viewedSessionId = active?.sessionId;
const viewedDone = active?.flags.done;
const viewedError = active?.flags.error;
useEffect(() => {
if (!viewedSessionId || (!viewedDone && !viewedError)) return;
useSessionsStore.getState().markSeen(viewedSessionId);
}, [viewedSessionId, viewedDone, viewedError]);
const history = useSessionHistory(
active?.sessionId,
active?.entries ?? NO_ENTRIES,
paired,
active?.workspaceId ?? workspaceId,
);
const models = useChatModels(workspaceId, paired);
const workspace = workspaces.find((item) => item.workspaceId === workspaceId);
// pi2.nvim's placeholder vocabulary, and the display title of the routed
// session: name → first message → `(unnamed)`. Never the session id.
const titlePhrases = useMemo(
() => ({ unnamed: t("chat.sessionUnnamed"), subagentUnnamed: t("chat.subagentUnnamed") }),
[t],
);
// Patch the window title from the routed session's display title: name →
// first message → nothing (an unnamed session keeps the page title).
const activeTitle = useMemo(
() => (active ? sessionTitle(active, titlePhrases) : null),
[active, titlePhrases],
);
const filter = useChatStore((state) => state.filter);
const setFilter = useChatStore((state) => state.setFilter);
@@ -218,9 +246,11 @@ function ChatExperience({ sessionId }: { sessionId?: string }) {
}, [activeSubagentId, closeDrawers, rowMenuId, setRowMenuId, setWsMenuOpen, treeOpen, trayOpen]);
useEffect(() => {
const title = active?.name?.trim() || (sessionMissing ? t("errors.sessionNotFound") : t("nav.chat"));
// A placeholder title is not a title for the window chrome.
const fallback = sessionMissing ? t("errors.sessionNotFound") : t("nav.chat");
const title = activeTitle && !activeTitle.provisional ? activeTitle.text : fallback;
document.title = `${title} — pi2.nvim`;
}, [active?.name, sessionMissing, t]);
}, [activeTitle, sessionMissing, t]);
// The optimistic "sending" chip disappears when the authoritative user
// entry arrives (via entry_appended) or after a safety timeout.
@@ -446,7 +476,7 @@ function ChatExperience({ sessionId }: { sessionId?: string }) {
async function closeSession(session: SessionState) {
await exec(chatCommands.closeSession(session.sessionId), "chat.closedProcess", {
name: session.name ?? session.sessionId,
name: sessionTitle(session, titlePhrases).text,
});
setClosing(null);
}
@@ -515,10 +545,10 @@ function ChatExperience({ sessionId }: { sessionId?: string }) {
) : null}
<div className="stream-title">
{active ? (
<StatusDot status={sessionDot(active)} title={t(`state.${sessionStatusKey(active)}`)} />
<StatusDot status={sessionDot(active).status} title={t(`state.${sessionStatusKey(active)}`)} />
) : null}
<h2 className="stream-name truncate" tabIndex={-1} ref={streamNameRef}>
{active?.name?.trim() || (active ? active.sessionId : (workspace?.name ?? t("nav.chat")))}
{active ? activeTitle?.text : (workspace?.name ?? t("nav.chat"))}
</h2>
{active?.flags.attention && active.attention.length ? (
<Badge tone="warn">{t("chat.pending", { n: active.attention.length })}</Badge>
@@ -753,8 +783,8 @@ function ChatExperience({ sessionId }: { sessionId?: string }) {
title={renaming?.kind === "session" ? t("chat.renameSession") : t("chat.renameSubagentAria")}
initial={
renaming?.kind === "session"
? (renaming.session.name ?? renaming.session.sessionId)
: (renaming?.subagent.name ?? renaming?.subagent.id ?? "")
? (renaming.session.name ?? "")
: (renaming?.subagent.name ?? "")
}
hint={
renaming?.kind === "session" ? t("chat.renameSessionHint") : t("chat.renameSubagentHint")
@@ -770,7 +800,7 @@ function ChatExperience({ sessionId }: { sessionId?: string }) {
}}
title={t("chat.closeProcess")}
description={
closing ? t("chat.closeSessionText", { name: closing.name ?? closing.sessionId }) : undefined
closing ? t("chat.closeSessionText", { name: sessionTitle(closing, titlePhrases).text }) : undefined
}
confirmLabel={t("chat.closeProcess")}
danger
+9 -3
View File
@@ -31,7 +31,7 @@ import { mergeTasks,
type DevicesResponse,
type StatusTask,
} from "@/features/status/queries";
import { deriveServerIdentity, type InfoExtras } from "@/features/status/server";
import { deriveServerIdentity, resolveServerStatus, type InfoExtras } from "@/features/status/server";
import { ServerInfoCard } from "@/features/status/server-info-card";
import { TasksCard } from "@/features/status/tasks-card";
import { partitionWorkspaces } from "@/features/workspaces/visibility";
@@ -91,7 +91,13 @@ export function StatusPage() {
wsState,
fetchedAt: info.dataUpdatedAt || null,
nameFallback: storedServer?.name || meta?.server?.name,
status: info.isError ? "offline" : healthOk === false ? "degraded" : undefined,
status: resolveServerStatus({
paired,
info: info.data,
infoError: info.isError,
healthError: health.isError,
healthOk,
}),
});
// Background tasks: the live store covers open sessions, the REST session
@@ -151,7 +157,7 @@ export function StatusPage() {
}
const statusLabel = t(`state.${server.status}`, { defaultValue: server.status });
const headDot = serverDotClass(server.status) as DotStatus;
const headDot = serverDotClass(server.status).replace("dot--", "") as DotStatus;
// "updated <relative>" — the prototype's quiet freshness hint in the head.
const updatedAt = info.dataUpdatedAt || null;
const updatedLabel = t("status.updated", {
+12 -3
View File
@@ -8,8 +8,8 @@ import { PageHeader } from "@/components/shared/page-header";
import { Button } from "@/components/ui/button";
import { Empty } from "@/components/ui/empty";
import { toast } from "@/components/ui/toast";
import { deriveServerIdentity, type InfoExtras } from "@/features/status/server";
import { useInfoQuery, useWorkspacesQuery } from "@/features/status/queries";
import { deriveServerIdentity, resolveServerStatus, type InfoExtras } from "@/features/status/server";
import { useHealthQuery, useInfoQuery, useWorkspacesQuery } from "@/features/status/queries";
import { ActivityColumn } from "@/features/workspaces/activity-column";
import { openWorkspace, workspaceSessionCount } from "@/features/workspaces/commands";
import { NewWorkspaceDialog, type NewWorkspaceInput } from "@/features/workspaces/new-workspace-dialog";
@@ -47,12 +47,14 @@ export function WorkspacesPage() {
const queryClient = useQueryClient();
const [dialogOpen, setDialogOpen] = useState(false);
const paired = useConnectionStore((state) => state.paired);
const endpoint = useConnectionStore((state) => state.endpoint);
const wsState = useConnectionStore((state) => state.wsState);
const storedServer = useConnectionStore((state) => state.server);
const workspaces = useWorkspacesQuery();
const info = useInfoQuery();
const health = useHealthQuery(paired);
// Persisted "show N hidden" toggle (localStorage, default off): secondary
// rows (hidden/ghost/temp/…) stay out of the list until asked for.
@@ -76,13 +78,20 @@ export function WorkspacesPage() {
);
const runningCount = useMemo(() => all.filter((workspace) => (workspace.liveCount || 0) > 0).length, [all]);
const healthOk = health.data?.ok ?? (health.data ? health.data.items.every((item) => item.ok) : undefined);
const server = deriveServerIdentity({
info: info.data as InfoExtras | undefined,
endpoint,
wsState,
fetchedAt: info.dataUpdatedAt || null,
nameFallback: storedServer?.name,
status: info.isError ? "offline" : undefined,
status: resolveServerStatus({
paired,
info: info.data,
infoError: info.isError,
healthError: health.isError,
healthOk,
}),
});
async function createWorkspace(input: NewWorkspaceInput) {
+6
View File
@@ -1,5 +1,6 @@
import { create } from "zustand";
import type { ServerStatusValue } from "@/features/status/server";
import type { InfoResponse } from "@/lib/api";
import { getDeviceToken, setDeviceToken } from "@/lib/api";
import type { WsConnectionState } from "@/lib/ws";
@@ -43,6 +44,7 @@ export interface ConnectionStore {
connectedAt: number;
token: string | null;
server: InfoResponse | null;
serverStatus: ServerStatusValue;
wsState: WsConnectionState;
isPaired: () => boolean;
@@ -50,6 +52,7 @@ export interface ConnectionStore {
connect: (options?: { endpoint?: string; deviceName?: string; token?: string | null }) => void;
disconnect: () => void;
setServer: (server: InfoResponse | null) => void;
setServerStatus: (status: ServerStatusValue) => void;
setWsState: (state: WsConnectionState) => void;
setToken: (token: string | null) => void;
}
@@ -62,6 +65,7 @@ function initialState() {
connectedAt: Number(read(CONNECTED_AT_KEY)) || 0,
token: getDeviceToken(),
server: null as InfoResponse | null,
serverStatus: "unknown" as ServerStatusValue,
wsState: "idle" as WsConnectionState,
};
}
@@ -102,11 +106,13 @@ export const useConnectionStore = create<ConnectionStore>((set, get) => ({
connectedAt: 0,
token: null,
server: null,
serverStatus: "unknown",
wsState: "idle",
});
},
setServer: (server) => set({ server }),
setServerStatus: (serverStatus) => set({ serverStatus }),
setWsState: (wsState) => set({ wsState }),
setToken: (token) => {
setDeviceToken(token);
+36 -4
View File
@@ -15,6 +15,14 @@ export interface SessionsStore {
renameSessionId: (from: string, to: string) => void;
removeSession: (sessionId: string) => void;
selectSession: (sessionId: string | null) => void;
/**
* `:PiSessions` TabEnter: the user is now looking at this session, so its
* unread notifications (`done` / `error` / a stale `attention` flag) are
* consumed. `:PiSessions` clears both on TabEnter and only sets `done` when
* the session is not the current tab; the browser has no tabs, so owning a
* row's notifications means opening it.
*/
markSeen: (sessionId: string) => void;
listFor: (workspaceId: string) => SessionState[];
getSession: (sessionId: string) => SessionState | undefined;
setStatus: (status: "idle" | "loading" | "error", error?: string | null) => void;
@@ -46,16 +54,20 @@ export const useSessionsStore = create<SessionsStore>((set, get) => ({
return { byWorkspace: { ...state.byWorkspace, [session.workspaceId]: [...list, session] } };
}
// Tree metadata is list metadata: a live update (`pi2:session`,
// reducer events, a rename) carries no `parentId`/`visible`/`task` and
// must not orphan the row. Explicit `undefined` is the only
// "not carried" marker — an explicit `parentId: null` means root and
// wins, which `??` would invert.
// reducer events, a rename) carries no `parentId`/`visible`/`task`/
// `tab`/`tabRank`/`createdAt`/`lastActiveAt` and must not orphan the row.
// Explicit `undefined` is the only "not carried" marker — an explicit
// `parentId: null` means root and wins, which `??` would invert.
const previous = list[index] as SessionState;
const merged: SessionState = {
...session,
parentId: session.parentId !== undefined ? session.parentId : previous.parentId,
visible: session.visible !== undefined ? session.visible : previous.visible,
task: session.task !== undefined ? session.task : previous.task,
tab: session.tab !== undefined ? session.tab : previous.tab,
tabRank: session.tabRank !== undefined ? session.tabRank : previous.tabRank,
createdAt: session.createdAt !== undefined ? session.createdAt : previous.createdAt,
lastActiveAt: session.lastActiveAt !== undefined ? session.lastActiveAt : previous.lastActiveAt,
};
const next = list.map((s, i) => (i === index ? merged : s));
return { byWorkspace: { ...state.byWorkspace, [session.workspaceId]: next } };
@@ -117,6 +129,26 @@ export const useSessionsStore = create<SessionsStore>((set, get) => ({
selectSession: (selectedSessionId) => set({ selectedSessionId }),
markSeen: (sessionId) =>
set((state) => {
let changed = false;
const byWorkspace: Record<string, SessionState[]> = {};
for (const [workspaceId, list] of Object.entries(state.byWorkspace)) {
const next = list.map((session) => {
if (session.sessionId !== sessionId) return session;
const attention = session.attention.length > 0;
if (!session.flags.done && !session.flags.error && session.flags.attention === attention) {
return session;
}
changed = true;
return { ...session, flags: { attention, done: false, error: false } };
});
byWorkspace[workspaceId] = next;
}
// Nothing to consume: keep the state object so zustand skips the render.
return changed ? { byWorkspace } : state;
}),
listFor: (workspaceId) => get().byWorkspace[workspaceId] ?? [],
getSession: (sessionId) => {
+10 -3
View File
@@ -379,15 +379,22 @@ code, pre { font-family: var(--font-mono); font-size: 0.875em; }
.dot { display: inline-block; width: .5rem; height: .5rem; border-radius: 50%; background: var(--muted-foreground); flex: none; }
.dot--lg { width: 9px; height: 9px; }
.dot--busy { background: var(--warn); animation: pulse 1.4s ease-in-out infinite; }
.dot--compacting { background: var(--info); animation: pulse 2s ease-in-out infinite; }
.dot--busy { background: var(--warn); }
.dot--compacting { background: var(--role-thinking); }
.dot--idle { background: var(--faint); }
.dot--ok { background: var(--ok); }
.dot--err { background: var(--err); animation: pulse 1.4s ease-in-out infinite; }
.dot--err { background: var(--err); }
.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); }
@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; }
.chip {
display: inline-flex; align-items: center; gap: var(--space-2);
padding: var(--space-1) var(--space-3);
+23 -4
View File
@@ -311,7 +311,8 @@
height: 11px;
}
/* 行:单行 = 折叠箭头 + 主按钮(点 + 名称 + !N)+ 行操作「…」 */
/* 行:单行 = 折叠箭头 + 主按钮(点 + 名称 + !N)+ 行操作「…」
pi2.nvim 的 :PiSessions 不做淡入淡出:hover / 选中态瞬时切换。 */
.tree-row {
display: flex;
align-items: center;
@@ -319,7 +320,6 @@
min-height: 32px;
padding: 0;
border-radius: var(--radius-sm);
transition: background var(--dur-fast) var(--ease-out);
}
.tree-row:hover {
background: var(--surface-1);
@@ -355,6 +355,21 @@
flex: 1 1 auto;
min-width: 0;
}
/* 没有名字的会话:pi2.nvim 的占位样式(comment 色 + 斜体),静止不动。 */
.tree-row .t-name.is-unnamed,
.tree-row .t-name.is-generating {
color: var(--faint);
font-style: italic;
}
/* 自动命名中的 120ms 盲文 spinner:前缀占位,由 JS 驱动帧,CSS 不参与动画。 */
.tree-row .t-spinner {
flex: none;
width: 1ch;
color: var(--faint);
font-family: var(--font-mono);
font-size: var(--fs-sm);
line-height: 1;
}
.tree-row .t-attn {
flex: none;
font-size: var(--fs-2xs);
@@ -389,7 +404,6 @@
}
.tree-toggle.open svg {
transform: rotate(90deg);
transition: transform var(--dur-fast) var(--ease-out);
}
.tree-toggle.leaf {
visibility: hidden;
@@ -400,7 +414,6 @@
width: 22px;
height: 22px;
opacity: 0;
transition: opacity var(--dur-fast) var(--ease-out);
}
.tree-row:hover .t-more,
.tree-row:focus-within .t-more,
@@ -432,6 +445,12 @@
background: color-mix(in oklch, var(--destructive) 12%, transparent);
}
/* 状态圆点:由 <html> 根节点上的单一全局时钟驱动(data-pi-blink-* 属性,见 app.css 与 blink.ts),
不再使用每个圆点独立的 CSS animation,避免相位漂移。当前聚焦会话叠加高亮背景。 */
.tree-row .dot--current {
background: var(--info);
}
/* 子会话 / 子代理行:更矮、更小、灰一档;状态只由圆点表达。 */
.tree-row--sub .tree-row__main {
height: 30px;
+180
View File
@@ -0,0 +1,180 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { BLINK_MS, blinkTick, resetBlinkClock, startBlinkClock } from "@/lib/blink";
describe("blink clock", () => {
const originalMatchMedia = window.matchMedia;
beforeEach(() => {
vi.useFakeTimers();
resetBlinkClock();
});
afterEach(() => {
resetBlinkClock();
window.matchMedia = originalMatchMedia;
vi.restoreAllMocks();
vi.clearAllTimers();
vi.useRealTimers();
});
it("applies 'on'/'on' synchronously on subscribe and transitions phases in lockstep", () => {
const unsub = startBlinkClock();
// Synchronously applied on subscribe at tick 0 (no flash of dim).
expect(blinkTick()).toBe(0);
expect(document.documentElement.getAttribute("data-pi-blink-fast")).toBe("on");
expect(document.documentElement.getAttribute("data-pi-blink-slow")).toBe("on");
// After 500ms: fast -> "dim", slow stays "on".
vi.advanceTimersByTime(BLINK_MS);
expect(blinkTick()).toBe(1);
expect(document.documentElement.getAttribute("data-pi-blink-fast")).toBe("dim");
expect(document.documentElement.getAttribute("data-pi-blink-slow")).toBe("on");
// After 1000ms: fast -> "on", slow -> "dim".
vi.advanceTimersByTime(BLINK_MS);
expect(blinkTick()).toBe(2);
expect(document.documentElement.getAttribute("data-pi-blink-fast")).toBe("on");
expect(document.documentElement.getAttribute("data-pi-blink-slow")).toBe("dim");
// After 1500ms: both "dim".
vi.advanceTimersByTime(BLINK_MS);
expect(blinkTick()).toBe(3);
expect(document.documentElement.getAttribute("data-pi-blink-fast")).toBe("dim");
expect(document.documentElement.getAttribute("data-pi-blink-slow")).toBe("dim");
// After 2000ms: cycle restarts at both "on".
vi.advanceTimersByTime(BLINK_MS);
expect(blinkTick()).toBe(4);
expect(document.documentElement.getAttribute("data-pi-blink-fast")).toBe("on");
expect(document.documentElement.getAttribute("data-pi-blink-slow")).toBe("on");
// The two phases remain derived from ONE tick counter in lockstep.
for (let i = 5; i <= 12; i++) {
vi.advanceTimersByTime(BLINK_MS);
expect(blinkTick()).toBe(i);
const expectedFast = i % 2 === 0 ? "on" : "dim";
const expectedSlow = Math.floor(i / 2) % 2 === 0 ? "on" : "dim";
expect(document.documentElement.getAttribute("data-pi-blink-fast")).toBe(expectedFast);
expect(document.documentElement.getAttribute("data-pi-blink-slow")).toBe(expectedSlow);
}
unsub();
});
it("ref-counts subscribers: two subscribers install ONE interval", () => {
const setIntervalSpy = vi.spyOn(window, "setInterval");
const unsub1 = startBlinkClock();
expect(setIntervalSpy).toHaveBeenCalledTimes(1);
expect(vi.getTimerCount()).toBe(1);
const unsub2 = startBlinkClock();
// Second subscriber must reuse the existing interval.
expect(setIntervalSpy).toHaveBeenCalledTimes(1);
expect(vi.getTimerCount()).toBe(1);
// Unsubscribing one keeps it ticking.
unsub1();
expect(vi.getTimerCount()).toBe(1);
vi.advanceTimersByTime(BLINK_MS);
expect(blinkTick()).toBe(1);
expect(document.documentElement.getAttribute("data-pi-blink-fast")).toBe("dim");
expect(document.documentElement.getAttribute("data-pi-blink-slow")).toBe("on");
// The last unsubscribe clears the interval, removes attributes, and resets tick to 0.
unsub2();
expect(vi.getTimerCount()).toBe(0);
expect(document.documentElement.getAttribute("data-pi-blink-fast")).toBeNull();
expect(document.documentElement.getAttribute("data-pi-blink-slow")).toBeNull();
expect(blinkTick()).toBe(0);
// Advancing time further produces no ticks.
vi.advanceTimersByTime(BLINK_MS * 4);
expect(blinkTick()).toBe(0);
expect(document.documentElement.getAttribute("data-pi-blink-fast")).toBeNull();
expect(document.documentElement.getAttribute("data-pi-blink-slow")).toBeNull();
});
it("returns an idempotent unsubscribe function", () => {
const unsub = startBlinkClock();
expect(vi.getTimerCount()).toBe(1);
// Multiple calls to the same unsubscribe handle do not decrement below zero or throw.
unsub();
expect(vi.getTimerCount()).toBe(0);
expect(blinkTick()).toBe(0);
unsub();
expect(vi.getTimerCount()).toBe(0);
expect(blinkTick()).toBe(0);
unsub();
expect(vi.getTimerCount()).toBe(0);
expect(blinkTick()).toBe(0);
// A subsequent subscription starts cleanly with a single interval.
const unsubNew = startBlinkClock();
expect(vi.getTimerCount()).toBe(1);
expect(blinkTick()).toBe(0);
expect(document.documentElement.getAttribute("data-pi-blink-fast")).toBe("on");
expect(document.documentElement.getAttribute("data-pi-blink-slow")).toBe("on");
unsubNew();
expect(vi.getTimerCount()).toBe(0);
});
it("pins both attributes to 'on' without installing an interval under prefers-reduced-motion: reduce", () => {
const matchMediaMock = vi.fn().mockImplementation((query: string) => ({
matches: query.includes("prefers-reduced-motion: reduce"),
media: query,
onchange: null,
addListener: vi.fn(),
removeListener: vi.fn(),
addEventListener: vi.fn(),
removeEventListener: vi.fn(),
dispatchEvent: vi.fn(),
}));
window.matchMedia = matchMediaMock;
const setIntervalSpy = vi.spyOn(window, "setInterval");
const unsub = startBlinkClock();
expect(matchMediaMock).toHaveBeenCalledWith("(prefers-reduced-motion: reduce)");
// Both attributes pinned "on".
expect(document.documentElement.getAttribute("data-pi-blink-fast")).toBe("on");
expect(document.documentElement.getAttribute("data-pi-blink-slow")).toBe("on");
// No interval installed at all.
expect(vi.getTimerCount()).toBe(0);
expect(setIntervalSpy).not.toHaveBeenCalled();
// Advancing time does not change attributes or tick.
vi.advanceTimersByTime(BLINK_MS * 10);
expect(document.documentElement.getAttribute("data-pi-blink-fast")).toBe("on");
expect(document.documentElement.getAttribute("data-pi-blink-slow")).toBe("on");
expect(blinkTick()).toBe(0);
// Unsubscribe clears attributes.
unsub();
expect(document.documentElement.getAttribute("data-pi-blink-fast")).toBeNull();
expect(document.documentElement.getAttribute("data-pi-blink-slow")).toBeNull();
expect(blinkTick()).toBe(0);
});
it("resetBlinkClock stops timer, clears attributes, and resets tick to 0", () => {
startBlinkClock();
vi.advanceTimersByTime(BLINK_MS * 3);
expect(blinkTick()).toBe(3);
expect(document.documentElement.getAttribute("data-pi-blink-fast")).toBe("dim");
expect(document.documentElement.getAttribute("data-pi-blink-slow")).toBe("dim");
resetBlinkClock();
expect(vi.getTimerCount()).toBe(0);
expect(document.documentElement.getAttribute("data-pi-blink-fast")).toBeNull();
expect(document.documentElement.getAttribute("data-pi-blink-slow")).toBeNull();
expect(blinkTick()).toBe(0);
});
});
+77
View File
@@ -0,0 +1,77 @@
import { afterEach, describe, expect, it } from "vitest";
import { fetchEntriesPage, HISTORY_PAGE_SIZE, setSessionMeta } from "@/features/chat/history";
import { mockApi } from "./helpers/api-mock";
const ENTRIES_PATH = /^\/api\/v1\/sessions\/[^/]+\/entries$/;
function page(entries: unknown[] = [], cursor: Record<string, unknown> = { hasMore: false }) {
return { status: 200, body: { entries, cursor } };
}
afterEach(() => {
// `sessionMeta` is module state; keep each case's rows isolated.
for (const id of ["s-hint", "s-meta", "s-cursor", "s-response"]) {
setSessionMeta(id, { workspaceId: undefined, sessionFile: undefined });
}
});
describe("history page request", () => {
it("routes with the caller's workspace hint and the row's session file", async () => {
setSessionMeta("s-hint", { workspaceId: "ws-meta", sessionFile: "/tmp/s-hint.jsonl" });
const fetchMock = mockApi([{ path: ENTRIES_PATH, handler: () => page() }]);
await fetchEntriesPage("s-hint", { workspaceId: "ws-page" });
const url = new URL(String(fetchMock.mock.calls[0]?.[0]), "http://localhost");
expect(url.pathname).toBe("/api/v1/sessions/s-hint/entries");
// The page's workspace wins: it is known before the list effect lands.
expect(url.searchParams.get("workspaceId")).toBe("ws-page");
expect(url.searchParams.get("sessionFile")).toBe("/tmp/s-hint.jsonl");
expect(url.searchParams.get("limit")).toBe(String(HISTORY_PAGE_SIZE));
expect(url.searchParams.has("before")).toBe(false);
});
it("falls back to the row's workspace when the caller has none", async () => {
setSessionMeta("s-meta", { workspaceId: "ws-meta" });
const fetchMock = mockApi([{ path: ENTRIES_PATH, handler: () => page() }]);
await fetchEntriesPage("s-meta", {});
const url = new URL(String(fetchMock.mock.calls[0]?.[0]), "http://localhost");
expect(url.searchParams.get("workspaceId")).toBe("ws-meta");
expect(url.searchParams.has("sessionFile")).toBe(false);
});
it("forwards the before cursor for older pages", async () => {
const fetchMock = mockApi([{ path: ENTRIES_PATH, handler: () => page() }]);
await fetchEntriesPage("s-cursor", { before: "e9", limit: 25, workspaceId: "ws-page" });
const url = new URL(String(fetchMock.mock.calls[0]?.[0]), "http://localhost");
expect(url.searchParams.get("before")).toBe("e9");
expect(url.searchParams.get("limit")).toBe("25");
});
it("projects raw entries and keeps the plugin's cursor", async () => {
mockApi([
{
path: ENTRIES_PATH,
handler: () =>
page(
[
{
type: "message",
id: "u1",
message: { role: "user", content: "hi", timestamp: 1_733_234_400_000 },
},
],
{ before: "u1", hasMore: true },
),
},
]);
const result = await fetchEntriesPage("s-response", { workspaceId: "ws-page" });
expect(result.entries.map((entry) => entry.id)).toEqual(["u1"]);
expect(result.entries[0]?.role).toBe("user");
expect(result.cursor).toEqual({ before: "u1", hasMore: true });
});
});
+108
View File
@@ -338,3 +338,111 @@ describe("chat message stream — layout contract", () => {
expect(css).toMatch(/@media \(prefers-reduced-motion: reduce\)/);
});
});
/* ------------------------------------------------------------------ */
/* Auto-follow: content growth must never look like a user scroll. */
/* ------------------------------------------------------------------ */
describe("chat message stream — auto-follow", () => {
/**
* jsdom has no layout: give the scroll container a fake viewport so the
* distance heuristic can be exercised (2000px of content, 600px visible).
*/
function renderWithViewport(props: Partial<MessageStreamProps> = {}) {
const utils = renderStream(props);
const scroll = utils.container.querySelector<HTMLElement>(".stream-scroll");
if (!scroll) throw new Error("the chat layout did not render a stream scroll");
const box = { top: 0, height: 2000, client: 600 };
Object.defineProperty(scroll, "scrollHeight", { configurable: true, get: () => box.height });
Object.defineProperty(scroll, "clientHeight", { configurable: true, get: () => box.client });
Object.defineProperty(scroll, "scrollTop", {
configurable: true,
get: () => box.top,
set: (value: number) => {
box.top = value;
},
});
const scrollTo = vi.fn((options?: ScrollToOptions) => {
box.top = Number(options?.top ?? box.height);
});
(scroll as unknown as { scrollTo: typeof scrollTo }).scrollTo = scrollTo;
const latest = () => utils.container.querySelector(".fab--latest.is-visible");
return { ...utils, scroll, box, scrollTo, latest };
}
it("keeps following when the stream grew under the viewport (no user input)", () => {
const { scroll, box, latest } = renderWithViewport();
// The virtualizer measured taller items after the pin: the scroll
// position is now far from the bottom, but nobody scrolled.
box.top = 900;
fireEvent.scroll(scroll);
expect(latest()).toBeNull();
// An explicit wheel up that moves the view up does stop following.
fireEvent.wheel(scroll, { deltaY: -120 });
box.top = 800;
fireEvent.scroll(scroll);
expect(latest()).not.toBeNull();
// Returning to the bottom (by wheel) re-arms it.
fireEvent.wheel(scroll, { deltaY: 4000 });
box.top = box.height - box.client;
fireEvent.scroll(scroll);
expect(latest()).toBeNull();
});
it("re-pins to the newest item on every content resize while following", () => {
const observed: (() => void)[] = [];
const original = globalThis.ResizeObserver;
class RecordingObserver {
constructor(callback: () => void) {
observed.push(callback);
}
observe(): void {}
unobserve(): void {}
disconnect(): void {}
}
globalThis.ResizeObserver = RecordingObserver as unknown as typeof ResizeObserver;
try {
const { box, scrollTo } = renderWithViewport();
expect(observed.length).toBeGreaterThan(0);
box.height = 3200;
for (const callback of observed) callback();
expect(scrollTo).toHaveBeenCalled();
expect(box.top).toBe(3200);
} finally {
globalThis.ResizeObserver = original;
}
});
it("stops re-pinning once the user scrolled away", () => {
const observed: (() => void)[] = [];
const original = globalThis.ResizeObserver;
class RecordingObserver {
constructor(callback: () => void) {
observed.push(callback);
}
observe(): void {}
unobserve(): void {}
disconnect(): void {}
}
globalThis.ResizeObserver = RecordingObserver as unknown as typeof ResizeObserver;
try {
const { scroll, box, scrollTo, latest } = renderWithViewport();
fireEvent.wheel(scroll, { deltaY: -200 });
box.top = 400;
fireEvent.scroll(scroll);
expect(latest()).not.toBeNull();
scrollTo.mockClear();
box.height = 3600;
for (const callback of observed) callback();
expect(scrollTo).not.toHaveBeenCalled();
} finally {
globalThis.ResizeObserver = original;
}
});
});
+148 -17
View File
@@ -122,25 +122,45 @@ function menuItems(): HTMLElement[] {
describe("session tree rows", () => {
it("renders every session row as a single line: dot + name + attention", () => {
renderTree({
sessions: [
sessionFixture({
sessionId: "s1",
name: "Alpha",
subagents: [],
attention: [
{ requestId: "r1", method: "ask", createdAt: 1, receivedAt: 2 },
{ requestId: "r2", method: "ask", createdAt: 3, receivedAt: 4 },
],
}),
sessionFixture({ sessionId: "s2", name: "Beta", subagents: [] }),
],
const sessions = [
sessionFixture({
sessionId: "s1",
name: "Alpha",
subagents: [],
attention: [
{ requestId: "r1", method: "ask", createdAt: 1, receivedAt: 2 },
{ requestId: "r2", method: "ask", createdAt: 3, receivedAt: 4 },
],
}),
sessionFixture({ sessionId: "s2", name: "Beta", status: "idle", subagents: [] }),
sessionFixture({
sessionId: "s3",
name: "Gamma",
status: "idle",
flags: { attention: false, done: true, error: false },
subagents: [],
}),
sessionFixture({ sessionId: "s4", name: "Delta", status: "busy", subagents: [] }),
childSession({ sessionId: "c1", name: "Child exited", parentId: "s1", status: "exited" }),
childSession({
sessionId: "c2",
name: "Child error",
parentId: "s1",
flags: { attention: false, done: false, error: true },
}),
];
const { rerender } = renderTree({
sessions,
selectedId: "s1",
});
const main = rowMain("s1");
// Single line: dot + name + `!N` only.
expect(main.querySelector(".dot")).not.toBeNull();
const s1Dot = main.querySelector(".dot");
expect(s1Dot).not.toBeNull();
expect(s1Dot).toHaveClass("dot", "dot--attention");
expect(s1Dot).not.toHaveClass("dot--current");
expect(main.querySelector(".t-name")).toHaveTextContent("Alpha");
expect(main.querySelector(".t-attn")).toHaveTextContent("!2");
// No second line, no child count, no inline row actions.
@@ -161,6 +181,41 @@ describe("session tree rows", () => {
// A row without attention keeps no badge at all.
expect(rowMain("s2").querySelector(".t-attn")).toBeNull();
// Status dot modifiers and classes:
// 1. Unselected done row renders dot--ok.
const s3Dot = rowMain("s3").querySelector(".dot");
expect(s3Dot).toHaveClass("dot", "dot--ok");
expect(s3Dot).not.toHaveClass("dot--current");
// 2. Child exited row renders hollow dot--exited (never dead red).
const c1Dot = rowMain("c1").querySelector(".dot");
expect(c1Dot).toHaveClass("dot", "dot--exited");
expect(c1Dot).not.toHaveClass("dot--dead");
expect(c1Dot).not.toHaveClass("dot--current");
// 3. Child error row unselected renders dot--err without steady modifier.
const c2DotUnselected = rowMain("c2").querySelector(".dot");
expect(c2DotUnselected).toHaveClass("dot", "dot--err");
expect(c2DotUnselected).not.toHaveClass("dot--steady");
// 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");
// 5. Selected busy row renders dot--busy + dot--current.
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");
// 6. Selected child with error renders dot--err + dot--steady.
rerender(treeElement({ sessions, selectedId: "c2" }));
const c2DotSelected = rowMain("c2").querySelector(".dot");
expect(c2DotSelected).toHaveClass("dot", "dot--err", "dot--steady");
expect(c2DotSelected).not.toHaveClass("dot--current");
});
it("draws child rows as a single line without a child-count badge", () => {
@@ -510,10 +565,12 @@ function workspaceBody() {
}
function sessionsBody() {
// Two live tabs. `tab` is the plugin's live projection of `attached_tab`;
// without it a row is disk history, not a tab.
return {
sessions: [
{ sessionId: "s1", name: "Alpha", workspaceId: "W1", cwd: "/work/w1", status: "idle" },
{ sessionId: "s2", name: "Beta", workspaceId: "W1", cwd: "/work/w1", status: "busy" },
{ sessionId: "s1", name: "Alpha", workspaceId: "W1", cwd: "/work/w1", status: "idle", tab: 1, live: true },
{ sessionId: "s2", name: "Beta", workspaceId: "W1", cwd: "/work/w1", status: "busy", tab: 2, live: true },
],
};
}
@@ -531,7 +588,16 @@ function subSessionBody() {
parentId: "s1",
visible: false,
},
{ sessionId: "s1", name: "Alpha", workspaceId: "W1", cwd: "/work/w1", status: "idle", visible: true },
{
sessionId: "s1",
name: "Alpha",
workspaceId: "W1",
cwd: "/work/w1",
status: "idle",
visible: true,
tab: 1,
live: true,
},
],
};
}
@@ -724,3 +790,68 @@ describe("chat session deep link", () => {
expect(await screen.findByTestId("session-not-found")).toBeInTheDocument();
});
});
/* ------------------------------------------------------------------ */
/* The list is the nvim tab set, not the workspace's JSONL history. */
/* ------------------------------------------------------------------ */
/** What `workspace.query{kind:"sessions"}` answers: live tabs ∪ every JSONL on disk. */
function mixedBody() {
return {
sessions: [
{ sessionId: "hist", name: "Yesterday", workspaceId: "W1", cwd: "/work/w1", status: "done", modified: 2 },
{
sessionId: "s1",
name: "Alpha",
workspaceId: "W1",
cwd: "/work/w1",
status: "idle",
tab: 1,
live: true,
},
],
};
}
describe("chat session list mirrors the nvim tabs", () => {
beforeEach(() => {
useSessionsStore.getState().reset();
useChatStore.setState({ history: {}, sending: null });
silentSocket();
});
afterEach(() => {
vi.unstubAllGlobals();
});
it("renders the tab-backed session and never a disk-only historical row", async () => {
mockApi([
{ path: "/api/v1/workspaces", handler: () => ({ body: workspaceBody() }) },
{ path: "/api/v1/workspaces/W1/sessions", handler: () => ({ body: mixedBody() }) },
{ path: "/api/v1/models", handler: () => ({ body: [] }) },
{ path: /^\/api\/v1\/sessions\/s1\/entries/, handler: () => ({ body: entriesBody("Alpha first message") }) },
]);
await renderPage(chatRoutes(), "/chat?workspace=W1");
expect(await screen.findByText("Alpha first message")).toBeInTheDocument();
await waitFor(() => expect(document.querySelector('[data-session-id="s1"]')).not.toBeNull());
expect(document.querySelector('[data-session-id="hist"]')).toBeNull();
expect(screen.queryByText("Yesterday")).toBeNull();
});
it("answers a deep link into history with not-found and no composer", async () => {
const fetchMock = mockApi([
{ path: "/api/v1/workspaces", handler: () => ({ body: workspaceBody() }) },
{ path: "/api/v1/workspaces/W1/sessions", handler: () => ({ body: mixedBody() }) },
{ path: "/api/v1/models", handler: () => ({ body: [] }) },
]);
await renderPage(chatRoutes(), "/chat/hist?workspace=W1");
expect(await screen.findByTestId("session-not-found")).toBeInTheDocument();
// A historical row has no live owner: replying must not be offered.
expect(within(streamPane()).queryByLabelText("Message input")).toBeNull();
expect(requestedUrls(fetchMock).some((url) => url.includes("/sessions/hist/entries"))).toBe(false);
});
});
+37
View File
@@ -60,11 +60,48 @@ describe("StatusDot", () => {
["err", "dot--err"],
["attention", "dot--attention"],
["exited", "dot--exited"],
["dead", "dot--dead"],
] as const)("maps %s to %s", (status, expected) => {
const { container } = render(<StatusDot status={status} />);
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("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");
const { container: c2 } = render(<StatusDot status="err" />);
expect(c2.firstElementChild).not.toHaveClass("dot--steady");
});
it("applies dot--current modifier when current is true", () => {
const { container } = render(<StatusDot status="busy" current={true} />);
expect(container.firstElementChild).toHaveClass("dot", "dot--busy", "dot--current");
});
it("does not apply dot--current when current is false or omitted", () => {
const { container: c1 } = render(<StatusDot status="busy" current={false} />);
expect(c1.firstElementChild).not.toHaveClass("dot--current");
const { container: c2 } = render(<StatusDot status="busy" />);
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("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("exposes the state label when a title is provided", () => {
render(<StatusDot status="ok" title="Online" />);
expect(screen.getByLabelText("Online")).toHaveAttribute("title", "Online");
+96
View File
@@ -0,0 +1,96 @@
import { act } from "@testing-library/react";
import { beforeEach, describe, expect, it } from "vitest";
import { renderPage, type TestRoute } from "./helpers/render-page";
import { PageSheet } from "@/components/shared/page-sheet";
import type { InfoResponse } from "@/lib/api";
import { setLanguage } from "@/lib/i18n";
import { useConnectionStore } from "@/stores/connection";
const realisticInfo: InfoResponse = {
v: 1,
daemonId: "daemon-test-1",
machineId: "machine-test-1",
platform: "linux",
hostname: "devbook-eos",
os: "Linux 6.12.0",
version: "0.1.3",
uptimeMs: 123456,
port: 7676,
capabilities: ["read", "steer"],
limits: { maxInstances: 5 },
};
const routes = (): TestRoute[] => [
{
path: "/",
component: () => (
<PageSheet
open={true}
onOpenChange={() => {}}
page="workspaces"
onSearch={() => {}}
/>
),
},
{
path: "/workspaces",
component: () => <div>Workspaces</div>,
},
{
path: "/status",
component: () => <div>Status</div>,
},
{
path: "/chat",
component: () => <div>Chat</div>,
},
];
describe("PageSheet", () => {
beforeEach(() => {
setLanguage("en");
useConnectionStore.getState().disconnect();
useConnectionStore.getState().connect({ endpoint: "http://127.0.0.1:7676" });
});
it("shows localized online state + 0.1.3 on the status row fact and never unknown / 未知 once serverStatus is online", async () => {
await renderPage(routes(), "/", { paired: true });
act(() => {
const store = useConnectionStore.getState();
store.setServer(realisticInfo);
store.setServerStatus("online");
});
const statusLink = document.querySelector('a[href="/status"]');
expect(statusLink).not.toBeNull();
const fact = statusLink?.querySelector(".sheet-row__fact");
expect(fact).not.toBeNull();
expect(fact?.textContent).toBe("Online · 0.1.3");
expect(fact?.textContent).not.toContain("Unknown");
// Verify Chinese localization
act(() => {
setLanguage("zh");
});
expect(fact?.textContent).toBe("在线 · 0.1.3");
expect(fact?.textContent).not.toContain("未知");
});
it("shows 0.1.3 even when pluginVersion is empty string via the fallback chain", async () => {
await renderPage(routes(), "/", { paired: true });
act(() => {
const store = useConnectionStore.getState();
store.setServer({ ...realisticInfo, pluginVersion: "", version: "0.1.3" } as unknown as InfoResponse);
store.setServerStatus("online");
});
const statusLink = document.querySelector('a[href="/status"]');
expect(statusLink).not.toBeNull();
const fact = statusLink?.querySelector(".sheet-row__fact");
expect(fact?.textContent).toBe("Online · 0.1.3");
});
});
+154
View File
@@ -0,0 +1,154 @@
import { act } from "@testing-library/react";
import { beforeEach, describe, expect, it } from "vitest";
import { renderPage, type TestRoute } from "./helpers/render-page";
import { ServerChip } from "@/components/shared/server-chip";
import type { InfoResponse } from "@/lib/api";
import { setLanguage } from "@/lib/i18n";
import { useConnectionStore } from "@/stores/connection";
/** Realistic daemon /info response payload without `status` field. */
const realisticInfo: InfoResponse = {
v: 1,
daemonId: "daemon-test-1",
machineId: "machine-test-1",
platform: "linux",
hostname: "devbook-eos",
os: "Linux 6.12.0",
version: "0.1.3",
uptimeMs: 123456,
port: 7676,
capabilities: ["read", "steer"],
limits: { maxInstances: 5 },
};
const routes = (): TestRoute[] => [
{
path: "/",
component: () => <ServerChip />,
},
{
path: "/status",
component: () => <div>Status Page</div>,
},
];
describe("ServerChip", () => {
beforeEach(() => {
setLanguage("en");
useConnectionStore.getState().disconnect();
useConnectionStore.getState().connect({ endpoint: "http://127.0.0.1:7676" });
});
it("renders dot--ok and Online in English / 在线 in Chinese when serverStatus is online with status-less info payload", async () => {
// Explicitly assert that realisticInfo does not contain a wire `status` field.
expect("status" in realisticInfo).toBe(false);
const { container } = await renderPage(routes(), "/", { paired: true });
act(() => {
const store = useConnectionStore.getState();
store.setServer(realisticInfo);
store.setServerStatus("online");
});
const dot = container.querySelector(".server-chip .dot");
expect(dot).not.toBeNull();
expect(dot).toHaveClass("dot--ok");
expect(dot).not.toHaveClass("dot--exited");
expect(dot?.getAttribute("title")).toBe("Online");
expect(dot?.getAttribute("aria-label")).toBe("Online");
// Verify Chinese localization
act(() => {
setLanguage("zh");
});
expect(dot?.getAttribute("title")).toBe("在线");
expect(dot?.getAttribute("aria-label")).toBe("在线");
});
it("renders dot--idle and Unknown / 未知 for the initial store value (unknown)", async () => {
expect(useConnectionStore.getState().serverStatus).toBe("unknown");
const { container } = await renderPage(routes(), "/", { paired: true });
const dot = container.querySelector(".server-chip .dot");
expect(dot).not.toBeNull();
expect(dot).toHaveClass("dot--idle");
expect(dot?.getAttribute("title")).toBe("Unknown");
expect(dot?.getAttribute("aria-label")).toBe("Unknown");
act(() => {
setLanguage("zh");
});
expect(dot?.getAttribute("title")).toBe("未知");
expect(dot?.getAttribute("aria-label")).toBe("未知");
});
it("renders dot--ok when server override carries a bogus status: 'offline' while store's serverStatus is online", async () => {
const bogusServer = { ...realisticInfo, status: "offline" } as unknown as InfoResponse;
const overrideRoutes = (): TestRoute[] => [
{
path: "/",
component: () => <ServerChip server={bogusServer} />,
},
];
const { container } = await renderPage(overrideRoutes(), "/", { paired: true });
act(() => {
const store = useConnectionStore.getState();
store.setServerStatus("online");
});
const dot = container.querySelector(".server-chip .dot");
expect(dot).not.toBeNull();
expect(dot).toHaveClass("dot--ok");
expect(dot).not.toHaveClass("dot--exited");
});
it("renders dot--idle and Unknown / 未知 when serverStatus is unknown", async () => {
const { container } = await renderPage(routes(), "/", { paired: true });
act(() => {
const store = useConnectionStore.getState();
store.setServer(realisticInfo);
store.setServerStatus("unknown");
});
const dot = container.querySelector(".server-chip .dot");
expect(dot).not.toBeNull();
expect(dot).toHaveClass("dot--idle");
expect(dot?.getAttribute("title")).toBe("Unknown");
expect(dot?.getAttribute("aria-label")).toBe("Unknown");
act(() => {
setLanguage("zh");
});
expect(dot?.getAttribute("title")).toBe("未知");
expect(dot?.getAttribute("aria-label")).toBe("未知");
});
it("renders dot--exited and Offline / 离线 when serverStatus is offline", async () => {
const { container } = await renderPage(routes(), "/", { paired: true });
act(() => {
const store = useConnectionStore.getState();
store.setServer(realisticInfo);
store.setServerStatus("offline");
});
const dot = container.querySelector(".server-chip .dot");
expect(dot).not.toBeNull();
expect(dot).toHaveClass("dot--exited");
expect(dot?.getAttribute("title")).toBe("Offline");
expect(dot?.getAttribute("aria-label")).toBe("Offline");
act(() => {
setLanguage("zh");
});
expect(dot?.getAttribute("title")).toBe("离线");
expect(dot?.getAttribute("aria-label")).toBe("离线");
});
});
+115
View File
@@ -0,0 +1,115 @@
import { describe, expect, it } from "vitest";
import { resolveServerStatus, type ServerStatusInput } from "@/features/status/server";
import type { InfoResponse } from "@/lib/api";
/** Exact real payload shape from the daemon: no `status` field present. */
const realisticInfo: InfoResponse = {
v: 1,
daemonId: "daemon-test-1",
machineId: "machine-test-1",
platform: "linux",
hostname: "devbook-eos",
os: "Linux 6.12.0",
version: "0.1.3",
uptimeMs: 123456,
port: 7676,
capabilities: ["read", "steer"],
limits: { maxInstances: 5 },
};
describe("resolveServerStatus", () => {
it("resolves unpaired client to offline even when info is present", () => {
const input: ServerStatusInput = {
paired: false,
info: realisticInfo,
healthOk: true,
};
expect(resolveServerStatus(input)).toBe("offline");
expect(resolveServerStatus({ paired: false })).toBe("offline");
expect(resolveServerStatus({ paired: false, info: realisticInfo })).toBe("offline");
});
it("resolves infoError to offline, even with stale cached info", () => {
const input: ServerStatusInput = {
paired: true,
infoError: true,
healthOk: true,
};
expect(resolveServerStatus(input)).toBe("offline");
expect(
resolveServerStatus({
paired: true,
info: realisticInfo,
infoError: true,
}),
).toBe("offline");
});
it("resolves healthError to degraded even when info is present", () => {
expect(
resolveServerStatus({
paired: true,
info: realisticInfo,
healthError: true,
}),
).toBe("degraded");
});
it("resolves info present + healthOk === false to degraded", () => {
const input: ServerStatusInput = {
paired: true,
info: realisticInfo,
healthOk: false,
};
expect(resolveServerStatus(input)).toBe("degraded");
});
it("resolves info present in exact real payload shape (no status field) to online", () => {
// Assert property absence so the regression contract is explicitly guarded.
expect("status" in realisticInfo).toBe(false);
expect(
resolveServerStatus({
paired: true,
info: realisticInfo,
}),
).toBe("online");
expect(
resolveServerStatus({
paired: true,
info: realisticInfo,
healthOk: true,
}),
).toBe("online");
});
it("resolves nothing yet to unknown", () => {
expect(
resolveServerStatus({
paired: true,
}),
).toBe("unknown");
});
it("resolves paired with info: null, healthOk: true to unknown", () => {
expect(
resolveServerStatus({
paired: true,
info: null,
healthOk: true,
}),
).toBe("unknown");
});
it("resolves paired with info: null, healthOk: null to unknown", () => {
expect(
resolveServerStatus({
paired: true,
info: null,
healthOk: null,
}),
).toBe("unknown");
});
});
+513
View File
@@ -0,0 +1,513 @@
import { describe, expect, it } from "vitest";
import type { SessionFlags, SessionState } from "@protocol/types";
import {
childSessionDot,
emptySessionState,
sessionDot,
sessionStatusKey,
subagentDot,
} from "@/features/chat/session-state";
type SessionOverrides = Omit<Partial<SessionState>, "flags"> & {
flags?: Partial<SessionFlags>;
};
function makeSession(overrides: SessionOverrides = {}): SessionState {
return {
...emptySessionState({ sessionId: overrides.sessionId ?? "s1", workspaceId: "w1" }),
...overrides,
flags: {
attention: false,
done: false,
error: false,
...(overrides.flags ?? {}),
},
};
}
function makeChild(overrides: SessionOverrides = {}): SessionState {
return makeSession({ parentId: "parent-1", ...overrides });
}
function makeSubagent(
overrides: Partial<SessionState["subagents"][number]> = {},
): SessionState["subagents"][number] {
return {
id: "sub-1",
status: "active",
...overrides,
};
}
describe("sessionDot (parent rows)", () => {
describe("base status matrix", () => {
it.each([
{
name: "exited -> dead",
state: makeSession({ status: "exited" }),
expected: { status: "dead" },
},
{
name: "error -> err",
state: makeSession({ flags: { error: true } }),
expected: { status: "err" },
},
{
name: "attention flag -> attention",
state: makeSession({ flags: { attention: true } }),
expected: { status: "attention" },
},
{
name: "attention array non-empty -> attention",
state: makeSession({ attention: [{ id: "q1" } as any] }),
expected: { status: "attention" },
},
{
name: "done -> ok",
state: makeSession({ flags: { done: true } }),
expected: { status: "ok" },
},
{
name: "busy -> busy",
state: makeSession({ status: "busy" }),
expected: { status: "busy" },
},
{
name: "compacting -> compacting",
state: makeSession({ status: "compacting" }),
expected: { status: "compacting" },
},
{
name: "interrupted -> dead",
state: makeSession({ status: "interrupted" }),
expected: { status: "dead" },
},
{
name: "starting -> idle",
state: makeSession({ status: "starting" }),
expected: { status: "idle" },
},
{
name: "idle -> idle",
state: makeSession({ status: "idle" }),
expected: { status: "idle" },
},
])("$name", ({ state, expected }) => {
expect(sessionDot(state)).toEqual(expected);
});
});
describe("priority collisions (bug fixes: exited > error > attention > done > busy)", () => {
it("error beats attention (flags.error outranks flags.attention)", () => {
const state = makeSession({
flags: { error: true, attention: true },
});
expect(sessionDot(state)).toEqual({ status: "err" });
});
it("error beats attention (flags.error outranks populated attention array)", () => {
const state = makeSession({
flags: { error: true },
attention: [{ id: "q1" } as any],
});
expect(sessionDot(state)).toEqual({ status: "err" });
});
it("exited beats error (status: exited outranks flags.error)", () => {
const state = makeSession({
status: "exited",
flags: { error: true },
});
expect(sessionDot(state)).toEqual({ status: "dead" });
});
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");
// …and it never wears the blue current marker either.
expect(sessionDot(makeSession({ status: "interrupted" }), { viewed: true })).toEqual({ status: "dead" });
});
it("attention beats done (flags.attention outranks flags.done)", () => {
const state = makeSession({
flags: { attention: true, done: true },
});
expect(sessionDot(state)).toEqual({ status: "attention" });
});
it("attention beats done (populated attention array outranks flags.done)", () => {
const state = makeSession({
flags: { done: true },
attention: [{ id: "q1" } as any],
});
expect(sessionDot(state)).toEqual({ status: "attention" });
});
it("done beats busy (flags.done outranks status: busy)", () => {
const state = makeSession({
status: "busy",
flags: { done: true },
});
expect(sessionDot(state)).toEqual({ status: "ok" });
});
it("exited beats attention (status: exited outranks flags.attention and attention array)", () => {
const state = makeSession({
status: "exited",
flags: { attention: true },
attention: [{ id: "q1" } as any],
});
expect(sessionDot(state)).toEqual({ status: "dead" });
});
it("error beats done (flags.error outranks flags.done)", () => {
const state = makeSession({
flags: { error: true, done: true },
});
expect(sessionDot(state)).toEqual({ status: "err" });
});
it("attention beats busy (flags.attention outranks status: busy)", () => {
const state = makeSession({
status: "busy",
flags: { attention: true },
});
expect(sessionDot(state)).toEqual({ status: "attention" });
});
});
describe("viewed overlay (you are here)", () => {
it.each([
{
name: "idle -> current",
state: makeSession({ status: "idle" }),
expected: { status: "idle", current: true },
},
{
name: "busy -> current (busy)",
state: makeSession({ status: "busy" }),
expected: { status: "busy", current: true },
},
{
name: "compacting -> current with status flipped to busy",
state: makeSession({ status: "compacting" }),
expected: { status: "busy", current: true },
},
])("$name", ({ state, expected }) => {
expect(sessionDot(state, { viewed: true })).toEqual(expected);
});
describe("no overlay when notification flags are set", () => {
it("suppresses current overlay when error is set", () => {
const state = makeSession({ status: "idle", flags: { error: true } });
expect(sessionDot(state, { viewed: true })).toEqual({ status: "err" });
});
it("suppresses current overlay when done is set", () => {
const state = makeSession({ status: "idle", flags: { done: true } });
expect(sessionDot(state, { viewed: true })).toEqual({ status: "ok" });
});
it("suppresses current overlay when flags.attention is set", () => {
const state = makeSession({ status: "idle", flags: { attention: true } });
expect(sessionDot(state, { viewed: true })).toEqual({ status: "attention" });
});
it("suppresses current overlay when attention array is non-empty", () => {
const state = makeSession({ status: "idle", attention: [{ id: "q1" } as any] });
expect(sessionDot(state, { viewed: true })).toEqual({ status: "attention" });
});
});
describe("no overlay when session is exited or interrupted", () => {
it("suppresses current overlay when status is exited", () => {
const state = makeSession({ status: "exited" });
expect(sessionDot(state, { viewed: true })).toEqual({ status: "dead" });
});
it("suppresses current overlay when status is interrupted", () => {
const state = makeSession({ status: "interrupted" });
expect(sessionDot(state, { viewed: true })).toEqual({ status: "dead" });
});
});
describe("no overlay when viewed is false or omitted", () => {
it("does not apply current when viewed: false on idle", () => {
const state = makeSession({ status: "idle" });
expect(sessionDot(state, { viewed: false })).toEqual({ status: "idle" });
});
it("does not apply current when viewed: false on busy", () => {
const state = makeSession({ status: "busy" });
expect(sessionDot(state, { viewed: false })).toEqual({ status: "busy" });
});
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" });
});
it("does not apply current when opts is omitted", () => {
const state = makeSession({ status: "idle" });
expect(sessionDot(state)).toEqual({ status: "idle" });
});
});
});
});
describe("childSessionDot (sub-session / tree depth > 0)", () => {
describe("base status matrix", () => {
it.each([
{
name: "exited -> exited (hollow ring)",
state: makeChild({ status: "exited" }),
opts: undefined,
expected: { status: "exited" },
},
{
name: "interrupted -> dead",
state: makeChild({ status: "interrupted" }),
opts: undefined,
expected: { status: "dead" },
},
{
name: "error with viewed -> { status: 'err', steady: true }",
state: makeChild({ flags: { error: true } }),
opts: { viewed: true },
expected: { status: "err", steady: true },
},
{
name: "error without viewed (viewed: false) -> { status: 'err', steady: false } (blinking)",
state: makeChild({ flags: { error: true } }),
opts: { viewed: false },
expected: { status: "err", steady: false },
},
{
name: "error without viewed (opts omitted) -> { status: 'err', steady: false } (blinking)",
state: makeChild({ flags: { error: true } }),
opts: undefined,
expected: { status: "err", steady: false },
},
{
name: "busy -> busy",
state: makeChild({ status: "busy" }),
opts: undefined,
expected: { status: "busy" },
},
{
name: "compacting -> busy (NOT compacting)",
state: makeChild({ status: "compacting" }),
opts: undefined,
expected: { status: "busy" },
},
{
name: "idle -> idle",
state: makeChild({ status: "idle" }),
opts: undefined,
expected: { status: "idle" },
},
])("$name", ({ state, opts, expected }) => {
expect(childSessionDot(state, opts)).toEqual(expected);
});
});
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");
});
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");
});
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");
});
it("returns idle instead of attention when attention array is populated on idle child", () => {
const state = makeChild({
status: "idle",
attention: [{ id: "q1" } as any],
});
const dot = childSessionDot(state);
expect(dot.status).not.toBe("attention");
expect(dot.status).toBe("idle");
});
it("returns busy instead of attention when flags.attention is set on busy child", () => {
const state = makeChild({
status: "busy",
flags: { attention: true },
attention: [{ id: "q1" } as any],
});
const dot = childSessionDot(state);
expect(dot.status).not.toBe("attention");
expect(dot.status).toBe("busy");
});
it("does not return ok or current when flags.done is set with viewed: true", () => {
const state = makeChild({ status: "idle", flags: { done: true } });
expect(childSessionDot(state, { viewed: true })).toEqual({ status: "idle" });
});
it("does not return attention or current when flags.attention is set with viewed: true", () => {
const state = makeChild({ status: "idle", flags: { attention: true } });
expect(childSessionDot(state, { viewed: true })).toEqual({ status: "idle" });
});
});
describe("viewed overlay on child rows", () => {
it("applies current overlay to idle child when viewed", () => {
const state = makeChild({ status: "idle" });
expect(childSessionDot(state, { viewed: true })).toEqual({
status: "idle",
current: true,
});
});
it("applies current overlay to busy child when viewed", () => {
const state = makeChild({ status: "busy" });
expect(childSessionDot(state, { viewed: true })).toEqual({
status: "busy",
current: true,
});
});
it("applies current overlay to compacting child with status flipped to busy", () => {
const state = makeChild({ status: "compacting" });
expect(childSessionDot(state, { viewed: true })).toEqual({
status: "busy",
current: true,
});
});
it("does not apply current overlay to exited child", () => {
const state = makeChild({ status: "exited" });
expect(childSessionDot(state, { viewed: true })).toEqual({
status: "exited",
});
});
it("does not apply current overlay to interrupted child", () => {
const state = makeChild({ status: "interrupted" });
expect(childSessionDot(state, { viewed: true })).toEqual({
status: "dead",
});
});
});
});
describe("subagentDot (manifest-only subagent tree rows)", () => {
it.each([
{
name: "active -> busy",
subagent: makeSubagent({ status: "active" }),
opts: undefined,
expected: { status: "busy" },
},
{
name: "completed -> exited",
subagent: makeSubagent({ status: "completed" }),
opts: undefined,
expected: { status: "exited" },
},
{
name: "dormant -> exited",
subagent: makeSubagent({ status: "dormant" }),
opts: undefined,
expected: { status: "exited" },
},
{
name: "failed with viewed -> steady err",
subagent: makeSubagent({ status: "failed" }),
opts: { viewed: true },
expected: { status: "err", steady: true },
},
{
name: "failed without viewed (viewed: false) -> blinking err",
subagent: makeSubagent({ status: "failed" }),
opts: { viewed: false },
expected: { status: "err", steady: false },
},
{
name: "failed without viewed (opts omitted) -> blinking err",
subagent: makeSubagent({ status: "failed" }),
opts: undefined,
expected: { status: "err", steady: false },
},
{
name: "interrupted -> dead",
subagent: makeSubagent({ status: "interrupted" }),
opts: undefined,
expected: { status: "dead" },
},
{
name: "unknown status -> idle",
subagent: makeSubagent({ status: "unknown" as any }),
opts: undefined,
expected: { status: "idle" },
},
])("$name", ({ subagent, opts, expected }) => {
expect(subagentDot(subagent, opts)).toEqual(expected);
});
});
describe("sessionStatusKey (stays distinct from dot)", () => {
it("returns 'interrupted' for interrupted session while dot returns 'dead'", () => {
const state = makeSession({ status: "interrupted" });
expect(sessionStatusKey(state)).toBe("interrupted");
expect(sessionDot(state)).toEqual({ status: "dead" });
});
it("returns 'attention' when flags.attention is true while dot returns 'attention'", () => {
const state = makeSession({ flags: { attention: true } });
expect(sessionStatusKey(state)).toBe("attention");
expect(sessionDot(state)).toEqual({ status: "attention" });
});
it("returns 'attention' when attention array has items while dot returns 'attention'", () => {
const state = makeSession({ attention: [{ id: "q1" } as any] });
expect(sessionStatusKey(state)).toBe("attention");
expect(sessionDot(state)).toEqual({ status: "attention" });
});
it("does not collapse interrupted into attention", () => {
const interrupted = makeSession({ status: "interrupted" });
const attention = makeSession({ flags: { attention: true } });
expect(sessionStatusKey(interrupted)).not.toBe(sessionStatusKey(attention));
});
it.each([
{ status: "busy" as const, expected: "busy" },
{ status: "starting" as const, expected: "busy" },
{ status: "compacting" as const, expected: "compacting" },
{ status: "exited" as const, expected: "exited" },
{ status: "idle" as const, expected: "idle" },
])("maps status $status to key '$expected'", ({ status, expected }) => {
const state = makeSession({ status });
expect(sessionStatusKey(state)).toBe(expected);
});
it("maps flags.error to 'error'", () => {
const state = makeSession({ flags: { error: true } });
expect(sessionStatusKey(state)).toBe("error");
});
it("maps flags.done to 'done'", () => {
const state = makeSession({ flags: { done: true } });
expect(sessionStatusKey(state)).toBe("done");
});
});
+355
View File
@@ -0,0 +1,355 @@
import { describe, expect, it } from "vitest";
import type { SessionState } from "@protocol/types";
import {
compareSiblings,
effectiveParentOf,
firstRootSession,
orderSessions,
type SiblingItem,
} from "@/features/chat/session-order";
import { emptySessionState } from "@/features/chat/session-state";
/** Minimal session row: only list metadata (`tab`, `createdAt`, `parentId`) matters here. */
function session(overrides: Partial<SessionState> & { sessionId: string }): SessionState {
const { sessionId, ...rest } = overrides;
return { ...emptySessionState({ sessionId, workspaceId: "w1" }), ...rest };
}
function ids(sessions: readonly SessionState[]): string[] {
return sessions.map((s) => s.sessionId);
}
function sibling(id: string, createdAt?: number | null): SiblingItem {
return createdAt === undefined ? { id } : { createdAt, id };
}
/** Deterministic Fisher–Yates shuffle (LCG seed) so a failure is reproducible. */
function shuffled<T>(items: readonly T[], seed: number): T[] {
const out = [...items];
let state = seed;
for (let i = out.length - 1; i > 0; i -= 1) {
state = (state * 1103515245 + 12345) % 2147483648;
const j = state % (i + 1);
const a = out[i]!;
out[i] = out[j]!;
out[j] = a;
}
return out;
}
describe("orderSessions — root rank (tab ASC)", () => {
it("orders roots by tab ascending and puts tabless roots last", () => {
const rows = [
session({ sessionId: "r3", tab: 3 }),
session({ sessionId: "plain" }),
session({ sessionId: "r1", tab: 1 }),
session({ sessionId: "r2", tab: 2 }),
];
expect(ids(orderSessions(rows))).toEqual(["r1", "r2", "r3", "plain"]);
});
it("ignores a non-positive or non-finite own tab", () => {
const rows = [
session({ sessionId: "b_zero", tab: 0 }),
session({ sessionId: "tabbed", tab: 4 }),
session({ sessionId: "b_negative", tab: -2 }),
session({ sessionId: "b_nan", tab: Number.NaN }),
session({ sessionId: "b_null", tab: null }),
];
// All the tabless rows tie at rank +Infinity, so plain code-unit id order decides.
expect(ids(orderSessions(rows))).toEqual(["tabbed", "b_nan", "b_negative", "b_null", "b_zero"]);
});
it("lets a child-view parent inherit the smallest tab of its descendants", () => {
const rows = [
session({ sessionId: "q", tab: 5 }),
session({ sessionId: "p" }),
session({ sessionId: "c", parentId: "p", tab: 2 }),
];
// `p` has no tab of its own but its subtree does: it lands at slot 2, before `q`.
expect(ids(orderSessions(rows))).toEqual(["p", "c", "q"]);
});
it("places a lineage at the earliest tab it occupies (smaller descendant tab wins over root tab)", () => {
const rows = [
session({ sessionId: "q", tab: 4 }),
session({ sessionId: "p", tab: 7 }),
session({ sessionId: "c", parentId: "p", tab: 2 }),
];
// Lineage p occupies tab 2 (via child c) and tab 7 (own tab); earliest is 2, so p lands before q (tab 4).
expect(ids(orderSessions(rows))).toEqual(["p", "c", "q"]);
});
it("prefers tabRank over a conflicting tab handle", () => {
// Visual tabline rank reflects :tabmove / mid-tabline insertion; handle is legacy fallback.
const rows = [
session({ sessionId: "moved_right", tab: 1, tabRank: 3 }),
session({ sessionId: "moved_left", tab: 5, tabRank: 1 }),
];
expect(ids(orderSessions(rows))).toEqual(["moved_left", "moved_right"]);
});
it("falls back to tab handle when tabRank is absent", () => {
const rows = [
session({ sessionId: "b", tab: 2 }),
session({ sessionId: "a", tab: 1 }),
];
expect(ids(orderSessions(rows))).toEqual(["a", "b"]);
});
it("orders mixed rows with tabRank and legacy tab handles deterministically", () => {
const rows = [
session({ sessionId: "rank2", tabRank: 2, tab: 9 }),
session({ sessionId: "handle1", tab: 1 }),
session({ sessionId: "rank3", tabRank: 3 }),
];
expect(ids(orderSessions(rows))).toEqual(["handle1", "rank2", "rank3"]);
});
it("inherits the minimum tab across the whole subtree, not just direct children", () => {
const rows = [
session({ sessionId: "other", tab: 6 }),
session({ sessionId: "p" }),
session({ sessionId: "c", parentId: "p", tab: 8 }),
session({ sessionId: "g", parentId: "c", tab: 3 }),
];
expect(ids(orderSessions(rows))).toEqual(["p", "c", "g", "other"]);
});
});
describe("orderSessions — root tie-break chain", () => {
it("sorts equal rank by createdAt DESC, then lastActiveAt DESC, then sessionId ASC", () => {
const rows = [
session({ sessionId: "b", createdAt: 100, lastActiveAt: 1_000 }),
session({ sessionId: "a", createdAt: 100, lastActiveAt: 1_000 }),
session({ sessionId: "c", createdAt: 100, lastActiveAt: 2_000 }),
session({ sessionId: "d", createdAt: 300, lastActiveAt: 500 }),
session({ sessionId: "e", lastActiveAt: 9_999 }),
session({ sessionId: "f" }),
];
expect(ids(orderSessions(rows))).toEqual(["d", "c", "a", "b", "e", "f"]);
});
it("applies the same tie-break chain when the equal rank comes from a tab", () => {
const rows = [
session({ sessionId: "b", tab: 1, createdAt: 100, lastActiveAt: 5 }),
session({ sessionId: "a", tab: 1, createdAt: 100, lastActiveAt: 9 }),
session({ sessionId: "c", tab: 1, createdAt: 200, lastActiveAt: 1 }),
];
expect(ids(orderSessions(rows))).toEqual(["c", "a", "b"]);
});
});
describe("compareSiblings", () => {
it("sorts createdAt DESC and puts missing createdAt last", () => {
expect([sibling("old", 1), sibling("new", 9), sibling("none")].sort(compareSiblings).map((s) => s.id)).toEqual([
"new",
"old",
"none",
]);
expect(compareSiblings(sibling("dated", 1), sibling("none"))).toBeLessThan(0);
expect(compareSiblings(sibling("none"), sibling("dated", 1))).toBeGreaterThan(0);
// Two missing createdAt values fall back to id ASC.
expect(compareSiblings(sibling("none"), sibling("alsoNone", null))).toBeGreaterThan(0);
});
it("tie-breaks equal createdAt (and missing createdAt) by id ascending", () => {
expect(compareSiblings(sibling("a", 5), sibling("b", 5))).toBeLessThan(0);
expect(compareSiblings(sibling("b", 5), sibling("a", 5))).toBeGreaterThan(0);
expect(compareSiblings(sibling("a", 5), sibling("a", 5))).toBe(0);
expect(compareSiblings(sibling("b"), sibling("a"))).toBeGreaterThan(0);
// Plain code-unit comparison: "B" (0x42) sorts before "a" (0x61), unlike localeCompare.
expect(compareSiblings(sibling("B", 1), sibling("a", 1))).toBeLessThan(0);
});
it("is a total order: every shuffled permutation sorts to the same sequence", () => {
const items: SiblingItem[] = [
sibling("a", 3),
sibling("b", 3),
sibling("c", 9),
sibling("d"),
sibling("e", null),
sibling("f", 1),
];
const expected = ["c", "a", "b", "f", "d", "e"];
for (let seed = 1; seed <= 20; seed += 1) {
expect(shuffled(items, seed).sort(compareSiblings).map((s) => s.id)).toEqual(expected);
}
});
});
describe("orderSessions — subtree flattening", () => {
it("emits a parent then its children by createdAt DESC, grandchildren nested", () => {
const rows = [
session({ sessionId: "root", tab: 1, createdAt: 10 }),
session({ sessionId: "childOld", parentId: "root", createdAt: 1 }),
session({ sessionId: "childNew", parentId: "root", createdAt: 5 }),
session({ sessionId: "grand1", parentId: "childOld", createdAt: 2 }),
session({ sessionId: "grand2", parentId: "childOld", createdAt: 3 }),
session({ sessionId: "grandNoDate", parentId: "childOld" }),
];
const ordered = orderSessions(rows);
expect(ids(ordered)).toEqual(["root", "childNew", "childOld", "grand2", "grand1", "grandNoDate"]);
// No row is dropped.
expect([...ids(ordered)].sort()).toEqual([...ids(rows)].sort());
});
it("tie-breaks equal createdAt siblings by sessionId ASC", () => {
const rows = [
session({ sessionId: "root", tab: 1 }),
session({ sessionId: "c_b", parentId: "root", createdAt: 7 }),
session({ sessionId: "c_a", parentId: "root", createdAt: 7 }),
session({ sessionId: "c_c", parentId: "root" }),
];
expect(ids(orderSessions(rows))).toEqual(["root", "c_a", "c_b", "c_c"]);
});
it("keeps a grandchild under its own parent, not directly under the root", () => {
const rows = [
session({ sessionId: "root", tab: 1 }),
session({ sessionId: "c1", parentId: "root", createdAt: 2 }),
session({ sessionId: "c2", parentId: "root", createdAt: 1 }),
session({ sessionId: "g1", parentId: "c2" }),
];
expect(ids(orderSessions(rows))).toEqual(["root", "c1", "c2", "g1"]);
});
it("renders a duplicate sessionId once, keeping the first occurrence", () => {
const rows = [
session({ sessionId: "root", tab: 1 }),
session({ sessionId: "dup", parentId: "root", createdAt: 1 }),
session({ sessionId: "dup", parentId: "root", createdAt: 999 }),
];
const ordered = orderSessions(rows);
expect(ids(ordered)).toEqual(["root", "dup"]);
expect(ordered[1]?.createdAt).toBe(1);
});
it("terminates on a parent cycle and renders both rows exactly once", () => {
const ordered = orderSessions([
session({ sessionId: "a", parentId: "b" }),
session({ sessionId: "b", parentId: "a" }),
]);
expect(ids(ordered)).toEqual(["a", "b"]);
});
it("keeps every row of a 3-cycle plus a child of the cycle", () => {
const rows = [
session({ sessionId: "a", parentId: "b" }),
session({ sessionId: "b", parentId: "c" }),
session({ sessionId: "c", parentId: "a" }),
session({ sessionId: "x", parentId: "a" }),
];
const ordered = orderSessions(rows);
const index = new Map(rows.map((r) => [r.sessionId, r]));
expect(ordered).toHaveLength(4);
expect([...ids(ordered)].sort()).toEqual(["a", "b", "c", "x"]);
// Cycle-breaking promotes every member and child of the cycle to a root ('never lose a row').
expect(effectiveParentOf(rows[3]!, index)).toBeNull();
});
it("treats a self-parent row as a root", () => {
const ordered = orderSessions([
session({ sessionId: "self", parentId: "self" }),
session({ sessionId: "other", tab: 1 }),
]);
expect(ids(ordered)).toEqual(["other", "self"]);
});
});
describe("orderSessions — determinism", () => {
it("yields the same id sequence for 20 shuffles of the same input", () => {
const rows = [
session({ sessionId: "r1", tab: 2, createdAt: 50 }),
session({ sessionId: "c1", parentId: "r1", createdAt: 20 }),
session({ sessionId: "c2", parentId: "r1", createdAt: 30 }),
session({ sessionId: "g2", parentId: "c2", createdAt: 5 }),
session({ sessionId: "g3", parentId: "c2" }),
session({ sessionId: "r2", createdAt: 400 }),
session({ sessionId: "g1", parentId: "r2", tab: 3 }),
session({ sessionId: "r3", createdAt: 100 }),
];
const expected = ["r1", "c2", "g2", "g3", "c1", "r2", "g1", "r3"];
expect(ids(orderSessions(rows))).toEqual(expected);
for (let seed = 1; seed <= 20; seed += 1) {
expect(ids(orderSessions(shuffled(rows, seed)))).toEqual(expected);
}
});
});
describe("firstRootSession", () => {
it("returns the first ordered root, skipping children that sort earlier", () => {
const rows = [
session({ sessionId: "child", parentId: "root", createdAt: 9_999 }),
session({ sessionId: "root", createdAt: 1 }),
];
expect(firstRootSession(rows)?.sessionId).toBe("root");
expect(ids(orderSessions(rows))).toEqual(["root", "child"]);
});
it("returns undefined for an empty list", () => {
expect(firstRootSession([])).toBeUndefined();
});
});
describe("effectiveParentOf", () => {
function indexOf(rows: readonly SessionState[]): Map<string, SessionState> {
return new Map(rows.map((row) => [row.sessionId, row]));
}
it("returns the parent id when the parent exists", () => {
const rows = [
session({ sessionId: "root" }),
session({ sessionId: "child", parentId: "root" }),
session({ sessionId: "grand", parentId: "child" }),
];
const index = indexOf(rows);
expect(effectiveParentOf(rows[1]!, index)).toBe("root");
// The direct parent is reported, never the grandparent.
expect(effectiveParentOf(rows[2]!, index)).toBe("child");
});
it("returns null for a missing parent, a null parent and a self parent", () => {
const orphan = session({ sessionId: "orphan", parentId: "gone" });
const root = session({ sessionId: "root" });
const self = session({ sessionId: "self", parentId: "self" });
const index = indexOf([orphan, root, self]);
expect(effectiveParentOf(orphan, index)).toBeNull();
expect(effectiveParentOf(root, index)).toBeNull();
expect(effectiveParentOf(self, index)).toBeNull();
});
it("returns null when the parent chain forms a cycle", () => {
const a = session({ sessionId: "a", parentId: "b" });
const b = session({ sessionId: "b", parentId: "a" });
const index = indexOf([a, b]);
expect(effectiveParentOf(a, index)).toBeNull();
expect(effectiveParentOf(b, index)).toBeNull();
});
});
+98
View File
@@ -0,0 +1,98 @@
import { describe, expect, it } from "vitest";
import { normalizeSessionsPayload, tabSessionRows } from "@/features/chat/session-state";
/**
* `workspace.query{kind:"sessions"}` rows come from the plugin as a union of the
* workspace's JSONL history and its live sessions. Only the tab-backed component
* is the nvim session list; everything else is history.
*/
function ids(rows: Record<string, unknown>[]): string[] {
return rows.map((row) => String(row.sessionId ?? row.session_id ?? row.id));
}
describe("tabSessionRows", () => {
it("drops disk-only history and keeps the tab-backed row", () => {
const raw = {
sessions: [
{ sessionId: "old-1", name: "history one", status: "done" },
{ sessionId: "tab-1", name: "the only tab", tab: 1, live: true, status: "idle" },
{ sessionId: "old-2", name: "history two" },
],
};
expect(ids(tabSessionRows(raw))).toEqual(["tab-1"]);
});
it("drops a live session that owns no tab", () => {
// A detached background session is not an nvim tab: `:PiSessions` renders
// it as a child row, never as a root.
const raw = {
sessions: [
{ sessionId: "tab-1", tab: 1, live: true },
{ sessionId: "detached", live: true, status: "busy" },
],
};
expect(ids(tabSessionRows(raw))).toEqual(["tab-1"]);
});
it("keeps the sub-sessions linked to a tab, at any depth", () => {
const raw = {
sessions: [
{ sessionId: "child", parentId: "tab-1", status: "interrupted" },
{ sessionId: "grandchild", parentId: "child", status: "done" },
{ sessionId: "tab-1", tab: 1, live: true },
{ sessionId: "orphan-history", parentId: "gone", status: "done" },
],
};
expect(ids(tabSessionRows(raw))).toEqual(["child", "grandchild", "tab-1"]);
});
it("keeps the parent row when the tab is in a child view", () => {
// `view_parent_id`: the tab is attached to the child session, the parent
// row anchors the tree and its other children stay in the list.
const raw = {
sessions: [
{ sessionId: "root", live: true, status: "idle" },
{ sessionId: "viewed-child", parentId: "root", tab: 2, live: true },
{ sessionId: "sibling", parentId: "root", status: "completed" },
],
};
expect(ids(tabSessionRows(raw))).toEqual(["root", "viewed-child", "sibling"]);
});
it("accepts a bare array payload and the snake_case aliases", () => {
const raw = [
{ session_id: "old" },
{ session_id: "child", parent_id: "tab-1" },
{ session_id: "tab-1", tab: 3 },
];
expect(ids(tabSessionRows(raw))).toEqual(["child", "tab-1"]);
});
it("returns no rows when nothing is attached to a tab", () => {
expect(tabSessionRows({ sessions: [{ sessionId: "old-1" }, { sessionId: "old-2" }] })).toEqual([]);
expect(tabSessionRows({ sessions: [] })).toEqual([]);
expect(tabSessionRows(undefined)).toEqual([]);
});
it("feeds the render states so a historical row never reaches the tree", () => {
const states = normalizeSessionsPayload(
tabSessionRows({
sessions: [
{ sessionId: "old-1", name: "history", status: "done" },
{ sessionId: "tab-1", name: "the only tab", tab: 1, live: true, status: "idle" },
],
}),
"w1",
);
expect(states.map((state) => state.sessionId)).toEqual(["tab-1"]);
expect(states[0]?.name).toBe("the only tab");
});
});
+74
View File
@@ -0,0 +1,74 @@
import { describe, expect, it } from "vitest";
import { FALLBACK_NAME_CHARS, sessionTitle, subagentTitle } from "@/features/chat/session-title";
const phrases = { unnamed: "(unnamed)", subagentUnnamed: "sub-session" };
describe("sessionTitle", () => {
it("prefers the session's own name", () => {
expect(sessionTitle({ name: "Fix login", firstMessage: "hello" }, phrases)).toEqual({
text: "Fix login",
kind: "name",
provisional: false,
spinner: false,
});
});
it("trims the name and falls through when it is blank", () => {
expect(sessionTitle({ name: " Fix login " }, phrases).text).toBe("Fix login");
expect(sessionTitle({ name: " ", firstMessage: "hello" }, phrases).text).toBe("hello");
expect(sessionTitle({ name: "", firstMessage: "" }, phrases).text).toBe("(unnamed)");
});
it("falls back to the first user message (pi2.nvim's first_message)", () => {
expect(sessionTitle({ name: null, firstMessage: " Fix the auth bug " }, phrases)).toEqual({
text: "Fix the auth bug",
kind: "first-message",
provisional: false,
spinner: false,
});
});
it("shows (unnamed) when nothing is known — never an id", () => {
const title = sessionTitle({ name: null, firstMessage: null }, phrases);
expect(title).toEqual({ text: "(unnamed)", kind: "unnamed", provisional: true, spinner: false });
});
it("suppresses the first message and spins while the backend generates a title", () => {
expect(sessionTitle({ name: null, firstMessage: "Fix the auth bug", titleGenerating: true }, phrases)).toEqual({
text: "(unnamed)",
kind: "generating",
provisional: true,
spinner: true,
});
});
it("drops the spinner the moment a real name arrives", () => {
const title = sessionTitle({ name: "Fix login", titleGenerating: true }, phrases);
expect(title.kind).toBe("name");
expect(title.spinner).toBe(false);
});
});
describe("subagentTitle", () => {
it("prefers the sub-session name", () => {
expect(subagentTitle({ name: "researcher", task: "Research the auth flow" }, phrases).text).toBe("researcher");
});
it("derives the name from the task prompt, capped like Manifest.fallback_name", () => {
const task = "x".repeat(FALLBACK_NAME_CHARS + 25);
const title = subagentTitle({ name: null, task }, phrases);
expect(title.text).toBe("x".repeat(FALLBACK_NAME_CHARS));
expect(title.kind).toBe("task");
expect(FALLBACK_NAME_CHARS).toBe(40);
});
it("falls back to sub-session — never the subagent id", () => {
expect(subagentTitle({ name: " ", task: "" }, phrases)).toEqual({
text: "sub-session",
kind: "unnamed",
provisional: true,
spinner: false,
});
});
});
+140
View File
@@ -0,0 +1,140 @@
import { render, screen } from "@testing-library/react";
import type { ComponentProps } from "react";
import { beforeAll, describe, expect, it, vi } from "vitest";
import { SessionTree } from "@/features/chat/session-tree";
import { setLanguage } from "@/lib/i18n";
import type { SessionState } from "@/lib/protocol";
import { sessionFixture, subagentFixture } from "./chat-fixtures";
beforeAll(async () => {
await setLanguage("en");
});
/** The title of the row for `sessionId` (`null` when the row is absent). */
function rowTitleText(container: HTMLElement, sessionId: string): string | null {
const row = container.querySelector<HTMLElement>(`[data-session-id="${sessionId}"]`);
return row?.querySelector<HTMLElement>(".t-name")?.textContent?.trim() ?? null;
}
function renderTree(overrides: Partial<ComponentProps<typeof SessionTree>> = {}) {
const sessions = overrides.sessions ?? [];
return render(
<SessionTree
sessions={sessions}
workspaces={[
{
workspaceId: "W1",
cwd: "/work/w1",
name: "W1",
trusted: true,
exists: true,
sessionCount: sessions.length,
liveCount: 0,
lastActiveAt: 0,
instance: null,
},
]}
activeWorkspaceId="W1"
selectedId={null}
activeSubagentId={null}
filter=""
collapsed={{}}
activeOnly={false}
showHidden={false}
connected
creating={false}
onFilter={vi.fn()}
onToggleCollapse={vi.fn()}
onToggleAll={vi.fn()}
onToggleActiveOnly={vi.fn()}
onToggleShowHidden={vi.fn()}
onSelectSession={vi.fn()}
onSelectWorkspace={vi.fn()}
onSelectSubagent={vi.fn()}
onNewSession={vi.fn()}
onRenameSession={vi.fn()}
onCloseSession={vi.fn()}
onDispatchSubagent={vi.fn()}
onRenameSubagent={vi.fn()}
{...overrides}
/>,
);
}
describe("session list titles (pi2.nvim parity)", () => {
it("renders (unnamed) for a session without a name and never the session id", () => {
const sessionId = "9f8c1d2e-0000-4000-8000-aaaaaaaaaaaa";
const { container } = renderTree({
sessions: [sessionFixture({ sessionId, name: null, firstMessage: null })],
});
expect(rowTitleText(container, sessionId)).toBe("(unnamed)");
expect(container.textContent ?? "").not.toContain(sessionId);
// Identity still rides on the DOM attribute (routing/select handlers).
expect(container.querySelector(`[data-session-id="${sessionId}"]`)).not.toBeNull();
});
it("marks the placeholder so it renders as the muted, non-animated state", () => {
const sessionId = "s-unnamed";
const { container } = renderTree({
sessions: [sessionFixture({ sessionId, name: null, firstMessage: null })],
});
const name = container.querySelector<HTMLElement>(`[data-session-id="${sessionId}"] .t-name`);
expect(name?.classList.contains("is-unnamed")).toBe(true);
expect(name?.classList.contains("is-generating")).toBe(false);
});
it("prefers the first user message over the placeholder", () => {
const sessionId = "s-first";
const { container } = renderTree({
sessions: [sessionFixture({ sessionId, name: null, firstMessage: "Fix the auth bug" })],
});
expect(rowTitleText(container, sessionId)).toBe("Fix the auth bug");
});
it("keeps (unnamed) and prefixes the braille spinner while a title is generated", () => {
const sessionId = "s-generating";
// The plugin's `pi-title` status is not on the wire yet, so the flag is
// injected here: the row must already react the way pi2.nvim does.
const session = {
...sessionFixture({ sessionId, name: null, firstMessage: "Fix the auth bug" }),
titleGenerating: true,
} as SessionState;
const { container } = renderTree({ sessions: [session] });
const row = container.querySelector<HTMLElement>(`[data-session-id="${sessionId}"]`);
// Spinner is a prefix, the name stays the placeholder (no first message).
expect(row?.querySelector(".t-spinner")).not.toBeNull();
expect(rowTitleText(container, sessionId)).toBe("(unnamed)");
expect(row?.querySelector(".t-name")?.classList.contains("is-generating")).toBe(true);
});
it("keeps the real name when there is one", () => {
const { container } = renderTree({
sessions: [sessionFixture({ sessionId: "s-named", name: "Alpha", subagents: [] })],
});
expect(rowTitleText(container, "s-named")).toBe("Alpha");
});
it("labels a nameless sub-session by its task prompt, not its id", () => {
const subagent = subagentFixture({ id: "sub-uuid-1234", name: undefined, task: "Survey the plugin bridge" });
const { container } = renderTree({
sessions: [sessionFixture({ sessionId: "s-parent", name: "Alpha", subagents: [subagent] })],
});
const sub = container.querySelector<HTMLElement>('[data-subagent-id="sub-uuid-1234"] .t-name');
expect(sub?.textContent?.trim()).toBe("Survey the plugin bridge");
expect(container.textContent ?? "").not.toContain("sub-uuid-1234");
});
it("falls back to sub-session when the manifest carries no name or task", () => {
const subagent = subagentFixture({ id: "sub-empty", name: undefined, task: undefined });
const { container } = renderTree({
sessions: [sessionFixture({ sessionId: "s-parent", name: "Alpha", subagents: [subagent] })],
});
expect(screen.getByText("sub-session")).toBeTruthy();
expect(container.textContent ?? "").not.toContain("sub-empty");
});
});
+126 -5
View File
@@ -126,7 +126,9 @@ describe("buildSessionTree", () => {
expect(tree[0]?.children[0]?.hidden).toBe(true);
});
it("preserves input order and counts rendered children only", () => {
it("orders roots canonically and counts rendered children only", () => {
// Roots ranked by tab asc (pi2.nvim manager.lua); ties broken by
// createdAt desc, lastActiveAt desc, sessionId asc (console determinism rule).
const tree = buildSessionTree([
sessionFixture({ sessionId: "s2", name: "Beta" }),
sessionFixture({ sessionId: "s1", name: "Alpha" }),
@@ -134,11 +136,130 @@ describe("buildSessionTree", () => {
childOf({ sessionId: "c2", visible: false }),
]);
// No sorting: roots keep the order the list delivered.
expect(ids(tree)).toEqual(["s2", "s1"]);
// Roots without tab or timestamp tie-break by sessionId asc: s1 before s2.
expect(ids(tree)).toEqual(["s1", "s2"]);
// The hidden child is not rendered, so it is not counted either.
expect(tree[1]?.childCount).toBe(1);
expect(ids(tree[1]?.children ?? [])).toEqual(["c1"]);
expect(tree[0]?.childCount).toBe(1);
expect(ids(tree[0]?.children ?? [])).toEqual(["c1"]);
});
it("sorts roots by tab asc with tab-less roots last", () => {
// Attached tabs ranked by tab visual order (pi2.nvim manager.lua);
// placing tab-less rows last is a console rule (nvim excludes detached sessions from Sessions.list()).
const tree = buildSessionTree([
sessionFixture({ sessionId: "tabless", tab: null, createdAt: 5000 }),
sessionFixture({ sessionId: "tab2", tab: 2, createdAt: 1000 }),
sessionFixture({ sessionId: "tab1", tab: 1, createdAt: 2000 }),
]);
expect(ids(tree)).toEqual(["tab1", "tab2", "tabless"]);
});
it("inherits viewing child tab for a child-view parent with no tab", () => {
// pi2.nvim lua/pi/sessions/manager.lua: in child view the parent row occupies
// the tab's slot (inherits smallest tab in its subtree).
const tree = buildSessionTree([
sessionFixture({ sessionId: "root2", tab: 2 }),
sessionFixture({ sessionId: "parent", tab: null }), // child has tab: 1
sessionFixture({ sessionId: "child", parentId: "parent", tab: 1 }),
sessionFixture({ sessionId: "root3", tab: 3 }),
]);
// "parent" inherits tab 1 from "child", so rank 1 < rank 2 < rank 3.
expect(ids(tree)).toEqual(["parent", "root2", "root3"]);
expect(ids(tree[0]?.children ?? [])).toEqual(["child"]);
});
it("sorts siblings by createdAt desc with sessionId asc tie-break", () => {
// pi2.nvim lua/pi/subsessions/manifest.lua: created_at desc, _id asc.
const tree = buildSessionTree([
sessionFixture({ sessionId: "parent", tab: 1 }),
sessionFixture({ sessionId: "c-old", parentId: "parent", createdAt: 1000 }),
sessionFixture({ sessionId: "c-tie-2", parentId: "parent", createdAt: 2000 }),
sessionFixture({ sessionId: "c-tie-1", parentId: "parent", createdAt: 2000 }),
sessionFixture({ sessionId: "c-new", parentId: "parent", createdAt: 3000 }),
sessionFixture({ sessionId: "c-no-time", parentId: "parent" }),
]);
expect(ids(tree[0]?.children ?? [])).toEqual([
"c-new",
"c-tie-1",
"c-tie-2",
"c-old",
"c-no-time",
]);
});
it("sorts child session rows using the same-id manifest entry createdAt when row createdAt is absent", () => {
// pi2.nvim lua/pi/subsessions/manifest.lua: siblings ordered by manifest entry
// created_at desc. The child session row's sort key inherits manifest createdAt.
const tree = buildSessionTree([
sessionFixture({
sessionId: "parent",
tab: 1,
subagents: [
subagentFixture({ id: "child-undated", createdAt: 5000 }),
],
}),
sessionFixture({ sessionId: "child-undated", parentId: "parent" }),
sessionFixture({ sessionId: "sibling-dated", parentId: "parent", createdAt: 1000 }),
]);
expect(ids(tree[0]?.children ?? [])).toEqual(["child-undated", "sibling-dated"]);
expect(tree[0]?.children[0]?.kind).toBe("session");
});
it("interleaves synthetic subagents among real child sessions by createdAt with session row winning", () => {
// pi2.nvim lua/pi/subsessions/manifest.lua: merged sibling order by manifest created_at desc,
// and a session row wins over a same-id manifest subagent for rendering.
const tree = buildSessionTree([
sessionFixture({
sessionId: "parent",
tab: 1,
subagents: [
subagentFixture({ id: "agent-newest", createdAt: 4000 }),
subagentFixture({ id: "real-child-1", createdAt: 3000, name: "synthetic version" }),
subagentFixture({ id: "agent-middle", createdAt: 2000 }),
subagentFixture({ id: "agent-oldest", createdAt: 500 }),
],
}),
sessionFixture({ sessionId: "real-child-1", parentId: "parent", createdAt: 9999 }),
sessionFixture({ sessionId: "real-child-2", parentId: "parent", createdAt: 1000 }),
]);
// real-child-1 is sorted by manifest createdAt (3000, not row's 9999):
// agent-newest (4000) > real-child-1 (3000) > agent-middle (2000) > real-child-2 (1000) > agent-oldest (500)
expect(ids(tree[0]?.children ?? [])).toEqual([
"agent-newest",
"real-child-1",
"agent-middle",
"real-child-2",
"agent-oldest",
]);
expect(tree[0]?.children[1]?.kind).toBe("session");
});
it("produces deterministic rendered order regardless of input array shuffle", () => {
// Total, deterministic order per rule 4.
const items = [
sessionFixture({ sessionId: "r2", tab: 2, createdAt: 1000 }),
sessionFixture({ sessionId: "r1", tab: 1, createdAt: 2000 }),
sessionFixture({ sessionId: "c1", parentId: "r1", createdAt: 3000 }),
sessionFixture({ sessionId: "c2", parentId: "r1", createdAt: 4000 }),
sessionFixture({ sessionId: "r3", tab: null, createdAt: 5000 }),
sessionFixture({ sessionId: "r4", tab: null, createdAt: 5000, lastActiveAt: 6000 }),
];
const treeOriginal = buildSessionTree(items);
const expectedRoots = ids(treeOriginal);
const expectedR1Children = ids(treeOriginal[0]?.children ?? []);
// Shuffle input and verify output matches
const shuffled = [items[4]!, items[1]!, items[5]!, items[0]!, items[3]!, items[2]!];
const treeShuffled = buildSessionTree(shuffled);
expect(ids(treeShuffled)).toEqual(expectedRoots);
expect(ids(treeShuffled[0]?.children ?? [])).toEqual(expectedR1Children);
});
it("marks the ancestor chain of the routed row forced-open", () => {
+173 -1
View File
@@ -1,4 +1,4 @@
import { beforeEach, describe, expect, it } from "vitest";
import { beforeEach, describe, expect, it, vi } from "vitest";
import { emptySessionState, normalizeSnapshotState } from "@/features/chat/session-state";
import { useSessionsStore } from "@/stores/sessions";
@@ -136,3 +136,175 @@ describe("sessions store — tree metadata", () => {
expect(state().getSession("c1")?.visible).toBe(false);
});
});
function fixture(
overrides: Omit<Partial<ReturnType<typeof sessionFixture>>, "flags"> & {
flags?: Partial<ReturnType<typeof sessionFixture>["flags"]>;
},
) {
return sessionFixture({
...overrides,
flags: {
attention: false,
done: false,
error: false,
...(overrides.flags ?? {}),
},
});
}
describe("sessions store — markSeen", () => {
it("clears flags.done when seen", () => {
state().setSessions("w1", [fixture({ sessionId: "s1", workspaceId: "w1", flags: { done: true } })]);
expect(state().getSession("s1")?.flags.done).toBe(true);
state().markSeen("s1");
expect(state().getSession("s1")?.flags).toEqual({
attention: false,
done: false,
error: false,
});
});
it("clears flags.error when seen", () => {
state().setSessions("w1", [fixture({ sessionId: "s1", workspaceId: "w1", flags: { error: true } })]);
expect(state().getSession("s1")?.flags.error).toBe(true);
state().markSeen("s1");
expect(state().getSession("s1")?.flags).toEqual({
attention: false,
done: false,
error: false,
});
});
it("clears both flags.done and flags.error simultaneously", () => {
state().setSessions("w1", [
fixture({ sessionId: "s1", workspaceId: "w1", flags: { done: true, error: true } }),
]);
state().markSeen("s1");
expect(state().getSession("s1")?.flags).toEqual({
attention: false,
done: false,
error: false,
});
});
it("keeps flags.attention when attention array is non-empty", () => {
state().setSessions("w1", [
fixture({
sessionId: "s1",
workspaceId: "w1",
flags: { done: true, attention: true },
attention: [{ id: "q1" } as any],
}),
]);
state().markSeen("s1");
expect(state().getSession("s1")?.flags).toEqual({
attention: true,
done: false,
error: false,
});
});
it("sets flags.attention to true if attention array has items even when flag was false", () => {
state().setSessions("w1", [
fixture({
sessionId: "s1",
workspaceId: "w1",
flags: { done: true, attention: false },
attention: [{ id: "q1" } as any],
}),
]);
state().markSeen("s1");
expect(state().getSession("s1")?.flags).toEqual({
attention: true,
done: false,
error: false,
});
});
it("clears stale flags.attention when attention array is empty", () => {
state().setSessions("w1", [
fixture({
sessionId: "s1",
workspaceId: "w1",
flags: { attention: true, done: false, error: false },
attention: [],
}),
]);
state().markSeen("s1");
expect(state().getSession("s1")?.flags).toEqual({
attention: false,
done: false,
error: false,
});
});
it("leaves other rows untouched in the same and other workspaces", () => {
const s1 = fixture({ sessionId: "s1", workspaceId: "w1", flags: { done: true } });
const s2 = fixture({ sessionId: "s2", workspaceId: "w1", flags: { done: true } });
const s3 = fixture({ sessionId: "s3", workspaceId: "w2", flags: { error: true } });
state().setSessions("w1", [s1, s2]);
state().setSessions("w2", [s3]);
const s2Before = state().getSession("s2");
const s3Before = state().getSession("s3");
state().markSeen("s1");
expect(state().getSession("s1")?.flags.done).toBe(false);
// Untouched rows preserve flags and object identity
expect(state().getSession("s2")).toBe(s2Before);
expect(state().getSession("s2")?.flags.done).toBe(true);
expect(state().getSession("s3")).toBe(s3Before);
expect(state().getSession("s3")?.flags.error).toBe(true);
});
it("returns the same state object (identity) and does not notify subscribers when there is nothing to consume", () => {
state().setSessions("w1", [
fixture({
sessionId: "s1",
workspaceId: "w1",
flags: { done: false, error: false, attention: false },
attention: [],
}),
]);
const before = useSessionsStore.getState();
const listener = vi.fn();
const unsub = useSessionsStore.subscribe(listener);
state().markSeen("s1");
const after = useSessionsStore.getState();
expect(after).toBe(before);
expect(listener).not.toHaveBeenCalled();
unsub();
});
it("is a no-op for an unknown id, returning the same state object without notifying subscribers", () => {
state().setSessions("w1", [
fixture({ sessionId: "s1", workspaceId: "w1", flags: { done: true } }),
]);
const before = useSessionsStore.getState();
const listener = vi.fn();
const unsub = useSessionsStore.subscribe(listener);
state().markSeen("unknown-id");
const after = useSessionsStore.getState();
expect(after).toBe(before);
expect(listener).not.toHaveBeenCalled();
expect(state().getSession("s1")?.flags.done).toBe(true);
unsub();
});
});
+31 -18
View File
@@ -4,25 +4,38 @@ import { afterEach, vi } from "vitest";
afterEach(() => {
cleanup();
localStorage.clear();
document.documentElement.removeAttribute("data-theme");
if (typeof localStorage !== "undefined") {
localStorage.clear();
}
if (typeof document !== "undefined") {
document.documentElement.removeAttribute("data-theme");
}
});
// next-themes / responsive helpers expect these in jsdom.
if (!window.matchMedia) {
Object.defineProperty(window, "matchMedia", {
writable: true,
value: vi.fn().mockImplementation((query: string) => ({
matches: false,
media: query,
onchange: null,
addListener: vi.fn(),
removeListener: vi.fn(),
addEventListener: vi.fn(),
removeEventListener: vi.fn(),
dispatchEvent: vi.fn(),
})),
});
if (typeof window !== "undefined") {
// next-themes / responsive helpers expect these in jsdom.
if (!window.matchMedia) {
Object.defineProperty(window, "matchMedia", {
writable: true,
value: vi.fn().mockImplementation((query: string) => ({
matches: false,
media: query,
onchange: null,
addListener: vi.fn(),
removeListener: vi.fn(),
addEventListener: vi.fn(),
dispatchEvent: vi.fn(),
})),
});
}
// jsdom ships stubs that print "Not implemented: ..." errors to stderr.
// Replace them with silent vi.fn() mocks.
window.scrollTo = vi.fn();
}
if (typeof HTMLCanvasElement !== "undefined") {
HTMLCanvasElement.prototype.getContext = vi.fn();
}
if (!globalThis.ResizeObserver) {
@@ -34,6 +47,6 @@ if (!globalThis.ResizeObserver) {
globalThis.ResizeObserver = ResizeObserverStub;
}
if (!Element.prototype.scrollIntoView) {
if (typeof Element !== "undefined") {
Element.prototype.scrollIntoView = vi.fn();
}
+30 -1
View File
@@ -284,7 +284,10 @@ describe("StatusPage", () => {
const head = document.querySelector(".page-head.status-head");
expect(head).not.toBeNull();
expect(head?.querySelector(".dot--lg")).not.toBeNull();
await waitFor(() => {
const dot = head?.querySelector(".dot--lg");
expect(dot).toHaveClass("dot--attention");
});
await waitFor(() =>
expect(within(head as HTMLElement).getByText(/pi2-box · pi2-box ·/)).toBeInTheDocument(),
);
@@ -305,6 +308,32 @@ describe("StatusPage", () => {
expect(within(info).queryByText("—")).not.toBeInTheDocument();
});
it("renders the page header dot with dot--ok for a healthy daemon", async () => {
mockApi(
apiRoutes([
{
path: "/api/v1/health",
handler: () => ({
body: {
ok: true,
checkedAt: Date.now(),
items: [{ name: "plugin", ok: true, detail: "connected" }],
},
}),
},
]),
);
await renderPage(routes(), "/status", { paired: true });
await screen.findByText("Server info");
const head = document.querySelector(".page-head.status-head");
expect(head).not.toBeNull();
await waitFor(() => {
const dot = head?.querySelector(".dot--lg");
expect(dot).toHaveClass("dot--ok");
});
});
it("counts failed health checks and keeps the per-check list", async () => {
mockApi(apiRoutes());
await renderPage(routes(), "/status", { paired: true });
+27 -11
View File
@@ -5,6 +5,25 @@ import { defineConfig } from "vitest/config";
const DAEMON = "http://127.0.0.1:7676";
const REPO_ROOT = path.resolve(import.meta.dirname, "..");
/**
* Dev/preview proxy for one daemon surface.
*
* `changeOrigin` rewrites `Host` only, so the browser's own `Origin`
* (`http://localhost:5173`) reaches the daemon — whose allowlist is derived from
* the daemon's own port — and every POST/WS upgrade would be rejected with
* `403 origin is not allowed`. Presenting the daemon's own origin (always in that
* derived allowlist) keeps `pnpm --dir web dev` working without `PI2_ORIGINS`,
* and keeps the daemon's Origin check on rather than bypassing it.
*/
function daemonProxy({ ws = false } = {}) {
return {
target: DAEMON,
changeOrigin: true,
headers: { origin: DAEMON },
...(ws ? { ws: true } : {}),
};
}
export default defineConfig({
plugins: [react()],
resolve: {
@@ -22,21 +41,14 @@ export default defineConfig({
port: 5173,
strictPort: false,
proxy: {
"/api": {
target: DAEMON,
changeOrigin: true,
},
"/ws": {
target: DAEMON,
changeOrigin: true,
ws: true,
},
"/api": daemonProxy(),
"/ws": daemonProxy({ ws: true }),
},
},
preview: {
proxy: {
"/api": { target: DAEMON, changeOrigin: true },
"/ws": { target: DAEMON, changeOrigin: true, ws: true },
"/api": daemonProxy(),
"/ws": daemonProxy({ ws: true }),
},
},
test: {
@@ -45,6 +57,10 @@ export default defineConfig({
setupFiles: ["./tests/setup.ts"],
include: ["tests/**/*.test.{ts,tsx}"],
css: true,
// Reuse environment instances across test files within workers to avoid
// recreating jsdom 35 times (which accounted for ~52% of CPU time).
isolate: false,
testTimeout: 15000,
restoreMocks: true,
},
});