Skip to content

fix(renderer): recover remote tab subscriptions after the stream ends - #21061

Closed
johnmarktaylor91 wants to merge 3 commits into
stablyai:mainfrom
johnmarktaylor91:fix/21052-remote-terminal-tab-sync
Closed

johnmarktaylor91 wants to merge 3 commits into
stablyai:mainfrom
johnmarktaylor91:fix/21052-remote-terminal-tab-sync

Conversation

@johnmarktaylor91

Copy link
Copy Markdown

Related to #21052. This does not claim to fix that incident — the evidence there does not establish which tab-stream failure occurred on the reporter's macOS client. What it does fix is a reproducible defect found while investigating, in the same subsystem, with the same symptom.

The defect

Both saved-environment tab consumers (active-session-subscription.ts, global-session-subscription.ts) install long-lived session.tabs subscriptions, but they:

  • have no terminal-close handler,
  • ignore the stream's end,
  • never re-subscribe.

So when the stream ends, the client keeps its last snapshot and silently stops learning about tabs created on the host. There is no error and no visible cue; the tab list is simply frozen until the app reconnects, at which point every missing tab appears at once.

The change

Handle close and end in both subscription paths, and re-subscribe when the window-visibility parking layer resumes. Three production files, 29 added lines and three replaced lines, plus one regression test covering stream end and resubscription.

Verification

Built from a clean install and ran the existing suites for the touched areas, then the new test:

pnpm install --frozen-lockfile
pnpm build
pnpm test src/main/runtime/runtime-rpc-mobile-terminal-streaming.test.ts \
          src/renderer/src/runtime/web-session-tabs-sync-client-owned-placement.test.ts
# Test Files 3 passed (3), Tests 39 passed (39)
pnpm test src/renderer/src/runtime/web-session-tabs-sync-stream-recovery.test.tsx

Both the baseline and the patched runs exit 0.

What I could not verify

I could not drive two GUI clients against one runtime, so I cannot confirm this is what the reporter hit. Two related findings from the same investigation, offered in case they are useful:

  • Pane output travels on terminal.multiplex, which is excluded from shared-control subscription routing. That is why pane content streams to a remote client live while the tab list does not, and it is worth knowing when reasoning about this class of bug.
  • terminal focus from the CLI sends navigation: 'host', so a remote client calling it gets ok while the navigation happens on the host. That is presumably intended, but it makes "focus reported success and nothing happened" an expected outcome rather than a symptom, which cost some time during triage.

The saved-environment tab consumers install long-lived session.tabs
subscriptions but never handle terminal close, ignore the stream's end
signal, and do not re-subscribe. When the stream ends the client keeps
its last snapshot and silently stops learning about tabs created on the
host, until the app reconnects.

Handle close and end in both subscription paths, and re-subscribe when
the window-visibility parking layer resumes, so a client that loses the
stream recovers instead of going quiet.

Adds a regression test covering stream end and resubscription.
@johnmarktaylor91

Copy link
Copy Markdown
Author

Adding a correction from further testing, so this PR is not read as a fix for #21052.

After the reporter's client was restarted it picked up all missing tabs. Twenty minutes later, with that freshly-reconnected client connected and in use, a newly created terminal again failed to appear. If a stream that ended without recovery were the cause there, a client reconnected twenty minutes earlier would have received it.

So the recovery defect this PR fixes is real and worth fixing on its own merits, but it is not the cause of that issue. I have said the same on #21052. Treat this as an independent robustness fix; the linked issue needs a different diagnosis.

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

ℹ️ No critical issues — one rough edge worth a look.

Reviewed changes

  • Retry callbacks for both tab streams — active-session-subscription.ts and global-session-subscription.ts now receive a requestRetry callback and reattach after the stream ends or the subscription response rejects; both also add onClose: requestRetry.
  • New retry primitive in the parking layer — window-visibility-subscription-parking.ts adds requestRetry to WindowVisibilitySubscriptionContext, fencing the old generation, unsubscribing, and scheduling a retry through the existing backoff helper.
  • Regression coverage — web-session-tabs-sync-stream-recovery.test.tsx exercises close, end, a rejected response, close-before-handle, and unmount cancellation for both subscription methods.

The recovery wiring is directionally right, the generation fence before unsubscribe correctly prevents a re-entrant close from stacking retries, and onError is deliberately left to shared-control replay. One issue inline: the retry that requestRetry schedules never widens its backoff, so a stream that keeps ending is resubscribed about once per second indefinitely.

Pullfrog  | Fix all ➔ | Fix 👍s ➔ | View workflow run | Using DeepSeek Flash (free via Pullfrog for OSS) | 𝕏

Comment on lines +133 to +140
requestRetry: () => {
if (!isCurrent()) {
return
}
// Fence callbacks before unsubscribe, which can synchronously report another close.
entry.generation += 1
unsubscribeEntry(entry, spec)
scheduleRetry(entry, spec)

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.

requestRetry schedules through scheduleRetry, but the counter that drives that backoff is reset to 0 on every successful subscribe (entry.retryAttempt = 0 in the pending-resolution handler at line 162). A stream that ends or is rejected after its handle resolves — exactly the case these new call sites add — therefore always retries at the initial ~1s delay instead of widening toward the 30s cap. The new test's second 1_250ms advance even depends on this (it would fail if the delay grew).

Technical details
# Backoff never widens for stream-end retries

## Affected sites
- `src/renderer/src/runtime/window-visibility-subscription-parking.ts:140` — `requestRetry` calls `scheduleRetry`, whose delay derives from `entry.retryAttempt`.
- `src/renderer/src/runtime/window-visibility-subscription-parking.ts:162` — `entry.retryAttempt = 0` on every successful subscribe resolution.
- `src/renderer/src/runtime/web-session-tabs-sync/active-session-subscription.ts:238,243,279` and `global-session-subscription.ts:187-197` — the new retry call sites (`end` / `ok:false` / `onClose`).

## Sequence
1. `startEntry` subscribes; the handle resolves and `isCurrent()` is true → `retryAttempt = 0`.
2. The stream later emits `end` / `ok:false` / `close` → `requestRetry` → `scheduleRetry`: `retryAttempt === 0` → delay `1000 + jitter`, `retryAttempt = 1`.
3. The retry subscribes; its handle resolves → `retryAttempt = 0` again.
4. Repeat → a fixed ~1s cadence, never `2 ** min(retryAttempt, 5)` toward `WINDOW_VISIBILITY_SUBSCRIPTION_RETRY_MAX_MS`.

Only the subscribe-promise *rejection* handler skips the reset, so rejection-only failures (e.g. a thrown pairing/id mismatch in the preload) do back off.

## Required outcome
A persistently ending or rejecting stream should widen its retry delay toward the 30s cap instead of resubscribing about once per second indefinitely, while the visibility park/resume path keeps resetting so each resume starts fresh.

## Suggested approach (optional)
Track stream-retry attempts separately from subscribe-failure attempts, or pass a flag from `requestRetry` into `scheduleRetry` that suppresses the line-162 reset for a retry cycle; clear the stream-retry counter once a subscription has stayed alive past a threshold.

## Open questions for the human (optional)
- Is a fixed ~1s reattach cadence intentional? The parallel `local-structured-session-tabs-sync/subscription.ts` uses a non-resetting counter (250ms → 5s) for the same reattach case, so the two implementations now diverge.

@coderabbitai

coderabbitai Bot commented Sep 16, 2026 •

Copy link
Copy Markdown
Contributor

Review in Change Stack →

Navigate logical layers of code changes, visualize relationships, and explore their blast radius.

📝 Walkthrough

Walkthrough

The change adds guarded retry support to visibility-managed session subscriptions. Active and global subscriptions request retries after failed responses, end events, and stream closure. The new test suite covers replacement subscriptions, stale updates, repeated retries, synchronous closure, disconnected errors, and unmount cancellation. The pre-commit hook now checks and invokes the shared hook. CLAUDE.md was removed.

Priority: ➖ Normal

Merge Risk: 🟡 Moderate · up to b0b16

Contributors without a global hook path can be blocked from committing. Handle the unset path before merging.

Architecture Summary

Architecture risk: 🔵 Low · up to b0b16

The change affects 2 systems.

Changed systems: src, CLAUDE.md

Architecture concerns
No architecture-level concerns identified.

Review details

Systems and components

  • observed — src (service) was modified; 4 changed files map to changed impact.
  • observed — CLAUDE.md (service) was modified; 1 changed file maps to changed impact.

Before / after behavior

  • observed — Modified behavior in src/renderer/src/runtime/web-session-tabs-sync-stream-recovery.test.tsx: Adds the happy-dom environment annotation and mocks queueAcceptedWebSessionTerminalSnapshot, useRuntimeSessionMirrorEnvironmentKey, and recoverWebSessionTerminalOrphansBeforeApply using the frameOrderingMocks fixtures before the suite definition.
  • observed — Modified behavior in src/renderer/src/runtime/web-session-tabs-sync-stream-recovery.test.tsx: Imports frame-ordering harness helpers (installFrameOrderingHarness, publish, runtimeSubscribe, settle, subscriptions, tabIds, findSubscription), the tab ID mapping helper, and useWebSessionTabsSync, then declares the METHODS list and opens a describe block that installs the harness with fake timers.
  • observed — Modified behavior in src/renderer/src/runtime/web-session-tabs-sync-stream-recovery.test.tsx: Adds a parametrized test for both subscribe methods asserting that, after the original subscription's onClose fires and 1,250 ms elapse, the replacement subscription is published a snapshot containing a new tab and the new tab appears in the tab set, and that publishing a stale updated message with empty tabs on the original subscription does not remove the new tab.
  • observed — Modified behavior in src/renderer/src/runtime/web-session-tabs-sync-stream-recovery.test.tsx: Adds a parametrized test for both subscribe methods asserting that an end message followed by a failed onResponse on the replacement subscription (after a 1,250 ms timer advance each) results in a second replacement subscription being created, demonstrating retry without a visibility change.
🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 50.00% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 4 functions across 4 files. (1 skipped: 1… Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly summarizes the main change: recovering remote tab subscriptions after the stream ends.
Description check ✅ Passed The description explains the defect, the change, the reason for the approach, verification results, and limits of the investigation. It does not use the template headings and omits visual proof, but i…
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.
Full details: Docstring Coverage

Explanation

Docstring coverage is 50.00% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 4 functions across 4 files. (1 skipped: 1 unsupported.)

  • Fix all pre-merge checks with AI

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


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Advanced

Run ID: b185760e-a447-49f6-9f5e-26acaafbb0eb

📥 Commits

Reviewing files that changed from the base of the PR and between bdb1800 and 9ce6fd6.

📒 Files selected for processing (4)
  • src/renderer/src/runtime/web-session-tabs-sync-stream-recovery.test.tsx
  • src/renderer/src/runtime/web-session-tabs-sync/active-session-subscription.ts
  • src/renderer/src/runtime/web-session-tabs-sync/global-session-subscription.ts
  • src/renderer/src/runtime/window-visibility-subscription-parking.ts

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

Comment on lines +133 to +140
requestRetry: () => {
if (!isCurrent()) {
return
}
// Fence callbacks before unsubscribe, which can synchronously report another close.
entry.generation += 1
unsubscribeEntry(entry, spec)
scheduleRetry(entry, spec)

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 | 🟡 Minor | ⚡ Quick win

🔎 Supported by static analysis

🏁 Script executed:

#!/bin/bash
set -euo pipefail

# Locate the runtime subscription type and bridge implementation. Verify whether
# onClose guarantees that the returned subscription promise settles.
rg -n -C 5 \
  -g '*.ts' -g '*.tsx' \
  '\bRuntimeSubscribe\b|runtimeEnvironments.*subscribe|subscribe\s*[:=]\s*.*\(' \
  src mobile

Repository: stablyai/orca

Length of output: 50370


🏁 Script executed:

#!/bin/bash
set -euo pipefail

printf '%s\n' '--- target module ---'
cat -n src/renderer/src/runtime/window-visibility-subscription-parking.ts

printf '%s\n' '--- exact runtimeEnvironments.subscribe references ---'
rg -n -C 4 --glob '*.ts' --glob '*.tsx' \
  'runtimeEnvironments\.subscribe|RuntimeSubscribe' src mobile | head -n 400

Repository: stablyai/orca

Length of output: 34225


🏁 Script executed:

#!/bin/bash
set -euo pipefail
printf '%s\n' '--- target module ---'
cat -n src/renderer/src/runtime/window-visibility-subscription-parking.ts
printf '%s\n' '--- exact runtime subscription references ---'
rg -n -C 4 --glob '*.ts' --glob '*.tsx' \
  'runtimeEnvironments\.subscribe|RuntimeSubscribe' src mobile | head -n 400

Repository: stablyai/orca

Length of output: 34216


🏁 Script executed:

#!/bin/bash
set -euo pipefail
cat -n src/renderer/src/runtime/window-visibility-subscription-parking.ts
rg -n -C 4 --glob '*.ts' --glob '*.tsx' 'runtimeEnvironments\.subscribe|RuntimeSubscribe' src mobile | head -n 400

Repository: stablyai/orca

Length of output: 34148


🏁 Script executed:

#!/bin/bash
set -euo pipefail

printf '%s\n' '--- runtimeEnvironments declarations and implementations ---'
rg -n -C 6 --glob '*.ts' --glob '*.tsx' --glob '*.d.ts' \
  'runtimeEnvironments\s*[:=]|runtimeEnvironments\.subscribe|onClose\s*[:?]|RuntimeSubscriptionCallbacks|subscribeEnvironment|environment.*subscribe' \
  src electron preload main shared | head -n 500

Repository: stablyai/orca

Length of output: 42052


🏁 Script executed:

#!/bin/bash
set -euo pipefail
rg -n -C 6 --glob '*.ts' --glob '*.tsx' --glob '*.d.ts' \
  'runtimeEnvironments\s*[:=]|runtimeEnvironments\.subscribe|RuntimeSubscriptionCallbacks|subscribeEnvironment|environment.*subscribe|onClose\s*[:?]' \
  src electron preload main shared 2>/dev/null | head -n 500

Repository: stablyai/orca

Length of output: 41601


🏁 Script executed:

#!/bin/bash
set -euo pipefail

printf '%s\n' '--- preload subscription implementation ---'
cat -n src/preload/runtime-environment-subscriptions.ts | sed -n '1,180p'

printf '%s\n' '--- main subscribe handler and transport binding ---'
rg -n -C 8 --glob '*.ts' --glob '*.tsx' \
  "runtimeEnvironments:subscribe|subscribeRemoteRuntime|Remote runtime subscription closed before it started|requestId" \
  src/main src/shared | head -n 500

Repository: stablyai/orca

Length of output: 50369


🏁 Script executed:

#!/bin/bash
set -euo pipefail
cat -n src/preload/runtime-environment-subscriptions.ts | sed -n '1,180p'
rg -n -C 8 --glob '*.ts' --glob '*.tsx' \
  "runtimeEnvironments:subscribe|subscribeRemoteRuntime|Remote runtime subscription closed before it started|requestId" \
  src/main src/shared | head -n 500

Repository: stablyai/orca

Length of output: 50369


🏁 Script executed:

#!/bin/bash
set -euo pipefail
cat -n src/renderer/src/runtime/web-session-tabs-sync/active-session-subscription.ts | sed -n '205,255p'

Repository: stablyai/orca

Length of output: 2369


🏁 Script executed:

#!/bin/bash
set -euo pipefail
cat -n src/renderer/src/runtime/web-session-tabs-sync/active-session-subscription.ts | sed -n '255,290p'

Repository: stablyai/orca

Length of output: 1690


Allow a retry to replace an invalidated pending subscription.

The active session passes requestRetry as onClose. The preload subscription removes the close callback before ipc.invoke('runtimeEnvironments:subscribe', ...) settles. If that promise remains pending, entry.pending stays set, so the scheduled startEntry() returns at its pending guard and tab updates stop. Track pending subscriptions by generation and let the retry replace the invalidated pending subscription. Keep the late-resolution guard so stale handles are unsubscribed. Add a test where the first subscription remains unresolved after onClose.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 1


ℹ️ Review info
⚙️ Run configuration
  • Configuration used: Repository UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: b6c91e6c-dd28-4ff9-9756-79d3a8fe9227
📥 Commits

Reviewing files that changed from the base of the PR and between 9ce6fd6 and b0b1653.

📒 Files selected for processing (2)
  • .husky/pre-commit
  • CLAUDE.md
💤 Files with no reviewable changes (1)
  • CLAUDE.md

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 9 remain after this review.

Comment thread .husky/pre-commit
#!/usr/bin/env sh
# Preserve the user's shared commit checks when Husky selects its own hooks directory.
g=$(git config --global --get core.hooksPath)
[ -x "$g/pre-commit" ] || { echo "COMMIT BLOCKED: shared pre-commit hook missing" >&2; exit 1; }

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

🔎 Supported by static analysis

🏁 Script executed:

rg -n --hidden --glob '!**/.git/**' 'core\.hooksPath|COMMIT BLOCKED|shared pre-commit' .

Repository: stablyai/orca

Length of output: 1553


🏁 Script executed:

printf '%s\n' '--- changed paths ---'
git diff --name-status 8153ec2306f2702745184299f72357f901c4142f b0b1653ae34dda2870ba7030caa3851fd7853dd5
printf '%s\n' '--- pre-commit at head ---'
git show b0b1653ae34dda2870ba7030caa3851fd7853dd5:.husky/pre-commit | nl -ba
printf '%s\n' '--- pre-commit diff ---'
git diff --unified=15 8153ec2306f2702745184299f72357f901c4142f b0b1653ae34dda2870ba7030caa3851fd7853dd5 -- .husky/pre-commit
printf '%s\n' '--- setup and hook references ---'
rg -n --hidden --glob '!**/.git/**' --glob '!**/node_modules/**' '(core\.hooksPath|husky|pre-commit|contributor|development setup|getting started|pnpm install)' README* CONTRIBUTING* package.json pnpm-workspace.yaml .github .husky config 2>/dev/null | head -n 240

Repository: stablyai/orca

Length of output: 13412


Skip shared-hook delegation when global core.hooksPath is unset.

When the global setting is unset, g is empty and the check targets /pre-commit. If that file is not executable, the hook exits before pnpm exec lint-staged, blocking commits in this repository. The contributor setup search found no instruction to configure a global hook path. Skip delegation when the path is unset, but keep the error when a configured path has no executable hook.

🐛 Suggested fix
 g=$(git config --global --get core.hooksPath)
-[ -x "$g/pre-commit" ] || { echo "COMMIT BLOCKED: shared pre-commit hook missing" >&2; exit 1; }
-"$g/pre-commit" "$@" || exit $?
+if [ -n "$g" ]; then
+  [ -x "$g/pre-commit" ] || { echo "COMMIT BLOCKED: shared pre-commit hook missing" >&2; exit 1; }
+  "$g/pre-commit" "$@" || exit $?
+fi
 pnpm exec lint-staged

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

Caution

The new .husky/pre-commit guard blocks git commit for any contributor without a machine-global core.hooksPath/pre-commit, and it is unrelated to this PR's tab-subscription fix. Drop that hunk before merging.

Reviewed changes

Since the prior pullfrog review (9ce6fd6), two commits landed that do not touch the tab-sync behavior or its test:

  • Commit-hook guard added — .husky/pre-commit now requires and chains a global core.hooksPath/pre-commit before running lint-staged.
  • CLAUDE.md import shim removed — the one-line @AGENTS.md file is deleted; Claude Code ≥ v2.1.277 reads AGENTS.md directly, so this is the documented @AGENTS.md-workaround cleanup and not a concern.

The tab-subscription recovery itself is unchanged since the prior review, and its one open thread (retry backoff never widening) is untouched by these commits.

Pullfrog  | Fix all ➔ | Fix 👍s ➔ | View workflow run | Using deepseek-v4.1-flash (free via Pullfrog for OSS) | 𝕏

Comment thread .husky/pre-commit
Comment on lines +3 to +5
g=$(git config --global --get core.hooksPath)
[ -x "$g/pre-commit" ] || { echo "COMMIT BLOCKED: shared pre-commit hook missing" >&2; exit 1; }
"$g/pre-commit" "$@" || exit $?

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.

This makes git commit fail for every contributor who has not set a machine-global core.hooksPath with an executable pre-commit: g resolves empty, [ -x "/pre-commit" ] is false, and the hook exits 1 with COMMIT BLOCKED. A clean clone — including this repo's own CI checkout — has no global core.hooksPath, so this is the common case, not an edge case. It also bakes a personal environment concern into a PR about tab subscriptions.

Technical details
# Global pre-commit guard blocks all commits

## Affected sites
- `.husky/pre-commit:3-5` — reads the *global* `core.hooksPath`, then hard-fails when `$g/pre-commit` is not executable.

## Required outcome
- A fresh clone with only the repository's Husky hook must be able to run `lint-staged` and commit successfully, independent of any machine-global git config.

## Suggested approach (optional)
- Revert this hunk to the two-line `pnpm exec lint-staged`, or move the global-hook chaining into an untracked user hook. If a shared staged-content check must run first, commit that check into the repo rather than reading it from global git config.

@johnmarktaylor91

Copy link
Copy Markdown
Author

Closing: superseded by #27098, which fixes the same bug upstream.

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