Skip to content

fix(mobile): bound terminal viewport resubscribe loop with backoff (STA-3337) - #12362

Merged
brennanb2025 merged 2 commits into
mainfrom
brennanb2025/sta-3337-terminal-resub-loop
Aug 4, 2026
Merged

brennanb2025 merged 2 commits into
mainfrom
brennanb2025/sta-3337-terminal-resub-loop

Conversation

@brennanb2025

Copy link
Copy Markdown
Contributor

Summary

Fixes STA-3337: with the mobile terminal view active, a host that answers terminal.subscribe with an empty scrollback frame and no usable dims sent the client into an unbounded unsubscribe → subscribe loop (~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):

  • Absent host dims are no longer coerced to 80x24 for the fit comparison. A dimless frame can never converge with the phone viewport, so the stream is now held open instead of torn down and re-armed.
  • Viewport-fit resubscribes are budgeted per handle (3 attempts) with escalating backoff (immediate → 750ms → 3s). The live stream stays up through the backoff so input keeps flowing; teardown happens only when the retry fires. The budget refills only when terminal.list drops the handle and later lists it again — the same absence-gated bound the chat-side stream uses in use-mobile-native-chat-terminal-stream.ts, so a still-listed non-converging handle cannot be re-funded on every list refresh.
  • On exhaustion the view degrades visibly instead of hot-looping: the terminal keeps rendering at host dims and the existing toast shows "Couldn't fit the terminal to this screen" once per exhaustion.
  • A fresh post-measure match with the host now counts as convergence (the pre-measure mismatch was a stale cached viewport) instead of forcing another teardown.
  • setTerminalModes keeps the Map identity when the mode didn't change, so same-mode stream frames no longer re-render the whole session route.

Host:

  • The terminal.subscribe scrollback 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 lint
  • pnpm typecheck
  • pnpm test
  • pnpm build
  • Added or updated high-quality tests that would catch regressions, or explained why tests were not needed

pnpm lint (full root suite) and mobile/ pnpm lint both pass. pnpm typecheck run at root and in mobile/. pnpm test = the full mobile suite from mobile/ (391 files, 2915 passed) plus the root suites covering terminal.subscribe (terminal-mobile-subscribe-tab-mount, terminal-subscribe-lease-only, terminal-subscribe-exit-waiter-leak, rpc/streaming); the remaining root suite and pnpm build are 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 subscribeSeqRef before 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, preventing terminal.list refreshes 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.subscribe params, 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

  • Old desktops in the field still emit dimless scrollback on the JSON stream path; the client-side hold covers them without a host upgrade.
  • A PTY that legitimately cannot converge to phone dims (e.g. pinned desktop display mode reporting desktop cols) now stops probing after 3 attempts and announces the degraded state once — the terminal remains usable at host dims, and the long-press sheet keeps working so the user can leave the view.
  • Follow-up candidates (not blockers): the fit pass could prefer the in-place terminal.updateViewport RPC (as useTerminalViewportRefit already does) over teardown/resubscribe on hosts that support it.

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

coderabbitai Bot commented Aug 3, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

The 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)
Check name Status Explanation
Description check ✅ Passed The description covers the summary, screenshots, testing, AI review, security audit, and follow-up notes with sufficient detail.
Title check ✅ Passed The title clearly identifies the mobile terminal viewport resubscribe loop fix, bounded retries, and backoff behavior.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
📝 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: 2


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: fbc9c9f6-3f16-4993-962d-276f46731298

📥 Commits

Reviewing files that changed from the base of the PR and between a7282fe and 0e95581.

📒 Files selected for processing (5)
  • mobile/app/h/[hostId]/session/[worktreeId].tsx
  • mobile/src/session/mobile-terminal-diagnostics.ts
  • mobile/src/session/mobile-terminal-viewport-resubscribe.test.ts
  • mobile/src/session/mobile-terminal-viewport-resubscribe.ts
  • src/main/runtime/rpc/methods/terminal.ts

Comment on lines +114 to +126
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]
}

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

Suggested change
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]
}

Comment on lines +3386 to +3389
// 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,

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.

🚀 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

@brennanb2025

Copy link
Copy Markdown
Contributor Author

QA evidence — post-review head 0e9558112a

Electron (macOS)

Attached to the intended sta-3337-terminal-resub-loop dev instance. The real terminal accepted input and visibly rendered its output.

Electron host terminal

iOS Simulator — iPhone 17 Pro

Ran the development build against the STA-3337 MOCK_NATIVE_CHAT=1 host, which returns subscribed plus empty 80×24 scrollback. After settling, mock totals remained flat at 4 subscribes / 3 unsubscribes across a five-second observation window, leaving one live stream instead of hot-looping. The tab long-press action sheet opened from terminal view and exposed “Switch to chat view,” proving the gesture remained usable after the faulty frame.

iOS terminal long-press after bounded resubscribe

Metro bundled successfully with no redbox. Deterministic review verification also passed 46 focused mobile tests and 114 host streaming/multiplex/mobile-integration tests (2 existing skips), plus mobile typecheck, targeted lint/React checks, formatting, and git diff --check. Live SSH/relay remains unexercised; the shared provider contract and unit coverage were reviewed.

@brennanb2025
brennanb2025 merged commit 0586bab into main Aug 4, 2026
43 checks passed
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
…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
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