12 Commits
Author SHA1 Message Date
yuez ce87799b61 test(e2e): cover prompt-history recall end to end
A14 (API) and B15 (browser) make the feature verifiable against a real daemon,
a real headless nvim and a real `pi`.

- A14: the prompt A4 sent through `prompt.send` is in the plugin's archive
  exactly once — the console → daemon → plugin → daemon → console round trip, and
  the guard for "a web send is recorded at all"; `?limit=1` answers the newest
  entry; a freshly added workspace with no instance answers
  `{live:false, supported:false, entries:[]}` and its `/workspaces` row still
  reports `instance: null`, which is the no-spawn rule a keystroke depends on
- B15: wipes the browser mirror, reloads, checks the console fetched
  `/prompt-history`, walks ↑ back to the prompt B6 sent, walks ↓ out to the empty
  draft, recalls with Ctrl+P from a mid-line caret, and asserts that browsing
  never sends anything
- `docs/e2e.md` documents both (A0–A14, B1–B15)

Attribution done while landing this: with the plugin change stashed, A14 fails
(the capability is absent) while A5 reproduces identically and B1/B2/B3/B9/B13
fail the same way — pre-existing, not this feature. A5 is the coalesced
`text_delta` after `agent_settled` the suite already lists as a suspected
product bug; A11 is model-dependent and passed on the rerun.
2026-11-02 11:13:37 +08:00
yuez b8f1fca5bd feat(web): recall prompt history from the plugin with a browser fallback
The composer's ↑/↓ history is the web port of pi2.nvim's prompt buffer, so it
has to walk the archive nvim walks — not a copy of it. Three tiers: the plugin
owns the text, the daemon relays one live-only read, the browser keeps a mirror.

- `features/chat/prompt-history.ts`: the readline rules (`appendEntry`: blank
  ignored, consecutive dedupe, newest 500), the `localStorage` mirror
  (`pi2-prompt-history`, per workspace, 40 workspaces LRU), the
  `PromptHistorySource` seam, and `PromptHistoryNav` — the per-composer cursor
  with a stashed draft, independent positions, and a reset on edit/send
- `features/chat/prompt-history-feed.ts`: `usePromptHistory(workspaceId)` reads
  `GET /workspaces/:id/prompt-history`, appends a send optimistically, refreshes
  the mirror from every successful read, and falls back to the mirror whenever
  the relay cannot answer (no plugin, no capability, a 404 from an older daemon,
  an offline browser). One workspace-scoped read per page, never per keystroke.
- composer: ↑ recalls from the first line, ↓ from the last line or while
  browsing, `<C-p>`/`<C-n>` always recall; an IME composition and a text
  selection keep their keys; the caret lands at the end of a recalled prompt and
  a manual edit ends recall
- fixes a mirror bug found while testing it: a full list that accepts one more
  entry and drops the oldest has the same length, so the old "unchanged" check
  silently stopped recording after 500 prompts
- `docs/prompt-history.md` records the tiers, the key map, the storage contract
  and what is deliberately not shared yet (cross-host, history without nvim);
  the UI mock server answers the new endpoint so the visual harness stays honest

Version skew is boring by design: an old daemon (404) or an old plugin (no
capability) keeps recall working from the mirror.
2026-11-02 11:12:41 +08:00
yuez 32292873f9 feat(daemon): serve a live-only prompt-history read
The web composer's ↑/↓ recall needs the plugin's prompt history, so the browser
and nvim walk one list instead of two. The daemon relays it and stores nothing:
it is a router, and the plugin stays the authority (AGENTS.md rule 2).

- plugin `hello` advertises the new `promptHistory` capability; the daemon never
  relays the read to a plugin that did not advertise it
- `workspace.query{kind:"promptHistory",limit}` is answered by the plugin from
  its own `prompt.history` archive (workspace cwd), oldest-first
- `GET /api/v1/workspaces/:id/prompt-history?limit=` → `{v, workspaceId, live,
  supported, entries}`; `limit` defaults to 200 and clamps to 500, an unknown
  workspace is a 404, and malformed entries are dropped
- the read deliberately does **not** call `instances.ensure()`: recall is a
  keystroke, not a lifecycle event, so a workspace with no connected plugin
  answers `{live:false, supported:false, entries:[]}` instead of booting an nvim
- `PluginConnection.capabilities` joins the interface the daemon sees, and the
  fake connection grows a writable one so the gate is testable

No event or reducer change: `fixtures/` are untouched.
2026-11-02 11:12:21 +08:00
yuez c24f30fe71 fix(e2e): redeem pairing codes at the public endpoint
Both harnesses posted the redeem body to `/api/v1/pair`, which mints a code and
requires a device/CLI token, so `e2e_pair` got a 401 and every run died at
"FATAL: pair redeem failed" before the first scenario. Redeeming is the public
half of pairing (ADR 0001): the code is the capability, and the endpoint is
`POST /api/v1/pair/redeem`, unauthenticated and rate limited.

- `scripts/e2e/lib.sh` and `scripts/e2e/visual.sh` post the `{code, deviceName,
  kind}` body to `/api/v1/pair/redeem`
- the suite reaches A0 again: `run-api.sh` runs A0–A14, `run-ui.sh` B1–B15
2026-11-02 11:11:40 +08:00
yuez 3a797ac3f7 feat(web): sort the workspace picker by recent use and make it searchable
The chat sidebar's workspace picker listed rows in daemon order, which says
nothing about where the user was last. It now orders by recent use and filters
as you type.

- new `features/chat/workspace-order.ts`: recency = browser-local stamp
  (`pi2-workspace-recency`, written whenever a workspace becomes active) >
  daemon `lastActiveAt` > name/id, so the order is deterministic and stable;
  search matches name, alias, cwd, directory name and id, whitespace-split
  terms all required
- `WorkspaceSwitch` becomes a filterable listbox: fixed search field on top
  (focused on open, cleared on close), scrolling row list, empty state,
  arrow/Home/End focus, Enter takes the first match, Esc returns focus to the
  trigger; rows are `role=option` + `aria-selected`
- pages/chat.tsx stamps whichever workspace is active (deep link, picker,
  default), styles and en/zh strings for the search field
- tests for ordering, matching, persistence and the keyboard/selection paths;
  the B5 UI e2e scenario follows the ARIA change and asserts the filter
2026-10-30 16:41:42 +08:00
yuez 00c81a56f4 feat(web): persist session-dot acknowledgements across reloads
`flags.done`/`flags.error` are unread markers: the plugin keeps raising them
until nvim's own TabEnter, while `markSeen` only cleared them in the in-memory
store. The next snapshot — a reload, or a reconnect's resync — replayed the
flag, so a notification the user had already consumed blinked again and the
dot looked stuck on unread.

The acknowledgement is now durable in `localStorage` (`pi2-seen-sessions`, per
browser), recorded under the occurrence it was given for: the id of the
transcript's newest entry. A replayed snapshot ends on the same entry, so
ingress clears the flag; the next completed turn appends entries first, so its
token differs and that new notification blinks again. A row with no entries
cannot be scoped and keeps the in-memory-only behaviour. `removeSession`
forgets the ledger row and the `tmp-N` → real-id migration moves it. This stays
a client-side view concern — the wire, the reducer and `fixtures/` are
untouched.
2026-10-30 16:19:40 +08:00
yuez 2f2f1bb518 feat(daemon): report host uptime, not only the daemon's process age
The status tile labelled "uptime" showed the age of the daemon *process*
(`/info.uptimeMs`), and `/info` was fetched once with a 30 s staleTime and no
refetch interval, so the figure also froze: on a box five days up, a
`pi2 update` restart made the tile read "3m" and it never moved again.

`os.uptime()` is now sampled with the other host figures and served as
`system.hostUptimeSec` — which the 3 s `/resources` poll already refreshes —
plus an additive `/info.hostUptimeMs`. The tile renders it through a
`LiveUptime` label that anchors the reported snapshot once and ticks locally,
so the counter advances without a refetch and cannot rewind on a re-render.
The daemon's own process age stays in the server card, relabelled
`status.daemonUptime`, next to the `pid`/`daemonId` that give it meaning.
2026-10-30 16:18:48 +08:00
yuez 01fd7b9922 fix(daemon): sample disk usage on the filesystems pi2d uses
The status tile read `—` on a fresh machine: the sampler ran `statfs` on the
daemon's state dir, which is created lazily on the first instance log, so the
call failed with ENOENT and `diskUsedBytes`/`diskTotalBytes`/`diskPercent` all
came back null — `/info` then dropped `disk` altogether and the failure was
indistinguishable from a full disk.

`probeMount()` now walks up to the nearest existing ancestor and then to the
filesystem boundary (`st_dev` change), so a sample describes a volume, not a
directory. Candidates are pi2d's own write targets — `/` (the home volume on
macOS, where `/` is the sealed read-only system volume), the pi session store
and the visible workspace roots — never a mount-table dump: an unrelated or
hung network mount must not stall the sampler. Rows are deduped by `st_dev`,
sorted most-constrained first, capped at four, and reported as `system.disks[]`
with the legacy scalars aliasing the worst row. A sample that yields nothing
now carries `diskError` instead of silent nulls.

The status tile shows the worst filesystem and, when several are in play, one
quiet row per mount instead of a single percentage that hides the full volume.
2026-10-30 16:17:43 +08:00
yuez 1d907c08fa fix(web): merge history and live entries in transcript order
Opening a long session from the recent-activity list showed the transcript
ending at an old `edit` tool call. The plugin's snapshot carries the whole
transcript (`state.entries`), while the first REST page holds only the newest
entries; mergeEntries appended every unmatched live entry after the page, so
the older messages landed past the newest ones and scrolling to the bottom
stopped on a message from the middle of the session.

Unmatched live entries are now inserted where their live neighbours put them —
before the history entry of the next match — and appended only when they follow
every match, so both windows stay one chronologically ordered, deduped stream.
The regression test covers a live window that starts before the history page.
2026-10-30 15:15:14 +08:00
yuez 17fcf931c0 feat(workspaces): title recent-activity rows from a bounded preview
The activity column's disk-only rows had no title: the recent feed carried file
metadata only, so every session outside a live instance rendered "(unnamed)".

recentSessions() now projects a display title for the rows it returns — the
latest `session_info` name and the first user message — from a 128 KiB head +
32 KiB tail of each session file, cached by (mtime, size). Entries are never
parsed into session state: the read is bounded, opt-in, and only paid for the
≤limit rows the caller renders, so the daemon stays a router.

The web client keeps the disk title as a fallback under the live state, and the
B4 e2e scenario asserts session-first rows with their links and titles.
2026-10-30 15:15:09 +08:00
yuez 086cac8c8e docs(adr): put install and update ownership in pi2d (ADR 0004)
Two owners for one artifact broke exactly as expected: on a machine with the
standalone pi2, the plugin's npm copy sat on a lower rung of the resolution
ladder, so `:PiWebUpdate` upgraded a copy nobody ran and reported success while
the daemon kept the old version.

ADR 0004 records the fix. The standalone artifact is the one self-updating
channel (`install.sh` + `pi2 update`, built on ADR 0003's receipt); npm, Homebrew
and the AUR stay as distributions whose upgrades belong to their package
manager — `pi2 update` refuses them with the right command, the uv model. The
plugin becomes a pure client: resolve, delegate, print.

docs/install.md and README.md are reordered to match: the standalone installer is
the recommended path, the package managers are alternatives that upgrade
themselves. ADR 0002 §2.1 keeps its survey but is marked amended where it had
left `:PiWebInstall` as a plugin-side npm installer.
2026-10-30 09:55:08 +08:00
yuez 2240289426 feat(cli): add pi2 uninstall for cross-channel state cleanup
`install.sh --uninstall`, `brew uninstall`, `npm rm -g` and
`pi2 uninstall-service` each own one slice; none of them removed the
runtime directory, and deleting the binary left a running daemon behind.

`pi2 uninstall` now owns the state for every channel: disable and remove
the unit, stop the daemon, delete the runtime dir, and — with `--purge` /
`--purge-config` — the data, state and env file. On the curl channel
`--purge` also deletes the install tree, last, because the running binary
lives inside it; npm/brew/AUR trees stay with their package manager, and
the command to remove them is printed instead.

Destructive by design: the plan is always printed, `--yes` (or an
interactive `y`) is required, non-TTY runs refuse without it, and
everything a reinstall would silently lose is an explicit opt-in. The
next-steps footer names what no CLI can clean: the browser's site data and
the plugin-private copy from `:PiWebInstall`.

Docs: rewrite the install.md uninstall section around the two layers
(state vs. binaries) with a table of every path, point deployment.md at
the new command, and update the README.
2026-10-30 09:40:05 +08:00
65 changed files with 4972 additions and 219 deletions

No files matched your search

+5 -2
View File
@@ -43,8 +43,10 @@ Adding bulk to this file is a mistake, not a contribution.
1. **`docs/protocol.md` is the contract.** Any wire change lands with the daemon, the web client 1. **`docs/protocol.md` is the contract.** Any wire change lands with the daemon, the web client
and the pi2.nvim bridge in view; `fixtures/` are regenerated via `scripts/gen-expected.ts`. and the pi2.nvim bridge in view; `fixtures/` are regenerated via `scripts/gen-expected.ts`.
2. **The daemon is not an agent runtime.** No `pi` spawning, no JSONL session parsing, no session 2. **The daemon is not an agent runtime.** No `pi` spawning, no session state, no entry parsing.
state. Snapshots and mutations are relayed to the plugin, which stays the single authority. The one JSONL read is the recent feed's bounded display-title preview (`name` + first user
message, 128 KiB head + 32 KiB tail, cached); snapshots and mutations are relayed to the plugin,
which stays the single authority.
3. **`dist/` and `web/dist/` are build output** — gitignored, never committed. They ship inside 3. **`dist/` and `web/dist/` are build output** — gitignored, never committed. They ship inside
the npm tarball through `prepack` + the `files` allowlist. the npm tarball through `prepack` + the `files` allowlist.
4. **Two lockfiles.** Root `pnpm-lock.yaml` and `web/pnpm-lock.yaml` are independent: use 4. **Two lockfiles.** Root `pnpm-lock.yaml` and `web/pnpm-lock.yaml` are independent: use
@@ -70,6 +72,7 @@ owner/repo/workflow filename, not the npm name).
| `docs/protocol.md` | the browser ↔ daemon ↔ plugin wire contract | | `docs/protocol.md` | the browser ↔ daemon ↔ plugin wire contract |
| `docs/install.md` | canonical CLI-first install guide, channels, run modes, services, `pi2 update` | | `docs/install.md` | canonical CLI-first install guide, channels, run modes, services, `pi2 update` |
| `docs/session-dot.md` | the session-list status dot: the `:PiSessions` matrix, the unread flags, the one blink clock | | `docs/session-dot.md` | the session-list status dot: the `:PiSessions` matrix, the unread flags, the one blink clock |
| `docs/prompt-history.md` | composer ↑/↓ recall: key rules, per-workspace `localStorage` contract, nvim parity |
| `docs/deployment.md` | env vars, runtime files, ports, auth, services, troubleshooting | | `docs/deployment.md` | env vars, runtime files, ports, auth, services, troubleshooting |
| `docs/e2e.md` | scenario ids, isolation, skip conditions, report paths | | `docs/e2e.md` | scenario ids, isolation, skip conditions, report paths |
| `docs/testing.md` | test architecture, performance tuning, hybrid core CPU guidelines | | `docs/testing.md` | test architecture, performance tuning, hybrid core CPU guidelines |
+28 -18
View File
@@ -22,21 +22,10 @@ Requirements: **Node >= 20** (for the npm channel; the curl installer and system
> **Status.** The daemon CLI, the web console and the standalone installer are ready today (`npm i -g @yuez/pi2d` and `install.sh` work today). `:PiWeb` and `:PiWebInstall` land with the next pi2.nvim release, so today the flow is `pi2 daemon` + `pi2 open` (or running the daemon as a user service). > **Status.** The daemon CLI, the web console and the standalone installer are ready today (`npm i -g @yuez/pi2d` and `install.sh` work today). `:PiWeb` and `:PiWebInstall` land with the next pi2.nvim release, so today the flow is `pi2 daemon` + `pi2 open` (or running the daemon as a user service).
### Channel A: Global package manager (Node >= 20) ### Recommended: the standalone installer (the self-updating channel)
If your machine has Node >= 20: One self-contained binary, no Node, no root — the only channel that updates itself with
`pi2 update`. Also the right choice for an older distro Node (Debian 12 ships 18) or musl systems:
```bash
npm i -g @yuez/pi2d
# or:
pnpm add -g @yuez/pi2d
bun add -g @yuez/pi2d
mise use -g npm:@yuez/pi2d
```
### Channel B: Standalone curl installer (no Node required)
For machines without Node, with an older distro Node (e.g. Debian 12 ships 18), or where you want a self-contained installation with no global npm or root access:
```bash ```bash
curl -fsSL https://raw.githubusercontent.com/zgs225/pi2d/main/scripts/install.sh | sh curl -fsSL https://raw.githubusercontent.com/zgs225/pi2d/main/scripts/install.sh | sh
@@ -47,13 +36,33 @@ points `~/.local/lib/pi2d/current` at it, writes an install receipt and symlinks
`~/.local/bin/pi2`. After that, `pi2 update` upgrades it in place (verified download, SLSA `~/.local/bin/pi2`. After that, `pi2 update` upgrades it in place (verified download, SLSA
provenance check, atomic `current` switch, one-step rollback). provenance check, atomic `current` switch, one-step rollback).
To uninstall: ### Or: a package manager (it owns the upgrade)
If you prefer npm-style installs (Node >= 20). Upgrades belong to that package manager —
`pi2 update` refuses npm trees and prints `npm i -g @yuez/pi2d@latest`:
```bash ```bash
curl -fsSL https://raw.githubusercontent.com/zgs225/pi2d/main/scripts/install.sh | sh -s -- --uninstall npm i -g @yuez/pi2d
# or:
pnpm add -g @yuez/pi2d
bun add -g @yuez/pi2d
mise use -g npm:@yuez/pi2d
``` ```
### Channel C: System packages (Homebrew, AUR) To uninstall, first remove the daemon's local state (runtime, service unit, and — with flags —
data/state/config), then the binaries:
```bash
pi2 uninstall --dry-run # what would be removed
pi2 uninstall --purge --purge-config --yes # daemon state, logs, env file (curl channel: also the tree)
```
On the npm / Homebrew / AUR channels the binary tree belongs to the package manager:
`npm rm -g @yuez/pi2d`, `brew uninstall pi2d`, `sudo pacman -R pi2d-bin`. See
[Complete removal](docs/install.md#uninstall) for the full table of paths and the two things
no CLI can clean (browser site data, the plugin-private copy).
### Or: Homebrew / AUR (they own the upgrade)
*(Available once the release that publishes binaries has shipped)*: *(Available once the release that publishes binaries has shipped)*:
@@ -62,7 +71,7 @@ curl -fsSL https://raw.githubusercontent.com/zgs225/pi2d/main/scripts/install.sh
brew install zgs225/tap/pi2d brew install zgs225/tap/pi2d
``` ```
- **Arch Linux / Manjaro / EndeavourOS (AUR `pi2d-bin`):** - **Arch Linux / Manjaro / EndeavourOS (AUR `pi2d-bin`):**
*(AUR account registration is temporarily closed upstream — until it reopens, Arch users install with the [curl installer](#channel-b-standalone-curl-installer-no-node-required) above)*: *(AUR account registration is temporarily closed upstream — until it reopens, Arch users install with the [standalone installer](#standalone) above)*:
```bash ```bash
paru -S pi2d-bin # or: yay -S pi2d-bin paru -S pi2d-bin # or: yay -S pi2d-bin
``` ```
@@ -127,6 +136,7 @@ pi2 install-service --write # render and write user service file
pi2 service status # unit, enabled, active, linger (--json for machines) pi2 service status # unit, enabled, active, linger (--json for machines)
pi2 service enable # daemon-reload + enable --now (start|stop|disable too) pi2 service enable # daemon-reload + enable --now (start|stop|disable too)
pi2 uninstall-service --write # remove user service file pi2 uninstall-service --write # remove user service file
pi2 uninstall [--dry-run] [--yes] [--purge] # remove local state (all channels)
pi2 status # daemon status, active instances, and health pi2 status # daemon status, active instances, and health
pi2 doctor # verify node/runtime, nvim, pi, curl, sockets, protocol pi2 doctor # verify node/runtime, nvim, pi, curl, sockets, protocol
pi2 --version # print version pi2 --version # print version
+6 -1
View File
@@ -1,6 +1,7 @@
# ADR 0002 — Installation and run model: CLI first, service-owned daemon, plugin attaches # ADR 0002 — Installation and run model: CLI first, service-owned daemon, plugin attaches
- Status: accepted (implementing) - Status: accepted (implementing), partially superseded by [ADR 0004](0004-one-self-updating-channel.md)
(the plugin no longer installs; the standalone artifact is the one self-updating channel)
- Date: 2026-10-28 - Date: 2026-10-28
- Supersedes: the implicit "the plugin installs and spawns the daemon" default in - Supersedes: the implicit "the plugin installs and spawns the daemon" default in
`README.md` §Install and the resolution table (explicit path → `PATH` → plugin `README.md` §Install and the resolution table (explicit path → `PATH` → plugin
@@ -108,6 +109,10 @@ The plugin's `:PiWebInstall` becomes an explicit convenience command that prompt
confirmation before installing `@yuez/pi2d@latest` (an optional `<version>` argument confirmation before installing `@yuez/pi2d@latest` (an optional `<version>` argument
pins one) into `<stdpath("data")>/pi2d`. It never runs `npx`. pins one) into `<stdpath("data")>/pi2d`. It never runs `npx`.
> **Amended by [ADR 0004](0004-one-self-updating-channel.md)**: `:PiWebInstall` no longer installs
> anything. The npm package keeps publishing, but the package manager owns its upgrades; the
> plugin prints commands and delegates to `pi2 update` (standalone channel only).
### 2.2 Run: the daemon owns its own lifecycle ### 2.2 Run: the daemon owns its own lifecycle
| Mode | Who starts it | When to use | | Mode | Who starts it | When to use |
@@ -0,0 +1,79 @@
# ADR 0004 — One self-updating channel: the standalone artifact, owned by `pi2d`
- Status: accepted (implementing)
- Date: 2026-10-30
- Amends: [ADR 0002](0002-install-and-run.md) §2.1 (distribution channels) and §2.3 (the plugin is a client)
- Builds on: [ADR 0003](0003-self-update.md) (the install receipt and the versioned layout)
## Context
`pi2d` ships through four distributions — the curl installer, npm, a Homebrew tap and an AUR
`-bin` package — and ADR 0002 §2.1 kept `:PiWebInstall` in the plugin as an "explicit
convenience command" that installs the npm package into `<stdpath("data")>/pi2d`.
That gave two owners for one piece of software, and it broke in exactly the way two owners
always do. On a machine with a standalone (curl-installed) `pi2`, the plugin's npm copy sat in
`plugin-data` — a lower rung of the resolution ladder — so `:PiWebUpdate` upgraded a second copy
nobody ran, reported success, and the daemon kept serving the old version. The fix (dispatch on
`installShape`) landed first, but it papered over the design problem: the plugin should never
have been installing anything.
What the ecosystem does, checked against primary sources:
| Project | Stance |
|---|---|
| **nvim-lspconfig** | "nvim-lspconfig does not install language servers for you." The client plugin resolves a command on `PATH`. |
| **eglot** (Emacs) | Same: `eglot-server-programs` names executables; the user's package manager provides them. |
| **mason.nvim** | A *dedicated* installer ("Portable package manager for Neovim"), installing into `stdpath("data")/mason` and shelling out to `cargo`/`npm`. It exists because clients do not install. |
| **coc.nvim** | The counter-example: a Node service that owns `:CocInstall`. It pays by bundling a runtime and re-implementing a package manager. |
| **uv**, **deno**, **bun** | Upstream owns `self update`, and it *refuses* package-manager-owned trees with the command that owns them (uv reads an install receipt; deno prints "update through your package manager"). |
| **esbuild** | npm's way to ship a compiled binary: 26 `optionalDependencies` (`@esbuild/linux-x64`, …) plus a `bin` shim. |
| **pi / dsh / Claude Code / Codex / opencode / aider …** | (ADR 0002 §1) The agent is a first-class CLI installed by a package manager or `curl \| sh`; the editor plugin spawns or attaches, never installs. |
The common denominator: **whoever wrote the files owns the upgrade.** Anything else duplicates an
installer and guarantees a second, stale copy.
## Decision
### 1. One self-updating channel, owned by `pi2d`
The standalone release artifact is the only channel the project maintains end to end:
- `scripts/install.sh` installs it (versioned layout + receipt, ADR 0003),
- `pi2 update` upgrades it in place (verified digest, SLSA provenance, atomic `current` switch,
one-step rollback),
- both live in this repository, next to the artifact they manage, and are the only place that
knows the release matrix, the layout and the service unit.
### 2. npm, Homebrew and the AUR stay as *distributions*, not as install logic
They keep publishing, and their users keep upgrading with `npm i -g`, `brew upgrade pi2d` or
`paru -Syu pi2d-bin`. They are not channels we implement: `pi2 update` reads the receipt and
refuses them with their own command, which is the `uv` model and the reason a receipt exists.
### 3. The plugin is a client, and clients do not install
`pi2.nvim` resolves the daemon, uses it, and prints commands. Concretely:
- `:PiWebUpdate` drives `pi2 update` on the standalone channel, and prints the owning command on
every other channel (no execution).
- `:PiWebInstall` stops installing anything: with no `pi2` it prints the install commands
(standalone first); with a `pi2` it reports where it lives and points at `:PiWebUpdate`.
- `web.install_dir` and the `plugin-data` rung of the resolution ladder become deprecated
read-only compatibility, so an existing npm copy keeps resolving while nothing writes a new one.
### 4. Deferred: shipping the binary through npm
An `optionalDependencies` shim (the esbuild model) would let npm deliver the *same* compiled
binary, collapsing `installShape` to a single value. It is not done now: it changes the npm
publish shape and buys nothing the standalone channel does not already provide.
## Consequences
- The plugin loses its installer (~200 lines and its specs); `pi2 update` gains no new code.
- `docs/install.md` and `README.md` reorder: the standalone installer is the path, the package
managers are alternatives that own their own upgrades.
- A user who prefers npm keeps working unchanged, but upgrades with npm — and `:PiWebUpdate`
tells them so instead of silently installing a second copy.
- The `mason.nvim`-shaped answer (a dedicated installer layer) stays available as a third party
deciding to wrap `install.sh`; we do not need to build one.
+6
View File
@@ -564,6 +564,12 @@ too). For a login-less service to keep running on Linux enable linger
(`loginctl enable-linger $USER`, `pi2 doctor` warns when it is off; (`loginctl enable-linger $USER`, `pi2 doctor` warns when it is off;
`pi2 service status --json` reports `linger`). `pi2 service status --json` reports `linger`).
`pi2 uninstall` chains the same steps plus the rest of the daemon's files:
disable + remove the unit, stop the daemon, delete the runtime directory, and
with `--purge` / `--purge-config` the data, state and env file as well. Use it
instead of this command when the goal is a clean machine, not just a missing
unit — see [install.md](install.md#uninstall) for the full table of paths.
## 10. Logs and health ## 10. Logs and health
- `pi2 daemon` logs JSONL to stderr: `systemctl --user status pi2` / - `pi2 daemon` logs JSONL to stderr: `systemctl --user status pi2` /
+27 -6
View File
@@ -28,8 +28,8 @@ the real daemon/plugin/browser, never `MOCK.*` data.
The v1 gate is green when: The v1 gate is green when:
- **A0–A13** (API/WS against a real headless nvim + real pi) pass. - **A0–A14** (API/WS against a real headless nvim + real pi) pass.
- **B1–B14** (Playwright against the daemon-served production bundle) pass. - **B1–B15** (Playwright against the daemon-served production bundle) pass.
- **C1–C4** (responsive, theme, language, no console errors) pass. - **C1–C4** (responsive, theme, language, no console errors) pass.
- `tsc --noEmit`, `vitest run` (daemon), `vitest run` (web) stay green. - `tsc --noEmit`, `vitest run` (daemon), `vitest run` (web) stay green.
- Every failure found while running this plan is either fixed and re-verified, or - Every failure found while running this plan is either fixed and re-verified, or
@@ -110,8 +110,8 @@ then the browser suite, each in its own temp root. Both drivers are standalone w
## 4. Scenarios ## 4. Scenarios
All scenario ids below are implemented in the two drivers: `scenario("A0", …)` … `scenario("A13", …)` All scenario ids below are implemented in the two drivers: `scenario("A0", …)` … `scenario("A14", …)`
in `api-e2e.mjs`, `scenario("B1", …)` … `scenario("B14", …)` and `scenario("C1", …)` … in `api-e2e.mjs`, `scenario("B1", …)` … `scenario("B15", …)` and `scenario("C1", …)` …
`scenario("C4", …)` in `ui-e2e.mjs`. A driver exits non-zero only on **FAIL**; SKIP is `scenario("C4", …)` in `ui-e2e.mjs`. A driver exits non-zero only on **FAIL**; SKIP is
tolerant, and every skip is printed with its reason and written into the report. tolerant, and every skip is printed with its reason and written into the report.
@@ -235,6 +235,18 @@ The plan's original intent below is unchanged; the legend **P0**/**P1**/**P2** s
daemon (next request still 200). daemon (next request still 200).
- every error is a JSON body with `code`, `message`, `retryable`. - every error is a JSON body with `code`, `message`, `retryable`.
**A14 Prompt history recall** (`GET /workspaces/:id/prompt-history`, protocol §3.1.1)
- the prompt A4 sent through `prompt.send` is in the plugin's archive: `live:true`,
`supported:true`, and the text appears **exactly once** in `entries` — the proof that
the round trip browser → daemon → plugin archive → daemon → browser works, and that a
web send is recorded by the plugin at all (`prompt.send` does not go through the chat
UI, so this is a real regression guard).
- `?limit=1` answers exactly one entry equal to the newest of the full read.
- a freshly added workspace with **no** instance answers `200 {live:false, supported:false,
entries:[]}`, and its `/workspaces` row still has `instance: null` afterwards: the read
must never spawn (`instances.ensure()` would boot an nvim on a keystroke).
- unknown workspace → `404`.
### 4.2 B — Browser suite (Playwright, daemon-served bundle) ### 4.2 B — Browser suite (Playwright, daemon-served bundle)
**B1 Unpaired guard** **B1 Unpaired guard**
@@ -326,6 +338,15 @@ The plan's original intent below is unchanged; the legend **P0**/**P1**/**P2** s
back restores English; no missing-key placeholder. back restores English; no missing-key placeholder.
- switch theme light/dark/system: `<html data-theme>` changes and persists. - switch theme light/dark/system: `<html data-theme>` changes and persists.
**B15 Composer recall**
- open the B6 session in a fresh page, delete `localStorage` `pi2-prompt-history` and reload,
then confirm the console still fetched `GET /workspaces/:id/prompt-history` (200) — recall
must work from the plugin's archive, not from the browser mirror.
- `↑` recalls the newest archived prompt, and walking `↑` reaches the prompt B6 sent (later
scenarios write into the same workspace archive, so the newest entry is not necessarily
B6's); walking `↓` back out restores the empty draft; `Ctrl+P` recalls from a mid-line caret.
- recall sends nothing: no `prompt.send` may appear while browsing.
### 4.3 C — Responsive / visual ### 4.3 C — Responsive / visual
- **C1** 1440×900, 768×1024, 380×780 on `/workspaces`, `/chat`, `/status`, `/connect` - **C1** 1440×900, 768×1024, 380×780 on `/workspaces`, `/chat`, `/status`, `/connect`
@@ -384,10 +405,10 @@ which were skipped and why (non-blocking only), and the command that reproduces
```bash ```bash
cd <repo> # the pi2 CLI/daemon checkout (this repository) cd <repo> # the pi2 CLI/daemon checkout (this repository)
# backend only (A0–A13): tsc, then `pi2 daemon` + headless nvim + real pi # backend only (A0–A14): tsc, then `pi2 daemon` + headless nvim + real pi
bash scripts/e2e/run-api.sh bash scripts/e2e/run-api.sh
# browser (B1–B14, C1–C4): also builds web/dist (pnpm), then Playwright # browser (B1–B15, C1–C4): also builds web/dist (pnpm), then Playwright
bash scripts/e2e/run-ui.sh bash scripts/e2e/run-ui.sh
# both, API first; exit 0 only when neither suite failed # both, API first; exit 0 only when neither suite failed
+122 -61
View File
@@ -10,50 +10,37 @@ This document is the canonical reference for installing, running, configuring, u
Find your situation in the table below to choose the right installation command and run model: Find your situation in the table below to choose the right installation command and run model:
Only the **standalone channel** updates itself (`pi2 update`). npm, Homebrew and the AUR stay
available, but the package manager that installed `pi2` owns its upgrades — `pi2 update` refuses
them and prints the command that does ([ADR 0004](adr/0004-one-self-updating-channel.md)).
| Situation | Recommended Command | What it gives you | | Situation | Recommended Command | What it gives you |
|---|---|---| |---|---|---|
| **I have Node 20+** | `npm i -g @yuez/pi2d`<br>*(or `pnpm add -g`, `bun add -g`, `mise use -g npm:@yuez/pi2d`)* | The `pi2` CLI running directly on your existing Node.js environment, updated via standard package manager commands. | | **Most machines (recommended)** | `curl -fsSL https://raw.githubusercontent.com/zgs225/pi2d/main/scripts/install.sh \| sh` | One self-contained binary plus the web UI in `~/.local/lib/pi2d/versions/<version>` (receipt, `current` symlink, `~/.local/bin/pi2`), upgraded in place with `pi2 update`. No Node, no npm, no root. |
| **no Node / old Node** | `curl -fsSL https://raw.githubusercontent.com/zgs225/pi2d/main/scripts/install.sh \| sh` | Standalone compiled binary in `~/.local/lib/pi2d` symlinked to `~/.local/bin/pi2`, upgraded in place with `pi2 update`. Requires zero Node/npm dependencies and no root access. | | **I prefer npm / pnpm / bun / mise** | `npm i -g @yuez/pi2d`<br>*(or `pnpm add -g`, `bun add -g`, `mise use -g npm:@yuez/pi2d`)* | The `pi2` CLI on your existing Node.js environment. **The package manager owns upgrades**: `npm i -g @yuez/pi2d@latest`. |
| **macOS** | `brew install zgs225/tap/pi2d`<br>*(or the curl installer)* | Native Homebrew formula. Places `pi2` in `$(brew --prefix)/bin` and web assets in `$(brew --prefix)/share/pi2d/web/dist`. | | **no Node / old Node (Debian 12, Alpine, NixOS)** | the curl installer *(above)* | Same artifact as the recommended row: zero runtime dependencies, `-musl` builds for musl distros. On NixOS Bun's `-musl` binaries need `nix-ld` (or an FHS env). |
| **Arch / EndeavourOS / Manjaro** | `curl -fsSL https://raw.githubusercontent.com/zgs225/pi2d/main/scripts/install.sh \| sh`<br>*(AUR `pi2d-bin` once AUR registration reopens)* | Standalone binary in `~/.local/lib/pi2d` + `~/.local/bin/pi2`. Package-manager channels are paused: the AUR is not accepting accounts, so the curl installer is the working path today. | | **macOS** | `brew install zgs225/tap/pi2d`<br>*(or the curl installer)* | Native Homebrew formula (`pi2` in `$(brew --prefix)/bin`). **Homebrew owns upgrades**: `brew upgrade pi2d`. |
| **NixOS** | `curl -fsSL https://raw.githubusercontent.com/zgs225/pi2d/main/scripts/install.sh \| sh`<br>*(or dev checkout)* | Standalone binary in user home (`~/.local/bin/pi2`). Bun's `-musl` binaries are dynamically linked against the musl loader, so running a prebuilt binary on NixOS needs `nix-ld` (or an FHS env / `steam-run`-style wrapper). | | **Arch / EndeavourOS / Manjaro** | the curl installer *(AUR `pi2d-bin` once registration reopens)* | AUR registration is paused upstream, so the curl installer is the working path today; `paru -Syu pi2d-bin` takes over once the package lands. |
| **I want it to survive reboot and logout** | `pi2 install-service --write`<br>`systemctl --user enable --now pi2.service`<br>`loginctl enable-linger $USER` | Background systemd user service (or launchd on macOS) that starts at boot and stays alive when SSH sessions disconnect. | | **I want it to survive reboot and logout** | `pi2 install-service --write`<br>`systemctl --user enable --now pi2.service`<br>`loginctl enable-linger $USER` | Background systemd user service (or launchd on macOS) that starts at boot and stays alive when SSH sessions disconnect. |
| **I only want to try it** | Install via curl or npm, then run:<br>`pi2 daemon` | Foreground daemon in your current terminal. Logs stream to stdout/stderr. Stop anytime with `Ctrl-C` or `pi2 stop`. | | **I only want to try it** | the curl installer, then `pi2 daemon` | Foreground daemon in your current terminal; stop with `Ctrl-C` or `pi2 stop`. |
| **I develop pi2d itself** | `git clone https://github.com/zgs225/pi2d.git`<br>`pnpm install && pnpm --dir web install` | Source checkout with hot-reloading backend (`pnpm dev`) and Vite dev server (`pnpm --dir web dev`). | | **I develop pi2d itself** | `git clone https://github.com/zgs225/pi2d.git`<br>`pnpm install && pnpm --dir web install` | Source checkout with hot-reloading backend (`pnpm dev`) and Vite dev server (`pnpm --dir web dev`). |
--- ---
## Install channels ## Install channels
`pi2d` distributes through four primary channels: `pi2d` ships one **self-updating** channel (the standalone artifact below) and three
**package-manager-owned** distributions. Whoever wrote the files owns the upgrade:
`scripts/install.sh` + `pi2 update` maintain the standalone tree, and npm / Homebrew / the AUR
maintain theirs.
### Channel A: Global package manager (Node >= 20) <a id="standalone"></a>
### Standalone installer — the self-updating channel
Best when your workstation or server already has Node.js (version 20 or later) installed. This is the recommended channel and the only one the project maintains end to end: one
self-contained binary, no Node runtime, no root, and `pi2 update` upgrades it in place. It is the
```bash right choice for machines without Node, distributions with an older Node (Debian 12 ships 18),
# npm musl systems and servers.
npm i -g @yuez/pi2d
# pnpm
pnpm add -g @yuez/pi2d
# bun
bun add -g @yuez/pi2d
# mise
mise use -g npm:@yuez/pi2d
```
**Where files land**:
- Executable binary: `$(npm config get prefix)/bin/pi2`
- Node package & web assets: `$(npm config get prefix)/lib/node_modules/@yuez/pi2d/` (with web assets in `web/dist/`)
---
### Channel B: Standalone curl installer (no Node required)
Best for systems with no Node runtime, machines with older distributions (such as Debian 12 shipping Node 18), or environments where you do not want to manage global npm packages.
```bash ```bash
curl -fsSL https://raw.githubusercontent.com/zgs225/pi2d/main/scripts/install.sh | sh curl -fsSL https://raw.githubusercontent.com/zgs225/pi2d/main/scripts/install.sh | sh
@@ -102,7 +89,33 @@ PI2_VERSION=0.1.6 PI2_BIN_DIR=/usr/local/bin PI2_INSTALL_DIR=/usr/local/lib/pi2d
--- ---
### Channel C: System packages (Homebrew & AUR) <a id="package-managers"></a>
### Package managers (npm / pnpm / bun / mise) — they own the upgrade
Best when your workstation or server already has Node.js (version 20 or later) installed.
```bash
# npm
npm i -g @yuez/pi2d
# pnpm
pnpm add -g @yuez/pi2d
# bun
bun add -g @yuez/pi2d
# mise
mise use -g npm:@yuez/pi2d
```
**Where files land**:
- Executable binary: `$(npm config get prefix)/bin/pi2`
- Node package & web assets: `$(npm config get prefix)/lib/node_modules/@yuez/pi2d/` (with web assets in `web/dist/`)
---
<a id="brew-aur"></a>
### Homebrew & AUR — they own the upgrade
*(Note: These channels are available once the release publishing compiled binaries has shipped).* *(Note: These channels are available once the release publishing compiled binaries has shipped).*
@@ -115,7 +128,7 @@ brew install zgs225/tap/pi2d
#### Arch Linux / Manjaro / EndeavourOS (AUR) #### Arch Linux / Manjaro / EndeavourOS (AUR)
> **AUR registration paused**: New user registration on the AUR is temporarily closed upstream (HTTP 503: "Registration on the AUR is paused while we deal with a wave of automated account creation..."). Until registration reopens and `pi2d-bin` can be submitted, the AUR channel is unavailable. Use **[Channel B: Standalone curl installer](#channel-b-standalone-curl-installer-no-node-required)** instead — it works on Arch today and `pi2 update`s with the same command. > **AUR registration paused**: New user registration on the AUR is temporarily closed upstream (HTTP 503: "Registration on the AUR is paused while we deal with a wave of automated account creation..."). Until registration reopens and `pi2d-bin` can be submitted, the AUR channel is unavailable. Use **[the standalone installer](#standalone)** instead — it works on Arch today and `pi2 update`s with the same command.
```bash ```bash
# (When AUR registration reopens) # (When AUR registration reopens)
@@ -311,24 +324,16 @@ systemctl --user restart pi2.service
### Upgrade per channel ### Upgrade per channel
- **Channel A (npm / pnpm / bun / mise)**: **Standalone installer — the self-updating channel:**
```bash
npm i -g @yuez/pi2d@latest
# or:
pnpm add -g @yuez/pi2d@latest
bun add -g @yuez/pi2d@latest
mise use -g npm:@yuez/pi2d@latest
```
- **Channel B (Standalone curl installer)**:
```bash ```bash
pi2 update pi2 update
``` ```
It downloads the release asset for this platform, checks it against the release's It downloads the release asset for this platform, checks it against the release's
`SHA256SUMS`, verifies its SLSA build provenance with `gh attestation verify` when the `SHA256SUMS`, verifies its SLSA build provenance with `gh attestation verify` when the GitHub
GitHub CLI is installed, runs the new binary once, then switches CLI is installed, runs the new binary once, then switches `~/.local/lib/pi2d/current` and
`~/.local/lib/pi2d/current` and rewrites the install receipt. The previous version is kept rewrites the install receipt. The previous version is kept for one-step rollback.
for one-step rollback.
| Command | What it does | | Command | What it does |
|---|---| |---|---|
@@ -341,49 +346,105 @@ systemctl --user restart pi2.service
| `pi2 update --skip-attestation` | Never call `gh` (offline machines, no GitHub CLI) | | `pi2 update --skip-attestation` | Never call `gh` (offline machines, no GitHub CLI) |
| `pi2 update --json` | Machine-readable result (stdout is pure JSON; progress goes to stderr) | | `pi2 update --json` | Machine-readable result (stdout is pure JSON; progress goes to stderr) |
Setting `PI2_BASE_URL` points the download at a mirror (`PI2_UPDATE_CACHE_TTL` changes the `PI2_BASE_URL` points the download at a mirror (`PI2_UPDATE_CACHE_TTL` changes the
version-lookup cache, default 86400 s). Re-running the installer still works and stays the version-lookup cache, default 86400 s). Re-running the installer still works and stays the
recovery path when the tree is damaged. recovery path when the tree is damaged.
- **Channel C (Homebrew)**: **Package managers — they own the upgrade** (`pi2 update` refuses with the command below):
```bash ```bash
npm i -g @yuez/pi2d@latest # or: pnpm add -g / bun add -g / mise use -g npm:@yuez/pi2d@latest
brew update && brew upgrade pi2d brew update && brew upgrade pi2d
paru -Syu pi2d-bin # AUR, when registration reopens
``` ```
- **Channel C (Arch AUR — when reopened)**: ### Uninstall
Removal has two layers: the daemon's **local state** (the same for every channel) and
the **binaries** (owned by the channel that installed them).
#### Step 1 — remove the daemon's local state: `pi2 uninstall`
```bash ```bash
paru -Syu pi2d-bin pi2 uninstall --dry-run # print the plan, change nothing
# or: pi2 uninstall # interactive confirmation
yay -Syu pi2d-bin pi2 uninstall --yes # scripts / no TTY
pi2 uninstall --purge --purge-config --yes # state and env file too
``` ```
### Uninstall per channel The command is channel-agnostic and runs in this order:
- **Channel A (npm / pnpm / bun)**: 1. `pi2 service disable` + remove the unit file — unless `--keep-service`
2. stop a running daemon (`pi2 stop`)
3. delete the runtime directory — sockets, `cli.token`, `daemon.lock`
4. with `--purge`: delete the data directory (`devices.json`, `workspaces.json`) and the
state directory (instance logs, `host-init/`, the update cache)
5. with `--purge-config`: delete `~/.config/pi2/env`
6. on the **curl channel only**, with `--purge`: delete `<prefix>` (`~/.local/lib/pi2d`)
and the `~/.local/bin/pi2` symlink. This runs last because the running binary lives
inside that tree.
| What | Default location (Linux) | Removed by | Why it is not always removed |
|---|---|---|---|
| Runtime | `$XDG_RUNTIME_DIR/pi2` | always | throwaway: sockets, lock, CLI token |
| Data | `~/.local/share/pi2` | `--purge` | paired devices, workspace trust and aliases |
| State | `~/.local/state/pi2` | `--purge` | instance logs, generated host-init, update cache |
| Config | `~/.config/pi2/env` | `--purge-config` | user-authored; may hold tokens for other tools |
| Service | `~/.config/systemd/user/pi2.service` (launchd plist on macOS) | default, or keep with `--keep-service` | — |
| Install tree | `~/.local/lib/pi2d` | `--purge` on the curl channel | npm/brew/AUR own their trees |
`pi2 uninstall` never deletes a tree a package manager tracks. Instead it prints the
command that does, plus the two things no CLI can clean for you:
- the **browser's site data** for the console (it caches the paired device token in
`localStorage`);
- the **plugin-private daemon copy** made by `:PiWebInstall` under Neovim's
`stdpath("data")/pi2d`.
Without `--purge` the command also prints the exact `rm -rf` fallback for the directories
it kept, so a full wipe never requires knowing the layout.
> Removing the state is safe to redo: a reinstall recreates the runtime directory, and
> `--purge` is the only thing that makes a reinstall forget paired devices and workspace
> trust.
#### Step 2 — remove the binaries (per channel)
- **npm / pnpm / bun**:
```bash ```bash
npm rm -g @yuez/pi2d npm rm -g @yuez/pi2d
# or: pnpm rm -g @yuez/pi2d / bun rm -g @yuez/pi2d # or: pnpm rm -g @yuez/pi2d / bun rm -g @yuez/pi2d
``` ```
- **Channel B (curl installer)**: - **Standalone installer** — after `pi2 uninstall --purge`, or instead of it when the
state does not matter:
```bash ```bash
curl -fsSL https://raw.githubusercontent.com/zgs225/pi2d/main/scripts/install.sh | sh -s -- --uninstall curl -fsSL https://raw.githubusercontent.com/zgs225/pi2d/main/scripts/install.sh | sh -s -- --uninstall
``` ```
*(Or manually delete `rm -rf ~/.local/lib/pi2d ~/.local/bin/pi2`)*. *(Or manually delete `rm -rf ~/.local/lib/pi2d ~/.local/bin/pi2`)*.
- **Channel C (Homebrew)**: - **Homebrew**:
```bash ```bash
brew uninstall pi2d brew uninstall pi2d
``` ```
- **Channel C (Arch AUR — when reopened)**: - **Arch AUR (when registration reopens)**:
```bash ```bash
sudo pacman -R pi2d-bin sudo pacman -R pi2d-bin
``` ```
If you configured a user service, remember to remove it before uninstalling the binary: If you only want the unit gone and the daemon kept running, `pi2 uninstall-service --write`
removes the file alone (and prints the disable commands).
#### Complete removal, copy-paste
```bash ```bash
pi2 uninstall-service --write # curl installer
pi2 uninstall --purge --purge-config --yes
# npm
pi2 uninstall --purge --purge-config --yes && npm rm -g @yuez/pi2d
# assert nothing is left behind
pi2 config --json | grep -E 'runtimeDir|dataDir|stateDir' # all should be gone
``` ```
--- ---
+116
View File
@@ -0,0 +1,116 @@
# Prompt input history (web composer)
The Chat composer recalls previously sent prompts with the arrow keys. The text
comes from the **plugin** (pi2.nvim owns the archive); the daemon relays a
live-only read; the browser keeps a mirror so recall still works when the relay
cannot answer. This document is the web-side map of that design — the wire
contract lives in `docs/protocol.md` §3.1.1.
## Key map
| Key | Behaviour |
|---|---|
| `↑` (`<C-p>`) | Recall the previous (older) prompt. |
| `↓` (`<C-n>`) | Walk back toward the newest entry; past it, restore the draft. |
| `Enter` / `Shift+Enter` | Unchanged: send / newline. |
`↑` and `↓` only recall when the caret has nowhere left to go — `↑` on the
**first** line, `↓` on the **last** line — or, for `↓`, while already browsing
history. A collapsed caret is required (a selection means "editing a fragment"),
and an IME composition (`isComposing`) keeps the keys to itself, because arrows
navigate its candidate window. `<C-p>` / `<C-n>` are the readline aliases and
always recall.
Recalling stashes the in-progress draft, which comes back when you walk past the
newest entry; the caret is parked at the end of the recalled text. Any manual
edit ends browsing, so a later `↓` can never overwrite what you typed. Sending
also ends browsing and records the prompt (trimmed).
## Who owns the text
Three tiers, in this precedence order:
| Tier | Owns | Lifetime |
|---|---|---|
| **pi2.nvim** (`prompt.history`, one archive per workspace cwd) | the entries | durable, per workspace, shared with every surface |
| **daemon** | nothing | — (relay only) |
| **browser mirror** (`localStorage`, `pi2-prompt-history`) | a fallback copy | per browser profile, bounded |
1. **The plugin is the authority.** Every prompt is recorded by pi2.nvim when it
is sent — `Store:add` inside `Chat:_send_message`, whichever surface sent it —
so nvim's ↑ and the console's ↑ walk the *same* list, and so does every device
paired to this daemon. The console writes nothing back: sending through the
composer already lands in that store through `prompt.send`.
2. **The daemon relays one read and stores nothing.**
`GET /api/v1/workspaces/:id/prompt-history?limit=` → `{live, supported, entries}`.
It is **live-only**: with no connected plugin it answers `live: false` instead
of `instances.ensure()`, because pressing ↑ must never boot an nvim. It is also
**capability-gated**: a plugin that did not advertise `promptHistory` gets no
command at all (`supported: false`). Unknown workspace → `404`.
3. **The browser mirror is the fallback.** Written on every send and refreshed
from every successful relay read, so losing the plugin (instance restart, an
older daemon that 404s the endpoint, an older plugin without the capability, an
offline browser) still recalls the last known history instead of only what this
browser typed. It is never authoritative: when the relay answers `supported`,
the plugin's entries win.
Version skew is therefore boring: a new console against an old daemon (404) or an
old plugin (no capability) simply keeps using the mirror.
## What is remembered
Mirrors `Store:add` in `lua/pi/prompt_history.lua`, on both the plugin and the
mirror:
* blank / whitespace-only prompts are not recorded;
* a prompt identical to the newest entry is skipped (readline consecutive
dedupe — a non-consecutive repeat *is* kept);
* entries are multi-line safe and stored verbatim;
* the newest 500 are kept (`HISTORY_LIMIT`; the plugin's `prompt.history.max`
defaults to the same).
## Scope and storage
The mirror is one `localStorage` key, `pi2-prompt-history`, holding
`{ [workspaceId]: string[] }`, entries oldest-first.
* **Scope = workspace id**, so every session in a workspace shares one archive
(like nvim's per-cwd store) while another workspace starts clean. A session not
yet bound to a workspace uses the `default` bucket rather than losing the send.
* **Bounded**: the 40 least-recently-used workspaces are kept
(`WORKSPACE_LIMIT`), so a long-lived profile cannot grow without bound.
* Every read/write tolerates a missing, corrupt or unwritable storage (private
mode, quota): the feature degrades to "no mirror", never to a broken composer.
* The **cursor** (position + stashed draft, `PromptHistoryNav`) never leaves the
composer. No server sees it, and two tabs never share it.
## Where it lives
| Path | Contents |
|---|---|
| `web/src/features/chat/prompt-history.ts` | the mirror (`readPromptHistory`, `rememberPrompt`, `replacePromptHistory`, `clearPromptHistory`), the readline rules (`appendEntry`), the `PromptHistorySource` seam and `PromptHistoryNav` |
| `web/src/features/chat/prompt-history-feed.ts` | `usePromptHistory(workspaceId, enabled)` — the relay read, the optimistic append after a send, the mirror refresh, and the fallback decision (`remote` / `live`) |
| `web/src/features/chat/composer.tsx` | key handling, draft stash, caret placement; recalls from and records into the injected source |
| `web/src/pages/chat.tsx` | builds the feed and injects it |
| `src/daemon/router.ts` | `relayPromptHistory` (live-only, capability-gated, no `ensure()`) |
| `src/daemon/http.ts` | `GET /api/v1/workspaces/:id/prompt-history` |
| `pi2.nvim` `lua/pi/web/bridge.lua` | advertises the `promptHistory` capability in `hello` |
| `pi2.nvim` `lua/pi/web/commands.lua` | answers `workspace.query{kind="promptHistory"}` from the workspace archive, and records every `prompt.send` into it (the TUI records inside `Chat:_send_message`, which a web send never reaches) |
| `web/tests/prompt-history.test.ts` | mirror + readline rules + cursor contract (the port of `tests/prompt_history_spec.lua`) |
| `web/tests/chat.prompt-history-feed.test.tsx` | relay, fallback, mirror refresh, version skew |
| `web/tests/chat.composer.test.tsx` | the keyboard rules |
## Not done (deliberately)
* **Cross-host sharing.** One daemon sees one host's plugins. Two machines running
their own `pi2d` still have separate archives; sharing them means a shared store
directory (Syncthing/NFS) *and* switching the plugin's store from whole-file
rewrite to append-only JSONL first, or two nvim processes in the same cwd clobber
each other.
* **History without nvim.** Because the plugin is the authority, a workspace with
no live plugin recalls only the mirror. Making the daemon hold the durable store
would lift that, at the cost of a second writer (the plugin must still work
standalone), conflict resolution and a daemon-owned user-data lifecycle — an ADR
decision, not a patch.
* **A "forget this workspace" action.** `clearPromptHistory(scope)` exists and is
tested; nothing in the UI calls it yet.
+59 -6
View File
@@ -67,8 +67,19 @@ The plugin dials the daemon (`<runtime>/d.sock`), sends `hello` first.
{"v":1,"type":"workspace.query","id":"req-2","payload":{"kind":"sessions"}} {"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) // 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}} {"v":1,"type":"workspace.query","id":"req-3","sessionId":"s1","payload":{"kind":"entries","limit":50}}
// workspace-scoped read, no sid: the answering instance *is* the workspace (see §3.1.1)
{"v":1,"type":"workspace.query","id":"req-4","payload":{"kind":"promptHistory","limit":200}}
``` ```
`hello.capabilities` is how a plugin announces optional behaviour; the daemon never
relays a feature-gated command to a plugin that has not advertised it. Known strings:
| Capability | Meaning |
|---|---|
| `snapshot` | answers `sub.subscribe` with a `snapshot` |
| `attention` | reports pending attention (§6) |
| `promptHistory` | answers `workspace.query{kind:"promptHistory"}` with the workspace's prompt input history (§3.1.1) |
Plugin obligations: Plugin obligations:
- **Say `bye` when leaving on purpose.** A plugin that stops the bridge (`:PiWebStop`, `VimLeavePre`) - **Say `bye` when leaving on purpose.** A plugin that stops the bridge (`:PiWebStop`, `VimLeavePre`)
@@ -93,13 +104,14 @@ Plugin obligations:
| Endpoint | Notes | | Endpoint | Notes |
|---|---| |---|---|
| `GET /api/v1/info` | `{v, daemonId, machineId, platform, hostname, os, version, uptimeMs, pid, port, capabilities, limits}`; additive `cpu`, `mem`, `disk` (integer percent, each omitted when unknown), `cpuCores`, `loadAvg` | | `GET /api/v1/info` | `{v, daemonId, machineId, platform, hostname, os, version, uptimeMs, pid, port, capabilities, limits}`; `uptimeMs` is the **daemon process** age, `hostUptimeMs` the host uptime (both omitted when unknown); additive `cpu`, `mem`, `disk` (integer percent of the **most constrained** filesystem, each omitted when unknown), `cpuCores`, `loadAvg` |
| `GET /api/v1/health` | `{ok, items:[{name, ok, detail}]}` | | `GET /api/v1/health` | `{ok, items:[{name, ok, detail}]}` |
| `GET /api/v1/workspaces` | `WorkspaceInfo[]` (registry + disk index + instance state) | | `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/workspaces/:id/sessions` | relayed `workspace.query{kind:"sessions"}` (row fields below) |
| `GET /api/v1/sessions/recent?limit=` | disk-projected recent sessions across every workspace (below); never spawns an instance | | `GET /api/v1/sessions/recent?limit=` | disk-projected recent sessions across every workspace (below); never spawns an instance |
| `GET /api/v1/sessions/:sid/entries?before=&limit=&workspaceId=&sessionFile=` | relayed `workspace.query{kind:"entries"}`; 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/attention?workspaceId=` | pending attention for one workspace |
| `GET /api/v1/workspaces/:id/prompt-history?limit=` | **live-only** `workspace.query{kind:"promptHistory"}`, never spawns; `{v, workspaceId, live, supported, entries}` (§3.1.1) |
| `GET /api/v1/devices` | paired devices (daemon-owned; `{id, name, kind, createdAt, lastSeenAt, revokedAt}`) | | `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}` | | `POST /api/v1/pair` | **authenticated**; mints `{code, url, expiresAt, nonce, qr, bases}` |
| `POST /api/v1/pair/redeem` | public + rate limited (`E_RATE_LIMITED`); `{code, kind, deviceName}` → `{token, device}` | | `POST /api/v1/pair/redeem` | public + rate limited (`E_RATE_LIMITED`); `{code, kind, deviceName}` → `{token, device}` |
@@ -116,6 +128,34 @@ does not know. A session that exists but has no JSONL yet (`pi` creates the file
the first entry) answers an **empty page** (`{entries:[], cursor:{hasMore:false}}`), the first entry) answers an **empty page** (`{entries:[], cursor:{hasMore:false}}`),
never an error: a new session has no history to fail on. never an error: a new session has no history to fail on.
#### Prompt input history (`/workspaces/:id/prompt-history`)
The composer's ↑/↓ recall reads the workspace's prompt history from the plugin, which
owns it (pi2.nvim's `prompt.history`, one archive per workspace cwd). The daemon is a
relay here and stores nothing: a browser that loses this read still works, it just
cannot see what nvim recorded.
```jsonc
GET /api/v1/workspaces/ws-1/prompt-history?limit=200
{ "v": 1, "workspaceId": "ws-1", "live": true, "supported": true,
"entries": ["oldest first", "newest last"] }
```
Three rules make this read safe to call from a keystroke handler:
- **It never spawns an instance.** A workspace with no connected plugin answers
`200 {live:false, supported:false, entries:[]}` instead of `instances.ensure()`, so
pressing ↑ on an idle workspace cannot boot an nvim. Every other relayed read spawns.
- **It is capability-gated.** A connected plugin that did not advertise `promptHistory`
answers `{live:true, supported:false, entries:[]}` and receives no command at all.
- **The client owns the fallback.** When `supported` is false the console recalls from its
browser-local mirror (`docs/prompt-history.md`). The cursor (position + stashed draft) is
always client state; only the text of the entries comes from the plugin.
`limit` defaults to 200 and is clamped to 500; the plugin answers oldest-first and the
daemon trims to the newest `limit` entries. Unknown workspace → `404`, exactly like
`/sessions` and `/attention`.
The `system` object on `GET /api/v1/resources` is additive (absent on daemons The `system` object on `GET /api/v1/resources` is additive (absent on daemons
older than 0.1.5, so clients must tolerate its absence) and reports **host** older than 0.1.5, so clients must tolerate its absence) and reports **host**
figures sampled by the daemon itself: figures sampled by the daemon itself:
@@ -123,12 +163,20 @@ figures sampled by the daemon itself:
| Field | Notes | | Field | Notes |
|---|---| |---|---|
| `sampledAt` | epoch ms; a sample is cached ~1 s and shared across callers | | `sampledAt` | epoch ms; a sample is cached ~1 s and shared across callers |
| `hostUptimeSec` | host uptime in whole seconds (`os.uptime()`), `null` when the OS has none. This is the figure a client shows as “uptime”; `/info.uptimeMs` stays the **daemon process** age, so a `pi2 update` restart does not reset it |
| `cpuPercent` | integer 0–100, `null` on the first sample (it is a delta between two reads) | | `cpuPercent` | integer 0–100, `null` on the first sample (it is a delta between two reads) |
| `cpuCores` | logical core count | | `cpuCores` | logical core count |
| `loadAvg` | 3-tuple `[1m, 5m, 15m]`, or `null` where the OS has no load average | | `loadAvg` | 3-tuple `[1m, 5m, 15m]`, or `null` where the OS has no load average |
| `memUsedBytes`, `memTotalBytes`, `memPercent` | **host** memory; `memPercent` is an integer. `totalRssBytes` stays the soft-limit input — it is instance RSS, not a host figure | | `memUsedBytes`, `memTotalBytes`, `memPercent` | **host** memory; `memPercent` is an integer. `totalRssBytes` stays the soft-limit input — it is instance RSS, not a host figure |
| `diskPath` | the filesystem the sample describes: the daemon's state dir | | `diskPath` | mount point of the most constrained filesystem (`disks[0]`), e.g. `/` or `/home`; the legacy scalar fields below alias that row |
| `diskUsedBytes`, `diskTotalBytes`, `diskPercent` | `diskPercent` integer, nullable; the byte counts are `null` when the stat fails | | `disks` | `DiskUsage[]`, at most 4, **most constrained first**. One row per distinct filesystem (`st_dev`) among the daemon's own write targets: `/` (the home volume on macOS), the pi session store and the visible (non-`secondary`) workspace roots. Not a mount-table dump — an unrelated or hung network mount is never touched |
| `disks[].mountPoint`, `disks[].fsType?`, `disks[].totalBytes`, `disks[].usedBytes`, `disks[].percent` | `mountPoint` is the filesystem boundary (never the sampled path), `fsType` a best-effort label (`ext4`, `btrfs`, …) omitted when unknown, `percent` an integer 0–100 |
| `diskUsedBytes`, `diskTotalBytes`, `diskPercent` | the worst row, for clients that predate `disks`; `null` when nothing could be sampled |
| `diskError` | present **only** when `disks` is empty — `"<path>: <code>"`, so a failed sample is distinguishable from a full disk instead of silently rendering `—` |
A candidate path that does not exist yet (the state dir is created lazily) no longer
blanks the sample: the probe walks up to the nearest existing ancestor and then to the
filesystem boundary, so `diskPercent` describes the volume, not a directory.
`GET /api/v1/models` no longer requires `workspaceId`. With one, the read is `GET /api/v1/models` no longer requires `workspaceId`. With one, the read is
relayed as before and may spawn that workspace's instance — the chat picker's relayed as before and may spawn that workspace's instance — the chat picker's
@@ -171,10 +219,14 @@ default; `secondary` rows belong behind a “show hidden” toggle. Lookups by
Recent session row (`GET /api/v1/sessions/recent?limit=`): a **disk projection**, not Recent session row (`GET /api/v1/sessions/recent?limit=`): a **disk projection**, not
session state. The daemon scans each known workspace's session directory, reads only session state. The daemon scans each known workspace's session directory, reads only
session headers (id, timestamp, cwd), and sorts by file mtime. It never parses session headers (id, timestamp, cwd), and sorts by file mtime. For the rows it returns
entries, never spawns an instance and never claims ownership of a live session. The (≤ `limit`) it also projects a bounded **display title** — the latest `session_info.name`
and the first user message — by reading at most 128 KiB from the start plus 32 KiB from
the end of each file, cached by (mtime, size); entries are never parsed into session
state. It never spawns an instance and never claims ownership of a live session. The
console layers live names/statuses over these rows from console layers live names/statuses over these rows from
`GET /api/v1/workspaces/:id/sessions` when that workspace has a connected instance. `GET /api/v1/workspaces/:id/sessions` when that workspace has a connected instance,
falling back to the disk title for history rows.
| Field | Notes | | Field | Notes |
|---|---| |---|---|
@@ -182,6 +234,7 @@ console layers live names/statuses over these rows from
| `workspaceId`, `workspaceName` | owning workspace, resolved from the daemon's registry/discovery | | `workspaceId`, `workspaceName` | owning workspace, resolved from the daemon's registry/discovery |
| `timestamp` | session start from the JSONL header (file-name fallback), epoch ms | | `timestamp` | session start from the JSONL header (file-name fallback), epoch ms |
| `modified` | file mtime, epoch ms — the recency sort key | | `modified` | file mtime, epoch ms — the recency sort key |
| `name?`, `firstMessage?` | bounded display-title projection: latest `session_info.name`, first user message (flattened, ≤80 chars). Both absent when the preview windows contain neither. |
The `limit` defaults to 20 and is clamped to 1–200. Rows are deduped by `sessionId` The `limit` defaults to 20 and is clamped to 1–200. Rows are deduped by `sessionId`
(two encoded directories can resolve to the same cwd) and returned newest first. (two encoded directories can resolve to the same cwd) and returned newest first.
+11
View File
@@ -122,6 +122,17 @@ so the session you open stops being green or red — which is why a viewed child
failure is solid while an unviewed one blinks. The canonical reducer (`src/protocol/reducer.ts`) failure is solid while an unviewed one blinks. The canonical reducer (`src/protocol/reducer.ts`)
and `fixtures/` are deliberately untouched: this is a client-side view concern. and `fixtures/` are deliberately untouched: this is a client-side view concern.
The acknowledgement is **durable**, because the plugin keeps raising the flag until nvim's own
`TabEnter`: an in-memory-only `markSeen` meant the next snapshot (a page reload, or a reconnect's
resync) replayed `done: true` and the green blink returned for a notification the user had
already seen. `web/src/features/chat/acknowledged.ts` persists it in `localStorage`
(`pi2-seen-sessions`, per browser) under the **occurrence** it was given for — the id of the
transcript's newest entry. A replayed snapshot is the same occurrence (same trailing entry id),
so the store clears the flag on ingress; the next completed turn appends entries first, so its
token differs and that new notification blinks again. A notification for a state with no entries
cannot be scoped and is never suppressed. `removeSession` forgets the row and the `tmp-N` →
real-id migration moves it.
## One clock for every dot ## One clock for every dot
No dot animates itself. `web/src/lib/blink.ts` owns a single ref-counted 500ms interval that No dot animates itself. `web/src/lib/blink.ts` owns a single ref-counted 500ms interval that
+5
View File
@@ -233,6 +233,11 @@ state (`/sessions`) and the WS snapshot — so no web code calls them.
| 19 子代理状态线并入 telemetry | `telemetry.tsx`(`.telemetry--sub`,标题只留身份) | | 19 子代理状态线并入 telemetry | `telemetry.tsx`(`.telemetry--sub`,标题只留身份) |
| 20 移动端顶栏胶囊 + 页面 sheet、删除底栏 | `components/shared/{page-pill,page-sheet}.tsx`、`app.css`;`.tabbar` 与 `--tabbar-h` 已删除 | | 20 移动端顶栏胶囊 + 页面 sheet、删除底栏 | `components/shared/{page-pill,page-sheet}.tsx`、`app.css`;`.tabbar` 与 `--tabbar-h` 已删除 |
`WorkspaceSwitch`(CHG-02)的排序与搜索契约落在 `features/chat/workspace-order.ts`:行按
**最近使用**排序(浏览器本地 `pi2-workspace-recency` 时间戳优先,其次 daemon 的 `lastActiveAt`,
再按名称 / id);顶部搜索框按名称、别名、cwd、目录名、id 过滤(空格分词,全部命中);
行是 `role=option` + `aria-selected`,Enter 取首个匹配,Esc 关闭并把焦点还给触发器。
### 9.1 与原型的有意偏差(数据模型所致) ### 9.1 与原型的有意偏差(数据模型所致)
| 原型 | pi2d 现实 | 我们的处理 | | 原型 | pi2d 现实 | 我们的处理 |
+97
View File
@@ -597,6 +597,8 @@ function deviation(key, title, detail, scenarioId) {
const state = { const state = {
w1: null, w1: null,
w2: null, w2: null,
/** A workspace that must stay un-spawned (A14's live-only prompt-history read). */
w3: null,
sid: null, // backend session id of the W1 session sid: null, // backend session id of the W1 session
sidTmp: null, // placeholder id returned by session.create sidTmp: null, // placeholder id returned by session.create
sessionFile: null, sessionFile: null,
@@ -606,6 +608,8 @@ const state = {
childId: null, childId: null,
routedWithWorkspace: false, routedWithWorkspace: false,
attentionFile: null, attentionFile: null,
/** A4 landed a `prompt.send`, so the plugin archive must hold that text. */
promptSent: false,
}; };
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
@@ -631,6 +635,25 @@ async function sessionsList(workspaceId) {
return { res, rows: rows ?? [] }; return { res, rows: rows ?? [] };
} }
/**
* `GET /workspaces/:id/prompt-history` — the composer's ↑/↓ feed
* (`docs/protocol.md` §3.1.1). `query` is appended verbatim, so a caller can pass
* `"?limit=1"` without a second helper.
*/
async function promptHistory(workspaceId, query = "") {
const res = await http("GET", `/api/v1/workspaces/${workspaceId}/prompt-history${query}`, {
token: CLI_TOKEN,
});
const body = res.json ?? {};
return {
res,
body,
live: body.live,
supported: body.supported,
entries: Array.isArray(body.entries) ? body.entries : null,
};
}
async function addWorkspace(name, ctx) { async function addWorkspace(name, ctx) {
const cwd = join(WORKSPACE_ROOTS, name); const cwd = join(WORKSPACE_ROOTS, name);
mkdirSync(cwd, { recursive: true }); mkdirSync(cwd, { recursive: true });
@@ -1406,6 +1429,8 @@ scenario("A4", "Prompt + streaming (real model)", async (ctx) => {
observed: apiError(send), observed: apiError(send),
}); });
if (send.status !== 202) return; if (send.status !== 202) return;
// A14 reads this prompt back out of the plugin's archive.
state.promptSent = true;
let settled; let settled;
try { try {
@@ -3023,6 +3048,78 @@ scenario("A13", "Console login handoff", async (ctx) => {
ctx.eq("the new token works → 200", freshToken.status, 200); ctx.eq("the new token works → 200", freshToken.status, 200);
}); });
// ---------------------------------------------------------------------------
// A14 — prompt history recall (the composer's ↑/↓)
// ---------------------------------------------------------------------------
scenario("A14", "Prompt history recall", async (ctx) => {
if (!state.w1) skip("A1 did not produce a workspace id");
if (!state.promptSent) skip("A4 did not send a prompt");
// The read behind the composer's ↑/↓. A4 sent PONG_PROMPT through
// `prompt.send`, and only the plugin can answer this — the daemon stores
// nothing — so a hit here is the whole round trip proven:
// browser → daemon → plugin archive → daemon → browser.
const full = await promptHistory(state.w1);
ctx.eq("GET /workspaces/:id/prompt-history → 200", full.res.status, 200);
ctx.eq("the read is versioned (v=1)", full.body.v, 1);
ctx.eq("workspaceId is echoed", full.body.workspaceId, state.w1);
ctx.eq("a connected plugin answers the read", full.live, true);
ctx.eq("the plugin advertises the promptHistory capability", full.supported, true);
ctx.check("entries is a string[]", full.entries !== null, {
expected: "entries: string[]",
observed: fmt(full.body, 300),
});
const entries = full.entries ?? [];
const hits = entries.filter((entry) => entry === PONG_PROMPT).length;
ctx.check("the prompt sent from the console was recorded by the plugin, exactly once", hits === 1, {
expected: `"${PONG_PROMPT}" ×1`,
observed: { hits, total: entries.length, tail: entries.slice(-3) },
});
// `limit` trims from the newest end: the plugin's archive is oldest-first, so
// a recall feed asks for the tail.
const one = await promptHistory(state.w1, "?limit=1");
ctx.eq("?limit=1 → 200", one.res.status, 200);
const single = one.entries ?? [];
ctx.check("?limit=1 answers exactly one entry", single.length === 1, {
expected: 1,
observed: single.length,
});
ctx.eq("?limit=1 is the newest archived prompt", single[0], entries.at(-1));
// A workspace with no connected plugin answers `live:false` **without
// spawning**: recall is a convenience, never a lifecycle event. This is the
// assertion that would catch `instances.ensure()` creeping back into the read.
const cold = await addWorkspace("w3-history", ctx);
state.w3 = cold.workspaceId;
const coldRead = await promptHistory(state.w3);
ctx.eq("a workspace with no instance still answers 200", coldRead.res.status, 200);
ctx.eq("…with live:false", coldRead.live, false);
ctx.eq("…with supported:false", coldRead.supported, false);
ctx.check("…and no entries", coldRead.entries !== null && coldRead.entries.length === 0, {
expected: "entries: []",
observed: fmt(coldRead.body, 200),
});
const coldRow = await workspaceRow(state.w3);
ctx.check("the cold read did not spawn an instance", (coldRow?.instance ?? null) === null, {
expected: "instance: null",
observed: coldRow?.instance ?? null,
});
const coldAgain = await promptHistory(state.w3);
ctx.eq("a second cold read is equally idle", coldAgain.live, false);
const unknown = await promptHistory("0123456789abcdef");
ctx.eq("an unknown workspace → 404", unknown.res.status, 404);
ctx.evidence.promptHistory = {
workspaceId: state.w1,
archived: entries.length,
newest: entries.at(-1)?.slice(0, 80),
coldWorkspace: state.w3,
};
});
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
// reporting // reporting
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
+3 -1
View File
@@ -159,9 +159,11 @@ e2e_pair() {
code="$(jq -r '.code // empty' <<<"$created")" code="$(jq -r '.code // empty' <<<"$created")"
[ -n "$code" ] || e2e_fail "pair.create returned no code: $created" [ -n "$code" ] || e2e_fail "pair.create returned no code: $created"
# Redeeming is the *public* half of pairing: the code is the capability, so
# this call carries no authorization (ADR 0001, docs/protocol.md §3.1).
token="$(curl -sS --max-time 10 -X POST -H 'Content-Type: application/json' \ token="$(curl -sS --max-time 10 -X POST -H 'Content-Type: application/json' \
-d "{\"code\":\"$code\",\"deviceName\":\"$name\",\"kind\":\"laptop\"}" \ -d "{\"code\":\"$code\",\"deviceName\":\"$name\",\"kind\":\"laptop\"}" \
"$E2E_BASE/api/v1/pair" | jq -r '.token // empty')" "$E2E_BASE/api/v1/pair/redeem" | jq -r '.token // empty')"
[ -n "$token" ] || e2e_fail "pair redeem failed" [ -n "$token" ] || e2e_fail "pair redeem failed"
E2E_DEVICE_TOKEN="$token" E2E_DEVICE_TOKEN="$token"
E2E_PAIR_CODE="$code" E2E_PAIR_CODE="$code"
+171 -14
View File
@@ -244,6 +244,12 @@ async function listWorkspaces() {
return Array.isArray(list) ? list : (list.workspaces ?? []); return Array.isArray(list) ? list : (list.workspaces ?? []);
} }
async function listRecentSessions(limit = 20) {
const body = await api("GET", `/api/v1/sessions/recent?limit=${limit}`);
const rows = body?.sessions ?? (Array.isArray(body) ? body : []);
return Array.isArray(rows) ? rows : [];
}
async function createSession(workspaceId) { async function createSession(workspaceId) {
const result = await cmd("session.create", { workspaceId }); const result = await cmd("session.create", { workspaceId });
if (result.status !== 202 && result.status !== 200) { if (result.status !== 202 && result.status !== 200) {
@@ -657,6 +663,9 @@ async function waitEnabled(page, selector, timeout = 30000) {
const COMPOSER_INPUT = '[data-testid="composer-input"]'; const COMPOSER_INPUT = '[data-testid="composer-input"]';
/** The short prompt B6 sends; B15 recalls it out of the plugin's archive. */
const PONG_PROMPT = "Reply with exactly the word PONG and nothing else.";
/** `article.msg[data-entry-id]` projections (id/role come from the product test ids). */ /** `article.msg[data-entry-id]` projections (id/role come from the product test ids). */
async function streamArticles(page) { async function streamArticles(page) {
return page.evaluate(() => return page.evaluate(() =>
@@ -1263,24 +1272,53 @@ scenario("B4", "Workspaces: seeded rows/order/counts, path validation, UI add +
observed: await statusLine.locator("a").evaluateAll((nodes) => nodes.map((node) => node.getAttribute("href"))), observed: await statusLine.locator("a").evaluateAll((nodes) => nodes.map((node) => node.getAttribute("href"))),
}); });
// --- recent-activity column (new in v0.1.1) --------------------------- // --- recent-activity column (session-first since 0.1.1) ---------------
const activity = page.locator('[data-testid="workspaces-activity"]'); const activity = page.locator('[data-testid="workspaces-activity"]');
ctx.check("recent-activity column is present", (await activity.count()) === 1, { observed: await activity.count() }); ctx.check("recent-activity column is present", (await activity.count()) === 1, { observed: await activity.count() });
const activityRows = activity.locator('[data-testid="workspace-activity-row"]'); const activityRows = activity.locator('[data-testid="workspace-activity-row"]');
const activityIds = await activityRows.evaluateAll((nodes) => nodes.map((node) => node.getAttribute("data-workspace-id"))); const activityIds = await activityRows.evaluateAll((nodes) => nodes.map((node) => node.getAttribute("data-session-id")));
const activityWorkspaces = await activityRows.evaluateAll((nodes) => nodes.map((node) => node.getAttribute("data-workspace-id")));
const activityTitles = await activityRows.evaluateAll((nodes) =>
nodes.map((node) => node.querySelector(".ws-activity__name")?.textContent ?? ""),
);
const activityHrefs = await activityRows.evaluateAll((nodes) => nodes.map((node) => node.getAttribute("href"))); const activityHrefs = await activityRows.evaluateAll((nodes) => nodes.map((node) => node.getAttribute("href")));
const expectedActivity = rowIds const recentFeed = await listRecentSessions(20);
.map((id) => apiList.find((item) => item.workspaceId === id)) const recentById = new Map(recentFeed.map((row) => [row.sessionId, row]));
.filter((item) => item && typeof item.lastActiveAt === "number" && Number.isFinite(item.lastActiveAt)) const visibleWorkspaces = new Set(expectedOrder.map((item) => item.workspaceId));
.sort((a, b) => (b.lastActiveAt ?? 0) - (a.lastActiveAt ?? 0)) ctx.check("recent activity lists at most the newest 5 sessions", activityIds.length <= 5 && activityIds.length === activityWorkspaces.length, {
.slice(0, 5) expected: "≤ 5",
.map((item) => item.workspaceId); observed: activityIds.length,
ctx.checkValue("recent activity lists the newest 5 workspaces", activityIds, expectedActivity); });
ctx.check( ctx.check(
"activity rows link into /chat?workspace=<id>", "activity rows belong to visible workspaces",
activityHrefs.every((href, index) => href === `/chat?workspace=${activityIds[index]}`), activityWorkspaces.every((id) => visibleWorkspaces.has(id)),
{ observed: { activityIds, activityWorkspaces } },
);
ctx.check(
"activity rows link into /chat/<session>?workspace=<id>",
activityHrefs.every(
(href, index) => href === `/chat/${activityIds[index]}?workspace=${activityWorkspaces[index]}`,
),
{ observed: activityHrefs }, { observed: activityHrefs },
); );
// Regression guard for the workspace-page bug: a session the daemon (or a
// live instance) can title must not render as `(unnamed)`/`(未命名)`.
const placeholder = /unnamed|未命名/i;
ctx.check(
"recent-activity titles use session metadata when available",
activityIds.every((id, index) => {
const feed = recentById.get(id);
const titled = Boolean(feed?.name || feed?.firstMessage);
return !titled || !placeholder.test(activityTitles[index] ?? "");
}),
{
observed: activityIds.map((id, index) => ({
id,
feed: recentById.get(id)?.name ?? recentById.get(id)?.firstMessage ?? null,
title: activityTitles[index],
})),
},
);
// --- empty path validation (no POST must happen) ---------------------- // --- empty path validation (no POST must happen) ----------------------
const requestsBefore = ctx.cmdRequests.length; const requestsBefore = ctx.cmdRequests.length;
@@ -1370,7 +1408,7 @@ scenario("B5", "Chat tree: workspace picker, New session → /chat/<sid>, rename
await page.goto(`${BASE}/chat?workspace=${encodeURIComponent(state.ws1)}`, { waitUntil: "domcontentloaded" }); await page.goto(`${BASE}/chat?workspace=${encodeURIComponent(state.ws1)}`, { waitUntil: "domcontentloaded" });
await page.locator(".tree-pane .pane-head").waitFor({ state: "visible", timeout: 20000 }); await page.locator(".tree-pane .pane-head").waitFor({ state: "visible", timeout: 20000 });
// v0.1.1: the workspace picker is a button + `menuitemradio` menu (no <select>). // v0.1.1: the workspace picker is a button + searchable `listbox` (no <select>).
const wsSwitch = page.locator('[data-testid="ws-switch"]'); const wsSwitch = page.locator('[data-testid="ws-switch"]');
const wsMenu = page.locator('[data-testid="ws-menu"]'); const wsMenu = page.locator('[data-testid="ws-menu"]');
ctx.check("workspace switch is present", (await wsSwitch.count()) === 1, { observed: await wsSwitch.count() }); ctx.check("workspace switch is present", (await wsSwitch.count()) === 1, { observed: await wsSwitch.count() });
@@ -1380,13 +1418,40 @@ scenario("B5", "Chat tree: workspace picker, New session → /chat/<sid>, rename
.locator("[data-workspace-id]") .locator("[data-workspace-id]")
.evaluateAll((nodes) => nodes.map((node) => node.getAttribute("data-workspace-id"))); .evaluateAll((nodes) => nodes.map((node) => node.getAttribute("data-workspace-id")));
const checkedWorkspaces = await wsMenu const checkedWorkspaces = await wsMenu
.locator('[data-workspace-id][aria-checked="true"]') .locator('[data-workspace-id][aria-selected="true"]')
.evaluateAll((nodes) => nodes.map((node) => node.getAttribute("data-workspace-id"))); .evaluateAll((nodes) => nodes.map((node) => node.getAttribute("data-workspace-id")));
ctx.checkValue("the workspace menu marks W1 as current", checkedWorkspaces, [state.ws1]); ctx.checkValue("the workspace menu marks W1 as current", checkedWorkspaces, [state.ws1]);
ctx.check("workspace menu lists every workspace", options.length >= 2 && options.includes(state.ws2), { ctx.check("workspace menu lists every workspace", options.length >= 2 && options.includes(state.ws2), {
expected: [state.ws1, state.ws2], expected: [state.ws1, state.ws2],
observed: options, observed: options,
}); });
// The picker is searchable: one row per match, and a blank query restores all.
const search = page.locator('[data-testid="ws-menu-search"]');
await search.fill("ws2");
const filtered = await wsMenu
.locator("[data-workspace-id]")
.evaluateAll((nodes) => nodes.map((node) => node.getAttribute("data-workspace-id")));
ctx.checkValue("the workspace search filters to W2", filtered, [state.ws2]);
await search.fill("no-such-workspace-xyz");
const noMatch = await waitFor(
async () => ((await wsMenu.locator("[data-testid='ws-menu-empty']").count()) > 0 ? true : null),
6000,
);
ctx.check("the workspace search reports an empty result", Boolean(noMatch), {
observed: await wsMenu.locator("[data-workspace-id]").count(),
});
await page.locator('[data-testid="ws-menu"] .ws-menu__input').fill("");
const restored = await waitFor(
async () =>
(await wsMenu.locator("[data-workspace-id]").count()) === options.length ? true : null,
6000,
);
ctx.check("clearing the search restores every workspace", Boolean(restored), {
expected: options.length,
observed: await wsMenu.locator("[data-workspace-id]").count(),
});
await wsSwitch.click(); await wsSwitch.click();
const menuClosed = await waitFor(async () => ((await wsMenu.isVisible()) ? null : true), 6000); const menuClosed = await waitFor(async () => ((await wsMenu.isVisible()) ? null : true), 6000);
ctx.check("the workspace menu closes on a second click", Boolean(menuClosed), { observed: await wsMenu.isVisible() }); ctx.check("the workspace menu closes on a second click", Boolean(menuClosed), { observed: await wsMenu.isVisible() });
@@ -1544,7 +1609,7 @@ scenario("B6", "Prompt + streaming: PONG turn, one user entry, no .streaming aft
await textarea.fill(""); await textarea.fill("");
// --- Enter sends, the assistant streams and settles ------------------ // --- Enter sends, the assistant streams and settles ------------------
const prompt = "Reply with exactly the word PONG and nothing else."; const prompt = PONG_PROMPT;
await textarea.fill(prompt); await textarea.fill(prompt);
await page.keyboard.press("Enter"); await page.keyboard.press("Enter");
const sent = await waitFor(async () => ctx.cmdRequests.find((request) => request.method === "prompt.send") ?? null, 15000); const sent = await waitFor(async () => ctx.cmdRequests.find((request) => request.method === "prompt.send") ?? null, 15000);
@@ -2595,6 +2660,98 @@ scenario("B14", "i18n + theme: language menu switches html[lang]/copy, theme seg
await ctx.shot(page, "b14-theme-i18n"); await ctx.shot(page, "b14-theme-i18n");
}); });
/* ------------------------------------------------------------------ */
/* B15 — composer ↑/↓ recall from the plugin archive */
/* ------------------------------------------------------------------ */
scenario("B15", "Composer recall: ↑ restores the prompt B6 sent, over the relay (mirror wiped)", async (ctx) => {
const pong = state.pongSession;
if (!pong) ctx.skip("B6 did not produce a session to reuse");
const { page } = await ctx.openPage("paired");
ctx.check("chat page becomes usable", await openChat(page, pong.sessionId, pong.workspaceId), {
expected: "textarea[aria-label='Message input'] enabled",
observed: { composer: await composerState(page) },
});
// Delete this browser's fallback mirror and reload, so recall can only work
// from the relayed archive (docs/prompt-history.md: the plugin owns the text,
// the mirror is only a fallback). A regression that dropped the relay would
// leave nothing to recall here.
await page.evaluate(() => localStorage.removeItem("pi2-prompt-history"));
await page.reload({ waitUntil: "domcontentloaded" });
ctx.check("chat page reloads usable", await openChat(page, pong.sessionId, pong.workspaceId), {
expected: "composer enabled after reload",
observed: { composer: await composerState(page) },
});
const relayed = await waitFor(
async () => ctx.apiCalls.find((call) => call.path.includes("/prompt-history") && call.status === 200) ?? null,
20000,
);
ctx.check("the console reads GET /workspaces/:id/prompt-history", Boolean(relayed), {
expected: "200 on /prompt-history",
observed: ctx.apiCalls.map((call) => `${call.method} ${call.path} ${call.status}`).slice(-10),
});
const textarea = page.locator(COMPOSER_INPUT);
await textarea.click();
await textarea.fill("");
// The archive is workspace-scoped, and later scenarios (B7's abort, B10's
// attention turn) send into the *same* workspace — so the newest entry is not
// necessarily B6's. Recall the newest first, then walk back until B6's prompt
// shows up; both directions are part of the contract, so this asserts more
// than a single-step recall would.
await page.keyboard.press("ArrowUp");
const newest = await waitFor(async () => (await textarea.inputValue()).trim() || null, 15000);
ctx.check("↑ recalls the newest archived prompt", Boolean(newest), {
expected: "a non-empty prompt",
observed: newest,
});
let reachedPong = newest === PONG_PROMPT;
for (let step = 0; step < 30 && !reachedPong; step += 1) {
// `↑` only recalls from the first line (nvim's rule), so park the caret
// there before each step.
await page.keyboard.press("Control+Home");
await page.keyboard.press("ArrowUp");
await sleep(120);
reachedPong = (await textarea.inputValue()) === PONG_PROMPT;
}
ctx.check("↑ walks back to the prompt B6 sent (archive round trip)", reachedPong, {
expected: PONG_PROMPT,
observed: await textarea.inputValue(),
});
// ↓ all the way back out: the stashed (empty) draft returns.
let draftBack = false;
for (let step = 0; step < 40 && !draftBack; step += 1) {
await page.keyboard.press("ArrowDown");
await sleep(120);
draftBack = (await textarea.inputValue()) === "";
}
ctx.check("↓ walks back out to the empty draft", draftBack, {
expected: "",
observed: await textarea.inputValue(),
});
// Ctrl+P is the readline alias: it recalls without moving the caret first.
await textarea.fill("half typed");
await page.keyboard.press("Control+p");
const viaCtrlP = await waitFor(async () => (await textarea.inputValue()) || null, 10000);
ctx.check("Ctrl+P recalls the newest entry from a mid-line caret", viaCtrlP === newest, {
expected: newest,
observed: viaCtrlP,
});
ctx.check("recall never sent anything",
!ctx.cmdRequests.some((request) => request.method === "prompt.send"),
{ observed: ctx.cmdRequests.map((request) => request.method) },
);
await ctx.shot(page, "b15-composer-recall");
});
/* ------------------------------------------------------------------ */ /* ------------------------------------------------------------------ */
/* C1 — responsive overflow */ /* C1 — responsive overflow */
/* ------------------------------------------------------------------ */ /* ------------------------------------------------------------------ */
+1 -1
View File
@@ -46,7 +46,7 @@ done
echo "instance: $ST workspace: $WSID" echo "instance: $ST workspace: $WSID"
CODE=$(cmd '{"method":"pair.create","params":{}}' | jq -r '.code') CODE=$(cmd '{"method":"pair.create","params":{}}' | jq -r '.code')
DEVTOKEN=$(curl -fsS -X POST "$BASE/api/v1/pair" -H 'Content-Type: application/json' \ DEVTOKEN=$(curl -fsS -X POST "$BASE/api/v1/pair/redeem" -H 'Content-Type: application/json' \
-d "{\"code\":\"$CODE\",\"deviceName\":\"Playwright\",\"kind\":\"laptop\"}" | jq -r '.token') -d "{\"code\":\"$CODE\",\"deviceName\":\"Playwright\",\"kind\":\"laptop\"}" | jq -r '.token')
echo "paired device token: ${DEVTOKEN:0:8}…" echo "paired device token: ${DEVTOKEN:0:8}…"
+24
View File
@@ -263,6 +263,12 @@ function serveStatic(req, res, pathname) {
return undefined; return undefined;
} }
/** Prompt-history fixture for `workspace.query{kind:"promptHistory"}` (protocol §3.1.1). */
const PROMPT_HISTORY_FIXTURE = [
"Summarise the diff and list the risky parts.",
"Run the full gate: typecheck, both test suites, smoke.",
];
/** Sessions of one workspace, in the shape `/workspaces/:id/sessions` acks. */ /** Sessions of one workspace, in the shape `/workspaces/:id/sessions` acks. */
function sessionsOf(workspaceId) { function sessionsOf(workspaceId) {
const rows = FIXTURES.sessions.filter((session) => session.workspaceId === workspaceId); const rows = FIXTURES.sessions.filter((session) => session.workspaceId === workspaceId);
@@ -366,6 +372,24 @@ async function handleApi(req, res, url) {
} }
return sendJson(res, 200, sessionsOf(workspaceId)); return sendJson(res, 200, sessionsOf(workspaceId));
} }
// Composer ↑ recall. Always "live" here: the harness should exercise the
// relayed path, not the browser-mirror fallback (which the unit tests cover).
match = /^\/api\/v1\/workspaces\/([^/]+)\/prompt-history$/.exec(pathname);
if (match && method === "GET") {
const workspaceId = decodeURIComponent(match[1]);
if (!FIXTURES.workspaces.some((workspace) => workspace.workspaceId === workspaceId)) {
return notFound(res, `unknown workspace ${workspaceId}`);
}
const raw = Number(url.searchParams.get("limit"));
const limit = Number.isFinite(raw) && raw > 0 ? Math.min(500, Math.floor(raw)) : 200;
return sendJson(res, 200, {
v: 1,
workspaceId,
live: true,
supported: true,
entries: PROMPT_HISTORY_FIXTURE.slice(-limit),
});
}
match = /^\/api\/v1\/sessions\/([^/]+)\/entries$/.exec(pathname); match = /^\/api\/v1\/sessions\/([^/]+)\/entries$/.exec(pathname);
if (match && method === "GET") { if (match && method === "GET") {
const sessionId = decodeURIComponent(match[1]); const sessionId = decodeURIComponent(match[1]);
+46
View File
@@ -10,6 +10,7 @@
* pi2 pairing create a pairing code for another device * pi2 pairing create a pairing code for another device
* pi2 install-service render/install a systemd user unit or LaunchAgent * pi2 install-service render/install a systemd user unit or LaunchAgent
* pi2 uninstall-service remove it again * pi2 uninstall-service remove it again
* pi2 uninstall remove the daemon's local state (all channels)
* pi2 service … status/start/stop/enable/disable that unit * pi2 service … status/start/stop/enable/disable that unit
* *
* Everything is discovered from the runtime dir: `daemon.json` carries the * Everything is discovered from the runtime dir: `daemon.json` carries the
@@ -50,6 +51,7 @@ import { diagnose, formatReport, reportToJson, type DoctorReport } from "./docto
import { runStop, STOP_USAGE, type StopOptions } from "./stop.js"; import { runStop, STOP_USAGE, type StopOptions } from "./stop.js";
import { runConfig, CONFIG_USAGE, type RunConfigOptions } from "./config.js"; import { runConfig, CONFIG_USAGE, type RunConfigOptions } from "./config.js";
import { runUpdate, UPDATE_USAGE } from "./update.js"; import { runUpdate, UPDATE_USAGE } from "./update.js";
import { runUninstall, UNINSTALL_USAGE, type UninstallOptions } from "./uninstall.js";
import { import {
parseServiceArgs, parseServiceArgs,
runServiceCommand, runServiceCommand,
@@ -86,6 +88,7 @@ Usage:
pi2 pairing [--base <url>] [--json] create a pairing code (URL + code + QR) pi2 pairing [--base <url>] [--json] create a pairing code (URL + code + QR)
pi2 install-service [--dry-run|--write] systemd user unit / LaunchAgent pi2 install-service [--dry-run|--write] systemd user unit / LaunchAgent
pi2 uninstall-service [--dry-run|--write] remove the unit pi2 uninstall-service [--dry-run|--write] remove the unit
pi2 uninstall [--dry-run] [--yes] [--purge] remove the daemon's local state
pi2 service status|start|stop|enable|disable control that unit (status [--json]) pi2 service status|start|stop|enable|disable control that unit (status [--json])
pi2 update [--check|--dry-run] upgrade a standalone (curl installer) pi2 in place pi2 update [--check|--dry-run] upgrade a standalone (curl installer) pi2 in place
pi2 --version | --help pi2 --version | --help
@@ -749,6 +752,8 @@ export interface Pi2Options {
serviceExists?: (path: string) => boolean; serviceExists?: (path: string) => boolean;
serviceUid?: number; serviceUid?: number;
serviceUser?: string; serviceUser?: string;
/** Injected `pi2 uninstall` runner (defaults to `runUninstall`). */
uninstall?: (options: UninstallOptions) => Promise<number>;
} }
export async function main(argv: readonly string[], options: Pi2Options = {}): Promise<number> { export async function main(argv: readonly string[], options: Pi2Options = {}): Promise<number> {
@@ -896,6 +901,47 @@ export async function main(argv: readonly string[], options: Pi2Options = {}): P
}; };
return command === "install-service" ? runInstallService(serviceOptions) : runUninstallService(serviceOptions); return command === "install-service" ? runInstallService(serviceOptions) : runUninstallService(serviceOptions);
} }
case "uninstall": {
let parsed;
try {
parsed = parseArgs(rest, {
booleans: [
"--dry-run",
"--yes",
"--purge",
"--purge-config",
"--keep-service",
"--keep-install",
"--help",
],
aliases: { "-y": "--yes", "-h": "--help" },
});
} catch (error) {
if (error instanceof UsageError) throw new UsageError(error.message, UNINSTALL_USAGE);
throw error;
}
if (boolFlag(parsed.flags, "--help")) {
out(UNINSTALL_USAGE);
return 0;
}
if (parsed.positionals.length > 0) {
throw new UsageError(`unexpected argument "${parsed.positionals[0]}"`, UNINSTALL_USAGE);
}
return await (options.uninstall ?? runUninstall)({
dryRun: boolFlag(parsed.flags, "--dry-run"),
yes: boolFlag(parsed.flags, "--yes"),
purge: boolFlag(parsed.flags, "--purge"),
purgeConfig: boolFlag(parsed.flags, "--purge-config"),
keepService: boolFlag(parsed.flags, "--keep-service"),
keepInstall: boolFlag(parsed.flags, "--keep-install"),
print: out,
warn: err,
...(options.runtime === undefined ? {} : { runtime: options.runtime }),
...(options.platform === undefined ? {} : { platform: options.platform }),
...(options.servicePaths === undefined ? {} : { servicePaths: options.servicePaths }),
...(options.isTTY === undefined ? {} : { isTTY: options.isTTY }),
});
}
case "update": { case "update": {
let parsed; let parsed;
try { try {
+485
View File
@@ -0,0 +1,485 @@
/**
* `pi2 uninstall` — remove what pi2 wrote to this machine.
*
* Every other removal path owns one slice and knows nothing about the others:
* `npm rm -g`, `brew uninstall`, `install.sh --uninstall` own a binary tree,
* `pi2 uninstall-service` owns the unit file, and none of them touches the
* runtime/data/state directories. Deleting the binary while the daemon still
* runs also leaves an orphan process. This command owns the *state* for every
* channel, and prints the channel's own command for the binary tree instead of
* deleting a tree a package manager tracks.
*
* The layout is the one `docs/deployment.md` documents:
*
* runtime sockets, `cli.token`, `daemon.lock` always removed
* data `devices.json`, `workspaces.json` `--purge`
* state instance logs, host-init, update cache `--purge`
* config `~/.config/pi2/env` `--purge-config`
* unit systemd/launchd file removed unless --keep-service
* install `<prefix>` on the curl channel `--purge` (last: we run from it)
*
* Destructive by design, so: a plan is printed first, nothing happens without
* `--yes` (or an interactive `y`), and everything a reinstall would silently
* lose is an explicit opt-in.
*
* Every side effect is injected (`removeDir`, `removeFile`, `disableService`,
* `removeService`, `stopDaemon`, `daemonPid`, `serviceInstalled`, `channel`,
* `confirm`) so the tests never touch the filesystem, systemd or a process.
*/
import { existsSync, rmSync } from "node:fs";
import { homedir, platform as osPlatform } from "node:os";
import { join, sep } from "node:path";
import { isBundledRuntime, versionedLayoutFor } from "../core/install.js";
import { dataDir, realpathSafe, runtimeDir, stateDir } from "../core/paths.js";
import { channelUninstallCommand } from "../core/release.js";
import {
assessLock,
DAEMON_JSON_FILE,
isPidAlive,
LOCK_FILE,
readBootId,
readDaemonJson,
readLockFile,
} from "./lock.js";
import { defaultServicePaths, renderService, type ServicePaths, type ServicePlatform } from "./service.js";
import { runServiceCommand } from "./service-control.js";
import { runStop } from "./stop.js";
import { CliError, errorMessage } from "./util.js";
export const UNINSTALL_USAGE = `pi2 uninstall — remove pi2's local state
Usage:
pi2 uninstall [options]
Stops the daemon, disables and removes the user service unit when one is
installed, and deletes the runtime directory (sockets, CLI token, lock).
Everything a reinstall would silently lose is opt-in:
--purge also delete the data dir (paired devices, workspace trust)
and the state dir (instance logs, host-init, update cache)
--purge-config also delete the env file (~/.config/pi2/env)
On the standalone channel (curl installer) \`--purge\` also removes the install
tree. It goes last, because the running binary lives inside it.
Options:
--dry-run print the plan, change nothing
-y, --yes do not ask for confirmation (required when stdin is not a TTY)
--purge also remove the data and state directories
--purge-config also remove the env file
--keep-service leave the user service unit installed
--keep-install never remove the curl-installer tree, even with --purge
-h, --help print this help and exit
The binaries themselves belong to the channel that installed them (npm, brew,
the AUR, or \`install.sh --uninstall\`); this command prints that command rather
than deleting a tree it does not own.
Environment:
PI2_RUNTIME_DIR runtime directory (default: $XDG_RUNTIME_DIR/pi2)
PI2_DATA_DIR data directory (default: ~/.local/share/pi2)
PI2_STATE_DIR state directory (default: ~/.local/state/pi2)
XDG_CONFIG_HOME locates the env file (default: ~/.config/pi2/env)`;
export type UninstallTarget = "service" | "daemon" | "runtime" | "data" | "state" | "config" | "install";
/** One line of the plan; `remove: false` is the "kept, and here is the flag" case. */
export interface UninstallStep {
target: UninstallTarget;
/** Absolute paths this step deletes. Empty for `daemon`. */
paths: string[];
remove: boolean;
/** `pid 4242` for the daemon step. */
detail?: string;
}
export type UninstallChannelName = "curl" | "brew" | "aur" | "npm" | "unknown";
export interface UninstallChannel {
installer: UninstallChannelName;
/** curl-installer layout only: `<prefix>` holding `versions/` and `current`. */
prefix?: string;
}
/**
* Which channel owns the binary tree. The versioned layout is unambiguous (only
* `install.sh` writes `<prefix>/versions/<version>/bin/pi2`); the rest is a
* best-effort read of where the executable sits, used only for the hint text.
*/
export function detectUninstallChannel(execPath: string, bundled: boolean): UninstallChannel {
const layout = versionedLayoutFor(execPath);
if (layout !== undefined) return { installer: "curl", prefix: layout.prefix };
if (!bundled) return { installer: "npm" };
if (execPath.includes("/Cellar/") || execPath.includes("/homebrew/")) return { installer: "brew" };
if (execPath.startsWith("/usr/")) return { installer: "aur" };
return { installer: "unknown" };
}
/** `$XDG_CONFIG_HOME/pi2/env` — the `EnvironmentFile=` a systemd unit points at. */
export function configEnvPath(
env: NodeJS.ProcessEnv = process.env,
home: string = homedir(),
): string {
return join(env.XDG_CONFIG_HOME ?? join(home, ".config"), "pi2", "env");
}
const TARGET_LABEL: Record<UninstallTarget, string> = {
service: "service unit",
daemon: "daemon",
runtime: "runtime dir",
data: "data dir",
state: "state dir",
config: "config file",
install: "install tree",
};
/** Why a kept path is kept — the flag that would remove it. */
const TARGET_HINT: Partial<Record<UninstallTarget, string>> = {
data: "--purge",
state: "--purge",
config: "--purge-config",
install: "--purge",
service: "--keep-service",
};
export interface UninstallPlanOptions {
runtime: string;
data: string;
state: string;
configEnv: string;
/** The unit file path (`renderService(...).path`). */
serviceUnit: string;
purge: boolean;
purgeConfig: boolean;
keepService?: boolean;
keepInstall?: boolean;
serviceInstalled: boolean;
daemonPid?: number;
channel: UninstallChannel;
/** Injected in tests; `existsSync` otherwise. */
exists?: (path: string) => boolean;
}
/** Pure: what would be touched, in execution order. */
export function planUninstall(options: UninstallPlanOptions): UninstallStep[] {
const exists = options.exists ?? existsSync;
const steps: UninstallStep[] = [];
if (options.serviceInstalled) {
steps.push({
target: "service",
paths: [options.serviceUnit],
remove: options.keepService !== true,
});
}
if (options.daemonPid !== undefined) {
steps.push({ target: "daemon", paths: [], remove: true, detail: `pid ${options.daemonPid}` });
}
if (exists(options.runtime)) {
steps.push({ target: "runtime", paths: [options.runtime], remove: true });
}
const optional: [UninstallTarget, string, boolean][] = [
["data", options.data, options.purge],
["state", options.state, options.purge],
["config", options.configEnv, options.purgeConfig],
];
for (const [target, path, remove] of optional) {
if (!exists(path)) continue;
steps.push({ target, paths: [path], remove });
}
// Only the tree pi2 itself wrote can be deleted here; npm/brew/AUR own theirs.
if (
options.purge &&
options.channel.installer === "curl" &&
options.channel.prefix !== undefined &&
exists(options.channel.prefix)
) {
steps.push({
target: "install",
paths: [options.channel.prefix],
remove: options.keepInstall !== true,
});
}
return steps;
}
/** One plan line: verb, target label, path (or pid), and the flag that keeps it. */
export function formatUninstallStep(step: UninstallStep, dryRun = false): string {
const verb = step.remove
? dryRun
? step.target === "daemon"
? "would stop"
: "would remove"
: step.target === "daemon"
? "stop"
: "remove"
: "keep";
const target = step.detail ?? step.paths.join(", ");
// The hint names the flag that would change the outcome, so it only makes
// sense on a kept step.
const hint = step.remove ? undefined : TARGET_HINT[step.target];
return ` ${verb.padEnd(14)}${TARGET_LABEL[step.target].padEnd(14)}${target}${hint === undefined ? "" : ` (${hint})`}`;
}
/** `~/.local/bin/pi2`, when it is a symlink into the curl-installer prefix. */
export function installerBinSymlink(prefix: string, home: string = homedir()): string | undefined {
const candidate = join(home, ".local", "bin", "pi2");
if (!existsSync(candidate)) return undefined;
return realpathSafe(candidate).startsWith(`${prefix}${sep}`) ? candidate : undefined;
}
export interface UninstallOptions {
runtime?: string;
data?: string;
state?: string;
configEnv?: string;
purge?: boolean;
purgeConfig?: boolean;
keepService?: boolean;
keepInstall?: boolean;
dryRun?: boolean;
yes?: boolean;
platform?: ServicePlatform;
servicePaths?: ServicePaths;
execPath?: string;
isBundled?: boolean;
homeDir?: string;
env?: NodeJS.ProcessEnv;
isTTY?: boolean;
print?: (line: string) => void;
warn?: (line: string) => void;
confirm?: (question: string) => Promise<boolean>;
exists?: (path: string) => boolean;
removeDir?: (path: string) => void;
removeFile?: (path: string) => void;
/** Live daemon pid, `undefined` when none is running. */
daemonPid?: (runtime: string) => number | undefined;
serviceInstalled?: (unitPath: string) => boolean;
stopDaemon?: (runtime: string) => Promise<void>;
disableService?: () => Promise<void>;
removeService?: (unitPath: string) => void;
channel?: UninstallChannel;
}
function defaultDaemonPid(runtime: string): number | undefined {
const lock = readDaemonJson(join(runtime, DAEMON_JSON_FILE)) ?? readLockFile(join(runtime, LOCK_FILE));
if (lock === undefined) return undefined;
return assessLock(lock, { isPidAlive, bootId: readBootId }).live ? lock.pid : undefined;
}
/** `pi2 stop`, with "there is nothing to stop" treated as success. */
async function defaultStopDaemon(runtime: string): Promise<void> {
try {
await runStop({ runtime, print: () => undefined });
} catch (error) {
if (error instanceof CliError && error.message.includes("no running pi2 daemon")) return;
throw error;
}
}
/** A single `y`/`yes` on stdin; everything else (including EOF) is a no. */
function defaultConfirm(question: string): Promise<boolean> {
return new Promise((resolve) => {
process.stdout.write(question);
const finish = (answer: boolean): void => {
process.stdin.pause();
process.stdin.removeListener("data", onData);
process.stdin.removeListener("end", onEnd);
resolve(answer);
};
const onData = (chunk: Buffer | string): void => finish(/^y(es)?$/i.test(String(chunk).trim()));
// EOF (Ctrl-D, a closed pipe) is a no, never a hang.
const onEnd = (): void => finish(false);
process.stdin.resume();
process.stdin.once("data", onData);
process.stdin.once("end", onEnd);
});
}
/** The commands that finish the job on the channel that owns the binaries. */
export function uninstallNextSteps(
steps: readonly UninstallStep[],
channel: UninstallChannel,
): string[] {
const lines: string[] = [];
const installRemoved = steps.some((step) => step.target === "install" && step.remove);
if (!installRemoved) {
lines.push(`remove the binaries (${channel.installer} channel): ${channelUninstallCommand(channel.installer)}`);
}
const kept = steps.filter((step) => !step.remove && step.target !== "service");
const keptDirs = kept.filter((step) => step.target !== "config").flatMap((step) => step.paths);
lines.push("clear the console's site data in the browser — it caches the paired device token");
lines.push('remove the plugin-private daemon copy, if `:PiWebInstall` ran: rm -rf <nvim stdpath("data")>/pi2d');
if (keptDirs.length > 0) {
lines.push(`rm -rf ${keptDirs.join(" ")}`);
}
return lines;
}
/** Kept service unit → the command that takes it down, platform-specific. */
export function keptServiceHint(platform: ServicePlatform, paths: ServicePaths): string | undefined {
return renderService(platform, paths).removeCommands[0];
}
/**
* Remove the daemon's local state.
*
* Returns 0 when there was nothing to do or everything succeeded, 1 when the
* confirmation was declined or any removal failed (each failure is reported on
* `warn` and does not stop the remaining steps).
*/
export async function runUninstall(options: UninstallOptions = {}): Promise<number> {
const print = options.print ?? ((line: string) => process.stdout.write(`${line}\n`));
const warn = options.warn ?? ((line: string) => process.stderr.write(`pi2: ${line}\n`));
const exists = options.exists ?? existsSync;
const removeDir = options.removeDir ?? ((path: string) => rmSync(path, { recursive: true, force: true }));
const removeFile = options.removeFile ?? ((path: string) => rmSync(path, { force: true }));
const home = options.homeDir ?? homedir();
const platform = options.platform ?? (osPlatform() === "darwin" ? "darwin" : "linux");
const servicePaths = options.servicePaths ?? defaultServicePaths();
const service = renderService(platform, servicePaths);
const channel =
options.channel ??
detectUninstallChannel(
options.execPath ?? process.execPath,
options.isBundled ?? isBundledRuntime(),
);
const dryRun = options.dryRun === true;
const paths = {
runtime: options.runtime ?? runtimeDir(),
data: options.data ?? dataDir(),
state: options.state ?? stateDir(),
configEnv: options.configEnv ?? configEnvPath(options.env ?? process.env, home),
};
const steps = planUninstall({
...paths,
serviceUnit: service.path,
purge: options.purge === true,
purgeConfig: options.purgeConfig === true,
...(options.keepService === undefined ? {} : { keepService: options.keepService }),
...(options.keepInstall === undefined ? {} : { keepInstall: options.keepInstall }),
serviceInstalled: (options.serviceInstalled ?? exists)(service.path),
...(options.daemonPid === undefined
? { daemonPid: defaultDaemonPid(paths.runtime) }
: { daemonPid: options.daemonPid(paths.runtime) }),
channel,
exists,
});
const installStep = steps.find((step) => step.target === "install");
if (installStep !== undefined && channel.prefix !== undefined) {
const link = installerBinSymlink(channel.prefix, home);
if (link !== undefined) installStep.paths.push(link);
}
print(dryRun ? "pi2 uninstall — dry run, nothing will be changed" : "pi2 uninstall");
for (const step of steps) print(formatUninstallStep(step, dryRun));
const removable = steps.filter((step) => step.remove);
if (removable.length === 0) {
print("nothing to remove: pi2 keeps no state for this user");
printNextSteps(print, steps, channel, keptServiceHint(platform, servicePaths));
return 0;
}
if (dryRun) {
printNextSteps(print, steps, channel, keptServiceHint(platform, servicePaths));
return 0;
}
if (options.yes !== true) {
const isTTY = options.isTTY ?? process.stdin.isTTY === true;
if (!isTTY && options.confirm === undefined) {
throw new CliError(
"refusing to remove anything without confirmation.\n" +
" re-run with --yes (scripts), or --dry-run to inspect the plan first.",
);
}
const confirmed = await (options.confirm ?? defaultConfirm)(`Remove these ${removable.length} item(s)? [y/N] `);
if (!confirmed) {
print("aborted — nothing was removed");
return 1;
}
}
let removed = 0;
let failures = 0;
let stopped: number | undefined;
const stopDaemon = options.stopDaemon ?? defaultStopDaemon;
const disableService = options.disableService ?? (() => defaultDisableService(platform, servicePaths));
const removeService = options.removeService ?? ((path: string) => removeFile(path));
for (const step of removable) {
if (step.target === "service") {
try {
await disableService();
} catch (error) {
warn(`could not disable ${service.name}: ${errorMessage(error)}`);
}
try {
removeService(service.path);
removed += 1;
} catch (error) {
failures += 1;
warn(`could not remove ${service.path}: ${errorMessage(error)}`);
}
continue;
}
if (step.target === "daemon") {
try {
await stopDaemon(paths.runtime);
stopped = 1;
} catch (error) {
failures += 1;
warn(`could not stop the daemon: ${errorMessage(error)}`);
}
continue;
}
for (const path of step.paths) {
try {
if (step.target === "config") removeFile(path);
else removeDir(path);
removed += 1;
} catch (error) {
failures += 1;
warn(`could not remove ${path}: ${errorMessage(error)}`);
}
}
}
const parts = [`removed ${removed} path(s)`];
if (stopped !== undefined) parts.push("stopped the daemon");
if (failures > 0) parts.push(`${failures} failure(s)`);
print(parts.join(", "));
printNextSteps(print, steps, channel, keptServiceHint(platform, servicePaths));
return failures > 0 ? 1 : 0;
}
function printNextSteps(
print: (line: string) => void,
steps: readonly UninstallStep[],
channel: UninstallChannel,
serviceHint?: string,
): void {
const lines = uninstallNextSteps(steps, channel);
const keptService = steps.some((step) => step.target === "service" && !step.remove);
if (keptService && serviceHint !== undefined) {
lines.push(`the service unit is still enabled: ${serviceHint}`);
}
if (lines.length === 0) return;
print("");
print("Next:");
for (const line of lines) print(` - ${line}`);
}
/** `pi2 service disable` — a missing manager is a warning, not a failure. */
async function defaultDisableService(platform: ServicePlatform, paths: ServicePaths): Promise<void> {
await runServiceCommand("disable", { platform, paths, print: () => undefined });
}
+12 -1
View File
@@ -145,7 +145,18 @@ export async function wireDaemon(options: WireOptions = {}): Promise<WiredDaemon
machineId: options.machineId ?? machineIdFor(env.HOSTNAME ?? process.env.HOSTNAME ?? "localhost"), machineId: options.machineId ?? machineIdFor(env.HOSTNAME ?? process.env.HOSTNAME ?? "localhost"),
startedAt, startedAt,
now, now,
sysinfo: createSysinfo({ now }), sysinfo: createSysinfo({
now,
// Only the filesystems pi2d actually writes to: root, the pi session
// store (built in) and the visible workspace roots. Hidden/secondary
// rows are excluded so a stale ghost dir never adds a disk row.
diskPaths: () =>
(workspaceStore?.list() ?? [])
.filter((workspace) => workspace.exists && workspace.visibility !== "secondary")
.sort((a, b) => (b.lastActiveAt ?? 0) - (a.lastActiveAt ?? 0))
.slice(0, 8)
.map((workspace) => workspace.cwd),
}),
...(options.server?.heartbeatMs === undefined ? {} : { heartbeatMs: options.server.heartbeatMs }), ...(options.server?.heartbeatMs === undefined ? {} : { heartbeatMs: options.server.heartbeatMs }),
...(options.server?.ws === undefined ? {} : { ws: options.server.ws }), ...(options.server?.ws === undefined ? {} : { ws: options.server.ws }),
}; };
+2
View File
@@ -22,6 +22,8 @@ export interface PluginConnection {
readonly hasUI: boolean; readonly hasUI: boolean;
readonly listenAddr: string | null; readonly listenAddr: string | null;
readonly pluginVersion: string; readonly pluginVersion: string;
/** Capability strings the plugin advertised in its `hello` (`snapshot`, `promptHistory`, …). */
readonly capabilities: string[];
/** Send one JSONL record to the plugin. */ /** Send one JSONL record to the plugin. */
send(record: Record<string, unknown>): void; send(record: Record<string, unknown>): void;
/** Forward a command; resolves with the plugin `ack` payload. */ /** Forward a command; resolves with the plugin `ack` payload. */
+22
View File
@@ -225,3 +225,25 @@ export function channelUpgradeCommand(installer: string): string {
return "npm i -g @yuez/pi2d@latest # or: brew upgrade pi2d"; return "npm i -g @yuez/pi2d@latest # or: brew upgrade pi2d";
} }
} }
/**
* The command that removes the *binary tree* for a channel, for `pi2 uninstall`.
*
* `pi2 uninstall` owns the state (runtime/data/state/config) and never touches a
* tree a package manager tracks — except the curl layout, which is the one pi2
* wrote itself and can delete.
*/
export function channelUninstallCommand(installer: string): string {
switch (installer) {
case "brew":
return "brew uninstall pi2d";
case "aur":
return "sudo pacman -R pi2d-bin";
case "npm":
return "npm rm -g @yuez/pi2d";
case "curl":
return `curl -fsSL https://raw.githubusercontent.com/${RELEASE_REPO}/main/scripts/install.sh | sh -s -- --uninstall`;
default:
return "npm rm -g @yuez/pi2d # or: brew uninstall pi2d";
}
}
+216 -18
View File
@@ -2,10 +2,11 @@
* Host sysinfo sampler — CPU / memory / disk with injectable I/O. * Host sysinfo sampler — CPU / memory / disk with injectable I/O.
* Zero runtime dependencies; no OS calls at import time. * Zero runtime dependencies; no OS calls at import time.
*/ */
import { statfs as nodeStatfs } from "node:fs/promises"; import { stat as nodeStat, statfs as nodeStatfs } from "node:fs/promises";
import * as nodeOs from "node:os"; import * as nodeOs from "node:os";
import { readFile as nodeReadFile } from "node:fs/promises"; import { readFile as nodeReadFile } from "node:fs/promises";
import { stateDir } from "./paths.js"; import { dirname, resolve as resolvePath } from "node:path";
import { IS_MAC, sessionsRoot, stateDir } from "./paths.js";
/* ------------------------------------------------------------------ */ /* ------------------------------------------------------------------ */
/* Public types */ /* Public types */
@@ -20,20 +21,48 @@ export interface StatFsLike {
bsize: number; bsize: number;
blocks: number; blocks: number;
bfree: number; bfree: number;
/** Linux filesystem magic (`f_type`); used for the best-effort `fsType` label. */
type?: number;
}
/** The slice of `fs.Stats` the mount probe needs. */
export interface StatLike {
dev: number | bigint;
}
/**
* One sampled filesystem. `mountPoint` is the boundary the probe found by
* walking up while `st_dev` stayed the same — never the raw candidate path,
* which is usually a deep, user-irrelevant directory.
*/
export interface DiskUsage {
mountPoint: string;
/** Best-effort type label (`ext4`, `btrfs`, …); absent when unknown. */
fsType?: string;
totalBytes: number;
usedBytes: number;
percent: number;
} }
export interface SystemStats { export interface SystemStats {
sampledAt: number; sampledAt: number;
/** Host uptime in whole seconds (`os.uptime()`), `null` when the OS has none. */
hostUptimeSec: number | null;
cpuPercent: number | null; cpuPercent: number | null;
cpuCores: number; cpuCores: number;
loadAvg: [number, number, number] | null; loadAvg: [number, number, number] | null;
memUsedBytes: number; memUsedBytes: number;
memTotalBytes: number; memTotalBytes: number;
memPercent: number; memPercent: number;
/** Mount point of the most constrained disk (`disks[0]`); legacy scalar fields alias it. */
diskPath: string; diskPath: string;
diskUsedBytes: number | null; diskUsedBytes: number | null;
diskTotalBytes: number | null; diskTotalBytes: number | null;
diskPercent: number | null; diskPercent: number | null;
/** At most `maxDisks` filesystems, most constrained first. */
disks: DiskUsage[];
/** Why no filesystem could be sampled; absent when `disks` is non-empty. */
diskError?: string;
} }
export interface SysinfoSampler { export interface SysinfoSampler {
@@ -47,9 +76,19 @@ export interface SysinfoDeps {
cpus?: () => Array<{ times: { user: number; nice: number; sys: number; idle: number; irq: number } }>; cpus?: () => Array<{ times: { user: number; nice: number; sys: number; idle: number; irq: number } }>;
totalmem?: () => number; totalmem?: () => number;
freemem?: () => number; freemem?: () => number;
uptime?: () => number;
loadavg?: () => number[]; loadavg?: () => number[];
platform?: NodeJS.Platform; platform?: NodeJS.Platform;
/** Primary disk candidate; defaults to `/` (the home volume on macOS). */
diskPath?: string; diskPath?: string;
/** Where pi keeps its sessions; sampled as a second candidate. Defaults to `sessionsRoot()`. */
sessionsPath?: string;
/** Extra candidates sampled per request (e.g. the visible workspace roots). */
diskPaths?: () => string[];
/** Whether two paths share a filesystem; injectable so tests never touch the disk. */
stat?: (path: string) => Promise<StatLike>;
/** How many filesystems to report; defaults to 4. */
maxDisks?: number;
cacheMs?: number; cacheMs?: number;
} }
@@ -120,6 +159,91 @@ export function cpuPercentBetween(prev: CpuTimes | null, next: CpuTimes): number
return Math.min(100, Math.max(0, Math.round(busy * 100))); return Math.min(100, Math.max(0, Math.round(busy * 100)));
} }
/** Linux `f_type` magics → a short label. Best effort: unknown magics stay unlabelled. */
const FS_MAGIC: Readonly<Record<number, string>> = {
0x01_02_19_94: "tmpfs",
0x2f_c1_2f_c1: "zfs",
0x41_50_46_53: "apfs",
0x4d_44: "vfat",
0x69_69: "nfs",
0x96_60: "iso9660",
0xef_53: "ext4",
0x20_11_ba_b0: "exfat",
0x53_46_54_4e: "ntfs",
0x58_46_53_42: "xfs",
0x73_71_73_68: "squashfs",
0x79_4c_76_30: "overlay",
0x91_23_68_3e: "btrfs",
0xf2_f5_20_10: "f2fs",
0xff_53_4d_42: "cifs",
};
/** Best-effort filesystem label from a `statfs.type` magic number. */
export function fsTypeFromMagic(magic: number | undefined): string | undefined {
if (magic === undefined || !Number.isFinite(magic)) return undefined;
return FS_MAGIC[magic];
}
export interface MountProbe {
/** Deepest existing ancestor of the candidate (what `statfs` may be called on). */
path: string;
/** Filesystem boundary above `path`; the user-facing label. */
mountPoint: string;
/** `st_dev` identity, stringified — the dedupe key. */
dev: string;
}
/**
* Resolve a candidate path to the filesystem that backs it.
*
* 1. Walk up until `stat` succeeds — `statfs` fails with `ENOENT` on a directory
* that does not exist yet (pi2d's state dir is created lazily), which used to
* null out the whole disk tile.
* 2. Keep walking up while the parent reports the same `st_dev`; the last dir
* that shares it is the mount point.
*
* Returns `null` when no ancestor exists (the path is on an unmounted tree).
*/
export async function probeMount(
candidate: string,
stat: (path: string) => Promise<StatLike>,
): Promise<MountProbe | null> {
let path = resolvePath(candidate);
let dev: string | null = null;
for (;;) {
try {
dev = String((await stat(path)).dev);
break;
} catch {
const parent = dirname(path);
if (parent === path) return null;
path = parent;
}
}
let mountPoint = path;
for (;;) {
const parent = dirname(mountPoint);
if (parent === mountPoint) break;
try {
if (String((await stat(parent)).dev) !== dev) break;
} catch {
break;
}
mountPoint = parent;
}
return { path, mountPoint, dev };
}
function describeError(path: string, err: unknown): string {
const code =
typeof err === "object" && err !== null && "code" in err
? String((err as { code?: unknown }).code)
: err instanceof Error
? err.message
: String(err);
return `${path}: ${code}`;
}
/** /**
* Derive disk usage from a statfs result. * Derive disk usage from a statfs result.
* Returns null if blocks is 0 (pseudo-fs like tmpfs without a block count). * Returns null if blocks is 0 (pseudo-fs like tmpfs without a block count).
@@ -144,16 +268,84 @@ export function createSysinfo(deps: SysinfoDeps = {}): SysinfoSampler {
const now = deps.now ?? Date.now; const now = deps.now ?? Date.now;
const cacheMs = deps.cacheMs ?? 1000; const cacheMs = deps.cacheMs ?? 1000;
const platform = deps.platform ?? process.platform; const platform = deps.platform ?? process.platform;
const diskPath = deps.diskPath ?? stateDir(); // `/` on macOS is the sealed read-only system volume, which reports ~100%
// used forever; the home volume is the honest "system disk" answer there.
const diskPath = deps.diskPath ?? (platform === "darwin" ? nodeOs.homedir() : platform === "win32" ? stateDir() : "/");
const maxDisks = Math.max(1, deps.maxDisks ?? 4);
const sessionsPath = deps.sessionsPath ?? sessionsRoot();
const extraDiskPaths = deps.diskPaths ?? (() => []);
// I/O callables — real by default, injectable for tests // I/O callables — real by default, injectable for tests
const readFile = deps.readFile ?? ((path: string) => nodeReadFile(path, "utf8")); const readFile = deps.readFile ?? ((path: string) => nodeReadFile(path, "utf8"));
const statfsImpl = deps.statfs ?? ((path: string) => nodeStatfs(path) as Promise<StatFsLike>); const statfsImpl = deps.statfs ?? ((path: string) => nodeStatfs(path) as Promise<StatFsLike>);
const statImpl = deps.stat ?? ((path: string) => nodeStat(path) as Promise<StatLike>);
const cpus = deps.cpus ?? (() => nodeOs.cpus()); const cpus = deps.cpus ?? (() => nodeOs.cpus());
const totalmem = deps.totalmem ?? (() => nodeOs.totalmem()); const totalmem = deps.totalmem ?? (() => nodeOs.totalmem());
const freemem = deps.freemem ?? (() => nodeOs.freemem()); const freemem = deps.freemem ?? (() => nodeOs.freemem());
const uptime = deps.uptime ?? (() => nodeOs.uptime());
const loadavg = deps.loadavg ?? (() => nodeOs.loadavg()); const loadavg = deps.loadavg ?? (() => nodeOs.loadavg());
/**
* Sample one row per distinct filesystem. Candidates are pi2d's own write
* targets (root, the pi session store, the visible workspace roots), never
* an enumeration of `/proc/mounts`: `statfs` on an unrelated, hung network
* mount would otherwise stall the whole sample.
*/
async function sampleDisks(): Promise<{ disks: DiskUsage[]; error?: string }> {
const extra = (() => {
try {
return extraDiskPaths();
} catch {
return [];
}
})();
const candidates = [diskPath, sessionsPath, ...extra]
.filter((path, index, all) => typeof path === "string" && path !== "" && all.indexOf(path) === index)
.slice(0, maxDisks * 2);
const probes = new Map<string, MountProbe>();
const failures: string[] = [];
for (const candidate of candidates) {
try {
const probe = await probeMount(candidate, statImpl);
if (probe === null) {
failures.push(`${candidate}: no existing ancestor`);
continue;
}
// Same `st_dev` ⇒ same filesystem ⇒ same row, whatever the path.
if (!probes.has(probe.dev)) probes.set(probe.dev, probe);
} catch (err) {
failures.push(describeError(candidate, err));
}
}
const disks: DiskUsage[] = [];
for (const probe of probes.values()) {
try {
const sf = await statfsImpl(probe.mountPoint);
const usage = diskFromStatfs(sf);
if (usage === null) {
failures.push(`${probe.mountPoint}: no block count`);
continue;
}
const fsType = fsTypeFromMagic(sf.type);
disks.push({
mountPoint: probe.mountPoint,
...(fsType === undefined ? {} : { fsType }),
...usage,
});
} catch (err) {
failures.push(describeError(probe.mountPoint, err));
}
}
// Worst first: the tile's headline number is the disk closest to full.
disks.sort((a, b) => b.percent - a.percent || b.totalBytes - a.totalBytes);
const capped = disks.slice(0, maxDisks);
if (capped.length > 0) return { disks: capped };
return { disks: [], error: failures[0] ?? "no filesystem could be sampled" };
}
let prevCpuTimes: CpuTimes | null = null; let prevCpuTimes: CpuTimes | null = null;
let cachedResult: SystemStats | null = null; let cachedResult: SystemStats | null = null;
let cachedAt = -Infinity; let cachedAt = -Infinity;
@@ -206,6 +398,17 @@ export function createSysinfo(deps: SysinfoDeps = {}): SysinfoSampler {
} }
} }
// ── Host uptime ──────────────────────────────────────────────
// The daemon's own process age lives on `/info.uptimeMs`; this is the
// figure a user reads as "how long has this box been up".
let hostUptimeSec: number | null = null;
try {
const raw = uptime();
if (Number.isFinite(raw) && raw >= 0) hostUptimeSec = Math.round(raw);
} catch {
hostUptimeSec = null;
}
// ── Memory ─────────────────────────────────────────────────── // ── Memory ───────────────────────────────────────────────────
let memTotalBytes: number; let memTotalBytes: number;
let memUsedBytes: number; let memUsedBytes: number;
@@ -245,33 +448,28 @@ export function createSysinfo(deps: SysinfoDeps = {}): SysinfoSampler {
: 0; : 0;
// ── Disk ───────────────────────────────────────────────────── // ── Disk ─────────────────────────────────────────────────────
let diskUsedBytes: number | null = null; const sampled = await sampleDisks();
let diskTotalBytes: number | null = null; const worst = sampled.disks[0];
let diskPercent: number | null = null; const diskUsedBytes = worst?.usedBytes ?? null;
try { const diskTotalBytes = worst?.totalBytes ?? null;
const sf = await statfsImpl(diskPath); const diskPercent = worst?.percent ?? null;
const result = diskFromStatfs(sf); const diskMount = worst?.mountPoint ?? diskPath;
if (result !== null) {
diskUsedBytes = result.usedBytes;
diskTotalBytes = result.totalBytes;
diskPercent = result.percent;
}
} catch {
// leave nulls
}
return { return {
sampledAt, sampledAt,
hostUptimeSec,
cpuPercent, cpuPercent,
cpuCores, cpuCores,
loadAvg: loadAvgResult, loadAvg: loadAvgResult,
memUsedBytes, memUsedBytes,
memTotalBytes, memTotalBytes,
memPercent, memPercent,
diskPath, diskPath: diskMount,
diskUsedBytes, diskUsedBytes,
diskTotalBytes, diskTotalBytes,
diskPercent, diskPercent,
disks: sampled.disks,
...(sampled.error === undefined ? {} : { diskError: sampled.error }),
}; };
} }
+17
View File
@@ -205,7 +205,10 @@ export function createApp(deps: AppDeps): Hono<Env> {
hostname: osHostname(), hostname: osHostname(),
os: `${osPlatform()} ${osRelease()}`, os: `${osPlatform()} ${osRelease()}`,
version: daemonVersion(), version: daemonVersion(),
// Process age of the daemon itself (`uptimeMs`), distinct from the host
// figure (`hostUptimeMs`) the status page shows as "uptime".
uptimeMs: Math.max(0, now() - startedAt), uptimeMs: Math.max(0, now() - startedAt),
...(typeof system?.hostUptimeSec === "number" ? { hostUptimeMs: system.hostUptimeSec * 1000 } : {}),
pid: process.pid, pid: process.pid,
port: config.port, port: config.port,
capabilities: ["ws", "sse", "devices", "attention"], capabilities: ["ws", "sse", "devices", "attention"],
@@ -328,6 +331,20 @@ export function createApp(deps: AppDeps): Hono<Env> {
return json(200, ack); return json(200, ack);
}); });
// Composer ↑ recall. Live-only by construction: the router reads an already
// connected instance and never calls `instances.ensure()`, so a recall can
// never spawn an nvim. An absent instance answers `{live:false,supported:false}`
// and an uncapable one `{live:true,supported:false}`, both with no entries.
app.get("/api/v1/workspaces/:id/prompt-history", async (c) => {
const workspaceId = c.req.param("id");
if (!workspaces.get(workspaceId)) throw DaemonError.notFound(`unknown workspace ${workspaceId}`);
const raw = c.req.query("limit");
// Absent or empty (a bare `?limit=`) lets the router apply its default.
const limit = raw === undefined || raw === "" ? undefined : Number(raw);
const result = await router.relayPromptHistory(workspaceId, limit);
return json(200, { v: 1, workspaceId, ...result });
});
app.get("/api/v1/models", async (c) => { app.get("/api/v1/models", async (c) => {
const workspaceId = c.req.query("workspaceId"); const workspaceId = c.req.query("workspaceId");
if (workspaceId) { if (workspaceId) {
+56
View File
@@ -13,6 +13,10 @@ import { DaemonError, toErrorPayload } from "./errors.js";
const DEDUPE_TTL_MS = 5 * 60 * 1000; const DEDUPE_TTL_MS = 5 * 60 * 1000;
/** Prompt-history read sizing: the composer recalls at most this many entries. */
const PROMPT_HISTORY_DEFAULT_LIMIT = 200;
const PROMPT_HISTORY_MAX_LIMIT = 500;
export interface RouterDeps { export interface RouterDeps {
auth: AuthStore; auth: AuthStore;
instances: InstanceManager; instances: InstanceManager;
@@ -54,6 +58,30 @@ function optionalString(params: Record<string, unknown>, key: string): string |
return typeof value === "string" && value.trim() !== "" ? value : undefined; return typeof value === "string" && value.trim() !== "" ? value : undefined;
} }
/** Clamp a caller-supplied prompt-history limit; garbage falls back to the default. */
function clampPromptHistoryLimit(raw: number | undefined): number {
if (typeof raw !== "number" || !Number.isFinite(raw)) return PROMPT_HISTORY_DEFAULT_LIMIT;
return Math.max(1, Math.min(PROMPT_HISTORY_MAX_LIMIT, Math.floor(raw)));
}
/**
* Keep only usable entries and trim to the newest `limit`.
*
* The plugin answers oldest-first, so the tail is the recent end; a missing or
* malformed `entries` payload degrades to an empty list rather than throwing.
*/
function normalizePromptHistoryEntries(raw: unknown, limit: number): string[] {
if (!Array.isArray(raw)) return [];
const entries = raw.filter((value): value is string => typeof value === "string" && value.trim() !== "");
return entries.slice(-limit);
}
export interface PromptHistoryResult {
live: boolean;
supported: boolean;
entries: string[];
}
export class CommandRouter { export class CommandRouter {
private readonly auth: AuthStore; private readonly auth: AuthStore;
private readonly instances: InstanceManager; private readonly instances: InstanceManager;
@@ -148,6 +176,34 @@ export class CommandRouter {
return this.relay(workspaceId, sessionId, method, params); return this.relay(workspaceId, sessionId, method, params);
} }
/**
* Live-only workspace read used by `GET /workspaces/:id/prompt-history`.
*
* Recall is a convenience, never a lifecycle event: this looks up an already
* connected instance and deliberately does **not** call `ensure()`, so pressing
* ↑ in the composer cannot boot an nvim. No connection answers
* `{live:false,supported:false}`, an instance that did not advertise
* `promptHistory` in its `hello` gets no command at all, and only a capable
* connection sees a relay (workspace-scoped: no `sessionId` on the envelope).
*/
async relayPromptHistory(workspaceId: string, limit?: number): Promise<PromptHistoryResult> {
if (typeof workspaceId !== "string" || workspaceId === "") {
throw DaemonError.badRequest("workspaceId is required");
}
const effectiveLimit = clampPromptHistoryLimit(limit);
const connection = this.instances.get(workspaceId);
if (!connection) return { live: false, supported: false, entries: [] };
if (!connection.capabilities.includes("promptHistory")) {
return { live: true, supported: false, entries: [] };
}
const ack = await connection.command({
id: `req-${randomUUID()}`,
method: "workspace.query",
params: { kind: "promptHistory", limit: effectiveLimit },
});
return { live: true, supported: true, entries: normalizePromptHistoryEntries(ack.entries, effectiveLimit) };
}
private async relay( private async relay(
workspaceId: string, workspaceId: string,
sessionId: string | undefined, sessionId: string | undefined,
+11 -3
View File
@@ -321,9 +321,10 @@ export type WorkspaceVisibilityReason = "hidden" | "ghost" | "temp" | "outside-r
/** /**
* One disk-projected session row for the cross-workspace recent-activity feed. * One disk-projected session row for the cross-workspace recent-activity feed.
* *
* This is file metadata only (header id/timestamp + mtime); the daemon never * This is file metadata plus an optional bounded display title (latest
* parses entries or owns session state (docs/protocol.md §3.1). Live names and * `session_info` name / first user message); the daemon never parses entries
* statuses are layered on by the client through `/workspaces/:id/sessions`. * into session state (docs/protocol.md §3.1). Live names and statuses are
* layered on by the client through `/workspaces/:id/sessions`.
*/ */
export interface RecentSessionInfo { export interface RecentSessionInfo {
sessionId: string; sessionId: string;
@@ -336,6 +337,13 @@ export interface RecentSessionInfo {
timestamp: number; timestamp: number;
/** File mtime, epoch ms — the recency sort key. */ /** File mtime, epoch ms — the recency sort key. */
modified: number; modified: number;
/**
* Latest `session_info.name` from the session file's bounded preview
* windows. Display metadata only; absent when the file has no name yet.
*/
name?: string;
/** First user message preview (flattened, ≤80 chars), when readable. */
firstMessage?: string;
} }
export type DaemonCommandMethod = export type DaemonCommandMethod =
+207 -4
View File
@@ -8,8 +8,12 @@
* and the separator), so the authoritative cwd is the first JSONL line: * and the separator), so the authoritative cwd is the first JSONL line:
* {"type":"session","version":3,"id":"…","timestamp":"…","cwd":"/abs/path"} * {"type":"session","version":3,"id":"…","timestamp":"…","cwd":"/abs/path"}
* *
* Scanning is header-only (one read of up to 64 KiB per directory) and cached * Workspace/session *listing* is header-only (one read of up to 64 KiB per
* per directory by (mtime, file count). The rest of a session file is never read. * directory) and cached per directory by (mtime, file count). `previewSession()`
* is the one opt-in exception: it reads a bounded head/tail window for a display
* title (latest `session_info.name` + first user message) so the recent-activity
* feed can label a session that has no live instance. It never parses entries
* into session state and is cached by (mtime, size).
*/ */
import { closeSync, openSync, readdirSync, readSync, statSync } from "node:fs"; import { closeSync, openSync, readdirSync, readSync, statSync } from "node:fs";
@@ -19,6 +23,30 @@ import { sessionsRoot, workspaceIdForCwd } from "../core/paths.js";
/** Maximum bytes read to obtain the first JSONL line. Headers are ~150 bytes. */ /** Maximum bytes read to obtain the first JSONL line. Headers are ~150 bytes. */
export const HEADER_READ_LIMIT = 64 * 1024; export const HEADER_READ_LIMIT = 64 * 1024;
/**
* Head window for a display title. The first user message and the auto-title
* `session_info` line both land in the first ~50 KiB of a real session (the
* system-prompt message is the bulk of it), so 128 KiB leaves generous room.
*/
export const PREVIEW_HEAD_LIMIT = 128 * 1024;
/** Tail window where a later `session_info.name` (rename / re-title) may live. */
export const PREVIEW_TAIL_LIMIT = 32 * 1024;
/** `firstMessage` is flattened and cut exactly like pi2.nvim's `history.parse`. */
export const PREVIEW_MESSAGE_CHARS = 80;
/** Bound the preview cache; a recent feed touches a few dozen files at most. */
const PREVIEW_CACHE_LIMIT = 512;
/** Bounded display metadata read from a session file. Never session state. */
export interface SessionPreview {
/** Latest non-empty `session_info.name`, when one is inside the windows. */
name?: string;
/** First user message, flattened to one line and cut to 80 characters. */
firstMessage?: string;
}
export interface DiscoveredWorkspace { export interface DiscoveredWorkspace {
workspaceId: string; workspaceId: string;
/** Authoritative cwd from the session header (not decoded from `dir`). */ /** Authoritative cwd from the session header (not decoded from `dir`). */
@@ -65,6 +93,13 @@ export interface Discovery {
discover(): DiscoveredWorkspace[]; discover(): DiscoveredWorkspace[];
/** Session files for a cwd, newest first (header-only, cheap). */ /** Session files for a cwd, newest first (header-only, cheap). */
listSessions(cwd: string, limit?: number): SessionFile[]; listSessions(cwd: string, limit?: number): SessionFile[];
/**
* Opt-in display title for one session file: the latest `session_info`
* name and the first user message. Reads at most `PREVIEW_HEAD_LIMIT` from
* the start plus `PREVIEW_TAIL_LIMIT` from the end, and caches by
* (mtime, size); `undefined` means the windows contain no usable title.
*/
previewSession(file: string, modified?: number): SessionPreview | undefined;
/** Drop one directory's cache entry, or the whole cache when omitted. */ /** Drop one directory's cache entry, or the whole cache when omitted. */
invalidate(dir?: string): void; invalidate(dir?: string): void;
/** The encoded directory used for a cwd, when it has been discovered. */ /** The encoded directory used for a cwd, when it has been discovered. */
@@ -91,6 +126,12 @@ interface SessionHeader {
timestamp?: string; timestamp?: string;
} }
interface PreviewCacheEntry {
mtimeMs: number;
size: number;
preview: SessionPreview | undefined;
}
export function isSessionDirName(name: string): boolean { export function isSessionDirName(name: string): boolean {
return name.length > 4 && name.startsWith("--") && name.endsWith("--"); return name.length > 4 && name.startsWith("--") && name.endsWith("--");
} }
@@ -99,6 +140,7 @@ class DiskDiscovery implements Discovery {
private readonly root: string; private readonly root: string;
private readonly logger: DiscoveryLogger | undefined; private readonly logger: DiscoveryLogger | undefined;
private readonly cache = new Map<string, CacheEntry>(); private readonly cache = new Map<string, CacheEntry>();
private readonly previews = new Map<string, PreviewCacheEntry>();
constructor(options: DiscoveryOptions = {}) { constructor(options: DiscoveryOptions = {}) {
this.root = options.root ?? sessionsRoot(); this.root = options.root ?? sessionsRoot();
@@ -156,9 +198,45 @@ class DiskDiscovery implements Discovery {
return sessions; return sessions;
} }
previewSession(file: string, modified?: number): SessionPreview | undefined {
let size: number;
let mtimeMs: number;
try {
const stat = statSync(file);
size = stat.size;
mtimeMs = modified ?? stat.mtimeMs;
} catch {
return undefined;
}
const cached = this.previews.get(file);
if (cached !== undefined && cached.mtimeMs === mtimeMs && cached.size === size) {
// Refresh insertion order so the LRU cap drops genuinely cold files.
this.previews.delete(file);
this.previews.set(file, cached);
return cached.preview;
}
const preview = readSessionPreview(file, size);
this.previews.set(file, { mtimeMs, size, preview });
if (this.previews.size > PREVIEW_CACHE_LIMIT) {
const oldest = this.previews.keys().next().value;
if (oldest !== undefined) this.previews.delete(oldest);
}
return preview;
}
invalidate(dir?: string): void { invalidate(dir?: string): void {
if (dir === undefined) this.cache.clear(); if (dir === undefined) {
else this.cache.delete(dir); this.cache.clear();
this.previews.clear();
} else {
this.cache.delete(dir);
const prefix = dir.endsWith("/") ? dir : `${dir}/`;
for (const file of this.previews.keys()) {
if (file.startsWith(prefix)) this.previews.delete(file);
}
}
} }
dirForCwd(cwd: string): string | undefined { dirForCwd(cwd: string): string | undefined {
@@ -304,6 +382,131 @@ function readSessionHeader(file: string): SessionHeader | undefined {
} }
} }
/**
* Bounded display-title projection for one session file.
*
* Reads the head window (first user message + any early `session_info` name)
* and, for longer files, the tail window (a later rename / auto-title). Lines
* are JSON-decoded only when a cheap substring prefilter hits, so multi-MB
* message or tool-output lines are never decoded. A partial trailing line (the
* window cut a line in half) fails the decode and is ignored; the tail window
* also drops its leading partial line before parsing.
*/
function readSessionPreview(file: string, size: number): SessionPreview | undefined {
let fd: number | undefined;
try {
fd = openSync(file, "r");
const headBytes = Math.min(size, PREVIEW_HEAD_LIMIT);
if (headBytes <= 0) return undefined;
const head = Buffer.allocUnsafe(headBytes);
const headRead = readSync(fd, head, 0, headBytes, 0);
if (headRead <= 0) return undefined;
const found = parsePreviewWindow(head.toString("utf8", 0, headRead), true);
let name = found.name;
let firstMessage = found.firstMessage;
if (size > headRead) {
const tailBytes = Math.min(size - headRead, PREVIEW_TAIL_LIMIT);
if (tailBytes > 0) {
const tail = Buffer.allocUnsafe(tailBytes);
const tailRead = readSync(fd, tail, 0, tailBytes, size - tailBytes);
if (tailRead > 0) {
const text = tail.toString("utf8", 0, tailRead);
// The first line is probably a partial one: drop it.
const newline = text.indexOf("\n");
const tailFound = parsePreviewWindow(newline >= 0 ? text.slice(newline + 1) : "", false);
if (tailFound.name !== undefined) name = tailFound.name;
}
}
}
if (name === undefined && firstMessage === undefined) return undefined;
return {
...(name === undefined ? {} : { name }),
...(firstMessage === undefined ? {} : { firstMessage }),
};
} catch {
return undefined;
} finally {
if (fd !== undefined) {
try {
closeSync(fd);
} catch {
// ignore
}
}
}
}
/** Parse one bounded window of JSONL lines into a display title. */
function parsePreviewWindow(text: string, findFirstMessage: boolean): SessionPreview {
let name: string | undefined;
let firstMessage: string | undefined;
for (const rawLine of text.split("\n")) {
const line = rawLine.endsWith("\r") ? rawLine.slice(0, -1) : rawLine;
if (line.length === 0) continue;
if (line.includes('"type":"session_info"')) {
const entry = parseJsonLine(line);
if (entry?.type === "session_info") {
const candidate = typeof entry.name === "string" ? entry.name.trim() : "";
if (candidate !== "") name = candidate;
}
}
if (findFirstMessage && firstMessage === undefined && line.includes('"type":"message"')) {
const entry = parseJsonLine(line);
const message = recordField(entry, "message");
if (entry?.type === "message" && message?.role === "user") {
const messageText = userMessageText(message.content);
if (messageText !== "") firstMessage = messageText;
}
}
}
return {
...(name === undefined ? {} : { name }),
...(firstMessage === undefined ? {} : { firstMessage }),
};
}
function parseJsonLine(line: string): Record<string, unknown> | undefined {
try {
const parsed: unknown = JSON.parse(line);
return parsed !== null && typeof parsed === "object" && !Array.isArray(parsed)
? (parsed as Record<string, unknown>)
: undefined;
} catch {
return undefined;
}
}
function recordField(value: Record<string, unknown> | undefined, key: string): Record<string, unknown> | undefined {
const field = value?.[key];
return field !== null && typeof field === "object" && !Array.isArray(field)
? (field as Record<string, unknown>)
: undefined;
}
/** First text part of a pi user message, flattened and cut for a row label. */
function userMessageText(content: unknown): string {
let text = "";
if (typeof content === "string") {
text = content;
} else if (Array.isArray(content)) {
for (const part of content) {
if (part !== null && typeof part === "object" && (part as { type?: unknown }).type === "text") {
const value = (part as { text?: unknown }).text;
if (typeof value === "string") {
text = value;
break;
}
}
}
}
return text.replace(/\s+/g, " ").trim().slice(0, PREVIEW_MESSAGE_CHARS);
}
/** `<YYYY-MM-DDTHH-MM-SS-mmmZ>_<id>.jsonl` → `{ id, timestamp }`. */ /** `<YYYY-MM-DDTHH-MM-SS-mmmZ>_<id>.jsonl` → `{ id, timestamp }`. */
export function parseSessionFileName(file: string): { id: string; timestamp: number } { export function parseSessionFileName(file: string): { id: string; timestamp: number } {
const name = basename(file).replace(/\.jsonl$/, ""); const name = basename(file).replace(/\.jsonl$/, "");
+10 -1
View File
@@ -266,6 +266,7 @@ class WorkspaceStore implements WorkspaceStoreHandle {
* stays bounded even on a workspace with a long history. Rows are deduped by * stays bounded even on a workspace with a long history. Rows are deduped by
* session id (two encoded directories can resolve to the same cwd) and sorted * session id (two encoded directories can resolve to the same cwd) and sorted
* by file mtime, then header timestamp, then id for a deterministic order. * by file mtime, then header timestamp, then id for a deterministic order.
* Only the returned rows get a bounded display-title preview.
*/ */
recentSessions(limit = 20): RecentSessionInfo[] { recentSessions(limit = 20): RecentSessionInfo[] {
const capped = clampLimit(limit); const capped = clampLimit(limit);
@@ -293,7 +294,15 @@ class WorkspaceStore implements WorkspaceStoreHandle {
b.timestamp - a.timestamp || b.timestamp - a.timestamp ||
a.sessionId.localeCompare(b.sessionId), a.sessionId.localeCompare(b.sessionId),
); );
return rows.slice(0, capped); const selected = rows.slice(0, capped);
// Enrich only the rows the caller will render: previews are bounded but
// per-file reads, so never pay for candidates that are sliced away.
for (const row of selected) {
const preview = this.discovery.previewSession(row.sessionFile, row.modified);
if (preview?.name !== undefined) row.name = preview.name;
if (preview?.firstMessage !== undefined) row.firstMessage = preview.firstMessage;
}
return selected;
} }
// ------------------------------------------------------------------ // ------------------------------------------------------------------
+367
View File
@@ -0,0 +1,367 @@
import { mkdirSync, symlinkSync, writeFileSync } from "node:fs";
import { join } from "node:path";
import { describe, expect, it } from "vitest";
import { main } from "../../src/cli/pi2.js";
import {
detectUninstallChannel,
formatUninstallStep,
installerBinSymlink,
planUninstall,
runUninstall,
uninstallNextSteps,
configEnvPath,
type UninstallChannel,
type UninstallOptions,
type UninstallStep,
} from "../../src/cli/uninstall.js";
import { CliError } from "../../src/cli/util.js";
import { removeDir, tempDir } from "./helpers.js";
const RUNTIME = "/home/u/run/pi2";
const DATA = "/home/u/.local/share/pi2";
const STATE = "/home/u/.local/state/pi2";
const CONFIG = "/home/u/.config/pi2/env";
const UNIT = "/home/u/.config/systemd/user/pi2.service";
const PREFIX = "/home/u/.local/lib/pi2d";
interface Harness {
options: UninstallOptions;
removed: string[];
removedFiles: string[];
lines: string[];
warnings: string[];
calls: string[];
}
/**
* A fake filesystem + fake systemd: `exists` answers from a set, removals are
* recorded, and every hook appends to `calls` so ordering is assertable.
*/
function harness(present: readonly string[], overrides: UninstallOptions = {}): Harness {
const files = new Set(present);
const removed: string[] = [];
const removedFiles: string[] = [];
const lines: string[] = [];
const warnings: string[] = [];
const calls: string[] = [];
const options: UninstallOptions = {
runtime: RUNTIME,
data: DATA,
state: STATE,
configEnv: CONFIG,
servicePaths: { homeDir: "/home/u", stateDir: STATE },
homeDir: "/home/u",
yes: true,
channel: { installer: "npm" },
print: (line) => lines.push(line),
warn: (line) => warnings.push(line),
exists: (path) => files.has(path),
removeDir: (path) => {
removed.push(path);
calls.push(`rmdir ${path}`);
},
removeFile: (path) => {
removedFiles.push(path);
calls.push(`rm ${path}`);
},
daemonPid: () => undefined,
serviceInstalled: (unitPath) => files.has(unitPath),
stopDaemon: async () => {
calls.push("stop daemon");
},
disableService: async () => {
calls.push("disable service");
},
removeService: (path) => {
removedFiles.push(path);
calls.push(`rm ${path}`);
},
...overrides,
};
return { options, removed, removedFiles, lines, warnings, calls };
}
describe("planUninstall", () => {
const base = {
runtime: RUNTIME,
data: DATA,
state: STATE,
configEnv: CONFIG,
serviceUnit: UNIT,
serviceInstalled: true,
daemonPid: 4242,
channel: { installer: "npm" } as UninstallChannel,
exists: () => true,
};
it("removes the service, the daemon and the runtime dir, and keeps the rest", () => {
const steps = planUninstall({ ...base, purge: false, purgeConfig: false });
expect(steps.map((step) => [step.target, step.remove])).toEqual([
["service", true],
["daemon", true],
["runtime", true],
["data", false],
["state", false],
["config", false],
]);
expect(steps[1]?.detail).toBe("pid 4242");
});
it("--purge adds data and state, --purge-config adds the env file", () => {
const steps = planUninstall({ ...base, purge: true, purgeConfig: true });
const removed = steps.filter((step) => step.remove).map((step) => step.target);
expect(removed).toEqual(["service", "daemon", "runtime", "data", "state", "config"]);
});
it("--keep-service keeps the unit but still cleans the state", () => {
const steps = planUninstall({ ...base, purge: false, purgeConfig: false, keepService: true });
expect(steps.find((step) => step.target === "service")?.remove).toBe(false);
expect(steps.find((step) => step.target === "runtime")?.remove).toBe(true);
});
it("only offers the install tree on the curl channel, and only with --purge", () => {
const curl: UninstallChannel = { installer: "curl", prefix: PREFIX };
expect(
planUninstall({ ...base, channel: curl, purge: false, purgeConfig: false }).some(
(step) => step.target === "install",
),
).toBe(false);
const purged = planUninstall({ ...base, channel: curl, purge: true, purgeConfig: false });
expect(purged.filter((step) => step.target === "install").map((step) => [step.paths, step.remove])).toEqual([
[[PREFIX], true],
]);
const kept = planUninstall({
...base,
channel: curl,
purge: true,
purgeConfig: false,
keepInstall: true,
});
expect(kept.find((step) => step.target === "install")?.remove).toBe(false);
});
it("skips paths that do not exist and steps with nothing to stop", () => {
const steps = planUninstall({
...base,
purge: true,
purgeConfig: true,
serviceInstalled: false,
daemonPid: undefined,
exists: (path) => path === DATA,
});
expect(steps.map((step) => [step.target, step.remove])).toEqual([["data", true]]);
});
});
describe("formatUninstallStep", () => {
const step: UninstallStep = { target: "data", paths: [DATA], remove: false };
it("names the flag that keeps a path", () => {
expect(formatUninstallStep(step)).toContain(`(${"--purge"})`);
});
it("does not suggest a flag on a step that is already removed", () => {
expect(formatUninstallStep({ ...step, remove: true })).not.toContain("--purge");
});
it("speaks in the future tense for a dry run", () => {
expect(formatUninstallStep({ ...step, remove: true }, true)).toContain("would remove");
});
});
describe("detectUninstallChannel", () => {
it("recognises the versioned curl layout", () => {
expect(detectUninstallChannel(`${PREFIX}/versions/0.1.9/bin/pi2`, true)).toEqual({
installer: "curl",
prefix: PREFIX,
});
});
it("falls back to the shape of the path for the package managers", () => {
expect(detectUninstallChannel("/usr/local/lib/node_modules/@yuez/pi2d/dist/cli/pi2.js", false).installer).toBe(
"npm",
);
expect(detectUninstallChannel("/opt/homebrew/Cellar/pi2d/0.1.9/bin/pi2", true).installer).toBe("brew");
expect(detectUninstallChannel("/usr/bin/pi2", true).installer).toBe("aur");
expect(detectUninstallChannel("/tmp/pi2", true).installer).toBe("unknown");
});
});
describe("configEnvPath", () => {
it("honours XDG_CONFIG_HOME", () => {
expect(configEnvPath({ XDG_CONFIG_HOME: "/x" }, "/home/u")).toBe("/x/pi2/env");
expect(configEnvPath({}, "/home/u")).toBe("/home/u/.config/pi2/env");
});
});
describe("runUninstall", () => {
it("dry-run prints the plan and touches nothing", async () => {
const h = harness([RUNTIME, DATA, STATE, CONFIG, UNIT], { dryRun: true });
expect(await runUninstall(h.options)).toBe(0);
expect(h.calls).toEqual([]);
expect(h.lines[0]).toContain("dry run");
expect(h.lines.join("\n")).toContain("--purge");
expect(h.lines.join("\n")).toContain("npm rm -g @yuez/pi2d");
});
it("stops the daemon, disables and removes the unit, then deletes the runtime dir", async () => {
const h = harness([RUNTIME, DATA, STATE, CONFIG, UNIT], { daemonPid: () => 4242 });
expect(await runUninstall(h.options)).toBe(0);
expect(h.calls).toEqual([
"disable service",
`rm ${UNIT}`,
"stop daemon",
`rmdir ${RUNTIME}`,
]);
expect(h.removed).not.toContain(DATA);
expect(h.lines.at(-1)).toContain("rm -rf");
});
it("--purge also deletes data and state; --purge-config the env file", async () => {
const h = harness([RUNTIME, DATA, STATE, CONFIG], { purge: true, purgeConfig: true, serviceInstalled: () => false });
expect(await runUninstall(h.options)).toBe(0);
expect(h.removed).toEqual([RUNTIME, DATA, STATE]);
expect(h.removedFiles).toEqual([CONFIG]);
expect(h.lines.join("\n")).not.toContain(`rm -rf ${DATA}`);
});
it("removes the curl install tree last, together with the bin symlink", async () => {
const dir = tempDir("pi2-uninstall-");
try {
const prefix = join(dir, "lib", "pi2d");
const binDir = join(prefix, "versions", "1.0.0", "bin");
mkdirSync(binDir, { recursive: true });
writeFileSync(join(binDir, "pi2"), "");
const home = join(dir, "home");
mkdirSync(join(home, ".local", "bin"), { recursive: true });
symlinkSync(join(binDir, "pi2"), join(home, ".local", "bin", "pi2"));
const h = harness([RUNTIME, prefix], {
homeDir: home,
purge: true,
channel: { installer: "curl", prefix },
});
expect(installerBinSymlink(prefix, home)).toBe(join(home, ".local", "bin", "pi2"));
expect(await runUninstall(h.options)).toBe(0);
expect(h.removed).toEqual([RUNTIME, prefix, join(home, ".local", "bin", "pi2")]);
expect(h.lines.join("\n")).not.toContain("install.sh");
} finally {
removeDir(dir);
}
});
it("keeps going when the service manager refuses, and reports the failure", async () => {
const h = harness([UNIT, RUNTIME], {
disableService: async () => {
throw new CliError("systemctl --user disable --now pi2.service failed: nope");
},
});
expect(await runUninstall(h.options)).toBe(0);
expect(h.warnings[0]).toContain("could not disable pi2.service");
expect(h.removed).toEqual([RUNTIME]);
});
it("counts a failed removal as a failure and exits 1", async () => {
const h = harness([RUNTIME, DATA], {
purge: true,
removeDir: (path) => {
if (path === DATA) throw new Error("EPERM");
},
});
expect(await runUninstall(h.options)).toBe(1);
expect(h.warnings[0]).toContain("could not remove");
expect(h.lines.join("\n")).toContain("1 failure(s)");
});
it("asks before removing and honours a no", async () => {
const h = harness([RUNTIME], { yes: false, isTTY: true, confirm: async () => false });
expect(await runUninstall(h.options)).toBe(1);
expect(h.calls).toEqual([]);
expect(h.lines.at(-1)).toContain("aborted");
});
it("refuses to run non-interactively without --yes", async () => {
const h = harness([RUNTIME], { yes: false, isTTY: false });
await expect(runUninstall(h.options)).rejects.toThrow("refusing to remove anything without confirmation");
expect(h.calls).toEqual([]);
});
it("succeeds when there is nothing left to remove", async () => {
const h = harness([]);
expect(await runUninstall(h.options)).toBe(0);
expect(h.lines.join("\n")).toContain("nothing to remove");
expect(h.calls).toEqual([]);
});
});
describe("uninstallNextSteps", () => {
it("prints the channel that owns the binaries", () => {
const steps: UninstallStep[] = [{ target: "runtime", paths: [RUNTIME], remove: true }];
expect(uninstallNextSteps(steps, { installer: "npm" }).join("\n")).toContain("npm rm -g @yuez/pi2d");
expect(uninstallNextSteps(steps, { installer: "brew" }).join("\n")).toContain("brew uninstall pi2d");
expect(uninstallNextSteps(steps, { installer: "curl" }).join("\n")).toContain("--uninstall");
});
it("skips the channel command once the install tree is gone", () => {
const steps: UninstallStep[] = [{ target: "install", paths: [PREFIX], remove: true }];
expect(uninstallNextSteps(steps, { installer: "curl" }).join("\n")).not.toContain("install.sh");
});
});
describe("pi2 uninstall (dispatch)", () => {
it("maps the flags onto the runner", async () => {
const seen: UninstallOptions[] = [];
const code = await main(["uninstall", "--dry-run", "--purge", "--purge-config", "--keep-service", "-y"], {
out: () => undefined,
runtime: "/tmp/pi2-run",
uninstall: async (options) => {
seen.push(options);
return 0;
},
});
expect(code).toBe(0);
expect(seen[0]).toMatchObject({
dryRun: true,
yes: true,
purge: true,
purgeConfig: true,
keepService: true,
runtime: "/tmp/pi2-run",
});
});
it("prints the command help", async () => {
const out: string[] = [];
const code = await main(["uninstall", "--help"], { out: (line) => out.push(line) });
expect(code).toBe(0);
expect(out.join("\n")).toContain("--purge-config");
});
it("rejects a positional argument with the command usage", async () => {
const err: string[] = [];
const code = await main(["uninstall", "everything"], { err: (line) => err.push(line) });
expect(code).toBe(2);
expect(err.join("\n")).toContain("unexpected argument");
expect(err.join("\n")).toContain("pi2 uninstall");
});
});
+161 -4
View File
@@ -4,13 +4,29 @@ import {
cpuTimesFromCpus, cpuTimesFromCpus,
createSysinfo, createSysinfo,
diskFromStatfs, diskFromStatfs,
fsTypeFromMagic,
parseMeminfo, parseMeminfo,
parseProcStat, parseProcStat,
probeMount,
} from "../../src/core/sysinfo.js"; } from "../../src/core/sysinfo.js";
const mem = (available = "MemAvailable: 512 kB") => `MemTotal: 1024 kB\n${available}\nMemFree: 128 kB\nBuffers: 64 kB\nCached: 128 kB\n`; const mem = (available = "MemAvailable: 512 kB") => `MemTotal: 1024 kB\n${available}\nMemFree: 128 kB\nBuffers: 64 kB\nCached: 128 kB\n`;
const cpus = (user: number, idle: number) => [{ times: { user, nice: 0, sys: 0, idle, irq: 0 } }]; const cpus = (user: number, idle: number) => [{ times: { user, nice: 0, sys: 0, idle, irq: 0 } }];
/** `path -> st_dev` fake: anything absent throws ENOENT, like a real stat. */
type FsTree = Record<string, number | bigint>;
function fakeStat(tree: FsTree) {
return async (path: string) => {
const dev = tree[path];
if (dev === undefined) throw Object.assign(new Error(`ENOENT: ${path}`), { code: "ENOENT" });
return { dev };
};
}
/** Every sampler call below injects `stat`+`statfs`, so no test touches the disk. */
const oneFs: FsTree = { "/": 1, "/pi/sessions": 1 };
describe("sysinfo", () => { describe("sysinfo", () => {
it("parses meminfo using MemAvailable and fallback fields", () => { it("parses meminfo using MemAvailable and fallback fields", () => {
expect(parseMeminfo(mem())).toEqual({ totalBytes: 1024 * 1024, availableBytes: 512 * 1024 }); expect(parseMeminfo(mem())).toEqual({ totalBytes: 1024 * 1024, availableBytes: 512 * 1024 });
@@ -49,6 +65,9 @@ describe("sysinfo", () => {
const result = await createSysinfo({ const result = await createSysinfo({
now: () => 1, now: () => 1,
platform: "darwin", platform: "darwin",
diskPath: "/",
sessionsPath: "/pi/sessions",
stat: fakeStat(oneFs),
cpus: () => cpus(10, 10), cpus: () => cpus(10, 10),
totalmem: () => Number.NaN, totalmem: () => Number.NaN,
freemem: () => Number.POSITIVE_INFINITY, freemem: () => Number.POSITIVE_INFINITY,
@@ -69,8 +88,13 @@ describe("sysinfo", () => {
now: () => clock, now: () => clock,
platform: "linux", platform: "linux",
diskPath: "/test", diskPath: "/test",
sessionsPath: "/pi/sessions",
// `/test` does not exist: the probe must land on the root filesystem
// instead of blanking the tile (the shipped bug).
stat: fakeStat(oneFs),
uptime: () => 4321.6,
readFile: async (path) => { reads++; return path === "/proc/stat" ? "cpu 10 0 0 10 0 0 0" : mem(); }, readFile: async (path) => { reads++; return path === "/proc/stat" ? "cpu 10 0 0 10 0 0 0" : mem(); },
statfs: async () => { stats++; return { bsize: 100, blocks: 10, bfree: 4 }; }, statfs: async () => { stats++; return { bsize: 100, blocks: 10, bfree: 4, type: 0xef53 }; },
cpus: () => cpus(10, 10), cpus: () => cpus(10, 10),
totalmem: () => 999, totalmem: () => 999,
freemem: () => 1, freemem: () => 1,
@@ -78,7 +102,21 @@ describe("sysinfo", () => {
cacheMs: 100, cacheMs: 100,
}); });
const first = await sampler.sample(); const first = await sampler.sample();
expect(first).toEqual({ sampledAt: 1000, cpuPercent: null, cpuCores: 1, loadAvg: [1.23, 2.35, 3.46], memUsedBytes: 512 * 1024, memTotalBytes: 1024 * 1024, memPercent: 50, diskPath: "/test", diskUsedBytes: 600, diskTotalBytes: 1000, diskPercent: 60 }); expect(first).toEqual({
sampledAt: 1000,
hostUptimeSec: 4322,
cpuPercent: null,
cpuCores: 1,
loadAvg: [1.23, 2.35, 3.46],
memUsedBytes: 512 * 1024,
memTotalBytes: 1024 * 1024,
memPercent: 50,
diskPath: "/",
diskUsedBytes: 600,
diskTotalBytes: 1000,
diskPercent: 60,
disks: [{ mountPoint: "/", fsType: "ext4", totalBytes: 1000, usedBytes: 600, percent: 60 }],
});
await sampler.sample(); await sampler.sample();
expect(reads).toBe(2); expect(reads).toBe(2);
expect(stats).toBe(1); expect(stats).toBe(1);
@@ -91,6 +129,9 @@ describe("sysinfo", () => {
it("resolves when total memory probing throws", async () => { it("resolves when total memory probing throws", async () => {
const sampler = createSysinfo({ const sampler = createSysinfo({
platform: "darwin", platform: "darwin",
diskPath: "/",
sessionsPath: "/pi/sessions",
stat: fakeStat(oneFs),
cpus: () => cpus(1, 1), cpus: () => cpus(1, 1),
totalmem: () => { throw new Error("totalmem unavailable"); }, totalmem: () => { throw new Error("totalmem unavailable"); },
freemem: () => 25, freemem: () => 25,
@@ -100,12 +141,48 @@ describe("sysinfo", () => {
await expect(sampler.sample()).resolves.toMatchObject({ memTotalBytes: 0, memUsedBytes: 0, memPercent: 0 }); await expect(sampler.sample()).resolves.toMatchObject({ memTotalBytes: 0, memUsedBytes: 0, memPercent: 0 });
}); });
it("falls back and resolves I/O failures with null CPU and disk", async () => { it("reports a host uptime independently of the daemon's own age", async () => {
const result = await createSysinfo({
platform: "linux",
diskPath: "/",
sessionsPath: "/pi/sessions",
stat: fakeStat(oneFs),
statfs: async () => ({ bsize: 100, blocks: 10, bfree: 4 }),
uptime: () => 5 * 86_400 + 3 * 3_600,
cpus: () => cpus(1, 1),
totalmem: () => 1,
freemem: () => 0,
loadavg: () => [0, 0, 0],
}).sample();
expect(result.hostUptimeSec).toBe(442_800);
});
it("nulls a host uptime the OS cannot report", async () => {
const base = {
platform: "linux" as const,
diskPath: "/",
sessionsPath: "/pi/sessions",
stat: fakeStat(oneFs),
statfs: async () => ({ bsize: 100, blocks: 10, bfree: 4 }),
cpus: () => cpus(1, 1),
totalmem: () => 1,
freemem: () => 0,
loadavg: () => [0, 0, 0],
};
for (const uptime of [() => Number.NaN, () => -1, () => Number.POSITIVE_INFINITY, () => { throw new Error("no uptime"); }]) {
await expect(createSysinfo({ ...base, uptime }).sample()).resolves.toMatchObject({ hostUptimeSec: null });
}
});
it("reports a diskError instead of silent nulls when nothing can be sampled", async () => {
const result = await createSysinfo({ const result = await createSysinfo({
now: () => 1, now: () => 1,
platform: "linux", platform: "linux",
diskPath: "/test",
sessionsPath: "/pi/sessions",
readFile: async () => { throw new Error("read"); }, readFile: async () => { throw new Error("read"); },
statfs: async () => { throw new Error("statfs"); }, stat: fakeStat(oneFs),
statfs: async () => { throw Object.assign(new Error("statfs"), { code: "ENOENT" }); },
cpus: () => { throw new Error("cpu"); }, cpus: () => { throw new Error("cpu"); },
totalmem: () => 0, totalmem: () => 0,
freemem: () => 0, freemem: () => 0,
@@ -116,7 +193,87 @@ describe("sysinfo", () => {
expect(result.diskUsedBytes).toBeNull(); expect(result.diskUsedBytes).toBeNull();
expect(result.diskTotalBytes).toBeNull(); expect(result.diskTotalBytes).toBeNull();
expect(result.diskPercent).toBeNull(); expect(result.diskPercent).toBeNull();
expect(result.disks).toEqual([]);
expect(result.diskError).toBe("/: ENOENT");
expect(result.diskPath).toBe("/test");
expect(result.memTotalBytes).toBe(0); expect(result.memTotalBytes).toBe(0);
expect(result.memUsedBytes).toBe(0); expect(result.memUsedBytes).toBe(0);
}); });
}); });
describe("disk probes", () => {
it("walks up to the nearest existing ancestor", async () => {
const tree: FsTree = { "/": 10, "/home": 20, "/home/u": 20 };
await expect(probeMount("/home/u/project", fakeStat(tree))).resolves.toEqual({
path: "/home/u",
mountPoint: "/home",
dev: "20",
});
// Nothing exists → null, not a throw.
await expect(probeMount("/nope", fakeStat({}))).resolves.toBeNull();
});
it("stops at the filesystem boundary, not at the root", async () => {
const tree: FsTree = { "/": 1, "/mnt": 1, "/mnt/data": 2, "/mnt/data/ws": 2 };
await expect(probeMount("/mnt/data/ws/x", fakeStat(tree))).resolves.toMatchObject({ mountPoint: "/mnt/data" });
await expect(probeMount("/mnt/data/ws/x", fakeStat(tree))).resolves.toMatchObject({ dev: "2" });
await expect(probeMount("/usr/lib", fakeStat(tree))).resolves.toMatchObject({ mountPoint: "/" });
});
it("labels known filesystem magics only", () => {
expect(fsTypeFromMagic(0xef53)).toBe("ext4");
expect(fsTypeFromMagic(0x9123683e)).toBe("btrfs");
expect(fsTypeFromMagic(0xdeadbeef)).toBeUndefined();
expect(fsTypeFromMagic(undefined)).toBeUndefined();
expect(fsTypeFromMagic(Number.NaN)).toBeUndefined();
});
it("dedupes by st_dev and reports the most constrained disk first", async () => {
const tree: FsTree = { "/": 1, "/pi/sessions": 1, "/home": 2, "/mnt/data": 3 };
const seen: string[] = [];
const result = await createSysinfo({
platform: "linux",
diskPath: "/",
sessionsPath: "/pi/sessions",
// Three workspace roots, two of them on the same filesystem as /home.
diskPaths: () => ["/home/a/one", "/home/a/two", "/mnt/data/ws"],
stat: fakeStat(tree),
statfs: async (path) => {
seen.push(path);
const freeBlocks = path === "/" ? 40 : path === "/home" ? 5 : 75;
return { bsize: 100, blocks: 100, bfree: freeBlocks, type: 0xef53 };
},
cpus: () => cpus(1, 1),
totalmem: () => 1,
freemem: () => 0,
loadavg: () => [0, 0, 0],
}).sample();
// One statfs per distinct filesystem: /home/a/one and /home/a/two collapsed.
expect(seen.sort()).toEqual(["/", "/home", "/mnt/data"]);
expect(result.disks.map((disk) => disk.mountPoint)).toEqual(["/home", "/", "/mnt/data"]);
expect(result.disks.map((disk) => disk.percent)).toEqual([95, 60, 25]);
// Legacy scalars alias the worst row.
expect(result.diskPath).toBe("/home");
expect(result.diskPercent).toBe(95);
expect(result.diskError).toBeUndefined();
});
it("caps the filesystem list", async () => {
const tree: FsTree = { "/": 1, "/pi/sessions": 1 };
for (let i = 0; i < 6; i += 1) tree[`/vol${i}`] = 10 + i;
const result = await createSysinfo({
platform: "linux",
diskPath: "/",
sessionsPath: "/pi/sessions",
diskPaths: () => [0, 1, 2, 3, 4, 5].map((i) => `/vol${i}/ws`),
stat: fakeStat(tree),
statfs: async () => ({ bsize: 100, blocks: 100, bfree: 5000 }),
cpus: () => cpus(1, 1),
totalmem: () => 1,
freemem: () => 0,
loadavg: () => [0, 0, 0],
}).sample();
expect(result.disks).toHaveLength(4);
});
});
+2
View File
@@ -31,6 +31,8 @@ export class FakeConnection implements PluginConnection {
readonly hasUI = true; readonly hasUI = true;
readonly listenAddr: string | null = null; readonly listenAddr: string | null = null;
readonly pluginVersion = "test-1.0.0"; readonly pluginVersion = "test-1.0.0";
/** Writable so a test can model a plugin that predates a capability. */
capabilities: string[] = ["promptHistory"];
subscribed = new Set<string>(); subscribed = new Set<string>();
snapshots = new Map<string, SessionState>(); snapshots = new Map<string, SessionState>();
+5
View File
@@ -35,6 +35,8 @@ export function testConfig(overrides: Partial<Config> = {}): Config {
/** Deterministic fake sampler returned when no override is provided. */ /** Deterministic fake sampler returned when no override is provided. */
export const FAKE_SYSTEM_STATS: SystemStats = { export const FAKE_SYSTEM_STATS: SystemStats = {
sampledAt: 1_700_000_000_000, sampledAt: 1_700_000_000_000,
// 5 days up, so the status tile and the daemon card differ on purpose.
hostUptimeSec: 432_000,
cpuPercent: 42, cpuPercent: 42,
cpuCores: 4, cpuCores: 4,
loadAvg: [1.5, 1.2, 0.9], loadAvg: [1.5, 1.2, 0.9],
@@ -45,6 +47,9 @@ export const FAKE_SYSTEM_STATS: SystemStats = {
diskUsedBytes: 50 * 1024 ** 3, diskUsedBytes: 50 * 1024 ** 3,
diskTotalBytes: 200 * 1024 ** 3, diskTotalBytes: 200 * 1024 ** 3,
diskPercent: 25, diskPercent: 25,
disks: [
{ mountPoint: "/tmp/pi2-test", fsType: "ext4", usedBytes: 50 * 1024 ** 3, totalBytes: 200 * 1024 ** 3, percent: 25 },
],
}; };
export function makeFakeSysinfoSampler(stats: Partial<SystemStats> = {}): SysinfoSampler { export function makeFakeSysinfoSampler(stats: Partial<SystemStats> = {}): SysinfoSampler {
+121 -1
View File
@@ -1,7 +1,7 @@
import { afterEach, beforeEach, describe, expect, it } from "vitest"; import { afterEach, beforeEach, describe, expect, it } from "vitest";
import * as os from "node:os"; import * as os from "node:os";
import { makeSessionState, makeWorkspaceInfo } from "./fakes.js"; import { makeSessionState, makeWorkspaceInfo } from "./fakes.js";
import { createHarness, TEST_LIMITS, type Harness } from "./harness.js"; import { createHarness, makeFakeSysinfoSampler, TEST_LIMITS, type Harness } from "./harness.js";
import { DaemonError } from "../../src/daemon/errors.js"; import { DaemonError } from "../../src/daemon/errors.js";
import { ERROR_CODES } from "../../src/protocol/errors.js"; import { ERROR_CODES } from "../../src/protocol/errors.js";
import { WorkspaceError } from "../../src/workspaces/errors.js"; import { WorkspaceError } from "../../src/workspaces/errors.js";
@@ -281,6 +281,96 @@ describe("HTTP API", () => {
); );
}); });
it("relays prompt history to a capable live instance without a session id", async () => {
conn.commandHandler = async (call) => {
if (call.method === "workspace.query" && call.params?.kind === "promptHistory") {
return { seq: 1, disposition: "started", entries: ["oldest", "newest"] } as never;
}
return { seq: 1, disposition: "started" };
};
const res = await fetch(`${h.url}/api/v1/workspaces/ws-1/prompt-history?limit=50`, authed());
expect(res.status).toBe(200);
expect(await res.json()).toEqual({
v: 1,
workspaceId: "ws-1",
live: true,
supported: true,
entries: ["oldest", "newest"],
});
const call = conn.commands.find((c) => c.params?.kind === "promptHistory");
expect(call?.method).toBe("workspace.query");
expect(call?.params).toEqual({ kind: "promptHistory", limit: 50 });
// Workspace-scoped: the read is not about one session.
expect(call).not.toHaveProperty("sessionId");
expect(h.instances.ensureCalls).toEqual([]);
});
it("answers empty prompt history without spawning an instance", async () => {
// No connection at all: the read must not call `instances.ensure()`.
h.instances.instances.delete("ws-1");
h.instances.states.delete("ws-1");
const res = await fetch(`${h.url}/api/v1/workspaces/ws-1/prompt-history`, authed());
expect(res.status).toBe(200);
expect(await res.json()).toEqual({ v: 1, workspaceId: "ws-1", live: false, supported: false, entries: [] });
expect(h.instances.ensureCalls).toEqual([]);
expect(conn.commands).toHaveLength(0);
});
it("skips the relay for a live instance without the promptHistory capability", async () => {
conn.capabilities = ["snapshot", "attention"];
const res = await fetch(`${h.url}/api/v1/workspaces/ws-1/prompt-history`, authed());
expect(res.status).toBe(200);
expect(await res.json()).toEqual({ v: 1, workspaceId: "ws-1", live: true, supported: false, entries: [] });
expect(conn.commands).toHaveLength(0);
expect(h.instances.ensureCalls).toEqual([]);
});
it("404s prompt history for an unknown workspace", async () => {
const res = await fetch(`${h.url}/api/v1/workspaces/ws-nope/prompt-history`, authed());
expect(res.status).toBe(404);
expect(((await res.json()) as { code: string }).code).toBe(ERROR_CODES.NOT_FOUND);
expect(conn.commands).toHaveLength(0);
});
it("clamps the prompt-history limit and keeps the newest entries", async () => {
const all = Array.from({ length: 600 }, (_, i) => `e${i}`);
conn.commandHandler = async () => ({ seq: 1, disposition: "started", entries: all }) as never;
const res = await fetch(`${h.url}/api/v1/workspaces/ws-1/prompt-history?limit=9999`, authed());
expect(res.status).toBe(200);
const body = (await res.json()) as { entries: string[] };
expect(conn.commands[0]?.params).toEqual({ kind: "promptHistory", limit: 500 });
expect(body.entries).toHaveLength(500);
// Oldest-first on the wire, so the tail is the recent end.
expect(body.entries[0]).toBe("e100");
expect(body.entries.at(-1)).toBe("e599");
// A garbage limit is ignored and the documented default applies.
conn.commands = [];
await fetch(`${h.url}/api/v1/workspaces/ws-1/prompt-history?limit=lots`, authed());
expect(conn.commands[0]?.params).toEqual({ kind: "promptHistory", limit: 200 });
});
it("normalizes a malformed prompt-history ack", async () => {
conn.commandHandler = async () =>
({ seq: 1, disposition: "started", entries: ["keep", 7, null, "", " ", "also"] }) as never;
const res = await fetch(`${h.url}/api/v1/workspaces/ws-1/prompt-history`, authed());
expect(res.status).toBe(200);
expect(((await res.json()) as { entries: string[] }).entries).toEqual(["keep", "also"]);
// A missing `entries` degrades to an empty list, never an error.
conn.commandHandler = async () => ({ seq: 1, disposition: "started" });
const bare = await fetch(`${h.url}/api/v1/workspaces/ws-1/prompt-history`, authed());
expect(bare.status).toBe(200);
expect(((await bare.json()) as { entries: string[] }).entries).toEqual([]);
});
it("serves the disk-projected recent-session feed for the activity column", async () => { it("serves the disk-projected recent-session feed for the activity column", async () => {
h.workspaces.recentSessionRows = [ h.workspaces.recentSessionRows = [
{ {
@@ -483,9 +573,39 @@ describe("HTTP API", () => {
cpu: 42, cpu: 42,
mem: 25, mem: 25,
disk: 25, disk: 25,
// Host uptime is additive and independent of `uptimeMs` (process age).
hostUptimeMs: 432_000_000,
})); }));
}); });
it("relays the per-filesystem disk list on resources", async () => {
const custom = await createHarness({
sysinfo: makeFakeSysinfoSampler({
disks: [
{ mountPoint: "/home", fsType: "btrfs", usedBytes: 950, totalBytes: 1000, percent: 95 },
{ mountPoint: "/", fsType: "ext4", usedBytes: 500, totalBytes: 1000, percent: 50 },
],
diskPath: "/home",
diskPercent: 95,
}),
});
try {
const response = await fetch(`${custom.url}/api/v1/resources`, {
headers: { Authorization: `Bearer ${custom.createToken()}` },
});
expect(response.status).toBe(200);
const system = (await response.json()).system;
expect(system.disks).toEqual([
{ mountPoint: "/home", fsType: "btrfs", usedBytes: 950, totalBytes: 1000, percent: 95 },
{ mountPoint: "/", fsType: "ext4", usedBytes: 500, totalBytes: 1000, percent: 50 },
]);
// The /info scalar stays the worst row, so old clients keep working.
expect(system.diskPercent).toBe(95);
} finally {
await custom.cleanup();
}
});
it("resolves bare models without spawning when no instance is ready", async () => { it("resolves bare models without spawning when no instance is ready", async () => {
const bare = await createHarness(); const bare = await createHarness();
try { try {
+79
View File
@@ -267,4 +267,83 @@ describe("workspace disk discovery", () => {
discovery.invalidate(); discovery.invalidate();
expect(discovery.discover()).toEqual([]); expect(discovery.discover()).toEqual([]);
}); });
describe("display-title preview", () => {
function titleFile(body: string): { dir: string; file: string } {
const dir = writeSessionDir(root, encodedDirName(sandbox), [
{ name: "2026-10-10T06-40-33-032Z_title.jsonl", cwd: sandbox, id: "title", body },
]);
return { dir, file: join(dir, "2026-10-10T06-40-33-032Z_title.jsonl") };
}
it("prefers the latest session_info name and falls back to the first user message", () => {
const { file } = titleFile(
[
JSON.stringify({ type: "session_info", name: "First name" }),
JSON.stringify({
type: "message",
message: { role: "user", content: [{ type: "text", text: "hello\n world from me" }] },
}),
JSON.stringify({ type: "session_info", name: "Renamed session" }),
].join("\n") + "\n",
);
const discovery = createDiscovery({ root });
// Listing stays header-only: no preview work on the hot path.
expect(discovery.listSessions(sandbox)[0]?.firstMessage).toBeUndefined();
expect(discovery.previewSession(file)).toEqual({
name: "Renamed session",
firstMessage: "hello world from me",
});
});
it("supports a plain-string user message and ignores assistant turns", () => {
const { file } = titleFile(
[
JSON.stringify({ type: "message", message: { role: "assistant", content: "not me" } }),
JSON.stringify({ type: "message", message: { role: "user", content: "plain string prompt" } }),
].join("\n") + "\n",
);
expect(createDiscovery({ root }).previewSession(file)).toEqual({ firstMessage: "plain string prompt" });
});
it("finds a name written past the head window in the tail window", () => {
const filler = `{"type":"note","data":"${"x".repeat(200 * 1024)}"}`;
const { file } = titleFile(
[
JSON.stringify({ type: "message", message: { role: "user", content: "start here" } }),
filler,
JSON.stringify({ type: "session_info", name: "Late name" }),
].join("\n") + "\n",
);
expect(createDiscovery({ root }).previewSession(file)).toEqual({
name: "Late name",
firstMessage: "start here",
});
});
it("caches by (mtime, size) and refreshes on invalidate()", () => {
const header = `${sessionHeader(sandbox, "title")}\n`;
const { file } = titleFile(`${JSON.stringify({ type: "session_info", name: "Cached" })}\n`);
const modified = statSync(file).mtimeMs;
const discovery = createDiscovery({ root });
expect(discovery.previewSession(file, modified)).toEqual({ name: "Cached" });
// Same size, deliberately reused recorded mtime: a cache hit.
writeFileSync(file, `${header}${JSON.stringify({ type: "session_info", name: "Edited" })}\n`);
expect(discovery.previewSession(file, modified)).toEqual({ name: "Cached" });
discovery.invalidate();
expect(discovery.previewSession(file, modified)).toEqual({ name: "Edited" });
});
it("returns undefined for a file with no readable title", () => {
const { file } = titleFile("garbage that is not json\n");
const discovery = createDiscovery({ root });
expect(discovery.previewSession(file)).toBeUndefined();
expect(discovery.previewSession(join(sandbox, "missing.jsonl"))).toBeUndefined();
});
});
}); });
+3
View File
@@ -156,6 +156,9 @@ describe("workspace store", () => {
timestamp: Date.parse("2026-10-13T06:40:33.032Z"), timestamp: Date.parse("2026-10-13T06:40:33.032Z"),
modified: Date.parse("2026-10-13T06:40:33.032Z"), modified: Date.parse("2026-10-13T06:40:33.032Z"),
sessionFile: expect.stringContaining("g1"), sessionFile: expect.stringContaining("g1"),
// The helper writes a user message "hi": the disk preview labels
// the row that has no live instance.
firstMessage: "hi",
}); });
// The default (no limit) still returns every discovered session, and an // The default (no limit) still returns every discovered session, and an
// out-of-range limit is clamped instead of exploding the header scan. // out-of-range limit is clamped instead of exploding the header scan.
+130
View File
@@ -0,0 +1,130 @@
import type { SessionState } from "@/lib/protocol";
/**
* Durable acknowledgements for the session-list notification dot.
*
* `flags.done` / `flags.error` are **unread markers**: the plugin raises them for
* a session the user is not looking at and clears them on nvim's TabEnter. The
* browser's TabEnter is `useSessionsStore.markSeen`, which used to clear the
* flags in the in-memory store only — so the next snapshot (a page reload, or a
* reconnect's resync) replayed `done: true` and the green blink came back for a
* notification the user had already seen. A fresh page load has no memory, but
* the plugin's flag still stands, so the dot looked stuck on "unread".
*
* The acknowledgement is therefore persisted (localStorage, per browser) under
* the *occurrence* it was given for: the id of the transcript's newest entry.
* The notification is the same one while the transcript still ends on that
* entry; the next completed turn appends entries, so the token changes and the
* new notification blinks again. This stays a client-side view concern — the
* wire, the reducer and `fixtures/` are untouched.
*/
export const SEEN_STORAGE_KEY = "pi2-seen-sessions";
/** Bound the ledger; a browser sees a few dozen sessions, not thousands. */
const SEEN_LIMIT = 200;
type Ledger = Record<string, string>;
/**
* Identity of the notification occurrence: the newest transcript entry.
*
* `undefined` when the state carries no entries (a REST list row before any
* snapshot). Such a session cannot be acknowledged durably — recording an empty
* token would swallow every future notification — so the caller keeps the
* in-memory-only behaviour.
*/
export function occurrenceToken(session: Pick<SessionState, "entries">): string | undefined {
const last = session.entries[session.entries.length - 1];
return last === undefined || last.id === "" ? undefined : last.id;
}
function storage(): Storage | undefined {
try {
return typeof localStorage === "undefined" ? undefined : localStorage;
} catch {
// Accessing `localStorage` can throw (Safari private mode, blocked cookies).
return undefined;
}
}
function read(): Ledger {
const store = storage();
if (store === undefined) return {};
try {
const raw = store.getItem(SEEN_STORAGE_KEY);
const parsed: unknown = raw === null ? null : JSON.parse(raw);
if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) return {};
const ledger: Ledger = {};
for (const [sessionId, token] of Object.entries(parsed as Record<string, unknown>)) {
if (typeof token === "string" && token !== "") ledger[sessionId] = token;
}
return ledger;
} catch {
return {};
}
}
function write(ledger: Ledger): void {
const store = storage();
if (store === undefined) return;
try {
// Insertion order is the LRU: drop the oldest keys past the cap.
const ids = Object.keys(ledger);
if (ids.length > SEEN_LIMIT) {
const trimmed: Ledger = {};
for (const id of ids.slice(ids.length - SEEN_LIMIT)) {
const token = ledger[id];
if (token !== undefined) trimmed[id] = token;
}
store.setItem(SEEN_STORAGE_KEY, JSON.stringify(trimmed));
return;
}
store.setItem(SEEN_STORAGE_KEY, JSON.stringify(ledger));
} catch {
// Quota or private mode: the in-memory store still clears the flag.
}
}
/** Record that the user has seen this session's notification. */
export function acknowledge(session: Pick<SessionState, "sessionId" | "entries">): void {
const token = occurrenceToken(session);
if (token === undefined) return;
const ledger = read();
// Re-insert so the entry moves to the LRU tail.
delete ledger[session.sessionId];
ledger[session.sessionId] = token;
write(ledger);
}
/** The session is gone: its ledger row is dead weight. */
export function forget(sessionId: string): void {
const ledger = read();
if (!(sessionId in ledger)) return;
delete ledger[sessionId];
write(ledger);
}
/** `tmp-N` → real id migration: the acknowledgement follows the session. */
export function move(from: string, to: string): void {
if (from === to) return;
const ledger = read();
const token = ledger[from];
if (token === undefined) return;
delete ledger[from];
ledger[to] = token;
write(ledger);
}
/**
* Clear a notification the user has already acknowledged for this occurrence.
* A replay of the same `done`/`error` (snapshot, reconnect, reload) therefore
* cannot resurrect the blink; a new completion appends an entry first, so its
* token differs and it is left alone.
*/
export function suppressAcknowledged(session: SessionState): SessionState {
if (!session.flags.done && !session.flags.error) return session;
const token = occurrenceToken(session);
if (token === undefined) return session;
if (read()[session.sessionId] !== token) return session;
return { ...session, flags: { ...session.flags, done: false, error: false } };
}
+107 -6
View File
@@ -1,5 +1,5 @@
import type { ModelRef, SessionState, ThinkingLevel } from "@protocol/types"; import type { ModelRef, SessionState, ThinkingLevel } from "@protocol/types";
import { useEffect, useLayoutEffect, useRef, useState } from "react"; import { useEffect, useLayoutEffect, useMemo, useRef, useState, type KeyboardEvent } from "react";
import { useTranslation } from "react-i18next"; import { useTranslation } from "react-i18next";
import { Icon } from "@/components/icons"; import { Icon } from "@/components/icons";
@@ -13,6 +13,7 @@ import { promptImage, type PromptImage, type PromptMode } from "./commands";
import type { ModelGroup } from "./data"; import type { ModelGroup } from "./data";
import { withCurrentModel } from "./data"; import { withCurrentModel } from "./data";
import { THINKING_LEVELS } from "./format"; import { THINKING_LEVELS } from "./format";
import { historyScope, localPromptHistorySource, PromptHistoryNav, type PromptHistorySource } from "./prompt-history";
import type { Attachment } from "./store"; import type { Attachment } from "./store";
export interface ComposerProps { export interface ComposerProps {
@@ -42,6 +43,13 @@ export interface ComposerProps {
queuedCount?: number; queuedCount?: number;
onSetModel: (model: ModelRef) => void; onSetModel: (model: ModelRef) => void;
onSetThinking: (level: ThinkingLevel) => void; onSetThinking: (level: ThinkingLevel) => void;
/**
* Where ↑/↓ recall reads from and where a send is recorded. `pages/chat.tsx`
* passes the plugin-backed feed (`usePromptHistory`) so nvim and the browser
* share one archive; without it the composer falls back to the browser-local
* mirror for this session's workspace.
*/
history?: PromptHistorySource;
disabled?: boolean; disabled?: boolean;
className?: string; className?: string;
} }
@@ -67,6 +75,7 @@ export function Composer({
queuedCount, queuedCount,
onSetModel, onSetModel,
onSetThinking, onSetThinking,
history,
disabled = false, disabled = false,
className, className,
}: ComposerProps) { }: ComposerProps) {
@@ -78,6 +87,21 @@ export function Composer({
const textareaRef = useRef<HTMLTextAreaElement | null>(null); const textareaRef = useRef<HTMLTextAreaElement | null>(null);
const fileRef = useRef<HTMLInputElement | null>(null); const fileRef = useRef<HTMLInputElement | null>(null);
/**
* Prompt recall (↑/↓) — see `prompt-history.ts`. The entries come from the
* injected feed (the plugin relay, or the browser mirror as fallback); the
* cursor is this composer's own, and is rebuilt when the source changes so a
* session switch or a lost plugin never carries a stranger's position over.
*/
const fallbackSource = useMemo(
() => localPromptHistorySource(historyScope(session?.workspaceId)),
[session?.workspaceId],
);
const source = history ?? fallbackSource;
const navRef = useRef<{ source: PromptHistorySource; nav: PromptHistoryNav } | null>(null);
/** Set by a recall so the layout effect can park the caret after the entry. */
const caretToEnd = useRef(false);
const enabled = Boolean(session) && connected && !disabled; const enabled = Boolean(session) && connected && !disabled;
const busy = session ? session.status === "busy" || session.status === "compacting" : false; const busy = session ? session.status === "busy" || session.status === "compacting" : false;
const queue = session?.queue ?? []; const queue = session?.queue ?? [];
@@ -104,6 +128,13 @@ export function Composer({
const max = 5 * 24; const max = 5 * 24;
element.style.height = `${Math.min(element.scrollHeight, max)}px`; element.style.height = `${Math.min(element.scrollHeight, max)}px`;
element.style.overflowY = element.scrollHeight > max ? "auto" : "hidden"; element.style.overflowY = element.scrollHeight > max ? "auto" : "hidden";
if (caretToEnd.current) {
// A recall replaced the whole value: keep typing after the entry
// instead of wherever the caret happened to be in the old draft.
caretToEnd.current = false;
const end = element.value.length;
element.setSelectionRange(end, end);
}
}, [text]); }, [text]);
useEffect(() => { useEffect(() => {
@@ -111,12 +142,81 @@ export function Composer({
textareaRef.current?.focus({ preventScroll: true }); textareaRef.current?.focus({ preventScroll: true });
}, [enabled]); }, [enabled]);
/** This composer's recall cursor, rebuilt when the source changes identity. */
function historyNav(): PromptHistoryNav {
if (navRef.current === null || navRef.current.source !== source) {
navRef.current = { source, nav: new PromptHistoryNav(source) };
}
return navRef.current.nav;
}
/** Replace the draft with an archived prompt (or the stashed draft). */
function recall(direction: "prev" | "next"): boolean {
const nav = historyNav();
const entry = direction === "prev" ? nav.prev(text) : nav.next();
if (entry === null) return false;
caretToEnd.current = true;
setText(entry);
return true;
}
/**
* Enter sends. ↑/↓ recall once there is nowhere left to move the caret, the
* way pi2.nvim's prompt buffer does it; `<C-p>`/`<C-n>` are the readline
* aliases and always recall. Anything else stays a plain textarea key.
*/
function handleKeyDown(event: KeyboardEvent<HTMLTextAreaElement>) {
// A composing IME owns ↑/↓ (candidate list) and Enter (commit).
if (event.nativeEvent.isComposing) return;
if (event.key === "Enter" && !event.shiftKey) {
event.preventDefault();
submit();
return;
}
const modifier = event.ctrlKey || event.metaKey;
if (modifier && !event.altKey && !event.shiftKey) {
const direction = event.key === "p" ? "prev" : event.key === "n" ? "next" : null;
if (direction === null) return;
event.preventDefault();
recall(direction);
return;
}
if (event.key !== "ArrowUp" && event.key !== "ArrowDown") return;
if (modifier || event.altKey || event.shiftKey) return;
// A selection means the user is editing a fragment, not recalling.
const element = event.currentTarget;
const { selectionStart, selectionEnd } = element;
if (selectionStart === null || selectionEnd === null) return;
if (selectionStart !== selectionEnd) return;
if (event.key === "ArrowUp") {
// Only from the first logical line: inside a multi-line entry ↑ still
// moves the caret (nvim's `<Up>` rule).
if (text.slice(0, selectionStart).includes("\n")) return;
if (recall("prev")) event.preventDefault();
return;
}
// ↓ recalls from the last logical line, and always while browsing, so the
// first ↓ out of a recalled prompt is never swallowed by a caret move.
const atLastLine = !text.slice(selectionEnd).includes("\n");
if (!atLastLine && !historyNav().navigating()) return;
if (recall("next")) event.preventDefault();
}
function submit(mode?: PromptMode) { function submit(mode?: PromptMode) {
const trimmed = text.trim(); const trimmed = text.trim();
if (!trimmed || !enabled) return; if (!trimmed || !enabled) return;
const images = attachments.map(({ mimeType, data }) => ({ mimeType, data })); const images = attachments.map(({ mimeType, data }) => ({ mimeType, data }));
setText(""); setText("");
setAttachments([]); setAttachments([]);
// Record the send and leave recall, exactly like pi2.nvim's prompt buffer.
source.remember(trimmed);
historyNav().reset();
// A busy session queues the message as a follow-up; idle sends a plain prompt. // A busy session queues the message as a follow-up; idle sends a plain prompt.
onSend(trimmed, images, mode ?? (busy ? "follow_up" : undefined)); onSend(trimmed, images, mode ?? (busy ? "follow_up" : undefined));
} }
@@ -218,12 +318,13 @@ export function Composer({
aria-label={t("chat.composerAria")} aria-label={t("chat.composerAria")}
data-testid="composer-input" data-testid="composer-input"
disabled={!enabled} disabled={!enabled}
onChange={(event) => setText(event.target.value)} onChange={(event) => {
onKeyDown={(event) => { setText(event.target.value);
if (event.key !== "Enter" || event.shiftKey || event.nativeEvent.isComposing) return; // A manual edit ends recall, so a later ↓ cannot clobber
event.preventDefault(); // the user's typing with a stale entry.
submit(); historyNav().reset();
}} }}
onKeyDown={handleKeyDown}
/> />
<div className="composer__bar"> <div className="composer__bar">
<button <button
@@ -0,0 +1,131 @@
import { useQuery, useQueryClient } from "@tanstack/react-query";
import { useCallback, useEffect, useMemo, useRef } from "react";
import { ApiError, api, type PromptHistoryResponse } from "@/lib/api";
import {
appendEntry,
HISTORY_LIMIT,
historyScope,
type PromptHistorySource,
readPromptHistory,
relayedPromptHistorySource,
rememberPrompt,
replacePromptHistory,
} from "./prompt-history";
/**
* Prompt input history, fed by the plugin (`docs/protocol.md` §3.1.1) with the
* browser mirror as fallback.
*
* The split matters, so it is explicit here:
*
* * **the entries** belong to pi2.nvim. Every prompt is recorded there on send,
* whichever surface sent it, so the web console and nvim recall the same list
* and so does every device paired to this daemon. The daemon relays one
* live-only read per workspace; it stores nothing.
* * **the mirror** (`localStorage`, `prompt-history.ts`) keeps recall working when
* the relay cannot answer: no plugin connected (`live: false`), a plugin older
* than the `promptHistory` capability (`supported: false`), a daemon older than
* the endpoint (`404`), or an offline browser. It is written on every send, so
* it is at worst behind the plugin — never authoritative.
* * **the cursor** stays with the composer (`PromptHistoryNav`); nothing here
* tries to persist a position.
*
* The query is deliberately cheap: one workspace-scoped read, cached by
* react-query, refreshed on focus and invalidated by nothing else. It never
* causes a spawn — the daemon answers `live: false` instead of booting an nvim.
*/
/** Entries asked of the plugin; matches the daemon's default for the endpoint. */
export const PROMPT_HISTORY_FETCH_LIMIT = 200;
/** react-query key prefix; one query per workspace. */
export const PROMPT_HISTORY_QUERY = "prompt-history";
export interface PromptHistoryFeed {
/** What the composer recalls from and records into. */
source: PromptHistorySource;
/** The plugin answered: the entries come from nvim, not from the mirror. */
remote: boolean;
/** The relay reported a connected plugin (it may still be unable to answer). */
live: boolean;
}
/** Keep only strings, drop blanks, keep the newest {@link HISTORY_LIMIT}. */
export function normalizeEntries(value: unknown): string[] {
if (!Array.isArray(value)) return [];
const entries = value.filter((entry): entry is string => typeof entry === "string" && entry.trim() !== "");
return entries.length > HISTORY_LIMIT ? entries.slice(entries.length - HISTORY_LIMIT) : entries;
}
/**
* History feed for one workspace.
*
* @param workspaceId the workspace whose archive to recall from (undefined =>
* nothing is fetched and the mirror bucket is `default`).
* @param enabled false while unpaired/offline; the composer then recalls from the
* mirror only.
*/
export function usePromptHistory(workspaceId: string | undefined, enabled: boolean): PromptHistoryFeed {
const scope = historyScope(workspaceId);
const queryClient = useQueryClient();
const query = useQuery({
queryKey: [PROMPT_HISTORY_QUERY, workspaceId],
queryFn: ({ signal }) =>
api.promptHistory(workspaceId ?? "", { limit: PROMPT_HISTORY_FETCH_LIMIT, signal }),
enabled: enabled && Boolean(workspaceId),
staleTime: 30_000,
// A daemon older than the endpoint 404s it: a permanent "no relay", so it
// must not burn retries (and must not surface as an error anywhere).
retry: (attempts, error) => !(error instanceof ApiError && error.status === 404) && attempts < 1,
});
const live = query.data?.live === true;
const remote = live && query.data?.supported === true;
const entries = useMemo(
() => (remote ? normalizeEntries(query.data?.entries) : []),
[remote, query.data],
);
// The getter below must see the newest list (a refetch landing mid-browse, or
// the optimistic append after a send) without rebuilding the nav cursor.
const entriesRef = useRef<readonly string[]>(entries);
entriesRef.current = entries;
// Refresh the fallback with what the plugin just told us, so losing it (or
// moving to a daemon that predates the endpoint) still recalls this history
// instead of starting from whatever only this browser typed.
useEffect(() => {
if (remote) replacePromptHistory(scope, entries);
}, [remote, entries, scope]);
const remember = useCallback(
(text: string) => {
// Always keep the mirror warm: it becomes the source the moment this
// workspace loses its plugin, and on an old daemon it is the only copy.
rememberPrompt(scope, text);
if (!remote || workspaceId === undefined) return;
// Optimistic append so ↑ right after a send recalls it immediately.
queryClient.setQueryData<PromptHistoryResponse>(
[PROMPT_HISTORY_QUERY, workspaceId],
(current) => {
if (current === undefined) return current;
return { ...current, entries: appendEntry(normalizeEntries(current.entries), text) };
},
);
},
[remote, scope, workspaceId, queryClient],
);
const source = useMemo<PromptHistorySource>(
() =>
relayedPromptHistorySource(
() => (remote ? entriesRef.current : readPromptHistory(scope)),
remember,
),
[remote, remember, scope],
);
return { source, remote, live };
}
+320
View File
@@ -0,0 +1,320 @@
/**
* Prompt input history — readline-style recall in the composer (↑ / ↓, `<C-p>` /
* `<C-n>`), scoped per workspace.
*
* This is the web console's port of pi2.nvim's `pi.prompt_history`, split the
* same way so both surfaces behave identically and both halves are unit-testable
* without a DOM.
*
* ## Who owns the text
*
* The **plugin owns the archive**. Every prompt is recorded by pi2.nvim when it
* is sent (`Store:add` inside `Chat:_send_message`), whichever surface sent it,
* and the console reads it back through the daemon's live-only relay
* (`GET /api/v1/workspaces/:id/prompt-history`, `docs/protocol.md` §3.1.1). Two
* consequences worth being explicit about:
*
* * nvim and the browser recall the same prompts, and so does every device paired
* to this daemon — one archive, one order, one dedupe rule;
* * the read never spawns an nvim. A workspace with no live plugin answers
* `supported: false`, and the console falls back to its browser-local mirror.
*
* The **mirror** (this file, `localStorage`) exists for that fallback and for
* version skew: a daemon older than the endpoint 404s, a plugin older than the
* `promptHistory` capability reports `supported: false`, and recall keeps
* working from what this browser recorded. It is written on every send, so it can
* only ever be behind the plugin, never authoritative.
*
* The **cursor** (position + stashed draft) is always this composer's own state
* ({@link PromptHistoryNav}) — no surface shares it, and no server sees it.
*
* ## Scoping
*
* `{ [workspaceId]: string[] }`, oldest entry first. nvim scopes history by the
* workspace cwd; the console's analogue is the workspace id every session
* carries, so a second session in the same workspace recalls the same prompts and
* another workspace starts clean. The mirror keeps the 40 most recently used
* workspaces ({@link WORKSPACE_LIMIT}) so a long-lived profile cannot grow
* without bound.
*
* Entries are mirrored verbatim (multi-line prompts included) and compared
* verbatim; only the blankness check trims. Every mirror read and write tolerates
* a missing, corrupt or unwritable `localStorage` (Safari private mode, quota):
* the feature degrades to "no mirror", never to a broken composer.
*/
/** `localStorage` key holding `{ [workspaceId]: string[] }`. */
export const PROMPT_HISTORY_KEY = "pi2-prompt-history";
/** Entries kept per workspace in the mirror; matches pi2.nvim's `prompt.history.max`. */
export const HISTORY_LIMIT = 500;
/**
* Workspaces kept in the mirror. Recall only ever needs the workspace the user is
* in; this bound exists so the key cannot grow forever. pi2.nvim keeps one file
* per workspace and never prunes; a browser shares a single ~5 MB budget.
*/
export const WORKSPACE_LIMIT = 40;
/** Bucket for a session with no workspace id (a `tmp-*` row before it settles). */
export const DEFAULT_SCOPE = "default";
type Document = Record<string, string[]>;
/**
* Everything recall needs from wherever the entries live. The composer only ever
* talks to this, so the plugin relay and the browser mirror are interchangeable.
*/
export interface PromptHistorySource {
/** Entries to show, oldest first, newest last. Called on every recall step. */
entries(): readonly string[];
/** Record a prompt that was just sent. */
remember(text: string): void;
}
/**
* Which bucket a session's history lives in. Falls back to
* {@link DEFAULT_SCOPE} so a session that has not been bound to a workspace yet
* still recalls *something* instead of silently losing the entry.
*/
export function historyScope(workspaceId: string | null | undefined): string {
const id = typeof workspaceId === "string" ? workspaceId.trim() : "";
return id === "" ? DEFAULT_SCOPE : id;
}
function storage(): Storage | undefined {
try {
return typeof localStorage === "undefined" ? undefined : localStorage;
} catch {
// Accessing `localStorage` can throw (Safari private mode, blocked cookies).
return undefined;
}
}
/** Parse the whole mirror document; anything unusable means "no mirror". */
function readDocument(): Document {
const store = storage();
if (store === undefined) return {};
try {
const raw = store.getItem(PROMPT_HISTORY_KEY);
const parsed: unknown = raw === null ? null : JSON.parse(raw);
if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) return {};
const out: Document = {};
for (const [scope, value] of Object.entries(parsed as Record<string, unknown>)) {
if (!Array.isArray(value)) continue;
const entries = value.filter((entry): entry is string => typeof entry === "string");
if (entries.length) out[scope] = entries;
}
return out;
} catch {
return {};
}
}
function writeDocument(document: Document): void {
const store = storage();
if (store === undefined) return;
try {
// Object key order is the LRU: `remember` re-inserts the touched scope so
// it moves to the tail, and the oldest scopes are dropped past the cap.
const scopes = Object.keys(document);
const kept =
scopes.length > WORKSPACE_LIMIT ? scopes.slice(scopes.length - WORKSPACE_LIMIT) : scopes;
const trimmed: Document = {};
for (const scope of kept) {
const entries = document[scope];
if (entries !== undefined && entries.length) trimmed[scope] = entries;
}
if (Object.keys(trimmed).length === 0) {
store.removeItem(PROMPT_HISTORY_KEY);
return;
}
store.setItem(PROMPT_HISTORY_KEY, JSON.stringify(trimmed));
} catch {
// Quota or private mode: recall still works for this page's lifetime.
}
}
/** Copy of one workspace's mirrored entries, oldest first. */
export function readPromptHistory(scope: string): string[] {
const entries = readDocument()[scope];
return entries === undefined ? [] : entries.slice();
}
/**
* The readline rules for one incoming entry, shared by the mirror and the
* optimistic update of the remote cache: blank input is ignored, a repeat of the
* newest entry is skipped, the oldest falls off past {@link HISTORY_LIMIT}.
*
* @returns the resulting entries (a new array), oldest first.
*/
export function appendEntry(entries: readonly string[], text: string): string[] {
if (typeof text !== "string" || text.trim() === "") return entries.slice();
if (entries[entries.length - 1] === text) return entries.slice();
const next = [...entries, text];
return next.length > HISTORY_LIMIT ? next.slice(next.length - HISTORY_LIMIT) : next;
}
/**
* Mirror a submitted prompt into `localStorage`. Mirrors pi2.nvim's `Store:add`:
* blank input is ignored, an entry identical to the newest one is skipped
* (readline consecutive dedupe — a non-consecutive repeat *is* kept).
*
* @returns the resulting entries, oldest first.
*/
export function rememberPrompt(scope: string, text: string): string[] {
const document = readDocument();
const current = document[scope] ?? [];
const entries = appendEntry(current, text);
// "Unchanged" must be judged on the content, not the length: a full list that
// accepts one more entry and drops the oldest has the same length (this slipped
// once — the mirror silently stopped recording after 500 prompts).
const unchanged =
entries.length === current.length &&
entries[entries.length - 1] === current[current.length - 1];
if (unchanged) return current.slice();
// Re-insert so this scope becomes the most recently used one.
delete document[scope];
document[scope] = entries;
writeDocument(document);
return entries.slice();
}
/** Drop one workspace's mirrored history. */
export function clearPromptHistory(scope: string): void {
const document = readDocument();
if (!(scope in document)) return;
delete document[scope];
writeDocument(document);
}
/**
* Overwrite one workspace's mirror with a snapshot taken from the plugin.
*
* The mirror is the fallback, and a fallback that only knows about prompts typed
* *in this browser* is a poor one: without this, losing the plugin (or opening a
* daemon that predates the endpoint) would recall nothing even though nvim had
* the history a second ago. So every successful relay read refreshes the mirror,
* and the fallback starts from the last known state instead of empty.
*
* This never makes the mirror authoritative — a supported relay always wins at
* read time — and the LRU bookkeeping is the same as {@link rememberPrompt}.
*/
export function replacePromptHistory(scope: string, entries: readonly string[]): void {
const document = readDocument();
const capped = appendEntryWindow(entries);
if (capped.length === 0) {
clearPromptHistory(scope);
return;
}
delete document[scope];
document[scope] = capped;
writeDocument(document);
}
/** Keep only usable entries, capped to the newest {@link HISTORY_LIMIT}. */
function appendEntryWindow(entries: readonly string[]): string[] {
const usable = entries.filter((entry) => typeof entry === "string" && entry.trim() !== "");
return usable.length > HISTORY_LIMIT ? usable.slice(usable.length - HISTORY_LIMIT) : usable;
}
/** The browser-local mirror as a source (also the fallback when the relay is cold). */
export function localPromptHistorySource(scope: string): PromptHistorySource {
return {
entries: () => readPromptHistory(scope),
remember: (text) => {
rememberPrompt(scope, text);
},
};
}
/**
* A source backed by a caller-owned list (the plugin relay's cached entries) with
* an explicit `remember` hook. The getter is re-read on every recall step, so a
* refetch or an optimistic append is visible without rebuilding the cursor.
*/
export function relayedPromptHistorySource(
entries: () => readonly string[],
remember: (text: string) => void,
): PromptHistorySource {
return { entries, remember };
}
/**
* The transient recall cursor for one composer.
*
* `index` is the position in the archive: `null` means "not browsing" — the
* textarea shows the user's own draft. `prev()` enters browsing and stashes the
* draft; walking back down past the newest entry restores it and leaves browsing.
* A composer that shares a workspace with another (two tabs, two sessions) keeps
* its own cursor: only the archive is shared.
*
* The source is queried on every step, so entries recorded elsewhere (another
* browser, nvim, a refetch that landed mid-browse) are recallable immediately.
*/
export class PromptHistoryNav {
private readonly source: PromptHistorySource;
private index: number | null = null;
private draft = "";
constructor(source: PromptHistorySource) {
this.source = source;
}
/**
* Step toward older entries. The first call stashes `draft` (what the user
* was typing) so the walk back down can restore it.
*
* @returns the entry to show, or `null` when there is nothing older.
*/
prev(draft = ""): string | null {
const entries = this.source.entries();
const size = entries.length;
if (size === 0) return null;
if (this.index === null) {
this.draft = draft;
this.index = size;
return entries[size - 1] ?? null;
}
if (this.index > 1) {
this.index -= 1;
return entries[this.index - 1] ?? null;
}
// Already at the oldest entry: no change.
return null;
}
/**
* Step toward newer entries, then out of browsing (restoring the stashed
* draft) once the newest entry has been passed.
*
* @returns the entry to show, or `null` when not browsing.
*/
next(): string | null {
if (this.index === null) return null;
const entries = this.source.entries();
const size = entries.length;
if (this.index < size) {
this.index += 1;
return entries[this.index - 1] ?? null;
}
const draft = this.draft;
this.reset();
return draft;
}
/** Whether the composer is currently showing an entry from the archive. */
navigating(): boolean {
return this.index !== null;
}
/**
* Leave browsing. Called after a send and whenever the user edits the text
* by hand — otherwise a later ↓ would overwrite their typing with a stale
* entry.
*/
reset(): void {
this.index = null;
this.draft = "";
}
}
+134
View File
@@ -0,0 +1,134 @@
/**
* Workspace picker ordering and search (chat sidebar, `.ws-menu`).
*
* The picker answers "which workspace was I in last?", so it lists rows by
* **recent use**, in this precedence order:
*
* 1. a browser-local "last opened here" stamp (`pi2-workspace-recency`), written
* whenever a workspace becomes the active one in the console;
* 2. the daemon's `lastActiveAt` (mtime of the workspace's newest session file),
* which carries across devices and survives a cleared browser profile;
* 3. alphabetical, then by id — a deterministic order for never-touched rows.
*
* Ordering is intentionally *not* pinned-first: the picker is a recency control,
* the `/workspaces` page is the curated list.
*/
import type { WorkspaceInfo } from "@/lib/protocol";
/** `localStorage` key holding `{ [workspaceId]: epoch ms }`. */
export const WORKSPACE_RECENCY_KEY = "pi2-workspace-recency";
/** Upper bound on persisted rows; a picker never needs more history than this. */
const RECENCY_LIMIT = 60;
export type WorkspaceRecency = Record<string, number>;
/** Display label: name → directory basename → id. */
export function workspaceLabel(workspace: WorkspaceInfo): string {
const name = workspace.name?.trim();
if (name) return name;
const cwd = workspace.cwd?.replace(/\/+$/, "");
if (cwd) {
const segments = cwd.split("/");
const base = segments[segments.length - 1];
if (base) return base;
}
return workspace.workspaceId;
}
/** `localStorage` read; any failure (private mode, corrupt JSON) means "no history". */
export function readWorkspaceRecency(): WorkspaceRecency {
try {
const raw = localStorage.getItem(WORKSPACE_RECENCY_KEY);
if (!raw) return {};
const parsed: unknown = JSON.parse(raw);
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return {};
const out: WorkspaceRecency = {};
for (const [id, value] of Object.entries(parsed as Record<string, unknown>)) {
if (typeof value === "number" && Number.isFinite(value)) out[id] = value;
}
return out;
} catch {
return {};
}
}
/** Stamp `workspaceId` as used now and persist; returns the updated map. */
export function markWorkspaceUsed(workspaceId: string, at: number = Date.now()): WorkspaceRecency {
if (!workspaceId) return readWorkspaceRecency();
const next: WorkspaceRecency = { ...readWorkspaceRecency(), [workspaceId]: at };
const trimmed = Object.entries(next)
.sort((a, b) => b[1] - a[1])
.slice(0, RECENCY_LIMIT);
const out = Object.fromEntries(trimmed);
try {
localStorage.setItem(WORKSPACE_RECENCY_KEY, JSON.stringify(out));
} catch {
// private mode / quota: ordering still works for this render
}
return out;
}
/** Recency score of one row: the later of local use and daemon activity. */
export function workspaceRecency(workspace: WorkspaceInfo, recency: WorkspaceRecency = {}): number {
const local = recency[workspace.workspaceId] ?? 0;
const remote = workspace.lastActiveAt ?? 0;
return Math.max(local, remote);
}
/** Most-recently-used first, with a stable alphabetical fallback. */
export function compareByRecentUse(
a: WorkspaceInfo,
b: WorkspaceInfo,
recency: WorkspaceRecency = {},
): number {
const delta = workspaceRecency(b, recency) - workspaceRecency(a, recency);
if (delta !== 0) return delta;
const byName = workspaceLabel(a).localeCompare(workspaceLabel(b), undefined, { sensitivity: "base" });
if (byName !== 0) return byName;
return a.workspaceId.localeCompare(b.workspaceId);
}
/** Sort a copy; the caller's array is never mutated. */
export function sortByRecentUse(
workspaces: readonly WorkspaceInfo[],
recency: WorkspaceRecency = {},
): WorkspaceInfo[] {
return workspaces.slice().sort((a, b) => compareByRecentUse(a, b, recency));
}
/** Split a raw query into lower-cased terms (empty when nothing was typed). */
export function searchTerms(query: string): string[] {
return query
.toLowerCase()
.split(/\s+/)
.filter((term) => term.length > 0);
}
/** Fields a workspace is searchable by, lower-cased and deduped. */
function haystack(workspace: WorkspaceInfo): string[] {
const cwd = workspace.cwd ?? "";
const base = workspaceLabel(workspace);
const fields = [base, workspace.name ?? "", workspace.alias ?? "", cwd, workspace.workspaceId];
const tail = cwd.replace(/\/+$/, "").split("/").pop();
if (tail) fields.push(tail);
return [...new Set(fields.map((field) => field.toLowerCase()).filter((field) => field.length > 0))];
}
/** Every term must hit some field (name, alias, cwd, basename or id). */
export function workspaceMatches(workspace: WorkspaceInfo, terms: readonly string[]): boolean {
if (!terms.length) return true;
const fields = haystack(workspace);
return terms.every((term) => fields.some((field) => field.includes(term)));
}
/** Filter a (already sorted) list; ordering is preserved. */
export function searchWorkspaces(
workspaces: readonly WorkspaceInfo[],
query: string,
): WorkspaceInfo[] {
const terms = searchTerms(query);
if (!terms.length) return workspaces.slice();
return workspaces.filter((workspace) => workspaceMatches(workspace, terms));
}
+114 -31
View File
@@ -1,9 +1,10 @@
import type { WorkspaceInfo } from "@protocol/types"; import type { WorkspaceInfo } from "@protocol/types";
import { useEffect, useRef } from "react"; import { useEffect, useMemo, useRef, useState } from "react";
import { useTranslation } from "react-i18next"; import { useTranslation } from "react-i18next";
import { Icon } from "@/components/icons"; import { Icon } from "@/components/icons";
import { cn } from "@/lib/utils"; import { cn } from "@/lib/utils";
import { readWorkspaceRecency, searchWorkspaces, sortByRecentUse, workspaceLabel } from "./workspace-order";
export interface WorkspaceSwitchProps { export interface WorkspaceSwitchProps {
/** Every workspace the daemon knows about (the menu lists all of them). */ /** Every workspace the daemon knows about (the menu lists all of them). */
@@ -18,17 +19,16 @@ export interface WorkspaceSwitchProps {
className?: string; className?: string;
} }
function workspaceLabel(workspace: WorkspaceInfo): string {
return workspace.name?.trim() || workspace.cwd || workspace.workspaceId;
}
/** /**
* `.ws-switch` + `.ws-menu` (v0.1.1 Chat IA v3). * `.ws-switch` + `.ws-menu` (v0.1.1 Chat IA v3).
* *
* The tree pane carries exactly ONE workspace, so the workspace picker is a * The tree pane carries exactly ONE workspace, so the workspace picker is a
* button with a menu instead of a native `<select>`: it shows the name, the * button with a popover instead of a native `<select>`: it shows the name, the
* session count and a chevron that rotates while open, and each menu row is a * session count and a chevron that rotates while open.
* `menuitemradio` with a check mark for the current workspace. *
* The menu is a filterable listbox: rows are ordered by **recent use** (see
* `./workspace-order`), the search field at the top filters by name, alias, path
* or id, and each row is an `option` with the current workspace selected.
*/ */
export function WorkspaceSwitch({ export function WorkspaceSwitch({
workspaces, workspaces,
@@ -43,10 +43,21 @@ export function WorkspaceSwitch({
const rootRef = useRef<HTMLDivElement | null>(null); const rootRef = useRef<HTMLDivElement | null>(null);
const buttonRef = useRef<HTMLButtonElement | null>(null); const buttonRef = useRef<HTMLButtonElement | null>(null);
const menuRef = useRef<HTMLDivElement | null>(null); const menuRef = useRef<HTMLDivElement | null>(null);
const listRef = useRef<HTMLDivElement | null>(null);
const inputRef = useRef<HTMLInputElement | null>(null);
const [query, setQuery] = useState("");
// Snapshot of "which workspace did I open last" taken when the menu opens,
// so a fresh pick is reflected the next time the user looks.
const [recency, setRecency] = useState(() => readWorkspaceRecency());
const active = workspaces.find((workspace) => workspace.workspaceId === activeWorkspaceId); const active = workspaces.find((workspace) => workspace.workspaceId === activeWorkspaceId);
const label = active ? workspaceLabel(active) : t("chat.noWorkspace"); const label = active ? workspaceLabel(active) : t("chat.noWorkspace");
const ordered = useMemo(() => sortByRecentUse(workspaces, recency), [workspaces, recency]);
const rows = useMemo(() => searchWorkspaces(ordered, query), [ordered, query]);
const filtering = query.trim().length > 0;
// Click outside closes the menu. `composedPath()` (not `contains`) because a // Click outside closes the menu. `composedPath()` (not `contains`) because a
// menu item selection re-renders and detaches the clicked node first. // menu item selection re-renders and detaches the clicked node first.
useEffect(() => { useEffect(() => {
@@ -60,37 +71,54 @@ export function WorkspaceSwitch({
return () => document.removeEventListener("pointerdown", onPointerDown, true); return () => document.removeEventListener("pointerdown", onPointerDown, true);
}, [open, onOpenChange]); }, [open, onOpenChange]);
// Opening moves focus into the menu (the checked row), like a real picker. // Opening: refresh the recency snapshot, clear the last query, focus the
// search field (there is always something to type in a searchable picker).
useEffect(() => { useEffect(() => {
if (!open) return; if (!open) {
setQuery("");
return;
}
setRecency(readWorkspaceRecency());
const frame = requestAnimationFrame(() => { const frame = requestAnimationFrame(() => {
const target = inputRef.current?.focus({ preventScroll: true });
menuRef.current?.querySelector<HTMLElement>('[aria-checked="true"]') ??
menuRef.current?.querySelector<HTMLElement>("[data-workspace-id]");
target?.focus({ preventScroll: true });
}); });
return () => cancelAnimationFrame(frame); return () => cancelAnimationFrame(frame);
}, [open]); }, [open]);
function moveFocus(delta: 1 | -1 | "home" | "end") { function close(refocus = true) {
const items = Array.from(menuRef.current?.querySelectorAll<HTMLElement>("[data-workspace-id]") ?? []); onOpenChange(false);
if (!refocus) return;
requestAnimationFrame(() => buttonRef.current?.focus({ preventScroll: true }));
}
function options(): HTMLElement[] {
return Array.from(listRef.current?.querySelectorAll<HTMLElement>("[data-workspace-id]") ?? []);
}
function moveFocus(move: 1 | -1 | "home" | "end") {
const items = options();
if (!items.length) return; if (!items.length) return;
const current = items.indexOf(document.activeElement as HTMLElement); const current = items.indexOf(document.activeElement as HTMLElement);
let next = current; let next = current;
if (delta === "home") next = 0; if (move === "home") next = 0;
else if (delta === "end") next = items.length - 1; else if (move === "end") next = items.length - 1;
else if (delta === 1) next = current < 0 ? 0 : (current + 1) % items.length; else if (move === 1) next = current < 0 ? 0 : (current + 1) % items.length;
else next = current < 0 ? items.length - 1 : (current - 1 + items.length) % items.length; else next = current < 0 ? items.length - 1 : (current - 1 + items.length) % items.length;
items[next]?.focus({ preventScroll: true }); items[next]?.focus({ preventScroll: true });
} }
function choose(workspaceId: string) {
onOpenChange(false);
onSelect(workspaceId);
}
return ( return (
<div className={cn("ws-switch-row", className)} ref={rootRef}> <div className={cn("ws-switch-row", className)} ref={rootRef}>
<button <button
ref={buttonRef} ref={buttonRef}
type="button" type="button"
className="ws-switch" className="ws-switch"
aria-haspopup="menu" aria-haspopup="listbox"
aria-expanded={open} aria-expanded={open}
aria-label={t("chat.workspaceSwitchAria", { name: label })} aria-label={t("chat.workspaceSwitchAria", { name: label })}
title={active?.cwd ?? label} title={active?.cwd ?? label}
@@ -108,12 +136,11 @@ export function WorkspaceSwitch({
<div <div
ref={menuRef} ref={menuRef}
className="ws-menu" className="ws-menu"
role="menu"
aria-label={t("chat.workspaceSwitch")}
data-testid="ws-menu" data-testid="ws-menu"
hidden={!open} hidden={!open}
onKeyDown={(event) => { onKeyDown={(event) => {
if (event.key === "ArrowDown" || event.key === "ArrowUp" || event.key === "Home" || event.key === "End") { if (event.key === "ArrowDown" || event.key === "ArrowUp" || event.key === "Home" || event.key === "End") {
// Arrow keys walk either the search field or the rows.
event.preventDefault(); event.preventDefault();
moveFocus( moveFocus(
event.key === "ArrowDown" event.key === "ArrowDown"
@@ -126,31 +153,79 @@ export function WorkspaceSwitch({
); );
return; return;
} }
if (
event.key === "Enter" &&
(event.target === inputRef.current || document.activeElement === inputRef.current)
) {
// Enter in the search field takes the best (first) match.
const first = rows[0];
if (!first) return;
event.preventDefault();
choose(first.workspaceId);
return;
}
if (event.key === "Escape" || event.key === "Tab") { if (event.key === "Escape" || event.key === "Tab") {
event.preventDefault(); event.preventDefault();
event.stopPropagation(); event.stopPropagation();
onOpenChange(false); close();
requestAnimationFrame(() => buttonRef.current?.focus({ preventScroll: true }));
} }
}} }}
> >
<div className="ws-menu__label">{t("chat.workspaceSwitch")}</div> <div className="ws-menu__search">
{workspaces.map((workspace) => { <Icon name="search" />
<input
ref={inputRef}
type="search"
className="ws-menu__input"
value={query}
autoComplete="off"
spellCheck={false}
aria-label={t("chat.workspaceSearchAria")}
aria-controls="ws-menu-list"
placeholder={t("chat.workspaceSearch")}
data-testid="ws-menu-search"
onChange={(event) => setQuery(event.target.value)}
/>
{query ? (
<button
type="button"
className="ws-menu__clear"
aria-label={t("chat.workspaceSearchClear")}
onClick={() => {
setQuery("");
inputRef.current?.focus({ preventScroll: true });
}}
>
<Icon name="x" />
</button>
) : null}
</div>
<div
ref={listRef}
id="ws-menu-list"
className="ws-menu__list"
role="listbox"
aria-label={t("chat.workspaceSwitch")}
>
{rows.map((workspace) => {
const checked = workspace.workspaceId === activeWorkspaceId; const checked = workspace.workspaceId === activeWorkspaceId;
const count = checked ? sessionCount : workspace.sessionCount; const count = checked ? sessionCount : workspace.sessionCount;
return ( return (
<button <button
key={workspace.workspaceId} key={workspace.workspaceId}
type="button" type="button"
role="menuitemradio" role="option"
aria-checked={checked} aria-selected={checked}
className={cn("ws-menu__item", checked && "is-active")} className={cn("ws-menu__item", checked && "is-active")}
data-workspace-id={workspace.workspaceId} data-workspace-id={workspace.workspaceId}
title={workspace.cwd} title={workspace.cwd}
tabIndex={-1}
onClick={() => { onClick={() => {
onOpenChange(false); if (checked) {
if (!checked) onSelect(workspace.workspaceId); close();
else requestAnimationFrame(() => buttonRef.current?.focus({ preventScroll: true })); return;
}
choose(workspace.workspaceId);
}} }}
> >
<Icon name={checked ? "check" : "folder"} /> <Icon name={checked ? "check" : "folder"} />
@@ -159,6 +234,14 @@ export function WorkspaceSwitch({
</button> </button>
); );
})} })}
{rows.length ? null : (
<div className="ws-menu__empty" data-testid="ws-menu-empty">
{filtering
? t("chat.workspaceSearchNoMatch", { query: query.trim() })
: t("chat.noWorkspace")}
</div>
)}
</div>
</div> </div>
</div> </div>
); );
+69 -6
View File
@@ -2,8 +2,9 @@ import { useTranslation } from "react-i18next";
import { Icon } from "@/components/icons"; import { Icon } from "@/components/icons";
import { RelativeTime } from "@/components/shared/relative-time"; import { RelativeTime } from "@/components/shared/relative-time";
import type { ResourcesResponse } from "@/lib/api"; import type { DiskUsage, ResourcesResponse } from "@/lib/api";
import { formatBytes, formatUptime, type ServerIdentity } from "@/features/status/server"; import { formatBytes, type ServerIdentity } from "@/features/status/server";
import { LiveUptime } from "@/features/status/uptime";
import { ErrorBlock } from "./card-parts"; import { ErrorBlock } from "./card-parts";
@@ -34,6 +35,53 @@ function readable(pct: number | null): string {
return pct == null ? "—" : `${Math.round(pct)}%`; return pct == null ? "—" : `${Math.round(pct)}%`;
} }
function diskTone(pct: number): string {
return pct > 90 ? "is-err" : pct > 80 ? "is-warn" : "";
}
/**
* Disk tile meta line. One filesystem reads `mountPoint · used / total`; several
* become a compact worst-first stack (the daemon caps the list at 4), because a
* single headline percent would hide the volume that is actually full.
*/
function DiskMeta({ disks, diskError, diskPath }: { disks: DiskUsage[]; diskError?: string; diskPath?: string }) {
if (disks.length === 0) {
const reason = diskError ?? diskPath ?? "—";
return (
<span className="faint truncate" title={reason}>
{reason}
</span>
);
}
const detail = (disk: DiskUsage) =>
[disk.mountPoint, disk.fsType, `${formatBytes(disk.usedBytes)} / ${formatBytes(disk.totalBytes)}`]
.filter(Boolean)
.join(" · ");
if (disks.length === 1) {
const disk = disks[0]!;
return (
<span className="faint truncate" title={detail(disk)}>
{disk.mountPoint} · {formatBytes(disk.usedBytes)} / {formatBytes(disk.totalBytes)}
</span>
);
}
return (
<div className="disk-rows">
{disks.map((disk) => (
<div className="disk-row" key={disk.mountPoint}>
<span className="disk-row__label truncate" title={detail(disk)}>
{disk.mountPoint}
</span>
<b className={`disk-row__pct ${diskTone(disk.percent)}`}>{readable(percent(disk.percent))}</b>
</div>
))}
</div>
);
}
export interface MetricsBlockProps { export interface MetricsBlockProps {
server: ServerIdentity; server: ServerIdentity;
resources: ResourcesResponse | undefined; resources: ResourcesResponse | undefined;
@@ -62,17 +110,30 @@ export function MetricsBlock({
}: MetricsBlockProps) { }: MetricsBlockProps) {
const { t } = useTranslation(); const { t } = useTranslation();
const system = resources?.system; const system = resources?.system;
const disks = system?.disks ?? [];
const cpu = percent(system?.cpuPercent ?? server.cpu); const cpu = percent(system?.cpuPercent ?? server.cpu);
const mem = percent(system?.memPercent ?? server.mem); const mem = percent(system?.memPercent ?? server.mem);
const disk = percent(system?.diskPercent ?? server.disk); // `disks` is worst-first, so `[0]` is the number worth showing; the scalars are
// the same row on new daemons and the only source on old ones.
const disk = percent(disks[0]?.percent ?? system?.diskPercent ?? server.disk);
// Host uptime, not the daemon's: this tile answers "how long has the box been
// up", and the polled `/resources` sample keeps it fresh.
const hostUptimeMs =
system?.hostUptimeSec != null ? system.hostUptimeSec * 1000 : server.hostUptimeSec != null ? server.hostUptimeSec * 1000 : null;
const live = t("status.live", { defaultValue: "Live" }); const live = t("status.live", { defaultValue: "Live" });
const cpuMeta = system const cpuMeta = system
? `${system.cpuCores} ${t("status.cores")}${system.loadAvg ? ` · ${t("status.load")} ${system.loadAvg[0].toFixed(2)}` : ""}` ? `${system.cpuCores} ${t("status.cores")}${system.loadAvg ? ` · ${t("status.load")} ${system.loadAvg[0].toFixed(2)}` : ""}`
: live; : live;
const memMeta = system ? `${formatBytes(system.memUsedBytes)} / ${formatBytes(system.memTotalBytes)}` : live; const memMeta = system ? `${formatBytes(system.memUsedBytes)} / ${formatBytes(system.memTotalBytes)}` : live;
const diskMeta = system ? ( const diskMeta = system ? (
<span className="faint truncate" title={system.diskPath}>{system.diskPath}</span> <DiskMeta
) : live; disks={disks}
{...(system.diskError === undefined ? {} : { diskError: system.diskError })}
{...(system.diskPath === undefined ? {} : { diskPath: system.diskPath })}
/>
) : (
live
);
const counts: Array<[string, string]> = [ const counts: Array<[string, string]> = [
[t("status.workspaces"), String(workspaceCount)], [t("status.workspaces"), String(workspaceCount)],
@@ -115,7 +176,9 @@ export function MetricsBlock({
<div className="tile status-tile" data-res="uptime"> <div className="tile status-tile" data-res="uptime">
<div className="tile__label">{t("status.uptime")}</div> <div className="tile__label">{t("status.uptime")}</div>
<div className="tile__value">{formatUptime(server.uptimeSec)}</div> <div className="tile__value">
<LiveUptime ms={hostUptimeMs} />
</div>
<div className="tile__meta"> <div className="tile__meta">
<span>{t("status.lastHeartbeat")}</span> <span>{t("status.lastHeartbeat")}</span>
<RelativeTime ts={server.lastHeartbeatAt} live={false} /> <RelativeTime ts={server.lastHeartbeatAt} live={false} />
+7 -2
View File
@@ -5,7 +5,8 @@ import { StatusDot } from "@/components/ui/status-dot";
import { KV, KVList } from "@/components/ui/kv"; import { KV, KVList } from "@/components/ui/kv";
import type { ResourcesResponse } from "@/lib/api"; import type { ResourcesResponse } from "@/lib/api";
import type { ServerIdentity } from "@/features/status/server"; import type { ServerIdentity } from "@/features/status/server";
import { formatBytes, formatUptime } from "@/features/status/server"; import { formatBytes } from "@/features/status/server";
import { LiveUptime } from "@/features/status/uptime";
import { ErrorBlock, LoadingBlock, StatusCard } from "./card-parts"; import { ErrorBlock, LoadingBlock, StatusCard } from "./card-parts";
@@ -49,7 +50,11 @@ export function ServerInfoCard({ server, resources, loading, error, onRetry }: S
{server.platform} {server.platform}
</KV> </KV>
<KV label={t("status.piVersion")}>{server.piVersion}</KV> <KV label={t("status.piVersion")}>{server.piVersion}</KV>
<KV label={t("status.uptime")}>{formatUptime(server.uptimeSec)}</KV> {/* This card is the daemon's own identity (pid, daemonId): its uptime
is the *process* age, which resets on every restart. */}
<KV label={t("status.daemonUptime")}>
<LiveUptime ms={server.uptimeMs ?? (server.uptimeSec != null ? server.uptimeSec * 1000 : null)} />
</KV>
<KV label="daemonId" mono> <KV label="daemonId" mono>
{server.daemonId} {server.daemonId}
</KV> </KV>
+5
View File
@@ -50,6 +50,7 @@ export function resolveServerStatus(input: ServerStatusInput): ServerStatusValue
export interface InfoExtras extends InfoResponse { export interface InfoExtras extends InfoResponse {
pid?: number; pid?: number;
kernel?: string; kernel?: string;
/** Daemon process age (seconds); kept as a derived alias of `uptimeMs`. */
uptimeSec?: number; uptimeSec?: number;
lastHeartbeat?: number; lastHeartbeat?: number;
mdns?: string; mdns?: string;
@@ -76,6 +77,8 @@ export interface ServerIdentity {
kernel: string; kernel: string;
uptimeSec: number | null; uptimeSec: number | null;
uptimeMs: number | null; uptimeMs: number | null;
/** Host uptime in seconds — what the status page labels “uptime”. */
hostUptimeSec: number | null;
pid: number | null; pid: number | null;
status: ServerStatusValue; status: ServerStatusValue;
wsConnected: boolean; wsConnected: boolean;
@@ -155,6 +158,7 @@ export function deriveServerIdentity({
const uptimeMs = finite(extras.uptimeMs); const uptimeMs = finite(extras.uptimeMs);
const uptimeSec = const uptimeSec =
uptimeMs != null ? Math.floor(uptimeMs / 1000) : typeof extras.uptimeSec === "number" ? extras.uptimeSec : null; uptimeMs != null ? Math.floor(uptimeMs / 1000) : typeof extras.uptimeSec === "number" ? extras.uptimeSec : null;
const hostUptimeMs = finite(extras.hostUptimeMs);
return { return {
name, name,
@@ -171,6 +175,7 @@ export function deriveServerIdentity({
kernel: text(extras.kernel), kernel: text(extras.kernel),
uptimeSec, uptimeSec,
uptimeMs, uptimeMs,
hostUptimeSec: hostUptimeMs != null ? Math.floor(hostUptimeMs / 1000) : null,
pid: finite(extras.pid), pid: finite(extras.pid),
status: resolvedStatus, status: resolvedStatus,
wsConnected: wsState === "open", wsConnected: wsState === "open",
+48
View File
@@ -0,0 +1,48 @@
import { useEffect, useMemo, useReducer } from "react";
import { formatUptime } from "@/features/status/server";
/**
* Seconds elapsed since `baseAtMs`, clamped at zero.
*
* A duration, not a timestamp: the daemon only reports a snapshot
* (`hostUptimeSec` on the polled `/resources`, `hostUptimeMs` on the rarely
* refetched `/info`), so the counter has to advance locally.
*/
export function uptimeSecondsFrom(baseAtMs: number, now: number): number {
return Math.max(0, Math.floor((now - baseAtMs) / 1000));
}
/** Epoch ms the counted duration started at, or `null` for an unusable value. */
export function uptimeAnchor(ms: number | null | undefined, now = Date.now()): number | null {
if (typeof ms !== "number" || !Number.isFinite(ms) || ms < 0) return null;
return now - ms;
}
export interface LiveUptimeProps {
/** Reported uptime in milliseconds; `null`/`undefined` renders an em dash. */
ms: number | null | undefined;
className?: string;
}
/**
* Ticking uptime label.
*
* `formatUptime` bottoms out at minutes, so a 30 s tick is enough. The anchor is
* memoised on `ms` alone: re-renders (and the 3 s `/resources` poll reporting the
* same second) never rewind or fast-forward the counter, while a genuinely newer
* sample re-anchors it.
*/
export function LiveUptime({ ms, className }: LiveUptimeProps) {
const [, tick] = useReducer((n: number) => n + 1, 0);
const anchor = useMemo(() => uptimeAnchor(ms), [ms]);
useEffect(() => {
if (anchor === null) return;
const timer = setInterval(tick, 30_000);
return () => clearInterval(timer);
}, [anchor]);
if (anchor === null) return <span className={className}>—</span>;
return <span className={className}>{formatUptime(uptimeSecondsFrom(anchor, Date.now()))}</span>;
}
@@ -55,11 +55,17 @@ type Phrases = { unnamed: string; subagentUnnamed: string };
function ActivityRow({ session, phrases }: { session: RecentSessionRow; phrases: Phrases }) { function ActivityRow({ session, phrases }: { session: RecentSessionRow; phrases: Phrases }) {
const { t } = useTranslation(); const { t } = useTranslation();
// A disk-only row has no live state; the session title contract then falls // A live row carries the authoritative name/first message. A disk-only row
// back to `(unnamed)` (never an id), and the dot is the hollow "exited". // gets the daemon's bounded preview (latest `session_info` name → first user
const title = session.state // message); only a session with neither falls back to `(unnamed)`. Merge the
? sessionTitle(session.state, phrases) // two so a sparse live row still keeps the disk title.
: { text: phrases.unnamed, provisional: true, spinner: false }; const title = sessionTitle(
{
name: session.state?.name || session.name,
firstMessage: session.state?.firstMessage || session.firstMessage,
},
phrases,
);
const dot = session.state ? sessionDot(session.state) : { status: "exited" as const }; const dot = session.state ? sessionDot(session.state) : { status: "exited" as const };
const label = session.state ? t(`state.${sessionStatusKey(session.state)}`) : t("state.exited"); const label = session.state ? t(`state.${sessionStatusKey(session.state)}`) : t("state.exited");
+13 -1
View File
@@ -20,6 +20,10 @@ export interface RecentSessionRow {
ts: number; ts: number;
/** Full state when a live instance answered for the workspace; null for disk-only rows. */ /** Full state when a live instance answered for the workspace; null for disk-only rows. */
state: SessionState | null; state: SessionState | null;
/** Disk title: latest `session_info` name in the file, when the daemon saw one. */
name?: string;
/** Disk title fallback: the first user message (≤80 chars). */
firstMessage?: string;
} }
function rec(value: unknown): Record<string, unknown> | undefined { function rec(value: unknown): Record<string, unknown> | undefined {
@@ -47,6 +51,8 @@ export function normalizeRecentSessions(payload: unknown): RecentSessionInfo[] {
const sessionId = str(row?.sessionId); const sessionId = str(row?.sessionId);
const workspaceId = str(row?.workspaceId); const workspaceId = str(row?.workspaceId);
if (!row || !sessionId || !workspaceId) continue; if (!row || !sessionId || !workspaceId) continue;
const name = str(row.name);
const firstMessage = str(row.firstMessage);
rows.push({ rows.push({
sessionId, sessionId,
workspaceId, workspaceId,
@@ -55,6 +61,8 @@ export function normalizeRecentSessions(payload: unknown): RecentSessionInfo[] {
sessionFile: str(row.sessionFile) ?? "", sessionFile: str(row.sessionFile) ?? "",
timestamp: num(row.timestamp) ?? 0, timestamp: num(row.timestamp) ?? 0,
modified: num(row.modified) ?? 0, modified: num(row.modified) ?? 0,
...(name === undefined ? {} : { name }),
...(firstMessage === undefined ? {} : { firstMessage }),
}); });
} }
return rows; return rows;
@@ -65,7 +73,9 @@ export function normalizeRecentSessions(payload: unknown): RecentSessionInfo[] {
* *
* Disk rows are the base (they exist after a daemon restart, before any * Disk rows are the base (they exist after a daemon restart, before any
* workspace is spawned). A live row with the same id replaces the metadata: * workspace is spawned). A live row with the same id replaces the metadata:
* it carries the authoritative name/first message/status. Sub-sessions are * it carries the authoritative name/first message/status. Disk rows keep the
* daemon's bounded display preview (`name`/`firstMessage`) so a history row in
* a workspace with no running instance still renders a title. Sub-sessions are
* dropped — the design's activity column is a list of workspace roots. * dropped — the design's activity column is a list of workspace roots.
*/ */
export function mergeRecentSessions( export function mergeRecentSessions(
@@ -105,6 +115,8 @@ export function mergeRecentSessions(
workspaceName: nameById.get(workspaceId) ?? entry.disk?.workspaceName ?? "", workspaceName: nameById.get(workspaceId) ?? entry.disk?.workspaceName ?? "",
ts, ts,
state: entry.live ?? null, state: entry.live ?? null,
...(entry.disk?.name === undefined ? {} : { name: entry.disk.name }),
...(entry.disk?.firstMessage === undefined ? {} : { firstMessage: entry.disk.firstMessage }),
}); });
} }
rows.sort((a, b) => b.ts - a.ts || a.sessionId.localeCompare(b.sessionId)); rows.sort((a, b) => b.ts - a.ts || a.sessionId.localeCompare(b.sessionId));
+46
View File
@@ -256,7 +256,10 @@ export interface InfoResponse {
port?: number; port?: number;
/** Additive identity fields (daemon ≥ 0.2): OS label and process uptime. */ /** Additive identity fields (daemon ≥ 0.2): OS label and process uptime. */
os?: string; os?: string;
/** **Daemon process** age; `hostUptimeMs` is the host figure. */
uptimeMs?: number; uptimeMs?: number;
/** Host uptime (daemon ≥ 0.1.8); absent on older builds. */
hostUptimeMs?: number;
/** Resource percentages from newer daemons (0..100). */ /** Resource percentages from newer daemons (0..100). */
cpu?: number; cpu?: number;
mem?: number; mem?: number;
@@ -302,8 +305,38 @@ export interface ModelsResponse {
pendingReason?: "fetching" | "no-instance" | "no-live-session"; pendingReason?: "fetching" | "no-instance" | "no-live-session";
} }
/**
* `GET /api/v1/workspaces/:id/prompt-history` (docs/protocol.md §3.1.1).
*
* `live` is "a plugin for this workspace is connected", `supported` is "and it
* advertised the `promptHistory` capability". The composer recalls from the
* browser mirror unless both are true, so a cold workspace, an old plugin or an
* old daemon all degrade to the same working fallback instead of an error.
*/
export interface PromptHistoryResponse {
v?: number;
workspaceId?: string;
live?: boolean;
supported?: boolean;
/** Oldest first, newest last; unvalidated here (the caller normalizes). */
entries?: unknown;
}
/** One sampled filesystem (daemon ≥ 0.1.8; older daemons only send the scalars). */
export interface DiskUsage {
/** Filesystem boundary, e.g. `/`, `/home`, `/mnt/data`. */
mountPoint: string;
/** Best-effort type label (`ext4`, `btrfs`, …); absent when unknown. */
fsType?: string;
totalBytes: number;
usedBytes: number;
percent: number;
}
export interface SystemStats { export interface SystemStats {
sampledAt: number; sampledAt: number;
/** Host uptime in whole seconds; `null`/absent on daemons < 0.1.8. */
hostUptimeSec?: number | null;
cpuPercent: number | null; cpuPercent: number | null;
cpuCores: number; cpuCores: number;
loadAvg: [number, number, number] | null; loadAvg: [number, number, number] | null;
@@ -314,6 +347,10 @@ export interface SystemStats {
diskUsedBytes: number | null; diskUsedBytes: number | null;
diskTotalBytes: number | null; diskTotalBytes: number | null;
diskPercent: number | null; diskPercent: number | null;
/** Most constrained first, at most 4 rows; absent on daemons < 0.1.8. */
disks?: DiskUsage[];
/** Present only when `disks` is empty — the sample failed, distinct from a full disk. */
diskError?: string;
} }
export interface ResourcesResponse { export interface ResourcesResponse {
@@ -366,6 +403,15 @@ export const api = {
}, },
attention: (workspaceId: string, signal?: AbortSignal) => attention: (workspaceId: string, signal?: AbortSignal) =>
request<unknown[]>(`/api/v1/attention?workspaceId=${encodeURIComponent(workspaceId)}`, { signal }), request<unknown[]>(`/api/v1/attention?workspaceId=${encodeURIComponent(workspaceId)}`, { signal }),
promptHistory: (workspaceId: string, options: { limit?: number; signal?: AbortSignal } = {}) => {
const params = new URLSearchParams();
if (options.limit !== undefined) params.set("limit", String(options.limit));
const query = params.size ? `?${params.toString()}` : "";
return request<PromptHistoryResponse>(
`/api/v1/workspaces/${encodeURIComponent(workspaceId)}/prompt-history${query}`,
{ signal: options.signal },
);
},
devices: (signal?: AbortSignal) => request<DeviceInfo[]>("/api/v1/devices", { signal }), devices: (signal?: AbortSignal) => request<DeviceInfo[]>("/api/v1/devices", { signal }),
revokeDevice: (deviceId: string, signal?: AbortSignal) => revokeDevice: (deviceId: string, signal?: AbortSignal) =>
request<void>(`/api/v1/devices/${encodeURIComponent(deviceId)}`, { method: "DELETE", signal }), request<void>(`/api/v1/devices/${encodeURIComponent(deviceId)}`, { method: "DELETE", signal }),
+27 -6
View File
@@ -355,6 +355,15 @@ function matchIndex(index: PoolIndex, candidate: Entry, isTaken: (at: number) =>
* then by `(role, text)` when the ids differ (the snapshot carries synthetic * then by `(role, text)` when the ids differ (the snapshot carries synthetic
* `m<N>` ids while the pages carry pi's raw entry ids). The historical position * `m<N>` ids while the pages carry pi's raw entry ids). The historical position
* is kept so the transcript never re-orders, and each message renders once. * is kept so the transcript never re-orders, and each message renders once.
*
* The two inputs are windows over the same transcript, not a page plus a tail:
* the plugin's snapshot carries the whole (bounded) session, while the first
* REST page is only the newest entries. A live entry without a counterpart is
* therefore inserted where its neighbours put it — before the history entry of
* the next match, or appended only when it follows every match. Appending all
* unmatched entries instead would move messages older than the page to the end
* of the stream, so the transcript would stop on an old message and the newest
* ones (already spliced into the page) would sit far above.
*/ */
export function mergeEntries(history: Entry[], live: Entry[]): Entry[] { export function mergeEntries(history: Entry[], live: Entry[]): Entry[] {
if (!history.length) return live; if (!history.length) return live;
@@ -365,18 +374,30 @@ export function mergeEntries(history: Entry[], live: Entry[]): Entry[] {
const historyIndex = indexPool(history); const historyIndex = indexPool(history);
const claimed = new Set<number>(); const claimed = new Set<number>();
const replaces = new Map<number, Entry>(); const replaces = new Map<number, Entry>();
/** Unmatched live entries keyed by the history index they precede (0..history.length). */
const inserts = new Map<number, Entry[]>();
let anchor = 0;
for (const entry of live) { for (const entry of live) {
const match = matchIndex(historyIndex, entry, (at) => claimed.has(at)); const match = matchIndex(historyIndex, entry, (at) => claimed.has(at));
if (match < 0) continue; if (match < 0) {
const bucket = inserts.get(anchor);
if (bucket) bucket.push(entry);
else inserts.set(anchor, [entry]);
continue;
}
claimed.add(match); claimed.add(match);
replaces.set(match, entry); replaces.set(match, entry);
anchor = Math.max(anchor, match + 1);
} }
const merged: Entry[] = history.map((entry, index) => replaces.get(index) ?? entry); const merged: Entry[] = [];
const rendered = new Set<Entry>(replaces.values()); history.forEach((entry, index) => {
for (const entry of live) { const bucket = inserts.get(index);
if (!rendered.has(entry)) merged.push(entry); if (bucket) merged.push(...bucket);
} merged.push(replaces.get(index) ?? entry);
});
const trailing = inserts.get(history.length);
if (trailing) merged.push(...trailing);
return merged; return merged;
} }
+5
View File
@@ -393,6 +393,10 @@
"chat.web.sources.other": "{n} sources", "chat.web.sources.other": "{n} sources",
"chat.workspace": "Workspace", "chat.workspace": "Workspace",
"chat.workspaceCrumb": "Workspace", "chat.workspaceCrumb": "Workspace",
"chat.workspaceSearch": "Search workspaces",
"chat.workspaceSearchAria": "Search workspaces by name or path",
"chat.workspaceSearchClear": "Clear search",
"chat.workspaceSearchNoMatch": "No workspace matches “{query}”",
"chat.workspaceSwitch": "Switch workspace", "chat.workspaceSwitch": "Switch workspace",
"chat.workspaceSwitchAria": "Workspace: {name}. Click to switch", "chat.workspaceSwitchAria": "Workspace: {name}. Click to switch",
"chat.you": "You", "chat.you": "You",
@@ -566,6 +570,7 @@
"status.cores": "cores", "status.cores": "cores",
"status.load": "load", "status.load": "load",
"status.created": "Created", "status.created": "Created",
"status.daemonUptime": "Daemon uptime",
"status.deviceCount": "{n}", "status.deviceCount": "{n}",
"status.devices": "Paired devices", "status.devices": "Paired devices",
"status.devicesError": "Failed to load paired devices", "status.devicesError": "Failed to load paired devices",
+5
View File
@@ -393,6 +393,10 @@
"chat.web.sources.other": "{n} 个来源", "chat.web.sources.other": "{n} 个来源",
"chat.workspace": "工作空间", "chat.workspace": "工作空间",
"chat.workspaceCrumb": "工作空间", "chat.workspaceCrumb": "工作空间",
"chat.workspaceSearch": "搜索工作空间",
"chat.workspaceSearchAria": "按名称或路径搜索工作空间",
"chat.workspaceSearchClear": "清除搜索",
"chat.workspaceSearchNoMatch": "没有匹配“{query}”的工作空间",
"chat.workspaceSwitch": "切换工作空间", "chat.workspaceSwitch": "切换工作空间",
"chat.workspaceSwitchAria": "工作空间:{name},点击切换", "chat.workspaceSwitchAria": "工作空间:{name},点击切换",
"chat.you": "你", "chat.you": "你",
@@ -566,6 +570,7 @@
"status.cores": "核心", "status.cores": "核心",
"status.load": "负载", "status.load": "负载",
"status.created": "创建", "status.created": "创建",
"status.daemonUptime": "守护进程运行时长",
"status.deviceCount": "{n} 台", "status.deviceCount": "{n} 台",
"status.devices": "已配对设备", "status.devices": "已配对设备",
"status.devicesError": "加载已配对设备失败", "status.devicesError": "加载已配对设备失败",
+12
View File
@@ -37,6 +37,7 @@ import { useSessionHistory } from "@/features/chat/history";
import { ChatLayout } from "@/features/chat/layout"; import { ChatLayout } from "@/features/chat/layout";
import { MessageStream } from "@/features/chat/message-stream"; import { MessageStream } from "@/features/chat/message-stream";
import { onSessionMigration, replaceChatUrl } from "@/features/chat/migration"; import { onSessionMigration, replaceChatUrl } from "@/features/chat/migration";
import { usePromptHistory } from "@/features/chat/prompt-history-feed";
import { DispatchModal, RenameDialog, TaskOutputModal, type DispatchInput } from "@/features/chat/modals"; import { DispatchModal, RenameDialog, TaskOutputModal, type DispatchInput } from "@/features/chat/modals";
import { SessionTray } from "@/features/chat/session-tray"; import { SessionTray } from "@/features/chat/session-tray";
import { sessionTitle } from "@/features/chat/session-title"; import { sessionTitle } from "@/features/chat/session-title";
@@ -51,6 +52,7 @@ import { SessionTree } from "@/features/chat/session-tree";
import { SubagentView } from "@/features/chat/subagent-view"; import { SubagentView } from "@/features/chat/subagent-view";
import { useChatStore, type TrayTab } from "@/features/chat/store"; import { useChatStore, type TrayTab } from "@/features/chat/store";
import { Telemetry } from "@/features/chat/telemetry"; import { Telemetry } from "@/features/chat/telemetry";
import { markWorkspaceUsed } from "@/features/chat/workspace-order";
import "@/styles/pages/chat.css"; import "@/styles/pages/chat.css";
@@ -106,6 +108,11 @@ function ChatExperience({ sessionId }: { sessionId?: string }) {
workspaces[0]?.workspaceId; workspaces[0]?.workspaceId;
const sessionsQuery = useChatSessions(workspaceId, paired); const sessionsQuery = useChatSessions(workspaceId, paired);
// "Recently used" for the workspace picker: whichever workspace is active
// (deep link, picker pick, default choice) gets a browser-local stamp.
useEffect(() => {
if (workspaceId) markWorkspaceUsed(workspaceId);
}, [workspaceId]);
const sessions = sessionsQuery.sessions; const sessions = sessionsQuery.sessions;
const sessionIds = useMemo(() => sessions.map((session) => session.sessionId), [sessions]); const sessionIds = useMemo(() => sessions.map((session) => session.sessionId), [sessions]);
useChatSocket(workspaceId, sessionIds, paired); useChatSocket(workspaceId, sessionIds, paired);
@@ -137,6 +144,10 @@ function ChatExperience({ sessionId }: { sessionId?: string }) {
active?.workspaceId ?? workspaceId, active?.workspaceId ?? workspaceId,
); );
const models = useChatModels(workspaceId, paired); const models = useChatModels(workspaceId, paired);
// Composer ↑/↓ recall: the plugin owns the archive, the daemon relays a
// live-only read, and the browser mirror covers a cold workspace or an old
// plugin. Never spawns an nvim (see docs/prompt-history.md).
const promptHistory = usePromptHistory(workspaceId, paired);
const workspace = workspaces.find((item) => item.workspaceId === workspaceId); const workspace = workspaces.find((item) => item.workspaceId === workspaceId);
// pi2.nvim's placeholder vocabulary, and the display title of the routed // pi2.nvim's placeholder vocabulary, and the display title of the routed
// session: name → first message → `(unnamed)`. Never the session id. // session: name → first message → `(unnamed)`. Never the session id.
@@ -718,6 +729,7 @@ function ChatExperience({ sessionId }: { sessionId?: string }) {
connected={connected} connected={connected}
paired={paired} paired={paired}
sending={sending} sending={sending}
history={promptHistory.source}
onSend={(text, images, mode) => void handleSend(text, images, mode)} onSend={(text, images, mode) => void handleSend(text, images, mode)}
onAbort={() => { onAbort={() => {
setSending(null); setSending(null);
+13 -4
View File
@@ -25,7 +25,8 @@ import {
type PairMeta, type PairMeta,
type PairTarget, type PairTarget,
} from "@/features/connect/pairing"; } from "@/features/connect/pairing";
import { deriveServerIdentity, formatUptime, type InfoExtras } from "@/features/status/server"; import { deriveServerIdentity, type InfoExtras } from "@/features/status/server";
import { LiveUptime } from "@/features/status/uptime";
import { useInfoQuery } from "@/features/status/queries"; import { useInfoQuery } from "@/features/status/queries";
import { getDeviceToken, setDeviceToken } from "@/lib/api"; import { getDeviceToken, setDeviceToken } from "@/lib/api";
import { useConnectionStore } from "@/stores/connection"; import { useConnectionStore } from "@/stores/connection";
@@ -104,8 +105,14 @@ export function ConnectPage() {
}); });
const defaultDeviceName = t("connect.defaultDeviceName"); const defaultDeviceName = t("connect.defaultDeviceName");
const osLabel = info.data?.os || info.data?.platform || server.os || "—"; const osLabel = info.data?.os || info.data?.platform || server.os || "—";
const uptimeSeconds = // Host uptime: this row labels it "uptime", and pinning it to the daemon
typeof info.data?.uptimeMs === "number" ? info.data.uptimeMs / 1000 : server.uptimeSec; // process made a five-day-old box read "3m" after a restart.
const uptimeMs =
typeof info.data?.hostUptimeMs === "number"
? info.data.hostUptimeMs
: server.hostUptimeSec != null
? server.hostUptimeSec * 1000
: null;
const defaultPort = defaultPortFor(info.data?.port ?? server.port); const defaultPort = defaultPortFor(info.data?.port ?? server.port);
/** /**
@@ -286,7 +293,9 @@ export function ConnectPage() {
{info.data?.pluginVersion || meta?.server?.pluginVersion || "—"} {info.data?.pluginVersion || meta?.server?.pluginVersion || "—"}
</KV> </KV>
<KV label={t("connect.os")}>{osLabel}</KV> <KV label={t("connect.os")}>{osLabel}</KV>
<KV label={t("connect.uptime")}>{formatUptime(uptimeSeconds)}</KV> <KV label={t("connect.uptime")}>
<LiveUptime ms={uptimeMs} />
</KV>
<p className="cn-note"> <p className="cn-note">
<span className="cn-ico"> <span className="cn-ico">
<Icon name="alert" /> <Icon name="alert" />
+21 -5
View File
@@ -1,5 +1,6 @@
import { create } from "zustand"; import { create } from "zustand";
import { acknowledge, forget, move, suppressAcknowledged } from "@/features/chat/acknowledged";
import type { SessionState } from "@/lib/protocol"; import type { SessionState } from "@/lib/protocol";
export interface SessionsStore { export interface SessionsStore {
@@ -41,7 +42,7 @@ export const useSessionsStore = create<SessionsStore>((set, get) => ({
setSessions: (workspaceId, sessions) => setSessions: (workspaceId, sessions) =>
set((state) => ({ set((state) => ({
byWorkspace: { ...state.byWorkspace, [workspaceId]: sessions }, byWorkspace: { ...state.byWorkspace, [workspaceId]: sessions.map(suppressAcknowledged) },
status: "idle", status: "idle",
error: null, error: null,
})), })),
@@ -51,7 +52,12 @@ export const useSessionsStore = create<SessionsStore>((set, get) => ({
const list = state.byWorkspace[session.workspaceId] ?? []; const list = state.byWorkspace[session.workspaceId] ?? [];
const index = list.findIndex((s) => s.sessionId === session.sessionId); const index = list.findIndex((s) => s.sessionId === session.sessionId);
if (index === -1) { if (index === -1) {
return { byWorkspace: { ...state.byWorkspace, [session.workspaceId]: [...list, session] } }; return {
byWorkspace: {
...state.byWorkspace,
[session.workspaceId]: [...list, suppressAcknowledged(session)],
},
};
} }
// Tree metadata is list metadata: a live update (`pi2:session`, // Tree metadata is list metadata: a live update (`pi2:session`,
// reducer events, a rename) carries no `parentId`/`visible`/`task`/ // reducer events, a rename) carries no `parentId`/`visible`/`task`/
@@ -69,7 +75,7 @@ export const useSessionsStore = create<SessionsStore>((set, get) => ({
createdAt: session.createdAt !== undefined ? session.createdAt : previous.createdAt, createdAt: session.createdAt !== undefined ? session.createdAt : previous.createdAt,
lastActiveAt: session.lastActiveAt !== undefined ? session.lastActiveAt : previous.lastActiveAt, lastActiveAt: session.lastActiveAt !== undefined ? session.lastActiveAt : previous.lastActiveAt,
}; };
const next = list.map((s, i) => (i === index ? merged : s)); const next = list.map((s, i) => (i === index ? suppressAcknowledged(merged) : s));
return { byWorkspace: { ...state.byWorkspace, [session.workspaceId]: next } }; return { byWorkspace: { ...state.byWorkspace, [session.workspaceId]: next } };
}), }),
@@ -108,6 +114,9 @@ export const useSessionsStore = create<SessionsStore>((set, get) => ({
byWorkspace[workspaceId] = next; byWorkspace[workspaceId] = next;
} }
if (!moved) return state; if (!moved) return state;
// An acknowledgement given on a `tmp-N` row belongs to the real id
// once the plugin reports it; keep it across the migration.
move(from, to);
return { return {
byWorkspace, byWorkspace,
selectedSessionId: state.selectedSessionId === from ? to : state.selectedSessionId, selectedSessionId: state.selectedSessionId === from ? to : state.selectedSessionId,
@@ -116,6 +125,7 @@ export const useSessionsStore = create<SessionsStore>((set, get) => ({
removeSession: (sessionId) => removeSession: (sessionId) =>
set((state) => { set((state) => {
forget(sessionId);
const byWorkspace: Record<string, SessionState[]> = {}; const byWorkspace: Record<string, SessionState[]> = {};
for (const [workspaceId, list] of Object.entries(state.byWorkspace)) { for (const [workspaceId, list] of Object.entries(state.byWorkspace)) {
byWorkspace[workspaceId] = list byWorkspace[workspaceId] = list
@@ -129,7 +139,12 @@ export const useSessionsStore = create<SessionsStore>((set, get) => ({
selectSession: (selectedSessionId) => set({ selectedSessionId }), selectSession: (selectedSessionId) => set({ selectedSessionId }),
markSeen: (sessionId) => markSeen: (sessionId) => {
// Remember *which* notification this is before clearing it: the plugin
// keeps raising `done`/`error` until nvim's TabEnter, so a later snapshot
// (reload / reconnect) must not revive a blink the user already consumed.
const current = get().getSession(sessionId);
if (current) acknowledge(current);
set((state) => { set((state) => {
let changed = false; let changed = false;
const byWorkspace: Record<string, SessionState[]> = {}; const byWorkspace: Record<string, SessionState[]> = {};
@@ -147,7 +162,8 @@ export const useSessionsStore = create<SessionsStore>((set, get) => ({
} }
// Nothing to consume: keep the state object so zustand skips the render. // Nothing to consume: keep the state object so zustand skips the render.
return changed ? { byWorkspace } : state; return changed ? { byWorkspace } : state;
}), });
},
listFor: (workspaceId) => get().byWorkspace[workspaceId] ?? [], listFor: (workspaceId) => get().byWorkspace[workspaceId] ?? [],
+66 -9
View File
@@ -158,26 +158,82 @@
right: 8px; right: 8px;
top: 42px; top: 42px;
z-index: 12; z-index: 12;
padding: 4px; display: flex;
flex-direction: column;
background: var(--popover); background: var(--popover);
color: var(--popover-foreground); color: var(--popover-foreground);
border: 1px solid var(--border); border: 1px solid var(--border);
border-radius: var(--radius-lg); border-radius: var(--radius-lg);
box-shadow: var(--shadow-lg); box-shadow: var(--shadow-lg);
max-height: min(50vh, 22rem); max-height: min(50vh, 22rem);
overflow-y: auto; overflow: hidden;
} }
.ws-menu[hidden] { .ws-menu[hidden] {
display: none; display: none;
} }
.ws-menu__label { /* 搜索框固定在顶部,只有下面的列表滚动 */
padding: 6px 8px 4px; .ws-menu__search {
font-size: var(--fs-2xs); display: flex;
font-weight: 650; flex: none;
letter-spacing: 0.08em; align-items: center;
text-transform: uppercase; gap: 6px;
padding: 0 8px;
border-bottom: 1px solid var(--border-subtle);
}
.ws-menu__search svg {
flex: none;
width: 14px;
height: 14px;
color: var(--faint); color: var(--faint);
} }
.ws-menu__input {
flex: 1;
min-width: 0;
height: 34px;
min-height: 34px;
padding: 0;
border: 0;
background: transparent;
color: var(--foreground);
font-size: var(--fs-sm);
appearance: none;
outline: none;
}
.ws-menu__input::-webkit-search-cancel-button {
appearance: none;
}
.ws-menu__input::placeholder {
color: var(--faint);
}
.ws-menu__clear {
display: inline-flex;
flex: none;
align-items: center;
justify-content: center;
width: 20px;
height: 20px;
border-radius: var(--radius-sm);
color: var(--faint);
}
.ws-menu__clear:hover {
background: var(--surface-2);
color: var(--foreground);
}
.ws-menu__clear svg {
width: 12px;
height: 12px;
}
.ws-menu__list {
flex: 1;
min-height: 0;
overflow-y: auto;
padding: 4px;
}
.ws-menu__empty {
padding: 10px 8px;
color: var(--faint);
font-size: var(--fs-sm);
}
.ws-menu__item { .ws-menu__item {
display: flex; display: flex;
align-items: center; align-items: center;
@@ -191,7 +247,8 @@
color: var(--secondary-foreground); color: var(--secondary-foreground);
} }
.ws-menu__item:hover, .ws-menu__item:hover,
.ws-menu__item:focus-visible { .ws-menu__item:focus-visible,
.ws-menu__item:focus {
background: var(--surface-2); background: var(--surface-2);
color: var(--foreground); color: var(--foreground);
outline: none; outline: none;
+19
View File
@@ -104,6 +104,25 @@
gap: 4px; gap: 4px;
min-width: 0; min-width: 0;
} }
/* Multi-filesystem disk tile: one quiet row per mount, worst first. */
.status-tile .disk-rows {
display: flex;
flex-direction: column;
gap: 2px;
width: 100%;
min-width: 0;
}
.status-tile .disk-row {
display: flex;
align-items: baseline;
justify-content: space-between;
gap: 6px;
min-width: 0;
}
.status-tile .disk-row__label { min-width: 0; }
.status-tile .disk-row__pct { flex: none; font-weight: 600; font-variant-numeric: tabular-nums; }
.status-tile .disk-row__pct.is-warn { color: var(--warn); }
.status-tile .disk-row__pct.is-err { color: var(--err); }
/* 3px meter: a quiet hairline rather than a progress bar */ /* 3px meter: a quiet hairline rather than a progress bar */
.meter { .meter {
+194
View File
@@ -2,6 +2,7 @@ import { fireEvent, render, screen } from "@testing-library/react";
import { beforeAll, describe, expect, it, vi } from "vitest"; import { beforeAll, describe, expect, it, vi } from "vitest";
import { Composer, type ComposerProps } from "@/features/chat/composer"; import { Composer, type ComposerProps } from "@/features/chat/composer";
import { readPromptHistory, rememberPrompt } from "@/features/chat/prompt-history";
import { setLanguage } from "@/lib/i18n"; import { setLanguage } from "@/lib/i18n";
import { sessionFixture } from "./chat-fixtures"; import { sessionFixture } from "./chat-fixtures";
@@ -215,3 +216,196 @@ describe("composer", () => {
expect(screen.queryByText(/prototype demo only/i)).not.toBeInTheDocument(); expect(screen.queryByText(/prototype demo only/i)).not.toBeInTheDocument();
}); });
}); });
/**
* Prompt recall (↑/↓), the web port of pi2.nvim's prompt-buffer history. The
* store/nav contract itself is covered in `prompt-history.test.ts`; here we
* only pin the keyboard rules the composer adds on top of it.
*/
describe("composer prompt history", () => {
/** Place a collapsed caret, so the ArrowUp/ArrowDown line rule is explicit. */
function caretAt(element: HTMLTextAreaElement, at: number): void {
element.setSelectionRange(at, at);
}
function input(): HTMLTextAreaElement {
return screen.getByTestId("composer-input") as HTMLTextAreaElement;
}
it("recalls older prompts on ArrowUp and the draft past the newest", () => {
rememberPrompt("w1", "first");
rememberPrompt("w1", "second");
renderComposer(sessionFixture({ status: "idle" }));
const textarea = input();
fireEvent.change(textarea, { target: { value: "my draft" } });
caretAt(textarea, 0);
// A recall swallows the key (the caret must not also move).
expect(fireEvent.keyDown(textarea, { key: "ArrowUp" })).toBe(false);
expect(textarea).toHaveValue("second");
expect(fireEvent.keyDown(textarea, { key: "ArrowUp" })).toBe(false);
expect(textarea).toHaveValue("first");
// At the oldest entry the key is left to the caret again.
expect(fireEvent.keyDown(textarea, { key: "ArrowUp" })).toBe(true);
expect(textarea).toHaveValue("first");
fireEvent.keyDown(textarea, { key: "ArrowDown" });
expect(textarea).toHaveValue("second");
// Past the newest entry the in-progress draft is restored.
fireEvent.keyDown(textarea, { key: "ArrowDown" });
expect(textarea).toHaveValue("my draft");
// Recall is over: ↓ is a plain caret move again.
expect(fireEvent.keyDown(textarea, { key: "ArrowDown" })).toBe(true);
expect(textarea).toHaveValue("my draft");
});
it("leaves ArrowUp to the caret inside a multi-line draft", () => {
rememberPrompt("w1", "old prompt");
renderComposer(sessionFixture({ status: "idle" }));
const textarea = input();
const draft = "line1\nline2";
fireEvent.change(textarea, { target: { value: draft } });
// Caret on the second line: ↑ must move the caret, not recall.
caretAt(textarea, draft.length);
expect(fireEvent.keyDown(textarea, { key: "ArrowUp" })).toBe(true);
expect(textarea).toHaveValue(draft);
// Caret on the first line: ↑ recalls.
caretAt(textarea, 0);
expect(fireEvent.keyDown(textarea, { key: "ArrowUp" })).toBe(false);
expect(textarea).toHaveValue("old prompt");
});
it("leaves ArrowDown to the caret above the last line", () => {
rememberPrompt("w1", "archived");
renderComposer(sessionFixture({ status: "idle" }));
const textarea = input();
const draft = "draft\ntail";
fireEvent.change(textarea, { target: { value: draft } });
caretAt(textarea, 2); // still on the first line
expect(fireEvent.keyDown(textarea, { key: "ArrowDown" })).toBe(true);
expect(textarea).toHaveValue(draft);
});
it("walks back out of a recalled multi-line entry from its last line", () => {
rememberPrompt("w1", "line1\nline2");
renderComposer(sessionFixture({ status: "idle" }));
const textarea = input();
fireEvent.change(textarea, { target: { value: "draft" } });
caretAt(textarea, 0);
expect(fireEvent.keyDown(textarea, { key: "ArrowUp" })).toBe(false);
expect(textarea).toHaveValue("line1\nline2");
// The caret is parked on the entry's last line, so ↓ leaves recall.
expect(fireEvent.keyDown(textarea, { key: "ArrowDown" })).toBe(false);
expect(textarea).toHaveValue("draft");
});
it("always recalls on Ctrl+P / Ctrl+N", () => {
rememberPrompt("w1", "alpha");
rememberPrompt("w1", "beta");
renderComposer(sessionFixture({ status: "idle" }));
const textarea = input();
fireEvent.change(textarea, { target: { value: "draft text" } });
caretAt(textarea, 3); // mid-line: the caret rule does not apply
fireEvent.keyDown(textarea, { key: "p", ctrlKey: true });
expect(textarea).toHaveValue("beta");
fireEvent.keyDown(textarea, { key: "p", ctrlKey: true });
expect(textarea).toHaveValue("alpha");
fireEvent.keyDown(textarea, { key: "n", ctrlKey: true });
expect(textarea).toHaveValue("beta");
fireEvent.keyDown(textarea, { key: "n", ctrlKey: true });
expect(textarea).toHaveValue("draft text");
});
it("moves the caret to the end of a recalled prompt", () => {
rememberPrompt("w1", "remembered prompt");
renderComposer(sessionFixture({ status: "idle" }));
const textarea = input();
fireEvent.keyDown(textarea, { key: "ArrowUp" });
expect(textarea).toHaveValue("remembered prompt");
expect(textarea.selectionStart).toBe("remembered prompt".length);
expect(textarea.selectionEnd).toBe("remembered prompt".length);
});
it("ends recall when the user edits by hand", () => {
rememberPrompt("w1", "older");
rememberPrompt("w1", "newer");
renderComposer(sessionFixture({ status: "idle" }));
const textarea = input();
fireEvent.keyDown(textarea, { key: "ArrowUp" });
expect(textarea).toHaveValue("newer");
fireEvent.change(textarea, { target: { value: "newer, edited" } });
caretAt(textarea, "newer, edited".length);
// No longer browsing: ↓ must not replace the edit with a stale entry.
expect(fireEvent.keyDown(textarea, { key: "ArrowDown" })).toBe(true);
expect(textarea).toHaveValue("newer, edited");
// ↓ again starts from the newest entry, not from where recall stopped.
expect(fireEvent.keyDown(textarea, { key: "ArrowUp" })).toBe(false);
expect(textarea).toHaveValue("newer");
});
it("remembers each send in its own workspace, trimmed and deduped", () => {
const { onSend, unmount } = renderComposer(sessionFixture({ status: "idle" }));
const textarea = input();
fireEvent.change(textarea, { target: { value: " padded " } });
fireEvent.keyDown(textarea, { key: "Enter" });
expect(onSend).toHaveBeenCalledWith("padded", [], undefined);
expect(readPromptHistory("w1")).toEqual(["padded"]);
unmount();
// Another workspace shares no history…
const other = renderComposer(sessionFixture({ status: "idle", workspaceId: "w2" }));
fireEvent.change(input(), { target: { value: "from w2" } });
fireEvent.keyDown(input(), { key: "Enter" });
expect(other.onSend).toHaveBeenCalledWith("from w2", [], undefined);
expect(readPromptHistory("w2")).toEqual(["from w2"]);
expect(readPromptHistory("w1")).toEqual(["padded"]);
other.unmount();
// …and the first one still recalls its own send.
renderComposer(sessionFixture({ status: "idle" }));
expect(fireEvent.keyDown(input(), { key: "ArrowUp" })).toBe(false);
expect(input()).toHaveValue("padded");
});
it("does not let an IME own-up compose recall its candidate list", () => {
rememberPrompt("w1", "archived");
renderComposer(sessionFixture({ status: "idle" }));
const textarea = input();
fireEvent.change(textarea, { target: { value: "nihao" } });
caretAt(textarea, 5);
expect(fireEvent.keyDown(textarea, { key: "ArrowUp", isComposing: true })).toBe(true);
expect(textarea).toHaveValue("nihao");
});
it("recalls from an injected feed and records sends into it", () => {
// `pages/chat.tsx` injects the plugin-backed feed; the composer must neither
// read the mirror nor decide where a send is recorded.
const entries: string[] = ["typed in nvim"];
const remember = vi.fn((text: string) => entries.push(text));
const { onSend } = renderComposer(sessionFixture({ status: "idle" }), {
history: { entries: () => entries, remember },
});
const textarea = input();
expect(fireEvent.keyDown(textarea, { key: "ArrowUp" })).toBe(false);
expect(textarea).toHaveValue("typed in nvim");
fireEvent.keyDown(textarea, { key: "Enter" });
expect(onSend).toHaveBeenCalledWith("typed in nvim", [], undefined);
expect(remember).toHaveBeenCalledWith("typed in nvim");
// The mirror stays untouched: the injected feed owns the archive now.
expect(readPromptHistory("w1")).toEqual([]);
});
});
+24
View File
@@ -148,6 +148,30 @@ describe("history entry projection", () => {
expect(merged[0]?.ts).toBe(TS); expect(merged[0]?.ts).toBe(TS);
}); });
it("inserts live entries older than the history window before it, never after the newest page", () => {
// The plugin's snapshot carries the whole transcript; the first REST page is
// only the newest window. The live entries that precede that window are
// older than every history entry, so appending them would end the
// transcript on an old message and hide everything after it.
const history = projectEntries([
{ type: "message", id: "h3", message: { role: "user", content: "third", timestamp: TS + 4 } },
{
type: "message",
id: "h4",
message: { role: "assistant", timestamp: TS + 5, content: [{ type: "text", text: "fourth" }] },
},
]);
const live = [
entryFixture({ id: "m1", role: "user", ts: TS, blocks: [{ type: "text", text: "first" }] }),
entryFixture({ id: "m2", role: "assistant", ts: TS + 1, blocks: [{ type: "text", text: "second" }] }),
entryFixture({ id: "m3", role: "user", ts: TS + 4, blocks: [{ type: "text", text: "third" }] }),
entryFixture({ id: "m4", role: "assistant", ts: TS + 5, blocks: [{ type: "text", text: "fourth" }] }),
];
const merged = mergeEntries(history, live);
expect(merged.map((entry) => entry.id)).toEqual(["m1", "m2", "m3", "m4"]);
});
it("keeps live-only entries and drops raw duplicates when prepending a page", () => { it("keeps live-only entries and drops raw duplicates when prepending a page", () => {
const live = [ const live = [
entryFixture({ id: "m1", role: "user", ts: TS, blocks: [{ type: "text", text: "hello" }] }), entryFixture({ id: "m1", role: "user", ts: TS, blocks: [{ type: "text", text: "hello" }] }),
+169
View File
@@ -0,0 +1,169 @@
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { act, render, waitFor } from "@testing-library/react";
import { describe, expect, it } from "vitest";
import {
normalizeEntries,
type PromptHistoryFeed,
PROMPT_HISTORY_FETCH_LIMIT,
usePromptHistory,
} from "@/features/chat/prompt-history-feed";
import { readPromptHistory, rememberPrompt } from "@/features/chat/prompt-history";
import { mockApi } from "./helpers/api-mock";
const PATH = "/api/v1/workspaces/w1/prompt-history";
/**
* Mount the hook and keep the newest snapshot. The feed is a plain object, so the
* tests assert on it directly instead of through rendered markup (the composer is
* the only consumer that renders anything).
*/
function renderFeed(workspaceId: string | undefined, enabled = true) {
const queryClient = new QueryClient({
defaultOptions: { queries: { retry: false, gcTime: 0, staleTime: 0, refetchOnWindowFocus: false } },
});
const feeds: PromptHistoryFeed[] = [];
function Probe() {
feeds.push(usePromptHistory(workspaceId, enabled));
return <div data-testid="feed" />;
}
const utils = render(
<QueryClientProvider client={queryClient}>
<Probe />
</QueryClientProvider>,
);
const feed = (): PromptHistoryFeed => {
const current = feeds[feeds.length - 1];
if (!current) throw new Error("the probe never rendered");
return current;
};
return { ...utils, queryClient, feed };
}
const remote = (body: Record<string, unknown>) => [{ method: "GET" as const, path: PATH, handler: () => ({ body }) }];
describe("prompt history feed: relayed from the plugin", () => {
it("recalls the plugin's entries when it is live and capable", async () => {
const fetchMock = mockApi(
remote({
v: 1,
workspaceId: "w1",
live: true,
supported: true,
entries: ["oldest", "middle", "newest"],
}),
);
const { feed } = renderFeed("w1");
await waitFor(() => expect(feed().remote).toBe(true));
expect(feed().live).toBe(true);
expect(feed().source.entries()).toEqual(["oldest", "middle", "newest"]);
// One cheap workspace-scoped read, no per-keystroke traffic.
expect(fetchMock).toHaveBeenCalledTimes(1);
expect(String((fetchMock.mock.calls[0]?.[0] as RequestInfo))).toContain(
`limit=${PROMPT_HISTORY_FETCH_LIMIT}`,
);
});
it("records a send into the mirror and appends it optimistically", async () => {
mockApi(
remote({ v: 1, workspaceId: "w1", live: true, supported: true, entries: ["first"] }),
);
const { feed } = renderFeed("w1");
await waitFor(() => expect(feed().remote).toBe(true));
act(() => feed().source.remember("second"));
// Recall sees it without waiting for a refetch…
await waitFor(() => expect(feed().source.entries()).toEqual(["first", "second"]));
// …and the fallback mirror is warm for the moment the plugin goes away.
expect(readPromptHistory("w1")).toEqual(["first", "second"]);
});
it("drops unusable entries from the relay payload", async () => {
mockApi(
remote({
live: true,
supported: true,
entries: ["keep", 7, null, " ", "also keep"],
}),
);
const { feed } = renderFeed("w1");
await waitFor(() => expect(feed().remote).toBe(true));
expect(feed().source.entries()).toEqual(["keep", "also keep"]);
});
it("refreshes the fallback mirror from the relay", async () => {
mockApi(
remote({ v: 1, workspaceId: "w1", live: true, supported: true, entries: ["typed in nvim"] }),
);
const { feed } = renderFeed("w1");
await waitFor(() => expect(feed().remote).toBe(true));
// The plugin's history is now the fallback's starting point, so a lost
// plugin (or an older daemon) still recalls what nvim recorded.
await waitFor(() => expect(readPromptHistory("w1")).toEqual(["typed in nvim"]));
});
});
describe("prompt history feed: browser mirror fallback", () => {
it("falls back when no plugin is connected for the workspace", async () => {
rememberPrompt("w1", "from this browser");
mockApi(remote({ v: 1, workspaceId: "w1", live: false, supported: false, entries: [] }));
const { feed } = renderFeed("w1");
await waitFor(() => expect(feed().live).toBe(false));
expect(feed().remote).toBe(false);
expect(feed().source.entries()).toEqual(["from this browser"]);
});
it("falls back when the live plugin is older than the capability", async () => {
rememberPrompt("w1", "mirror only");
mockApi(remote({ v: 1, workspaceId: "w1", live: true, supported: false, entries: [] }));
const { feed } = renderFeed("w1");
await waitFor(() => expect(feed().live).toBe(true));
expect(feed().remote).toBe(false);
expect(feed().source.entries()).toEqual(["mirror only"]);
});
it("falls back when the daemon predates the endpoint (404), without retrying", async () => {
rememberPrompt("w1", "mirror only");
const fetchMock = mockApi([
{ method: "GET", path: PATH, handler: () => ({ status: 404, body: { code: "E_NOT_FOUND" } }) },
]);
const { feed } = renderFeed("w1");
await waitFor(() => expect(fetchMock).toHaveBeenCalled());
// A 404 is a permanent "no relay", not a transient failure: one attempt.
expect(fetchMock).toHaveBeenCalledTimes(1);
expect(feed().remote).toBe(false);
expect(feed().source.entries()).toEqual(["mirror only"]);
});
it("keeps working unpaired: no fetch, mirror only", () => {
const fetchMock = mockApi([]);
rememberPrompt("default", "offline draft");
const { feed } = renderFeed("", false);
expect(fetchMock).not.toHaveBeenCalled();
expect(feed().remote).toBe(false);
expect(feed().source.entries()).toEqual(["offline draft"]);
});
});
describe("normalizeEntries", () => {
it("keeps only non-blank strings", () => {
expect(normalizeEntries(undefined)).toEqual([]);
expect(normalizeEntries("nope")).toEqual([]);
expect(normalizeEntries(["a", 1, null, " ", "b"])).toEqual(["a", "b"]);
});
it("keeps the newest entries when the payload is long", () => {
const many = Array.from({ length: 600 }, (_, index) => `e${index}`);
const entries = normalizeEntries(many);
expect(entries).toHaveLength(500);
expect(entries[entries.length - 1]).toBe("e599");
});
});
+230
View File
@@ -0,0 +1,230 @@
import { beforeEach, describe, expect, it } from "vitest";
import {
appendEntry,
clearPromptHistory,
DEFAULT_SCOPE,
HISTORY_LIMIT,
historyScope,
localPromptHistorySource,
PROMPT_HISTORY_KEY,
PromptHistoryNav,
readPromptHistory,
relayedPromptHistorySource,
rememberPrompt,
WORKSPACE_LIMIT,
} from "@/features/chat/prompt-history";
/** Seed one workspace without going through the composer. */
function seed(scope: string, ...entries: string[]): void {
for (const entry of entries) rememberPrompt(scope, entry);
}
function writeRaw(value: string): void {
localStorage.setItem(PROMPT_HISTORY_KEY, value);
}
beforeEach(() => {
localStorage.clear();
});
describe("prompt history: store", () => {
it("starts empty", () => {
expect(readPromptHistory("w1")).toEqual([]);
});
it("stores entries newest-last", () => {
seed("w1", "one", "two");
expect(readPromptHistory("w1")).toEqual(["one", "two"]);
});
it("ignores empty and whitespace-only entries", () => {
seed("w1", "", " ", "\n\t ");
expect(readPromptHistory("w1")).toEqual([]);
});
it("dedupes consecutive duplicates but keeps a non-consecutive repeat", () => {
seed("w1", "same", "same", "other", "same");
expect(readPromptHistory("w1")).toEqual(["same", "other", "same"]);
});
it("preserves multi-line entries", () => {
seed("w1", "line1\nline2\nline3");
expect(readPromptHistory("w1")).toEqual(["line1\nline2\nline3"]);
});
it("drops the oldest entry past the cap", () => {
for (let index = 1; index <= HISTORY_LIMIT + 5; index += 1) rememberPrompt("w1", `e${index}`);
const entries = readPromptHistory("w1");
expect(entries).toHaveLength(HISTORY_LIMIT);
expect(entries[0]).toBe("e6");
expect(entries[entries.length - 1]).toBe(`e${HISTORY_LIMIT + 5}`);
});
it("isolates workspaces", () => {
seed("w1", "from-w1");
expect(readPromptHistory("w2")).toEqual([]);
});
it("drops the least recently used workspace past the cap", () => {
for (let index = 0; index < WORKSPACE_LIMIT; index += 1) seed(`w${index}`, `p${index}`);
// Touch the oldest again: it must survive the next trim, `w1` must not.
seed("w0", "again");
seed("new", "fresh");
expect(readPromptHistory("w0")).toEqual(["p0", "again"]);
expect(readPromptHistory("w1")).toEqual([]);
expect(readPromptHistory("new")).toEqual(["fresh"]);
expect(readPromptHistory("w2")).toEqual(["p2"]);
});
it("clears one workspace only", () => {
seed("w1", "keep");
seed("w2", "drop");
clearPromptHistory("w2");
expect(readPromptHistory("w1")).toEqual(["keep"]);
expect(readPromptHistory("w2")).toEqual([]);
expect(localStorage.getItem(PROMPT_HISTORY_KEY)).toContain("keep");
});
it("removes the key entirely when the last workspace is cleared", () => {
seed("w1", "only");
clearPromptHistory("w1");
expect(localStorage.getItem(PROMPT_HISTORY_KEY)).toBeNull();
});
it("tolerates corrupt storage and foreign shapes", () => {
writeRaw("{ this is not json ]");
expect(readPromptHistory("w1")).toEqual([]);
expect(rememberPrompt("w1", "recovered")).toEqual(["recovered"]);
writeRaw(JSON.stringify({ w1: "not-listed", w2: [1, "kept", null], w3: [] }));
expect(readPromptHistory("w1")).toEqual([]);
expect(readPromptHistory("w2")).toEqual(["kept"]);
expect(readPromptHistory("w3")).toEqual([]);
writeRaw(JSON.stringify(["not", "a", "document"]));
expect(readPromptHistory("w1")).toEqual([]);
});
it("round-trips through the stored document", () => {
seed("w1", "alpha", "multi\nline");
const raw = localStorage.getItem(PROMPT_HISTORY_KEY);
expect(raw).not.toBeNull();
expect(JSON.parse(raw ?? "{}")).toEqual({ w1: ["alpha", "multi\nline"] });
});
});
describe("prompt history: scope", () => {
it("uses the workspace id, else the default bucket", () => {
expect(historyScope("ws-abc")).toBe("ws-abc");
expect(historyScope(" ws-abc ")).toBe("ws-abc");
expect(historyScope("")).toBe(DEFAULT_SCOPE);
expect(historyScope(null)).toBe(DEFAULT_SCOPE);
expect(historyScope(undefined)).toBe(DEFAULT_SCOPE);
});
});
describe("prompt history: navigation", () => {
/** Cursor over the browser mirror — the fallback source. */
function localNav(scope = "w1"): PromptHistoryNav {
return new PromptHistoryNav(localPromptHistorySource(scope));
}
it("returns null on an empty store", () => {
const nav = localNav();
expect(nav.prev("draft")).toBeNull();
expect(nav.navigating()).toBe(false);
});
it("walks toward older entries and stashes the draft", () => {
seed("w1", "one", "two", "three");
const nav = localNav();
expect(nav.prev("draft")).toBe("three");
expect(nav.navigating()).toBe(true);
expect(nav.prev()).toBe("two");
expect(nav.prev()).toBe("one");
// At the oldest entry: no further change, still browsing.
expect(nav.prev()).toBeNull();
expect(nav.navigating()).toBe(true);
});
it("walks back and restores the stashed draft at the present", () => {
seed("w1", "one", "two");
const nav = localNav();
expect(nav.prev("my draft")).toBe("two");
expect(nav.prev()).toBe("one");
expect(nav.next()).toBe("two");
// Past the newest entry: the draft comes back and recall ends.
expect(nav.next()).toBe("my draft");
expect(nav.navigating()).toBe(false);
});
it("is a no-op when not navigating", () => {
seed("w1", "one");
expect(localNav().next()).toBeNull();
});
it("starts from the newest entry again after a reset", () => {
seed("w1", "one");
const nav = localNav();
nav.prev("draft");
nav.reset();
expect(nav.navigating()).toBe(false);
expect(nav.prev("x")).toBe("one");
});
it("keeps one cursor per composer over a shared store", () => {
seed("w1", "one", "two");
const a = localNav();
const b = localNav();
expect(a.prev("draft-a")).toBe("two");
expect(a.prev()).toBe("one");
expect(b.navigating()).toBe(false);
expect(b.prev("draft-b")).toBe("two");
expect(a.prev()).toBeNull();
expect(b.next()).toBe("draft-b");
});
it("sees entries added to the store by another composer", () => {
seed("w1", "one");
const nav = localNav();
rememberPrompt("w1", "two");
expect(nav.prev("draft")).toBe("two");
expect(nav.prev()).toBe("one");
});
it("navigates a relayed source and re-reads it on every step", () => {
let entries: string[] = ["one"];
const nav = new PromptHistoryNav(relayedPromptHistorySource(() => entries, () => {}));
expect(nav.prev("draft")).toBe("one");
// An entry recorded elsewhere (nvim, another device) becomes reachable
// without rebuilding the cursor: the source is read on every step.
entries = ["one", "two"];
expect(nav.next()).toBe("two");
expect(nav.next()).toBe("draft");
expect(nav.navigating()).toBe(false);
});
});
describe("prompt history: readline rules", () => {
it("appends, skips a repeated newest entry, and keeps a non-consecutive repeat", () => {
expect(appendEntry([], "a")).toEqual(["a"]);
expect(appendEntry(["a"], "a")).toEqual(["a"]);
expect(appendEntry(["a"], "b")).toEqual(["a", "b"]);
expect(appendEntry(["a", "b"], "a")).toEqual(["a", "b", "a"]);
});
it("ignores blank input and preserves multi-line prompts", () => {
expect(appendEntry(["a"], " ")).toEqual(["a"]);
expect(appendEntry([], "l1\nl2")).toEqual(["l1\nl2"]);
});
it("caps the list at the newest history limit", () => {
let entries: string[] = [];
for (let index = 1; index <= HISTORY_LIMIT + 3; index += 1) entries = appendEntry(entries, `e${index}`);
expect(entries).toHaveLength(HISTORY_LIMIT);
expect(entries[0]).toBe("e4");
expect(entries[entries.length - 1]).toBe(`e${HISTORY_LIMIT + 3}`);
});
});
+99 -1
View File
@@ -1,8 +1,9 @@
import { beforeEach, describe, expect, it, vi } from "vitest"; import { beforeEach, describe, expect, it, vi } from "vitest";
import { SEEN_STORAGE_KEY } from "@/features/chat/acknowledged";
import { emptySessionState, normalizeSnapshotState } from "@/features/chat/session-state"; import { emptySessionState, normalizeSnapshotState } from "@/features/chat/session-state";
import { useSessionsStore } from "@/stores/sessions"; import { useSessionsStore } from "@/stores/sessions";
import { sessionFixture } from "./chat-fixtures"; import { entryFixture, sessionFixture } from "./chat-fixtures";
function state() { function state() {
return useSessionsStore.getState(); return useSessionsStore.getState();
@@ -308,3 +309,100 @@ describe("sessions store — markSeen", () => {
unsub(); unsub();
}); });
}); });
describe("sessions store — an acknowledged notification never replays", () => {
const entries = (...ids: string[]) => ids.map((id) => entryFixture({ id }));
it("keeps done cleared when a reload's snapshot replays the same notification", () => {
const transcript = entries("e1", "e2");
state().setSessions("w1", [
fixture({ sessionId: "s1", workspaceId: "w1", flags: { done: true }, entries: transcript }),
]);
state().markSeen("s1");
expect(state().getSession("s1")?.flags.done).toBe(false);
// The occurrence the browser acknowledged is the transcript tail.
expect(JSON.parse(localStorage.getItem(SEEN_STORAGE_KEY) ?? "{}")).toEqual({ s1: "e2" });
// Page reload: the store is empty, but the plugin still raises `done`
// until nvim's TabEnter, so the snapshot carries it again.
state().reset();
state().upsertSession(
normalizeSnapshotState("s1", "w1", {
state: { status: "idle", flags: { attention: false, done: true, error: false }, entries: transcript },
}),
);
expect(state().getSession("s1")?.flags.done).toBe(false);
// A reconnect replays it too, through the cached-row merge.
state().upsertSession({
...emptySessionState({ sessionId: "s1", workspaceId: "w1" }),
flags: { attention: false, done: true, error: false },
entries: transcript,
});
expect(state().getSession("s1")?.flags.done).toBe(false);
});
it("blinks again once the next turn appends an entry", () => {
state().setSessions("w1", [
fixture({ sessionId: "s1", workspaceId: "w1", flags: { done: true }, entries: entries("e1") }),
]);
state().markSeen("s1");
state().upsertSession({
...emptySessionState({ sessionId: "s1", workspaceId: "w1" }),
status: "idle",
flags: { attention: false, done: true, error: false },
entries: entries("e1", "e2"),
});
expect(state().getSession("s1")?.flags.done).toBe(true);
});
it("re-arms an acknowledged error the same way", () => {
state().setSessions("w1", [
fixture({ sessionId: "s1", workspaceId: "w1", flags: { error: true }, entries: entries("e1") }),
]);
state().markSeen("s1");
state().reset();
state().upsertSession({
...emptySessionState({ sessionId: "s1", workspaceId: "w1" }),
status: "idle",
flags: { attention: false, done: false, error: true },
entries: entries("e1"),
});
expect(state().getSession("s1")?.flags.error).toBe(false);
state().upsertSession({
...emptySessionState({ sessionId: "s1", workspaceId: "w1" }),
status: "idle",
flags: { attention: false, done: false, error: true },
entries: entries("e1", "e2"),
});
expect(state().getSession("s1")?.flags.error).toBe(true);
});
it("carries the acknowledgement across the tmp-N → real-id migration", () => {
state().setSessions("w1", [
fixture({ sessionId: "tmp-1", workspaceId: "w1", flags: { done: true }, entries: entries("e1") }),
]);
state().markSeen("tmp-1");
state().renameSessionId("tmp-1", "real-1");
state().reset();
state().upsertSession(
normalizeSnapshotState("real-1", "w1", {
state: { status: "idle", flags: { attention: false, done: true, error: false }, entries: entries("e1") },
}),
);
expect(state().getSession("real-1")?.flags.done).toBe(false);
});
it("forgets the acknowledgement when the session is removed", () => {
state().setSessions("w1", [
fixture({ sessionId: "s1", workspaceId: "w1", flags: { done: true }, entries: entries("e1") }),
]);
state().markSeen("s1");
state().removeSession("s1");
expect(JSON.parse(localStorage.getItem(SEEN_STORAGE_KEY) ?? "{}")).not.toHaveProperty("s1");
});
});
+4 -1
View File
@@ -64,6 +64,8 @@ const resourcesBody = {
physicalMemoryBytes: 2048 * 1024 * 1024, physicalMemoryBytes: 2048 * 1024 * 1024,
system: { system: {
sampledAt: Date.now(), sampledAt: Date.now(),
// Host uptime, deliberately different from the daemon's own age in `infoBody`.
hostUptimeSec: 3 * 86_400,
cpuPercent: 37, cpuPercent: 37,
cpuCores: 8, cpuCores: 8,
loadAvg: [1.23, 0.98, 0.75], loadAvg: [1.23, 0.98, 0.75],
@@ -264,7 +266,8 @@ describe("StatusPage", () => {
expect(document.querySelector('.status-tile[data-res="disk"] .tile__meta')).toHaveTextContent("/var/lib/pi2"); expect(document.querySelector('.status-tile[data-res="disk"] .tile__meta')).toHaveTextContent("/var/lib/pi2");
expect(document.querySelector('.status-tile[data-res="cpu"] .tile__meta')).toHaveTextContent("8"); expect(document.querySelector('.status-tile[data-res="cpu"] .tile__meta')).toHaveTextContent("8");
expect(document.querySelector('.status-tile[data-res="cpu"] .tile__meta')).toHaveTextContent("1.23"); expect(document.querySelector('.status-tile[data-res="cpu"] .tile__meta')).toHaveTextContent("1.23");
expect(document.querySelector('.status-tile[data-res="uptime"] .tile__value')).toHaveTextContent("2h 5m"); // The tile shows the host, not the daemon process (`/info.uptimeMs` is 2h 5m).
expect(document.querySelector('.status-tile[data-res="uptime"] .tile__value')).toHaveTextContent("3d 0h 0m");
const counts = document.querySelector(".status-counts"); const counts = document.querySelector(".status-counts");
expect(counts).not.toBeNull(); expect(counts).not.toBeNull();
+51
View File
@@ -0,0 +1,51 @@
import { act, render } from "@testing-library/react";
import { afterEach, describe, expect, it, vi } from "vitest";
import { LiveUptime, uptimeAnchor, uptimeSecondsFrom } from "@/features/status/uptime";
afterEach(() => {
vi.useRealTimers();
});
describe("uptime anchoring", () => {
it("anchors a reported duration at the matching epoch instant", () => {
expect(uptimeAnchor(5_000, 10_000)).toBe(5_000);
expect(uptimeAnchor(3 * 86_400_000, 1_000)).toBe(1_000 - 3 * 86_400_000);
});
it("rejects values a clock cannot start from", () => {
expect(uptimeAnchor(null)).toBeNull();
expect(uptimeAnchor(undefined)).toBeNull();
expect(uptimeAnchor(Number.NaN)).toBeNull();
expect(uptimeAnchor(Number.POSITIVE_INFINITY)).toBeNull();
// A negative duration would render as a rewind, not as uptime.
expect(uptimeAnchor(-1)).toBeNull();
});
it("counts forward and never below zero", () => {
expect(uptimeSecondsFrom(1_000, 62_000)).toBe(61);
expect(uptimeSecondsFrom(1_000, 1_000)).toBe(0);
expect(uptimeSecondsFrom(1_000, 0)).toBe(0);
});
});
describe("LiveUptime", () => {
it("renders an em dash when the daemon reports nothing", () => {
const { container } = render(<LiveUptime ms={null} />);
expect(container.textContent).toBe("—");
});
it("ticks without needing a fresh /info sample", () => {
vi.useFakeTimers();
vi.setSystemTime(new Date("2026-01-01T00:00:00Z"));
// `/info` was only fetched once; the label must keep counting locally.
const { container } = render(<LiveUptime ms={5 * 60_000} />);
expect(container.textContent).toBe("0h 5m");
act(() => {
vi.advanceTimersByTime(60_000);
});
expect(container.textContent).toBe("0h 6m");
});
});
+129
View File
@@ -0,0 +1,129 @@
import { describe, expect, it } from "vitest";
import type { WorkspaceInfo } from "@/lib/protocol";
import {
markWorkspaceUsed,
readWorkspaceRecency,
searchWorkspaces,
sortByRecentUse,
workspaceLabel,
WORKSPACE_RECENCY_KEY,
workspaceRecency,
} from "@/features/chat/workspace-order";
function workspace(
overrides: Partial<WorkspaceInfo> & Pick<WorkspaceInfo, "workspaceId" | "cwd" | "name">,
): WorkspaceInfo {
return {
trusted: true,
exists: true,
sessionCount: 0,
liveCount: 0,
lastActiveAt: 0,
instance: null,
...overrides,
};
}
const alpha = workspace({ workspaceId: "WA", cwd: "/work/alpha", name: "Alpha", lastActiveAt: 100 });
const bravo = workspace({ workspaceId: "WB", cwd: "/srv/bravo", name: "Bravo", lastActiveAt: 300 });
const charlie = workspace({ workspaceId: "WC", cwd: "/work/charlie", name: "Charlie", lastActiveAt: 200 });
describe("workspaceLabel", () => {
it("prefers the name, falls back to the cwd basename, then the id", () => {
expect(workspaceLabel(alpha)).toBe("Alpha");
expect(workspaceLabel(workspace({ workspaceId: "W", cwd: "/deep/path/proj/", name: " " }))).toBe("proj");
expect(workspaceLabel(workspace({ workspaceId: "W9", cwd: "/", name: "" }))).toBe("W9");
});
});
describe("sortByRecentUse", () => {
it("orders by the daemon's lastActiveAt", () => {
expect(sortByRecentUse([alpha, bravo, charlie]).map((w) => w.workspaceId)).toEqual(["WB", "WC", "WA"]);
});
it("lets a browser-local stamp beat lastActiveAt", () => {
const recency = { WA: 900 };
expect(sortByRecentUse([bravo, charlie, alpha], recency).map((w) => w.workspaceId)).toEqual([
"WA",
"WB",
"WC",
]);
});
it("falls back to the name, then the id, for never-touched rows", () => {
const newer = workspace({ workspaceId: "WZ", cwd: "/work/newer", name: "Newer", lastActiveAt: 0 });
const sameNameB = workspace({ workspaceId: "W2", cwd: "/a/beta", name: "beta", lastActiveAt: 0 });
const sameNameA = workspace({ workspaceId: "W1", cwd: "/a/alpha", name: "alpha", lastActiveAt: 0 });
expect(sortByRecentUse([sameNameB, newer, sameNameA]).map((w) => w.workspaceId)).toEqual([
"W1",
"W2",
"WZ",
]);
});
it("never mutates the caller's array", () => {
const list = [alpha, bravo];
sortByRecentUse(list);
expect(list.map((w) => w.workspaceId)).toEqual(["WA", "WB"]);
});
});
describe("workspaceRecency", () => {
it("takes the later of the local stamp and the daemon activity", () => {
expect(workspaceRecency(charlie, { WC: 50 })).toBe(200);
expect(workspaceRecency(charlie, { WC: 500 })).toBe(500);
expect(workspaceRecency(workspace({ workspaceId: "WN", cwd: "/n", name: "N" }))).toBe(0);
});
});
describe("searchWorkspaces", () => {
const sorted = sortByRecentUse([alpha, bravo, charlie]);
it("returns everything in the given order when the query is blank", () => {
expect(searchWorkspaces(sorted, "").map((w) => w.workspaceId)).toEqual(["WB", "WC", "WA"]);
expect(searchWorkspaces(sorted, " ").map((w) => w.workspaceId)).toEqual(["WB", "WC", "WA"]);
});
it("matches the name case-insensitively", () => {
expect(searchWorkspaces(sorted, "CHAR").map((w) => w.workspaceId)).toEqual(["WC"]);
});
it("matches the cwd, the basename and the id", () => {
expect(searchWorkspaces(sorted, "/srv").map((w) => w.workspaceId)).toEqual(["WB"]);
expect(searchWorkspaces(sorted, "alpha").map((w) => w.workspaceId)).toEqual(["WA"]);
expect(searchWorkspaces(sorted, "wc").map((w) => w.workspaceId)).toEqual(["WC"]);
});
it("matches an alias", () => {
const aliased = workspace({ workspaceId: "WD", cwd: "/x/y", name: "Delta", alias: "delta-nvim" });
expect(searchWorkspaces([aliased], "nvim").map((w) => w.workspaceId)).toEqual(["WD"]);
});
it("requires every whitespace-separated term to hit some field", () => {
expect(searchWorkspaces(sorted, "work char").map((w) => w.workspaceId)).toEqual(["WC"]);
expect(searchWorkspaces(sorted, "work charlie extra")).toEqual([]);
});
});
describe("recency persistence", () => {
it("round-trips through localStorage and keeps the newest stamps", () => {
markWorkspaceUsed("WA", 1000);
markWorkspaceUsed("WB", 2000);
expect(readWorkspaceRecency()).toEqual({ WA: 1000, WB: 2000 });
markWorkspaceUsed("WA", 3000);
expect(readWorkspaceRecency()).toEqual({ WA: 3000, WB: 2000 });
expect(sortByRecentUse([bravo, alpha], readWorkspaceRecency()).map((w) => w.workspaceId)).toEqual([
"WA",
"WB",
]);
});
it("survives a corrupt payload", () => {
localStorage.setItem(WORKSPACE_RECENCY_KEY, "{not json");
expect(readWorkspaceRecency()).toEqual({});
localStorage.setItem(WORKSPACE_RECENCY_KEY, '{"WA": "nope", "WB": 5}');
expect(readWorkspaceRecency()).toEqual({ WB: 5 });
});
});
+148
View File
@@ -0,0 +1,148 @@
import { fireEvent, render, screen, waitFor } from "@testing-library/react";
import { useState } from "react";
import { beforeAll, describe, expect, it, vi } from "vitest";
import type { WorkspaceInfo } from "@/lib/protocol";
import { setLanguage } from "@/lib/i18n";
import { WorkspaceSwitch } from "@/features/chat/workspace-switch";
import { WORKSPACE_RECENCY_KEY } from "@/features/chat/workspace-order";
beforeAll(async () => {
await setLanguage("en");
});
function workspace(
overrides: Partial<WorkspaceInfo> & Pick<WorkspaceInfo, "workspaceId" | "cwd" | "name">,
): WorkspaceInfo {
return {
trusted: true,
exists: true,
sessionCount: 0,
liveCount: 0,
lastActiveAt: 0,
instance: null,
...overrides,
};
}
const alpha = workspace({ workspaceId: "WA", cwd: "/work/alpha", name: "Alpha", lastActiveAt: 100, sessionCount: 4 });
const bravo = workspace({ workspaceId: "WB", cwd: "/srv/bravo", name: "Bravo", lastActiveAt: 300, sessionCount: 2 });
const charlie = workspace({ workspaceId: "WC", cwd: "/work/charlie", name: "Charlie", lastActiveAt: 200 });
/** The picker with live open state, so open/close paths are exercised. */
function Harness({
workspaces = [alpha, bravo, charlie],
activeWorkspaceId = "WC",
initiallyOpen = true,
onSelect = vi.fn(),
}: {
workspaces?: WorkspaceInfo[];
activeWorkspaceId?: string | null;
initiallyOpen?: boolean;
onSelect?: (workspaceId: string) => void;
}) {
const [open, setOpen] = useState(initiallyOpen);
return (
<WorkspaceSwitch
workspaces={workspaces}
activeWorkspaceId={activeWorkspaceId}
sessionCount={7}
open={open}
onOpenChange={setOpen}
onSelect={onSelect}
/>
);
}
function rowIds(): string[] {
return screen
.getAllByRole("option")
.map((element) => element.getAttribute("data-workspace-id") ?? "");
}
describe("WorkspaceSwitch", () => {
it("lists workspaces most-recently-used first", () => {
render(<Harness />);
expect(rowIds()).toEqual(["WB", "WC", "WA"]);
// The active row is selected, and the trigger shows the live count.
expect(screen.getByRole("option", { selected: true })).toHaveAttribute("data-workspace-id", "WC");
expect(screen.getByTestId("ws-switch")).toHaveTextContent("Charlie");
expect(screen.getByTestId("ws-switch")).toHaveTextContent("7");
});
it("puts a browser-locally used workspace on top", () => {
localStorage.setItem(WORKSPACE_RECENCY_KEY, JSON.stringify({ WA: 5_000 }));
render(<Harness />);
expect(rowIds()).toEqual(["WA", "WB", "WC"]);
});
it("filters as the user types and reports no match", () => {
render(<Harness />);
const search = screen.getByTestId("ws-menu-search");
fireEvent.change(search, { target: { value: "char" } });
expect(rowIds()).toEqual(["WC"]);
fireEvent.change(search, { target: { value: "zzz" } });
expect(screen.queryAllByRole("option")).toEqual([]);
expect(screen.getByTestId("ws-menu-empty")).toHaveTextContent("zzz");
// The clear button empties the field and keeps focus in the picker.
fireEvent.click(screen.getByRole("button", { name: "Clear search" }));
expect(rowIds()).toEqual(["WB", "WC", "WA"]);
expect(search).toHaveValue("");
});
it("selects the first match with Enter from the search field", () => {
const onSelect = vi.fn();
render(<Harness onSelect={onSelect} />);
const search = screen.getByTestId("ws-menu-search");
fireEvent.change(search, { target: { value: "bravo" } });
fireEvent.keyDown(search, { key: "Enter" });
expect(onSelect).toHaveBeenCalledWith("WB");
expect(screen.queryAllByRole("option")).toEqual([]);
});
it("moves focus with the arrow keys and closes on Escape", async () => {
render(<Harness />);
const search = screen.getByTestId("ws-menu-search");
await waitFor(() => expect(search).toHaveFocus());
fireEvent.keyDown(search, { key: "ArrowDown" });
expect(screen.getByRole("option", { name: /Bravo/ })).toHaveFocus();
fireEvent.keyDown(search, { key: "ArrowDown" });
expect(screen.getByRole("option", { name: /Charlie/ })).toHaveFocus();
fireEvent.keyDown(search, { key: "ArrowUp" });
expect(screen.getByRole("option", { name: /Bravo/ })).toHaveFocus();
fireEvent.keyDown(search, { key: "End" });
expect(screen.getByRole("option", { name: /Alpha/ })).toHaveFocus();
fireEvent.keyDown(search, { key: "Escape" });
expect(screen.queryAllByRole("option")).toEqual([]);
await waitFor(() => expect(screen.getByTestId("ws-switch")).toHaveFocus());
});
it("selects a clicked row and closes; clicking the active row only closes", () => {
const onSelect = vi.fn();
render(<Harness onSelect={onSelect} />);
fireEvent.click(screen.getByRole("option", { name: /Alpha/ }));
expect(onSelect).toHaveBeenCalledWith("WA");
expect(screen.queryAllByRole("option")).toEqual([]);
fireEvent.click(screen.getByTestId("ws-switch"));
fireEvent.click(screen.getByRole("option", { selected: true }));
expect(onSelect).toHaveBeenCalledTimes(1);
expect(screen.queryAllByRole("option")).toEqual([]);
});
it("disables the trigger when the daemon reports no workspaces", () => {
render(<Harness workspaces={[]} activeWorkspaceId={null} initiallyOpen={false} />);
const trigger = screen.getByTestId("ws-switch");
expect(trigger).toBeDisabled();
expect(trigger).toHaveTextContent("No workspaces yet");
});
});
+39
View File
@@ -275,6 +275,45 @@ describe("WorkspacesPage", () => {
expect(row?.querySelector(".dot")).toHaveClass("dot--busy"); expect(row?.querySelector(".dot")).toHaveClass("dot--busy");
}); });
it("titles disk-only rows from the daemon's bounded display preview", async () => {
const items = [
workspace({ workspaceId: "ws-a", cwd: "/work/a", name: "Alpha" }),
workspace({ workspaceId: "ws-b", cwd: "/work/b", name: "Bravo" }),
];
mockApi([
{ path: "/api/v1/info", handler: () => ({ body: infoBody }) },
{ path: "/api/v1/workspaces", handler: () => ({ body: items }) },
recentRoute([
diskSession({
sessionId: "s-name",
workspaceId: "ws-a",
workspaceName: "Alpha",
modified: 2_000,
name: "Renamed session",
}),
diskSession({
sessionId: "s-msg",
workspaceId: "ws-b",
workspaceName: "Bravo",
modified: 1_000,
firstMessage: "Please fix the recent list",
}),
]),
]);
await renderPage(routes(), "/workspaces", { paired: true });
await waitForCards(2);
const activity = screen.getByTestId("workspaces-activity");
expect(await within(activity).findByText("Renamed session")).toBeInTheDocument();
expect(within(activity).getByText("Please fix the recent list")).toBeInTheDocument();
// Neither row has a live instance; the title is data, not `(unnamed)`.
const rows = within(activity).getAllByTestId("workspace-activity-row");
expect(rows[0]?.querySelector(".ws-activity__name")).toHaveTextContent("Renamed session");
expect(rows[1]?.querySelector(".ws-activity__name")).toHaveTextContent("Please fix the recent list");
expect(within(activity).queryByText("(unnamed)")).toBeNull();
});
it("opens the new-workspace dialog from the empty state", async () => { it("opens the new-workspace dialog from the empty state", async () => {
const fetchMock = mockApi([ const fetchMock = mockApi([
{ path: "/api/v1/info", handler: () => ({ body: infoBody }) }, { path: "/api/v1/info", handler: () => ({ body: infoBody }) },