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): owner controls, unlimited records and the input seam in both shells
review9c23e2002853
diff --git a/src/core/pty-manager.control-input.test.ts b/src/core/pty-manager.control-input.test.tsindex 5b23bf91e..8bffeafe1 100644--- a/src/core/pty-manager.control-input.test.ts+++ b/src/core/pty-manager.control-input.test.ts@@ -10,7 +10,8 @@ import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'import { initPlatform, resetPlatformForTests } from './platform'import { fakePlatform } from './platform-fake'import { TMUX_SOCKET, sessionName } from './tmux-naming'-import { keysCommandText, remoteKeysArgs } from './watch-link/pane-input'+import { PANE_INPUT_DEADLINE_MS, keysCommandText, remoteKeysArgs } from './watch-link/pane-input'+import { INPUT_DELIVERY_TIMEOUT_MS } from './watch-link/link-host'import { DEFAULT_SETTINGS } from '../shared/types'type Call = { file: string; args: string[]; input: string | undefined }@@ -111,7 +112,10 @@ beforeEach(() => {vi.resetModules()initPlatform(fakePlatform())})-afterEach(() => resetPlatformForTests())+afterEach(() => {+ vi.useRealTimers()+ resetPlatformForTests()+})describe('watcherInputRoute', () => {it('routes each backend to the pane, or refuses', async () => {@@ -361,6 +365,26 @@ describe('nodeControlSupport', () => {expect((await manager(null)).mgr.nodeControlSupport('node-new')).toBe('ok')})+ // A node with no session anywhere would be CREATED in the selected backend, and a Zellij session+ // refuses control. A live (or released) session still answers for itself: the backend follows the+ // session that exists.+ it('no session or record on a machine whose new sessions are Zellij: unsupported', async () => {+ const zellij = { ...DEFAULT_SETTINGS, tmuxEnabled: true, sessionBackend: 'zellij' as const }+ const fresh = await manager(null)+ fresh.mgr.getSettings = () => zellij+ expect(fresh.mgr.nodeControlSupport('node-new')).toBe('unsupported')+ const noTmux = await manager(null, null)+ noTmux.mgr.getSettings = () => zellij+ expect(noTmux.mgr.nodeControlSupport('node-new')).toBe('unsupported')+ const live = await manager({})+ live.mgr.getSettings = () => zellij+ expect(live.mgr.nodeControlSupport(NODE)).toBe('ok')+ const released = await manager(null)+ released.mgr.getSettings = () => zellij+ released.mgr.released.set(NODE, { sessionId: 'old', remote: false })+ expect(released.mgr.nodeControlSupport(NODE)).toBe('ok')+ })+it('no session, no record, no tmux to make one: unknown', async () => {expect((await manager(null, null)).mgr.nodeControlSupport('node-new')).toBe('unknown')const off = await manager(null)@@ -368,3 +392,51 @@ describe('nodeControlSupport', () => {expect(off.mgr.nodeControlSupport('node-new')).toBe('unknown')})})++// Every step of a session's input chain settles in bounded time, whatever the route: a delivery that+// never answers would otherwise hold the chain — and every later chunk would wait behind it, to land+// long after the link host (which gives up at INPUT_DELIVERY_TIMEOUT_MS) told its controller it was+// dropped.+describe('controlInput — bounded on every route', () => {+ it('the deadline is the link host\'s own', () => {+ expect(PANE_INPUT_DEADLINE_MS).toBe(INPUT_DELIVERY_TIMEOUT_MS)+ })++ for (const [route, session] of [+ ['a direct Windows pane', 'pane'],+ ['the session host', 'host']+ ] as const) {+ it(`${route}: a paste that never answers is false at the deadline, and the chain moves on`, async () => {+ const sendText = vi.fn((): Promise<boolean> => new Promise(() => {}))+ if (session === 'host') hostSendKeys.mockImplementation(() => new Promise(() => {}))+ const { mgr } = await manager(+ session === 'pane' ? { nativeWindowsPane: { sendText }, tmuxBacked: false, persistKey: undefined } : { sessionHost: true }+ )+ vi.useFakeTimers()+ let answer: boolean | null = null+ void mgr.controlInput('sess-1', { kind: 'paste', text: 'a' }).then((v) => (answer = v))+ await vi.advanceTimersByTimeAsync(PANE_INPUT_DEADLINE_MS - 1)+ expect(answer).toBeNull()+ await vi.advanceTimersByTimeAsync(1)+ expect(answer).toBe(false)+ sendText.mockImplementation(async () => true)+ hostSendKeys.mockImplementation(async () => true)+ expect(await mgr.controlInput('sess-1', { kind: 'paste', text: 'b' })).toBe(true)+ })+ }++ it('a chunk that could not START before the deadline is dropped undelivered: its caller gave up on it', async () => {+ const sendText = vi.fn((): Promise<boolean> => new Promise(() => {}))+ const { mgr } = await manager({ nativeWindowsPane: { sendText }, tmuxBacked: false, persistKey: undefined })+ vi.useFakeTimers()+ const first = mgr.controlInput('sess-1', { kind: 'paste', text: 'a' })+ const second = mgr.controlInput('sess-1', { kind: 'paste', text: 'b' }) // queued behind the hung one+ await vi.advanceTimersByTimeAsync(PANE_INPUT_DEADLINE_MS)+ expect(await first).toBe(false)+ expect(await second).toBe(false)+ expect(sendText).toHaveBeenCalledTimes(1) // 'b' never reached the pane+ sendText.mockImplementation(async () => true)+ expect(await mgr.controlInput('sess-1', { kind: 'paste', text: 'c' })).toBe(true)+ expect(sendText).toHaveBeenLastCalledWith('c', false)+ })+})diff --git a/src/core/pty-manager.ts b/src/core/pty-manager.tsindex abfc16771..e812e1e14 100644--- a/src/core/pty-manager.ts+++ b/src/core/pty-manager.ts@@ -68,11 +68,13 @@ import {type VisibleCapture} from './watch-link/capture-route'import {+ PANE_INPUT_DEADLINE_MS,controlInputPlan,remoteControlInputPlan,type ControlInputChunk,type WatcherInputRoute} from './watch-link/pane-input'+import type { ControlSupport } from '../shared/watch-link-types'import { sanitizePasteText } from './paste-injection'import {localWatcherAttachArgs,@@ -310,6 +312,24 @@ function runWithStdin(file: string, args: readonly string[], input: string): Proreturn p as unknown as Promise<unknown>}+/** `p`'s answer, or false once `ms` passed (the timer never holds the process). A rejection is false. */+function settleWithin(p: Promise<boolean>, ms: number): Promise<boolean> {+ return new Promise<boolean>((resolve) => {+ const timer = setTimeout(() => resolve(false), ms)+ timer.unref?.()+ p.then(+ (v) => {+ clearTimeout(timer)+ resolve(v)+ },+ () => {+ clearTimeout(timer)+ resolve(false)+ }+ )+ })+}+// Minimal tmux config so the user's ~/.tmux.conf never interferes. The tmux server// (under our socket) keeps sessions alive while no client is attached, which is what// gives us continuity across node remounts and full app restarts.@@ -4968,10 +4988,25 @@ export class PtyManager {* settled, so keys and pastes reach the pane in the order they were typed. The Session is re-read* inside each step (it can be gone by then → false), and the tmux name is resolved from it, never* from the caller. A false is never retried here (a timed-out delivery may well have run).+ *+ * BOUNDED on every route (PANE_INPUT_DEADLINE_MS, the link host's own deadline). The tmux and SSH+ * routes are bounded already (`runWithStdin`: PROC_TIMEOUT_MS), the session host's request by its+ * own timeout once connected — but its reconnect can wait on a host that is still starting, and a+ * step that never settled would hold every later chunk behind it, to land long after the link host+ * told its controller it was dropped. So a step answers false at the deadline (a late delivery may+ * still land, as with any timed-out one), and a chunk that could not even START by its deadline is+ * dropped undelivered: whoever handed it over has given up on it.*/controlInput(sessionId: string, chunk: ControlInputChunk): Promise<boolean> {+ const handedAt = Date.now()const prev = this.controlInputChains.get(sessionId) ?? Promise.resolve(true)- const step = prev.then(() => this.deliverControlInput(sessionId, chunk)).catch(() => false)+ const step = prev+ .then(() =>+ Date.now() - handedAt >= PANE_INPUT_DEADLINE_MS+ ? false+ : settleWithin(this.deliverControlInput(sessionId, chunk), PANE_INPUT_DEADLINE_MS)+ )+ .catch(() => false)this.controlInputChains.set(sessionId, step)void step.then(() => {if (this.controlInputChains.get(sessionId) === step) this.controlInputChains.delete(sessionId)@@ -5038,13 +5073,18 @@ export class PtyManager {/*** Can a live link offer Control on this node? `unsupported` for a Zellij node (session-wide key- * bindings); `ok` when a session for it is live or released (its pane can be reached), or when a- * new node would be tmux-backed here; `unknown` otherwise (nothing to tell from yet).+ * bindings), or a node with no session on a machine whose new sessions are Zellij; `ok` when a+ * session for it is live or released (its pane can be reached), or when a new node would be+ * tmux-backed here; `unknown` otherwise (nothing to tell from yet).*/- nodeControlSupport(persistKey: string): 'ok' | 'unsupported' | 'unknown' {+ nodeControlSupport(persistKey: string): ControlSupport {const live = this.liveSessionForPersistKey(persistKey)if (this.zellijKeys.has(persistKey) || live?.zellij) return 'unsupported'if (live || this.released.has(persistKey)) return 'ok'+ // No session here: a new one would be created in the SELECTED backend, and a Zellij one refuses+ // control. (A node whose tmux session is warm but not held by this process reads the same way+ // until it is mounted; the live branch above answers it then.)+ if (this.zellijSelected()) return 'unsupported'if (this.tmuxPath && this.getSettings().tmuxEnabled) return 'ok'return 'unknown'}diff --git a/src/core/relay/scoped-guest-policy.test.ts b/src/core/relay/scoped-guest-policy.test.tsindex 6ca1df999..85fdbf5ae 100644--- a/src/core/relay/scoped-guest-policy.test.ts+++ b/src/core/relay/scoped-guest-policy.test.ts@@ -264,6 +264,11 @@ describe('relay host — host-only channels refused to every peer', () => {(v): v is string => typeof v === 'string' && v.startsWith('watchLink:'))expect(methods).toHaveLength(14)+ // The Control link's owner verbs are among them, by name: a peer must never set a link's+ // password, turn its typing on, clear its lock, or probe a terminal for it.+ for (const ch of [IPC.watchLinkSetControl, IPC.watchLinkSetPassword, IPC.watchLinkAllowControl, IPC.watchLinkControlSupport]) {+ expect(methods, ch).toContain(ch)+ }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/api.test.ts b/src/core/watch-link/api.test.tsindex 7877ee531..c9a592553 100644--- a/src/core/watch-link/api.test.ts+++ b/src/core/watch-link/api.test.ts@@ -89,6 +89,32 @@ describe('createWatchLinkApi', () => {}})+ // Unlimited (`ttlSeconds: 0`): the server answers `expiresAt: null` — accepted for that request and+ // for no other. A null to a finite request, or no expiry at all, is a malformed reply.+ it('create with ttlSeconds 0 accepts a null expiry, and only for that request', async () => {+ const { a, calls } = api(() => res(200, { linkId: LID, expiresAt: null }))+ expect(await a.create('ent', 'h', 0)).toEqual({ ok: true, linkId: LID, expiresAt: null })+ expect(calls[0].body).toEqual({ entitlement: 'ent', joinKeyHash: 'h', ttlSeconds: 0 })+ for (const ttl of [900, 3600, 86400]) {+ expect(await api(() => res(200, { linkId: LID, expiresAt: null })).a.create('e', 'h', ttl)).toEqual({ ok: false, error: 'network' })+ }+ expect(await api(() => res(200, { linkId: LID })).a.create('e', 'h', 0)).toEqual({ ok: false, error: 'network' })+ expect(await api(() => res(200, { linkId: LID, expiresAt: 'never' })).a.create('e', 'h', 0)).toEqual({ ok: false, error: 'network' })+ })++ it('create with ttlSeconds 0 answered with an end time (a capped server) re-anchors it like any other', async () => {+ const serverNow = Date.parse('Tue, 29 Sep 2026 10:00:00 GMT')+ const { a } = api(() => res(200, { linkId: LID, expiresAt: serverNow / 1000 + 86400 }, { date: new Date(serverNow).toUTCString() }), 5_000)+ expect(await a.create('ent', 'h', 0)).toEqual({ ok: true, linkId: LID, expiresAt: 5_000 + 86_400_000 })+ })++ it('a 400 bad_ttl to an Unlimited request is ttl-unsupported (an older server); any other 400 stays bad-request', async () => {+ expect(await api(() => res(400, { error: 'bad_ttl' })).a.create('e', 'h', 0)).toEqual({ ok: false, error: 'ttl-unsupported' })+ expect(await api(() => res(400, { error: 'bad_ttl' })).a.create('e', 'h', 3600)).toEqual({ ok: false, error: 'bad-request' })+ expect(await api(() => res(400, { error: 'bad_request' })).a.create('e', 'h', 0)).toEqual({ ok: false, error: 'bad-request' })+ expect(await api(() => res(400, null)).a.create('e', 'h', 0)).toEqual({ ok: false, error: 'bad-request' })+ })+it('maps create errors', async () => {const cases: [Response, string][] = [[res(402, { error: 'not_entitled' }), 'not-entitled'],diff --git a/src/core/watch-link/api.ts b/src/core/watch-link/api.tsindex d28777e5e..e564d695c 100644--- a/src/core/watch-link/api.ts+++ b/src/core/watch-link/api.ts@@ -3,10 +3,25 @@import { tokenTtlMs, type MintResult } from '../relay/host-token'import { LINK_ID_RE } from '../../shared/watch-link/link'-export type CreateError = 'not-entitled' | 'limit-active' | 'limit-daily' | 'rate-limited' | 'license-check' | 'bad-request' | 'network'+/** `ttl-unsupported`: a `400 {"error":"bad_ttl"}` answered to an Unlimited request (`ttlSeconds` 0) —+ * a server older than unlimited links. The same 400 to a finite request stays `bad-request`. */+export type CreateError =+ | 'not-entitled'+ | 'limit-active'+ | 'limit-daily'+ | 'rate-limited'+ | 'license-check'+ | 'bad-request'+ | 'ttl-unsupported'+ | 'network'export type HostTokenResult = MintResult | { ok: false; kind: 'gone'; reason: 'revoked' | 'expired' }export interface WatchLinkApi {- create(entitlement: string, joinKeyHash: string, ttlSeconds: number): Promise<{ ok: true; linkId: string; expiresAt: number } | { ok: false; error: CreateError }>+ /** `ttlSeconds` 0 asks for an Unlimited link; only then may the answer's `expiresAt` be null. */+ create(+ entitlement: string,+ joinKeyHash: string,+ ttlSeconds: number+ ): Promise<{ ok: true; linkId: string; expiresAt: number | null } | { ok: false; error: CreateError }>hostToken(linkId: string, entitlement: string): Promise<HostTokenResult>status(linkId: string, entitlement: string): Promise<'live' | 'revoked' | 'expired' | 'unknown'>revoke(linkId: string, entitlement: string): Promise<boolean>@@ -86,11 +101,17 @@ export function createWatchLinkApi(o: { apiBase: string; fetch?: typeof fetch; n// the URL could not carry (`formatWatchLink` refuses it, and the store would drop the record at// the next boot) is malformed too.const linkId = r.json?.linkId- if (r.status === 200 && typeof linkId === 'string' && LINK_ID_RE.test(linkId) && typeof exp === 'number' && Number.isFinite(exp) && exp > 0) {- // `expiresAt` is an instant on the SERVER's clock; the Date header turns it into time left,- // which is then anchored on this machine's clock (see tokenTtlMs).- const t = now()- return { ok: true, linkId, expiresAt: t + tokenTtlMs(exp, r.date, t) }+ if (r.status === 200 && typeof linkId === 'string' && LINK_ID_RE.test(linkId)) {+ // No end time — an Unlimited link — only when one was asked for. A null to a finite request is+ // a malformed reply: taken as given it would be a link nobody asked to outlive its choice.+ if (exp === null && ttlSeconds === 0) return { ok: true, linkId, expiresAt: null }+ if (typeof exp === 'number' && Number.isFinite(exp) && exp > 0) {+ // `expiresAt` is an instant on the SERVER's clock; the Date header turns it into time left,+ // which is then anchored on this machine's clock (see tokenTtlMs). A capped server answers an+ // Unlimited request with an end time too: re-anchored the same way.+ const t = now()+ return { ok: true, linkId, expiresAt: t + tokenTtlMs(exp, r.date, t) }+ }}if (r.status === 402 || r.status === 403) return { ok: false, error: 'not-entitled' }if (r.status === 429) {@@ -98,7 +119,9 @@ export function createWatchLinkApi(o: { apiBase: string; fetch?: typeof fetch; nreturn { ok: false, error: scope === 'active_links' ? 'limit-active' : scope === 'license' ? 'limit-daily' : 'rate-limited' }}if (r.status === 503) return { ok: false, error: 'license-check' }- if (r.status === 400) return { ok: false, error: 'bad-request' }+ if (r.status === 400) {+ return { ok: false, error: ttlSeconds === 0 && r.json?.error === 'bad_ttl' ? 'ttl-unsupported' : 'bad-request' }+ }return { ok: false, error: 'network' }},async hostToken(linkId, entitlement) {diff --git a/src/core/watch-link/link-host.test.ts b/src/core/watch-link/link-host.test.tsindex e659ee063..7e117988a 100644--- a/src/core/watch-link/link-host.test.ts+++ b/src/core/watch-link/link-host.test.ts@@ -2312,6 +2312,18 @@ describe('createLinkHost — control', () => {await vi.waitFor(() => expect(typingOf(watcher)).toEqual([['Ada']]))})+ // The owner must never read "Bob · typing" beside an "Ada took control" notice: while a viewer+ // controls, the owner's list names it as the typing set does. Once it stops, its chat name again.+ it("the owner's viewer list names a controller by its unlock name, and by its chat name once it stops", async () => {+ const { t, clock, vs } = await controllers(['Ada'])+ expect(vs[0].c.sendChat('Bob', 'hi')).toBe(true)+ await vi.waitFor(() => expect(t.chats).toHaveLength(1))+ await type(vs[0], 'a', clock)+ expect(t.host.viewers()[0]).toMatchObject({ name: 'Ada', controlling: true, typing: true })+ expect(await ask(vs[0], () => vs[0].c.release())).toEqual({ state: 'available' })+ expect(t.host.viewers()[0]).toMatchObject({ name: 'Bob', controlling: false })+ })+it('stop() with a pending batch and a live typing set leaves no timer behind', async () => {const { t, clock, vs } = await controllers(['Ada', 'Bob'])await type(vs[0], 'a', clock)diff --git a/src/core/watch-link/link-host.ts b/src/core/watch-link/link-host.tsindex 06fcaa0b7..f835322dd 100644--- a/src/core/watch-link/link-host.ts+++ b/src/core/watch-link/link-host.ts@@ -154,7 +154,7 @@ import {import type { HostTokenResult } from './api'import { unavailableCapture, type VisibleCapture } from './capture-route'import { createInputSplitter, createTypingTracker, type InputSplitter } from './control-input'-import { WATCHER_INPUT_ROUTES, type ControlInputChunk, type WatcherInputRoute } from './pane-input'+import { PANE_INPUT_DEADLINE_MS, WATCHER_INPUT_ROUTES, type ControlInputChunk, type WatcherInputRoute } from './pane-input'import { isTerminalReport } from '../terminal-reports'import { createStreamFilter, type StreamFilter } from './stream-filter'import { createTokenBucket, type TokenBucket } from './token-bucket'@@ -207,7 +207,7 @@ export const DROPPED_NOTICE_MIN_MS = 10_000export const INPUT_GRACE_MS = 5000/** A pane delivery that has not answered by now counts as failed: the batch stops (`dropped`) and the* link's chain moves on. A late answer is ignored. */-export const INPUT_DELIVERY_TIMEOUT_MS = 20_000+export const INPUT_DELIVERY_TIMEOUT_MS = PANE_INPUT_DEADLINE_MSconst RATE = 256 * 1024const BURST = 1024 * 1024@@ -279,6 +279,7 @@ export interface LinkHostDeps {export type LinkRuntimeStatus = 'live' | 'reconnecting' | 'refused'export interface LinkViewer {viewerId: string+ /** While controlling, the name it unlocked under; otherwise its chat name (null before it chats). */name: string | nulljoinedAt: number/** Connected, but its last join found no session to watch (R63): what the owner must be told,@@ -1368,13 +1369,16 @@ export function createLinkHost(record: WatchLinkRecord, deps: LinkHostDeps): Linconst now = deps.now()for (const c of conns) {if (c.joinedAt === null || c.ended) continue+ // The effective state: a flag the host has not yet been told to clear never reads as control.+ const controlling = controlStateFor(c).state === 'controlling'out.push({viewerId: c.viewerId,- name: c.name,+ // While it controls, the name it unlocked under — the one the typing set and the owner's+ // "took control" notice use — never a later chat name beside them.+ name: controlling ? (c.controlName ?? c.name) : c.name,joinedAt: c.joinedAt,waiting: c.joinRefused && c.sessionId === null,- // The effective state: a flag the host has not yet been told to clear never reads as control.- controlling: controlStateFor(c).state === 'controlling',+ controlling,typing: tracker.typing(c.viewerId, now)})}diff --git a/src/core/watch-link/pane-input.ts b/src/core/watch-link/pane-input.tsindex 4b9d3ace8..66f12b8f3 100644--- a/src/core/watch-link/pane-input.ts+++ b/src/core/watch-link/pane-input.ts@@ -101,6 +101,15 @@ export type WatcherInputRoute = 'tmux' | 'ssh' | 'write' | 'none'/** Every route, for a reader that must check one it did not produce (link-host.ts `normalizeJoin`). */export const WATCHER_INPUT_ROUTES = ['tmux', 'ssh', 'write', 'none'] as const satisfies readonly WatcherInputRoute[]+/**+ * How long one chunk of a controller's input may take, from the moment it is handed over: the link+ * host gives up on it then (INPUT_DELIVERY_TIMEOUT_MS is this value) and tells its controller it was+ * dropped, and `PtyManager.controlInput` answers false at the same deadline and moves the session's+ * chain on — so a delivery that never answers cannot hold every later chunk behind it, and a chunk+ * that could not even START by then is never delivered at all.+ */+export const PANE_INPUT_DEADLINE_MS = 20_000+/** Bytes per `send-keys -H` line: 3 characters each on the line, so ~3 KiB a line. */export const KEYS_PER_COMMAND = 1024diff --git a/src/core/watch-link/pty-seam.test.ts b/src/core/watch-link/pty-seam.test.tsindex acb601dfb..8feee2781 100644--- a/src/core/watch-link/pty-seam.test.ts+++ b/src/core/watch-link/pty-seam.test.ts@@ -9,7 +9,9 @@ function fakeManager(over: Partial<Record<keyof WatchPtyManager, unknown>> = {})kill: vi.fn(),captureVisible: vi.fn(async () => ({ screen: 'x', cursor: { x: 1, y: 2 } })),syncWatcherClientSize: vi.fn(async () => true),- hasSession: vi.fn(() => true)+ hasSession: vi.fn(() => true),+ watcherInputRoute: vi.fn((_s: string): string => 'tmux'),+ controlInput: vi.fn(async (_s: string, _c: unknown) => true)}return Object.assign(m, over) as typeof m}@@ -18,7 +20,7 @@ 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, input: 'none' })+ expect(await pty.join(7, 'n1', 'v-1')).toEqual({ sessionId: 's1', cols: 120, rows: 40, altScreen: true, input: 'tmux' })expect(m.joinAsWatcher).toHaveBeenCalledWith(7, { persistKey: 'n1', viewerId: 'v-1' })expect(m.sessionSize).toHaveBeenCalledWith('s1')expect(m.kill).not.toHaveBeenCalled()@@ -74,4 +76,28 @@ describe('createWatchPty — the WatchPty seam both shells wire (R39)', () => {m.hasSession.mockReturnValue(false)expect(pty.alive('s1')).toBe(false)})++ // Control: the join reports how a controller's input reaches the JOINED session's pane (the route+ // PtyManager decides — Zellij and an unknown session answer `none`), and input goes to the pane.+ it("a join carries the joined session's input route, read from PtyManager", async () => {+ for (const route of ['tmux', 'ssh', 'write', 'none']) {+ const m = fakeManager({ watcherInputRoute: vi.fn(() => route) })+ expect(await createWatchPty(m as unknown as WatchPtyManager).join(7, 'n1', 'v-1')).toMatchObject({ input: route })+ expect(m.watcherInputRoute).toHaveBeenCalledWith('s1')+ }+ // A refused join never asks.+ const none = fakeManager({ sessionSize: vi.fn(() => null) })+ await createWatchPty(none as unknown as WatchPtyManager).join(7, 'n1', 'v-1')+ expect(none.watcherInputRoute).not.toHaveBeenCalled()+ })++ it("input goes to PtyManager.controlInput for that session, and its answer comes back as it is", async () => {+ const m = fakeManager()+ const pty = createWatchPty(m as unknown as WatchPtyManager)+ expect(await pty.input('s1', { kind: 'keys', data: 'ls\r' })).toBe(true)+ expect(m.controlInput).toHaveBeenCalledWith('s1', { kind: 'keys', data: 'ls\r' })+ m.controlInput.mockResolvedValueOnce(false)+ expect(await pty.input('s1', { kind: 'paste', text: 'x' })).toBe(false)+ expect(m.controlInput).toHaveBeenLastCalledWith('s1', { kind: 'paste', text: 'x' })+ })})diff --git a/src/core/watch-link/pty-seam.ts b/src/core/watch-link/pty-seam.tsindex 95224ea6b..0adcab5e9 100644--- a/src/core/watch-link/pty-seam.ts+++ b/src/core/watch-link/pty-seam.ts@@ -8,14 +8,24 @@// 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).+// - `alive` is PtyManager's explicit `hasSession` (R38), `syncSize` its per-session serialized sync (R24);+// - a join reports how a controller's input reaches the JOINED session's PANE+// (`watcherInputRoute`: `none` for Zellij or a session it no longer holds, which refuses control),+// and `input` is `controlInput` — the pane, never a tmux client's key table.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'+ | 'joinAsWatcher'+ | 'sessionSize'+ | 'kill'+ | 'captureVisible'+ | 'syncWatcherClientSize'+ | 'hasSession'+ | 'controlInput'+ | 'watcherInputRoute'>/** Where a node's session lives, from the SHELL's own records. `requireRemote` for every node of an@@ -41,14 +51,18 @@ export function createWatchPty(pty: WatchPtyManager, remoteFor: (nodeId: string)pty.kill(clientId, res.sessionId, viewerId)return null}- // Control is not wired to the pane yet: every join answers `none` (control refused) and no- // input is delivered (fail closed).- return { sessionId: res.sessionId, cols: size.cols, rows: size.rows, altScreen: res.tmuxClient === true, input: 'none' }+ return {+ sessionId: res.sessionId,+ cols: size.cols,+ rows: size.rows,+ altScreen: res.tmuxClient === true,+ input: pty.watcherInputRoute(res.sessionId)+ }},leave: (clientId, sessionId, viewerId) => pty.kill(clientId, sessionId, viewerId),captureVisible: (sessionId) => pty.captureVisible(sessionId),syncSize: (sessionId) => pty.syncWatcherClientSize(sessionId),alive: (sessionId) => pty.hasSession(sessionId),- input: async () => false+ input: (sessionId, chunk) => pty.controlInput(sessionId, chunk)}}diff --git a/src/core/watch-link/service.test.ts b/src/core/watch-link/service.test.tsindex 3f8794393..eac048cf1 100644--- a/src/core/watch-link/service.test.ts+++ b/src/core/watch-link/service.test.ts@@ -3,6 +3,7 @@ import { join } from 'node:path'import { readFileSync } from 'node:fs'import { testTmpDir } from '../test-tmp'import {+ createFifoGate,createWatchLinkService,registerWatchLinkIpc,sendToOwners,@@ -16,7 +17,8 @@ import { WatchLinkStore, WatchLinkStoreUnreadable, type WatchLinkRecord, type Saimport 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 type { ControlSupport, WatchLinkNotice, WatchLinkView } from '../../shared/watch-link-types'+import { hashControlPassword, verifyControlPassword, type ControlPasswordHash } from './password'import { IPC } from '../../shared/ipc'import { fakePlatform } from '../platform-fake'@@ -30,12 +32,15 @@ const HOUR = 3600_000function fakeApi(over: Partial<ApiClient> = {}) {const calls: string[] = []+ const ttls: number[] = []let n = 0const api: ApiClient = {- create: async () => {+ create: async (_ent, _hash, ttl) => {calls.push('create')+ ttls.push(ttl)n++- return { ok: true, linkId: `Link${String(n).padStart(18, '0')}`, expiresAt: Date.now() + HOUR }+ // Like the server: Unlimited (0) answers no end time.+ return { ok: true, linkId: `Link${String(n).padStart(18, '0')}`, expiresAt: ttl === 0 ? null : Date.now() + HOUR }},hostToken: async (id) => {calls.push(`hostToken ${id}`)@@ -52,13 +57,15 @@ function fakeApi(over: Partial<ApiClient> = {}) {},...over}- return { api, calls }+ return { api, calls, ttls }}interface FakeHost {record: WatchLinkRecorddeps: LinkHostDepsstopped: string[]+ /** controlChanged / passwordChanged / allowControl, in call order. */+ hooks: string[]starts: numberstatus: LinkRuntimeStatusviewers: LinkViewer[]@@ -67,7 +74,7 @@ interface FakeHost {function fakeHosts() {const made: FakeHost[] = []const createHost = (record: WatchLinkRecord, deps: LinkHostDeps): LinkHost => {- const h: FakeHost = { record, deps, stopped: [], starts: 0, status: 'live', viewers: [], chat: [] }+ const h: FakeHost = { record, deps, stopped: [], hooks: [], starts: 0, status: 'live', viewers: [], chat: [] }made.push(h)return {start: () => {@@ -81,9 +88,15 @@ function fakeHosts() {chatHistory: () => h.chat,status: () => h.status,viewers: () => h.viewers,- controlChanged: () => {},- passwordChanged: () => {},- allowControl: () => {}+ controlChanged: () => {+ h.hooks.push('controlChanged')+ },+ passwordChanged: () => {+ h.hooks.push('passwordChanged')+ },+ allowControl: () => {+ h.hooks.push('allowControl')+ }}}return { made, createHost }@@ -113,10 +126,15 @@ interface Opts {persistTimeoutMs?: numberworkspaceWaitMs?: numbernow?: () => number+ controlSupport?: (nodeId: string) => ControlSupport+ hashPassword?: (pw: string) => Promise<ControlPasswordHash>+ verifyPassword?: (pw: string, h: ControlPasswordHash) => Promise<boolean>+ /** The REAL link host (and a relay transport no test reaches) instead of the fake. */+ realHost?: boolean}function service(o: Opts = {}) {const file = join(testTmpDir('wls-'), 'watch-links.json')- const { api, calls } = fakeApi(o.api)+ const { api, calls, ttls } = fakeApi(o.api)const hosts = fakeHosts()const nodes = o.nodes ?? new Map<string, WatchLinkNodeState>([['n1', 'present'], ['n2', 'present']])const emitted: [string, unknown[]][] = []@@ -133,7 +151,16 @@ function service(o: Opts = {}) {clients: { attach: () => 1, detach: () => {} },pty: o.pty ?? fakePty(),emit: (ch, ...a) => emitted.push([ch, a]),- createHost: hosts.createHost,+ ...(o.realHost+ ? {+ transport: () => {+ throw new Error('no relay in this test')+ }+ }+ : { createHost: hosts.createHost }),+ ...(o.controlSupport ? { controlSupport: o.controlSupport } : {}),+ ...(o.hashPassword ? { hashPassword: o.hashPassword } : {}),+ ...(o.verifyPassword ? { verifyPassword: o.verifyPassword } : {}),...(o.unsupported ? { unsupported: true } : {}),...(o.persistTimeoutMs ? { persistTimeoutMs: o.persistTimeoutMs } : {}),...(o.workspaceWaitMs ? { workspaceWaitMs: o.workspaceWaitMs } : {}),@@ -142,7 +169,7 @@ function service(o: Opts = {}) {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 }+ return { s, calls, ttls, 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 => ({@@ -886,14 +913,46 @@ describe('registerWatchLinkIpc / sendToOwners', () => {expect(await p.handlers[IPC.watchLinkCreate](1, req())).toEqual({ ok: false, error: 'unsupported' })})- it('registers exactly the seven request channels', () => {+ it('registers exactly the eleven 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()+ [+ IPC.watchLinkCreate, IPC.watchLinkList, IPC.watchLinkRevoke, IPC.watchLinkRevokeAll, IPC.watchLinkKick,+ IPC.watchLinkChatSend, IPC.watchLinkChatHistory, IPC.watchLinkSetControl, IPC.watchLinkSetPassword,+ IPC.watchLinkAllowControl, IPC.watchLinkControlSupport+ ].sort())})+ it('the Control channels answer owners only, and refuse arguments of the wrong type', async () => {+ const t = service({ controlSupport: () => 'ok', hashPassword: fastHash })+ const p = fakePlatform({ isOwnerClient: (id) => id === 1 })+ registerWatchLinkIpc(p, t.s)+ const made = (await p.handlers[IPC.watchLinkCreate](1, ctlReq())) as { ok: true; link: WatchLinkView }+ const id = made.link.linkId+ const h = t.hosts.made[0]+ // A client that is not the machine's owner reaches nothing.+ expect(await p.handlers[IPC.watchLinkSetControl](2, id, false)).toBe(false)+ expect(await p.handlers[IPC.watchLinkSetPassword](2, id, 'another password')).toBe(false)+ expect(await p.handlers[IPC.watchLinkAllowControl](2, id)).toBe(false)+ expect(await p.handlers[IPC.watchLinkControlSupport](2, 'n1')).toBe('unknown')+ // Wrong types.+ expect(await p.handlers[IPC.watchLinkSetControl](1, id, 'false')).toBe(false)+ expect(await p.handlers[IPC.watchLinkSetControl](1, 7, false)).toBe(false)+ expect(await p.handlers[IPC.watchLinkSetPassword](1, id, 12345678)).toBe(false)+ expect(await p.handlers[IPC.watchLinkAllowControl](1, null)).toBe(false)+ expect(await p.handlers[IPC.watchLinkControlSupport](1, 5)).toBe('unknown')+ expect(h.hooks).toEqual([])+ // The owner.+ expect(await p.handlers[IPC.watchLinkControlSupport](1, 'n1')).toBe('ok')+ expect(await p.handlers[IPC.watchLinkSetControl](1, id, false)).toBe(true)+ expect(await p.handlers[IPC.watchLinkSetPassword](1, id, 'another password')).toBe(true)+ h.deps.onControlLocked()+ expect(await p.handlers[IPC.watchLinkAllowControl](1, id)).toBe(true)+ expect(h.hooks).toEqual(['controlChanged', 'passwordChanged', 'allowControl'])+ })+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)@@ -935,6 +994,398 @@ describe('createWatchLinkService — real store', () => {})})+// --- Control links and Unlimited links ------------------------------------------------------------------++const PW = 'correct horse battery'+const NEW_PW = 'staple gun ninety'+const ctlReq = (over: Record<string, unknown> = {}) => req({ role: 'controller', password: PW, ...over })+/** A hash shaped like scrypt's (16-byte salt, 32-byte key) without its ~80 ms: for the tests that+ * are about the plumbing, not the password. Different every call, like a fresh salt. */+let fastN = 0+const fastHash = async (): Promise<ControlPasswordHash> => {+ fastN+++ return {+ salt: Buffer.alloc(16, fastN % 256).toString('base64'),+ hash: Buffer.alloc(32, (fastN * 7) % 256).toString('base64')+ }+}+const allLogged = (spies: ReturnType<typeof vi.spyOn>[]) => spies.flatMap((sp) => sp.mock.calls.flat().map(String)).join('\n')++describe('createWatchLinkService — creating a Control link', () => {+ it('hashes the password, keeps only {salt, hash} in the record, and the host checks against it', async () => {+ const t = service()+ const r = await t.s.create(ctlReq())+ if (!r.ok) throw new Error(r.error)+ expect(r.link).toMatchObject({ role: 'controller', control: { enabled: true, locked: false } })+ const text = readFileSync(t.file, 'utf8')+ expect(text).not.toContain(PW)+ expect(text).not.toContain(Buffer.from(PW).toString('base64'))+ expect(text).not.toContain(Buffer.from(PW).toString('hex'))+ const [loaded] = await t.store.load()+ expect(Object.keys(loaded.control ?? {}).sort()).toEqual(['enabled', 'hash', 'locked', 'salt'])+ expect(loaded.control).toMatchObject({ enabled: true, locked: false })+ expect(await verifyControlPassword(PW, loaded.control!)).toBe(true)+ const h = t.hosts.made[0]+ expect(await h.deps.verifyPassword(PW)).toBe(true)+ expect(await h.deps.verifyPassword('not the password')).toBe(false)+ })++ it('a viewer or commenter link ignores a password field: no control, nothing of it on disk', async () => {+ const t = service()+ for (const role of ['viewer', 'commenter']) {+ const r = await t.s.create(req({ role, password: PW }))+ if (!r.ok) throw new Error(r.error)+ expect(r.link.control).toBeNull()+ }+ expect(readFileSync(t.file, 'utf8')).not.toContain(PW)+ expect((await t.store.load()).map((l) => l.control)).toEqual([undefined, undefined])+ expect(await t.hosts.made[0].deps.verifyPassword(PW)).toBe(false)+ })++ it('a Control link without an acceptable password is bad-password, and nothing is asked of the server', async () => {+ const t = service()+ for (const password of [undefined, '', 'short', 12345678, 'abcdefg\n', 'x'.repeat(129), null, {}]) {+ expect(await t.s.create(ctlReq({ password })), JSON.stringify(password)).toEqual({ ok: false, error: 'bad-password' })+ }+ // A request that is malformed otherwise is bad-request, whatever its password.+ expect(await t.s.create(ctlReq({ password: 'short', ttlSeconds: 7 }))).toEqual({ ok: false, error: 'bad-request' })+ expect(t.calls).toEqual([])+ expect(t.hosts.made).toEqual([])+ })++ it('a Control link on a terminal that cannot take input (Zellij) is control-unsupported, before any request', async () => {+ const answers = new Map<string, ControlSupport>([['n1', 'unsupported'], ['n2', 'unknown']])+ const t = service({ controlSupport: (id) => answers.get(id) ?? 'ok' })+ expect(await t.s.create(ctlReq())).toEqual({ ok: false, error: 'control-unsupported' })+ expect(t.calls).toEqual([])+ // Only a Control link is asked about; unknown leaves the create to decide.+ expect((await t.s.create(req({ role: 'commenter' }))).ok).toBe(true)+ expect((await t.s.create(ctlReq({ nodeId: 'n2' }))).ok).toBe(true)+ // A check that throws reads as unknown.+ const u = service({+ controlSupport: () => {+ throw new Error('boom')+ }+ })+ expect((await u.s.create(ctlReq())).ok).toBe(true)+ // A shell that wires no check: unknown.+ expect((await service().s.create(ctlReq())).ok).toBe(true)+ })++ it('the password is hashed BEFORE the server create: a hash that fails creates no server row, and logs nothing of it', async () => {+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})+ const t = service({+ hashPassword: async (pw) => {+ throw new Error(`scrypt said no about ${pw}`)+ }+ })+ const r = await t.s.create(ctlReq())+ expect(r.ok).toBe(false)+ expect(t.calls).toEqual([])+ expect(t.hosts.made).toEqual([])+ expect(allLogged([warn])).not.toContain(PW)+ warn.mockRestore()+ })+})++describe('createWatchLinkService — creating an Unlimited link', () => {+ it('asks for ttlSeconds 0 and records expiresAt: null, with no expiry timer: still live after any time', async () => {+ vi.useFakeTimers()+ const t = service()+ const r = await t.s.create(req({ ttlSeconds: 0 }))+ if (!r.ok) throw new Error(r.error)+ expect(t.ttls).toEqual([0])+ expect(r.link.expiresAt).toBeNull()+ expect((await t.store.load())[0].expiresAt).toBeNull()+ expect(vi.getTimerCount()).toBe(0)+ await vi.advanceTimersByTimeAsync(400 * 24 * HOUR)+ expect(t.s.list().map((l) => l.expiresAt)).toEqual([null])+ expect(t.hosts.made[0].stopped).toEqual([])+ })++ it('an older server (ttl-unsupported) creates nothing here', async () => {+ const t = service({ api: { create: async () => ({ ok: false, error: 'ttl-unsupported' }) } })+ expect(await t.s.create(req({ ttlSeconds: 0 }))).toEqual({ ok: false, error: 'ttl-unsupported' })+ expect(t.hosts.made).toEqual([])+ expect(t.s.list()).toEqual([])+ expect(await t.store.load()).toEqual([])+ })++ // The backend checks an Unlimited link's license daily at its host-token mint and answers 402 once+ // the owner's Pro lapsed. That is the same refusal as any other: the REAL host stops minting (no+ // retry loop) and the owner's view reads `status: 'refused'`.+ it("a 402 at the mint (Pro lapsed) stops minting for good and the view reads status 'refused'", async () => {+ const quiet = [vi.spyOn(console, 'warn').mockImplementation(() => {}), vi.spyOn(console, 'error').mockImplementation(() => {})]+ vi.useFakeTimers()+ let mints = 0+ const t = service({+ realHost: true,+ api: {+ hostToken: async () => {+ mints+++ return { ok: false, kind: 'refused', status: 402 }+ }+ }+ })+ const r = await t.s.create(req({ ttlSeconds: 0 }))+ if (!r.ok) throw new Error(r.error)+ await vi.waitFor(() => expect(mints).toBe(1))+ await vi.advanceTimersByTimeAsync(48 * HOUR)+ expect(mints).toBe(1)+ expect(t.s.list()[0]).toMatchObject({ status: 'refused', expiresAt: null })+ expect(t.states().at(-1)?.[0].status).toBe('refused')+ for (const q of quiet) q.mockRestore()+ })+})++describe('createWatchLinkService — the Control host seams', () => {+ it('a lock is set on the record SYNCHRONOUSLY, then written, and the owner is told', async () => {+ const t = service()+ const r = await t.s.create(ctlReq())+ if (!r.ok) throw new Error(r.error)+ const h = t.hosts.made[0]+ h.deps.onControlLocked()+ expect(h.record.control?.locked).toBe(true) // before any await: the host's lock rests on it+ expect(t.notices().at(-1)).toEqual({ kind: 'control-locked', linkId: r.link.linkId, nodeId: 'n1', title: 'build' })+ expect((await t.store.load())[0].control?.locked).toBe(true)+ await flush()+ expect(t.states().at(-1)?.[0].control).toEqual({ enabled: true, locked: true })+ })++ it('a lock whose write fails still holds in memory, and the failure is logged', async () => {+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})+ let outcome: SaveOutcome = 'saved'+ const f = fakeStore({ save: async () => outcome })+ const t = service({ store: f.store })+ const r = await t.s.create(ctlReq())+ if (!r.ok) throw new Error(r.error)+ outcome = 'failed'+ t.hosts.made[0].deps.onControlLocked()+ await vi.waitFor(() => expect(warn.mock.calls.some(([l]) => /lock/.test(String(l)))).toBe(true))+ expect(t.s.list()[0].control).toEqual({ enabled: true, locked: true })+ const c = t.hosts.made[0].record.control!+ expect(allLogged([warn])).not.toMatch(new RegExp([PW, c.salt, c.hash].map((x) => x.replace(/[+/=]/g, '\\$&')).join('|')))+ warn.mockRestore()+ })++ it('a viewer taking control tells the owner, under the name it gave (bidi stripped)', async () => {+ const t = service()+ const r = await t.s.create(ctlReq())+ if (!r.ok) throw new Error(r.error)+ t.hosts.made[0].deps.onControlTaken('E\u202eve')+ expect(t.notices().at(-1)).toEqual({ kind: 'control-taken', linkId: r.link.linkId, nodeId: 'n1', title: 'build', name: 'Eve' })+ await flush()+ expect(t.states().length).toBeGreaterThan(0)+ })++ it("the owner's view carries each viewer's controlling and typing from the host, and the link's control state", async () => {+ const t = service()+ const r = await t.s.create(ctlReq())+ if (!r.ok) throw new Error(r.error)+ t.hosts.made[0].viewers = [+ { viewerId: 'v-1', name: 'Ada', joinedAt: 5, waiting: false, controlling: true, typing: true },+ { viewerId: 'v-2', name: null, joinedAt: 6, waiting: false, controlling: false, typing: false }+ ]+ expect(t.s.list()[0].viewers.map((v) => [v.controlling, v.typing])).toEqual([[true, true], [false, false]])+ expect(t.s.list()[0].control).toEqual({ enabled: true, locked: false })+ })+})++describe('createWatchLinkService — the owner controls a Control link', () => {+ it('setControl writes enabled, persists it and tells the host; refused for anything but a live Control link', async () => {+ const t = service()+ const r = await t.s.create(ctlReq())+ const v = await t.s.create(req({ role: 'commenter', nodeId: 'n2' }))+ if (!r.ok || !v.ok) throw new Error('create failed')+ const h = t.hosts.made[0]+ expect(await t.s.setControl(r.link.linkId, false)).toBe(true)+ expect(h.hooks).toEqual(['controlChanged'])+ expect((await t.store.load()).find((l) => l.linkId === r.link.linkId)?.control?.enabled).toBe(false)+ await flush()+ expect(t.states().at(-1)?.find((l) => l.linkId === r.link.linkId)?.control).toEqual({ enabled: false, locked: false })+ expect(await t.s.setControl(r.link.linkId, true)).toBe(true)+ expect(h.hooks).toEqual(['controlChanged', 'controlChanged'])+ // Not a Control link, an unknown link, an ended one.+ expect(await t.s.setControl(v.link.linkId, false)).toBe(false)+ expect(await t.s.setControl('Nope000000000000000000', false)).toBe(false)+ await t.s.revoke(r.link.linkId)+ expect(await t.s.setControl(r.link.linkId, false)).toBe(false)+ expect(t.hosts.made[1].hooks).toEqual([])+ })++ it('setPassword checks the new password, swaps the hash, persists, and demotes every controller; the old one stops working', async () => {+ const t = service()+ const r = await t.s.create(ctlReq())+ if (!r.ok) throw new Error(r.error)+ const h = t.hosts.made[0]+ const before = { ...(await t.store.load())[0].control! }+ for (const bad of ['short', 'abcdefg\n', 'x'.repeat(129), 12345678]) {+ expect(await t.s.setPassword(r.link.linkId, bad as string)).toBe(false)+ }+ expect(h.hooks).toEqual([])+ expect(await t.s.setPassword(r.link.linkId, NEW_PW)).toBe(true)+ expect(h.hooks).toEqual(['passwordChanged'])+ const after = (await t.store.load())[0].control!+ expect(after.salt).not.toBe(before.salt)+ expect(after.hash).not.toBe(before.hash)+ expect(readFileSync(t.file, 'utf8')).not.toContain(NEW_PW)+ // The host checks against the CURRENT hash.+ expect(await h.deps.verifyPassword(NEW_PW)).toBe(true)+ expect(await h.deps.verifyPassword(PW)).toBe(false)+ const v = await t.s.create(req({ role: 'viewer', nodeId: 'n2' }))+ if (!v.ok) throw new Error(v.error)+ expect(await t.s.setPassword(v.link.linkId, NEW_PW)).toBe(false)+ })++ it('allowControl clears the lock, persists it and tells the host', async () => {+ const t = service({ hashPassword: fastHash })+ const r = await t.s.create(ctlReq())+ if (!r.ok) throw new Error(r.error)+ const h = t.hosts.made[0]+ h.deps.onControlLocked()+ expect(await t.s.allowControl(r.link.linkId)).toBe(true)+ expect(h.hooks).toEqual(['allowControl'])+ expect((await t.store.load())[0].control?.locked).toBe(false)+ expect(t.s.list()[0].control).toEqual({ enabled: true, locked: false })+ expect(await t.s.allowControl('Nope000000000000000000')).toBe(false)+ })++ it('a change whose write fails is undone in memory and at the host, and answers false; a lock is never undone', async () => {+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})+ let outcome: SaveOutcome = 'saved'+ const f = fakeStore({ save: async () => outcome })+ const t = service({ store: f.store })+ const r = await t.s.create(ctlReq())+ if (!r.ok) throw new Error(r.error)+ const id = r.link.linkId+ const h = t.hosts.made[0]+ outcome = 'failed'+ const saves = f.saves.length+ expect(await t.s.setControl(id, false)).toBe(false)+ expect(t.s.list()[0].control).toEqual({ enabled: true, locked: false })+ expect(h.hooks).toEqual(['controlChanged', 'controlChanged']) // told, then told it is back+ expect(f.saves.length).toBe(saves + 2) // the write that failed, and the corrected list behind it+ expect(f.saves.at(-1)?.[0].control?.enabled).toBe(true)+ h.hooks.length = 0+ expect(await t.s.setPassword(id, NEW_PW)).toBe(false)+ expect(h.hooks).toEqual(['passwordChanged', 'passwordChanged'])+ expect(await h.deps.verifyPassword(PW)).toBe(true)+ expect(await h.deps.verifyPassword(NEW_PW)).toBe(false)+ h.hooks.length = 0+ h.deps.onControlLocked() // its own write fails too: the lock holds+ expect(await t.s.allowControl(id)).toBe(false)+ expect(h.hooks).toEqual(['allowControl', 'controlChanged'])+ expect(t.s.list()[0].control).toEqual({ enabled: true, locked: true })+ const c = h.record.control!+ expect(allLogged([warn])).not.toMatch(+ new RegExp([PW, NEW_PW, c.salt, c.hash].map((x) => x.replace(/[+/=]/g, '\\$&')).join('|'))+ )+ warn.mockRestore()+ })++ it('a change whose write does not answer is bounded: undone, false', async () => {+ const held = deferred<SaveOutcome>()+ let hang = false+ const f = fakeStore({ save: () => (hang ? held.promise : Promise.resolve('saved')) })+ const t = service({ store: f.store, persistTimeoutMs: 20, hashPassword: fastHash })+ const r = await t.s.create(ctlReq())+ if (!r.ok) throw new Error(r.error)+ hang = true+ expect(await t.s.setControl(r.link.linkId, false)).toBe(false)+ expect(t.s.list()[0].control).toEqual({ enabled: true, locked: false })+ held.resolve('saved')+ })+})++describe('createWatchLinkService — one bound on scrypt', () => {+ it('a FIFO gate: a third task waits for a slot, slots go in arrival order, a failure frees its slot', async () => {+ const gate = createFifoGate(2)+ const started: string[] = []+ const held = new Map<string, ReturnType<typeof deferred<string>>>()+ const run = (k: string) =>+ gate(() => {+ started.push(k)+ const d = deferred<string>()+ held.set(k, d)+ return d.promise+ })+ const out = ['a', 'b', 'c', 'd', 'e'].map((k) => run(k).catch((e: Error) => `x${e.message}`))+ await flush()+ expect(started).toEqual(['a', 'b'])+ held.get('b')!.reject(new Error('b'))+ await flush()+ expect(started).toEqual(['a', 'b', 'c'])+ held.get('a')!.resolve('a')+ await flush()+ expect(started).toEqual(['a', 'b', 'c', 'd'])+ held.get('c')!.resolve('c')+ held.get('d')!.resolve('d')+ await flush()+ held.get('e')!.resolve('e')+ expect(await Promise.all(out)).toEqual(['a', 'xb', 'c', 'd', 'e'])+ // A task that throws synchronously frees its slot too.+ const t2 = createFifoGate(1)+ await expect(+ t2(() => {+ throw new Error('sync')+ })+ ).rejects.toThrow('sync')+ expect(await t2(async () => 'next')).toBe('next')+ })++ it("every link host's password check goes through ONE 2-slot gate, in order; a new password's hash waits its turn too", async () => {+ const started: string[] = []+ const held = new Map<string, ReturnType<typeof deferred<boolean>>>()+ const t = service({+ hashPassword: async (pw) => {+ started.push(`hash:${pw}`)+ return fastHash()+ },+ verifyPassword: (pw) => {+ started.push(pw)+ const d = deferred<boolean>()+ held.set(pw, d)+ return d.promise+ }+ })+ for (const nodeId of ['n1', 'n2', 'n1']) expect((await t.s.create(ctlReq({ nodeId }))).ok).toBe(true)+ started.length = 0+ const [a, b, c] = t.hosts.made+ const results = [a.deps.verifyPassword('pa'), b.deps.verifyPassword('pb'), c.deps.verifyPassword('pc')]+ const changed = t.s.setPassword(a.record.linkId, NEW_PW)+ await flush()+ expect(started).toEqual(['pa', 'pb'])+ held.get('pb')!.resolve(false)+ await flush()+ expect(started).toEqual(['pa', 'pb', 'pc'])+ held.get('pa')!.resolve(true)+ await flush()+ expect(started).toEqual(['pa', 'pb', 'pc', `hash:${NEW_PW}`])+ held.get('pc')!.resolve(true)+ expect(await Promise.all(results)).toEqual([true, false, true])+ expect(await changed).toBe(true)+ })+})++describe('createWatchLinkService — controlSupport', () => {+ it("answers the shell's check; anything else, a throw, an unsafe id or no check at all is unknown", () => {+ const answers: Record<string, unknown> = { n1: 'ok', n2: 'unsupported', n3: 'maybe' }+ const t = service({ controlSupport: (id) => answers[id] as ControlSupport })+ expect(t.s.controlSupport('n1')).toBe('ok')+ expect(t.s.controlSupport('n2')).toBe('unsupported')+ expect(t.s.controlSupport('n3')).toBe('unknown')+ expect(t.s.controlSupport('../x')).toBe('unknown')+ expect(t.s.controlSupport(7 as unknown as string)).toBe('unknown')+ const boom = service({+ controlSupport: () => {+ throw new Error('x')+ }+ })+ expect(boom.s.controlSupport('n1')).toBe('unknown')+ expect(service().s.controlSupport('n1')).toBe('unknown')+ })+})+// A sanitizer whose character class renders as `[-]` cannot be reviewed by reading it (R46/M1): the// owner-side files spell every bidi and zero-width character as an escape.describe('no literal bidi or zero-width characters in the live-link owner sources', () => {diff --git a/src/core/watch-link/service.ts b/src/core/watch-link/service.tsindex 39da61e2e..27cbf8915 100644--- a/src/core/watch-link/service.ts+++ b/src/core/watch-link/service.ts@@ -33,6 +33,24 @@// the API refused once the license layer reports a change — a 7-day token expiring under a running// link is the ordinary case (R41).//+// CONTROL LINKS (role 'controller'). The password is checked by `controlPasswordProblem` and hashed+// (scrypt, ./password.ts) BEFORE the server row is created, so a hash that fails creates nothing; only+// {salt, hash} is kept, never the plaintext, and nothing logged carries the password, the hash or the+// salt. Every scrypt run of this process — the hosts' unlock checks and the owner's new passwords — goes+// through ONE FIFO gate of SCRYPT_SLOTS (each run is ~32 MiB and ~80 ms on libuv's 4-thread pool, and+// unlock attempts arrive from strangers): a run waits for a slot, it is never refused. The lock the+// link host asks for (`onControlLocked`) is set on the record synchronously — the host reads the record+// live — and is never undone by a failed write. The owner's changes (typing on/off, a new password,+// allow again) reach the host at once (turning typing off or replacing a leaked password must not wait+// on the disk), are then written, and are undone in memory and at the host when the write fails or does+// not answer within PERSIST_TIMEOUT_MS: the owner is answered false, never told a change was kept that+// the next launch would not have.+//+// AN UNLIMITED LINK (`ttlSeconds` 0) has `expiresAt: null`: no expiry timer, no expiry check on a host+// change, never pruned for time at launch. It ends like any link otherwise, and when its owner's Pro+// lapses the server refuses its host-token mint (402) — the host stops minting and the view says+// `refused`, the same state as any refused mint.+//// 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).@@ -51,6 +69,7 @@ import {TITLE_MAX,WATCH_LINK_TTLS,stripBidiControls,+ type ControlSupport,type CreateWatchLinkError,type CreateWatchLinkRequest,type CreateWatchLinkResult,@@ -59,9 +78,16 @@ import {type WatchLinkView,type WatchLinkViewerView} from '../../shared/watch-link-types'+import { controlPasswordProblem } from '../../shared/watch-link-password'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 { hashControlPassword, verifyControlPassword, type ControlPasswordHash } from './password'+import {+ WatchLinkStoreUnreadable,+ type WatchLinkControlRecord,+ 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. */@@ -71,6 +97,8 @@ export const PERSIST_TIMEOUT_MS = 10_000/** The longest `init()` waits for the boot workspace load before deciding with the nodes it cannot* place yet read as unknown (which keeps their links: the safe side). */export const WORKSPACE_READY_TIMEOUT_MS = 10_000+/** Concurrent scrypt runs (unlock checks and new passwords) this process allows. */+export const SCRYPT_SLOTS = 2export type WatchLinkNodeState = 'present' | 'absent' | 'unknown'@@ -92,6 +120,9 @@ export interface WatchLinkServiceDeps {pty: WatchPty/** Owner clients only (`sendToOwners`). */emit(channel: string, ...args: unknown[]): void+ /** Can this node's terminal take a Control link's input (`PtyManager.nodeControlSupport`)? Absent,+ * throwing or anything else answers `unknown`, which leaves the create to decide. */+ controlSupport?(nodeId: string): ControlSupport/** This shell cannot host links (the Server Edition until it has a license layer — R43). */unsupported?: booleannow?(): number@@ -105,6 +136,10 @@ export interface WatchLinkServiceDeps {createHost?: typeof createLinkHost/** TEST ONLY: the relay transport the link hosts dial. */transport?: () => RelayTransport+ /** TEST ONLY: scrypt's hash (./password.ts). */+ hashPassword?: (pw: string) => Promise<ControlPasswordHash>+ /** TEST ONLY: scrypt's check (./password.ts). */+ verifyPassword?: (pw: string, h: ControlPasswordHash) => Promise<boolean>}export interface WatchLinkService {@@ -123,6 +158,16 @@ export interface WatchLinkService {onWorkspaceChanged(): void/** After the license layer reports a change: re-arm every host the API refused. */onEntitlementChanged(): void+ /** A live Control link: turn typing on or off. False for any other link, or when it could not be+ * saved (then nothing changed). */+ setControl(linkId: string, enabled: boolean): Promise<boolean>+ /** A live Control link: replace its password (every controller drops back to watching). False for+ * a password `controlPasswordProblem` refuses, any other link, or a change that could not be saved. */+ setPassword(linkId: string, pw: string): Promise<boolean>+ /** A live Control link locked by wrong passwords: allow unlocking again. False as setControl. */+ allowControl(linkId: string): Promise<boolean>+ /** Whether this node's terminal can take a Control link's input (the create dialog asks). */+ controlSupport(nodeId: string): ControlSupport/** 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>@@ -163,19 +208,60 @@ function cleanText(raw: unknown, max: number): string | null {return out || null}-function parseRequest(raw: unknown): CreateWatchLinkRequest | null {- if (!raw || typeof raw !== 'object') return null+/** A create request as the owner sent it: everything checked, the password apart from the request+ * (only a Control link carries one; another role's `password` field is ignored). */+type ParsedRequest = { req: Omit<CreateWatchLinkRequest, 'password'>; password: string | null }++function parseRequest(raw: unknown): ParsedRequest | 'bad-request' | 'bad-password' {+ if (!raw || typeof raw !== 'object') return 'bad-request'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+ if (typeof r.nodeId !== 'string' || !isSafeNodeId(r.nodeId)) return 'bad-request'+ if (r.role !== 'viewer' && r.role !== 'commenter' && r.role !== 'controller') return 'bad-request'+ // 0 is Unlimited: no end time.+ if (!(WATCH_LINK_TTLS as readonly unknown[]).includes(r.ttlSeconds)) return 'bad-request'const label = cleanText(r.label, LABEL_MAX)- if (!label) return null+ if (!label) return 'bad-request'const title = cleanText(r.title, TITLE_MAX) ?? 'Terminal'- return { nodeId: r.nodeId, role: r.role, ttlSeconds: r.ttlSeconds as CreateWatchLinkRequest['ttlSeconds'], label, title }+ const req: ParsedRequest['req'] = { nodeId: r.nodeId, role: r.role, ttlSeconds: r.ttlSeconds as CreateWatchLinkRequest['ttlSeconds'], label, title }+ if (r.role !== 'controller') return { req, password: null }+ if (controlPasswordProblem(r.password) !== null) return 'bad-password'+ return { req, password: r.password as string }}+/**+ * At most `slots` tasks run at once; the rest wait, and get a slot in the order they asked (FIFO). A+ * task's failure (a rejection, or a throw) frees its slot like a success. Nothing is ever refused.+ */+export function createFifoGate(slots: number): <T>(task: () => Promise<T>) => Promise<T> {+ let active = 0+ const waiting: (() => void)[] = []+ const release = (): void => {+ const next = waiting.shift()+ if (next) next() // the slot passes straight to the next in line+ else active--+ }+ return <T>(task: () => Promise<T>): Promise<T> =>+ new Promise<T>((resolve, reject) => {+ const run = (): void => {+ let p: Promise<T>+ try {+ p = Promise.resolve(task())+ } catch (err) {+ p = Promise.reject(err)+ }+ p.then(resolve, reject).finally(release)+ }+ if (active < slots) {+ active+++ run()+ } else waiting.push(run)+ })+}++/** A live Control link's record, with its control state. */+type ControlRecord = WatchLinkRecord & { control: WatchLinkControlRecord }+/** 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) }@@ -191,6 +277,8 @@ export function sendToOwners(}const errorText = (err: unknown): string => (err instanceof Error ? err.message : String(err))+/** An error's NAME only: what failed around a password (its hash, its check) may be in the message. */+const errorName = (err: unknown): string => (err instanceof Error ? err.name : 'not an Error')const TIMEOUT = Symbol('timeout')export function createWatchLinkService(deps: WatchLinkServiceDeps): WatchLinkService {@@ -200,6 +288,10 @@ export function createWatchLinkService(deps: WatchLinkServiceDeps): WatchLinkSerconst createHost = deps.createHost ?? createLinkHostconst persistTimeoutMs = deps.persistTimeoutMs ?? PERSIST_TIMEOUT_MSconst workspaceWaitMs = deps.workspaceWaitMs ?? WORKSPACE_READY_TIMEOUT_MS+ const hashPassword = deps.hashPassword ?? hashControlPassword+ const verifyPassword = deps.verifyPassword ?? verifyControlPassword+ // ONE gate for every scrypt run of this service — the process has one — whichever link asks.+ const scrypt = createFifoGate(SCRYPT_SLOTS)// A wait on init covers init's own (bounded) workspace wait plus the links file's load: init's// bound always fires first, so a slow workspace never reads as a failed write.const initWaitMs = workspaceWaitMs + persistTimeoutMs@@ -282,8 +374,8 @@ export function createWatchLinkService(deps: WatchLinkServiceDeps): WatchLinkSername: v.name === null ? null : stripBidiControls(v.name),joinedAt: v.joinedAt,waiting: v.waiting === true,- controlling: false,- typing: false+ controlling: v.controlling === true,+ typing: v.typing === true}))} catch (err) {warn(`reading a link's state failed: ${errorText(err)}`)@@ -300,7 +392,7 @@ export function createWatchLinkService(deps: WatchLinkServiceDeps): WatchLinkSerurl: formatWatchLink(r.linkId, r.secret),status,viewers,- control: null+ control: r.role === 'controller' && r.control ? { enabled: r.control.enabled, locked: r.control.locked } : null}}const list = (): WatchLinkView[] => (unsupported ? [] : [...records.values()].map(viewOf))@@ -348,6 +440,32 @@ export function createWatchLinkService(deps: WatchLinkServiceDeps): WatchLinkSerreturn p}+ function controlSupportOf(nodeId: string): ControlSupport {+ try {+ const s = deps.controlSupport?.(nodeId)+ return s === 'ok' || s === 'unsupported' ? s : 'unknown'+ } catch {+ return 'unknown' // a check that cannot answer leaves the create to decide+ }+ }++ /** The scrypt check of a Control link, through the gate. The record's {salt, hash} is read when the+ * check RUNS — a password change swaps them in place, and a check queued for a slot meanwhile must+ * be made against the new one. Never rejects (a failed check is a wrong password). */+ function checkPassword(r: WatchLinkRecord, pw: string): Promise<boolean> {+ if (r.role !== 'controller' || !r.control) return Promise.resolve(false)+ return scrypt(() => {+ const c = r.control+ return c ? verifyPassword(pw, { salt: c.salt, hash: c.hash }) : Promise.resolve(false)+ }).then(+ (ok) => ok === true,+ (err) => {+ warn(`checking a control password failed (${errorName(err)})`)+ return false+ }+ )+ }+function revokeServer(linkId: string): void {const ent = deps.entitlement()if (!ent) return@@ -433,12 +551,29 @@ export function createWatchLinkService(deps: WatchLinkServiceDeps): WatchLinkSeronViewerJoined: (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 }),- // A Control link is not wired to the owner's controls yet: no password opens it, and a lock- // holds in memory only (the host reads `record.control` and never writes it).- verifyPassword: async () => false,- onControlTaken: () => {},+ verifyPassword: (pw) => checkPassword(r, pw),+ onControlTaken: (name) => {+ notice({+ kind: 'control-taken',+ linkId: r.linkId,+ nodeId: r.nodeId,+ title: stripBidiControls(r.title),+ // A name the viewer gave itself (sanitized by the host); no bidi override reaches the owner.+ name: stripBidiControls(String(name))+ })+ emitState()+ },onControlLocked: () => {+ // SYNCHRONOUSLY, before any I/O: the host's lock rests on this flag (it reads the record live+ // and never writes it). Never undone: a lock whose write fails still holds until quit.if (r.control) r.control.locked = true+ if (records.get(r.linkId) === r) {+ void persist().then((saved) => {+ if (!saved) warn("a Control link's lock could not be saved; it holds until nodeterm quits")+ })+ }+ notice({ kind: 'control-locked', linkId: r.linkId, nodeId: r.nodeId, title: stripBidiControls(r.title) })+ emitState()}})} catch (err) {@@ -544,13 +679,54 @@ export function createWatchLinkService(deps: WatchLinkServiceDeps): WatchLinkSerconst init = (): Promise<void> =>(initPromise ??= runInit().catch((err) => warn(`resuming live links failed: ${errorText(err)}`)))+ /** The record of a LIVE Control link (listed, a controller, with its control state), or null. */+ function liveControl(linkId: unknown): ControlRecord | null {+ if (unsupported || stopped || typeof linkId !== 'string') return null+ const r = records.get(linkId)+ return r && r.role === 'controller' && r.control ? (r as ControlRecord) : null+ }+ function tellHost(linkId: string, fn: (h: LinkHost) => void): void {+ const h = hosts.get(linkId)+ if (!h) return+ try {+ fn(h)+ } catch (err) {+ warn(`telling a link host about a control change failed: ${errorText(err)}`)+ }+ }++ /**+ * An owner's change to a Control link. Applied in memory and told to the host AT ONCE (typing off or+ * a replaced password must not wait on the disk), then written. A write that fails, or does not+ * answer within PERSIST_TIMEOUT_MS, undoes the change (`undo` restores only what is still this+ * change's own value), tells the host again, queues the corrected list behind the write, and answers+ * false: the owner is never told a change was kept that the next launch would not have.+ */+ async function changeControl(+ r: ControlRecord,+ o: { apply(): void; undo(): void; host(h: LinkHost): void; undoHost(h: LinkHost): void }+ ): Promise<boolean> {+ o.apply()+ tellHost(r.linkId, o.host)+ emitState()+ const written = await within(persist(), persistTimeoutMs)+ if (written === true) return true+ o.undo()+ tellHost(r.linkId, o.undoHost)+ if (records.get(r.linkId) === r) void persist()+ emitState()+ warn("an owner's change to a Control link could not be saved; it was undone")+ return false+ }+return {init,async create(raw) {if (unsupported || stopped) return fail('unsupported')- const req = parseRequest(raw)- if (!req) return fail('bad-request')+ const parsed = parseRequest(raw)+ if (parsed === 'bad-request' || parsed === 'bad-password') return fail(parsed)+ const req = parsed.reqif (!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.@@ -560,11 +736,27 @@ export function createWatchLinkService(deps: WatchLinkServiceDeps): WatchLinkSer}if (stopped) return fail('unsupported')if (nodeStateOf(req.nodeId) !== 'present') return fail('node-missing')+ // Before any request: a terminal whose key bindings are session-wide (Zellij) is never typed into.+ if (req.role === 'controller' && controlSupportOf(req.nodeId) === 'unsupported') return fail('control-unsupported')if (records.size + creating + opaqueHeld() >= MAX_LINKS_PER_MACHINE) return fail('limit-machine')const ent = deps.entitlement()if (!ent) return fail('not-entitled')creating++try {+ // Hashed BEFORE the server row exists: a hash that fails creates nothing anywhere. Only the+ // {salt, hash} goes on; the plaintext is not referenced past this.+ let control: WatchLinkControlRecord | undefined+ if (req.role === 'controller' && parsed.password !== null) {+ let h: ControlPasswordHash+ try {+ h = await scrypt(() => hashPassword(parsed.password as string))+ } catch (err) {+ warn(`hashing a control password failed (${errorName(err)}); nothing was created`)+ return fail('network')+ }+ parsed.password = null+ control = { enabled: true, locked: false, salt: h.salt, hash: h.hash }+ }const secret = newWatchLinkSecret()const joinKeyHash = await sha256Hex(deriveWatchLinkKeys(secret).joinKey)const created = await deps.api.create(ent, joinKeyHash, req.ttlSeconds)@@ -580,8 +772,10 @@ export function createWatchLinkService(deps: WatchLinkServiceDeps): WatchLinkSerlabel: req.label,title: req.title,createdAt: now(),+ // null for an Unlimited link (the API accepts a null only for a `ttlSeconds` 0 request).expiresAt: created.expiresAt,- secret+ secret,+ ...(control ? { control } : {})}writing.set(record.linkId, record)let written: boolean | typeof TIMEOUT@@ -705,6 +899,78 @@ export function createWatchLinkService(deps: WatchLinkServiceDeps): WatchLinkSer}},+ async setControl(linkId, enabled) {+ const r = liveControl(linkId)+ if (!r || typeof enabled !== 'boolean') return false+ const c = r.control+ if (c.enabled === enabled) return true+ const before = c.enabled+ return changeControl(r, {+ apply: () => {+ c.enabled = enabled+ },+ undo: () => {+ if (c.enabled === enabled) c.enabled = before+ },+ host: (h) => h.controlChanged(),+ undoHost: (h) => h.controlChanged()+ })+ },++ async setPassword(linkId, pw) {+ if (!liveControl(linkId) || controlPasswordProblem(pw) !== null) return false+ let h: ControlPasswordHash+ try {+ h = await scrypt(() => hashPassword(pw))+ } catch (err) {+ warn(`hashing a new control password failed (${errorName(err)}); nothing changed`)+ return false+ }+ // The link may have ended (or this run stopped) while the hash ran.+ const r = liveControl(linkId)+ if (!r) return false+ const c = r.control+ const before = { salt: c.salt, hash: c.hash }+ return changeControl(r, {+ apply: () => {+ c.salt = h.salt+ c.hash = h.hash+ },+ undo: () => {+ if (c.hash !== h.hash) return // a later password replaced this one meanwhile+ c.salt = before.salt+ c.hash = before.hash+ },+ // Either way every controller drops back to watching: one that unlocked with the new password+ // during the write must unlock again with the one that holds.+ host: (x) => x.passwordChanged(),+ undoHost: (x) => x.passwordChanged()+ })+ },++ async allowControl(linkId) {+ const r = liveControl(linkId)+ if (!r) return false+ const c = r.control+ if (!c.locked) return true+ return changeControl(r, {+ apply: () => {+ c.locked = false+ },+ // Locking again is always safe (and a lock that arrived meanwhile is the same state).+ undo: () => {+ c.locked = true+ },+ host: (h) => h.allowControl(),+ undoHost: (h) => h.controlChanged()+ })+ },++ controlSupport(nodeId) {+ if (typeof nodeId !== 'string' || !isSafeNodeId(nodeId)) return 'unknown'+ return controlSupportOf(nodeId)+ },+shutdown() {if (!stopped) {stopped = true@@ -762,4 +1028,13 @@ export function registerWatchLinkIpc(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) : [])+ p.handleWithSender(IPC.watchLinkSetControl, (sender: number, id: unknown, enabled: unknown) =>+ owner(sender) && str(id) && typeof enabled === 'boolean' ? s.setControl(id, enabled) : false)+ // The password is handed straight to the service, which keeps only its hash; never logged here.+ p.handleWithSender(IPC.watchLinkSetPassword, (sender: number, id: unknown, pw: unknown) =>+ owner(sender) && str(id) && str(pw) ? s.setPassword(id, pw) : false)+ p.handleWithSender(IPC.watchLinkAllowControl, (sender: number, id: unknown) =>+ owner(sender) && str(id) ? s.allowControl(id) : false)+ p.handleWithSender(IPC.watchLinkControlSupport, (sender: number, nodeId: unknown) =>+ owner(sender) && str(nodeId) ? s.controlSupport(nodeId) : ('unknown' satisfies ControlSupport))}diff --git a/src/core/watch-link/store.test.ts b/src/core/watch-link/store.test.tsindex 798954af0..c9a1997b8 100644--- a/src/core/watch-link/store.test.ts+++ b/src/core/watch-link/store.test.ts@@ -601,6 +601,31 @@ describe('controller records and unlimited expiry', () => {expect(await new WatchLinkStore({ file: f, seal, unseal }).load()).toEqual([ctl()])})+ // `control` IFF the role is 'controller' at WRITE time too: a record the next load would drop is+ // never written. The whole save answers 'failed' and the file stays as it was (a bug, made loud).+ it("refuses to write a record that breaks control-iff-controller: 'failed', the file untouched", async () => {+ const f = file()+ const s = new WatchLinkStore({ file: f, seal, unseal })+ expect(await s.save([ctl()])).toBe('saved')+ const before = readFileSync(f, 'utf8')+ const broken: WatchLinkRecord[] = [+ rec({ role: 'viewer', control }),+ rec({ role: 'commenter', control }),+ rec({ role: 'controller' }),+ ctl({ control: { ...control, salt: b64(new Uint8Array(15).fill(1)) } }),+ ctl({ control: { ...control, hash: 'not base64!' } }),+ ctl({ control: { ...control, enabled: 'yes' } as unknown as WatchLinkRecord['control'] }),+ ctl({ control: { ...control, locked: undefined } as unknown as WatchLinkRecord['control'] })+ ]+ for (const r of broken) {+ expect(await s.save([rec({ linkId: 'OtherLinkIjKlMnOpQrStU' }), r]), JSON.stringify(r.control ?? r.role)).toBe('failed')+ expect(readFileSync(f, 'utf8')).toBe(before)+ }+ // A store that refused a bad list still writes the next good one.+ expect(await s.save([rec()])).toBe('saved')+ expect(await s.load()).toEqual([rec()])+ })+it('never writes the plaintext password: the file holds only its salt and scrypt hash', async () => {const password = 'correct horse battery staple'const h = await hashControlPassword(password)diff --git a/src/core/watch-link/store.ts b/src/core/watch-link/store.tsindex d890c62ba..94849250c 100644--- a/src/core/watch-link/store.ts+++ b/src/core/watch-link/store.ts@@ -43,7 +43,8 @@// written as it is, not sealed: the hash is scrypt'd, and anyone who can read this 0600 file under// userData is already this user. `control` is present IFF the role is 'controller', and a load drops// any entry that breaks that rule: a hand-edited file cannot give a viewer link a password, and a-// controller link with no password is not a link this build can host.+// controller link with no password is not a link this build can host. A save refuses ('failed', the+// file untouched) a list holding such a record: it would be written only for the next load to drop it.//// AN UNLIMITED LINK has `expiresAt: null`: it lives until it is stopped. An opaque one is carried// until it is discarded, never dropped for time.@@ -305,6 +306,12 @@ export class WatchLinkStore {}async save(records: readonly WatchLinkRecord[]): Promise<SaveOutcome> {+ // `control` IFF the role is 'controller', and then well-formed — at WRITE time as on load: a record+ // the next load would drop is never written. The whole save fails and the file stays as it was:+ // such a record is a bug, and a link the next run silently loses is the worst way to find it.+ for (const r of records) {+ if (r.role === 'controller' ? !readControl(r.control) : r.control !== undefined) return 'failed'+ }const links: FileEntry[] = []let outcome: SaveOutcome = 'saved'// Only the records in THIS list keep a cached sealed form: a stopped link's goes with it.diff --git a/src/main/index.ts b/src/main/index.tsindex 6fc73a230..bd935b59e 100644--- a/src/main/index.ts+++ b/src/main/index.ts@@ -3309,6 +3309,10 @@ app.whenReady().then(async () => {...(ref ? { sshRemote: { conn: ref.conn, controlPath: ref.controlPath, remoteCwd: ref.remoteCwd ?? '~' } } : {})}}),+ // Can a Control link type into this node? A node of an SSH project runs in its HOST's tmux (Zellij+ // is a local-only backend), so this machine's backend choice says nothing about it: 'ok' (a host+ // with no tmux at all answers every keystroke false, which the link host reports as dropped).+ controlSupport: (nodeId) => (workspaceStore.sshProjectIdForNode(nodeId) ? 'ok' : ptyManager.nodeControlSupport(nodeId)),emit: (channel, ...args) => sendToOwners(corePlatform, channel, ...args)})registerWatchLinkIpc(corePlatform, watchLinks)diff --git a/src/main/watch-link-control-wiring.test.ts b/src/main/watch-link-control-wiring.test.tsnew file mode 100644index 000000000..a77f58668--- /dev/null+++ b/src/main/watch-link-control-wiring.test.ts@@ -0,0 +1,70 @@+// Source-level: a Control link's hops close over shell objects no unit test can build (PtyManager, the+// workspace store, the Electron and Server Edition platforms), and a dropped hop compiles fine while+// shipping the feature inert — no `controlSupport` and every Zellij node is offered Control; a channel+// left out of `registerWatchLinkIpc` and the owner's button answers nothing. Same remedy as+// watch-link-wiring.test.ts and hook-verified-parity.test.ts.+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 from `marker` up to the next line that closes a block 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'++const CONTROL_CHANNELS = ['watchLinkSetControl', 'watchLinkSetPassword', 'watchLinkAllowControl', 'watchLinkControlSupport']+const ALL_CHANNELS = [+ 'watchLinkCreate', 'watchLinkList', 'watchLinkRevoke', 'watchLinkRevokeAll', 'watchLinkKick',+ 'watchLinkChatSend', 'watchLinkChatHistory', ...CONTROL_CHANNELS+]++describe('live-link Control wiring', () => {+ for (const shell of [MAIN, SERVER]) {+ it(`${shell} hands the service PtyManager's control check, local nodes only`, () => {+ const block = blockAfter(read(shell), 'watchLinks = createWatchLinkService({', ' ')+ expect(block).toMatch(/controlSupport: \(nodeId\) =>/)+ expect(block).toMatch(/ptyManager\.nodeControlSupport\(nodeId\)/)+ // A node of an SSH project runs in its HOST's tmux: the local backend choice says nothing about it.+ expect(block).toMatch(/workspaceStore\.sshProjectIdForNode\(nodeId\) \? 'ok' : ptyManager\.nodeControlSupport\(nodeId\)/)+ })+ }++ it('registerWatchLinkIpc registers all eleven owner request channels, each behind the owner check', () => {+ const src = read('src/core/watch-link/service.ts')+ const reg = src.slice(src.indexOf('export function registerWatchLinkIpc('))+ for (const ch of ALL_CHANNELS) {+ const at = reg.indexOf(`p.handleWithSender(IPC.${ch},`)+ expect(at, ch).toBeGreaterThan(-1)+ // The handler's own line(s) up to the next registration ask `owner(sender)` first.+ const next = reg.indexOf('p.handleWithSender(', at + 1)+ expect(reg.slice(at, next < 0 ? undefined : next), ch).toMatch(/owner\(sender\)/)+ }+ expect(reg.match(/p\.handleWithSender\(IPC\.watchLink/g)).toHaveLength(ALL_CHANNELS.length)+ })++ it('the preload, the Server Edition bridge and the relay stub all carry the four Control members', () => {+ const preload = read('src/preload/index.ts')+ for (const ch of CONTROL_CHANNELS) expect(preload, ch).toContain(`IPC.${ch}`)+ const bridge = read('src/renderer/bridge/ws-bridge.ts')+ const api = bridge.slice(bridge.indexOf('export function buildWatchLinkApi('))+ for (const ch of CONTROL_CHANNELS) expect(api, ch).toContain(`client.request(IPC.${ch}`)+ // A dropped socket answers the safe value, never a rejection the UI did not expect.+ expect(api).toMatch(/IPC\.watchLinkControlSupport, nodeId\) as Promise<ControlSupport>\)\.catch\(\(\): ControlSupport => 'unknown'\)/)+ const stub = read('src/renderer/bridge/stubs.ts')+ const relay = stub.slice(stub.indexOf(' watchLink: {'))+ for (const m of ['setControl', 'setPassword', 'allowControl', 'controlSupport']) expect(relay, m).toMatch(new RegExp(`${m}: async`))+ })++ it('the pty seam hands joins their input route and input to the pane, from PtyManager', () => {+ const seam = read('src/core/watch-link/pty-seam.ts')+ expect(seam).toMatch(/input: pty\.watcherInputRoute\(res\.sessionId\)/)+ expect(seam).toMatch(/input: \(sessionId, chunk\) => pty\.controlInput\(sessionId, chunk\)/)+ })+})diff --git a/src/server/index.ts b/src/server/index.tsindex bb6342bf6..4ad027800 100644--- a/src/server/index.ts+++ b/src/server/index.ts@@ -1117,6 +1117,9 @@ export async function startServer(// 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 } : {})),+ // The same check as the desktop (links stay unsupported here, but the member answers): a node of an+ // SSH project would run in its host's tmux, never this core's Zellij.+ controlSupport: (nodeId) => (workspaceStore.sshProjectIdForNode(nodeId) ? 'ok' : ptyManager.nodeControlSupport(nodeId)),emit: (channel, ...args) => sendToOwners(platform, channel, ...args),unsupported: true})diff --git a/src/shared/host-control.test.ts b/src/shared/host-control.test.tsindex d889d4e4b..dcbb44958 100644--- a/src/shared/host-control.test.ts+++ b/src/shared/host-control.test.ts@@ -70,6 +70,13 @@ describe('isHostOnlyChannel', () => {)expect(owner).toHaveLength(14)for (const ch of owner) expect(isHostOnlyChannel(ch), ch).toBe(true)+ // The Control link's owner verbs by name: typing on/off, a new password, allow-again and the+ // terminal check. A relay peer (a hosted editor included) that could reach them would type into the+ // host's terminal through any of its Control links, or set the password that opens one.+ for (const ch of [IPC.watchLinkSetControl, IPC.watchLinkSetPassword, IPC.watchLinkAllowControl, IPC.watchLinkControlSupport]) {+ expect(owner, ch).toContain(ch)+ 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