Repository navigation
fix(mobile): stop Codex background terminals from native chat - #11988
brennanb2025 wants to merge 7 commits into
Conversation
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Repository UI Review profile: CHILL Plan: Team Run ID: 📒 Files selected for processing (5)
🚧 Files skipped from review as they are similar to previous changes (1)
Included review availability: Your plan provides up to 10 included reviews per hour; 3 remain after this review. 📝 WalkthroughWalkthroughThe mobile native-chat Stop flow now receives the active agent reference and a Codex background-terminal cleanup callback. Codex cleanup dispatches Merge Risk: ⚪ Minimal · up to Mobile native-chat Stop now sends Codex /stop cleanup only after an accepted interrupt on a live Codex route, while preserving other agents’ behavior. The covered cleanup and failure-reporting paths leave no actionable current-head merge risk. 🚥 Pre-merge checks | ✅ 3 | ❌ 2❌ Failed checks (2 warnings)
✅ Passed checks (3 passed)
Full details: Description checkExplanation The description explains the change, rationale, scope, implementation, limitations, and testing in detail. However, it omits required template sections, including the Linked Issue, Visual Proof or an explicit N/A statement, AI Disclosure, Review, Agent skill upstream boundary, Notes, and checklist confirmations. Resolution Add the required template sections. Provide a linked issue after “Fixes #”, add before-and-after visual proof or write “N/A” with a reason, complete the AI Disclosure when applicable, address Review and Agent skill upstream boundary, document the requested compatibility and performance considerations, and confirm the checklist items.
✨ Finishing Touches 💡 1📝 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 |
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (1)
mobile/src/session/use-mobile-native-chat-stop.test.ts (1)
229-245: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winAdd coverage for the remaining stop error branches.
This test covers the
'rejected'cleanup outcome. Two other new branches inuse-mobile-native-chat-stop.tsstay uncovered:
- The
'unknown'cleanup outcome at line 143, which reports "Stop unconfirmed — check chat before retrying". MakesendRequestreject the/stopcall with a delivery-unknown error to reach it.- A rejected second Escape. This branch decides whether
/stopcleanup runs at all, so it pairs with the gating concern raised onuse-mobile-native-chat-stop.tslines 125-137.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID: 2c066bab-4f2b-4403-956e-8f9efedd4b9a
📒 Files selected for processing (3)
mobile/src/session/use-mobile-native-chat-controller.tsmobile/src/session/use-mobile-native-chat-stop.test.tsmobile/src/session/use-mobile-native-chat-stop.ts
| if (!escapes.includes('accepted')) { | ||
| // An ambiguous Escape may have landed; a definite failure would invite | ||
| // a retry into changed prompt state. | ||
| onSendError( | ||
| escapes.includes('unknown') | ||
| ? 'Stop unconfirmed — check chat before retrying' | ||
| : 'Stop not sent' | ||
| ) | ||
| .then((response) => { | ||
| if (isTerminalSendRpcAccepted(response)) { | ||
| sawAccepted = true | ||
| } else { | ||
| sawRejected = true | ||
| } | ||
| }) | ||
| // Why: disconnect can race either fire-and-forget Escape; record one verdict | ||
| // instead of leaking an unhandled RPC rejection. | ||
| .catch((error: unknown) => { | ||
| if (isRpcDeliveryUnknown(error) || isLogicalClientCutoverError(error)) { | ||
| sawUnknown = true | ||
| } else { | ||
| sawRejected = true | ||
| } | ||
| }) | ||
| .finally(() => { | ||
| pending -= 1 | ||
| reportIfSettled() | ||
| }) | ||
| } | ||
| sendEscape() | ||
| dropSecondEscapeRef.current = () => { | ||
| pending -= 1 | ||
| reportIfSettled() | ||
| } | ||
| // Why: two paced Escape bytes reliably stop TUIs without remote coalescing. | ||
| timerRef.current = setTimeout(() => { | ||
| timerRef.current = null | ||
| dropSecondEscapeRef.current = null | ||
| sendEscape() | ||
| pending -= 1 | ||
| reportIfSettled() | ||
| }, 80) | ||
| return | ||
| } | ||
| if (agent !== 'codex' || !(await waitForNextStep())) { | ||
| return | ||
| } |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟠 Major | ⚡ Quick win
Require both Escape writes to be acknowledged before /stop cleanup.
Line 125 proceeds when at least one Escape is 'accepted'. The second Escape can be 'rejected' while the flow continues silently. Codex needs two Escapes to interrupt the turn. If the second Escape never lands, the turn stays active and /stop is typed into a busy TUI as ordinary chat input.
The PR objective states that two acknowledged, paced Escape writes interrupt the conversation. Align the code with that contract, and report the partial failure so the user can retry.
🐛 Proposed fix to gate cleanup on both Escape acknowledgements
const escapes = outcomes as MobileNativeChatSendOutcome[]
- if (!escapes.includes('accepted')) {
+ if (!escapes.every((outcome) => outcome === 'accepted')) {
// An ambiguous Escape may have landed; a definite failure would invite
// a retry into changed prompt state.
onSendError(
escapes.includes('unknown')
? 'Stop unconfirmed — check chat before retrying'
: 'Stop not sent'
)
return
}📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| if (!escapes.includes('accepted')) { | |
| // An ambiguous Escape may have landed; a definite failure would invite | |
| // a retry into changed prompt state. | |
| onSendError( | |
| escapes.includes('unknown') | |
| ? 'Stop unconfirmed — check chat before retrying' | |
| : 'Stop not sent' | |
| ) | |
| .then((response) => { | |
| if (isTerminalSendRpcAccepted(response)) { | |
| sawAccepted = true | |
| } else { | |
| sawRejected = true | |
| } | |
| }) | |
| // Why: disconnect can race either fire-and-forget Escape; record one verdict | |
| // instead of leaking an unhandled RPC rejection. | |
| .catch((error: unknown) => { | |
| if (isRpcDeliveryUnknown(error) || isLogicalClientCutoverError(error)) { | |
| sawUnknown = true | |
| } else { | |
| sawRejected = true | |
| } | |
| }) | |
| .finally(() => { | |
| pending -= 1 | |
| reportIfSettled() | |
| }) | |
| } | |
| sendEscape() | |
| dropSecondEscapeRef.current = () => { | |
| pending -= 1 | |
| reportIfSettled() | |
| } | |
| // Why: two paced Escape bytes reliably stop TUIs without remote coalescing. | |
| timerRef.current = setTimeout(() => { | |
| timerRef.current = null | |
| dropSecondEscapeRef.current = null | |
| sendEscape() | |
| pending -= 1 | |
| reportIfSettled() | |
| }, 80) | |
| return | |
| } | |
| if (agent !== 'codex' || !(await waitForNextStep())) { | |
| return | |
| } | |
| if (!escapes.includes('accepted')) { | |
| // An ambiguous Escape may have landed; a definite failure would invite | |
| // a retry into changed prompt state. | |
| onSendError( | |
| escapes.includes('unknown') | |
| ? 'Stop unconfirmed — check chat before retrying' | |
| : 'Stop not sent' | |
| ) | |
| return | |
| } | |
| if (agent !== 'codex' || !(await waitForNextStep())) { | |
| return | |
| } |
Greptile SummaryThis PR introduces a per-terminal stop-lease system to eliminate PTY write-ordering races in the mobile native-chat Stop flow. A new
Confidence Score: 5/5The change is safe to merge. The new lease system is well-isolated, covers all identified interleaving scenarios with explicit tests, and the fallback paths (rejected/unknown cleanup, route change, unmount) are all handled. All changed paths are covered by dedicated unit and integration tests. The core lease primitives (priority ordering, stale-token release, per-terminal isolation) are verified end-to-end. No existing behavior for Claude or non-Codex agents is altered. The module-level cleanup map concern is minor and bounded in practice. Files Needing Attention: mobile/src/session/mobile-native-chat-stop-cleanup.ts — the module-level
|
| Filename | Overview |
|---|---|
| mobile/src/session/mobile-native-chat-stop-lease.ts | New priority-queue lease system; token-checked release prevents stale releases from retiring successors. Logic is correct and well-tested. |
| mobile/src/session/use-mobile-native-chat-stop.ts | Stop handler rewritten to own the full interrupt+cleanup sequence under a lease; recovery path correctly handles busy/none/rejected/unknown outcomes with distinct error messages. |
| mobile/src/session/mobile-native-chat-stop-cleanup.ts | Module-level map persists pending cleanup across remounts; entries keyed by streamIdentity are deleted on non-rejected outcome but have no automatic eviction if the stream is never revisited. |
| mobile/src/session/use-mobile-native-chat-writer-gate.ts | New gate hook wraps every controller write path; cancels queued requests on route change and credits waited time back into the caller's deadline via the owner parameter. |
| mobile/src/session/use-mobile-native-chat-controller-writers.ts | Clean extraction of writer wiring from the controller; all writes now flow through the shared gate. Exposes runWrite for callers that need multi-step lease ownership. |
| mobile/src/session/use-mobile-native-chat-image-attachments.ts | Image send now enters the writer gate before paste+submit, shares one budget, and correctly credits stop-wait time back to the text-submit leg. |
| mobile/src/session/use-mobile-native-chat-controller.ts | Controller updated to wire agentRef and sessionId into Stop, route writers through the new gate, and expose runNativeChatWrite for image attachments. |
| mobile/src/session/mobile-native-chat-stop-lease.test.ts | Comprehensive lease unit tests covering priority ordering, per-terminal isolation, stale-token release, and cancel-without-starvation. |
| mobile/src/session/use-mobile-native-chat-controller-stop.test.ts | Integration tests cover writer queuing, FIFO ordering, rejected cleanup, route/session replacement, unmount, deadline credit, and duplicate Stop suppression. |
Sequence Diagram
sequenceDiagram
participant UI as UI (Stop tap)
participant SH as useMobileNativeChatStop
participant LS as StopLeaseQueue
participant WG as WriterGate (pending writes)
participant PTY as PTY / sendMobileNativeChatMessage
participant CL as StopCleanupMap
UI->>SH: handleNativeChatStop()
SH->>CL: hasMobileNativeChatStopCleanup(stream)?
alt pending cleanup exists
SH->>SH: recoverPendingCleanup()
else normal stop
SH->>LS: requestMobileNativeChatStopLease(terminal)
alt stop already pending/active
LS-->>SH: null (duplicate suppressed)
else lease granted after active write settles
LS-->>SH: lease acquired
SH->>PTY: ESC (first)
SH->>PTY: ESC (second, same budget)
PTY-->>SH: accepted
alt "agent === codex"
SH->>PTY: /stop (fresh budget)
PTY-->>SH: accepted / rejected / unknown
alt rejected
SH->>CL: rememberMobileNativeChatStopCleanup()
SH-->>UI: error: cleanup pending
else unknown
SH-->>UI: error: cleanup unconfirmed
end
end
SH->>LS: lease.release()
LS->>WG: grantNext() — queued writers resume FIFO
end
end
Note over WG,PTY: Composer send / card answer / image paste each acquire a write lease and queue behind Stop
Reviews (3): Last reviewed commit: "fix(mobile): serialize native chat termi..." | Re-trigger Greptile
| } from './mobile-native-chat-send' | ||
|
|
||
| const ESCAPE = String.fromCharCode(27) | ||
| const CODEX_STOP_BACKGROUND_TERMINALS = '/stop' |
There was a problem hiding this comment.
Magic string
'codex' for agent-specific path
CODEX_STOP_BACKGROUND_TERMINALS is a named constant, but the controlling branch agent !== 'codex' on line 135 is a bare string literal. If the agent name returned by resolveMobileNativeChat ever changes, or if a second agent needing the same cleanup is introduced, the check silently falls back to Escape-only behavior with no compile-time signal. Extracting this into a constant (e.g. const CODEX_AGENT = 'codex') at the top of the file alongside CODEX_STOP_BACKGROUND_TERMINALS would make the coupling visible and the two constants easy to update together.
Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!
There was a problem hiding this comment.
🧹 Nitpick comments (3)
mobile/src/session/use-mobile-native-chat-controller-stop.test.ts (1)
150-161: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueExtract the duplicated
react-test-rendererdeprecation suppression. Both test files repeat the sameconsole.errorspy that filters the deprecation warning and then restores the original. Move the logic into one concrete module, for examplemobile/src/session/react-test-renderer-deprecation-silence.ts, and call it from both files. Avoid a vague module name such asutilsorhelpers.
mobile/src/session/use-mobile-native-chat-controller-stop.test.ts#L150-L161: replace the inline spy with a call to the shared silencer around the first render.mobile/src/session/use-mobile-native-chat-image-stop.test.ts#L93-L109: replace the inline spy with the same shared call.Source: Coding guidelines
mobile/src/session/mobile-native-chat-image-attachment-scope.ts (1)
3-3: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueConsider making the shared empty fallback read-only.
NO_MOBILE_NATIVE_CHAT_ATTACHMENTSis one module-level array shared by every scope's fallback. The current type allows mutation. A futurepushon a fallback value would leak attachments into every scope.♻️ Proposed typing change
-export const NO_MOBILE_NATIVE_CHAT_ATTACHMENTS: PendingNativeChatImage[] = [] +export const NO_MOBILE_NATIVE_CHAT_ATTACHMENTS: readonly PendingNativeChatImage[] = []
MobileNativeChatImageAttachments.attachmentsand theArgs.baseSendcall sites read the value only, so the widened type needs no runtime change. Verify that the declared types ofattachmentsand thependingImageslocal acceptreadonly.mobile/src/session/use-mobile-native-chat-writer-gate.ts (1)
27-42: 🩺 Stability & Availability | 🔵 Trivial | ⚡ Quick winSet a bounded timeout on the stop-lease wait.
waitForMobileNativeChatStopLease(terminal)can wait onlease.settledindefinitely. If a Stopterminal.sendcall never settles, later mobile-native chat writes park behind this lease with no user feedback. Add an upper-bound wait and report a focused error/fallback instead of letting the wait continue.Source: Learnings
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID: 47658ad8-afa6-4ec2-93c3-c1b5babcbeb6
📒 Files selected for processing (15)
mobile/app/h/[hostId]/session/[worktreeId].tsxmobile/src/session/mobile-native-chat-image-attachment-error.tsmobile/src/session/mobile-native-chat-image-attachment-scope.tsmobile/src/session/mobile-native-chat-stop-lease.test.tsmobile/src/session/mobile-native-chat-stop-lease.tsmobile/src/session/use-mobile-native-chat-controller-stop.test.tsmobile/src/session/use-mobile-native-chat-controller-writers.tsmobile/src/session/use-mobile-native-chat-controller.tsmobile/src/session/use-mobile-native-chat-image-attachments.test.tsmobile/src/session/use-mobile-native-chat-image-attachments.tsmobile/src/session/use-mobile-native-chat-image-stop.test.tsmobile/src/session/use-mobile-native-chat-stop.test.tsmobile/src/session/use-mobile-native-chat-stop.tsmobile/src/session/use-mobile-native-chat-writer-gate.tsmobile/src/session/use-mobile-session-image-attachments.ts
🚧 Files skipped from review as they are similar to previous changes (1)
- mobile/src/session/use-mobile-native-chat-stop.ts
There was a problem hiding this comment.
Actionable comments posted: 2
🧹 Nitpick comments (6)
mobile/src/session/use-mobile-native-chat-controller-stop.test.ts (1)
332-334: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winAssert the admitted write started before you unmount.
Line 333 flushes one microtask and then the test unmounts. The test never confirms that
messageWriteran. If the mock was not invoked,finishMessagestays undefined and line 343 fails with aTypeErrorinstead of a clear assertion failure. The other tests in this file guard the same pattern, for example line 227 and line 264.♻️ Proposed assertion
const active = controller!.handleNativeChatSend('in flight') await Promise.resolve() + expect(messageWrite).toHaveBeenCalledOnce() act(() => renderer?.unmount())mobile/src/session/mobile-native-chat-stop-lease.ts (2)
91-106: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueRename
grantedto reflect its settled meaning.
cancelsetspending.granted = trueto make cancellation idempotent. The field then means "settled" (granted or cancelled), not "granted". A later reader can misinterpret a cancelled request as granted. Rename the field tosettled, or add a one-line comment.♻️ Proposed rename
type PendingLease = { readonly kind: MobileNativeChatTerminalLease['kind'] readonly token: object readonly resolve: (lease: MobileNativeChatTerminalLease | null) => void - granted: boolean + /** Granted or cancelled; blocks a second settle. */ + settled: boolean lease: MobileNativeChatTerminalLease | null }
63-71: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueEncode the write-lease invariant in the type instead of a non-null assertion.
requestLeasereturnsnullonly whenkind === 'stop'.requestMobileNativeChatWriteLeaseuses!to erase that. An overload signature removes the assertion and keeps the invariant checked by the compiler.♻️ Proposed overloads
+function requestLease( + terminal: string, + kind: 'write' +): MobileNativeChatTerminalLeaseRequest +function requestLease( + terminal: string, + kind: 'stop' +): MobileNativeChatTerminalLeaseRequest | null function requestLease( terminal: string, kind: MobileNativeChatTerminalLease['kind'] ): MobileNativeChatTerminalLeaseRequest | null {export function requestMobileNativeChatWriteLease( terminal: string ): MobileNativeChatTerminalLeaseRequest { - return requestLease(terminal, 'write')! + return requestLease(terminal, 'write') }Also applies to: 110-114
mobile/src/session/mobile-native-chat-stop-cleanup.ts (1)
11-31: 🚀 Performance & Scalability | 🔵 Trivial | 💤 Low valueConsider an expiry for
pendingByStreamentries.
rememberMobileNativeChatStopCleanupadds an entry per stream identity.recoverMobileNativeChatStopCleanupremoves an entry only after a non-rejected send. A cleanup that never succeeds keeps its entry for the process lifetime. The stream identity includes the session id and terminal handle, so a long app run over many sessions accumulates entries.Consider a timestamp plus a bounded age check, or a cap on map size, so the pending set cannot grow without limit.
mobile/src/session/use-mobile-native-chat-writer-gate.ts (1)
35-44: 🎯 Functional Correctness | 🔵 Trivial | 💤 Low valueConsider
useLayoutEffectto record the active route.
activeRouteRef.currentis assigned in a passive effect.runWritecompares its render-timeclient,enabled, andstreamIdentityagainst that ref. Between commit and the passive effect flush, the ref still holds the previous route, soisCurrent()returnsfalseand the write returnsstaleResult.The window is small and the fallback is safe.
mobile/src/session/use-mobile-native-chat-stop.tsalready records its own route in auseLayoutEffectfor the same reason. Aligning the two removes the window and the asymmetry.♻️ Proposed change
- useEffect(() => { - activeRouteRef.current = { client, enabled, streamIdentity } - return () => { + useLayoutEffect(() => { + activeRouteRef.current = { client, enabled, streamIdentity } + return () => { routeVersionRef.current += 1 for (const request of pendingRef.current) { request.cancel() } pendingRef.current.clear() } }, [client, enabled, streamIdentity])mobile/src/session/use-mobile-native-chat-image-attachments.ts (1)
253-257: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueCollapse the duplicated owner ternary.
actionisMobileNativeChatWriteAction | nullandbaseSend'sownerparameter does not acceptnull, so both call sites branch.action ?? undefinedremoves the branch and the duplication.♻️ Proposed change
// Text-only sends paste nothing first, so 'unknown' leaves no stale input. - const outcome = action - ? await baseSend(text, undefined, deadline, action) - : await baseSend(text, undefined, deadline) + const outcome = await baseSend(text, undefined, deadline, action ?? undefined) return outcome !== 'rejected'const previews = pendingImages.map((attachment) => attachment.previewUri) - const outcome = action - ? await baseSend(text, previews, textDeadline, action) - : await baseSend(text, previews, textDeadline) + const outcome = await baseSend(text, previews, textDeadline, action ?? undefined)Also applies to: 300-303
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID: 7337ab3b-1ec3-47ef-9d55-f88ab943970a
📒 Files selected for processing (14)
mobile/app/h/[hostId]/session/[worktreeId].tsxmobile/src/session/mobile-native-chat-stop-cleanup.tsmobile/src/session/mobile-native-chat-stop-lease.test.tsmobile/src/session/mobile-native-chat-stop-lease.tsmobile/src/session/use-mobile-native-chat-controller-stop.test.tsmobile/src/session/use-mobile-native-chat-controller-writers.tsmobile/src/session/use-mobile-native-chat-controller.tsmobile/src/session/use-mobile-native-chat-image-attachments.test.tsmobile/src/session/use-mobile-native-chat-image-attachments.tsmobile/src/session/use-mobile-native-chat-image-stop.test.tsmobile/src/session/use-mobile-native-chat-stop.test.tsmobile/src/session/use-mobile-native-chat-stop.tsmobile/src/session/use-mobile-native-chat-writer-gate.tsmobile/src/session/use-mobile-session-image-attachments.ts
🚧 Files skipped from review as they are similar to previous changes (3)
- mobile/app/h/[hostId]/session/[worktreeId].tsx
- mobile/src/session/use-mobile-native-chat-stop.ts
- mobile/src/session/use-mobile-native-chat-stop.test.ts
| const send = hook!.sendNativeChat('look') | ||
| for (let index = 0; index < 20 && !finishSubmit; index += 1) { | ||
| await Promise.resolve() | ||
| } | ||
| const stop = requestMobileNativeChatStopLease('terminal-1') | ||
| const stopStarted = vi.fn() | ||
| void stop?.acquired.then(stopStarted) | ||
| await Promise.resolve() | ||
| expect(stopStarted).not.toHaveBeenCalled() |
There was a problem hiding this comment.
📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win
Assert that the mock ran before you call its captured resolver. Both tests capture a resolver inside a mock implementation, wait a fixed number of microtasks, and then call the resolver without proving the mock was invoked. If the wait is too short, the resolver stays undefined, the test fails with TypeError instead of a failed expectation, and the intervening lease assertion passes for the wrong reason. Other tests in use-mobile-native-chat-controller-stop.test.ts already guard this, for example line 227 and line 264.
mobile/src/session/use-mobile-native-chat-image-stop.test.ts#L194-L202: addexpect(baseSend).toHaveBeenCalledOnce()after the spin loop at lines 195-197, before requesting the Stop lease.mobile/src/session/use-mobile-native-chat-controller-stop.test.ts#L332-L334: addexpect(messageWrite).toHaveBeenCalledOnce()after theawait Promise.resolve()at line 333, before the unmount.
📍 Affects 2 files
mobile/src/session/use-mobile-native-chat-image-stop.test.ts#L194-L202(this comment)mobile/src/session/use-mobile-native-chat-controller-stop.test.ts#L332-L334
| const request = requestMobileNativeChatWriteLease(terminal) | ||
| pendingRef.current.add(request) | ||
| let lease: MobileNativeChatTerminalLease | null = null | ||
| try { | ||
| lease = await request.acquired | ||
| if (!lease || !isCurrent()) { | ||
| return staleResult | ||
| } | ||
| return await write({ lease, terminal, isCurrent }) | ||
| } finally { | ||
| pendingRef.current.delete(request) | ||
| lease?.release() | ||
| } |
There was a problem hiding this comment.
🩺 Stability & Availability | 🟠 Major | ⚡ Quick win
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
set -euo pipefail
# Find every stop-lease request site and show the surrounding release handling.
rg -n -C 20 'requestMobileNativeChatStopLease' mobile/src
# Show the paced Escape / cleanup send sites and their deadline arguments.
rg -n -C 6 'openMobileNativeChatSendBudget|sendMobileNativeChatMessageWithOutcome' mobile/src/sessionRepository: stablyai/orca
Length of output: 50369
🏁 Script executed:
#!/bin/bash
set -euo pipefail
echo "== mobile-native-chat-stop-lease outline =="
ast-grep outline mobile/src/session/mobile-native-chat-stop-lease.ts || true
echo
echo "== mobile-native-chat-stop-lease relevant source =="
sed -n '1,145p' mobile/src/session/mobile-native-chat-stop-lease.ts
echo
echo "== use-mobile-native-chat-writer-gate relevant source =="
sed -n '1,140p' mobile/src/session/use-mobile-native-chat-writer-gate.ts
echo
echo "== relevant stop send source snippets =="
sed -n '145,265p' mobile/src/session/use-mobile-native-chat-stop.ts
sed -n '35,95p' mobile/src/session/mobile-native-chat-stop-cleanup.ts
echo
echo "== focused grep for requestMobileNativeChatStopLease and leases in session source =="
rg -n 'requestMobileNativeChatStopLease|stopLease|acquired|release\(' mobile/src/session | grep -E 'mobile-native-chat-stop-lease.ts|use-mobile-native-chat-stop.ts|mobile-native-chat-stop-cleanup.ts|use-mobile-native-chat-writer-gate.ts' || trueRepository: stablyai/orca
Length of output: 14272
🏁 Script executed:
#!/bin/bash
set -euo pipefail
echo "== use-mobile-native-chat-write send gate and wait path =="
rg -n -C 10 'runWrite|clearMobileNativeChatInput|sendNativeChat|pendingKey|isMobileNativeChatInputStale' mobile/src/session/use-mobile-native-chat-write.ts
echo
echo "== focused usages of useMobileNativeChatWriterGate and runWrite =="
rg -n -C 8 'useMobileNativeChatWriterGate|runWrite\(async|runWrite<|runWrite\(' mobile/src/session mobile/src || true
echo
echo "== stop cleanup hook relevant source =="
sed -n '1,150p' mobile/src/session/use-mobile-native-chat-stop.ts
echo
echo "== read-only behavioral model of stop lease queueing and unbounded acquired waits =="
node - <<'JS'
function runModel() {
const events = []
let acquiredStopResolve = null
let acquiredEscapeResolve = null
let acquiredCleanupResolve = null
let next = null
let stopped = false
function acquireStop() {
events.push('acquire-stop-request')
return new Promise((resolve) => { acquiredStopResolve = resolve })
}
function cancelStop() {
if (acquiredStopResolve) acquiredStopResolve(null)
}
async function stopPath() {
const lease = await acquireStop()
if (!lease) { events.push('stop-canceled'); return false }
events.push('stop-leasel-held', 'scheduled-escape')
await new Promise((r) => setTimeout(r, 1))
events.push('escape-starts', 'escape-sends')
setTimeout(() => acquiredEscapeResolve && acquiredEscapeResolve('accepted'), 1)
events.push('cleanup-cancelled')
cancelStop()
return true
}
async function cleanupPath() {
const lease = await acquireStop()
if (!lease) { events.push('cleanup-busy'); return 'busy' }
events.push('cleanup-leasel-held', 'cleanup-sends')
await acquireCleanupResolve ??= Promise.resolve('rejected')
events.push('cleanup-released')
return 'rejected'
}
async function writer() {
events.push('writer-blocked-on-acquire')
if (stopped) await acquireEscapeResolve ??= Promise.resolve('accepted')
else await acquireCleanupResolve ??= Promise.resolve('completed')
events.push('writer-released')
}
setTimeout(stopPath)
setTimeout(() => writer(), 3)
setTimeout(cleanupPath)
setTimeout(async () => {
events.push('advance-stop')
acquiredStopResolve && acquiredStopResolve({ release: () => { events.push('stop-released') } })
}, 5)
setTimeout(async () => {
events.push('advance-escape')
acquiredEscapeResolve && acquiredEscapeResolve('accepted')
}, 10)
setTimeout(() => { acquiredCleanupResolve && acquiredCleanupResolve('cancelled'); events.push('stopped'), completed = true }, 12)
}
runModel()
JSRepository: stablyai/orca
Length of output: 383
🏁 Script executed:
#!/bin/bash
set -euo pipefail
echo "== session file candidates =="
fd -i 'mobile-native-chat|use-mobile-native' mobile/src/session | sed -n '1,80p'
echo
echo "== runWrite call sites =="
rg -n -C 10 'useMobileNativeChatWriterGate|runWrite\(async|runWrite<|runWrite\(|sendNativeChat\(' mobile/src/session mobile/src || true
echo
echo "== stop cleanup hook relevant source =="
sed -n '80,275p' mobile/src/session/use-mobile-native-chat-stop.ts
echo
echo "== read-only behavioral model of stop lease queueing and unbounded acquired waits =="
node - <<'JS'
async function simulate() {
const events = [];
let acquiredStopResolve = null;
let acquiredEscapeResolve = null;
let acquiredCleanupResolve = null;
async function acquireStop(name) {
events.push(`${name}-acquire`);
return new Promise((resolve) => {
if (name === 'stop') acquiredStopResolve = resolve;
if (name === 'cleanup') acquiredCleanupResolve = resolve;
});
}
async function stopPath() {
const lease = await acquireStop('stop');
if (!lease) { events.push('stop-canceled'); return false; }
events.push('stop-holds-lease', 'scheduled-escape');
await new Promise((r) => setTimeout(r, 1));
events.push('escape-starts', 'escape-sends');
setTimeout(() => acquiredEscapeResolve && acquiredEscapeResolve('accepted'), 1);
events.push('cleanup-blocks-on-acquire');
const cleanup = await acquireStop('cleanup');
return cleanup ? 'rejected' : 'busy';
}
async function writerPath() {
events.push('writer-blocked-on-acquire');
await acquiredEscapeResolve ??= Promise.resolve('accepted');
events.push('writer-released');
}
setTimeout(stopPath);
setTimeout(writerPath, 3);
setTimeout(async () => { events.push('advance-stop'); acquiredStopResolve && acquiredStopResolve({ release: () => events.push('stop-released') }); }, 5);
setTimeout(async () => { events.push('advance-escape'); acquiredEscapeResolve && acquiredEscapeResolve('accepted'); }, 10);
setTimeout(async () => { events.push('advance-cleanup'); acquiredCleanupResolve && acquiredCleanupResolve('rejected'); }, 12);
await new Promise((resolve) => setTimeout(resolve, 15));
for (const e of events) console.log(e);
}
simulate();
JSRepository: stablyai/orca
Length of output: 50370
🏁 Script executed:
#!/bin/bash
set -euo pipefail
echo "== sendNativeChat implementation =="
sed -n '205,225p' mobile/src/session/use-mobile-native-chat-image-attachments.ts
rg -n -C 12 'async \(text: string\)|sendNativeChat\. =|const sendNativeChat|runWrite\(' mobile/src/session/use-mobile-native-chat-image-attachments.ts
echo
echo "== all direct requestMobileNativeChatStopLease usages in tracked source =="
rg -n -C 12 'requestMobileNativeChatStopLease\(' mobile/src | grep -v test | grep -v node_modules || true
echo
echo "== stop hook full relevant implementation =="
sed -n '150,270p' mobile/src/session/use-mobile-native-chat-stop.ts
echo
echo "== read-only behavioral model of stop lease queueing and unbounded acquired waits =="
node - <<'JS'
(async () => {
const events = [];
let stopAcquireResolve = null;
let cleanupAcquireResolve = null;
let writerAcquireResolve = null;
function acquireStop(name) {
events.push(`${name}-acquire-queued`);
return new Promise((resolve) => {
if (name === 'stop') stopAcquireResolve = resolve;
if (name === 'cleanup') cleanupAcquireResolve = resolve;
if (name === 'writer') writerAcquireResolve = resolve;
});
}
async function stopPath() {
const stop = await acquireStop('stop');
if (!stop) { events.push('stop-canceled'); return false; }
events.push('stop-holds-lease');
await new Promise((resolve) => setTimeout(resolve, 1));
events.push('escape-starts');
setTimeout(() => stopAcquireResolve && stopAcquireResolve({ release: () => events.push('stop-released') }), 5);
return true;
}
async function cleanupPath() {
const cleanup = await acquireStop('cleanup');
events.push(`cleanup-received-${cleanup ? 'lease' : 'busy'}`);
return cleanup ? 'rejected' : 'busy';
}
async function writerPath() {
const lease = await acquireStop('writer');
events.push('writer-stuck-blocked');
}
setTimeout(stopPath);
setTimeout(writerPath, 0.3);
setTimeout(cleanupPath, 0.4);
await new Promise((resolve) => setTimeout(resolve, 12));
for (const event of events) console.log(event);
})();
JSRepository: stablyai/orca
Length of output: 12076
Bound stop-lease waits before allowing queued sends to proceed.
runWrite waits on request.acquired without a timeout, while stop send paths await request.acquired before crediting their send budget. Two stop-related callers can stack (use-mobile-native-chat-stop.ts and recoverMobileNativeChatStopCleanup), but only recoverMobileNativeChatStopCleanup releases it in finally; the running stop can leave the cleanup and all queued writers blocked until the writer lease holder releases. Add a bounded deadline/timeout to stop-lease acquisition or separate stop from queued writes.
Source: Learnings
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.
Stop wrote two Escapes and nothing else. That interrupts the agent's turn, but the background terminals the turn spawned keep running: interrupting a turn and reaping background terminals are two distinct operations in the agent, and only the second one stops them. A `sleep 180` survived Stop and kept running while the composer showed the agent as idle. After the interrupt is confirmed, Stop now dispatches Codex's own `/stop` through the existing send seam, so the cleanup types key by key (the TUI reads a pasted burst as prose, not a command), clears the input line first so it cannot submit a draft the user left in the composer, and takes the per-terminal write lock instead of opening a second unserialized write path into the same PTY. Gated on an exact `codex` match, never "not claude": typing a literal `/stop` into an agent without that command would post it as a prompt. The Escapes themselves stay ungated by the write lock, so Stop still always fires; only the cleanup leg can be refused, and it says so rather than failing silently.
|
Note GitHub couldn't provide a complete incremental comparison for this pull request, so CodeRabbit is performing a full review instead. This review may take a little longer. |
|
Updated to What changed since the last review. The 1,857-line lease / writer-gate / persisted-retry architecture is gone. #12502 landed an acquire-or-reject terminal write lock a month ago ( What actually ships now. After both Escapes settle with at least one accepted, and only for an exact This addresses the original defect. Escape interrupts a Codex turn but does not reap its background terminals — the agent runtime models interrupt and background-terminal cleanup as two distinct operations, and Deliberate decision worth reviewing. The write lock covers the Evidence. Red-then-green with two ablations, both applied after committing and restored by file path, with
Full mobile suite 517 files / 4,215 passed, 3 skipped. Companion PR: #19259, which implements Still not covered, and honest about it: PTY-scrape native chat is the wrong long-term shape for this — desktop has the identical hole at |
|
Closing this without merging. The surface it fixes is being retired. Terminal-based native chat for Codex is being restructured into structured native chat in the next few days, and this fix is gated on an exact It also has no tracking issue. No linked Linear issue and no STA reference — it came out of an automation run rather than a user report. The defect is real and stays fixed. Interrupting a Codex turn does not reap the background terminals that turn spawned: interrupt and background-terminal cleanup are two distinct operations in the agent runtime, and Escape drives only the first. A real #19259 handles it properly, on the surface that survives. It implements For the record, the work here was not wasted: it established the mechanism (Stop writes two Escape bytes into the PTY and nothing else), proved that no process-group signalling path is reachable from Stop, and identified the adapter gap that #19259 fills. |
Stop wrote two Escapes and nothing else. That interrupts the agent's turn, but the background terminals the turn spawned keep running: interrupting a turn and reaping background terminals are two distinct operations in the agent, and only the second one stops them. A real
sleep 180survived Stop and kept running while the chat showed the agent as idle.After the interrupt is confirmed, Stop now dispatches Codex's own
/stopthrough the existing send seam. That means the cleanup types key by key rather than as one burst — a pasted burst is read as prose, not a command — clears the input line first so it cannot submit a draft the user left in the composer, and takes the per-terminal write lock instead of opening a second unserialized write path into the same PTY. It is not a new mechanism:dispatchCommandwas already the exact-codex-gated, lock-acquiring, stale-input-healing slash-command dispatcher on this surface, and/stopis already in the shipped command catalog for this agent.Gated on an exact
codexmatch, never "not claude": typing a literal/stopinto an agent without that command would post it as a prompt.The Escapes themselves stay ungated by the write lock, so Stop still always fires. Only the cleanup leg can be refused, and it says so rather than failing silently — "Agent stopped; background terminals may still be running" on a rejection, "background cleanup unconfirmed" on a lost ack, neither of which reads as "Stop failed" and invites a second Escape into changed composer state.
Known and pre-existing: because the Escapes are deliberately not lock-gated, an Escape can still land in the middle of an in-flight paste sequence. That is unchanged from main and is the direct, intended cost of keeping the interrupt unconditional — gating the emergency stop behind a lock a paste happens to hold would turn it into a silent no-op, which is the failure this PR exists to remove.
Scope
This is the PTY native-chat surface. Structured Codex sessions are a separate lane with their own Stop; that gap is fixed by #19259, which adds the Codex adapter's
backgroundTaskState/stopBackgroundTasks. The two cannot both fire for one session — the hook here is constructed withenabled: inputSendable && !activeChatStructured, and the UI callsactiveChatStructured ? structuredNativeChat.cancel : handleNativeChatStop. Longer term the right shape is migrating these surfaces to structured rather than typing commands into a composer; #19259 carries that direction and this PR does not claim to.This branch supersedes its own earlier architecture
The FIFO stop lease, writer gate, controller-writer plumbing and module-level cleanup-retry map are dropped in favour of
mobile-native-chat-terminal-write-lock.ts, which landed in #12502 and already serializes writer-vs-writer per terminal. Two of the three defects this PR previously fixed existed only because it typed into a shared composer through its own new write path; the third, cross-agent stale replay, is already covered by main'sactiveRouteRefre-check atuse-mobile-native-chat-stop.ts:79-87.Net diff versus
mainis 5 files, +354/−27, all undermobile/src/session/— the old 1,857-line architecture nets out to zero.Testing
Mobile suite 517 files / 4,215 passed, 3 skipped. Red-then-green by ablation, both applied after committing and restored by file path with
HEADre-verified afterwards rather than only the working tree: removing the cleanup trigger fails 3 tests; breaking the dispatcher binding fails 2, including the exact typed byte sequence['\x15','/','s','t','o','p','\r']. Green after restore: 22/22.mobile/ tsc --noEmit, oxlint and oxfmt clean. Both lockfiles byte-identical tomain; neither commit contains one.Note for review: root
pnpm tcis not a meaningful gate for this branch — it is mobile-only, somobile/ tsc --noEmitis the real one.