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.
This commit is contained in:
yuez committed 2026-11-02 11:12:21 +08:00
1 parent c24f30fe71
commit 32292873f9
6 files changed
+204

No files matched your search

+40
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`)
@@ -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/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:
+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. */
+14
View File
@@ -331,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,
+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>();
+90
View File
@@ -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 = [
{ {