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.
TypeScript adhdagent-orchestrationai-agentscanvasclaude-codecodexcoding-agentsdeveloper-toolselectrongeminilinuxmacosmultiplexeropencodeparallel-agentsterminalterminal-emulatorterminal-multiplexertmuxworkspace-manager
feat(live-links): protocol and types for the Control role and unlimited links
reviewff7a42ff09db
diff --git a/src/core/relay/scoped-guest-policy.test.ts b/src/core/relay/scoped-guest-policy.test.tsindex e0e69f5ef..6ca1df999 100644--- a/src/core/relay/scoped-guest-policy.test.ts+++ b/src/core/relay/scoped-guest-policy.test.ts@@ -263,7 +263,7 @@ describe('relay host — host-only channels refused to every peer', () => {const methods = (Object.values(IPC) as unknown[]).filter((v): v is string => typeof v === 'string' && v.startsWith('watchLink:'))- expect(methods).toHaveLength(10)+ expect(methods).toHaveLength(14)methods.forEach((method, i) =>t.client.send(JSON.stringify({ t: 'req', id: 200 + i, method, args: [{ nodeId: 'a1', role: 'viewer', ttlSeconds: 3600, label: 'x' }] })))diff --git a/src/core/watch-link/client.test.ts b/src/core/watch-link/client.test.tsindex fc4f160d7..2149073de 100644--- a/src/core/watch-link/client.test.ts+++ b/src/core/watch-link/client.test.ts@@ -13,6 +13,7 @@ import { createTrustGate, deniedFrame, type TrustGate } from '../relay/relay-truimport { encodePtyData } from '../../shared/rpc'import { connectWatchClient, TRUST_CONFIRM_JSON, type WatchSocket } from '../../shared/watch-link/client'import { deriveWatchLinkKeys, type WatchLinkKeys } from '../../shared/watch-link/keys'+import { INPUT_MAX } from '../../shared/watch-link/protocol'function hostWith(opts: { keys?: WatchLinkKeys; autoApprove?: boolean } = {}) {const keys = opts.keys ?? deriveWatchLinkKeys(nacl.randomBytes(32))@@ -148,6 +149,32 @@ describe('connectWatchClient against the real relay socket', () => {expect(h.tunnel.at(-1)).toBe(JSON.stringify({ t: 'cast', method: 'watch:chat', args: [{ name: 'Ada', text: 'hi' }] }))})+ it('sends the control casts only while open, exactly as the host reads them', async () => {+ const h = hostWith()+ const { socket, sent } = counting(h.peerT)+ const c = connectWatchClient({ socket, keys: h.keys, events: events().ev })+ expect(c.unlock('Mert', 'pw')).toBe(false)+ expect(c.sendInput('ab')).toBe(false)+ expect(c.release()).toBe(false)+ await vi.waitFor(() => expect(h.tunnel).toContain(TRUST_CONFIRM_JSON))+ h.confirm()+ // Every one of them is a TAG_TUNNEL_TEXT frame: the host's onTunnel hands only those over as 'text'.+ expect(c.unlock('Mert', 'pw')).toBe(true)+ expect(h.tunnel.at(-1)).toBe('{"t":"cast","method":"watch:unlock","args":[{"name":"Mert","password":"pw"}]}')+ expect(c.sendInput('ab')).toBe(true)+ expect(h.tunnel.at(-1)).toBe('{"t":"cast","method":"watch:input","args":[{"data":"ab"}]}')+ expect(c.release()).toBe(true)+ expect(h.tunnel.at(-1)).toBe('{"t":"cast","method":"watch:release","args":[]}')+ // Over the cap (or empty, or not a string): refused here, and nothing leaves the client.+ const before = { tunnel: h.tunnel.length, binary: sent.binary }+ expect(c.sendInput('x'.repeat(INPUT_MAX + 1))).toBe(false)+ expect(c.sendInput('')).toBe(false)+ expect(c.sendInput(7 as never)).toBe(false)+ expect({ tunnel: h.tunnel.length, binary: sent.binary }).toEqual(before)+ expect(c.sendInput('x'.repeat(INPUT_MAX))).toBe(true)+ expect(h.tunnel).toHaveLength(before.tunnel + 1)+ })+it('keeps both directions flowing past seq 255', async () => {// A strictly increasing counter stays increasing under most encodings, so a short exchange// cannot tell the relay's little-endian seq from a byte-swapped copy. Past one byte it can:diff --git a/src/core/watch-link/service.test.ts b/src/core/watch-link/service.test.tsindex 4dd184893..e50c01840 100644--- a/src/core/watch-link/service.test.ts+++ b/src/core/watch-link/service.test.ts@@ -742,7 +742,7 @@ describe('createWatchLinkService — the host seams', () => {h.chat = [{ id: 'y', name: '\u200fMal', text: 'a\u202ab', 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\u202eve', joinedAt: 5, waiting: false }]- expect(t.s.list()[0].viewers).toEqual([{ viewerId: 'v-1', name: 'Eve', joinedAt: 5, waiting: false }])+ expect(t.s.list()[0].viewers).toEqual([{ viewerId: 'v-1', name: 'Eve', joinedAt: 5, waiting: false, controlling: false, typing: false }])})// R63: a viewer the host could not join to a session reaches the owner's view as `waiting`.diff --git a/src/core/watch-link/service.ts b/src/core/watch-link/service.tsindex 41f0a3983..d1f449f7e 100644--- a/src/core/watch-link/service.ts+++ b/src/core/watch-link/service.ts@@ -281,7 +281,9 @@ export function createWatchLinkService(deps: WatchLinkServiceDeps): WatchLinkServiewerId: v.viewerId,name: v.name === null ? null : stripBidiControls(v.name),joinedAt: v.joinedAt,- waiting: v.waiting === true+ waiting: v.waiting === true,+ controlling: false,+ typing: false}))} catch (err) {warn(`reading a link's state failed: ${errorText(err)}`)@@ -297,7 +299,8 @@ export function createWatchLinkService(deps: WatchLinkServiceDeps): WatchLinkSerexpiresAt: r.expiresAt,url: formatWatchLink(r.linkId, r.secret),status,- viewers+ viewers,+ control: null}}const list = (): WatchLinkView[] => (unsupported ? [] : [...records.values()].map(viewOf))diff --git a/src/preload/index.ts b/src/preload/index.tsindex 96a8db228..d9ac40ebd 100644--- a/src/preload/index.ts+++ b/src/preload/index.ts@@ -963,6 +963,10 @@ const api: NodeTerminalApi = {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),+ setControl: (linkId, enabled) => ipcRenderer.invoke(IPC.watchLinkSetControl, linkId, enabled),+ setPassword: (linkId, password) => ipcRenderer.invoke(IPC.watchLinkSetPassword, linkId, password),+ allowControl: (linkId) => ipcRenderer.invoke(IPC.watchLinkAllowControl, linkId),+ controlSupport: (nodeId) => ipcRenderer.invoke(IPC.watchLinkControlSupport, nodeId),onState: subscribeWatchLinkState,onChat: subscribeWatchLinkChat,onNotice: subscribeWatchLinkNoticediff --git a/src/renderer/bridge/stubs.ts b/src/renderer/bridge/stubs.tsindex fd0e41a4f..67f6f5515 100644--- a/src/renderer/bridge/stubs.ts+++ b/src/renderer/bridge/stubs.ts@@ -665,6 +665,10 @@ export function buildStubApi(): Omit<kick: async () => false,sendChat: async () => null,chatHistory: async () => [],+ setControl: async () => false,+ setPassword: async () => false,+ allowControl: async () => false,+ controlSupport: async () => 'unknown' as const,onState: noopUnsub,onChat: noopUnsub,onNotice: noopUnsubdiff --git a/src/renderer/bridge/ws-bridge.ts b/src/renderer/bridge/ws-bridge.tsindex 5764929fd..a71cbfc68 100644--- a/src/renderer/bridge/ws-bridge.ts+++ b/src/renderer/bridge/ws-bridge.ts@@ -78,6 +78,7 @@ import { sanitizeStationNotices } from '@shared/station-notice'import { sanitizeOutcomeRecords } from '@shared/station-outcome'import { sanitizeHandoverRecords } from '@shared/station-handover'import type {+ ControlSupport,CreateWatchLinkResult,RevokeAllOutcome,WatchChatMessage,@@ -1031,6 +1032,13 @@ export function buildWatchLinkApi(client: RpcClient): Pick<NodeTerminalApi, 'wat(client.request(IPC.watchLinkChatSend, linkId, text) as Promise<WatchChatMessage | null>).catch(() => null),chatHistory: (linkId) =>(client.request(IPC.watchLinkChatHistory, linkId) as Promise<WatchChatMessage[]>).catch(() => []),+ setControl: (linkId, enabled) =>+ (client.request(IPC.watchLinkSetControl, linkId, enabled) as Promise<boolean>).catch(() => false),+ setPassword: (linkId, password) =>+ (client.request(IPC.watchLinkSetPassword, linkId, password) as Promise<boolean>).catch(() => false),+ allowControl: (linkId) => (client.request(IPC.watchLinkAllowControl, linkId) as Promise<boolean>).catch(() => false),+ controlSupport: (nodeId) =>+ (client.request(IPC.watchLinkControlSupport, nodeId) as Promise<ControlSupport>).catch((): ControlSupport => 'unknown'),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),diff --git a/src/renderer/components/LiveLinkChip.surfaces.test.tsx b/src/renderer/components/LiveLinkChip.surfaces.test.tsxindex 4caf52ac6..1aa514a54 100644--- a/src/renderer/components/LiveLinkChip.surfaces.test.tsx+++ b/src/renderer/components/LiveLinkChip.surfaces.test.tsx@@ -40,7 +40,8 @@ const link = (over: Partial<WatchLinkView> = {}): WatchLinkView => ({expiresAt: Date.now() + 3_600_000,url: 'u',status: 'live',- viewers: [{ viewerId: 'v', name: null, joinedAt: 0, waiting: false }],+ viewers: [{ viewerId: 'v', name: null, joinedAt: 0, waiting: false, controlling: false, typing: false }],+ control: null,...over})const session: KanbanSession = { id: 'n1', title: 'build', color: '#fff', kind: 'terminal', spawn: {} } as KanbanSessiondiff --git a/src/renderer/components/LiveLinkChip.test.tsx b/src/renderer/components/LiveLinkChip.test.tsxindex 5436ebd90..2b8829856 100644--- a/src/renderer/components/LiveLinkChip.test.tsx+++ b/src/renderer/components/LiveLinkChip.test.tsx@@ -35,6 +35,7 @@ const link = (over: Partial<WatchLinkView> = {}): WatchLinkView => ({url: 'https://nodeterm.dev/s/L#1.secret',status: 'live',viewers: [],+ control: null,...over})const msg = (id: string, over: Partial<WatchChatMessage> = {}): WatchChatMessage => ({@@ -128,7 +129,7 @@ describe('LiveLinkChip', () => {// state (empty), so `renderToStaticMarkup` can never show a link.it('shows LIVE with the viewer count, as a no-drag button', () => {render(<LiveLinkChip nodeId="n1" source="local" className="extra" />)- setLinks([link({ viewers: [{ viewerId: 'v', name: null, joinedAt: 0, waiting: false }] })])+ setLinks([link({ viewers: [{ viewerId: 'v', name: null, joinedAt: 0, waiting: false, controlling: false, typing: false }] })])const c = chip()!expect(c.tagName).toBe('BUTTON')expect(c.textContent).toBe('LIVE · 1')@@ -162,7 +163,7 @@ describe('LiveLinkChip', () => {describe('LiveLinkPopover', () => {it('opens on click with role, time, the controls and the kick note', () => {render(<LiveLinkChip nodeId="n1" source="local" />)- setLinks([link({ viewers: [{ viewerId: 'v1', name: null, joinedAt: 0, waiting: false }, { viewerId: 'v2', name: 'Cy', joinedAt: 0, waiting: false }] })])+ setLinks([link({ viewers: [{ viewerId: 'v1', name: null, joinedAt: 0, waiting: false, controlling: false, typing: false }, { viewerId: 'v2', name: 'Cy', joinedAt: 0, waiting: false, controlling: false, typing: false }] })])click(chip()!)const p = pop()!expect(p.textContent).toContain('Can watch')@@ -202,8 +203,8 @@ describe('LiveLinkPopover', () => {setLinks([link({viewers: [- { viewerId: 'v1', name: null, joinedAt: 0, waiting: true },- { viewerId: 'v2', name: null, joinedAt: 0, waiting: false }+ { viewerId: 'v1', name: null, joinedAt: 0, waiting: true, controlling: false, typing: false },+ { viewerId: 'v2', name: null, joinedAt: 0, waiting: false, controlling: false, typing: false }]})])@@ -328,7 +329,7 @@ describe('LiveLinkPopover', () => {it('a failed Kick says so: not reached, or nobody to kick (M3)', async () => {render(<LiveLinkChip nodeId="n1" source="local" />)- setLinks([link({ viewers: [{ viewerId: 'v1', name: null, joinedAt: 0, waiting: false }] })])+ setLinks([link({ viewers: [{ viewerId: 'v1', name: null, joinedAt: 0, waiting: false, controlling: false, typing: false }] })])click(chip()!)api.kick.mockImplementationOnce(async () => {throw new Error('socket down')@@ -369,7 +370,7 @@ describe('LiveLinkPopover', () => {describe('LiveLinkPopover — Commenter chat', () => {it('renders every viewer string as text, never as markup', () => {render(<LiveLinkChip nodeId="n1" source="local" />)- setLinks([link({ role: 'commenter', label: '<b>Ada</b>', viewers: [{ viewerId: 'v', name: '<i>Eve</i>', joinedAt: 0, waiting: false }] })])+ setLinks([link({ role: 'commenter', label: '<b>Ada</b>', viewers: [{ viewerId: 'v', name: '<i>Eve</i>', joinedAt: 0, waiting: false, controlling: false, typing: false }] })])act(() => useWatchLinks.getState().addChat('L', msg('1', { name: '<u>Eve</u>', text: '<img src=x onerror=alert(1)>' })))click(chip()!)const p = pop()!diff --git a/src/renderer/components/LiveLinkDialog.test.tsx b/src/renderer/components/LiveLinkDialog.test.tsxindex 0f76938ab..6856b8341 100644--- a/src/renderer/components/LiveLinkDialog.test.tsx+++ b/src/renderer/components/LiveLinkDialog.test.tsx@@ -87,7 +87,8 @@ const created = (url = 'https://nodeterm.dev/s/abc#1.k'): CreateWatchLinkResultexpiresAt: Date.now() + 3_600_000,url,status: 'live',- viewers: []+ viewers: [],+ control: null}})diff --git a/src/renderer/components/LiveLinkDialog.tsx b/src/renderer/components/LiveLinkDialog.tsxindex 67be706ec..d6c63713d 100644--- a/src/renderer/components/LiveLinkDialog.tsx+++ b/src/renderer/components/LiveLinkDialog.tsx@@ -44,7 +44,8 @@ export type DialogState =phase: 'done'url: stringlinkId: string- expiresAt: number+ /** null: an Unlimited link. */+ expiresAt: number | nullcopied?: booleanstopping?: booleanerror?: string | nulldiff --git a/src/renderer/components/kanban/CardModal.liveLink.test.tsx b/src/renderer/components/kanban/CardModal.liveLink.test.tsxindex a9974223c..740b86b02 100644--- a/src/renderer/components/kanban/CardModal.liveLink.test.tsx+++ b/src/renderer/components/kanban/CardModal.liveLink.test.tsx@@ -44,6 +44,7 @@ const link = (over: Partial<WatchLinkView> = {}): WatchLinkView => ({url: 'https://nodeterm.dev/s/L#1.secret',status: 'live',viewers: [],+ control: null,...over})diff --git a/src/renderer/components/kanban/GlobalKanbanView.liveLink.test.tsx b/src/renderer/components/kanban/GlobalKanbanView.liveLink.test.tsxindex e8e8fea24..6b0e041ba 100644--- a/src/renderer/components/kanban/GlobalKanbanView.liveLink.test.tsx+++ b/src/renderer/components/kanban/GlobalKanbanView.liveLink.test.tsx@@ -38,7 +38,8 @@ const link = (nodeId: string): WatchLinkView => ({expiresAt: Date.now() + 3_600_000,url: 'u',status: 'live',- viewers: []+ viewers: [],+ control: null})let root: Root | null = nulldiff --git a/src/renderer/components/settings/sections/LiveLinksSection.test.tsx b/src/renderer/components/settings/sections/LiveLinksSection.test.tsxindex 6c3985075..5a888c224 100644--- a/src/renderer/components/settings/sections/LiveLinksSection.test.tsx+++ b/src/renderer/components/settings/sections/LiveLinksSection.test.tsx@@ -54,9 +54,10 @@ const link = (over: Partial<WatchLinkView> = {}): WatchLinkView => ({url: 'https://nodeterm.dev/s/L1#1.SECRET',status: 'live',viewers: [- { viewerId: 'a', name: null, joinedAt: 0, waiting: false },- { viewerId: 'b', name: null, joinedAt: 0, waiting: false }+ { viewerId: 'a', name: null, joinedAt: 0, waiting: false, controlling: false, typing: false },+ { viewerId: 'b', name: null, joinedAt: 0, waiting: false, controlling: false, typing: false }],+ control: null,...over})diff --git a/src/renderer/lib/liveLink.test.ts b/src/renderer/lib/liveLink.test.tsindex af2144771..0f0696555 100644--- a/src/renderer/lib/liveLink.test.ts+++ b/src/renderer/lib/liveLink.test.ts@@ -32,7 +32,7 @@ import {viewerName} from './liveLink'import type { CreateWatchLinkError, WatchLinkView } from '@shared/watch-link-types'-import { DEFAULT_WATCH_LINK_TTL, WATCH_LINK_TTLS } from '@shared/watch-link-types'+import { DEFAULT_WATCH_LINK_TTL, UNLIMITED_TTL, WATCH_LINK_TTLS } from '@shared/watch-link-types'import { commentSegments } from '@shared/board-comment'import { pinNeutralMachineNoun } from './testMachineNoun'@@ -49,9 +49,10 @@ const link = (over: Partial<WatchLinkView> = {}): WatchLinkView => ({url: 'u',status: 'live',viewers: [],+ control: null,...over})-const viewer = (id: string) => ({ viewerId: id, name: null, joinedAt: 0, waiting: false })+const viewer = (id: string) => ({ viewerId: id, name: null, joinedAt: 0, waiting: false, controlling: false, typing: false })const RELAY_SENTENCE = 'Live links are created on the machine that runs this terminal.'const R43 = 'Live links need a Pro license on this server — not available in the Server Edition yet'@@ -67,7 +68,10 @@ const ALL_ERRORS: CreateWatchLinkError[] = ['node-missing','bad-request','persist-failed',- 'unsupported'+ 'unsupported',+ 'ttl-unsupported',+ 'control-unsupported',+ 'bad-password']describe('chipView', () => {@@ -150,6 +154,10 @@ describe('time', () => {expect(formatRemaining(24 * 60 * MIN - 1, 0)).toBe('ends in 23 h 59 min')expect(formatRemaining(24 * 60 * MIN, 0)).toBe('ends in 24 h')})+ it('an Unlimited link has no end time', () => {+ expect(formatRemaining(null, 5)).toBe('No end time')+ expect(formatUntil(null, 5)).toBe('you stop it')+ })it('a clock time is hours and minutes, never seconds (H25)', () => {const at = new Date(2026, 9, 1, 15, 42, 37).getTime()expect(formatClock(at)).toBe(new Date(at).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' }))@@ -196,6 +204,14 @@ describe('createErrorMessage', () => {expect(createErrorMessage('limit-machine', 'desktop')).toBe('Stop a live link first — 5 can be active at once.')expect(createErrorMessage('relay-unavailable', 'desktop')).toBe('Live links need the installed app.')})++ it('the Unlimited and Control refusals', () => {+ expect(createErrorMessage('ttl-unsupported', 'desktop')).toBe('Unlimited links need a newer server. Pick an end time.')+ expect(createErrorMessage('control-unsupported', 'desktop')).toBe(+ "Control isn't available for this terminal: its Zellij session's key bindings would reach every session."+ )+ expect(createErrorMessage('bad-password', 'desktop')).toBe('The password must be 8 to 128 characters, with no line breaks.')+ })})describe('shareDisabledReason (H1)', () => {@@ -248,11 +264,12 @@ describe('noticeText', () => {describe('fixed lists (H19)', () => {it('TTL options come from the shared list, in order, with the labels the spec names', () => {- expect(TTL_OPTIONS.map((o) => o.value)).toEqual([...WATCH_LINK_TTLS])+ // Unlimited is in the shared list but not offered yet: the dialog does not explain it.+ expect(TTL_OPTIONS.map((o) => o.value)).toEqual(WATCH_LINK_TTLS.filter((v) => v !== UNLIMITED_TTL))expect(TTL_OPTIONS.map((o) => o.value)).toEqual([900, 3600, 28800, 86400])expect(TTL_OPTIONS.map((o) => o.label)).toEqual(['15 min', '1 hour', '8 hours', '24 hours'])expect(DEFAULT_TTL).toBe(DEFAULT_WATCH_LINK_TTL)- expect(ROLE_LABEL).toEqual({ viewer: 'Can watch', commenter: 'Can watch and chat' })+ expect(ROLE_LABEL).toEqual({ viewer: 'Can watch', commenter: 'Can watch and chat', controller: 'Can watch, chat and type' })})})@@ -276,9 +293,9 @@ describe('copy Task 17 reads (R47, R48, R52, H11, H23, H26)', () => {describe('viewerName', () => {it('a viewer who has not chatted is numbered; a name loses its bidi controls', () => {- expect(viewerName({ viewerId: 'a', name: null, joinedAt: 0, waiting: false }, 0)).toBe('Viewer 1')- expect(viewerName({ viewerId: 'a', name: ' ', joinedAt: 0, waiting: false }, 2)).toBe('Viewer 3')- expect(viewerName({ viewerId: 'a', name: 'Bob\u2066', joinedAt: 0, waiting: false }, 0)).toBe('Bob')+ expect(viewerName({ viewerId: 'a', name: null, joinedAt: 0, waiting: false, controlling: false, typing: false }, 0)).toBe('Viewer 1')+ expect(viewerName({ viewerId: 'a', name: ' ', joinedAt: 0, waiting: false, controlling: false, typing: false }, 2)).toBe('Viewer 3')+ expect(viewerName({ viewerId: 'a', name: 'Bob\u2066', joinedAt: 0, waiting: false, controlling: false, typing: false }, 0)).toBe('Bob')})})diff --git a/src/renderer/lib/liveLink.ts b/src/renderer/lib/liveLink.tsindex 3e4b57931..dcd79a083 100644--- a/src/renderer/lib/liveLink.ts+++ b/src/renderer/lib/liveLink.ts@@ -20,21 +20,30 @@ import {DEFAULT_WATCH_LINK_TTL,MAX_LINKS_PER_MACHINE,stripBidiControls,+ UNLIMITED_TTL,WATCH_LINK_TTLS} from '@shared/watch-link-types'import { otherMachines, thisMachine } from './machineName'-export const ROLE_LABEL: Record<WatchLinkRole, string> = { viewer: 'Can watch', commenter: 'Can watch and chat' }+export const ROLE_LABEL: Record<WatchLinkRole, string> = {+ viewer: 'Can watch',+ commenter: 'Can watch and chat',+ controller: 'Can watch, chat and type'+}/** A `Record` over the shared TTL list, so a TTL added there fails to compile here until it is named. */const TTL_LABEL: Record<WatchLinkTtl, string> = {900: '15 min',3600: '1 hour',28800: '8 hours',- 86400: '24 hours'+ 86400: '24 hours',+ 0: 'Unlimited'}-/** The create dialog's expiry choices — derived from the list core validates against (H19). */-export const TTL_OPTIONS: { value: WatchLinkTtl; label: string }[] = WATCH_LINK_TTLS.map((value) => ({+/** The create dialog's expiry choices — derived from the list core validates against (H19). Unlimited+ * is not offered yet: the dialog does not say what a link with no end time means. */+export const TTL_OPTIONS: { value: WatchLinkTtl; label: string }[] = WATCH_LINK_TTLS.filter(+ (value) => value !== UNLIMITED_TTL+).map((value) => ({value,label: TTL_LABEL[value]}))@@ -176,8 +185,10 @@ export function statusLine(link: Pick<WatchLinkView, 'status' | 'viewers'>): str}/** How long a link still runs. Hours AND minutes past the hour: a floored "1 h" for 1 h 59 min- * understated by up to an hour the one figure that says how long a broadcast goes on. */-export function formatRemaining(expiresAt: number, now: number): string {+ * understated by up to an hour the one figure that says how long a broadcast goes on. `null` is an+ * Unlimited link. */+export function formatRemaining(expiresAt: number | null, now: number): string {+ if (expiresAt === null) return 'No end time'const ms = expiresAt - nowif (ms <= 0) return 'ended'if (ms < 60_000) return 'ends in under a minute'@@ -197,9 +208,10 @@ export function formatClock(ms: number): string {* When a link ends, for "Anyone with this link can watch until …" (R64/M1). The time alone is the* time TODAY: a 24 h link made at 15:43 read "until 15:43", which looks like it ends now, and an 8 h* link past midnight read like today. So a different day is named — "tomorrow 15:43", or the weekday- * and date further out.+ * and date further out. An Unlimited link (`null`) runs "until you stop it".*/-export function formatUntil(expiresAt: number, now: number): string {+export function formatUntil(expiresAt: number | null, now: number): string {+ if (expiresAt === null) return 'you stop it'const end = new Date(expiresAt)const today = new Date(now)const dayStart = (d: Date): number => new Date(d.getFullYear(), d.getMonth(), d.getDate()).getTime()@@ -278,6 +290,12 @@ export function createErrorMessage(e: CreateWatchLinkError, surface: LiveLinkSurif (surface === 'server') return SERVER_EDITION_UNSUPPORTEDif (surface === 'relay') return RELAY_TAB_UNSUPPORTEDreturn "Live links can't be created here right now."+ case 'ttl-unsupported':+ return 'Unlimited links need a newer server. Pick an end time.'+ case 'control-unsupported':+ return "Control isn't available for this terminal: its Zellij session's key bindings would reach every session."+ case 'bad-password':+ return 'The password must be 8 to 128 characters, with no line breaks.'}}diff --git a/src/renderer/state/watchLinks.test.ts b/src/renderer/state/watchLinks.test.tsindex 53e3ae743..5518c346b 100644--- a/src/renderer/state/watchLinks.test.ts+++ b/src/renderer/state/watchLinks.test.ts@@ -13,6 +13,7 @@ const link = (id: string, nodeId: string, over: Partial<WatchLinkView> = {}): Waurl: 'u',status: 'live',viewers: [],+ control: null,...over})const msg = (id: string, from: 'viewer' | 'sharer' = 'viewer', at = 0): WatchChatMessage => ({@@ -39,13 +40,13 @@ describe('watchLinks store', () => {s.setLinks([link('a', 'n1'), link('c', 'n2')])const before = useWatchLinks.getState()// A fresh deserialized list (new objects, same content) except n2's link gained a viewer.- s.setLinks([link('a', 'n1'), link('c', 'n2', { viewers: [{ viewerId: 'v', name: null, joinedAt: 1, waiting: false }] })])+ s.setLinks([link('a', 'n1'), link('c', 'n2', { viewers: [{ viewerId: 'v', name: null, joinedAt: 1, waiting: false, controlling: false, typing: false }] })])const after = useWatchLinks.getState()expect(after.byNode.n1).toBe(before.byNode.n1)expect(after.byNode.n1[0]).toBe(before.byNode.n1[0])expect(after.byNode.n2).not.toBe(before.byNode.n2)// A push identical in content changes nothing at all.- s.setLinks([link('a', 'n1'), link('c', 'n2', { viewers: [{ viewerId: 'v', name: null, joinedAt: 1, waiting: false }] })])+ s.setLinks([link('a', 'n1'), link('c', 'n2', { viewers: [{ viewerId: 'v', name: null, joinedAt: 1, waiting: false, controlling: false, typing: false }] })])expect(useWatchLinks.getState()).toBe(after)})@@ -53,7 +54,7 @@ describe('watchLinks store', () => {// A fixture with every field of the type, iterated by key: a field added to WatchLinkView (and// to this fixture, which the type forces) is covered without editing the comparison.const base: WatchLinkView = link('a', 'n1', {- viewers: [{ viewerId: 'v', name: 'Eve', joinedAt: 5, waiting: false }]+ viewers: [{ viewerId: 'v', name: 'Eve', joinedAt: 5, waiting: false, controlling: false, typing: false }]})const bump = (v: unknown): unknown =>typeof v === 'number'@@ -64,7 +65,9 @@ describe('watchLinks store', () => {? !v: Array.isArray(v)? []- : v+ : v === null+ ? { changed: true }+ : vfor (const key of Object.keys(base) as (keyof WatchLinkView)[]) {useWatchLinks.setState({ links: [], byNode: {}, chats: {}, unread: {}, hydrated: false })useWatchLinks.getState().setLinks([base])diff --git a/src/shared/host-control.test.ts b/src/shared/host-control.test.tsindex 225dfc239..d889d4e4b 100644--- a/src/shared/host-control.test.ts+++ b/src/shared/host-control.test.ts@@ -1,6 +1,7 @@import { describe, it, expect } from 'vitest'import { IPC } from './ipc'import { HOST_ONLY_REFUSAL, isHostOnlyChannel } from './host-control'+import { WATCH_CHAT_CAST, WATCH_EVENT, WATCH_INPUT_CAST, WATCH_RELEASE_CAST, WATCH_UNLOCK_CAST } from './watch-link/protocol'/*** The ONE list both shells consult. It exists so the desktop's relay admission and any future@@ -67,7 +68,7 @@ describe('isHostOnlyChannel', () => {const owner = (Object.values(IPC) as unknown[]).filter((v): v is string => typeof v === 'string' && v.startsWith('watchLink:'))- expect(owner).toHaveLength(10)+ expect(owner).toHaveLength(14)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)@@ -75,6 +76,13 @@ describe('isHostOnlyChannel', () => {// 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)+ // Every viewer message, Control's included (unlock, input, release, the per-viewer control state+ // and the typing set).+ const viewer = [...Object.values(WATCH_EVENT), WATCH_CHAT_CAST, WATCH_UNLOCK_CAST, WATCH_INPUT_CAST, WATCH_RELEASE_CAST]+ for (const ch of viewer) {+ expect(ch.startsWith('watch:'), ch).toBe(true)+ expect(isHostOnlyChannel(ch), ch).toBe(false)+ }})it('carries the refusal wording the peer sees, so both shells answer identically', () => {diff --git a/src/shared/ipc.ts b/src/shared/ipc.tsindex 02f205abb..c1a023f7b 100644--- a/src/shared/ipc.ts+++ b/src/shared/ipc.ts@@ -280,6 +280,14 @@ export const IPC = {watchLinkChatSend: 'watchLink:chat-send',/** invoke: `(linkId)` → WatchChatMessage[] — this run's last messages (memory only). */watchLinkChatHistory: 'watchLink:chat-history',+ /** invoke: `(linkId, enabled)` → boolean — a Control link: turn typing on or off. */+ watchLinkSetControl: 'watchLink:set-control',+ /** invoke: `(linkId, password)` → boolean — a Control link: replace its password. */+ watchLinkSetPassword: 'watchLink:set-password',+ /** invoke: `(linkId)` → boolean — a Control link locked by wrong passwords: allow unlocking again. */+ watchLinkAllowControl: 'watchLink:allow-control',+ /** invoke: `(nodeId)` → ControlSupport — whether the node's terminal can take a Control link's input. */+ watchLinkControlSupport: 'watchLink:control-support',/** core → owner clients only: the full list on every change, never a delta. */watchLinkState: 'watchLink:state',/** core → owner clients only: `(linkId, WatchChatMessage)`. */diff --git a/src/shared/watch-link-password.test.ts b/src/shared/watch-link-password.test.tsnew file mode 100644index 000000000..a32e2ceb9--- /dev/null+++ b/src/shared/watch-link-password.test.ts@@ -0,0 +1,20 @@+import { describe, expect, it } from 'vitest'+import { generateControlPassword, controlPasswordProblem, CONTROL_PASSWORD_ALPHABET, CONTROL_PASSWORD_LENGTH } from './watch-link-password'++describe('control password', () => {+ it('generates 16 symbols from the 32-symbol alphabet, uniformly (byte & 31)', () => {+ const pw = generateControlPassword((n) => Uint8Array.from({ length: n }, (_, i) => i * 37))+ expect(pw).toHaveLength(CONTROL_PASSWORD_LENGTH)+ expect([...pw].every((c) => CONTROL_PASSWORD_ALPHABET.includes(c))).toBe(true)+ expect(CONTROL_PASSWORD_ALPHABET).toHaveLength(32)+ expect(/[ilou]/.test(CONTROL_PASSWORD_ALPHABET)).toBe(false)+ })+ it('validates typed passwords', () => {+ expect(controlPasswordProblem('1234567')).toBe('short')+ expect(controlPasswordProblem('12345678')).toBeNull()+ expect(controlPasswordProblem('🙂'.repeat(8))).toBeNull() // code points, not UTF-16 units+ expect(controlPasswordProblem('x'.repeat(129))).toBe('long')+ expect(controlPasswordProblem('abcdefg\n')).toBe('control')+ expect(controlPasswordProblem(12345678)).toBe('type')+ })+})diff --git a/src/shared/watch-link-password.ts b/src/shared/watch-link-password.tsnew file mode 100644index 000000000..60a6026f8--- /dev/null+++ b/src/shared/watch-link-password.ts@@ -0,0 +1,38 @@+// A Control link's password, OWNER side: the generator and the validator the create dialog and the+// core service share (docs/live-links.md). Not in src/shared/watch-link/ on purpose: the viewer page+// never makes or judges a password, it only carries one inside the E2E tunnel (`PASSWORD_MAX`).+// The plaintext is never stored; core keeps a scrypt hash only (src/core/watch-link/password.ts).+import { PASSWORD_MAX } from './watch-link/protocol'++/** The shortest password a person may type, in code points. The longest is the unlock cast's own cap,+ * `PASSWORD_MAX` (128), so a password the owner set can always be sent by a viewer. */+export const CONTROL_PASSWORD_MIN = 8+/** What Generate makes: 16 symbols of 5 bits each, 80 bits. */+export const CONTROL_PASSWORD_LENGTH = 16+/** Crockford's base32 in lower case: no i, l, o or u, so nothing reads as another symbol. */+export const CONTROL_PASSWORD_ALPHABET = '0123456789abcdefghjkmnpqrstvwxyz'++/** `randomBytes` is the caller's CSPRNG (`crypto.getRandomValues` in the renderer). 32 symbols divide+ * 256, so `byte & 31` picks every symbol with the same probability. */+export function generateControlPassword(randomBytes: (n: number) => Uint8Array): string {+ const b = randomBytes(CONTROL_PASSWORD_LENGTH)+ let out = ''+ for (let i = 0; i < CONTROL_PASSWORD_LENGTH; i++) out += CONTROL_PASSWORD_ALPHABET[b[i] & 31]+ return out+}++export type ControlPasswordProblem = 'type' | 'short' | 'long' | 'control'+/** Why a typed password is refused, or null when it is acceptable. Lengths count code points, so an+ * emoji is one character, as a person counts it. C0/C1 controls (a pasted line break) are refused:+ * the viewer types the password into a one-line field and could never send one back. */+export function controlPasswordProblem(pw: unknown): ControlPasswordProblem | null {+ if (typeof pw !== 'string') return 'type'+ // A code point is at most two UTF-16 units: past this many units it is too long whatever it holds,+ // and an IPC caller's megabyte string is never split into an array of code points.+ if (pw.length > PASSWORD_MAX * 2) return 'long'+ const n = Array.from(pw).length+ if (n < CONTROL_PASSWORD_MIN) return 'short'+ if (n > PASSWORD_MAX) return 'long'+ if (/[\u0000-\u001f\u007f-\u009f]/.test(pw)) return 'control'+ return null+}diff --git a/src/shared/watch-link-types.ts b/src/shared/watch-link-types.tsindex 68a320d9d..895cbe7ca 100644--- a/src/shared/watch-link-types.ts+++ b/src/shared/watch-link-types.ts@@ -6,9 +6,12 @@ import type { WatchChatMessage, WatchLinkRole } from './watch-link/protocol'import { BIDI_CONTROL_CHARS } from './presence'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+/** The expiry choices, in seconds: 15 min, 1 h (the default), 8 h, 24 h, and Unlimited (`0`): no end+ * time, the link lives until it is stopped (`expiresAt: null`). No other value is accepted. */+export const WATCH_LINK_TTLS = [900, 3600, 28800, 86400, 0] as constexport type WatchLinkTtl = (typeof WATCH_LINK_TTLS)[number]+/** The wire value of Unlimited. */+export const UNLIMITED_TTL = 0export const DEFAULT_WATCH_LINK_TTL: WatchLinkTtl = 3600/** Active links per machine (spec D6). */export const MAX_LINKS_PER_MACHINE = 5@@ -23,6 +26,9 @@ export interface CreateWatchLinkRequest {ttlSeconds: WatchLinkTtllabel: stringtitle: string+ /** A Control link's password, required for that role (`controlPasswordProblem` must pass) and+ * ignored for the others. Core keeps only its hash; the plaintext is never stored or logged. */+ password?: string}/**@@ -43,6 +49,10 @@ export interface CreateWatchLinkRequest {* 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.+ * - `ttl-unsupported` — the API refused an Unlimited link (an older server): pick an end time.+ * - `control-unsupported` — a Control link on a terminal that cannot take typed input safely (a+ * Zellij session, whose key bindings would reach every session).+ * - `bad-password` — a Control link without an acceptable password.*/export type CreateWatchLinkError =| 'not-entitled'@@ -57,6 +67,9 @@ export type CreateWatchLinkError =| 'bad-request'| 'persist-failed'| 'unsupported'+ | 'ttl-unsupported'+ | 'control-unsupported'+ | 'bad-password'export type CreateWatchLinkResult = { ok: true; link: WatchLinkView } | { ok: false; error: CreateWatchLinkError }export interface WatchLinkViewerView {@@ -68,6 +81,19 @@ export interface WatchLinkViewerView {* own (Windows' session host, no local tmux, Zellij) the terminal must be OPEN in this app. The* owner is told ("Viewers are waiting — open this terminal in nodeterm to let them watch"). */waiting: boolean+ /** Unlocked a Control link with its password: may type until it disconnects, is kicked, or the+ * owner turns typing off. Always false on the other roles. */+ controlling: boolean+ /** Typed in the last few seconds (the chip's "1 typing"). */+ typing: boolean+}++/** A Control link's owner-side state. */+export interface WatchLinkControlView {+ /** Typing is on: a viewer with the password may unlock. */+ enabled: boolean+ /** Too many wrong passwords across the link: nobody may unlock until the owner allows it again. */+ locked: boolean}export interface WatchLinkView {@@ -77,7 +103,8 @@ export interface WatchLinkView {label: stringtitle: stringcreatedAt: number- expiresAt: number+ /** Epoch ms; null for an Unlimited link (no end time). */+ expiresAt: number | null/** 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");@@ -85,6 +112,8 @@ export interface WatchLinkView {* may not relay) — the chip "refused". */status: 'live' | 'reconnecting' | 'refused'viewers: WatchLinkViewerView[]+ /** Present exactly for a Control link. */+ control: WatchLinkControlView | null}export type WatchLinkNotice =@@ -98,6 +127,15 @@ export type WatchLinkNotice =* sealed earlier stay saved — sent after that create). Copy: "only the link just created is not* saved" unless the renderer knows it is the first cause. */| { kind: 'not-persistent' }+ /** A viewer unlocked a Control link. `name` is the name it gave itself: a claim, shown as one. */+ | { kind: 'control-taken'; linkId: string; nodeId: string; title: string; name: string }+ /** Too many wrong passwords: control is locked on that link until the owner allows it again. */+ | { kind: 'control-locked'; linkId: string; nodeId: string; title: string }++/** Whether a node's terminal can take a Control link's input: `ok` (tmux, the Windows session host, a+ * plain shell), `unsupported` (Zellij — its key bindings are session-wide), or `unknown` (nothing+ * can tell right now; the dialog keeps Control offered and the create decides). */+export type ControlSupport = 'ok' | 'unsupported' | 'unknown'/*** What "Stop all" reached. THIS machine's links always stop at once, before the answer; the answer@@ -124,6 +162,15 @@ export interface WatchLinkApi {/** 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[]>+ /** A Control link: turn typing on or off. False when the link is not a live Control link or the+ * change could not be saved. */+ setControl(linkId: string, enabled: boolean): Promise<boolean>+ /** A Control link: replace its password (every current controller drops back to watching). */+ setPassword(linkId: string, password: string): Promise<boolean>+ /** A Control link locked by wrong passwords: allow unlocking again (and reset the count). */+ allowControl(linkId: string): Promise<boolean>+ /** Whether this node's terminal can take a Control link's input (the dialog asks once on open). */+ controlSupport(nodeId: string): Promise<ControlSupport>/** The full list on every change, never a delta. */onState(cb: (links: WatchLinkView[]) => void): () => voidonChat(cb: (linkId: string, msg: WatchChatMessage) => void): () => voiddiff --git a/src/shared/watch-link/client.ts b/src/shared/watch-link/client.tsindex fe4c57771..3ef635b79 100644--- a/src/shared/watch-link/client.ts+++ b/src/shared/watch-link/client.ts@@ -1,14 +1,15 @@// The browser half of a live link: the CLIENT role of src/core/relay/relay-socket.ts (handshake,// sealed frames, keepalive) plus the trust gate's client obligation (send our own trust:confirm,-// open only once the host's arrives). Nothing here writes to the terminal: after the handshake it-// sends only its own trust:confirm, keepalives, and the viewer's chat casts (`sendChat`). Whether a-// chat cast is accepted is the link host's decision, and an obligation on it: the link host (Task 11)-// accepts one only on a Commenter link. Nothing on this side enforces that.+// open only once the host's arrives). After the handshake it sends only its own trust:confirm,+// keepalives, and the viewer's casts: chat (`sendChat`) and, on a Control link, unlock / input /+// release. Whether a cast is accepted is the link host's decision, and an obligation on it: chat only+// on a Commenter or Control link, input only from a viewer that unlocked with the link's password.+// Nothing on this side enforces that; `sendInput`'s size cap only keeps an oversized cast off the wire.import nacl from 'tweetnacl'import { b64ToBytes, bytesToB64, concatBytes, utf8 } from './bytes'import { hkdfSha256 } from './hkdf'import type { WatchLinkKeys } from './keys'-import { WATCH_CHAT_CAST } from './protocol'+import { INPUT_MAX, WATCH_CHAT_CAST, WATCH_INPUT_CAST, WATCH_RELEASE_CAST, WATCH_UNLOCK_CAST } from './protocol'import {NONCE_BYTES, RELAY_SESSION_INFO, ROLE_CLIENT, ROLE_HOST, TAG_RPC, TAG_TUNNEL_BIN, TAG_TUNNEL_TEXT,decodePtyFrame, openBox, parseTunnelJson, readHeader, sealBox, withHeader@@ -44,6 +45,13 @@ export interface WatchClientEvents {*/export interface WatchClient {sendChat(name: string, text: string): boolean+ /** Ask to type, with the link's password. The answer is a `watch:control` event, not a return value. */+ unlock(name: string, password: string): boolean+ /** Typed bytes, sent as given. Refused here (false, nothing sent) when empty, not a string, or longer+ * than `INPUT_MAX` UTF-16 units. */+ sendInput(data: string): boolean+ /** Stop typing: back to watching. */+ release(): booleanclose(): voidisOpen(): boolean}@@ -202,11 +210,19 @@ export function connectWatchClient(opts: {})socket.send(JSON.stringify({ type: 'e2ee_hello', publicKeyB64: bytesToB64(keys.viewer.publicKey), nonceB64: bytesToB64(ourNonce) }))+ function cast(method: string, args: unknown[]): boolean {+ if (!opened || state !== 'ready') return false+ return sendSealed(TAG_TUNNEL_TEXT, utf8(JSON.stringify({ t: 'cast', method, args })))+ }+return {- sendChat(name, text) {- if (!opened || state !== 'ready') return false- return sendSealed(TAG_TUNNEL_TEXT, utf8(JSON.stringify({ t: 'cast', method: WATCH_CHAT_CAST, args: [{ name, text }] })))+ sendChat: (name, text) => cast(WATCH_CHAT_CAST, [{ name, text }]),+ unlock: (name, password) => cast(WATCH_UNLOCK_CAST, [{ name, password }]),+ sendInput(data) {+ if (typeof data !== 'string' || data.length === 0 || data.length > INPUT_MAX) return false+ return cast(WATCH_INPUT_CAST, [{ data }])},+ release: () => cast(WATCH_RELEASE_CAST, []),close() {shutdown()socket.close()diff --git a/src/shared/watch-link/protocol.control.test.ts b/src/shared/watch-link/protocol.control.test.tsnew file mode 100644index 000000000..0e5c315aa--- /dev/null+++ b/src/shared/watch-link/protocol.control.test.ts@@ -0,0 +1,21 @@+import { describe, expect, it } from 'vitest'+import { readControlEvent, readTypingNames, isWatchEndReason, TYPING_NAMES_MAX } from './protocol'++describe('control protocol readers', () => {+ it('accepts only known states and reasons', () => {+ expect(readControlEvent({ state: 'controlling' })).toEqual({ state: 'controlling' })+ expect(readControlEvent({ state: 'available', reason: 'wrong' })).toEqual({ state: 'available', reason: 'wrong' })+ expect(readControlEvent({ state: 'god' })).toBeNull()+ expect(readControlEvent({ state: 'off', reason: 'nope' })).toEqual({ state: 'off' })+ expect(readControlEvent(null)).toBeNull()+ })+ it('sanitizes and bounds typing names', () => {+ const many = Array.from({ length: 30 }, (_, i) => `n${i}`)+ expect(readTypingNames({ names: many })).toHaveLength(TYPING_NAMES_MAX)+ expect(readTypingNames({ names: ['ab', 'ab', 7, ' '] })).toEqual(['ab'])+ expect(readTypingNames('x')).toEqual([])+ })+ it('knows the new end reason', () => {+ expect(isWatchEndReason('attempts')).toBe(true)+ })+})diff --git a/src/shared/watch-link/protocol.ts b/src/shared/watch-link/protocol.tsindex 1875b659a..d7b469d35 100644--- a/src/shared/watch-link/protocol.ts+++ b/src/shared/watch-link/protocol.ts@@ -9,13 +9,28 @@ export const WATCH_EVENT = {keyframe: 'watch:keyframe',waiting: 'watch:waiting',chat: 'watch:chat',- end: 'watch:end'+ end: 'watch:end',+ /** To ONE viewer, never a broadcast: its control state, after an unlock or when control changes+ * under it (turned off, locked). The initial state rides `watch:meta`. */+ control: 'watch:control',+ /** To every joined viewer: who typed in the last few seconds (`WatchTypingEvent`). */+ typing: 'watch:typing'} as const-/** The one message a viewer may send (Commenter links only). */+/** A viewer's chat line (Commenter and Control links). */export const WATCH_CHAT_CAST = 'watch:chat'+/** Control links only: `{ name, password }`. Answered to that viewer alone with `watch:control`. */+export const WATCH_UNLOCK_CAST = 'watch:unlock'+/** Control links only, from a controlling viewer: `{ data }`, at most `INPUT_MAX` UTF-16 units. */+export const WATCH_INPUT_CAST = 'watch:input'+/** Control links only: drop the sender back to watching. No arguments. */+export const WATCH_RELEASE_CAST = 'watch:release'-export type WatchLinkRole = 'viewer' | 'commenter'-export const WATCH_END_REASONS = ['revoked', 'expired', 'node-gone', 'session-ended', 'host-stopping', 'kicked'] as const+/** A Control link (`controller`) is a Commenter link plus typing for whoever unlocks it with the+ * link's password. Every addition to this protocol is additive, so `WATCH_PROTOCOL_VERSION` stays 1:+ * an older viewer page ignores the new events and simply cannot take control. */+export type WatchLinkRole = 'viewer' | 'commenter' | 'controller'+/** `attempts`: too many wrong passwords on this connection (it may reconnect through the link). */+export const WATCH_END_REASONS = ['revoked', 'expired', 'node-gone', 'session-ended', 'host-stopping', 'kicked', 'attempts'] as constexport type WatchLinkEndReason = (typeof WATCH_END_REASONS)[number]export function isWatchEndReason(x: unknown): x is WatchLinkEndReason {return typeof x === 'string' && (WATCH_END_REASONS as readonly string[]).includes(x)@@ -27,10 +42,62 @@ export interface WatchMeta {/** Sharer-supplied; render as text, marked as set by the sharer. */label: stringtitle: string- /** Epoch ms on the host's clock, corrected to the server's. */- expiresAt: number+ /** Epoch ms on the host's clock, corrected to the server's; `null` for a link with no end time. */+ expiresAt: number | nullcols: numberrows: number+ /** A Control link's state for THIS viewer at join; absent on every other role. */+ control?: WatchControlEvent+}++/** `controlling`: this viewer may type. `available`: a Control link this viewer may unlock.+ * `off`: the owner turned typing off. `locked`: too many wrong passwords across the link. */+export type WatchControlState = 'controlling' | 'available' | 'off' | 'locked'+/** Why an unlock was refused or control was taken away: `wrong` password, the link is `locked`,+ * typing is `off`, an attempt `too-soon` after the last, the terminal is `unsupported`, or input was+ * `dropped` (typing too fast, or no session to type into). */+export type WatchControlReason = 'wrong' | 'locked' | 'off' | 'too-soon' | 'unsupported' | 'dropped'+const CONTROL_STATES: readonly WatchControlState[] = ['controlling', 'available', 'off', 'locked']+const CONTROL_REASONS: readonly WatchControlReason[] = ['wrong', 'locked', 'off', 'too-soon', 'unsupported', 'dropped']+export interface WatchControlEvent {+ state: WatchControlState+ reason?: WatchControlReason+}+export interface WatchTypingEvent {+ /** Self-chosen names: claims, shown as such. */+ names: string[]+}++/** The largest `watch:input` cast, in UTF-16 units. */+export const INPUT_MAX = 16384+/** The longest password the unlock cast carries, in code points. */+export const PASSWORD_MAX = 128+/** The most names one `watch:typing` event carries. */+export const TYPING_NAMES_MAX = 10++/** A `watch:control` payload (or `WatchMeta.control`), or null when it is not one. An unknown reason+ * is dropped, never the state with it. */+export function readControlEvent(x: unknown): WatchControlEvent | null {+ if (!x || typeof x !== 'object') return null+ const { state, reason } = x as Record<string, unknown>+ if (!(CONTROL_STATES as readonly unknown[]).includes(state)) return null+ const out: WatchControlEvent = { state: state as WatchControlState }+ if ((CONTROL_REASONS as readonly unknown[]).includes(reason)) out.reason = reason as WatchControlReason+ return out+}+/** A `watch:typing` payload's names: each one a clean chat name, deduplicated in order, at most+ * `TYPING_NAMES_MAX`. Anything else reads as nobody typing. */+export function readTypingNames(x: unknown): string[] {+ if (!x || typeof x !== 'object') return []+ const names = (x as Record<string, unknown>).names+ if (!Array.isArray(names)) return []+ const out: string[] = []+ for (const raw of names) {+ if (out.length >= TYPING_NAMES_MAX) break+ const name = sanitizeChatName(raw)+ if (name !== null && !out.includes(name)) out.push(name)+ }+ return out}export interface WatchKeyframe {sessionId: string