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
fix(watch-link): keep sealed links through a keychain that stops sealing, and tighten the registry
reviewa32789936f8c
diff --git a/src/core/watch-link/service.test.ts b/src/core/watch-link/service.test.tsindex dab0e4ea6..8c6dc652f 100644--- a/src/core/watch-link/service.test.ts+++ b/src/core/watch-link/service.test.ts@@ -6,6 +6,7 @@ import {createWatchLinkService,registerWatchLinkIpc,sendToOwners,+ shutdownWithin,workspaceNodeState,type WatchLinkNodeState,type WatchLinkService,@@ -106,6 +107,7 @@ interface Opts {workspaceReady?: () => Promise<unknown>unsupported?: booleanpersistTimeoutMs?: number+ workspaceWaitMs?: numbernow?: () => number}function service(o: Opts = {}) {@@ -130,6 +132,7 @@ function service(o: Opts = {}) {createHost: hosts.createHost,...(o.unsupported ? { unsupported: true } : {}),...(o.persistTimeoutMs ? { persistTimeoutMs: o.persistTimeoutMs } : {}),+ ...(o.workspaceWaitMs ? { workspaceWaitMs: o.workspaceWaitMs } : {}),...(o.now ? { now: o.now } : {})})services.push(s)@@ -155,7 +158,7 @@ const flush = async (n = 20) => {for (let i = 0; i < n; i++) await Promise.resolve()}/** A store that records every save and answers the outcomes a test chose. */-function fakeStore(o: { load?: () => Promise<WatchLinkRecord[]>; save?: (r: readonly WatchLinkRecord[]) => Promise<SaveOutcome> } = {}) {+function fakeStore(o: { load?: () => Promise<WatchLinkRecord[]>; save?: (r: readonly WatchLinkRecord[]) => Promise<SaveOutcome>; opaque?: number } = {}) {const saves: WatchLinkRecord[][] = []let discarded = 0const store: Store = {@@ -166,7 +169,8 @@ function fakeStore(o: { load?: () => Promise<WatchLinkRecord[]>; save?: (r: read},discardOpaque: () => {discarded++- }+ },+ opaqueCount: () => o.opaque ?? 0}return { store, saves, discarded: () => discarded }}@@ -195,7 +199,7 @@ describe('createWatchLinkService — create', () => {expect(await t.s.create(req({ nodeId: '../x' }))).toEqual(bad)expect(await t.s.create(req({ nodeId: 12 }))).toEqual(bad)expect(await t.s.create(req({ label: '' }))).toEqual(bad)- expect(await t.s.create(req({ label: '\u0007 ' }))).toEqual(bad)+ expect(await t.s.create(req({ label: '\u0007\u202e ' }))).toEqual(bad)expect(await t.s.create(req({ label: 5 }))).toEqual(bad)expect(await t.s.create(null)).toEqual(bad)expect(await t.s.create('x')).toEqual(bad)@@ -211,7 +215,7 @@ describe('createWatchLinkService — create', () => {it('cleans the label and title: controls and bidi overrides stripped, capped in UTF-16 units without splitting a pair', async () => {const t = service()- const r = await t.s.create(req({ label: ' Ada\u0000 ', title: `x${'😀'.repeat(50)}` }))+ const r = await t.s.create(req({ label: ' A\u202eda\u0000\u200f ', title: `x\u2066${'😀'.repeat(50)}` }))if (!r.ok) throw new Error(r.error)expect(r.link.label).toBe('Ada')expect(r.link.title).toBe(`x${'😀'.repeat(39)}`) // 1 + 78 units; one more pair would be 81 > 80@@ -307,6 +311,47 @@ describe('createWatchLinkService — create', () => {expect(t.hosts.made.map((h) => h.record.linkId)).toEqual(['Link000000000000000001', 'Link000000000000000002'])})+ it('links the keychain could not unseal this run count against the cap (R46/M3)', async () => {+ const f = fakeStore({ opaque: 3 })+ const t = service({ store: f.store })+ expect((await t.s.create(req())).ok).toBe(true)+ expect((await t.s.create(req())).ok).toBe(true)+ expect(await t.s.create(req())).toEqual({ ok: false, error: 'limit-machine' }) // 2 + 3 opaque = 5+ expect(t.calls.filter((c) => c === 'create')).toHaveLength(2)+ })++ it('a node that leaves every project while the record is being written: node-missing, revoked, off disk (R46/M4)', async () => {+ const held = deferred<SaveOutcome>()+ let saves = 0+ const f = fakeStore({ save: () => (++saves === 1 ? held.promise : Promise.resolve('saved')) })+ const t = service({ store: f.store })+ const creating = t.s.create(req())+ await vi.waitFor(() => expect(saves).toBe(1))+ t.nodes.set('n1', 'absent') // deleted during the write; no workspace change could see this record+ held.resolve('saved')+ expect(await creating).toEqual({ ok: false, error: 'node-missing' })+ expect(t.calls).toContain('revoke Link000000000000000001')+ expect(t.hosts.made).toEqual([])+ expect(t.s.list()).toEqual([])+ expect(f.saves.at(-1)).toEqual([]) // the list without it, queued behind the write that carried it+ })++ it('a create is not blocked by a workspace load that never finishes: init decides after its own bound (R46/M5)', async () => {+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})+ const f = fakeStore({ load: async () => [record({ nodeId: 'n2' })] })+ const t = service({+ store: f.store,+ workspaceReady: () => new Promise(() => {}),+ workspaceWaitMs: 20,+ nodes: new Map([['n1', 'present'], ['n2', 'unknown']])+ })+ expect((await t.s.create(req())).ok).toBe(true)+ expect(t.s.list().map((l) => l.nodeId).sort()).toEqual(['n1', 'n2']) // the resumed link is kept (unknown)+ expect(t.calls.filter((c) => c.startsWith('revoke '))).toEqual([])+ expect(warn.mock.calls.filter(([l]) => /did not finish loading/.test(String(l)))).toHaveLength(1)+ warn.mockRestore()+ })+it('waits for init: a create during the boot load counts the resumed links and never hosts one twice (G11)', async () => {const loading = deferred<WatchLinkRecord[]>()const f = fakeStore({ load: () => loading.promise })@@ -324,10 +369,15 @@ describe('createWatchLinkService — create', () => {})it('a create waiting on an init that never settles is bounded too', async () => {+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})const f = fakeStore({ load: () => new Promise(() => {}) })- const t = service({ store: f.store, persistTimeoutMs: 20 })+ const t = service({ store: f.store, persistTimeoutMs: 20, workspaceWaitMs: 20 })+ expect(await t.s.create(req())).toEqual({ ok: false, error: 'persist-failed' })expect(await t.s.create(req())).toEqual({ ok: false, error: 'persist-failed' })expect(t.calls).not.toContain('create')+ // Diagnosable, once: it is the links file that did not load, not a failed write.+ expect(warn.mock.calls.filter(([l]) => /links file did not load/.test(String(l)))).toHaveLength(1)+ warn.mockRestore()})it('the Server Edition (unsupported): create answers unsupported, list is empty, nothing is loaded or hosted (R43)', async () => {@@ -396,7 +446,7 @@ describe('createWatchLinkService — ending a link', () => {it('Stop all reaches the server even when the boot load hangs (a stop never waits on the disk)', async () => {const f = fakeStore({ load: () => new Promise(() => {}) })- const t = service({ store: f.store, persistTimeoutMs: 20 })+ const t = service({ store: f.store, persistTimeoutMs: 20, workspaceWaitMs: 20 })await t.s.revokeAll()await t.s.revoke('Link000000000000000001')expect(t.calls).toEqual(['revokeAll'])@@ -642,12 +692,13 @@ describe('createWatchLinkService — the host seams', () => {const r = await t.s.create(req({ role: 'commenter' }))if (!r.ok) throw new Error('create failed')const h = t.hosts.made[0]- h.deps.onChat({ id: 'x', name: 'Eve', text: 'hi there', at: 1, from: 'viewer' })+ h.deps.onChat({ id: 'x', name: 'E\u202eve\u061c', text: 'hi\u2066 there \u{1F468}\u200d\u{1F469}', at: 1, from: 'viewer' })const chat = t.emitted.find(([ch]) => ch === IPC.watchLinkChat)- expect(chat?.[1]).toEqual([r.link.linkId, { id: 'x', name: 'Eve', text: 'hi there', at: 1, from: 'viewer' }])- h.chat = [{ id: 'y', name: 'Mal', text: 'ab', at: 2, from: 'viewer' }]+ // Bidi (ALM included) gone; the ZWJ joining an emoji sequence stays.+ expect(chat?.[1]).toEqual([r.link.linkId, { id: 'x', name: 'Eve', text: 'hi there \u{1F468}\u200d\u{1F469}', at: 1, from: 'viewer' }])+ 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: 'Eve', joinedAt: 5 }]+ h.viewers = [{ viewerId: 'v-1', name: 'E\u202eve', joinedAt: 5 }]expect(t.s.list()[0].viewers).toEqual([{ viewerId: 'v-1', name: 'Eve', joinedAt: 5 }])})@@ -665,6 +716,41 @@ describe('createWatchLinkService — the host seams', () => {})})+describe('state pushes are coalesced (R46/M7)', () => {+ it('one push per end, although the stopped host also reports a change; one push for a whole shutdown', async () => {+ const t = service()+ for (const nodeId of ['n1', 'n2', 'n1']) expect((await t.s.create(req({ nodeId }))).ok).toBe(true)+ // Like the real link host: `stop` reports a change.+ for (const h of t.hosts.made) {+ const deps = h.deps+ h.stopped = new Proxy(h.stopped, {+ get: (arr, k) => (k === 'push' ? (...a: string[]) => (deps.onChange(), arr.push(...a)) : Reflect.get(arr, k))+ })+ }+ const before = t.states().length+ await t.s.revoke(t.s.list()[0].linkId)+ await flush()+ expect(t.states().length - before).toBe(1)+ expect(t.states().at(-1)).toHaveLength(2)+ await t.s.shutdown()+ await flush()+ expect(t.states().length - before).toBe(2)+ })+})++describe('shutdownWithin (R46/M6)', () => {+ it('answers at the bound when the last write hangs, at once when it lands, and nothing for no service', async () => {+ const hung = { shutdown: () => new Promise<void>(() => {}) } as unknown as WatchLinkService+ const t0 = Date.now()+ await shutdownWithin(hung, 30)+ expect(Date.now() - t0).toBeGreaterThanOrEqual(25)+ const quick = { shutdown: vi.fn(async () => {}) } as unknown as WatchLinkService+ await shutdownWithin(quick, 60_000) // would time the test out if it waited for the bound+ expect((quick as unknown as { shutdown: ReturnType<typeof vi.fn> }).shutdown).toHaveBeenCalledTimes(1)+ await shutdownWithin(null, 60_000)+ })+})+describe('registerWatchLinkIpc / sendToOwners', () => {it('the IPC answers owners only', async () => {const t = service()@@ -740,3 +826,14 @@ describe('createWatchLinkService — real store', () => {expect(JSON.parse(readFileSync(t.file, 'utf8')).links).toEqual([])})})++// 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', () => {+ const LITERAL = new RegExp('[\\u061c\\u200b-\\u200f\\u202a-\\u202e\\u2066-\\u2069\\ufeff]')+ for (const f of ['service.ts', 'service.test.ts', 'pty-seam.ts', '../../shared/watch-link-types.ts', '../../shared/presence.ts']) {+ it(f, () => {+ expect(LITERAL.test(readFileSync(join(__dirname, f), 'utf8'))).toBe(false)+ })+ }+})diff --git a/src/core/watch-link/service.ts b/src/core/watch-link/service.tsindex 10ffc26f0..cf08e43a3 100644--- a/src/core/watch-link/service.ts+++ b/src/core/watch-link/service.ts@@ -63,15 +63,18 @@ import type { RelayTransport } from '../relay/relay-socket'/** setTimeout's own ceiling (a longer delay fires at once). A link lives ≤ 24 h, far below it. */const MAX_DELAY_MS = 2_147_483_647-/** The longest a create waits for its local write (or for the boot load it must count). */+/** The longest a create waits for its local write (or for the links file's boot load). */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_000export type WatchLinkNodeState = 'present' | 'absent' | 'unknown'export interface WatchLinkServiceDeps {api: WatchLinkApiClientrelayUrl: string- store: Pick<WatchLinkStore, 'load' | 'save' | 'discardOpaque'>+ store: Pick<WatchLinkStore, 'load' | 'save' | 'discardOpaque' | 'opaqueCount'>/** The stored Pro entitlement token, or null. Travels only in the API client's JSON body. */entitlement(): string | null/** False in a build that may not relay (an unpackaged dev build): no create, and resumed links@@ -94,6 +97,8 @@ export interface WatchLinkServiceDeps {/** TEST ONLY. */persistTimeoutMs?: number/** TEST ONLY. */+ workspaceWaitMs?: number+ /** TEST ONLY. */createHost?: typeof createLinkHost/** TEST ONLY: the relay transport the link hosts dial. */transport?: () => RelayTransport@@ -188,6 +193,10 @@ export function createWatchLinkService(deps: WatchLinkServiceDeps): WatchLinkSerconst clearT = deps.clearTimeout ?? ((h: unknown) => clearTimeout(h as ReturnType<typeof setTimeout>))const createHost = deps.createHost ?? createLinkHostconst persistTimeoutMs = deps.persistTimeoutMs ?? PERSIST_TIMEOUT_MS+ const workspaceWaitMs = deps.workspaceWaitMs ?? WORKSPACE_READY_TIMEOUT_MS+ // 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 + persistTimeoutMsconst unsupported = deps.unsupported === trueconst records = new Map<string, WatchLinkRecord>()@@ -209,6 +218,12 @@ export function createWatchLinkService(deps: WatchLinkServiceDeps): WatchLinkSerconst fail = (error: CreateWatchLinkError): CreateWatchLinkResult => ({ ok: false, error })const warn = (line: string): void => console.warn(`[watch-link] ${line}`)+ const warned = new Set<string>()+ const warnOnce = (kind: string, line: string): void => {+ if (warned.has(kind)) return+ warned.add(kind)+ warn(line)+ }const persistentNow = (): boolean => !storeLatched && !sealRefusedfunction safeEmit(channel: string, ...args: unknown[]): void {@@ -279,7 +294,27 @@ export function createWatchLinkService(deps: WatchLinkServiceDeps): WatchLinkSer}}const list = (): WatchLinkView[] => (unsupported ? [] : [...records.values()].map(viewOf))- const emitState = (): void => safeEmit(IPC.watchLinkState, list())+ // Coalesced (R46/M7): ending a link stops its host, whose `stop` reports a change, and then the end+ // reports its own; a shutdown stops every host. One push per synchronous burst — each push carries+ // every link's URL, and the list is read when the push goes out, so it is never stale.+ let statePending = false+ const emitState = (): void => {+ if (statePending) return+ statePending = true+ queueMicrotask(() => {+ statePending = false+ safeEmit(IPC.watchLinkState, list())+ })+ }+ /** Links this machine holds but cannot host this run (sealed, keychain locked) — they count against+ * the cap like any link (R46/M3). */+ const opaqueHeld = (): number => {+ try {+ return deps.store.opaqueCount()+ } catch {+ return 0+ }+ }/** Write the current records. Called, not awaited, wherever the owner must not wait on the disk;* the store snapshots at call time and serializes its writes, so disk order is call order. */@@ -430,10 +465,14 @@ export function createWatchLinkService(deps: WatchLinkServiceDeps): WatchLinkSerasync function runInit(): Promise<void> {if (unsupported) returnif (deps.workspaceReady) {- try {- await deps.workspaceReady()- } catch {- // A failed load leaves nodes unknown, which keeps every link: the safe side.+ // A failed load leaves nodes unknown, which keeps every link: the safe side. A load that does+ // not finish (a stalled mount) is waited for no longer than WORKSPACE_READY_TIMEOUT_MS (R46/M5).+ const ready = await within(+ Promise.resolve().then(() => deps.workspaceReady!()).then(() => 'ready', () => 'failed'),+ workspaceWaitMs+ )+ if (ready === TIMEOUT) {+ warn(`the workspace did not finish loading within ${workspaceWaitMs} ms; resuming links whose node cannot be placed yet`)}}let loaded: WatchLinkRecord[] = []@@ -487,10 +526,13 @@ export function createWatchLinkService(deps: WatchLinkServiceDeps): WatchLinkSerif (!deps.relayAllowed()) return fail('relay-unavailable')// The resumed links count against the cap, and init must never start a host for a link a// create already started (G11). Bounded: a hung disk answers, it does not hang the dialog.- if ((await within(init(), persistTimeoutMs)) === TIMEOUT) return fail('persist-failed')+ if ((await within(init(), initWaitMs)) === TIMEOUT) {+ warnOnce('init-timeout', `the live-links file did not load within ${initWaitMs} ms`)+ return fail('persist-failed')+ }if (stopped) return fail('unsupported')if (nodeStateOf(req.nodeId) !== 'present') return fail('node-missing')- if (records.size + creating >= MAX_LINKS_PER_MACHINE) return fail('limit-machine')+ if (records.size + creating + opaqueHeld() >= MAX_LINKS_PER_MACHINE) return fail('limit-machine')const ent = deps.entitlement()if (!ent) return fail('not-entitled')creating++@@ -528,6 +570,13 @@ export function createWatchLinkService(deps: WatchLinkServiceDeps): WatchLinkSerrevokeServer(record.linkId)return fail(stopped ? 'unsupported' : 'persist-failed')}+ // The node may have left every project while the record was being written — a workspace+ // change could not see this record then (it is not a link yet). Absent now: undo it (R46/M4).+ if (nodeStateOf(record.nodeId) === 'absent') {+ void persist()+ revokeServer(record.linkId)+ return fail('node-missing')+ }records.set(record.linkId, record)start(record)emitState()@@ -545,14 +594,14 @@ export function createWatchLinkService(deps: WatchLinkServiceDeps): WatchLinkSerasync revoke(linkId) {if (unsupported || typeof linkId !== 'string') return- await within(init(), persistTimeoutMs) // no link exists before init; a hung load must not hang the stop+ await within(init(), initWaitMs) // no link exists before init; a hung load must not hang the stopend(linkId, 'revoked', { serverRevoke: true, notify: false })},async revokeAll() {if (unsupported) return// Bounded like revoke: on a disk that hangs, "Stop all" still reaches the server below.- await within(init(), persistTimeoutMs)+ await within(init(), initWaitMs)const gone = [...records.keys()].map(drop)// "Stop all" revokes every link of the license server-side, the ones this run cannot unseal too.try {@@ -632,6 +681,25 @@ export function createWatchLinkService(deps: WatchLinkServiceDeps): WatchLinkSer}}+/**+ * `shutdown()` bounded: the service's last write may hang on a stalled disk, and a shell's close must+ * not (R46/M6). The Server Edition awaits this in both close paths; the desktop races its own 1.5 s+ * flush instead. The timer is cleared (and never holds the process) either way.+ */+export async function shutdownWithin(s: WatchLinkService | null, ms: number): Promise<void> {+ if (!s) return+ let timer: ReturnType<typeof setTimeout> | undefined+ const bound = new Promise<void>((resolve) => {+ timer = setTimeout(resolve, ms)+ timer.unref?.()+ })+ try {+ await Promise.race([s.shutdown(), bound])+ } finally {+ clearTimeout(timer)+ }+}+/** The owner IPC. Relay peers never reach these handlers (the `watchLink:` prefix is host-only and* refused before any policy runs); the owner check is the belt behind that, for any other client. */export function registerWatchLinkIpc(diff --git a/src/core/watch-link/service.workspace.test.ts b/src/core/watch-link/service.workspace.test.tsnew file mode 100644index 000000000..4f1e1d30b--- /dev/null+++ b/src/core/watch-link/service.workspace.test.ts@@ -0,0 +1,149 @@+// The node-gone rule against the REAL workspace store (ruling R44). A lost or corrupt workspace.json+// is rebuilt from nothing during the run: the renderer's load sets the corrupt file aside and its+// unconditional boot save writes an EMPTY index. That index must not read as a complete read of every+// project — every node would be "absent" and every live link revoked a second after launch, while+// each project's own `.nodeterm/project.json` still holds its nodes.+import { describe, it, expect, afterEach } from 'vitest'+import { promises as fs } from 'node:fs'+import path from 'node:path'+import { testTmpDir } from '../test-tmp'+import { initPlatform, resetPlatformForTests } from '../platform'+import { fakePlatform } from '../platform-fake'+import { WorkspaceStore } from '../workspace-store'+import { createWatchLinkService, workspaceNodeState, type WatchLinkService } from './service'+import type { WatchLinkRecord } from './store'+import type { WatchLinkApi as ApiClient } from './api'+import type { LinkHost } from './link-host'+import type { Project, Workspace } from '../../shared/types'++const services: WatchLinkService[] = []+afterEach(async () => {+ for (const s of services.splice(0)) await s.shutdown()+ resetPlatformForTests()+})++const project = (cwd: string): Project => ({+ id: 'p1', name: 'foo', color: '#7aa2f7', viewport: { x: 0, y: 0, zoom: 1 }, cwd,+ nodes: [{ id: 'term-1', kind: 'terminal', position: { x: 0, y: 0 }, size: { width: 1, height: 1 }, title: 't', color: '#fff', group: null }]+})+const ws = (projects: Project[]): Workspace => ({ version: 2, activeProjectId: projects[0]?.id ?? '', projects })++/** A machine with one folder project holding node `term-1`, its index written by a previous run. */+async function machine() {+ const userData = testTmpDir('nt-wl-ws-')+ const projRoot = testTmpDir('nt-wl-proj-')+ initPlatform(fakePlatform({ userDataDir: userData }))+ await new WorkspaceStore().save(ws([project(projRoot)]))+ return { userData, projRoot, index: path.join(userData, 'workspace.json') }+}++/** The live-link service over this store, resuming one link to `term-1`. */+function linksOver(store: WorkspaceStore) {+ const calls: string[] = []+ const stopped: string[] = []+ const api: ApiClient = {+ create: async () => ({ ok: false, error: 'network' }),+ hostToken: async () => ({ ok: false, kind: 'network' }),+ status: async () => 'live',+ revoke: async (id) => {+ calls.push(`revoke ${id}`)+ return true+ },+ revokeAll: async () => true+ }+ const record: WatchLinkRecord = {+ linkId: 'Keep000000000000000000', nodeId: 'term-1', role: 'viewer', label: 'A', title: 't',+ createdAt: 0, expiresAt: Date.now() + 3_600_000, secret: new Uint8Array(32).fill(1)+ }+ const s = createWatchLinkService({+ api,+ relayUrl: 'wss://r',+ store: { load: async () => [record], save: async () => 'saved', discardOpaque: () => {}, opaqueCount: () => 0 },+ entitlement: () => 'ent',+ relayAllowed: () => true,+ nodeState: (id) => workspaceNodeState(store, id),+ clients: { attach: () => 1, detach: () => {} },+ pty: {+ join: async () => null, leave: () => {}, captureVisible: async () => ({ screen: '', cursor: null }),+ syncSize: async () => true, alive: () => true+ },+ emit: () => {},+ createHost: (): LinkHost => ({+ start: () => {}, stop: (r) => { stopped.push(r) }, kick: () => false, postSharerChat: () => null,+ chatHistory: () => [], status: () => 'live', viewers: () => []+ })+ })+ services.push(s)+ store.onPersist = () => s.onWorkspaceChanged()+ return { s, calls, stopped }+}+const settle = async () => {+ for (let i = 0; i < 20; i++) await Promise.resolve()+}++describe('an index rebuilt from nothing is never a complete read (R44)', () => {+ it('control: with a readable index, a node that leaves every project IS absent and its link ends', async () => {+ await machine()+ const store = new WorkspaceStore()+ await store.load({ sideline: false })+ const links = linksOver(store)+ await links.s.init()+ expect(workspaceNodeState(store, 'term-1')).toBe('present')+ await store.save(ws([])) // the user removed the project+ expect(workspaceNodeState(store, 'term-1')).toBe('absent')+ await settle()+ expect(links.calls).toEqual(['revoke Keep000000000000000000'])+ expect(links.stopped).toEqual(['node-gone'])+ })++ it('a CORRUPT index: boot read, the renderer sets it aside, its empty boot save — the node stays unknown, no link is revoked', async () => {+ const m = await machine()+ await fs.writeFile(m.index, '{nope')+ const store = new WorkspaceStore()+ await store.load({ sideline: false }) // the desktop's boot read (bootWorkspaceLoad)+ const links = linksOver(store)+ await links.s.init()+ expect(links.s.list()).toHaveLength(1)+ await store.load() // the renderer's load: sets the corrupt file aside+ expect((await fs.readdir(m.userData)).some((n) => n.startsWith('workspace.json.corrupt-'))).toBe(true)+ await store.save(ws([])) // the renderer's unconditional boot save: an EMPTY index+ expect(JSON.parse(await fs.readFile(m.index, 'utf8')).entries).toEqual([])+ expect(workspaceNodeState(store, 'term-1')).toBe('unknown')+ expect(store.knownNodeIds()).toBeUndefined()+ await settle()+ expect(links.calls).toEqual([])+ expect(links.stopped).toEqual([])+ expect(links.s.list()).toHaveLength(1)+ // The project file still holds the node: reopening the folder brings it back with the same id.+ expect(await fs.readFile(path.join(m.projRoot, '.nodeterm/project.json'), 'utf8')).toContain('term-1')+ })++ it('a DELETED index is the same (for the rest of the run, even once projects are added back)', async () => {+ const m = await machine()+ await fs.rm(m.index)+ const store = new WorkspaceStore()+ await store.load({ sideline: false })+ const links = linksOver(store)+ await links.s.init()+ await store.load()+ await store.save(ws([]))+ expect(workspaceNodeState(store, 'term-1')).toBe('unknown')+ const other = testTmpDir('nt-wl-other-')+ await store.save(ws([{ ...project(other), id: 'p2', nodes: [] }])) // a project added back, not the node's+ expect(workspaceNodeState(store, 'term-1')).toBe('unknown')+ await settle()+ expect(links.calls).toEqual([])+ })++ it('an index that could not be READ (EIO, EACCES) is the same: a failed read is never evidence', async () => {+ const m = await machine()+ await fs.rm(m.index)+ await fs.mkdir(m.index) // readFile answers EISDIR: the store falls back to an empty workspace+ const store = new WorkspaceStore()+ await store.load({ sideline: false })+ expect(store.knownNodeIds()).toBeUndefined()+ await fs.rmdir(m.index)+ await store.save(ws([]))+ expect(workspaceNodeState(store, 'term-1')).toBe('unknown')+ })+})diff --git a/src/core/watch-link/store.test.ts b/src/core/watch-link/store.test.tsindex 42f37f7f7..a4f2ae4ba 100644--- a/src/core/watch-link/store.test.ts+++ b/src/core/watch-link/store.test.ts@@ -381,6 +381,21 @@ describe('opaque entries (a sealed secret this run cannot unseal)', () => {expect(JSON.parse(readFileSync(f, 'utf8')).links).toEqual([sealedEntry])})+ it('opaqueCount() counts the ones still carried: not past their expiry, not discarded', async () => {+ const f = file()+ expect(await new WatchLinkStore({ file: f, seal, unseal }).save([rec(), other])).toBe('saved')+ let t = EXPIRES_AT - 1+ const s = new WatchLinkStore({ file: f, seal, unseal: locked, now: () => t })+ expect(s.opaqueCount()).toBe(0)+ await s.load()+ expect(s.opaqueCount()).toBe(2)+ t = EXPIRES_AT+ expect(s.opaqueCount()).toBe(0)+ t = EXPIRES_AT - 1+ s.discardOpaque()+ expect(s.opaqueCount()).toBe(0)+ })+it('discardOpaque() drops them from the next save ("Stop all": the server revoked them)', async () => {const f = file()expect(await new WatchLinkStore({ file: f, seal, unseal }).save([rec()])).toBe('saved')@@ -406,3 +421,76 @@ describe('opaque entries (a sealed secret this run cannot unseal)', () => {expect(JSON.parse(readFileSync(f, 'utf8')).links).toEqual([])})})++// Ruling R45: when the keychain starts refusing to SEAL mid-run, the links this run already holds a+// sealed form of — read at boot, or sealed by an earlier write — are written with that ciphertext; only+// a link that was never sealed is left out ('memory-only'). Writing no live link at all lost every+// link loaded fine at boot, and writing nothing would keep a link stopped offline on disk (hosted again+// at the next launch). A link no longer in the list is still dropped.+describe('a keychain that stops sealing mid-run (R45)', () => {+ const a = rec({ linkId: 'AaaaEfGhIjKlMnOpQrStUv', secret: new Uint8Array(32).fill(1) })+ const b = rec({ linkId: 'BbbbEfGhIjKlMnOpQrStUv', secret: new Uint8Array(32).fill(2) })+ const c = rec({ linkId: 'CcccEfGhIjKlMnOpQrStUv', secret: new Uint8Array(32).fill(3) })+ const switchable = () => {+ const state = { refuse: false }+ const flaky = (b: Buffer) => {+ if (state.refuse) throw new Error('keychain locked')+ return seal(b)+ }+ return { state, flaky }+ }+ const ids = (f: string) => (JSON.parse(readFileSync(f, 'utf8')).links as { linkId: string }[]).map((e) => e.linkId)++ it('boot-loaded links survive it with the ciphertext they were read with; a revoked one is gone; a new one is not written', async () => {+ const f = file()+ expect(await new WatchLinkStore({ file: f, seal, unseal }).save([a, b])).toBe('saved')+ const before = JSON.parse(readFileSync(f, 'utf8')).links+ const k = switchable()+ const s = new WatchLinkStore({ file: f, seal: k.flaky, unseal })+ expect(await s.load()).toEqual([a, b])+ k.state.refuse = true+ expect(await s.save([a, b])).toBe('saved') // everything it holds is on disk: nothing is memory-only+ expect(JSON.parse(readFileSync(f, 'utf8')).links).toEqual(before)+ expect(await s.save([a])).toBe('saved') // b stopped: gone from the file, not resurrected+ expect(ids(f)).toEqual([a.linkId])+ expect(await s.save([a, c])).toBe('memory-only') // c was never sealed: left out, a kept+ expect(ids(f)).toEqual([a.linkId])+ // Next launch, keychain back: a resumes; b (stopped) and c (never written) do not.+ expect(await new WatchLinkStore({ file: f, seal, unseal }).load()).toEqual([a])+ })++ it('a link sealed by an earlier write this run survives it too', async () => {+ const f = file()+ const k = switchable()+ const s = new WatchLinkStore({ file: f, seal: k.flaky, unseal })+ expect(await s.save([c])).toBe('saved')+ k.state.refuse = true+ expect(await s.save([c, b])).toBe('memory-only')+ expect(ids(f)).toEqual([c.linkId])+ expect(await new WatchLinkStore({ file: f, seal, unseal }).load()).toEqual([c])+ })++ it('a sealed form is reused only for the SAME secret', async () => {+ const f = file()+ const k = switchable()+ const s = new WatchLinkStore({ file: f, seal: k.flaky, unseal })+ expect(await s.save([a])).toBe('saved')+ k.state.refuse = true+ expect(await s.save([{ ...a, secret: new Uint8Array(32).fill(9) }])).toBe('memory-only')+ expect(ids(f)).toEqual([])+ })++ it('never re-seals a secret it already holds sealed (the file does not churn on every write)', async () => {+ const f = file()+ let seals = 0+ const counting = (b: Buffer) => {+ seals+++ return seal(b)+ }+ const s = new WatchLinkStore({ file: f, seal: counting, unseal })+ await s.save([a])+ await s.save([a, b])+ await s.save([a, b])+ expect(seals).toBe(2)+ })+})diff --git a/src/core/watch-link/store.ts b/src/core/watch-link/store.tsindex 8d10b7646..e6e420068 100644--- a/src/core/watch-link/store.ts+++ b/src/core/watch-link/store.ts@@ -1,9 +1,9 @@// Active live links survive an app restart (spec D8). The secret is sealed through the platform's// secret seam: Electron safeStorage on the desktop, and ABSENT on the Server Edition by design// (headless, no keychain: raw bytes in a 0600 file, the same rule as its node secrets). On the-// desktop there is no plaintext fallback: if sealing throws, no live link is written (the file keeps-// only the opaque entries below) and links live in memory for this run; a raw secret found on a-// desktop is refused, never adopted.+// desktop there is no plaintext fallback: if sealing throws, a link that was never sealed is not+// written (it lives in memory for this run; see R45 below for the ones that were); a raw secret found+// on a desktop is refused, never adopted.//// What is sealed is the BASE64 TEXT of the secret, never its bytes. The desktop seam is a string// seam (`safeStorage.encryptString(b.toString('utf8'))` / `Buffer.from(decryptString(b), 'utf8')`),@@ -32,6 +32,11 @@// until its own `expiresAt` passes; the first write after that drops it. A sealed secret that unseals// but is malformed, and a raw secret found on a desktop, are not opaque: they are dropped as before.// `discardOpaque()` is for "Stop all", whose server revoke has ended every link of the license.+//+// A KEYCHAIN THAT STOPS SEALING MID-RUN (controller ruling R45). The store keeps the sealed form of+// every secret it read or sealed this run and reuses it on every write (it never re-seals), so when+// `seal` starts throwing only a link it NEVER sealed is left out (reported 'memory-only'); links read+// at boot and links sealed earlier stay on disk, and a link no longer in the list is still dropped.import { promises as fs } from 'node:fs'import { renameAtomic, writeFileAtomic } from '../fs-atomic'import { LINK_ID_RE } from '../../shared/watch-link/link'@@ -64,6 +69,12 @@ export class WatchLinkStoreUnreadable extends Error {}}+/** A secret's base64 text and the sealed text the file holds for it. */+interface SealedForm {+ secret: string+ sealed: string+}+interface FileEntry {linkId: stringnodeId: string@@ -105,6 +116,9 @@ export class WatchLinkStore {/** Valid entries whose sealed secret this run could not unseal (R42), carried back on every write* until their own `expiresAt`. Set by each `load()`. */private opaque: FileEntry[] = []+ /** The sealed form of every secret this run read or sealed, by link id (R45): reused on every+ * write, so a keychain that starts refusing mid-run costs only a link it never sealed. */+ private sealedForms = new Map<string, SealedForm>()constructor(private readonly o: {@@ -121,6 +135,14 @@ export class WatchLinkStore {this.opaque = []}+ /** How many opaque entries are still carried (not past their own expiry): links this machine holds+ * but cannot host this run. They count against the per-machine cap (R46), or a run with a locked+ * keychain could create five more and the next launch would find ten. */+ opaqueCount(): number {+ const t = (this.o.now ?? Date.now)()+ return this.opaque.filter((e) => e.expiresAt > t).length+ }+load(): Promise<WatchLinkRecord[]> {const loading = this.writing.then(() => this.read())this.writing = loading.then(noop, noop)@@ -162,6 +184,7 @@ export class WatchLinkStore {const out: WatchLinkRecord[] = []const opaque: FileEntry[] = []+ const sealedForms = new Map<string, SealedForm>()for (const e of Array.isArray(links) ? (links.slice(0, MAX_ENTRIES) as Partial<FileEntry>[]) : []) {if (!e || !str(e.linkId, 22) || !LINK_ID_RE.test(e.linkId)) continue// `isSafeNodeId` does not check the type: `12` and `["n1"]` pass its regex by coercion.@@ -178,9 +201,11 @@ export class WatchLinkStore {continue}if (!secret) continue+ if (sealed) sealedForms.set(e.linkId, { secret: Buffer.from(secret).toString('base64'), sealed: e.secret })out.push({ linkId: e.linkId, nodeId: e.nodeId, role: e.role, label: e.label, title: e.title, createdAt: e.createdAt, expiresAt: e.expiresAt, secret })}this.opaque = opaque+ this.sealedForms = sealedFormsreturn out}@@ -225,20 +250,31 @@ export class WatchLinkStore {}async save(records: readonly WatchLinkRecord[]): Promise<SaveOutcome> {- let links: FileEntry[] = []+ 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.+ const sealedNext = new Map<string, SealedForm>()try {for (const r of records) {const text = Buffer.from(r.secret).toString('base64')let secret = textif (this.o.seal) {- try {- secret = this.o.seal(Buffer.from(text, 'utf8')).toString('base64')- } catch {- // The keychain refused: no plaintext fallback. Write no live link, keep them in memory.- outcome = 'memory-only'- break+ const known = this.sealedForms.get(r.linkId)+ if (known && known.secret === text) {+ // Never re-sealed: the form read at boot or sealed earlier this run is still valid, and a+ // keychain that has started refusing must not cost a link it already holds sealed (R45).+ secret = known.sealed+ } else {+ try {+ secret = this.o.seal(Buffer.from(text, 'utf8')).toString('base64')+ } catch {+ // The keychain refused and this link was never sealed: no plaintext fallback. It is left+ // out of the file (it lives in memory this run); every other link is written.+ outcome = 'memory-only'+ continue+ }}+ sealedNext.set(r.linkId, { secret: text, sealed: secret })}links.push({linkId: r.linkId, nodeId: r.nodeId, role: r.role, label: r.label, title: r.title,@@ -249,7 +285,7 @@ export class WatchLinkStore {// Not a seal failure (a malformed record): leave the old file exactly as it is.return 'failed'}- if (outcome === 'memory-only') links = []+ if (this.o.seal) this.sealedForms = sealedNext// Everything above ran synchronously at call time, so the chain is extended in call order. The// opaque entries are joined at WRITE time: a save issued while a load was still reading carries// what that load found.diff --git a/src/main/watch-link-wiring.test.ts b/src/main/watch-link-wiring.test.tsindex d51cbe27c..803c45e90 100644--- a/src/main/watch-link-wiring.test.ts+++ b/src/main/watch-link-wiring.test.ts@@ -77,11 +77,14 @@ describe('live-link wiring', () => {expect(block).toMatch(/unsupported: true/)expect(block).toMatch(/detach: \(id\) => \{\s*dropUiClient\(id\)\s*platform\.detach\(id\)/)expect(s).toMatch(/if \(otherServerHere\) \{\s*console\.error\('Live links: NOT started — another nodeterm server owns this data directory\.'\)\s*\} else void watchLinks\.init\(\)/)- // Both close paths stop the hosts after hosting ends and before the pty layer goes.+ // Both close paths stop the hosts after hosting ends and before the pty layer goes — bounded+ // (R46/M6): a hung last write must not hold the server's close.+ expect(s).toMatch(/const WATCH_LINKS_STOP_MS = 2_000/)+ expect(s).not.toMatch(/await watchLinks\?\.shutdown\(\)/)const closes = s.split('async close()').slice(1)expect(closes).toHaveLength(2)for (const c of closes) {- const stop = c.indexOf('await watchLinks?.shutdown()')+ const stop = c.indexOf('await shutdownWithin(watchLinks, WATCH_LINKS_STOP_MS)')expect(stop).toBeGreaterThan(c.indexOf('hosted.stop()'))expect(stop).toBeLessThan(c.indexOf('await ptyManager.killAll()'))}diff --git a/src/server/index.ts b/src/server/index.tsindex 83f46ae90..71a11beed 100644--- a/src/server/index.ts+++ b/src/server/index.ts@@ -118,6 +118,7 @@ import {createWatchLinkService,registerWatchLinkIpc,sendToOwners,+ shutdownWithin,workspaceNodeState,type WatchLinkService} from '../core/watch-link/service'@@ -131,6 +132,8 @@ const API_BASE = process.env.NODETERM_API_BASE || 'https://api.nodeterm.dev'// The hosted team relay's wss endpoint. Same env override + default as the desktop's RELAY_URL// (src/main/remote/host-service.ts), derived locally for the same reason as API_BASE.const RELAY_URL = process.env.NODETERM_RELAY_URL || 'wss://relay.nodeterm.dev'+/** How long close() waits for the live-link service's last write (the desktop races 1.5 s). */+const WATCH_LINKS_STOP_MS = 2_000/*** App version fed to ServerPlatform (surfaced to the renderer as the desktop app's@@ -1056,8 +1059,9 @@ export async function startServer(// pty subscriptions) while the pty layer is still up. Same two lines in the serving close().await teamAdmin.close()hosted.stop()- // Stop the live-link hosts while the pty layer is still up (their viewers leave cleanly).- await watchLinks?.shutdown()+ // Stop the live-link hosts while the pty layer is still up (their viewers leave cleanly),+ // bounded: the links file's last write must not hold the close on a stalled disk.+ await shutdownWithin(watchLinks, WATCH_LINKS_STOP_MS)// Detach PTY clients — tmux sessions keep running (Phase 1 contract).sessionReaper.stop()pressure.stop()@@ -1123,7 +1127,7 @@ export async function startServer(await teamAdmin.close()hosted.stop()// Stop the live-link hosts while the pty layer is still up (see the headless close() above).- await watchLinks?.shutdown()+ await shutdownWithin(watchLinks, WATCH_LINKS_STOP_MS)// End the browser WebSockets next, BEFORE the canvas authority stops (N3). Once it has stopped// and been detached, a save from a still-attached tab is written un-overlaid, over its final// flush. Ending the sockets stops new saves; the `idle()` below lets the ones already queueddiff --git a/src/shared/presence.test.ts b/src/shared/presence.test.tsindex f78f564d9..240b60fa4 100644--- a/src/shared/presence.test.ts+++ b/src/shared/presence.test.ts@@ -1,5 +1,6 @@import { describe, it, expect } from 'vitest'import {+ BIDI_CONTROL_CHARS,PRESENCE_COLORS,capCodePoints,defaultNameFor,@@ -143,6 +144,12 @@ describe('sanitizeIdentity', () => {expect(sanitizeIdentity({ name: real, color: PRESENCE_COLORS[0] }, fallback).name).toBe(real)})+ it('strips the Arabic letter mark too (U+061C, a bidi control), and only bidi from BIDI_CONTROL_CHARS', () => {+ expect(sanitizeIdentity({ name: 'Ada\u061cLove', color: PRESENCE_COLORS[0] }, fallback).name).toBe('AdaLove')+ const text = 'a\u061cb\u200ec\u202ed\u2069e \u{1F468}\u200d\u{1F469}\u200b'+ expect(text.replace(BIDI_CONTROL_CHARS, '')).toBe('abcde \u{1F468}\u200d\u{1F469}\u200b')+ })+it('trims after truncating, so a cap landing on a space leaves no trailing space', () => {const name = 'a'.repeat(NAME_MAX_LEN - 1) + ' tail'const out = sanitizeIdentity({ name, color: PRESENCE_COLORS[0] }, fallback).namediff --git a/src/shared/presence.ts b/src/shared/presence.tsindex a980b8a83..65e02af67 100644--- a/src/shared/presence.ts+++ b/src/shared/presence.ts@@ -150,17 +150,31 @@ export function capCodePoints(text: string, max: number): string {return bounded.slice(0, max).join('')}+/**+ * The directional formatting characters, as a character-class BODY (escapes only — a bidi character+ * written literally makes the pattern unreadable, and a file carrying one is flagged as bidi text):+ * ALM (U+061C), LRM/RLM (U+200E/F), the embeddings and overrides (U+202A–E) and the isolates+ * (U+2066–9). ONE definition: `UNSAFE_DISPLAY_CHARS` below and the live-link owner side+ * (@shared/watch-link-types `stripBidiControls`) are built from it.+ */+const BIDI_CONTROL_CLASS = '\\u061c\\u200e\\u200f\\u202a-\\u202e\\u2066-\\u2069'+/** Only the directional formatting characters (see BIDI_CONTROL_CLASS) — for text where the other+ * zero-width characters must survive (a ZWJ joins an emoji sequence). Global: use with `replace`. */+export const BIDI_CONTROL_CHARS = new RegExp(`[${BIDI_CONTROL_CLASS}]`, 'g')+/*** Characters a display name may never contain. Names are UNVERIFIED by design (anyone may claim* any name), but they must not be able to MISRENDER: a bidi override (U+202E) reverses everything* after it, so a name stored as "Ada" + U+202E + "gnihsihp" DISPLAYS as "Adaphishing" — one peer* visually impersonating another with a string that inspects as something else. The marks/isolates- * (U+200B-200F, U+2066-2069, U+FEFF) do the same job more quietly, and C0/C1 controls (newlines,+ * (U+061C, U+200B-200F, U+2066-2069, U+FEFF) do the same job more quietly, and C0/C1 controls (newlines,* NUL, escapes) break a name out of its one-line chip. Strip them all; ordinary spaces, accents,* CJK and emoji are untouched.*/-// eslint-disable-next-line no-control-regex-export const UNSAFE_DISPLAY_CHARS = /[\u0000-\u001f\u007f-\u009f\u200b-\u200f\u202a-\u202e\u2066-\u2069\ufeff]/g+export const UNSAFE_DISPLAY_CHARS = new RegExp(+ `[\\u0000-\\u001f\\u007f-\\u009f\\u200b-\\u200f\\ufeff${BIDI_CONTROL_CLASS}]`,+ 'g'+)/** The name this file has always used for it. ONE set: the board's display text strips the same* characters (@shared/kanban-ops `displayText`). Global, so use it with `replace`, never `test`. */const UNSAFE_NAME_CHARS = UNSAFE_DISPLAY_CHARSdiff --git a/src/shared/watch-link-types.ts b/src/shared/watch-link-types.tsindex ddb712af9..7f8f50947 100644--- a/src/shared/watch-link-types.ts+++ b/src/shared/watch-link-types.ts@@ -3,6 +3,7 @@// viewer's protocol — that is src/shared/watch-link/ (vendored byte for byte into nodeterm-web), and// this file must stay out of that directory.import type { WatchChatMessage, WatchLinkRole } from './watch-link/protocol'+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. */@@ -109,14 +110,12 @@ export interface WatchLinkApi {}/**- * Directional formatting characters: LRM/RLM, the embeddings and overrides (U+202A–E) and the- * isolates (U+2066–9). The vendored chat sanitizer strips C0/C1 but not these, and a name or a title- * carrying an RLO reorders whatever the owner's UI draws after it. Stripped from every string the- * owner side shows that someone else wrote: a viewer's chat name and text, and the link's label and- * title (a title can come from a git-shared node title).+ * Strip the directional formatting characters (ALM, LRM/RLM, the embeddings and overrides, the+ * isolates — @shared/presence's ONE definition) from a string the owner side shows that someone else+ * wrote: a viewer's chat name and text, and the link's label and title (a title can come from a+ * git-shared node title). The vendored chat sanitizer strips C0/C1 but not these, and an RLO reorders+ * whatever the owner's UI draws after it. Only bidi: a ZWJ that joins an emoji sequence survives.*/-export const BIDI_CONTROLS = /[--]/g-export function stripBidiControls(s: string): string {- return s.replace(BIDI_CONTROLS, '')+ return s.replace(BIDI_CONTROL_CHARS, '')}