Skip to content

fix(mobile): stop Codex background terminals from native chat - #11988

Closed
brennanb2025 wants to merge 7 commits into
mainfrom
brennanb2025/mobile-native-chat-stop-background-tools
Closed

brennanb2025 wants to merge 7 commits into
mainfrom
brennanb2025/mobile-native-chat-stop-background-tools

Conversation

@brennanb2025

@brennanb2025 brennanb2025 commented Aug 1, 2026 •

Copy link
Copy Markdown
Contributor

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 180 survived Stop and kept running while the chat showed the agent as idle.

After the interrupt is confirmed, Stop now dispatches Codex's own /stop through 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: dispatchCommand was already the exact-codex-gated, lock-acquiring, stale-input-healing slash-command dispatcher on this surface, and /stop is already in the shipped command catalog for this agent.

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 — "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 with enabled: inputSendable && !activeChatStructured, and the UI calls activeChatStructured ? 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's activeRouteRef re-check at use-mobile-native-chat-stop.ts:79-87.

Net diff versus main is 5 files, +354/−27, all under mobile/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 HEAD re-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 to main; neither commit contains one.

Note for review: root pnpm tc is not a meaningful gate for this branch — it is mobile-only, so mobile/ tsc --noEmit is the real one.

@coderabbitai

coderabbitai Bot commented Aug 1, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Team

Run ID: 066a55cf-9998-4ca3-ae2b-5d6297bb0495

📥 Commits

Reviewing files that changed from the base of the PR and between ffff6ea and e72756b.

📒 Files selected for processing (5)
  • mobile/src/session/codex-background-terminal-stop.test.ts
  • mobile/src/session/codex-background-terminal-stop.ts
  • mobile/src/session/use-mobile-native-chat-controller.ts
  • mobile/src/session/use-mobile-native-chat-stop.test.ts
  • mobile/src/session/use-mobile-native-chat-stop.ts
🚧 Files skipped from review as they are similar to previous changes (1)
  • mobile/src/session/use-mobile-native-chat-stop.ts

Included review availability: Your plan provides up to 10 included reviews per hour; 3 remain after this review.


📝 Walkthrough

Walkthrough

The mobile native-chat Stop flow now receives the active agent reference and a Codex background-terminal cleanup callback. Codex cleanup dispatches /stop through the existing command dispatcher and terminal write lock. Stop handling validates route liveness, performs cleanup after an accepted Escape, and reports rejected or unconfirmed cleanup. Tests cover controller wiring, paced command input, lock handling, cleanup outcomes, non-Codex agents, and stale routes.

Merge Risk: ⚪ Minimal · up to e7275

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)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 17.65% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 17 functions across 12 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
Description check ⚠️ Warning 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 … 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, docume…
✅ Passed checks (3 passed)
Check name Status Explanation
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.
Title check ✅ Passed The title clearly and concisely identifies the main change: preventing Codex background terminals from continuing after native chat Stop.
Full details: Description check

Explanation

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.

  • Fix all pre-merge checks with AI
✨ 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.

@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-stop.test.ts (1)

229-245: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Add coverage for the remaining stop error branches.

This test covers the 'rejected' cleanup outcome. Two other new branches in use-mobile-native-chat-stop.ts stay uncovered:

  • The 'unknown' cleanup outcome at line 143, which reports "Stop unconfirmed — check chat before retrying". Make sendRequest reject the /stop call with a delivery-unknown error to reach it.
  • A rejected second Escape. This branch decides whether /stop cleanup runs at all, so it pairs with the gating concern raised on use-mobile-native-chat-stop.ts lines 125-137.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 2c066bab-4f2b-4403-956e-8f9efedd4b9a

📥 Commits

Reviewing files that changed from the base of the PR and between 16c5526 and e6030bd.

📒 Files selected for processing (3)
  • mobile/src/session/use-mobile-native-chat-controller.ts
  • mobile/src/session/use-mobile-native-chat-stop.test.ts
  • mobile/src/session/use-mobile-native-chat-stop.ts

Comment on lines +125 to +137
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
}

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.

🎯 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.

Suggested change
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-apps

greptile-apps Bot commented Aug 1, 2026 •

Copy link
Copy Markdown

Greptile Summary

This PR introduces a per-terminal stop-lease system to eliminate PTY write-ordering races in the mobile native-chat Stop flow. A new MobileNativeChatTerminalLeaseQueue enforces that: (1) Stop always runs before queued writers; (2) only one Stop can be pending per terminal; and (3) every controller writer—send, card answer, permission response, image paste—gates on the same lease before touching the PTY.

  • New lease module (mobile-native-chat-stop-lease.ts) implements a priority-queue for terminal writes: a Stop request slots ahead of pending write requests but behind an already-active write, and duplicate Stops are rejected synchronously.
  • New cleanup-recovery module (mobile-native-chat-stop-cleanup.ts) persists a pending /stop entry keyed by stream identity so a reconnected or remounted component can finish interrupted Codex cleanup without re-sending Escapes.
  • Controller writers refactored (use-mobile-native-chat-controller-writers.ts) into a dedicated hook that wraps all writer paths through useMobileNativeChatWriterGate, and the image-attachment send path now accepts runNativeChatWrite so paste + submit share one lease and one budget.

Confidence Score: 5/5

The 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 pendingByStream map has no maximum-size guard; worth a glance if the app ever runs in very long-lived sessions with repeated interrupted Codex stops.

Important Files Changed

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
Loading

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'

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 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!

@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.

🧹 Nitpick comments (3)
mobile/src/session/use-mobile-native-chat-controller-stop.test.ts (1)

150-161: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Extract the duplicated react-test-renderer deprecation suppression. Both test files repeat the same console.error spy that filters the deprecation warning and then restores the original. Move the logic into one concrete module, for example mobile/src/session/react-test-renderer-deprecation-silence.ts, and call it from both files. Avoid a vague module name such as utils or helpers.

  • 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 value

Consider making the shared empty fallback read-only.

NO_MOBILE_NATIVE_CHAT_ATTACHMENTS is one module-level array shared by every scope's fallback. The current type allows mutation. A future push on 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.attachments and the Args.baseSend call sites read the value only, so the widened type needs no runtime change. Verify that the declared types of attachments and the pendingImages local accept readonly.

mobile/src/session/use-mobile-native-chat-writer-gate.ts (1)

27-42: 🩺 Stability & Availability | 🔵 Trivial | ⚡ Quick win

Set a bounded timeout on the stop-lease wait.

waitForMobileNativeChatStopLease(terminal) can wait on lease.settled indefinitely. If a Stop terminal.send call 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

📥 Commits

Reviewing files that changed from the base of the PR and between e6030bd and e3e0248.

📒 Files selected for processing (15)
  • mobile/app/h/[hostId]/session/[worktreeId].tsx
  • mobile/src/session/mobile-native-chat-image-attachment-error.ts
  • mobile/src/session/mobile-native-chat-image-attachment-scope.ts
  • mobile/src/session/mobile-native-chat-stop-lease.test.ts
  • mobile/src/session/mobile-native-chat-stop-lease.ts
  • mobile/src/session/use-mobile-native-chat-controller-stop.test.ts
  • mobile/src/session/use-mobile-native-chat-controller-writers.ts
  • mobile/src/session/use-mobile-native-chat-controller.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-image-stop.test.ts
  • mobile/src/session/use-mobile-native-chat-stop.test.ts
  • mobile/src/session/use-mobile-native-chat-stop.ts
  • mobile/src/session/use-mobile-native-chat-writer-gate.ts
  • mobile/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

@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: 2

🧹 Nitpick comments (6)
mobile/src/session/use-mobile-native-chat-controller-stop.test.ts (1)

332-334: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Assert the admitted write started before you unmount.

Line 333 flushes one microtask and then the test unmounts. The test never confirms that messageWrite ran. If the mock was not invoked, finishMessage stays undefined and line 343 fails with a TypeError instead 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 value

Rename granted to reflect its settled meaning.

cancel sets pending.granted = true to 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 to settled, 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 value

Encode the write-lease invariant in the type instead of a non-null assertion.

requestLease returns null only when kind === 'stop'. requestMobileNativeChatWriteLease uses ! 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 value

Consider an expiry for pendingByStream entries.

rememberMobileNativeChatStopCleanup adds an entry per stream identity. recoverMobileNativeChatStopCleanup removes 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 value

Consider useLayoutEffect to record the active route.

activeRouteRef.current is assigned in a passive effect. runWrite compares its render-time client, enabled, and streamIdentity against that ref. Between commit and the passive effect flush, the ref still holds the previous route, so isCurrent() returns false and the write returns staleResult.

The window is small and the fallback is safe. mobile/src/session/use-mobile-native-chat-stop.ts already records its own route in a useLayoutEffect for 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 value

Collapse the duplicated owner ternary.

action is MobileNativeChatWriteAction | null and baseSend's owner parameter does not accept null, so both call sites branch. action ?? undefined removes 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

📥 Commits

Reviewing files that changed from the base of the PR and between e3e0248 and 9eacac4.

📒 Files selected for processing (14)
  • mobile/app/h/[hostId]/session/[worktreeId].tsx
  • mobile/src/session/mobile-native-chat-stop-cleanup.ts
  • mobile/src/session/mobile-native-chat-stop-lease.test.ts
  • mobile/src/session/mobile-native-chat-stop-lease.ts
  • mobile/src/session/use-mobile-native-chat-controller-stop.test.ts
  • mobile/src/session/use-mobile-native-chat-controller-writers.ts
  • mobile/src/session/use-mobile-native-chat-controller.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-image-stop.test.ts
  • mobile/src/session/use-mobile-native-chat-stop.test.ts
  • mobile/src/session/use-mobile-native-chat-stop.ts
  • mobile/src/session/use-mobile-native-chat-writer-gate.ts
  • mobile/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

Comment on lines +194 to +202
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()

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 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: add expect(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: add expect(messageWrite).toHaveBeenCalledOnce() after the await 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

Comment on lines +74 to +86
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()
}

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.

🩺 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/session

Repository: 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' || true

Repository: 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()
JS

Repository: 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();
JS

Repository: 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);
})();
JS

Repository: 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

brennanb2025 and others added 4 commits August 1, 2026 18:43
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.
@coderabbitai

coderabbitai Bot commented Sep 7, 2026

Copy link
Copy Markdown
Contributor

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.

@brennanb2025

Copy link
Copy Markdown
Contributor Author

Updated to e72756b195 — brought onto current main and rescoped.

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 (mobile-native-chat-terminal-write-lock.ts), so the writer-serialization half of this PR was superseded, and resolving its conflicts would have meant re-litigating that design. 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's activeRouteRef re-check at use-mobile-native-chat-stop.ts:79-87.

What actually ships now. After both Escapes settle with at least one accepted, and only for an exact codex match on a still-live route, Stop dispatches /stop through main's existing dispatchCommand (use-mobile-native-chat-message-send.ts:277-318) — which already acquires the write lock, heals stale input, gates on exact 'codex', and types key-by-key via typeAgentTuiCommand. That last part matters: a bundled { text: '/stop', enter: true } burst is classified by the TUI as prose rather than a command, which :144 explicitly warns about.

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 /stop ("Stop all background terminals") is already in Orca's own shipped catalog at native-chat-slash-commands.ts:79. The August native QA failure, where a real sleep 180 survived a second Stop past 15 seconds while the UI still showed Working, is exactly this gap.

Deliberate decision worth reviewing. The write lock covers the /stop write only, never the Escapes. Gating the interrupt behind a lock a mid-flight paste holds would stop Stop from firing at all — a worse failure than the one being fixed. Consequence, stated plainly: Escape-into-a-mid-flight-paste remains possible, unchanged from main. That is pre-existing and out of scope here. If the /stop write is rejected because the lock is busy, the user is told background terminals may still be running rather than being left to assume success.

Evidence. Red-then-green with two ablations, both applied after committing and restored by file path, with HEAD re-verified after each restore rather than only the working tree:

  • removing the cleanup trigger → 3 tests fail
  • breaking the dispatcher binding → 2 tests fail, expected [] to deeply equal ['\x15','/','s','t','o','p','\r']
  • green after restore: 22/22

Full mobile suite 517 files / 4,215 passed, 3 skipped. tsc --noEmit clean (this branch is mobile-only, so the root typecheck says nothing about it — mobile/ is its real gate). oxlint and oxfmt clean. Both lockfiles byte-identical to main; neither commit contains one.

Companion PR: #19259, which implements backgroundTaskState / stopBackgroundTasks on the Codex structured adapter. The two do not overlap and cannot double-fire: useMobileNativeChatStop is constructed with enabled: inputSendable && !activeChatStructured, and the UI calls activeChatStructured ? structuredNativeChat.cancel : handleNativeChatStop, so a session is on exactly one lane. #19259 alone would leave this bug live for every PTY-lane user; this PR alone would leave structured sessions unfixed.

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 NativeChatResolvedView.tsx:117, and the right fix for both is migrating those surfaces to structured rather than typing into a composer. This PR does not resolve that; it fixes the reported bug on the surface users are on today.

@brennanb2025 brennanb2025 changed the title fix(mobile): stop Codex background tools from native chat fix(mobile): stop Codex background terminals from native chat Sep 7, 2026
@brennanb2025

Copy link
Copy Markdown
Contributor Author

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 codex match — deliberately, so a literal /stop could never be typed into another agent's TUI. That gating means its entire value sits on the surface going away: it does not help Claude, Cursor, Gemini or any other agent on the PTY path, and it does not touch the structured path at all.

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 sleep 180 survived Stop while the chat showed the agent as idle.

#19259 handles it properly, on the surface that survives. It implements backgroundTaskState and stopBackgroundTasks on the Codex structured session adapter behind a capability probe — the methods Claude's adapter already implements and Codex's did not — which lights up the desktop background-tasks UI that has been shipped for a while, and adds the equivalent control on mobile. That is Orca's own answer to "stop the agent's background work": a typed adapter capability surfaced as a distinct control, rather than synthesising keystrokes into a shared composer.

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.

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