Skip to content

Node-based terminal manager for AI coding agents — tmux-backed terminals and parallel agent sessions as draggable nodes on an infinite pan/zoom canvas. macOS, Linux, and a browser Server Edition.

feat(dino): game engine broadcasts snapshots + renders a remote spectator view (dino Task 3)

enes7936d3a26e1c
diff --git a/src/renderer/nodes/dino/dino-game.ts b/src/renderer/nodes/dino/dino-game.ts
index e96f9a8a7..5cb24f4ab 100644
--- a/src/renderer/nodes/dino/dino-game.ts
+++ b/src/renderer/nodes/dino/dino-game.ts
@@ -1,5 +1,10 @@
+import type { DinoSnapshot } from '@shared/presence'
+import { DinoSync, type DinoSyncEmit } from './dino-sync'
import spriteUrl from './sprite-1x.png'
+/** One obstacle as it rides a snapshot (no collision box — a spectator only draws). */
+type DinoObstacleSnap = DinoSnapshot['obstacles'][number]
+
/**
* A small, self-contained T-Rex–style endless runner rendered to a <canvas>.
*
@@ -10,11 +15,27 @@ import spriteUrl from './sprite-1x.png'
* Chrome offline sprite sheet (`sprite-1x.png`), drawn frame-by-frame from its
* real atlas coordinates and tinted light so it reads on the dark field. The
* public interface matches DinoNode; high score is seeded in and reported out.
+ *
+ * Live/shared play (see docs/superpowers/specs/2026-07-14-dino-live-design.md): the
+ * game can BROADCAST its state as the authority (`opts.onSnapshot`, throttled to
+ * DINO_BROADCAST_HZ) and SPECTATE a remote authority (`setRemote(snap)` — the sim +
+ * input are suspended and the snapshot is drawn instead). A local key while spectating
+ * takes over (seeds from the last snapshot, then plays + broadcasts). With no
+ * `onSnapshot` and no `setRemote` call, behavior is byte-identical to solo play.
*/
export function createDinoGame(
host: HTMLElement,
- opts: { initialHighScore: number; onHighScore: (score: number) => void }
-): { destroy: () => void } {
+ opts: {
+ initialHighScore: number
+ onHighScore: (score: number) => void
+ onSnapshot?: (snap: DinoSnapshot | null) => void
+ }
+): {
+ destroy: () => void
+ setRemote: (snap: DinoSnapshot | null) => void
+ isRemote: () => boolean
+ isAuthority: () => boolean
+} {
const canvas = document.createElement('canvas')
canvas.className = 'dino-canvas'
host.appendChild(canvas)
@@ -132,6 +153,57 @@ export function createDinoGame(
}
let obstacles: Obstacle[] = []
+ // Live/shared play: local-authority vs. remote-spectator mode + broadcast throttle.
+ const sync = new DinoSync()
+
+ function emit(what: DinoSyncEmit) {
+ if (!opts.onSnapshot) return
+ if (what === 'snapshot') opts.onSnapshot(currentSnapshot())
+ else if (what === 'null') opts.onSnapshot(null)
+ }
+
+ // The minimal per-frame state a spectator needs to redraw this run.
+ function currentSnapshot(): DinoSnapshot {
+ return {
+ y: dinoY,
+ ducking,
+ crashed,
+ started,
+ score,
+ speed,
+ groundScroll,
+ obstacles: obstacles.map((o) => ({
+ kind: o.kind,
+ x: o.x,
+ y: o.y,
+ sx: o.sx,
+ sw: o.sw,
+ sh: o.sh,
+ flap: o.flap
+ }))
+ }
+ }
+
+ // Rebuild a full Obstacle (with its collision box) from a wire snapshot. The box is
+ // only needed once we take over and run our own sim; drawing ignores it.
+ function obstacleFromSnap(o: DinoObstacleSnap): Obstacle {
+ const col =
+ o.kind === 'bird' ? BIRD.col : o.sw === CACTUS_LARGE.w ? CACTUS_LARGE.col : CACTUS_SMALL.col
+ return { kind: o.kind, x: o.x, y: o.y, sx: o.sx, sw: o.sw, sh: o.sh, flap: o.flap, col }
+ }
+
+ // Adopt a remote snapshot as the live state so the shared draw() renders it verbatim.
+ function applyRemote(snap: DinoSnapshot) {
+ dinoY = snap.y
+ ducking = snap.ducking
+ crashed = snap.crashed
+ started = snap.started
+ score = snap.score
+ speed = snap.speed
+ groundScroll = snap.groundScroll
+ obstacles = snap.obstacles.map(obstacleFromSnap)
+ }
+
function reset() {
score = 0
speed = 320
@@ -198,6 +270,7 @@ export function createDinoGame(
// --- Update + draw --------------------------------------------------------
function update(dt: number) {
+ if (sync.isRemote()) return // spectator: physics suspended, draw() renders the remote snap
if (crashed || !started) return
score += dt * 22
speed += dt * 14
@@ -302,6 +375,7 @@ export function createDinoGame(
last = now
update(dt)
draw()
+ emit(sync.tick(now, started || crashed)) // broadcast (throttled) while authoritative
raf = requestAnimationFrame(frame)
}
function start() {
@@ -310,19 +384,49 @@ export function createDinoGame(
raf = requestAnimationFrame(frame)
}
function stop() {
+ emit(sync.endBroadcast()) // one null on the stop edge (no-op while spectating)
if (raf) cancelAnimationFrame(raf)
raf = 0
}
+ // Enter/leave spectator mode. A remote snapshot keeps the loop running (to draw) even
+ // when unfocused; leaving returns the own sim to its pre-start idle frame.
+ function setRemote(snap: DinoSnapshot | null) {
+ if (snap) {
+ sync.setRemote(snap)
+ applyRemote(snap)
+ start()
+ draw()
+ } else {
+ const wasRemote = sync.isRemote()
+ sync.setRemote(null)
+ if (wasRemote) {
+ reset()
+ started = false
+ }
+ if (!focused) stop()
+ draw()
+ }
+ }
+
+ // A local key while spectating → take over: seed from the last remote snap for
+ // continuity (so the dino doesn't teleport), then the caller's input plays as authority.
+ function takeOverIfRemote() {
+ const seed = sync.takeOver()
+ if (seed) applyRemote(seed)
+ }
+
// --- Input (scoped to host focus) -----------------------------------------
const onKey = (e: KeyboardEvent) => {
if (e.key === ' ' || e.key === 'ArrowUp' || e.key === 'Spacebar') {
e.preventDefault()
e.stopPropagation()
+ takeOverIfRemote()
jump()
} else if (e.key === 'ArrowDown') {
e.preventDefault()
e.stopPropagation()
+ takeOverIfRemote()
ducking = true
}
}
@@ -336,6 +440,10 @@ export function createDinoGame(
const onBlur = () => {
focused = false
ducking = false
+ if (sync.isRemote()) {
+ draw() // spectator keeps watching without focus
+ return
+ }
stop()
draw() // leave a static idle frame
}
@@ -369,6 +477,9 @@ export function createDinoGame(
audio = null
}
canvas.remove()
- }
+ },
+ setRemote,
+ isRemote: () => sync.isRemote(),
+ isAuthority: () => sync.isAuthority()
}
}
diff --git a/src/renderer/nodes/dino/dino-sync.test.ts b/src/renderer/nodes/dino/dino-sync.test.ts
new file mode 100644
index 000000000..e8660646b
--- /dev/null
+++ b/src/renderer/nodes/dino/dino-sync.test.ts
@@ -0,0 +1,107 @@
+import { describe, it, expect } from 'vitest'
+import type { DinoSnapshot } from '@shared/presence'
+import { DinoSync, DINO_BROADCAST_HZ, DINO_BROADCAST_INTERVAL_MS } from './dino-sync'
+
+function snap(over: Partial<DinoSnapshot> = {}): DinoSnapshot {
+ return {
+ y: -12,
+ ducking: false,
+ crashed: false,
+ started: true,
+ score: 123,
+ speed: 400,
+ groundScroll: 6,
+ obstacles: [{ kind: 'cactus', x: 200, y: 0, sx: 228, sw: 17, sh: 35, flap: 0 }],
+ ...over
+ }
+}
+
+describe('DinoSync', () => {
+ it('starts in local (authority) mode', () => {
+ const s = new DinoSync()
+ expect(s.isAuthority()).toBe(true)
+ expect(s.isRemote()).toBe(false)
+ expect(s.mode).toBe('local')
+ expect(s.remoteSnap).toBe(null)
+ })
+
+ it('throttles broadcast to ~20 Hz (one emit per interval, first frame immediate)', () => {
+ expect(DINO_BROADCAST_HZ).toBe(20)
+ expect(DINO_BROADCAST_INTERVAL_MS).toBe(50)
+ const s = new DinoSync()
+ expect(s.tick(0, true)).toBe('snapshot') // first active frame emits immediately
+ expect(s.tick(10, true)).toBe('none')
+ expect(s.tick(49, true)).toBe('none')
+ expect(s.tick(50, true)).toBe('snapshot') // 50 ms later → emit
+ expect(s.tick(60, true)).toBe('none')
+ expect(s.tick(100, true)).toBe('snapshot')
+ })
+
+ it('emits exactly one null on the transition into idle, then nothing', () => {
+ const s = new DinoSync()
+ s.tick(0, true) // broadcasting
+ expect(s.tick(50, false)).toBe('null') // active → idle: one null
+ expect(s.tick(100, false)).toBe('none') // stays idle: no spam
+ expect(s.tick(150, false)).toBe('none')
+ })
+
+ it('does not emit a null at pure startup idle (no prior broadcast)', () => {
+ const s = new DinoSync()
+ expect(s.tick(0, false)).toBe('none')
+ expect(s.tick(16, false)).toBe('none')
+ expect(s.endBroadcast()).toBe('none')
+ })
+
+ it('endBroadcast (blur/stop/destroy) emits one null, then none', () => {
+ const s = new DinoSync()
+ s.tick(0, true) // broadcasting
+ expect(s.endBroadcast()).toBe('null')
+ expect(s.endBroadcast()).toBe('none')
+ })
+
+ it('re-broadcasts immediately after a stop edge when active resumes', () => {
+ const s = new DinoSync()
+ s.tick(0, true)
+ s.endBroadcast()
+ expect(s.tick(5, true)).toBe('snapshot') // resumed run emits at once, not throttled
+ })
+
+ it('setRemote(snap) enters remote mode and suspends all emits (spectator is silent)', () => {
+ const s = new DinoSync()
+ const view = snap()
+ s.setRemote(view)
+ expect(s.isRemote()).toBe(true)
+ expect(s.isAuthority()).toBe(false)
+ expect(s.remoteSnap).toBe(view)
+ expect(s.tick(0, true)).toBe('none') // a spectator never broadcasts
+ expect(s.tick(1000, true)).toBe('none')
+ expect(s.endBroadcast()).toBe('none')
+ })
+
+ it('setRemote(null) returns to local authority', () => {
+ const s = new DinoSync()
+ s.setRemote(snap())
+ s.setRemote(null)
+ expect(s.isAuthority()).toBe(true)
+ expect(s.remoteSnap).toBe(null)
+ })
+
+ it('takeOver() flips remote→local and returns the seed snapshot', () => {
+ const s = new DinoSync()
+ const view = snap({ score: 999 })
+ s.setRemote(view)
+ const seed = s.takeOver()
+ expect(seed).toBe(view)
+ expect(s.isAuthority()).toBe(true)
+ expect(s.isRemote()).toBe(false)
+ expect(s.remoteSnap).toBe(null)
+ // take-over resumes broadcasting on the next active frame, immediately
+ expect(s.tick(5000, true)).toBe('snapshot')
+ })
+
+ it('takeOver() is a no-op (null) when already local', () => {
+ const s = new DinoSync()
+ expect(s.takeOver()).toBe(null)
+ expect(s.isAuthority()).toBe(true)
+ })
+})
diff --git a/src/renderer/nodes/dino/dino-sync.ts b/src/renderer/nodes/dino/dino-sync.ts
new file mode 100644
index 000000000..67505e49a
--- /dev/null
+++ b/src/renderer/nodes/dino/dino-sync.ts
@@ -0,0 +1,93 @@
+import type { DinoSnapshot } from '@shared/presence'
+
+/**
+ * The pure broadcast/spectate state machine behind {@link createDinoGame} — mode
+ * (local authority vs. remote spectator), the ~20 Hz broadcast throttle, and the
+ * single null-on-stop edge. Kept free of the DOM/canvas so it is unit-testable in a
+ * plain node env (the game glue in dino-game.ts owns the rAF loop + drawing).
+ */
+export const DINO_BROADCAST_HZ = 20
+export const DINO_BROADCAST_INTERVAL_MS = 1000 / DINO_BROADCAST_HZ
+
+/** What a per-frame {@link DinoSync.tick} decides the caller should publish. */
+export type DinoSyncEmit = 'snapshot' | 'null' | 'none'
+
+export class DinoSync {
+ private _mode: 'local' | 'remote' = 'local'
+ private _remote: DinoSnapshot | null = null
+ private lastEmit = 0
+ /** True once we've published at least one snapshot for the current run, so we know
+ * a following idle/stop is a *transition* that owes exactly one null. */
+ private broadcasting = false
+
+ get mode(): 'local' | 'remote' {
+ return this._mode
+ }
+ get remoteSnap(): DinoSnapshot | null {
+ return this._remote
+ }
+ isRemote(): boolean {
+ return this._mode === 'remote'
+ }
+ isAuthority(): boolean {
+ return this._mode === 'local'
+ }
+
+ /**
+ * Per-frame broadcast decision (call once per rAF frame in the local sim).
+ * `active` = the run is in progress or on the game-over screen (`started || crashed`).
+ * A spectator (remote mode) never broadcasts. An active run emits a snapshot at most
+ * once per {@link DINO_BROADCAST_INTERVAL_MS} (first active frame emits immediately);
+ * a return to idle emits a single null.
+ */
+ tick(now: number, active: boolean): DinoSyncEmit {
+ if (this._mode === 'remote') return 'none'
+ if (active) {
+ if (!this.broadcasting || now - this.lastEmit >= DINO_BROADCAST_INTERVAL_MS) {
+ this.lastEmit = now
+ this.broadcasting = true
+ return 'snapshot'
+ }
+ return 'none'
+ }
+ return this.endBroadcast()
+ }
+
+ /**
+ * A hard stop edge (blur / stop() / destroy). Emits exactly one null iff we were
+ * mid-broadcast, otherwise nothing — so null is never spammed. No-op while spectating.
+ */
+ endBroadcast(): DinoSyncEmit {
+ if (this._mode === 'remote') return 'none'
+ if (this.broadcasting) {
+ this.broadcasting = false
+ return 'null'
+ }
+ return 'none'
+ }
+
+ /** Enter remote spectator mode with `snap`, or return to local authority with null. */
+ setRemote(snap: DinoSnapshot | null): void {
+ if (snap) {
+ this._mode = 'remote'
+ this._remote = snap
+ } else {
+ this._mode = 'local'
+ this._remote = null
+ }
+ }
+
+ /**
+ * Local input arrived while spectating → take over as authority. Flips to local mode
+ * and returns the last remote snapshot to seed the sim from (for continuity), or null
+ * if we were already the authority (a no-op). The next active frame re-broadcasts at once.
+ */
+ takeOver(): DinoSnapshot | null {
+ if (this._mode !== 'remote') return null
+ const seed = this._remote
+ this._mode = 'local'
+ this._remote = null
+ this.broadcasting = false
+ return seed
+ }
+}