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): a save waits for a pending load, and node ids must be strings
review2e701e11ba0a
diff --git a/src/core/watch-link/store.test.ts b/src/core/watch-link/store.test.tsindex dd0578a02..6468cdeeb 100644--- a/src/core/watch-link/store.test.ts+++ b/src/core/watch-link/store.test.ts@@ -107,6 +107,8 @@ describe('WatchLinkStore', () => {rawEntry({ nodeId: '../x', linkId: 'A1CdEfGhIjKlMnOpQrStUv' }),rawEntry({ nodeId: 'a b', linkId: 'A2CdEfGhIjKlMnOpQrStUv' }),rawEntry({ nodeId: 'x'.repeat(129), linkId: 'A3CdEfGhIjKlMnOpQrStUv' }),+ rawEntry({ nodeId: 12, linkId: 'A4CdEfGhIjKlMnOpQrStUv' }),+ rawEntry({ nodeId: ['n1'], linkId: 'A5CdEfGhIjKlMnOpQrStUv' }),rawEntry()])expect(await new WatchLinkStore({ file: f }).load()).toEqual([rec()])@@ -150,6 +152,21 @@ describe('WatchLinkStore', () => {expect(await s.load()).toEqual([rec()])})+ it('sets aside JSON that is not an object ([] or null) and stays writable', async () => {+ for (const body of ['[]', 'null']) {+ const f = file()+ writeFileSync(f, body)+ const s = new WatchLinkStore({ file: f })+ expect(await s.load()).toEqual([])+ expect(existsSync(f)).toBe(false)+ const aside = readdirSync(dirname(f)).filter((n) => n.startsWith('watch-links.json.corrupt-'))+ expect(aside).toHaveLength(1)+ expect(readFileSync(join(dirname(f), aside[0]), 'utf8')).toBe(body)+ expect(await s.save([rec()])).toBe('saved')+ expect(await s.load()).toEqual([rec()])+ }+ })+describe('never writes over a file it could not read', () => {const expectLatched = async (s: WatchLinkStore, f: string, before: string) => {const writes = vi.mocked(writeFileAtomic).mock.calls.length@@ -198,6 +215,43 @@ describe('WatchLinkStore', () => {await expectLatched(s, f, before)})+ it('a save issued while load() is pending waits for it (real {"v":2} file)', async () => {+ const f = file()+ writeLinks(f, [rawEntry()], 2)+ const before = readFileSync(f, 'utf8')+ const s = new WatchLinkStore({ file: f })+ const loading = s.load()+ const saving = s.save([])+ await expect(loading).rejects.toBeInstanceOf(WatchLinkStoreUnreadable)+ expect(await saving).toBe('failed')+ expect(readFileSync(f, 'utf8')).toBe(before)+ })++ it('a save issued while a slow read is held waits for its verdict', async () => {+ const f = file()+ expect(await new WatchLinkStore({ file: f }).save([rec()])).toBe('saved')+ const before = readFileSync(f, 'utf8')+ let release!: () => void+ const gate = new Promise<void>((r) => { release = r })+ const eacces = Object.assign(new Error('EACCES: permission denied, open'), { code: 'EACCES' })+ const open = vi.spyOn(fsp, 'open').mockImplementationOnce(async () => {+ await gate // the read is still in flight when the save arrives+ throw eacces+ })+ const writes = vi.mocked(writeFileAtomic).mock.calls.length+ const s = new WatchLinkStore({ file: f })+ const loading = s.load()+ const saving = s.save([])+ for (let i = 0; i < 10; i++) await Promise.resolve() // microtasks only, no timers+ expect(vi.mocked(writeFileAtomic).mock.calls.length).toBe(writes) // nothing written yet+ release()+ await expect(loading).rejects.toBeInstanceOf(WatchLinkStoreUnreadable)+ open.mockRestore()+ expect(await saving).toBe('failed')+ expect(vi.mocked(writeFileAtomic).mock.calls.length).toBe(writes)+ expect(readFileSync(f, 'utf8')).toBe(before)+ })+it('an unparseable file that cannot be set aside rejects and latches the store', async () => {const f = file()writeFileSync(f, '{nope')diff --git a/src/core/watch-link/store.ts b/src/core/watch-link/store.tsindex b9fe89512..007e434da 100644--- a/src/core/watch-link/store.ts+++ b/src/core/watch-link/store.ts@@ -16,10 +16,13 @@// next boot or a newer build. JSON that does not parse is set aside as `<file>.corrupt-<ts>` and the// store starts empty; if the set-aside fails, the same latch applies.//-// Saves are SERIALIZED: each write waits for the previous one to finish. Two overlapping atomic-// writes can still complete out of order, and the older snapshot would then be what stays on disk —-// a revoked link resurrected at the next boot. The snapshot is taken (and sealed) when `save` is-// CALLED, so disk order is call order; a failed write never breaks the chain for the next save.+// Loads and saves are SERIALIZED, in call order, on one chain: each waits for the previous one to+// settle. Two overlapping atomic writes can still complete out of order, and the older snapshot would+// then be what stays on disk — a revoked link resurrected at the next boot. And a save issued while a+// load is still reading must not run before that load's verdict: it would write over a file the load+// is about to refuse (a slow EACCES/EIO, a newer build's version), or land between reading a corrupt+// file and setting it aside. The snapshot is taken (and sealed) when `save` is CALLED, so disk order+// is call order; a failed load or write never breaks the chain for what follows.import { promises as fs } from 'node:fs'import { renameAtomic, writeFileAtomic } from '../fs-atomic'import { LINK_ID_RE } from '../../shared/watch-link/link'@@ -69,6 +72,7 @@ export const MAX_FILE_BYTES = 1024 * 1024/** Entries past this are dropped on read. */export const MAX_ENTRIES = 200const SECRET_BYTES = 32+const noop = (): void => {}const str = (v: unknown, max: number): v is string => typeof v === 'string' && v.length <= maxconst num = (v: unknown): v is number => typeof v === 'number' && Number.isFinite(v)@@ -85,14 +89,20 @@ function decodeSecret(text: string): Uint8Array | null {}export class WatchLinkStore {- /** The previous save's write, settled either way: the next write starts only after it. */+ /** The previous load or write, settled either way: the next one starts only after it. */private writing: Promise<void> = Promise.resolve()/** False once `load()` found a file it could not read: never write over it this run. */private writable = trueconstructor(private readonly o: { file: string; seal?: (b: Buffer) => Buffer; unseal?: (b: Buffer) => Buffer }) {}- async load(): Promise<WatchLinkRecord[]> {+ load(): Promise<WatchLinkRecord[]> {+ const loading = this.writing.then(() => this.read())+ this.writing = loading.then(noop, noop)+ return loading+ }++ private async read(): Promise<WatchLinkRecord[]> {let text: stringtry {const handle = await fs.open(this.o.file, 'r')@@ -127,12 +137,14 @@ export class WatchLinkStore {const out: WatchLinkRecord[] = []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) || !isSafeNodeId(e.nodeId)) continue+ 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.+ if (typeof e.nodeId !== 'string' || !isSafeNodeId(e.nodeId)) continueif (e.role !== 'viewer' && e.role !== 'commenter') continueif (!str(e.label, 40) || !str(e.title, 80) || !num(e.createdAt) || !num(e.expiresAt) || typeof e.secret !== 'string') continueconst secret = this.readSecret(e.secret, e.sealed === true)if (!secret) continue- out.push({ linkId: e.linkId, nodeId: e.nodeId as string, role: e.role, label: e.label, title: e.title, createdAt: e.createdAt, expiresAt: e.expiresAt, 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 })}return out}