Skip to content

fix(mobile): serialize native chat PTY writes and fence superseded ask keystrokes (STA-3333) - #12502

Merged
brennanb2025 merged 7 commits into
mainfrom
brennanb2025/sta-3333-pty-write-lock
Aug 4, 2026
Merged

brennanb2025 merged 7 commits into
mainfrom
brennanb2025/sta-3333-pty-write-lock

Conversation

@brennanb2025

Copy link
Copy Markdown
Contributor

Summary

Split from #12373 (item 8 of the STA-3333 native-chat QA sweep) as an independent PR against main. It carries only the PTY write-serialization fix and its regression tests — no answer-UX or dismissal-state changes from that sweep.

Two composed native-chat write sequences into one PTY could interleave their bytes. The per-terminal send-in-flight guard lived in a useRef inside the image-attachments hook, so it only ever covered the composer's own clear/paste/settle/submit sequence — ask answers, permission choices, and question answers wrote straight past it. Tapping a prompt card while an image paste was mid-flight wove a keystroke into the middle of that sequence.

  • Shared write lock. The guard moves to a module-scope per-terminal lock (mobile-native-chat-terminal-write-lock.ts), now also taken by ask answers, permission responses, and question answers. Module scope for the same reason as the existing stale-input marker: the terminal outlives any one screen, and independent hooks share the same PTY. A second sender is rejected up front rather than woven in.
  • Ask answers are ordered, not raced. A superseding answer now waits for the prior chain's in-flight RPC instead of writing alongside it.
  • Superseding answers are fenced once a key has landed. An accepted — or ambiguously-delivered — keystroke has already moved the remote selector, so a replacement answer's from-scratch key plan would answer the wrong question. The successor is dropped in that case. A definitely rejected key moved nothing, so the successor proceeds normally.
  • No deadlocks. A superseding answer inherits the cancelled chain's hold (refcounted; only the last chain out releases), so changing your mind mid-answer still works. Stop/cancel deliberately stay unguarded, so an interrupt can never deadlock against the send it cancels. A hung holder is bounded by the pre-existing send budget.

User-visible effect: a card tap during a mid-flight send now reports "Answer not sent" / "Response not sent" and can simply be retried, instead of silently corrupting the agent's input line or double-stepping its selector.

Screenshots

No visual change — this is transport-ordering logic behind the existing inline send-error banner.

Testing

  • pnpm lint (oxlint root + mobile clean; changed-code quality gate: 0 new native / 0 type-aware / 0 React Doctor findings across the 9 changed files; max-lines ratchet OK, no max-lines disables added)
  • pnpm typecheck (mobile tsc --noEmit, exit 0)
  • pnpm test (mobile src/session suite: 114 files, 911 passed)
  • pnpm build — not run; no build-affecting changes (CI covers it)
  • Added or updated high-quality tests that would catch regressions

Tests added — all at the concurrency/selector-movement seams:

Test Guards
rejects an answer while another composed write holds the terminal ask answer vs. in-flight paste
rejects a choice while another composed write holds the terminal, then recovers permission choice; also asserts the hold is released on the way out
rejects a question answer while another composed write holds the terminal question answer; same release assertion
fences a superseding answer after the cancelled chain moved the selector the core selector-movement fence; also asserts both chains unwind and free the lock
does not write a successor after the prior in-flight key is accepted successor queues behind the RPC rather than racing it
does not write a successor after the prior delivery becomes ambiguous ambiguous delivery is treated as selector-moved
lets a queued successor continue after the prior key is definitely rejected negative control — the fence must not become a blanket block

Verified non-vacuous: with the source changes reverted (tests kept), 6 of the 7 fail. The 7th is the deliberate negative control, which passes before and after.

AI Review Report

Self-reviewed with focus on:

  1. Deadlock and lock-leak risk. Every acquire is paired with a release in a finally, so a throwing send cannot strand the lock. The ask path is the only refcounted holder: a superseding answer re-enters before the cancelled chain unwinds, inherits the hold, and only the last chain out releases — verified by the two tests that assert the terminal is re-acquirable after both chains settle. Stop/cancel intentionally bypass the lock so an interrupt cannot deadlock against the send it cancels.
  2. Over-fencing. The fence keys on selector movement, not on "an error happened": a definitely-rejected key wrote nothing and lets the successor through (locked by the negative-control test). Without that distinction a transient rejection would have silently swallowed the user's next answer.
  3. Scope discipline. This is item 8 only. fix(mobile): native chat QA sweep — reconnect history, stale status, prompt-card and paging fixes (STA-3333) #12373's item 7 (abort-path error copy) touches the same function and is deliberately not included here — fail() and the supersede checkpoints are left exactly as they are on main, so the two splits stay independent.
  4. Cross-platform. Explicitly checked: no keyboard shortcuts, shortcut labels, file paths, shell invocation, or Electron platform branches are touched. This is React Native transport-ordering logic, identical on iOS and Android, and agnostic of the desktop host OS — it behaves the same for native, WSL, SSH, and relay-connected hosts, and for both git-worktree and folder workspaces, because the lock is keyed on the opaque terminal handle the host already issues. No Git commands involved.

Security Audit

No new input parsing from untrusted sources, no command execution, no path handling, no auth or secret handling, and no dependency changes. The new module holds only in-memory terminal-handle strings in a module-scope Set — no persistence and no cross-user surface. The IPC/RPC surface is unchanged: no new methods, and the fix only withholds writes that would previously have been sent. Rejection messages are fixed literals, not server-echoed content. If anything the change is a net reduction in risk, since it removes a path where two senders could compose an unintended byte sequence on a PTY.

Notes

Refs STA-3333.

Two composed native-chat write sequences into one PTY interleaved their
bytes: the per-terminal send-in-flight guard lived inside the image
attachments hook, so ask answers, permission choices, and question
answers wrote straight past it. Move the guard to a shared module-scope
write lock (the terminal outlives any one screen) and take it on all
four paths.

Ask answers additionally queue behind the prior chain's RPC rather than
racing it, and a superseding answer is fenced once a key has actually
landed: an accepted or ambiguously-delivered keystroke already moved the
remote selector, so a replacement's from-scratch key plan would answer
the wrong question. A superseding answer inherits the cancelled chain's
hold (refcounted, last chain out releases) so changing your mind
mid-answer still works, and Stop/cancel stay unguarded so an interrupt
can never deadlock against the send it cancels.

Refs STA-3333.
@coderabbitai

coderabbitai Bot commented Aug 4, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

The change adds a shared per-terminal write lock for native chat operations. Permission responses, question answers, and image attachment sends now reject concurrent writes and release the lock after completion. Answer sending coordinates superseding turns, tracks predecessor delivery safety, fences unsafe successors, and preserves the lock during queued writes. Tests cover contention, recovery, fencing, delivery outcomes, accepted-action callbacks, and lock cleanup.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 33.33% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly summarizes the main change: serializing native chat PTY writes and fencing superseded ask keystrokes.
Description check ✅ Passed The description covers the required summary, screenshots, testing, AI review, security audit, and notes sections with sufficient detail.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • Create stacked PR
  • Commit on current branch

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.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

The fence added for superseding Ask answers returned false with no
onSendError, and the card re-enables on a false result — so a queued
answer vanished with no banner and no toast, looking exactly like a dead
button. Every other bail in answerAsk reports. Keep the generation-
mismatch branch silent: a newer answer owns the error surface.

Also covers the hold-count release, which had no test at all: replacing
it with an unconditional release left all 58 tests green while silently
reopening the terminal mid-sequence — the exact interleave this PR fixes.
A chain that finished its key plan reported `true` even after a newer answer
superseded it. The route sends through useNativeChatAcceptedAction, whose
accepted callback retires the send-error banner — and that callback runs after
the successor's fence report, because finishTurn() fires in `finally`, before
the chain's own promise settles. So the successful predecessor deterministically
wiped the fence message the successor had just raised: every healthy write took
that branch, which made the previous commit's report vacuous exactly where it
mattered.

A superseded chain now reports no success, matching every other supersession
checkpoint in this hook.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 1


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: cf352c4a-e9c2-41f7-9dd2-6407a3adaa71

📥 Commits

Reviewing files that changed from the base of the PR and between e9cf106 and c36f2ce.

📒 Files selected for processing (9)
  • mobile/src/session/mobile-native-chat-permission-send.test.ts
  • mobile/src/session/mobile-native-chat-permission-send.ts
  • mobile/src/session/mobile-native-chat-terminal-write-lock.ts
  • mobile/src/session/use-mobile-native-chat-answer-send.test.ts
  • mobile/src/session/use-mobile-native-chat-answer-send.ts
  • mobile/src/session/use-mobile-native-chat-image-attachments.test.ts
  • mobile/src/session/use-mobile-native-chat-image-attachments.ts
  • mobile/src/session/use-mobile-native-chat-message-send.test.ts
  • mobile/src/session/use-mobile-native-chat-message-send.ts

Comment on lines +217 to 237
// A question answer is not composer text, so it never syncs the draft. It
// reaches this send directly (not through the image hook's locked path), so
// it takes the per-terminal write lock itself: an answer landing mid-flight
// in an image paste sequence would interleave bytes into the PTY.
const answerQuestion = useCallback(
async (text: string): Promise<boolean> =>
(await sendMessage(text, undefined, false)) !== 'rejected',
[sendMessage]
async (text: string): Promise<boolean> => {
const terminal = handleRef.current
if (terminal && !acquireMobileNativeChatTerminalWrite(terminal)) {
onSendError('Answer not sent')
return false
}
try {
return (await sendMessage(text, undefined, false)) !== 'rejected'
} finally {
if (terminal) {
releaseMobileNativeChatTerminalWrite(terminal)
}
}
},
[handleRef, onSendError, sendMessage]
)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🗄️ Data Integrity & Integration | 🟠 Major | 🏗️ Heavy lift

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Find who consumes the message-send surface and whether those paths hold the lock.
set -euo pipefail

echo '--- consumers of the hook ---'
rg -nP --type=ts -C4 '\buseMobileNativeChatMessageSend\s*\(' mobile

echo '--- direct send / sendWithOutcome call sites ---'
rg -nP --type=ts -C4 '\.(send|sendWithOutcome)\s*\(' mobile/src mobile/app

echo '--- baseSend wiring (locked image path) ---'
rg -nP --type=ts -C4 '\bbaseSend\b' mobile/src mobile/app

echo '--- all lock acquisition sites ---'
rg -nP --type=ts -C3 'acquireMobileNativeChatTerminalWrite' mobile

Repository: stablyai/orca

Length of output: 50369


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo '--- relevant hook implementation lines ---'
sed -n '180,250p' 'mobile/src/session/use-mobile-native-chat-message-send.ts'

echo '--- relevant controller wiring lines ---'
sed -n '230,265p' 'mobile/src/session/use-mobile-native-chat-controller.ts'

echo '--- image hook relevant lines ---'
sed -n '250,325p' 'mobile/src/session/use-mobile-native-chat-image-attachments.ts'

echo '--- controller exports and consumers ---'
rg -NP --type=ts -C3 '\b(handleNativeChatSend|handleNativeChatSendWithOutcome|baseSend|sendNativeChat)\b' mobile/src/session/mobile src 2>/dev/null || true

echo '--- sendWithOutcome definitions in message-send file ---'
rg -NP --type=ts -C3 'sendWithOutcome|send:' 'mobile/src/session/use-mobile-native-chat-message-send.ts'

Repository: stablyai/orca

Length of output: 8296


Lock the unlocked sender surface.

sendNativeChat in use-mobile-native-chat-image-attachments.ts reaches baseSend without acquiring acquireMobileNativeChatTerminalWrite, while answerQuestion acquires the same per-terminal write lock. This leaves normal composer sends and image sends interleaved with question answers through sendMessage/terminal.send; make sendNativeChat take the lock too rather than documenting send as unlocked.

@brennanb2025

Copy link
Copy Markdown
Contributor Author

Mobile emulator QA — both ask-answer send paths exercised live

Run against this branch at c36f2ce14e on an iOS simulator ("PR 12502 QA") driven only by orca emulator tap + xcrun simctl (no Computer Use, AppleScript, or input injection), with MOCK_NATIVE_CHAT=1 serving an AskUserQuestion prompt of two single-select questions.

1. Stepping path (Claude/Codex) — paced keystroke groups

Ask card rendered, both questions answered, "Send answer" tapped.

Mock server observed exactly three writes, correctly paced ~1016 ms apart:

[mock] terminal.send mode=accept text="2"
[mock] terminal.send mode=accept text="1"
[mock] terminal.send mode=accept text="\r"

Card dismissed with no error banner — i.e. return groups.length > 0 && generationRef.current === generation resolved true on the happy path, and the new write lock / turn chain does not regress a normal answer.

pr12502-qa-01-ask-card.png
pr12502-qa-02-answers-picked.png
pr12502-qa-03-after-send.png

2. Paste path (Grok) — single composed write

Same fixture with agentType: 'grok' / launchAgent: 'grok', so shouldStepNativeChatAskAnswer routes to the pasted-label branch — the other line this PR changed.

Mock server observed exactly one write:

[mock] terminal.send mode=accept text="Staging\nNo"

Card dismissed with no error banner — the paste branch's return sent && generationRef.current === generation also resolves true when not superseded.

pr12502-30.png
pr12502-qa-11-paste-answers-picked.png
pr12502-qa-12-paste-after-send.png

Desktop regression smoke (Electron, CDP-attached)

This is a mobile-only change under mobile/src/session/, so the desktop shell is a regression smoke test rather than the changed code. Captured at 54ed019570; the later commit is mobile-only.

01-desktop-shell-boot.png
02-orca-mobile-surface.png

What remains unverified on-device

The superseded-answer case itself (a second answer landing while the first chain is mid-flight) is covered by unit tests, not by the emulator run — driving two answers inside one ~1 s pacing step is not reliably reproducible through tap automation. The four added tests cover superseded-lands on both the step and paste paths, triple-fence-reports-once, and late-third-queues-behind.

The QA-only mock fixture edit was reverted; the branch contains no test-harness or screenshot changes.

The supersession guards added in c36f2ce read `generationRef`, but
`cancelPending()` bumps that counter from three callers with no successor
chain: Stop, ask-cancel, and the lease effect that fires on every
disconnect. An answer whose key had already landed then reported false —
`fail()` never runs on an accepted write, so the card stayed up silent
with Submit re-enabled, and the retry wrote the same key into a selector
that key had already advanced.

Test the turn slot instead: a successor takes it synchronously before
its first await and cannot resolve ahead of this chain, so it means
"a successor took over" exactly, without catching bare cancellations.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🧹 Nitpick comments (1)
mobile/src/session/use-mobile-native-chat-answer-send.ts (1)

153-158: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Condense the new protocol comments.

Keep the selector-safety rationale. Replace these multi-line implementation walkthroughs with concise comments. The control flow already shows the implementation details.

As per coding guidelines, comments must be concise, limited to non-obvious information, and preferably one line.

Also applies to: 264-268, 293-293

Source: Coding guidelines


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 2ad98dd2-f69e-4d63-8ac1-479ef543733a

📥 Commits

Reviewing files that changed from the base of the PR and between c36f2ce and d101086731c373964696374ccaf11ab4c65ea905.

📒 Files selected for processing (2)
  • mobile/src/session/use-mobile-native-chat-answer-send.test.ts
  • mobile/src/session/use-mobile-native-chat-answer-send.ts
🚧 Files skipped from review as they are similar to previous changes (1)
  • mobile/src/session/use-mobile-native-chat-answer-send.test.ts

Comment on lines +136 to +151
// eslint-disable-next-line no-console
console.log('[PROBE] chain start gen=', generation)
let sawUnknownOutcome = false
let sawAcceptedGroup = false
// One budget for the whole answer instead of a fresh timeout per keystroke
// group, which let an N-group selector hold the card for N × the send timeout.
// It bounds transport time only: each deliberate pacing wait is credited back
// below, so a long multi-question answer still gets a full budget to write in.
let deadline = openMobileNativeChatSendBudget()
const sendTerminal = async (body: string, enter: boolean): Promise<boolean> => {
const activeRoute = activeRouteRef.current
if (
!activeRoute.enabled ||
activeRoute.client !== client ||
activeRoute.sessionId !== sessionId ||
activeRoute.streamIdentity !== streamIdentity ||
handleRef.current !== handle
) {
let predecessorSafe = true
try {
predecessorSafe = await previousTurn
// eslint-disable-next-line no-console
console.log(
'[PROBE] chain gen=',
generation,
'resumed predecessorSafe=',
predecessorSafe,
'current=',
generationRef.current
)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win

Remove the probe logging.

These console.log calls run for every answer chain. They add production log noise and require no-console suppression. Remove them before release.

…neration

The fence-report guard tested generationRef, which answers "was I
cancelled", not "did a successor replace me". Stop and ask-cancel both
write an Escape that clears the ask card, so their silence is harmless.
A dropped input lease bumps the same counter and writes nothing: the
card stays up with Submit re-enabled while the predecessor's option key
has already advanced the live selector, so the retry double-steps it.

Gate on the turn slot, matching the two success returns.
@brennanb2025
brennanb2025 force-pushed the brennanb2025/sta-3333-pty-write-lock branch from d101086 to b277516 Compare August 4, 2026 11:03
@brennanb2025

Copy link
Copy Markdown
Contributor Author

Review rounds 3 & 4 — two more blockers found and fixed

Follow-up to the QA comment above. Review continued past that comment and found two further defects, both in the same class as rounds 1–2 (a write that actually landed reported as a plain false, which is silent — the card re-enables and the retry double-steps a selector that already moved).

Correction to the QA comment above

That comment quotes the guard expression as it stood at 54ed0195. It has since changed, so two lines in it are now stale:

  • Line 17 — return groups.length > 0 && generationRef.current === generation
  • Line 33 — return sent && generationRef.current === generation

Both now read … && writeTurnsRef.current.get(handle) === turn. The observed QA behaviour in that comment is unaffected — both expressions resolve true on the un-superseded happy path it exercised — but the quoted source is not current. Reason for the change is round 3 below.

Round 3 — 14d0a16b — the generation counter is not a supersession signal

The two success returns fenced on generationRef.current === generation. That counter answers "was I cancelled", never "did a successor replace me" — and cancelPending() has three callers that create no successor chain:

Caller Bumps generation Writes an Escape (clears the ask card)
use-mobile-native-chat-stop.ts:49 (Stop) ✅ ✅
use-mobile-native-chat-cancel-ask.ts:24 (cancel ask) ✅ ✅
the hook's own effect, deps [client, enabled, sessionId, streamIdentity] ✅ ❌ nothing

So an answer that was fully accepted and then hit Stop returned false — a landed write reported as a failure, with no banner, because fail() only runs when the send itself failed.

The correct discriminator is the turn slot: writeTurnsRef.current.get(handle) === turn. A successor claims that slot synchronously, before its first await (:132), and can never resolve ahead of this chain — it awaits this chain's turn, which resolves in this chain's finally. The test is exact where the counter is only correlated.

Round 4 — b277516d — the same confusion one branch up, on the fence-report path

The !predecessorSafe branch guarded its onSendError('Answer not sent — check chat before retrying') with the same generation test. I initially cleared this as a non-defect by reasoning "Stop writes an Escape, which clears the ask card, so suppressing the banner is correct." That is true for Stop and for cancel-ask. It is false for the third caller — the lease-drop effect writes nothing.

Concretely: a transport blip drops enabled, the generation bumps, the ask card stays up with Submit re-enabled, and a queued answer whose predecessor's option key already landed goes completely silent. The re-tap writes the same option digit into a selector that key already advanced.

Same one-line cure, same discriminator:

if (writeTurnsRef.current.get(handle) === turn) {
  onSendError('Answer not sent — check chat before retrying')
}

Known tradeoff, stated deliberately: the fix cannot separate Stop from a lease drop (both are non-successor bumps with the slot intact), so Stop now also shows the banner. The message is literally true in that case — the predecessor's keys may well have landed — so it is the right side to err on.

Evidence

Both fixes are proven non-vacuous by mutation, each mutation applied on a scratch copy and reverted:

Mutation Tests killed
M1 — :259+:283 back to the generation guard exactly the 2 Stop-with-no-successor tests (28 pass)
M2 — :259+:283 guards deleted exactly the 4 fence tests (26 pass)
M3 — :148 back to the generation guard exactly the new lease-drop test (30 pass)
M4 — :148 → true exactly fences a third answer behind an already-fenced successor, reporting once (30 pass)

Disjoint kill sets, each matching the defect its guard addresses.

Gates at b277516d: use-mobile-native-chat-answer-send 31/31; full mobile session suite 920/920 across 114 files; tsc, oxlint, code-quality native plugins, React Doctor changed-lines, oxfmt all exit 0; CI green (42 pass, 1 skipping).

Lock-hold audit (no perf regression): all four acquire sites — mobile-native-chat-permission-send.ts:45, use-mobile-native-chat-image-attachments.ts:228, use-mobile-native-chat-message-send.ts:224, use-mobile-native-chat-answer-send.ts:122 — acquire immediately before a try/finally release and bail before acquiring, so the hold count balances. One chain's worst-case hold is bounded at the 15s shared transport budget (MIN_WRITE_TIMEOUT_MS returns 'rejected' rather than restarting the clock on an exhausted budget) plus 1s per inter-group pacing gap. A chain that accepted any group fences its successor, so queued chains add ~0 to the hold.

QA staleness — please read before merging

The screenshots and QA notes in the comment above were captured at c36f2ce14e (mobile) and 54ed019570 (desktop). Neither includes rounds 3 or 4. Those two commits are covered by unit tests plus the mutation matrix above, not by re-run device QA — both fixes are one-line guard swaps on paths that need a queued-answer race against a dropped input lease, which is not reliably reachable by hand on a device. I'd rather say that plainly than imply the screenshots cover the current head.

Residual, not fixed here (follow-up)

The send-error banner is scoped per tab (mobileNativeChatScopeKey(hostId, worktreeId, tabId) — no handle component), while the fence is scoped per terminal handle. A fenced answer's banner can therefore be attributed to the wrong scope if the handle changes under a stable tab.

Deliberately left alone: pre-PR there is no fence on that path at all, so this is not a regression this PR introduces. The obvious fix — adding the handle to the scope key — churns the scope null → handle on tab open and blanks pending-handle banners, trading a narrow race for a broader one in the same silent-loss class, and it edits the session route (scope creep against this PR's stated bounds). The in-file alternative (testing handleRef.current === handle in the success returns) reintroduces a silent false on the handle-change path that two existing tests specifically protect.

Scope note: this PR remains limited to (a) native-chat PTY write serialization/ordering and (b) fencing unsafe queued/superseding ask keystrokes. Partial-answer abort UX is #12503 and ask-dismissal state is #12497; neither is touched here.

The slot delete in the finally was the one line in this hook no test
killed: without it a landed answer's resolved-false turn stays parked,
so every later answer on that handle reads a fenced predecessor and the
ask card dies after its first use.
@brennanb2025

Copy link
Copy Markdown
Contributor Author

Round 5 — 57a06d06 — the one line in this hook no test was holding

Review continued past the comment above and found a coverage hole with total consequences. Not a code defect — the guard is correct as written — but nothing in the suite was standing behind it.

use-mobile-native-chat-answer-send.ts:288-290, the turn-slot release in the finally:

if (writeTurnsRef.current.get(handle) === turn) {
  writeTurnsRef.current.delete(handle)
}

Delete those three lines and the entire mobile suite stays green (3027 tests, exit 0). It was the only surviving mutation out of 13 run against this file. What it protects against:

  1. A successful answer ends with sawAcceptedGroup === true, so finishTurn(false) at :287 parks a resolved-false promise in writeTurnsRef. That is correct — a queued successor must be fenced, because accepted keys already moved the live selector.
  2. Without the delete, that promise outlives the chain that owned it. The next unrelated answer reads predecessorSafe === false at :140, writes nothing, and reports Answer not sent — check chat before retrying at :149 — the slot check passes, since the new chain installed its own turn at :132.
  3. Permanently. Every answer after the first is dead for the life of the hook instance, on the ask card that is this PR's entire subject.

Why the existing 31 missed it: every multi-answer test drives overlapping chains — the second call is issued before the first settles, so it reads a pending turn, never a parked one. The only two sequential answerAsk calls in the file are at :421 and :427, and the first bails at the lock check (:122) before it ever touches writeTurnsRef. So no test drove two completed sequential answers.

Now covered by answers again on the same handle after an earlier answer already landed.

Verified rather than assumed: the test passes at head (32/32); applying the mutation in place under a git hash-object guard kills exactly that one test, with the other 31 green; the source was then restored via git checkout HEAD -- and asserted byte-identical to blob b893f7ae.

Gates at 57a06d06: 32/32 answer-send, 921/921 across 114 session files, tsc / oxlint / code-quality native plugins / React Doctor / oxfmt all exit 0.

Independent confirmation of the lock side (scope (a))

A second reviewer attacked serialization directly and found no defect. All four composed-write paths acquire before their try and release in a finally, and none releases a hold it failed to take (every acquire-failure branch returns before the try): use-mobile-native-chat-answer-send.ts:122/:296, mobile-native-chat-permission-send.ts:45/:61, use-mobile-native-chat-message-send.ts:224/:232, use-mobile-native-chat-image-attachments.ts:228/:352. The composer's plain-text send is not an unlocked fifth path — sendWithOutcome has one consumer, nativeChatBaseSend at [worktreeId].tsx:3692, which feeds the locked sendNativeChat, and correctly does not re-acquire inside (that would deadlock the non-reentrant Set). Stop (use-mobile-native-chat-stop.ts:98) is deliberately unlocked — it must be able to interrupt a mid-flight write.

A 13-scenario leak battery (plain success, rejected send, throwing send, 2- and 3-deep supersession, unmount / lease-drop / handle-change / Stop mid-flight, foreign-holder rejection, both early returns, plus a 40-trial fuzz at depth 1–3) ends with the lock free in every case. Mutating remaining <= 0 to remaining < 0 kills 10 of 13. Notably, mutating const remaining = (holds.get(handle) ?? 1) - 1 to 0 — first chain out frees the lock while its successor is still writing — survives that whole battery and is killed only by this PR's own keeps the terminal locked while a queued successor writes. The shared-hold refcount is the subtlest new logic here and it is genuinely pinned.

Suite also re-run shuffled (--sequence.shuffle.files --sequence.shuffle.tests) with no order dependence.

Worth a separate ticket: no-console is not configured anywhere

Surfaced by an incident during this review — two console.log('[PROBE]', …) lines were committed to this branch and CI went fully green over them (42 pass).

The cause is not that the disable comments were honored. no-console is configured nowhere in this repo — not .oxlintrc.json, not mobile/.oxlintrc.json, not any config/oxlint-*.json, and no custom plugin. I verified empirically: appending a bare console.log with no disable comment to a tracked module still gives npx oxlint exit 0 and npx oxlint -c config/oxlint-code-quality-native-plugins.json --deny-warnings exit 0.

So debug logging currently passes every gate and ships. Out of scope for this PR — flagging it as a follow-up, not fixing it here.

Follow-ups recorded, deliberately not fixed in this PR

  • use-mobile-diff-review-send-actions.ts:80-83 does a composed heal + terminal.send into a terminal handle with no write lock — the same interleaving hazard this PR exists to prevent. Pre-existing, different surface, and fixing it means editing a file outside this PR's touched set.
  • The per-tab banner scope vs per-handle fence residual, as described in the previous comment. Unchanged.
  • no-console above.

Scope is unchanged: (a) native-chat PTY write serialization/ordering and (b) fencing unsafe queued/superseding ask keystrokes. Nothing here touches partial-answer abort UX (#12503) or ask-dismissal state (#12497).

@brennanb2025

Copy link
Copy Markdown
Contributor Author

Review closed — final state

Head 57a06d0669. CI fully green: 42 SUCCESS, 1 SKIPPED, zero non-pass. Five rounds, five findings, all fixed and mutation-verified.

Commit Fix
c5ccd756 (original) serialize native-chat PTY writes
54ed0195 report a fenced answer instead of dropping it silently
c36f2ce1 a superseded answer must not clear the fence banner
14d0a16b fence on the turn slot, not the generation counter
b277516d same swap on the fence-report guard (dropped-lease path)
57a06d06 cover the turn-slot release after a landed answer

The fence is one-shot — worth stating explicitly

"Reports exactly once" was verified at 2-deep, 3-deep simultaneous, 4-deep, and late-third. But the simultaneous and late-third cases get there by different mechanisms, and the distinction matters for anyone reading this code later:

  • Simultaneous: C already owns the turn slot when B resumes, so B is suppressed and C reports.
  • Late third: B resumes and reports first, and its finally deletes the slot it owns (:288-290). C then arrives with previousTurn defaulting to Promise.resolve(true) — C is not a fenced chain at all. It writes its key and resolves true.

That is by design. The fence is scoped to chains already queued behind the unsafe write — those composed their key plan against pre-supersession state. A later tap is a deliberate re-answer after the banner said "check chat," and the card intentionally re-enables on a false result. It is also exactly what 57a06d06 protects: without the slot delete, that later tap would be fenced forever and the card would die after its first use.

So: the fence does not persist across later taps, and nothing in this PR claims it does.

Areas checked with nothing found

  • SSH / relay hosts. No host-type coupling in any added line. The lock keys on the terminal-handle string, which is host-agnostic, and the send already passes budgetSpansConnect: true so a reconnect wait is charged inside the one shared budget rather than starting a fresh clock.
  • Folder workspaces. No git-specific assumption in the changed code — streamIdentity and the scope key carry a worktreeId that is simply the workspace id for a folder workspace. Nothing here reads git state.
  • Reconnect, enabled false → true. cancelPending() fires on the false transition and again as effect cleanup. Any in-flight chain still unwinds through its finally, because pacing waits are resolved by cancelPending and every send carries a deadline — so both the write lock and the turn slot are released. No stale slot survives a reconnect.

One real issue found here, correctly belonging to #12503

Tracing the reconnect path surfaced a genuine silent-loss hole, and it is not this PR's to fix:

In the stepping loop, a dropped lease mid-sequence makes sendTerminal return false (the activeRoute.enabled check), which calls fail() — and fail() gates its onSendError on generationRef.current === generation. The lease drop already bumped the generation, so nothing is reported. A multi-question answer whose first group landed goes silent, the card stays up (a lease drop writes no Escape), and the retry double-steps the selector.

Same class as round 4, different line. Two reasons it is not fixed here:

  1. It is pre-existing. fail() is byte-identical at the merge-base e9cf106769 — this PR does not touch it.
  2. It is fix(mobile): report a partly-sent ask answer honestly (STA-3333) #12503's scope. The string it suppresses is 'Answer partly sent — check chat before retrying', and fix(mobile): report a partly-sent ask answer honestly (STA-3333) #12503 is "fix(mobile): report a partly-sent ask answer honestly (STA-3333)." Fixing it here would widen this PR into the partial-answer reporting split.

Flagging for #12503 rather than fixing.

QA coverage — more precise than my earlier note

I understated this above. Correcting:

  • Desktop QA at 54ed0195 still covers head. git diff --name-only 54ed019570..HEAD returns only the two mobile/src/session/ files — no file outside mobile/ has changed in the entire branch since that run. The desktop shell is untouched, so that regression smoke test's validity is unaffected.
  • Mobile QA at c36f2ce1 covers everything except the rounds 4–5 lines. Those are a one-line guard swap plus a test-only commit. The guard path needs a queued-answer race against a dropped input lease, which is not reliably reachable by hand on a device — unit tests plus the mutation matrix are the real evidence there, and I would rather say that than imply the screenshots cover it.

Follow-ups recorded, deliberately not fixed here

  1. fail() silent on a dropped lease mid-sequence — fix(mobile): report a partly-sent ask answer honestly (STA-3333) #12503, per above.
  2. use-mobile-diff-review-send-actions.ts:80-83 — composed heal + terminal.send into a terminal handle with no write lock, the same interleaving hazard this PR exists to prevent. Pre-existing, different surface.
  3. no-console is configured nowhere in the repo, so debug logging passes every gate and ships. Verified empirically: a bare console.log in a tracked module still gives oxlint exit 0 and the code-quality gate exit 0.
  4. The per-tab banner scope vs per-handle fence residual, unchanged from the earlier comment.

Scope is unchanged and intact: (a) native-chat PTY write serialization/ordering, (b) fencing unsafe queued/superseding ask keystrokes. Nothing here touches partial-answer abort UX (#12503) or ask-dismissal state (#12497).

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 1


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 5b2f9c3b-1b5b-4892-bfa7-99085fa940bc

📥 Commits

Reviewing files that changed from the base of the PR and between b277516 and 0a24423.

📒 Files selected for processing (2)
  • mobile/src/session/mobile-native-chat-terminal-write-lock.test.ts
  • mobile/src/session/use-mobile-native-chat-answer-send.test.ts
🚧 Files skipped from review as they are similar to previous changes (1)
  • mobile/src/session/use-mobile-native-chat-answer-send.test.ts

} from './mobile-native-chat-terminal-write-lock'

describe('mobile-native-chat-terminal-write-lock', () => {
afterEach(resetMobileNativeChatTerminalWritesForTests)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win

Assert that released terminals can be acquired again.

The test calls releaseMobileNativeChatTerminalWrite but does not check its effect. The afterEach reset clears the state after the test, so a broken release implementation can pass. Add an acquisition assertion after each release, then release the new holds.

Proposed test adjustment
     releaseMobileNativeChatTerminalWrite('terminal-a')
     releaseMobileNativeChatTerminalWrite('terminal-b')
+    expect(acquireMobileNativeChatTerminalWrite('terminal-a')).toBe(true)
+    expect(acquireMobileNativeChatTerminalWrite('terminal-b')).toBe(true)
+    releaseMobileNativeChatTerminalWrite('terminal-a')
+    releaseMobileNativeChatTerminalWrite('terminal-b')

Also applies to: 17-18

@brennanb2025

Copy link
Copy Markdown
Contributor Author

Final clean review + current-head QA

Reviewed and validated at 0a24423626.

  • Same-model, same-effort follow-up review returned CLEAN after adding the terminal-isolation regression test. The new test proves terminal B remains writable while terminal A holds its lock; no product scope was added.
  • Focused tests: 69/69 passed. Mobile typecheck, lint, and format passed; changed-code quality reported 0 findings.
  • GitHub CI is green across Mobile Checks and all PR Checks.
  • Reliability invariant: composed writes to the same terminal never overlap, while different terminals remain concurrent. There is no exact reliability-manifest entry for this invariant; that is an accepted evidence gap backed by deterministic focused tests.
  • Performance audit: lock state uses O(1) Set/Map operations, with no scans or polling, and waiting remains bounded by the existing send budget.

Electron regression smoke

Validated through Electron CDP at the current head.

Electron mobile surface

iOS current-head QA

The ask card rendered, accepted both selections, and dismissed without an error/redbox after Send. The mock observed the exact paced writes "1", "1", "\r".

Ask card
Selections
After send

@brennanb2025
brennanb2025 merged commit d27d69f into main Aug 4, 2026
43 checks passed
brennanb2025 pushed a commit that referenced this pull request Sep 7, 2026
Takes main's side across the whole tree. The PR's FIFO stop lease, writer
gate, controller-writer plumbing and module-level cleanup-retry map are
obsolete: #12502 landed mobile-native-chat-terminal-write-lock.ts, which
already serializes writer-vs-writer per terminal. Only the Codex /stop leg
survives, and it is written fresh on main's structure in the next commit.
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
…k keystrokes (STA-3333) (stablyai#12502)

* fix(mobile): serialize native chat PTY writes

Two composed native-chat write sequences into one PTY interleaved their
bytes: the per-terminal send-in-flight guard lived inside the image
attachments hook, so ask answers, permission choices, and question
answers wrote straight past it. Move the guard to a shared module-scope
write lock (the terminal outlives any one screen) and take it on all
four paths.

Ask answers additionally queue behind the prior chain's RPC rather than
racing it, and a superseding answer is fenced once a key has actually
landed: an accepted or ambiguously-delivered keystroke already moved the
remote selector, so a replacement's from-scratch key plan would answer
the wrong question. A superseding answer inherits the cancelled chain's
hold (refcounted, last chain out releases) so changing your mind
mid-answer still works, and Stop/cancel stay unguarded so an interrupt
can never deadlock against the send it cancels.

Refs STA-3333.

* fix(mobile): report a fenced native-chat answer instead of dropping it

The fence added for superseding Ask answers returned false with no
onSendError, and the card re-enables on a false result — so a queued
answer vanished with no banner and no toast, looking exactly like a dead
button. Every other bail in answerAsk reports. Keep the generation-
mismatch branch silent: a newer answer owns the error surface.

Also covers the hold-count release, which had no test at all: replacing
it with an unconditional release left all 58 tests green while silently
reopening the terminal mid-sequence — the exact interleave this PR fixes.

* fix(mobile): stop a superseded answer from clearing the fence banner

A chain that finished its key plan reported `true` even after a newer answer
superseded it. The route sends through useNativeChatAcceptedAction, whose
accepted callback retires the send-error banner — and that callback runs after
the successor's fence report, because finishTurn() fires in `finally`, before
the chain's own promise settles. So the successful predecessor deterministically
wiped the fence message the successor had just raised: every healthy write took
that branch, which made the previous commit's report vacuous exactly where it
mattered.

A superseded chain now reports no success, matching every other supersession
checkpoint in this hook.

* fix(mobile): fence on the turn slot, not the generation counter

The supersession guards added in c36f2ce read `generationRef`, but
`cancelPending()` bumps that counter from three callers with no successor
chain: Stop, ask-cancel, and the lease effect that fires on every
disconnect. An answer whose key had already landed then reported false —
`fail()` never runs on an accepted write, so the card stayed up silent
with Submit re-enabled, and the retry wrote the same key into a selector
that key had already advanced.

Test the turn slot instead: a successor takes it synchronously before
its first await and cannot resolve ahead of this chain, so it means
"a successor took over" exactly, without catching bare cancellations.

* fix(mobile): report a fenced answer when a dropped lease bumps the generation

The fence-report guard tested generationRef, which answers "was I
cancelled", not "did a successor replace me". Stop and ask-cancel both
write an Escape that clears the ask card, so their silence is harmless.
A dropped input lease bumps the same counter and writes nothing: the
card stays up with Submit re-enabled while the predecessor's option key
has already advanced the live selector, so the retry double-steps it.

Gate on the turn slot, matching the two success returns.

* test(mobile): cover the turn-slot release after a landed answer

The slot delete in the finally was the one line in this hook no test
killed: without it a landed answer's resolved-false turn stays parked,
so every later answer on that handle reads a fenced predecessor and the
ask card dies after its first use.

* test(mobile): keep PTY write locks terminal-scoped
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant