← Back to Pull requests

fix(cli): stage a rewound turn's quotes into the replacement submit #5265

Open
ggbdpq opened this pull request with 3119 lines diff across 12 files
View on GitHub
ggbdpq ggbdpq commented on Sep 13, 2026 15:28 UTC
Author

Summary

/rewind on a turn that carried quotes used to fail closed with rewind_unsupported_quotes (#5109, behavior C): the TUI could only refill the human-facing text, so the replacement submit would silently drop the turn's structured context.

The runtime-host driver now returns the rewound turn's QuoteRefs verbatim on rewindToTurn, and submitMessage forwards quotes through turn.message.submit — the protocol admission already accepts client-authored quotes (only session-context attachments are Host-owned, and #4804 made a quote alone meaningful content). Attachments and directory references still fail closed, since the TUI cannot re-attach files.

The TUI stages the restored quotes keyed to the branched session:

  • the status line carries a quotes:<n> segment while staging is live (accent salience, dropRank with the other chrome),

  • bare /quotes lists the staged excerpts; /quotes clear is the explicit removal,

  • the first admitted submit consumes the staging; a refusal or failure restages it for the retry, and switching sessions invalidates it without every switch path having to clear it.
  • The now-dead rewind_unsupported_quotes code and its localized copy are removed together with the branch that emitted them.

    Part of #5109 — the remaining scope (editing a selected message that itself carries attachments) still needs the Host to expose the rewritten target-owned refs.

    Verification

    | Check | Result |
    | --- | --- |
    | New driver tests (red before the fix: rewind rejected quoted turns; submit content lacked quotes) | 2/2 green after |
    | New runner tests (staging visible via notice + status segment; submit carries the QuoteRefs verbatim and consumes them; /quotes clear drops them) | 2/2 green after |
    | pi-tui-runner full suite | 207/209 — the 2 failures (restores the terminal before exiting on SIGTERM, forces signal exit when outer cleanup never settles) fail identically on pristine upstream/main built in a clean worktree on this machine: pre-existing Windows signal-handling failures |
    | runtime-host-session-driver full suite | 25/75 — the 50 failures are all the documented pre-existing Windows class (Session cwd no longer exists: /tmp POSIX fixtures); none of them is a test added or modified here |
    | tui-copy-catalog, tui-primary-guidance, core slash-command-catalog | 8/8, 8/8, 1/1 |
    | check:asf-headers | passed locally (audited 3773 covered in checkout mode) |
    | format:check | the repo-wide run segfaults on this machine (biome crash during the full-tree walk, environmental); all 8 changed files pass biome check --formatter-enabled=true --linter-enabled=false individually, and upstream CI runs the repo-wide gate |

    AI use

    Select exactly one:

  • No generative tool made a substantive contribution

  • Generative tooling made a substantive contribution
  • Tool(s) and scope: GLM-5.3-Flash (ZCode) implemented the driver/TUI changes and tests under human direction and review.

    Checklist

  • Tests cover the change and fail without it

  • Lint, format, typecheck and the affected suites pass locally
  • Does this PR entail a change in behavior?

  • Yes — rewinding a quoted turn now restores its quotes into the replacement submit instead of refusing; /quotes is a new TUI command.

  • No
  • Diff: 3119 lines (+2674 / -445) across 12 files Reviewer: Astro-Han Review duration: 63787m
    All Vouch review confidence checks passed
    Residual risk 0.07 = Change Risk (0.66) × (1 − Review Confidence (0.90)). Review depth and reviewer attention state are adequate.
    Model 1 · Change Risk (XGBoost)
    Score: 0.66 · 3119 lines diff across 12 files
    0.66
    Model 2 · Review Depth (DistilBERT)
    Depth Score: 0.92 · 5 substantive comment(s)
    0.92
    Model 3 · Review Timing & Attention
    Session adequacy: 100% · Reviewer familiarity: 50%
    89%
    Bedrock Claude 3 · Risk Narration
    (disconnected)
    Groq
    Groq Risk Narration
    AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
    Model 1 · Change Risk Attribution
    SHAP Weights
    Diff Size diff_size
    0.400
    Real PR Conversation Timeline
    86 items
    Astro-Han Astro-Han commented on code on Sep 14, 2026 09:58 UTC
    Code Review
    packages/cli/src/pi-tui-runner.ts:1
    @@ -1293,6 +1328,10 @@ export async function runMakaPiTui(input: MakaPiTuiInput): Promise<void> {
             // The Message never became anything, so its row goes with the failure
             // notice that replaces it. The text stays in editor history for a retry.
             removeTransientUserMessage(messageId);
    +        if (staged.length > 0) {
    +          stagedRewindQuotes = staged;
    +          stagedQuotesSessionId = input.driver.getSessionId();
    +        }

    [P1] Restore failed-submit quotes only to their original draft

    Reachability ②: an admission request can be pending while /session other-session succeeds. Both failure branches tag the old staged payload with driver.getSessionId() at callback time, which is now the other Session. In a real-runner probe, I rewound a quoted turn, held its submit promise, switched Sessions, then rejected the original request; the next unrelated message in the new Session carried the old quote. This silently sends context to the wrong conversation (and potentially a different model connection).

    Could you capture the originating Session/draft generation before dispatch and restore only if that same draft still owns the result? Apply that check to both blocked and rejected responses, and prevent stale callbacks from overwriting a newer staged draft or explicit clear. A regression through submit → switch → delayed refusal → submit should carry no old quotes into the new Session.

    Astro-Han Astro-Han commented on code on Sep 14, 2026 09:58 UTC
    Code Review
    packages/cli/src/pi-tui-runner.ts:1
    @@ -1270,13 +1291,27 @@ export async function runMakaPiTui(input: MakaPiTuiInput): Promise<void> {
         const messageId = randomUUID();
         appendUserPrompt(state, text, messageId, true);
         requestRender();
    +    // Quotes staged by a rewind (#5109) ride this message and only this one:
    +    // the staging clears as the message dispatches, and a refusal or failure

    [P2] Let a quote-only replacement reach this submission path

    Reachability ①: a Desktop message can contain only QuoteRefs, so rewind now returns an empty prompt with nonempty quotes. The unchanged submitPrompt, steerRunningTurn and Alt+Enter guards still reject empty text before reaching this new quote-forwarding path. A runner probe restoring prompt: '' with one quote shows quotes:1, but Enter produces zero driver submissions; the user must invent extra text to resend the retained content.

    Please make the relevant editor/submit guards consider the current draft's quotes as meaningful content, while still rejecting truly empty drafts. Cover a quote-only rewind sent unchanged, and the corresponding empty draft after /quotes clear.

    Astro-Han Astro-Han commented on Sep 14, 2026 09:58 UTC
    Reviewer

    Thanks for addressing the quoted-turn gap in #5109. I reviewed eb5c88fc3fcc56849fddb954349ff9a7074caae6. Returning the existing QuoteRefs and forwarding them through the existing Host admission is the right direction; attachments can continue to fail closed until their target-owned refs can be restored.

    I found two reachable issues, detailed inline: P1, a delayed failure can attach one Session's staged quotes to another Session; P2, a quote-only replacement still cannot pass the text-only submit guards. These are draft ownership/content-admission issues within the existing runner, not a reason to introduce a new revision or import framework. Please bind retry restoration to the original draft/session identity and treat staged quotes as meaningful content at the submit entry points.

    Validation: the two new runner tests pass in an exact-source bundle with local dependencies. Two additional probes through the real runner/editor submission path reproduce both findings. I also checked the production driver's switch/admission code: session switching does not wait on the submit admission queue, so the delayed-failure interleaving is reachable. I did not run an installed TUI with a live Host or the full repository suite.

    Codex-assisted review with local reproduction.

    ggbdpq ggbdpq commented on Sep 14, 2026 13:11 UTC
    Author

    Both findings fixed at 6ca7ff99bf74d6e6caa024976bf40f2b1a7b0004:

    P1 (wrong-Session restore): the originating Session and a staging generation counter are captured at dispatch. The restore now runs only when the Session is unchanged and no newer staging or explicit clear bumped the generation — a switched Session, a newer rewind, or /quotes clear while the admission was in flight all leave the stale callback empty-handed.

    P2 (quote-only replacement): submitPrompt, steerRunningTurn and Alt+Enter now treat staged quotes as meaningful content, so an unchanged quote-only rewind reaches the driver; after /quotes clear the empty draft is truly empty and keeps refusing.

    Regressions: restores a failed quote submit only to its originating session (rewind → held admission → switch → reject → next submit in the new Session carries no quotes) and lets a quote-only rewind reach the submit path unchanged (empty prompt + staged quotes submits verbatim; after clear, nothing). Full pi-tui-runner suite 209/211 — the 2 failures are the pre-existing Windows SIGTERM pair already characterized on this PR's base.

    Astro-Han Astro-Han commented on Sep 15, 2026 15:43 UTC
    Reviewer

    Thanks for the quick turnaround — the quote-only submit path reads correctly. Two findings on the restage guard, reviewed at 6ca7ff99b.

    P1 — restageForRetry can never restore. originGeneration is captured before clearStagedQuotes() runs (pi-tui-runner.ts: the capture sits above the stagedGeneration += 1 inside clearStagedQuotes). By the time a blocked result or a failure lands, stagedGeneration !== originGeneration is always true, so the restore never executes. Reachable on the ordinary failure path: /rewind → submit → admission refused or fails → the staged quotes are silently dropped instead of returning for the retry the feature promises. The new tests can't see it: "restores a failed quote submit only to its originating session" asserts the other session stays clean, which also holds when restage never runs; nothing covers the same-session restore. Smallest fix: read stagedGeneration after clearStagedQuotes(), and add the positive case — same-session failed submit restages the quotes.

    P2 — a newer rewind does not invalidate an in-flight restage. The rewind path assigns stagedRewindQuotes/stagedQuotesSessionId directly (~pi-tui-runner.ts:2193) without bumping stagedGeneration, so after the capture order is fixed, a re-rewind landing while an admission is in flight would still be overwritten by the older failure's restage — the exact case the comment lists. Bump the generation on that assignment too (or route both writes through one setter).

    Everything else in the delta looks right — session-id capture and the empty-text-with-quotes gates in submitPrompt/steerRunningTurn/handleSubmit cover the paths we discussed.

    @me2seeks you know the TUI submit path best — could you sanity-check the restage semantics above?

    <details><summary>中文版</summary>

    在 6ca7ff99b 复核。P1:originGeneration 在 clearStagedQuotes()(内部 stagedGeneration += 1)之前捕获,失败或 blocked 落地时守卫恒真,restageForRetry 永不执行——带 staged quotes 的提交失败后 quotes 静默丢失,不回到草稿供重试。新测试只断言另一会话不继承,restage 不执行时也成立,所以没兜住;最小修法是把 generation 读取挪到 dispatch-clear 之后,并补同会话失败恢复的正例。P2:rewind 重新 stage 的赋值(~pi-tui-runner.ts:2193)不 bump generation,修好顺序后「in-flight 期间新 rewind」仍会被旧失败回调覆写,需在赋值处一并 bump。其余 delta(session 捕获、空文本+quotes 放行)没问题。

    </details>

    AI assistance: I used Devin to re-check the delta against the earlier findings; the assessment is mine.

    ggbdpq ggbdpq commented on Sep 16, 2026 23:10 UTC
    Author

    Both findings fixed at 399f15e08:

    P1 (restage unreachable): originGeneration is now read after the dispatch's own clearStagedQuotes(), so the guard compares against the staging state the submit actually left behind — an ordinary failure passes and restages, while a Session switch, a newer rewind, or an explicit clear landing in flight still vetoes. Added the positive case: a same-session failed submit restages the quotes onto the next submit (fails on the old order — restage never ran).

    P2 (stale restage overwrites newer staging): all staged-quote writes now route through one setStagedQuotes setter that bumps stagedGeneration (the rewind assignment included), so the write-site invariant no longer depends on the clear happening to sit next to it. Added the displacement case: a re-rewind landing while the first admission is in flight wins — the stale failure's restage is vetoed and the next submit carries the newer rewind's quotes (asserted with per-rewind distinct quote texts).

    Verification: full pi-tui-runner suite 211/213 — the only 2 failures are the pre-existing SIGTERM pair documented in the local baseline (fail identically on the unmodified base); biome clean on both touched files.

    Astro-Han Astro-Han commented on Sep 17, 2026 11:06 UTC
    Reviewer

    Thanks for pushing this through three review rounds — I re-reviewed the current head (399f15e0) with fresh eyes, focusing on the staging semantics rather than the earlier findings.

    What I verified

  • Both earlier findings are genuinely fixed. originGeneration is now read after the dispatch's own clearStagedQuotes() (pi-tui-runner.ts:1310-1324), and every write routes through setStagedQuotes, which bumps the generation (:623-628, used by the rewind path at :2199-2205). So an ordinary failure restages, while a Session switch, a newer rewind, or /quotes clear landing in flight vetoes the stale callback. All four new runner tests (__tests__/pi-tui-runner.test.ts:6780-7082) exercise exactly those vetoes plus the positive restage case.

  • Quote-only submits are admissible end to end. hasMeaningfulMessageContent (packages/core/src/events.ts:186) is the single predicate shared by protocol admission (packages/runtime-host/src/protocol/turn.ts:472-489), storage and compaction, so empty text + quotes is legal at every boundary. I also confirmed pi-tui's editor does call onSubmit('') for Enter on an empty buffer (editor.js:submitValue), so the new gates at :1227, :1367, :1385 are actually reachable — and that addToHistory drops empty input, so no empty history entry is created.

  • No duplication when the admission outcome is lost. RuntimeHostMakaSessionDriverImpl#submitMessage swallows outcome_unknown / interrupted-after-dispatch and resolves undefined, i.e. success, so the staging stays consumed rather than being re-sent on a retry. That's the right call for this feature.

  • Quotes are the right refs, verbatim, in order. rewindToTurn returns promptMessage.quotes from the rewound turn (runtime-host-session-driver.ts:901), the revision copy retains the copied turn ids, and the driver forwards a copy unchanged (:546). A newer rewind replaces (not appends to) the staging, so no cross-turn accumulation. No dedup is needed — the refs come from the Host, which already applied TURN_MESSAGE_QUOTE_MAX_COUNT/size limits when they were admitted.

  • Attachments and directory refs still fail closed before any branch exists — the driver test asserts no session.revision.create for those carriers (__tests__/runtime-host-session-driver.test.ts:2125-2213), so a quoted and attached turn can't half-rewind.

  • Repo-wide grep finds no leftover references to the removed rewind_unsupported_quotes code or copy outside the two changed files; the new /quotes entry is wired through both catalogs with all three locales filled in.
  • Findings

    1. A quoted replacement submit renders as nothing in the TUI transcript. This is the one thing I'd like a decision on. The TUI never renders QuoteRefs: the durable user projection emits message.displayText ?? message.text only (pi-transcript.ts:1086-1096), renderUserBlock returns [] for blank text (:2229-2230), and the pending bar prints Steering: with an empty preview for a queued one (:1972). So for the quote-only flow this PR explicitly enables (:6987), the user sends a message and sees no row for it — just an assistant reply to an invisible prompt, with the quotes:<n> segment gone and /quotes now reporting "No restored quotes are staged", i.e. no remaining evidence of what went out. The desktop already solves both halves: quote chips plus a structured-only branch that avoids an empty bubble (packages/ui/src/chat-turn.tsx:250-275). Rendering the quotes (or at least a · N restored quote(s) hint) in the durable user entry would close the loop; happy for it to be a follow-up, but it's user-visible as-is.

    2. nit — the staging is hidden on a Session switch, not invalidated. effectiveStagedQuotes() compares stagedQuotesSessionId to getSessionId() (:615-619), so leaving the branched session drops quotes:<n>, but coming back later (/session, the side-conversation toggle, /resume) silently re-arms the old quotes and the next submit carries them with no notice — potentially many turns later. The comment at :609-611 says switch paths "invalidate" the staging, which isn't quite what the code does. If resurrection isn't intended, bump stagedGeneration (or clear) when the view leaves that session; if it is, the comment and the copy could say so.

    3. nit — /quotes clear always reports success. The handler clears and pushes quotesCleared unconditionally (:4296-4302), so it claims "Restored quotes discarded" when nothing was staged, and also when the quotes are currently riding an in-flight submit (which will still carry them). Bare /quotes already distinguishes the empty case with quotesNone; clear could reuse that check.

    4. nit — a few cheap coverage gaps.

  • restageForRetry() is called on the disposition === 'blocked' branch (:1337) but no test covers it — only the rejected-promise path does. The existing HostSkillDriver (__tests__/pi-tui-runner.test.ts:11545) can refuse, so a quoted rewind plus a refused skill would cover it directly.

  • Every staging test uses a single quote, so ordering, the quotes:<n> count, and the /quotes listing order for >1 excerpt are unverified. A two-quote rewind result would pin all three.

  • /quotes is declared midTurn: 'local' but no test runs it mid-turn, which is the disposition most likely to regress silently.
  • 5. nit — a second rewind can dangle the quotes' provenance. Nothing validates sourceTurnId against the branched session, and a revision copy slices before the target turn (packages/runtime-host/src/server/session-revision-coordinator.ts:371-380). Rewinding twice in a row can therefore stage refs whose source turn no longer exists in the new branch. The inline text is intact so nothing is dropped from the model input; only a chip click-through in the desktop may fail to resolve. Not worth changing here — just noting the staging deliberately carries refs it doesn't re-validate.

    Net: I found no correctness bug in the staging/restage logic itself — the generation + session-id guards hold up under the interleavings I traced. Item 1 is the one I'd want an explicit answer on; the rest are nits.

    Astro-Han Astro-Han commented on Sep 17, 2026 11:06 UTC
    Reviewer

    Thanks for pushing this through three review rounds — I re-reviewed the current head (399f15e0) with fresh eyes, focusing on the staging semantics rather than the earlier findings.

    What I verified

  • Both earlier findings are genuinely fixed. originGeneration is now read after the dispatch's own clearStagedQuotes() (pi-tui-runner.ts:1310-1324), and every write routes through setStagedQuotes, which bumps the generation (:623-628, used by the rewind path at :2199-2205). So an ordinary failure restages, while a Session switch, a newer rewind, or /quotes clear landing in flight vetoes the stale callback. All four new runner tests (__tests__/pi-tui-runner.test.ts:6780-7082) exercise exactly those vetoes plus the positive restage case.

  • Quote-only submits are admissible end to end. hasMeaningfulMessageContent (packages/core/src/events.ts:186) is the single predicate shared by protocol admission (packages/runtime-host/src/protocol/turn.ts:472-489), storage and compaction, so empty text + quotes is legal at every boundary. I also confirmed pi-tui's editor does call onSubmit('') for Enter on an empty buffer (editor.js:submitValue), so the new gates at :1227, :1367, :1385 are actually reachable — and that addToHistory drops empty input, so no empty history entry is created.

  • No duplication when the admission outcome is lost. RuntimeHostMakaSessionDriverImpl#submitMessage swallows outcome_unknown / interrupted-after-dispatch and resolves undefined, i.e. success, so the staging stays consumed rather than being re-sent on a retry. That's the right call for this feature.

  • Quotes are the right refs, verbatim, in order. rewindToTurn returns promptMessage.quotes from the rewound turn (runtime-host-session-driver.ts:901), the revision copy retains the copied turn ids, and the driver forwards a copy unchanged (:546). A newer rewind replaces (not appends to) the staging, so no cross-turn accumulation. No dedup is needed — the refs come from the Host, which already applied TURN_MESSAGE_QUOTE_MAX_COUNT/size limits when they were admitted.

  • Attachments and directory refs still fail closed before any branch exists — the driver test asserts no session.revision.create for those carriers (__tests__/runtime-host-session-driver.test.ts:2125-2213), so a quoted and attached turn can't half-rewind.

  • Repo-wide grep finds no leftover references to the removed rewind_unsupported_quotes code or copy outside the two changed files; the new /quotes entry is wired through both catalogs with all three locales filled in.
  • Findings

    1. A quoted replacement submit renders as nothing in the TUI transcript. This is the one thing I'd like a decision on. The TUI never renders QuoteRefs: the durable user projection emits message.displayText ?? message.text only (pi-transcript.ts:1086-1096), renderUserBlock returns [] for blank text (:2229-2230), and the pending bar prints Steering: with an empty preview for a queued one (:1972). So for the quote-only flow this PR explicitly enables (:6987), the user sends a message and sees no row for it — just an assistant reply to an invisible prompt, with the quotes:<n> segment gone and /quotes now reporting "No restored quotes are staged", i.e. no remaining evidence of what went out. The desktop already solves both halves: quote chips plus a structured-only branch that avoids an empty bubble (packages/ui/src/chat-turn.tsx:250-275). Rendering the quotes (or at least a · N restored quote(s) hint) in the durable user entry would close the loop; happy for it to be a follow-up, but it's user-visible as-is.

    2. nit — the staging is hidden on a Session switch, not invalidated. effectiveStagedQuotes() compares stagedQuotesSessionId to getSessionId() (:615-619), so leaving the branched session drops quotes:<n>, but coming back later (/session, the side-conversation toggle, /resume) silently re-arms the old quotes and the next submit carries them with no notice — potentially many turns later. The comment at :609-611 says switch paths "invalidate" the staging, which isn't quite what the code does. If resurrection isn't intended, bump stagedGeneration (or clear) when the view leaves that session; if it is, the comment and the copy could say so.

    3. nit — /quotes clear always reports success. The handler clears and pushes quotesCleared unconditionally (:4296-4302), so it claims "Restored quotes discarded" when nothing was staged, and also when the quotes are currently riding an in-flight submit (which will still carry them). Bare /quotes already distinguishes the empty case with quotesNone; clear could reuse that check.

    4. nit — a few cheap coverage gaps.

  • restageForRetry() is called on the disposition === 'blocked' branch (:1337) but no test covers it — only the rejected-promise path does. The existing HostSkillDriver (__tests__/pi-tui-runner.test.ts:11545) can refuse, so a quoted rewind plus a refused skill would cover it directly.

  • Every staging test uses a single quote, so ordering, the quotes:<n> count, and the /quotes listing order for >1 excerpt are unverified. A two-quote rewind result would pin all three.

  • /quotes is declared midTurn: 'local' but no test runs it mid-turn, which is the disposition most likely to regress silently.
  • 5. nit — a second rewind can dangle the quotes' provenance. Nothing validates sourceTurnId against the branched session, and a revision copy slices before the target turn (packages/runtime-host/src/server/session-revision-coordinator.ts:371-380). Rewinding twice in a row can therefore stage refs whose source turn no longer exists in the new branch. The inline text is intact so nothing is dropped from the model input; only a chip click-through in the desktop may fail to resolve. Not worth changing here — just noting the staging deliberately carries refs it doesn't re-validate.

    Net: I found no correctness bug in the staging/restage logic itself — the generation + session-id guards hold up under the interleavings I traced. Item 1 is the one I'd want an explicit answer on; the rest are nits.

    ggbdpq ggbdpq commented on Sep 17, 2026 22:59 UTC
    Author

    Addressed everything actionable at 8822a0911 — thank you for tracing the editor's empty-buffer Enter and the driver's outcome-unknown swallow; both were load-bearing for the original findings.

    Item 1 (quote-only submit renders as nothing) — implemented now, not deferred. The durable user entry carries the restored-quote count and renders a trace line: blank text renders · N restored quote(s) as its row, and a quoted message with text appends the hint under it. Locale-free structural text, matching the quotes:<n> status segment's convention; localized chips stay desktop-side as you noted. Pinned in pi-transcript.test.ts through replaceTranscriptWithStoredMessages + renderMakaPiTranscript (blank+quotes, text+quotes, and no-quotes cases).

    Item 2 (hidden vs invalidated) — the staging is now invalidated. applySwitchResult — the single choke point every session change routes through — clears the staging outright; the rewind re-stages its own quotes after the switch settles. The stale comment now describes what the code does. Resurrection is no longer possible from any path.

    Item 3 (clear always reports success) — fixed. /quotes clear with nothing staged reports quotesNone instead of claiming a discard; this also covers the in-flight case, where the honest answer is that there is nothing left to clear. The quote-only test that had pinned the old lying copy now asserts the truthful one.

    Item 4 (coverage) — all three gaps closed:

  • blocked-disposition restage: a quoted rewind whose replacement the Host refuses (blocked + failed skill invocation) restages; the retry carries the refs again.

  • two-quote rewind: quotes:2, the /quotes listing order, and the replacement submit's ref order are all pinned (two distinct excerpts).

  • /quotes mid-turn: with a running Turn claiming busy, the listing still routes through the local disposition.
  • Item 5 (dangling provenance after a second rewind) — agreed, no change here: the refs are carried deliberately un-revalidated, and the desktop chip click-through is the place that resolves them.

    Verification: full pi-tui-runner + pi-transcript suites 328/332 — the only failures are the two pre-existing SIGTERM cases on the local baseline (fail identically without this branch's changes); biome clean on all four touched files.

    ggbdpq ggbdpq commented on Sep 20, 2026 03:43 UTC
    Author

    Gentle ping — everything actionable from your 09-17 review landed at 8822a0911 (the transcript trace line for quote-only submits, switch-path invalidation via applySwitchResult, the truthful /quotes clear copy, and the three coverage gaps). The head is now a127b13e: same tree plus a merge of main and a CI retrigger. Checks are green and the branch merges cleanly — re-review whenever you have a moment.

    me2seeks me2seeks requested changes on Sep 20, 2026 09:36 UTC
    Changes Requested Reviewer

    Review(对抗式复核,head a127b13ed)

    方向认可:把 rewind 掉的 turn 的 QuoteRef 原样返回并转发进替换 submit,而不是 fail-closed(rewind_unsupported_quotes),同时删掉死代码和对应文案,这是干净的做法。前几轮 review 的 P1(generation 读取顺序)和 switch 失效化确实已修好,我复核确认。

    不过还有 1 个 P1 和 1 个 P2 需要处理。

    ---

    P1 — outcome_unknown 路径下 staged quotes 会被静默吞掉,且永不 restage

    restageForRetry() 只在两个分支被调用(packages/cli/src/pi-tui-runner.ts):

  • .then 里 result?.disposition === 'blocked'

  • .catch 里
  • 但真实 driver 在「投递结果未知」时不抛异常,而是 resolve undefined(packages/cli/src/runtime-host-session-driver.ts:551-557):

    } catch (error) {
      if (
        (error instanceof RuntimeHostOperationError && error.code === 'outcome_unknown') ||
        (error instanceof RuntimeHostRequestInterruptedError && error.dispatch === 'dispatched')
      ) {
        return undefined;   // 注意:resolve,不是 reject
      }
      throw error;
    }
    

    #admit(:1271)把这个 undefined 原样透传。于是对于 outcome_unknown / interrupted-after-dispatch 的 submit:

  • .then 里 result?.disposition 是 undefined、if (result) 为 false → 不 restage;

  • .catch 不触发 → 不 restage。
  • 而 staging 在 dispatch 时已经被 clearStagedQuotes() 清掉,所以 quotes 被静默消费、永久丢失。

    这里需要纠正上一轮 review 的一个判断。上一轮把这条路径读成了「resolve undefined,i.e. success,所以 staging 保持消费是正确的」。但按 RuntimeHostRequestInterruptedError 自己的文案(packages/runtime-host/src/client/connection.ts:328-330),dispatch === 'dispatched' 的含义是:

    'the operation outcome is unknown; do not retry it automatically'

    message-coordinator.ts:1236 的 outcome_unknown 同样是「Message disposition cannot be proven in this Host Epoch」——结果无法证明,而不是「已确认接纳」。所以这不是一个「有意保持消费」的设计,而是一个未被识别的缺口:恰恰在「消息可能没被接纳」时,把上下文静默丢掉了。

    需要说明的是,这里存在一个真实的两难:如果消息其实已经被接纳,restage 会导致重试时重复发送 quotes。但当前代码既没有注释说明这是有意为之,也没有测试覆盖这条路径。建议明确决策并写清理由(例如「outcome_unknown 视为已接纳,故不 restage,避免重复」),或者按语义选择 restage 并说明重复风险。

    测试盲区:所有新测试用的 HeldSubmitQuotedDriver.submitMessage 都是 reject(packages/cli/src/__tests__/pi-tui-runner.test.ts 的 new Promise((_, reject) => ...)),没有任何用例走 resolve-undefined 这条真实路径。

    ---

    P2 — 任意带 quotes 的用户消息都会被标成「restored quote」,不只是 rewind 恢复的

    packages/cli/src/pi-transcript.ts(本 PR 新增):

    const restoredQuotes = message.quotes?.length;
    entries.push({
      kind: 'user',
      messageId: message.id,
      text: message.displayText ?? message.text,
      ...(restoredQuotes ? { quotes: restoredQuotes } : {}),
    });
    

    渲染时无条件加标签:

    const hint = `· ${entry.quotes} restored quote${entry.quotes === 1 ? '' : 's'}`;
    

    问题是 StoredMessage.quotes 并不是「rewind 恢复」专属字段——桌面端普通引用消息也写入同一个字段,并且会进入 TUI 渲染的同一份 durable transcript:

  • apps/desktop/src/renderer/features/workbar/tools/side-chat/use-quote-companion.ts:1238(普通引用提交)

  • apps/desktop/src/main/session-local-service.ts:198(把 content.quotes 投影回本地消息)

  • 桌面端 edit & resend 的 restage 路径(#5274)同样会写入该字段
  • 而 TUI 在打开/切换会话时会走 applySwitchResult → replaceTranscript(messages) → storedMessagesToTranscriptEntries(pi-tui-runner.ts:1878、pi-transcript.ts:422),所以任何带引用的用户消息都会显示「· N restored quotes」,事实错误。

    本 PR 自己的测试也把这个错误固化了:pi-transcript.test.ts 里 message-2 是 text: 'with words' + 一个 quote,断言输出 · 1 restored quote。而 packages/ui 对同一字段的中性投影是「Inline quoted excerpts」(packages/ui/src/materialize.ts:62),两边语义已经分叉。

    建议:把标签改成中性(例如「· N quote(s)」),或者给 entry 增加一个真正的「restored」标记(由 rewind 路径显式设置),而不是用「有没有 quotes」来推断。

    ---

    已确认没问题的点

  • 删除的代码没有残留引用:全仓 grep 无 rewind_unsupported_quotes / unsupportedQuotes 残留。

  • quote-only submit 链路通:hasMeaningfulMessageContent 是 protocol admission / 存储 / compaction 共用的单一谓词,空 text + quotes 在各边界都合法;/quotes 三个 locale(en / zh-CN / zh-TW)文案齐全。

  • /quotes 解析:parts = trimmed.split(/\s+/),/quotes、/quotes clear、其它形式走 usage 提示,与文件内其它命令(如 /host)一致;midTurn: 'local' 是合法取值。

  • /new 路径:newSession 不调用 clearStagedQuotes(),但 startNewSession 会把 #sessionId 置 null,effectiveStagedQuotes() 因 session 不匹配返回 [],且之后任何切回都会经 applySwitchResult 清空——不会 resurrect,属于注释措辞不够精确,不是 active bug。
  • ---

    小结:P1 建议在合并前明确决策并补测试;P2 建议改中性标签。其余为已澄清项。

    ggbdpq ggbdpq commented on Sep 20, 2026 15:19 UTC
    Author

    Thanks for the adversarial re-read — both findings confirmed and fixed on cb6d10882 (merged latest main first, no conflicts).

    P1 — outcome_unknown restage. Confirmed: the real driver resolves undefined for outcome_unknown and for an interruption after dispatch, and the .then arm only handled disposition === 'blocked', so the staging was silently consumed exactly when admission was least proven. Decision: restage on the unknown path and surface a notice ("Submit outcome unknown; staged quotes restored for retry."). An unproven outcome is not an admission; losing the user's explicitly staged context is the irreversible branch, while the duplicate-ride risk if the message did land stays visible (status line quotes:N) and discardable (/quotes clear). The restage still routes through the same session/generation guards, so a Session switch, newer rewind, or explicit clear landing in flight keeps winning.

    P2 — neutral trace. Also confirmed: StoredMessage.quotes carries every quoted user message (desktop plain quotes and edit-restaged ones included), not just rewind restages, so the durable trace mislabeled them. The trace line is now the neutral · N quote(s), matching @maka/ui's neutral projection of the same field.

    Tests: new UnknownOutcomeSubmitDriver pins the resolve-undefined path (all prior held-submit tests rejected — the reviewer-noted blind spot), and the transcript test now asserts the neutral wording instead of enshrining the old label. Both fail against the pre-fix source and pass on cb6d10882; the rest of the two suites is unchanged (only the two known SIGTERM flakes, pre-existing and unrelated).

    ggbdpq ggbdpq commented on Sep 20, 2026 15:30 UTC
    Author

    Follow-up on c07c577a7: the first push's CI failure was my mistake, not the fix itself — the unknown-outcome notice was a visible literal in pi-tui-runner, which check:tui-copy correctly rejects. The notice now goes through the rewind copy catalog (quotesRestoredUnknown, en / zh-CN / zh-TW), guard green, test re-run green.

    ggbdpq ggbdpq commented on Sep 24, 2026 11:27 UTC
    Author

    Gentle ping — the head is dcb9c22a4 (CI green, merges cleanly into the current main): the fixes for your 09-20 review plus one style cleanup commit. Everything actionable from that review is in — the outcome_unknown restage with the catalog notice and the neutral N quote(s) label — so a re-review whenever you have a moment would be much appreciated.

    hqhq1025 hqhq1025 commented on code on Sep 25, 2026 15:41 UTC
    Code Review
    packages/cli/src/pi-tui-runner.ts:1
    @@ -1361,16 +1396,59 @@ export async function runMakaPiTui(input: MakaPiTuiInput): Promise<void> {
         const messageId = randomUUID();
         appendUserPrompt(state, text, messageId, true);
         requestRender();
    +    // Quotes staged by a rewind (#5109) ride this message and only this one:
    +    // the staging clears as the message dispatches, and a refusal or failure
    +    // restages them for the retry.
    +    const staged = effectiveStagedQuotes();
    +    const originSessionId = input.driver.getSessionId();
    +    if (staged.length > 0) clearStagedQuotes();
    +    // The generation is read after the dispatch's own clear: the restore
    +    // guard compares against the staging state this submit actually left
    +    // behind, so an ordinary failure still passes while a Session switch, a
    +    // newer rewind, or an explicit clear landing while the admission was in
    +    // flight has since bumped it and must not inherit context meant for the
    +    // original conversation (#5109 review).
    +    const originGeneration = stagedGeneration;
    +    const restageForRetry = (): boolean => {
    +      if (!staged.length) return false;
    +      if (input.driver.getSessionId() !== originSessionId) return false;
    +      if (stagedGeneration !== originGeneration) return false;

    P2: The generation only changes when staging is written. After a quoted submit clears staging, a second ordinary submit in the same session does not advance it; /quotes clear also returns early while staging is empty (lines 4695-4705). If the first admission then fails or resolves without a receipt, this callback restages its old QuoteRefs, so a later unrelated message silently carries the earlier quote despite the intervening user intent. Invalidate the pending restoration when an ordinary submit or explicit clear supersedes it, and test both orderings with a held admission.

    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.

    hqhq1025 hqhq1025 commented on Sep 25, 2026 15:41 UTC
    Reviewer

    This change now carries rewound QuoteRefs through the CLI driver and into the replacement submit, accepts quote-only submits, and uses neutral wording in the durable transcript. I found one remaining failure-ordering issue below. The current-head test check passed, but I did not run local TUI tests or a cross-surface smoke test. The earlier CHANGES_REQUESTED review is attached to an older commit, not this head.

    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.

    ggbdpq ggbdpq commented on code on Sep 26, 2026 13:15 UTC
    Code Review
    packages/cli/src/pi-tui-runner.ts:1
    @@ -1361,16 +1396,59 @@ export async function runMakaPiTui(input: MakaPiTuiInput): Promise<void> {
         const messageId = randomUUID();
         appendUserPrompt(state, text, messageId, true);
         requestRender();
    +    // Quotes staged by a rewind (#5109) ride this message and only this one:
    +    // the staging clears as the message dispatches, and a refusal or failure
    +    // restages them for the retry.
    +    const staged = effectiveStagedQuotes();
    +    const originSessionId = input.driver.getSessionId();
    +    if (staged.length > 0) clearStagedQuotes();
    +    // The generation is read after the dispatch's own clear: the restore
    +    // guard compares against the staging state this submit actually left
    +    // behind, so an ordinary failure still passes while a Session switch, a
    +    // newer rewind, or an explicit clear landing while the admission was in
    +    // flight has since bumped it and must not inherit context meant for the
    +    // original conversation (#5109 review).
    +    const originGeneration = stagedGeneration;
    +    const restageForRetry = (): boolean => {
    +      if (!staged.length) return false;
    +      if (input.driver.getSessionId() !== originSessionId) return false;
    +      if (stagedGeneration !== originGeneration) return false;

    Thank you — the ordering you describe is real in the failure callback's guard, and both supersessions are now advanced explicitly: an ordinary quote-less submit and an empty-staging /quotes clear each call a new supersedePendingRestage() (a generation bump without a staging write), so the callback refuses. Pushed at b261e8dd2.

    One finding from trying to write the two regression tests you asked for: through the public TUI harness the interleaving is currently unreachable, because the runner parks user input for the whole in-flight window — submitPrompt returns through restoreDraft when busy, and runControl refuses nested actions while one is running — so no ordinary submit or command can land between the dispatch and the settlement that arms the callback. Both orderings deadlock waiting for a driver call that the busy gate prevents. The invalidation is still worth having (the guard now holds by construction rather than by the busy gate staying where it is, and this file's routing is actively being reworked upstream), but a black-box regression for these two orderings would first need a driver that starts a Turn without ever resolving its admission receipt — the existing HeldSubmitQuotedDriver blocks the runner before a second submit can be attempted. If you'd like, I can follow up with that harness work as its own change.

    hqhq1025 hqhq1025 commented on Sep 26, 2026 15:13 UTC
    Reviewer

    At this head, I found no new substantiated P0–P3 issue. The follow-up increments the quote-staging generation for a quote-less submit and for an explicit /quotes clear when staging is empty. The earlier quoted submission's failure/unknown-outcome callback checks that generation before restoring, so these later intents no longer inherit its quotes. I also rechecked the rewind-to-staging-to-Host submission path, quote-only input, session-switch invalidation, and transcript disclosure. The PR changes 9 files; no schema migration is involved.

    The current-head CI test check passed, and the diff and merge-tree checks were clean against the latest main. I did not run local TUI tests or a terminal smoke test. The two newly fixed interleavings do not have dedicated black-box regressions; input gating may make them unreachable in the current harness, so a future routing change should preserve this generation guard. An older CHANGES_REQUESTED review remains in GitHub's review decision; human reviewers need to decide readiness.

    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.

    Astro-Han Astro-Han commented on code on Sep 27, 2026 11:13 UTC
    Code Review
    packages/cli/src/pi-tui-runner.ts:1
    @@ -1414,7 +1503,7 @@ export async function runMakaPiTui(input: MakaPiTuiInput): Promise<void> {
         // be queued onto it and no fresh turn may open — keep the draft.
         if (interruptRequested) return;
         const text = editor.getExpandedText().trim();
    -    if (!text) return;
    +    if (!text && effectiveStagedQuotes().length === 0) return;

    P2 — This lets staged quotes ride a queued message, but the retraction path cannot give them back: retractQueued() in runtime-host-session-driver.ts:587-597 drops content.quotes from the Host's reply, and acceptRetraction (line 1389) restores only the text. After Alt+↑ / Esc the quotes are gone with no notice, and a quote-only message leaves an empty editor. Either restore the retracted messages' quotes into staging, or keep staged quotes out of the queue until retraction can preserve them.

    Astro-Han Astro-Han commented on Sep 27, 2026 11:13 UTC
    Reviewer

    Reviewed at this head by three independent AI reviewers (different model families). The fix is sound, but all three found the same context-loss path (P2, inline), so we would hold the merge until it is addressed.

    What works: the driver now returns the rewound turn's QuoteRefs and they travel verbatim in content.quotes through the single submit path; attachments and directory references still fail closed. Staging is keyed by session and cleared on switch; the generation guard (including the bump for quote-less submits and /quotes clear on an empty stage) stops a stale failure callback from restaging over newer intent; quote-only input is accepted at all three entry points; the transcript marks quoted user messages. About 79% of the +1071 lines are tests, and they distinguish the new behaviour from the old refusal.

    The P2: quotes that ride a queued or steered message are dropped silently when the user takes that message back (Alt+↑ or Esc). The Host's queue.retract returns full MessageContent, including quotes, but RuntimeHostSessionDriver.retractQueued() (runtime-host-session-driver.ts:587-597) keeps only text and message ids, and acceptRetraction (pi-tui-runner.ts:1389) refills only the text. A resubmit then goes out without the quotes, and for a quote-only message the whole input disappears. The PR's own MidTurnQuotesDriver test sets up exactly this state. Please carry the quotes through retraction and restage them (with a test covering one and several queued messages), or refuse to queue staged quotes until they can be preserved.

    Smaller notes:

  • On an unknown outcome the quotes are restaged without checking whether the message was actually accepted, so they can be sent twice.

  • When a later plain submit supersedes a failed quoted submit's restore, the quotes are dropped with no notice.

  • A quote-only message leaves no row while pending, queued or steered, and the · N quote(s) line reads like typed text.

  • Unused ShellRunSnapshotResult import in session-driver.ts.
  • Also: an older CHANGES_REQUESTED review on a previous head still affects the PR's review decision.

    Not verified: a real terminal session against a live Host.

    ---

    Automated review notice: This review was posted by an automated review agent operated by Astro-Han. It combines independent reviews from several AI models. It is not an independent human review and does not replace one.

    ggbdpq ggbdpq commented on Sep 27, 2026 12:21 UTC
    Author

    Addressed on head fea2f7ac2:

    P2 (quotes lost on retraction): MakaRetractedMessages now carries the retracted entries' quotes — the Host already returns the full MessageContent — and acceptRetraction restages them on the current session through the generation-guarded setter, so the restoration obeys the same veto rules as every other staging write (a session switch, a newer rewind, or /quotes clear landing in flight still wins). Two runner tests cover the steered case and a multi-message retraction where one entry carries quotes and one does not. The unused ShellRunSnapshotResult import is dropped too.

    On the smaller notes:

  • Restage without an acceptance receipt (double-send risk): this is the deliberate outcome-unknown stance this series settled on earlier — when no receipt comes back, the quotes return visibly (the quotes: N status line) and /quotes clear is the escape hatch. Distinguishing "delivered but unacknowledged" from "never admitted" needs a delivery receipt from the Host, which this PR deliberately does not build.

  • No notice when a later plain submit supersedes a pending restoration: agreed this is a UX gap; surfacing a notice needs a small render-side change I would rather keep out of this series. Happy to follow up.

  • Quote-only messages render no pending row: same — follow-up material, tracked here so it does not get lost.
  • On the older CHANGES_REQUESTED: its P1 (quotes swallowed on outcome-unknown, never restaged) is what the generation-guarded restage on this head fixed, and its P2 (quote-only replacement refused at the submit guards) was confirmed fixed in the second-round review. Nothing outstanding is tracked against that review that this head does not address — happy to re-review or have it re-checked.

    Local verification: cli build clean, pi-tui-runner suite 232/234 with the only two failures the pre-existing Windows SIGTERM pair (same baseline as earlier rounds), new tests green; CI is running on this head.

    hqhq1025 hqhq1025 commented on code on Sep 27, 2026 13:11 UTC
    Code Review
    packages/cli/src/pi-tui-runner.ts:1
    @@ -1342,9 +1391,15 @@ export async function runMakaPiTui(input: MakaPiTuiInput): Promise<void> {
         if (index >= 0) state.entries.splice(index, 1);
       };
     
    -  const acceptRetraction = (retracted: { text: string; messageIds: readonly string[] }) => {
    +  const acceptRetraction = (retracted: MakaRetractedMessages) => {
         for (const messageId of retracted.messageIds) removeTransientUserMessage(messageId);
         refillEditorFromQueues(retracted.text);
    +    // The Host returns the full MessageContent with a retraction: quotes that
    +    // rode a queued or steered message come back with it and restage here, so
    +    // the re-edited retry does not go out without them (#5109 review).
    +    if (retracted.quotes.length > 0) {
    +      setStagedQuotes(retracted.quotes, input.driver.getSessionId());

    [P2] Keep the retraction bound to its originating Session. Alt+Up starts an async queue.retract for Session A; while it is pending, mid-turn /session can switch the driver to B (switchAwayMidTurn does not wait for this task and applySwitchResult clears staging). When the response for A arrives, this line uses the current getSessionId() and stages A's QuoteRefs under B, where the next submit can send A's context to the wrong Session. Capture the owner before the first await and discard or otherwise fence a response after a switch; add a delayed-retract/switch regression.

    hqhq1025 hqhq1025 commented on Sep 27, 2026 13:11 UTC
    Reviewer

    Reviewed the current head 92615d63 (nine files, +1071/-71 overall; the latest two commits change five CLI files). This revision carries retracted MessageContent.quotes through the Runtime Host driver (runtime-host-session-driver.ts:587-600) and restages them in the TUI (pi-tui-runner.ts:1394-1402). The new TUI tests cover a quoted queued message and a quoted message among multiple retracted entries. The earlier generation-supersession fix remains in place.

    I found one P2 cross-Session race in the new restaging path, noted inline. The current-head test check succeeds, the static merge with fresh main 2a568ef9 and git diff --check are clean, and I found no schema/migration change. I did not run the local TUI suite (dependencies are not installed here), a real Host/TUI concurrency test, or terminal smoke. An older CHANGES_REQUESTED review remains on this PR; a green current-head check does not resolve that human review.

    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.

    ggbdpq ggbdpq commented on Sep 27, 2026 14:57 UTC
    Author

    Fixed on head 668a57654. The runner now captures the owning session before the first await in both retraction paths (interrupt and Alt+Up), and a response that lands after the driver has re-keyed is discarded outright — neither its text nor its quotes reach the session the switch landed on, whose staging stays as applySwitchResult left it. A delayed-retract/session-switch regression covers it (discards a retraction that lands after a mid-turn session switch): the retraction is held on a gate, the switch completes, the response is released, and the switched-to session's status line shows no staged quotes. Full pi-tui-runner suite green locally (232/234 with only the pre-existing Windows SIGTERM pair); CI running on this head.

    hqhq1025 hqhq1025 commented on code on Sep 27, 2026 15:22 UTC
    Code Review
    packages/cli/src/pi-tui-runner.ts:1
    @@ -1427,8 +1534,17 @@ export async function runMakaPiTui(input: MakaPiTuiInput): Promise<void> {
       // prepended to the current draft for re-editing.
       const retractQueuedMessages = () => {
         void (async () => {
    +      // Same session fence as the interrupt path: a mid-turn `/session` that
    +      // lands while the retraction is in flight must not inherit the quotes
    +      // or the text of the session we left (#5109 review).
    +      const retractionSessionId = input.driver.getSessionId();
           await settlePendingEnqueues();
    -      const retracted = (await input.driver.retractQueued?.()) ?? { text: '', messageIds: [] };
    +      const retracted = (await input.driver.retractQueued?.()) ?? {

    [P1] The session check happens only after retractQueued() has acted. If an A enqueue is still pending, Alt+Up waits in settlePendingEnqueues(); a permitted mid-turn /session B can complete during that wait. RuntimeHostSessionDriver.retractQueued() reads its current #sessionId when called, so this now retracts B's queued messages, and the following mismatch check discards their text and quotes. The new regression only switches after the retraction request is already in flight. Bind the request to the captured session (or abort before dispatch on a mismatch), and test a switch during pending-enqueue settlement.

    hqhq1025 hqhq1025 commented on code on Sep 27, 2026 15:22 UTC
    Code Review
    packages/cli/src/pi-tui-runner.ts:1
    @@ -1266,10 +1309,21 @@ export async function runMakaPiTui(input: MakaPiTuiInput): Promise<void> {
         // Serializing these operations also preserves that ordering over a Host
         // connection where both calls are asynchronous.
         void (async () => {
    +      // Fence the retraction to the session it was asked for: a mid-turn
    +      // `/session` landing while the Host call is in flight re-keys the
    +      // driver, and neither the retracted text nor its quotes may land in
    +      // the session we switched to (#5109 review).
    +      const retractionSessionId = input.driver.getSessionId();
           await settlePendingEnqueues();
    -      const retracted = (await input.driver.retractQueued?.()) ?? { text: '', messageIds: [] };
    -      acceptRetraction(retracted);
    -      requestRender();
    +      const retracted = (await input.driver.retractQueued?.()) ?? {
    +        text: '',
    +        messageIds: [],
    +        quotes: [],
    +      };
    +      if (input.driver.getSessionId() === retractionSessionId) {
    +        acceptRetraction(retracted);
    +        requestRender();
    +      }
           await input.driver.stop();

    [P1] The interrupt path fences only acceptRetraction; it still calls driver.stop() unconditionally after an A retraction returns. Mid-turn /session B is allowed while that await is outstanding, and RuntimeHostSessionDriver.stop() targets the currently attached root turn. If B has an active turn, Ctrl+C intended for A therefore aborts B after the switch, even though the code discarded A's retraction. Keep the stop bound to A's turn/session (and cover this delayed-retraction switch), rather than stopping whichever session is current on completion.

    hqhq1025 hqhq1025 commented on Sep 27, 2026 15:22 UTC
    Reviewer

    Reviewed the two-file follow-up and the surrounding TUI/driver session-switch paths. The new response-time check prevents a late A retraction from staging quotes into B in the covered test, but it does not bind the retraction request or the subsequent interrupt to A. The two races below can affect B. Node 24 build:test and the focused quote/retraction tests (3/3) pass; current-head CI test succeeds, and the merge-tree against current main and diff-check are clean. No schema/migration change. I did not run an interactive TUI/Host race reproduction; the findings follow the reachable asynchronous control flow and driver target selection.

    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.

    hqhq1025 hqhq1025 commented on code on Sep 27, 2026 23:13 UTC
    Code Review
    packages/cli/src/__tests__/pi-tui-runner.test.ts:1
    @@ -7602,6 +7604,779 @@ Slug openai-work<cursor>
         ]);
       });
     
    +  test('stages a rewound turn quotes into the replacement submit', async () => {
    +    const terminal = new FakeTerminal();
    +    const driver = new QuotedRewindDriver(
    +      [{ turnId: 'turn-1', label: 'first question' }],
    +      [
    +        storedUserMessage('user-1', 'turn-1', 'first question'),
    +        storedAssistantMessage('assistant-1', 'turn-1', 'first answer'),
    +      ],
    +    );
    +    const run = runMakaPiTui({
    +      title: 'Maka',
    +      driver,
    +      cwd: '/repo',
    +      model: 'claude-sonnet-4-5',
    +      connectionSlug: 'claude-subscription',
    +      permissionMode: 'ask',
    +      terminal,
    +    });
    +
    +    terminal.input('/rewind');
    +    terminal.input('\r');
    +    await waitFor(() => plainTerminalOutput(terminal.output()).includes('first question'));
    +    terminal.input('\r');
    +    await waitFor(() => driver.rewound.length === 1);
    +    // The restored quotes are visible while staging is live: the rewind
    +    // notice names them and the status line carries a quotes:<n> segment.
    +    await waitFor(() => plainTerminalOutput(terminal.output()).includes('quoted context'));
    +    await waitFor(() => plainTerminalOutput(terminal.output()).includes('quotes:1'));
    +
    +    // The replacement submit carries the staged QuoteRefs verbatim.
    +    terminal.input('answer with this context');
    +    terminal.input('\r');
    +    await waitFor(() => driver.submittedQuotes.length === 1);
    +    assert.deepEqual(driver.submittedQuotes[0], [
    +      { text: 'a large pasted excerpt', label: 'earlier turn', sourceTurnId: 'turn-0' },
    +    ]);
    +    // Staging is consumed by the submit it rode on.
    +    terminal.input('plain follow-up');
    +    terminal.input('\r');
    +    await waitFor(() => driver.submittedQuotes.length === 2);
    +    assert.equal(driver.submittedQuotes[1], undefined);
    +
    +    exitMaka(terminal);
    +    await Promise.race([
    +      run,
    +      delay(CLOSE_BUDGET_MS).then(() => {
    +        throw new Error('TUI did not close during test cleanup');
    +      }),
    +    ]);
    +  });
    +
    +  test('restores a failed quote submit only to its originating session', async () => {
    +    const terminal = new FakeTerminal();
    +    const driver = new HeldSubmitQuotedDriver(
    +      [{ turnId: 'turn-1', label: 'first question' }],
    +      [storedUserMessage('user-1', 'turn-1', 'first question')],
    +    );
    +    const run = runMakaPiTui({
    +      title: 'Maka',
    +      driver,
    +      cwd: '/repo',
    +      model: 'claude-sonnet-4-5',
    +      connectionSlug: 'claude-subscription',
    +      permissionMode: 'ask',
    +      terminal,
    +    });
    +
    +    terminal.input('/rewind');
    +    terminal.input('\r');
    +    await waitFor(() => plainTerminalOutput(terminal.output()).includes('first question'));
    +    terminal.input('\r');
    +    await waitFor(() => plainTerminalOutput(terminal.output()).includes('quotes:1'));
    +    terminal.input('resend this');
    +    terminal.input('\r');
    +    await waitFor(() => driver.submittedQuotes.length === 1);
    +
    +    // A Session switch lands while the admission is still pending.
    +    driver.switchSession('session-other');
    +    driver.hold(new Error('admission outcome unknown'));
    +    await waitFor(() =>
    +      plainTerminalOutput(terminal.output()).includes('admission outcome unknown'),
    +    );
    +
    +    // The next message in the new Session must not carry the old quotes.
    +    terminal.input('unrelated follow-up');
    +    terminal.input('\r');
    +    await waitFor(() => driver.submittedQuotes.length === 2);
    +    assert.equal(driver.submittedQuotes[1], undefined);
    +
    +    exitMaka(terminal);
    +    await Promise.race([
    +      run,
    +      delay(CLOSE_BUDGET_MS).then(() => {
    +        throw new Error('TUI did not close during test cleanup');
    +      }),
    +    ]);
    +  });
    +
    +  test('restages a failed quote submit back onto the same session', async () => {
    +    const terminal = new FakeTerminal();
    +    const driver = new HeldSubmitQuotedDriver(
    +      [{ turnId: 'turn-1', label: 'first question' }],
    +      [storedUserMessage('user-1', 'turn-1', 'first question')],
    +    );
    +    const run = runMakaPiTui({
    +      title: 'Maka',
    +      driver,
    +      cwd: '/repo',
    +      model: 'claude-sonnet-4-5',
    +      connectionSlug: 'claude-subscription',
    +      permissionMode: 'ask',
    +      terminal,
    +    });
    +
    +    terminal.input('/rewind');
    +    terminal.input('\r');
    +    await waitFor(() => plainTerminalOutput(terminal.output()).includes('first question'));
    +    terminal.input('\r');
    +    await waitFor(() => plainTerminalOutput(terminal.output()).includes('quotes:1'));
    +    terminal.input('resend this');
    +    terminal.input('\r');
    +    await waitFor(() => driver.submittedQuotes.length === 1);
    +
    +    // The admission fails with the Session unchanged: the quotes return to
    +    // the staging for the retry the feature promises (#5109 review).
    +    driver.hold(new Error('admission outcome unknown'));
    +    await waitFor(() =>
    +      plainTerminalOutput(terminal.output()).includes('admission outcome unknown'),
    +    );
    +    await waitFor(() => plainTerminalOutput(terminal.output()).includes('quotes:1'));
    +
    +    terminal.input('retry then');
    +    terminal.input('\r');
    +    await waitFor(() => driver.submittedQuotes.length === 2);
    +    assert.deepEqual(driver.submittedQuotes[1], [
    +      { text: 'a large pasted excerpt', label: 'earlier turn', sourceTurnId: 'turn-0' },
    +    ]);
    +
    +    exitMaka(terminal);
    +    await Promise.race([
    +      run,
    +      delay(CLOSE_BUDGET_MS).then(() => {
    +        throw new Error('TUI did not close during test cleanup');
    +      }),
    +    ]);
    +  });
    +
    +  test('restages quotes when a submit resolves without a receipt (outcome unknown)', async () => {
    +    const terminal = new FakeTerminal();
    +    const driver = new UnknownOutcomeSubmitDriver(
    +      [{ turnId: 'turn-1', label: 'first question' }],
    +      [storedUserMessage('user-1', 'turn-1', 'first question')],
    +    );
    +    const run = runMakaPiTui({
    +      title: 'Maka',
    +      driver,
    +      cwd: '/repo',
    +      model: 'claude-sonnet-4-5',
    +      connectionSlug: 'claude-subscription',
    +      permissionMode: 'ask',
    +      terminal,
    +    });
    +
    +    terminal.input('/rewind');
    +    terminal.input('\r');
    +    await waitFor(() => plainTerminalOutput(terminal.output()).includes('first question'));
    +    terminal.input('\r');
    +    await waitFor(() => plainTerminalOutput(terminal.output()).includes('quotes:1'));
    +    terminal.input('resend this');
    +    terminal.input('\r');
    +    await waitFor(() => driver.submittedQuotes.length === 1);
    +
    +    // The dispatch consumed the staging and the Host then resolved without a
    +    // receipt: the quotes must come back instead of vanishing silently, with
    +    // a notice naming the uncertainty (#5109 review).
    +    driver.resolveUnknown();
    +    await waitFor(() => plainTerminalOutput(terminal.output()).includes('Submit outcome unknown'));
    +
    +    terminal.input('retry then');
    +    terminal.input('\r');
    +    await waitFor(() => driver.submittedQuotes.length === 2);
    +    assert.deepEqual(driver.submittedQuotes[1], [
    +      { text: 'a large pasted excerpt', label: 'earlier turn', sourceTurnId: 'turn-0' },
    +    ]);
    +
    +    exitMaka(terminal);
    +    await Promise.race([
    +      run,
    +      delay(CLOSE_BUDGET_MS).then(() => {
    +        throw new Error('TUI did not close during test cleanup');
    +      }),
    +    ]);
    +  });
    +
    +  test('a newer rewind displaces an in-flight quote submit restage', async () => {
    +    const terminal = new FakeTerminal();
    +    const driver = new PerRewindQuotedDriver(
    +      [{ turnId: 'turn-1', label: 'first question' }],
    +      [storedUserMessage('user-1', 'turn-1', 'first question')],
    +    );
    +    const run = runMakaPiTui({
    +      title: 'Maka',
    +      driver,
    +      cwd: '/repo',
    +      model: 'claude-sonnet-4-5',
    +      connectionSlug: 'claude-subscription',
    +      permissionMode: 'ask',
    +      terminal,
    +    });
    +
    +    terminal.input('/rewind');
    +    terminal.input('\r');
    +    await waitFor(() => plainTerminalOutput(terminal.output()).includes('first question'));
    +    terminal.input('\r');
    +    await waitFor(() => plainTerminalOutput(terminal.output()).includes('quotes:1'));
    +    terminal.input('resend this');
    +    terminal.input('\r');
    +    await waitFor(() => driver.submittedQuotes.length === 1);
    +
    +    // A second rewind lands while the first submit's admission is still in
    +    // flight: its own quotes are the new staging (#5109 review). The picker
    +    // opens through runControl's async activity acquire, so wait for the
    +    // driver call before selecting — scrollback still shows the first
    +    // picker's frame, and text alone cannot tell the two openings apart.
    +    terminal.input('/rewind');
    +    terminal.input('\r');
    +    await waitFor(() => driver.pickerOpens === 2);
    +    terminal.input('\r');
    +    await waitFor(() => driver.rewound.length === 2);
    +    await waitFor(() => plainTerminalOutput(terminal.output()).includes('quotes:1'));
    +
    +    // The stale admission fails now: its restage must not overwrite the
    +    // newer rewind's staging.
    +    driver.hold(new Error('admission outcome unknown'));
    +    await waitFor(() =>
    +      plainTerminalOutput(terminal.output()).includes('admission outcome unknown'),
    +    );
    +
    +    terminal.input('follow-up');
    +    terminal.input('\r');
    +    await waitFor(() => driver.submittedQuotes.length === 2);
    +    assert.deepEqual(driver.submittedQuotes[1], [
    +      { text: 'excerpt from rewind 2', label: 'earlier turn', sourceTurnId: 'turn-0' },
    +    ]);
    +
    +    exitMaka(terminal);
    +    await Promise.race([
    +      run,
    +      delay(CLOSE_BUDGET_MS).then(() => {
    +        throw new Error('TUI did not close during test cleanup');
    +      }),
    +    ]);
    +  });
    +
    +  test('lets a quote-only rewind reach the submit path unchanged', async () => {
    +    const terminal = new FakeTerminal();
    +    const driver = new HeldSubmitQuotedDriver(
    +      [{ turnId: 'turn-1', label: 'first question' }],
    +      [storedUserMessage('user-1', 'turn-1', 'first question')],
    +    );
    +    const run = runMakaPiTui({
    +      title: 'Maka',
    +      driver,
    +      cwd: '/repo',
    +      model: 'claude-sonnet-4-5',
    +      connectionSlug: 'claude-subscription',
    +      permissionMode: 'ask',
    +      terminal,
    +    });
    +
    +    terminal.input('/rewind');
    +    terminal.input('\r');
    +    // The rewound prompt is empty and the quotes stage: they alone are the
    +    // replacement content, so Enter with nothing typed must submit them.
    +    await waitFor(() => plainTerminalOutput(terminal.output()).includes('first question'));
    +    terminal.input('\r');
    +    await waitFor(() => plainTerminalOutput(terminal.output()).includes('quotes:1'));
    +    terminal.input('\r');
    +    await waitFor(() => driver.submittedQuotes.length === 1);
    +    assert.deepEqual(driver.submittedQuotes[0], [
    +      { text: 'a large pasted excerpt', label: 'earlier turn', sourceTurnId: 'turn-0' },
    +    ]);
    +
    +    // After the explicit clear an empty draft is truly empty: no submit.
    +    // The submit consumed the staging, so the clear reports the truth —
    +    // there is nothing left to discard (#5109 review).
    +    terminal.input('/quotes clear');
    +    terminal.input('\r');
    +    await waitFor(() =>
    +      plainTerminalOutput(terminal.output()).includes('No restored quotes are staged'),
    +    );
    +    terminal.input('\r');
    +    await delay(200);
    +    assert.equal(driver.submittedQuotes.length, 1);
    +
    +    exitMaka(terminal);
    +    await Promise.race([
    +      run,
    +      delay(CLOSE_BUDGET_MS).then(() => {
    +        throw new Error('TUI did not close during test cleanup');
    +      }),
    +    ]);
    +  });
    +
    +  test('discards staged quotes only through the explicit /quotes clear', async () => {
    +    const terminal = new FakeTerminal();
    +    const driver = new QuotedRewindDriver(
    +      [{ turnId: 'turn-1', label: 'first question' }],
    +      [
    +        storedUserMessage('user-1', 'turn-1', 'first question'),
    +        storedAssistantMessage('assistant-1', 'turn-1', 'first answer'),
    +      ],
    +    );
    +    const run = runMakaPiTui({
    +      title: 'Maka',
    +      driver,
    +      cwd: '/repo',
    +      model: 'claude-sonnet-4-5',
    +      connectionSlug: 'claude-subscription',
    +      permissionMode: 'ask',
    +      terminal,
    +    });
    +
    +    terminal.input('/rewind');
    +    terminal.input('\r');
    +    await waitFor(() => plainTerminalOutput(terminal.output()).includes('first question'));
    +    terminal.input('\r');
    +    await waitFor(() => driver.rewound.length === 1);
    +    await waitFor(() => plainTerminalOutput(terminal.output()).includes('quotes:1'));
    +
    +    // Ctrl+C clears the refilled draft so /quotes is not appended to it.
    +    terminal.input('\x03');
    +    // Bare /quotes lists what is staged, including the quote body.
    +    terminal.input('/quotes');
    +    terminal.input('\r');
    +    await waitFor(() => plainTerminalOutput(terminal.output()).includes('a large pasted excerpt'));
    +
    +    // The explicit clear drops the staging; the next submit carries nothing.
    +    terminal.input('/quotes clear');
    +    terminal.input('\r');
    +    await waitFor(() =>
    +      plainTerminalOutput(terminal.output()).includes('Restored quotes discarded'),
    +    );
    +    terminal.input('plain');
    +    terminal.input('\r');
    +    await waitFor(() => driver.submittedQuotes.length === 1);
    +    assert.equal(driver.submittedQuotes[0], undefined);
    +
    +    // And bare /quotes on an empty staging says so.
    +    terminal.input('/quotes');
    +    terminal.input('\r');
    +    await waitFor(() =>
    +      plainTerminalOutput(terminal.output()).includes('No restored quotes are staged'),
    +    );
    +
    +    exitMaka(terminal);
    +    await Promise.race([
    +      run,
    +      delay(CLOSE_BUDGET_MS).then(() => {
    +        throw new Error('TUI did not close during test cleanup');
    +      }),
    +    ]);
    +  });
    +
    +  test('restages quotes when the Host blocks the replacement submit', async () => {
    +    const terminal = new FakeTerminal();
    +    const driver = new BlockedQuotedRewindDriver(
    +      {
    +        loaded: [],
    +        failed: [{ request: 'typo', reason: 'not_found' }],
    +        receipts: [],
    +      },
    +      [{ turnId: 'turn-1', label: 'first question' }],
    +    );
    +    const run = runMakaPiTui({
    +      title: 'Maka',
    +      driver,
    +      cwd: '/repo',
    +      model: 'claude-sonnet-4-5',
    +      connectionSlug: 'claude-subscription',
    +      permissionMode: 'ask',
    +      terminal,
    +    });
    +
    +    terminal.input('/rewind');
    +    terminal.input('\r');
    +    await waitFor(() => plainTerminalOutput(terminal.output()).includes('first question'));
    +    terminal.input('\r');
    +    await waitFor(() => plainTerminalOutput(terminal.output()).includes('quotes:1'));
    +    terminal.input('resend this');
    +    terminal.input('\r');
    +    await waitFor(() => driver.submittedQuotes.length === 1);
    +
    +    // The Host refuses the dispatch (blocked disposition): the quotes return
    +    // to the staging for the retry, exactly as a failed admission would.
    +    await waitFor(() => plainTerminalOutput(terminal.output()).includes('Could not load skills'));
    +    terminal.input('retry then');
    +    terminal.input('\r');
    +    await waitFor(() => driver.submittedQuotes.length === 2);
    +    assert.deepEqual(driver.submittedQuotes[1], [
    +      { text: 'a large pasted excerpt', label: 'earlier turn', sourceTurnId: 'turn-0' },
    +    ]);
    +
    +    exitMaka(terminal);
    +    await Promise.race([
    +      run,
    +      delay(CLOSE_BUDGET_MS).then(() => {
    +        throw new Error('TUI did not close during test cleanup');
    +      }),
    +    ]);
    +  });
    +
    +  test('renders and submits multiple staged quotes in rewind order', async () => {
    +    const terminal = new FakeTerminal();
    +    // Two quotes per rewind: the count, the listing, and the submit must all
    +    // carry the rewind's order.
    +    const driver = new TwoQuoteRewindDriver([{ turnId: 'turn-1', label: 'first question' }]);
    +    const run = runMakaPiTui({
    +      title: 'Maka',
    +      driver,
    +      cwd: '/repo',
    +      model: 'claude-sonnet-4-5',
    +      connectionSlug: 'claude-subscription',
    +      permissionMode: 'ask',
    +      terminal,
    +    });
    +
    +    terminal.input('/rewind');
    +    terminal.input('\r');
    +    await waitFor(() => plainTerminalOutput(terminal.output()).includes('first question'));
    +    terminal.input('\r');
    +    await waitFor(() => plainTerminalOutput(terminal.output()).includes('quotes:2'));
    +
    +    // /quotes lists both, in rewind order. The rewind refilled the editor
    +    // with the discarded prompt; Ctrl+C clears it so /quotes is not appended
    +    // to it.
    +    terminal.input('\x03');
    +    terminal.input('/quotes');
    +    terminal.input('\r');
    +    await waitFor(() => plainTerminalOutput(terminal.output()).includes('Staged quotes:'));
    +    const transcript = plainTerminalOutput(terminal.output());
    +    const firstAt = transcript.indexOf('first excerpt');
    +    const secondAt = transcript.indexOf('second excerpt');
    +    assert.ok(firstAt !== -1 && secondAt > firstAt, 'listing keeps rewind order');
    +
    +    // The replacement submit carries both refs, in the same order.
    +    terminal.input('resend with both');
    +    terminal.input('\r');
    +    await waitFor(() => driver.submittedQuotes.length === 1);
    +    assert.deepEqual(driver.submittedQuotes[0], [
    +      { text: 'first excerpt', label: 'earlier turn', sourceTurnId: 'turn-0' },
    +      { text: 'second excerpt', label: 'later turn', sourceTurnId: 'turn-0' },
    +    ]);
    +
    +    exitMaka(terminal);
    +    await Promise.race([
    +      run,
    +      delay(CLOSE_BUDGET_MS).then(() => {
    +        throw new Error('TUI did not close during test cleanup');
    +      }),
    +    ]);
    +  });
    +
    +  test('lists staged quotes mid-turn through the local disposition', async () => {
    +    const terminal = new FakeTerminal();
    +    const driver = new MidTurnQuotesDriver([{ turnId: 'turn-1', label: 'first question' }]);
    +    const run = runMakaPiTui({
    +      title: 'Maka',
    +      driver,
    +      cwd: '/repo',
    +      model: 'claude-sonnet-4-5',
    +      connectionSlug: 'claude-subscription',
    +      permissionMode: 'ask',
    +      terminal,
    +    });
    +
    +    terminal.input('/rewind');
    +    terminal.input('\r');
    +    await waitFor(() => plainTerminalOutput(terminal.output()).includes('first question'));
    +    terminal.input('\r');
    +    await waitFor(() => plainTerminalOutput(terminal.output()).includes('quotes:1'));
    +
    +    // A running Turn claims busy; /quotes is composer-side staging and must
    +    // still route through the local mid-turn disposition.
    +    driver.startBlockingTurn();
    +    await waitFor(() => terminal.progressStates.at(-1) === true);
    +    terminal.input('/quotes');
    +    terminal.input('\r');
    +    await waitFor(() => plainTerminalOutput(terminal.output()).includes('a large pasted excerpt'));
    +    assert.ok(
    +      plainTerminalOutput(terminal.output()).includes('Staged quotes:'),
    +      'the mid-turn listing renders the staged quotes',
    +    );
    +
    +    driver.turnGate.resolve();
    +    await waitFor(() => terminal.progressStates.at(-1) === false);
    +
    +    exitMaka(terminal);
    +    await Promise.race([
    +      run,
    +      delay(CLOSE_BUDGET_MS).then(() => {
    +        throw new Error('TUI did not close during test cleanup');
    +      }),
    +    ]);
    +  });
    +
    +  test('restages a steered quote submit when it is retracted mid-turn', async () => {
    +    const terminal = new FakeTerminal();
    +    const driver = new RetractingQuotesDriver([{ turnId: 'turn-1', label: 'first question' }]);
    +    const run = runMakaPiTui({
    +      title: 'Maka',
    +      driver,
    +      cwd: '/repo',
    +      model: 'claude-sonnet-4-5',
    +      connectionSlug: 'claude-subscription',
    +      permissionMode: 'ask',
    +      terminal,
    +    });
    +
    +    terminal.input('/rewind');
    +    terminal.input('\r');
    +    await waitFor(() => plainTerminalOutput(terminal.output()).includes('first question'));
    +    terminal.input('\r');
    +    await waitFor(() => plainTerminalOutput(terminal.output()).includes('quotes:1'));
    +
    +    // The running Turn turns the submit into a steering message carrying the
    +    // staged quotes; the staging clears as it dispatches.
    +    driver.startBlockingTurn();
    +    await waitFor(() => terminal.progressStates.at(-1) === true);
    +    terminal.input('queued resend');
    +    terminal.input('\r');
    +    await waitFor(() => driver.submittedQuotes.length === 1);
    +    assert.deepEqual(driver.submittedQuotes[0], [
    +      { text: 'a large pasted excerpt', label: 'earlier turn', sourceTurnId: 'turn-0' },
    +    ]);
    +
    +    // Alt+Up takes the message back. The Host's queue.retract returns the
    +    // full MessageContent, so the quotes ride the retraction — and they must
    +    // land back in the staging instead of vanishing with the queue row
    +    // (#5109 review, third round).
    +    terminal.input('\x1b[1;3A'); // Alt+Up
    +    await waitFor(() => driver.retractCalls === 1);
    +    await waitFor(() => plainTerminalOutput(terminal.output()).includes('quotes:1'));
    +
    +    // The retry carries them again.
    +    terminal.input('retry then');
    +    terminal.input('\r');
    +    await waitFor(() => driver.submittedQuotes.length === 2);
    +    assert.deepEqual(driver.submittedQuotes[1], [
    +      { text: 'a large pasted excerpt', label: 'earlier turn', sourceTurnId: 'turn-0' },
    +    ]);
    +
    +    driver.turnGate.resolve();
    +    await waitFor(() => terminal.progressStates.at(-1) === false);
    +
    +    exitMaka(terminal);
    +    await Promise.race([
    +      run,
    +      delay(CLOSE_BUDGET_MS).then(() => {
    +        throw new Error('TUI did not close during test cleanup');
    +      }),
    +    ]);
    +  });
    +
    +  test('restages the quoted message among several retracted queue entries', async () => {
    +    const terminal = new FakeTerminal();
    +    const driver = new RetractingQuotesDriver([{ turnId: 'turn-1', label: 'first question' }]);
    +    const run = runMakaPiTui({
    +      title: 'Maka',
    +      driver,
    +      cwd: '/repo',
    +      model: 'claude-sonnet-4-5',
    +      connectionSlug: 'claude-subscription',
    +      permissionMode: 'ask',
    +      terminal,
    +    });
    +
    +    terminal.input('/rewind');
    +    terminal.input('\r');
    +    await waitFor(() => plainTerminalOutput(terminal.output()).includes('first question'));
    +    terminal.input('\r');
    +    await waitFor(() => plainTerminalOutput(terminal.output()).includes('quotes:1'));
    +
    +    driver.startBlockingTurn();
    +    await waitFor(() => terminal.progressStates.at(-1) === true);
    +    // One quoted steering message and one plain queued follow-up.
    +    terminal.input('quoted resend');
    +    terminal.input('\r');
    +    await waitFor(() => driver.submittedQuotes.length === 1);
    +    await waitFor(() => driver.queuedRows.length === 1);
    +    terminal.input('plain follow-up');
    +    terminal.input('\r');
    +    await waitFor(() => driver.submittedQuotes.length === 2);
    +    assert.equal(driver.submittedQuotes[1], undefined);
    +    await waitFor(() => driver.queuedRows.length === 2);
    +
    +    terminal.input('\x1b[1;3A'); // Alt+Up retracts both.
    +    await waitFor(() => driver.retractCalls === 1);
    +    // The quotes survive a multi-message retraction; the texts are both back.
    +    await waitFor(() => plainTerminalOutput(terminal.output()).includes('quotes:1'));
    +    await waitFor(() => {
    +      const screen = plainTerminalOutput(terminal.screenOutput());
    +      return screen.includes('quoted resend') && screen.includes('plain follow-up');
    +    });
    +
    +    driver.turnGate.resolve();
    +    await waitFor(() => terminal.progressStates.at(-1) === false);
    +
    +    exitMaka(terminal);
    +    await Promise.race([
    +      run,
    +      delay(CLOSE_BUDGET_MS).then(() => {
    +        throw new Error('TUI did not close during test cleanup');
    +      }),
    +    ]);
    +  });
    +
    +  test('does not retract the switched-to queue when enqueues settle after a switch', async () => {
    +    const terminal = new FakeTerminal();
    +    const driver = new RetractingQuotesDriver([{ turnId: 'turn-1', label: 'first question' }]);
    +    const run = runMakaPiTui({
    +      title: 'Maka',
    +      driver,
    +      cwd: '/repo',
    +      model: 'claude-sonnet-4-5',
    +      connectionSlug: 'claude-subscription',
    +      permissionMode: 'ask',
    +      terminal,
    +    });
    +
    +    terminal.input('/rewind');
    +    terminal.input('\r');
    +    await waitFor(() => plainTerminalOutput(terminal.output()).includes('first question'));
    +    terminal.input('\r');
    +    await waitFor(() => plainTerminalOutput(terminal.output()).includes('quotes:1'));
    +
    +    driver.startBlockingTurn();
    +    await waitFor(() => terminal.progressStates.at(-1) === true);
    +    terminal.input('queued resend');
    +    terminal.input('\r');
    +    await waitFor(() => driver.submittedQuotes.length === 1);
    +
    +    // Park a second enqueue inside the driver, then Alt+Up: the runner must
    +    // wait for that enqueue, notice the session moved underneath it, and drop
    +    // the retraction *before* calling retractQueued — otherwise the Host call
    +    // retracts the switched-to session's queue and the mismatch fence then
    +    // discards those messages silently (#5109 review).
    +    driver.enqueueGate = deferred<void>();
    +    terminal.input('second queued');
    +    terminal.input('\r');
    +    driver.switchSession('session-other');

    P3: This test never sends Alt+Up (terminal.input("\x1b[1;3A")). It switches sessions and asserts retractCalls === 0 without ever starting retractQueuedMessages(), so the test also passes with the old implementation that retracted the new session queue after settlePendingEnqueues(). Trigger Alt+Up while enqueueGate is held, then switch sessions before resolving the gate; assert that no retract request reaches the new session. A same-head test run currently passes 2/2, but this case does not distinguish the reported P1.

    hqhq1025 hqhq1025 commented on Sep 27, 2026 23:13 UTC
    Reviewer

    I reviewed the current head against the two previously reported cross-session retraction races. Both production paths now check the originating session after pending enqueues settle and again after the retraction response (packages/cli/src/pi-tui-runner.ts:1317-1330,1544-1553). The interrupt no longer calls stop() after a session switch. I did not find a remaining substantiated production P0-P2 in this delta. One P3 test gap is noted inline. Local Node 24 clean install, build:test, both new focused tests, and diff-check passed. This is not merge-ready: fresh main 542f04a4 conflicts in packages/cli/src/__tests__/runtime-host-session-driver.test.ts, and no checks are reported for this head. I did not run a real Runtime Host/TUI switch race or the full test suite.

    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.

    hqhq1025 hqhq1025 commented on code on Sep 28, 2026 01:09 UTC
    Code Review
    packages/cli/src/__tests__/pi-tui-runner.test.ts:1
    @@ -7602,6 +7604,779 @@ Slug openai-work<cursor>
         ]);
       });
     
    +  test('stages a rewound turn quotes into the replacement submit', async () => {
    +    const terminal = new FakeTerminal();
    +    const driver = new QuotedRewindDriver(
    +      [{ turnId: 'turn-1', label: 'first question' }],
    +      [
    +        storedUserMessage('user-1', 'turn-1', 'first question'),
    +        storedAssistantMessage('assistant-1', 'turn-1', 'first answer'),
    +      ],
    +    );
    +    const run = runMakaPiTui({
    +      title: 'Maka',
    +      driver,
    +      cwd: '/repo',
    +      model: 'claude-sonnet-4-5',
    +      connectionSlug: 'claude-subscription',
    +      permissionMode: 'ask',
    +      terminal,
    +    });
    +
    +    terminal.input('/rewind');
    +    terminal.input('\r');
    +    await waitFor(() => plainTerminalOutput(terminal.output()).includes('first question'));
    +    terminal.input('\r');
    +    await waitFor(() => driver.rewound.length === 1);
    +    // The restored quotes are visible while staging is live: the rewind
    +    // notice names them and the status line carries a quotes:<n> segment.
    +    await waitFor(() => plainTerminalOutput(terminal.output()).includes('quoted context'));
    +    await waitFor(() => plainTerminalOutput(terminal.output()).includes('quotes:1'));
    +
    +    // The replacement submit carries the staged QuoteRefs verbatim.
    +    terminal.input('answer with this context');
    +    terminal.input('\r');
    +    await waitFor(() => driver.submittedQuotes.length === 1);
    +    assert.deepEqual(driver.submittedQuotes[0], [
    +      { text: 'a large pasted excerpt', label: 'earlier turn', sourceTurnId: 'turn-0' },
    +    ]);
    +    // Staging is consumed by the submit it rode on.
    +    terminal.input('plain follow-up');
    +    terminal.input('\r');
    +    await waitFor(() => driver.submittedQuotes.length === 2);
    +    assert.equal(driver.submittedQuotes[1], undefined);
    +
    +    exitMaka(terminal);
    +    await Promise.race([
    +      run,
    +      delay(CLOSE_BUDGET_MS).then(() => {
    +        throw new Error('TUI did not close during test cleanup');
    +      }),
    +    ]);
    +  });
    +
    +  test('restores a failed quote submit only to its originating session', async () => {
    +    const terminal = new FakeTerminal();
    +    const driver = new HeldSubmitQuotedDriver(
    +      [{ turnId: 'turn-1', label: 'first question' }],
    +      [storedUserMessage('user-1', 'turn-1', 'first question')],
    +    );
    +    const run = runMakaPiTui({
    +      title: 'Maka',
    +      driver,
    +      cwd: '/repo',
    +      model: 'claude-sonnet-4-5',
    +      connectionSlug: 'claude-subscription',
    +      permissionMode: 'ask',
    +      terminal,
    +    });
    +
    +    terminal.input('/rewind');
    +    terminal.input('\r');
    +    await waitFor(() => plainTerminalOutput(terminal.output()).includes('first question'));
    +    terminal.input('\r');
    +    await waitFor(() => plainTerminalOutput(terminal.output()).includes('quotes:1'));
    +    terminal.input('resend this');
    +    terminal.input('\r');
    +    await waitFor(() => driver.submittedQuotes.length === 1);
    +
    +    // A Session switch lands while the admission is still pending.
    +    driver.switchSession('session-other');
    +    driver.hold(new Error('admission outcome unknown'));
    +    await waitFor(() =>
    +      plainTerminalOutput(terminal.output()).includes('admission outcome unknown'),
    +    );
    +
    +    // The next message in the new Session must not carry the old quotes.
    +    terminal.input('unrelated follow-up');
    +    terminal.input('\r');
    +    await waitFor(() => driver.submittedQuotes.length === 2);
    +    assert.equal(driver.submittedQuotes[1], undefined);
    +
    +    exitMaka(terminal);
    +    await Promise.race([
    +      run,
    +      delay(CLOSE_BUDGET_MS).then(() => {
    +        throw new Error('TUI did not close during test cleanup');
    +      }),
    +    ]);
    +  });
    +
    +  test('restages a failed quote submit back onto the same session', async () => {
    +    const terminal = new FakeTerminal();
    +    const driver = new HeldSubmitQuotedDriver(
    +      [{ turnId: 'turn-1', label: 'first question' }],
    +      [storedUserMessage('user-1', 'turn-1', 'first question')],
    +    );
    +    const run = runMakaPiTui({
    +      title: 'Maka',
    +      driver,
    +      cwd: '/repo',
    +      model: 'claude-sonnet-4-5',
    +      connectionSlug: 'claude-subscription',
    +      permissionMode: 'ask',
    +      terminal,
    +    });
    +
    +    terminal.input('/rewind');
    +    terminal.input('\r');
    +    await waitFor(() => plainTerminalOutput(terminal.output()).includes('first question'));
    +    terminal.input('\r');
    +    await waitFor(() => plainTerminalOutput(terminal.output()).includes('quotes:1'));
    +    terminal.input('resend this');
    +    terminal.input('\r');
    +    await waitFor(() => driver.submittedQuotes.length === 1);
    +
    +    // The admission fails with the Session unchanged: the quotes return to
    +    // the staging for the retry the feature promises (#5109 review).
    +    driver.hold(new Error('admission outcome unknown'));
    +    await waitFor(() =>
    +      plainTerminalOutput(terminal.output()).includes('admission outcome unknown'),
    +    );
    +    await waitFor(() => plainTerminalOutput(terminal.output()).includes('quotes:1'));
    +
    +    terminal.input('retry then');
    +    terminal.input('\r');
    +    await waitFor(() => driver.submittedQuotes.length === 2);
    +    assert.deepEqual(driver.submittedQuotes[1], [
    +      { text: 'a large pasted excerpt', label: 'earlier turn', sourceTurnId: 'turn-0' },
    +    ]);
    +
    +    exitMaka(terminal);
    +    await Promise.race([
    +      run,
    +      delay(CLOSE_BUDGET_MS).then(() => {
    +        throw new Error('TUI did not close during test cleanup');
    +      }),
    +    ]);
    +  });
    +
    +  test('restages quotes when a submit resolves without a receipt (outcome unknown)', async () => {
    +    const terminal = new FakeTerminal();
    +    const driver = new UnknownOutcomeSubmitDriver(
    +      [{ turnId: 'turn-1', label: 'first question' }],
    +      [storedUserMessage('user-1', 'turn-1', 'first question')],
    +    );
    +    const run = runMakaPiTui({
    +      title: 'Maka',
    +      driver,
    +      cwd: '/repo',
    +      model: 'claude-sonnet-4-5',
    +      connectionSlug: 'claude-subscription',
    +      permissionMode: 'ask',
    +      terminal,
    +    });
    +
    +    terminal.input('/rewind');
    +    terminal.input('\r');
    +    await waitFor(() => plainTerminalOutput(terminal.output()).includes('first question'));
    +    terminal.input('\r');
    +    await waitFor(() => plainTerminalOutput(terminal.output()).includes('quotes:1'));
    +    terminal.input('resend this');
    +    terminal.input('\r');
    +    await waitFor(() => driver.submittedQuotes.length === 1);
    +
    +    // The dispatch consumed the staging and the Host then resolved without a
    +    // receipt: the quotes must come back instead of vanishing silently, with
    +    // a notice naming the uncertainty (#5109 review).
    +    driver.resolveUnknown();
    +    await waitFor(() => plainTerminalOutput(terminal.output()).includes('Submit outcome unknown'));
    +
    +    terminal.input('retry then');
    +    terminal.input('\r');
    +    await waitFor(() => driver.submittedQuotes.length === 2);
    +    assert.deepEqual(driver.submittedQuotes[1], [
    +      { text: 'a large pasted excerpt', label: 'earlier turn', sourceTurnId: 'turn-0' },
    +    ]);
    +
    +    exitMaka(terminal);
    +    await Promise.race([
    +      run,
    +      delay(CLOSE_BUDGET_MS).then(() => {
    +        throw new Error('TUI did not close during test cleanup');
    +      }),
    +    ]);
    +  });
    +
    +  test('a newer rewind displaces an in-flight quote submit restage', async () => {
    +    const terminal = new FakeTerminal();
    +    const driver = new PerRewindQuotedDriver(
    +      [{ turnId: 'turn-1', label: 'first question' }],
    +      [storedUserMessage('user-1', 'turn-1', 'first question')],
    +    );
    +    const run = runMakaPiTui({
    +      title: 'Maka',
    +      driver,
    +      cwd: '/repo',
    +      model: 'claude-sonnet-4-5',
    +      connectionSlug: 'claude-subscription',
    +      permissionMode: 'ask',
    +      terminal,
    +    });
    +
    +    terminal.input('/rewind');
    +    terminal.input('\r');
    +    await waitFor(() => plainTerminalOutput(terminal.output()).includes('first question'));
    +    terminal.input('\r');
    +    await waitFor(() => plainTerminalOutput(terminal.output()).includes('quotes:1'));
    +    terminal.input('resend this');
    +    terminal.input('\r');
    +    await waitFor(() => driver.submittedQuotes.length === 1);
    +
    +    // A second rewind lands while the first submit's admission is still in
    +    // flight: its own quotes are the new staging (#5109 review). The picker
    +    // opens through runControl's async activity acquire, so wait for the
    +    // driver call before selecting — scrollback still shows the first
    +    // picker's frame, and text alone cannot tell the two openings apart.
    +    terminal.input('/rewind');
    +    terminal.input('\r');
    +    await waitFor(() => driver.pickerOpens === 2);
    +    terminal.input('\r');
    +    await waitFor(() => driver.rewound.length === 2);
    +    await waitFor(() => plainTerminalOutput(terminal.output()).includes('quotes:1'));
    +
    +    // The stale admission fails now: its restage must not overwrite the
    +    // newer rewind's staging.
    +    driver.hold(new Error('admission outcome unknown'));
    +    await waitFor(() =>
    +      plainTerminalOutput(terminal.output()).includes('admission outcome unknown'),
    +    );
    +
    +    terminal.input('follow-up');
    +    terminal.input('\r');
    +    await waitFor(() => driver.submittedQuotes.length === 2);
    +    assert.deepEqual(driver.submittedQuotes[1], [
    +      { text: 'excerpt from rewind 2', label: 'earlier turn', sourceTurnId: 'turn-0' },
    +    ]);
    +
    +    exitMaka(terminal);
    +    await Promise.race([
    +      run,
    +      delay(CLOSE_BUDGET_MS).then(() => {
    +        throw new Error('TUI did not close during test cleanup');
    +      }),
    +    ]);
    +  });
    +
    +  test('lets a quote-only rewind reach the submit path unchanged', async () => {
    +    const terminal = new FakeTerminal();
    +    const driver = new HeldSubmitQuotedDriver(
    +      [{ turnId: 'turn-1', label: 'first question' }],
    +      [storedUserMessage('user-1', 'turn-1', 'first question')],
    +    );
    +    const run = runMakaPiTui({
    +      title: 'Maka',
    +      driver,
    +      cwd: '/repo',
    +      model: 'claude-sonnet-4-5',
    +      connectionSlug: 'claude-subscription',
    +      permissionMode: 'ask',
    +      terminal,
    +    });
    +
    +    terminal.input('/rewind');
    +    terminal.input('\r');
    +    // The rewound prompt is empty and the quotes stage: they alone are the
    +    // replacement content, so Enter with nothing typed must submit them.
    +    await waitFor(() => plainTerminalOutput(terminal.output()).includes('first question'));
    +    terminal.input('\r');
    +    await waitFor(() => plainTerminalOutput(terminal.output()).includes('quotes:1'));
    +    terminal.input('\r');
    +    await waitFor(() => driver.submittedQuotes.length === 1);
    +    assert.deepEqual(driver.submittedQuotes[0], [
    +      { text: 'a large pasted excerpt', label: 'earlier turn', sourceTurnId: 'turn-0' },
    +    ]);
    +
    +    // After the explicit clear an empty draft is truly empty: no submit.
    +    // The submit consumed the staging, so the clear reports the truth —
    +    // there is nothing left to discard (#5109 review).
    +    terminal.input('/quotes clear');
    +    terminal.input('\r');
    +    await waitFor(() =>
    +      plainTerminalOutput(terminal.output()).includes('No restored quotes are staged'),
    +    );
    +    terminal.input('\r');
    +    await delay(200);
    +    assert.equal(driver.submittedQuotes.length, 1);
    +
    +    exitMaka(terminal);
    +    await Promise.race([
    +      run,
    +      delay(CLOSE_BUDGET_MS).then(() => {
    +        throw new Error('TUI did not close during test cleanup');
    +      }),
    +    ]);
    +  });
    +
    +  test('discards staged quotes only through the explicit /quotes clear', async () => {
    +    const terminal = new FakeTerminal();
    +    const driver = new QuotedRewindDriver(
    +      [{ turnId: 'turn-1', label: 'first question' }],
    +      [
    +        storedUserMessage('user-1', 'turn-1', 'first question'),
    +        storedAssistantMessage('assistant-1', 'turn-1', 'first answer'),
    +      ],
    +    );
    +    const run = runMakaPiTui({
    +      title: 'Maka',
    +      driver,
    +      cwd: '/repo',
    +      model: 'claude-sonnet-4-5',
    +      connectionSlug: 'claude-subscription',
    +      permissionMode: 'ask',
    +      terminal,
    +    });
    +
    +    terminal.input('/rewind');
    +    terminal.input('\r');
    +    await waitFor(() => plainTerminalOutput(terminal.output()).includes('first question'));
    +    terminal.input('\r');
    +    await waitFor(() => driver.rewound.length === 1);
    +    await waitFor(() => plainTerminalOutput(terminal.output()).includes('quotes:1'));
    +
    +    // Ctrl+C clears the refilled draft so /quotes is not appended to it.
    +    terminal.input('\x03');
    +    // Bare /quotes lists what is staged, including the quote body.
    +    terminal.input('/quotes');
    +    terminal.input('\r');
    +    await waitFor(() => plainTerminalOutput(terminal.output()).includes('a large pasted excerpt'));
    +
    +    // The explicit clear drops the staging; the next submit carries nothing.
    +    terminal.input('/quotes clear');
    +    terminal.input('\r');
    +    await waitFor(() =>
    +      plainTerminalOutput(terminal.output()).includes('Restored quotes discarded'),
    +    );
    +    terminal.input('plain');
    +    terminal.input('\r');
    +    await waitFor(() => driver.submittedQuotes.length === 1);
    +    assert.equal(driver.submittedQuotes[0], undefined);
    +
    +    // And bare /quotes on an empty staging says so.
    +    terminal.input('/quotes');
    +    terminal.input('\r');
    +    await waitFor(() =>
    +      plainTerminalOutput(terminal.output()).includes('No restored quotes are staged'),
    +    );
    +
    +    exitMaka(terminal);
    +    await Promise.race([
    +      run,
    +      delay(CLOSE_BUDGET_MS).then(() => {
    +        throw new Error('TUI did not close during test cleanup');
    +      }),
    +    ]);
    +  });
    +
    +  test('restages quotes when the Host blocks the replacement submit', async () => {
    +    const terminal = new FakeTerminal();
    +    const driver = new BlockedQuotedRewindDriver(
    +      {
    +        loaded: [],
    +        failed: [{ request: 'typo', reason: 'not_found' }],
    +        receipts: [],
    +      },
    +      [{ turnId: 'turn-1', label: 'first question' }],
    +    );
    +    const run = runMakaPiTui({
    +      title: 'Maka',
    +      driver,
    +      cwd: '/repo',
    +      model: 'claude-sonnet-4-5',
    +      connectionSlug: 'claude-subscription',
    +      permissionMode: 'ask',
    +      terminal,
    +    });
    +
    +    terminal.input('/rewind');
    +    terminal.input('\r');
    +    await waitFor(() => plainTerminalOutput(terminal.output()).includes('first question'));
    +    terminal.input('\r');
    +    await waitFor(() => plainTerminalOutput(terminal.output()).includes('quotes:1'));
    +    terminal.input('resend this');
    +    terminal.input('\r');
    +    await waitFor(() => driver.submittedQuotes.length === 1);
    +
    +    // The Host refuses the dispatch (blocked disposition): the quotes return
    +    // to the staging for the retry, exactly as a failed admission would.
    +    await waitFor(() => plainTerminalOutput(terminal.output()).includes('Could not load skills'));
    +    terminal.input('retry then');
    +    terminal.input('\r');
    +    await waitFor(() => driver.submittedQuotes.length === 2);
    +    assert.deepEqual(driver.submittedQuotes[1], [
    +      { text: 'a large pasted excerpt', label: 'earlier turn', sourceTurnId: 'turn-0' },
    +    ]);
    +
    +    exitMaka(terminal);
    +    await Promise.race([
    +      run,
    +      delay(CLOSE_BUDGET_MS).then(() => {
    +        throw new Error('TUI did not close during test cleanup');
    +      }),
    +    ]);
    +  });
    +
    +  test('renders and submits multiple staged quotes in rewind order', async () => {
    +    const terminal = new FakeTerminal();
    +    // Two quotes per rewind: the count, the listing, and the submit must all
    +    // carry the rewind's order.
    +    const driver = new TwoQuoteRewindDriver([{ turnId: 'turn-1', label: 'first question' }]);
    +    const run = runMakaPiTui({
    +      title: 'Maka',
    +      driver,
    +      cwd: '/repo',
    +      model: 'claude-sonnet-4-5',
    +      connectionSlug: 'claude-subscription',
    +      permissionMode: 'ask',
    +      terminal,
    +    });
    +
    +    terminal.input('/rewind');
    +    terminal.input('\r');
    +    await waitFor(() => plainTerminalOutput(terminal.output()).includes('first question'));
    +    terminal.input('\r');
    +    await waitFor(() => plainTerminalOutput(terminal.output()).includes('quotes:2'));
    +
    +    // /quotes lists both, in rewind order. The rewind refilled the editor
    +    // with the discarded prompt; Ctrl+C clears it so /quotes is not appended
    +    // to it.
    +    terminal.input('\x03');
    +    terminal.input('/quotes');
    +    terminal.input('\r');
    +    await waitFor(() => plainTerminalOutput(terminal.output()).includes('Staged quotes:'));
    +    const transcript = plainTerminalOutput(terminal.output());
    +    const firstAt = transcript.indexOf('first excerpt');
    +    const secondAt = transcript.indexOf('second excerpt');
    +    assert.ok(firstAt !== -1 && secondAt > firstAt, 'listing keeps rewind order');
    +
    +    // The replacement submit carries both refs, in the same order.
    +    terminal.input('resend with both');
    +    terminal.input('\r');
    +    await waitFor(() => driver.submittedQuotes.length === 1);
    +    assert.deepEqual(driver.submittedQuotes[0], [
    +      { text: 'first excerpt', label: 'earlier turn', sourceTurnId: 'turn-0' },
    +      { text: 'second excerpt', label: 'later turn', sourceTurnId: 'turn-0' },
    +    ]);
    +
    +    exitMaka(terminal);
    +    await Promise.race([
    +      run,
    +      delay(CLOSE_BUDGET_MS).then(() => {
    +        throw new Error('TUI did not close during test cleanup');
    +      }),
    +    ]);
    +  });
    +
    +  test('lists staged quotes mid-turn through the local disposition', async () => {
    +    const terminal = new FakeTerminal();
    +    const driver = new MidTurnQuotesDriver([{ turnId: 'turn-1', label: 'first question' }]);
    +    const run = runMakaPiTui({
    +      title: 'Maka',
    +      driver,
    +      cwd: '/repo',
    +      model: 'claude-sonnet-4-5',
    +      connectionSlug: 'claude-subscription',
    +      permissionMode: 'ask',
    +      terminal,
    +    });
    +
    +    terminal.input('/rewind');
    +    terminal.input('\r');
    +    await waitFor(() => plainTerminalOutput(terminal.output()).includes('first question'));
    +    terminal.input('\r');
    +    await waitFor(() => plainTerminalOutput(terminal.output()).includes('quotes:1'));
    +
    +    // A running Turn claims busy; /quotes is composer-side staging and must
    +    // still route through the local mid-turn disposition.
    +    driver.startBlockingTurn();
    +    await waitFor(() => terminal.progressStates.at(-1) === true);
    +    terminal.input('/quotes');
    +    terminal.input('\r');
    +    await waitFor(() => plainTerminalOutput(terminal.output()).includes('a large pasted excerpt'));
    +    assert.ok(
    +      plainTerminalOutput(terminal.output()).includes('Staged quotes:'),
    +      'the mid-turn listing renders the staged quotes',
    +    );
    +
    +    driver.turnGate.resolve();
    +    await waitFor(() => terminal.progressStates.at(-1) === false);
    +
    +    exitMaka(terminal);
    +    await Promise.race([
    +      run,
    +      delay(CLOSE_BUDGET_MS).then(() => {
    +        throw new Error('TUI did not close during test cleanup');
    +      }),
    +    ]);
    +  });
    +
    +  test('restages a steered quote submit when it is retracted mid-turn', async () => {
    +    const terminal = new FakeTerminal();
    +    const driver = new RetractingQuotesDriver([{ turnId: 'turn-1', label: 'first question' }]);
    +    const run = runMakaPiTui({
    +      title: 'Maka',
    +      driver,
    +      cwd: '/repo',
    +      model: 'claude-sonnet-4-5',
    +      connectionSlug: 'claude-subscription',
    +      permissionMode: 'ask',
    +      terminal,
    +    });
    +
    +    terminal.input('/rewind');
    +    terminal.input('\r');
    +    await waitFor(() => plainTerminalOutput(terminal.output()).includes('first question'));
    +    terminal.input('\r');
    +    await waitFor(() => plainTerminalOutput(terminal.output()).includes('quotes:1'));
    +
    +    // The running Turn turns the submit into a steering message carrying the
    +    // staged quotes; the staging clears as it dispatches.
    +    driver.startBlockingTurn();
    +    await waitFor(() => terminal.progressStates.at(-1) === true);
    +    terminal.input('queued resend');
    +    terminal.input('\r');
    +    await waitFor(() => driver.submittedQuotes.length === 1);
    +    assert.deepEqual(driver.submittedQuotes[0], [
    +      { text: 'a large pasted excerpt', label: 'earlier turn', sourceTurnId: 'turn-0' },
    +    ]);
    +
    +    // Alt+Up takes the message back. The Host's queue.retract returns the
    +    // full MessageContent, so the quotes ride the retraction — and they must
    +    // land back in the staging instead of vanishing with the queue row
    +    // (#5109 review, third round).
    +    terminal.input('\x1b[1;3A'); // Alt+Up
    +    await waitFor(() => driver.retractCalls === 1);
    +    await waitFor(() => plainTerminalOutput(terminal.output()).includes('quotes:1'));
    +
    +    // The retry carries them again.
    +    terminal.input('retry then');
    +    terminal.input('\r');
    +    await waitFor(() => driver.submittedQuotes.length === 2);
    +    assert.deepEqual(driver.submittedQuotes[1], [
    +      { text: 'a large pasted excerpt', label: 'earlier turn', sourceTurnId: 'turn-0' },
    +    ]);
    +
    +    driver.turnGate.resolve();
    +    await waitFor(() => terminal.progressStates.at(-1) === false);
    +
    +    exitMaka(terminal);
    +    await Promise.race([
    +      run,
    +      delay(CLOSE_BUDGET_MS).then(() => {
    +        throw new Error('TUI did not close during test cleanup');
    +      }),
    +    ]);
    +  });
    +
    +  test('restages the quoted message among several retracted queue entries', async () => {
    +    const terminal = new FakeTerminal();
    +    const driver = new RetractingQuotesDriver([{ turnId: 'turn-1', label: 'first question' }]);
    +    const run = runMakaPiTui({
    +      title: 'Maka',
    +      driver,
    +      cwd: '/repo',
    +      model: 'claude-sonnet-4-5',
    +      connectionSlug: 'claude-subscription',
    +      permissionMode: 'ask',
    +      terminal,
    +    });
    +
    +    terminal.input('/rewind');
    +    terminal.input('\r');
    +    await waitFor(() => plainTerminalOutput(terminal.output()).includes('first question'));
    +    terminal.input('\r');
    +    await waitFor(() => plainTerminalOutput(terminal.output()).includes('quotes:1'));
    +
    +    driver.startBlockingTurn();
    +    await waitFor(() => terminal.progressStates.at(-1) === true);
    +    // One quoted steering message and one plain queued follow-up.
    +    terminal.input('quoted resend');
    +    terminal.input('\r');
    +    await waitFor(() => driver.submittedQuotes.length === 1);
    +    await waitFor(() => driver.queuedRows.length === 1);
    +    terminal.input('plain follow-up');
    +    terminal.input('\r');
    +    await waitFor(() => driver.submittedQuotes.length === 2);
    +    assert.equal(driver.submittedQuotes[1], undefined);
    +    await waitFor(() => driver.queuedRows.length === 2);
    +
    +    terminal.input('\x1b[1;3A'); // Alt+Up retracts both.
    +    await waitFor(() => driver.retractCalls === 1);
    +    // The quotes survive a multi-message retraction; the texts are both back.
    +    await waitFor(() => plainTerminalOutput(terminal.output()).includes('quotes:1'));
    +    await waitFor(() => {
    +      const screen = plainTerminalOutput(terminal.screenOutput());
    +      return screen.includes('quoted resend') && screen.includes('plain follow-up');
    +    });
    +
    +    driver.turnGate.resolve();
    +    await waitFor(() => terminal.progressStates.at(-1) === false);
    +
    +    exitMaka(terminal);
    +    await Promise.race([
    +      run,
    +      delay(CLOSE_BUDGET_MS).then(() => {
    +        throw new Error('TUI did not close during test cleanup');
    +      }),
    +    ]);
    +  });
    +
    +  test('does not retract the switched-to queue when enqueues settle after a switch', async () => {
    +    const terminal = new FakeTerminal();
    +    const driver = new RetractingQuotesDriver([{ turnId: 'turn-1', label: 'first question' }]);
    +    const run = runMakaPiTui({
    +      title: 'Maka',
    +      driver,
    +      cwd: '/repo',
    +      model: 'claude-sonnet-4-5',
    +      connectionSlug: 'claude-subscription',
    +      permissionMode: 'ask',
    +      terminal,
    +    });
    +
    +    terminal.input('/rewind');
    +    terminal.input('\r');
    +    await waitFor(() => plainTerminalOutput(terminal.output()).includes('first question'));
    +    terminal.input('\r');
    +    await waitFor(() => plainTerminalOutput(terminal.output()).includes('quotes:1'));
    +
    +    driver.startBlockingTurn();
    +    await waitFor(() => terminal.progressStates.at(-1) === true);
    +    terminal.input('queued resend');
    +    terminal.input('\r');
    +    await waitFor(() => driver.submittedQuotes.length === 1);
    +
    +    // Park a second enqueue inside the driver, then Alt+Up: the runner must
    +    // wait for that enqueue, notice the session moved underneath it, and drop
    +    // the retraction *before* calling retractQueued — otherwise the Host call
    +    // retracts the switched-to session's queue and the mismatch fence then
    +    // discards those messages silently (#5109 review).
    +    driver.enqueueGate = deferred<void>();
    +    terminal.input('second queued');
    +    terminal.input('\r');
    +    driver.switchSession('session-other');

    P3 (unchanged on this empty-tree head): This test does not emit Alt+Up while the enqueue is held, so it never invokes the retraction path it claims to cover. Switching sessions and asserting retractCalls === 0 passes under the old P1 implementation too. Send Alt+Up before switching, then resolve the enqueue gate and assert that the new session receives no queue.retract request.

    hqhq1025 hqhq1025 commented on Sep 28, 2026 01:09 UTC
    Reviewer

    This head is a tree-identical, empty CI-retrigger commit on top of d9aa90ee; the two earlier production P1 fixes remain present at packages/cli/src/pi-tui-runner.ts:1317-1330,1544-1553. The P3 regression-test gap remains (inline). My prior Node 24 clean build and two focused tests apply to the identical tree; I did not rerun an unchanged suite. This is not merge-ready: the PR still conflicts with fresh main 9e765abb in packages/cli/src/__tests__/runtime-host-session-driver.test.ts, and this head currently has no registered CI checks. Real Runtime Host/TUI switch races and the full test suite remain unverified.

    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.

    ggbdpq ggbdpq commented on Sep 28, 2026 02:18 UTC
    Author

    Merged latest main (f58f30203) and closed out the P3 — head is now 4e61b5fe5.

    Merge: one file conflicted (runtime-host-session-driver.test.ts) — the fake driver gained this PR's session.revision.create stub and main's turn.resume.start stub side by side; both kept.

    P3 (the regression test never retracts): fixed. The switched-queue case now sends Alt+Up () while the enqueue gate is still held, then switches sessions, then resolves the gate — so the retraction request is genuinely in flight across the switch, which is the interleaving the two P1 fences guard. Red-checked: with the post-settlePendingEnqueues() session fence neutered, the updated test fails (the retraction lands on the switched-to session); with the fence restored it passes. All six focused retraction tests pass on the rebuilt cli.

    On the 53 runtime-host-session-driver failures locally: all of them are Session cwd no longer exists: /tmp — main's newer tests in that file assume a POSIX /tmp. They come from the merge, fail identically on Windows regardless of this branch's changes, and are unaffected on Linux CI.

    Remaining from your review: nothing else on my side — the two production P1 fences are present at pi-tui-runner.ts:1317-1330,1544-1553 as you confirmed, and the P3 is now closed with a test that actually discriminates.

    hqhq1025 hqhq1025 commented on Sep 28, 2026 03:13 UTC
    Reviewer

    I reviewed this exact head after the main merge and regression-test update. The new test now sends Alt+Up while a pending enqueue is held, then switches sessions before releasing it (packages/cli/src/__tests__/pi-tui-runner.test.ts:8249-8264). It reaches the retraction path and would fail under the previous post-settle-unfenced implementation; the production fences and stop guard remain at packages/cli/src/pi-tui-runner.ts:1317-1330,1544-1553. I found no remaining substantiated P0-P3 in this reviewed delta. Local Node 24 clean install, build:test, three focused retraction/switch tests, and diff-check passed. The PR merges cleanly with current main 0fd75408, but it is not merge-ready: the current-head hosted test check failed after an approximately 898-second timeout in acp-goal-plan-child-process.test.js. That file is outside the nine-file effective PR diff, but I have not established whether the timeout is environmental; the required check remains red. I did not run the full suite or a real Runtime Host/TUI switch race.

    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.

    ggbdpq ggbdpq commented on Sep 28, 2026 03:21 UTC
    Author

    The test failure on the current head 4e61b5fe5 is not from this PR: it is the main-preexisting acp-goal-plan-child-process.test.js timeout (ACP client operation timed out after 15000ms on the AskUserQuestion step; the file then runs to the 900s harness timeout), now filed as #5777. Red starts at 0fd754083 (#5434's merge); parent ca1ac87ca is green. The failure signature on this head is identical to main's, and this PR's changes (TUI retraction staging and the session-driver test fixtures) do not touch the ACP child-process path.

    Astro-Han Astro-Han commented on code on Sep 28, 2026 03:24 UTC
    Code Review
    packages/cli/src/pi-tui-runner.ts:1
    @@ -1427,8 +1537,19 @@ export async function runMakaPiTui(input: MakaPiTuiInput): Promise<void> {
       // prepended to the current draft for re-editing.
       const retractQueuedMessages = () => {
         void (async () => {
    +      // Same session fence as the interrupt path: a mid-turn `/session` that
    +      // lands while enqueues or the retraction are in flight must neither
    +      // retract the new session's queue nor inherit the quotes or the text
    +      // of the session we left (#5109 review).
    +      const retractionSessionId = input.driver.getSessionId();
           await settlePendingEnqueues();
    -      const retracted = (await input.driver.retractQueued?.()) ?? { text: '', messageIds: [] };
    +      if (input.driver.getSessionId() !== retractionSessionId) return;
    +      const retracted = (await input.driver.retractQueued?.()) ?? {
    +        text: '',
    +        messageIds: [],
    +        quotes: [],
    +      };
    +      if (input.driver.getSessionId() !== retractionSessionId) return;

    P2: if the session changed during retractQueued(), the retraction already succeeded on the Host, so returning here silently drops the user's queued text and quotes. For example, Alt+↑ during a side-conversation toggle; retractQueuedMessages also has no detaching guard. Please guard on detaching before retracting, and restore or notify instead of discarding when this fence trips.

    Astro-Han Astro-Han commented on Sep 28, 2026 03:24 UTC
    Reviewer

    Independent second review of head 4e61b5fe (a different model lineage from the parallel review). No P0/P1. Both earlier P1s are fixed, and mutation testing confirms the new tests pin them:

  • Removing the pre-retract fence at pi-tui-runner.ts:1546 fails "does not retract the switched-to queue…".

  • Removing the pre-stop fence at :1325 fails "keeps the interrupt stop bound…".
  • The hosted CI failure is unrelated. The only failing test is acp-goal-plan-child-process.test.js ("submits and executes a Plan through the model, ACP, and real Host"), an ACP harness timeout. The same test fails on main in runs 36371168218 (0fd75408) and 36329671976 (fffc19fb), and the ACP path doesn't import the code changed here.

    P2: the fences can drop user input or a stop request silently (pi-tui-runner.ts:1552, :1325, :1319).

  • Alt+↑ during a side-conversation toggle. retractQueuedMessages has no detaching guard, so pressing Alt+↑ while the toggle (several RPCs) is in flight really retracts A's queue on the Host. When the switch completes, the post-retract fence (:1552) returns and discards the retracted text and quotes. They are now in neither A's queue nor any editor, and the user gets no notice. Before this PR they landed, misplaced but visible, in B's editor.

  • Esc Esc or Ctrl+C racing the toggle. The toggle key (:2170) doesn't check interruptRequested. A's queue is retracted and then dropped, stop() is skipped, and A keeps running. The user's stop request is silently lost.

  • A misleading test comment. "The switch owns stopping the old turn" doesn't hold: in Runtime Host mode a mid-turn switch only detaches (:2066-2070).
  • The windows are short, but the failure is silent loss of user input. Minimum fixes: add the detaching guard to retractQueuedMessages, make the toggle respect interruptRequested, and when a fence trips after a successful retract, restore the text and quotes (or notify) instead of discarding them.

    Structural note: the TUI fences on the current session between awaits, but the driver's retractQueued, stop and submitMessage bind to whatever session is current when they execute. submitMessage goes through a serial admission queue, so a message staged with A's quotes can be sent to B if the switch lands in between. Passing an expected session id into those driver calls, or refusing a switch while an interrupt or retract is in flight (as requestTurnInterrupt already does), would close this whole class.

    P3:

  • Test gaps. Removing the pre-retract interrupt check (:1319) survives the suite. Removing the clear on session switch (:2003) together with the session-key check (:707) also survives, because tests switch sessions by calling the fake driver directly rather than via /session, the side toggle or /resume. The driver's mapping of non-empty retracted quotes (runtime-host-session-driver.ts:627) is untested.

  • Retract merges quotes past the Host's cap. Retract flattens quotes from all queued messages, including other clients', into the staged set, which can exceed the 16-quote cap. Every subsequent submit is then rejected and re-staged until /quotes clear.

  • A session switch drops quotes without notice, including quotes that only exist because of a retract.

  • Quote-only submits have no transcript row until the canonical message arrives. The transient row (:1427) and the steering_message path (pi-transcript.ts:988) carry no quote count.

  • Failed or blocked submits re-stage quotes silently. The text isn't restored to the editor (:1462, :1496), so the quotes ride the next unrelated message.

  • Minor. "· N quotes" and "quotes:N" are hard-coded English, and joining retracted text leaves stray blank paragraphs for quote-only messages.
  • Verified: the three touched test files, 430/433 passing with 3 skipped, plus about 12 mutations.

    Not verified: the P2 timing against a real Host or terminal (reachability is from the code), multi-client end to end, and Windows.

    ---
    Automated review (Claude lineage) by the Qronos review line on behalf of @Astro-Han; key claims were checked against the code, but please verify before acting.

    ggbdpq ggbdpq commented on Sep 28, 2026 04:10 UTC
    Author

    All three minimum fixes from this review are in on head 3b27537b7:

  • detaching guard on retractQueuedMessages — mirrors the interrupt path's guard: a retract asked during the handoff is swallowed until the switch settles, so nothing strips the leaving session's queue mid-flight.

  • The toggle respects interruptRequested — Esc Esc / Ctrl+C converging with the toggle no longer retract-and-drop the queue while skipping the stop; the toggle is refused until the interrupt settles. This also closes the fence at :1325 from the source side, so that fence now only remains as depth.

  • A fence that trips after a successful retract reports instead of dropping — the Alt+Up landing fence now pushes an error notice naming what was taken back (queued messages and quotes) and saying the text could not be restored. It deliberately does not restage the quotes under the old session's key: applySwitchResult clears staging on every switch precisely because a silent resurrection on return would send context the user can no longer see (#5109 review retired that path), so the notice is the honest half of restore-or-notify.

  • The misleading test comment now says a mid-turn switch only detaches.
  • Tests: two new runner tests — a retract swallowed inside a gated mid-turn detach handoff, and a toggle refused while the interrupt's pre-stop retraction hangs on its gate — plus the existing switched-retraction regression now also asserts the notice. All three fail on the previous head and pass on this one. Runner suite 238/240 (the two failures are the preexisting SIGTERM exit tests on this host); driver suite 25/78 with all 53 failures in the preexisting POSIX /tmp fixture class (25 passes matches the recorded baseline, and the driver tests do not import the changed module). Biome and ASF headers clean.

    On the structural note (expected session ids into retractQueued/stop/submitMessage): agreed it closes the whole class, but it crosses the driver interface and every driver implementation, so it deserves its own change rather than riding this one — happy to open that follow-up.

    The P3 list stands as recorded; none of those items are addressed here.

    If the fresh test job turns red, it is the main-preexisting acp-goal-plan-child-process.test.js timeout tracked in #5777, not this change.

    ggbdpq ggbdpq commented on Sep 28, 2026 04:39 UTC
    Author

    Follow-up on the intermediate red: the first push (3b27537b7) tripped check:tui-copy — the fence-tripped notice's visible literals were not registered in the copy inventory, a gate this change's local matrix missed. Both literals are allowlisted in a72756ce7 (same inventory treatment as every other runner notice), the gate's own tests stay 7/7, and the fresh test job on that head is green. Current head: a72756ce7.

    hqhq1025 hqhq1025 commented on code on Sep 28, 2026 05:12 UTC
    Code Review
    packages/cli/src/pi-tui-runner.ts:1
    @@ -1426,9 +1536,45 @@ export async function runMakaPiTui(input: MakaPiTuiInput): Promise<void> {
       // Alt+↑: take back every queued message from the Runtime Host, joined and
       // prepended to the current draft for re-editing.
       const retractQueuedMessages = () => {
    +    // Mirror the interrupt path's guard: a detach in flight re-keys the driver
    +    // mid-retraction, so the retraction would strip the queue of the session
    +    // the user is leaving and the landing fence would drop what came back.
    +    // Swallow until the handoff settles.
    +    if (detaching) return;
         void (async () => {
    +      // Same session fence as the interrupt path: a mid-turn `/session` that
    +      // lands while enqueues or the retraction are in flight must neither
    +      // retract the new session's queue nor inherit the quotes or the text
    +      // of the session we left (#5109 review).
    +      const retractionSessionId = input.driver.getSessionId();
           await settlePendingEnqueues();
    -      const retracted = (await input.driver.retractQueued?.()) ?? { text: '', messageIds: [] };
    +      if (input.driver.getSessionId() !== retractionSessionId) return;
    +      const retracted = (await input.driver.retractQueued?.()) ?? {
    +        text: '',
    +        messageIds: [],
    +        quotes: [],
    +      };
    +      if (input.driver.getSessionId() !== retractionSessionId) {
    +        // The retraction succeeded on the Host, but the switch landed first:
    +        // the content belongs to the session we left, and neither the editor
    +        // nor the quote staging of the one we landed on may take it. Restoring
    +        // it anywhere would need a per-session draft handoff, so say what
    +        // happened instead of dropping the user's input without a trace
    +        // (#5109 review).
    +        const counts = [
    +          retracted.messageIds.length > 0 ? `${retracted.messageIds.length} queued message(s)` : '',
    +          retracted.quotes.length > 0 ? `${retracted.quotes.length} quote(s)` : '',
    +        ]
    +          .filter(Boolean)
    +          .join(' and ');
    +        state.entries.push({
    +          kind: 'notice',
    +          level: 'error',
    +          text: `The session switched while the retraction was in flight${counts ? `: ${counts} came back` : ''}, but the retracted text could not be restored to the editor.`,

    P2: Keep the retracted content recoverable when the switch wins. retractQueued() has already removed the queued message from the Host, but this branch reports only counts and discards retracted.text and retracted.quotes. Switching back cannot restore the queued draft. The new test checks that a loss notice appears, not that the data survives. Serialize navigation behind an in-flight retraction, or retain the payload in a draft owned by the original session; a notice alone does not fix the data loss.

    hqhq1025 hqhq1025 commented on Sep 28, 2026 05:12 UTC
    Reviewer

    The new handoff guard and interrupt-toggle gate cover the two entry-order races, and the focused tests pass. However, the successful-retraction/late-switch path still loses the user’s retracted content (inline finding). I cannot treat a loss notification as recovery. The current hosted test is green and the fresh-main merge tree is clean, but this P2 blocks readiness. I did not run a real Host/TUI side-conversation race or the full local suite.

    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.

    Astro-Han Astro-Han commented on code on Sep 28, 2026 05:16 UTC
    Code Review
    packages/cli/src/pi-tui-runner.ts:1
    @@ -2040,7 +2192,11 @@ export async function runMakaPiTui(input: MakaPiTuiInput): Promise<void> {
     
       const toggleSideConversation = async (): Promise<void> => {
         const pair = sideConversation;
    -    if (!pair || detaching || (busy && !turnRunning)) return;
    +    // An interrupt converging (stop + pre-stop retraction in flight) owns this
    +    // session until it settles: toggling away mid-handoff would drop the
    +    // retracted queue on the fence and leave the stop request aimed at a
    +    // session the TUI no longer watches (#5109 review).
    +    if (!pair || detaching || interruptRequested || (busy && !turnRunning)) return;

    P2: this gate covers detaching and interruptRequested but not a retraction that is still in flight. If Alt+↑ is followed by this toggle, the retracted text lands in the editor and is then overwritten by the draft that switchView saved earlier, with no notice. Consider a retracting flag checked here and in the mid-turn /session branch.

    Astro-Han Astro-Han commented on Sep 28, 2026 05:16 UTC
    Reviewer

    A second, independent review of head a72756ce (Claude lineage). It adds to the hqhq1025 review 5334255733 and does not repeat its findings.

    What's fixed. Mutation checks confirm three fixes; for each, removing the change makes its new test fail:

  • the detaching entry guard (pi-tui-runner.ts:1543);

  • the late-landing notice (:1557-1577);

  • the interrupt-toggle gate (:2199), which also covers the earlier Esc Esc sub-issue.
  • P2: a retraction in flight, followed by a side switch, loses the queued text without any notice. We reproduced this with a temporary test. It is a different path from the one in the review above:
    1. Alt+↑ starts a retraction.
    2. The side toggle at :2199 doesn't check whether a retraction is in flight, so the switch proceeds.
    3. The driver changes its session ID only at the end of switchSession (runtime-host-session-driver.ts:831). Both fences at :1548-1579 therefore pass, and the retracted text goes into the editor.
    4. switchView (:2202-2213) then overwrites the editor with the draft it saved before the retraction landed, and applySwitchResult clears the quotes.

    The messages are gone from the Host queue, they're in neither draft, and no notice appears. A fix: add a retracting flag and have the toggle and the mid-turn /session branch refuse or wait while it is set, as they do for interruptRequested.

    P3:

  • An empty retraction that lands after a switch still shows the error notice (:1557-1577). It should return quietly when there are no messages and no quotes.

  • As the review above says, the notice gives only counts, so the text can't be recovered. Carrying the text in the notice, or keeping a per-session draft, would fix this.
  • Tests: pi-tui-runner 240/240 and runtime-host-session-driver 78/78 pass, and the TUI copy check passes. Not run: the full suite, and a real Host/TUI race.

    ---
    Automated review (Claude lineage) by the Qronos review line on behalf of @Astro-Han; please verify before acting.

    ggbdpq ggbdpq commented on Sep 28, 2026 05:54 UTC
    Author

    Both findings are addressed on head 5cee83425:

  • P2 (retraction in flight, then a switch loses the text): a retracting flag now gates the side toggle and the mid-turn /session branch, as interruptRequested already gated the toggle — the switch is refused until the retraction settles, and since the driver re-keys only at the end of switchSession, refusing is the only ordering that keeps the fences meaningful. The new test drives exactly the reproduced sequence: retraction hung on a gate, toggle refused (side-1 unchanged), gate released, the retracted text lands in the editor, and the next toggle proceeds from that editor so the saved side draft carries it.

  • P3 (empty retraction raises the loss notice): the landing fence now returns quietly when the retraction carries no text, no message ids and no quotes — nothing was lost, so there is nothing to report.

  • P3 (the notice carries only counts): left as is. With the gate above, the notice is now a last-resort backstop behind the entry guards rather than the recovery path, so carrying the full text in it would buy little; the per-session draft handoff remains the structural fix if the reviewer wants it, and that belongs with the expected-session-id follow-up already proposed in the thread.
  • Tests: the two new cases fail on a72756ce7 and pass here (the empty-retraction one on the notice assertion, the toggle one on the session id); all five retraction-race tests pass together. Runner suite 240/242 — the two failures remain the preexisting SIGTERM exit tests on this host; biome, ASF headers, check:tui-copy and check:locale-hygiene clean. The driver suite is untouched by this diff (it does not import the changed module).

    If the fresh test job turns red, it is the main-preexisting acp-goal-plan-child-process.test.js timeout tracked in #5777, not this change.

    ggbdpq ggbdpq commented on Sep 28, 2026 06:38 UTC
    Author

    Merged latest main — head is now 0313ab531. That merge also carries #5779's inventory refresh, so the Check Windows test inventory red on 5cee83425 (an upstream main regression from the #5747 rewrite, not this change: the tree at 5cee83425 itself passes the check locally against CI's own Node) should clear on this head.

    hqhq1025 hqhq1025 commented on code on Sep 28, 2026 07:19 UTC
    Code Review
    packages/cli/src/pi-tui-runner.ts:1
    @@ -2088,8 +2257,11 @@ export async function runMakaPiTui(input: MakaPiTuiInput): Promise<void> {
         }
         // One detach at a time (#3380): a second mid-turn switch while the first
         // is still handing the view over would clear `detaching` early, reopen
    -    // the interrupt window, and double-apply the adoption.
    -    if (detaching) return;
    +    // the interrupt window, and double-apply the adoption. A retraction in
    +    // flight is refused for the same reason: the driver re-keys at the end of
    +    // a switch, so the fences would pass and the retracted text would be
    +    // overwritten by the stale draft (#5109 review).
    +    if (detaching || retracting) return;

    [P2] Guard the idle /session path while a retraction is pending too. The new retracting check only runs after if (!turnRunning): that branch immediately calls switchSession(sessionId) at lines 2251-2255. A user can start Alt+Up while a turn is running, let the turn finish before the Host's retraction response returns, then run /session <other>; the idle branch re-keys the driver despite retracting === true. When the Host response arrives, the fence at lines 1563-1583 reports counts but discards the already-retracted text and quotes, leaving nothing in the old session queue. This is the previous loss mode through an unguarded navigation path. The new test exercises only Ctrl+/ while the turn remains active; add a deterministic delayed-response test that transitions to idle and invokes /session outside the side pair. Also make the flag reentrancy-safe: Alt+Up currently has no retracting admission check at line 1547, so one completed request can clear the boolean while another remains in flight.

    hqhq1025 hqhq1025 commented on Sep 28, 2026 07:19 UTC
    Reviewer

    Reviewed commit 0313ab531d8dc43f7e615bc3ae1fd8574fdebaf2. The new retracting guard prevents a single in-flight Alt+Up retraction from racing the side toggle and the mid-turn /session switch. The new test holds the retraction response, attempts Ctrl+/, then checks that salvaged text reaches the editor (pi-tui-runner.test.ts:8486-8542); the two focused new tests pass locally after a CLI build.

    The prior content-loss issue is not fully resolved; one remaining switch path is identified inline. Current-head hosted test passed, and merge-tree/diff-check against fresh main de4fc5ff are clean. I did not run the full suite or a real Host/TUI concurrency trace.

    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.

    ggbdpq ggbdpq commented on Sep 28, 2026 07:38 UTC
    Author

    Both findings addressed on head 02f3e82e2 (plus a merge of latest main):

  • Idle /session while a retraction is pending: goToSession's runControl branch now refuses while retracting is set, exactly the delayed-response shape the review described — retraction hung on a gate, an idle /session outside the pair is refused (side-1 unchanged), the gate releases, and the salvaged text lands in the editor it belongs to.

  • Re-entrancy: Alt+Up now refuses while a retraction is already in flight (retracting admission check), so a first completion can no longer clear the flag while a second request is still out.
  • Both new tests fail on 0313ab531 and pass here; all six retraction-race tests pass together (runner suite 242/244, the two failures being the preexisting SIGTERM exit tests on this host). Biome, ASF headers, check:tui-copy, check:locale-hygiene and the Windows inventory check all clean; the merged tree carries no protocol changes (epoch guard green).

    me2seeks me2seeks commented on Sep 28, 2026 08:52 UTC
    Reviewer

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

    Summary


    Fixes the CLI losing a rewound turn's quotes: rewind-restored quotes are now staged for the next submit, keyed to the session they were restored in (stagedQuotesSessionId), cleared outright on every session switch, and kept across a refused/failed submit for retry. The race fencing is the strong part: a monotonically increasing stagedGeneration is captured at dispatch, and an in-flight submit's failure callback only re-arms quotes if no write landed since — so a stale callback can't resurrect quotes after /quotes clear or a quote-free submit (both advance the generation without touching the staging pair, as the comment documents). Copy catalog gains quotesRestored/quotesRestoredUnknown/quotesCleared/quotesNone/quotesUsage/quotesListHeading in place of the single unsupportedQuotes. CI test green.

    Findings


    1. [P3] effectiveStagedQuotes() reads input.driver.getSessionId() at render time; if a session switch is in-flight (driver already re-pointed but applySwitchResult not yet run), the stale staging could render once for the new session before clearing. The generation fence prevents the wrong quotes from submitting, so the blast radius is one transient render — acceptable, worth a comment.

    Verdict


    merge-ready — careful session-keyed staging with generation-fenced callbacks; the two rounds of #5109 review feedback are visibly addressed in the design comments.

    hqhq1025 hqhq1025 commented on code on Sep 28, 2026 09:12 UTC
    Code Review
    packages/cli/src/pi-tui-runner.ts:1
    @@ -2080,6 +2252,11 @@ export async function runMakaPiTui(input: MakaPiTuiInput): Promise<void> {
         const leavesPair =
           pair !== undefined && sessionId !== pair.parentSessionId && sessionId !== pair.sideSessionId;
         if (!turnRunning) {
    +      // The idle switch re-keys the driver inside runControl, and a retraction
    +      // still out would land after that re-key: the fence would report counts
    +      // and discard what the Host already took back. Refuse until it settles
    +      // (#5109 review).
    +      if (retracting) return;

    [P2] Recheck retracting after the activity lease wait, before re-keying. This check happens before runControl, but runControl awaits activities.acquire(sessionId) at lines 1152-1155 before invoking switchSession; an existing session activity can keep that wait pending. During the wait, Alt+Up is still handled by the root key handler (:5058-5065) and retractQueuedMessages has no busy guard (:1542-1551). Sequence: idle /session other passes this check and waits for a held activity lease; Alt+Up starts a Host retraction; the lease is released and the queued switch re-keys the driver; the retraction response then hits the switched-session fence and discards the text/quotes already removed from the Host queue. The new idle test starts Alt+Up before /session, so it does not cover this reversed order. Put the guard at the actual switch boundary (or serialize retraction with the control lease), and test a deliberately held activity lease plus Alt+Up before releasing it.

    hqhq1025 hqhq1025 commented on Sep 28, 2026 09:12 UTC
    Reviewer

    Reviewed commit 78903d54da4e477030f052f075162b6013117fc2. The new admission check prevents overlapping Alt+Up retractions (pi-tui-runner.ts:1542-1551), and the idle /session test now distinguishes the previous direct-switch gap (pi-tui-runner.test.ts:8538-8623). A new asynchronous ordering gap remains, described inline.

    Node 24 CLI build and three focused retraction tests passed locally. The current-head hosted test passed, and merge-tree/diff-check against fresh main de4fc5ff are clean. I did not run the full suite or a real Host/TUI trace; the inline scenario is a control-flow finding involving a delayed activity lease.

    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.

    ggbdpq ggbdpq commented on Sep 28, 2026 12:26 UTC
    Author

    All six addressed with one mechanism — head f0b31c98e serializes session switches behind an in-flight retraction:

  • Both retraction paths (Alt+Up and the interrupt) register on a retraction task set, and switchSession/switchAwayMidTurn now await settleRetractions() at entry. That covers every gap raised: the idle /session branch (07:19), the activity-lease wait inside runControl (09:12), the detach toggle (05:16), and Alt+Up's own settlePendingEnqueues wait (03:24/09:12 reversed order). While a retraction is in flight the switch simply waits; when it lands, acceptRetraction has already restored the text and quotes into the session they were asked for, so the switch re-keys a driver whose abandoned payload is intact — switching back shows the recovered draft, and nothing is discarded (05:12/03:24's data-loss half).

  • The parked-enqueue regression now fires Alt+Up while the enqueue is held (01:09 — the previous version never exercised the retraction path), asserting no retractQueued call reaches the moved-to session; a new regression pins the switch-behind-retraction ordering through a held Host gate (05:12's serialization ask).
  • Full pi-tui-runner suite green locally (236/238 with only the pre-existing Windows SIGTERM pair); CI running on this head.

    ggbdpq ggbdpq commented on Sep 28, 2026 16:06 UTC
    Author

    Confirmed the race on the reviewed commit (78903d54d): the idle /session guard ran before runControl, but runControl parks on activities.acquire before reaching the switch, and Alt+Up stays live during that wait, so a retraction started mid-wait could land after the released lease let the switch re-key - the switched-session fence then discarded what the Host had already taken back.

    This head supersedes the flag-based guard reviewed at 78903d54d with the reviewer's second option: serialization at the actual switch boundary. Both retraction paths register on a pending-retraction task set, and switchSession (and the mid-turn detach path) await settleRetractions() before re-keying the driver. A retraction started while the switch waits on the activity lease therefore always completes - landing its text and quotes via acceptRetraction in the session they were queued for - before the re-key, and the fence discard path is no longer reachable from this sequence.

    Added the regression in the reversed order the review asked for (a16a934d7): hold the session's activity lease, start the idle /session so runControl parks on the lease, fire Alt+Up during the wait, then release. The test asserts the retraction completes before the switch re-keys (retract-done: precedes switch: in the driver event log), the retracted text reaches the editor, and the staged quote comes back.

    Red/green evidence: with the settleRetractions() await at the switch boundary removed, the new test fails with the event log switch:session-other,retract-done:session-other (the switch re-keys first and the retraction is discarded); with it restored, the test passes, and the four focused retraction tests (does not retract the switched-to queue..., serializes a mid-turn session switch..., the new idle test, discards a retraction that lands after a mid-turn session switch) each pass individually. biome check on the changed file, check:asf-headers, and the protocol epoch guard (epoch 197, no protocol changes) are clean.

    New head: a16a934d7

    hqhq1025 hqhq1025 commented on code on Sep 28, 2026 19:14 UTC
    Code Review
    packages/cli/src/pi-tui-runner.ts:1
    @@ -1892,6 +2035,10 @@ export async function runMakaPiTui(input: MakaPiTuiInput): Promise<void> {
       // A failure leaves the active session untouched and the next prompt still
       // lands on the old one.
       const switchSession = async (sessionId: string, relocateCwd?: string) => {
    +    // A session switch waits for an in-flight retraction: the retracted text
    +    // and quotes must land in the session they were asked for before the
    +    // driver re-keys (#5109 review).
    +    await settleRetractions();

    [P2] Keep retraction and switch mutually exclusive through the driver's re-key, not only before it. This await drains retractions already pending, but input.driver.switchSession() is asynchronous and Alt+Up remains active while runControl is busy (:5028-5035). After this await returns, a user can press Alt+Up while the driver is still fetching/opening the target session; retractQueued() sends queue.retract for the old session (runtime-host-session-driver.ts:615-620). If the Host removes the queued message and the driver then sets its new session ID (:822-831) before the retract response arrives, the :1567 session fence discards the returned text and quotes. The new lease-wait test starts Alt+Up before this await and its fake switch is immediate, so it cannot catch this order. Block new retractions during the entire switch, or serialize the switch and retraction under one lock.

    hqhq1025 hqhq1025 commented on Sep 28, 2026 19:14 UTC
    Reviewer

    Reviewed exact head a16a934d7e8479cbac82f91d410161a1f28da647. The new test covers Alt+Up while the idle /session command is still waiting for an activity lease, and the existing boundary wait orders that specific case correctly. One P2 race remains, attached inline: Alt+Up can start after that wait returns but while the driver's asynchronous switch is in progress, so a Host retraction can be discarded after changing sessions. This remains a blocker for the claimed no-loss behavior.

    Node 24 clean npm ci, CLI/dependency build, and 4 focused retraction tests pass. Hosted test is green; static merge-tree against current main 2f322055 and git diff --check are clean. I traced the TUI key handler, both retraction fences, the switch boundary, and the Runtime Host driver's request/re-key order. I did not run a real Host/TUI race or full suite; the current fake switches immediately and does not model the in-progress switch window. No schema/migration change is in the PR. This is not a merge approval.

    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.

    ggbdpq ggbdpq commented on code on Sep 28, 2026 22:37 UTC
    Code Review
    packages/cli/src/pi-tui-runner.ts:1
    @@ -1892,6 +2035,10 @@ export async function runMakaPiTui(input: MakaPiTuiInput): Promise<void> {
       // A failure leaves the active session untouched and the next prompt still
       // lands on the old one.
       const switchSession = async (sessionId: string, relocateCwd?: string) => {
    +    // A session switch waits for an in-flight retraction: the retracted text
    +    // and quotes must land in the session they were asked for before the
    +    // driver re-keys (#5109 review).
    +    await settleRetractions();

    Confirmed - the settleRetractions() drain only orders retractions that started before the switch, and the driver switchSession() does real asynchronous work (stopping user commands, opening the target Session channel) before it re-keys, so an Alt+Up pressed in that window still addresses the old Session and the switched-session fence then discards what the Host removed.

    Fixed on the first suggested axis: new retractions are blocked for the entire switch. Every runner-level switch path - idle /session, the mid-turn detach, and rewind (its driver call re-keys the same way) - now runs inside a switch window (a counter, so the paths compose), and retractQueuedMessages drops the keypress while a window is open. Dropping it loses nothing: the entries stay queued on the Host, and Alt+Up after the switch lands retracts from the session that is then current. Blocking over a lock, because pairing a retraction-side wait with the drain re-check loop could otherwise cycle (switch waits retraction, retraction waits switch); a blocking check is order-free.

    The new regression test models the in-progress window the previous test could not: the fake driver now parks inside switchSession before its re-key. On the previous head the test fails with a queue.retract crossing the window (retractCalls 1 !== 0); with the gate it passes (queue untouched, no retract-done), and removing the gate alone makes it fail again (ablation). The four previous focused retraction tests and the rewind in-flight tests pass individually; the full runner suite is 241 tests with only the two known pre-existing SIGTERM failures.

    Head: b48832dbf.

    hqhq1025 hqhq1025 commented on Sep 29, 2026 07:21 UTC
    Reviewer

    Reviewed exact head b48832dbf714bb4d8454677e1238e4203dcf0d7a. The new switch-window guard closes the previously reported /session race, and its focused regression passes.

    [P2] The same Runtime Host re-key remains unguarded through the side-conversation APIs. /side can run while a Turn has queued follow-ups, but packages/cli/src/pi-tui-runner.ts:2302-2305 calls driver.openSideConversation() directly; the Runtime Host implementation eventually calls switchSession(sideSessionId) at packages/cli/src/runtime-host-session-driver.ts:944-975 without incrementing sessionSwitchesInFlight. Alt+Up therefore remains live at pi-tui-runner.ts:5067-5074. If queue.retract removes the old Session's entries while that internal switch re-keys, the response-time session fence at :1591 drops the returned text and quotes, reproducing the same silent input loss this commit fixes for /session. closeSideConversation() has the same direct re-key at :2343-2347. Please wrap these switch-owning operations in the same window and add a delayed open/close plus Alt+Up regression.

    Node 24 clean npm ci, build:test, and three focused retraction/switch tests passed. Hosted test is green, git diff --check passes, and the merge tree against current main 03237142 is clean. I did not run a real Host/TUI timing reproduction, the complete test suite, or native Windows/macOS.

    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.

    ggbdpq ggbdpq commented on Sep 29, 2026 22:50 UTC
    Author

    Pushed 0ac4a7ef9 — both side-conversation transitions now hold the same switch window.

    What's guarded (on top of the three paths the previous commit already covered):

  • /side open: both entry paths (turnRunning and idle) wrap the driver call in holdSwitchWindow(...).

  • /side close: the body moved to runCloseSideConversation, and closeSideConversation is now a holdSwitchWindow(...) wrapper — so the three existing call sites (interrupt-and-close and the Ctrl+C path included) inherit the guard unchanged.
  • Class sweep, not just the reported instance — every runner-level operation that ends in a driver re-key: idle /session, mid-turn detach, and rewind branch-and-switch were already guarded; /side open and close were the only unguarded ones. Excluded after checking the mechanism rather than the name: discardSideConversation (explicit-id cleanup, never re-keys the driver's session identity), /new (sessionId = null, and retractQueued is a safe no-op on null identity — queue.retract is never emitted, so the silent-loss mechanism cannot occur), and resumeLatest (startup path; no live queue and Alt+Up is not yet active). All session-identity assignment sites in the driver were audited.

    Regression: two tests with a gate-holding driver (openGate/closeGate park the switch mid-flight, before the re-key) firing Alt+Up inside the window. Red on the previous head (no queue.retract may cross... 1 !== 0), green with the guards, red again with only the two new wrappers removed (ablation). Zero-loss semantics held: the retracted entry stays in the Host queue and takes effect after the switch lands. Focused retraction/switch/side set 25/25, quotes 6/6.

    Honest scope: focused suites ran locally; the full runner suite and the real-driver end-to-end window ride on CI.

    hqhq1025 hqhq1025 commented on code on Sep 29, 2026 23:20 UTC
    Code Review
    packages/cli/src/pi-tui-runner.ts:1
    @@ -2135,26 +2318,32 @@ export async function runMakaPiTui(input: MakaPiTuiInput): Promise<void> {
           });
           requestRender();
         };
    +    // Opening re-keys the driver onto the side Session through asynchronous
    +    // work (the Host forks the parent and switches onto the fork), the same
    +    // switchSession re-key path as `/session`, so both entry paths hold the
    +    // switch window: a retraction asked inside it would address the parent
    +    // while the Host removes its queued entries, and the side-session fence
    +    // would then discard what the Host removed (#5265 review).
         if (turnRunning) {
           if (detaching) return;
           detaching = true;
           try {
    -        await adopt();
    +        await holdSwitchWindow(adopt);

    [P2] Drain retractions that started before entering the side switch window

    holdSwitchWindow only prevents new Alt+Up requests after its counter is incremented. It does not wait for a retraction already present in pendingRetractionTasks. This remains reachable: queue a follow-up, gate retractQueued(), press Alt+Up, then run /side. On this head the driver re-keys to the side Session before the retraction resolves; the Host-side retract removes the parent queue entry, and the response-time session fence at pi-tui-runner.ts:1591 then drops the returned text and quotes.

    I reproduced that ordering with a temporary test through the real TUI key/command path: the session became side-1 while the retract gate was still closed. The ordinary /session path avoids the same loss by awaiting settleRetractions() inside its held window (pi-tui-runner.ts:2065). Please drain already-started retractions inside the held window before both side open and side close begin their driver re-key, and add coverage where Alt+Up starts before /side/close rather than only during them.

    hqhq1025 hqhq1025 commented on Sep 29, 2026 23:20 UTC
    Reviewer

    Reviewed exact head 0ac4a7ef9c1f09563ab101116d858d9667bc6507.

    The new open/close guards do block Alt+Up after the side-conversation re-key has entered its switch window, and both added regressions discriminate those two wrappers. However, an already-started retraction is still allowed to cross the re-key; see the inline P2.

    Validation: clean npm ci; build:test; full typecheck, lint, format, ASF header, Windows inventory, and diff checks; focused side-open/close tests 2/2; complete CLI suite 1,356 passed / 3 skipped. Removing only the new open/close wrappers made both added tests fail with retractCalls 1 instead of 0. A separate temporary production-runner probe that started Alt+Up before /side reproduced the remaining race on this head. Hosted test is green. Current main is 19 commits ahead of the PR while the PR is 22 commits ahead of main; git merge-tree --write-tree completed without conflicts.

    I did not exercise an interactive terminal against a separately running real Runtime Host, packaged Electron, or native Windows/macOS.

    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.

    ggbdpq ggbdpq commented on code on Sep 30, 2026 00:21 UTC
    Code Review
    packages/cli/src/pi-tui-runner.ts:1
    @@ -2135,26 +2318,32 @@ export async function runMakaPiTui(input: MakaPiTuiInput): Promise<void> {
           });
           requestRender();
         };
    +    // Opening re-keys the driver onto the side Session through asynchronous
    +    // work (the Host forks the parent and switches onto the fork), the same
    +    // switchSession re-key path as `/session`, so both entry paths hold the
    +    // switch window: a retraction asked inside it would address the parent
    +    // while the Host removes its queued entries, and the side-session fence
    +    // would then discard what the Host removed (#5265 review).
         if (turnRunning) {
           if (detaching) return;
           detaching = true;
           try {
    -        await adopt();
    +        await holdSwitchWindow(adopt);

    Pushed 0f26b77c7 — all three re-key paths now drain before switching.

  • /side open: await settleRetractions() at the top of the shared adopt, while the driver still points at the parent.

  • /side close: same drain at the top of runCloseSideConversation — an in-flight retraction lands while the driver still points at the side Session, before the re-key onto the parent.

  • Rewind had the same hole and is fixed in the same commit: rewindToTurn re-keys onto a freshly minted branch Session, so a retraction already in flight when the window opened would hit the same fence drop; it now drains inside the held window first. Reachability checked: rewind only requires idle, and a pending retraction holds no busy gate.
  • Coverage follows the ordering you called out — Alt+Up starts before the switch, not during it. Four new tests with a retract-gate driver (open idle / open mid-turn / close / rewind; the rewind variant mints a fresh branch id per rewind, matching the real driver). All four fail on the previous head with exactly the loss ordering described (open-start:session-branch, open:side-1, close-start:side-1, close:session-branch, rewind 2 !== 1), pass with the drains, and fail again with only the three settle calls removed (ablation). Focused retraction/switch/side set 29/29.

    Honest scope: reproduced through the real TUI key/command harness with a gated fake driver on the same event order, not against a live Runtime Host connection; the two SIGTERM failures in the full runner file are pre-existing (re-verified against the unfixed baseline).

    hqhq1025 hqhq1025 commented on code on Sep 30, 2026 01:15 UTC
    Code Review
    packages/cli/src/pi-tui-runner.ts:1
    @@ -2117,6 +2300,13 @@ export async function runMakaPiTui(input: MakaPiTuiInput): Promise<void> {
         const previousActivity = currentActivityCompletion;
         let opened = false;
         const adopt = async () => {
    +      // The window blocks only retractions asked inside it: one already in
    +      // flight when the open started must drain here, while the driver still
    +      // points at the parent — the Host removes the parent's queued entries as
    +      // the retraction resolves, and a response landing after the re-key onto
    +      // the side Session would be discarded by the side-session fence (#5265
    +      // review).
    +      await settleRetractions();

    [P2] Keep the recovered parent draft out of the new side editor. Once this await resolves, acceptRetraction() has put the parent's retracted text into the shared editor. The code then re-keys to the side Session and records that text as parentDraft, but never replaces the editor with the empty sideDraft. The existing new test actually requires queued resend to remain visible after getSessionId() becomes side-1, so pressing Enter can submit the parent's recovered message in the side conversation and the same text is retained for the parent as well. This contradicts the established per-view draft behavior in Ctrl+/ toggles side views, preserves drafts. A temporary assertion that the new side editor was empty failed with actual value queued resend. Capture the parent draft and switch the editor to the side draft (or cancel the open) after the drain, and make the regression assert both sides' draft ownership.

    hqhq1025 hqhq1025 commented on code on Sep 30, 2026 01:15 UTC
    Code Review
    packages/cli/src/pi-tui-runner.ts:1
    @@ -2135,28 +2325,39 @@ export async function runMakaPiTui(input: MakaPiTuiInput): Promise<void> {
           });
           requestRender();
         };
    +    // Opening re-keys the driver onto the side Session through asynchronous
    +    // work (the Host forks the parent and switches onto the fork), the same
    +    // switchSession re-key path as `/session`, so both entry paths hold the
    +    // switch window: a retraction asked inside it would address the parent
    +    // while the Host removes its queued entries, and the side-session fence
    +    // would then discard what the Host removed (#5265 review).
         if (turnRunning) {
           if (detaching) return;
           detaching = true;
           try {
    -        await adopt();
    +        await holdSwitchWindow(adopt);
           } catch (error) {
             reportError(error);
           } finally {
             detaching = false;
             startPendingAttachedTurn();
           }
         } else {
    -      await runControl(adopt);
    +      await runControl(() => holdSwitchWindow(adopt));
         }
         if (!opened || !prompt) return;
         await previousActivity?.catch(() => undefined);
         submitPrompt(prompt);
       };
     
    -  const closeSideConversation = async (): Promise<void> => {
    +  const runCloseSideConversation = async (): Promise<void> => {
         const pair = sideConversation;
         if (!pair || !input.driver.closeSideConversation) return;
    +    // Same drain as the open: a retraction asked while the side Session was
    +    // active must land while the driver still points at it — past the re-key
    +    // onto the parent, the close's session fence discards the text and quotes
    +    // the Host already removed from the side queue (#5265 review).
    +    await settleRetractions();

    [P2] Re-check or preserve the side draft after this drain. The Ctrl+C close guard sees an empty editor before the pending retraction finishes; this await then restores side follow-up into the editor, but editor.setText(pair.parentDraft) below overwrites it and the close removes the side conversation. The new close test only checks ordering and the final Session id, so it passes while the retracted message is still lost. A temporary assertion that the recovered text remained visible after close failed. Please either abort the close once the drain produces a non-empty draft, or persist/transfer that recovered content before replacing the editor, and assert the final user-visible draft in the regression.

    hqhq1025 hqhq1025 commented on Sep 30, 2026 01:15 UTC
    Reviewer

    Reviewed exact head 0f26b77c7f24c4d554beaa22abf6f8a0d5c0106d. The new drains correctly order the Host retraction before each re-key, and all four focused regressions pass. However, the restored payload is still mishandled after the drain on both Side Chat transitions; see the two inline P2 findings.

    Validation: Node 24.18.1 build:test; full typecheck, lint, format, ASF header, Windows inventory, and diff checks; focused new regressions 4/4; complete CLI suite 1,360 passed / 3 skipped. Two temporary production-runner assertions reproduced the remaining behavior: the parent text was visible in the new side editor, and the side text was absent after close. Both diagnostic edits were removed and the exact-head tests were rebuilt and rerun. Hosted test is green. The PR is 23 commits ahead / 20 behind current main 28cc4e64; git merge-tree --write-tree completed without conflicts.

    I did not exercise a separately running real Runtime Host through an interactive terminal, packaged Electron, or native Windows/macOS.

    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.

    ggbdpq ggbdpq commented on code on Sep 30, 2026 02:45 UTC
    Code Review
    packages/cli/src/pi-tui-runner.ts:1
    @@ -2117,6 +2300,13 @@ export async function runMakaPiTui(input: MakaPiTuiInput): Promise<void> {
         const previousActivity = currentActivityCompletion;
         let opened = false;
         const adopt = async () => {
    +      // The window blocks only retractions asked inside it: one already in
    +      // flight when the open started must drain here, while the driver still
    +      // points at the parent — the Host removes the parent's queued entries as
    +      // the retraction resolves, and a response landing after the re-key onto
    +      // the side Session would be discarded by the side-session fence (#5265
    +      // review).
    +      await settleRetractions();

    Fixed on bd25e82fc: after the drain, adopt captures the recovered parent text as parentDraft and now switches the editor to the side view's own (empty) draft, so Enter in the side conversation can no longer resubmit the parent's message and Ctrl+/ restores the parent text from parentDraft. The idle-open regression now asserts the side editor opens empty and that a close round trip brings queued resend back in the parent editor; the mid-turn variant asserts the empty side editor. Both failed on the previous head with exactly your reproduction (queued resend visible in the new side editor).

    ggbdpq ggbdpq commented on code on Sep 30, 2026 02:45 UTC
    Code Review
    packages/cli/src/pi-tui-runner.ts:1
    @@ -2135,28 +2325,39 @@ export async function runMakaPiTui(input: MakaPiTuiInput): Promise<void> {
           });
           requestRender();
         };
    +    // Opening re-keys the driver onto the side Session through asynchronous
    +    // work (the Host forks the parent and switches onto the fork), the same
    +    // switchSession re-key path as `/session`, so both entry paths hold the
    +    // switch window: a retraction asked inside it would address the parent
    +    // while the Host removes its queued entries, and the side-session fence
    +    // would then discard what the Host removed (#5265 review).
         if (turnRunning) {
           if (detaching) return;
           detaching = true;
           try {
    -        await adopt();
    +        await holdSwitchWindow(adopt);
           } catch (error) {
             reportError(error);
           } finally {
             detaching = false;
             startPendingAttachedTurn();
           }
         } else {
    -      await runControl(adopt);
    +      await runControl(() => holdSwitchWindow(adopt));
         }
         if (!opened || !prompt) return;
         await previousActivity?.catch(() => undefined);
         submitPrompt(prompt);
       };
     
    -  const closeSideConversation = async (): Promise<void> => {
    +  const runCloseSideConversation = async (): Promise<void> => {
         const pair = sideConversation;
         if (!pair || !input.driver.closeSideConversation) return;
    +    // Same drain as the open: a retraction asked while the side Session was
    +    // active must land while the driver still points at it — past the re-key
    +    // onto the parent, the close's session fence discards the text and quotes
    +    // the Host already removed from the side queue (#5265 review).
    +    await settleRetractions();

    Fixed on bd25e82fc by aborting the close: the close is only admitted from an empty draft, so a non-empty editor after the drain means the drain (or typing under it) restored content — the close now returns early with a notice ("Side conversation kept open — the retracted message was restored to the draft.", registered in the TUI copy inventory) instead of overwriting the recovered text with parentDraft. A later Ctrl+C clears the restored draft like any draft, and the next close goes through. The close regression now asserts the abort: no driver close call, session stays on the side, side follow-up remains visible in the editor, and the notice renders; it failed on the previous head where the text was overwritten and lost.

    ggbdpq ggbdpq commented on Sep 30, 2026 03:04 UTC
    Author

    Gentle ping on this one — it has been open for two and a half weeks, and every finding across the review rounds is addressed. The current head bd25e82fc fixes the last two inline P2s from the latest automated review (the drained retraction's payload landing in the wrong editor on side open/close): the idle/mid-turn open regressions now assert the side editor starts empty with the recovered text owned by the parent draft, and the close regression asserts the abort that keeps the recovered side text visible. Runner suite 245/247 (the two failures are the known pre-existing SIGTERM tests), the hosted test check is green on this head, and the merge tree against current main is clean.

    @zhiiw could you take a look for a human review when you have a moment? Happy to address anything that comes up.

    Astro-Han Astro-Han commented on code on Sep 30, 2026 06:49 UTC
    Code Review
    packages/cli/src/pi-tui-runner.ts:1
    @@ -2126,6 +2316,12 @@ export async function runMakaPiTui(input: MakaPiTuiInput): Promise<void> {
             parentDraft: editor.getText(),

    P2: by the time this runs, applySwitchResult has already called clearStagedQuotes() unconditionally, so any quotes the retraction just restaged for the old session are gone (the same applies to /session, a quote-only side close, and rewind). The Host has already dropped them from the queue, so this was the only copy. Carrying staged quotes into parentDraft (and restoring them on close), or deferring the clear until after the retraction settles, would keep them. A test that asserts what the TUI actually submits after the round trip would catch this.

    Astro-Han Astro-Han commented on code on Sep 30, 2026 06:49 UTC
    Code Review
    packages/cli/src/pi-tui-runner.ts:1
    @@ -1891,7 +2058,11 @@ export async function runMakaPiTui(input: MakaPiTuiInput): Promise<void> {
       // The driver validates the durable cwd before adopting the resumed session.
       // A failure leaves the active session untouched and the next prompt still
       // lands on the old one.
    -  const switchSession = async (sessionId: string, relocateCwd?: string) => {
    +  const runSessionSwitch = async (sessionId: string, relocateCwd?: string) => {
    +    // A session switch waits for an in-flight retraction: the retracted text
    +    // and quotes must land in the session they were asked for before the
    +    // driver re-keys (#5109 review).
    +    await settleRetractions();

    P2: the Ctrl+/ toggle path captures the draft (around line 2229) before this wait for the pending retraction, then writes that stale draft back into the editor. With Alt+Up in flight and then Ctrl+/, the side editor, the parent editor and the Host queue all end up empty, with no notice. Capturing the draft after the wait (as the /side open path now does) would fix it.

    Astro-Han Astro-Han commented on Sep 30, 2026 06:49 UTC
    Reviewer

    Reviewed exact head bd25e82fc2044fee586c8a16660129fc88417605 (incremental from 0f26b77c). Thanks for the quick iteration. The two message-text losses from the last round are fixed:

  • Opening /side now saves the recovered parent text as the parent draft and opens the side editor empty.

  • Closing the side chat is cancelled with a notice when the editor is non-empty after the wait, so text is no longer overwritten.

  • With the 0f26b77c runner restored and the new tests kept, the idle-open, mid-turn-open and close tests fail, so they discriminate the fix.
  • Two P2 losses remain (inline):

  • Retracted quotes are dropped on every session change. They are restaged for the old session, then applySwitchResult clears staging unconditionally. This affects side open, /session, a quote-only side close and rewind. The Host has already removed them, so the TUI held the only copy. A probe confirmed resubmitting after a side round trip sends no quotes. The tests only assert the quotes the fake driver returned, not what the TUI submits.

  • Ctrl+/ still loses retracted text. The toggle captures the draft before waiting for the pending retraction, then overwrites the editor with that stale draft. A probe with Alt+Up in flight followed by Ctrl+/ left the side editor, parent editor and Host queue all empty, with no notice.
  • P3:

  • The close-cancel check looks only at text, so a retraction that restored only quotes still closes and loses them.

  • The cancel notice always says "retracted message", even when the text was typed.

  • Rewind replaces the retracted message's quotes with the rewound turn's quotes; the test uses the same quote on both sides, so it doesn't show this.
  • Checks run locally: build, typecheck, ASF headers, git diff --check, Windows test inventory, TUI copy check, Biome; focused CLI tests 45/45, full CLI suite 1359 pass / 0 fail (one pre-existing cancellation in an untouched file). Not run: a live Runtime Host, Node 24, Windows/macOS.

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

    hqhq1025 hqhq1025 commented on code on Sep 30, 2026 06:53 UTC
    Code Review
    packages/cli/src/pi-tui-runner.ts:1
    @@ -2135,28 +2331,53 @@ export async function runMakaPiTui(input: MakaPiTuiInput): Promise<void> {
           });
           requestRender();
         };
    +    // Opening re-keys the driver onto the side Session through asynchronous
    +    // work (the Host forks the parent and switches onto the fork), the same
    +    // switchSession re-key path as `/session`, so both entry paths hold the
    +    // switch window: a retraction asked inside it would address the parent
    +    // while the Host removes its queued entries, and the side-session fence
    +    // would then discard what the Host removed (#5265 review).
         if (turnRunning) {
           if (detaching) return;
           detaching = true;
           try {
    -        await adopt();
    +        await holdSwitchWindow(adopt);
           } catch (error) {
             reportError(error);
           } finally {
             detaching = false;
             startPendingAttachedTurn();
           }
         } else {
    -      await runControl(adopt);
    +      await runControl(() => holdSwitchWindow(adopt));
         }
         if (!opened || !prompt) return;
         await previousActivity?.catch(() => undefined);
         submitPrompt(prompt);
       };
     
    -  const closeSideConversation = async (): Promise<void> => {
    +  const runCloseSideConversation = async (): Promise<void> => {
         const pair = sideConversation;
         if (!pair || !input.driver.closeSideConversation) return;
    +    // Same drain as the open: a retraction asked while the side Session was
    +    // active must land while the driver still points at it — past the re-key
    +    // onto the parent, the close's session fence discards the text and quotes
    +    // the Host already removed from the side queue (#5265 review).
    +    await settleRetractions();
    +    // The close is only admitted from an empty draft, so anything in the
    +    // editor here was restored by the drain (or typed under it): aborting
    +    // keeps the recovered side text visible instead of overwriting it with
    +    // the parent draft below, and a later Ctrl+C clears it like any draft
    +    // (#5265 review).
    +    if (editor.getText().length > 0) {

    [P2] Recheck the editor after the asynchronous side close

    This new empty-editor guard runs before await input.driver.closeSideConversation(...). The real driver awaits a session switch and cleanup (runtime-host-session-driver.ts:984-993), while runControl only sets editor.disableSubmit = true, not a typing lock (pi-tui-runner.ts:1131-1159). A user can type a new side draft during that wait; when the promise resolves, line 2386 unconditionally replaces it with pair.parentDraft. The new guard therefore prevents text restored before the close RPC, but silently discards text entered while it is in flight. The adjacent rewind test explicitly exercises typing during a control wait; no close test covers this interval. Preserve or recheck the live editor text before overwriting it after the await.

    hqhq1025 hqhq1025 commented on Sep 30, 2026 06:53 UTC
    Reviewer

    Reviewed exact head bd25e82fc2044fee586c8a16660129fc88417605. The previous parent-text leak on side open and the post-retraction text overwrite on side close are addressed by this revision. I found one additional P2 in a later close window (inline). The two P2 findings already published in review 5362482066, concerning lost retracted quotes on session changes and stale drafts in Ctrl+/, remain and are not duplicated here. This head is not ready to merge.

    Validation: Node 24 clean npm ci, build:test, focused TUI switch/retraction/close tests 8/8, git diff --check, and a clean merge-tree against current main ed38ccbb. Exact-head hosted test passed. The new finding follows the async close control flow and the editor input contract; I did not run a dedicated live-TUI close-gate reproduction. Native Windows/macOS and a real separated Runtime Host were not tested.

    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.

    ggbdpq ggbdpq commented on code on Sep 30, 2026 07:43 UTC
    Code Review
    packages/cli/src/pi-tui-runner.ts:1
    @@ -2126,6 +2316,12 @@ export async function runMakaPiTui(input: MakaPiTuiInput): Promise<void> {
             parentDraft: editor.getText(),

    {"body":"Fixed on 5e538681b: retraction-restored quotes now ride the recovered draft text, so the #5109 rule stands while the quotes stop dying.\n\n- applySwitchResult still clears turn-staged quotes outright on every session change (silent resurrection stays impossible), but quotes staged by acceptRetraction now carry a followDraft lane that the clear spares. They stay keyed to wherever their text lives — the editor the switch does not discard.\n- Where the text is parked, the quotes are parked with it: the side pair gained parentQuotes/sideQuotes slots captured next to the draft on open/toggle and staged back for the owning view on return/close.\n- A rewind that branches without its own quotes keeps the drained quotes; one that carries its own still replaces them (the #5109 replacement semantics, now pinned by a test).\n\nTests assert what the TUI actually submitted (driver.submittedQuotes), not what the fake returns:\n\n- carries retraction-restored quotes through a side conversation round trip — red on bd25e82fc exactly as your probe (resubmit after the side round trip sent no quotes), green now.\n- carries retraction-restored quotes across a /session switch — red/green the same way.\n- keeps drained quotes when a rewind branches without quotes of its own — red/green the same way (the quote-less branch is the case where nothing replaces the drained quotes)."}

    ggbdpq ggbdpq commented on code on Sep 30, 2026 07:43 UTC
    Code Review
    packages/cli/src/pi-tui-runner.ts:1
    @@ -1891,7 +2058,11 @@ export async function runMakaPiTui(input: MakaPiTuiInput): Promise<void> {
       // The driver validates the durable cwd before adopting the resumed session.
       // A failure leaves the active session untouched and the next prompt still
       // lands on the old one.
    -  const switchSession = async (sessionId: string, relocateCwd?: string) => {
    +  const runSessionSwitch = async (sessionId: string, relocateCwd?: string) => {
    +    // A session switch waits for an in-flight retraction: the retracted text
    +    // and quotes must land in the session they were asked for before the
    +    // driver re-keys (#5109 review).
    +    await settleRetractions();

    {"body":"Fixed on 5e538681b: the toggle now captures the draft — and the staged quotes riding it — after switchSession/switchAwayMidTurn resolve. Both paths already drain the pending retraction first, so the capture lands on what the drain restored, the same ordering the /side open uses with its explicit settleRetractions().\n\nTest: captures the draft a retraction restores while a side toggle waits it out — Alt+Up held on the Host call, Ctrl+/ parks behind it (asserted: no switch-start while the gate is closed), gate resolved; toggling back to the side view shows the recovered side follow-up in the side draft. Red on bd25e82fc with your reproduction (side draft empty after the round trip), green now."}

    ggbdpq ggbdpq commented on code on Sep 30, 2026 07:43 UTC
    Code Review
    packages/cli/src/pi-tui-runner.ts:1
    @@ -2135,28 +2331,53 @@ export async function runMakaPiTui(input: MakaPiTuiInput): Promise<void> {
           });
           requestRender();
         };
    +    // Opening re-keys the driver onto the side Session through asynchronous
    +    // work (the Host forks the parent and switches onto the fork), the same
    +    // switchSession re-key path as `/session`, so both entry paths hold the
    +    // switch window: a retraction asked inside it would address the parent
    +    // while the Host removes its queued entries, and the side-session fence
    +    // would then discard what the Host removed (#5265 review).
         if (turnRunning) {
           if (detaching) return;
           detaching = true;
           try {
    -        await adopt();
    +        await holdSwitchWindow(adopt);
           } catch (error) {
             reportError(error);
           } finally {
             detaching = false;
             startPendingAttachedTurn();
           }
         } else {
    -      await runControl(adopt);
    +      await runControl(() => holdSwitchWindow(adopt));
         }
         if (!opened || !prompt) return;
         await previousActivity?.catch(() => undefined);
         submitPrompt(prompt);
       };
     
    -  const closeSideConversation = async (): Promise<void> => {
    +  const runCloseSideConversation = async (): Promise<void> => {
         const pair = sideConversation;
         if (!pair || !input.driver.closeSideConversation) return;
    +    // Same drain as the open: a retraction asked while the side Session was
    +    // active must land while the driver still points at it — past the re-key
    +    // onto the parent, the close's session fence discards the text and quotes
    +    // the Host already removed from the side queue (#5265 review).
    +    await settleRetractions();
    +    // The close is only admitted from an empty draft, so anything in the
    +    // editor here was restored by the drain (or typed under it): aborting
    +    // keeps the recovered side text visible instead of overwriting it with
    +    // the parent draft below, and a later Ctrl+C clears it like any draft
    +    // (#5265 review).
    +    if (editor.getText().length > 0) {

    {"body":"Fixed on 5e538681b: after the driver call and applySwitchResult land, the close now reads the live editor instead of unconditionally restoring pair.parentDraft. Input typed during the window outranks the parked parent draft — it is kept as-is, with the parent draft appended below a blank line when both are non-empty, so nothing is silently dropped.\n\nTest: keeps text typed while a side conversation close is in flight — closeGate parks the fake driver inside closeSideConversation, the test types during the hold, and the text must survive the re-key onto the parent. Red on bd25e82fc (editor restored to the empty parent draft), green now."}

    ggbdpq ggbdpq commented on Sep 30, 2026 07:43 UTC
    Author

    {"body":"Addressing the three P3s from https://github.com/apache/maka/pull/5265#pullrequestreview-5362482066 on 5e538681b:\n\n- Close-cancel looked only at text. The guard now also aborts when effectiveStagedQuotes() is non-empty, so a quote-only retraction keeps the side conversation open. aborts a side close when a quote-only retraction left staged quotes: red on bd25e82fc (close proceeded; the later submit carried no quotes), green now (close aborted, the resubmit carries the quote).\n- Cancel notice blamed a retracted message. Two neutral literals replace it — Side conversation kept open — the editor draft was kept. and Side conversation kept open — the staged quotes were kept. — registered in the check-tui-copy allowlist. does not blame a retraction for a draft the user typed when keeping the side open: the draft is typed during the close's drain window with a queue-empty retraction pending; red on bd25e82fc (old wording claimed a retraction), green now (neutral wording, no \"retracted message\" anywhere in the transcript).\n- Rewind replacement was invisible. PerRewindBranchRetractingDriver now mints a distinct quote per rewind, and drains a retraction started before a rewind branches asserts the resubmit carries excerpt from rewind 2, not the retracted excerpt from rewind 1 — the replacement is the designed #5109 behavior and is now pinned. With the quote made distinct, removing the rewind's own quotes (next test) also exposes the case where nothing replaces the drained ones.\n\nAblation (each guard re-reds its test when removed alone): unconditional clearStagedQuotes() in applySwitchResult re-reds the three quote-survival tests; the toggle's post-drain capture re-reds the Ctrl+/ test; restoring the unconditional setText(parentDraft) re-reds the close-window test; dropping the staged-quotes half of the close guard re-reds the quote-only test; the old literal re-reds the wording test.\n\n| Check | Result |\n| --- | --- |\n| New tests on pre-fix runner (bd25e82fc) | 7/7 red, matching the review reproductions |\n| New tests on 5e538681b | 7/7 green |\n| Full pi-tui-runner suite | 254 tests: 252 pass, 2 fail = the known pre-existing SIGTERM tests |\n| npm run check:tui-copy | ok (18 files) |\n| npm run check:locale-hygiene (base upstream/main) | passed |\n| npm run check:asf-headers | ok |\n| Biome on touched files | clean |\n| git diff --check upstream/main HEAD | clean |\n| git merge-tree --write-tree HEAD upstream/main | clean — no merge needed |"}

    hqhq1025 hqhq1025 commented on code on Sep 30, 2026 09:27 UTC
    Code Review
    packages/cli/src/pi-tui-runner.ts:1
    @@ -1361,16 +1491,61 @@ export async function runMakaPiTui(input: MakaPiTuiInput): Promise<void> {
         const messageId = randomUUID();
         appendUserPrompt(state, text, messageId, true);
         requestRender();
    +    // Quotes staged by a rewind (#5109) ride this message and only this one:
    +    // the staging clears as the message dispatches, and a refusal or failure
    +    // restages them for the retry.
    +    const staged = effectiveStagedQuotes();
    +    const originSessionId = input.driver.getSessionId();
    +    if (staged.length > 0) clearStagedQuotes();
    +    else supersedePendingRestage();
    +    // The generation is read after the dispatch's own clear: the restore
    +    // guard compares against the staging state this submit actually left
    +    // behind, so an ordinary failure still passes while a Session switch, a
    +    // newer rewind, or an explicit clear landing while the admission was in
    +    // flight has since bumped it and must not inherit context meant for the
    +    // original conversation (#5109 review).
    +    const originGeneration = stagedGeneration;
    +    const originFollowDraft = stagedQuotesFollowDraft;

    [P2] Capture the draft-following provenance before clearing the staged quotes. When a retraction-restored quote is submitted, line 1499 calls clearStagedQuotes(), which sets stagedQuotesFollowDraft to false. This new read therefore always records false for a quoted submission. If admission then fails or returns no receipt, restageForRetry() restores the quotes as ordinary turn-staged quotes; a subsequent /session or side-view switch clears them in applySwitchResult() rather than carrying the retry context with the recovered draft. The new switch tests cover the quote before submission, and the failure tests retry without a switch, so they miss this combined path.

    ggbdpq ggbdpq commented on Oct 08, 2026 12:41 UTC
    Author

    @hqhq1025 gentle ping for a re-review when you have a moment.

    Your 09-30 P2 ("Reserve the mid-turn detach before awaiting the retraction drain") was confirmed against the code at eb0f8e4ed and is now fixed at d8bef9273: runMidTurnSwitch sets detaching before the retraction drain (the latch the other navigation guards read), and goToSession's one-detach guard now covers the idle branch too, since the running Turn can end while the drain is pending. Two regressions drive two navigations across one held retraction and assert a single driver.switchSession; both are red on eb0f8e4ed with two concurrent re-keys and green now. The full pi-tui-runner file passes 257/257 on this head.

    Details are in the thread. (Re-requesting you through the review UI isn't available to this account, hence the mention.)

    ggbdpq ggbdpq commented on Oct 08, 2026 16:21 UTC
    Author

    @hqhq1025 Re-review requested at head 737f47071 (merge of main 49e01b15 plus one commit).

  • P2 (CI): adapted to #5910 — all 22 retraction sends now use \x1b[1;2D (Shift+Left), Alt+Up comments/titles renamed, including five stale mentions in pi-tui-runner.ts. The full pi-tui-runner suite passes 260/260 locally on this head (two new guards included).

  • P3: openSideConversation returns early on detaching; the /new gap you noted is closed with the same guard in newSession. Regressions for both entries fail on the previous head with the concurrent re-key.
  • Also on this head: local build:test, check:asf-headers, TUI copy check, git diff --check, and Biome on the touched files are clean; focused pi-transcript + runtime-host-session-driver suites pass (192 pass / 0 fail / 3 skip). Not run: full CLI suite, a live Runtime Host, native Windows/macOS.

    ggbdpq ggbdpq commented on Oct 10, 2026 01:10 UTC
    Author

    @me2seeks your changes-requested review is attached to head a127b13ed from Sep 20, twenty commits ago. Both findings in it have since been fixed and independently confirmed:

  • P1 (staged quotes silently swallowed on outcome_unknown) — the staging-generation supersession guard landed right after your review; @hqhq1025's re-review of Sep 26 verified it ("the failure/unknown-outcome callback checks that generation before restoring") and the Sep 30 chain re-verified provenance survives failed submits (5e538681b).

  • P2 — same guard, same confirmations.
  • Since then: 14 incremental review rounds by @hqhq1025 across successive heads (final one: "no remaining substantiated P0-P3"), @Astro-Han's incremental review of the current head 737f47071 found nothing new ("No P0-P3. CI test passes, and the PR is mergeable"), all 25 review threads are resolved with evidence links, CI is green, and the branch is MERGEABLE.

    Could you either re-review the current head or dismiss the outdated review so the merge gate reflects reality? Happy to walk through any remaining concern.

    ggbdpq ggbdpq commented on Oct 10, 2026 11:17 UTC
    Author

    Merged main (031bca51) into this branch to clear the conflicts — new head is 59cc0ef2a.

    Conflict resolution, file by file:

  • pi-tui-runner.ts (3 hunks): kept main's goToSession → Promise<boolean> signature (consumed by /resume auto-resume) together with this PR's whole-command detaching guard (the idle branch is reachable mid-drain), dropping main's inner duplicate guard; kept both MakaSessionRewindResult and MakaSessionListOptions imports.

  • pi-tui-runner.test.ts (1 hunk): import union of both sides (QuoteRef + MakaSessionCatalogIncompleteError).
  • Local verification on the merge commit: the 4 drain-window regression tests pass; full pi-tui-runner suite 278/278 (main's #3582 added tests, so the count grew from 260); pi-transcript 114 pass / 3 skipped (pre-existing Windows-path guards); runtime-host-session-driver 86/86; biome check and check:asf-headers clean; core→storage→mcp→runtime→runtime-host→eval→cli build chain green.

    One note on CI: the test job failure on this head is pre-existing on main, not from this merge — apps/desktop is byte-identical to main, and the same TS2769 (workhub-dock.test.ts(99,87), enabled prop not in WorkHubDock's props) reproduces locally on a clean main checkout. It was introduced by #5938 (1de4871a6), whose own CI test job also failed.

    ggbdpq ggbdpq commented on Oct 10, 2026 15:34 UTC
    Author

    @liugddx — escalation for the merge gate on this one, since it has been stuck for three weeks on a stale review.

    The only remaining blocker is me2seeks's CHANGES_REQUESTED from 2026-09-20, filed against a127b13ed — roughly 20 commits before the current head 737f47071. Since then:

  • all 25 review threads are resolved (each with the fix SHA and reviewer endorsement quoted);

  • hqhq1025 reviewed 14 heads incrementally with zero open findings, and Astro-Han's review of the current head found nothing;

  • the review's own P1/P2 concerns were fixed and confirmed in-thread;

  • me2seeks has not returned since 09-20 and has not re-reviewed any of the 20 subsequent commits (evidence comment).
  • Could you either dismiss the stale review or review the current head? The branch has not moved since the thread clear-out, CI is green, and it is mergeable. This is one of eight PRs we are trying to land this week.

    ggbdpq ggbdpq commented on Oct 11, 2026 14:50 UTC
    Author

    All four findings from your review of 4d7764420 are addressed, via the split you asked for:

    | Finding | Resolution |
    | --- | --- |
    | P2 scope: split the retraction/switch fencing | fencing now lives in #6070 (fix/tui-switch-fencing, net diff vs main is fencing-only); this PR slimmed to the quote half (5a9623e71 — the ~1,276 fencing test lines are gone from here) |
    | P3: /new is the only re-keying path outside the switch window | fixed on #6070 (586759fc7): /new drains in-flight retractions then holds the switch window, the way /session is wrapped; regression test runs red before the fix |
    | P3: live transient row carries no quote count | a06a9e293: staged.length passes through appendUserPrompt, so a quote-only resubmit renders its quote count immediately; test traces the quote count on the live transient row of a quote-only submit red→green |
    | P3: no retractQueued coverage with non-empty quotes | 27a82ea71 adds returns retracted quotes so the TUI can restage them; the drains/blocks table-driven consolidation went to #6070 with its suites |

    Two judgment calls to flag:

    1. The quote-only side-close abort ("staged quotes were kept") stayed in this PR — it has no meaning without quote staging, and the plain-text half of that abort went to #6070. Whichever of the two PRs merges second gets rebased so both halves survive.
    2. a06a9e293 also passes the quote count through on the steering_message ack echo, which overwrites the same transient row by messageId — same bug class one hop over; say the word if you'd rather keep this PR strictly to the :1498 call site.

    Test matrix after the split (both heads): pi-tui-runner 261/261 here / 257/257 on #6070, pi-transcript 117 (114 pass / 3 skip), runtime-host-session-driver 87/87 here / 85/85 on #6070, tui-copy-catalog 8/8, check:tui-copy ok, biome clean on changed files, check:asf-headers pass.

    Ready for re-review.

    liugddx liugddx commented on Oct 11, 2026 15:44 UTC
    Contributor

    Thanks @ggbdpq, the split is exactly what I asked for, and I re-checked it at 27a82ea71. All four of my findings on 4d7764420 are resolved here or in #6070:

  • The fencing is gone from this branch.

  • The live row now gets staged.length (pi-tui-runner.ts:1459-1460).

  • The driver test covers non-empty retracted quotes.

  • /new drains and holds the switch window in #6070.
  • Both of your judgment calls are fine with me. The quote-only side-close guard belongs here. Carrying the count through the steering_message acknowledgement is the same bug class, and Astro-Han's probe confirms it.

    I'm not approving this exact head yet. It conflicts with #6070 in pi-tui-runner.ts, its tests and check-tui-copy.mjs, and the combined side-close, draft, retraction and switch paths haven't been tested together. Suggested order: land #6070 first (it only needs the AI-use declaration), then rebase this PR on it, keeping both the quote and the plain-text protections, and rerun the combined suites. I'll review and approve the rebased head.

    @me2seeks, both findings from your CHANGES_REQUESTED review on a127b13ed have since been fixed: outcome-unknown restaging (pi-tui-runner.ts, with its regression red when disabled) and the neutral N quote(s) label. Could you re-review or dismiss when you get a chance? It's the remaining blocker on this PR.

    ggbdpq ggbdpq commented on Oct 11, 2026 15:50 UTC
    Author

    @liugddx @me2seeks All findings from both rounds are addressed at 27a82ea7: the fencing split lives in #6070, and the quote count on the live row is fixed in a06a9e293. Astro-Han's re-review of this head found no new P0–P2 issue, and CI is green. The only thing still blocking the merge is the 09-20 CHANGES_REQUESTED on a127b13ed. Could you re-review, or dismiss it if you're satisfied?

    ggbdpq ggbdpq commented on Oct 11, 2026 18:30 UTC
    Author

    The combined state you asked about is rehearsed and green. I merged fix/tui-switch-fencing + fix/tui-rewind-quote-staging locally (scratch 4233ef339, not pushed — the real rebase happens after #6070 lands, per your order): both side-close protections coexist (plain-text kept-draft abort + quote-only guard, the combined form the merge base already had), the /new drain sits on top, and the combined suites pass — pi-tui-runner 280/280, runtime-host-session-driver 87/87, pi-transcript 114 pass / 3 platform skips, tui-copy-catalog 8/8, check:tui-copy / biome / check:asf-headers clean.

    One finding worth recording for the rebase: both branches are "merge base minus the other half", so a plain rebase silently drops the QuoteRef pipeline files (session-driver.ts, runtime-host-session-driver.ts, tui-copy-catalog.ts, slash-command-catalog.ts, pi-transcript.ts) with no conflict markers. The worked-out recipe restores those from the quote side and replays the two fix commits (a06a9e293, 27a82ea71) plus the /new drain; also, the fencing branch's driver-side rewind_unsupported_quotes rejection chain must yield to the quote side's restage behavior. Will execute as soon as #6070 lands.

    Reviewers
    Assignees
    ggbdpq ggbdpq
    Labels
    risk: low confidence: 89.9% reviewed
    Vouch Risk Breakdown
    AI-powered review risk analysis
    Change Risk
    Change Risk · Model 1 (XGBoost)
    Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
    Score: 66.1% (HIGH) · Higher = larger blast radius
    66.1%
    Review Confidence
    Review Confidence · Models 2 & 3
    Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
    Score: 89.9% · Lower = rushed or shallow review
    89.9%
    Residual Risk
    Residual Risk · Core Equation
    Residual = Change × (1 − Confidence)
    Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
    Score: 6.7% · Safe to merge
    6.7%
    Repository