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(watch-link): the link host — viewer sessions, keyframes, throttling, chat and kick

reviewde6462962d86
diff --git a/src/core/watch-link/chat-cast.guard.test.ts b/src/core/watch-link/chat-cast.guard.test.ts
new file mode 100644
index 000000000..2ea6293eb
--- /dev/null
+++ b/src/core/watch-link/chat-cast.guard.test.ts
@@ -0,0 +1,50 @@
+// A viewer's chat reaches the owner ONLY through a live link's own relay session: the cast arrives on
+// that session's `PeerAttach.cast`, which the link host answers (link-host.ts), after the watcher
+// policy admitted it for a Commenter link only (watcher-policy.ts). Nothing registers `watch:chat` on
+// a platform. If something did, a hosted Editor or a Server Edition browser tab — clients of the same
+// core, whose casts go to the platform — could post "viewer" chat into the owner's popover, and a
+// Viewer link's refusal would no longer be the only door.
+//
+// So this names every file allowed to mention the cast, and fails on any other, with its reason. The
+// event of the same name (`WATCH_EVENT.chat`, host → viewer) is written only through the link host too.
+import { describe, expect, it } from 'vitest'
+import { readFileSync, readdirSync, statSync } from 'node:fs'
+import { join, relative } from 'node:path'
+
+const SRC = join(__dirname, '..', '..')
+
+const ALLOWED: Record<string, string> = {
+ 'shared/watch-link/protocol.ts': 'defines the cast and the event',
+ 'shared/watch-link/client.ts': "the viewer's browser client sends the cast",
+ 'core/watch-link/watcher-policy.ts': 'admits the cast for a Commenter link only',
+ 'core/watch-link/link-host.ts': "answers the cast on the link's own relay session"
+}
+
+function sources(dir: string, out: string[] = []): string[] {
+ for (const entry of readdirSync(dir)) {
+ const p = join(dir, entry)
+ if (statSync(p).isDirectory()) {
+ if (entry !== 'node_modules') sources(p, out)
+ } else if (/\.tsx?$/.test(entry) && !/\.test\.tsx?$/.test(entry)) out.push(p)
+ }
+ return out
+}
+
+describe('the watch:chat cast', () => {
+ it('is mentioned by no source file outside the live-link path', () => {
+ const offenders: string[] = []
+ for (const file of sources(SRC)) {
+ const rel = relative(SRC, file).replace(/\\/g, '/')
+ const text = readFileSync(file, 'utf8').replace(/\r\n/g, '\n')
+ if (/WATCH_CHAT_CAST|['"`]watch:chat['"`]/.test(text) && !(rel in ALLOWED)) offenders.push(rel)
+ }
+ expect(offenders).toEqual([])
+ })
+
+ it('every allowlisted file still exists and still mentions it (a stale entry is a hole)', () => {
+ for (const rel of Object.keys(ALLOWED)) {
+ const text = readFileSync(join(SRC, rel), 'utf8')
+ expect(/WATCH_CHAT_CAST|['"`]watch:chat['"`]/.test(text), rel).toBe(true)
+ }
+ })
+})
diff --git a/src/core/watch-link/link-host.test.ts b/src/core/watch-link/link-host.test.ts
new file mode 100644
index 000000000..41e36b59f
--- /dev/null
+++ b/src/core/watch-link/link-host.test.ts
@@ -0,0 +1,798 @@
+// The link host against the REAL relay host, the REAL hosted scheduler and the REAL browser client
+// (src/shared/watch-link/client.ts) over an in-process transport. Only the pty and the clients registry
+// are fakes, and they record every call, so "nothing a viewer sent reached the pty" is checkable.
+//
+// Timing-sensitive cases run on a MANUAL clock injected as the link host's (and so the scheduler's)
+// setTimeout/now; the handshake itself is real async crypto, awaited with vi.waitFor on real time.
+import { describe, it, expect, vi, afterEach } from 'vitest'
+import nacl from 'tweetnacl'
+import { transportPair } from '../relay/transport-pair'
+import { connectRelay, type RelayTransport } from '../relay/relay-socket'
+import { publicKeyToB64 } from '../relay/e2ee'
+import { encodePtyData, parseRpcMessage } from '../../shared/rpc'
+import { IPC } from '../../shared/ipc'
+import { isHostOnlyChannel } from '../../shared/host-control'
+import { connectWatchClient } from '../../shared/watch-link/client'
+import { deriveWatchLinkKeys } from '../../shared/watch-link/keys'
+import { WATCH_EVENT, type WatchKeyframe } from '../../shared/watch-link/protocol'
+import {
+ createLinkHost,
+ CONFIRM_DEADLINE_MS,
+ FULL_STATUS_POLL_MS,
+ MAX_VIEWERS_PER_LINK,
+ REJOIN_BACKOFF_MS,
+ REJOIN_STABLE_MS,
+ SETTLE_BOUND_MS,
+ WATCHER_SIZE_SYNC_MS,
+ type LinkHost,
+ type WatchJoin,
+ type WatchPty
+} from './link-host'
+import type { HostTokenResult } from './api'
+import type { VisibleCapture } from './capture-route'
+import type { WatchLinkRecord } from './store'
+import type { UiSink } from '../ui-sink-registry'
+
+const ESC = '\x1b'
+const TRUST_CONFIRM = '{"t":"cast","method":"trust:confirm","args":[]}'
+
+const hosts: LinkHost[] = []
+afterEach(() => {
+ for (const h of hosts.splice(0)) h.stop('revoked')
+ vi.restoreAllMocks()
+})
+
+/** A clock and timer queue owned by the test. Firing a timer lets the event loop turn once, so the
+ * async work it starts (a join, a capture) settles before the next one fires. */
+function manualClock() {
+ let t = 1_000_000
+ let nextId = 1
+ const timers = new Map<number, { at: number; fn: () => void }>()
+ const flush = (): Promise<void> => new Promise((r) => setImmediate(r))
+ return {
+ now: () => t,
+ setTimeout: (fn: () => void, ms: number): unknown => {
+ const id = nextId++
+ timers.set(id, { at: t + Math.max(0, ms), fn })
+ return id
+ },
+ clearTimeout: (h: unknown) => {
+ timers.delete(h as number)
+ },
+ async advance(ms: number): Promise<void> {
+ const end = t + ms
+ for (;;) {
+ let best: [number, { at: number; fn: () => void }] | null = null
+ for (const e of timers) if (e[1].at <= end && (!best || e[1].at < best[1].at)) best = e
+ if (!best) break
+ timers.delete(best[0])
+ t = best[1].at
+ best[1].fn()
+ await flush()
+ await flush()
+ }
+ t = end
+ await flush()
+ await flush()
+ },
+ flush
+ }
+}
+type ManualClock = ReturnType<typeof manualClock>
+
+interface SetupOpts {
+ role?: 'viewer' | 'commenter'
+ join?: (clientId: number, nodeId: string, viewerId: string) => Promise<WatchJoin | null> | WatchJoin | null
+ capture?: (sid: string) => Promise<VisibleCapture> | VisibleCapture
+ alive?: (sid: string) => boolean
+ /** The host side's socket backlog, per listener (in the order listeners were opened). */
+ buffered?: (listener: number) => number
+ clock?: ManualClock
+ mint?: () => Promise<HostTokenResult>
+ status?: () => Promise<'live' | 'revoked' | 'expired' | 'unknown'>
+}
+
+function setup(o: SetupOpts = {}) {
+ const secret = nacl.randomBytes(32)
+ const record: WatchLinkRecord = {
+ linkId: 'AbCdEfGhIjKlMnOpQrStUv', nodeId: 'node-1', role: o.role ?? 'viewer', label: 'Ada', title: 'build',
+ createdAt: 0, expiresAt: Date.now() + 3600_000, secret
+ }
+ const peers: RelayTransport[] = []
+ const sinks = new Map<number, UiSink>()
+ let nextId = 1_000_000
+ const left: string[] = []
+ /** Every pty call, in order: 'join', 'sync:<sid>', 'capture:<sid>'. */
+ const calls: string[] = []
+ const joinArgs: [number, string, string][] = []
+ const joinTimes: number[] = []
+ let mints = 0
+ const clock = o.clock
+ const now = clock ? clock.now : () => Date.now()
+ const pty: WatchPty = {
+ join: async (clientId, nodeId, viewerId) => {
+ calls.push('join')
+ joinArgs.push([clientId, nodeId, viewerId])
+ joinTimes.push(now())
+ return o.join ? o.join(clientId, nodeId, viewerId) : { sessionId: 's1', cols: 100, rows: 30, altScreen: true }
+ },
+ leave: (_c, sid, vid) => {
+ left.push(`${sid}/${vid}`)
+ },
+ captureVisible: async (sid) => {
+ calls.push(`capture:${sid}`)
+ return o.capture ? o.capture(sid) : { screen: 'SCREEN', cursor: null }
+ },
+ syncSize: async (sid) => {
+ calls.push(`sync:${sid}`)
+ return true
+ },
+ alive: (sid) => (o.alive ? o.alive(sid) : true)
+ }
+ const chats: unknown[] = []
+ const joined: number[] = []
+ const gone: string[] = []
+ const host = createLinkHost(record, {
+ relayUrl: 'wss://relay.test',
+ mint: async () => {
+ mints++
+ return o.mint ? o.mint() : { ok: true, pairingToken: 'tok', hostId: '', ttlMs: 120_000 }
+ },
+ status: o.status ?? (async () => 'live'),
+ clients: {
+ attach: (s) => {
+ const id = nextId++
+ sinks.set(id, s)
+ return id
+ },
+ detach: (id) => {
+ sinks.delete(id)
+ }
+ },
+ pty,
+ transport: () => {
+ const i = peers.length
+ const { hostT, peerT } = transportPair({ hostBuffered: () => o.buffered?.(i) ?? 0 })
+ peers.push(peerT)
+ return hostT
+ },
+ now,
+ setTimeout: clock ? clock.setTimeout : (fn, ms) => setTimeout(fn, ms),
+ clearTimeout: clock ? clock.clearTimeout : (h) => clearTimeout(h as ReturnType<typeof setTimeout>),
+ onChange: () => {},
+ onChat: (m) => chats.push(m),
+ onViewerJoined: (n) => joined.push(n),
+ onGone: (r) => gone.push(r)
+ })
+ hosts.push(host)
+ return {
+ record, host, peers, sinks, left, calls, joinArgs, joinTimes, chats, joined, gone,
+ keys: deriveWatchLinkKeys(secret),
+ mints: () => mints,
+ /** The n-th attached viewer's sink (attach order). */
+ sink: (n = 0) => [...sinks.values()][n]
+ }
+}
+type Setup = ReturnType<typeof setup>
+
+function viewer(peer: RelayTransport, keys: ReturnType<typeof deriveWatchLinkKeys>) {
+ const log = { open: 0, events: [] as [string, unknown[]][], pty: [] as string[], denied: [] as string[], closed: 0 }
+ const c = connectWatchClient({
+ socket: peer,
+ keys,
+ events: {
+ onOpen: () => { log.open++ },
+ onEvent: (ch, a) => { log.events.push([ch, a]) },
+ onPtyData: (_s, d) => { log.pty.push(d) },
+ onDenied: (r) => { log.denied.push(r) },
+ onClose: () => { log.closed++ }
+ }
+ })
+ const named = (ch: string) => log.events.filter((e) => e[0] === ch).map((e) => e[1][0])
+ return { c, log, named, keyframes: () => named(WATCH_EVENT.keyframe) as WatchKeyframe[] }
+}
+type Viewer = ReturnType<typeof viewer>
+
+/** Open the n-th listener's viewer and wait for its first keyframe. */
+async function openViewer(t: Setup, n = 0): Promise<Viewer> {
+ await vi.waitFor(() => expect(t.peers.length).toBeGreaterThan(n))
+ const v = viewer(t.peers[n], t.keys)
+ await vi.waitFor(() => expect(v.keyframes().length).toBeGreaterThanOrEqual(1))
+ return v
+}
+const pty = (sink: UiSink, sid: string, data: string): void => sink.sendBinary(encodePtyData(sid, data))
+const ptyEvent = (sink: UiSink, channel: string, ...args: unknown[]): void =>
+ sink.sendText(JSON.stringify({ t: 'ev', channel, args }))
+
+describe('createLinkHost — a viewer session', () => {
+ it('opens a viewer, sends meta then the visible keyframe, then the filtered stream', async () => {
+ const t = setup()
+ t.host.start()
+ await vi.waitFor(() => expect(t.peers).toHaveLength(1))
+ const v = viewer(t.peers[0], t.keys)
+ await vi.waitFor(() => expect(v.log.events.map((e) => e[0])).toEqual([WATCH_EVENT.meta, WATCH_EVENT.keyframe]))
+ expect(v.log.events[0][1][0]).toMatchObject({ v: 1, role: 'viewer', label: 'Ada', title: 'build', cols: 100, rows: 30 })
+ // No cursor was read, so the keyframe carries none (not `cursor: null`).
+ expect(v.log.events[1][1][0]).toEqual({ sessionId: 's1', screen: 'SCREEN', altScreen: true })
+ const [id, sink] = [...t.sinks.entries()][0]
+ expect(id).toBeGreaterThanOrEqual(1_000_000)
+ // The join is MID-STREAM (R12): nothing is shown until the first escape, then OSC 52 is removed.
+ pty(sink, 's1', 'lost')
+ pty(sink, 's1', `${ESC}[Ha${ESC}]52;c;c2VjcmV0\x07b`)
+ expect(v.log.pty).toEqual([`${ESC}[Hab`])
+ expect(t.joined).toEqual([1])
+ expect(t.host.viewers()).toHaveLength(1)
+ // The host built every join argument itself: its client id, the record's node, a fresh viewer id.
+ expect(t.joinArgs).toEqual([[id, 'node-1', t.host.viewers()[0].viewerId]])
+ expect(t.host.viewers()[0].viewerId).toMatch(/^v-[0-9a-f]{8}$/)
+ // A replacement listener opened for the next viewer.
+ await vi.waitFor(() => expect(t.peers).toHaveLength(2))
+ })
+
+ it("a keyframe carries the host's cursor, and its screen passes a FRESH filter (R9, R10)", async () => {
+ const screen =
+ `${ESC}[1mhi${ESC}[m ${ESC}]8;;https://evil.test/${ESC}\\link${ESC}]8;;${ESC}\\ ` +
+ `${ESC}]52;c;c2VjcmV0\x07end${ESC}P1$r0m${ESC}\\\n`
+ const t = setup({ capture: () => ({ screen, cursor: { x: 3, y: 1 } }) })
+ t.host.start()
+ const v = await openViewer(t)
+ expect(v.keyframes()[0]).toEqual({
+ sessionId: 's1',
+ screen: `${ESC}[1mhi${ESC}[m link end\n`,
+ altScreen: true,
+ cursor: { x: 3, y: 1 }
+ })
+ })
+
+ it('a keyframe of a backend with no visible capture is an empty screen, and altScreen follows the join', async () => {
+ const t = setup({
+ join: () => ({ sessionId: 's1', cols: 80, rows: 24, altScreen: false }),
+ capture: () => ({ screen: '', cursor: null })
+ })
+ t.host.start()
+ const v = await openViewer(t)
+ expect(v.keyframes()[0]).toEqual({ sessionId: 's1', screen: '', altScreen: false })
+ })
+
+ it("denies a peer whose key is not the link's viewer key, and reopens a listener", async () => {
+ const t = setup()
+ t.host.start()
+ await vi.waitFor(() => expect(t.peers).toHaveLength(1))
+ const stranger = deriveWatchLinkKeys(nacl.randomBytes(32))
+ const v = viewer(t.peers[0], { ...t.keys, viewer: stranger.viewer })
+ await vi.waitFor(() => expect(v.log.denied).toEqual(['denied']))
+ expect(v.log.open).toBe(0)
+ expect(t.sinks.size).toBe(0)
+ expect(t.calls).toEqual([])
+ await vi.waitFor(() => expect(t.peers.length).toBeGreaterThanOrEqual(2))
+ })
+})
+
+describe('createLinkHost — read-only, both directions', () => {
+ it('sends a raw peer nothing but the trust confirm before its own confirm; then refuses every request and drops every cast', async () => {
+ const t = setup()
+ t.host.start()
+ await vi.waitFor(() => expect(t.peers).toHaveLength(1))
+ const replies = new Map<number, { ok: boolean; error?: { code: string } }>()
+ const frames: { kind: 'text' | 'binary'; json: string | null; beforeOurConfirm: boolean }[] = []
+ let confirmed = false
+ let rawClosed = 0
+ const raw = connectRelay({
+ url: 'x', token: 'x', role: 'client', theirPubB64: publicKeyToB64(t.keys.host.publicKey),
+ ourKeys: { publicKey: t.keys.viewer.publicKey, secretKey: t.keys.viewer.secretKey },
+ transport: t.peers[0], onReady: () => {}, onRpc: () => {}, onFrame: () => {},
+ onClose: () => { rawClosed++ },
+ onTunnel: (kind, p) => {
+ const json = kind === 'text' ? new TextDecoder().decode(p) : null
+ frames.push({ kind, json, beforeOurConfirm: !confirmed })
+ const m = json ? parseRpcMessage(json) : null
+ if (m?.t === 'res') replies.set(m.id, m as { ok: boolean; error?: { code: string } })
+ }
+ })
+ // The host confirms its own half at once (the key is the link's), and then must send NOTHING more:
+ // no meta, no keyframe, no pty frame, while the fake pty would happily serve a session (F20).
+ await vi.waitFor(() => expect(frames.some((f) => f.json?.includes('trust:confirm'))).toBe(true))
+ await new Promise((r) => setTimeout(r, 30))
+ expect(t.sinks.size).toBe(0)
+ expect(t.calls).toEqual([])
+ for (const f of frames) {
+ expect(f.kind).toBe('text')
+ expect(parseRpcMessage(f.json!)).toEqual({ t: 'cast', method: 'trust:confirm', args: [] })
+ }
+ confirmed = true
+ raw.sendTunnelText(TRUST_CONFIRM)
+ await vi.waitFor(() => expect(t.sinks.size).toBe(1))
+ await vi.waitFor(() => expect(frames.some((f) => f.json?.includes(WATCH_EVENT.keyframe))).toBe(true))
+
+ // One request for every channel IPC names (and every per-session channel), and the same as a cast.
+ const methods = [
+ ...(Object.values(IPC) as unknown[]).filter((v): v is string => typeof v === 'string'),
+ ...(Object.values(IPC) as unknown[])
+ .filter((v): v is (id: string) => string => typeof v === 'function')
+ .map((f) => f('s1'))
+ ]
+ methods.forEach((method, i) => {
+ raw.sendTunnelText(JSON.stringify({ t: 'req', id: i + 1, method, args: ['s1', 'rm -rf ~\r', 1, 1] }))
+ raw.sendTunnelText(JSON.stringify({ t: 'cast', method, args: ['s1', 'rm -rf ~\r', 1, 1] }))
+ })
+ await vi.waitFor(() => expect(replies.size).toBe(methods.length))
+ methods.forEach((method, i) => {
+ const r = replies.get(i + 1)!
+ expect(r.ok, method).toBe(false)
+ // Host-only channels are refused by relay-host before any policy; everything else by the watcher's.
+ expect(r.error?.code, method).toBe(isHostOnlyChannel(method) ? 'E_FORBIDDEN' : 'E_ROLE')
+ })
+ // Refused by the ACCESS policy: a request or cast that reached the link host's own PeerAttach would
+ // have closed this viewer (fail closed). It is still here, and the pty saw only the host's calls.
+ expect(t.host.viewers()).toHaveLength(1)
+ expect(rawClosed).toBe(0)
+ expect(new Set(t.calls)).toEqual(new Set(['join', 'sync:s1', 'capture:s1']))
+ expect(t.joinArgs).toHaveLength(1)
+ expect(t.chats).toEqual([])
+ })
+
+ it('a viewer link drops chat casts; the viewer stays connected', async () => {
+ const t = setup({ role: 'viewer' })
+ t.host.start()
+ const v = await openViewer(t)
+ expect(v.c.sendChat('Ada', 'hello')).toBe(true)
+ await new Promise((r) => setTimeout(r, 20))
+ expect(t.chats).toEqual([])
+ expect(t.host.chatHistory()).toEqual([])
+ expect(t.host.viewers()).toHaveLength(1)
+ })
+
+ it('a pty event for the watched session is consumed (never forwarded), and another session is invisible', async () => {
+ const t = setup()
+ t.host.start()
+ const v = await openViewer(t)
+ const sink = t.sink()
+ pty(sink, 's1', `${ESC}[H`)
+ pty(sink, 's2', `${ESC}[Hother`)
+ ptyEvent(sink, IPC.ptyResync('s1'), 'history')
+ ptyEvent(sink, IPC.ptySize('s1'), { cols: 90, rows: 20 })
+ ptyEvent(sink, IPC.ptySize('s2'), { cols: 1, rows: 1 })
+ await new Promise((r) => setTimeout(r, 10))
+ expect(v.log.pty).toEqual([`${ESC}[H`])
+ expect(v.log.events.map((e) => e[0])).toEqual([WATCH_EVENT.meta, WATCH_EVENT.keyframe, IPC.ptySize('s1')])
+ })
+})
+
+describe('createLinkHost — joining, waiting, rejoining', () => {
+ it('waits (once), then streams when the session appears', async () => {
+ const clock = manualClock()
+ let running = false
+ const t = setup({ clock, join: () => (running ? { sessionId: 's9', cols: 80, rows: 24, altScreen: false } : null) })
+ t.host.start()
+ await vi.waitFor(() => expect(t.peers).toHaveLength(1))
+ const v = viewer(t.peers[0], t.keys)
+ await vi.waitFor(() => expect(v.log.events.map((e) => e[0])).toEqual([WATCH_EVENT.waiting]))
+ await clock.advance(REJOIN_BACKOFF_MS[0])
+ expect(t.joinArgs).toHaveLength(2)
+ expect(v.log.events.map((e) => e[0])).toEqual([WATCH_EVENT.waiting]) // not repeated per retry
+ running = true
+ await clock.advance(REJOIN_BACKOFF_MS[1])
+ await vi.waitFor(() => expect(v.log.events.map((e) => e[0])).toEqual([WATCH_EVENT.waiting, WATCH_EVENT.meta, WATCH_EVENT.keyframe]))
+ expect(v.named(WATCH_EVENT.meta)[0]).toMatchObject({ cols: 80, rows: 24 })
+ })
+
+ it('every join starts the filter mid-stream: the first join AND a rejoin after the session ended', async () => {
+ const clock = manualClock()
+ let n = 0
+ const t = setup({ clock, join: () => ({ sessionId: `s${++n}`, cols: 80, rows: 24, altScreen: true }) })
+ t.host.start()
+ const v = await openViewer(t)
+ const sink = t.sink()
+ pty(sink, 's1', 'x')
+ pty(sink, 's1', `${ESC}[Hy`)
+ expect(v.log.pty).toEqual([`${ESC}[Hy`])
+ ptyEvent(sink, IPC.ptyExit('s1'), 0)
+ await clock.flush()
+ expect(v.named(WATCH_EVENT.waiting)).toHaveLength(1)
+ expect(t.left).toEqual([`s1/${t.host.viewers()[0].viewerId}`])
+ await clock.advance(REJOIN_BACKOFF_MS[0])
+ await vi.waitFor(() => expect(v.keyframes().map((k) => k.sessionId)).toContain('s2'))
+ // A second meta (R14), and the rejoined session's filter is mid-stream again.
+ expect(v.named(WATCH_EVENT.meta)).toHaveLength(2)
+ pty(sink, 's2', 'z')
+ pty(sink, 's1', `${ESC}[Hdead`)
+ pty(sink, 's2', `${ESC}[Hw`)
+ expect(v.log.pty).toEqual([`${ESC}[Hy`, `${ESC}[Hw`])
+ // The lifecycle event itself never reached the viewer.
+ expect(v.log.events.map((e) => e[0]).filter((c) => c.startsWith('pty:'))).toEqual([])
+ })
+
+ it('the rejoin backoff grows for sessions that exit at once, and resets only after one stayed up 30 s (R26)', async () => {
+ const clock = manualClock()
+ let n = 0
+ const t = setup({ clock, join: () => ({ sessionId: `s${++n}`, cols: 80, rows: 24, altScreen: true }) })
+ t.host.start()
+ const v = await openViewer(t)
+ const sink = t.sink()
+ const exitCurrent = async (): Promise<void> => {
+ await vi.waitFor(() => expect(v.keyframes().map((k) => k.sessionId)).toContain(`s${n}`))
+ ptyEvent(sink, IPC.ptyExit(`s${n}`), 0)
+ await clock.flush()
+ }
+ await exitCurrent()
+ const expected = [2_000, 4_000, 8_000, 15_000, 30_000, 30_000]
+ for (const d of expected) {
+ await clock.advance(d)
+ await exitCurrent()
+ }
+ const deltas = t.joinTimes.slice(1).map((x, i) => x - t.joinTimes[i])
+ expect(deltas).toEqual(expected)
+ // This one stays up for REJOIN_STABLE_MS from its join keyframe: the backoff resets.
+ await clock.advance(30_000)
+ await vi.waitFor(() => expect(v.keyframes().map((k) => k.sessionId)).toContain(`s${n}`))
+ await clock.advance(REJOIN_STABLE_MS)
+ ptyEvent(sink, IPC.ptyExit(`s${n}`), 0)
+ await clock.flush()
+ const before = t.joinTimes.length
+ await clock.advance(REJOIN_BACKOFF_MS[0])
+ expect(t.joinTimes).toHaveLength(before + 1)
+ })
+
+ it('a join that throws is "waiting" and backs off; a capture that throws is an empty keyframe', async () => {
+ const clock = manualClock()
+ let fail = true
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})
+ const t = setup({
+ clock,
+ join: () => {
+ if (fail) throw new Error('spawn failed')
+ return { sessionId: 's1', cols: 80, rows: 24, altScreen: true }
+ },
+ capture: () => {
+ throw new Error('capture failed')
+ }
+ })
+ t.host.start()
+ await vi.waitFor(() => expect(t.peers).toHaveLength(1))
+ const v = viewer(t.peers[0], t.keys)
+ await vi.waitFor(() => expect(v.named(WATCH_EVENT.waiting)).toHaveLength(1))
+ fail = false
+ await clock.advance(REJOIN_BACKOFF_MS[0])
+ await vi.waitFor(() => expect(v.keyframes()).toHaveLength(1))
+ expect(v.keyframes()[0]).toEqual({ sessionId: 's1', screen: '', altScreen: true })
+ expect(warn).toHaveBeenCalled()
+ })
+
+ it('an exit that raced the join (the session is already gone) is waiting + rejoin, not a dead stream (R30)', async () => {
+ const clock = manualClock()
+ const dead = new Set(['s1'])
+ let n = 0
+ const t = setup({ clock, join: () => ({ sessionId: `s${++n}`, cols: 80, rows: 24, altScreen: true }), alive: (s) => !dead.has(s) })
+ t.host.start()
+ await vi.waitFor(() => expect(t.peers).toHaveLength(1))
+ const v = viewer(t.peers[0], t.keys)
+ await vi.waitFor(() => expect(v.named(WATCH_EVENT.waiting)).toHaveLength(1))
+ expect(v.keyframes()).toEqual([])
+ expect(t.left).toEqual([`s1/${t.host.viewers()[0].viewerId}`])
+ expect(t.calls).not.toContain('capture:s1')
+ await clock.advance(REJOIN_BACKOFF_MS[0])
+ await vi.waitFor(() => expect(v.keyframes().map((k) => k.sessionId)).toEqual(['s2']))
+ })
+
+ it('a session gone by the time its capture returns gets no keyframe: waiting + rejoin (R30)', async () => {
+ const clock = manualClock()
+ const dead = new Set<string>()
+ let n = 0
+ const t = setup({
+ clock,
+ join: () => ({ sessionId: `s${++n}`, cols: 80, rows: 24, altScreen: true }),
+ capture: (sid) => {
+ if (sid === 's1') dead.add('s1') // exits while being captured
+ return { screen: 'SCREEN', cursor: null }
+ },
+ alive: (s) => !dead.has(s)
+ })
+ t.host.start()
+ await vi.waitFor(() => expect(t.peers).toHaveLength(1))
+ const v = viewer(t.peers[0], t.keys)
+ await vi.waitFor(() => expect(v.named(WATCH_EVENT.waiting)).toHaveLength(1))
+ expect(v.keyframes()).toEqual([])
+ await clock.advance(REJOIN_BACKOFF_MS[0])
+ await vi.waitFor(() => expect(v.keyframes().map((k) => k.sessionId)).toEqual(['s2']))
+ })
+})
+
+describe('createLinkHost — keyframes and the stream', () => {
+ it('sync runs after a join (before its keyframe capture), before every keyframe capture, and every 10 s while watched', async () => {
+ const clock = manualClock()
+ const t = setup({ clock })
+ t.host.start()
+ const v = await openViewer(t)
+ expect(t.calls).toEqual(['join', 'sync:s1', 'capture:s1'])
+ pty(t.sink(), 's1', `${ESC}[H`) // settles the filter: one follow-up keyframe at the min interval
+ await clock.advance(1_000)
+ expect(t.calls.slice(3)).toEqual(['sync:s1', 'capture:s1'])
+ expect(v.keyframes()).toHaveLength(2)
+ await clock.advance(WATCHER_SIZE_SYNC_MS - 1_000)
+ expect(t.calls.slice(5)).toEqual(['sync:s1'])
+ await clock.advance(WATCHER_SIZE_SYNC_MS)
+ expect(t.calls.slice(6)).toEqual(['sync:s1'])
+ // No joined viewer: no more syncs.
+ t.host.kick(t.host.viewers()[0].viewerId)
+ await clock.advance(3 * WATCHER_SIZE_SYNC_MS)
+ expect(t.calls.slice(7)).toEqual([])
+ })
+
+ it('onOverBudget stops the stream NOW even while a keyframe timer is armed (F10)', async () => {
+ const clock = manualClock()
+ let buffered = 0
+ const t = setup({ clock, buffered: () => buffered })
+ t.host.start()
+ const v = await openViewer(t)
+ const sink = t.sink()
+ // Settling arms the follow-up keyframe timer while the stream keeps flowing.
+ pty(sink, 's1', `${ESC}[H`)
+ expect(v.log.pty).toEqual([`${ESC}[H`])
+ buffered = 600 * 1024
+ pty(sink, 's1', 'a') // dropped: over the buffer limit
+ buffered = 0
+ pty(sink, 's1', 'b') // must NOT follow the dropped frame without a repaint between
+ expect(v.log.pty).toEqual([`${ESC}[H`])
+ await clock.advance(1_000)
+ expect(v.keyframes()).toHaveLength(2)
+ pty(sink, 's1', 'c')
+ expect(v.log.pty).toEqual([`${ESC}[H`, 'c'])
+ })
+
+ it('a stalled viewer is throttled to keyframes, painted only once its socket drained', async () => {
+ const clock = manualClock()
+ let buffered = 0
+ const t = setup({ clock, buffered: () => buffered })
+ t.host.start()
+ const v = await openViewer(t)
+ const sink = t.sink()
+ pty(sink, 's1', `${ESC}[H`)
+ await clock.advance(1_000) // the settle follow-up
+ expect(v.keyframes()).toHaveLength(2)
+ buffered = 1_000_000
+ for (let i = 0; i < 50; i++) pty(sink, 's1', 'y\r\n')
+ expect(v.log.pty).toEqual([`${ESC}[H`])
+ await clock.advance(3_000) // still backed up: no keyframe on top of the backlog
+ expect(v.keyframes()).toHaveLength(2)
+ buffered = 0
+ await clock.advance(1_000)
+ expect(v.keyframes()).toHaveLength(3)
+ pty(sink, 's1', 'after')
+ expect(v.log.pty).toEqual([`${ESC}[H`, 'after'])
+ })
+
+ it('the token bucket throttles a flood to at most one keyframe a second', async () => {
+ const clock = manualClock()
+ const t = setup({ clock })
+ t.host.start()
+ const v = await openViewer(t)
+ const sink = t.sink()
+ pty(sink, 's1', `${ESC}[H`)
+ await clock.advance(1_000)
+ const chunk = 'x'.repeat(64 * 1024)
+ for (let i = 0; i < 40; i++) pty(sink, 's1', chunk) // 2.5 MB at one instant: past the 1 MB burst
+ const forwarded = v.log.pty.join('').length
+ expect(forwarded).toBeLessThanOrEqual(1024 * 1024)
+ await clock.advance(1_000)
+ expect(v.keyframes()).toHaveLength(3)
+ })
+
+ it('a follow-up keyframe when the filter settles after the join keyframe; one at 2 s if it has not (R23)', async () => {
+ const clock = manualClock()
+ const t = setup({ clock })
+ t.host.start()
+ const v = await openViewer(t)
+ const sink = t.sink()
+ // Settles half a second in: the follow-up comes at the min interval, and the 2 s bound adds none.
+ await clock.advance(500)
+ pty(sink, 's1', `${ESC}[H`)
+ await clock.advance(499)
+ expect(v.keyframes()).toHaveLength(1)
+ await clock.advance(1)
+ expect(v.keyframes()).toHaveLength(2)
+ await clock.advance(5_000)
+ expect(v.keyframes()).toHaveLength(2)
+ })
+
+ it('an unsettled filter gets a keyframe at the 2 s bound, and one more when it settles later (R23)', async () => {
+ const clock = manualClock()
+ const t = setup({ clock })
+ t.host.start()
+ const v = await openViewer(t)
+ await clock.advance(SETTLE_BOUND_MS - 1)
+ expect(v.keyframes()).toHaveLength(1)
+ await clock.advance(1)
+ expect(v.keyframes()).toHaveLength(2)
+ await clock.advance(3_000)
+ expect(v.keyframes()).toHaveLength(2)
+ pty(t.sink(), 's1', `${ESC}[H`)
+ await clock.advance(0)
+ expect(v.keyframes()).toHaveLength(3)
+ await clock.advance(10_000)
+ expect(v.keyframes()).toHaveLength(3)
+ })
+
+ it('a filter that settled before the join keyframe was painted takes no follow-up', async () => {
+ const clock = manualClock()
+ let release: (c: VisibleCapture) => void = () => {}
+ const t = setup({ clock, capture: () => new Promise<VisibleCapture>((r) => (release = r)) })
+ t.host.start()
+ await vi.waitFor(() => expect(t.peers).toHaveLength(1))
+ const v = viewer(t.peers[0], t.keys)
+ await vi.waitFor(() => expect(t.calls).toContain('capture:s1'))
+ pty(t.sink(), 's1', `${ESC}[Hx`) // not forwarded (no keyframe yet), but the filter settles
+ release({ screen: 'SCREEN', cursor: null })
+ await vi.waitFor(() => expect(v.keyframes()).toHaveLength(1))
+ await clock.advance(10_000)
+ expect(v.keyframes()).toHaveLength(1)
+ expect(v.log.pty).toEqual([])
+ })
+
+ it("one capture per session is shared by the link's viewers joining it together (R27)", async () => {
+ const clock = manualClock()
+ const releases: ((c: VisibleCapture) => void)[] = []
+ const t = setup({ clock, capture: () => new Promise<VisibleCapture>((r) => releases.push(r)) })
+ t.host.start()
+ await vi.waitFor(() => expect(t.peers).toHaveLength(1))
+ const a = viewer(t.peers[0], t.keys)
+ await vi.waitFor(() => expect(t.calls).toContain('capture:s1'))
+ await vi.waitFor(() => expect(t.peers).toHaveLength(2))
+ const b = viewer(t.peers[1], t.keys)
+ await vi.waitFor(() => expect(t.joinArgs).toHaveLength(2))
+ await clock.flush()
+ expect(t.calls.filter((c) => c === 'capture:s1')).toHaveLength(1)
+ releases[0]({ screen: 'ONE', cursor: null })
+ await vi.waitFor(() => expect(b.keyframes()).toHaveLength(1))
+ expect(a.keyframes().map((k) => k.screen)).toEqual(['ONE'])
+ expect(b.keyframes().map((k) => k.screen)).toEqual(['ONE'])
+ })
+
+ it('a keyframe asked for while a capture runs waits for a NEWER one; the stream resumes only on it', async () => {
+ const clock = manualClock()
+ const releases: ((c: VisibleCapture) => void)[] = []
+ const t = setup({ clock, capture: () => new Promise<VisibleCapture>((r) => releases.push(r)) })
+ t.host.start()
+ await vi.waitFor(() => expect(t.peers).toHaveLength(1))
+ const v = viewer(t.peers[0], t.keys)
+ await vi.waitFor(() => expect(releases).toHaveLength(1))
+ // The 2 s bound asks for a keyframe while the join keyframe's capture is still running.
+ await clock.advance(SETTLE_BOUND_MS)
+ expect(releases).toHaveLength(1) // one capture in flight per session: the second is queued
+ releases[0]({ screen: 'OLD', cursor: null })
+ await vi.waitFor(() => expect(releases).toHaveLength(2))
+ expect(v.keyframes().map((k) => k.screen)).toEqual(['OLD'])
+ pty(t.sink(), 's1', `${ESC}[Hbetween`) // after the OLD paint, before the newer one: not forwarded
+ expect(v.log.pty).toEqual([])
+ releases[1]({ screen: 'NEW', cursor: null })
+ await vi.waitFor(() => expect(v.keyframes().map((k) => k.screen)).toEqual(['OLD', 'NEW']))
+ pty(t.sink(), 's1', 'after')
+ expect(v.log.pty).toEqual(['after'])
+ })
+})
+
+describe('createLinkHost — chat', () => {
+ it('relays commenter chat, rate-limited and sanitized, to viewers and the owner', async () => {
+ const t = setup({ role: 'commenter' })
+ t.host.start()
+ const v = await openViewer(t)
+ expect(v.c.sendChat('Ada', 'hello\u0007')).toBe(true)
+ expect(v.c.sendChat('Ada', 'again')).toBe(true) // inside 2 s: dropped by the host
+ await vi.waitFor(() => expect(t.chats).toHaveLength(1))
+ expect(t.chats[0]).toMatchObject({ name: 'Ada', text: 'hello', from: 'viewer' })
+ await vi.waitFor(() => expect(v.named(WATCH_EVENT.chat)).toHaveLength(1))
+ expect(t.host.viewers()[0].name).toBe('Ada')
+ expect(t.host.postSharerChat('hi back')).toMatchObject({ from: 'sharer', name: 'Ada', text: 'hi back' })
+ await vi.waitFor(() => expect(v.named(WATCH_EVENT.chat)).toHaveLength(2))
+ expect(t.host.chatHistory()).toHaveLength(2)
+ })
+
+ it('a sharer cannot chat on a viewer link', async () => {
+ const t = setup({ role: 'viewer' })
+ expect(t.host.postSharerChat('hi')).toBeNull()
+ })
+
+ it('skips chat for a viewer over 512 KB behind, and closes one over 8 MB behind — no end, not a revoke (R28)', async () => {
+ const buffered = [0, 0]
+ const t = setup({ role: 'commenter', buffered: (i) => buffered[i] ?? 0 })
+ t.host.start()
+ const a = await openViewer(t, 0)
+ const b = await openViewer(t, 1)
+ expect(t.host.viewers()).toHaveLength(2)
+ const aId = t.host.viewers()[0].viewerId
+ buffered[0] = 600 * 1024
+ t.host.postSharerChat('one')
+ await vi.waitFor(() => expect(b.named(WATCH_EVENT.chat)).toHaveLength(1))
+ expect(a.named(WATCH_EVENT.chat)).toHaveLength(0)
+ buffered[0] = 9 * 1024 * 1024
+ t.host.postSharerChat('two')
+ await vi.waitFor(() => expect(b.named(WATCH_EVENT.chat)).toHaveLength(2))
+ await vi.waitFor(() => expect(a.log.closed).toBe(1))
+ expect(a.named(WATCH_EVENT.end)).toEqual([])
+ expect(t.host.viewers().map((x) => x.viewerId)).not.toContain(aId)
+ expect(t.left).toContain(`s1/${aId}`)
+ expect(t.gone).toEqual([])
+ })
+})
+
+describe('createLinkHost — ending', () => {
+ it('kick ends one viewer with a reason; stop ends everyone, leaves the pty and mints nothing (F1)', async () => {
+ const t = setup()
+ t.host.start()
+ const a = await openViewer(t, 0)
+ const b = await openViewer(t, 1)
+ await vi.waitFor(() => expect(t.host.viewers()).toHaveLength(2))
+ await vi.waitFor(() => expect(t.peers).toHaveLength(3))
+ expect(t.host.kick(t.host.viewers()[0].viewerId)).toBe(true)
+ expect(t.host.kick('v-nobody0')).toBe(false)
+ await vi.waitFor(() => expect(a.named(WATCH_EVENT.end)).toEqual([{ reason: 'kicked' }]))
+ await new Promise((r) => setTimeout(r, 10))
+ const minted = t.mints()
+ t.host.stop('revoked')
+ await vi.waitFor(() => expect(b.named(WATCH_EVENT.end)).toEqual([{ reason: 'revoked' }]))
+ await new Promise((r) => setTimeout(r, 20))
+ expect(t.mints()).toBe(minted)
+ expect(t.left).toHaveLength(2)
+ expect(t.sinks.size).toBe(0)
+ expect(t.host.viewers()).toEqual([])
+ })
+
+ it('start after stop is a no-op (F26)', async () => {
+ const t = setup()
+ t.host.stop('revoked')
+ t.host.start()
+ await new Promise((r) => setTimeout(r, 10))
+ expect(t.mints()).toBe(0)
+ expect(t.peers).toHaveLength(0)
+ })
+
+ it('a 410 from the host-token route ends the link as gone', async () => {
+ const t = setup({ mint: async () => ({ ok: false, kind: 'gone', reason: 'expired' }) })
+ t.host.start()
+ await vi.waitFor(() => expect(t.gone).toEqual(['expired']))
+ })
+
+ it('a peer that never confirms is closed at the confirm deadline, freeing its slot (R31)', async () => {
+ const clock = manualClock()
+ const t = setup({ clock })
+ t.host.start()
+ await vi.waitFor(() => expect(t.peers).toHaveLength(1))
+ let closed = 0
+ connectRelay({
+ url: 'x', token: 'x', role: 'client', theirPubB64: publicKeyToB64(t.keys.host.publicKey),
+ ourKeys: { publicKey: t.keys.viewer.publicKey, secretKey: t.keys.viewer.secretKey },
+ transport: t.peers[0], onReady: () => {}, onRpc: () => {}, onFrame: () => {},
+ onClose: () => { closed++ }
+ })
+ await vi.waitFor(() => expect(t.peers).toHaveLength(2)) // bridged: a replacement opened
+ await clock.advance(CONFIRM_DEADLINE_MS - 1)
+ expect(closed).toBe(0)
+ await clock.advance(1)
+ expect(closed).toBe(1)
+ expect(t.sinks.size).toBe(0)
+ // A confirming viewer on the replacement is not affected by that deadline.
+ const v = viewer(t.peers[1], t.keys)
+ await vi.waitFor(() => expect(v.keyframes()).toHaveLength(1))
+ await clock.advance(CONFIRM_DEADLINE_MS)
+ expect(t.host.viewers()).toHaveLength(1)
+ })
+
+ it('a full link opens no 11th listener and polls status; a server-side revoke ends it', async () => {
+ const clock = manualClock()
+ let state: 'live' | 'revoked' = 'live'
+ const status = vi.fn(async () => state)
+ const t = setup({ clock, status })
+ t.host.start()
+ const vs: Viewer[] = []
+ for (let i = 0; i < MAX_VIEWERS_PER_LINK; i++) vs.push(await openViewer(t, i))
+ await clock.flush()
+ expect(t.peers).toHaveLength(MAX_VIEWERS_PER_LINK) // no idle listener while full
+ await clock.advance(FULL_STATUS_POLL_MS)
+ expect(status).toHaveBeenCalledTimes(1)
+ expect(t.gone).toEqual([])
+ state = 'revoked'
+ await clock.advance(FULL_STATUS_POLL_MS)
+ expect(status).toHaveBeenCalledTimes(2)
+ expect(t.gone).toEqual(['revoked'])
+ for (const v of vs) expect(v.named(WATCH_EVENT.end)).toEqual([{ reason: 'revoked' }])
+ })
+})
diff --git a/src/core/watch-link/link-host.ts b/src/core/watch-link/link-host.ts
new file mode 100644
index 000000000..cc6f5bd83
--- /dev/null
+++ b/src/core/watch-link/link-host.ts
@@ -0,0 +1,877 @@
+// One live link at runtime: its standing relay listeners (one hosted-scheduler, capped at
+// MAX_VIEWERS_PER_LINK bridged), and for every connected viewer a relay-host session whose peer key
+// must be the one derived from the link secret. The viewer is attached as a QUIET, SELF-PACED core
+// client; the host joins the node's RUNNING session on its behalf (join-only, never a size vote,
+// every argument built from the host's own records — nothing comes from the viewer), sends meta and a
+// visible-screen keyframe, then streams through the watcher sink (watcher-policy.ts).
+//
+// READ-ONLY IS ENFORCED HERE, on the host. The relay-host `access` hook refuses every request and
+// every cast but a Commenter's chat (watcherAccess), and this module's own `PeerAttach` is the second
+// layer: it forwards nothing to any platform, and a request or a non-chat cast that reaches it anyway
+// means the access policy failed, so the session is CLOSED (fail closed, as relay-host does for a
+// throwing wrapSink). No viewer byte, size or resize reaches a pty: the join, the size sync and the
+// capture take only ids the host chose. No `interceptReq` is ever supplied (it would bypass `access`).
+//
+// relay-host never tells us about ends it caused itself (`deny`, `close`): every such path goes
+// through `ended()`, which reports to the scheduler exactly once (the hosted-service pattern).
+//
+// THE STREAM. The watcher's filter (stream-filter.ts) starts MID-STREAM on every join: a viewer
+// co-attaches to a running session and its first byte may fall inside an OSC 52. Frames that arrive
+// before `c.sessionId` is known never reach the filter at all (the wrapper needs the session id), so
+// a join can never start in text mode. A mid-stream filter swallows text until the first escape; the
+// join keyframe is sent at once, and if the filter had not settled by then ONE follow-up keyframe is
+// taken when it does (`onSettled`), plus one at SETTLE_BOUND_MS after the join if it still has not
+// (controller ruling R23). The filter is never reset to text mode to "unstick" it: inside a string
+// that would print the string's payload.
+//
+// KEYFRAMES are a visible-only capture (never history) passed through a FRESH text-mode filter (a
+// capture starts in ground state, and `capture-pane -e` emits OSC 8 verbatim — R9), with the host's
+// cursor when it was read (R10) and `altScreen` from the join (a tmux client paints on the alternate
+// screen — R18). One capture per session is in flight at a time, shared by this link's viewers of
+// that session (R27): a JOIN keyframe may share a capture already running (that viewer has forwarded
+// nothing of this session, so an earlier screen cannot paint over newer output it showed), any other
+// keyframe needs a capture STARTED after it asked. A per-viewer sequence makes sure an older result
+// is never painted after a newer one, and streaming resumes only on the newest.
+//
+// SIZE. A viewer never sizes anything. Its meta carries the joined session's CURRENT size (R25). A
+// watcher's OWN tmux client (spawned when no owner Session is held) attaches with `ignore-size`, but
+// tmux honours that only while some client WITHOUT the flag is attached to the server (measured,
+// tmux 3.4): when the watcher is the only client, tmux's `window-size latest` sizes the window to it.
+// So `syncSize` (PtyManager.syncWatcherClientSize, serialized per session there — R24) keeps that
+// client at the window's size: before every keyframe capture (the screen then matches the size) and
+// every WATCHER_SIZE_SYNC_MS while this link has a joined viewer. Residual: the window lands on the
+// last-synced size until another client sizes it, for up to one interval.
+//
+// SPLIT PANES: a keyframe captures the session's ACTIVE pane only (`=nt-<id>:`); the stream, which is
+// the tmux client's own output, repairs the rest as tmux redraws it.
+//
+// BACKLOG. A watcher is self-paced (the registry never pauses or drops for it), so it bounds its own
+// backlog: pty frames stop at WATCHER_BUFFER_LIMIT (watcher-policy), chat is skipped for a viewer that
+// far behind, and past VIEWER_BACKLOG_CLOSE the viewer's session is closed (R28): a socket that never
+// drains must not grow the host's memory. meta, keyframe, waiting and end are small and rare.
+//
+// REJOIN. A session that ends (exit, closed, recycled, or found gone after a join or a capture — R30)
+// sends the viewer `watch:waiting` and rejoins on a backoff. The backoff is reset only once a joined
+// session stayed up for REJOIN_STABLE_MS from its join keyframe (R26), never on a join or a lifecycle
+// event: an old remote tmux that rejects the client flags, or an owner's repeated `-D`, attaches then
+// exits at once, and resetting on success turned that into a spawn + read + capture every 2 s forever.
+//
+// Nothing here throws out of a callback or a void promise: relay-host calls into this module from a
+// socket's message emit and from the trust gate's async settle, where a throw is lost or unhandled.
+import nacl from 'tweetnacl'
+import { connectRelayHost, type PeerAttach, type RelayHostSession } from '../relay/relay-host'
+import type { RelayTransport } from '../relay/relay-socket'
+import { createHostedScheduler, type Listener, type SchedulerStatus } from '../relay/hosted-scheduler'
+import type { MintResult } from '../relay/host-token'
+import type { UiSink } from '../ui-sink-registry'
+import type { RpcErr } from '../../shared/rpc'
+import { bytesToB64, bytesToHex } from '../../shared/watch-link/bytes'
+import { deriveWatchLinkKeys } from '../../shared/watch-link/keys'
+import {
+ WATCH_CHAT_CAST,
+ WATCH_EVENT,
+ WATCH_PROTOCOL_VERSION,
+ sanitizeChatName,
+ sanitizeChatText,
+ type WatchChatMessage,
+ type WatchKeyframe,
+ type WatchLinkEndReason,
+ type WatchMeta
+} from '../../shared/watch-link/protocol'
+import type { HostTokenResult } from './api'
+import { unavailableCapture, type VisibleCapture } from './capture-route'
+import { createStreamFilter, type StreamFilter } from './stream-filter'
+import { createTokenBucket, type TokenBucket } from './token-bucket'
+import {
+ WATCHER_BUFFER_LIMIT,
+ WATCHER_REFUSAL,
+ WATCHER_RESUME_BELOW,
+ watcherAccess,
+ wrapWatcherSink
+} from './watcher-policy'
+import type { WatchLinkRecord } from './store'
+
+export const MAX_VIEWERS_PER_LINK = 10
+/** While the link is full (no idle listener, so no mint), how often the API is asked whether the link
+ * was revoked or expired server-side. */
+export const FULL_STATUS_POLL_MS = 5 * 60_000
+export const CHAT_MIN_INTERVAL_MS = 2_000
+export const CHAT_HISTORY_MAX = 200
+export const KEYFRAME_MIN_INTERVAL_MS = 1_000
+/** Rejoin delays, by attempt. The last repeats (R26: an instant-exit loop climbs to the 30 s cap). */
+export const REJOIN_BACKOFF_MS = [2_000, 4_000, 8_000, 15_000, 30_000]
+/** A joined session that stayed up this long (from its join keyframe) resets the rejoin backoff. */
+export const REJOIN_STABLE_MS = 30_000
+/** An unsettled mid-stream filter gets one more keyframe this long after the join (R23). */
+export const SETTLE_BOUND_MS = 2_000
+/** How often a watcher's own tmux client is re-synced to the window size while the link has viewers. */
+export const WATCHER_SIZE_SYNC_MS = 10_000
+/** A peer that completed the handshake with the right key but has not confirmed by now is closed: it
+ * would hold one of the link's viewer slots until its socket drops (R31). */
+export const CONFIRM_DEADLINE_MS = 30_000
+/** A viewer whose socket backlog passes this is closed (viewer gone, not a revoke) — R28. */
+export const VIEWER_BACKLOG_CLOSE = 8 * 1024 * 1024
+const RATE = 256 * 1024
+const BURST = 1024 * 1024
+
+/** What `WatchPty.join` answers for a session the viewer now watches. */
+export interface WatchJoin {
+ sessionId: string
+ /** The joined session's CURRENT size (`PtyManager.sessionSize`), never a viewer's (R25). */
+ cols: number
+ rows: number
+ /** The stream is a tmux client's output (`PtyCreateResult.tmuxClient`), which tmux paints on the
+ * alternate screen whatever the pane's application does (R18). */
+ altScreen: boolean
+}
+
+/**
+ * The pty seam (wired to PtyManager by the shells). Every argument is the HOST's: a node id from the
+ * link record, a viewer id this module minted, a session id `join` answered. Nothing from a viewer.
+ */
+export interface WatchPty {
+ /**
+ * Join the node's RUNNING session for this viewer (`joinAsWatcher`: join-only, no size vote, remote
+ * fields from the host's own records). null for every refusal — no running session, any
+ * `unavailable` (`join-only`, `ssh`, `codex-account`), a spawn refused because the window size could
+ * not be read — and the caller may also throw; both mean "waiting, try again later".
+ */
+ join(clientId: number, nodeId: string, viewerId: string): Promise<WatchJoin | null>
+ leave(clientId: number, sessionId: string, viewerId: string): void
+ /** The visible screen and cursor, never history (`PtyManager.captureVisible`). */
+ captureVisible(sessionId: string): Promise<VisibleCapture>
+ /** Keep a watcher's OWN tmux client at the window's size (`PtyManager.syncWatcherClientSize`, which
+ * serializes per session). Takes no size: nothing a viewer says can size anything. */
+ syncSize(sessionId: string): Promise<boolean>
+ /** The session is still known to the pty layer (an exit can race the join or a capture — R30). */
+ alive(sessionId: string): boolean
+}
+export interface QuietClients {
+ attach(sink: UiSink): number
+ detach(id: number): void
+}
+export interface LinkHostDeps {
+ relayUrl: string
+ mint(): Promise<HostTokenResult>
+ status(): Promise<'live' | 'revoked' | 'expired' | 'unknown'>
+ clients: QuietClients
+ pty: WatchPty
+ transport?: () => RelayTransport
+ now(): number
+ setTimeout(fn: () => void, ms: number): unknown
+ clearTimeout(h: unknown): void
+ onChange(): void
+ onChat(msg: WatchChatMessage): void
+ onViewerJoined(count: number): void
+ onGone(reason: 'revoked' | 'expired'): void
+}
+export type LinkRuntimeStatus = 'live' | 'reconnecting' | 'refused'
+export interface LinkViewer {
+ viewerId: string
+ name: string | null
+ joinedAt: number
+}
+export interface LinkHost {
+ start(): void
+ stop(reason: WatchLinkEndReason): void
+ kick(viewerId: string): boolean
+ postSharerChat(text: string): WatchChatMessage | null
+ chatHistory(): WatchChatMessage[]
+ status(): LinkRuntimeStatus
+ viewers(): LinkViewer[]
+}
+
+interface Conn {
+ viewerId: string
+ ev: { onBridged(): void; onClose(): void }
+ session: RelayHostSession | null
+ clientId: number | null
+ /** The WRAPPED watcher sink relay-host attached (every event we send passes its outbound filter). */
+ sink: UiSink | null
+ attachFailed: boolean
+ bridged: boolean
+ ended: boolean
+ confirmTimer: unknown
+ /** When both ends confirmed and the viewer became a client; null before. */
+ joinedAt: number | null
+ name: string | null
+ lastChatAt: number
+ // The watched session (null while waiting).
+ sessionId: string | null
+ altScreen: boolean
+ joining: boolean
+ waiting: boolean
+ streaming: boolean
+ filter: StreamFilter
+ bucket: TokenBucket
+ /** The current session's mid-stream filter has left its unknown start state. */
+ settled: boolean
+ /** Take one more keyframe when it does (it had not when the join keyframe was painted). */
+ followUpOnSettle: boolean
+ /** The current session's first keyframe was painted. */
+ painted: boolean
+ kfSeq: number
+ kfDelivered: number
+ lastKeyframeAt: number
+ keyframeTimer: unknown
+ settleTimer: unknown
+ stableTimer: unknown
+ rejoinAttempt: number
+ rejoinTimer: unknown
+ warned: Set<string>
+}
+
+interface CaptureSlot {
+ current: { epoch: number; result: Promise<VisibleCapture> } | null
+ /** The one rerun queued behind `current`, shared by every keyframe that needs a newer capture. */
+ next: { result: Promise<VisibleCapture>; start(): void } | null
+}
+
+const errorText = (err: unknown): string => (err instanceof Error ? err.message : String(err))
+
+function normalizeJoin(r: unknown): WatchJoin | null {
+ if (!r || typeof r !== 'object') return null
+ const o = r as Partial<WatchJoin>
+ if (typeof o.sessionId !== 'string' || !o.sessionId) return null
+ const dim = (n: unknown, d: number): number => (Number.isInteger(n) && (n as number) > 0 ? (n as number) : d)
+ return { sessionId: o.sessionId, cols: dim(o.cols, 80), rows: dim(o.rows, 24), altScreen: o.altScreen === true }
+}
+
+function normalizeCapture(c: unknown): VisibleCapture {
+ if (!c || typeof c !== 'object' || typeof (c as VisibleCapture).screen !== 'string') return unavailableCapture()
+ const cur = (c as VisibleCapture).cursor
+ const ok = !!cur && Number.isInteger(cur.x) && Number.isInteger(cur.y) && cur.x >= 0 && cur.y >= 0
+ return { screen: (c as VisibleCapture).screen, cursor: ok ? { x: cur!.x, y: cur!.y } : null }
+}
+
+export function createLinkHost(record: WatchLinkRecord, deps: LinkHostDeps): LinkHost {
+ const keys = deriveWatchLinkKeys(record.secret)
+ const hostKeys = { publicKey: keys.host.publicKey, secretKey: keys.host.secretKey }
+ const expectedViewerKey = bytesToB64(keys.viewer.publicKey)
+ const conns = new Set<Conn>()
+ const chat: WatchChatMessage[] = []
+ const captures = new Map<string, CaptureSlot>()
+ let captureEpoch = 0
+ let sched: SchedulerStatus | null = null
+ let pollTimer: unknown = null
+ let syncTimer: unknown = null
+ let stopped = false
+ const warnedHost = new Set<string>()
+
+ const clearTimer = (h: unknown): void => {
+ if (h !== null) deps.clearTimeout(h)
+ }
+ /** One line per kind per viewer (or per link): a failure that repeats every rejoin must not flood. */
+ const warn = (c: Conn | null, kind: string, detail: string): void => {
+ const seen = c ? c.warned : warnedHost
+ if (seen.has(kind)) return
+ seen.add(kind)
+ console.warn(`[watch-link] ${kind}: ${detail}`)
+ }
+ /** A callback the registry owns must not throw into relay-host's emit or the trust gate's settle. */
+ const safe = (label: string, fn: () => void): void => {
+ try {
+ fn()
+ } catch (err) {
+ console.warn(`[watch-link] ${label} threw: ${errorText(err)}`)
+ }
+ }
+ const bufferedOf = (c: Conn): number => {
+ try {
+ return c.sink?.bufferedAmount?.() ?? 0
+ } catch {
+ return 0
+ }
+ }
+
+ /** Send one `watch:*` event through the viewer's own (filtered) sink. False when not sent. */
+ function send(c: Conn, channel: string, payload: unknown, opts: { chat?: boolean } = {}): boolean {
+ if (c.ended || !c.sink) return false
+ const buffered = bufferedOf(c)
+ if (buffered > VIEWER_BACKLOG_CLOSE) {
+ dropStalled(c)
+ return false
+ }
+ if (opts.chat && buffered > WATCHER_BUFFER_LIMIT) return false
+ try {
+ c.sink.sendText(JSON.stringify({ t: 'ev', channel, args: [payload] }))
+ } catch {
+ // A dead socket: relay-host's own close tears the session down.
+ }
+ return true
+ }
+ function dropStalled(c: Conn): void {
+ warn(null, 'a viewer stopped draining its socket; closed it', `backlog over ${VIEWER_BACKLOG_CLOSE} bytes`)
+ c.session?.close()
+ ended(c)
+ }
+ function leave(clientId: number | null, sessionId: string, viewerId: string, c: Conn | null): void {
+ if (clientId === null || clientId < 0) return
+ try {
+ deps.pty.leave(clientId, sessionId, viewerId)
+ } catch (err) {
+ warn(c, 'leaving a watched session failed', errorText(err))
+ }
+ }
+ const aliveOf = (c: Conn, sessionId: string): boolean => {
+ try {
+ return deps.pty.alive(sessionId) === true
+ } catch (err) {
+ warn(c, 'the session liveness check failed', errorText(err))
+ return false
+ }
+ }
+
+ function ended(c: Conn): void {
+ if (c.ended) return
+ c.ended = true
+ conns.delete(c)
+ for (const h of [c.confirmTimer, c.rejoinTimer, c.keyframeTimer, c.settleTimer, c.stableTimer]) clearTimer(h)
+ c.confirmTimer = c.rejoinTimer = c.keyframeTimer = c.settleTimer = c.stableTimer = null
+ const sid = c.sessionId
+ c.sessionId = null
+ c.streaming = false
+ if (sid !== null) leave(c.clientId, sid, c.viewerId, c)
+ safe('the scheduler', () => c.ev.onClose())
+ updateSyncTimer()
+ if (c.joinedAt !== null && !stopped) safe('onChange', deps.onChange)
+ }
+ function endConn(c: Conn, reason: WatchLinkEndReason): void {
+ send(c, WATCH_EVENT.end, { reason })
+ c.session?.close()
+ ended(c)
+ }
+ /** The access policy let something through: fail closed. */
+ function policyBreach(c: Conn, what: string): void {
+ // `what` names a peer-chosen method: quoted and capped, so it cannot forge a log line.
+ console.warn(`[watch-link] a viewer's ${JSON.stringify(what.slice(0, 80))} got past the watcher policy; closing that viewer`)
+ c.session?.close()
+ ended(c)
+ }
+
+ // --- captures: one in flight per session, shared by this link's viewers (R27) ---------------------
+
+ async function runCapture(sessionId: string): Promise<VisibleCapture> {
+ // Size first, so the screen is captured at the size the viewer is about to be told.
+ try {
+ await deps.pty.syncSize(sessionId)
+ } catch (err) {
+ warn(null, 'the watcher size sync failed', errorText(err))
+ }
+ try {
+ return normalizeCapture(await deps.pty.captureVisible(sessionId))
+ } catch (err) {
+ warn(null, 'a keyframe capture failed', errorText(err))
+ return unavailableCapture()
+ }
+ }
+ function startCapture(sessionId: string, slot: CaptureSlot): Promise<VisibleCapture> {
+ const result = runCapture(sessionId)
+ slot.current = { epoch: ++captureEpoch, result }
+ void result.then(() => {
+ slot.current = null
+ const next = slot.next
+ slot.next = null
+ if (next) next.start()
+ else if (captures.get(sessionId) === slot) captures.delete(sessionId)
+ })
+ return result
+ }
+ /** A capture of `sessionId` that started after epoch `needAfter` (-1: any, even one running now). */
+ function captureFor(sessionId: string, needAfter: number): Promise<VisibleCapture> {
+ let slot = captures.get(sessionId)
+ if (!slot) {
+ slot = { current: null, next: null }
+ captures.set(sessionId, slot)
+ }
+ if (!slot.current) return startCapture(sessionId, slot)
+ if (slot.current.epoch > needAfter) return slot.current.result
+ if (slot.next) return slot.next.result
+ const s = slot
+ let resolve: (v: VisibleCapture | Promise<VisibleCapture>) => void = () => {}
+ const result = new Promise<VisibleCapture>((r) => (resolve = r))
+ s.next = { result, start: () => resolve(stopped ? unavailableCapture() : startCapture(sessionId, s)) }
+ return result
+ }
+
+ // --- keyframes ------------------------------------------------------------------------------------
+
+ function requestKeyframe(c: Conn, join: boolean): void {
+ const sid = c.sessionId
+ if (sid === null || c.ended || stopped) return
+ // Nothing is forwarded from here until the newest keyframe is painted: a frame sent now could be
+ // painted over by an older screen.
+ c.streaming = false
+ const seq = ++c.kfSeq
+ void captureFor(sid, join ? -1 : captureEpoch).then((cap) => {
+ try {
+ deliverKeyframe(c, sid, seq, cap)
+ } catch (err) {
+ warn(c, 'painting a keyframe failed', errorText(err))
+ }
+ })
+ }
+ function deliverKeyframe(c: Conn, sid: string, seq: number, cap: VisibleCapture): void {
+ if (c.ended || stopped || c.sessionId !== sid || seq <= c.kfDelivered) return
+ if (!aliveOf(c, sid)) {
+ sessionOver(c)
+ return
+ }
+ const kf: WatchKeyframe = {
+ sessionId: sid,
+ // A FRESH filter: the capture starts in ground state, and carries OSC 8 links verbatim (R9).
+ screen: createStreamFilter().push(cap.screen),
+ altScreen: c.altScreen,
+ ...(cap.cursor ? { cursor: { x: cap.cursor.x, y: cap.cursor.y } } : {})
+ }
+ if (!send(c, WATCH_EVENT.keyframe, kf)) return
+ c.kfDelivered = seq
+ c.lastKeyframeAt = deps.now()
+ if (seq === c.kfSeq) c.streaming = true
+ if (!c.painted) {
+ c.painted = true
+ c.followUpOnSettle = !c.settled
+ clearTimer(c.stableTimer)
+ c.stableTimer = deps.setTimeout(() => {
+ c.stableTimer = null
+ c.rejoinAttempt = 0
+ }, REJOIN_STABLE_MS)
+ }
+ }
+ /** A keyframe at most KEYFRAME_MIN_INTERVAL_MS after the last one, once the socket has drained. */
+ function scheduleKeyframe(c: Conn): void {
+ if (c.ended || stopped || c.sessionId === null || c.keyframeTimer !== null) return
+ const tick = (): void => {
+ c.keyframeTimer = null
+ if (c.ended || stopped || c.sessionId === null) return
+ const buffered = bufferedOf(c)
+ if (buffered > VIEWER_BACKLOG_CLOSE) {
+ dropStalled(c)
+ return
+ }
+ // Wait for the socket to drain before painting over it.
+ if (buffered > WATCHER_RESUME_BELOW) {
+ c.keyframeTimer = deps.setTimeout(tick, KEYFRAME_MIN_INTERVAL_MS)
+ return
+ }
+ requestKeyframe(c, false)
+ }
+ c.keyframeTimer = deps.setTimeout(tick, Math.max(0, KEYFRAME_MIN_INTERVAL_MS - (deps.now() - c.lastKeyframeAt)))
+ }
+ /** WatcherSinkDeps.onOverBudget: stop forwarding NOW, whatever is armed (F10), then repaint. */
+ function throttle(c: Conn): void {
+ c.streaming = false
+ scheduleKeyframe(c)
+ }
+ function onSettled(c: Conn, sid: string): void {
+ if (c.ended || c.sessionId !== sid) return
+ c.settled = true
+ clearTimer(c.settleTimer)
+ c.settleTimer = null
+ if (c.followUpOnSettle) {
+ c.followUpOnSettle = false
+ scheduleKeyframe(c)
+ }
+ }
+
+ // --- joining the node's session -------------------------------------------------------------------
+
+ function enterWaiting(c: Conn): void {
+ if (c.waiting) return
+ c.waiting = true
+ send(c, WATCH_EVENT.waiting, {})
+ }
+ function scheduleRejoin(c: Conn): void {
+ if (c.ended || stopped || c.rejoinTimer !== null) return
+ const delay = REJOIN_BACKOFF_MS[Math.min(c.rejoinAttempt, REJOIN_BACKOFF_MS.length - 1)]
+ c.rejoinAttempt++
+ c.rejoinTimer = deps.setTimeout(() => {
+ c.rejoinTimer = null
+ runJoin(c)
+ }, delay)
+ }
+ const runJoin = (c: Conn): void => {
+ join(c).catch((err) => warn(c, 'a join failed', errorText(err)))
+ }
+ async function join(c: Conn): Promise<void> {
+ if (c.ended || stopped || c.clientId === null || c.clientId < 0 || c.joining || c.sessionId !== null) return
+ c.joining = true
+ const clientId = c.clientId
+ let res: WatchJoin | null = null
+ try {
+ res = normalizeJoin(await deps.pty.join(clientId, record.nodeId, c.viewerId))
+ } catch (err) {
+ warn(c, 'joining the node session failed', errorText(err))
+ } finally {
+ c.joining = false
+ }
+ if (c.ended || stopped) {
+ if (res) leave(clientId, res.sessionId, c.viewerId, c)
+ return
+ }
+ // An exit that raced the join was delivered before this viewer knew its session id, and dropped.
+ if (res && !aliveOf(c, res.sessionId)) {
+ leave(clientId, res.sessionId, c.viewerId, c)
+ res = null
+ }
+ if (!res) {
+ enterWaiting(c)
+ scheduleRejoin(c)
+ return
+ }
+ const sid = res.sessionId
+ // EVERY join restarts the filter mid-stream (R12): this is a running session.
+ c.filter.reset({ midStream: true, onSettled: () => onSettled(c, sid) })
+ c.sessionId = sid
+ c.altScreen = res.altScreen
+ c.streaming = false
+ c.painted = false
+ c.settled = false
+ c.followUpOnSettle = false
+ c.waiting = false
+ // Meta after EVERY (re)attach: the viewer leaves `waiting` on it (R14).
+ const meta: WatchMeta = {
+ v: WATCH_PROTOCOL_VERSION,
+ role: record.role,
+ label: record.label,
+ title: record.title,
+ expiresAt: record.expiresAt,
+ cols: res.cols,
+ rows: res.rows
+ }
+ if (!send(c, WATCH_EVENT.meta, meta)) return
+ clearTimer(c.settleTimer)
+ c.settleTimer = deps.setTimeout(() => {
+ c.settleTimer = null
+ if (c.sessionId === sid && !c.settled) scheduleKeyframe(c)
+ }, SETTLE_BOUND_MS)
+ requestKeyframe(c, true)
+ updateSyncTimer()
+ }
+ /** The watched session is over: leave it, say so, look for the next one. */
+ function sessionOver(c: Conn): void {
+ const sid = c.sessionId
+ if (sid === null || c.ended) return
+ c.sessionId = null
+ c.streaming = false
+ c.followUpOnSettle = false
+ for (const h of [c.keyframeTimer, c.settleTimer, c.stableTimer]) clearTimer(h)
+ c.keyframeTimer = c.settleTimer = c.stableTimer = null
+ const clientId = c.clientId
+ // Deferred: a lifecycle event arrives from inside PtyManager's own delivery loop for that session.
+ queueMicrotask(() => leave(clientId, sid, c.viewerId, c))
+ enterWaiting(c)
+ scheduleRejoin(c)
+ updateSyncTimer()
+ }
+
+ // --- size sync ------------------------------------------------------------------------------------
+
+ function activeSessions(): Set<string> {
+ const out = new Set<string>()
+ for (const c of conns) if (!c.ended && c.sessionId !== null) out.add(c.sessionId)
+ return out
+ }
+ function syncSize(sessionId: string): void {
+ try {
+ void deps.pty.syncSize(sessionId).catch((err) => warn(null, 'the watcher size sync failed', errorText(err)))
+ } catch (err) {
+ warn(null, 'the watcher size sync failed', errorText(err))
+ }
+ }
+ function updateSyncTimer(): void {
+ if (stopped || activeSessions().size === 0) {
+ clearTimer(syncTimer)
+ syncTimer = null
+ return
+ }
+ if (syncTimer !== null) return
+ syncTimer = deps.setTimeout(() => {
+ syncTimer = null
+ if (stopped) return
+ for (const sid of activeSessions()) syncSize(sid)
+ updateSyncTimer()
+ }, WATCHER_SIZE_SYNC_MS)
+ }
+
+ // --- chat -----------------------------------------------------------------------------------------
+
+ function publish(msg: WatchChatMessage): void {
+ chat.push(msg)
+ if (chat.length > CHAT_HISTORY_MAX) chat.splice(0, chat.length - CHAT_HISTORY_MAX)
+ for (const c of [...conns]) if (c.joinedAt !== null && !c.ended) send(c, WATCH_EVENT.chat, msg, { chat: true })
+ safe('onChat', () => deps.onChat(msg))
+ safe('onChange', deps.onChange)
+ }
+ function onViewerCast(c: Conn, method: string, args: unknown[]): void {
+ // relay-host's access hook admits a Commenter's chat cast and nothing else.
+ if (method !== WATCH_CHAT_CAST || record.role !== 'commenter') {
+ policyBreach(c, `cast ${method}`)
+ return
+ }
+ if (c.ended || c.joinedAt === null) return
+ const now = deps.now()
+ if (now - c.lastChatAt < CHAT_MIN_INTERVAL_MS) return
+ const p = args[0]
+ if (!p || typeof p !== 'object') return
+ const name = sanitizeChatName((p as { name?: unknown }).name)
+ const text = sanitizeChatText((p as { text?: unknown }).text)
+ if (!name || !text) return
+ c.lastChatAt = now
+ c.name = name
+ publish({ id: bytesToHex(nacl.randomBytes(8)), name, text, at: now, from: 'viewer' })
+ }
+
+ // --- listeners and viewer sessions ----------------------------------------------------------------
+
+ const bridged = (c: Conn): void => {
+ if (c.bridged) return
+ c.bridged = true
+ safe('the scheduler', () => c.ev.onBridged())
+ }
+
+ function openListener(token: string, ev: { onBridged(): void; onClose(): void }): Listener {
+ const c: Conn = {
+ viewerId: `v-${bytesToHex(nacl.randomBytes(4))}`,
+ ev,
+ session: null,
+ clientId: null,
+ sink: null,
+ attachFailed: false,
+ bridged: false,
+ ended: false,
+ confirmTimer: null,
+ joinedAt: null,
+ name: null,
+ lastChatAt: -Infinity,
+ sessionId: null,
+ altScreen: false,
+ joining: false,
+ waiting: false,
+ streaming: false,
+ filter: createStreamFilter({ midStream: true }),
+ bucket: createTokenBucket({ ratePerSec: RATE, burst: BURST, now: deps.now }),
+ settled: false,
+ followUpOnSettle: false,
+ painted: false,
+ kfSeq: 0,
+ kfDelivered: 0,
+ lastKeyframeAt: -Infinity,
+ keyframeTimer: null,
+ settleTimer: null,
+ stableTimer: null,
+ rejoinAttempt: 0,
+ rejoinTimer: null,
+ warned: new Set()
+ }
+ conns.add(c)
+ const attach: PeerAttach = {
+ attach: (sink) => {
+ c.sink = sink
+ try {
+ c.clientId = deps.clients.attach(sink)
+ } catch (err) {
+ // Answered with an id nothing owns; onOpen then closes the session.
+ warn(c, 'registering a viewer failed', errorText(err))
+ c.attachFailed = true
+ c.clientId = -1
+ }
+ return c.clientId
+ },
+ detach: (id) => {
+ if (id < 0) return
+ try {
+ deps.clients.detach(id)
+ } catch (err) {
+ warn(c, 'unregistering a viewer failed', errorText(err))
+ }
+ },
+ // Never reached: the access hook refuses every request first. If one arrives, the policy failed.
+ dispatch: async (_id, req): Promise<RpcErr> => {
+ policyBreach(c, `request ${req.method}`)
+ return { t: 'res', id: req.id, ok: false, error: { code: 'E_ROLE', message: WATCHER_REFUSAL } }
+ },
+ cast: (_id, method, args) => {
+ try {
+ onViewerCast(c, method, args)
+ } catch (err) {
+ warn(c, 'a viewer cast failed', errorText(err))
+ }
+ }
+ }
+ try {
+ c.session = connectRelayHost({
+ url: deps.relayUrl,
+ token,
+ ourKeys: hostKeys,
+ attach,
+ transport: deps.transport?.(),
+ // Answered from our OWN record, never from anything the peer sent: the handshake key must be
+ // the one only a holder of the link secret can derive.
+ autoApprove: (peerKeyB64) => {
+ bridged(c) // a completed handshake proves the relay leg; the scheduler opens a replacement
+ if (peerKeyB64 !== expectedViewerKey) return false
+ clearTimer(c.confirmTimer)
+ c.confirmTimer = deps.setTimeout(() => {
+ c.confirmTimer = null
+ if (c.ended || c.joinedAt !== null) return
+ c.session?.close()
+ ended(c)
+ }, CONFIRM_DEADLINE_MS)
+ return true
+ },
+ hooks: {
+ access: (_s, kind, method) => watcherAccess(kind, method, record.role),
+ wrapSink: (_s, base) =>
+ wrapWatcherSink(base, {
+ sessionId: () => c.sessionId,
+ streaming: () => c.streaming,
+ filter: c.filter,
+ bucket: c.bucket,
+ onOverBudget: () => throttle(c),
+ onLifecycle: () => sessionOver(c)
+ })
+ },
+ // A peer with any other key: refused at once, never an approval dialog.
+ onPeerPending: (s) => {
+ c.session ??= s
+ s.deny('denied')
+ ended(c)
+ },
+ onOpen: (s) => {
+ c.session ??= s
+ clearTimer(c.confirmTimer)
+ c.confirmTimer = null
+ if (c.ended || stopped || c.attachFailed) {
+ s.close()
+ ended(c)
+ return
+ }
+ c.joinedAt = deps.now()
+ safe('onViewerJoined', () => deps.onViewerJoined(viewers().length))
+ safe('onChange', deps.onChange)
+ runJoin(c)
+ },
+ onClose: () => ended(c)
+ })
+ } catch (err) {
+ conns.delete(c)
+ throw err
+ }
+ return {
+ bridged: false,
+ close: () => {
+ c.session?.close()
+ ended(c)
+ }
+ }
+ }
+
+ function viewers(): LinkViewer[] {
+ const out: LinkViewer[] = []
+ for (const c of conns) if (c.joinedAt !== null && !c.ended) out.push({ viewerId: c.viewerId, name: c.name, joinedAt: c.joinedAt })
+ return out
+ }
+ function gone(reason: 'revoked' | 'expired'): void {
+ if (stopped) return
+ stop(reason)
+ safe('onGone', () => deps.onGone(reason))
+ }
+ function armFullPoll(s: SchedulerStatus): void {
+ const full = s.state === 'running' && s.idle === 0 && s.bridged >= MAX_VIEWERS_PER_LINK
+ if (!full || stopped) {
+ clearTimer(pollTimer)
+ pollTimer = null
+ return
+ }
+ if (pollTimer !== null) return
+ pollTimer = deps.setTimeout(() => {
+ pollTimer = null
+ void (async () => {
+ let st: 'live' | 'revoked' | 'expired' | 'unknown' = 'unknown'
+ try {
+ st = await deps.status()
+ } catch (err) {
+ warn(null, 'the link status poll failed', errorText(err))
+ }
+ if (stopped) return
+ if (st === 'revoked' || st === 'expired') gone(st)
+ else if (sched) armFullPoll(sched)
+ })()
+ }, FULL_STATUS_POLL_MS)
+ }
+
+ const scheduler = createHostedScheduler(
+ {
+ mint: async (): Promise<MintResult> => {
+ const r = await deps.mint()
+ if (!r.ok && r.kind === 'gone') {
+ const reason = r.reason
+ queueMicrotask(() => gone(reason))
+ return { ok: false, kind: 'refused', status: 410 }
+ }
+ return r
+ },
+ open: openListener,
+ setTimeout: deps.setTimeout,
+ clearTimeout: deps.clearTimeout,
+ onStatus: (s) => {
+ sched = s
+ armFullPoll(s)
+ safe('onChange', deps.onChange)
+ },
+ maxBridged: MAX_VIEWERS_PER_LINK
+ },
+ deps.now
+ )
+
+ function stop(reason: WatchLinkEndReason): void {
+ if (stopped) return
+ stopped = true
+ // Tell every viewer first: the scheduler's stop closes every listener, bridged ones included, and
+ // a closed session can no longer be told anything (F1).
+ for (const c of [...conns]) if (c.joinedAt !== null && !c.ended) send(c, WATCH_EVENT.end, { reason })
+ // `stopped` before the listeners close, so no ended() re-mints a listener.
+ scheduler.stop()
+ clearTimer(pollTimer)
+ pollTimer = null
+ clearTimer(syncTimer)
+ syncTimer = null
+ for (const c of [...conns]) {
+ c.session?.close()
+ ended(c)
+ }
+ safe('onChange', deps.onChange)
+ }
+
+ return {
+ start: () => {
+ if (!stopped) scheduler.start()
+ },
+ stop,
+ kick(viewerId) {
+ for (const c of conns) {
+ if (c.viewerId === viewerId && c.joinedAt !== null && !c.ended) {
+ endConn(c, 'kicked')
+ return true
+ }
+ }
+ return false
+ },
+ postSharerChat(text) {
+ const clean = sanitizeChatText(text)
+ if (!clean || record.role !== 'commenter' || stopped) return null
+ const msg: WatchChatMessage = { id: bytesToHex(nacl.randomBytes(8)), name: record.label, text: clean, at: deps.now(), from: 'sharer' }
+ publish(msg)
+ return msg
+ },
+ chatHistory: () => [...chat],
+ status() {
+ if (!sched) return 'reconnecting'
+ if (sched.state === 'backend-refused') return 'refused'
+ if (sched.idle > 0 || sched.bridged >= MAX_VIEWERS_PER_LINK) return 'live'
+ return sched.lastError ? 'reconnecting' : 'live'
+ },
+ viewers
+ }
+}