Skip to content

fix(watchtogether): harden realtime sync, room lifecycle, and lobby UX - #273

Merged
Quick104 merged 3 commits into
mainfrom
fix/watch-together-review-hardening
Jul 2, 2026
Merged

Quick104 merged 3 commits into
mainfrom
fix/watch-together-review-hardening

Conversation

@Quick104

@Quick104 Quick104 commented Jul 2, 2026 •

Copy link
Copy Markdown
Contributor

Problem

A deep review of the Watch Together feature (server internal/watchtogether + handler, web lobby/player integration) found a crash-grade websocket write race, a client/server error contract that leaves users on an infinite "Connecting…" screen, several stuck-state and griefing hazards in the sync state machine, unbounded resource growth, ~800 lines of dead duplicated code, and a batch of lobby UX/a11y gaps. This PR remediates all verified findings in one pass, per maintainer request.

No pre-existing scope issue covers Watch Together hardening; this work was requested directly from the review session.

Server changes

  • WS write race (critical): pong and error replies wrote to the raw gorilla conn while broadcasts from other members' goroutines wrote through the mutex-guarded wrapper. All writes now go through watchTogetherRoomConn.
  • Terminal error contract: connect failures now send room_closed with not_found/ended reasons before closing, so clients can stop reconnecting to dead rooms.
  • Lock/DB separation: every state mutation previously held the service-wide mutex across Postgres round-trips — one slow query stalled every room. Persistence now happens outside the lock via a shared persistRoomChangeLocked helper using the existing generation CAS, with reconciliation that never regresses a newer local generation. This also collapsed six duplicated persist/conflict blocks.
  • Dead code: deleted the unused non-ForConnection method family (~450 lines, only referenced by tests, already drifted from the live copies), the unused RoomCommandDispatcher wiring, and orphaned helpers. Tests now exercise the production entry points.
  • Latency measurement: transport lead was serverNow − client_sent_at — one-way latency plus client clock skew, spoofable and unclamped (a guest with a skewed clock delayed every command for the whole room). The server now measures RTT from protocol-level ping/pong on its own clock, primed immediately on connect, clamped to [350ms, 5s].
  • Waiting-state deadlock: a not-ready member disconnecting no longer strands the room — readiness is re-evaluated on disconnect. A 30s waiting deadline (epoch-guarded timer) marks stragglers ignoreWait and resumes for everyone ready; ignoreWait members can't drag the room back into waiting and rejoin the barrier on attach/ready. This activates the previously dead ignoreWait field.
  • Host-close timer race: the 15s host-disconnect timer callback now verifies the host is still gone before closing (Timer.Stop can't recall an in-flight callback).
  • Buffering anchor clamp: a buffering report can no longer teleport the shared anchor more than 5s from the expected position.
  • Selection change: switching content clears all members' stale session attachments and readiness, so a ready from the previous item's session can't count toward the new one.
  • Janitor: evicts memberless live rooms from memory and closes rooms idle >24h (new ListIdleRoomIDs repo query). Previously rooms accumulated forever in both the map and the DB.
  • Members in snapshot (additive API): members[] with user_id, profile_id, display_name (resolved via UserStoreProvider), is_host, is_self, connected. No existing fields changed.

Web changes

  • Terminal errors surfaced: REST room fetch 404/410/403 and terminal WS error codes now set closedReason (synchronously, so the reconnect loop can't race it) instead of being swallowed; the reconnect-forever "Connecting…" dead end is gone.
  • Render churn: useWatchTogetherPlaybackSync return is memoized and VideoPlayer's 13-listener video-event effect depends on narrowed primitives — it no longer re-subscribes on every render (this affected all playback, not just watch parties).
  • Invite links survive auth: RequireAuth/RequireProfile preserve the destination via ?redirect=, and profile selection honors it.
  • Lobby UX: proper terminal ended/missing-token states with CTAs (no more contradictory "room ended" + "waiting for host"), End-room confirmation dialog + toasts (shared watchTogetherActions helpers dedupe lobby and player), candidate spotlight clears after "Start for Everyone", connection status + member count visible on mobile, participant list with host badge and guest Leave button, document title, no more raw-UUID flash.
  • A11y: focus-visible reveal + aria labels/pressed on suggestion controls, role="alert" banners, labeled search/clear controls, inert on the hidden player panel, keyboard-navigable selection-mode radio group.
  • Consistency: unified ConnectionStatusDot component (lobby and player previously used different palettes and vocabularies), design-token radii on the Join page, user-facing copy rewrites.
  • Dead code: deleted useWatchTogetherRoom.ts (345 lines, zero importers).

Risks / notes

  • The lock/DB separation is the highest-risk change: correctness still rests on the generation CAS (unchanged), with a documented unlock/relock window and generation-guarded reconciliation. Conflict paths refresh from the DB and converge.
  • Waiting-deadline behavior is new: rooms now resume without stragglers after 30s instead of waiting indefinitely (previously they could hang forever).
  • NewService signature changed (dropped unused dispatcher, added profile-name resolver); janitor goroutine starts with the service.
  • Clients older than this change ignore the new members field and still handle room_closed; the JSON ping/pong stays for the client clock-offset estimate.
  • Follow-ups deliberately not included: per-room locking granularity, participant avatars, Android/Apple client members-list adoption.

Verification

  • go build ./internal/..., go test ./internal/watchtogether/... ./internal/api/handlers/ — pass; go vet clean; golangci-lint clean on changed code (remaining hits are pre-existing/known local goconst false positives).
  • New Go tests: disconnect-resumes-waiting-room, buffering anchor clamp, ping clamp, selection clears stale sessions; existing tests migrated to the production *ForConnection entry points.
  • pnpm run lint (0 errors), pnpm run format:check, tsc --noEmit — clean. vitest: 1126 passed, 4 failed — the 4 are pre-existing failures in unrelated setup-wizard/compat-proxy suites (verified on clean tree; baseline had 8, this branch fixes 4 via a Profiles test mock and adds passing coverage for the redirect flow).
  • make verify-local-paths — clean.
  • No UI screenshots: changes verified via typecheck/lint/tests; the watch-together flows need a live multi-client room to capture meaningfully.

AI-use disclosure

Implemented by Claude Code (Claude Fable 5) from a human-requested deep review; all findings were code-verified before fixing, and the maintainer requested the single-PR remediation.

🤖 Generated with Claude Code

Summary by CodeRabbit

  • New Features
    • Added participant display details in watch parties (names, host/self indicators, connection status).
    • Added a clearer connection indicator and an “end watch party” confirmation dialog.
    • Improved login/profile redirects to return users to their original page.
    • Enhanced the watch-party join screen with accessible keyboard navigation and improved invite/token auto-join UI.
  • Bug Fixes
    • Improved handling of missing/ended/forbidden watch rooms with clearer terminal states.
    • Made watch-party syncing more reliable across buffering, readiness, and reconnect scenarios.

Remediates all findings from a deep review of the Watch Together feature.

Server:
- Serialize every websocket write (pong/error replies bypassed the write
  mutex, racing broadcasts on the same gorilla conn)
- Send room_closed with a reason on terminal connect failures so clients
  stop reconnecting to dead rooms
- Persist room state outside the service-wide mutex via a shared
  generation-CAS helper; drop ~450 lines of dead duplicated methods
- Measure transport latency from server-side ping/pong RTT (was one-way
  client-clock delta, poisoned by clock skew) and clamp the lead time
- Re-evaluate readiness when a waiting participant disconnects and add a
  30s waiting deadline that skips stragglers (activates ignoreWait)
- Guard the host-disconnect close timer against reconnect races
- Clamp buffering-report anchor moves; clear stale member sessions on
  selection change
- Janitor: evict empty live rooms and close rooms idle >24h
- Snapshot gains an additive members list with profile display names

Web:
- Surface terminal room errors (REST 404/410/403 and WS error codes) as
  closedReason instead of reconnecting forever on "Connecting..."
- Memoize the playback-sync hook and narrow VideoPlayer's video-listener
  effect deps to stop re-subscribing 13 listeners on every render
- Preserve invite-link destination through login/profile guards
- Lobby: terminal ended/missing-token states with CTAs, End-room confirm
  dialog, toast feedback via shared action helpers (dedup with player),
  participant list with guest Leave, mobile-visible connection status,
  document title, a11y labels/focus reveal, unified status dot component
- Delete dead useWatchTogetherRoom hook (345 lines, zero importers)

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
@coderabbitai

ghost commented Jul 2, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Note

Currently processing new changes in this PR. This may take a few minutes, please wait...

⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: fd02986a-0f21-4715-b8ba-ee03c9480c0b

📥 Commits

Reviewing files that changed from the base of the PR and between b546712 and 1a9e590.

📒 Files selected for processing (3)
  • internal/watchtogether/service.go
  • internal/watchtogether/service_test.go
  • web/src/pages/WatchTogetherJoin.tsx
 _____________________________________________________________
< What, what, what, what, what, what, what, what, what, what? >
 -------------------------------------------------------------
  \
   \   (\__/)
       (•ㅅ•)
       /   づ
📝 Walkthrough

Walkthrough

Watch-together server logic now measures RTT server-side, emits terminal room-close states, resolves member display names, and evicts idle rooms through new waiting/persistence machinery. The frontend adds shared connection UI, room actions, terminal-state handling, redirect preservation, and accessibility updates.

Changes

Backend watch-together service and websocket

Layer / File(s) Summary
Websocket ping/pong RTT and terminal closes
internal/api/handlers/watch_together.go
Tracks ping send time atomically, measures RTT from pong on the server, sends room_closed messages for not-found and ended rooms, and stops using client-reported latency for ping handling.
Profile display name resolver
internal/watchtogether/profile_names.go, internal/api/router.go
Adds a userstore-backed profile-name resolver with Guest fallback and wires it into NewService.
Idle room query and snapshot member types
internal/watchtogether/repository.go, internal/watchtogether/types.go
Adds an idle-room repository query and extends room snapshots with connected member summaries.
Service state, persistence, and waiting infrastructure
internal/watchtogether/service.go
Adds timing constants, removes dispatcher wiring, introduces optimistic persistence and waiting-deadline helpers, and adds janitor eviction for idle rooms.
Connect, transport, selection, and snapshot flows
internal/watchtogether/service.go
Updates connect/disconnect, attach-session, transport, ready/buffering, ping, policy, selection, and snapshot building to use the new persistence and waiting infrastructure.
Service test suite updates and new coverage
internal/watchtogether/service_test.go
Refactors tests to per-connection APIs and adds coverage for stale session clearing, waiting-room resume, buffering clamping, ping clamping, persistence failure, and stale conflict recovery.

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

Frontend watch-together UI and redirect handling

Layer / File(s) Summary
Shared connection status and end-party dialog components
web/src/components/watchtogether/*, web/src/lib/watchTogether.ts
Adds shared connection status UI, the end-party confirmation dialog, and expanded room member snapshot types.
Watch-together action helpers
web/src/lib/watchTogetherActions.ts
Adds clipboard fallback logic and helper functions for copying invite links, toggling guest control, and ending a room.
Room connection terminal-state handling
web/src/player/hooks/useWatchTogetherRoomConnection.ts, web/src/player/hooks/useWatchTogetherRoom.ts
Removes the old room hook and updates the connection hook to map terminal fetch and websocket errors into closed reasons.
Playback sync hook memoization and cached state
web/src/player/hooks/useWatchTogetherPlaybackSync.ts
Caches room playback state, updates readiness and buffering guards, and memoizes the playback sync API object.
VideoPlayer watch-together wiring update
web/src/player/components/VideoPlayer.tsx
Switches VideoPlayer to the shared action helpers, derives a room-active flag, and updates event handling and effect dependencies.
Panel and room page UI integration
web/src/player/components/WatchTogetherPanel.tsx, web/src/pages/WatchTogetherRoomPage.tsx, web/src/pages/WatchTogetherSuggestionPanel.tsx
Updates the watch-together panel and room page to use shared connection UI, confirmation dialogs, terminal states, participant lists, and accessibility labels.
Join page keyboard nav and auto-join UI
web/src/pages/WatchTogetherJoin.tsx
Adds keyboard-navigable selection mode options, auto-join pending state, and text and styling updates on the join page.
Auth redirect preservation
web/src/App.tsx, web/src/pages/Profiles.tsx, web/src/pages/Profiles.test.tsx
Adds redirect preservation in the app guards, uses sanitized redirect targets in profiles, and updates tests for redirect handling.

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

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title is concise and accurately summarizes the main Watch Together server and web hardening, lifecycle, and UX changes.
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
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix/watch-together-review-hardening

Comment @coderabbitai help to get the list of available commands.

…r noUncheckedIndexedAccess

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: b5467122e6

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

if persistErr != nil {
if errors.Is(persistErr, ErrRoomStateConflict) {
if refreshed != nil {
live.room = *refreshed

ghost Jul 2, 2026

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Don't overwrite newer live state on CAS conflicts

With the new unlock around the database write, another goroutine can advance live.room.Generation while this request is persisting. If this request then loses the CAS, assigning refreshed unconditionally can overwrite that newer in-memory state with an older database row, even though the success path below explicitly guards against regression. In concurrent transport/ready/buffering events this can drop the winner's room mutation and broadcast stale snapshots; guard the conflict refresh by generation or retry/merge before replacing live.room.

Useful? React with 👍 / 👎.

ghost Jul 2, 2026

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Fixed in 1a9e590. persistRoomChangeLocked now (a) decrements the failed writer's own optimistic generation increment under the lock — so each writer's increment is either persisted or undone exactly once and concurrent stacked increments are preserved — and (b) only adopts the conflict-refresh row when refreshed.Generation >= live.room.Generation, so a stale refresh can no longer overwrite a concurrent writer's newer in-memory state. The decrement is what makes the guard safe: without it, a solo writer's failed CAS would leave a phantom local generation that blocks ever adopting the database row. Regression test: TestStaleLiveConflictAdoptsDatabaseRow.

Comment thread internal/watchtogether/service.go Outdated
Comment on lines +1127 to +1128
if conflict || err != nil {
return s.prepareSnapshotDispatchesLocked(live), nil

ghost Jul 2, 2026

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Propagate waiting-resume persistence failures

When the last participant becomes ready or the waiting deadline fires, a non-conflict UpdateAnchor failure reaches this branch as err != nil, but the code still prepares snapshots from the already-mutated in-memory room and returns no error. During a transient database failure, clients are told the room left waiting even though the row was not persisted, so a reload or service restart puts the room back in the old state; propagate the error or roll back instead of broadcasting success.

Useful? React with 👍 / 👎.

ghost Jul 2, 2026

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Fixed in 1a9e590. maybeResumeFromWaitingLocked now snapshots the pre-transition state; on a non-conflict persistence failure it restores the waiting anchor/pause/state fields (the generation rollback happens in the persist helper) and re-arms the 30s waiting deadline so the resume is retried rather than silently dropped — clients keep seeing waiting, matching the database. The disarm now happens only after a successful persist. Regression test: TestReadyPersistFailureKeepsWaitingState.

…state; roll back unpersisted waiting-resume

Addresses Codex review on PR #273:
- persistRoomChangeLocked now undoes the failed writer's optimistic
  generation increment and only adopts the refreshed database row when it
  is at least as new as the local copy, so a stale conflict refresh can
  no longer overwrite a concurrent writer's newer in-memory state (and a
  failed write can no longer leave a phantom generation)
- maybeResumeFromWaitingLocked restores the waiting state and re-arms the
  deadline when the resume transition fails to persist, instead of
  broadcasting a resume the database never recorded

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
@Quick104
Quick104 merged commit 54e796c into main Jul 2, 2026
@Quick104
Quick104 deleted the fix/watch-together-review-hardening branch July 2, 2026 15:34

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

🧹 Nitpick comments (4)
web/src/components/watchtogether/ConnectionStatusDot.tsx (1)

18-32: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Consider extending this to cover boolean member-connection dots too.

The docstring states this component should be used so "every surface uses the same palette + vocabulary," but the participants list in WatchTogetherRoomPage.tsx renders its own inline dot (member.connected ? "bg-emerald-400" : "bg-white/25") instead of reusing this component. Since ConnectionStatusDot only accepts the 3-state connection union, it can't be reused as-is for the boolean member.connected field.

Consider accepting a boolean variant (e.g. state: WatchTogetherConnectionState | boolean) or exporting a small shared boolean-dot helper so both surfaces stay visually consistent as intended.

♻️ Possible approach
-export function ConnectionStatusDot({
+export function ConnectionStatusDot({
   state,
   className = "h-2 w-2",
 }: {
-  state: WatchTogetherConnectionState;
+  state: WatchTogetherConnectionState | boolean;
   className?: string;
 }) {
-  const color =
-    state === "connected"
-      ? "bg-emerald-400"
-      : state === "connecting"
-        ? "animate-pulse bg-amber-300"
-        : "bg-red-400";
+  const resolved = typeof state === "boolean" ? (state ? "connected" : "disconnected") : state;
+  const color =
+    resolved === "connected"
+      ? "bg-emerald-400"
+      : resolved === "connecting"
+        ? "animate-pulse bg-amber-300"
+        : "bg-red-400";
   return <span aria-hidden="true" className={`inline-block rounded-full ${color} ${className}`} />;
 }
🤖 Prompt for 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.

In `@web/src/components/watchtogether/ConnectionStatusDot.tsx` around lines 18 -
32, The participant list is using a separate inline boolean dot instead of the
shared ConnectionStatusDot, so the visual palette and vocabulary can drift.
Update ConnectionStatusDot to support the boolean member-connected case used by
WatchTogetherRoomPage (either by widening state to include boolean or by adding
a small shared boolean-dot helper), then reuse that shared path for
member.connected so both surfaces render the same indicator styles.
web/src/pages/WatchTogetherRoomPage.tsx (1)

319-342: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick win

role="alert" shouldn't wrap interactive buttons.

RoomTerminalState always renders role="alert" around a <Button> (e.g. "Join with a code", "Start a new party"). Per MDN, alert content should only be text — interactive controls (links/buttons) shouldn't live inside an alert region, and alert shouldn't be used for content present at initial page load (the missing-token case fires on first render, not a dynamic transition). Consider role="status" for the message, or drop the live-region role for the initial-load variant and only apply an alert/live-region purely to the text on dynamic close.

♿ Suggested restructuring
   return (
     <div
-      role="alert"
       className="mx-auto flex w-full max-w-5xl flex-col items-center gap-3 px-6 py-24 text-center"
     >
       <div className="bg-surface flex size-16 items-center justify-center rounded-2xl border border-white/10">
         <Users className="text-muted-foreground size-7" />
       </div>
-      <h1 className="mt-2 text-xl font-semibold tracking-tight">{title}</h1>
-      <p className="text-muted-foreground max-w-sm text-sm">{description}</p>
+      <h1 role="status" className="mt-2 text-xl font-semibold tracking-tight">{title}</h1>
+      <p className="text-muted-foreground max-w-sm text-sm">{description}</p>
       <div className="mt-3 flex items-center gap-2">{children}</div>
     </div>
   );

As per MDN: "the alert role should only be used for text content, not interactive elements such as links or buttons."

Also applies to: 567-591

🤖 Prompt for 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.

In `@web/src/pages/WatchTogetherRoomPage.tsx` around lines 319 - 342, The
RoomTerminalState alert region is wrapping interactive buttons, which violates
the intended live-region semantics. Update RoomTerminalState so the text message
is separated from any action controls: keep the announcement role only on the
non-interactive text, and render buttons like “Join with a code” or “Start a new
party” outside that alert region. For the missing-token/initial-load path in
WatchTogetherRoomPage, avoid using an alert live region altogether and prefer a
non-alert layout or role="status" only for dynamic text updates; apply the same
fix to the other terminal-state usage as well.
internal/watchtogether/repository.go (1)

155-184: 🚀 Performance & Scalability | 🔵 Trivial | ⚡ Quick win

Add ORDER BY to make idle-room selection deterministic and fair.

Without ordering, LIMIT $2 returns an arbitrary subset when there are more idle rooms than the limit, which can let the same batch of rooms get skipped repeatedly by the janitor while newer idle rooms crowd them out.

♻️ Proposed fix
 	const query = `
 		SELECT id FROM watch_together_rooms
 		WHERE phase <> 'ended'
 		  AND GREATEST(anchor_updated_at, created_at) < $1
+		ORDER BY GREATEST(anchor_updated_at, created_at) ASC
 		LIMIT $2
 	`
🤖 Prompt for 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.

In `@internal/watchtogether/repository.go` around lines 155 - 184, The idle-room
query in ListIdleRoomIDs is using LIMIT without a stable order, so the janitor
can pick an arbitrary and unfair subset of rooms. Update the SQL in
Repository.ListIdleRoomIDs to add a deterministic ORDER BY on an appropriate
idle-age field (for example the same expression used in the WHERE clause or
another stable timestamp) before LIMIT so older idle rooms are selected first.
internal/watchtogether/profile_names.go (1)

29-42: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Consider adding unit tests for the fallback branches.

ProfileDisplayName has several fallback branches (nil receiver/provider, ForUser error, GetProfile error/nil, empty trimmed name) that drive what every room member sees in the UI. A small table-driven test would lock in this behavior.

🤖 Prompt for 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.

In `@internal/watchtogether/profile_names.go` around lines 29 - 42, Add
table-driven unit tests for ProfileDisplayName to cover every fallback path: nil
receiver/provider, provider.ForUser returning an error or nil store,
store.GetProfile returning an error or nil profile, and a profile name that
trims to empty. Use userStoreProfileNames, ProfileDisplayName, and
fallbackMemberName as the key symbols to locate the behavior, and assert that
each branch returns the fallback name while the happy path returns the
profile.Name.
🤖 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 `@internal/watchtogether/service.go`:
- Line 158: Make Close safe for concurrent callers by removing the race around
janitorStop in the Close method. The current select/default pattern can let
multiple goroutines enter the cleanup path and close janitorStop more than once,
so update the shutdown logic in Close to use a synchronization primitive or
one-time guard that ensures the channel is closed exactly once. Use the Close
method and janitorStop field to locate the fix.
- Around line 1059-1060: The waiting-deadline timer callback is currently tied
only to roomID and epoch, so a queued callback from an old liveRoom can affect a
reloaded room instance after sweepIdleRooms deletes the empty room. Update the
timer setup in the waiting-resume flow around live.waitingTimer, waiting-room
rearm logic, and handleWaitingDeadline so the callback is bound to the specific
liveRoom instance (or validates it is still the same instance) before making any
state changes, and apply the same guard wherever the waiting timer is created or
reset.
- Around line 1126-1129: The resume path in persistAnchorLocked handling is
swallowing real persistence failures by treating err the same as conflict, so
ready flows can report success even when the transition was not saved. Update
the logic around persistAnchorLocked and the resume-from-waiting branch so
conflicts still fall back to prepareSnapshotDispatchesLocked, but any non-nil
error is returned separately and propagated by the user-initiated handlers that
call this path.
- Around line 1005-1024: The persistence flow in the room update helper can
leave live.room ahead of the database when persist(roomCopy, expected) fails,
especially on ErrRoomStateConflict in the refresh path. In this block around the
persist/persistErr handling, make sure live.room is restored from the
pre-mutation state or refreshed from s.repo.GetRoomByID before returning on any
failure, and only keep the mutated state when persistence succeeds. Use the
existing live.room, persisted, refreshed, persistErr, and ErrRoomStateConflict
branches to ensure later snapshots never expose rejected local changes.
- Around line 1290-1298: The member sort in sort.Slice for the members list
still has an unstable tie when DisplayName and ProfileID are equal, so add a
final deterministic comparator using UserID or the member key as the last
fallback. Update the comparison logic in the members ordering block to keep
host-first, then DisplayName, then ProfileID, and finally the new tie-breaker so
members[] stays stable regardless of Go map iteration.

In `@internal/watchtogether/types.go`:
- Around line 77-86: Remove the raw numeric user identifier from MemberSummary
so the snapshot only exposes profile_id, display_name, is_host, is_self, and
connected. Update the MemberSummary struct in watchtogether/types.go to drop
UserID, and then audit any constructors, serializers, or uses of MemberSummary
to ensure they no longer populate or rely on user_id.

In `@web/src/player/hooks/useWatchTogetherRoomConnection.ts`:
- Around line 127-132: clearClosedReasonRef sync reset is missing in the room
recovery flow, so reconnect logic can read a stale terminal reason after leaving
a closed room. Update the reset paths in useWatchTogetherRoomConnection to use a
new clearClosedReason helper (paired with markClosed) that immediately sets
closedReasonRef.current to null before calling setClosedReason(null), and
replace the existing setClosedReason(null) calls in the reset timer paths with
that helper.

---

Nitpick comments:
In `@internal/watchtogether/profile_names.go`:
- Around line 29-42: Add table-driven unit tests for ProfileDisplayName to cover
every fallback path: nil receiver/provider, provider.ForUser returning an error
or nil store, store.GetProfile returning an error or nil profile, and a profile
name that trims to empty. Use userStoreProfileNames, ProfileDisplayName, and
fallbackMemberName as the key symbols to locate the behavior, and assert that
each branch returns the fallback name while the happy path returns the
profile.Name.

In `@internal/watchtogether/repository.go`:
- Around line 155-184: The idle-room query in ListIdleRoomIDs is using LIMIT
without a stable order, so the janitor can pick an arbitrary and unfair subset
of rooms. Update the SQL in Repository.ListIdleRoomIDs to add a deterministic
ORDER BY on an appropriate idle-age field (for example the same expression used
in the WHERE clause or another stable timestamp) before LIMIT so older idle
rooms are selected first.

In `@web/src/components/watchtogether/ConnectionStatusDot.tsx`:
- Around line 18-32: The participant list is using a separate inline boolean dot
instead of the shared ConnectionStatusDot, so the visual palette and vocabulary
can drift. Update ConnectionStatusDot to support the boolean member-connected
case used by WatchTogetherRoomPage (either by widening state to include boolean
or by adding a small shared boolean-dot helper), then reuse that shared path for
member.connected so both surfaces render the same indicator styles.

In `@web/src/pages/WatchTogetherRoomPage.tsx`:
- Around line 319-342: The RoomTerminalState alert region is wrapping
interactive buttons, which violates the intended live-region semantics. Update
RoomTerminalState so the text message is separated from any action controls:
keep the announcement role only on the non-interactive text, and render buttons
like “Join with a code” or “Start a new party” outside that alert region. For
the missing-token/initial-load path in WatchTogetherRoomPage, avoid using an
alert live region altogether and prefer a non-alert layout or role="status" only
for dynamic text updates; apply the same fix to the other terminal-state usage
as well.
🪄 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: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 1d497ee4-c015-478a-9f2a-ef5886d82989

📥 Commits

Reviewing files that changed from the base of the PR and between 3605eec and b546712.

📒 Files selected for processing (22)
  • internal/api/handlers/watch_together.go
  • internal/api/router.go
  • internal/watchtogether/profile_names.go
  • internal/watchtogether/repository.go
  • internal/watchtogether/service.go
  • internal/watchtogether/service_test.go
  • internal/watchtogether/types.go
  • web/src/App.tsx
  • web/src/components/watchtogether/ConnectionStatusDot.tsx
  • web/src/components/watchtogether/EndWatchPartyDialog.tsx
  • web/src/lib/watchTogether.ts
  • web/src/lib/watchTogetherActions.ts
  • web/src/pages/Profiles.test.tsx
  • web/src/pages/Profiles.tsx
  • web/src/pages/WatchTogetherJoin.tsx
  • web/src/pages/WatchTogetherRoomPage.tsx
  • web/src/pages/WatchTogetherSuggestionPanel.tsx
  • web/src/player/components/VideoPlayer.tsx
  • web/src/player/components/WatchTogetherPanel.tsx
  • web/src/player/hooks/useWatchTogetherPlaybackSync.ts
  • web/src/player/hooks/useWatchTogetherRoom.ts
  • web/src/player/hooks/useWatchTogetherRoomConnection.ts
💤 Files with no reviewable changes (1)
  • web/src/player/hooks/useWatchTogetherRoom.ts

hostDisconnectTTL time.Duration
now func() time.Time

janitorStop chan struct{}

ghost Jul 2, 2026

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 | 🟠 Major | ⚡ Quick win

Make Close safe for concurrent callers.

Line 195 can race: two goroutines can both take the default branch before either closes janitorStop, causing a double-close panic.

Proposed fix
 	janitorStop chan struct{}
+	janitorStopOnce sync.Once
 
 	mu    sync.Mutex
 	rooms map[string]*liveRoom
 }
@@
 func (s *Service) Close() {
 	if s == nil || s.janitorStop == nil {
 		return
 	}
-	select {
-	case <-s.janitorStop:
-	default:
+	s.janitorStopOnce.Do(func() {
 		close(s.janitorStop)
-	}
+	})
 }

Also applies to: 191-198

🤖 Prompt for 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.

In `@internal/watchtogether/service.go` at line 158, Make Close safe for
concurrent callers by removing the race around janitorStop in the Close method.
The current select/default pattern can let multiple goroutines enter the cleanup
path and close janitorStop more than once, so update the shutdown logic in Close
to use a synchronization primitive or one-time guard that ensures the channel is
closed exactly once. Use the Close method and janitorStop field to locate the
fix.

Comment thread internal/watchtogether/service.go Resolved
Comment on lines +1059 to +1060
live.waitingTimer = time.AfterFunc(waitingResumeDeadline, func() {
s.handleWaitingDeadline(roomID, epoch)

ghost Jul 2, 2026

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 | 🟠 Major | ⚡ Quick win

Bind waiting-deadline callbacks to the live-room instance.

sweepIdleRooms can delete an empty liveRoom while a stopped timer callback is already queued. If the room reloads and arms a new waiting period with the same epoch, the old callback can act on the new room instance.

Proposed fix
 	epoch := live.waitingEpoch
 	roomID := live.room.ID
+	owner := live
 	live.waitingTimer = time.AfterFunc(waitingResumeDeadline, func() {
-		s.handleWaitingDeadline(roomID, epoch)
+		s.handleWaitingDeadline(roomID, epoch, owner)
 	})
 }
@@
-func (s *Service) handleWaitingDeadline(roomID string, epoch int64) {
+func (s *Service) handleWaitingDeadline(roomID string, epoch int64, owner *liveRoom) {
 	s.mu.Lock()
 	live := s.rooms[roomID]
-	if live == nil || live.waitingEpoch != epoch || live.room.PlaybackState != RoomPlaybackStateWaiting {
+	if live == nil || live != owner || live.waitingEpoch != epoch || live.room.PlaybackState != RoomPlaybackStateWaiting {
 		s.mu.Unlock()
 		return
 	}

Also applies to: 1075-1079, 1156-1164

🤖 Prompt for 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.

In `@internal/watchtogether/service.go` around lines 1059 - 1060, The
waiting-deadline timer callback is currently tied only to roomID and epoch, so a
queued callback from an old liveRoom can affect a reloaded room instance after
sweepIdleRooms deletes the empty room. Update the timer setup in the
waiting-resume flow around live.waitingTimer, waiting-room rearm logic, and
handleWaitingDeadline so the callback is bound to the specific liveRoom instance
(or validates it is still the same instance) before making any state changes,
and apply the same guard wherever the waiting timer is created or reset.

Comment thread internal/watchtogether/service.go Resolved
Comment on lines +1290 to +1298
sort.Slice(members, func(i, j int) bool {
if members[i].IsHost != members[j].IsHost {
return members[i].IsHost
}
if members[i].DisplayName != members[j].DisplayName {
return members[i].DisplayName < members[j].DisplayName
}
return members[i].ProfileID < members[j].ProfileID
})

ghost Jul 2, 2026

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

Add a final tie-breaker for member ordering.

Equal display names and profile IDs still leave ordering dependent on Go map iteration. Add UserID or the member key as a final comparator to keep members[] stable.

Proposed fix
 		if members[i].DisplayName != members[j].DisplayName {
 			return members[i].DisplayName < members[j].DisplayName
 		}
+		if members[i].UserID != members[j].UserID {
+			return members[i].UserID < members[j].UserID
+		}
 		return members[i].ProfileID < members[j].ProfileID
 	})
📝 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
sort.Slice(members, func(i, j int) bool {
if members[i].IsHost != members[j].IsHost {
return members[i].IsHost
}
if members[i].DisplayName != members[j].DisplayName {
return members[i].DisplayName < members[j].DisplayName
}
return members[i].ProfileID < members[j].ProfileID
})
sort.Slice(members, func(i, j int) bool {
if members[i].IsHost != members[j].IsHost {
return members[i].IsHost
}
if members[i].DisplayName != members[j].DisplayName {
return members[i].DisplayName < members[j].DisplayName
}
if members[i].UserID != members[j].UserID {
return members[i].UserID < members[j].UserID
}
return members[i].ProfileID < members[j].ProfileID
})
🤖 Prompt for 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.

In `@internal/watchtogether/service.go` around lines 1290 - 1298, The member sort
in sort.Slice for the members list still has an unstable tie when DisplayName
and ProfileID are equal, so add a final deterministic comparator using UserID or
the member key as the last fallback. Update the comparison logic in the members
ordering block to keep host-first, then DisplayName, then ProfileID, and finally
the new tie-breaker so members[] stays stable regardless of Go map iteration.

Comment on lines +77 to +86
// MemberSummary describes one connected room member in a snapshot.
type MemberSummary struct {
UserID int `json:"user_id"`
ProfileID string `json:"profile_id"`
DisplayName string `json:"display_name"`
IsHost bool `json:"is_host"`
IsSelf bool `json:"is_self"`
Connected bool `json:"connected"`
}

ghost Jul 2, 2026

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.

🔒 Security & Privacy | 🟠 Major | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
rg -n 'user_id' web/src/lib/watchTogether.ts web/src/components/watchtogether web/src/player/components/WatchTogetherPanel.tsx 2>/dev/null
rg -n 'MemberSummary' internal/watchtogether -B2 -A15

Repository: Silo-Server/silo-server

Length of output: 4415


🏁 Script executed:

#!/bin/bash
set -euo pipefail

sed -n '1,220p' web/src/lib/watchTogether.ts
printf '\n---\n'
rg -n '\buser_id\b' web/src/lib/watchTogether.ts web/src -g '!**/*.map'
printf '\n---\n'
sed -n '1288,1320p' internal/watchtogether/service.go
printf '\n---\n'
sed -n '1,140p' internal/watchtogether/types.go

Repository: Silo-Server/silo-server

Length of output: 17817


🏁 Script executed:

#!/bin/bash
set -euo pipefail

rg -n 'WatchTogetherRoomMember|members\?\.|member\.user_id|user_id.*watchtogether|watchTogether' web/src -g '!**/*.map'

Repository: Silo-Server/silo-server

Length of output: 10297


🏁 Script executed:

#!/bin/bash
set -euo pipefail

sed -n '640,760p' web/src/pages/WatchTogetherRoomPage.tsx
printf '\n---\n'
sed -n '1,220p' web/src/player/hooks/useWatchTogetherRoomConnection.ts
printf '\n---\n'
rg -n 'member|members' web/src/pages/WatchTogetherRoomPage.tsx web/src/player/hooks/useWatchTogetherRoomConnection.ts web/src/player/components/WatchTogetherPanel.tsx

Repository: Silo-Server/silo-server

Length of output: 12438


Drop user_id from MemberSummary
The room member list only uses profile_id, display_name, is_host, is_self, and connected; sending the raw numeric user ID to every participant adds unnecessary account identifier exposure.

🤖 Prompt for 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.

In `@internal/watchtogether/types.go` around lines 77 - 86, Remove the raw numeric
user identifier from MemberSummary so the snapshot only exposes profile_id,
display_name, is_host, is_self, and connected. Update the MemberSummary struct
in watchtogether/types.go to drop UserID, and then audit any constructors,
serializers, or uses of MemberSummary to ensure they no longer populate or rely
on user_id.

Comment on lines +127 to +132
// Sets the ref synchronously (before the state commit) so the reconnect
// loop can never fire between setState and the ref-syncing effect above.
const markClosed = useCallback((reason: string) => {
closedReasonRef.current = reason;
setClosedReason(reason);
}, []);

ghost Jul 2, 2026

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

Clear closedReasonRef synchronously too.

markClosed() makes terminal state synchronous, but the reset paths still call setClosedReason(null) only. After leaving a closed room, closedReasonRef.current can remain stale until React commits, so reconnect decisions may still see the previous terminal reason.

Suggested fix
   const markClosed = useCallback((reason: string) => {
     closedReasonRef.current = reason;
     setClosedReason(reason);
   }, []);
+
+  const clearClosedReason = useCallback(() => {
+    closedReasonRef.current = null;
+    setClosedReason(null);
+  }, []);

Then use clearClosedReason() in the reset timer paths instead of setClosedReason(null).

🤖 Prompt for 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.

In `@web/src/player/hooks/useWatchTogetherRoomConnection.ts` around lines 127 -
132, clearClosedReasonRef sync reset is missing in the room recovery flow, so
reconnect logic can read a stale terminal reason after leaving a closed room.
Update the reset paths in useWatchTogetherRoomConnection to use a new
clearClosedReason helper (paired with markClosed) that immediately sets
closedReasonRef.current to null before calling setClosedReason(null), and
replace the existing setClosedReason(null) calls in the reset timer paths with
that helper.

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