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(watch-link): keep links a locked keychain cannot unseal, and ask PtyManager whether a session exists
reviewaf290b8e74ed
diff --git a/src/core/pty-manager.ts b/src/core/pty-manager.tsindex bfa9d238d..5501d0eb2 100644--- a/src/core/pty-manager.ts+++ b/src/core/pty-manager.ts@@ -4475,6 +4475,15 @@ export class PtyManager {return this.sessions.get(sessionId)?.nodeId}+ /**+ * Is this session known to the manager — created and not yet ended? Read-only. A live link's host+ * asks it after a join and after every keyframe capture (controller rulings R30/R38): the session's+ * exit can race either, and its `pty:exit` was delivered before the viewer knew the session id.+ */+ hasSession(sessionId: string): boolean {+ return this.sessions.has(sessionId)+ }+/*** The CURRENT screen of a live session, by sessionId — the redraw sent to a client that fell so* far behind that its socket backlog was discarded (see ServerPlatform's WS_DROP_WATER). Reusesdiff --git a/src/core/pty-watch-join.test.ts b/src/core/pty-watch-join.test.tsindex 7f23bcfee..c94772f53 100644--- a/src/core/pty-watch-join.test.ts+++ b/src/core/pty-watch-join.test.ts@@ -619,6 +619,27 @@ describe('sessionSize', () => {})})+// Controller ruling R38: a live link asks "is the session I joined still there?" after the join and+// after every capture (an exit can race either — R30). An explicit accessor, not `nodeOfSession(sid)+// !== undefined`, which would lean on every watched session having been created with a persistKey.+describe('hasSession', () => {+ it('is true for a live session, owner or watcher, and false once it ended', async () => {+ const m = await manager()+ const own = await create(OWNER, { cols: 120, rows: 40 })+ const w = await m.joinAsWatcher(WATCHER, WATCH)+ expect(m.hasSession(own.sessionId)).toBe(true)+ expect(m.hasSession(w.sessionId)).toBe(true)+ spawned[spawned.length - 1].onExitCb!({ exitCode: 0 })+ expect(m.hasSession(own.sessionId)).toBe(false)+ })++ it('is false for a session this manager never created', async () => {+ const m = await manager()+ expect(m.hasSession('no-such-session')).toBe(false)+ expect(m.hasSession('')).toBe(false)+ })+})+describe('watchSizeFor', () => {it('is the size the live pty runs at, whatever the watcher reported', async () => {const m = await manager()diff --git a/src/core/watch-link/store.test.ts b/src/core/watch-link/store.test.tsindex 6468cdeeb..42f37f7f7 100644--- a/src/core/watch-link/store.test.ts+++ b/src/core/watch-link/store.test.ts@@ -312,3 +312,97 @@ describe('WatchLinkStore', () => {expect(await s.load()).toEqual([rec({ label: 'Bob' })])})})++// Ruling R42(b): an entry whose SEALED secret cannot be unsealed this run (the keychain is locked at+// login, or was reset) is not evidence that the link is gone. The store keeps it verbatim — never+// returned by load(), never erased by a save — until its own expiresAt passes. Only then is it dropped.+describe('opaque entries (a sealed secret this run cannot unseal)', () => {+ const locked = () => {+ throw new Error('keychain locked')+ }+ const other = rec({ linkId: 'OtherLinkIjKlMnOpQrStU', label: 'Bob' })++ it('survives a save verbatim and comes back once the keychain answers again', async () => {+ const f = file()+ expect(await new WatchLinkStore({ file: f, seal, unseal }).save([rec()])).toBe('saved')+ const sealedEntry = JSON.parse(readFileSync(f, 'utf8')).links[0]++ // This run: the keychain refuses. The link is not returned (it cannot be hosted without its secret).+ const s = new WatchLinkStore({ file: f, seal, unseal: locked })+ expect(await s.load()).toEqual([])+ // A save of this run's own links (a new one) must not erase it.+ expect(await s.save([other])).toBe('saved')+ const onDisk = JSON.parse(readFileSync(f, 'utf8')).links as Record<string, unknown>[]+ expect(onDisk).toHaveLength(2)+ expect(onDisk.find((e) => e.linkId === rec().linkId)).toEqual(sealedEntry)+ // An empty save (every live link revoked) keeps it too.+ expect(await s.save([])).toBe('saved')+ expect(JSON.parse(readFileSync(f, 'utf8')).links).toEqual([sealedEntry])++ // Next run the keychain answers: the link is back, secret intact.+ expect(await new WatchLinkStore({ file: f, seal, unseal }).load()).toEqual([rec()])+ })++ it('is dropped by the first save after its own expiresAt', async () => {+ const f = file()+ expect(await new WatchLinkStore({ file: f, seal, unseal }).save([rec()])).toBe('saved')+ let t = EXPIRES_AT - 1+ const s = new WatchLinkStore({ file: f, seal, unseal: locked, now: () => t })+ expect(await s.load()).toEqual([])+ expect(await s.save([])).toBe('saved')+ expect(JSON.parse(readFileSync(f, 'utf8')).links).toHaveLength(1)+ t = EXPIRES_AT+ expect(await s.save([])).toBe('saved')+ expect(JSON.parse(readFileSync(f, 'utf8')).links).toEqual([])+ // Gone for good: time going back does not bring it back.+ t = EXPIRES_AT - 1+ expect(await s.save([])).toBe('saved')+ expect(JSON.parse(readFileSync(f, 'utf8')).links).toEqual([])+ })++ it('a live record with the same id wins over the opaque copy (never two entries for one link)', async () => {+ const f = file()+ expect(await new WatchLinkStore({ file: f, seal, unseal }).save([rec()])).toBe('saved')+ const s = new WatchLinkStore({ file: f, seal, unseal: locked })+ expect(await s.load()).toEqual([])+ expect(await s.save([rec({ label: 'Live' })])).toBe('saved')+ const links = JSON.parse(readFileSync(f, 'utf8')).links as Record<string, unknown>[]+ expect(links).toHaveLength(1)+ expect(links[0].label).toBe('Live')+ })++ it('is kept when sealing fails too (memory-only writes no live link, but never erases one it could not read)', async () => {+ const f = file()+ expect(await new WatchLinkStore({ file: f, seal, unseal }).save([rec()])).toBe('saved')+ const sealedEntry = JSON.parse(readFileSync(f, 'utf8')).links[0]+ const s = new WatchLinkStore({ file: f, seal: locked, unseal: locked })+ expect(await s.load()).toEqual([])+ expect(await s.save([other])).toBe('memory-only')+ expect(JSON.parse(readFileSync(f, 'utf8')).links).toEqual([sealedEntry])+ })++ 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')+ const s = new WatchLinkStore({ file: f, seal, unseal: locked })+ expect(await s.load()).toEqual([])+ s.discardOpaque()+ expect(await s.save([])).toBe('saved')+ expect(JSON.parse(readFileSync(f, 'utf8')).links).toEqual([])+ })++ it('only a sealed entry the keychain REFUSED is opaque: a malformed or raw-on-desktop one is still dropped', async () => {+ const f = file()+ const sealB64 = (bytes: Uint8Array) => seal(Buffer.from(b64(bytes), 'utf8')).toString('base64')+ writeLinks(f, [+ // Unsealed fine, but the wrong length: malformed, not a keychain problem.+ rawEntry({ linkId: 'ShortSealIjKlMnOpQrStU', secret: sealB64(new Uint8Array(31).fill(7)), sealed: true }),+ // A raw secret on a desktop is never adopted.+ rawEntry({ linkId: 'RawOnDesktopKlMnOpQrSt' })+ ])+ const s = new WatchLinkStore({ file: f, seal, unseal })+ expect(await s.load()).toEqual([])+ expect(await s.save([])).toBe('saved')+ expect(JSON.parse(readFileSync(f, 'utf8')).links).toEqual([])+ })+})diff --git a/src/core/watch-link/store.ts b/src/core/watch-link/store.tsindex 007e434da..8d10b7646 100644--- a/src/core/watch-link/store.ts+++ b/src/core/watch-link/store.ts@@ -1,8 +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, the file is written EMPTY 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, 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.//// 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')`),@@ -23,6 +24,14 @@// 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.+//+// OPAQUE ENTRIES (controller ruling R42). A sealed secret the keychain REFUSES to unseal this run+// (locked at login, or reset) says nothing about whether the link is gone: the next run may unseal it.+// So such an entry is kept exactly as it was read — never returned by `load()` (nothing can host a+// link without its secret), never erased by a `save()` — and carried back verbatim on every write+// 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.import { promises as fs } from 'node:fs'import { renameAtomic, writeFileAtomic } from '../fs-atomic'import { LINK_ID_RE } from '../../shared/watch-link/link'@@ -93,8 +102,24 @@ export class WatchLinkStore {private writing: Promise<void> = Promise.resolve()/** False once `load()` found a file it could not read: never write over it this run. */private writable = true+ /** 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[] = []++ constructor(+ private readonly o: {+ file: string+ seal?: (b: Buffer) => Buffer+ unseal?: (b: Buffer) => Buffer+ /** Clock for dropping an opaque entry past its `expiresAt` (tests). */+ now?: () => number+ }+ ) {}- constructor(private readonly o: { file: string; seal?: (b: Buffer) => Buffer; unseal?: (b: Buffer) => Buffer }) {}+ /** Forget every opaque entry: the next write leaves them out ("Stop all" revoked them server-side). */+ discardOpaque(): void {+ this.opaque = []+ }load(): Promise<WatchLinkRecord[]> {const loading = this.writing.then(() => this.read())@@ -136,16 +161,26 @@ export class WatchLinkStore {if (v !== 1) throw this.latch('unknown-version', `${this.o.file} has version ${JSON.stringify(v)}, expected 1`)const out: WatchLinkRecord[] = []+ const opaque: FileEntry[] = []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.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') continue- const secret = this.readSecret(e.secret, e.sealed === true)+ const sealed = e.sealed === true+ const secret = this.readSecret(e.secret, sealed)+ if (secret === 'refused') {+ opaque.push({+ linkId: e.linkId, nodeId: e.nodeId, role: e.role, label: e.label, title: e.title,+ createdAt: e.createdAt, expiresAt: e.expiresAt, secret: e.secret, sealed: true+ })+ continue+ }if (!secret) continueout.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 = opaquereturn out}@@ -163,17 +198,30 @@ export class WatchLinkStore {}}- private readSecret(stored: string, sealed: boolean): Uint8Array | null {- try {- if (sealed) {- if (!this.o.unseal) return null- return decodeSecret(this.o.unseal(Buffer.from(stored, 'base64')).toString('utf8'))+ /** The secret; null for a malformed one (dropped); 'refused' for a sealed one this run cannot+ * unseal — no keychain here, or it refused (kept as an opaque entry, R42). */+ private readSecret(stored: string, sealed: boolean): Uint8Array | null | 'refused' {+ if (sealed) {+ if (!this.o.unseal) return 'refused'+ let text: string+ try {+ text = this.o.unseal(Buffer.from(stored, 'base64')).toString('utf8')+ } catch {+ return 'refused'}- // A desktop (it can seal) never adopts a raw secret it finds on disk.- return this.o.seal ? null : decodeSecret(stored)- } catch {- return null+ return decodeSecret(text)}+ // A desktop (it can seal) never adopts a raw secret it finds on disk.+ return this.o.seal ? null : decodeSecret(stored)+ }++ /** The opaque entries this write carries: none past its own expiry (dropped for good), none a live+ * record replaces. */+ private carriedOpaque(live: readonly FileEntry[]): FileEntry[] {+ const t = (this.o.now ?? Date.now)()+ this.opaque = this.opaque.filter((e) => e.expiresAt > t)+ const ids = new Set(live.map((e) => e.linkId))+ return this.opaque.filter((e) => !ids.has(e.linkId))}async save(records: readonly WatchLinkRecord[]): Promise<SaveOutcome> {@@ -187,7 +235,7 @@ export class WatchLinkStore {try {secret = this.o.seal(Buffer.from(text, 'utf8')).toString('base64')} catch {- // The keychain refused: no plaintext fallback. Write nothing, keep links in memory.+ // The keychain refused: no plaintext fallback. Write no live link, keep them in memory.outcome = 'memory-only'break}@@ -202,10 +250,12 @@ export class WatchLinkStore {return 'failed'}if (outcome === 'memory-only') links = []- const data = JSON.stringify({ v: 1, links })- // Everything above ran synchronously at call time, so the chain is extended in call order.+ // 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.const write = this.writing.then(() => {if (!this.writable) throw new Error('watch-link store is latched: it could not read its file')+ const data = JSON.stringify({ v: 1, links: [...links, ...this.carriedOpaque(links)] })return writeFileAtomic(this.o.file, data, { mode: 0o600 })})this.writing = write.catch(() => {})