/ concept-collection / commonroom
Sign in
concept-collection / commonroom
commonroom / CLAUDE.md
119 lines · 7.6 KBPreviewCodeBlameHistoryRaw
1# CLAUDE.md
3Tips for future agents working in this repo. It combines the p2p techniques of
4the sibling projects `commonview` (auto-connecting mesh) and `commoncall`
5(WebRTC media, settings, screen share) — read those first; this file only
6covers what is different here.
8## Architecture
10```
11src/p2p/
12 identity.ts schnorr keypair; pubkey hex = peer ID — ported from commoncall
13 nostr.ts minimal relay client + topic scheme — ported (roomTopic takes a room ID)
14 peer.ts WebRTC wrapper: media + control channel — ported (replaceTrack generalized to audio|video)
15 settings.ts shared ROOM settings, quality presets — default quality is 'medium', not 'auto'
16 turn.ts optional TURN: build-time endpoint, credential fetch, sanitizers
17 network.ts the heart: rooms, presence, mesh, media, settings sync, relay sharing
18src/App.tsx landing form (light) + in-room view (dark), video grid with
19 click-to-spotlight (gallery ↔ one big tile + filmstrip; Esc or
20 click again to return), control bar, chat panel (side panel on
21 wide screens, overlay ≤700px, unread badge)
22worker/ Cloudflare Worker that mints TURN credentials — deployed
23 separately (wrangler), NOT part of `npm run build`
24```
26## Key design decisions
28- **Rooms, no registry.** The room ID is any string (whitespace stripped,
29 exact otherwise, case-sensitive); `roomTopic` hashes it into the nostr
30 presence topic. The URL hash holds the room (`#<encoded-room>`) so the
31 address bar is the invite link.
32- **Auto-mesh, no consent handshake.** Unlike commoncall, entering the room IS
33 the consent: on every presence announcement, `maybeConnect` brings up a
34 `Peer` (initiator = smaller peer ID, commonview's stalled-connection retry
35 at 15 s). All of commoncall's call-request/accept machinery is gone.
36- **Muted by default; placeholder tracks.** getUserMedia runs at entry but
37 tracks start `enabled = false`. Every participant ALWAYS carries exactly one
38 audio + one video track (denied/missing devices get a silent
39 AudioContext-destination track / black canvas-capture track), so
40 offer/answer stays symmetric and the one-offer, no-renegotiation design
41 holds. Unmuting without a real device retries getUserMedia and upgrades the
42 placeholder via `replaceTrack` on every connection. getUserMedia failures
43 surface a cause-specific notice (`mediaErrorMessage`: permission vs
44 not-found vs device-busy, error name included) both at join and on retry —
45 on Linux, a camera held by another browser fails with NotReadableError,
46 which is NOT a permissions problem. The combined audio+video request fails
47 as a whole in that case, so `acquireMedia` retries each kind separately.
48- **Soft cap of 8** (`MAX_PARTICIPANTS`). A peer already holding 7 connections
49 answers an unknown peer's announcement/offer with `{t:'room-full'}` on the
50 newcomer's topic instead of connecting; a newcomer with zero connections
51 that receives room-full tears down and shows a notice. Two simultaneous
52 joiners racing for the last slot can briefly exceed the cap — accepted.
53- **Settings are room-wide, multi-party LWW.** One entry per key in
54 `settingsMeta` (`{rev, by}`); changes broadcast `{t:'set', key, value, rev,
55 by}` to all peers (complete graph — no relaying), late joiners get every
56 entry inside each peer's `hello`, and a same-rev tie is won by the SMALLER
57 setter ID. Default quality is `medium` — so quality caps are applied to each
58 sender on connect (`applyVideoParamsTo`, with one delayed retry because
59 encodings may not exist right at 'connected'), not only on change.
60- **Mute is per-participant, NOT a shared setting** — same as commoncall: own
61 flags, `{t:'mute'}` notices, `track.enabled` toggling, and the notice
62 carries the EFFECTIVE outgoing video state (screen share overrides camera
63 mute). Remote participants are assumed muted until told otherwise.
64- **Screen share = track swap on every connection.** `getDisplayMedia` +
65 `replaceTrack` per peer; a peer that joins mid-share gets the screen track
66 from `outgoingStream()`. Same-kind replacement avoids renegotiation — never
67 addTrack mid-connection.
68- **Chat is ephemeral and never relayed.** `{t:'chat', text}` broadcasts on
69 the control channels; every message arrives directly from its author over a
70 channel established via signed signaling, so authorship needs no extra
71 crypto. There is deliberately NO history replay for late joiners — replay
72 would mean peers relaying others' messages, which a malicious peer could
73 fabricate; adding history requires signing each message. Log capped at 500,
74 messages at 2000 chars. Join/left lines are derived locally: hello carries a
75 self-reported `joinedAt`, and a peer whose join predates ours gets no
76 "joined" line on first sight (they were already here) — but `chatSeen`
77 ensures a blip-reconnect logs "joined" to match its "left". Links: only
78 http(s) URLs matched by `withLinks` become anchors (target=_blank,
79 rel=noopener noreferrer); never linkify other schemes.
80- **TURN is optional, token-gated, and shared room-wide.** `VITE_TURN_ENDPOINT`
81 (build time) points at `worker/`; unset ⇒ the whole feature is hidden and
82 `BASE_ICE_SERVERS` (STUN + openrelay) is used, as before. One participant
83 enters a token on the landing form, `mintIce` exchanges it for an
84 `{iceServers, expiresAt}` and it is broadcast as `{t:'ice'}` — on `connect`
85 to each peer, and again on refresh (`scheduleIceRefresh`, 5 min before
86 expiry). Peers `adoptIce` it; our own credentials always beat a shared one
87 (only we can refresh them), otherwise the later `expiresAt` wins. Share the
88 CREDENTIAL, never the token — the token never leaves the browser it was
89 typed into. **Peer-supplied ICE is untrusted:** `sanitizeIceConfig` bounds
90 and scheme-checks it before it reaches `RTCPeerConnection`.
91- **Credentials can't help the connection that carried them.** `Peer` takes
92 `iceServers` at construction and never renegotiates them, so a peer learns
93 credentials from the first peer it reaches and uses them for the NEXT
94 connection. Stalled pairs recover via the existing `CONNECT_RETRY_MS` path,
95 which calls `iceServers()` afresh — deliberately no proactive teardown on
96 adoption, since rebuilding a half-open pair out of step with the other side
97 is exactly what that retry already handles.
98- **Cleanup is join-generation-guarded.** `joinSeq` is bumped on every
99 join/leave; async work (getUserMedia, topic hashing, display capture)
100 re-checks it after each await. `leave()` unsubscribes topics, stops all
101 tracks, closes the AudioContext, and resets settings to defaults.
103## Testing
105`npm run dev`, then open the room in two browsers (identity is
106per-browser-profile via localStorage, so two tabs in one profile are the SAME
107peer — use a private window or second browser). `npm run build` type-checks
108(`tsc -b`) and bundles. Let the user test multi-party media in real browsers;
109don't try to automate camera/mic flows.
111The Worker CAN be tested without a browser: `cd worker && cp .dev.vars.example
112.dev.vars && npm run dev`, then curl it. With the example values, token checks
113work (`goodtoken` passes, anything else 401s) and the upstream call 404s, which
114surfaces as a 502 — enough to cover auth, CORS and method handling. `cd worker
115&& npx tsc --noEmit` type-checks it; the root `tsc -b` does not (it only
116includes `src`). The sanitizers in `turn.ts` are pure and testable under node
117via `npx esbuild src/p2p/turn.ts --format=esm --define:import.meta.env='{}'`.
118Whether a relay is actually USED can only be seen in a real browser
119(chrome://webrtc-internals, candidate pair type `relay`).
moveopenescclose