Skip to content

fix(web): detect half-open server socket with a liveness heartbeat - #6697

Merged
nwparker merged 1 commit into
stablyai:mainfrom
nwparker:nwparker/perf-web-client-heartbeat
Jun 29, 2026
Merged

nwparker merged 1 commit into
stablyai:mainfrom
nwparker:nwparker/perf-web-client-heartbeat

Conversation

@nwparker

@nwparker nwparker commented Jun 29, 2026 •

Copy link
Copy Markdown
Contributor

What

Add an app-level liveness heartbeat to the web/mobile-browser runtime client so it detects a silently half-open WebSocket and reconnects, instead of freezing on stale data.

ELI5

If your phone's connection to the host dies silently (cellular handoff, NAT idle timeout, server crash with no clean close), the browser still thinks the socket is open and just sits there showing stale data forever — it never reconnects because nothing told it the line went dead. This makes the client notice the silence and reconnect.

The problem

The browser WebSocket API handles protocol pings/pongs transparently — they never surface to page JS. So on a half-open connection the socket stays readyState === OPEN with no onclose/onerror, and the only reconnect triggers (onclose/onerror) never fire. The server's 15s ping reaps the server's view of the client, but that signal is invisible to the browser. Result: silent UI freeze until a manual reload.

(Desktop/main-process transports are unaffected — they already heartbeat via real ws ping/pong.)

The fix

A liveness watchdog on the connected socket:

  • every inbound frame (reply, subscription push, keepalive, probe echo) stamps lastInboundFrameAt and clears any outstanding probe;
  • a visibility-gated 10s interval, after 25s of silence, sends a cheap fire-and-forget status.get probe (id intentionally unmatched → adds no pending request/timeout);
  • only if that sent probe stays unanswered for another 20s does it ws.close() to drive the existing scheduleReconnect() path.

Closing is gated on an unanswered probe, never on raw accumulated silence, and a suspended tick loop (backgrounded/frozen tab — a tick landing ≥2 intervals late) re-baselines the liveness clocks. Together these guarantee a tab backgrounded for minutes can't be mistaken for a dead socket and false-close its live subscriptions on resume.

No server change: the client already calls status.get over this connection, and any inbound frame already proves liveness server-side.

Measurement

Pair a browser client, then silently drop the host's packets (a firewall rule that DROPs rather than RSTs the port). Before: the client never reconnects until a manual reload. After: it detects the gap and reconnects in ~45–55s.

Degraded UX

One tiny frame per ~25s only while the tab is visible and the connection has gone quiet — negligible traffic, skipped entirely while hidden (battery). No behavior change on a healthy connection. Trade-off: worst-case dead-socket detection is ~45–55s (vs. an unbounded freeze today); this latency is the deliberate cost of guaranteeing a real round-trip attempt before declaring the socket dead (no false positives).

Tests

web-runtime-client-heartbeat.test.ts drives the watchdog with injected time/visibility: idle probe, probe-unanswered close + reconnect, the hidden→visible no-false-close regression, hidden-tab skip, non-connected skip, inbound-frame reset. All 78 web tests pass.

Verification

Independent adversarial review across two rounds. Round 1 caught a real false-close on the hidden→visible transition (raw-silence close); this PR fixes it by gating the close on an unanswered probe + suspended-tick re-baseline. Round 2 verdict: SAFE — false-close now structurally impossible, dead sockets still detected within ~45–55s, no masking of real deaths, no new leak/double-arm/probe-id collision.

Made with Orca 🐋

The browser WebSocket API hides protocol pings/pongs, so when the server
connection goes dark without a FIN/RST (mobile NAT idle timeout, server crash,
wifi->cellular handoff) the socket stays readyState===OPEN with no
onclose/onerror. The web/mobile client then silently freezes on stale data and
never reconnects until a manual reload — the server-side 15s ping reaps the
server's view of the client, but that signal is invisible to page JS.

Add an app-level liveness watchdog on the connected socket:
- every inbound frame (reply, subscription push, keepalive, probe echo) stamps
  lastInboundFrameAt and clears any outstanding probe;
- a visibility-gated 10s interval, after 25s of silence, sends a cheap
  fire-and-forget status.get probe (id intentionally unmatched, so it adds no
  pending request/timeout);
- ONLY if that sent probe stays unanswered for another 20s does it close the
  socket to drive the existing scheduleReconnect() path.

Closing is gated on an unanswered PROBE, never on raw accumulated silence, and a
suspended tick loop (backgrounded/frozen tab: a tick landing >=2 intervals late)
re-baselines the liveness clocks. Together these guarantee a tab backgrounded
for minutes cannot be mistaken for a dead socket and false-close its live
subscriptions on the first tick after returning to the foreground.

No server change: the client already calls status.get over this connection, and
any inbound frame already proves liveness server-side. The probe is skipped
while the tab is hidden (no visible stale data, saves battery). Desktop/main
transports are untouched — they already heartbeat via ws ping/pong.

Degraded UX: one tiny frame per ~25s only while the tab is visible and the
connection has gone quiet; negligible traffic, no behavior change on a healthy
connection.

Adds a deterministic heartbeat test suite driving the watchdog with injected
time/visibility: idle probe, probe-unanswered close + reconnect, the
hidden->visible no-false-close regression, hidden-tab skip, non-connected skip,
and inbound-frame reset. Provides setInterval/clearInterval in the existing
client test's window stub now that 'connected' arms an interval.

Co-authored-by: Orca <help@stably.ai>
@coderabbitai

coderabbitai Bot commented Jun 29, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

WebRuntimeClient gains a liveness heartbeat watchdog implemented via setInterval. New timing constants define the idle threshold, probe grace window, and tick interval. New private fields track the last inbound frame timestamp, last tick timestamp (for detecting suspended timers), and whether a status.get probe is in-flight. On each inbound WebSocket frame, liveness timestamps are reset and any outstanding probe is cleared. The tick function suppresses probing when the document is hidden, re-baselines clocks after a suspended timer gap, sends an encrypted status.get probe after sufficient idle silence, and closes the socket if a probe goes unanswered beyond the grace window. Start/stop hooks are added to the connected-state transition, socket-closure path, and general timer-cleanup routine. A new Vitest suite covers all scenarios using a FakeWebSocket and overridable now/isDocumentVisible seams.

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Description check ⚠️ Warning The description explains the change well but omits required template sections for Screenshots, AI Review Report, Security Audit, and Notes. Reformat the PR description to match the repository template and add the missing Summary, Screenshots, Testing, AI Review Report, Security Audit, and Notes sections.
Docstring Coverage ⚠️ Warning Docstring coverage is 33.33% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed The title is concise and accurately summarizes the main change: a liveness heartbeat for half-open WebSocket detection.
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.

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

Run ID: 2170279a-efbe-4d10-93cf-5043b95e9339

📥 Commits

Reviewing files that changed from the base of the PR and between 1dc63e9 and 4cc8b1e.

📒 Files selected for processing (3)
  • src/renderer/src/web/web-runtime-client-heartbeat.test.ts
  • src/renderer/src/web/web-runtime-client.test.ts
  • src/renderer/src/web/web-runtime-client.ts

Comment on lines +194 to +196
// A reply lands: onmessage stamps lastInboundFrameAt and clears the probe.
internals.lastInboundFrameAt = internals.now()
internals.heartbeatProbeSentAt = null

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

Exercise the real onmessage path here.

These lines manually reset heartbeat state, so the test never verifies the upstream contract in src/renderer/src/web/web-runtime-client.ts:393-405 that inbound frames clear heartbeatProbeSentAt and refresh lastInboundFrameAt. If that wiring regresses, this test still passes. Stub handleSocketMessage and invoke socket.onmessage?.(...) instead.

@nwparker
nwparker merged commit aa79465 into stablyai:main Jun 29, 2026
2 checks passed
@nwparker
nwparker deleted the nwparker/perf-web-client-heartbeat branch June 29, 2026 04:16
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
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