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

No files matched your search

+107 -6
View File
@@ -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<HTMLTextAreaElement | 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 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; `<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) {
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}
/>
<div className="composer__bar">
<button