Review of PR #819: "fix: a Talk picked right after the page loads connects"
From mnema-talk v3.3.13, rendered on this site.
Head: 129718cde514c01499437acd6f50b309d85dc2d8, branch msch128/talk-join-waits-for-socket.
I read all six changed files in the diff, plus the full current webrtc/session.ts, webrtc/state.ts and stores/socket.ts. I also read the code around the change: App.vue watchers (lines 135-206), lobby.ts, mediaRoom.ts, micPipeline.ts (setupMicPipeline and teardownMicPipeline), voiceAudio.ts cleanupVoiceAudio, peer.ts setupPeerConnection, and the harness fixture.
Local checks (fresh worktree of the PR head)
npm ci: ok.npm run typecheck: ok.npm run lint: ok, so max-lines 400/800, max-lines-per-function 80 and sonarjs cognitive-complexity 15 hold.npx vitest runon useWebRTC.devices, useWebRTC.signaling and screenStartup: 101/101 passed.- Sizes: session.ts has 321 lines, state.ts 213, devices.test.ts 768 (limit 800).
joinVoiceChannelruns from line 121 to 181, so 61 lines. No gates were weakened. - Coverage: these three files alone give session.ts 83 % lines and 65 % branches. The new lines 160-167 and 211 are covered. The 80 % per-file gate counts the whole suite, and the PR says
test:coveragepassed. CI was still pending when I checked. - I also ran scratch probe tests, listed below. They are deleted and nothing was pushed.
1. Root cause: confirmed
sendSocketEvent(stores/socket.ts:241-245) sends only whenws && isConnected. Otherwise the event is dropped without any error.rejoinAfterReconnectruns only fromwatch(reconnectCount)(App.vue:197).reconnectCountis bumped only whenhadConnectionis already set (socket.ts:171), so it never fires on the first open.resumeVoiceSession(App.vue:202-206) runs on the first connect, but it returns early whenvoice.currentChannelIdis already set (session.ts:306). An early manual join sets that.- Result: a
voice_joinsent before the first open is lost, and nothing sends it again. The server never offers. The root cause is real.
2. Races
- Ordering against the reconnect resume: correct.
handleSocketOpensetsisConnected = true(socket.ts:163) and then bumpsreconnectCount(171). That queues two pre-flush jobs: thesocketUpwatcher and App's rejoin watcher. Both run in the same synchronousflushJobspass.resolve()only queues theawaitcontinuation as a microtask, sorejoinAfterReconnectstill seesjoinAwaitsSocket === trueand backs off. I checked this with a probe that wires a realwatchthe way App.vue does: exactly onevoice_join(non-resume) is sent. The PR's own test callsrejoinAfterReconnect()before flipping the socket, which is not the real order, but the outcome is the same. - Leave while waiting:
endCallbumpsjoinGeneration. On wake the join sees the mismatch and returns, and the flag is cleared. Thevoice_leaveis dropped while the socket is down, which is harmless because the server never saw a join. Media and roster cleanup happen inendCall. But see FIX 1: the held stream is not stopped in every pipeline variant. - Joining another channel while waiting: both joins wait. On connect, A's continuation runs first (gen mismatch, so it clears the flag and returns), then B sends. No rejoin can run between the two continuations. Only one join is sent. Fine.
- Several joins of the same channel while waiting:
canJoinVoiceChannellets a second click through, becauselocalAudioStreamis still null while waiting. That second join tears down A's pipeline and asks for the mic again. The older join backs out. The cost is a second getUserMedia, and nothing is wrong on the wire. The mic-wait phase already behaves this way, so I make no change request. - Socket never connects: no timeout. The join promise and its watcher stay pending until the next
isConnectedtrue edge. A leave bumps the generation, so the eventual wake is a no-op. The leak is one watcher closure per abandoned join, which is bounded and acceptable. While waiting, the UI shows the Talk as joined (voice.setChannelmakesvoice.isConnectedtrue), which is also true during the mic wait. The connection banner already explains why. Acceptable. - Reconnect while waiting (the socket was up before, then dropped, then the member joins): the resume is suppressed and the held join sends a fresh
voice_join. That is correct, because the server needs a join for the new channel. - Logout while waiting:
endAccountSessioncallsleaveVoiceChannel(gen++).closeSocketresetshadConnection. On the next login's open, the stale watcher fires, sees the mismatch and clears the flag. NoreconnectCountbump happens for that open, so nothing is suppressed. Fine. - Unmount: the RTC state lives in the composable's shared cx, and
watchis created after severalawaits, so it has no active effect scope. An unmount cannot stop the watcher and strand the flag. Fine.
3. Can the flag get stuck?
It is cleared on both exits after the wait. It can stay up in one case: if setupPeerConnection throws between the wait and line 173. new RTCPeerConnection(rtcConfig) at peer.ts:150 throws on an invalid ICE server entry or under a browser policy. The exception rejects the join, st.joinAwaitsSocket stays true for the page's lifetime, and every later rejoinAfterReconnect returns early. After that, any socket drop in a later call loses that call's media for good. This is an edge case, but the fix costs nothing (FIX 2).
4. Other events that sendSocketEvent drops the same way (not for this PR)
voice_joinof a lobby (lobby.ts:54). Dropped before the first connect. It hasLOBBY_WAIT_MSwith a "lobby unavailable" toast, so it fails visibly rather than hanging. This is the closest sibling of this bug and the strongest follow-up candidate.voice_joinresume (session.ts:216). Pre-existing related issue, confirmed by a probe: a reconnect while the join is still in its microphone wait (prompt open) sendsvoice_join {resume:true}for a join that was never sent, and then the real join follows, so two joins go out. The new flag covers only the socket wait. Setting it fromvoice.setChanneluntil the send would cover both.voice_leave(session.ts:250). A leave while the socket is down is lost. The server holds the seat until its grace time runs out, so others see a ghost member for a short while.webrtc_answer/webrtc_candidate(peer.ts): lost during a drop, then recovered by the resume renegotiating.media_handshake(mediaRoom.ts:18): held untilopenMediaRoom. Wires sent during a drop are lost, then recovered bymediaCall().resume().voice_mute_state,webrtc_subscribe: re-sent byattachSubscriptionson rejoin. Covered.stage_hand/stage_talk_power(useStage.ts),talk_reaction,webrtc_screenshare_start/stop,webrtc_camera_stop,webrtc_layers,webrtc_request_keyframe: user actions during a drop are lost silently, with no retry and no notice. Screenshare and camera start/stop state is not re-announced by the resume path, which deserves a separate check.typing,voice_speakingandwebrtc_diagare ephemeral and fine to drop.
5. Do the tests prove the behaviour?
Yes, they are behavioural. Mutation check:
- Reverting session.ts to main makes all 3 new tests fail.
- Keeping the wait but removing the
joinAwaitsSocketguard inrejoinAfterReconnectmakes "sends no resume beside a join held for the socket" fail.
Gaps:
- No test covers the real event order (socket up, then the reconnect watcher). My probe showed it works.
- No test checks that the microphone is released when a held join backs out.
- No test covers the flag being released when the post-wait code throws.
The harness change (chat.isConnected = true in setup() and in the three direct useChatStore call sites) is needed so that existing tests do not hang on the new wait. It is correct.
6. Repo limits
All within limits, as listed under local checks above. No gate was weakened.
Findings needing a change
FIX 1: microphone left open when a held join backs out. web/src/talk/composables/webrtc/session.ts:164-167.
prepareAudioPipeline stops its streams on a generation mismatch (session.ts:81-89). The new back-out after the socket wait does not. In the normal pipeline the raw capture is in st.rawMicStream, and endCall → teardownMicPipeline stops it. But there are paths where the capture is sent unrouted and never stored in st:
- no AudioContext: micPipeline.ts:321-323 returns
streamdirectly; routeCapturefailing, orcontextStalledwith 100 % volume and no filter: micPipeline.ts:340. In those paths nobody stops the stream.
Failure scenario: the member picks a Talk right after load, in a browser where new AudioContext() throws (WebView or policy). They grant the mic while the socket is still connecting, then click Leave. When the socket comes up, the join returns at line 166 without stopping the tracks. The microphone stays captured, and the OS and browser recording indicator stays on until a reload.
The same leak happens when they join another Talk while waiting, because cleanupVoiceAudio does not know the held stream. I reproduced this with a probe (window.AudioContext throwing, leave while held, then stream.getTracks()[0].stop was never called). The default-pipeline variant of the same probe passes. Before this PR the window between the mic grant and the send had no await, so the leak is new. It can also last a long time, because the reconnect backoff goes up to 30 s and the wait may never end.
Fix: stopStreams(sendStream) in the mismatch branch, matching prepareAudioPipeline. Add a unit test: leave while held, AudioContext unavailable, expect the capture's tracks to be stopped.
FIX 2: the flag can stick if the post-wait code throws. web/src/talk/composables/webrtc/session.ts:171-173.
st.joinAwaitsSocket = false runs only after setupPeerConnection and the send. If new RTCPeerConnection(...) throws (peer.ts:150, for example an invalid ICE server URL from the server's config), the flag stays true. Every later rejoinAfterReconnect in this page then returns early, so after any socket drop in a later call the media is never resumed and the call goes silent.
Fix: clear the flag right after the wait, unconditionally (st.joinAwaitsSocket = false directly after await socketUp(cx) / before the generation check). Nothing async can run between that point and the send, so the reconnect guard is unchanged. Alternatively use try/finally.
Optional, not blocking: follow up separately on the lobby voice_join (lobby.ts:54) and the resume during the mic wait (section 4).
VERDICT: FIX
- web/src/talk/composables/webrtc/session.ts:164-167: stop
sendStreamwhen a join held for the socket backs out. Otherwise, without an AudioContext (or with unrouted capture), a leave or a switch while waiting leaves the microphone captured until a reload. Reproduced with a probe test. - web/src/talk/composables/webrtc/session.ts:171-173: clear
joinAwaitsSocketright after the wait, not aftersetupPeerConnectionand the send. A throwingnew RTCPeerConnectionotherwise leaves the flag up, and every later reconnect resume is suppressed for the page's lifetime.
After the review (added by the author)
- FIX 1: a held join that backs out stops its send stream, as
prepareAudioPipelinedoes. Test: without an AudioContext, a leave while the join is held stops the capture's track. - FIX 2:
joinAwaitsSocketdrops right after the wait, before the generation check. Test: with a throwingRTCPeerConnection, the join rejects and a later reconnect still sends its resume. - Both tests fail with their fix reverted. The socket-wait tests moved to
useWebRTC.socketWait.test.ts, which keepsuseWebRTC.devices.test.tswell below the 800-line limit. - The follow-ups of section 4 (the lobby's
voice_join, a resume during the microphone prompt, and the leave and stage events lost during a drop) are recorded outside this pull request.
Round 2 (head a5aeecd856808eec703e134f3d77eefe7ac8f131)
Changes since 129718cde: session.ts (+7/-4), new useWebRTC.socketWait.test.ts (79 lines), devices.test.ts (-37 lines), doc/security/reviews/2026-11/819.md and its README row.
FIX 1: resolved
session.ts now calls stopStreams(sendStream) in the branch where the join backs out after a generation change. That matches prepareAudioPipeline, and stopStreams handles a null stream. In the routed pipeline, sendStream is the join's own destination stream, so stopping it cannot touch a newer join's capture.
- Test: "releases the microphone of a held join the member left, also when it was sent unrouted" stubs AudioContext and webkitAudioContext as undefined. The harness
afterEachcallsvi.unstubAllGlobals(), so the stub does not leak into other tests. - Mutation: with the
stopStreamsline deleted, that test fails, 1 of 5 in the file.
FIX 2: resolved
st.joinAwaitsSocket = false now runs directly after await socketUp(cx) inside the waiting branch. It is no longer cleared in the mismatch branch, and no longer after the send.
- The ordering argument from round 1 still holds. The flag is cleared in the await continuation, which runs after the flush where App's
reconnectCountwatcher callsrejoinAfterReconnect. That reconnect is still suppressed. - From the clear to the send there is no await, so no resume can slip in between.
- Two joins waiting at once: each continuation clears the flag. No rejoin can run between them. Fine.
- Test: "lets a later reconnect resume the call when setting up the held join threw" makes
RTCPeerConnectionthrow. The join rejects, and a laterrejoinAfterReconnectsendsvoice_join {resume:true}. - Mutation: with the clear moved back to after the send (the round-1 shape), that test fails, 1 of 5.
Test move
The three round-1 tests are in socketWait.test.ts with identical bodies. Only two titles were shortened. devices.test.ts is back to the same content as before the PR (its diff against 129718cde is exactly the removal of those three tests and the flushPromises import).
- Totals: 101 tests in round 1 across devices, signaling and screenStartup. Round 2 runs 103 across those plus socketWait: the 3 moved and 2 new. No test was dropped.
Addendum (doc/security/reviews/2026-11/819.md)
It is a verbatim copy of my round-1 report plus an "After the review" section. That section matches the code:
- FIX 1 and FIX 2 are described correctly.
- "Both tests fail with their fix reverted" is verified above.
- The reason for the move (devices.test.ts stays well below 800) is true: 731 lines.
- It says the section 4 follow-ups are "recorded outside this pull request". I could not see where, so the lead should make sure they are actually tracked.
The README row is accurate.
Checks
npm ci,npm run typecheckandnpm run lintpass.- Targeted vitest run on 4 files: 103/103 passed.
- Sizes: session.ts 324 lines (limit 400).
joinVoiceChannelis about 64 lines (limit 80). socketWait.test.ts 79, devices.test.ts 731 (limit 800). - No gate was changed. My worktree is removed, and nothing was pushed or commented.
VERDICT (round 2): MERGE