fix(cli): stage a rewound turn's quotes into the replacement submit #5265
[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.
[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.
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.
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.
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.
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.
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
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.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.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.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.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.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.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.
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
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.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.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.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.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.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.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.
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 + failed skill invocation) restages; the retry carries the refs again.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.
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.
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 投影回本地消息)而 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」来推断。
---
已确认没问题的点
rewind_unsupported_quotes / unsupportedQuotes 残留。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 建议改中性标签。其余为已澄清项。
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).
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.
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.
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.
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.
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.
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.
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.
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:
· N quote(s) line reads like typed text.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.
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:
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.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.
[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.
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.
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.
[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.
[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.
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.
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.
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.
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.
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.
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 ([1;3A) 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.
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.
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.
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.
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:
pi-tui-runner.ts:1546 fails "does not retract the switched-to queue…".: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).
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.: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.: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:
: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./quotes clear.:1427) and the steering_message path (pi-transcript.ts:988) carry no quote count.:1462, :1496), so the quotes ride the next unrelated message.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.
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.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.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.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.
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.
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.
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.
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.
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:
detaching entry guard (pi-tui-runner.ts:1543);:1557-1577);: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:
:1557-1577). It should return quietly when there are no messages and no quotes.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.
Both findings are addressed on head 5cee83425:
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.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.
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.
[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.
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.
Both findings addressed on head 02f3e82e2 (plus a merge of latest main):
/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.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).
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.
[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.
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.
All six addressed with one mechanism — head f0b31c98e serializes session switches behind an in-flight retraction:
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).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.
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
[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.
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.
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.
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.
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.
[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.
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.
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.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).
[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.
[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.
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.
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).
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.
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.
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.
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.
Reviewed exact head bd25e82fc2044fee586c8a16660129fc88417605 (incremental from 0f26b77c). Thanks for the quick iteration. The two message-text losses from the last round are fixed:
/side now saves the recovered parent text as the parent draft and opens the side editor empty.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):
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.P3:
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.
[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.
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.
{"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)."}
{"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."}
{"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."}
{"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 |"}
[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.
@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.)
@hqhq1025 Re-review requested at head 737f47071 (merge of main 49e01b15 plus one commit).
\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).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.
@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:
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).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.
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.
@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:
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.
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.
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:
staged.length (pi-tui-runner.ts:1459-1460)./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.
@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?
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.
Astro-Han
ggbdpq
Summary
/rewindon a turn that carried quotes used to fail closed withrewind_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 onrewindToTurn, andsubmitMessageforwards quotes throughturn.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:
quotes:<n>segment while staging is live (accent salience, dropRank with the other chrome),/quoteslists the staged excerpts;/quotes clearis the explicit removal,The now-dead
rewind_unsupported_quotescode 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 cleardrops them) | 2/2 green after ||
pi-tui-runnerfull suite | 207/209 — the 2 failures (restores the terminal before exiting on SIGTERM,forces signal exit when outer cleanup never settles) fail identically on pristineupstream/mainbuilt in a clean worktree on this machine: pre-existing Windows signal-handling failures ||
runtime-host-session-driverfull suite | 25/75 — the 50 failures are all the documented pre-existing Windows class (Session cwd no longer exists: /tmpPOSIX fixtures); none of them is a test added or modified here ||
tui-copy-catalog,tui-primary-guidance, coreslash-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 passbiome check --formatter-enabled=true --linter-enabled=falseindividually, and upstream CI runs the repo-wide gate |AI use
Select exactly one:
Tool(s) and scope: GLM-5.3-Flash (ZCode) implemented the driver/TUI changes and tests under human direction and review.
Checklist
Does this PR entail a change in behavior?
/quotesis a new TUI command.