From 32292873f98023226c5223184e3451ba4a28c630 Mon Sep 17 00:00:00 2001 From: yuez Date: Mon, 2 Nov 2026 11:12:21 +0800 Subject: [PATCH] feat(daemon): serve a live-only prompt-history read MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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. --- docs/protocol.md | 40 ++++++++++++++++++ src/core/interfaces.ts | 2 + src/daemon/http.ts | 14 +++++++ src/daemon/router.ts | 56 +++++++++++++++++++++++++ test/daemon/fakes.ts | 2 + test/daemon/http.test.ts | 90 ++++++++++++++++++++++++++++++++++++++++ 6 files changed, 204 insertions(+) diff --git a/docs/protocol.md b/docs/protocol.md index 795af5c..85a030b 100644 --- a/docs/protocol.md +++ b/docs/protocol.md @@ -67,8 +67,19 @@ The plugin dials the daemon (`/d.sock`), sends `hello` first. {"v":1,"type":"workspace.query","id":"req-2","payload":{"kind":"sessions"}} // a session-scoped read keeps the sid on the envelope (see §3.1 entries) {"v":1,"type":"workspace.query","id":"req-3","sessionId":"s1","payload":{"kind":"entries","limit":50}} +// 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: - **Say `bye` when leaving on purpose.** A plugin that stops the bridge (`:PiWebStop`, `VimLeavePre`) @@ -100,6 +111,7 @@ Plugin obligations: | `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/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}`) | | `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}` | @@ -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}}`), 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 older than 0.1.5, so clients must tolerate its absence) and reports **host** figures sampled by the daemon itself: diff --git a/src/core/interfaces.ts b/src/core/interfaces.ts index 906b5d0..90041d0 100644 --- a/src/core/interfaces.ts +++ b/src/core/interfaces.ts @@ -22,6 +22,8 @@ export interface PluginConnection { readonly hasUI: boolean; readonly listenAddr: string | null; readonly pluginVersion: string; + /** Capability strings the plugin advertised in its `hello` (`snapshot`, `promptHistory`, …). */ + readonly capabilities: string[]; /** Send one JSONL record to the plugin. */ send(record: Record): void; /** Forward a command; resolves with the plugin `ack` payload. */ diff --git a/src/daemon/http.ts b/src/daemon/http.ts index 1ae4def..8c89209 100644 --- a/src/daemon/http.ts +++ b/src/daemon/http.ts @@ -331,6 +331,20 @@ export function createApp(deps: AppDeps): Hono { 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) => { const workspaceId = c.req.query("workspaceId"); if (workspaceId) { diff --git a/src/daemon/router.ts b/src/daemon/router.ts index d0ca2f8..5c392b9 100644 --- a/src/daemon/router.ts +++ b/src/daemon/router.ts @@ -13,6 +13,10 @@ import { DaemonError, toErrorPayload } from "./errors.js"; 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 { auth: AuthStore; instances: InstanceManager; @@ -54,6 +58,30 @@ function optionalString(params: Record, key: string): string | 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 { private readonly auth: AuthStore; private readonly instances: InstanceManager; @@ -148,6 +176,34 @@ export class CommandRouter { 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 { + 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( workspaceId: string, sessionId: string | undefined, diff --git a/test/daemon/fakes.ts b/test/daemon/fakes.ts index d37767f..9bcd3c1 100644 --- a/test/daemon/fakes.ts +++ b/test/daemon/fakes.ts @@ -31,6 +31,8 @@ export class FakeConnection implements PluginConnection { readonly hasUI = true; readonly listenAddr: string | null = null; readonly pluginVersion = "test-1.0.0"; + /** Writable so a test can model a plugin that predates a capability. */ + capabilities: string[] = ["promptHistory"]; subscribed = new Set(); snapshots = new Map(); diff --git a/test/daemon/http.test.ts b/test/daemon/http.test.ts index 0e47140..7a9b06b 100644 --- a/test/daemon/http.test.ts +++ b/test/daemon/http.test.ts @@ -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 () => { h.workspaces.recentSessionRows = [ {