Skip to content

fix(ui): keep AskUserQuestion wizard progress across session switches - #5814

Closed
UncertaintyDeterminesYou4ndMe wants to merge 1 commit into
apache:mainfrom
UncertaintyDeterminesYou4ndMe:fix/user-question-wizard-progress
Closed

UncertaintyDeterminesYou4ndMe wants to merge 1 commit into
apache:mainfrom
UncertaintyDeterminesYou4ndMe:fix/user-question-wizard-progress

Conversation

@UncertaintyDeterminesYou4ndMe

@UncertaintyDeterminesYou4ndMe UncertaintyDeterminesYou4ndMe commented Sep 29, 2026 •

Copy link
Copy Markdown
Contributor

Fixes #5813.

Problem

The multi-question AskUserQuestion wizard kept its progress — current question, committed per-question answers, in-flight free-form text — in component-local useState. Switching to another session unmounts the prompt, so returning restarted the wizard at question 1 and dropped the answers already given.

Fix

The wizard's progress is cached per request and restored on mount, so a session-switch round trip resumes exactly where the user left off.

The cache is a WeakMap keyed by the request object the interaction queue holds, and the queue owns that object's lifetime: enqueueInteraction dedupes by id, reconcileInteractions now keeps the object the surface already shows instead of swapping in the runtime's IPC copy (same content — a pending request's fields are fixed; only the read's timestamp differs), and the queue drops the object when the runtime settles the request (answer ack, tool result, terminal Turn event, or a live set that no longer lists it). Every surface builds its queue from these helpers, so the cached progress lives exactly as long as the request is pending, and the prompt never decides when a request is over:

  • No resolution signal from the adapters. The Desktop answer and stop adapters report a bridge failure with a toast and fulfill anyway; the prompt cannot tell that from a real resolution, and no longer tries. A request the runtime still holds stays in the queue, its object stays alive, and the answers stay put for the retry.
  • No eviction bound. A settled request leaves the queue and its entry goes with it, so there is nothing for later requests to push a still-pending wizard out of.

Progress and the request it belongs to live in one state object, so the persistence effect always writes under the right request, including on the commit where the request prop just changed; the request-change effect swaps in the target request's cached progress, so two pending requests in different sessions keep independent progress.

Scope notes

  • The cache is per renderer process: the main chat surface and the WorkHub WebContentsView each keep their own copy. The same request shown in two surfaces resumes independently; first submit wins. Cross-surface sync is out of scope.
  • WorkHub has no session switching. It renders one coordination session, and its sessionId changes only when the default Runtime Host is re-resolved (host changed, removed, or unavailable and later recovered), which tears the whole surface down first: transcript, execution state, and the interaction queue. The wizard restarts together with the rest of the surface in that case; carrying progress across a Host loss is out of scope. The main chat surface, where the issue was reported, switches sessions with a queue kept per session, and that is the path this fix covers.
  • No renderer-ledger changes: the fix is in @maka/ui plus tests.

Test plan

packages/ui user-question-prompt.test.tsx, mounted prompt: a remount with the same request resumes the wizard; two pending requests keep independent progress; a rejected submit and a fulfilled-but-failed stop both keep the progress; a fulfilled submit does not clear it (the prompt never forgets on its own); a rehydration through reconcileInteractions with a structured clone of the request, as a session switch does over IPC, resumes the wizard. That last test fails when reconcileInteractions takes the runtime's copy; interaction-queue.test.ts pins the identity contract directly, and a further prompt test checks that a structured clone handed to the prompt outside the queue starts a fresh wizard, so a requestId-keyed map does not pass. Without the cache write, every prompt test fails.

apps/desktop user-question-prompt-adapters.test.ts mounts the real prompt against the real createAppShellStopAction and createAppShellChatActions with a failing bridge: a failed stop or answer, reported as a toast and fulfilled, leaves the wizard resumable after a remount.

@github-actions github-actions Bot added the effort/M Under 500 readable lines label Sep 29, 2026

@hqhq1025 hqhq1025 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewed exact head fbf11d8120a01d1cbe6d40371b6fba5ef6c7f6ce.

The per-request state object and bounded cache fix the normal session-switch/remount path, but the failure-retention contract does not hold through the Desktop production adapters. I found 1 P2 (inline): failed answer/stop operations are caught by their callers and returned as fulfilled promises, so this component clears the cache even though the request is still pending. Switching away after that failure loses the wizard progress again.

Validation: clean install; build:test; full UI suite (697/697); full typecheck; lint; format; ASF headers; renderer architecture; focused prompt and AppShell stop tests; git diff --check. I also reproduced the production Stop path with the real createAppShellStopAction: the IPC rejected and the error toast fired, but remounting the same request restarted at 1 / 2 instead of resuming 2 / 2. Hosted test is green. Current main is 03237142; the PR is 1 commit ahead / 2 behind and merge-tree is clean.

Not verified: packaged Electron, native Windows/macOS, or a real Runtime Host transport failure.

Automated review notice: This comment was posted by an automated review agent operated by hqhq1025. It is not an independent human review and does not replace one.

// Answered: drop the cached progress so a later remount (should the
// resolved prompt linger) does not resurrect a half-finished wizard.
// On failure the cache stays, preserving the answers for the retry.
clearQuestionWizardProgress(requestId);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2] Do not infer production success from promise fulfillment here. The main-chat adapter catches bridge failures and resolves normally (apps/desktop/src/renderer/app-shell-chat-actions.ts:523-549), and Side Chat does the same (apps/desktop/src/renderer/features/workbar/tools/side-chat/use-quote-companion.ts:1694-1703). Consequently, a rejected respondToUserQuestion is shown as an error but this line still clears the cache; switching sessions then loses the answers the user was supposed to retry. The Stop path has the same mismatch: createAppShellStopAction catches and resolves at apps/desktop/src/renderer/app-shell-stop-action.ts:51-79, while Side Chat catches at use-quote-companion.ts:1431-1478, so the clear at lines 185-187 also runs after a failed stop. The new failure tests inject callbacks that reject directly and therefore do not exercise either production adapter. Please propagate an explicit applied/failed result (or preserve rejection through this boundary) and cover the mounted Desktop callback path.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 734c39e — thank you, the reproduction against the real createAppShellStopAction was exactly right.

The applied/failed signal now travels as an explicit boolean result instead of promise settlement:

  • UserQuestionPrompt's onRespond / onStop accept false as "not applied": the cached wizard progress is kept (rejection still works for callers that propagate it, e.g. WorkHub).
  • createAppShellStopAction resolves true only when the stop IPC succeeds, false on failure / no-op — still never rejects, so the fire-and-forget Composer Stop / Escape paths stay safe.
  • createAppShellChatActions.respondToUserQuestion returns respondToInteraction's new boolean (toast on failure, false). Sandbox boundary / form responders keep Promise<void> and discard it.
  • Side Chat's respondToUserQuestion and stop return the boolean too, and the panel passes companion.stop through instead of void-ing it.

Coverage for the mounted Desktop callback path: apps/desktop/src/main/__tests__/user-question-prompt-adapters.test.ts mounts the real prompt against the real stop action / chat actions with a failing bridge — a failed stop or answer leaves the wizard resumable at 2 / 2 after a remount, and a later success clears the cache. The app-shell-stop-action suite asserts the boolean directly, and the prompt suite covers the false contract on both callbacks.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Update: I reworked the fix and force-pushed 30a310325 — the explicit boolean contract is gone, and the adapters are untouched.

Why: threading the boolean through the adapters grew two ratcheted legacy files (app-shell-chat-actions.ts +24, app-shell-stop-action.ts +17 nonTriviaTokens), and --strict-base forbids any debt increase against the base commit — the ledger history only ever decreases. The contract was fighting the architecture ratchet.

The replacement is a stronger and simpler invariant: the per-request progress cache is write-only and FIFO-bounded, and nothing ever clears it. Your P2 reproduction hinged on the component clearing the cache when a swallowed failure resolved normally; with no clearing at all, failure retention holds unconditionally, no adapter cooperation needed. A resolved request never renders the prompt again (its requestId is never reused), so the lingering entry is unreachable and falls out through eviction.

The mounted Desktop coverage stays, reworked to the real failure semantics: user-question-prompt-adapters.test.ts mounts the prompt against the real createAppShellStopAction / createAppShellChatActions with a rejecting bridge — failed stop/answer (toast + resolve) leaves the wizard resumable at 2 / 2 after a remount. The prompt suite covers remount resume, two pending requests, failed submit, and failed stop.

@hqhq1025 hqhq1025 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewed exact head 734c39e858ddff1671ce59ae32841c0cbe001910.

The previous AppShell/Side Chat failure-retention issue is fixed: their production adapters now return false, and the mounted adapter regressions pass. This head is still not merge-ready:

  • P1: the current hosted test run fails check:renderer-architecture. src/renderer/app-shell-chat-actions.ts changed from the ledgered 3525 to 3549 non-trivia tokens, and src/renderer/app-shell-stop-action.ts from 302 to 319, but apps/desktop/renderer-architecture.json was not refreshed.
  • P2: WorkHub still violates the new stop-result contract (inline). A failed Host stop is caught and resolves undefined, so this prompt treats it as applied and clears the per-request wizard cache.

Validation: build:test; full UI suite (699/699); focused AppShell/Side Chat/WorkHub tests (106/106); full typecheck; lint; format; ASF headers; Windows inventory; git diff --check; current-main merge-tree. I also ran a temporary production-controller probe: with WorkHub services.stop throwing host unavailable, controller.stop() surfaced the error but fulfilled with undefined, which is the success value this prompt clears on. The diagnostic source change was removed and the worktree is clean.

Current main is ae71ab31; the PR is 2 commits ahead / 3 behind and merge-tree is clean. Not verified: packaged Electron, native Windows/macOS, or a real Runtime Host transport failure.

Automated review notice: This comment was posted by an automated review agent operated by hqhq1025. It is not an independent human review and does not replace one.

*/
onRespond(response: UserQuestionResponse): void | boolean | Promise<void | boolean>;
/** Same applied/failed contract as `onRespond`. */
onStop(): void | boolean | Promise<void | boolean>;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2] WorkHub still passes a failure-swallowing stop callback into this contract. workhub-root.tsx:302-304 wires controller.stop here, while use-workhub-controller.ts:619-635 catches stopTurn failures, reports them, and fulfills with undefined. The prompt therefore reaches applied !== false and clears the cache even though the question and running turn remain. I reproduced the production controller behavior with services.stop throwing: the error was exposed in controller state, but controller.stop() fulfilled undefined. Please make the WorkHub adapter return false (including the deferred deliverStop path) on a stop that was not applied, and add a mounted WorkHub prompt regression.

@hqhq1025 hqhq1025 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewed exact head 30a310325d2076d6a91f9969918618787bc58f77.

This revision removes the adapter-result contract, so the previous WorkHub stop finding and renderer-architecture failure no longer apply. The normal remount path and the mounted Desktop failure paths pass, but the unconditional retention introduces a new P2 (inline): completed requests share the same 32-entry FIFO with unresolved drafts and can evict progress that the user still needs.

Validation: build:test; focused prompt/Desktop adapter tests (7/7); full UI suite (697/697); full typecheck; lint; format; ASF headers; renderer architecture; Windows inventory; model metadata; git diff --check; current-main merge-tree. A temporary production-component regression kept one request at 2 / 2, successfully completed 32 distinct later requests, and then remounted the pending request; it failed with actual 1 / 2 versus expected 2 / 2. The diagnostic test was removed and the worktree is clean. Hosted test is green.

Current main is 0f98c2a4; the PR is 1 commit ahead / 5 behind and merge-tree is clean. Not verified: packaged Electron, native Windows/macOS, or a real Runtime Host transport failure.

Automated review notice: This comment was posted by an automated review agent operated by hqhq1025. It is not an independent human review and does not replace one.

if (wizardProgressCache.has(requestId)) wizardProgressCache.delete(requestId);
else if (wizardProgressCache.size >= MAX_CACHED_WIZARD_PROGRESS) {
const oldest = wizardProgressCache.keys().next();
if (!oldest.done) wizardProgressCache.delete(oldest.value);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2] Keep resolved residue from evicting a still-pending wizard. Successful answers and stops are never removed, so every completed request permanently occupies this same 32-entry FIFO until later activity evicts it. I reproduced the reachable sequence through UserQuestionPrompt: leave request A partially answered at question 2, successfully complete 32 distinct later requests, then remount A. The 32nd new id deletes A here, and createQuestionWizardState restarts it at question 1, losing the user's committed answer. This reintroduces the reported data-loss bug under the cache's own bound. Please separate unresolved state from completed residue, or clear entries from an authoritative request-resolution signal that cannot be confused by adapters swallowing bridge failures, and cover one pending request followed by 32 completed requests.

@UncertaintyDeterminesYou4ndMe

Copy link
Copy Markdown
Contributor Author

Addressed in 6a7a31b84 (rebased onto current main 28cc4e647) — thank you, the 1-pending + 32-completed reproduction was exactly right, and the split you suggested is what I landed on.

Resolution now demotes instead of occupying the pending bound. The cache is two separately FIFO-bounded maps (32 each):

  • pendingWizardProgress — drafts for requests this surface has not resolved. Only other pending drafts can evict these.
  • resolvedWizardResidue — entries for requests a settled answer/stop resolved here. They compete only with each other.

writeQuestionWizardProgress writes to pending (hoisting the entry out of residue if a possibly-lying resolution had parked it there — progress changing means the request is live again). The new resolveQuestionWizardProgress moves pending → residue on a settled answer or stop.

Why demotion rather than clearing on an authoritative signal: the component still cannot tell a real resolution from an adapter's swallowed bridge failure, and demotion is the operation that is safe under that lie — the entry stays readable from the residue if the request resurfaces, while a truthful resolution never renders the prompt again, so the entry falls out through the residue bound. Failure retention therefore holds unconditionally, and completed residue can never evict a wizard still waiting for answers.

Coverage: user-question-prompt.test.tsx gains exactly your scenario through the mounted UserQuestionPrompt — park request A at 2 / 2, run 32 distinct requests to a settled submit, remount A: resumes at 2 / 2 with the committed answer. The mounted Desktop adapter regressions (failed stop / failed answer through the real app-shell actions) stay green at 2 / 2 resume, since the residue remains readable after a swallowed failure.

Validation on this head: @maka/ui build + prompt suite 6/6, Desktop adapter tests 2/2, full UI suite (692 pass, 6 pre-existing mermaid/prompt-rail failures unchanged), lint clean. Not verified: packaged Electron, native Windows/macOS.

@github-actions github-actions Bot added effort/L Under 1000 readable lines and removed effort/M Under 500 readable lines labels Sep 30, 2026

@hqhq1025 hqhq1025 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewed exact head 6a7a31b841c2e02c10bd735932f64bd8d37c7589. The split pending/residue caches fix the reported case where completed requests evicted an untouched pending wizard. I found one remaining P2 on the failed-submit/stop path (inline).

Validation: Node 24 clean npm ci, build:test, focused UI/Desktop adapter tests 8/8, git diff --check, and a clean merge-tree against current main 0aa2707b. Exact-head hosted test passed. A direct probe of the built cache helper shows the failed request at question 2 before 32 later completions, then question 1 afterward. I traced the production Desktop adapter, which catches a rejected IPC and fulfills the callback, into the new demotion path. I did not exercise packaged Electron, native Windows/macOS, or a real Host transport failure.

Automated review notice: This comment was posted by an automated review agent operated by hqhq1025. It is not an independent human review and does not replace one.

const progress = pendingWizardProgress.get(requestId);
if (!progress) return;
pendingWizardProgress.delete(requestId);
writeBounded(resolvedWizardResidue, requestId, progress);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2] Keep failed requests out of the bounded resolved residue

A Desktop answer or stop IPC failure is caught by the production adapter and its callback fulfills (app-shell-chat-actions.ts:523-546, app-shell-stop-action.ts:51-79). The prompt therefore calls resolveQuestionWizardProgress even though the request is still pending. This moves its only cached progress into resolvedWizardResidue; 32 later successful questions evict it at this line. If the user switches back to the failed request, its wizard restarts at question 1 and loses committed answers. I reproduced the boundary with the built helper (questionIndex 1 before the 32 completions, 0 afterward). The new test covers an untouched pending request, not this reachable failed-request path. Demote only on an authoritative success (or make failures reject consistently), while keeping unresolved progress protected from completed residue eviction.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Addressed in e892d84e0 by changing what the cache is keyed on, rather than by adding another resolution rule — thank you for the failed-request trace; it showed the pending/residue split was still asking the prompt to judge a signal it cannot judge.

The progress now lives in a WeakMap keyed by the request object the interaction queue holds, and the queue owns that object's lifetime: enqueueInteraction dedupes by id, reconcileInteractions keeps the object the surface already shows instead of swapping in the runtime's IPC copy (same content — a pending request's fields are fixed; only the read's timestamp differs), and the queue drops the object on answer ack, tool result, terminal Turn event, or a live set that no longer lists it. The prompt writes progress on every change and never clears it; resolveQuestionWizardProgress, the residue map and the FIFO bound are gone.

Against your sequence: the Desktop adapter swallows the IPC failure and fulfills, the prompt does nothing with that, the runtime still holds the request, so the queue still holds the object and the entry stays readable — after 32, or any number of, later completions, since there is no bound and settled requests leave with their queue entry. A truthful resolution dequeues the object and the entry goes with it.

Coverage: the prompt suite keeps the mounted Desktop-adapter regressions (failed stop / failed answer through the real createAppShellStopAction / createAppShellChatActions, toast + fulfill, resume at 2 / 2) and adds a rehydration test that takes the request through reconcileInteractions with a structured clone, as the session-switch IPC read does; that test fails when reconcile keeps the runtime's copy, and interaction-queue.test.ts pins the identity contract directly. Without the cache write all six prompt tests fail.

Scope note in the description: WorkHub rebuilds its queue when its session or host coordination changes, so it resumes only within one such resolution; the main chat surface, where #5813 was reported, keeps a queue per session.

Fixes apache#5813.

The multi-question wizard kept its progress in component-local state, so
switching sessions and back restarted it at question 1 and dropped the
answers already given.

Cache the progress per request and restore it on mount. The cache is a
WeakMap keyed by the request object the interaction queue holds, and the
queue owns that object's lifetime: enqueue dedupes by id, reconcile now
keeps the object the surface already shows instead of the runtime's IPC
copy, and the queue drops it when the runtime settles the request. The
progress therefore lives exactly as long as the request is pending,
without the prompt deciding when a request is over (the Desktop adapters
report a failed answer or stop with a toast and fulfill anyway, so
fulfillment is no evidence of resolution) and without an eviction bound
that later requests could push a still-pending wizard out of.
@UncertaintyDeterminesYou4ndMe

Copy link
Copy Markdown
Contributor Author

Rewritten as e892d84e0 (rebased onto current main, single commit). The four review rounds each hit the same wall: the prompt was asked to decide when a request is resolved, and it cannot — the Desktop adapters report a failed answer or stop with a toast and fulfill anyway. The new head removes that decision instead of refining it: progress is cached in a WeakMap keyed by the request object the interaction queue holds, reconcileInteractions keeps the queued object across rehydration, and the entry lives exactly as long as the queue holds the request. No resolve call, no residue map, no FIFO bound. Details and the test plan are in the updated description; the inline reply on the last P2 walks through that sequence.

@hqhq1025 hqhq1025 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewed the current head. The new WeakMap removes the 32-entry eviction of still-pending requests, and the main chat queue retains request objects across live-set hydration. However, WorkHub still loses wizard progress on a session switch (inline finding), so this is not ready to merge. Node 24 build:test and 18 focused UI/adapter tests pass; the exact-head hosted test is green, and the branch merges cleanly with current main. I did not run packaged Electron or native Windows/macOS, nor a full WorkHub UI end-to-end test.\n\n> Automated review notice: This comment was posted by an automated review agent operated by hqhq1025. It is not an independent human review and does not replace one.

// WebContentsView each keep their own copy. The same request shown in two
// surfaces resumes independently; first submit wins. Cross-surface sync is
// out of scope.
const progressByRequest = new WeakMap<UserQuestionRequest, QuestionWizardProgress>();

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2] Preserve WorkHub progress when its queue is rebuilt. WorkHub clears interactions on every sessionId change (use-workhub-controller.ts:371-383). Returning to the first session rehydrates a new request object, so this object-keyed WeakMap misses the still-pending request and createQuestionWizardState() restarts at question 1, losing earlier answers. A built-helper probe gives index 1 before the switch and index 0 with empty text after clear + rehydration. The new rehydration test retains the same queue object and does not exercise this WorkHub path.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This sessionId change is not a session switch. WorkHub renders a single coordination session and has no session selector (controller.sessions is only used to link work items in workhub-root.tsx). sessionId is set only by startWorkHubCoordinationLifecycle (renderer/application/contracts/workhub-workspace/coordination-lifecycle.ts), which re-resolves it when the default Runtime Host changes, is removed, or goes unavailable and later recovers. Before every re-resolution the lifecycle calls onResolving, which sets sessionId to undefined and resets the surface (transcript, execution projection, stop state, error), so the queue clear at 371-383 is one part of a full teardown, not a switch away and back. When the same coordination session resolves again, the whole WorkHub view is rebuilt from the Host, and the wizard restarting is consistent with everything else on that surface.

The built-helper probe (clear, then rehydrate) reproduces that teardown, not the flow in #5813. The issue is the main chat surface, where sessions are user-switched and the queue is kept per session; that is the path this PR fixes and tests. Keeping WorkHub wizard progress across a default-Host loss would mean retaining request objects for a session the surface has revoked, which is a separate change from this fix, so I am leaving it out. I have rewritten the WorkHub scope note in the description to say this explicitly.

@Astro-Han

Copy link
Copy Markdown
Contributor

Thanks for working on this! #5854 fixed the same issue (keeping AskUserQuestion wizard progress across session switches) and has now been merged, so I'm closing this one as a duplicate. If you see a case that #5854 doesn't cover, please open an issue or a follow-up PR.

@Astro-Han Astro-Han closed this Oct 13, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

effort/L Under 1000 readable lines

Projects

None yet

Development

Successfully merging this pull request may close these issues.

AskUserQuestion multi-question wizard resets to question 1 after switching sessions

3 participants