Repository navigation
fix(mobile): bound terminal viewport resubscribe loop with backoff (STA-3337) - #12362
Conversation
…TA-3337) An empty scrollback frame with absent host dims was coerced to 80x24, which never equals a phone viewport, arming a zero-delay unsubscribe/resubscribe loop (~25/s) that broke long-press gestures and drained battery. - Absent host dims now hold the stream instead of resubscribing. - Fit resubscribes are budgeted per handle (3 attempts, escalating backoff) with an absence-gated refill mirroring the chat-side rearm bound; on exhaustion the view degrades visibly via toast instead of hot-looping. - A fresh post-measure match counts as convergence instead of resubscribing. - setTerminalModes keeps the Map identity when the mode is unchanged, so same-mode frames no longer re-render the session route. - Host emits the subscriber viewport as scrollback dims when the snapshot and PTY size are both unavailable, so current hosts converge immediately.
📝 WalkthroughWalkthroughThe change adds validated terminal viewport dimensions and bounded resubscription retries with capped backoff. Per-terminal retry budgets now reset, refill, and clear with terminal lifecycle events. The session screen uses shared fit-pass logic for scrollback and resize handling, while diagnostics report held and exhausted retries. Legacy and binary subscription snapshots use requested viewport dimensions before default values. Comprehensive tests cover convergence, stale work, cancellation, exhaustion, and budget lifecycle. 🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 passed)
✨ Finishing Touches📝 Generate docstrings
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 2
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID: fbc9c9f6-3f16-4993-962d-276f46731298
📒 Files selected for processing (5)
mobile/app/h/[hostId]/session/[worktreeId].tsxmobile/src/session/mobile-terminal-diagnostics.tsmobile/src/session/mobile-terminal-viewport-resubscribe.test.tsmobile/src/session/mobile-terminal-viewport-resubscribe.tssrc/main/runtime/rpc/methods/terminal.ts
| observeResize( | ||
| handle: string, | ||
| data: Readonly<Record<string, unknown>>, | ||
| viewport: TerminalViewportDims | null | ||
| ): readonly [number, number] { | ||
| const { hostCols, hostRows } = readTerminalViewportDims(data) | ||
| const cols = hostCols ?? 80 | ||
| const rows = hostRows ?? 24 | ||
| if (viewport?.cols === cols && viewport.rows === rows) { | ||
| this.markConverged(handle) | ||
| } | ||
| return [cols, rows] | ||
| } |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win
Do not treat fallback dimensions as convergence.
observeResize replaces absent host dimensions with 80/24 before the comparison. If the measured viewport is 80x24, the method calls markConverged, which clears the attempt count, the exhaustion marker, and the retry generation. The host reported no dimensions in that case, so the budget refills for a handle that cannot converge. resolveTerminalViewportResubscribe holds on the same input, so the two paths disagree.
Compare only reported dimensions, and keep the defaults for rendering.
🐛 Proposed fix
const { hostCols, hostRows } = readTerminalViewportDims(data)
const cols = hostCols ?? 80
const rows = hostRows ?? 24
- if (viewport?.cols === cols && viewport.rows === rows) {
+ if (hostCols != null && hostRows != null && viewport?.cols === cols && viewport.rows === rows) {
this.markConverged(handle)
}
return [cols, rows]📝 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.
| observeResize( | |
| handle: string, | |
| data: Readonly<Record<string, unknown>>, | |
| viewport: TerminalViewportDims | null | |
| ): readonly [number, number] { | |
| const { hostCols, hostRows } = readTerminalViewportDims(data) | |
| const cols = hostCols ?? 80 | |
| const rows = hostRows ?? 24 | |
| if (viewport?.cols === cols && viewport.rows === rows) { | |
| this.markConverged(handle) | |
| } | |
| return [cols, rows] | |
| } | |
| observeResize( | |
| handle: string, | |
| data: Readonly<Record<string, unknown>>, | |
| viewport: TerminalViewportDims | null | |
| ): readonly [number, number] { | |
| const { hostCols, hostRows } = readTerminalViewportDims(data) | |
| const cols = hostCols ?? 80 | |
| const rows = hostRows ?? 24 | |
| if (hostCols != null && hostRows != null && viewport?.cols === cols && viewport.rows === rows) { | |
| this.markConverged(handle) | |
| } | |
| return [cols, rows] | |
| } |
| // Why: prefer the subscriber's viewport over the 80x24 stopgap when the PTY has | ||
| // no size yet — the mismatch made mobile burn its resubscribe budget (STA-3337). | ||
| cols: serialized?.cols ?? size?.cols ?? params.viewport?.cols ?? 80, | ||
| rows: serialized?.rows ?? size?.rows ?? params.viewport?.rows ?? 24, |
There was a problem hiding this comment.
🚀 Performance & Scalability | 🟡 Minor | ⚡ Quick win
Keep the resize baseline consistent with the snapshot fallback.
When serialized and PTY columns are unavailable, this frame uses params.viewport?.cols. However, Lines 3407-3408 set lastResizeCols without that fallback. A later resize event with the same columns is then treated as a width change and triggers an unnecessary full restream. Use the same fallback chain for lastResizeCols.
Proposed fix
- lastResizeCols = serialized?.cols ?? size?.cols
+ lastResizeCols = serialized?.cols ?? size?.cols ?? params.viewport?.cols
QA evidence — post-review head
|
…TA-3337) (stablyai#12362) * fix(mobile): bound terminal viewport resubscribe loop with backoff (STA-3337) An empty scrollback frame with absent host dims was coerced to 80x24, which never equals a phone viewport, arming a zero-delay unsubscribe/resubscribe loop (~25/s) that broke long-press gestures and drained battery. - Absent host dims now hold the stream instead of resubscribing. - Fit resubscribes are budgeted per handle (3 attempts, escalating backoff) with an absence-gated refill mirroring the chat-side rearm bound; on exhaustion the view degrades visibly via toast instead of hot-looping. - A fresh post-measure match counts as convergence instead of resubscribing. - setTerminalModes keeps the Map identity when the mode is unchanged, so same-mode frames no longer re-render the session route. - Host emits the subscriber viewport as scrollback dims when the snapshot and PTY size are both unavailable, so current hosts converge immediately. * fix(mobile): cancel stale viewport retries after convergence


Summary
Fixes STA-3337: with the mobile terminal view active, a host that answers
terminal.subscribewith an empty scrollback frame and no usable dims sent the client into an unboundedunsubscribe→subscribeloop (~25 cycles/s measured live) with no backoff and no attempt cap. Each pass re-initialized xterm mid-gesture (reproducibly breaking the tab title's long-press action sheet) and re-rendered the session route, draining battery and bandwidth for as long as the view stayed mounted.Client (primary fix — must be robust regardless of host version):
terminal.listdrops the handle and later lists it again — the same absence-gated bound the chat-side stream uses inuse-mobile-native-chat-terminal-stream.ts, so a still-listed non-converging handle cannot be re-funded on every list refresh.setTerminalModeskeeps the Map identity when the mode didn't change, so same-mode stream frames no longer re-render the whole session route.Host:
terminal.subscribescrollback emission now falls back to the subscriber's own viewport when both the serialized snapshot and the PTY size are unavailable (JSON and binary stream paths), so current hosts report converging dims instead of nothing (JSON path) or a hardcoded 80x24 (binary path).The decision logic lives in a new pure module
mobile/src/session/mobile-terminal-viewport-resubscribe.ts(decision function, post-measure convergence check, per-handle budget, and the orchestrated fit pass), which also brings the session route back under the max-lines gate.Linear: STA-3337
Screenshots
No visual change in normal operation. The only new UI behavior is the existing toast component showing "Couldn't fit the terminal to this screen" once if fit attempts exhaust (degraded-host edge case; reproducing requires the STA-3337 mock-host rig, see the ticket).
Testing
pnpm lintpnpm typecheckpnpm testpnpm buildpnpm lint(full root suite) andmobile/ pnpm lintboth pass.pnpm typecheckrun at root and inmobile/.pnpm test= the full mobile suite frommobile/(391 files, 2915 passed) plus the root suites coveringterminal.subscribe(terminal-mobile-subscribe-tab-mount,terminal-subscribe-lease-only,terminal-subscribe-exit-waiter-leak,rpc/streaming); the remaining root suite andpnpm buildare left to CI. The new unit tests cover the resubscribe decision (absent dims, convergence, bound, backoff ordering), budget semantics (charge, converge-reset, no refill while still listed, absence-gated refill, single exhaustion announcement), and the orchestrated fit pass (stale-generation guards on deferred retries, backoff keeps the stream up until the retry fires, attempts charged only when the resubscribe actually armed).AI Review Report
Main risks checked: (1) stale-generation races — every async resume point, including the new backoff timer callback, re-checks
subscribeSeqRefbefore tearing anything down, so a tab switch or reconnect during the backoff cannot resubscribe a stale generation; (2) budget re-funding — refills are absence-gated exactly like the chat-side rearm budget, preventingterminal.listrefreshes from re-arming the loop; (3) interplay with the other resubscribe drivers (foreground recovery,useTerminalViewportRefit, chat cover/resume) — the budget scopes only to the scrollback fit pass, so user- and layout-driven refits remain unaffected; (4) input-lease continuity — backoff defers the teardown, not just the retry, so the subscription (and the input floor it carries) stays live between attempts; (5) old-host compatibility — pre-binary desktops that emit dimless JSON scrollback now hold instead of looping, with no host upgrade required.Cross-platform compatibility was explicitly reviewed for macOS, Linux, and Windows hosts and iOS/Android clients: the change is pure TypeScript state logic plus the route's existing timer (
scheduleDelayedAction) and toast utilities — no keyboard shortcuts, shortcut labels, file paths, shell behavior, or Electron platform-specific APIs are touched. SSH-hosted and folder (non-worktree) workspaces use the same stream path; the fix is host-agnostic.Security Audit
Host-provided cols/rows are accepted only when they are finite numbers greater than zero; anything else is treated as absent. No command execution, no path handling, no auth or secret handling, and no dependency changes. The host-side change only echoes back viewport values the client itself supplied in the schema-validated
terminal.subscribeparams, so nothing new crosses the RPC boundary. The behavioral direction is defensive: the change strictly reduces client-initiated RPC volume (previously unbounded, now capped at 3 fit attempts per handle per lifetime-with-refill).Notes
terminal.updateViewportRPC (asuseTerminalViewportRefitalready does) over teardown/resubscribe on hosts that support it.