Skip to content

refactor(workspace-client,web): standardize reconnecting WS clients on partysocket - #5637

Merged
Kitenite merged 5 commits into
mainfrom
hoakiet98/super-1469-partysocket-ws-consolidation
Jul 12, 2026
Merged

Kitenite merged 5 commits into
mainfrom
hoakiet98/super-1469-partysocket-ws-consolidation

Conversation

@Kitenite

@Kitenite Kitenite commented Jul 12, 2026 •

Copy link
Copy Markdown
Member

Links

Summary

  • Adds createRelaySocket in @superset/workspace-client: a ~75-line wrapper over partysocket's generic reconnecting WebSocket. It re-signs the URL with a fresh token and runs the _whoowns preflight before every attempt, treats a preflight 403 as a definitive denial (permanent close + onAccessDenied, or slow-poll via accessDeniedRetryMs), and disables buffering so send semantics stay "only while open".
  • Migrates the two simplest hand-rolled reconnect loops onto it with zero consumer changes: the eventBus (desktop host events) and web's WebTerminal/TerminalConnection.
  • The desktop terminal transport is deferred by design (its sleep/wake watchdog, coalescer, and socket-identity logic don't map onto partysocket's silent socket swapping) — rationale in the design doc.

Why / Context

The stale-token reconnect-loop bug (#5628, ~25 users/day) existed because three transports each hand-roll backoff + token freshness and drift independently. partysocket's async URL provider — evaluated before every dial — makes that bug class structurally impossible for anything built on the wrapper. Research/selection rationale in the design doc; partysocket is the maintained reconnecting-websocket fork (Cloudflare/PartyKit, 1.3.0 June 2026).

How It Works

  • The preflight lives inside partysocket's async url provider. Spike result (was the design doc's blocking question): a rejecting provider surfaces as an error event and re-enters partysocket's backoff loop — verified in partysocket's source (_connect's catch → _handleError → _connect) and empirically against a live server.
  • eventBus: connect/scheduleReconnect/disposed machinery deleted; partysocket owns reconnection. fs:watch replay still happens on each open. 403 → 5-min slow poll (unchanged semantics from fix(desktop): refresh relay JWT on WS reconnect and stop retrying definitive 403s #5628).
  • Web terminal: keeps the 12-attempt budget (own counter → "error" state, since partysocket's maxRetries exhausts silently), visibility/pageshow/online resume via reconnect() (also the recovery path after budget exhaustion), replay=0 suppression, and fatal exit/error handling. New behavior: web terminals now also get the fly-affinity preflight and fatal-403 handling.
  • Web imports via a new @superset/workspace-client/relay-socket subpath export so the React/tRPC barrel stays out of web's graph.

Manual QA / Verification done

  • Wrapper unit tests (real WS server + scriptable _whoowns): fresh token per attempt, fatal 403 (no dial, single denial callback, CLOSED), 403 slow-poll then recovery when access granted, local URLs skip preflight. Fatal-close test mutation-verified.
  • Live dev desktop (CDP): signed in, sidebar/workspaces load, local /events socket opens through the wrapper (Network.webSocketCreated handshake confirmed), and unreachable relay hosts retry with backoff without console errors (the two React setState warnings present trace to DockBadgeController — pre-existing, unrelated).
  • Not tested live: a real relay-fronted eventBus 403 (needs a second-user setup; covered by the wrapper unit tests and by fix(desktop): refresh relay JWT on WS reconnect and stop retrying definitive 403s #5628's relay-side E2E), and web terminal against production relay (typecheck + identical control-flow mapping; worth a spot check on preview).

Testing

  • bun test packages/workspace-client apps/web (17 pass): wrapper behavior (fresh token per attempt, fatal 403, 403 slow-poll recovery, http→ws conversion), eventBus's first-ever regression suite (listener routing, per-host connection sharing, fs:watch refcounting, watch replay after reconnect, last-listener cleanup), and TerminalConnection (dial shape, binary/control delivery, fresh-token + replay=0 redial, permanent stop on exit). The fresh-token redial test fails if fix(desktop): refresh relay JWT on WS reconnect and stop retrying definitive 403s #5628's stale-URL bug is reintroduced (mutation-verified).
  • TerminalConnection now takes getToken/relayUrl as constructor deps (WebTerminal injects the real ones) so it's unit-testable without web's env/posthog module graph.
  • bun run lint, bunx turbo typecheck --filter=@superset/desktop --filter=@superset/web --filter=@superset/workspace-client
  • Desktop renderer lib suite: only the 10 pre-existing font-test failures (identical on clean main)

Known Limitations

  • Desktop terminal transport still hand-rolled (deferred; see design doc phase 4).
  • partysocket's connectionTimeout (4s default) now applies to both migrated transports — previously unbounded browser default; strictly tighter.

Open in Stage

Summary by cubic

Standardized reconnecting WebSocket clients on partysocket via createRelaySocket that refreshes tokens, preflights on every attempt, converts http→ws, and handles 403s. Migrated the event bus and web terminal; added regression tests, addressing SUPER-1469.

  • Refactors

    • Added createRelaySocket in @superset/workspace-client: fresh token per dial, _whoowns preflight on each attempt, 403 → permanent close or slow‑poll via accessDeniedRetryMs, http(s)→ws(s) conversion, and unbuffered sends by default (maxEnqueuedMessages=0).
    • Moved event bus and WebTerminal/TerminalConnection to the wrapper: event bus replays fs:watch on open and closes when the last listener unsubscribes; terminal injects getToken/relayUrl, keeps the 12‑attempt budget and resumes via reconnect(), sets replay=0 after first bytes, and stops on exit/error.
    • Recorded the verification outcome in plans/done/20260712-partysocket-ws-consolidation.md.
  • Dependencies

    • Added [email protected]; new export @superset/workspace-client/relay-socket; apps/web adds @superset/workspace-client and dev @types/bun (tsconfig includes bun).

Written for commit 7005f11. Summary will update on new commits.

Review in cubic

Summary by CodeRabbit

  • New Features
    • Introduced a reconnecting relay-socket transport with refreshed authentication for terminal streaming and workspace event delivery.
    • Added public exports for relay-socket creation and related types in the workspace-client package (including a new ./relay-socket entry).
  • Bug Fixes
    • Improved reconnect handling across tab visibility and ensured permanent stop on definitive access denial; prevented retry loops after terminal exit.
  • Tests
    • Added Bun coverage for relay probing/reconnect, terminal reconnect/exit behavior, and event-bus routing + fs watch refcounting.
  • Chores
    • Updated workspace-client dependencies/exports and improved web TypeScript environment typings.

…n partysocket (SUPER-1469)

Adds createRelaySocket — a thin wrapper over partysocket's generic
reconnecting WebSocket that re-signs the URL with a fresh token and runs the
_whoowns preflight before every attempt, treats a preflight 403 as a
definitive denial (permanent close, or slow-poll via accessDeniedRetryMs),
and keeps send semantics unbuffered.

Migrates the two simplest hand-rolled reconnect loops onto it with zero
consumer changes:
- workspace-client eventBus (desktop host events)
- apps/web WebTerminal TerminalConnection (kept attempt budget, visibility
  resume, and replay-suppression semantics; web now also gets the fly-affinity
  preflight)

The desktop terminal transport is deferred by design — see
plans/done/20260712-partysocket-ws-consolidation.md.

Spike result: a rejecting async url provider surfaces as an error event and
re-enters partysocket's backoff (verified in source and empirically), so the
preflight can safely live inside the url provider.
@ghost

ghost commented Jul 12, 2026 •

Copy link
Copy Markdown

Ready to review this PR? Stage has broken it down into 7 individual chapters for you:

Title
1 Update design documentation
2 Add partysocket dependency and exports
3 Implement createRelaySocket wrapper
4 Migrate eventBus to use RelaySocket
5 Configure web app dependencies
6 Migrate WebTerminal to RelaySocket
7 Other changes
Open in Stage

Chapters generated by Stage for commit 7005f11 on Jul 12, 2026 9:41pm UTC.

@coderabbitai

coderabbitai Bot commented Jul 12, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

The change adds a shared RelaySocket abstraction backed by partysocket, including token refresh, relay affinity probing, access-denial handling, and retries. Event-bus and web-terminal connections now use it, with package exports, dependency wiring, and connection behavior tests.

Changes

Relay transport consolidation

Layer / File(s) Summary
Relay socket abstraction and public API
packages/workspace-client/src/lib/relaySocket/*, packages/workspace-client/src/index.ts, packages/workspace-client/package.json, plans/done/...
Adds createRelaySocket, per-attempt token signing, affinity probing, access-denial handling, reconnect configuration, package exports, and consolidation records.
Relay socket behavior tests
packages/workspace-client/src/lib/relaySocket/relaySocket.test.ts
Tests fresh tokens, preflight denial, retry probing and recovery, and non-host WebSocket URLs.
Event bus relay integration
packages/workspace-client/src/lib/eventBus.ts, packages/workspace-client/src/lib/eventBus.test.ts
Uses RelaySocket for shared event-bus connections, watch replay, message handling, subscriber cleanup, and reconnect validation.
Web terminal relay integration
apps/web/src/app/workspaces/[workspaceId]/components/WebTerminal/*, apps/web/package.json, apps/web/tsconfig.json
Uses RelaySocket for terminal setup, reconnection, resume handling, terminal messages, disposal, dependency injection, and integration tests.

Estimated code review effort: 4 (Complex) | ~45 minutes

Sequence Diagram(s)

sequenceDiagram
  participant EventBus
  participant TerminalConnection
  participant RelaySocket
  participant Relay
  participant WorkspaceServer
  EventBus->>RelaySocket: create shared connection
  TerminalConnection->>RelaySocket: create terminal connection
  RelaySocket->>Relay: probe affinity and connect with token
  Relay-->>RelaySocket: deliver messages
  RelaySocket-->>EventBus: dispatch server events
  RelaySocket-->>TerminalConnection: deliver binary and control messages
  EventBus->>RelaySocket: replay active fs:watch commands
  RelaySocket->>WorkspaceServer: send watch commands
Loading

Possibly related PRs

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 40.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
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.
Title check ✅ Passed The title accurately summarizes the main change: standardizing reconnecting WebSocket clients on partysocket.
Description check ✅ Passed The description is detailed and covers summary, context, implementation, testing, and limitations, with only minor template sections omitted.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch hoakiet98/super-1469-partysocket-ws-consolidation

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.

@greptile-apps

greptile-apps Bot commented Jul 12, 2026

Copy link
Copy Markdown
Contributor

Greptile Summary

This PR standardizes two reconnecting WebSocket clients on a shared relay socket wrapper. The main changes are:

  • Adds createRelaySocket in @superset/workspace-client.
  • Adds a relay-socket subpath export and partysocket dependency.
  • Migrates the workspace event bus reconnect loop to the wrapper.
  • Migrates the web terminal reconnect loop to the wrapper.
  • Adds wrapper tests for token refresh, preflight handling, and access denial.

Confidence Score: 5/5

This looks safe to merge after checking the terminal replay behavior.

  • The shared wrapper keeps token refresh and preflight logic in one place.
  • The event bus migration preserves open-time watch replay.
  • The terminal reconnect path can skip daemon replay after any received bytes, which may miss output in a narrow disconnect window.

apps/web/src/app/workspaces/[workspaceId]/components/WebTerminal/TerminalConnection.ts

Important Files Changed

Filename Overview
packages/workspace-client/src/lib/relaySocket/relaySocket.ts Adds the shared relay socket wrapper with per-attempt signing, preflight probing, access-denied handling, and partysocket reconnect options.
packages/workspace-client/src/lib/eventBus.ts Replaces the event bus hand-rolled reconnect loop with the shared relay socket and keeps fs:watch replay on open.
apps/web/src/app/workspaces/[workspaceId]/components/WebTerminal/TerminalConnection.ts Moves the web terminal connection lifecycle onto the shared relay socket and keeps terminal state, resume, fatal-close, and replay controls.
packages/workspace-client/package.json Adds the relay-socket subpath export and partysocket dependency.
apps/web/package.json Adds the workspace-client dependency for the web terminal import.

Sequence Diagram

%%{init: {'theme': 'neutral'}}%%
sequenceDiagram
  participant Client as EventBus / WebTerminal
  participant RelaySocket as createRelaySocket
  participant Token as getToken()
  participant Preflight as _whoowns preflight
  participant Socket as partysocket

  Client->>RelaySocket: create socket with buildUrl()
  RelaySocket->>Token: request fresh token
  Token-->>RelaySocket: token
  RelaySocket->>Preflight: probe signed URL
  alt access denied
    RelaySocket->>Client: onAccessDenied()
    RelaySocket-->>Socket: close or delayed retry
  else allowed
    RelaySocket-->>Socket: signed WebSocket URL
    Socket-->>Client: open / message / close events
  end
  Socket->>RelaySocket: reconnect attempt
  RelaySocket->>Token: request fresh token again
Loading
%%{init: {'theme': 'base', 'themeVariables': {"darkMode": true, "background": "#0d1117", "primaryColor": "#21262d", "primaryTextColor": "#e6edf3", "primaryBorderColor": "#8b949e", "lineColor": "#8b949e", "textColor": "#e6edf3", "edgeLabelBackground": "#161b22", "actorBkg": "#21262d", "actorBorder": "#8b949e", "actorTextColor": "#e6edf3", "actorLineColor": "#8b949e", "signalColor": "#8b949e", "signalTextColor": "#e6edf3", "noteBkgColor": "#373320", "noteBorderColor": "#d4a72c", "noteTextColor": "#f0e6c0", "labelBoxBkgColor": "#21262d", "labelBoxBorderColor": "#8b949e", "labelTextColor": "#e6edf3", "loopTextColor": "#e6edf3", "activationBkgColor": "#30363d", "activationBorderColor": "#8b949e"}}}%%
sequenceDiagram
  participant Client as EventBus / WebTerminal
  participant RelaySocket as createRelaySocket
  participant Token as getToken()
  participant Preflight as _whoowns preflight
  participant Socket as partysocket

  Client->>RelaySocket: create socket with buildUrl()
  RelaySocket->>Token: request fresh token
  Token-->>RelaySocket: token
  RelaySocket->>Preflight: probe signed URL
  alt access denied
    RelaySocket->>Client: onAccessDenied()
    RelaySocket-->>Socket: close or delayed retry
  else allowed
    RelaySocket-->>Socket: signed WebSocket URL
    Socket-->>Client: open / message / close events
  end
  Socket->>RelaySocket: reconnect attempt
  RelaySocket->>Token: request fresh token again
Loading
Prompt To Fix All With AI
Fix the following 1 code review issue. Work through them one at a time, proposing concise fixes.

---

### Issue 1 of 1
apps/web/src/app/workspaces/[workspaceId]/components/WebTerminal/TerminalConnection.ts:163
**Replay Skips Missed Output**

When the socket receives any binary bytes before a later disconnect, the next URL adds `replay=0`. If the disconnect happens before xterm has all output from the daemon ring buffer, the reconnect suppresses the server replay that was supposed to fill the gap, so terminal output produced while offline can be lost.

Reviews (1): Last reviewed commit: "refactor(workspace-client,web): standard..." | Re-trigger Greptile

// Once xterm holds scrollback, skip the daemon ring-buffer re-dump on
// reattach; the in-memory buffer still replays output missed offline.
if (this.hasReceivedBytes) url.searchParams.set("replay", "0");
return url.toString();

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.

P2 Replay Skips Missed Output

When the socket receives any binary bytes before a later disconnect, the next URL adds replay=0. If the disconnect happens before xterm has all output from the daemon ring buffer, the reconnect suppresses the server replay that was supposed to fill the gap, so terminal output produced while offline can be lost.

Prompt To Fix With AI
This is a comment left during a code review.
Path: apps/web/src/app/workspaces/[workspaceId]/components/WebTerminal/TerminalConnection.ts
Line: 163

Comment:
**Replay Skips Missed Output**

When the socket receives any binary bytes before a later disconnect, the next URL adds `replay=0`. If the disconnect happens before xterm has all output from the daemon ring buffer, the reconnect suppresses the server replay that was supposed to fill the gap, so terminal output produced while offline can be lost.

How can I resolve this? If you propose a fix, please make it concise.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Pre-existing semantics carried over verbatim from the old implementation (and mirrored in the desktop transport): replay=0 after first bytes is deliberate — the host-side in-memory buffer replays output missed while disconnected; replay only controls the daemon ring-buffer re-dump of scrollback xterm already holds. Not a regression in this PR; if the offline-gap concern is real it predates this change and belongs in a host-service issue.

@github-actions

github-actions Bot commented Jul 12, 2026 •

Copy link
Copy Markdown
Contributor

🧹 Preview Cleanup Complete

The following preview resources have been cleaned up:

  • ✅ Neon database branch

Thank you for your contribution! 🎉

@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

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@packages/workspace-client/src/lib/relaySocket/relaySocket.ts`:
- Around line 48-63: The 403 retry path in provider still passes through
PartySocket’s backoff after sleeping, causing compounded delays. Update the
access-denied handling in provider to use a terminal connection shutdown path
when accessDeniedRetryMs is configured, bypassing PartySocket’s retry/reconnect
state while preserving the callback, configured delay behavior, and immediate
close behavior for unset accessDeniedRetryMs.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 7a7ec1b1-9b38-4e51-a75a-892e23b21280

📥 Commits

Reviewing files that changed from the base of the PR and between b9d862f and 16bf53d.

⛔ Files ignored due to path filters (1)
  • bun.lock is excluded by !**/*.lock
📒 Files selected for processing (9)
  • apps/web/package.json
  • apps/web/src/app/workspaces/[workspaceId]/components/WebTerminal/TerminalConnection.ts
  • packages/workspace-client/package.json
  • packages/workspace-client/src/index.ts
  • packages/workspace-client/src/lib/eventBus.ts
  • packages/workspace-client/src/lib/relaySocket/index.ts
  • packages/workspace-client/src/lib/relaySocket/relaySocket.test.ts
  • packages/workspace-client/src/lib/relaySocket/relaySocket.ts
  • plans/done/20260712-partysocket-ws-consolidation.md

@cubic-dev-ai cubic-dev-ai 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.

2 issues found across 10 files

Prompt for AI agents (unresolved issues)

Check if these issues are valid — if so, understand the root cause of each and fix them. If appropriate, use sub-agents to investigate and fix each issue separately.


<file name="apps/web/src/app/workspaces/[workspaceId]/components/WebTerminal/TerminalConnection.ts">

<violation number="1" location="apps/web/src/app/workspaces/[workspaceId]/components/WebTerminal/TerminalConnection.ts:126">
P2: Terminal retries never reach the 12-attempt error state when `buildUrl`, `getAuthToken`, or the relay URL-provider preflight rejects: those failures emit `error`, but this handler assumes a later `close`. Account for provider-error retries (without double-counting socket errors that do close) so the existing retry budget still bounds this path.</violation>
</file>

<file name="packages/workspace-client/src/lib/relaySocket/relaySocket.ts">

<violation number="1" location="packages/workspace-client/src/lib/relaySocket/relaySocket.ts:56">
P2: When `accessDeniedRetryMs` is configured, the effective retry interval compounds: the provider sleeps for `accessDeniedRetryMs` and then throws, but partysocket treats the rejection as a failed attempt—incrementing its internal retry counter and adding its own exponentially-growing backoff delay before the next `_connect()`. The actual cadence becomes `accessDeniedRetryMs + partysocket_backoff` rather than a fixed `accessDeniedRetryMs` interval.

The test "keeps re-probing at accessDeniedRetryMs" passes only because it uses very short delays (50ms retry + 10–20ms partysocket backoff). With the production value of 5 minutes, the growing library delay would be noticeable after several 403 cycles.

Consider either resetting partysocket's retry state before throwing (via `socket._retryCount = 0` or similar), or restructuring the 403 path to bypass partysocket's backoff entirely (e.g., close + schedule a manual reconnect after `accessDeniedRetryMs`).</violation>
</file>
Architecture diagram
sequenceDiagram
    participant WebTerm as Web Terminal
    participant Desktop as Desktop (eventBus)
    participant RelaySock as createRelaySocket
    participant PartySock as partysocket
    participant Relay as Relay (edge)
    participant Host as Host Service
    participant Auth as auth-token

    Note over RelaySock,PartySock: NEW: Unified reconnecting WS wrapper

    WebTerm->>RelaySock: createRelaySocket(opts)

    Desktop->>RelaySock: createRelaySocket(opts)

    rect rgb(240, 245, 250)
        Note over RelaySock,Auth: On every connection attempt
        PartySock->>RelaySock: async url provider
        RelaySock->>RelaySock: buildUrl() + getToken() → signed URL
        alt URL contains /hosts/ (relay-fronted)
            RelaySock->>Relay: GET /_whoowns (preflight)
            alt 403 (definitive denial)
                Relay-->>RelaySock: 403 Forbidden
                RelaySock->>RelaySock: onAccessDenied()
                alt accessDeniedRetryMs set
                    RelaySock->>RelaySock: sleep(accessDeniedRetryMs)
                    RelaySock-->>PartySock: reject (retry loop)
                else no retry configured
                    RelaySock->>PartySock: close(1000, "denied")
                    RelaySock-->>PartySock: reject (no-op after close)
                end
            else 200 allowed
                Relay-->>RelaySock: OK
                RelaySock-->>PartySock: return signed URL
                PartySock->>Relay: WebSocket upgrade
                Relay->>Host: forward
                Host-->>Relay: upgrade
                Relay-->>WebTerm: open
            end
        else local URL (no /hosts/)
            RelaySock-->>PartySock: return signed URL (no preflight)
            PartySock->>Host: WebSocket upgrade directly
            Host-->>WebTerm: open
        end
    end

    Note over PartySock: partysocket owns backoff<br/>and reconnection

    alt Web Terminal: on open
        PartySock-->>WebTerm: open event
        WebTerm->>WebTerm: reset failedAttempts
        WebTerm->>WebTerm: mark everAttached
    else Web Terminal: on close (unexpected)
        PartySock-->>WebTerm: close event
        WebTerm->>WebTerm: failedAttempts++
        alt failedAttempts >= 12
            WebTerm->>WebTerm: emitState("error")
            WebTerm->>PartySock: close()
        else document.hidden
            Note over WebTerm: frozen tab – don't count
        else
            WebTerm->>WebTerm: emitState(reconnecting|connecting)
            PartySock->>PartySock: auto-reconnect
        end
    else Web Terminal: handleResume (visibility/online)
        WebTerm->>WebTerm: failedAttempts = 0
        alt socket not OPEN or CONNECTING
            WebTerm->>PartySock: reconnect()
        end
    end

    alt eventBus: on open
        PartySock-->>Desktop: open event
        Desktop->>Desktop: replay fs:watch commands
    else eventBus: on close (no more subscribers)
        Desktop->>PartySock: close(1000, "No more subscribers")
    end

    Note over WebTerm,Desktop: Both consumers use same wrapper –<br/>WebTerm adds attempt budget,<br/>eventBus adds fs:watch replay

    Params->>RelaySock: maxEnqueuedMessages: 0 (no buffering)
Loading

Reply with feedback, questions, or to request a fix.

Re-trigger cubic

this.emitState(this.everAttached ? "reconnecting" : "connecting");
});

socket.addEventListener("error", () => {

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.

P2: Terminal retries never reach the 12-attempt error state when buildUrl, getAuthToken, or the relay URL-provider preflight rejects: those failures emit error, but this handler assumes a later close. Account for provider-error retries (without double-counting socket errors that do close) so the existing retry budget still bounds this path.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At apps/web/src/app/workspaces/[workspaceId]/components/WebTerminal/TerminalConnection.ts, line 126:

<comment>Terminal retries never reach the 12-attempt error state when `buildUrl`, `getAuthToken`, or the relay URL-provider preflight rejects: those failures emit `error`, but this handler assumes a later `close`. Account for provider-error retries (without double-counting socket errors that do close) so the existing retry budget still bounds this path.</comment>

<file context>
@@ -67,12 +70,66 @@ export class TerminalConnection {
+			this.emitState(this.everAttached ? "reconnecting" : "connecting");
+		});
+
+		socket.addEventListener("error", () => {
+			// close fires after error; partysocket owns the retry loop.
+		});
</file context>

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Valid gap: provider-side failures (token fetch rejection, preflight throw) surface as error events without a close, so the close-counted budget doesn't see them — worst case is indefinite silent retry with the UI stuck on "connecting" if the token fetch rejects forever. Two mitigating facts: partysocket's own backoff still bounds the retry rate, and this surface (web terminal) is currently unused. Fixing it properly means the wrapper exposing an attempt/error callback rather than consumers guessing event semantics — that's queued as part of the SUPER-1469 phase 4 wrapper API work (desktop terminal migration), where the same accounting is needed for real. Not addressed in this PR.

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.

The parent comment is too broad for this PR: the web terminal surface is currently unused, and the durable attempt/error accounting belongs in the phase 4 wrapper API work. The retry-rate behavior is still bounded by partysocket, but this PR doesn’t need to fix the provider-error accounting path.

if (opts.accessDeniedRetryMs == null) {
socket?.close(1000, "relay access denied");
} else {
await sleep(opts.accessDeniedRetryMs);

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.

P2: When accessDeniedRetryMs is configured, the effective retry interval compounds: the provider sleeps for accessDeniedRetryMs and then throws, but partysocket treats the rejection as a failed attempt—incrementing its internal retry counter and adding its own exponentially-growing backoff delay before the next _connect(). The actual cadence becomes accessDeniedRetryMs + partysocket_backoff rather than a fixed accessDeniedRetryMs interval.

The test "keeps re-probing at accessDeniedRetryMs" passes only because it uses very short delays (50ms retry + 10–20ms partysocket backoff). With the production value of 5 minutes, the growing library delay would be noticeable after several 403 cycles.

Consider either resetting partysocket's retry state before throwing (via socket._retryCount = 0 or similar), or restructuring the 403 path to bypass partysocket's backoff entirely (e.g., close + schedule a manual reconnect after accessDeniedRetryMs).

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At packages/workspace-client/src/lib/relaySocket/relaySocket.ts, line 56:

<comment>When `accessDeniedRetryMs` is configured, the effective retry interval compounds: the provider sleeps for `accessDeniedRetryMs` and then throws, but partysocket treats the rejection as a failed attempt—incrementing its internal retry counter and adding its own exponentially-growing backoff delay before the next `_connect()`. The actual cadence becomes `accessDeniedRetryMs + partysocket_backoff` rather than a fixed `accessDeniedRetryMs` interval.

The test "keeps re-probing at accessDeniedRetryMs" passes only because it uses very short delays (50ms retry + 10–20ms partysocket backoff). With the production value of 5 minutes, the growing library delay would be noticeable after several 403 cycles.

Consider either resetting partysocket's retry state before throwing (via `socket._retryCount = 0` or similar), or restructuring the 403 path to bypass partysocket's backoff entirely (e.g., close + schedule a manual reconnect after `accessDeniedRetryMs`).</comment>

<file context>
@@ -0,0 +1,73 @@
+			if (opts.accessDeniedRetryMs == null) {
+				socket?.close(1000, "relay access denied");
+			} else {
+				await sleep(opts.accessDeniedRetryMs);
+			}
+			// Rejecting aborts this attempt; partysocket surfaces it as an error
</file context>

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Same assessment as the CodeRabbit thread above: bounded at +maxReconnectionDelay (30s on a 5-minute floor), and the option is a minimum interval by contract. Resetting _retryCount would reach into private internals; a parallel manual-reconnect timer re-introduces exactly the hand-rolled state machine this PR deletes. Accepting ≤10% drift on denied-host polling.

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.

The parent comment was too broad here: accessDeniedRetryMs is a minimum slow-poll interval, and the extra partysocket delay is capped at maxReconnectionDelay, so the denied-host cadence stays bounded. I agree with keeping the wrapper as-is rather than reaching into _retryCount or adding a parallel reconnect timer.

…lConnection

eventBus gets its first tests (listener routing, per-host connection sharing,
fs:watch refcounting, watch replay after reconnect, last-listener cleanup).
TerminalConnection takes its env wiring (getToken/relayUrl) via constructor
deps — WebTerminal injects the real ones — so the class is importable in bun
tests without web's env/posthog modules; tests cover dial shape, binary +
control delivery, fresh-token + replay=0 redial, and permanent stop on exit.
The fresh-token redial test fails if the original #5628 stale-URL bug is
reintroduced (mutation-verified). Web tsconfig gains bun test types.
@Kitenite

Copy link
Copy Markdown
Member Author

Perf check — partysocket clones + re-dispatches every message event, and web terminal binary PTY frames now flow through that path, so I benchmarked it (bun, local WS server, 50k × 512B binary frames, median of 3, interleaved):

Path frames/sec median for 50k frames
raw WebSocket.onmessage (old) ~574k 87ms
createRelaySocket listener (new) ~434k 115ms

Overhead ≈ 0.56µs/frame. Real terminal traffic is network- and xterm-render-bound at a few thousand frames/sec, so this is ~0.3% CPU at worst-case output rates — negligible. The desktop terminal transport (the genuinely hot path, unmigrated) is unaffected.

Other perf-relevant deltas, reasoned rather than benched: web terminals gain one preflight RTT before the first dial (deliberate — fly edge affinity + denial visibility, same as desktop already did); reconnect network load strictly decreases (403s now poll at 5min instead of 1–30s exponential); token fetches per attempt are TTL-cached/deduped on both platforms; and partysocket's 4s connectionTimeout makes hung connects retry sooner than the old unbounded browser default.

@Kitenite

Copy link
Copy Markdown
Member Author

Live E2E (CDP + real browser) on this branch — full rig: local relay running this repo's relay code, dev desktop with relay exposure (host-service tunneled), web dev server, Chrome driven via CDP.

Verified end-to-end through the migrated code:

  • Desktop eventBus (wrapper): signed in, workspaces render, local /events socket opens; no new console errors.
  • Web terminal happy path: created a terminal in the workspace page → attached through relay tunnel → typed echo WEB_E2E_$((40+2)) → WEB_E2E_42 echoed back.
  • Access denial in the browser: with an org member lacking a v2_users_hosts row, the relay 403s surface in the web UI; after granting the row (+30s denial-cache expiry) everything works.
  • Reconnect under fire: restarted the relay beneath the live terminal. Network trace shows the exact designed behavior — _whoowns preflight probed with the signed token at exponential backoff (5 × 503 while the tunnel re-registered, no WS dial attempted during failed preflights), then 200 → reattach with scrollback intact → echo RECONNECTED_$((50+5)) → RECONNECTED_55.

The relay-restart recovery is the scenario that used to strand clients; it now self-heals in ~15s with zero user action.

@Kitenite

Copy link
Copy Markdown
Member Author

Stress test: this branch vs revert (old eventBus from main) — identical harness against both implementations: 150 concurrent connections to one WS server, 15,000-event broadcast flood, 3× server flap (mass disconnect), dispose sweep.

Metric OLD (revert) NEW (branch)
Mass connect ×150 52ms 103ms (+0.3ms/conn)
15,000-event flood 63ms 64ms
Delivery 15000/15000 15000/15000
Flap recovery (rapid, 300ms apart) 1062/1089/1065ms 1064/1431/1736ms
Flap recovery (realistic, ≥5s uptime) ~1065ms constant ~1092ms constant
Dials per flap (herd size) 150 (minimal) 150 (minimal)
Dispose all closed, 0 zombies all closed, 0 zombies
JS heap delta +0.9MB +1.6MB (≈ +4.7KB/conn)

Reading: throughput, delivery, herd behavior, and cleanup are at parity. Two intentional differences: (1) under rapid flapping (server bouncing faster than every 5s), partysocket escalates backoff per attempt and only resets after 5s of stable uptime — recovery grows 1.0→1.4→1.7s instead of staying constant. That's protective (a flapping relay gets progressively less hammering) and fully resets with ≥5s uptime, verified above. (2) ~5KB extra heap per connection for the partysocket instance — trivial at realistic host counts.

No regression that would motivate a revert; the rapid-flap backoff escalation is arguably the better behavior for relay protection.

@Kitenite
Kitenite merged commit 7d23b25 into main Jul 12, 2026
19 checks passed
@Kitenite
Kitenite deleted the hoakiet98/super-1469-partysocket-ws-consolidation branch July 12, 2026 22:48

This branch was previously deployed

1 inactive deployment
preview — 7005f11c Deployed Jul 12, 2026 by Kitenite via Deploy Web #6429
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