Skip to content

fix(room): fix WebGL leaks and context loss, avatar fallbacks, and spatial physics - #46

Merged
kixelated merged 8 commits into
mainfrom
quest/m1/webgl-physics
Nov 26, 2026
Merged

kixelated merged 8 commits into
mainfrom
quest/m1/webgl-physics

Conversation

@kixelated

@kixelated kixelated commented Nov 26, 2026 •

Copy link
Copy Markdown
Collaborator

Finishes quest/m1/webgl-physics.md (deleted here).

Problem

From the 2026-11-25 audit, re-checked against main after the MoQ bump (#42). All of these were still present:

  • Every tile owned a MeshBuffer, and each of the three renderers cached a VAO per mesh in a map that was never evicted. That leaked 3 VAOs (plus 3 buffers) per join/leave and re-ran bufferData whenever a drag or zoom crossed the subdivision threshold.
  • A lost WebGL context was never handled, so the canvas stayed black until a reload. Canvas.close() also left contexts for GC to collect, even though browsers cap live contexts.
  • The page background shader ran at 60fps on every page, including the web pages where nothing moves over it.
  • The profile preview opened its own AudioContext and fetched all 7 notification .opus files, even on the lobby page, which already has a Sound.
  • u_avatarActive tested the Signal object, so it was always 1. The dead avatar = new Image() field stopped #runAvatar from ever falling back to Api.randomAvatar().
  • Vector.normalize() returned NaN for a zero vector, so a tile leaving from exactly (0, 0) got NaN bounds. Tiles with identical centers never separated.
  • Broadcast.tick decayed deformVelocity and zoomDeform twice per tick.
  • Physics ran on setInterval(1000/60) even in hidden tabs, and its step count was tied to timer delivery rather than elapsed time.
  • Dragging a remote peer replaced the whole peers.positions record, which dropped requests to other peers. Requests were also never removed, so a resubscribe replayed stale moves.

Approach

  • Shared meshes (gl/mesh.ts, gl/context.ts): GLContext owns one static unit quad and one 20×20 grid. Each renderer binds both once through Meshes and draws the grid only while Deform.active is true. The duplicate a_texCoord attribute is dropped because it always equaled a_position.
  • Context loss (canvas.ts, video.ts, space.ts): Canvas.context is a Signal<GLContext | undefined>. It is cleared on webglcontextlost (with preventDefault) and rebuilt on webglcontextrestored. The background renderer, the Space renderers, and each tile's Textures are effects on that signal, and the upload effects re-fill textures from the current frame, avatar, and meme. Canvas.close() frees its context through WEBGL_lose_context.
  • Idle GPU: Canvas.scene replaces onRender. Without a scene (non-room pages), the background is drawn once and then redrawn only on resize or visibility change; a Space sets the scene to animate. Rendering already stopped while the document was hidden.
  • Profile sound: Profile takes the page's sound when it has one (the lobby passes the room's) and creates a muted one only where none exists. Sound now loads notification sounds on first use.
  • Avatars: u_avatarActive reads avatarSize.peek(), and the dead field is removed, so the random-avatar fallback works. The loader keeps the last URL (real or random) while user details are missing or empty, loads each URL once (SVGs at a fixed 512px), and re-uploads it on resize or context restore, so a tile's fallback face never changes and never flashes black.
  • Physics (physics.ts): Stepper counts fixed 60Hz steps from @moq/clock time on each rendered frame. Physics therefore pauses whenever rendering does and runs at the same speed at any frame rate; a stall drops the backlog past 4 steps. Broadcast.step() (physics) is now separate from tick(now) (time-based fades). Deform keeps one decay pass at the product of the old two (0.8 drag, 0.76 zoom), so the feel is unchanged. repel() breaks identical-center ties horizontally. normalize() returns zero for a zero vector, and a tile at the exact center leaves downward.
  • Peer moves (peers.ts): request merges into the record (copying the dragged position) and skips a move the peer already made unless it reverses one in flight. settle drops a request once the peer publishes that x/y/s, and drop removes it when the peer's handle goes away. A local publisher's moves are cleared as soon as it leaves the space, so a reused publisher (a new screen share) can't replay them.
  • Also fixed: the role-specific effects in Space.add and Broadcast.#runTarget are registered only for their role, which removes the "Effect did not subscribe" warnings. A remove() that finishes after Space.close() no longer splices index -1 out of the rip list.

Impact

  • Public API: none (app-internal). Canvas.onRender, Canvas.gl, and Canvas.glContext are replaced by Canvas.scene and Canvas.context. Broadcast.mesh, deformVelocity, and zoomDeform are replaced by Broadcast.deform. Video's texture fields move to Video.textures.
  • Wire: none. peers.positions keeps its shape; it now holds every pending move and drops settled ones.
  • Visual: the page background on non-room pages is a still frame instead of a slow wobble. Physics pauses whenever the canvas isn't rendering.

Alternatives

  • Scaling every physics constant by dt instead of using fixed steps. Rejected: the spring/damping constants were tuned per 60Hz step, and fixed steps keep them exact.
  • Keeping the background animated on web pages at a lower frame rate. Rejected: the quest asked to stop it, and a still frame costs nothing.

Caused by

No single PR. The bugs date from the WebGL renderer and deform-mesh work ported in before this repository's history, and the 2026-11-25 audit (found by check) surfaced them.

Follow-ups

  • quest/m1/remote-control.md (now [M]): the "Remote Control" setting gates whether you can send moves rather than whether others can move you. room/index.ts applies incoming moves unconditionally, and locked() keys on a handle that is always published. Its Plan now also carries the per-move confirmation ID decided below. No open decisions.
  • Also drops the Related link to this quest from quest/m1/peer-avatars.md (merged from main), since this PR deletes the quest.

Overlap

  • #43 (room-media) also edits app/src/room/sound.ts (the lines next to the notification loader this PR makes lazy) and app/src/sup.tsx (separate hunks). Whichever PR lands second resolves a small textual conflict.

Decisions

Maintainer, 2026-11-25 via /quest-run (comment):

  • The open review finding (a self-cancelling peer move can stay queued and later snap a tile back once): ✅ accept it here (rejected: fix it in this PR, drop the PR). Recorded with quest review --accept on e108e35. The per-move confirmation-ID fix changes the hang/location.json wire format and must work with older clients, so it is folded into quest/m1/remote-control.md's Plan.
  • The quest/m1/remote-control.md follow-up: ✅ keep it (rejected: drop it).

Validation

  • quest gate just check: Quest validation, tsc, Biome (one pre-existing warning in components/updater.tsx), API and app tests (all pass, including the new physics.test.ts and peers.test.ts, which use Clock.Manual). bun run build succeeds. Re-run on the head merged with main (fix: recover camera and microphone input toggles #33, fix: preserve speaker gain across reload and mute #35, fix(auth)!: harden OAuth, JWT auth, avatar uploads, and chat sanitization #44): all pass (26 API, 41 app, 2 browser media tests). Main's new changes touch none of this PR's files, so the browser checks below still apply.
  • Real browser (built app, vite preview, Chrome via agent-browser) on /about, whose demo runs a full Space:
    • Tiles fly in and separate. Avatars render. Dragging a tile moves, dims, and deforms it on the grid mesh. Console: no errors or warnings, except meme URL errors caused by VITE_APP_URL, which only the .env.* modes define and the plain preview build lacked.
    • Forced WEBGL_lose_context.loseContext() then restoreContext() on the demo canvas: after restore, the background, tiles, and avatar textures all render again, with no GL errors.
    • The root page background was pixel-identical across ~6s (0 changed pixels in the header strip), while the demo canvas kept animating (7% of pixels changed).
  • Not exercised live:
    • Frame pacing: the harness issues animation frames only on screenshots (rAF 0fps while timers ran), so the Stepper unit tests cover frame-rate independence instead.
    • The Profile preview: /account and the lobby need the API and sign-in.
    • Two-peer dragging: it needs a relay; peers.test.ts covers merge, settle, and drop.

Models

Size: M
Implementer: Claude Code, claude-opus-5-5, high
Implementer: Claude Code, claude-opus-5-5, unknown (iterate, M)

🤖 Generated with Claude Code

(Written by Claude Opus 5.5)

Review

Rewritten by quest review after each round.

  • Head: fff7142

  • Base: origin/main at 048c95a

  • Risk: medium, the base has no RISK.md to name what is always high or customer-facing, so every change is medium

  • Classified: medium by default

  • Reviewer: Codex, gpt-6.2-sol, high effort

  • Session: 01a215f0-0dbe-7f40-97ff-e1cfd732db38, round 4

  • Score: 10/10, The branch can land as is because the maintainer accepted the remaining peer-move issue for follow-up and the new branch changes introduce no findings.

  • Rounds: 4; first round 3 (medium 3); findings 5 (medium 5): fixed 4, refuted 1, open 0

  • Findings: none

  • The last round's findings, at e108e35:

    • Refuted: medium, app/src/room/peers.ts:17: Acknowledge reversals even when the peer is already there; The maintainer accepted the existing behavior for this branch and recorded the deferred wire-format fix in `quest/m1/remote-control.md:26`.

kixelated and others added 3 commits November 25, 2026 19:19
Quest-Claim: 866dd43e79628f90
…s per frame

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Adds the Remote Control follow-up quest.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@kixelated kixelated changed the title Fix WebGL resource leaks, avatar fallbacks, and spatial physics fix(room): fix WebGL leaks and context loss, avatar fallbacks, and spatial physics Nov 26, 2026
kixelated and others added 2 commits November 25, 2026 19:44
…sher, and keep the fallback avatar

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…ves as it leaves

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@kixelated

Copy link
Copy Markdown
Collaborator Author

Maintainer decision (2026-11-25, /quest-run):

  • Accept the open finding (a self-cancelling peer move can replay later). Fold the per-move confirmation-ID fix into quest/m1/remote-control.md.
  • Keep follow-up quest/m1/remote-control.md.
  • Pick: /quest-merge once the new head is reviewed and checks pass.

(Written by Claude Opus 5.5 with high)

@kixelated
kixelated marked this pull request as ready for review November 26, 2026 04:44
@coderabbitai

coderabbitai Bot commented Nov 26, 2026 •

Copy link
Copy Markdown

Warning

Review limit reached

You've used all free OSS reviews for now. Wait for the free limit to reset to keep reviewing this public repository.

Next included review available in 29 minutes.

Check out review usage here.

View limit details

Limit details: You’ve used the included review currently available.

Learn how review limits work.

Review configuration:

Run configuration

  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: Organization UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: bffda45a-8670-4e52-b73b-66742685fb33
Commits

Reviewing files that changed from the base of the PR and between 76d1206 and 00445f0.

Files selected for processing: 21

  • app/src/components/profile.tsx
  • app/src/room/broadcast.ts
  • app/src/room/canvas.ts
  • app/src/room/geometry.ts
  • app/src/room/gl/audio.ts
  • app/src/room/gl/border.ts
  • app/src/room/gl/broadcast.ts
  • app/src/room/gl/broadcast.vert
  • app/src/room/gl/context.ts
  • app/src/room/gl/mesh.ts
  • app/src/room/peers.test.ts
  • app/src/room/peers.ts
  • app/src/room/physics.test.ts
  • app/src/room/physics.ts
  • app/src/room/sound.ts
  • app/src/room/space.ts
  • app/src/room/video.ts
  • app/src/sup.tsx
  • quest/m1/peer-avatars.md
  • quest/m1/remote-control.md
  • quest/m1/webgl-physics.md
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

Share

@kixelated
kixelated enabled auto-merge (squash) November 26, 2026 05:13
@kixelated
kixelated merged commit 86bab84 into main Nov 26, 2026
2 checks passed
@kixelated
kixelated deleted the quest/m1/webgl-physics branch November 26, 2026 05:21
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