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 live-link registry and owner IPC, wired into both shells and every bridge

review6c8e3760c36d
diff --git a/src/core/relay/scoped-guest-policy.test.ts b/src/core/relay/scoped-guest-policy.test.ts
index d7f5ee2ba..1577e1312 100644
--- a/src/core/relay/scoped-guest-policy.test.ts
+++ b/src/core/relay/scoped-guest-policy.test.ts
@@ -251,6 +251,26 @@ describe('relay host — host-only channels refused to every peer', () => {
await vi.waitFor(() => expect(t.dispatched.map((r) => r.method)).toEqual([IPC.workspaceLoad]))
expect(t.casts).toEqual([])
})
+ // Live links: an editor (or an unscoped Team Access seat) passes every access check, so the host-only
+ // prefix is the one thing between a peer and publishing a host terminal with the host's Pro — and the
+ // list answer carries every link's secret. Refused BEFORE any policy runs, whatever the hooks say.
+ for (const [label, hooks] of [['no policy hooks (full access)', undefined], ['policy hooks', 'scoped']] as const) {
+ it(`refuses every watchLink channel, request and cast, with ${label}`, async () => {
+ const t = openHost(hooks === 'scoped' ? scopedGuestHooks('alpha', deps()) : undefined)
+ await vi.waitFor(() => expect(t.opened.length).toBe(2))
+ const methods = (Object.values(IPC) as unknown[]).filter(
+ (v): v is string => typeof v === 'string' && v.startsWith('watchLink:')
+ )
+ expect(methods).toHaveLength(10)
+ methods.forEach((method, i) =>
+ t.client.send(JSON.stringify({ t: 'req', id: 200 + i, method, args: [{ nodeId: 'a1', role: 'viewer', ttlSeconds: 3600, label: 'x' }] }))
+ )
+ for (const method of methods) t.client.send(JSON.stringify({ t: 'cast', method, args: [] }))
+ await vi.waitFor(() => expect(t.frames.filter((f) => f.includes('E_FORBIDDEN')).length).toBe(methods.length))
+ expect(t.dispatched).toEqual([])
+ expect(t.casts).toEqual([])
+ })
+ }
it('still lets a hosted team\'s own verbs through to their interceptor', async () => {
const t = openHost()
await vi.waitFor(() => expect(t.opened.length).toBe(2))
diff --git a/src/core/watch-link/pty-seam.test.ts b/src/core/watch-link/pty-seam.test.ts
new file mode 100644
index 000000000..4d601b495
--- /dev/null
+++ b/src/core/watch-link/pty-seam.test.ts
@@ -0,0 +1,77 @@
+import { describe, it, expect, vi } from 'vitest'
+import { createWatchPty, type WatchPtyManager } from './pty-seam'
+import type { PtyCreateResult } from '../../shared/types'
+
+function fakeManager(over: Partial<Record<keyof WatchPtyManager, unknown>> = {}) {
+ const m = {
+ joinAsWatcher: vi.fn(async (_c: number, _o: object): Promise<PtyCreateResult> => ({ sessionId: 's1', tmuxClient: true }) as PtyCreateResult),
+ sessionSize: vi.fn((_s: string): { cols: number; rows: number } | null => ({ cols: 120, rows: 40 })),
+ kill: vi.fn(),
+ captureVisible: vi.fn(async () => ({ screen: 'x', cursor: { x: 1, y: 2 } })),
+ syncWatcherClientSize: vi.fn(async () => true),
+ hasSession: vi.fn(() => true)
+ }
+ return Object.assign(m, over) as typeof m
+}
+
+describe('createWatchPty — the WatchPty seam both shells wire (R39)', () => {
+ it('joins with the host ids only (never a size), and reports the JOINED session size and tmux-ness', async () => {
+ const m = fakeManager()
+ const pty = createWatchPty(m as unknown as WatchPtyManager)
+ expect(await pty.join(7, 'n1', 'v-1')).toEqual({ sessionId: 's1', cols: 120, rows: 40, altScreen: true })
+ expect(m.joinAsWatcher).toHaveBeenCalledWith(7, { persistKey: 'n1', viewerId: 'v-1' })
+ expect(m.sessionSize).toHaveBeenCalledWith('s1')
+ expect(m.kill).not.toHaveBeenCalled()
+ })
+
+ it('altScreen is true only for a tmux client', async () => {
+ const m = fakeManager({ joinAsWatcher: vi.fn(async () => ({ sessionId: 's1' })) })
+ expect(await createWatchPty(m as unknown as WatchPtyManager).join(7, 'n1', 'v-1')).toMatchObject({ altScreen: false })
+ })
+
+ it('no session: null, nothing to leave', async () => {
+ const m = fakeManager({ joinAsWatcher: vi.fn(async () => ({ sessionId: '', unavailable: 'join-only' })) })
+ expect(await createWatchPty(m as unknown as WatchPtyManager).join(7, 'n1', 'v-1')).toBeNull()
+ expect(m.kill).not.toHaveBeenCalled()
+ })
+
+ it('a joined session whose size is unknown is REFUSED — never an 80x24 guess — and left, not leaked', async () => {
+ const m = fakeManager({ sessionSize: vi.fn(() => null) })
+ expect(await createWatchPty(m as unknown as WatchPtyManager).join(7, 'n1', 'v-1')).toBeNull()
+ expect(m.kill).toHaveBeenCalledWith(7, 's1', 'v-1')
+ })
+
+ it('an unavailable answer that still names a session is refused and left', async () => {
+ const m = fakeManager({ joinAsWatcher: vi.fn(async () => ({ sessionId: 's1', unavailable: 'ssh' })) })
+ expect(await createWatchPty(m as unknown as WatchPtyManager).join(7, 'n1', 'v-1')).toBeNull()
+ expect(m.kill).toHaveBeenCalledWith(7, 's1', 'v-1')
+ expect(m.sessionSize).not.toHaveBeenCalled()
+ })
+
+ it("a remote node's fields come from the shell's own records, requireRemote included", async () => {
+ const m = fakeManager()
+ const sshRemote = { conn: { host: 'h' } as never, controlPath: '/cp', remoteCwd: '~' }
+ const pty = createWatchPty(m as unknown as WatchPtyManager, (nodeId) =>
+ nodeId === 'r1' ? { requireRemote: true, sshRemote } : nodeId === 'r2' ? { requireRemote: true } : {}
+ )
+ await pty.join(7, 'r1', 'v-1')
+ await pty.join(7, 'r2', 'v-2')
+ expect(m.joinAsWatcher.mock.calls).toEqual([
+ [7, { persistKey: 'r1', viewerId: 'v-1', sshRemote, requireRemote: true }],
+ [7, { persistKey: 'r2', viewerId: 'v-2', requireRemote: true }]
+ ])
+ })
+
+ it('leave, capture, size sync and liveness go to the matching PtyManager member', async () => {
+ const m = fakeManager()
+ const pty = createWatchPty(m as unknown as WatchPtyManager)
+ pty.leave(7, 's1', 'v-1')
+ expect(m.kill).toHaveBeenCalledWith(7, 's1', 'v-1')
+ expect(await pty.captureVisible('s1')).toEqual({ screen: 'x', cursor: { x: 1, y: 2 } })
+ expect(await pty.syncSize('s1')).toBe(true)
+ expect(m.syncWatcherClientSize).toHaveBeenCalledWith('s1')
+ expect(pty.alive('s1')).toBe(true)
+ m.hasSession.mockReturnValue(false)
+ expect(pty.alive('s1')).toBe(false)
+ })
+})
diff --git a/src/core/watch-link/pty-seam.ts b/src/core/watch-link/pty-seam.ts
new file mode 100644
index 000000000..e6e5aa047
--- /dev/null
+++ b/src/core/watch-link/pty-seam.ts
@@ -0,0 +1,51 @@
+// The live link's pty seam (link-host.ts `WatchPty`) over PtyManager — ONE definition both shells
+// wire, because the join's rules are easy to get subtly wrong and a second copy is how one shell
+// ends up a rule behind the other:
+// - the join passes only ids the host chose: the node id, the viewer id the link host minted, and
+// remote fields from the shell's own records (`remoteFor`) — never a size (R39): a watcher's own
+// tmux client is spawned at the window size PtyManager reads itself, or not at all (R19/R20);
+// - the size the viewer is told is the JOINED session's current size (`sessionSize`, R25), and a
+// session whose size is unknown is REFUSED rather than given a guessed 80x24 (R37/R39);
+// - a refusal that had already attached leaves what it attached (the link host only knows a session
+// id this seam answered, so it could not leave it);
+// - `alive` is PtyManager's explicit `hasSession` (R38), `syncSize` its per-session serialized sync (R24).
+import type { PtyCreateOptions } from '../../shared/types'
+import type { PtyManager } from '../pty-manager'
+import type { WatchPty } from './link-host'
+
+export type WatchPtyManager = Pick<
+ PtyManager,
+ 'joinAsWatcher' | 'sessionSize' | 'kill' | 'captureVisible' | 'syncWatcherClientSize' | 'hasSession'
+>
+
+/** Where a node's session lives, from the SHELL's own records. `requireRemote` for every node of an
+ * SSH project (a downed master must never let the local tmux attach a same-named local orphan). */
+export interface WatchRemote {
+ sshRemote?: PtyCreateOptions['sshRemote']
+ requireRemote?: boolean
+}
+
+export function createWatchPty(pty: WatchPtyManager, remoteFor: (nodeId: string) => WatchRemote = () => ({})): WatchPty {
+ return {
+ async join(clientId, nodeId, viewerId) {
+ const remote = remoteFor(nodeId)
+ const res = await pty.joinAsWatcher(clientId, {
+ persistKey: nodeId,
+ viewerId,
+ ...(remote.sshRemote ? { sshRemote: remote.sshRemote } : {}),
+ ...(remote.requireRemote ? { requireRemote: true } : {})
+ })
+ if (!res.sessionId) return null
+ const size = res.unavailable ? null : pty.sessionSize(res.sessionId)
+ if (!size) {
+ pty.kill(clientId, res.sessionId, viewerId)
+ return null
+ }
+ return { sessionId: res.sessionId, cols: size.cols, rows: size.rows, altScreen: res.tmuxClient === true }
+ },
+ leave: (clientId, sessionId, viewerId) => pty.kill(clientId, sessionId, viewerId),
+ captureVisible: (sessionId) => pty.captureVisible(sessionId),
+ syncSize: (sessionId) => pty.syncWatcherClientSize(sessionId),
+ alive: (sessionId) => pty.hasSession(sessionId)
+ }
+}
diff --git a/src/core/watch-link/service.test.ts b/src/core/watch-link/service.test.ts
new file mode 100644
index 000000000..dab0e4ea6
--- /dev/null
+++ b/src/core/watch-link/service.test.ts
@@ -0,0 +1,742 @@
+import { describe, it, expect, vi, afterEach } from 'vitest'
+import { join } from 'node:path'
+import { readFileSync } from 'node:fs'
+import { testTmpDir } from '../test-tmp'
+import {
+ createWatchLinkService,
+ registerWatchLinkIpc,
+ sendToOwners,
+ workspaceNodeState,
+ type WatchLinkNodeState,
+ type WatchLinkService,
+ type WatchLinkServiceDeps
+} from './service'
+import { WatchLinkStore, WatchLinkStoreUnreadable, type WatchLinkRecord, type SaveOutcome } from './store'
+import type { WatchLinkApi as ApiClient } from './api'
+import type { LinkHost, LinkHostDeps, LinkRuntimeStatus, LinkViewer, WatchPty } from './link-host'
+import type { WatchChatMessage } from '../../shared/watch-link/protocol'
+import type { WatchLinkNotice, WatchLinkView } from '../../shared/watch-link-types'
+import { IPC } from '../../shared/ipc'
+import { fakePlatform } from '../platform-fake'
+
+const services: WatchLinkService[] = []
+afterEach(async () => {
+ for (const s of services.splice(0)) await s.shutdown()
+ vi.useRealTimers()
+})
+
+const HOUR = 3600_000
+
+function fakeApi(over: Partial<ApiClient> = {}) {
+ const calls: string[] = []
+ let n = 0
+ const api: ApiClient = {
+ create: async () => {
+ calls.push('create')
+ n++
+ return { ok: true, linkId: `Link${String(n).padStart(18, '0')}`, expiresAt: Date.now() + HOUR }
+ },
+ hostToken: async (id) => {
+ calls.push(`hostToken ${id}`)
+ return { ok: true, pairingToken: 't', hostId: '', ttlMs: 120_000 }
+ },
+ status: async () => 'live',
+ revoke: async (id) => {
+ calls.push(`revoke ${id}`)
+ return true
+ },
+ revokeAll: async () => {
+ calls.push('revokeAll')
+ return true
+ },
+ ...over
+ }
+ return { api, calls }
+}
+
+interface FakeHost {
+ record: WatchLinkRecord
+ deps: LinkHostDeps
+ stopped: string[]
+ starts: number
+ status: LinkRuntimeStatus
+ viewers: LinkViewer[]
+ chat: WatchChatMessage[]
+}
+function fakeHosts() {
+ const made: FakeHost[] = []
+ const createHost = (record: WatchLinkRecord, deps: LinkHostDeps): LinkHost => {
+ const h: FakeHost = { record, deps, stopped: [], starts: 0, status: 'live', viewers: [], chat: [] }
+ made.push(h)
+ return {
+ start: () => {
+ h.starts++
+ },
+ stop: (r) => {
+ h.stopped.push(r)
+ },
+ kick: (id) => h.viewers.some((v) => v.viewerId === id),
+ postSharerChat: (text) => ({ id: 'm1', name: record.label, text, at: 1, from: 'sharer' }),
+ chatHistory: () => h.chat,
+ status: () => h.status,
+ viewers: () => h.viewers
+ }
+ }
+ return { made, createHost }
+}
+
+const fakePty = (over: Partial<WatchPty> = {}): WatchPty => ({
+ join: async () => ({ sessionId: 's1', cols: 80, rows: 24, altScreen: true }),
+ leave: () => {},
+ captureVisible: async () => ({ screen: '', cursor: null }),
+ syncSize: async () => true,
+ alive: () => true,
+ ...over
+})
+
+type Store = WatchLinkServiceDeps['store']
+
+interface Opts {
+ api?: Partial<ApiClient>
+ nodes?: Map<string, WatchLinkNodeState>
+ entitlement?: string | null
+ relayAllowed?: boolean
+ store?: Store
+ pty?: WatchPty
+ workspaceReady?: () => Promise<unknown>
+ unsupported?: boolean
+ persistTimeoutMs?: number
+ now?: () => number
+}
+function service(o: Opts = {}) {
+ const file = join(testTmpDir('wls-'), 'watch-links.json')
+ const { api, calls } = fakeApi(o.api)
+ const hosts = fakeHosts()
+ const nodes = o.nodes ?? new Map<string, WatchLinkNodeState>([['n1', 'present'], ['n2', 'present']])
+ const emitted: [string, unknown[]][] = []
+ const store = o.store ?? new WatchLinkStore({ file })
+ const ent = { value: o.entitlement === undefined ? 'ent' : o.entitlement }
+ const s = createWatchLinkService({
+ api,
+ relayUrl: 'wss://r',
+ store,
+ entitlement: () => ent.value,
+ relayAllowed: () => o.relayAllowed ?? true,
+ nodeState: (id) => nodes.get(id) ?? 'absent',
+ ...(o.workspaceReady ? { workspaceReady: o.workspaceReady } : {}),
+ clients: { attach: () => 1, detach: () => {} },
+ pty: o.pty ?? fakePty(),
+ emit: (ch, ...a) => emitted.push([ch, a]),
+ createHost: hosts.createHost,
+ ...(o.unsupported ? { unsupported: true } : {}),
+ ...(o.persistTimeoutMs ? { persistTimeoutMs: o.persistTimeoutMs } : {}),
+ ...(o.now ? { now: o.now } : {})
+ })
+ services.push(s)
+ const notices = () => emitted.filter(([ch]) => ch === IPC.watchLinkNotice).map(([, a]) => a[0] as WatchLinkNotice)
+ const states = () => emitted.filter(([ch]) => ch === IPC.watchLinkState).map(([, a]) => a[0] as WatchLinkView[])
+ return { s, calls, api, hosts, nodes, emitted, notices, states, store, file, ent }
+}
+const req = (over: Record<string, unknown> = {}) => ({ nodeId: 'n1', role: 'viewer', ttlSeconds: 3600, label: 'Ada', title: 'build', ...over })
+const record = (over: Partial<WatchLinkRecord> = {}): WatchLinkRecord => ({
+ linkId: 'Good000000000000000000', nodeId: 'n1', role: 'viewer', label: 'A', title: 't', createdAt: 0,
+ expiresAt: Date.now() + 60_000, secret: new Uint8Array(32).fill(3), ...over
+})
+const deferred = <T>() => {
+ let resolve!: (v: T) => void
+ let reject!: (e: unknown) => void
+ const promise = new Promise<T>((res, rej) => {
+ resolve = res
+ reject = rej
+ })
+ return { promise, resolve, reject }
+}
+const flush = async (n = 20) => {
+ for (let i = 0; i < n; i++) await Promise.resolve()
+}
+/** A store that records every save and answers the outcomes a test chose. */
+function fakeStore(o: { load?: () => Promise<WatchLinkRecord[]>; save?: (r: readonly WatchLinkRecord[]) => Promise<SaveOutcome> } = {}) {
+ const saves: WatchLinkRecord[][] = []
+ let discarded = 0
+ const store: Store = {
+ load: o.load ?? (async () => []),
+ save: (r) => {
+ saves.push([...r])
+ return o.save ? o.save(r) : Promise.resolve('saved')
+ },
+ discardOpaque: () => {
+ discarded++
+ }
+ }
+ return { store, saves, discarded: () => discarded }
+}
+
+describe('createWatchLinkService — create', () => {
+ it('creates a link, persists it, starts a host and answers the URL', async () => {
+ const t = service()
+ const r = await t.s.create(req())
+ expect(r.ok).toBe(true)
+ if (!r.ok) return
+ expect(r.link.url).toMatch(/^https:\/\/nodeterm\.dev\/s\/Link0+1#1\.[A-Za-z0-9_-]{43}$/)
+ expect(r.link).toMatchObject({ nodeId: 'n1', role: 'viewer', label: 'Ada', title: 'build', status: 'live', viewers: [] })
+ expect(t.hosts.made).toHaveLength(1)
+ expect(t.hosts.made[0].starts).toBe(1)
+ expect(await t.store.load()).toHaveLength(1)
+ expect(t.states().at(-1)?.map((l) => l.linkId)).toEqual([r.link.linkId])
+ expect(t.notices()).toEqual([]) // persisted: no not-persistent notice
+ })
+
+ it('refuses bad input, a node no project holds, no relay, no entitlement and a sixth link — before any request', async () => {
+ const t = service({ nodes: new Map([['n1', 'present'], ['maybe', 'unknown'], ['gone', 'absent']]) })
+ const bad = { ok: false, error: 'bad-request' }
+ expect(await t.s.create(req({ ttlSeconds: 7200 }))).toEqual(bad)
+ expect(await t.s.create(req({ ttlSeconds: '3600' }))).toEqual(bad)
+ expect(await t.s.create(req({ role: 'editor' }))).toEqual(bad)
+ expect(await t.s.create(req({ nodeId: '../x' }))).toEqual(bad)
+ expect(await t.s.create(req({ nodeId: 12 }))).toEqual(bad)
+ expect(await t.s.create(req({ label: '' }))).toEqual(bad)
+ expect(await t.s.create(req({ label: '\u0007‮ ' }))).toEqual(bad)
+ expect(await t.s.create(req({ label: 5 }))).toEqual(bad)
+ expect(await t.s.create(null)).toEqual(bad)
+ expect(await t.s.create('x')).toEqual(bad)
+ // Create requires PRESENT: "unknown" is not "there" (R40).
+ expect(await t.s.create(req({ nodeId: 'gone' }))).toEqual({ ok: false, error: 'node-missing' })
+ expect(await t.s.create(req({ nodeId: 'maybe' }))).toEqual({ ok: false, error: 'node-missing' })
+ expect(await service({ relayAllowed: false }).s.create(req())).toEqual({ ok: false, error: 'relay-unavailable' })
+ expect(await service({ entitlement: null }).s.create(req())).toEqual({ ok: false, error: 'not-entitled' })
+ for (let i = 0; i < 5; i++) expect((await t.s.create(req())).ok).toBe(true)
+ expect(await t.s.create(req())).toEqual({ ok: false, error: 'limit-machine' })
+ expect(t.calls.filter((c) => c === 'create')).toHaveLength(5)
+ })
+
+ it('cleans the label and title: controls and bidi overrides stripped, capped in UTF-16 units without splitting a pair', async () => {
+ const t = service()
+ const r = await t.s.create(req({ label: ' A‮da\u0000‏ ', title: `x⁦${'😀'.repeat(50)}` }))
+ if (!r.ok) throw new Error(r.error)
+ expect(r.link.label).toBe('Ada')
+ expect(r.link.title).toBe(`x${'😀'.repeat(39)}`) // 1 + 78 units; one more pair would be 81 > 80
+ expect(r.link.title.length).toBeLessThanOrEqual(80)
+ const blank = await t.s.create(req({ title: '\u0001' }))
+ expect(blank.ok && blank.link.title).toBe('Terminal')
+ // What was written reloads (the store refuses a label over 40 / a title over 80 units).
+ expect(await t.store.load()).toHaveLength(2)
+ })
+
+ it('passes API refusals through without starting or persisting anything', async () => {
+ const t = service({ api: { create: async () => ({ ok: false, error: 'limit-daily' }) } })
+ expect(await t.s.create(req())).toEqual({ ok: false, error: 'limit-daily' })
+ expect(t.hosts.made).toHaveLength(0)
+ expect(t.s.list()).toEqual([])
+ })
+
+ it('a failed local write revokes the server row and leaves nothing behind (spec: no half-created link)', async () => {
+ const f = fakeStore({ save: async () => 'failed' })
+ const t = service({ store: f.store })
+ expect(await t.s.create(req())).toEqual({ ok: false, error: 'persist-failed' })
+ expect(t.calls).toContain('revoke Link000000000000000001')
+ expect(t.hosts.made).toHaveLength(0)
+ expect(t.s.list()).toEqual([])
+ })
+
+ it('a local write that HANGS is bounded: persist-failed, the row revoked, and the corrected list queued behind it', async () => {
+ const held = deferred<SaveOutcome>()
+ const f = fakeStore({ save: () => held.promise })
+ const t = service({ store: f.store, persistTimeoutMs: 20 })
+ expect(await t.s.create(req())).toEqual({ ok: false, error: 'persist-failed' })
+ expect(t.calls).toContain('revoke Link000000000000000001')
+ expect(t.hosts.made).toHaveLength(0)
+ // The write that hangs carries the link; the one queued after it does not, so when the disk
+ // recovers the file ends without it.
+ expect(f.saves.map((s) => s.length)).toEqual([1, 0])
+ held.resolve('saved')
+ })
+
+ it('two concurrent creates at four links: one is created, the other answers limit-machine (G17)', async () => {
+ const gate = deferred<void>()
+ let n = 0
+ const t = service({
+ api: {
+ create: async () => {
+ n++
+ const id = `Race${String(n).padStart(18, '0')}`
+ if (n === 5) await gate.promise // the fifth create is in flight while the sixth asks
+ return { ok: true, linkId: id, expiresAt: Date.now() + HOUR }
+ }
+ }
+ })
+ for (let i = 0; i < 4; i++) expect((await t.s.create(req())).ok).toBe(true)
+ const fifth = t.s.create(req())
+ await flush()
+ const sixth = await t.s.create(req())
+ expect(sixth).toEqual({ ok: false, error: 'limit-machine' })
+ gate.resolve()
+ expect((await fifth).ok).toBe(true)
+ expect(n).toBe(5)
+ expect(t.s.list()).toHaveLength(5)
+ })
+
+ it('a create whose write is pending counts ONCE against the cap', async () => {
+ const held = deferred<SaveOutcome>()
+ let saves = 0
+ const f = fakeStore({ save: () => (++saves === 4 ? held.promise : Promise.resolve('saved')) })
+ const t = service({ store: f.store })
+ for (let i = 0; i < 3; i++) expect((await t.s.create(req())).ok).toBe(true)
+ const fourth = t.s.create(req()) // its write is held: created server-side, not yet answered
+ await vi.waitFor(() => expect(saves).toBe(4))
+ expect((await t.s.create(req())).ok).toBe(true) // the fifth: 4 links + this one = 5
+ held.resolve('saved')
+ expect((await fourth).ok).toBe(true)
+ expect(await t.s.create(req())).toEqual({ ok: false, error: 'limit-machine' })
+ })
+
+ it('a link being written is no link yet: not listed, and no stop can end it half-way; a concurrent write keeps it on disk', async () => {
+ const held = deferred<SaveOutcome>()
+ let saves = 0
+ const f = fakeStore({ save: () => (++saves === 2 ? held.promise : Promise.resolve('saved')) })
+ const t = service({ store: f.store })
+ expect((await t.s.create(req({ nodeId: 'n2' }))).ok).toBe(true)
+ const creating = t.s.create(req())
+ await vi.waitFor(() => expect(saves).toBe(2))
+ expect(t.s.list().map((l) => l.nodeId)).toEqual(['n2'])
+ await t.s.revoke('Link000000000000000001') // the other link ends meanwhile…
+ expect(f.saves.at(-1)?.map((r) => r.linkId)).toEqual(['Link000000000000000002']) // …and its write keeps this one
+ held.resolve('saved')
+ const r = await creating
+ expect(r.ok).toBe(true)
+ expect(t.s.list().map((l) => l.linkId)).toEqual(['Link000000000000000002'])
+ expect(t.hosts.made.map((h) => h.record.linkId)).toEqual(['Link000000000000000001', 'Link000000000000000002'])
+ })
+
+ it('waits for init: a create during the boot load counts the resumed links and never hosts one twice (G11)', async () => {
+ const loading = deferred<WatchLinkRecord[]>()
+ const f = fakeStore({ load: () => loading.promise })
+ const t = service({ store: f.store })
+ void t.s.init()
+ const loaded = Array.from({ length: 5 }, (_, i) => record({ linkId: `Boot${String(i).padStart(18, '0')}` }))
+ const creating = t.s.create(req())
+ await flush()
+ expect(t.calls).not.toContain('create') // nothing asked before the load settled
+ loading.resolve(loaded)
+ expect(await creating).toEqual({ ok: false, error: 'limit-machine' })
+ expect(t.hosts.made.map((h) => h.record.linkId)).toEqual(loaded.map((r) => r.linkId))
+ await t.s.init() // idempotent: the same promise, no second start
+ expect(t.hosts.made).toHaveLength(5)
+ })
+
+ it('a create waiting on an init that never settles is bounded too', async () => {
+ const f = fakeStore({ load: () => new Promise(() => {}) })
+ const t = service({ store: f.store, persistTimeoutMs: 20 })
+ expect(await t.s.create(req())).toEqual({ ok: false, error: 'persist-failed' })
+ expect(t.calls).not.toContain('create')
+ })
+
+ it('the Server Edition (unsupported): create answers unsupported, list is empty, nothing is loaded or hosted (R43)', async () => {
+ const load = vi.fn(async () => [record()])
+ const f = fakeStore({ load })
+ const t = service({ store: f.store, unsupported: true })
+ await t.s.init()
+ expect(await t.s.create(req())).toEqual({ ok: false, error: 'unsupported' })
+ expect(t.s.list()).toEqual([])
+ await t.s.revokeAll()
+ t.s.onWorkspaceChanged()
+ await flush()
+ expect(load).not.toHaveBeenCalled()
+ expect(f.saves).toEqual([])
+ expect(t.hosts.made).toEqual([])
+ expect(t.calls).toEqual([])
+ })
+})
+
+describe('createWatchLinkService — ending a link', () => {
+ it('revoke stops the host, forgets the record and revokes server-side, with no notice (the owner did it)', async () => {
+ const t = service()
+ const r = await t.s.create(req())
+ if (!r.ok) throw new Error('create failed')
+ await t.s.revoke(r.link.linkId)
+ expect(t.hosts.made[0].stopped).toEqual(['revoked'])
+ expect(t.s.list()).toEqual([])
+ expect(await t.store.load()).toEqual([])
+ expect(t.calls).toContain(`revoke ${r.link.linkId}`)
+ expect(t.notices()).toEqual([])
+ expect(t.states().at(-1)).toEqual([])
+ })
+
+ it('revoke is complete locally and reaches the server even when the write HANGS (Task 9 note B)', async () => {
+ const f = fakeStore()
+ const t = service({ store: f.store })
+ const r = await t.s.create(req())
+ if (!r.ok) throw new Error('create failed')
+ const held = deferred<SaveOutcome>()
+ f.store.save = (recs) => {
+ f.saves.push([...recs])
+ return held.promise
+ }
+ await t.s.revoke(r.link.linkId) // resolves although the write never lands
+ expect(t.calls).toContain(`revoke ${r.link.linkId}`)
+ expect(t.hosts.made[0].stopped).toEqual(['revoked'])
+ expect(t.states().at(-1)).toEqual([])
+ expect(f.saves.at(-1)).toEqual([]) // the write was ISSUED before the sessions ended (spec order)
+ held.resolve('saved')
+ })
+
+ it('revokeAll ends every link without a notice, discards opaque entries and calls the server ONCE (G14)', async () => {
+ const f = fakeStore()
+ const t = service({ store: f.store })
+ await t.s.create(req())
+ await t.s.create(req({ nodeId: 'n2' }))
+ await t.s.revokeAll()
+ expect(t.s.list()).toEqual([])
+ expect(t.hosts.made.map((h) => h.stopped)).toEqual([['revoked'], ['revoked']])
+ expect(t.calls.filter((c) => c === 'revokeAll')).toHaveLength(1)
+ expect(t.calls.filter((c) => c.startsWith('revoke '))).toEqual([])
+ expect(t.notices()).toEqual([])
+ expect(f.discarded()).toBe(1)
+ expect(f.saves.at(-1)).toEqual([])
+ })
+
+ it('Stop all reaches the server even when the boot load hangs (a stop never waits on the disk)', async () => {
+ const f = fakeStore({ load: () => new Promise(() => {}) })
+ const t = service({ store: f.store, persistTimeoutMs: 20 })
+ await t.s.revokeAll()
+ await t.s.revoke('Link000000000000000001')
+ expect(t.calls).toEqual(['revokeAll'])
+ })
+
+ it('a node that is ABSENT ends every link of the node, revokes each, and tells the owner', async () => {
+ const t = service()
+ await t.s.create(req())
+ await t.s.create(req({ role: 'commenter' }))
+ await t.s.create(req({ nodeId: 'n2' }))
+ t.nodes.set('n1', 'absent')
+ t.s.onWorkspaceChanged()
+ await vi.waitFor(() => expect(t.s.list().map((l) => l.nodeId)).toEqual(['n2']))
+ expect(t.hosts.made.filter((h) => h.stopped.includes('node-gone'))).toHaveLength(2)
+ expect(t.calls.filter((c) => c.startsWith('revoke '))).toHaveLength(2)
+ expect(t.notices().filter((n) => n.kind === 'ended' && n.reason === 'node-gone')).toHaveLength(2)
+ })
+
+ it('a node whose state is UNKNOWN is never ended or revoked (an unread project is not evidence)', async () => {
+ const t = service()
+ await t.s.create(req())
+ t.nodes.set('n1', 'unknown')
+ t.s.onWorkspaceChanged()
+ await flush()
+ expect(t.s.list()).toHaveLength(1)
+ expect(t.hosts.made[0].stopped).toEqual([])
+ expect(t.calls.filter((c) => c.startsWith('revoke '))).toEqual([])
+ })
+
+ it('a node-state check that throws reads as unknown', async () => {
+ const t = service()
+ await t.s.create(req())
+ t.nodes.get = () => {
+ throw new Error('boom')
+ }
+ t.s.onWorkspaceChanged()
+ await flush()
+ expect(t.s.list()).toHaveLength(1)
+ })
+
+ it('a server-side end (onGone) ends the link locally, tells the owner, and does not revoke again', async () => {
+ const t = service()
+ const r = await t.s.create(req())
+ if (!r.ok) throw new Error('create failed')
+ t.hosts.made[0].deps.onGone('revoked')
+ expect(t.s.list()).toEqual([])
+ expect(t.notices()).toEqual([{ kind: 'ended', linkId: r.link.linkId, nodeId: 'n1', title: 'build', reason: 'revoked' }])
+ expect(t.calls.filter((c) => c.startsWith('revoke '))).toEqual([])
+ })
+
+ it('expiry ends the link with an expired notice and no server revoke', async () => {
+ vi.useFakeTimers()
+ const t = service({ api: { create: async () => ({ ok: true, linkId: 'Exp0000000000000000000', expiresAt: Date.now() + 1000 }) } })
+ expect((await t.s.create(req())).ok).toBe(true)
+ await vi.advanceTimersByTimeAsync(999)
+ expect(t.s.list()).toHaveLength(1)
+ await vi.advanceTimersByTimeAsync(1)
+ expect(t.s.list()).toEqual([])
+ expect(t.hosts.made[0].stopped).toEqual(['expired'])
+ expect(t.notices()).toEqual([{ kind: 'ended', linkId: 'Exp0000000000000000000', nodeId: 'n1', title: 'build', reason: 'expired' }])
+ expect(t.calls.filter((c) => c.startsWith('revoke '))).toEqual([])
+ })
+
+ it('a host change after the link expired ends it even if its timer slept past (G24: monotonic timers across a lid-close)', async () => {
+ let clock = 1_000_000
+ const t = service({
+ now: () => clock,
+ api: { create: async () => ({ ok: true, linkId: 'Lid0000000000000000000', expiresAt: clock + HOUR }) }
+ })
+ expect((await t.s.create(req())).ok).toBe(true)
+ clock += HOUR // the wall clock moved on; the expiry timer (monotonic) has not fired
+ t.hosts.made[0].deps.onChange()
+ await vi.waitFor(() => expect(t.s.list()).toEqual([]))
+ expect(t.notices().at(-1)).toMatchObject({ kind: 'ended', reason: 'expired' })
+ })
+
+ it('shutdown stops hosts as host-stopping, keeps the records, and nothing ends a link after it', async () => {
+ const t = service()
+ await t.s.create(req())
+ await t.s.shutdown()
+ expect(t.hosts.made[0].stopped).toEqual(['host-stopping'])
+ expect(await t.store.load()).toHaveLength(1)
+ t.nodes.set('n1', 'absent')
+ t.s.onWorkspaceChanged()
+ await flush()
+ expect(t.calls.filter((c) => c.startsWith('revoke '))).toEqual([])
+ expect(await t.s.create(req())).toEqual({ ok: false, error: 'unsupported' })
+ })
+})
+
+describe('createWatchLinkService — init (resume at launch)', () => {
+ it('resumes live and UNKNOWN records, drops expired ones, and revokes only an ABSENT one', async () => {
+ const t = service({ nodes: new Map([['n1', 'present'], ['maybe', 'unknown']]) })
+ const good = record()
+ await t.store.save([
+ good,
+ record({ linkId: 'Maybe00000000000000000', nodeId: 'maybe' }),
+ record({ linkId: 'Old0000000000000000000', expiresAt: Date.now() - 1 }),
+ record({ linkId: 'Orph000000000000000000', nodeId: 'gone' })
+ ])
+ await t.s.init()
+ expect(t.s.list().map((l) => l.linkId)).toEqual(['Good000000000000000000', 'Maybe00000000000000000'])
+ expect(t.hosts.made.map((h) => h.record.linkId)).toEqual(['Good000000000000000000', 'Maybe00000000000000000'])
+ expect(t.calls.filter((c) => c.startsWith('revoke '))).toEqual(['revoke Orph000000000000000000'])
+ expect((await t.store.load()).map((r) => r.linkId)).toEqual(['Good000000000000000000', 'Maybe00000000000000000'])
+ })
+
+ it('the launch-time empty workspace revokes NOTHING: every node reads unknown until the index is read', async () => {
+ // What `workspaceNodeState` answers before the workspace store has loaded its index.
+ const t = service({ nodes: new Map([['n1', 'unknown'], ['n2', 'unknown']]) })
+ await t.store.save([record(), record({ linkId: 'Two0000000000000000000', nodeId: 'n2' })])
+ await t.s.init()
+ expect(t.s.list()).toHaveLength(2)
+ expect(t.calls.filter((c) => c.startsWith('revoke '))).toEqual([])
+ })
+
+ it('decides nothing before the workspace load it is handed has settled (R40)', async () => {
+ const ready = deferred<void>()
+ const nodes = new Map<string, WatchLinkNodeState>([['n1', 'unknown']])
+ const f = fakeStore({ load: async () => [record()] })
+ const t = service({ store: f.store, nodes, workspaceReady: () => ready.promise })
+ const init = t.s.init()
+ await flush()
+ expect(t.hosts.made).toEqual([])
+ nodes.set('n1', 'absent') // the load completed and the node is really gone
+ ready.resolve()
+ await init
+ expect(t.s.list()).toEqual([])
+ expect(t.calls).toEqual(['revoke Good000000000000000000'])
+ })
+
+ it('a workspace load that fails still lets init run (every answer is then unknown)', async () => {
+ const f = fakeStore({ load: async () => [record()] })
+ const t = service({ store: f.store, nodes: new Map([['n1', 'unknown']]), workspaceReady: () => Promise.reject(new Error('x')) })
+ await t.s.init()
+ expect(t.s.list()).toHaveLength(1)
+ })
+
+ it('writes the file only when it pruned something (R42a)', async () => {
+ const f = fakeStore({ load: async () => [record()] })
+ const t = service({ store: f.store })
+ await t.s.init()
+ expect(f.saves).toEqual([])
+ const g = fakeStore({ load: async () => [record(), record({ linkId: 'Old0000000000000000000', expiresAt: 1 })] })
+ const u = service({ store: g.store })
+ await u.s.init()
+ expect(g.saves.map((s) => s.map((r) => r.linkId))).toEqual([['Good000000000000000000']])
+ })
+
+ it('an unreadable links file: init resolves, runs memory-only, never writes, and says so on every create (R22/R42c)', async () => {
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})
+ const f = fakeStore({ load: async () => Promise.reject(new WatchLinkStoreUnreadable('unknown-version', 'watch-links.json has version 2, expected 1')) })
+ const t = service({ store: f.store })
+ await expect(t.s.init()).resolves.toBeUndefined()
+ expect(warn).toHaveBeenCalledTimes(1)
+ expect(String(warn.mock.calls[0][0])).toMatch(/unknown-version/)
+ expect((await t.s.create(req())).ok).toBe(true)
+ expect((await t.s.create(req())).ok).toBe(true)
+ await t.s.revoke('Link000000000000000001')
+ expect(f.saves).toEqual([])
+ expect(t.notices().filter((n) => n.kind === 'not-persistent')).toHaveLength(3) // boot + each create
+ warn.mockRestore()
+ })
+
+ it('a keychain that refuses to seal: created links work, and every create says they are not persisted (R42c)', async () => {
+ const f = fakeStore({ save: async () => 'memory-only' })
+ const t = service({ store: f.store })
+ expect((await t.s.create(req())).ok).toBe(true)
+ expect((await t.s.create(req())).ok).toBe(true)
+ expect(t.notices().filter((n) => n.kind === 'not-persistent')).toHaveLength(2)
+ expect(t.hosts.made).toHaveLength(2)
+ })
+
+ it('in a build that may not relay, resumed links are kept and listed refused, and nothing is hosted (G21)', async () => {
+ const f = fakeStore({ load: async () => [record()] })
+ const t = service({ store: f.store, relayAllowed: false })
+ await t.s.init()
+ expect(t.hosts.made).toEqual([])
+ expect(t.s.list().map((l) => l.status)).toEqual(['refused'])
+ })
+
+ it('keeps at most five resumed links; the rest are pruned and revoked', async () => {
+ const recs = Array.from({ length: 7 }, (_, i) => record({ linkId: `Many${String(i).padStart(18, '0')}` }))
+ const f = fakeStore({ load: async () => recs })
+ const t = service({ store: f.store })
+ await t.s.init()
+ expect(t.s.list()).toHaveLength(5)
+ expect(t.calls.filter((c) => c.startsWith('revoke '))).toHaveLength(2)
+ })
+})
+
+describe('createWatchLinkService — the host seams', () => {
+ it('never mints with an empty entitlement: a local refusal, no request (R41b)', async () => {
+ const t = service()
+ await t.s.create(req())
+ t.ent.value = null
+ expect(await t.hosts.made[0].deps.mint()).toEqual({ ok: false, kind: 'refused', status: 402 })
+ expect(t.calls.filter((c) => c.startsWith('hostToken'))).toEqual([])
+ expect(await t.hosts.made[0].deps.status()).toBe('unknown')
+ t.ent.value = 'ent2'
+ expect((await t.hosts.made[0].deps.mint()).ok).toBe(true)
+ })
+
+ it('an entitlement change re-arms ONLY the refused hosts (R41a)', async () => {
+ const t = service()
+ await t.s.create(req())
+ await t.s.create(req({ nodeId: 'n2' }))
+ t.hosts.made[0].status = 'refused'
+ t.s.onEntitlementChanged()
+ expect(t.hosts.made.map((h) => h.starts)).toEqual([2, 1])
+ })
+
+ it('checks the node before every join: absent ends the link (node-gone + revoke), unknown joins (R29/G8)', async () => {
+ const join = vi.fn(async () => ({ sessionId: 's1', cols: 80, rows: 24, altScreen: true }))
+ const t = service({ pty: fakePty({ join }) })
+ const r = await t.s.create(req())
+ if (!r.ok) throw new Error('create failed')
+ const pty = t.hosts.made[0].deps.pty
+ t.nodes.set('n1', 'unknown')
+ expect(await pty.join(1, 'n1', 'v-1')).toMatchObject({ sessionId: 's1' })
+ t.nodes.set('n1', 'absent')
+ expect(await pty.join(1, 'n1', 'v-2')).toBeNull()
+ expect(join).toHaveBeenCalledTimes(1)
+ expect(t.s.list()).toEqual([])
+ expect(t.hosts.made[0].stopped).toEqual(['node-gone'])
+ expect(t.calls).toContain(`revoke ${r.link.linkId}`)
+ // The other members pass straight through.
+ expect(pty.alive('s1')).toBe(true)
+ expect(await pty.syncSize('s1')).toBe(true)
+ expect(await pty.captureVisible('s1')).toEqual({ screen: '', cursor: null })
+ })
+
+ it('tells the owner when someone starts watching', async () => {
+ const t = service()
+ const r = await t.s.create(req())
+ if (!r.ok) throw new Error('create failed')
+ t.hosts.made[0].deps.onViewerJoined(2)
+ expect(t.notices()).toEqual([{ kind: 'joined', linkId: r.link.linkId, nodeId: 'n1', title: 'build', viewers: 2 }])
+ })
+
+ it('strips bidi controls from everything a viewer wrote before the owner sees it', async () => {
+ const t = service()
+ const r = await t.s.create(req({ role: 'commenter' }))
+ if (!r.ok) throw new Error('create failed')
+ const h = t.hosts.made[0]
+ h.deps.onChat({ id: 'x', name: 'E‮ve', text: 'hi⁦ there', at: 1, from: 'viewer' })
+ const chat = t.emitted.find(([ch]) => ch === IPC.watchLinkChat)
+ expect(chat?.[1]).toEqual([r.link.linkId, { id: 'x', name: 'Eve', text: 'hi there', at: 1, from: 'viewer' }])
+ h.chat = [{ id: 'y', name: '‏Mal', text: 'a‪b', at: 2, from: 'viewer' }]
+ expect(t.s.chatHistory(r.link.linkId)).toEqual([{ id: 'y', name: 'Mal', text: 'ab', at: 2, from: 'viewer' }])
+ h.viewers = [{ viewerId: 'v-1', name: 'E‮ve', joinedAt: 5 }]
+ expect(t.s.list()[0].viewers).toEqual([{ viewerId: 'v-1', name: 'Eve', joinedAt: 5 }])
+ })
+
+ it('kick, owner chat and history go to the link host; an unknown link answers nothing', async () => {
+ const t = service()
+ const r = await t.s.create(req({ role: 'commenter' }))
+ if (!r.ok) throw new Error('create failed')
+ t.hosts.made[0].viewers = [{ viewerId: 'v-1', name: null, joinedAt: 1 }]
+ expect(t.s.kick(r.link.linkId, 'v-1')).toBe(true)
+ expect(t.s.kick(r.link.linkId, 'v-9')).toBe(false)
+ expect(t.s.sendChat(r.link.linkId, 'hello')).toMatchObject({ text: 'hello', from: 'sharer' })
+ expect(t.s.kick('Nope000000000000000000', 'v-1')).toBe(false)
+ expect(t.s.sendChat('Nope000000000000000000', 'x')).toBeNull()
+ expect(t.s.chatHistory('Nope000000000000000000')).toEqual([])
+ })
+})
+
+describe('registerWatchLinkIpc / sendToOwners', () => {
+ it('the IPC answers owners only', async () => {
+ const t = service()
+ const p = fakePlatform({ isOwnerClient: (id) => id === 1 })
+ registerWatchLinkIpc(p, t.s)
+ expect(await p.handlers[IPC.watchLinkCreate](2, req())).toEqual({ ok: false, error: 'unsupported' })
+ expect(await p.handlers[IPC.watchLinkList](2)).toEqual([])
+ expect(await p.handlers[IPC.watchLinkKick](2, 'x', 'y')).toBe(false)
+ expect(await p.handlers[IPC.watchLinkChatSend](2, 'x', 'y')).toBeNull()
+ expect(await p.handlers[IPC.watchLinkChatHistory](2, 'x')).toEqual([])
+ const made = (await p.handlers[IPC.watchLinkCreate](1, req())) as { ok: boolean; link: WatchLinkView }
+ expect(made.ok).toBe(true)
+ expect(await p.handlers[IPC.watchLinkRevoke](2, made.link.linkId)).toBeUndefined()
+ await p.handlers[IPC.watchLinkRevokeAll](2)
+ expect((await p.handlers[IPC.watchLinkList](1)) as WatchLinkView[]).toHaveLength(1) // a non-owner stopped nothing
+ await p.handlers[IPC.watchLinkRevoke](1, made.link.linkId)
+ expect(await p.handlers[IPC.watchLinkList](1)).toEqual([])
+ })
+
+ it('a platform with no owner notion answers nobody', async () => {
+ const t = service()
+ const p = fakePlatform()
+ delete (p as { isOwnerClient?: unknown }).isOwnerClient
+ registerWatchLinkIpc(p, t.s)
+ expect(await p.handlers[IPC.watchLinkCreate](1, req())).toEqual({ ok: false, error: 'unsupported' })
+ })
+
+ it('registers exactly the seven request channels', () => {
+ const p = fakePlatform({ isOwnerClient: () => true })
+ registerWatchLinkIpc(p, service().s)
+ expect(Object.keys(p.handlers).sort()).toEqual(
+ [IPC.watchLinkCreate, IPC.watchLinkList, IPC.watchLinkRevoke, IPC.watchLinkRevokeAll, IPC.watchLinkKick, IPC.watchLinkChatSend, IPC.watchLinkChatHistory].sort()
+ )
+ })
+
+ it('sendToOwners reaches owner clients only (the link URL carries its secret)', () => {
+ const p = fakePlatform({ isOwnerClient: (id) => id === 3 })
+ p.clients.push(2, 3, 4)
+ sendToOwners(p, IPC.watchLinkState, [])
+ expect(p.sent).toEqual([{ to: 3, channel: IPC.watchLinkState, args: [[]] }])
+ })
+})
+
+describe('workspaceNodeState', () => {
+ const store = (held: Record<string, string[]>, known: Set<string> | undefined) => ({
+ projectIdsForNode: (id: string) => held[id] ?? [],
+ knownNodeIds: () => known
+ })
+ it('present when a project holds it', () => {
+ expect(workspaceNodeState(store({ n1: ['p1'] }, undefined), 'n1')).toBe('present')
+ })
+ it('absent only on a complete read that lacks it', () => {
+ expect(workspaceNodeState(store({}, new Set(['n2'])), 'n1')).toBe('absent')
+ expect(workspaceNodeState(store({}, new Set()), 'n1')).toBe('absent')
+ })
+ it('unknown when the read is incomplete (index not loaded, an unread project)', () => {
+ expect(workspaceNodeState(store({}, undefined), 'n1')).toBe('unknown')
+ })
+ it('present when the complete read has it even if the project scan does not', () => {
+ expect(workspaceNodeState(store({}, new Set(['n1'])), 'n1')).toBe('present')
+ })
+})
+
+// A store round trip with the real file: the brief's end-to-end persistence claim.
+describe('createWatchLinkService — real store', () => {
+ it('a created link is on disk, and a revoked one is gone from it', async () => {
+ const t = service()
+ const r = await t.s.create(req())
+ if (!r.ok) throw new Error('create failed')
+ expect(JSON.parse(readFileSync(t.file, 'utf8')).links).toHaveLength(1)
+ await t.s.revoke(r.link.linkId)
+ await t.store.load() // queued behind the revoke's write
+ expect(JSON.parse(readFileSync(t.file, 'utf8')).links).toEqual([])
+ })
+})
diff --git a/src/core/watch-link/service.ts b/src/core/watch-link/service.ts
new file mode 100644
index 000000000..10ffc26f0
--- /dev/null
+++ b/src/core/watch-link/service.ts
@@ -0,0 +1,655 @@
+// The live-link registry (docs/live-links.md): the owner's side of every link this machine hosts —
+// at most MAX_LINKS_PER_MACHINE, each with its link host (link-host.ts). Records are persisted
+// (spec D8) and resumed at launch. Owner state goes to OWNER clients only (`sendToOwners`): every
+// view carries the link's URL, and the URL carries the secret.
+//
+// A LINK ENDS on: the owner's Stop (`revoke`, no notice — the owner did it), Stop all (`revokeAll`,
+// one server call), its expiry (a timer, plus a re-check on every host change because timers are
+// monotonic and a closed lid pauses them — G24), the node leaving every project, or the server saying
+// it is gone (a mint or status answering 410 — `onGone`, which does raise a notice).
+//
+// NODE GONE IS TRI-STATE (controller ruling R40). `nodeState` answers present / absent / unknown, and
+// only ABSENT ends a link and revokes it server-side: an empty answer during the launch-time workspace
+// load, or for a node in a project whose file was not read this run, is not evidence the node is gone,
+// and a revoke cannot be undone. `init()` first waits for the workspace load it is handed, then keeps
+// (and hosts) a link whose node is unknown — its join is join-only, so a node that never comes back
+// costs a waiting viewer, never a spawned session. Create requires PRESENT. The same check runs before
+// every join (R29): the link host is registry-free, so the registry wraps its `pty.join`.
+//
+// PERSISTENCE never blocks the owner (Task 9 note B, spec revoke order). Ending a link removes the
+// record and ISSUES the write (the store snapshots at call time) before the sessions end, and never
+// waits for it before the server revoke: a disk that hangs must not keep a revoked link's viewers
+// connected or its server row alive. A create does wait for its write (a link that cannot be
+// written must not exist: the server row is revoked), but no longer than PERSIST_TIMEOUT_MS.
+// A links file that could not be read (WatchLinkStoreUnreadable) turns this run MEMORY-ONLY: the
+// store is latched and never written, links still work and end at quit, and the owner is told on
+// every create (R22, R42c) — as when the keychain refuses to seal (the store answers memory-only).
+// `init()` writes only when it actually pruned something (R42a), so a boot never rewrites the file.
+//
+// ENTITLEMENT. A host never mints with an empty entitlement (the API would answer 400, which stops
+// minting for good): it answers itself a local refusal, and `onEntitlementChanged` re-arms every host
+// the API refused once the license layer reports a change — a 7-day token expiring under a running
+// link is the ordinary case (R41).
+//
+// THE SERVER EDITION registers this same service with `unsupported: true` until it has a license layer
+// (R43): create answers `unsupported`, list answers [], nothing is loaded, hosted or revoked. The same
+// mode is what a Server Edition that does not own its data dir would need (G15).
+//
+// Nothing here throws out of a callback or a void promise; every timer is cleared by `end`/`shutdown`.
+import type { CorePlatform } from '../platform'
+import type { WorkspaceStore } from '../workspace-store'
+import { IPC } from '../../shared/ipc'
+import { isSafeNodeId } from '../../shared/safe-id'
+import { formatWatchLink } from '../../shared/watch-link/link'
+import { deriveWatchLinkKeys, newWatchLinkSecret, sha256Hex } from '../../shared/watch-link/keys'
+import type { WatchChatMessage, WatchLinkEndReason } from '../../shared/watch-link/protocol'
+import {
+ LABEL_MAX,
+ MAX_LINKS_PER_MACHINE,
+ TITLE_MAX,
+ WATCH_LINK_TTLS,
+ stripBidiControls,
+ type CreateWatchLinkError,
+ type CreateWatchLinkRequest,
+ type CreateWatchLinkResult,
+ type WatchLinkNotice,
+ type WatchLinkView,
+ type WatchLinkViewerView
+} from '../../shared/watch-link-types'
+import type { HostTokenResult, WatchLinkApi as WatchLinkApiClient } from './api'
+import { createLinkHost, type LinkHost, type QuietClients, type WatchPty } from './link-host'
+import { WatchLinkStoreUnreadable, type WatchLinkRecord, type WatchLinkStore } from './store'
+import type { RelayTransport } from '../relay/relay-socket'
+
+/** setTimeout's own ceiling (a longer delay fires at once). A link lives ≤ 24 h, far below it. */
+const MAX_DELAY_MS = 2_147_483_647
+/** The longest a create waits for its local write (or for the boot load it must count). */
+export const PERSIST_TIMEOUT_MS = 10_000
+
+export type WatchLinkNodeState = 'present' | 'absent' | 'unknown'
+
+export interface WatchLinkServiceDeps {
+ api: WatchLinkApiClient
+ relayUrl: string
+ store: Pick<WatchLinkStore, 'load' | 'save' | 'discardOpaque'>
+ /** The stored Pro entitlement token, or null. Travels only in the API client's JSON body. */
+ entitlement(): string | null
+ /** False in a build that may not relay (an unpackaged dev build): no create, and resumed links
+ * are kept but not hosted (G21) — a dev run must not host the installed app's links. */
+ relayAllowed(): boolean
+ /** Is the node in some project (present), provably in none (absent), or cannot be told (unknown)?
+ * The shells answer with `workspaceNodeState`. */
+ nodeState(nodeId: string): WatchLinkNodeState
+ /** Resolves once the workspace index has been read: `init()` decides nothing before it (R40). */
+ workspaceReady?(): Promise<unknown>
+ clients: QuietClients
+ pty: WatchPty
+ /** Owner clients only (`sendToOwners`). */
+ emit(channel: string, ...args: unknown[]): void
+ /** This shell cannot host links (the Server Edition until it has a license layer — R43). */
+ unsupported?: boolean
+ now?(): number
+ setTimeout?(fn: () => void, ms: number): unknown
+ clearTimeout?(h: unknown): void
+ /** TEST ONLY. */
+ persistTimeoutMs?: number
+ /** TEST ONLY. */
+ createHost?: typeof createLinkHost
+ /** TEST ONLY: the relay transport the link hosts dial. */
+ transport?: () => RelayTransport
+}
+
+export interface WatchLinkService {
+ /** Load and resume the persisted links. Idempotent (one promise); never rejects. */
+ init(): Promise<void>
+ create(req: unknown): Promise<CreateWatchLinkResult>
+ list(): WatchLinkView[]
+ revoke(linkId: string): Promise<void>
+ revokeAll(): Promise<void>
+ kick(linkId: string, viewerId: string): boolean
+ sendChat(linkId: string, text: string): WatchChatMessage | null
+ chatHistory(linkId: string): WatchChatMessage[]
+ /** After every workspace load/save: a node that is now ABSENT ends its links. */
+ onWorkspaceChanged(): void
+ /** After the license layer reports a change: re-arm every host the API refused. */
+ onEntitlementChanged(): void
+ /** Stop every host (`host-stopping`), keep the records for the next launch. Resolves once the
+ * last write this service issued has settled (the caller bounds it). */
+ shutdown(): Promise<void>
+}
+
+/**
+ * The node-gone rule over the workspace store, shared by both shells: present when some project
+ * holds the node; absent only when the store has a COMPLETE read of every project (`knownNodeIds`)
+ * and the node is not in it; unknown otherwise (the index not loaded yet, a project file not read
+ * this run, an SSH project with no cache).
+ */
+export function workspaceNodeState(
+ store: Pick<WorkspaceStore, 'projectIdsForNode' | 'knownNodeIds'>,
+ nodeId: string
+): WatchLinkNodeState {
+ if (store.projectIdsForNode(nodeId).length > 0) return 'present'
+ const known = store.knownNodeIds()
+ if (!known) return 'unknown'
+ return known.has(nodeId) ? 'present' : 'absent'
+}
+
+// C0/C1 controls and DEL; the bidi controls are `stripBidiControls`'s.
+const CONTROLS = /[\u0000-\u001f\u007f-\u009f]/g
+
+/** A label or title as the owner typed it (or as a git-shared node title says): controls and bidi
+ * overrides gone, trimmed, capped at `max` UTF-16 units — the unit the store checks on load —
+ * without splitting a surrogate pair. null when nothing is left. */
+function cleanText(raw: unknown, max: number): string | null {
+ if (typeof raw !== 'string') return null
+ const s = stripBidiControls(raw.replace(CONTROLS, '')).trim()
+ let out = ''
+ for (const ch of s) {
+ if (out.length + ch.length > max) break
+ out += ch
+ }
+ out = out.trim()
+ return out || null
+}
+
+function parseRequest(raw: unknown): CreateWatchLinkRequest | null {
+ if (!raw || typeof raw !== 'object') return null
+ const r = raw as Record<string, unknown>
+ // `isSafeNodeId` coerces: `12` passes its regex. The type check comes first.
+ if (typeof r.nodeId !== 'string' || !isSafeNodeId(r.nodeId)) return null
+ if (r.role !== 'viewer' && r.role !== 'commenter') return null
+ if (!(WATCH_LINK_TTLS as readonly unknown[]).includes(r.ttlSeconds)) return null
+ const label = cleanText(r.label, LABEL_MAX)
+ if (!label) return null
+ const title = cleanText(r.title, TITLE_MAX) ?? 'Terminal'
+ return { nodeId: r.nodeId, role: r.role, ttlSeconds: r.ttlSeconds as CreateWatchLinkRequest['ttlSeconds'], label, title }
+}
+
+/** A chat message as the OWNER is shown it: whatever a viewer wrote, without bidi overrides. */
+function ownerChat(msg: WatchChatMessage): WatchChatMessage {
+ return { ...msg, name: stripBidiControls(msg.name), text: stripBidiControls(msg.text) }
+}
+
+/** Send to the machine's OWNER clients only — never a relay peer, never a live link's viewer. */
+export function sendToOwners(
+ p: Pick<CorePlatform, 'clientIds' | 'isOwnerClient' | 'sendTo'>,
+ channel: string,
+ ...args: unknown[]
+): void {
+ for (const id of p.clientIds()) if (p.isOwnerClient?.(id) === true) p.sendTo(id, channel, ...args)
+}
+
+const errorText = (err: unknown): string => (err instanceof Error ? err.message : String(err))
+const TIMEOUT = Symbol('timeout')
+
+export function createWatchLinkService(deps: WatchLinkServiceDeps): WatchLinkService {
+ const now = deps.now ?? Date.now
+ const setT = deps.setTimeout ?? ((fn: () => void, ms: number) => setTimeout(fn, ms))
+ const clearT = deps.clearTimeout ?? ((h: unknown) => clearTimeout(h as ReturnType<typeof setTimeout>))
+ const createHost = deps.createHost ?? createLinkHost
+ const persistTimeoutMs = deps.persistTimeoutMs ?? PERSIST_TIMEOUT_MS
+ const unsupported = deps.unsupported === true
+
+ const records = new Map<string, WatchLinkRecord>()
+ /** Created server-side, being written: in every write's snapshot (a concurrent write must not drop
+ * it from disk), but not yet a link — not listed, not hosted, and no stop path can end it half-way. */
+ const writing = new Map<string, WatchLinkRecord>()
+ const hosts = new Map<string, LinkHost>()
+ const expiry = new Map<string, unknown>()
+ let initPromise: Promise<void> | null = null
+ /** Creates between their cap check and their answer (G17): they count against the cap. A create's
+ * record joins `records` only as it answers, so it is never counted twice. */
+ let creating = 0
+ let stopped = false
+ /** The links file could not be read: never write it this run (R22). */
+ let storeLatched = false
+ /** The last write could not seal (the keychain refused): links live in memory only. */
+ let sealRefused = false
+ let lastWrite: Promise<unknown> = Promise.resolve()
+
+ const fail = (error: CreateWatchLinkError): CreateWatchLinkResult => ({ ok: false, error })
+ const warn = (line: string): void => console.warn(`[watch-link] ${line}`)
+ const persistentNow = (): boolean => !storeLatched && !sealRefused
+
+ function safeEmit(channel: string, ...args: unknown[]): void {
+ try {
+ deps.emit(channel, ...args)
+ } catch (err) {
+ warn(`telling the owner failed: ${errorText(err)}`)
+ }
+ }
+ const notice = (n: WatchLinkNotice): void => safeEmit(IPC.watchLinkNotice, n)
+
+ function nodeStateOf(nodeId: string): WatchLinkNodeState {
+ try {
+ const s = deps.nodeState(nodeId)
+ return s === 'present' || s === 'absent' ? s : 'unknown'
+ } catch {
+ return 'unknown' // a check that cannot answer is never evidence of absence
+ }
+ }
+
+ /** `p`'s answer, or TIMEOUT after `ms` (the timer is cleared as soon as `p` settles). A rejection
+ * reads as a timeout: either way the caller got no answer. */
+ function within<T>(p: Promise<T>, ms: number): Promise<T | typeof TIMEOUT> {
+ return new Promise((resolve) => {
+ const h = setT(() => resolve(TIMEOUT), ms)
+ p.then(
+ (v) => {
+ clearT(h)
+ resolve(v)
+ },
+ () => {
+ clearT(h)
+ resolve(TIMEOUT)
+ }
+ )
+ })
+ }
+
+ function viewOf(r: WatchLinkRecord): WatchLinkView {
+ const h = hosts.get(r.linkId)
+ // No host: a build that may not relay (G21), or a host that could not be built — nobody can
+ // watch it, which is what `refused` says.
+ let status: WatchLinkView['status'] = 'refused'
+ let viewers: WatchLinkViewerView[] = []
+ if (h) {
+ try {
+ status = h.status()
+ viewers = h.viewers().map((v) => ({
+ viewerId: v.viewerId,
+ name: v.name === null ? null : stripBidiControls(v.name),
+ joinedAt: v.joinedAt
+ }))
+ } catch (err) {
+ warn(`reading a link's state failed: ${errorText(err)}`)
+ }
+ }
+ return {
+ linkId: r.linkId,
+ nodeId: r.nodeId,
+ role: r.role,
+ label: stripBidiControls(r.label),
+ title: stripBidiControls(r.title),
+ createdAt: r.createdAt,
+ expiresAt: r.expiresAt,
+ url: formatWatchLink(r.linkId, r.secret),
+ status,
+ viewers
+ }
+ }
+ const list = (): WatchLinkView[] => (unsupported ? [] : [...records.values()].map(viewOf))
+ const emitState = (): void => safeEmit(IPC.watchLinkState, list())
+
+ /** Write the current records. Called, not awaited, wherever the owner must not wait on the disk;
+ * the store snapshots at call time and serializes its writes, so disk order is call order. */
+ function persist(): Promise<boolean> {
+ if (storeLatched) return Promise.resolve(true) // memory-only this run: nothing is written
+ const p = deps.store.save([...records.values(), ...writing.values()]).then(
+ (outcome) => {
+ sealRefused = outcome === 'memory-only'
+ return outcome !== 'failed'
+ },
+ () => false
+ )
+ lastWrite = p
+ return p
+ }
+
+ function revokeServer(linkId: string): void {
+ const ent = deps.entitlement()
+ if (!ent) return
+ void deps.api.revoke(linkId, ent).catch(() => false) // best effort (the client never rejects)
+ }
+
+ function armExpiry(r: WatchLinkRecord): void {
+ const t = expiry.get(r.linkId)
+ if (t !== undefined) clearT(t)
+ const delay = Math.min(MAX_DELAY_MS, Math.max(0, r.expiresAt - now()))
+ expiry.set(
+ r.linkId,
+ setT(() => {
+ expiry.delete(r.linkId)
+ if (records.get(r.linkId) !== r) return
+ if (now() < r.expiresAt) armExpiry(r) // a clamped delay: not yet
+ else end(r.linkId, 'expired', { serverRevoke: false, notify: true })
+ }, delay)
+ )
+ }
+
+ /** The host's pty seam, with the node-gone check before every join (R29, G8). */
+ function guardedPty(r: WatchLinkRecord): WatchPty {
+ return {
+ join: async (clientId, nodeId, viewerId) => {
+ // Off the link host's own call stack: ending the link stops that host.
+ await Promise.resolve()
+ if (nodeStateOf(nodeId) === 'absent') {
+ end(r.linkId, 'node-gone', { serverRevoke: true, notify: true })
+ return null
+ }
+ return deps.pty.join(clientId, nodeId, viewerId)
+ },
+ leave: (clientId, sessionId, viewerId) => deps.pty.leave(clientId, sessionId, viewerId),
+ captureVisible: (sessionId) => deps.pty.captureVisible(sessionId),
+ syncSize: (sessionId) => deps.pty.syncSize(sessionId),
+ alive: (sessionId) => deps.pty.alive(sessionId)
+ }
+ }
+
+ function onHostChange(linkId: string): void {
+ const r = records.get(linkId)
+ if (r && now() >= r.expiresAt) {
+ // A reconnect after a lid-close: the expiry timer may not have fired yet (G24). Deferred: this
+ // runs inside the link host's own status callback, and ending the link stops that host.
+ queueMicrotask(() => end(linkId, 'expired', { serverRevoke: false, notify: true }))
+ return
+ }
+ emitState()
+ }
+
+ function start(r: WatchLinkRecord): void {
+ if (stopped || hosts.has(r.linkId)) return
+ armExpiry(r)
+ if (!deps.relayAllowed()) return // kept and listed `refused`, never hosted (G21)
+ let host: LinkHost
+ try {
+ host = createHost(r, {
+ relayUrl: deps.relayUrl,
+ mint: async (): Promise<HostTokenResult> => {
+ const ent = deps.entitlement()
+ // Never a request with an empty entitlement: the API answers 400, and a 400 stops minting
+ // for good. The same end state, reached locally; `onEntitlementChanged` re-arms it (R41).
+ if (!ent) return { ok: false, kind: 'refused', status: 402 }
+ return deps.api.hostToken(r.linkId, ent)
+ },
+ status: async () => {
+ const ent = deps.entitlement()
+ return ent ? deps.api.status(r.linkId, ent) : 'unknown'
+ },
+ clients: deps.clients,
+ pty: guardedPty(r),
+ transport: deps.transport,
+ now,
+ setTimeout: setT,
+ clearTimeout: clearT,
+ onChange: () => onHostChange(r.linkId),
+ onChat: (msg) => safeEmit(IPC.watchLinkChat, r.linkId, ownerChat(msg)),
+ onViewerJoined: (count) =>
+ notice({ kind: 'joined', linkId: r.linkId, nodeId: r.nodeId, title: stripBidiControls(r.title), viewers: count }),
+ onGone: (reason) => end(r.linkId, reason, { serverRevoke: false, notify: true })
+ })
+ } catch (err) {
+ warn(`a link could not be hosted: ${errorText(err)}`)
+ return
+ }
+ hosts.set(r.linkId, host)
+ try {
+ host.start()
+ } catch (err) {
+ warn(`a link host did not start: ${errorText(err)}`)
+ }
+ }
+
+ /** Forget the record and its timer; the host is returned for the caller to stop AFTER the write
+ * was issued (spec: delete and write the record first, then end the sessions). */
+ function drop(linkId: string): { record: WatchLinkRecord; host: LinkHost | undefined } | null {
+ const record = records.get(linkId)
+ if (!record) return null
+ records.delete(linkId)
+ const t = expiry.get(linkId)
+ if (t !== undefined) clearT(t)
+ expiry.delete(linkId)
+ const host = hosts.get(linkId)
+ hosts.delete(linkId)
+ return { record, host }
+ }
+ function stopHost(host: LinkHost | undefined, reason: WatchLinkEndReason): void {
+ try {
+ host?.stop(reason)
+ } catch (err) {
+ warn(`stopping a link host failed: ${errorText(err)}`)
+ }
+ }
+
+ function end(
+ linkId: string,
+ reason: 'expired' | 'revoked' | 'node-gone',
+ o: { serverRevoke: boolean; notify: boolean }
+ ): void {
+ const gone = drop(linkId)
+ if (!gone) return
+ void persist()
+ stopHost(gone.host, reason)
+ emitState()
+ if (o.notify) {
+ notice({ kind: 'ended', linkId, nodeId: gone.record.nodeId, title: stripBidiControls(gone.record.title), reason })
+ }
+ if (o.serverRevoke) revokeServer(linkId)
+ }
+
+ async function runInit(): Promise<void> {
+ if (unsupported) return
+ if (deps.workspaceReady) {
+ try {
+ await deps.workspaceReady()
+ } catch {
+ // A failed load leaves nodes unknown, which keeps every link: the safe side.
+ }
+ }
+ let loaded: WatchLinkRecord[] = []
+ try {
+ loaded = await deps.store.load()
+ } catch (err) {
+ // The store refuses to write over a file it could not read (and latched itself); any other
+ // failure is treated the same way, because writing over it is the one unrecoverable mistake.
+ storeLatched = true
+ const why = err instanceof WatchLinkStoreUnreadable ? `${err.reason}: ${err.message}` : errorText(err)
+ warn(`live links will not be saved this run — the links file could not be read (${why})`)
+ }
+ if (stopped) return
+ const t = now()
+ let pruned = false
+ for (const r of loaded) {
+ if (records.has(r.linkId)) continue
+ if (r.expiresAt <= t) {
+ pruned = true
+ continue
+ }
+ if (nodeStateOf(r.nodeId) === 'absent') {
+ pruned = true
+ revokeServer(r.linkId)
+ continue
+ }
+ if (records.size >= MAX_LINKS_PER_MACHINE) {
+ // A hand-edited file: this machine hosts five links at most.
+ pruned = true
+ revokeServer(r.linkId)
+ continue
+ }
+ records.set(r.linkId, r)
+ }
+ if (pruned) void persist()
+ for (const r of [...records.values()]) start(r)
+ emitState()
+ if (!persistentNow()) notice({ kind: 'not-persistent' })
+ }
+
+ const init = (): Promise<void> =>
+ (initPromise ??= runInit().catch((err) => warn(`resuming live links failed: ${errorText(err)}`)))
+
+ return {
+ init,
+
+ async create(raw) {
+ if (unsupported || stopped) return fail('unsupported')
+ const req = parseRequest(raw)
+ if (!req) return fail('bad-request')
+ if (!deps.relayAllowed()) return fail('relay-unavailable')
+ // The resumed links count against the cap, and init must never start a host for a link a
+ // create already started (G11). Bounded: a hung disk answers, it does not hang the dialog.
+ if ((await within(init(), persistTimeoutMs)) === TIMEOUT) return fail('persist-failed')
+ if (stopped) return fail('unsupported')
+ if (nodeStateOf(req.nodeId) !== 'present') return fail('node-missing')
+ if (records.size + creating >= MAX_LINKS_PER_MACHINE) return fail('limit-machine')
+ const ent = deps.entitlement()
+ if (!ent) return fail('not-entitled')
+ creating++
+ try {
+ const secret = newWatchLinkSecret()
+ const joinKeyHash = await sha256Hex(deriveWatchLinkKeys(secret).joinKey)
+ const created = await deps.api.create(ent, joinKeyHash, req.ttlSeconds)
+ if (!created.ok) return fail(created.error)
+ if (stopped) {
+ revokeServer(created.linkId)
+ return fail('unsupported')
+ }
+ const record: WatchLinkRecord = {
+ linkId: created.linkId,
+ nodeId: req.nodeId,
+ role: req.role,
+ label: req.label,
+ title: req.title,
+ createdAt: now(),
+ expiresAt: created.expiresAt,
+ secret
+ }
+ writing.set(record.linkId, record)
+ let written: boolean | typeof TIMEOUT
+ try {
+ written = await within(persist(), persistTimeoutMs)
+ } finally {
+ writing.delete(record.linkId)
+ }
+ if (written !== true || stopped) {
+ // No half-created link: queue the list without it behind whatever is stuck (so a write
+ // that lands late is overwritten), and revoke the server row. (Quitting meanwhile is the
+ // same: the owner was never shown this link.)
+ void persist()
+ revokeServer(record.linkId)
+ return fail(stopped ? 'unsupported' : 'persist-failed')
+ }
+ records.set(record.linkId, record)
+ start(record)
+ emitState()
+ if (!persistentNow()) notice({ kind: 'not-persistent' })
+ return { ok: true, link: viewOf(record) }
+ } catch (err) {
+ warn(`creating a live link failed: ${errorText(err)}`)
+ return fail('network')
+ } finally {
+ creating--
+ }
+ },
+
+ list,
+
+ async revoke(linkId) {
+ if (unsupported || typeof linkId !== 'string') return
+ await within(init(), persistTimeoutMs) // no link exists before init; a hung load must not hang the stop
+ end(linkId, 'revoked', { serverRevoke: true, notify: false })
+ },
+
+ async revokeAll() {
+ if (unsupported) return
+ // Bounded like revoke: on a disk that hangs, "Stop all" still reaches the server below.
+ await within(init(), persistTimeoutMs)
+ const gone = [...records.keys()].map(drop)
+ // "Stop all" revokes every link of the license server-side, the ones this run cannot unseal too.
+ try {
+ deps.store.discardOpaque()
+ } catch (err) {
+ warn(`forgetting unreadable links failed: ${errorText(err)}`)
+ }
+ void persist()
+ for (const g of gone) stopHost(g?.host, 'revoked')
+ emitState()
+ const ent = deps.entitlement()
+ if (ent) void deps.api.revokeAll(ent).catch(() => false)
+ },
+
+ kick(linkId, viewerId) {
+ try {
+ return hosts.get(linkId)?.kick(viewerId) ?? false
+ } catch (err) {
+ warn(`kicking a viewer failed: ${errorText(err)}`)
+ return false
+ }
+ },
+
+ sendChat(linkId, text) {
+ try {
+ const msg = hosts.get(linkId)?.postSharerChat(text) ?? null
+ return msg ? ownerChat(msg) : null
+ } catch (err) {
+ warn(`sending a chat message failed: ${errorText(err)}`)
+ return null
+ }
+ },
+
+ chatHistory(linkId) {
+ try {
+ return (hosts.get(linkId)?.chatHistory() ?? []).map(ownerChat)
+ } catch {
+ return []
+ }
+ },
+
+ onWorkspaceChanged() {
+ if (unsupported || stopped) return
+ void init().then(() => {
+ if (stopped) return
+ for (const r of [...records.values()]) {
+ if (nodeStateOf(r.nodeId) === 'absent') end(r.linkId, 'node-gone', { serverRevoke: true, notify: true })
+ }
+ })
+ },
+
+ onEntitlementChanged() {
+ if (stopped) return
+ for (const h of hosts.values()) {
+ try {
+ if (h.status() === 'refused') h.start()
+ } catch (err) {
+ warn(`re-arming a link host failed: ${errorText(err)}`)
+ }
+ }
+ },
+
+ shutdown() {
+ if (!stopped) {
+ stopped = true
+ for (const t of expiry.values()) clearT(t)
+ expiry.clear()
+ const all = [...hosts.values()]
+ hosts.clear()
+ for (const h of all) stopHost(h, 'host-stopping')
+ }
+ return lastWrite.then(
+ () => undefined,
+ () => undefined
+ )
+ }
+ }
+}
+
+/** The owner IPC. Relay peers never reach these handlers (the `watchLink:` prefix is host-only and
+ * refused before any policy runs); the owner check is the belt behind that, for any other client. */
+export function registerWatchLinkIpc(
+ p: Pick<CorePlatform, 'handleWithSender' | 'isOwnerClient'>,
+ s: WatchLinkService
+): void {
+ const owner = (id: number): boolean => p.isOwnerClient?.(id) === true
+ const str = (v: unknown): v is string => typeof v === 'string'
+ p.handleWithSender(IPC.watchLinkCreate, (sender: number, req: unknown) =>
+ owner(sender) ? s.create(req) : ({ ok: false, error: 'unsupported' } satisfies CreateWatchLinkResult))
+ p.handleWithSender(IPC.watchLinkList, (sender: number) => (owner(sender) ? s.list() : []))
+ p.handleWithSender(IPC.watchLinkRevoke, (sender: number, id: unknown) =>
+ owner(sender) && str(id) ? s.revoke(id) : undefined)
+ p.handleWithSender(IPC.watchLinkRevokeAll, (sender: number) => (owner(sender) ? s.revokeAll() : undefined))
+ p.handleWithSender(IPC.watchLinkKick, (sender: number, id: unknown, viewer: unknown) =>
+ owner(sender) && str(id) && str(viewer) ? s.kick(id, viewer) : false)
+ p.handleWithSender(IPC.watchLinkChatSend, (sender: number, id: unknown, text: unknown) =>
+ owner(sender) && str(id) && str(text) ? s.sendChat(id, text) : null)
+ p.handleWithSender(IPC.watchLinkChatHistory, (sender: number, id: unknown) =>
+ owner(sender) && str(id) ? s.chatHistory(id) : [])
+}
diff --git a/src/main/index.ts b/src/main/index.ts
index e7b00e05a..89aa787ad 100644
--- a/src/main/index.ts
+++ b/src/main/index.ts
@@ -107,7 +107,17 @@ import type { CardLabelEdit } from '../core/project-kanban-write'
import { WorkspaceWatcher } from '../core/workspace-watcher'
import { SettingsStore } from '../core/settings-store'
import { registerAgentEnvIpc } from '../core/agent-env-ipc'
-import { presenceHub } from '../core/presence/hub'
+import { allocateRelayClientId, presenceHub } from '../core/presence/hub'
+import {
+ createWatchLinkService,
+ registerWatchLinkIpc,
+ sendToOwners,
+ workspaceNodeState,
+ type WatchLinkService
+} from '../core/watch-link/service'
+import { createWatchLinkApi } from '../core/watch-link/api'
+import { WatchLinkStore } from '../core/watch-link/store'
+import { createWatchPty } from '../core/watch-link/pty-seam'
import { SshStore } from './ssh-store'
import { GitService } from '../core/git-service'
import { ProjectTrustStore } from '../core/project-trust-store'
@@ -374,7 +384,7 @@ import {
} from './media-protocol'
import { initPlatform, platform } from '../core/platform'
import { electronPlatform } from './platform-electron'
-import { wirePeerRegistry } from './peer-registry'
+import { registerPeerSink, unregisterPeerSink, wirePeerRegistry } from './peer-registry'
import { WEBGL_CONTEXT_CAP_DESKTOP } from '../shared/webgl'
// Dev-only: NT_MULTI lets a SECOND instance run (host + client testing on one machine) with an
@@ -517,6 +527,10 @@ wirePeerRegistry({
// Set once the app window is ready; used by the quit hooks to tear down SSH-project masters and
// (via the closures below) to resolve a live SSH project's ControlMaster for remote workspace IO.
let sshProjectManager: ReturnType<typeof initSshProject> | undefined
+// Live links (src/core/watch-link/service.ts). Assigned in `whenReady`; declared here because the
+// workspace store's `onPersist`, the license callback and the quit handler read it at call time (the
+// boot workspace load's `onPersist` runs before the assignment — a later `const` would be a TDZ throw).
+let watchLinks: WatchLinkService | null = null
// The standalone Codex relay bundle (`out/main/codex-relay.js`, built by scripts/build-codex-relay.mjs
// after electron-vite build), uploaded to a Linux host for managed Codex accounts. Read once, beside
@@ -569,6 +583,8 @@ const workspaceWatcher = new WorkspaceWatcher({
workspaceStore.onPersist = () => {
workspaceWatcher.sync()
refreshNodeTokens()
+ // A node the store now provably holds nowhere (a delete, the canvas authority's op) ends its links.
+ watchLinks?.onWorkspaceChanged()
}
// "Which host owns this node?", answered WITHOUT a live session — the persisted index, not the
// in-memory `Session`. A delete arrives precisely when there may be nothing attached (an app
@@ -2132,8 +2148,10 @@ app.whenReady().then(async () => {
// here, and its sender leg (board-log line in the sender's project) resolves projects through the
// index, which nothing else has loaded yet at this point of boot (the renderer's own
// `workspace.load` comes later). Read-only load (`sideline: false`), like the relay path's.
+ // Shared with the live links' `init()` below, which must not judge a node gone before this read.
+ const bootWorkspaceLoad = workspaceStore.load({ sideline: false })
void restoreDeliveryQueue(messagingDeps.queue, deliveryQueueFile, {
- ready: workspaceStore.load({ sideline: false })
+ ready: bootWorkspaceLoad
})
/** The one display-title rule for everything the HOST sends out (push alerts, Live Activity
@@ -3142,6 +3160,49 @@ app.whenReady().then(async () => {
}
}
})
+ // Live links (docs/live-links.md): a Pro, read-only, expiring browser link to one terminal, hosted
+ // by this machine over the E2E relay. The viewer is a QUIET, SELF-PACED relay peer (never in a
+ // broadcast, never a pause ticket); the pty seam and the node-gone rule are core's, shared with the
+ // Server Edition. `init()` decides nothing before the boot workspace load (R40): an empty answer
+ // while the index is still being read is not evidence that a node is gone.
+ watchLinks = createWatchLinkService({
+ api: createWatchLinkApi({ apiBase: RELAY_API_BASE }),
+ relayUrl: RELAY_URL,
+ // Sealed through the keychain seam; if it refuses, links live in memory and the owner is told.
+ store: new WatchLinkStore({
+ file: join(corePlatform.userDataDir, 'watch-links.json'),
+ seal: corePlatform.sealSecret?.bind(corePlatform),
+ unseal: corePlatform.unsealSecret?.bind(corePlatform)
+ }),
+ entitlement: getStoredEntitlement,
+ relayAllowed,
+ nodeState: (nodeId) => workspaceNodeState(workspaceStore, nodeId),
+ workspaceReady: () => bootWorkspaceLoad,
+ clients: {
+ attach: (sink) => {
+ const id = allocateRelayClientId()
+ // No presence join: a viewer puts no cursor or facepile on the owner's canvas.
+ registerPeerSink(id, sink, { quiet: true, selfPaced: true })
+ return id
+ },
+ // → presenceHub.leave (a no-op for an id that never joined) and PtyManager.dropClient.
+ detach: (id) => unregisterPeerSink(id)
+ },
+ // A node of an SSH project is watched on ITS host over that project's master, or not at all:
+ // `requireRemote` for every such node, and the remote fields from this machine's own records.
+ pty: createWatchPty(ptyManager, (nodeId) => {
+ const projectId = workspaceStore.sshProjectIdForNode(nodeId)
+ if (!projectId) return {}
+ const ref = sshProjectManager?.refForProject(projectId)
+ return {
+ requireRemote: true,
+ ...(ref ? { sshRemote: { conn: ref.conn, controlPath: ref.controlPath, remoteCwd: ref.remoteCwd ?? '~' } } : {})
+ }
+ }),
+ emit: (channel, ...args) => sendToOwners(corePlatform, channel, ...args)
+ })
+ registerWatchLinkIpc(corePlatform, watchLinks)
+ void watchLinks.init()
const ackSweeper = createAckSweeper({
handlers: { ackDone, onUnreadClear: (id) => sendToMain(IPC.agentUnreadClear, id) }
})
@@ -4172,7 +4233,9 @@ app.whenReady().then(async () => {
buildMirrorUsage(usageService.snapshot(), settingsStore.get().claudeAccounts ?? [], Date.now())
)
initTelemetry(() => settingsStore.get())
- initLicense(() => {})
+ // A license change (activate, refresh, a lapsed token replaced) re-arms every live link the API
+ // refused: a link host whose 7-day entitlement expired under it stops minting until then (R41).
+ initLicense(() => watchLinks?.onEntitlementChanged())
// Lazy getter: sshProjectManager is created just below, so a remote account op (which only runs
// after the user has connected an SSH project) always sees the live manager.
initClaudeAccounts(() => sshProjectManager)
@@ -4825,10 +4888,14 @@ app.on('before-quit', (e) => {
}
quitFlushed = true
e.preventDefault()
+ // Live links: tell every viewer the host is stopping while the relay sockets are still up, before
+ // killAll tears their pty subscriptions out from under the link hosts. The records stay on disk (the
+ // links resume at the next launch); the last write the service issued lands inside the raced flush.
+ const watchLinksStopped = watchLinks?.shutdown()
// Pending throttled .nodeterm mirror writes must land BEFORE the ControlMasters die — killing
// a master mid-write used to leave a truncated project.json on the server. The masters are
// therefore kept up through the raced flush and dropped on the second before-quit pass.
- const flush = Promise.allSettled([remoteWorkspaceIO.flush(), ptyManager.killAll()])
+ const flush = Promise.allSettled([remoteWorkspaceIO.flush(), ptyManager.killAll(), watchLinksStopped])
void Promise.race([flush, new Promise((r) => setTimeout(r, 1500))])
// Then let whisper go. A dictation still transcribing when Electron tears down the main
// process's node env aborts the WHOLE app from inside the native addon (SIGABRT in
diff --git a/src/main/station-outcome-wiring.test.ts b/src/main/station-outcome-wiring.test.ts
index 6b8068450..9bcfc87b2 100644
--- a/src/main/station-outcome-wiring.test.ts
+++ b/src/main/station-outcome-wiring.test.ts
@@ -72,8 +72,12 @@ describe('desktop main', () => {
expect(withdraw).toBeGreaterThan(-1)
expect(withdraw).toBeLessThan(main.indexOf('sendToMain(IPC.agentStatus, enriched)'))
expect(main).toContain('flushAllDurableFactsSync()')
- // The restore waits for the workspace index, or a restore-time expiry reaches no sender.
- expect(main.slice(queue, queue + 200)).toContain('ready: workspaceStore.load({ sideline: false })')
+ // The restore waits for the workspace index, or a restore-time expiry reaches no sender. The boot
+ // read is shared with the live links' init (which must not judge a node gone before it either).
+ expect(main.slice(queue, queue + 200)).toContain('ready: bootWorkspaceLoad')
+ const bootLoad = main.indexOf('const bootWorkspaceLoad = workspaceStore.load({ sideline: false })')
+ expect(bootLoad).toBeGreaterThan(holds)
+ expect(bootLoad).toBeLessThan(queue)
// A second instance that lost the hook endpoint stands every durable file down.
const gate = main.indexOf('const hookStartupWarning = await hookServer.startForApp()')
expect(gate).toBeGreaterThan(-1)
diff --git a/src/main/watch-link-wiring.test.ts b/src/main/watch-link-wiring.test.ts
new file mode 100644
index 000000000..d51cbe27c
--- /dev/null
+++ b/src/main/watch-link-wiring.test.ts
@@ -0,0 +1,105 @@
+// Source-level: the live-link wiring closes over shell objects no unit test can build (the Electron
+// app, the Server Edition's platform, PtyManager, the workspace store), and an unwired service
+// compiles fine while doing nothing — the hook-verified-parity.test.ts remedy for the same hole.
+import { describe, it, expect } from 'vitest'
+import { readFileSync } from 'node:fs'
+import { join } from 'node:path'
+
+const read = (p: string) => readFileSync(join(__dirname, '..', '..', p), 'utf8').replace(/\r\n/g, '\n')
+/** The source of the arrow function assigned at `marker`, up to its closing `}` at column `indent`. */
+function blockAfter(src: string, marker: string, indent: string): string {
+ const start = src.indexOf(marker)
+ if (start < 0) throw new Error(`not found: ${marker}`)
+ const end = src.indexOf(`\n${indent}}`, start)
+ return src.slice(start, end < 0 ? undefined : end)
+}
+
+const MAIN = 'src/main/index.ts'
+const SERVER = 'src/server/index.ts'
+
+describe('live-link wiring', () => {
+ for (const shell of [MAIN, SERVER]) {
+ it(`${shell} creates, registers and inits the service over the shared seams`, () => {
+ const s = read(shell)
+ expect(s).toMatch(/createWatchLinkService\(\{/)
+ expect(s).toMatch(/registerWatchLinkIpc\((corePlatform|platform), watchLinks\)/)
+ expect(s).toMatch(/void watchLinks\.init\(\)/)
+ // The viewer is a QUIET, SELF-PACED client: absent from broadcasts and clientIds, and the registry
+ // never pauses a shared pty for it.
+ expect(s).toMatch(/quiet: true, selfPaced: true/)
+ // ONE join rule set (pty-seam.ts) and ONE node-gone rule (tri-state, R40) for both shells.
+ expect(s).toMatch(/pty: createWatchPty\(ptyManager,/)
+ expect(s).toMatch(/nodeState: \(nodeId\) => workspaceNodeState\(workspaceStore, nodeId\)/)
+ // Owner state to OWNER clients only: every view carries its link's secret.
+ expect(s).toMatch(/emit: \(channel, \.\.\.args\) => sendToOwners\((corePlatform|platform), channel, \.\.\.args\)/)
+ })
+
+ it(`${shell} tells the service about every workspace load/save`, () => {
+ const s = read(shell)
+ const onPersist = blockAfter(s, 'workspaceStore.onPersist = () => {', shell === MAIN ? '' : ' ')
+ expect(onPersist).toMatch(/watchLinks\?\.onWorkspaceChanged\(\)/)
+ // Declared BEFORE the closure (it runs at the boot load — a later `const` would be a TDZ throw).
+ expect(s.indexOf('let watchLinks: WatchLinkService | null = null')).toBeGreaterThan(-1)
+ expect(s.indexOf('let watchLinks: WatchLinkService | null = null')).toBeLessThan(s.indexOf('workspaceStore.onPersist = () => {'))
+ })
+ }
+
+ it('the desktop waits for the boot workspace load, hosts SSH nodes over their own master, and re-arms on a license change', () => {
+ const s = read(MAIN)
+ expect(s).toMatch(/const bootWorkspaceLoad = workspaceStore\.load\(\{ sideline: false \}\)/)
+ expect(s).toMatch(/workspaceReady: \(\) => bootWorkspaceLoad/)
+ expect(s).toMatch(/entitlement: getStoredEntitlement/)
+ expect(s).toMatch(/initLicense\(\(\) => watchLinks\?\.onEntitlementChanged\(\)\)/)
+ // A node of an SSH project is watched on its host, or not at all.
+ const remote = blockAfter(s, 'pty: createWatchPty(ptyManager,', ' ')
+ expect(remote).toMatch(/workspaceStore\.sshProjectIdForNode\(nodeId\)/)
+ expect(remote).toMatch(/requireRemote: true/)
+ expect(remote).toMatch(/sshProjectManager\?\.refForProject\(projectId\)/)
+ // The secret is sealed through the keychain seam.
+ expect(s).toMatch(/seal: corePlatform\.sealSecret\?\.bind\(corePlatform\)/)
+ expect(s).toMatch(/unseal: corePlatform\.unsealSecret\?\.bind\(corePlatform\)/)
+ })
+
+ it('the desktop stops the hosts on the FIRST quit pass, inside the raced flush and before killAll', () => {
+ const s = read(MAIN)
+ const quit = s.slice(s.indexOf("app.on('before-quit'"))
+ const firstPass = quit.slice(quit.indexOf('quitFlushed = true'))
+ const stop = firstPass.indexOf('watchLinks?.shutdown()')
+ expect(stop).toBeGreaterThan(-1)
+ expect(stop).toBeLessThan(firstPass.indexOf('ptyManager.killAll()'))
+ expect(firstPass).toMatch(/Promise\.allSettled\(\[[^\]]*watchLinksStopped/)
+ })
+
+ it('the Server Edition registers the service UNSUPPORTED with no entitlement (R43), and never inits it on a data dir it does not own', () => {
+ const s = read(SERVER)
+ const block = blockAfter(s, 'watchLinks = createWatchLinkService({', ' ')
+ expect(block).toMatch(/entitlement: \(\) => null/)
+ expect(block).toMatch(/unsupported: true/)
+ expect(block).toMatch(/detach: \(id\) => \{\s*dropUiClient\(id\)\s*platform\.detach\(id\)/)
+ expect(s).toMatch(/if \(otherServerHere\) \{\s*console\.error\('Live links: NOT started — another nodeterm server owns this data directory\.'\)\s*\} else void watchLinks\.init\(\)/)
+ // Both close paths stop the hosts after hosting ends and before the pty layer goes.
+ const closes = s.split('async close()').slice(1)
+ expect(closes).toHaveLength(2)
+ for (const c of closes) {
+ const stop = c.indexOf('await watchLinks?.shutdown()')
+ expect(stop).toBeGreaterThan(c.indexOf('hosted.stop()'))
+ expect(stop).toBeLessThan(c.indexOf('await ptyManager.killAll()'))
+ }
+ })
+
+ it('the preload exposes every owner channel', () => {
+ const p = read('src/preload/index.ts')
+ for (const ch of [
+ 'watchLinkCreate', 'watchLinkList', 'watchLinkRevoke', 'watchLinkRevokeAll', 'watchLinkKick',
+ 'watchLinkChatSend', 'watchLinkChatHistory', 'watchLinkState', 'watchLinkChat', 'watchLinkNotice'
+ ]) {
+ expect(p).toContain(`IPC.${ch}`)
+ }
+ })
+
+ it('the relay tab takes the inert stub and never names the channels', () => {
+ const r = read('src/renderer/bridge/relay-api.ts')
+ expect(r).toMatch(/watchLink: stub\.watchLink/)
+ expect(r).not.toMatch(/IPC\.watchLink/)
+ })
+})
diff --git a/src/preload/index.ts b/src/preload/index.ts
index f7be8380b..e9f9e8de6 100644
--- a/src/preload/index.ts
+++ b/src/preload/index.ts
@@ -23,6 +23,7 @@ import type {
} from '../shared/types'
import type { ClientId, PeerDiff, PeerIdentity, PeerState } from '../shared/presence'
import type { ProjectConsentRequest, ProjectSetupEvent } from '../shared/project-settings'
+import type { WatchChatMessage, WatchLinkNotice, WatchLinkView } from '../shared/watch-link-types'
// Fan a single ipcRenderer listener per channel out to many renderer subscribers. Without
// this, every node that subscribes (e.g. Cmd+M markdown toggle on each terminal/editor) adds
@@ -76,6 +77,10 @@ const subscribeProjectSetupConsentDismiss = subscribe<[{ requestId: string }]>(
// payload carries the projectId, fanned out the same way — nobody broadcasts it yet (Task 2), but
// the renderer cache subscribes ahead of the emitter.
const subscribeProjectTrustChanged = subscribe<[{ projectId: string }]>(IPC.projectTrustChanged)
+// Live links: owner-only pushes from core (the node chip, the popover and Settings all listen).
+const subscribeWatchLinkState = subscribe<[WatchLinkView[]]>(IPC.watchLinkState)
+const subscribeWatchLinkChat = subscribe<[string, WatchChatMessage]>(IPC.watchLinkChat)
+const subscribeWatchLinkNotice = subscribe<[WatchLinkNotice]>(IPC.watchLinkNotice)
const api: NodeTerminalApi = {
pty: {
@@ -893,6 +898,19 @@ const api: NodeTerminalApi = {
ipcRenderer.on(IPC.stationHandoverChanged, handler)
return () => ipcRenderer.removeListener(IPC.stationHandoverChanged, handler)
}
+ },
+ // Live links (src/core/watch-link/service.ts). Owner-only IPC; the service answers this window.
+ watchLink: {
+ create: (req) => ipcRenderer.invoke(IPC.watchLinkCreate, req),
+ list: () => ipcRenderer.invoke(IPC.watchLinkList),
+ revoke: (linkId) => ipcRenderer.invoke(IPC.watchLinkRevoke, linkId),
+ revokeAll: () => ipcRenderer.invoke(IPC.watchLinkRevokeAll),
+ kick: (linkId, viewerId) => ipcRenderer.invoke(IPC.watchLinkKick, linkId, viewerId),
+ sendChat: (linkId, text) => ipcRenderer.invoke(IPC.watchLinkChatSend, linkId, text),
+ chatHistory: (linkId) => ipcRenderer.invoke(IPC.watchLinkChatHistory, linkId),
+ onState: subscribeWatchLinkState,
+ onChat: subscribeWatchLinkChat,
+ onNotice: subscribeWatchLinkNotice
}
}
diff --git a/src/renderer/bridge/relay-api.test.ts b/src/renderer/bridge/relay-api.test.ts
index 01c0f18b3..092514bb0 100644
--- a/src/renderer/bridge/relay-api.test.ts
+++ b/src/renderer/bridge/relay-api.test.ts
@@ -152,6 +152,26 @@ describe('buildRelayApi', () => {
expect((local.relayClient.disconnect as ReturnType<typeof vi.fn>)).toHaveBeenCalledWith('conn-7')
})
+ it('live links: a relay tab takes the inert stub, never the LOCAL preload member, and sends nothing', async () => {
+ const { local } = fakeLocalApi()
+ const localWatchLink = { NAME: 'local-watch-link', create: vi.fn(), list: vi.fn() }
+ ;(local as unknown as { watchLink: unknown }).watchLink = localWatchLink
+ ;(globalThis as Record<string, unknown>).window = { nodeTerminal: local }
+ const t = new FakeTransport()
+ const { api } = buildRelayApi('conn-1', t)
+ expect(api.watchLink).not.toBe(localWatchLink)
+ await expect(
+ api.watchLink.create({ nodeId: 'n1', role: 'viewer', ttlSeconds: 3600, label: 'Ada', title: 'build' })
+ ).resolves.toEqual({ ok: false, error: 'unsupported' })
+ await expect(api.watchLink.list()).resolves.toEqual([])
+ await expect(api.watchLink.kick('l', 'v')).resolves.toBe(false)
+ await expect(api.watchLink.sendChat('l', 'x')).resolves.toBeNull()
+ await expect(api.watchLink.chatHistory('l')).resolves.toEqual([])
+ expect(typeof api.watchLink.onState(() => {})).toBe('function')
+ expect(localWatchLink.create).not.toHaveBeenCalled()
+ expect(t.sent).toEqual([]) // nothing crossed the relay
+ })
+
it('produces a value that satisfies NodeTerminalApi', () => {
const { local } = fakeLocalApi()
;(globalThis as Record<string, unknown>).window = { nodeTerminal: local }
diff --git a/src/renderer/bridge/relay-api.ts b/src/renderer/bridge/relay-api.ts
index ccd750cc2..ed36e88e1 100644
--- a/src/renderer/bridge/relay-api.ts
+++ b/src/renderer/bridge/relay-api.ts
@@ -196,6 +196,10 @@ export function buildRelayApi(
stationNotice: stub.stationNotice,
stationOutcome: stub.stationOutcome,
stationHandover: stub.stationHandover,
+ // Live links publish THIS machine's terminals; a relay tab shows another machine's, so it takes
+ // the inert stub (create answers `unsupported`). Never the local preload's real member, which
+ // `...local` would otherwise hand it: that would offer to publish a node id this core does not run.
+ watchLink: stub.watchLink,
// The mirror identity seed is a deliberate no-op here: a relay tab's nodes belong to the HOST's
// core, whose mirror is seeded by the host's own renderer from its own localStorage. This
// machine's localStorage holds no identity for them, and `...local` would plant this machine's
diff --git a/src/renderer/bridge/stubs.ts b/src/renderer/bridge/stubs.ts
index 76c70cff9..471bf14d7 100644
--- a/src/renderer/bridge/stubs.ts
+++ b/src/renderer/bridge/stubs.ts
@@ -600,6 +600,21 @@ export function buildStubApi(): Omit<
list: async () => [],
onChanged: noopUnsub
},
+ // Live links are created on the machine that runs the terminal. The Server Edition overrides this
+ // with the real bridge (`buildWatchLinkApi`); a relay tab keeps it — the peer's terminals are not
+ // this machine's to publish (and every `watchLink:` channel is host-only on the peer anyway).
+ watchLink: {
+ create: async () => ({ ok: false, error: 'unsupported' }),
+ list: async () => [],
+ revoke: async () => {},
+ revokeAll: async () => {},
+ kick: async () => false,
+ sendChat: async () => null,
+ chatHistory: async () => [],
+ onState: noopUnsub,
+ onChat: noopUnsub,
+ onNotice: noopUnsub
+ },
// Governs nothing by default. The Server Edition overrides it with the real bridge
// (`buildCanvasAuthorityApi`); a relay tab answers from its own connection (relay-api.ts).
canvasAuthority: {
diff --git a/src/renderer/bridge/ws-bridge.namespaces.test.ts b/src/renderer/bridge/ws-bridge.namespaces.test.ts
index a39d05e47..1f3dace7a 100644
--- a/src/renderer/bridge/ws-bridge.namespaces.test.ts
+++ b/src/renderer/bridge/ws-bridge.namespaces.test.ts
@@ -5,7 +5,8 @@ import {
buildClaudeAccountsApi,
buildFilesApi,
buildRealApi,
- buildSessionMemoryApi
+ buildSessionMemoryApi,
+ buildWatchLinkApi
} from './ws-bridge'
import { buildStubApi } from './stubs'
import { E_UNSUPPORTED } from '../../shared/rpc'
@@ -239,3 +240,59 @@ describe('buildHostedApi and the Server Edition', () => {
expect(install).not.toMatch(/\bhosted\s*:/)
})
})
+
+// Live links in the Server Edition: a REAL bridge over the owner-only `watchLink:*` channels (the
+// service answers create `unsupported` there until that edition has a license layer — R43).
+describe('buildWatchLinkApi', () => {
+ it('every member rides its own watchLink channel, with its arguments', async () => {
+ const c = fakeClient()
+ const api = buildWatchLinkApi(c as never).watchLink
+ const req = { nodeId: 'n1', role: 'viewer' as const, ttlSeconds: 3600 as const, label: 'Ada', title: 't' }
+ await api.create(req)
+ await api.list()
+ await api.revoke('L1')
+ await api.revokeAll()
+ await api.kick('L1', 'v-1')
+ await api.sendChat('L1', 'hi')
+ await api.chatHistory('L1')
+ api.onState(() => {})
+ api.onChat(() => {})
+ api.onNotice(() => {})
+ expect(c.calls).toEqual([
+ { kind: 'request', method: IPC.watchLinkCreate, args: [req] },
+ { kind: 'request', method: IPC.watchLinkList, args: [] },
+ { kind: 'request', method: IPC.watchLinkRevoke, args: ['L1'] },
+ { kind: 'request', method: IPC.watchLinkRevokeAll, args: [] },
+ { kind: 'request', method: IPC.watchLinkKick, args: ['L1', 'v-1'] },
+ { kind: 'request', method: IPC.watchLinkChatSend, args: ['L1', 'hi'] },
+ { kind: 'request', method: IPC.watchLinkChatHistory, args: ['L1'] },
+ { kind: 'subscribe', method: IPC.watchLinkState, args: [] },
+ { kind: 'subscribe', method: IPC.watchLinkChat, args: [] },
+ { kind: 'subscribe', method: IPC.watchLinkNotice, args: [] }
+ ])
+ })
+
+ it('a dropped socket: create answers network and the reads answer empty, never an unhandled rejection', async () => {
+ const down = { request: () => Promise.reject(new Error('E_DISCONNECTED')), subscribe: () => () => {} }
+ const api = buildWatchLinkApi(down as never).watchLink
+ await expect(api.create({ nodeId: 'n1', role: 'viewer', ttlSeconds: 3600, label: 'A', title: 't' })).resolves.toEqual({
+ ok: false,
+ error: 'network'
+ })
+ await expect(api.list()).resolves.toEqual([])
+ await expect(api.kick('L', 'v')).resolves.toBe(false)
+ await expect(api.sendChat('L', 'x')).resolves.toBeNull()
+ await expect(api.chatHistory('L')).resolves.toEqual([])
+ // A stop that did not reach the server must be visible to the UI.
+ await expect(api.revoke('L')).rejects.toThrow()
+ await expect(api.revokeAll()).rejects.toThrow()
+ })
+
+ it('is spread into the Server Edition api, and into no builder a relay tab shares', () => {
+ const src = readFileSync(join(__dirname, 'ws-bridge.ts'), 'utf8').replace(/\r\n/g, '\n')
+ const install = src.slice(src.indexOf('export async function installWsBridge'))
+ expect(install).toContain('...buildWatchLinkApi(client)')
+ const relay = readFileSync(join(__dirname, 'relay-api.ts'), 'utf8').replace(/\r\n/g, '\n')
+ expect(relay).not.toContain('buildWatchLinkApi')
+ })
+})
diff --git a/src/renderer/bridge/ws-bridge.ts b/src/renderer/bridge/ws-bridge.ts
index f67ade5b7..bfe975901 100644
--- a/src/renderer/bridge/ws-bridge.ts
+++ b/src/renderer/bridge/ws-bridge.ts
@@ -73,6 +73,12 @@ import { buildStubApi, unsupported } from './stubs'
import { sanitizeStationNotices } from '@shared/station-notice'
import { sanitizeOutcomeRecords } from '@shared/station-outcome'
import { sanitizeHandoverRecords } from '@shared/station-handover'
+import type {
+ CreateWatchLinkResult,
+ WatchChatMessage,
+ WatchLinkNotice,
+ WatchLinkView
+} from '@shared/watch-link-types'
import { mountPickerRoot, openDirectoryPicker } from './dialog-picker'
import { encodePcmForWire } from './speech-encode'
import { type FrameTransport, WebSocketFrameTransport } from './frame-transport'
@@ -971,6 +977,44 @@ export function buildTriggersApi(client: RpcClient): Pick<NodeTerminalApi, 'trig
}
}
+/**
+ * The Server Edition's live links — the REAL bridge, backed by the same core service the desktop
+ * registers (src/core/watch-link/service.ts). Its browser tabs are the server's own user (owner
+ * clients), so the host-only `watchLink:` prefix does not refuse them. Until that edition has a license
+ * layer the service answers create `unsupported` and list `[]` (R43). Kept OUT of every builder a relay
+ * tab spreads (and out of the scoped-guest / access-policy BUILDERS lists): a relay tab shows another
+ * machine's terminals, which are not this browser's to publish — relay-api.ts takes the inert stub.
+ * A dropped socket answers create `network`; revoke and revokeAll reject, so the UI can say the stop
+ * did not reach the server.
+ */
+export function buildWatchLinkApi(client: RpcClient): Pick<NodeTerminalApi, 'watchLink'> {
+ return {
+ watchLink: {
+ create: (req) =>
+ (client.request(IPC.watchLinkCreate, req) as Promise<CreateWatchLinkResult>).catch(
+ (): CreateWatchLinkResult => ({ ok: false, error: 'network' })
+ ),
+ list: () => (client.request(IPC.watchLinkList) as Promise<WatchLinkView[]>).catch(() => []),
+ revoke: async (linkId) => {
+ await client.request(IPC.watchLinkRevoke, linkId)
+ },
+ revokeAll: async () => {
+ await client.request(IPC.watchLinkRevokeAll)
+ },
+ kick: (linkId, viewerId) =>
+ (client.request(IPC.watchLinkKick, linkId, viewerId) as Promise<boolean>).catch(() => false),
+ sendChat: (linkId, text) =>
+ (client.request(IPC.watchLinkChatSend, linkId, text) as Promise<WatchChatMessage | null>).catch(() => null),
+ chatHistory: (linkId) =>
+ (client.request(IPC.watchLinkChatHistory, linkId) as Promise<WatchChatMessage[]>).catch(() => []),
+ onState: (cb) => client.subscribe(IPC.watchLinkState, ((links: WatchLinkView[]) => cb(links)) as Listener),
+ onChat: (cb) =>
+ client.subscribe(IPC.watchLinkChat, ((linkId: string, msg: WatchChatMessage) => cb(linkId, msg)) as Listener),
+ onNotice: (cb) => client.subscribe(IPC.watchLinkNotice, ((n: WatchLinkNotice) => cb(n)) as Listener)
+ }
+ }
+}
+
export function buildSessionMemoryApi(client: RpcClient): Pick<NodeTerminalApi, 'sessionMemory'> {
return {
sessionMemory: {
@@ -1280,6 +1324,7 @@ export async function installWsBridge(): Promise<boolean> {
...buildSpeechApi(client),
...buildUsageApi(client),
...buildSessionMemoryApi(client),
+ ...buildWatchLinkApi(client),
...buildWallpaperApi(client),
...buildTriggersApi(client),
...buildGitHubApi(client),
diff --git a/src/server/index.ts b/src/server/index.ts
index f1cca4fb6..83f46ae90 100644
--- a/src/server/index.ts
+++ b/src/server/index.ts
@@ -114,6 +114,16 @@ import { isPremium, getStoredEntitlement } from '../core/license'
import { getDeviceId } from '../core/device-id'
import { createHostedService } from '../core/relay/hosted-service'
import { startTeamAdmin } from '../core/relay/team-admin'
+import {
+ createWatchLinkService,
+ registerWatchLinkIpc,
+ sendToOwners,
+ workspaceNodeState,
+ type WatchLinkService
+} from '../core/watch-link/service'
+import { createWatchLinkApi } from '../core/watch-link/api'
+import { WatchLinkStore } from '../core/watch-link/store'
+import { createWatchPty } from '../core/watch-link/pty-seam'
// Same env-override + default as src/core/check.ts / license.ts / src/main/telemetry.ts — each
// shell derives it locally rather than sharing an import (src/server must not import src/main).
@@ -720,6 +730,10 @@ export async function startServer(
(project) => platform.broadcast(IPC.workspaceServerChange, project)
)
})
+ // Live links (src/core/watch-link/service.ts). Assigned after the hosted-team block below; declared
+ // here because the onPersist closure runs at the boot load just below (a later `const` would be a
+ // TDZ throw inside that load, which it would then report as a failed load).
+ let watchLinks: WatchLinkService | null = null
// Every load()/save() is a canvas change as far as links are concerned: a browser drawing a
// bridge edge reaches us as the workspace save it triggers. It also refreshes the local-ref
// watcher set, so projects added or removed while the server runs get the same hand-edit path.
@@ -727,6 +741,7 @@ export async function startServer(
workspaceWatcher.sync()
contextLink.refresh()
refreshNodeTokens()
+ watchLinks?.onWorkspaceChanged()
}
// Nothing has read the workspace index yet — the desktop gets its first load from the renderer,
// and this shell may never have one. Read it once so links are live before any browser connects.
@@ -990,6 +1005,41 @@ export async function startServer(
authority.sharedChanged()
}
+ // Live links (docs/live-links.md): the SAME core service the desktop registers, over the real seams.
+ // This edition has no license layer yet (`initLicense` is desktop-only), so the service is registered
+ // UNSUPPORTED with no entitlement (controller ruling R43): create answers `unsupported` — the browser
+ // shows "Live links need a Pro license on this server — not available in the Server Edition yet",
+ // never an Upgrade button — list answers [], and nothing is loaded, hosted or revoked. A server
+ // license layer (a named follow-up) changes `entitlement` and drops `unsupported`, nothing else.
+ // Headless, no keychain: the links file is a 0600 file in the data dir (spec D8). The workspace
+ // index was read above, so there is no load to wait for.
+ watchLinks = createWatchLinkService({
+ api: createWatchLinkApi({ apiBase: API_BASE }),
+ relayUrl: RELAY_URL,
+ store: new WatchLinkStore({ file: path.join(config.dataDir, 'watch-links.json') }),
+ entitlement: () => null,
+ relayAllowed: () => true,
+ nodeState: (nodeId) => workspaceNodeState(workspaceStore, nodeId),
+ clients: {
+ attach: (sink) => platform.attach(sink, { quiet: true, selfPaced: true }),
+ // The per-client drops a departed client is owed (its pty subscriptions), then the sink.
+ detach: (id) => {
+ dropUiClient(id)
+ platform.detach(id)
+ }
+ },
+ // No SSH-project manager here: a node of an SSH project is joinable only while this core holds
+ // its session live (join-only never spawns), and never through the local tmux.
+ pty: createWatchPty(ptyManager, (nodeId) => (workspaceStore.sshProjectIdForNode(nodeId) ? { requireRemote: true } : {})),
+ emit: (channel, ...args) => sendToOwners(platform, channel, ...args),
+ unsupported: true
+ })
+ registerWatchLinkIpc(platform, watchLinks)
+ // Two servers on one data dir would host (and revoke) each other's links.
+ if (otherServerHere) {
+ console.error('Live links: NOT started — another nodeterm server owns this data directory.')
+ } else void watchLinks.init()
+
// Headless notification host: every core service above (incl. the loopback hook server, which
// is its own listener and MUST run) is booted, but we bind NO public HTTP/WS listener — no
// renderer serving, no auth surface, no open port. The granted push senders reach the phone over
@@ -1006,6 +1056,8 @@ export async function startServer(
// pty subscriptions) while the pty layer is still up. Same two lines in the serving close().
await teamAdmin.close()
hosted.stop()
+ // Stop the live-link hosts while the pty layer is still up (their viewers leave cleanly).
+ await watchLinks?.shutdown()
// Detach PTY clients — tmux sessions keep running (Phase 1 contract).
sessionReaper.stop()
pressure.stop()
@@ -1070,6 +1122,8 @@ export async function startServer(
// headless close() above).
await teamAdmin.close()
hosted.stop()
+ // Stop the live-link hosts while the pty layer is still up (see the headless close() above).
+ await watchLinks?.shutdown()
// End the browser WebSockets next, BEFORE the canvas authority stops (N3). Once it has stopped
// and been detached, a save from a still-attached tab is written un-overlaid, over its final
// flush. Ending the sockets stops new saves; the `idle()` below lets the ones already queued
diff --git a/src/shared/host-control.test.ts b/src/shared/host-control.test.ts
index e7b57696e..225dfc239 100644
--- a/src/shared/host-control.test.ts
+++ b/src/shared/host-control.test.ts
@@ -60,6 +60,23 @@ describe('isHostOnlyChannel', () => {
expect(isHostOnlyChannel('notgithubControl:approve')).toBe(false)
})
+ it('every owner live-link channel is host-only, and the viewer protocol is not in that namespace', () => {
+ // A live link publishes a host terminal to anyone with its URL, paid for with the host's Pro, and
+ // the list answer carries every link's secret. A hosted editor passes every access check, so this
+ // prefix is the only thing between a teammate and a link.
+ const owner = (Object.values(IPC) as unknown[]).filter(
+ (v): v is string => typeof v === 'string' && v.startsWith('watchLink:')
+ )
+ expect(owner).toHaveLength(10)
+ for (const ch of owner) expect(isHostOnlyChannel(ch), ch).toBe(true)
+ // A namespace, not a list: a verb added later is refused the day it is added.
+ expect(isHostOnlyChannel('watchLink:something-new')).toBe(true)
+ // The viewer's own tunnel messages are `watch:*` — never refused as host-only, or a Commenter
+ // could not chat (relay-host refuses host-only methods before any policy runs).
+ expect(isHostOnlyChannel('watch:chat')).toBe(false)
+ expect(isHostOnlyChannel('watch:meta')).toBe(false)
+ })
+
it('carries the refusal wording the peer sees, so both shells answer identically', () => {
expect(HOST_ONLY_REFUSAL).toBe('host-control method is not available to relay peers')
})
diff --git a/src/shared/host-control.ts b/src/shared/host-control.ts
index 3d63e05bc..4aa07c54c 100644
--- a/src/shared/host-control.ts
+++ b/src/shared/host-control.ts
@@ -31,6 +31,9 @@ import { IPC } from './ipc'
* about the host's panes it never measured.
* - `station-notice:list` — every project's failed-station ids and titles, unscoped. A relay tab
* never asks (it takes the inert stub), and a guest bound to ONE project must not read the rest.
+ * - `watchLink:*` — live links (src/core/watch-link/service.ts): a link publishes one of the host's
+ * terminals to anyone holding its URL and is paid for with the host's Pro. An editor passes every
+ * access check, so only this list keeps a teammate from minting one.
*
* DELIBERATELY NOT LISTED: `project-setup:subscribe`/`unsubscribe` and the `project-setup:event:*`
* push. They neither start nor authorize anything, and a peer that can see the canvas can already
@@ -58,7 +61,11 @@ export const HOST_ONLY_CHANNEL_PREFIXES: readonly string[] = [
'pairing:',
'remote:',
'relay:host:',
- 'relay:client:'
+ 'relay:client:',
+ // Live links: publishing a host terminal to anyone with a URL, with the host's Pro. No relay peer
+ // may create, list (every link's URL carries its secret), stop, kick or chat as the owner. The
+ // viewer's own protocol is `watch:*`, which this prefix deliberately does not match.
+ 'watchLink:'
]
export const HOST_ONLY_CHANNELS: ReadonlySet<string> = new Set([
diff --git a/src/shared/ipc.ts b/src/shared/ipc.ts
index dab1c3536..3540d94e5 100644
--- a/src/shared/ipc.ts
+++ b/src/shared/ipc.ts
@@ -254,6 +254,30 @@ export const IPC = {
stationHandoverList: 'station-handover:list',
/** core → every renderer: the FULL current list on each change, never a delta. */
stationHandoverChanged: 'station-handover:changed',
+ /** Live links (docs/live-links.md, src/core/watch-link/service.ts). OWNER-ONLY: every `watchLink:`
+ * channel is host-only (host-control.ts), so no relay peer — hosted owners and editors included —
+ * can create a link, which would publish a host terminal with the host's Pro. The viewer's own
+ * tunnel protocol is `watch:*` (src/shared/watch-link/protocol.ts), deliberately NOT this
+ * namespace. invoke: `create(CreateWatchLinkRequest)` → CreateWatchLinkResult. */
+ watchLinkCreate: 'watchLink:create',
+ /** invoke: the current links (WatchLinkView[]), for a renderer that booted after a push. */
+ watchLinkList: 'watchLink:list',
+ /** invoke: `(linkId)` — stop one link now (local first, then a best-effort server revoke). */
+ watchLinkRevoke: 'watchLink:revoke',
+ /** invoke: stop every link on this machine, then one server revoke-all. */
+ watchLinkRevokeAll: 'watchLink:revoke-all',
+ /** invoke: `(linkId, viewerId)` → boolean — end ONE viewer's connection (the link stays). */
+ watchLinkKick: 'watchLink:kick',
+ /** invoke: `(linkId, text)` → WatchChatMessage | null — the owner's reply on a Commenter link. */
+ watchLinkChatSend: 'watchLink:chat-send',
+ /** invoke: `(linkId)` → WatchChatMessage[] — this run's last messages (memory only). */
+ watchLinkChatHistory: 'watchLink:chat-history',
+ /** core → owner clients only: the full list on every change, never a delta. */
+ watchLinkState: 'watchLink:state',
+ /** core → owner clients only: `(linkId, WatchChatMessage)`. */
+ watchLinkChat: 'watchLink:chat',
+ /** core → owner clients only: a `WatchLinkNotice`. */
+ watchLinkNotice: 'watchLink:notice',
/** Canvas sync: a client casts its local node mutations here; the core reflector
* (src/core/canvas-sync.ts) stamps each with the total order (`seq`) and sends it back out on the
* SAME channel to EVERY attached client — the sender included, whose copy is its ack (see
diff --git a/src/shared/types.ts b/src/shared/types.ts
index 72f44e77b..6c8113edf 100644
--- a/src/shared/types.ts
+++ b/src/shared/types.ts
@@ -4265,4 +4265,9 @@ export interface NodeTerminalApi {
list(): Promise<import('./station-handover').StationHandoverRecord[]>
onChanged(cb: (records: import('./station-handover').StationHandoverRecord[]) => void): () => void
}
+ /** Live links (src/core/watch-link/service.ts): a read-only, expiring browser link to one terminal,
+ * hosted by THIS machine. Owner-only (`watchLink:*` is host-only). Desktop: real. Server Edition:
+ * the real bridge, whose create answers `unsupported` until that edition has a license layer.
+ * Relay tab: an inert stub (a peer's terminals are not this machine's to publish). */
+ watchLink: import('./watch-link-types').WatchLinkApi
}
diff --git a/src/shared/watch-link-types.ts b/src/shared/watch-link-types.ts
new file mode 100644
index 000000000..ddb712af9
--- /dev/null
+++ b/src/shared/watch-link-types.ts
@@ -0,0 +1,122 @@
+// Live links, OWNER side (docs/live-links.md): what the renderer and the core registry
+// (src/core/watch-link/service.ts) say to each other over the host-only `watchLink:*` IPC. NOT the
+// viewer's protocol — that is src/shared/watch-link/ (vendored byte for byte into nodeterm-web), and
+// this file must stay out of that directory.
+import type { WatchChatMessage, WatchLinkRole } from './watch-link/protocol'
+export type { WatchChatMessage, WatchLinkRole }
+
+/** The expiry choices, in seconds: 15 min, 1 h (the default), 8 h, 24 h. No other value is accepted. */
+export const WATCH_LINK_TTLS = [900, 3600, 28800, 86400] as const
+export type WatchLinkTtl = (typeof WATCH_LINK_TTLS)[number]
+export const DEFAULT_WATCH_LINK_TTL: WatchLinkTtl = 3600
+/** Active links per machine (spec D6). */
+export const MAX_LINKS_PER_MACHINE = 5
+/** "Shown to viewers as" — UTF-16 units, the same bound the store checks on load. */
+export const LABEL_MAX = 40
+/** The node title shown to viewers — UTF-16 units, the same bound the store checks on load. */
+export const TITLE_MAX = 80
+
+export interface CreateWatchLinkRequest {
+ nodeId: string
+ role: WatchLinkRole
+ ttlSeconds: WatchLinkTtl
+ label: string
+ title: string
+}
+
+/**
+ * Why a create failed. Which copy each one needs is the renderer's (Tasks 15–17):
+ * - `not-entitled` — no Pro entitlement stored, or the API answered 402/403: "Live links need an
+ * active Pro plan." + Upgrade.
+ * - `limit-machine` — 5 links active on this machine (checked locally, before any request).
+ * - `limit-active` / `limit-daily` / `rate-limited` — the API's 429, by scope.
+ * - `network` — a timeout, a thrown fetch, a 5xx or a malformed reply. Never "you are offline":
+ * "Couldn't reach nodeterm's service. Nothing was shared."
+ * - `license-check` — the API could not check the license right now (503).
+ * - `relay-unavailable` — relaying is disabled in this build (an unpackaged dev build).
+ * - `node-missing` — no project holds the node (a node opened seconds ago may not be saved yet:
+ * flush the canvas save before asking).
+ * - `bad-request` — the request did not validate (here or at the API).
+ * - `persist-failed` — the server row was created but could not be written locally; it was revoked.
+ * - `unsupported` — this surface cannot create links: the Server Edition until it has a license
+ * layer ("Live links need a Pro license on this server — not available in the Server Edition
+ * yet", never an Upgrade button — R43), a relay tab ("Live links are created on the machine that
+ * runs this terminal"), a client that is not the machine's owner, or an app that is quitting.
+ */
+export type CreateWatchLinkError =
+ | 'not-entitled'
+ | 'limit-machine'
+ | 'limit-active'
+ | 'limit-daily'
+ | 'rate-limited'
+ | 'network'
+ | 'license-check'
+ | 'relay-unavailable'
+ | 'node-missing'
+ | 'bad-request'
+ | 'persist-failed'
+ | 'unsupported'
+export type CreateWatchLinkResult = { ok: true; link: WatchLinkView } | { ok: false; error: CreateWatchLinkError }
+
+export interface WatchLinkViewerView {
+ viewerId: string
+ /** The name the viewer chatted under, if it has chatted; null otherwise ("Viewer 1"…). */
+ name: string | null
+ joinedAt: number
+}
+
+export interface WatchLinkView {
+ linkId: string
+ nodeId: string
+ role: WatchLinkRole
+ label: string
+ title: string
+ createdAt: number
+ expiresAt: number
+ /** The full link, secret included (in the fragment). Owner clients only; never logged. */
+ url: string
+ /** `live` = listening or full; `reconnecting` = the relay leg is down or not yet up (chip "offline");
+ * `refused` = the API refuses to mint for this link (an expired/lapsed entitlement, or a build that
+ * may not relay) — the chip "refused". */
+ status: 'live' | 'reconnecting' | 'refused'
+ viewers: WatchLinkViewerView[]
+}
+
+export type WatchLinkNotice =
+ /** Someone started watching: how an owner notices a leaked link. `viewers` counts the link's own. */
+ | { kind: 'joined'; linkId: string; nodeId: string; title: string; viewers: number }
+ /** A link ended on its own: `revoked` here is a SERVER-side revoke (an owner's own Stop raises none). */
+ | { kind: 'ended'; linkId: string; nodeId: string; title: string; reason: 'expired' | 'revoked' | 'node-gone' }
+ /** Links are not written to disk this run (the keychain refused to seal, or the links file could
+ * not be read): they work, and end at quit. Sent at boot and after every create while it holds. */
+ | { kind: 'not-persistent' }
+
+/** `window.nodeTerminal.watchLink`. Desktop: real (preload). Server Edition: real bridge, and create
+ * answers `unsupported` until that edition has a license layer. Relay tab: an inert stub. */
+export interface WatchLinkApi {
+ create(req: CreateWatchLinkRequest): Promise<CreateWatchLinkResult>
+ list(): Promise<WatchLinkView[]>
+ revoke(linkId: string): Promise<void>
+ revokeAll(): Promise<void>
+ kick(linkId: string, viewerId: string): Promise<boolean>
+ /** A Commenter link's owner reply; null when the link is not a Commenter link or the text is empty. */
+ sendChat(linkId: string, text: string): Promise<WatchChatMessage | null>
+ chatHistory(linkId: string): Promise<WatchChatMessage[]>
+ /** The full list on every change, never a delta. */
+ onState(cb: (links: WatchLinkView[]) => void): () => void
+ onChat(cb: (linkId: string, msg: WatchChatMessage) => void): () => void
+ onNotice(cb: (n: WatchLinkNotice) => void): () => void
+}
+
+/**
+ * Directional formatting characters: LRM/RLM, the embeddings and overrides (U+202A–E) and the
+ * isolates (U+2066–9). The vendored chat sanitizer strips C0/C1 but not these, and a name or a title
+ * carrying an RLO reorders whatever the owner's UI draws after it. Stripped from every string the
+ * owner side shows that someone else wrote: a viewer's chat name and text, and the link's label and
+ * title (a title can come from a git-shared node title).
+ */
+export const BIDI_CONTROLS = /[‎‏‪-‮⁦-⁩]/g
+
+export function stripBidiControls(s: string): string {
+ return s.replace(BIDI_CONTROLS, '')
+}