Repository navigation
fix(watchtogether): harden realtime sync, room lifecycle, and lobby UX - #273
Conversation
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>
|
Note Currently processing new changes in this PR. This may take a few minutes, please wait... ⚙️ Run configurationConfiguration used: Organization UI Review profile: CHILL Plan: Pro Plus Run ID: 📒 Files selected for processing (3)
📝 WalkthroughWalkthroughWatch-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. ChangesBackend watch-together service and websocket
Estimated code review effort: 4 (Complex) | ~75 minutes Frontend watch-together UI and redirect handling
Estimated code review effort: 4 (Complex) | ~60 minutes 🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 passed)
✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
Comment |
…r noUncheckedIndexedAccess Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
left a comment
There was a problem hiding this comment.
💡 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 |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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.
| if conflict || err != nil { | ||
| return s.prepareSnapshotDispatchesLocked(live), nil |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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>
left a comment
There was a problem hiding this comment.
Actionable comments posted: 7
🧹 Nitpick comments (4)
web/src/components/watchtogether/ConnectionStatusDot.tsx (1)
18-32: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winConsider 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.tsxrenders its own inline dot (member.connected ? "bg-emerald-400" : "bg-white/25") instead of reusing this component. SinceConnectionStatusDotonly accepts the 3-state connection union, it can't be reused as-is for the booleanmember.connectedfield.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.
RoomTerminalStatealways rendersrole="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). Considerrole="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 winAdd
ORDER BYto make idle-room selection deterministic and fair.Without ordering,
LIMIT $2returns 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 winConsider adding unit tests for the fallback branches.
ProfileDisplayNamehas several fallback branches (nil receiver/provider,ForUsererror,GetProfileerror/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
📒 Files selected for processing (22)
internal/api/handlers/watch_together.gointernal/api/router.gointernal/watchtogether/profile_names.gointernal/watchtogether/repository.gointernal/watchtogether/service.gointernal/watchtogether/service_test.gointernal/watchtogether/types.goweb/src/App.tsxweb/src/components/watchtogether/ConnectionStatusDot.tsxweb/src/components/watchtogether/EndWatchPartyDialog.tsxweb/src/lib/watchTogether.tsweb/src/lib/watchTogetherActions.tsweb/src/pages/Profiles.test.tsxweb/src/pages/Profiles.tsxweb/src/pages/WatchTogetherJoin.tsxweb/src/pages/WatchTogetherRoomPage.tsxweb/src/pages/WatchTogetherSuggestionPanel.tsxweb/src/player/components/VideoPlayer.tsxweb/src/player/components/WatchTogetherPanel.tsxweb/src/player/hooks/useWatchTogetherPlaybackSync.tsweb/src/player/hooks/useWatchTogetherRoom.tsweb/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{} |
There was a problem hiding this comment.
🩺 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.
| live.waitingTimer = time.AfterFunc(waitingResumeDeadline, func() { | ||
| s.handleWaitingDeadline(roomID, epoch) |
There was a problem hiding this comment.
🩺 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.
| 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 | ||
| }) |
There was a problem hiding this comment.
🎯 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.
| 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.
| // 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"` | ||
| } | ||
|
|
There was a problem hiding this comment.
🔒 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 -A15Repository: 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.goRepository: 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.tsxRepository: 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.
| // 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); | ||
| }, []); |
There was a problem hiding this comment.
🎯 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.
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
watchTogetherRoomConn.room_closedwithnot_found/endedreasons before closing, so clients can stop reconnecting to dead rooms.persistRoomChangeLockedhelper using the existing generation CAS, with reconciliation that never regresses a newer local generation. This also collapsed six duplicated persist/conflict blocks.ForConnectionmethod family (~450 lines, only referenced by tests, already drifted from the live copies), the unusedRoomCommandDispatcherwiring, and orphaned helpers. Tests now exercise the production entry points.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].ignoreWaitand resumes for everyone ready;ignoreWaitmembers can't drag the room back into waiting and rejoin the barrier on attach/ready. This activates the previously deadignoreWaitfield.readyfrom the previous item's session can't count toward the new one.ListIdleRoomIDsrepo query). Previously rooms accumulated forever in both the map and the DB.members[]withuser_id,profile_id,display_name(resolved viaUserStoreProvider),is_host,is_self,connected. No existing fields changed.Web changes
closedReason(synchronously, so the reconnect loop can't race it) instead of being swallowed; the reconnect-forever "Connecting…" dead end is gone.useWatchTogetherPlaybackSyncreturn is memoized andVideoPlayer'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).RequireAuth/RequireProfilepreserve the destination via?redirect=, and profile selection honors it.watchTogetherActionshelpers 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.role="alert"banners, labeled search/clear controls,inerton the hidden player panel, keyboard-navigable selection-mode radio group.ConnectionStatusDotcomponent (lobby and player previously used different palettes and vocabularies), design-token radii on the Join page, user-facing copy rewrites.useWatchTogetherRoom.ts(345 lines, zero importers).Risks / notes
NewServicesignature changed (dropped unused dispatcher, added profile-name resolver); janitor goroutine starts with the service.membersfield and still handleroom_closed; the JSON ping/pong stays for the client clock-offset estimate.Verification
go build ./internal/...,go test ./internal/watchtogether/... ./internal/api/handlers/— pass;go vetclean;golangci-lintclean on changed code (remaining hits are pre-existing/known local goconst false positives).*ForConnectionentry 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.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