From b8f1fca5bde9c81dde5a1915838b595efcb161b4 Mon Sep 17 00:00:00 2001 From: yuez Date: Mon, 2 Nov 2026 11:12:41 +0800 Subject: [PATCH] feat(web): recall prompt history from the plugin with a browser fallback MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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, ``/`` 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. --- AGENTS.md | 1 + docs/prompt-history.md | 116 +++++++ scripts/ui-mock-server.mjs | 24 ++ web/src/features/chat/composer.tsx | 113 ++++++- web/src/features/chat/prompt-history-feed.ts | 131 ++++++++ web/src/features/chat/prompt-history.ts | 320 +++++++++++++++++++ web/src/lib/api.ts | 26 ++ web/src/pages/chat.tsx | 6 + web/tests/chat.composer.test.tsx | 194 +++++++++++ web/tests/chat.prompt-history-feed.test.tsx | 169 ++++++++++ web/tests/prompt-history.test.ts | 230 +++++++++++++ 11 files changed, 1324 insertions(+), 6 deletions(-) create mode 100644 docs/prompt-history.md create mode 100644 web/src/features/chat/prompt-history-feed.ts create mode 100644 web/src/features/chat/prompt-history.ts create mode 100644 web/tests/chat.prompt-history-feed.test.tsx create mode 100644 web/tests/prompt-history.test.ts diff --git a/AGENTS.md b/AGENTS.md index 85d9b17..10b863d 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -72,6 +72,7 @@ owner/repo/workflow filename, not the npm name). | `docs/protocol.md` | the browser ↔ daemon ↔ plugin wire contract | | `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/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/e2e.md` | scenario ids, isolation, skip conditions, report paths | | `docs/testing.md` | test architecture, performance tuning, hybrid core CPU guidelines | diff --git a/docs/prompt-history.md b/docs/prompt-history.md new file mode 100644 index 0000000..e3ff76d --- /dev/null +++ b/docs/prompt-history.md @@ -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 | +|---|---| +| `↑` (``) | Recall the previous (older) prompt. | +| `↓` (``) | 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. `` / `` 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. diff --git a/scripts/ui-mock-server.mjs b/scripts/ui-mock-server.mjs index 7e9da2f..7050e85 100644 --- a/scripts/ui-mock-server.mjs +++ b/scripts/ui-mock-server.mjs @@ -263,6 +263,12 @@ function serveStatic(req, res, pathname) { 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. */ function sessionsOf(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)); } + // 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); if (match && method === "GET") { const sessionId = decodeURIComponent(match[1]); diff --git a/web/src/features/chat/composer.tsx b/web/src/features/chat/composer.tsx index adead9c..ab6070f 100644 --- a/web/src/features/chat/composer.tsx +++ b/web/src/features/chat/composer.tsx @@ -1,5 +1,5 @@ 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 { Icon } from "@/components/icons"; @@ -13,6 +13,7 @@ import { promptImage, type PromptImage, type PromptMode } from "./commands"; import type { ModelGroup } from "./data"; import { withCurrentModel } from "./data"; import { THINKING_LEVELS } from "./format"; +import { historyScope, localPromptHistorySource, PromptHistoryNav, type PromptHistorySource } from "./prompt-history"; import type { Attachment } from "./store"; export interface ComposerProps { @@ -42,6 +43,13 @@ export interface ComposerProps { queuedCount?: number; onSetModel: (model: ModelRef) => 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; className?: string; } @@ -67,6 +75,7 @@ export function Composer({ queuedCount, onSetModel, onSetThinking, + history, disabled = false, className, }: ComposerProps) { @@ -78,6 +87,21 @@ export function Composer({ const textareaRef = useRef(null); const fileRef = useRef(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 busy = session ? session.status === "busy" || session.status === "compacting" : false; const queue = session?.queue ?? []; @@ -104,6 +128,13 @@ export function Composer({ const max = 5 * 24; element.style.height = `${Math.min(element.scrollHeight, max)}px`; 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]); useEffect(() => { @@ -111,12 +142,81 @@ export function Composer({ textareaRef.current?.focus({ preventScroll: true }); }, [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; ``/`` are the readline + * aliases and always recall. Anything else stays a plain textarea key. + */ + function handleKeyDown(event: KeyboardEvent) { + // 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 `` 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) { const trimmed = text.trim(); if (!trimmed || !enabled) return; const images = attachments.map(({ mimeType, data }) => ({ mimeType, data })); setText(""); 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. onSend(trimmed, images, mode ?? (busy ? "follow_up" : undefined)); } @@ -218,12 +318,13 @@ export function Composer({ aria-label={t("chat.composerAria")} data-testid="composer-input" disabled={!enabled} - onChange={(event) => setText(event.target.value)} - onKeyDown={(event) => { - if (event.key !== "Enter" || event.shiftKey || event.nativeEvent.isComposing) return; - event.preventDefault(); - submit(); + onChange={(event) => { + setText(event.target.value); + // A manual edit ends recall, so a later ↓ cannot clobber + // the user's typing with a stale entry. + historyNav().reset(); }} + onKeyDown={handleKeyDown} />