Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins
TypeScript ai-agentcoding-agentdesktop-appelectronglobali18nlocal-firstmcppipi-agentpi-desktoppluginsreactrusttypescript
feat(chat): recall sent prompts per conversation with ArrowUp
renwangaf89e7e082bd5
diff --git a/apps/desktop/src/components/Composer.tsx b/apps/desktop/src/components/Composer.tsxindex abf119faa..cf48a0947 100644--- a/apps/desktop/src/components/Composer.tsx+++ b/apps/desktop/src/components/Composer.tsx@@ -53,6 +53,7 @@ import {} from "../features/chat/composer/editor";import { useComposerAttachments } from "../features/chat/composer/hooks/useComposerAttachments";import { useComposerDraft } from "../features/chat/composer/hooks/useComposerDraft";+import { useComposerInputHistory } from "../features/chat/composer/hooks/useComposerInputHistory";import { useComposerSubmit } from "../features/chat/composer/hooks/useComposerSubmit";import { ComposerImageAttachments } from "../features/chat/composer/ComposerImageAttachments";import { ComposerInput } from "../features/chat/composer/ComposerInput";@@ -192,6 +193,11 @@ export function Composer({insertNewlineInEditor,handleInput,} = draft;+ const inputHistory = useComposerInputHistory({+ draftKey,+ referenceSessionId,+ draft,+ });const approvalPending = planCheckpoint?.status === "pending";const largePasteThreshold = normalizeLargePasteThreshold(@@ -420,6 +426,7 @@ export function Composer({sendPrompt,steerPrompt,showToast,+ recordHistory: inputHistory.record,draft: {ref,draftSnapshot,@@ -441,6 +448,13 @@ export function Composer({submit,} = submitController;+ // Both submit entry points (the composer's Enter and the toolbar's Send)+ // leave history browsing before the draft is cleared.+ const submitFromComposer = (steering?: boolean) => {+ inputHistory.exitBrowsing();+ return submit(steering);+ };+const voiceEnabled = !!settings?.voice?.enabled;const voice = useVoiceInput({enabled: voiceEnabled,@@ -584,9 +598,13 @@ export function Composer({composerAc={composerAc}onPaste={pasteClipboardFiles}onAcceptCompletion={acceptCompletion}- onSubmit={(steering) => void submit(steering)}+ onSubmit={(steering) => void submitFromComposer(steering)}onInsertNewline={insertNewlineInEditor}- onInput={handleInput}+ onInput={(source, caret) => {+ inputHistory.exitBrowsing();+ handleInput(source, caret);+ }}+ onHistoryNavigate={inputHistory.navigate}onCompositionStart={() => setComposing(true)}onCompositionEnd={(event) => {setComposing(false);@@ -630,7 +648,7 @@ export function Composer({runActive={runActive}hasDraftContent={hasDraftContent}abort={abort}- submit={submit}+ submit={submitFromComposer}voicePhase={voice.state.phase}voiceEnabled={voiceEnabled}onVoiceToggle={voice.toggle}diff --git a/apps/desktop/src/features/chat/composer/ComposerInput.tsx b/apps/desktop/src/features/chat/composer/ComposerInput.tsxindex 3eb5a138e..2984cdc3f 100644--- a/apps/desktop/src/features/chat/composer/ComposerInput.tsx+++ b/apps/desktop/src/features/chat/composer/ComposerInput.tsx@@ -31,6 +31,8 @@ export type ComposerInputProps = {onSubmit: (steering?: boolean) => void;onInsertNewline: () => void;onInput: (source: string, caret: number) => void;+ /** Terminal-style recall; returns true when the arrow key was consumed. */+ onHistoryNavigate: (direction: "older" | "newer") => boolean;onCompositionStart: () => void;onCompositionEnd: (event: FormEvent<HTMLDivElement>) => void;onFocus: () => void;@@ -54,6 +56,7 @@ export function ComposerInput({onSubmit,onInsertNewline,onInput,+ onHistoryNavigate,onCompositionStart,onCompositionEnd,onFocus,@@ -136,6 +139,17 @@ export function ComposerInput({return;}}+ if (+ (event.key === "ArrowUp" || event.key === "ArrowDown") &&+ !event.shiftKey &&+ !event.altKey &&+ !event.metaKey &&+ !event.ctrlKey &&+ onHistoryNavigate(event.key === "ArrowUp" ? "older" : "newer")+ ) {+ event.preventDefault();+ return;+ }if (event.key === "Enter" &&!event.shiftKey &&diff --git a/apps/desktop/src/features/chat/composer/hooks/useComposerInputHistory.ts b/apps/desktop/src/features/chat/composer/hooks/useComposerInputHistory.tsnew file mode 100644index 000000000..029699ad1--- /dev/null+++ b/apps/desktop/src/features/chat/composer/hooks/useComposerInputHistory.ts@@ -0,0 +1,95 @@+import { useEffect, useRef } from "react";+import type { ComposerDraftSnapshot } from "../../../../lib/composer-smart-stop";+import {+ loadComposerInputHistory,+ rememberComposerInput,+ type ComposerHistoryEntry,+} from "../../../../lib/composer-input-history";+import { createFileReference } from "../editor";+import { runHistoryStep, type HistoryDirection } from "../input-history";+import type { ComposerDraftController } from "./useComposerDraft";++type UseComposerInputHistoryOptions = {+ draftKey: string;+ /** Conversation whose history is recalled; "" for the empty home composer. */+ referenceSessionId: string;+ draft: Pick<+ ComposerDraftController,+ "readLiveDraft" | "fileReferencesRef" | "applyEditorDraft" | "draftRevision"+ >;+};++export type ComposerInputHistoryController = {+ /** Returns true when the key was consumed by history navigation. */+ navigate: (direction: HistoryDirection) => boolean;+ exitBrowsing: () => void;+ record: (snapshot: ComposerDraftSnapshot, sessionId: string) => void;+};++/**+ * Terminal-style recall of the accepted submissions of one conversation.+ * Browsing starts only from an empty draft; any edit, submission, or session+ * switch ends it so the arrows go back to native caret movement. The step itself+ * lives in `runHistoryStep`.+ */+export function useComposerInputHistory({+ draftKey,+ referenceSessionId,+ draft,+}: UseComposerInputHistoryOptions): ComposerInputHistoryController {+ const indexRef = useRef<number | null>(null);+ const entriesRef = useRef<readonly ComposerHistoryEntry[]>([]);+ /** Draft revision the entry on screen was applied at. */+ const appliedRevisionRef = useRef(-1);++ const exitBrowsing = () => {+ indexRef.current = null;+ entriesRef.current = [];+ };++ useEffect(() => {+ exitBrowsing();+ }, [draftKey]);++ const navigate = (direction: HistoryDirection): boolean => {+ // Every real draft change marks a revision, so a revision that moved on its+ // own means the user edited the recalled entry behind our back (typing,+ // dictation, an attachment). A submit calls `exitBrowsing` up front.+ const edited =+ indexRef.current !== null &&+ draft.draftRevision(draftKey) !== appliedRevisionRef.current;+ const result = runHistoryStep({+ entries: entriesRef.current,+ index: indexRef.current,+ // A browse starts from an empty draft and every step replaces it, so this+ // only ever keeps leftovers of a previous conversation in the same slot.+ keptReferences: draft.fileReferencesRef.current.filter(+ (reference) => reference.sessionId !== referenceSessionId,+ ),+ direction,+ draftEmpty:+ !draft.readLiveDraft().trim() &&+ !draft.fileReferencesRef.current.some(+ (reference) => reference.sessionId === referenceSessionId,+ ),+ edited,+ loadHistory: () => loadComposerInputHistory(referenceSessionId),+ createReference: (reference) =>+ createFileReference(reference.path, reference.name, referenceSessionId, reference),+ effects: {+ applyDraft: (text, references, caret) =>+ draft.applyEditorDraft(text, [...references], caret),+ },+ });+ entriesRef.current = result.entries;+ indexRef.current = result.index;+ if (result.applied) appliedRevisionRef.current = draft.draftRevision(draftKey);+ return result.consumed;+ };++ const record = (snapshot: ComposerDraftSnapshot, sessionId: string) => {+ rememberComposerInput(sessionId, snapshot);+ };++ return { navigate, exitBrowsing, record };+}diff --git a/apps/desktop/src/features/chat/composer/hooks/useComposerSubmit.ts b/apps/desktop/src/features/chat/composer/hooks/useComposerSubmit.tsindex d6c8c8dfc..e99da1df3 100644--- a/apps/desktop/src/features/chat/composer/hooks/useComposerSubmit.ts+++ b/apps/desktop/src/features/chat/composer/hooks/useComposerSubmit.ts@@ -36,6 +36,8 @@ type UseComposerSubmitOptions = {sendPrompt: AppState["sendPrompt"];steerPrompt: AppState["steerPrompt"];showToast: AppState["showToast"];+ /** Record an accepted submission for ArrowUp recall. */+ recordHistory?: (snapshot: ComposerDraftSnapshot, sessionId: string) => void;draft: Pick<ComposerDraftController,| "ref"@@ -79,6 +81,7 @@ export function useComposerSubmit({sendPrompt,steerPrompt,showToast,+ recordHistory,draft,}: UseComposerSubmitOptions): ComposerSubmitController {const [enhancingPrompt, setEnhancingPrompt] = useState(false);@@ -210,6 +213,15 @@ export function useComposerSubmit({const submittedDraftKey = draftKey;const submittedDraftRevision = draft.draftRevision(submittedDraftKey);const submittedDraft = draft.draftSnapshot(text);+ // Recall keeps what the user typed, in the conversation that submitted it.+ // For a mode command that is the whole `/agent …` text rather than its body,+ // so re-submitting re-runs it; every other recorded path stores exactly the+ // accepted payload. A send from the empty home has no session yet, so the id+ // is resolved after the submission materialized it.+ const remember = () => {+ const targetSessionId = activeSessionId ?? useAppStore.getState().activeSessionId;+ if (targetSessionId) recordHistory?.(submittedDraft, targetSessionId);+ };// Slash dispatch stays local for builtin and extension commands, while// templates, skills, and unknown aliases continue as normal prompt text. A// command source that cannot be read is a third case: the composer cannot@@ -251,6 +263,7 @@ export function useComposerSubmit({draft.draftSnapshot(visibleCommandBody),);if (accepted) draft.clearDraftForKey(submittedDraftKey, submittedDraftRevision, submittedDraft);+ if (accepted) remember();} catch (error) {showToast(error instanceof Error ? error.message : String(error), {variant: "error",@@ -262,6 +275,7 @@ export function useComposerSubmit({try {await runExtensionCommand(command.name, commandBody);draft.clearDraftForKey(submittedDraftKey, submittedDraftRevision, submittedDraft);+ remember();} catch (error) {showToast(error instanceof Error ? error.message : String(error), {variant: "error",@@ -274,6 +288,7 @@ export function useComposerSubmit({if (command.kind === "builtin") await runPaletteCommand(command.id);else await api.executeCommand(command.id);draft.clearDraftForKey(submittedDraftKey, submittedDraftRevision, submittedDraft);+ remember();} catch (error) {showToast(error instanceof Error ? error.message : String(error), {variant: "error",@@ -292,6 +307,7 @@ export function useComposerSubmit({? await steerPrompt(inlineContent, submittedDraft): await sendPrompt(inlineContent, submittedDraft);if (!accepted) draft.restoreDraftForKey(submittedDraftKey, submittedDraft);+ else remember();};return {diff --git a/apps/desktop/src/features/chat/composer/input-history.ts b/apps/desktop/src/features/chat/composer/input-history.tsnew file mode 100644index 000000000..b49cca159--- /dev/null+++ b/apps/desktop/src/features/chat/composer/input-history.ts@@ -0,0 +1,126 @@+import type { ComposerHistoryEntry } from "../../../lib/composer-input-history";++export type HistoryDirection = "older" | "newer";++/**+ * Move the browse cursor. `null` means "not browsing" (the empty draft the+ * user started from); index 0 is the newest entry.+ */+export function stepHistoryIndex(+ index: number | null,+ direction: HistoryDirection,+ length: number,+): number | null {+ if (length <= 0) return null;+ if (direction === "older") return index === null ? 0 : Math.min(index + 1, length - 1);+ if (index === null || index <= 0) return null;+ return index - 1;+}++export type HistoryNavigationPlan =+ /** Not ours: leave the key to the editor's native caret movement. */+ | { action: "ignore" }+ /** Ours, but the boundary entry is already on screen. */+ | { action: "keep" }+ /** Show the entry at `index` (0 is the newest). */+ | { action: "load"; index: number }+ /** Leave browsing and empty the draft. */+ | { action: "exit" };++/**+ * Decide what one ArrowUp/ArrowDown does.+ *+ * `index` is the entry on screen, or `null` when not browsing — the caller+ * passes `null` for a draft the user edited, because browsing never survives an+ * edit. `draftEmpty` means no text and no references for this session, which is+ * the only draft a fresh browse may start from.+ */+export function planHistoryNavigation(input: {+ index: number | null;+ direction: HistoryDirection;+ length: number;+ draftEmpty: boolean;+}): HistoryNavigationPlan {+ if (input.index === null) {+ if (input.direction === "newer" || !input.draftEmpty || input.length === 0) {+ return { action: "ignore" };+ }+ return { action: "load", index: 0 };+ }+ const next = stepHistoryIndex(input.index, input.direction, input.length);+ if (next === null) return { action: "exit" };+ if (next === input.index) return { action: "keep" };+ return { action: "load", index: next };+}++export type HistoryStepEffects<TReference> = {+ /** Replace the draft: text, its references, and the caret to land on. */+ applyDraft: (text: string, references: readonly TReference[], caret: number) => void;+};++export type HistoryStepResult = {+ /** True when the key belongs to history and must not move the caret. */+ consumed: boolean;+ /** Browse snapshot to keep for the next step ([] when not browsing). */+ entries: readonly ComposerHistoryEntry[];+ /** Entry index on screen, or null when not browsing. */+ index: number | null;+ /** True when an entry was applied, so the caller can record its revision. */+ applied: boolean;+};++/**+ * Run one ArrowUp/ArrowDown against a browse snapshot and apply its effect.+ *+ * Kept free of React and of the draft controller so the whole recall sequence —+ * fresh browse, stepping, boundary, and an edit behind the recalled text — is+ * drivable from a test. Every entry comes from the current conversation, so its+ * references are always restored with it.+ */+export function runHistoryStep<TReference>(options: {+ /** Snapshot of the active browse, empty when not browsing. */+ entries: readonly ComposerHistoryEntry[];+ /** Entry index on screen, or null when not browsing. */+ index: number | null;+ /** References belonging to other conversations that must survive the step. */+ keptReferences: readonly TReference[];+ direction: HistoryDirection;+ draftEmpty: boolean;+ /** The draft changed behind the recalled entry, so browsing is over. */+ edited: boolean;+ loadHistory: () => readonly ComposerHistoryEntry[];+ createReference: (+ reference: ComposerHistoryEntry["fileReferences"][number],+ ) => TReference;+ effects: HistoryStepEffects<TReference>;+}): HistoryStepResult {+ const browsing = options.index !== null && !options.edited;+ const entries = browsing ? options.entries : options.loadHistory();+ const plan = planHistoryNavigation({+ index: browsing ? options.index : null,+ direction: options.direction,+ length: entries.length,+ draftEmpty: options.draftEmpty,+ });+ if (plan.action === "ignore") {+ if (options.edited) {+ return { consumed: false, entries: [], index: null, applied: false };+ }+ return { consumed: false, entries: options.entries, index: options.index, applied: false };+ }+ if (plan.action === "keep") {+ return { consumed: true, entries: options.entries, index: options.index, applied: false };+ }+ if (plan.action === "exit") {+ options.effects.applyDraft("", options.keptReferences, 0);+ return { consumed: true, entries: [], index: null, applied: false };+ }+ const entry = entries[plan.index];+ if (!entry) return { consumed: true, entries: [], index: null, applied: false };+ options.effects.applyDraft(+ entry.text,+ [...options.keptReferences, ...entry.fileReferences.map(options.createReference)],+ entry.text.length,+ );+ return { consumed: true, entries, index: plan.index, applied: true };+}diff --git a/apps/desktop/src/lib/composer-input-history.ts b/apps/desktop/src/lib/composer-input-history.tsnew file mode 100644index 000000000..9b5205ec5--- /dev/null+++ b/apps/desktop/src/lib/composer-input-history.ts@@ -0,0 +1,148 @@+import type { ComposerDraftSnapshot } from "./composer-smart-stop";++/**+ * Per-conversation composer input history (ArrowUp recall).+ *+ * One localStorage key holds bounded buckets, newest-used first: recalling in a+ * conversation never shows another conversation's prompts. A bucket keeps the+ * text and the file references of each accepted submission, like+ * `plugin-launcher-history.ts` keeps its MRU list. Storage is best-effort: a+ * missing, blocked, or corrupted store yields an empty history and never breaks+ * sending.+ */+export type ComposerHistoryEntry = {+ text: string;+ fileReferences: ComposerDraftSnapshot["fileReferences"];+};++type HistoryBucket = { sessionId: string; entries: ComposerHistoryEntry[] };++type HistoryReference = ComposerHistoryEntry["fileReferences"][number];++const KEY = "pi.desktop.composerInputHistory";+/** Entries kept per conversation. */+export const COMPOSER_INPUT_HISTORY_MAX = 100;+/** Conversations with retained history; the oldest written bucket is dropped. */+export const COMPOSER_INPUT_HISTORY_SESSIONS_MAX = 20;++function historyStorage(): Storage | null {+ try {+ return typeof globalThis !== "undefined" && "localStorage" in globalThis+ ? globalThis.localStorage+ : null;+ } catch {+ return null;+ }+}++function readReference(value: unknown): HistoryReference | null {+ if (!value || typeof value !== "object") return null;+ const row = value as Record<string, unknown>;+ if (typeof row.path !== "string" || !row.path || typeof row.name !== "string") return null;+ const kind = row.kind === "image" || row.kind === "file" ? row.kind : undefined;+ return {+ path: row.path,+ name: row.name,+ kind,+ ...(typeof row.mimeType === "string" && row.mimeType ? { mimeType: row.mimeType } : {}),+ ...(typeof row.token === "string" && row.token ? { token: row.token } : {}),+ };+}++function readEntry(value: unknown): ComposerHistoryEntry | null {+ if (!value || typeof value !== "object") return null;+ const row = value as Record<string, unknown>;+ if (typeof row.text !== "string" || !Array.isArray(row.fileReferences)) return null;+ const fileReferences: HistoryReference[] = [];+ for (const reference of row.fileReferences) {+ const parsed = readReference(reference);+ if (!parsed) return null;+ fileReferences.push(parsed);+ }+ if (!row.text.trim() && fileReferences.length === 0) return null;+ return { text: row.text, fileReferences };+}++/** Tolerant read: malformed buckets, entries, and rows are dropped, not fatal. */+function readBuckets(): HistoryBucket[] {+ const storage = historyStorage();+ if (!storage) return [];+ try {+ const raw = storage.getItem(KEY);+ if (!raw) return [];+ const parsed = JSON.parse(raw) as unknown;+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return [];+ const sessions = (parsed as { sessions?: unknown }).sessions;+ if (!Array.isArray(sessions)) return [];+ const buckets: HistoryBucket[] = [];+ for (const value of sessions) {+ if (!value || typeof value !== "object") continue;+ const row = value as Record<string, unknown>;+ if (typeof row.sessionId !== "string" || !row.sessionId) continue;+ if (!Array.isArray(row.entries)) continue;+ const entries: ComposerHistoryEntry[] = [];+ for (const candidate of row.entries) {+ const entry = readEntry(candidate);+ if (entry) entries.push(entry);+ if (entries.length >= COMPOSER_INPUT_HISTORY_MAX) break;+ }+ buckets.push({ sessionId: row.sessionId, entries });+ if (buckets.length >= COMPOSER_INPUT_HISTORY_SESSIONS_MAX) break;+ }+ return buckets;+ } catch {+ return [];+ }+}++function writeBuckets(buckets: readonly HistoryBucket[]): void {+ const storage = historyStorage();+ if (!storage) return;+ try {+ storage.setItem(KEY, JSON.stringify({ sessions: buckets }));+ } catch {+ // History is best-effort; a full or blocked storage must not break sending.+ }+}++/** Prompts accepted in one conversation, newest first. */+export function loadComposerInputHistory(sessionId: string): ComposerHistoryEntry[] {+ if (!sessionId) return [];+ return readBuckets().find((bucket) => bucket.sessionId === sessionId)?.entries ?? [];+}++function sameContent(left: ComposerHistoryEntry, right: ComposerHistoryEntry): boolean {+ return (+ left.text === right.text &&+ left.fileReferences.length === right.fileReferences.length &&+ left.fileReferences.every(+ (reference, index) => reference.path === right.fileReferences[index]?.path,+ )+ );+}++/** Prepend one accepted submission to its conversation; duplicates collapse. */+export function rememberComposerInput(+ sessionId: string,+ snapshot: ComposerDraftSnapshot,+): void {+ if (!sessionId) return;+ if (!snapshot.text.trim() && snapshot.fileReferences.length === 0) return;+ const entry: ComposerHistoryEntry = {+ text: snapshot.text,+ fileReferences: snapshot.fileReferences.map((reference) => ({ ...reference })),+ };+ const buckets = readBuckets();+ const current = buckets.find((bucket) => bucket.sessionId === sessionId);+ if (current?.entries[0] && sameContent(current.entries[0], entry)) {+ // Still the most recent conversation, even though the content repeats.+ writeBuckets([current, ...buckets.filter((bucket) => bucket !== current)]);+ return;+ }+ const entries = [entry, ...(current?.entries ?? [])].slice(0, COMPOSER_INPUT_HISTORY_MAX);+ // Newest-used bucket first, so the oldest conversation is the one dropped.+ writeBuckets([+ { sessionId, entries },+ ...buckets.filter((bucket) => bucket.sessionId !== sessionId),+ ].slice(0, COMPOSER_INPUT_HISTORY_SESSIONS_MAX));+}diff --git a/apps/desktop/test/composer-input-history.test.mjs b/apps/desktop/test/composer-input-history.test.mjsnew file mode 100644index 000000000..e14093002--- /dev/null+++ b/apps/desktop/test/composer-input-history.test.mjs@@ -0,0 +1,305 @@+import { readComposerModule, readComposerSource } from "./helpers/source-contracts.mjs";+import assert from "node:assert/strict";+import test from "node:test";+import {+ COMPOSER_INPUT_HISTORY_MAX,+ COMPOSER_INPUT_HISTORY_SESSIONS_MAX,+ loadComposerInputHistory,+ rememberComposerInput,+} from "../src/lib/composer-input-history.ts";+import {+ planHistoryNavigation,+ runHistoryStep,+ stepHistoryIndex,+} from "../src/features/chat/composer/input-history.ts";++const KEY = "pi.desktop.composerInputHistory";++function installStorage({ failWrites = false } = {}) {+ const data = new Map();+ const storage = {+ getItem: (key) => (data.has(key) ? data.get(key) : null),+ setItem: (key, value) => {+ if (failWrites) throw new Error("QuotaExceededError");+ data.set(key, String(value));+ },+ removeItem: (key) => data.delete(key),+ };+ Object.defineProperty(globalThis, "localStorage", {+ value: storage,+ configurable: true,+ writable: true,+ });+ return data;+}++test.afterEach(() => {+ delete globalThis.localStorage;+});++const snap = (text, fileReferences = []) => ({ text, fileReferences });+const texts = (sessionId) => loadComposerInputHistory(sessionId).map((entry) => entry.text);++/** Drive `runHistoryStep` the way `useComposerInputHistory.navigate` does. */+function createHarness(history, { sessionId = "s1" } = {}) {+ const state = {+ entries: [],+ index: null,+ applied: [],+ consumed: [],+ keptReferences: [],+ };+ const run = (direction, { draftEmpty, edited = false } = {}) => {+ const result = runHistoryStep({+ entries: state.entries,+ index: state.index,+ keptReferences: state.keptReferences,+ direction,+ draftEmpty,+ edited,+ loadHistory: () => (history === "store" ? loadComposerInputHistory(sessionId) : history),+ createReference: (reference) => ({ ...reference, attached: true }),+ effects: {+ applyDraft: (text, references, caret) => state.applied.push({ text, references, caret }),+ },+ });+ state.entries = result.entries;+ state.index = result.index;+ state.consumed.push(result.consumed);+ return result;+ };+ return { state, run };+}++test("records per conversation, newest-first, collapsing consecutive duplicates (AC1)", () => {+ installStorage();+ rememberComposerInput("s1", snap("a"));+ rememberComposerInput("s1", snap("b"));+ rememberComposerInput("s1", snap("b"));+ assert.deepEqual(texts("s1"), ["b", "a"]);+});++test("a conversation never recalls another conversation's prompts (AC1)", () => {+ installStorage();+ rememberComposerInput("s1", snap("from A"));+ rememberComposerInput("s2", snap("from B", [{ path: "C:\\w\\b.ts", name: "b.ts" }]));+ assert.deepEqual(texts("s1"), ["from A"]);+ assert.deepEqual(texts("s2"), ["from B"]);+ assert.deepEqual(texts("s3"), []);+ assert.deepEqual(texts(""), []);+ // The same text in another conversation is its own entry, not a duplicate.+ rememberComposerInput("s2", snap("from A"));+ assert.deepEqual(texts("s2"), ["from A", "from B"]);+});++test("skips empty submissions and caps one conversation's history (AC1)", () => {+ installStorage();+ rememberComposerInput("s1", snap(" "));+ assert.equal(loadComposerInputHistory("s1").length, 0);+ for (let i = 0; i < COMPOSER_INPUT_HISTORY_MAX + 5; i += 1) {+ rememberComposerInput("s1", snap(`m${i}`));+ }+ const history = loadComposerInputHistory("s1");+ assert.equal(history.length, COMPOSER_INPUT_HISTORY_MAX);+ assert.equal(history[0].text, `m${COMPOSER_INPUT_HISTORY_MAX + 4}`);+});++test("keeps a bounded number of conversations, newest written first (AC7)", () => {+ installStorage();+ for (let i = 0; i < COMPOSER_INPUT_HISTORY_SESSIONS_MAX; i += 1) {+ rememberComposerInput(`s${i}`, snap(`m${i}`));+ }+ // Re-writing the oldest conversation moves it to the front of the retention+ // order, so `s1` survives and the last-written conversation is dropped.+ rememberComposerInput("s0", snap("again"));+ rememberComposerInput(`s${COMPOSER_INPUT_HISTORY_SESSIONS_MAX}`, snap("newest session"));+ assert.deepEqual(texts("s0"), ["again", "m0"]);+ assert.deepEqual(texts("s1"), []);+ assert.deepEqual(texts(`s${COMPOSER_INPUT_HISTORY_SESSIONS_MAX}`), ["newest session"]);+});++test("corrupted or blocked storage yields an empty history (AC7)", () => {+ const data = installStorage();+ data.set(KEY, "{not json");+ assert.deepEqual(loadComposerInputHistory("s1"), []);+ data.set(KEY, JSON.stringify({ sessions: "nope" }));+ assert.deepEqual(loadComposerInputHistory("s1"), []);+ data.set(KEY, JSON.stringify([{ text: "legacy array shape" }]));+ assert.deepEqual(loadComposerInputHistory("s1"), []);+ data.set(+ KEY,+ JSON.stringify({+ sessions: [+ { sessionId: "s1", entries: [{ text: 1 }, { text: "ok", fileReferences: [] }] },+ { sessionId: "", entries: [] },+ { entries: [] },+ ],+ }),+ );+ assert.deepEqual(texts("s1"), ["ok"]);+ delete globalThis.localStorage;+ assert.deepEqual(loadComposerInputHistory("s1"), []);+ installStorage({ failWrites: true });+ assert.doesNotThrow(() => rememberComposerInput("s1", snap("x")));+});++test("browse index walks older, clamps, and unwinds (AC2)", () => {+ const len = 2;+ let index = null;+ const seen = [];+ for (const direction of ["older", "older", "older", "newer", "newer"]) {+ index = stepHistoryIndex(index, direction, len);+ seen.push(index);+ }+ assert.deepEqual(seen, [0, 1, 1, 0, null]);+ assert.equal(stepHistoryIndex(null, "newer", len), null);+ assert.equal(stepHistoryIndex(null, "older", 0), null);+});++test("an empty draft starts a browse and walks both directions (AC2)", () => {+ const plan = (index, direction, draftEmpty = true) =>+ planHistoryNavigation({ index, direction, length: 3, draftEmpty });+ assert.deepEqual(plan(null, "older"), { action: "load", index: 0 });+ assert.deepEqual(plan(0, "older"), { action: "load", index: 1 });+ assert.deepEqual(plan(2, "older"), { action: "keep" });+ assert.deepEqual(plan(2, "newer"), { action: "load", index: 1 });+ assert.deepEqual(plan(0, "newer"), { action: "exit" });+ assert.deepEqual(plan(null, "newer"), { action: "ignore" });+ assert.deepEqual(+ planHistoryNavigation({ index: null, direction: "older", length: 0, draftEmpty: true }),+ { action: "ignore" },+ );+});++test("an unsent draft and an edited entry keep the arrows native (AC3, AC4)", () => {+ assert.deepEqual(+ planHistoryNavigation({ index: null, direction: "older", length: 5, draftEmpty: false }),+ { action: "ignore" },+ );+ assert.deepEqual(+ planHistoryNavigation({ index: null, direction: "newer", length: 5, draftEmpty: false }),+ { action: "ignore" },+ );+ assert.deepEqual(+ planHistoryNavigation({ index: null, direction: "older", length: 5, draftEmpty: true }),+ { action: "load", index: 0 },+ );+});++test("recall walks this conversation's history and unwinds to empty (AC2)", () => {+ installStorage();+ rememberComposerInput("s1", snap("m1"));+ rememberComposerInput("s1", snap("m2"));+ rememberComposerInput("s1", snap("m3"));+ const { state, run } = createHarness("store", { sessionId: "s1" });+ run("older", { draftEmpty: true });+ run("older", { draftEmpty: false });+ run("older", { draftEmpty: false });+ run("older", { draftEmpty: false });+ run("newer", { draftEmpty: false });+ run("newer", { draftEmpty: false });+ run("newer", { draftEmpty: false });+ assert.deepEqual(+ state.applied.map((step) => step.text),+ ["m3", "m2", "m1", "m2", "m3", ""],+ );+ assert.deepEqual(state.consumed, [true, true, true, true, true, true, true]);+ assert.equal(state.index, null, "passing the newest entry leaves the draft empty");+ assert.equal(state.applied.at(-1).caret, 0);+});++test("a recalled entry brings its own references back (AC6)", () => {+ const entry = {+ text: "see the shot",+ fileReferences: [+ { path: "C:\\scratch\\s1\\a.png", name: "a.png", kind: "image", token: "\ue001" },+ { path: "src/foo.ts", name: "foo.ts", kind: "file", token: "\ue002" },+ ],+ };+ const { state, run } = createHarness([entry]);+ run("older", { draftEmpty: true });+ assert.equal(state.applied[0].text, "see the shot");+ assert.deepEqual(+ state.applied[0].references.map((reference) => reference.path),+ ["C:\\scratch\\s1\\a.png", "src/foo.ts"],+ );+ assert.equal(state.applied[0].caret, entry.text.length);+});++test("a fresh arrow with text and an edit behind the entry are both native (AC3, AC4)", () => {+ const history = [+ { text: "m2", fileReferences: [] },+ { text: "m1", fileReferences: [] },+ ];+ const { state, run } = createHarness(history);+ assert.equal(run("older", { draftEmpty: false }).consumed, false);+ assert.equal(run("newer", { draftEmpty: false }).consumed, false);+ assert.equal(state.applied.length, 0, "an unsent draft is never replaced");++ run("older", { draftEmpty: true });+ assert.equal(state.applied.length, 1);+ // The user typed into the recalled entry: the next arrow is a caret move.+ assert.equal(run("older", { draftEmpty: false, edited: true }).consumed, false);+ assert.equal(state.applied.length, 1);+ assert.equal(state.index, null, "editing ends browsing");+ // Deleting back to empty starts a fresh browse from the newest entry.+ run("older", { draftEmpty: true });+ assert.deepEqual(state.applied.at(-1).text, "m2");+});++test("keydown order: IME guard < autocomplete < history < send (AC5)", async () => {+ const source = await readComposerModule("ComposerInput.tsx");+ const start = source.indexOf("onKeyDown={(event: ReactKeyboardEvent");+ const handler = source.slice(start, source.indexOf(" />", start));+ const ime = handler.indexOf("event.nativeEvent.isComposing");+ const autocomplete = handler.indexOf("composerAc.hasItems");+ const history = handler.indexOf("onHistoryNavigate(");+ const send = handler.search(+ /event\.key === "Enter"\s*&&\s*!event\.shiftKey\s*&&\s*\(enterToSend/,+ );+ assert.ok(ime > -1 && autocomplete > ime, "IME guard runs before autocomplete");+ assert.ok(history > autocomplete, "autocomplete keeps arrow priority over history");+ assert.ok(send > history, "history branch precedes the send branch");+ const branch = handler.slice(handler.lastIndexOf("if (", history), history);+ for (const modifier of ["shiftKey", "altKey", "metaKey", "ctrlKey"]) {+ assert.ok(branch.includes(`!event.${modifier}`), `history ignores ${modifier} arrows`);+ }+});++test("history is recorded only on accepted submissions of the submitting conversation (AC1)", async () => {+ const source = await readComposerModule("hooks/useComposerSubmit.ts");+ assert.match(source, /const targetSessionId = activeSessionId \?\? useAppStore\.getState\(\)\.activeSessionId;/);+ assert.match(source, /if \(targetSessionId\) recordHistory\?\.\(submittedDraft, targetSessionId\);/);+ assert.match(+ source,+ /if \(!accepted\) draft\.restoreDraftForKey\(submittedDraftKey, submittedDraft\);\s*else remember\(\);/,+ );+ const blocked = source.slice(+ source.indexOf('dispatch.action === "blocked"'),+ source.indexOf('dispatch.action === "dispatch"'),+ );+ assert.ok(!blocked.includes("remember()"), "blocked slash commands are not recorded");+ const recordCalls = source.match(/remember\(\);/g) ?? [];+ assert.equal(recordCalls.length, 4, "mode, extension, palette, and prompt paths record");+});++test("the composer wires recall, its exits, and the record point (AC3)", async () => {+ const composer = await readComposerSource();+ const hook = await readComposerModule("hooks/useComposerInputHistory.ts");+ // The behaviour under test above is the one the hook actually runs.+ assert.match(hook, /runHistoryStep\(\{/);+ assert.match(hook, /loadHistory: \(\) => loadComposerInputHistory\(referenceSessionId\)/);+ assert.match(hook, /draft\.draftRevision\(draftKey\) !== appliedRevisionRef\.current/);+ assert.match(hook, /useEffect\(\(\) => \{\s*exitBrowsing\(\);\s*\}, \[draftKey\]\);/);+ assert.match(composer, /onInput=\{\(source, caret\) => \{\s*inputHistory\.exitBrowsing\(\);/);+ assert.match(composer, /onHistoryNavigate=\{inputHistory\.navigate\}/);+ assert.match(composer, /recordHistory: inputHistory\.record/);+ // Both submit entry points — the composer's Enter and the toolbar's Send —+ // leave browsing before the draft is cleared.+ assert.match(+ composer,+ /const submitFromComposer = \(steering\?: boolean\) => \{\s*inputHistory\.exitBrowsing\(\);\s*return submit\(steering\);\s*\};/,+ );+ assert.match(composer, /onSubmit=\{\(steering\) => void submitFromComposer\(steering\)\}/);+ assert.match(composer, /submit=\{submitFromComposer\}/);+});diff --git a/docs/spec/04-ux/09-interaction-patterns.md b/docs/spec/04-ux/09-interaction-patterns.mdindex 6a48c4577..0df410596 100644--- a/docs/spec/04-ux/09-interaction-patterns.md+++ b/docs/spec/04-ux/09-interaction-patterns.md@@ -374,6 +374,20 @@ may be retained while exactly one workspace supplies the visible shell context.completed send clears only the draft belonging to the session that submittedit, even if the user switches sessions while the request is in flight;deleted sessions cannot retain drafts.+- The composer also recalls the accepted submissions of its own conversation,+ newest-first, with ArrowUp/ArrowDown (D625). ArrowUp starts browsing only when+ the draft is empty (no text and no references), and while browsing both keys+ keep walking history even through a multi-line entry; ArrowDown past the+ newest entry returns to the empty draft. A user edit, a submission, or a+ session change ends browsing, after which the arrows are native caret movement+ again. The open autocomplete menu and IME composition keep priority. Another+ conversation's prompts are never recalled, so a recalled entry always brings+ its own file and image references back with its text. History survives a+ restart (renderer-local `localStorage`: 100 entries per conversation, 20+ conversations, consecutive duplicates collapsed) and records only accepted+ submissions: a normal or steering prompt, or a dispatched slash, extension, or+ mode command. The empty home composer has no conversation, so it recalls+ nothing.- Every tool call resolves `workspaceRoot` from the originating durablesession, not from the currently selected project tab. Background completionrefreshes the matching row without redirecting the active conversation.diff --git a/docs/spec/06-delivery/04-e2e-test-plan.md b/docs/spec/06-delivery/04-e2e-test-plan.mdindex 877f801d5..02f0da587 100644--- a/docs/spec/06-delivery/04-e2e-test-plan.md+++ b/docs/spec/06-delivery/04-e2e-test-plan.md@@ -1459,6 +1459,45 @@ identify the platform validation still needed.`pnpm test:e2e:composer-paste`; real desktop recording uses isolated data anda local model with a controlled response delay.+#### E2E-COMPOSER-input-history-recall++- **Preconditions**: Provider configured; the composer history store+ (`pi.desktop.composerInputHistory`) is empty or at a known state; sessions A+ and B exist, with A docked and B available to select.+- **Steps**: 1) In A send `alpha`, then `beta`, then `beta` again. 2) With the+ composer empty, press ArrowUp three times, then ArrowDown three times.+ 3) Press ArrowUp once, type one character, and press ArrowUp again.+ 4) Press ArrowUp, then send once and confirm the next ArrowUp starts from the+ newest entry again. 5) Reopen the app and press ArrowUp in the composer.+ 6) Type `@` to open the file menu and press ArrowUp/ArrowDown, then close it.+ 7) Recall a multi-line entry with ArrowUp and keep pressing ArrowUp/ArrowDown.+ 8) Send a prompt carrying a pasted image and a workspace `@` file, then recall+ it in A. 9) Switch to B, press ArrowUp in B's empty composer, then send `beta`+ in B and press ArrowUp there. 10) Return to A and press ArrowUp. 11) Select+ all, delete, and press ArrowUp. 12) Open the empty home composer (New task+ before any first prompt) and press ArrowUp.+- **Expected**: History is newest-first within A and `beta` is recorded once.+ ArrowUp loads `beta`, then `alpha`, then stays on `alpha`; ArrowDown returns to+ `beta` and then leaves the composer empty. Typing a character ends browsing, so+ the following ArrowUp moves the caret instead of replacing the text. After a+ send, recall starts from the newest entry. History survives a restart. With the+ autocomplete menu open the arrows still move its highlight and never touch+ history. A recalled multi-line entry keeps working with the arrows. The entry+ recalled in A shows its image chip and its file chip again. B's empty composer+ recalls nothing from A; once B sends `beta`, ArrowUp in B loads B's own `beta`+ and stops there, and A's history is unchanged on returning. An emptied composer+ browses history again, and the empty home composer recalls nothing. IME+ composition is unaffected.+- **Specs linked**: `04-ux/09-interaction-patterns.md`,+ `08-meta/decisions-log.md` (D625), `04-ux/08-component-spec.md`+- **Acceptance**: C (composer input and session isolation)+- **Milestone**: M2+- **Status**: Source-level regression covered+ (`composer-input-history.test.mjs`: store rules, per-conversation isolation,+ browse stepping, restored references, keydown branch order, record points).+ Real recall loop in the desktop renderer, the reopened-app case, and the+ rendered chips are Draft.+#### E2E-011d: New task creates an immediate durable empty slot- **Preconditions**: Provider configured; at least one real session exists sodiff --git a/docs/spec/08-meta/decisions-log.md b/docs/spec/08-meta/decisions-log.mdindex 23d429bff..25b365510 100644--- a/docs/spec/08-meta/decisions-log.md+++ b/docs/spec/08-meta/decisions-log.md@@ -437,6 +437,7 @@ section mirrors only marketplace/catalog items still blocking nothing.| D123 | Composer slash commands, three sources | **Typing `/` at position 0 of the composer opens an inline command menu merging (a) pi prompt templates from `<workspace>/.pi/prompts/*.md` and `~/.pi/agent/prompts/*.md` (project overrides user-global on name conflict; frontmatter `description`/`argument-hint`), (b) builtin palette commands through slash aliases defined in one registry shared with palette search, and (c) plugin palette commands. On send, builtin/plugin invocations execute locally through the existing renderer switch / `commandPalette/execute` without creating a session or prompting the model; template invocations are expanded in the Electron main `agent/prompt` handler before persistence (`parseCommandArgs` + `substituteArgs` from pi-agent-core), persisting `content = expanded` plus a new optional `command` field carrying the typed form; unknown `/foo` is sent as literal text.** | Reuses pi's exact CLI semantics and template assets, keeps agent reseed faithful (reseed replays `content`), and keeps the transcript readable by rendering the typed invocation as a chip (ADR 0024). || D124 | `@` file references are plain-text light references | **`@` at a token boundary opens a fuzzy file menu over a workspace index served by the new Electron-only channel `pi-desktop/fs/index` (files+dirs, `git ls-files -co --exclude-standard` fast path with ignore-set walk fallback, 8000-entry cap with truncation flag, short TTL cache, workspace-rooted, fails soft without a workspace). Accepting creates the canonical `@rel/path ` reference for files (quoted `@"a b.txt" ` when the path has spaces) and inserts `@dir/` without trailing space for directories; D209 amends completed-file draft presentation without changing the dispatched plain-text path. The model follows references with its Read tool in both Plan and Agent. No prompt content inlining or provider attachment conversion; clipboard file materialization is defined by D197.** | Matches pi CLI's model-facing semantics, avoids context inflation and truncation rules, and keeps user-driven file browsing out of the agent tool/permission path per ADR 0019. || D125 | Composer autocomplete interaction and IME contract | **One menu component anchored above the composer, full composer width, focus always stays in the textarea. Keys while open: ↑/↓ cycle with wraparound, Enter/Tab accept, Escape closes only the menu (takes precedence over the composer's clear/blur Escape), typing filters live; Enter never sends while an item is highlighted, and an empty result list counts as closed. The menu closes on outside mousedown, blur, deleting past the trigger character, or session switch. All key handling and trigger detection sit behind the IME guard (`isComposing || keyCode === 229` plus composition start/end tracking): during composition nothing triggers, updates, or intercepts, and state is re-evaluated on compositionend.** | First explicit IME rule in the spec — zh-CN Enter-to-send plus candidate confirmation must never fight the menu; uniform insert-then-dispatch keeps two-Enter flows fast and predictable. |+| D625 | Composer input history recall with ArrowUp/ArrowDown | **Amend D125 / D209 / D301: the accepted submissions of one conversation — a normal or steering prompt and a dispatched slash, extension, or mode command — are recorded newest-first in renderer-local `localStorage` (`pi.desktop.composerInputHistory`, one bounded bucket per conversation held newest-written-first, 100 entries per conversation, 20 conversations, consecutive duplicates collapsed) with the draft text and its file-reference snapshot, and recalling shows only that conversation's prompts. With the autocomplete menu closed and the draft empty (no text and no references), ArrowUp loads the newest entry and further ArrowUp walks older entries to the oldest; ArrowDown walks newer entries and past the newest returns to the empty draft. While browsing, both keys keep driving history even for a multi-line entry; any user input event, a submission, or a draft-key (session) change ends browsing, after which arrows are native again. IME composition and an open autocomplete menu keep priority over history. Because an entry is always recalled in the conversation that sent it, its file and image references are restored with its text, and no cross-conversation notice or i18n string exists. The caret moves to the end of the recalled text; the empty home composer (no conversation) recalls nothing, and a prompt sent from home is recorded in the conversation that submission materialized. Storage is best-effort: a missing, blocked, or corrupted store reads as empty and never breaks sending. No protocol, host, storage-schema, permission, theme, or packaging change. See `04-ux/09-interaction-patterns.md` and E2E-COMPOSER-input-history-recall.** | Retyping or re-copying a previous instruction is the most repeated composer action, and the app already keeps renderer-local MRU history for the plugin launcher (D219). Scoping the history to the conversation keeps a recalled draft's context intact and makes attachment restoration unconditional, because attachments live in that conversation's own scratch directory. || D197 | Composer clipboard files become session-scratch references | **When the composer clipboard contains one or more OS files/images, the renderer intercepts the file paste, transfers bounded bytes plus name/MIME metadata through the Electron-only `pi-desktop/composer/pasteFiles` channel, and includes the durable session id. Electron main verifies the session, sanitizes names, and writes unique files below `<data_dir>/scratch/<sessionId>/pasted/`; D209 amends the draft presentation while preserving each returned absolute path as the quoted-or-unquoted `@` reference sent to the agent. Text-only paste remains native. A home composer creates or reuses a durable session first. Clipboard bytes never enter the prompt, workspace, or artifact store, and session deletion removes the pasted files with the scratch root.** | Fixes the broken file/image paste path without dirtying the project or inventing provider-specific binary prompt plumbing; it reuses the existing scratch containment and lifecycle contract. || D209 | Composer file references separate compact display from canonical prompt paths | **Completed workspace-file selections and materialized clipboard files become renderer-owned, session-scoped reference chips. A chip persistently displays only the leaf name, exposes the canonical path through tooltip/accessibility metadata, and can be removed without deleting scratch bytes. Immediately before submit, references serialize in stable order after the visible draft with D124's exact quoting, so reference-only drafts, slash templates, and Agent/Plan/Goal mode aliases retain their current behavior. Accepted dispatch clears the active editor but keeps a renderer-only, turn-scoped pre-serialization snapshot while smart Stop can still undo an unanswered send. That undo restores the original text and chips rather than prefilling serialized message content; abort after reply start keeps the partial transcript and restores nothing. Rejected/failed sends retain the active draft. `ComposerPastedFile.name` is the sanitized original leaf label while `path` retains the UUID-backed absolute storage identity. No binary payload, provider attachment, host RPC, or schema is added.** *(amended by D362: chips are inline sentinel-backed elements in the contenteditable draft)* | Long relative paths and UUID-backed scratch paths overwhelmed the prompt row even though only the agent needs them. Separating presentation from serialization preserves exact tool-readable paths, duplicate-name identity, textarea/IME behavior, and the text-only provider contract (ADR 0070). || D362 | Accepted `@` files insert the same inline chip as paste | **Amend D209 / D125 in the renderer: accepting a completed workspace file from the `@` menu (Enter, Tab, or click) replaces the trigger token with one private-use sentinel in the draft and stores that token on the reference, the same path clipboard paste already uses. The chip paints at the caret; that confirmation never sends. Directories still insert `@dir/` as text. Token-less references are not a visible draft surface. Workspace-relative chips still drop on project switch; absolute scratch/paste paths stay. No IPC, storage, host-protocol, or schema change.** | After chips moved inline, file accept still stripped `@query` and stored a token-less reference that no longer painted, so Enter made the file vanish. |@@ -7067,3 +7068,52 @@ must keep splitting are covered by `markdown-blocks.test.mjs`.`--composer-dock-height`. There is no scroll state, protocol, persistence,theme schema, or permission change. See `04-ux/08-component-spec.md` andE2E-CHAT-opaque-floating-decision-and-retry-surfaces.++## 2026-09-25 — Composer recalls its own conversation's submissions with ArrowUp/ArrowDown (D625)++- The composer had no way to reuse what was just sent: repeating or tweaking an+ instruction meant retyping it or copying it back out of the transcript, even+ though a terminal, a shell history, and this app's own plugin launcher (D219)+ all keep recent input one keystroke away.+- The history belongs to the conversation. Recalling shows only the prompts+ accepted in the conversation on screen, so a draft never appears with another+ conversation's context and a deleted conversation's prompts cannot surface in a+ live one. Store shape: one renderer-local `localStorage` key+ (`pi.desktop.composerInputHistory`) holding bounded buckets newest-written+ first, 100 entries per conversation and 20 conversations, with consecutive+ duplicates collapsed. No schema, host, or IPC change.+- Scoping by conversation also settles attachments. Picked, pasted, and dropped+ files are copied into the sending session's scratch directory, and the image+ input loader accepts them only under the current project, the current session+ scratch, or `data_dir/attachments`; a recalled entry therefore always belongs+ to the session whose scratch root holds its files, so its chips and previews+ come back with its text and no "attachments were left behind" notice is+ needed. (An earlier shape of this change kept one global history and stripped+ attachments on a cross-session recall, which is why that notice and its i18n+ string existed; both are gone.)+- Recording happens only on an accepted submission. The four accept paths — a+ normal or steering prompt, a dispatched extension command, a dispatched+ builtin or palette command, and a mode command with a body — record the+ submitted draft under the submitting conversation; a blocked slash source, an+ unconfigured model, an empty draft, and a rejected send do not. A rejected send+ restores its draft exactly as before and leaves history untouched. The empty+ home composer has no conversation, so it recalls nothing, and a prompt sent+ from home is recorded under the session that submission materialized — the+ first prompt of a new conversation is recallable from inside it.+- ArrowUp starts browsing only from an empty draft (no text and no references),+ which is what keeps the feature out of the way of a multi-line draft where the+ same key has to move the caret. Once browsing, ↑/↓ keep driving history —+ including through a recalled multi-line entry — until a user edit, a+ submission, or a conversation change (the draft key) ends browsing. IME+ composition and an open autocomplete menu are checked first, so ↑/↓ still cycle+ menu items and a confirming Enter during composition still commits text rather+ than sending it (D125).+- Storage is best-effort, matching `plugin-launcher-history.ts`: an unreadable+ store, malformed JSON, a row that fails validation, a payload in the earlier+ array shape, or a throwing `setItem` degrades to no history instead of failing+ a send. The source-level coverage in `composer-input-history.test.mjs` pins the+ per-conversation isolation, the caps, the browse sequence, the restored+ references, the keydown branch order (IME guard, autocomplete, history, send),+ the four record points, and the exit points; the real recall loop in the+ renderer and the rendered chips remain a Draft UI scenario+ (E2E-COMPOSER-input-history-recall).