ଅ essay

SEARCH · essays, work, books, rabbit holes

yjs · crdt · realtime · multiplayer · hocuspocus · react · talks · julian-jaynes

Bicameral: one live table on Yjs

A conspiracy-night talk where the speaker's phone is the Game Master, the projector follows, and every phone in the room is a player. Two Yjs documents and one free server hold it together.

Yjs turned "keep a room of devices in sync" into "edit two shared objects", and Hocuspocus turned "who may edit" into one flag per connection.

The projector, at double speed. The Voice of the Gods, then the idols, the Indus, the Bronze Age collapse and Kalinga, each scene a paper diorama in a shoebox.

A talk you play, not watch

I gave a talk on Julian Jaynes’ Bicameral Mind at a local conspiracy night, and I built it as a tabletop game. I am the Game Master. The room are my players.

Jaynes argued that until about 3,000 years ago, people did not introspect. One half of the brain spoke commands, and the other half heard them as the voice of a god and obeyed. That idea begs to be performed, not described. So at one point in the talk, every phone in the room turns into a cloud-god and tells its owner to raise their right hand. Some phones whisper a private command that only that person hears.

There are three kinds of screen:

URLDeviceWhat it does
/gmMy phoneScroll the talk, open encounters, whisper, spotlight, laser pointer, blackout
/screenProjector laptopNothing; it follows me
/Audience phones, via a QR codeJoin as a character, then write, answer, obey or walk only while I allow it

The talk runs 20 scenes. Between them sit encounters: open-ended thoughts that float into the projector’s sky, trivia and Stroop speed rounds, the Voice of the Gods, and a free-roam mode where players steer tiny avatars across the projector. XP and a “Most Bicameral” leaderboard close it out.

The problem: many screens, one truth, no budget

Every device in the room has to agree on what is happening, within a frame or two, over venue Wi-Fi and mobile data. Three constraints shaped everything.

  1. One writer for the story, many writers for the crowd. Only I may move the talk forward. Players may write, but only inside a window I open, and the server must enforce that, not the client. Someone in a conspiracy-night crowd will open devtools.
  2. It must be free. No paid realtime service, no managed database. It runs on Render’s free tier, with a Cloudflare quick tunnel from my laptop as the backup.
  3. It must survive the room. Phones lock, reload and drop off Wi-Fi. My own phone might reload mid-talk. A reconnecting device has to land in the right place without a “resync” button.

A hand-rolled WebSocket server with JSON messages would cover the happy path. It would not cover reconnection, late joiners, out-of-order delivery or merging two writes to the same list. Those are exactly what a CRDT gives you for free.

How Yjs carries it

Yjs let me treat the whole room as two shared JavaScript objects. Every device holds a local copy, writes to it, and Yjs ships the binary diffs. Reconnects, late joiners and concurrent pushes to the same array merge by themselves. Hocuspocus is the server: a thin WebSocket relay for Yjs documents with hooks for auth and persistence.

Two documents per room, split by who may write

The key design move was splitting state by write permission rather than by feature.

DocumentHoldsWho writes
room:stage (a Y.Map)scene, scroll progress, the open encounter, laser pointer, blackout, QR, spotlight, sound cuesThe GM only, always
room:crowdthoughts (Y.Array), answers and obeys (Y.Map, keyed encounterId:uid)Players, only while an encounter is open; the GM always
Awareness on crowdEach player’s character and avatar positionEach player, for themselves; never stored

Because the permission boundary is the document boundary, the server never inspects individual writes. It only decides, per connection, whether that connection is read-only.

The GM writes the stage; players write the crowd only in encounters Game Master phone Token gm|key, checked Writes stage and crowd Player phones Read stage at all times Write crowd in encounters Publish own presence Hocuspocus server stage doc · Y.Map scene, progress, encounter, pointer, blackout, sfx crowd doc thoughts · Y.Array answers, obeys · Y.Map awareness (on crowd) characters, avatar x and y ephemeral, never stored Projector role screen read-only on both gets every diff always if open ~12 Hz encounter.openflips readOnly
Room architecture: two documents, one awareness channel, three roles.

The GM’s writes to the stage are always accepted. A player’s write to the crowd lands only while the stage’s encounter is open, because the server watches that flag and flips each player connection’s readOnly.

// server/index.ts: role from the token, read-only decided per connection
if (role !== 'gm') {
  connectionConfig.readOnly = doc === 'stage' || role === 'screen'
    ? true
    : !encounterOpen(instance.documents.get(docName(room, 'stage')))
}

The server also watches the stage doc. When I open or close an encounter, it flips every player’s crowd connection in place, with no reconnect:

crowd.connections.forEach((_v, conn) => {
  if (conn.context?.role === 'player') conn.readOnly = !open
})

Awareness for things that move

Avatars walking across the projector are not document state. They use Yjs awareness, an ephemeral side channel that is broadcast and then forgotten. Players publish at most every 80 ms (about 12 Hz). On Render’s free tier those arrive in batches of about 5 Hz, so the projector eases each avatar with a 250 ms CSS transition to hide the steps. The server also clears any awareness a non-GM sends on the stage doc, so nobody can fake my laser pointer.

Derived, never written: XP

No client ever writes a score. Every screen computes XP from the crowd doc: 15 per thought (capped at 3 per encounter), 25 per obeyed command, and trivia at 100 for a right answer plus up to 100 for speed. A player who edits their own client can only change what their own screen shows.

Persistence that costs nothing

Hocuspocus’ database extension snapshots each doc to a .bin file, debounced to every 2 s. If the server restarts mid-talk, scene position, thoughts and scores come back. React reads Yjs through useSyncExternalStore with a cached snapshot, so components re-render only when their own type changes.

One interaction, end to end

Take the showpiece: I whisper “Stand up” to a single player.

  1. On my phone I pick the command, choose Whisper to one…, pick the player, and press Speak.
  2. My phone writes one transaction to the stage doc: encounter = { type: "voice", open: true, prompt, voice, targets: [uid] }.
  3. Hocuspocus relays the diff to every device. Its own observer sees open flip to true and makes every player’s crowd connection writable.
  4. Each phone checks targets. Only the named player’s phone turns into the cloud-god, vibrates and plays the whisper clip. Everyone else sees nothing new.
  5. The player taps I obeyed. Their phone writes obeys.set("encounterId:uid", …) to the crowd doc.
  6. Every screen observes that write and re-derives XP, so the projector’s party list and the player’s own badge both gain 25.
  7. I close the encounter. The server sees open flip back and every player’s crowd connection becomes read-only again.

Scrolling the talk itself is the same pattern at a higher rate. My phone turns scroll position into { scene, progress } and writes it at most every 50 ms (about 20 Hz), always sending the latest value. The laser pointer streams at about 30 Hz. If my phone reloads, it reads the stage doc and scrolls itself back to where the projector already is.

Reading the numbers in the demo

The whole 144-second demo, with two players, a thoughts round, two god commands, two trivia rounds and a walk, moved 18.7 KB of Yjs document updates to the projector. The peak was 18 updates per second.

The whole demo, 144 seconds, no sound. Every screen side by side: my phone, the projector, two players, and underneath, the live Yjs log and the roles panel.

The demo video is a single take of a /showcase page. It puts the GM phone, the projector, two player phones and two terminal-style panels on one 1920×1080 canvas. The panels are not mock-ups. The page opens its own connection to the room with the read-only screen role and prints what it actually receives.

The status bar

StatWhat it countsSeen in the demo
updates/sYjs update events on both docs, counted over 500 ms windows and scaled to per second0 at rest; 10–18 while I scroll or draw with the pointer
KB syncedRunning total of the bytes in those binary updates since the page opened0 → 18.7 KB over 144 s
awareness/sAwareness change events per second (presence that actually moved)0 until the walk; 12 with two players walking
playersAwareness states whose role is player0 → 1 → 2 as the phones join

Three caveats when you explain these:

  • They are what one follower received, not server totals. With N followers the server sends roughly N times this.
  • KB synced counts document updates only. Awareness traffic and WebSocket framing are not in it, which is why walking barely moves it.
  • The rates are sampled every 500 ms, so a single tap often reads as 2 updates/s.
The whole demo moved under 20 KB of Yjs updates 18.7 KB of document updates by 2:20, peak 18 updates/s, as one follower received them thoughts god voice trivia walk 0 KB 5 KB 10 KB 15 KB 20 KB Running total synced 0:00: 0 KB0:04: 0 KB0:08: 0 KB0:12: 0.3 KB0:16: 0.7 KB0:20: 1.3 KB0:24: 1.9 KB0:28: 2 KB0:32: 2.3 KB0:36: 2.4 KB0:40: 2.9 KB0:44: 4 KB0:48: 4.7 KB0:52: 5.5 KB0:56: 6.2 KB1:00: 7.7 KB1:04: 8.4 KB1:08: 9.4 KB1:12: 9.6 KB1:16: 9.9 KB1:20: 10 KB1:24: 10.7 KB1:28: 11.9 KB1:32: 12.6 KB1:36: 13.7 KB1:40: 15.2 KB1:44: 15.9 KB1:48: 16.8 KB1:52: 17.1 KB1:56: 17.3 KB2:00: 17.6 KB2:04: 17.6 KB2:08: 18.4 KB2:12: 18.4 KB2:16: 18.7 KB2:20: 18.7 KB 18.7 KB Updates per second 0/s 10/s 20/s 0:00: 0 updates/s0:04: 0 updates/s0:08: 0 updates/s0:12: 14 updates/s0:16: 0 updates/s0:20: 10 updates/s0:24: 2 updates/s0:28: 0 updates/s0:32: 2 updates/s0:36: 4 updates/s0:40: 0 updates/s0:44: 14 updates/s0:48: 0 updates/s0:52: 0 updates/s0:56: 0 updates/s1:00: 12 updates/s1:04: 2 updates/s1:08: 2 updates/s1:12: 0 updates/s1:16: 2 updates/s1:20: 0 updates/s1:24: 0 updates/s1:28: 16 updates/s1:32: 0 updates/s1:36: 2 updates/s1:40: 18 updates/s1:44: 12 updates/s1:48: 2 updates/s1:52: 0 updates/s1:56: 2 updates/s2:00: 2 updates/s2:04: 2 updates/s2:08: 0 updates/s2:12: 0 updates/s2:16: 14 updates/s2:20: 0 updates/s 0:000:301:001:302:00
Read off the inspector status bar in the demo video: 36 samples, one every 4 seconds.

Traffic comes in short bursts when I scroll or draw with the pointer, and sits at zero between them. The walk at 2:08 sends awareness to 12 events a second, yet the total barely moves, because awareness is not counted.

The log, interaction by interaction

Each row is a moment in the video, the line the log prints, and what the panels do.

TimeInteractionLog linePanels
0:08, 0:10Two players joinaware · awareness: 2 players at the table (+Gargi)players 0 → 2
0:16–0:21I tap Next, scene 2stage.scene = 1, stage.progress = 0.25010–14 updates/s
0:25I open a Thoughts encounterstage.encounter = { type: "thoughts", open: true, prompt: "…" }Roles panel: crowd OPEN, players get write
0:28, 0:31Players post thoughtscrowd · thoughts.push("…") · HectorKB ticks up; bubbles float onto the projector
0:36I close itstage.encounter = { type: "thoughts", open: false }crowd LOCKED
0:59Laser pointer from my phonestage.pointer = { x: 0.42, y: 0.31, on: true }Updates climb with the ~30 Hz stream
1:11Voice of the Gods, to allstage.encounter = { type: "voice", open: true, prompt: "Raise your right hand" }Both phones become the cloud-god
1:14, 1:15Players tap I obeyedcrowd · obeys.set(Hector) · "I obeyed"+25 XP on both phones
1:17Whisper to one playerstage.encounter = { type: "voice", … }Only one phone lights up
1:50, 1:58Trivia, then a Stroop roundcrowd · answers.set(Gargi, choice 0, 2140 ms)Histogram on the projector; XP after reveal
2:08Walk the Earthstage.walk = trueawareness/s 0 → 12; KB nearly flat
2:19Leaderboardstage.leaderboard = trueFinal total 18.7 KB

The example values inside quotes and braces are illustrative; the shape of each line is exactly what the inspector prints.

Two things engineers will ask about

Why does the log repeat stage.scene = 3? Every scroll tick writes scene and progress together, and Yjs emits a change even when a key is set to the value it already holds. The log shows at most four progress lines a second to stay readable, so the repeated scene lines are what is left. It is harmless but wasteful; see the lessons below.

Is the roles panel reading the server? No. It applies the server’s rule to the encounter it sees: GM writes both docs, projector writes neither, players write crowd only while an encounter is open. The proof that the server enforces it is npm run acl-test, which passes all seven checks against a live server: a player cannot write the stage, cannot write the crowd while it is locked, and a wrong presenter key is rejected.

The craft: a shoebox on every screen

Sync is half of it; the other half is that a room should want to look up. Each of the 20 scenes is a paper diorama in a shoebox, and the same box is rendered on the projector and on every phone.

The shoebox pass, no sound. The same talk with every scene as a paper diorama, on the projector and on the phones.
  • Plates. One generated plate per scene, all matched to a single reference style, with rules that keep the cutting pipeline happy: separate foreground figures, a calm caption band along the bottom, no text. A script cuts each plate into a back wall and foreground cutouts listed in a layers.json.
  • The box. The projector screen is the box’s opening. An off-axis projection pins the opening to the screen edges while the eye drifts, so only the inside moves. Cutouts pivot at their feet and sway, and light shafts with dust fall from the painted beams.
  • Phones look around. On a phone, tilting the device moves the eye inside the box. Tilt is written straight to CSS variables, so it re-projects without React re-renders.
  • Collage. Accents are CC0 museum objects from The Met and the Cleveland Museum of Art: a Sumerian worshipper, an Assyrian lamassu, Indus Valley seals, a Corinthian helmet.
  • The god’s voice. 40 command lines, generated offline with the open-source Kokoro text-to-speech model and ffmpeg. Each line has three takes: a booming male voice with temple reverb for the projector, and a close female or male whisper for phones. Each phone keeps one voice. No speech API is called at runtime.
  • The player’s phone is an aged notepad. When the god speaks, the words write themselves in like an enchanted diary.

What I’d tell another engineer

What worked

  • Split documents by who may write, not by feature. Server-side permissions shrink to one boolean per connection. Hocuspocus can flip readOnly on a live connection, so opening an encounter needs no reconnect.
  • Derive anything players would want to cheat. Scores are a pure function of the crowd doc. There is no score field to forge.
  • Put motion in awareness, and smooth it on the receiver. Document history never fills with avatar coordinates, and a 250 ms ease hides the free tier’s ~5 Hz batching.
  • Throttle at the writer, always send the latest value. 20 Hz for scroll and 30 Hz for the pointer feel live, and an idle room costs nothing.
  • Build the inspector. The /showcase page made sync visible, caught bugs, and became the demo. A yjs tail panel is worth an afternoon on any Yjs project.
  • Test the rules, not the UI. npm run acl-test (7 checks) and npm run load -- 80 15 (80 simulated players walking and posting for 15 s) ran against the real server.

Limits and what I’d change

  • Skip unchanged keys. Each scroll tick rewrites scene even when it has not changed. Comparing before each set would trim every scroll update and clean up the log.
  • Permissions are per document, not per key. While an encounter is open, a player with devtools could write an answer under someone else’s id. For one evening that was acceptable. A product would validate each write on the server or give each player their own sub-document.
  • The presenter key is one shared secret in the connection token. That is fine for one speaker and one night, not for a multi-GM platform.
  • The free tier is a trade. Render’s free instance sleeps after about 15 idle minutes, so I opened /screen a few minutes early to wake it. A restart there also wipes the disk, so the 2-second snapshots only protect a run on my own laptop. The Cloudflare quick tunnel from my laptop was the backup.

The one-line version for engineers: Yjs turned “keep a room of devices in sync” into “edit two shared objects”, and Hocuspocus turned “who may edit” into one flag per connection.


It also lives in rabbit holes, with a recording.

The World Beneath

turn-based roguelike · 8×8 textmode · CRT

Under the site there’s a small world. Click the screen to start: pick a companion, find the ten caches, and see how far down the temple goes.

The ring

water douses fire · fire burns root · root grounds spark · spark shocks water. Lead with what beats what’s in front of you: ×2 one way, ×½ the other.

Walk
arrows, WASD, or click
Act
Enter · Z waits · M menu
Margins
more marks hide in long reads
·