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): DinoNode broadcasts as authority + spectates peers, with a lowest-id tiebreak (dino Task 4)

enes3e9d04a0aae3
diff --git a/src/renderer/nodes/DinoNode.tsx b/src/renderer/nodes/DinoNode.tsx
index a483b5eeb..13803c41d 100644
--- a/src/renderer/nodes/DinoNode.tsx
+++ b/src/renderer/nodes/DinoNode.tsx
@@ -1,8 +1,11 @@
-import { useEffect, useRef } from 'react'
+import { useEffect, useRef, useState } from 'react'
import { NodeResizer, useReactFlow, type NodeProps } from '@xyflow/react'
+import { useShallow } from 'zustand/react/shallow'
import { type CanvasNode } from '../state/workspace'
import { useProjects } from '../state/projects'
+import { useSession, useActiveSessionPresence } from '../session/session'
import { createDinoGame } from './dino/dino-game'
+import { shouldSpectate } from './dino/dino-authority'
/**
* A dino node: a small self-contained T-Rex–style runner on a canvas. No PTY.
@@ -11,10 +14,30 @@ import { createDinoGame } from './dino/dino-game'
* data.highScore — we seed the game with it and store new records back. The game
* scopes its own keyboard/sound to the focusable host element, so it only reacts
* while this node is focused and stays silent when you're on another node.
+ *
+ * Live/shared play (docs/superpowers/specs/2026-07-14-dino-live-design.md): while WE author a run
+ * the engine broadcasts each frame over presence (`api.presence.dino`); while a peer authors this
+ * node we SPECTATE their snapshots (`game.setRemote`). A lowest-clientId tiebreak (shouldSpectate)
+ * settles a brief take-over race so every client converges on one authority. Solo (no peers) →
+ * `selectDino` is null → we never spectate and the broadcast casts are hub no-ops, so play is
+ * byte-identical to before.
*/
export function DinoNode({ id, data, selected }: NodeProps<CanvasNode>) {
const { updateNodeData, deleteElements } = useReactFlow()
const hostRef = useRef<HTMLDivElement>(null)
+ const gameRef = useRef<ReturnType<typeof createDinoGame> | null>(null)
+
+ // The active session's api + presence. DinoNode renders under Canvas's active-session provider,
+ // which is KEYED on `session.id` (Canvas.tsx), so this node REMOUNTS on a session swap — the
+ // mount-time `api` capture below is therefore always the current session's, no ref needed.
+ const { api } = useSession()
+ const presence = useActiveSessionPresence()
+ // The peer (if any) broadcasting a live dino for THIS node, and our own id for the tiebreak.
+ // selectDino excludes self and already applies the lowest-clientId rule, so `peer` is the one
+ // authority to consider. useShallow: a new PeerState object arrives ~20 Hz while spectating.
+ const peer = presence.store(useShallow((s) => presence.selectDino(s, id)))
+ const myId = presence.store((s) => s.myId)
+ const [spectating, setSpectating] = useState(false)
useEffect(() => {
const host = hostRef.current
@@ -27,14 +50,45 @@ export function DinoNode({ id, data, selected }: NodeProps<CanvasNode>) {
// closed) starts from it. Dino only runs while its project is active.
const s = useProjects.getState()
s.setDinoHighScore(s.activeProjectId, score)
- }
+ },
+ // Authority broadcast: each throttled frame while we play, one null on stop/idle. Solo → a
+ // hub no-op (no peers). `api` is captured once at mount (safe — see the remount note above).
+ onSnapshot: (snap) => api.presence.dino(snap ? { nodeId: id, snap } : null)
})
- return () => game.destroy()
+ gameRef.current = game
+ return () => {
+ // Belt-and-suspenders: guarantee our authority stop reaches the hub even if the last frame we
+ // broadcast was mid-run (destroy() already emits null via onSnapshot when mid-broadcast; a
+ // repeat null is an idempotent hub no-op).
+ game.destroy()
+ api.presence.dino(null)
+ gameRef.current = null
+ }
// Mount once; never re-run (would respawn the game). data.highScore is read
// as the seed only.
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [])
+ // Spectate vs. play. Reacts to the broadcasting peer + our id: when we should spectate, feed the
+ // peer's snapshot to the engine; otherwise LOCAL. `setRemote(null)` is idempotent while already
+ // LOCAL (it does NOT reset a live local run), so calling it on every non-spectating render is safe.
+ useEffect(() => {
+ const game = gameRef.current
+ if (!game) return
+ const spectate = shouldSpectate({
+ myId,
+ peerClientId: peer?.clientId ?? null,
+ iAmAuthority: game.isAuthority()
+ })
+ if (spectate && peer?.dino) {
+ game.setRemote(peer.dino.snap)
+ setSpectating(true)
+ } else {
+ game.setRemote(null)
+ setSpectating(false)
+ }
+ }, [peer, myId])
+
return (
<div className={`dino-node${selected ? ' selected' : ''}`} style={{ borderColor: data.color }}>
<NodeResizer minWidth={400} minHeight={160} isVisible={selected} color={data.color} />
@@ -47,6 +101,15 @@ export function DinoNode({ id, data, selected }: NodeProps<CanvasNode>) {
spellCheck={false}
onChange={(e) => updateNodeData(id, { title: e.target.value })}
/>
+ {spectating && peer && (
+ <span
+ className="dino-node__watching nodrag"
+ style={{ color: peer.color, borderColor: `${peer.color}66` }}
+ title={`${peer.name} is playing this dino`}
+ >
+ ▷ {peer.name} is playing
+ </span>
+ )}
<button
className="term-node__close"
title="Close"
diff --git a/src/renderer/nodes/dino/dino-authority.test.ts b/src/renderer/nodes/dino/dino-authority.test.ts
new file mode 100644
index 000000000..4b2e369a3
--- /dev/null
+++ b/src/renderer/nodes/dino/dino-authority.test.ts
@@ -0,0 +1,30 @@
+import { describe, it, expect } from 'vitest'
+import { shouldSpectate } from './dino-authority'
+
+/**
+ * The authority tiebreak: given my clientId, the peer broadcasting for this node, and whether my
+ * own engine currently authors a run, decide whether I spectate the peer or keep playing locally.
+ * Lower clientId wins — so I keep playing only when I already author AND my id beats the peer's.
+ */
+describe('shouldSpectate', () => {
+ it('no peer broadcasting → play locally (false)', () => {
+ expect(shouldSpectate({ myId: 1, peerClientId: null, iAmAuthority: false })).toBe(false)
+ expect(shouldSpectate({ myId: 1, peerClientId: null, iAmAuthority: true })).toBe(false)
+ })
+
+ it('a peer broadcasts and I do not author → spectate (true)', () => {
+ expect(shouldSpectate({ myId: 5, peerClientId: 2, iAmAuthority: false })).toBe(true)
+ })
+
+ it('a peer broadcasts, I author, my id is LOWER → keep playing (false), the peer yields', () => {
+ expect(shouldSpectate({ myId: 1, peerClientId: 5, iAmAuthority: true })).toBe(false)
+ })
+
+ it('a peer broadcasts, I author, my id is HIGHER → yield and spectate (true)', () => {
+ expect(shouldSpectate({ myId: 9, peerClientId: 5, iAmAuthority: true })).toBe(true)
+ })
+
+ it('myId is null (hello in flight) → cannot win the tiebreak, so spectate (true)', () => {
+ expect(shouldSpectate({ myId: null, peerClientId: 5, iAmAuthority: true })).toBe(true)
+ })
+})
diff --git a/src/renderer/nodes/dino/dino-authority.ts b/src/renderer/nodes/dino/dino-authority.ts
new file mode 100644
index 000000000..ab8ab43a3
--- /dev/null
+++ b/src/renderer/nodes/dino/dino-authority.ts
@@ -0,0 +1,26 @@
+import type { ClientId } from '@shared/presence'
+
+/**
+ * The authority tiebreak for a live dino node. A pure decision so it can be unit-tested apart from
+ * the canvas engine and the presence store.
+ *
+ * `selectDino` already hands us the LOWEST-clientId OTHER peer broadcasting for this node (or null),
+ * so the only question left is whether that peer beats US: if I currently author a run and my own
+ * clientId is lower than the peer's, I keep playing (the peer will see my broadcast and yield);
+ * otherwise I spectate. Lower clientId always wins, which is what makes every client converge on one
+ * authority during a take-over race.
+ *
+ * - `peerClientId === null` → nobody is broadcasting for this node → play locally (never spectate).
+ * - `myId === null` (hello in flight) → I cannot win the tiebreak, so I spectate.
+ */
+export function shouldSpectate(args: {
+ myId: ClientId | null
+ peerClientId: ClientId | null
+ iAmAuthority: boolean
+}): boolean {
+ const { myId, peerClientId, iAmAuthority } = args
+ if (peerClientId === null) return false // no peer authoring this node → play locally
+ // A peer is broadcasting. Spectate UNLESS I already author AND my clientId wins (lower wins).
+ if (iAmAuthority && myId !== null && myId < peerClientId) return false
+ return true
+}
diff --git a/src/renderer/styles.css b/src/renderer/styles.css
index bc7a5ad6c..214fd43a8 100644
--- a/src/renderer/styles.css
+++ b/src/renderer/styles.css
@@ -4870,6 +4870,18 @@ body,
background: #0b0b0f;
outline: none;
}
+/* "▷ <name> is playing" — shown while spectating a peer's live run. Tiny, non-interactive. */
+.dino-node__watching {
+ flex: 0 0 auto;
+ padding: 1px 7px;
+ border: 1px solid;
+ border-radius: 999px;
+ font-size: 11px;
+ font-weight: 600;
+ line-height: 1.5;
+ white-space: nowrap;
+ pointer-events: none;
+}
/* The game fills the body; it sizes the canvas itself via a ResizeObserver. */
.dino-canvas {
display: block;