Skip to content

Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins

fix(asktool): keep card drafts across session switches

liubaib6863ae2bb6f
diff --git a/apps/desktop/src/components/AskToolCard.tsx b/apps/desktop/src/components/AskToolCard.tsx
index c1c1daa4e..34c64efba 100644
--- a/apps/desktop/src/components/AskToolCard.tsx
+++ b/apps/desktop/src/components/AskToolCard.tsx
@@ -3,38 +3,45 @@ import { useTranslation } from "react-i18next";
import {
askToolOptionDescription,
askToolOptionLabel,
- type AskToolQuestion,
} from "@pi-desktop/shared";
import { AskToolRichText } from "./AskToolRichText";
-import type { PendingAsk } from "../lib/pending-asks";
+import {
+ emptyAskDraft,
+ type AskDraft,
+ type AskDraftAnswer,
+ type PendingAsk,
+} from "../lib/pending-asks";
import { useAppStore } from "../stores/app-store";
import { Button } from "./ui";
-type DraftAnswer = {
- values: string[];
- customSelected: boolean;
- customText: string;
- skipped: boolean;
-};
+type DraftAnswer = AskDraftAnswer;
const CUSTOM_OPTION = "__asktool_custom__";
-function emptyDrafts(questions: AskToolQuestion[]): DraftAnswer[] {
- return questions.map(() => ({
- values: [],
- customSelected: false,
- customText: "",
- skipped: false,
- }));
-}
-
export function AskToolCard({ request, queued = 0 }: { request: PendingAsk; queued?: number }) {
const { t } = useTranslation();
const resolveAsk = useAppStore((state) => state.resolveAsk);
const showToast = useAppStore((state) => state.showToast);
- const [index, setIndex] = useState(0);
- const [drafts, setDrafts] = useState(() => emptyDrafts(request.questions));
+ const storedDraft = useAppStore((state) => state.askDrafts[request.requestId]);
+ const setAskDraft = useAppStore((state) => state.setAskDraft);
const [resolving, setResolving] = useState(false);
+ // The store owns the draft, so a session switch (which unmounts this card)
+ // cannot reset the answers. Read lazily rather than seeding during render.
+ const draft: AskDraft =
+ storedDraft && storedDraft.answers.length === request.questions.length
+ ? {
+ ...storedDraft,
+ index: Math.min(
+ Math.max(0, storedDraft.index),
+ request.questions.length - 1,
+ ),
+ }
+ : emptyAskDraft(request.questions);
+ const index = draft.index;
+ const drafts = draft.answers;
+ const updateDraft = (next: AskDraft) => setAskDraft(request.requestId, next);
+ const setIndex = (nextIndex: number) =>
+ updateDraft({ ...draft, index: nextIndex });
const current = request.questions[index];
const currentDraft = drafts[index];
@@ -54,14 +61,17 @@ export function AskToolCard({ request, queued = 0 }: { request: PendingAsk; queu
[drafts],
);
- const updateDraft = (update: (draft: DraftAnswer) => DraftAnswer) => {
- setDrafts((previous) =>
- previous.map((draft, draftIndex) => (draftIndex === index ? update(draft) : draft)),
- );
+ const updateCurrentDraft = (update: (answer: DraftAnswer) => DraftAnswer) => {
+ updateDraft({
+ ...draft,
+ answers: drafts.map((answer, draftIndex) =>
+ draftIndex === index ? update(answer) : answer,
+ ),
+ });
};
const selectOption = (option: string) => {
- updateDraft((draft) => {
+ updateCurrentDraft((draft) => {
if (option === CUSTOM_OPTION) {
return {
...draft,
@@ -113,18 +123,24 @@ export function AskToolCard({ request, queued = 0 }: { request: PendingAsk; queu
? { ...draft, skipped: true }
: draft,
);
- setDrafts(nextDrafts);
- if (index === request.questions.length - 1) void submit(nextDrafts);
- else setIndex((value) => value + 1);
+ if (index === request.questions.length - 1) {
+ updateDraft({ ...draft, answers: nextDrafts });
+ void submit(nextDrafts);
+ } else {
+ updateDraft({ ...draft, answers: nextDrafts, index: index + 1 });
+ }
};
const skip = () => {
const nextDrafts = drafts.map((draft, draftIndex) =>
draftIndex === index ? { ...draft, skipped: true, values: [], customSelected: false } : draft,
);
- setDrafts(nextDrafts);
- if (index === request.questions.length - 1) void submit(nextDrafts);
- else setIndex((value) => value + 1);
+ if (index === request.questions.length - 1) {
+ updateDraft({ ...draft, answers: nextDrafts });
+ void submit(nextDrafts);
+ } else {
+ updateDraft({ ...draft, answers: nextDrafts, index: index + 1 });
+ }
};
return (
@@ -223,7 +239,7 @@ export function AskToolCard({ request, queued = 0 }: { request: PendingAsk; queu
placeholder={t("askTool.customPlaceholder")}
aria-label={t("askTool.customOption")}
onChange={(event) =>
- updateDraft((draft) => ({ ...draft, customText: event.target.value, skipped: false }))
+ updateCurrentDraft((draft) => ({ ...draft, customText: event.target.value, skipped: false }))
}
autoFocus
/>
diff --git a/apps/desktop/src/lib/pending-asks.ts b/apps/desktop/src/lib/pending-asks.ts
index b7da1fda5..76b306619 100644
--- a/apps/desktop/src/lib/pending-asks.ts
+++ b/apps/desktop/src/lib/pending-asks.ts
@@ -1,4 +1,4 @@
-import type { AskToolRequest } from "@pi-desktop/shared";
+import type { AskToolQuestion, AskToolRequest } from "@pi-desktop/shared";
export type PendingAsk = AskToolRequest;
export type AskQueues = Record<string, PendingAsk[]>;
@@ -56,3 +56,76 @@ export function clearSessionAsks(queues: AskQueues, sessionId: string): AskQueue
delete next[sessionId];
return next;
}
+
+/** One question's in-progress answer, owned by the store so a remount is harmless. */
+export type AskDraftAnswer = {
+ values: string[];
+ customSelected: boolean;
+ customText: string;
+ skipped: boolean;
+};
+
+/** The card's per-request draft: which question is open plus every answer. */
+export type AskDraft = {
+ index: number;
+ answers: AskDraftAnswer[];
+};
+
+/** Drafts keyed by requestId; the ask itself already lives in `AskQueues`. */
+export type AskDrafts = Record<string, AskDraft>;
+
+export function emptyAskDraft(questions: AskToolQuestion[]): AskDraft {
+ return {
+ index: 0,
+ answers: questions.map(() => ({
+ values: [],
+ customSelected: false,
+ customText: "",
+ skipped: false,
+ })),
+ };
+}
+
+export function setAskDraft(
+ drafts: AskDrafts,
+ requestId: string,
+ draft: AskDraft,
+): AskDrafts {
+ return { ...drafts, [requestId]: draft };
+}
+
+export function dropAskDraft(drafts: AskDrafts, requestId: string): AskDrafts {
+ if (!(requestId in drafts)) return drafts;
+ const next = { ...drafts };
+ delete next[requestId];
+ return next;
+}
+
+/** Drop the drafts of every ask still queued for a session. */
+export function dropSessionAskDrafts(
+ drafts: AskDrafts,
+ queues: AskQueues,
+ sessionId: string,
+): AskDrafts {
+ const queue = queues[sessionId];
+ if (!queue || queue.length === 0) return drafts;
+ let next = drafts;
+ for (const ask of queue) next = dropAskDraft(next, ask.requestId);
+ return next;
+}
+
+/** Drop the drafts of the asks tied to one tool call. */
+export function dropToolCallAskDrafts(
+ drafts: AskDrafts,
+ queues: AskQueues,
+ sessionId: string,
+ toolCallId: string,
+): AskDrafts {
+ const queue = queues[sessionId];
+ if (!queue || queue.length === 0) return drafts;
+ let next = drafts;
+ for (const ask of queue) {
+ if (ask.toolCallId === toolCallId) next = dropAskDraft(next, ask.requestId);
+ }
+ return next;
+}
diff --git a/apps/desktop/src/stores/app-state.ts b/apps/desktop/src/stores/app-state.ts
index 21b76b5b9..a2d018447 100644
--- a/apps/desktop/src/stores/app-state.ts
+++ b/apps/desktop/src/stores/app-state.ts
@@ -40,7 +40,7 @@ import type {
SessionSort,
} from "../lib/sidebar-preferences";
import type { PermissionQueues } from "../lib/pending-permissions";
-import type { AskQueues } from "../lib/pending-asks";
+import type { AskDraft, AskDrafts, AskQueues } from "../lib/pending-asks";
import type {
QueuedPromptDirection,
QueuedPrompts,
@@ -176,6 +176,8 @@ export type AppState = {
pendingPermissions: PermissionQueues;
/** Inline asktool requests, queued per session without an expiry. */
pendingAsks: AskQueues;
+ /** In-progress AskTool answers keyed by requestId, so a remount keeps them. */
+ askDrafts: AskDrafts;
/** Renderer-owned, in-memory prompt queue, isolated by session. */
queuedPrompts: QueuedPrompts;
/** Planning state is durable per session, including sessions outside view. */
@@ -377,6 +379,10 @@ export type AppState = {
sessionId: string,
resolution: AskToolResolution,
) => Promise<void>;
+ /** Persist one question card's in-progress answers by requestId. */
+ setAskDraft: (requestId: string, draft: AskDraft) => void;
+ /** Forget a request's draft once it is resolved or dismissed. */
+ dropAskDraft: (requestId: string) => void;
resolvePlan: (resolution: PlanResolveRequest) => Promise<PlanResolutionResult>;
showToast: (message: string, options?: ToastOptions) => void;
dismissToast: (id: number) => void;
diff --git a/apps/desktop/src/stores/slices/events-slice.ts b/apps/desktop/src/stores/slices/events-slice.ts
index fe4ef21dd..16761c221 100644
--- a/apps/desktop/src/stores/slices/events-slice.ts
+++ b/apps/desktop/src/stores/slices/events-slice.ts
@@ -25,6 +25,8 @@ import {
import { createFrameBatcher } from "../../lib/frame-batcher";
import {
clearSessionAsks,
+ dropSessionAskDrafts,
+ dropToolCallAskDrafts,
enqueueAsk,
removeAskForToolCall,
} from "../../lib/pending-asks";
@@ -360,6 +362,11 @@ export function createEventsSlice({
state.pendingAsks,
envelope.sessionId,
),
+ askDrafts: dropSessionAskDrafts(
+ state.askDrafts,
+ state.pendingAsks,
+ envelope.sessionId,
+ ),
latestTurnResults:
event.type === "error" && event.error.code === "TURN_ABORTED"
? withoutRecordKey(state.latestTurnResults, envelope.sessionId)
@@ -452,10 +459,17 @@ export function createEventsSlice({
envelope.sessionId,
event.toolCallId,
);
+ const askDrafts = dropToolCallAskDrafts(
+ state.askDrafts,
+ state.pendingAsks,
+ envelope.sessionId,
+ event.toolCallId,
+ );
return pendingPermissions === state.pendingPermissions &&
- pendingAsks === state.pendingAsks
+ pendingAsks === state.pendingAsks &&
+ askDrafts === state.askDrafts
? {}
- : { pendingPermissions, pendingAsks };
+ : { pendingPermissions, pendingAsks, askDrafts };
});
}
diff --git a/apps/desktop/src/stores/slices/initial-state.ts b/apps/desktop/src/stores/slices/initial-state.ts
index 2b98d8697..18eeb7e63 100644
--- a/apps/desktop/src/stores/slices/initial-state.ts
+++ b/apps/desktop/src/stores/slices/initial-state.ts
@@ -72,6 +72,7 @@ export function createInitialState(): AppStateData {
pluginViews: [],
pendingPermissions: {},
pendingAsks: {},
+ askDrafts: {},
queuedPrompts: {},
planningStates: {},
pendingPlans: {},
diff --git a/apps/desktop/src/stores/slices/interaction-slice.ts b/apps/desktop/src/stores/slices/interaction-slice.ts
index dcf29e0ef..f0af490d5 100644
--- a/apps/desktop/src/stores/slices/interaction-slice.ts
+++ b/apps/desktop/src/stores/slices/interaction-slice.ts
@@ -5,8 +5,11 @@ import type {
} from "@pi-desktop/shared";
import { api } from "../../lib/api";
import {
+ dropAskDraft as removeAskDraft,
headAsk,
removeAsk,
+ setAskDraft as applyAskDraft,
+ type AskDraft,
} from "../../lib/pending-asks";
import {
headPermission,
@@ -43,6 +46,8 @@ export function createInteractionSlice({
| "navForward"
| "resolvePermission"
| "resolveAsk"
+ | "setAskDraft"
+ | "dropAskDraft"
| "resolvePlan"
| "showToast"
| "dismissToast"
@@ -152,10 +157,23 @@ export function createInteractionSlice({
sessionId,
resolution.requestId,
),
+ askDrafts: removeAskDraft(state.askDrafts, resolution.requestId),
}));
}
},
+ setAskDraft: (requestId: string, draft: AskDraft) => {
+ set((state) => ({
+ askDrafts: applyAskDraft(state.askDrafts, requestId, draft),
+ }));
+ },
+
+ dropAskDraft: (requestId: string) => {
+ set((state) => ({
+ askDrafts: removeAskDraft(state.askDrafts, requestId),
+ }));
+ },
+
resolvePlan: async (resolution: PlanResolveRequest) => {
const activeRequest = interactionRuntime.planResolutionRequests.get(
resolution.proposalId,
diff --git a/apps/desktop/src/stores/slices/project-slice.ts b/apps/desktop/src/stores/slices/project-slice.ts
index 51e1bb182..119515042 100644
--- a/apps/desktop/src/stores/slices/project-slice.ts
+++ b/apps/desktop/src/stores/slices/project-slice.ts
@@ -14,6 +14,7 @@ import {
} from "../../lib/session-panes";
import {
clearSessionAsks,
+ dropSessionAskDrafts,
} from "../../lib/pending-asks";
import {
clearSessionPermissions,
@@ -174,6 +175,7 @@ function clearLocalSessionState(
id,
);
const pendingAsks = clearSessionAsks(state.pendingAsks, id);
+ const askDrafts = dropSessionAskDrafts(state.askDrafts, state.pendingAsks, id);
const latestTurnResults = withoutRecordKey(state.latestTurnResults, id);
const planningStates = withoutRecordKey(state.planningStates, id);
const pendingPlans = withoutRecordKey(state.pendingPlans, id);
@@ -202,6 +204,7 @@ function clearLocalSessionState(
isRunning: state.activeSessionId === id ? false : state.isRunning,
pendingPermissions,
pendingAsks,
+ askDrafts,
latestTurnResults,
planningStates,
pendingPlans,
diff --git a/apps/desktop/src/stores/slices/session-slice.ts b/apps/desktop/src/stores/slices/session-slice.ts
index e1c41d699..3a6a21b40 100644
--- a/apps/desktop/src/stores/slices/session-slice.ts
+++ b/apps/desktop/src/stores/slices/session-slice.ts
@@ -35,6 +35,7 @@ import {
type SessionMeta,
} from "../../lib/sidebar-preferences";
import { api } from "../../lib/api";
+import { dropAskDraft } from "../../lib/pending-asks";
import { isRemoteSession, safeSessionSummary, sessionAllows } from "../../lib/remote-session-safety";
import { createRefreshCoordinator } from "../../lib/refresh-coordinator";
import { openRemoteProjectSession, remoteProjectForSession } from "../../lib/remote-project-session";
@@ -344,15 +345,24 @@ export function createSessionSlice({
sessionId,
pendingPermissions,
);
+ const keptAskIds = new Set(pendingAsks.map((ask) => ask.requestId));
+ let askDrafts = state.askDrafts;
+ for (const ask of state.pendingAsks[sessionId] ?? []) {
+ if (!keptAskIds.has(ask.requestId)) {
+ askDrafts = dropAskDraft(askDrafts, ask.requestId);
+ }
+ }
if (
nextPendingAsks === state.pendingAsks &&
- nextPendingPermissions === state.pendingPermissions
+ nextPendingPermissions === state.pendingPermissions &&
+ askDrafts === state.askDrafts
) {
return {};
}
return {
pendingAsks: nextPendingAsks,
pendingPermissions: nextPendingPermissions,
+ askDrafts,
};
});
},
diff --git a/docs/adr/README.md b/docs/adr/README.md
index 18a7a9a6c..b3412c13e 100644
--- a/docs/adr/README.md
+++ b/docs/adr/README.md
@@ -20,6 +20,7 @@ Each ADR includes:
| ID | Title | Status |
|---|---|---|
+| asktool-draft-survives-session-switch | [AskTool drafts survive a card remount](asktool-draft-survives-session-switch.md) | Accepted |
| provider-metadata-client-certificate-retry | [Provider metadata recovery from optional client certificates](provider-metadata-client-certificate-retry.md) | Implemented candidate |
| device-local-project-lists-in-config-sync | [Device-local project lists in configuration sync](device-local-project-lists-in-config-sync.md) | Accepted |
| s3-only-configuration-backup-sync | [S3-only encrypted configuration backup and synchronization](s3-only-configuration-backup-sync.md) | Accepted; supersedes WebDAV decisions in 0300 / 0301 |
diff --git a/docs/adr/asktool-draft-survives-session-switch.md b/docs/adr/asktool-draft-survives-session-switch.md
new file mode 100644
index 000000000..23fe0ca0f
--- /dev/null
+++ b/docs/adr/asktool-draft-survives-session-switch.md
@@ -0,0 +1,50 @@
+# ADR asktool-draft-survives-session-switch: AskTool drafts survive a card remount
+
+- Status: Accepted
+- Date: 2026-10-20
+- Issues: #1765
+- Amends: the "Request transitions" rule in `docs/spec/04-ux/11-asktool-question-card.md`
+
+## Context
+
+The card's question index and draft answers were component state. Switching
+sessions unmounts the card — `Composer` renders it only while the active session
+has a head ask — so returning to the same pending ask remounted a fresh card at
+question one with every answer cleared. The ask itself survived because it lives
+in the store; only the in-progress answers were lost, which made the user redo
+the whole card.
+
+The existing specification froze the opposite behavior: "Unsubmitted card drafts
+are local to the mounted card and are reset when it is replaced." That rule
+predates the session-switch case and no longer matches what users expect.
+
+## Decision
+
+Draft answers and the open question index live in the app store, keyed by
+`requestId` (`askDrafts`). `AskToolCard` reads and writes that entry instead of
+owning `useState`, so unmounting and remounting the same request is harmless.
+A missing entry falls back lazily to an empty draft at read time; the card does
+not seed the store during render.
+
+The draft is dropped when the ask is resolved or dismissed, when its tool call
+finishes, when the session's asks are cleared, and when a pending-queue reconcile
+removes the ask. Drafts remain renderer memory, like `pendingAsks`; they are not
+persisted across an application restart and never leak between requests.
+
+## Consequences
+
+- Switching sessions and returning to the same pending ask keeps the selected
+ options, the custom text, skipped markers, and the open question.
+- Resolved, dismissed, and removed asks leave no draft behind.
+- `AskToolCard` becomes a controlled view over store state; it keeps no
+ draft-local `useState`.
+- The "Request transitions" section of the asktool card spec is amended: drafts
+ belong to the request, not to the mounted card instance.
+
+## Validation
+
+`pnpm test:e2e:asktool-card` adds `E2E-ASKTOOL-draft-survives-session-switch`:
+it selects an option, advances to question two, unmounts the card, remounts the
+same `requestId`, and asserts the open question and the earlier selection
+survive. The existing compact-card flows keep passing. `pnpm typecheck` and
+`pnpm lint` cover the renderer types and style tokens.
diff --git a/docs/spec/04-ux/11-asktool-question-card.md b/docs/spec/04-ux/11-asktool-question-card.md
index 434db0499..625037ea5 100644
--- a/docs/spec/04-ux/11-asktool-question-card.md
+++ b/docs/spec/04-ux/11-asktool-question-card.md
@@ -96,8 +96,16 @@ applies on narrow screens; the card does not rely on page-level scrolling.
## Request transitions
-The question index, draft answers, and submission state belong to the displayed
-request. Switching chats or advancing the pending queue mounts a fresh card at
-question one with empty answers and enabled actions. State from the previous
-request must not leak into the destination request. Unsubmitted card drafts are
-local to the mounted card and are reset when it is replaced.
+The question index and draft answers belong to the request, not to the mounted
+card instance. They live in the app store keyed by `requestId`, so switching
+chats and returning to the same pending ask restores the open question and every
+answer the user had already entered (see
+[ADR asktool-draft-survives-session-switch](../../adr/asktool-draft-survives-session-switch.md)).
+A request with no stored draft opens at question one with empty answers and
+enabled actions.
+
+Drafts never leak between requests: they are keyed by `requestId` and dropped
+when the ask is resolved or dismissed, when its tool call completes, and when the
+session's pending asks are cleared. Submission state stays local to the mounted
+card. Drafts are renderer memory, like the pending ask itself, and do not survive
+an application restart.
diff --git a/docs/spec/06-delivery/04-e2e-test-plan.md b/docs/spec/06-delivery/04-e2e-test-plan.md
index 73b1fa67d..78aee5469 100644
--- a/docs/spec/06-delivery/04-e2e-test-plan.md
+++ b/docs/spec/06-delivery/04-e2e-test-plan.md
@@ -516,6 +516,21 @@
actions, and measures the multi-block question layout. Runtime boundary
validation is covered by `packages/agent-runtime/src/runtime.test.ts`.
+### E2E-ASKTOOL-draft-survives-session-switch
+
+- **Preconditions:** No live provider is required; the fixture stubs
+ `api.resolveAskTool` and seeds one two-question ask through the real store
+ slice.
+- **Steps:** Mount the production `AskToolCard`, select the second option on
+ question one, advance to question two, unmount the card (the session switch
+ the dock performs), and remount it with the same `requestId`. Then click the
+ first step indicator to return to question one.
+- **Expected:** The remounted card opens on question two with the earlier
+ selection still marked, and question one still shows the selected option.
+ Resolving or dismissing the ask clears the stored draft.
+- **Status:** Automated in `pnpm test:e2e:asktool-card` as the
+ `E2E-ASKTOOL-draft-survives-session-switch` flow.
+
### E2E-POWER-keep-awake-setting
- **Preconditions:** An isolated desktop profile with the setting absent; no
diff --git a/scripts/e2e/asktool-card.tsx b/scripts/e2e/asktool-card.tsx
index 26fdbeec2..8bfa0abe1 100644
--- a/scripts/e2e/asktool-card.tsx
+++ b/scripts/e2e/asktool-card.tsx
@@ -8,7 +8,8 @@
* the user-visible paths: the new header action order, select → next →
* submit, skip → submit, decline-all, and a custom answer.
*
- * Scenario: E2E-ASKTOOL-compact-card-interaction. It also pins the compact
+ * Scenario: E2E-ASKTOOL-compact-card-interaction and
+ * E2E-ASKTOOL-draft-survives-session-switch. It also pins the compact
* question block: a multi-paragraph question body stays one stacked text
* column rather than lining its blocks up in a row.
*/
@@ -391,6 +392,42 @@ export async function asktoolCardProbe() {
"the maximum-length question remains answerable",
);
+ // Flow H: the draft survives an unmount/remount with the same requestId —
+ // switching sessions in the real app unmounts the card the same way.
+ const persisted = mount("ask-persist");
+ await until(() => options().length > 0, "persist flow mounts");
+ flushSync(() => options()[1]!.click()); // select "beta" on question 1
+ flushSync(() => headerButtons().primary.click()); // next -> question 2
+ await until(
+ () => questionText().includes("Allow rollback?"),
+ "persist flow advances to question 2",
+ );
+ flushSync(() => root.render(null)); // unmount (session switched away)
+ flushSync(() =>
+ root.render(
+ <I18nextProvider i18n={i18n}>
+ <AskToolCard key={persisted.requestId} request={persisted} />
+ </I18nextProvider>,
+ ),
+ );
+ await until(() => options().length > 0, "persist flow remounts");
+ assert(
+ questionText().includes("Allow rollback?"),
+ "the remounted card resumes on the question the user left",
+ );
+ const indicators = [
+ ...host.querySelectorAll<HTMLButtonElement>(".asktool-indicator"),
+ ];
+ flushSync(() => indicators[0]!.click());
+ await until(
+ () => questionText().includes("Which upgrade path?"),
+ "the indicator returns to question 1",
+ );
+ assert(
+ options()[1]!.classList.contains("selected"),
+ "the answer selected before the remount is still selected",
+ );
+
assert(errors.length === 0, `render errors: ${errors.map(String)}`);
return { ok: true, resolutions: resolutions.length };
} catch (error) {