Repository navigation
fix(mobile): heal an orphaned native-chat image paste across screen unmounts - #10480
Conversation
…nmounts The stale-input marker lived in a per-screen `useRef`, but the condition it tracks — a bracketed image paste sitting unsubmitted on the agent's composer line — lives on the host and outlives the screen. Backing out of a session and returning remounted the hook with an empty Set, so the next message submitted on top of the orphaned paste and the agent received `<image path><text>`. Move the marker to a module-level store keyed by terminal handle, and consult and consume it from every write path that can submit the composer: the image hook's text-only send, the controller send (which the chat overlay's question card reaches directly, bypassing the image hook), and the ask-answer send. Permission choices and the Escape cancel deliberately do NOT heal: they are `enter: false` keys for an active overlay that swallows the clear, so healing there would consume the marker without clearing the line and leave the next real message corrupted. Desktop scopes its Ctrl+U the same way.
📝 WalkthroughWalkthroughAdds centralized per-terminal stale-input tracking and healing for mobile native chat. Attachment handling now records stale state across paste and send failures and repairs it through an empty image-path RPC request. Answer and controller send flows heal before submitting, abort on failed healing, and retain generation checks. Permission and Escape flows explicitly avoid healing. Tests cover marker isolation, healing outcomes, send failures, and recovery after screen remounts. 🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✨ Finishing Touches📝 Generate docstrings
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
|
Re the two CodeRabbit pre-merge check warnings (there were no actionable inline comments — 0 findings across all 9 files at Description check — actioned. The body now follows Docstring Coverage 30.77% vs 80% — declining, with reasoning. This one conflicts with the repo's own documented style rule in
Raising coverage to 80% here would mean adding docstrings to The commenting effort in this PR is deliberately spent where the reasoning is non-obvious rather than spread evenly for a coverage number:
Happy to add them if a maintainer prefers the threshold over the style rule — flagging the conflict rather than silently ignoring the check. |
…swers The heal ran on every ask answer, but Claude's and Codex's selector shapes cannot submit the composer: a single-select answer is a bare option digit and every stepping group is written `enter: false` (the host coerces it), so the clear is swallowed by the live overlay while the host still acks the write. That consumed the one-shot marker and left the orphaned paste to corrupt the next real message — the same failure this PR exists to fix, through a new door that main did not have. Scope the heal to the pasted-label shape, which does commit the composer. Desktop splits it the same way: use-native-chat-interactive-send.ts routes only the non-stepping answer through the clearing sender and never pre-clears sendNativeChatAskAnswer. Also pin the three deliberate skips (selector answer, permission choice, Escape cancel) with tests, so the PR's central design argument is an invariant rather than a comment, and guard the failed-heal toast with the generation check every other error surface in answerAsk already uses.
Review — deviation adjudicated (upheld), one HIGH gap found in the opposite directionReviewed with three independent subagents plus a first-hand pass. Pushed The deliberate scope call is CORRECT — do not revert itThe filed spec demanded the permission-response and Escape-cancel paths heal too. Declining that was right, and for a stronger reason than the body gives:
HIGH — the same reasoning condemned a heal the PR added (fixed in
|
There was a problem hiding this comment.
🧹 Nitpick comments (1)
mobile/src/session/use-mobile-native-chat-answer-send.ts (1)
159-166: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winCondense the repeated stale-marker rationale. Keep each as one focused sentence; the implementation and tests already establish the detailed mechanics.
mobile/src/session/use-mobile-native-chat-answer-send.ts#L159-L166: replace with a concise comment explaining that only Enter-committing pasted labels heal.mobile/src/session/use-mobile-native-chat-answer-send.test.ts#L259-L261: replace with a concise marker-retention assertion rationale.mobile/src/session/mobile-native-chat-permission-send.test.ts#L93-L95: replace with a concise permission-choice marker-retention rationale.As per coding guidelines, comments must be concise, limited to non-obvious information, and preferably one line.
Source: Coding guidelines
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID: 84370b59-a565-498a-a266-3db00536d92f
📒 Files selected for processing (5)
mobile/src/session/mobile-native-chat-permission-send.test.tsmobile/src/session/mobile-native-chat-stale-input.tsmobile/src/session/use-mobile-native-chat-answer-send.test.tsmobile/src/session/use-mobile-native-chat-answer-send.tsmobile/src/session/use-mobile-native-chat-controller.test.ts
🚧 Files skipped from review as they are similar to previous changes (2)
- mobile/src/session/mobile-native-chat-stale-input.ts
- mobile/src/session/use-mobile-native-chat-controller.test.ts
…#11035) * fix(mobile): heal a stale input line before sending diff-review notes The stale-input marker is keyed by terminal handle, not by surface, so a paste orphaned on a terminal by native chat is still marked when the user sends diff-review notes to that same terminal — and those notes were submitted on top of it. Gate the send on the heal, as the native-chat answer send already does; when the clear fails, surface the error instead of dropping the note silently. Completes a follow-up deliberately deferred by #10480. * test(mobile): assert the post-heal send carries the notes, not another clear * style(mobile): trim the stale-heal comment to its non-obvious why Keeps the terminal-handle keying and the #10228 link (why a NativeChat-named helper runs in diff review) and the deviceToken rationale; drops the clause that restated the call. Addresses CodeRabbit review feedback.
…nmounts (stablyai#10480) * fix(mobile): heal an orphaned native-chat image paste across screen unmounts The stale-input marker lived in a per-screen `useRef`, but the condition it tracks — a bracketed image paste sitting unsubmitted on the agent's composer line — lives on the host and outlives the screen. Backing out of a session and returning remounted the hook with an empty Set, so the next message submitted on top of the orphaned paste and the agent received `<image path><text>`. Move the marker to a module-level store keyed by terminal handle, and consult and consume it from every write path that can submit the composer: the image hook's text-only send, the controller send (which the chat overlay's question card reaches directly, bypassing the image hook), and the ask-answer send. Permission choices and the Escape cancel deliberately do NOT heal: they are `enter: false` keys for an active overlay that swallows the clear, so healing there would consume the marker without clearing the line and leave the next real message corrupted. Desktop scopes its Ctrl+U the same way. * fix(mobile): stop the ask heal from burning the marker on selector answers The heal ran on every ask answer, but Claude's and Codex's selector shapes cannot submit the composer: a single-select answer is a bare option digit and every stepping group is written `enter: false` (the host coerces it), so the clear is swallowed by the live overlay while the host still acks the write. That consumed the one-shot marker and left the orphaned paste to corrupt the next real message — the same failure this PR exists to fix, through a new door that main did not have. Scope the heal to the pasted-label shape, which does commit the composer. Desktop splits it the same way: use-native-chat-interactive-send.ts routes only the non-stepping answer through the clearing sender and never pre-clears sendNativeChatAskAnswer. Also pin the three deliberate skips (selector answer, permission choice, Escape cancel) with tests, so the PR's central design argument is an invariant rather than a comment, and guard the failed-heal toast with the generation check every other error surface in answerAsk already uses.
…stablyai#11035) * fix(mobile): heal a stale input line before sending diff-review notes The stale-input marker is keyed by terminal handle, not by surface, so a paste orphaned on a terminal by native chat is still marked when the user sends diff-review notes to that same terminal — and those notes were submitted on top of it. Gate the send on the heal, as the native-chat answer send already does; when the clear fails, surface the error instead of dropping the note silently. Completes a follow-up deliberately deferred by stablyai#10480. * test(mobile): assert the post-heal send carries the notes, not another clear * style(mobile): trim the stale-heal comment to its non-obvious why Keeps the terminal-handle keying and the stablyai#10228 link (why a NativeChat-named helper runs in diff review) and the deviceToken rationale; drops the clause that restated the call. Addresses CodeRabbit review feedback.
Summary
Mobile native chat marks a terminal's composer line "stale" when an image paste lands but the follow-up text+Enter never confirms, so the next send clears it with a leading Ctrl+U first. That marker was component-local React state:
mobile/src/session/use-mobile-native-chat-image-attachments.ts:113(pre-fix) —staleInputTerminalsRef = useRef(new Set<string>())The hook is per-session-screen (
mobile/app/h/[hostId]/session/[worktreeId].tsx:3623→mobile/src/session/use-mobile-session-image-attachments.ts:73), but the condition it tracks — a bracketed paste sitting unsubmitted on the agent's composer line — lives on the host and outlives the screen.Failure 1 — marker lost on unmount. Attach an image and send; the paste lands (
mobile/src/session/mobile-native-chat-image-send.ts:39-52), the text+Enter returnsunknown, so the terminal is marked stale and the chips clear. Back out of the session screen and return → the hook remounts with an emptySet→ the stale check isfalse, the healing\x15is skipped, and the agent receives<image path><text>: the image is silently re-attached and the message body corrupted. This is exactly what the in-code comment ("both must heal first") says must not happen.Failure 2 — one reader. The marker was read at exactly one site. The chat overlay wires the question card straight past the image hook that owned that read (
mobile/src/session/MobileNativeChatOverlay.tsx:51—onAnswerQuestion={controller.handleNativeChatSend}), and the ask-answer path submits its own Enter, so both could commit on top of the orphaned paste.The fix
New
mobile/src/session/mobile-native-chat-stale-input.tsowns the marker in a module-level store keyed by terminal handle — a lifetime that matches the host-side condition instead of the screen — plus a singlehealMobileNativeChatStaleInputthat clears the line and consumes the marker only once the host accepts the clear.Consulted and consumed by every write path that can submit the composer:
handleNativeChatSendWithOutcomeanswerAsk(pasted-label shape only)User-visible change: a message sent after a session screen was left and re-entered no longer silently re-attaches the previous image. If the healing clear itself is rejected, the send is refused with the existing "Message not sent" / "Answer not sent" toast rather than submitting onto a dirty line.
Deliberate scope call (deviates from the filed spec)
The task asked for permission/ask/cancel to heal too. Ask does, but only in its pasted-label shape — see the correction below. Permission choices and the Escape cancel deliberately do not, and healing them would be a regression rather than a fix: those are
enter: falsekeys for an active overlay that swallows the clear (mobile-native-chat-permission.tssends only1/y/n/a/ESC, never Enter). A Ctrl+U there would not reach the composer, yet would still consume the marker — leaving the next real message to be corrupted by the paste still sitting there. That is Failure 1 through a different door. Since these paths cannot submit the composer, a stale line cannot corrupt them, and leaving the marker armed for the next text send is strictly safer.Desktop scopes its Ctrl+U at least as narrowly:
clearUnsubmittedAgentInputis called only fromsendNativeChatMessageandsendNativeChatMessageWithImageAttachments(native-chat-runtime-send.ts:73, :166) and their cancel hooks, so approval digits and ESC bypass it entirely (use-native-chat-interactive-send.ts:74-82, :155-158). The comment atnative-chat-runtime-send.ts:33-37carves out verified option commands for a different reason (a model-switch observer can miss confirmation markers), so it is not the citation for this skip. All skips are commented in-code so they read as decisions, not oversights.Correction (review,
86f6c81982). The first version of this change healed every ask answer, on the stated premise that "both answer shapes commit with Enter." That is false for the selector shapes, and the heal was over-broad in exactly the way this section argues against: Claude's single-question single-select builds[{raw:'2'}]and Codex's builds[{raw:'1'}]— no Enter at all (src/shared/native-chat-ask.ts:211-213, :259-262; the trailingASK_ENTERis gated at:220-223on multi-question or multi-select) — and every stepping group is writtenenter: false(use-mobile-native-chat-answer-send.ts:187), which the host coerces anyway (src/main/runtime/rpc/methods/terminal.ts:1345). A bare option digit cannot submit the composer, so healing there burned the one-shot marker against the overlay where the live-overlay premise is strongest (the ask card is built from the structuredinteractivePromptand the user is tapping it), leaving the paste to corrupt the next real message. That was newly reachable in this PR — onmainthe ask path never touched the marker. The heal is now scoped to the pasted-label shape, matching desktop's split atuse-native-chat-interactive-send.ts:132-140, and the three skips (selector answer, permission choice, Escape cancel) are test-pinned so the argument is an invariant rather than a comment.Residual, stated plainly: for the multi-question / multi-select / free-text shapes that do end in a raw
\r, a stale card whose overlay already closed can still submit the composer. Desktop accepts the same risk, and the selector groups would land as literal text in that case anyway, so the line is garbage either way — but the marker now survives to clean it before the next real message. Properly fixing that belongs in card invalidation (use-mobile-native-chat-ask-dismiss.ts), not in pre-clearing.Screenshots
No visual change. This is terminal-write sequencing behind the existing composer; no UI, layout, copy, or token changes.
Testing
pnpm lint— rootnpm run lintpasses end-to-end;mobile/oxlintclean (incl.config/oxlint-react-doctor.jsonvia pre-commit) andoxfmt --checkclean.pnpm typecheck— root passes;mobile/tsc --noEmitclean.pnpm test— full mobile suite: 339 files / 2465 tests pass, 2 skipped (2462 atbb46ca226a, +3 from the review fix). The root desktop suite was not run: the change is entirely undermobile/, and the root tsconfig/vitest do not compile or includemobile/.pnpm build— not run. Electron desktop packaging is unaffected by a mobile-only change.Regression tests were verified to actually catch the bug. I stashed only the source changes while keeping the new tests, and confirmed the 5 behavior tests fail against pre-fix code and pass after:
Plus
mobile-native-chat-stale-input.test.tsunit-covers per-terminal isolation, no-write-when-unmarked, consume-on-accept, and marker retention when the clear is rejected or throws.All touched files stay under their
max-linescaps with no disable and no per-file bump — the image hook shrank 281 → 272 effective lines.AI Review Report
Reviewed by CodeRabbit (
bb46ca226a, all 9 files): no actionable comments generated — zero inline findings. Two non-code pre-merge checks were raised; the description one is actioned by this rewrite, and I've declined the 80% docstring-coverage threshold in a PR comment with reasoning, because hitting it would mean documenting three self-describing one-lineSetwrappers, whichAGENTS.md("Concise/Brief Non-obvious comments ONLY … DO NOT explain the obvious") explicitly prohibits.My own review focused on the risks specific to moving state out of React:
resetMobileNativeChatStaleInputForTests()in thebeforeEachof all three affected suites.baseSend, so the controller's new heal is a no-op there; verified by the pre-existing ride-along tests that assert exactterminal.sendcounts.pasteMobileNativeChatImagePaths→isTerminalSendRpcAcceptedpath as the old inline block, so only an explicitaccepted === trueconsumes the marker; an ambiguous ack conservatively retains it.awaitand re-checks it after, so a concurrent answer cannot double-step the selector.terminal.sendwriter undermobile/src/session/to confirm none that can submit the composer was missed.use-mobile-native-chat-stop.tssends only Escape, so it is correctly in the skip category.Cross-platform: nothing platform-dependent is touched. No
metaKey/ctrlKeyor accelerators, no shortcut labels, no filesystem paths or path separators, no shell invocation, no Electron main/renderer or IPC code, no native modules. The change is pure TypeScript in the React Native client operating on an existing RPC, so it behaves identically for macOS, Linux, and Windows hosts, and over SSH and folder workspaces as well as git worktrees (a terminal handle is opaque to this logic).Security Audit
Low risk; no new attack surface.
\x15control character sent to a terminal the user already owns and already writes to via this same path.terminal.sendrequest and the existing device-token client field; no new method, no protocol version change, no runtime-compatibility concern.imagePathslist.Notes
Residual risk and adjacent work:
awaiton persisted storage in front of every send. A persisted store keyed by handle would close it.term_<uuid>per pty), so a marker can never clear the wrong terminal, and an entry for a dead handle is inert. But it can go stale on a live handle: nothing observes the host line being cleaned out of band — the desktop user submitting or Ctrl+U-ing it themselves, or the same tab viewed as a raw terminal and submitted there. The next mobile send then fires one\x15that wipes whatever is on that line. Pre-fix this window closed on screen unmount; now it stays open, which is the cost of matching the marker's lifetime to the host-side condition. Reaping markers for handles absent from the session route's tab list would narrow it.mobile/src/session/use-mobile-diff-review-send-actions.ts:77-80submits a review prompt withenter: trueto a chosen terminal, so it can also commit on top of a stale paste. It is not a native-chat write path and does not regress with this change, but the same heal would apply.Not device-verified. No phone or paired relay was used — this reproduces the defect at the hook/controller seam with a stubbed RPC transport, not against a real agent TUI. Specifically not verified on-device: that the healing
\x15visibly clears a real Claude/Codex composer after a backgrounded-and-restored screen, and the premise above that a live permission overlay swallows Ctrl+U. Worth one manual pass: attach an image, send on a flaky connection until the send reports unconfirmed, back out of the session and return, then send a plain message and confirm no image rides along.