Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins
TypeScript ai-agentcoding-agentdesktop-appelectronglobali18nlocal-firstmcppipi-agentpi-desktoppluginsreactrusttypescript
fix(chat): record composer history in submitting session
vastsabcd00db8f647
diff --git a/apps/desktop/src/features/chat/composer/hooks/useComposerSubmit.ts b/apps/desktop/src/features/chat/composer/hooks/useComposerSubmit.tsindex 8c73cbfd7..fbb1649c2 100644--- a/apps/desktop/src/features/chat/composer/hooks/useComposerSubmit.ts+++ b/apps/desktop/src/features/chat/composer/hooks/useComposerSubmit.ts@@ -18,6 +18,7 @@ import {resolveSlashDispatch,} from "../slash-dispatch";import { readEditorValue, setEditorCaret, type ComposerFileReference } from "../editor";+import type { ComposerDraftSnapshot } from "../../../../lib/composer-smart-stop";import type { ComposerDraftController } from "./useComposerDraft";type UseComposerSubmitOptions = {@@ -217,9 +218,12 @@ export function useComposerSubmit({// 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.+ let acceptedSessionId = activeSessionId ?? undefined;const remember = () => {- const targetSessionId = activeSessionId ?? useAppStore.getState().activeSessionId;- if (targetSessionId) recordHistory?.(submittedDraft, targetSessionId);+ if (acceptedSessionId) recordHistory?.(submittedDraft, acceptedSessionId);+ };+ const captureAcceptedSession = (sessionId: string) => {+ acceptedSessionId = sessionId;};// Slash dispatch stays local for builtin and extension commands, while// templates, skills, and unknown aliases continue as normal prompt text. A@@ -260,6 +264,8 @@ export function useComposerSubmit({activeFileReferences,),draft.draftSnapshot(visibleCommandBody),+ activeSessionId ?? undefined,+ captureAcceptedSession,);if (accepted) draft.clearDraftForKey(submittedDraftKey, submittedDraftRevision, submittedDraft);if (accepted) remember();@@ -304,7 +310,12 @@ export function useComposerSubmit({draft.clearDraftForKey(submittedDraftKey, submittedDraftRevision, submittedDraft);const accepted = steering? await steerPrompt(inlineContent, submittedDraft)- : await sendPrompt(inlineContent, submittedDraft);+ : await sendPrompt(+ inlineContent,+ submittedDraft,+ activeSessionId ?? undefined,+ captureAcceptedSession,+ );if (!accepted) draft.restoreDraftForKey(submittedDraftKey, submittedDraft);else remember();};diff --git a/apps/desktop/src/stores/app-state.ts b/apps/desktop/src/stores/app-state.tsindex 1e70dfc1d..6ce0c0ad8 100644--- a/apps/desktop/src/stores/app-state.ts+++ b/apps/desktop/src/stores/app-state.ts@@ -214,6 +214,7 @@ export type AppState = {content: string,draft?: ComposerDraftSnapshot,targetSessionId?: string,+ onAccepted?: (sessionId: string) => void,) => Promise<boolean>;steerPrompt: (content: string, draft?: ComposerDraftSnapshot) => Promise<boolean>;enqueuePrompt: (diff --git a/apps/desktop/src/stores/slices/queue-slice.ts b/apps/desktop/src/stores/slices/queue-slice.tsindex 64163a88f..956ae40fe 100644--- a/apps/desktop/src/stores/slices/queue-slice.ts+++ b/apps/desktop/src/stores/slices/queue-slice.ts@@ -370,7 +370,7 @@ export function createQueueSlice({}},- sendPrompt: async (content, draft, requestedSessionId) => {+ sendPrompt: async (content, draft, requestedSessionId, onAccepted) => {let sessionId = requestedSessionId ?? get().activeSessionId;const submissionKey = sessionId ? `session:${sessionId}` : "draft";if (pendingSubmissions.has(submissionKey)) return false;@@ -404,6 +404,7 @@ export function createQueueSlice({return false;}const accepted = await get().enqueuePrompt(content, draft, sessionId);+ if (accepted) onAccepted?.(sessionId);return accepted;}const startedIn = sessionId;@@ -478,6 +479,7 @@ export function createQueueSlice({if (submitted?.abortResolution && (await submitted.abortResolution)) {return false;}+ onAccepted?.(startedIn);return true;} catch (error) {runtime.submittedComposerDrafts.delete(startedIn);diff --git a/apps/desktop/test/composer-input-history.test.mjs b/apps/desktop/test/composer-input-history.test.mjsindex e14093002..1b225d262 100644--- a/apps/desktop/test/composer-input-history.test.mjs+++ b/apps/desktop/test/composer-input-history.test.mjs@@ -1,4 +1,4 @@-import { readComposerModule, readComposerSource } from "./helpers/source-contracts.mjs";+import { readComposerModule, readComposerSource, readStoreModule } from "./helpers/source-contracts.mjs";import assert from "node:assert/strict";import test from "node:test";import {@@ -266,10 +266,12 @@ test("keydown order: IME guard < autocomplete < history < send (AC5)", async ()}});-test("history is recorded only on accepted submissions of the submitting conversation (AC1)", async () => {+test("accepted history uses sendPrompt's materialized session, not later global selection", 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, /let acceptedSessionId = activeSessionId \?\? undefined;/);+ assert.match(source, /const captureAcceptedSession = \(sessionId: string\) => \{\s*acceptedSessionId = sessionId;/);+ assert.match(source, /activeSessionId \?\? undefined,\s*captureAcceptedSession/);+ assert.match(source, /if \(acceptedSessionId\) recordHistory\?\.\(submittedDraft, acceptedSessionId\);/);assert.match(source,/if \(!accepted\) draft\.restoreDraftForKey\(submittedDraftKey, submittedDraft\);\s*else remember\(\);/,@@ -279,6 +281,30 @@ test("history is recorded only on accepted submissions of the submitting converssource.indexOf('dispatch.action === "dispatch"'),);assert.ok(!blocked.includes("remember()"), "blocked slash commands are not recorded");+});++test("sendPrompt returns the accepted session for Home history recording", async () => {+ const source = await readStoreModule("slices/queue-slice.ts");+ const sendPrompt = source.slice(+ source.indexOf("sendPrompt: async (content, draft, requestedSessionId, onAccepted)"),+ );+ assert.ok(sendPrompt.length > 0, "sendPrompt implementation not found");+ assert.match(+ sendPrompt,+ /await api\.prompt\(\{[\s\S]*?\}\);[\s\S]*?onAccepted\?\.\(startedIn\);\s*return true/,+ );+ assert.match(+ sendPrompt,+ /const accepted = await get\(\)\.enqueuePrompt\(content, draft, sessionId\);\s*if \(accepted\) onAccepted\?\.\(sessionId\);\s*return accepted/,+ );+ const submit = await readComposerModule("hooks/useComposerSubmit.ts");+ assert.match(submit, /captureAcceptedSession = \(sessionId: string\) => \{\s*acceptedSessionId = sessionId;/);+ assert.match(submit, /activeSessionId \?\? undefined,\s*captureAcceptedSession/);+ assert.doesNotMatch(submit, /activeSessionId \?\? useAppStore\.getState\(\)\.activeSessionId/);+});++test("history is recorded across the accepted composer paths", async () => {+ const source = await readComposerModule("hooks/useComposerSubmit.ts");const recordCalls = source.match(/remember\(\);/g) ?? [];assert.equal(recordCalls.length, 4, "mode, extension, palette, and prompt paths record");});diff --git a/apps/desktop/test/composer-send-state.test.mjs b/apps/desktop/test/composer-send-state.test.mjsindex d772e40eb..584e375d5 100644--- a/apps/desktop/test/composer-send-state.test.mjs+++ b/apps/desktop/test/composer-send-state.test.mjs@@ -283,17 +283,21 @@ test("mode slash prefixes send the trailing prompt and retain failed drafts", ());assert.match(submit,- /const submittedDraftRevision = draft\.draftRevision\(submittedDraftKey\);\s*const submittedDraft = draft\.draftSnapshot\(text\);[\s\S]*?draft\.clearDraftForKey\(submittedDraftKey, submittedDraftRevision, submittedDraft\);\s*const accepted = steering[\s\S]*?await steerPrompt\(inlineContent, submittedDraft\)[\s\S]*?await sendPrompt\(inlineContent, submittedDraft\);\s*if \(!accepted\) draft\.restoreDraftForKey\(submittedDraftKey, submittedDraft\);/,+ /const submittedDraftRevision = draft\.draftRevision\(submittedDraftKey\);\s*const submittedDraft = draft\.draftSnapshot\(text\);[\s\S]*?draft\.clearDraftForKey\(submittedDraftKey, submittedDraftRevision, submittedDraft\);\s*const accepted = steering\s*\?\s*await steerPrompt\(inlineContent, submittedDraft\)\s*:\s*await sendPrompt\(\s*inlineContent,\s*submittedDraft,\s*activeSessionId \?\? undefined,\s*captureAcceptedSession,\s*\);\s*if \(!accepted\) draft\.restoreDraftForKey\(submittedDraftKey, submittedDraft\);/,);assert.match(store, /draft\?: ComposerDraftSnapshot/);const sendPrompt = queueSlice.slice(- queueSlice.indexOf("sendPrompt: async (content, draft, requestedSessionId)"),+ queueSlice.indexOf("sendPrompt: async (content, draft, requestedSessionId, onAccepted)"),);assert.match(sendPrompt, /return false;/);assert.match(sendPrompt,// The prompt call carries the submitted content and attachment mapping.- /await api\.prompt\(\{[\s\S]*?sessionId,[\s\S]*?content,[\s\S]*?attachments:[\s\S]*?promptAttachmentsFromDraft\(draft\.fileReferences\)[\s\S]*?\}\);[\s\S]*?return true/,+ /await api\.prompt\(\{[\s\S]*?sessionId,[\s\S]*?content,[\s\S]*?attachments:[\s\S]*?promptAttachmentsFromDraft\(draft\.fileReferences\)[\s\S]*?\}\);[\s\S]*?onAccepted\?\.\(startedIn\);\s*return true/,+ );+ assert.match(+ sendPrompt,+ /const accepted = await get\(\)\.enqueuePrompt\(content, draft, sessionId\);\s*if \(accepted\) onAccepted\?\.\(sessionId\);\s*return accepted/,);});@@ -350,7 +354,7 @@ test("draft attachment routing keeps image chips structured and file chips textutest("the user row is inserted before the host round trip and echoed under the same id (D288)", () => {const sendPrompt = queueSlice.slice(- queueSlice.indexOf("sendPrompt: async (content, draft, requestedSessionId)"),+ queueSlice.indexOf("sendPrompt: async (content, draft, requestedSessionId, onAccepted)"),);assert.ok(sendPrompt.length > 0, "sendPrompt not found");const insertAt = sendPrompt.indexOf("insertOptimisticUserMessage(startedIn, optimisticMessage)");diff --git a/docs/spec/04-ux/09-interaction-patterns.md b/docs/spec/04-ux/09-interaction-patterns.mdindex 9c9dc0a1b..096b8543c 100644--- a/docs/spec/04-ux/09-interaction-patterns.md+++ b/docs/spec/04-ux/09-interaction-patterns.md@@ -375,7 +375,7 @@ may be retained while exactly one workspace supplies the visible shell context.it, 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+ newest-first, with ArrowUp/ArrowDown (D632). ArrowUp starts browsing only whenthe draft is empty (no text and no references), and while browsing both keyskeep walking history even through a multi-line entry; ArrowDown past thenewest entry returns to the empty draft. A user edit, a submission, or a@@ -387,7 +387,8 @@ may be retained while exactly one workspace supplies the visible shell context.conversations, consecutive duplicates collapsed) and records only acceptedsubmissions: a normal or steering prompt, or a dispatched slash, extension, ormode command. The empty home composer has no conversation, so it recalls- nothing.+ nothing; its accepted prompt is stored under the session ID returned by the+ submission flow, even if the user navigates elsewhere before acceptance.- 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 e561450d3..312c82033 100644--- a/docs/spec/06-delivery/04-e2e-test-plan.md+++ b/docs/spec/06-delivery/04-e2e-test-plan.md@@ -1490,42 +1490,32 @@ identify the platform validation still needed.#### 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.+- **Preconditions**: Isolated Electron test profile and the production Composer+ input/draft/history/submit hooks mounted in the renderer fixture. The send+ boundary is deterministic; no provider or network credentials are needed.+- **Steps**: 1) In session A, send `alpha`, `beta`, and `beta` again through+ Enter; press ArrowUp twice and ArrowDown twice. 2) Edit a recalled draft and+ confirm arrows no longer replace it. 3) Send a prompt with a file reference,+ recall it, and inspect the rendered chip. 4) Switch to B, verify A's history+ is absent, send `beta`, and verify B recalls only its own entry. 5) Start the+ first Home prompt with the send boundary held, switch to B before acceptance,+ release it, then open the materialized session and recall the prompt. 6) Exit+ Electron and launch a new process with the same isolated profile; recall A's+ attachment entry and the Home-created session's prompt.+- **Expected**: Duplicate consecutive `beta` is stored once; ArrowUp/ArrowDown+ walk newest-to-oldest and back to an empty draft. Editing ends browsing.+ Attachment text and its rendered file chip return together. Sessions A and B+ remain isolated. The delayed Home send is recorded under the session ID+ materialized by `sendPrompt`, not the session selected when the send finishes.+ Both histories and the attachment survive a real Electron process restart.- **Specs linked**: `04-ux/09-interaction-patterns.md`,- `08-meta/decisions-log.md` (D625), `04-ux/08-component-spec.md`+ `08-meta/decisions-log.md` (D632), `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.+- **Status**: Automated by `pnpm test:e2e:composer-paste` (renderer keyboard+ interactions, Home session switch, attachment recall, and second-process+ persistence); store callback race regression is covered by+ `apps/desktop/test/composer-input-history.test.mjs`.#### E2E-011d: New task creates an immediate durable empty slotdiff --git a/docs/spec/08-meta/decisions-log.md b/docs/spec/08-meta/decisions-log.mdindex 4130b880e..b863014db 100644--- a/docs/spec/08-meta/decisions-log.md+++ b/docs/spec/08-meta/decisions-log.md@@ -439,7 +439,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. |+| D632 | 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. |@@ -7250,9 +7250,11 @@ must keep splitting are covered by `markdown-blocks.test.mjs`.submitted draft under the submitting conversation; a blocked slash source, anunconfigured model, an empty draft, and a rejected send do not. A rejected sendrestores 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.+ home composer has no session, so it recalls nothing. On acceptance,+ `sendPrompt` passes the actual target session ID to history recording; it is+ not inferred by rereading global `activeSessionId` after the asynchronous send.+ Thus a Home-first send that finishes after navigation remains in the session+ that the submission materialized.- 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 thesame key has to move the caret. Once browsing, ↑/↓ keep driving history —@@ -7264,9 +7266,11 @@ must keep splitting are covered by `markdown-blocks.test.mjs`.- Storage is best-effort, matching `plugin-launcher-history.ts`: an unreadablestore, malformed JSON, a row that fails validation, a payload in the earlierarray 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).+ a send.+- `composer-input-history.test.mjs` covers storage, per-conversation navigation,+ and the `sendPrompt` callback retaining the materialized session across a+ selection change. `pnpm test:e2e:composer-paste` mounts the production input,+ draft, history, and submit hooks in an Electron renderer; it checks keyboard+ navigation, session isolation, a rendered file chip, the delayed Home-send+ switch, and restoration from a second Electron process using the same test+ profile (E2E-COMPOSER-input-history-recall).diff --git a/docs/zh-CN/spec/08-meta/decisions-log.md b/docs/zh-CN/spec/08-meta/decisions-log.mdindex 3d8914985..25a0e5f00 100644--- a/docs/zh-CN/spec/08-meta/decisions-log.md+++ b/docs/zh-CN/spec/08-meta/decisions-log.md@@ -461,6 +461,7 @@| D152 | 直接运行时流渲染 | **辅助内容直接通过增量 Markdown 块缓存渲染每个运行时流块。渲染器不添加 requestAnimationFrame 打字机状态循环。 KaTeX 的 Vite 内联字体仍然是本地资源,并被狭窄的 `font-src 'self' data:` CSP 指令所允许。** | 重复的动画循环可能会在持续流期间触发 React 的嵌套更新防护,而之前的 CSP 会阻止捆绑的数学字体并产生控制台错误。 || D153 | 推理会话默认为最大思考 | *(由 D303 取代)* **新创建的会话(其继承的默认模型支持推理)从该模型的 pi 发布的 `supportedThinkingLevels` 中的最高规范条目开始。非推理模型和缺失的能力元数据从 `off` 开始;现有会议保留其持久选择。这改进了 D096,而无需添加提供程序覆盖。** | 具有推理能力的模型应该默认使用最强大的可用努力,同时保留明确的每会话选择和 pi-ai 的模型权威。 || D264 | Composer 输入避开全量排序与冗余 DOM 写入 | **`@` 文件菜单用有界 top-K 选择从匹配列表中挑出可见行,而不再排序全部匹配;该选择返回的行集合与顺序与完整排序完全一致,而较小且按命令类型分组的命令列表保留完整排序。Composer 自动调整高度与 `--composer-dock-height` 发布都是幂等的:高度未变化时不做 DOM 写入,也不会使整个文档样式失效,`height: auto` 测量探针仅在文本框可能需要收缩时读取。增长到七行、超过第七行后内部滚动,以及 delete/submit 后的收缩均保持不变。当一次按键既未改变草稿文件引用状态也未改变光标位置时,两者都保持原有的身份与取值,因此草稿缓存序列化 effect 和自动完成触发检测不再每次按键都重跑。不改动 IPC、存储、主机协议或 schema。** | 在大型工作区中打开 `@` 菜单时,每次按键都要对整个 8000 条的文件索引做一次完整排序才显示 50 行,还要为测量探针付一次强制同步重排,而每次按键新建的 `fileReferences` 数组身份又会重跑草稿缓存序列化 effect。代价是输入延迟而非正确性;与完整排序的顺序等价性由单元测试覆盖。 |+| D632 | Composer 按 ↑/↓ 召回当前会话的提交历史 | **修订 D125 / D209 / D301:每个会话仅记录已接受的常规或 steering 提示,以及已派发的 slash、扩展和模式命令;记录按新到旧存入渲染器 `localStorage`(`pi.desktop.composerInputHistory`),每会话最多 100 条、最多 20 个会话,连续重复项合并。空草稿按 ↑ 开始召回,↑/↓ 在历史中导航,越过最新项后恢复为空;编辑、提交或切换会话会结束浏览,IME 与自动补全优先。召回同时恢复该会话自己的文件和图片引用;首页无会话时不提供召回。首页首条消息被接受时,提交流程将实际 materialize 的 sessionId 回传给历史记录器,不再于异步结束后读取全局活动会话,因此导航竞态不会串写历史。不改协议、host、schema、权限、主题或打包。** | 重复输入指令无需重打;按会话隔离可保持上下文一致,并可无条件恢复存于该会话 scratch 目录的附件。 |## T. 发布交付决策@@ -5094,3 +5095,17 @@ Markdown 源码,不是 `text/html` 负载;对禁用行内 HTML 的外部编- 该变化只影响元数据和 UI 投影,不改写持久化 wire ID、提供商身份或 host 能力归属。参见`03-runtime/13-model-catalog-and-selection.md` §11.3 与`04-ux/08-component-spec.md` §11。+## 2026-09-27 —— Composer 用 ↑/↓ 召回当前会话已提交的内容(D632)++- 重复使用上一条指令是 Composer 中常见操作。历史保存在渲染器本地+ `localStorage`(键 `pi.desktop.composerInputHistory`),按会话分桶,+ 每个会话保留最近 100 条、最多保留 20 个会话;连续重复内容只记录一次。+- 只有成功接受的提示或已派发命令会进入历史。首页没有会话时不召回;+ 首页首条消息发送成功后,`sendPrompt` 将实际创建的 sessionId 回传给记录器。+ 即使请求等待期间用户切换会话,历史仍写入原提交 materialize 的会话。+- 空草稿按 ↑ 召回最新内容,↑/↓ 可继续遍历;越过最新项回到空草稿。+ 编辑、提交或会话切换结束浏览;IME 组字和打开的自动补全菜单优先处理按键。+ 同会话附件随历史一起恢复,不会从其他会话召回。+- `composer-input-history.test.mjs` 覆盖存储、导航和 sessionId 回传竞态;+ `pnpm test:e2e:composer-paste` 覆盖真实渲染器键盘操作、附件芯片、发送期间+ 切换会话,以及重启 Electron 进程后的历史恢复。参见 E2E-COMPOSER-input-history-recall。diff --git a/scripts/e2e-composer-paste.mjs b/scripts/e2e-composer-paste.mjsindex 0ddd0e337..98f9347aa 100644--- a/scripts/e2e-composer-paste.mjs+++ b/scripts/e2e-composer-paste.mjs@@ -25,7 +25,10 @@ try {format: "iife",jsx: "automatic",loader: { ".woff": "file", ".woff2": "file", ".ttf": "file" },- define: { "process.env.NODE_ENV": '"production"' },+ define: {+ "process.env.NODE_ENV": '"production"',+ "import.meta.env.DEV": "false",+ },alias: {"@pi-desktop/i18n": join(root, "packages/i18n/src/index.ts"),react: join(root, "apps/desktop/node_modules/react"),@@ -133,6 +136,32 @@ ipcMain.handle("pi-desktop/clipboard/recordPaste", (_event, input) => {return { ok: true, data: null };});app.whenReady().then(async () => {+ if (process.argv.includes("--history-check")) {+ try {+ const window = new BrowserWindow({ show: false, webPreferences: {+ preload: ${JSON.stringify(join(root, "apps/desktop/out/preload/index.cjs"))},+ sandbox: true, contextIsolation: true, nodeIntegration: false, backgroundThrottling: false,+ } });+ window.webContents.on("console-message", (event) => {+ if (!event.message.startsWith("PI_PREVIEW_KEY:")) return;+ const key = event.message.slice("PI_PREVIEW_KEY:".length);+ assert(["Escape", "Tab", "ArrowUp", "ArrowDown", "Enter"].includes(key));+ const keyCode = key === "ArrowUp" ? "Up" : key === "ArrowDown" ? "Down" : key;+ window.webContents.sendInputEvent({ type: "keyDown", keyCode });+ window.webContents.sendInputEvent({ type: "keyUp", keyCode });+ });+ await window.loadFile(path.join(__dirname, "index.html"));+ await window.webContents.executeJavaScript('globalThis.composerPreviewPressKey = key => new Promise(resolve => { document.addEventListener("keyup", () => requestAnimationFrame(resolve), { once: true }); console.log("PI_PREVIEW_KEY:" + key); }); void 0');+ const result = await window.webContents.executeJavaScript('globalThis.composerHistoryProbe("verify")');+ assert.equal(result.ok, true, JSON.stringify(result));+ console.log("COMPOSER_HISTORY_RESTART " + JSON.stringify(result));+ app.quit();+ } catch (error) {+ console.error("COMPOSER_HISTORY_RESTART " + JSON.stringify({ ok: false, error: String(error), stack: error?.stack }));+ app.exit(1);+ }+ return;+ }await fs.mkdir(path.join(__dirname, "attachments"));await fs.writeFile(path.join(__dirname, "attachments", "a".repeat(64)), Buffer.alloc(512 * 1024 + 1));await fs.writeFile(path.join(__dirname, "attachments", "b".repeat(64)), Buffer.from([0, 1, 2, 0]));@@ -150,9 +179,10 @@ app.whenReady().then(async () => {window.webContents.on("console-message", async (event) => {if (!event.message.startsWith("PI_PREVIEW_KEY:")) return;const key = event.message.slice("PI_PREVIEW_KEY:".length);- assert(["Escape", "Tab"].includes(key));- window.webContents.sendInputEvent({ type: "keyDown", keyCode: key });- window.webContents.sendInputEvent({ type: "keyUp", keyCode: key });+ assert(["Escape", "Tab", "ArrowUp", "ArrowDown", "Enter"].includes(key));+ const keyCode = key === "ArrowUp" ? "Up" : key === "ArrowDown" ? "Down" : key;+ window.webContents.sendInputEvent({ type: "keyDown", keyCode });+ window.webContents.sendInputEvent({ type: "keyUp", keyCode });});await window.webContents.executeJavaScript('globalThis.composerPreviewPressKey = key => new Promise(resolve => { document.addEventListener("keyup", () => requestAnimationFrame(resolve), { once: true }); console.log("PI_PREVIEW_KEY:" + key); }); void 0');if (process.env.PI_COMPOSER_PREVIEW_SCREENSHOT) {@@ -198,6 +228,9 @@ app.whenReady().then(async () => {assert.equal(mimeSets.filter((mimes) => mimes === "video/mp4").length, 1);assert(history.some(text => text.includes("Word paragraph")), "short text missing from clipboard history");console.log("COMPOSER_PASTE_PROBE " + JSON.stringify({ ...result, scratchBytesVerified: true }));+ const historyResult = await window.webContents.executeJavaScript('globalThis.composerHistoryProbe("prepare")');+ assert.equal(historyResult.ok, true, JSON.stringify(historyResult));+ console.log("COMPOSER_HISTORY_PREPARE " + JSON.stringify(historyResult));app.quit();} catch (error) {console.error("COMPOSER_PASTE_PROBE " + JSON.stringify({ ok: false, error: String(error), stack: error?.stack, savedCount: saved.length }));@@ -208,36 +241,53 @@ app.whenReady().then(async () => {);const env = { ...process.env };delete env.ELECTRON_RUN_AS_NODE;- const child = spawn(electronBinary, [join(temp, "main.cjs")], {- env,- stdio: ["ignore", "pipe", "pipe"],- });- let output = "";- for (const stream of [child.stdout, child.stderr])- stream.on("data", (data) => {- output += data;- });- const timeout = setTimeout(() => child.kill("SIGKILL"), 45_000);- let code;- try {- code = await new Promise((resolve, reject) => {- child.once("error", reject);- child.once("close", resolve);+ const runElectron = async (args = []) => {+ const child = spawn(electronBinary, [join(temp, "main.cjs"), ...args], {+ env,+ stdio: ["ignore", "pipe", "pipe"],});- } finally {- clearTimeout(timeout);- }- const line = output+ let output = "";+ for (const stream of [child.stdout, child.stderr])+ stream.on("data", (data) => {+ output += data;+ });+ const timeout = setTimeout(() => child.kill("SIGKILL"), 45_000);+ let code;+ try {+ code = await new Promise((resolve, reject) => {+ child.once("error", reject);+ child.once("close", resolve);+ });+ } finally {+ clearTimeout(timeout);+ }+ return { code, output };+ };+ const firstRun = await runElectron();+ const pasteLine = firstRun.output.split(/\r?\n/).find((line) => line.startsWith("COMPOSER_PASTE_PROBE "));assert(- line,- `renderer returned no result (exit=${code}): ${output.slice(-3000)}`,+ pasteLine,+ `renderer returned no paste result (exit=${firstRun.code}): ${firstRun.output.slice(-3000)}`,+ );+ const pasteResult = JSON.parse(pasteLine.slice("COMPOSER_PASTE_PROBE ".length));+ console.log("COMPOSER_PASTE_PROBE " + JSON.stringify(pasteResult));+ assert.equal(firstRun.code, 0, firstRun.output.slice(-4000));+ assert.equal(pasteResult.ok, true);++ const restartRun = await runElectron(["--history-check"]);+ const restartLine = restartRun.output+ .split(/\r?\n/)+ .find((line) => line.startsWith("COMPOSER_HISTORY_RESTART "));+ assert(+ restartLine,+ `renderer returned no restart result (exit=${restartRun.code}): ${restartRun.output.slice(-3000)}`,);- const result = JSON.parse(line.slice("COMPOSER_PASTE_PROBE ".length));- console.log("COMPOSER_PASTE_PROBE " + JSON.stringify(result));- assert.equal(code, 0, output.slice(-4000));- assert.equal(result.ok, true);+ const restartResult = JSON.parse(restartLine.slice("COMPOSER_HISTORY_RESTART ".length));+ console.log("COMPOSER_HISTORY_RESTART " + JSON.stringify(restartResult));+ assert.equal(restartRun.code, 0, restartRun.output.slice(-4000));+ assert.equal(restartResult.ok, true);} finally {await rm(temp, { recursive: true, force: true });}diff --git a/scripts/e2e/composer-paste.tsx b/scripts/e2e/composer-paste.tsxindex 240a9b1fa..bcfd1cc42 100644--- a/scripts/e2e/composer-paste.tsx+++ b/scripts/e2e/composer-paste.tsx@@ -1,4 +1,8 @@import { serializeInlineComposerFileReferences } from "@pi-desktop/shared";+import { useComposerInputHistory } from "../../apps/desktop/src/features/chat/composer/hooks/useComposerInputHistory";+import type { AppState } from "../../apps/desktop/src/stores/app-state";+import { createQueueSlice } from "../../apps/desktop/src/stores/slices/queue-slice";+import type { SessionRuntime } from "../../apps/desktop/src/stores/runtime/session-runtime";import { useComposerSubmit } from "../../apps/desktop/src/features/chat/composer/hooks/useComposerSubmit";import { verifyComposerSubmission } from "./composer-submission";import { ComposerImageAttachments } from "../../apps/desktop/src/features/chat/composer/ComposerImageAttachments";@@ -39,20 +43,23 @@ declare global {var composerPreviewPressKey: (key: string) => Promise<void>;var composerPreviewCapture: (() => Promise<void>) | undefined;var composerPasteProbe: () => Promise<unknown>;+ var composerHistoryProbe: (phase: "prepare" | "verify") => Promise<unknown>;}const assert = (value: unknown, message: string) => {if (!value) throw new Error(message);};-const sessions = [{ id: "paste-a" }, { id: "paste-b" }];+const sessions = [{ id: "paste-a" }, { id: "paste-b" }, { id: "history-created-session" }];const noop = () => {};let controller: ComposerDraftController;let pastePending: Promise<unknown> | undefined;let submitted = 0;let rejectSubmission: () => Promise<void>;+let historySendPrompt: AppState["sendPrompt"] = async () => false;+let latestSubmission: Promise<void> = Promise.resolve();function Fixture({ sessionId, t, workspacePath }: { sessionId: string; t: TFunction; workspacePath: string }) {const draft = useComposerDraft({variant: "docked",- activeSessionId: sessionId,+ activeSessionId: sessionId || null,workspacePath,sessions,composerPrefill: null,@@ -62,15 +69,28 @@ function Fixture({ sessionId, t, workspacePath }: { sessionId: string; t: TFunctinputBlocked: false,});controller = draft;- rejectSubmission = useComposerSubmit({- value: draft.value, draftKey: draft.draftKey, activeSessionId: sessionId,+ const inputHistory = useComposerInputHistory({+ draftKey: draft.draftKey,+ referenceSessionId: sessionId,+ draft,+ });+ const submitController = useComposerSubmit({+ value: draft.value, draftKey: draft.draftKey, activeSessionId: sessionId || null,thinkingLevel: "off", modelReady: true, sendBlocked: false, pasting: false,activeFileReferences: draft.activeFileReferences, t, draft,- sendPrompt: async () => false, steerPrompt: async () => false, showToast: noop,- }).submit;+ recordHistory: inputHistory.record,+ sendPrompt: (...args) => historySendPrompt(...args),+ steerPrompt: async () => false, showToast: noop,+ });+ rejectSubmission = submitController.submit;+ const submitFromComposer = (steering?: boolean) => {+ inputHistory.exitBrowsing();+ submitted++;+ return submitController.submit(steering);+ };const attachments = useComposerAttachments({inputBlocked: false,- activeSessionId: sessionId,+ activeSessionId: sessionId || null,draftKey: draft.draftKey,largePasteThreshold: 600,t,@@ -97,9 +117,10 @@ function Fixture({ sessionId, t, workspacePath }: { sessionId: string; t: TFunctpastePending = Promise.resolve(attachments.pasteClipboardFiles(event));}}onAcceptCompletion={noop}- onSubmit={() => { submitted++; }}+ onSubmit={(steering) => { latestSubmission = submitFromComposer(steering); }}+ onHistoryNavigate={inputHistory.navigate}onInsertNewline={draft.insertNewlineInEditor}- onInput={draft.handleInput}+ onInput={(source, caret) => { inputHistory.exitBrowsing(); draft.handleInput(source, caret); }}onCompositionStart={noop}onCompositionEnd={noop}onFocus={noop}@@ -904,3 +925,217 @@ globalThis.composerPasteProbe = async () => {resetComposerDraftCache();}};++globalThis.composerHistoryProbe = async (phase) => {+ const i18n = createInstance();+ await i18n.init({+ lng: "en",+ resources: { en: { translation: en } },+ interpolation: { escapeValue: false },+ });+ const host = document.createElement("div");+ document.body.append(host);+ const errors: unknown[] = [];+ const root = createRoot(host, {+ onUncaughtError: (error) => errors.push(error),+ });+ const render = (sessionId: string) => {+ useAppStore.setState({ activeSessionId: sessionId || null });+ flushSync(() =>+ root.render(+ <I18nextProvider i18n={i18n}>+ <Fixture+ key={sessionId || "home"}+ sessionId={sessionId}+ t={i18n.t}+ workspacePath=""+ />+ </I18nextProvider>,+ ),+ );+ assert(errors.length === 0, `React failed: ${errors.map(String).join("; ")}`);+ };+ const frame = () => new Promise<void>((resolve) => requestAnimationFrame(() => resolve()));+ const press = async (key: string) => {+ controller.ref.current!.focus();+ await globalThis.composerPreviewPressKey(key);+ await frame();+ assert(errors.length === 0, `React failed after ${key}: ${errors.map(String).join("; ")}`);+ };+ try {+ resetComposerDraftCache();+ if (phase === "prepare") {+ historySendPrompt = async (_content, _draft, sessionId, onAccepted) => {+ if (!sessionId) throw new Error("a docked prompt must submit to its selected session");+ onAccepted?.(sessionId);+ return true;+ };+ render("paste-a");+ await frame();+ const send = async (text: string, references: ReturnType<typeof createFileReference>[] = []) => {+ flushSync(() => controller.applyEditorDraft(text, references, text.length));+ await frame();+ await press("Enter");+ await latestSubmission;+ await frame();+ assert(readEditorValue(controller.ref.current!) === "", "accepted send did not clear its draft");+ };+ await send("alpha");+ await send("beta");+ await send("beta");+ await press("ArrowUp");+ assert(readEditorValue(controller.ref.current!) === "beta", "ArrowUp did not recall the newest entry");+ await press("ArrowUp");+ assert(readEditorValue(controller.ref.current!) === "alpha", "ArrowUp did not walk to the older entry");+ await press("ArrowDown");+ assert(readEditorValue(controller.ref.current!) === "beta", "ArrowDown did not walk forward");+ await press("ArrowDown");+ assert(readEditorValue(controller.ref.current!) === "", "ArrowDown past newest did not clear the draft");++ const fileReference = createFileReference(+ "/scratch/paste-a/history.txt",+ "history.txt",+ "paste-a",+ { kind: "file", token: "\uE050" },+ );+ const attachedText = `inspect \uE050`;+ await send(attachedText, [fileReference]);+ await press("ArrowUp");+ assert(+ controller.fileReferences.some((reference) => reference.path === fileReference.path) &&+ controller.ref.current!.querySelector(".composer-chip-name")?.textContent === "history.txt",+ "history recall did not restore and render the file attachment chip",+ );++ render("paste-b");+ await frame();+ await press("ArrowUp");+ assert(readEditorValue(controller.ref.current!) === "", "session B recalled session A history");+ await send("beta");+ await press("ArrowUp");+ assert(readEditorValue(controller.ref.current!) === "beta", "session B did not recall its own entry");+ render("paste-a");+ await frame();+ flushSync(() => controller.applyEditorDraft("", [], 0));+ await frame();+ await press("ArrowUp");+ assert(+ controller.fileReferences.some((reference) => reference.path === fileReference.path),+ "returning to session A did not restore its attached history entry",+ );++ render("");+ await frame();+ await press("ArrowUp");+ assert(readEditorValue(controller.ref.current!) === "", "the empty home composer recalled another session");+ const homeText = "first home prompt";+ flushSync(() => controller.applyEditorDraft(homeText, [], homeText.length));+ await frame();+ await frame();+ let signalStarted!: () => void;+ let releaseSend!: () => void;+ const started = new Promise<void>((resolve) => { signalStarted = resolve; });+ const sendGate = new Promise<void>((resolve) => { releaseSend = resolve; });+ const originalPrompt = api.prompt;+ let queueState = {+ activeSessionId: null,+ pendingPlans: {},+ runningSessions: {},+ sessions: [{ id: "history-created-session" }],+ messages: [],+ latestTurnResults: {},+ sessionOutcomes: {},+ isRunning: false,+ } as unknown as AppState;+ const queueRuntime = {+ beginNavigationIntent: () => 1,+ submittedComposerDrafts: new Map(),+ sessionTranscriptCache: new Map(),+ insertOptimisticUserMessage: () => {},+ retractOptimisticUserMessage: () => {},+ } as unknown as SessionRuntime;+ const queueSlice = createQueueSlice({+ get: () => queueState,+ set: (update) => {+ const next = typeof update === "function" ? update(queueState) : update;+ queueState = { ...queueState, ...next };+ },+ runtime: queueRuntime,+ promptAttachmentsFromDraft: () => [],+ withoutRecordKey: (record, key) => {+ const next = { ...record };+ delete next[key];+ return next;+ },+ promptFallbackSessionTitle: () => "",+ untitledTaskTitle: () => "",+ isDefaultSessionTitle: () => false,+ viewingSessionIdForPrompt: () => null,+ messageErrorFromUnknown: () => { throw new Error("unexpected prompt failure"); },+ assistantErrorMessage: () => { throw new Error("unexpected prompt failure"); },+ materializeDraftSession: async () => "history-created-session",+ });+ historySendPrompt = queueSlice.sendPrompt;+ api.prompt = async (input) => {+ assert(input.sessionId === "history-created-session", "prompt used the wrong materialized session");+ signalStarted();+ await sendGate;+ queueState = { ...queueState, activeSessionId: "paste-b" };+ useAppStore.setState({ activeSessionId: "paste-b" });+ };+ try {+ await press("Enter");+ await started;+ const homeSubmission = latestSubmission;+ render("paste-b");+ releaseSend();+ await homeSubmission;+ } finally {+ api.prompt = originalPrompt;+ }+ render("history-created-session");+ await frame();+ await press("ArrowUp");+ assert(+ readEditorValue(controller.ref.current!) === "first home prompt",+ "home's first prompt was not recorded under its materialized session after navigation",+ );+ return {+ ok: true,+ arrowNavigation: true,+ sessionIsolation: true,+ renderedAttachmentRecall: true,+ homeSessionSwitchDuringSend: true,+ };+ }++ render("paste-a");+ await frame();+ await press("ArrowUp");+ const recalledText = readEditorValue(controller.ref.current!);+ assert(+ controller.fileReferences.some((reference) => reference.name === "history.txt") &&+ controller.ref.current!.querySelector(".composer-chip-name")?.textContent === "history.txt",+ "attachment history did not survive the Electron process restart",+ );+ assert(recalledText === "inspect \uE050", "the latest attached prompt changed after restart");+ render("history-created-session");+ await frame();+ await press("ArrowUp");+ assert(+ readEditorValue(controller.ref.current!) === "first home prompt",+ "the Home-created session history did not survive the Electron process restart",+ );+ return {+ ok: true,+ processRestartPersistence: true,+ attachmentPersistence: true,+ materializedHomeSessionPersistence: true,+ };+ } finally {+ historySendPrompt = async () => false;+ flushSync(() => root.unmount());+ host.remove();+ resetComposerDraftCache();+ }+};