Skip to content

Reconnect the live view after a dropped connection - #524

Open
masnwilliams wants to merge 6 commits into
mainfrom
hypeship/live-view-auto-reconnect
Open

masnwilliams wants to merge 6 commits into
mainfrom
hypeship/live-view-auto-reconnect

Conversation

@masnwilliams

@masnwilliams masnwilliams commented Nov 23, 2026 •

Copy link
Copy Markdown
Contributor

Summary

On a phone, the live view goes black when the page is locked or backgrounded and never comes back. Two things happen while the page is suspended, and the client recovered from neither:

  • The websocket dies (1006). The client treated any close after connecting as final: a red "websocket closed" notification and "Browser has been shut down and is no longer available", with the browser still running.
  • The server destroys the WebRTC peer while the websocket survives. neko gives up on a peer after 4s without traffic and sends signal/close. The legacy protocol proxy dropped that message (fixed in Forward signal/close to legacy clients neko#39), and on its own the client keeps an open socket and shows a black video element with no message.

On iOS Safari in Low Power Mode the first autoplay can also be refused even muted, which left a black box with no hint that a tap starts it.

This makes the live view restore a dropped session on its own, show what it is doing, and prompt for a tap only when the browser refuses playback of a live stream. It absorbs #521.

Changes

Reconnect (utils/reconnect.ts, neko/base.ts, neko/index.ts)

  • After a connect has succeeded once, these restore the session with a fresh websocket and peer:
    • a websocket close (any code except 4410);
    • signal/close from the server;
    • ICE failed/closed, or disconnected with the socket already gone;
    • a peer that receives no media when the page comes back.
  • Retries back off at 0, 1, 2, 4 and 8s, capped at 10s. A page that hides while an attempt is starting goes back to waiting without counting a failure. A session that drops within 10s of reconnecting keeps backing off, so it can't loop. Nothing is attempted while the page is hidden. visibilitychange (visible), pageshow and online retry at once.
  • When the page comes back with a session that still looks connected, the client checks that RTP bytes are still arriving (2s of getStats). iOS can resume a page with a socket that reads as open and a peer the server already destroyed, and nothing fires. On desktop, where a background tab keeps streaming, this check passes and nothing reconnects.
  • Real end states stop retrying:
    • Before each attempt the client fetches its own live view URL (5s timeout, so a hung fetch on a dead network counts as a network error instead of stalling). The proxy answers 401 ("Live view access has ended": browser deleted or link expired), 403, 404 or 410 once the session is over; that ends it. A 5xx (including the 502 retry page while a browser wakes) or a network error is retried.
    • A close with 4410 (the proxy's session-gone code) ends it.
    • A server system/disconnect ends it, as before (kicked, ...), except connection shutdown. neko sends that as it stops on a restart as well as on teardown, so the socket close that follows decides.
  • disconnect() clears buffered remote ICE candidates, so candidates from a dropped attempt can't reach the next peer.
  • First connects are unchanged (Report live view connect failures by stage, without retrying #417): same stage bounds, one KERNEL_CONNECTION_TIMEOUT/KERNEL_CONNECTION_FAILED, no retry. A failed reconnect attempt posts neither and doesn't give up.
  • The websocket URL template the proxy rewrites to append the token is untouched; the production bundle still contains it exactly once.

UI and parent frame

  • While restoring, the overlay says "Reconnecting..." over the last frame (existing connection.reconnecting string). The red notification only shows when the session has ended. "Browser has been shut down" only shows for a real end state.
  • New messages to the embedding page, in the existing KERNEL_* style:
    • KERNEL_RECONNECTING with attempt, for each pending attempt;
    • KERNEL_DISCONNECTED with reason, once an established session ends;
    • KERNEL_CONNECTED is posted again after a successful reconnect, as on first connect.
  • The dashboard ignores types it doesn't know, so nothing changes there.

Autoplay (from #521, components/video.vue)

  • A play refused with NotAllowedError on a touch device shows "Tap to start live view" (aria-label matches). The text reads "Click to start live view" when the pointer isn't coarse (matchMedia('(pointer: coarse)'), falling back to touch support); the prompt itself still only appears on touch devices.
  • The prompt only renders over a connected session and is cleared on a drop. After a reconnect the new stream's play() runs again, and the prompt returns only if that is refused too.

Testing

  • bun test tests: 299 pass. New tests:

    • the reconnect scheduler: immediate first attempt, a page hiding during the fetch, backoff and cap, no loop on a session that drops right away, waiting while hidden, wake skipping the backoff, no double attempt, refusal ending the session, network errors still attempting, stop;
    • the client: a close after connecting is a recoverable drop with nothing posted; signal/close closes the socket and drops; failed and timed-out reconnect attempts are retried; candidates from a dropped attempt are cleared; without reporting or giving up; a successful reconnect reports connected again; 4410 and server disconnects end the session; a first connect that never succeeded is not recoverable;
    • stream liveness: bytes arriving, no bytes, ICE disconnected, no session;
    • the autoplay prompt: cleared on a drop, shown again if the reconnected play is refused; tap and click text, the fallback without matchMedia, and the aria-label matching the text.

    All but the successful-reconnect test fail against the previous client.

  • npm run build passes with the same lint warnings as main. Prettier is clean.

  • Production browsers. Two fresh headful stealth browsers at 390x844. One got this branch's client hot-patched in (built from the deployed client source plus only this diff; the unpatched rebuild matches the deployed bundle byte for byte), plus a neko binary built from v3.0.8-v1.6.4 with only Forward signal/close to legacy clients neko#39 applied. The other stayed as shipped. Viewer: headless Chromium on desktop, sampling once a second whether the socket was open, whether RTP bytes were arriving, and the overlay text.

    Drop Shipped client + neko This branch + neko#39
    UDP to every remote ICE candidate cut for 12s (server destroys the peer, websocket stays up) media stops, socket open, no message; still black after UDP returns signal/close arrives, "Reconnecting...", new socket and peer, media back ~5s after the drop with UDP still blocked
    Websocket closed "Browser has been shut down and is no longer available", stays "Reconnecting...", media back in ~1s
    supervisorctl restart neko (connection shutdown, then close) not run "Reconnecting..." while neko is down, media back ~5s after neko is ready
    TCP 443 to the host blackholed for 40s, then the session dropped not run "Reconnecting..." throughout; hung attempts time out and back off; media back ~6s after the network returns

    On both, desktop load plays with sound and shows no prompt. The neko log on the patched browser shows the peer destroyed and no couldn't rewrite text message ... signal/close error, followed by the client's new session. Not covered: a real iPhone (in progress), a deleted browser end to end (the probe's 401/410 handling is unit tested), Firefox.

Overlaps #488 (draft), which shows a reload message instead of reconnecting.


Note

High Risk
Changes WebRTC/WebSocket lifecycle, retry policy, and parent-frame KERNEL_* messaging for the live view client—core session connectivity paths with broad mobile/desktop impact.

Overview
Automatically restores a live view after transient drops (websocket close, signal/close, dead media on wake) instead of treating them as fatal shutdowns. A new Reconnector backs off retries, probes the live-view URL before each attempt to stop when the session is truly over (401/403/404/410, WS 4410, server kick), and retries immediately when the page becomes visible or the network returns.

Connection client changes distinguish first-connect failures from recoverable drops: recoverable, streamAlive() via RTP stats, clearing stale ICE candidates, handling signal/close, and only emitting KERNEL_CONNECTION_* on initial connect—not on failed reconnect tries. Embedders get KERNEL_RECONNECTING (with attempt) and KERNEL_DISCONNECTED when a session really ends.

UI: a semi-transparent "Reconnecting…" overlay keeps the last frame visible; the disconnected overlay only shows after a real end. On touch devices, autoplay blocked by NotAllowedError shows a Tap/Click to start live view prompt (connected sessions only, cleared on drop).

Tests cover the reconnect scheduler, dropped-session client behavior, stream liveness, and autoplay prompting.

Reviewed by Cursor Bugbot for commit ad0b828. Bugbot is set up for automated code reviews on this repo. Configure here.

@cursor cursor Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Cursor Bugbot has reviewed your changes using default effort and found 2 potential issues.

Fix All in Cursor

❌ Bugbot Autofix is OFF. To automatically fix reported issues with cloud agents, enable autofix in the Cursor dashboard.

Reviewed by Cursor Bugbot for commit 2ced795. Configure here.

This branch has not been deployed

No deployments
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