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(stores): serialize mutations — clears stay cleared, disk agrees with memory (#159)
Jason Whyte81125d03e958
diff --git a/src/core/settings-store.test.ts b/src/core/settings-store.test.tsindex f6316a27e..84f232886 100644--- a/src/core/settings-store.test.ts+++ b/src/core/settings-store.test.ts@@ -158,37 +158,17 @@ describe('settings:save atomic write', () => {// concurrently (src/server/ws.ts). One fixed `${file}.tmp` name means two of them share a single// tmp file: one writer's rename publishes the other's half-written bytes, or moves the file out// from under it entirely and the loser's rename fails.- it('two overlapping saves never share a tmp file (no torn write, no leftovers)', async () => {+ it('overlapping saves never reuse a tmp name (no torn write, no leftovers)', async () => {const settingsPath = path.join(dir, 'settings.json')- // Hold every settings writer between its tmp write and its rename, so BOTH tmp files are on- // disk before either rename runs — the overlap window a real crash tears open.+ // save() calls are serialized by the store's saveChain, so their writes arrive one after the+ // other — uniqueness is carried by the `<pid>.<seq>` name alone. That name is what protects+ // writers that bypass the chain (a second `nodeterm-server --data-dir X` process on the same+ // dir) and the crash window between tmp-write and rename, so it stays pinned here.const tmps: string[] = []- let open!: () => void- let timer!: ReturnType<typeof setTimeout>- // If a future change serializes the writers, the second write never arrives and the barrier- // would hang to an opaque 5s vitest timeout. Fail loudly, naming what this test pins.- const bothWritten = Promise.race([- new Promise<void>((r) => (open = r)),- new Promise<never>((_, reject) => {- timer = setTimeout(- () => reject(new Error('second concurrent tmp write never arrived — writers appear ' +- 'serialized; this test pins the unique-tmp-name design')),- 2000- )- })- ])const realWriteFile = fs.writeFilevi.spyOn(fs, 'writeFile').mockImplementation((async (p: any, ...rest: any[]) => {- const out = await (realWriteFile as any)(p, ...rest)- if (String(p).startsWith(settingsPath)) {- tmps.push(String(p))- if (tmps.length >= 2) {- clearTimeout(timer)- open()- }- await bothWritten- }- return out+ if (String(p).startsWith(settingsPath)) tmps.push(String(p))+ return (realWriteFile as any)(p, ...rest)}) as any)new SettingsStore().registerIpc()@@ -199,13 +179,41 @@ describe('settings:save atomic write', () => {await Promise.all([save(9), save(100)])vi.restoreAllMocks()- expect(new Set(tmps).size).toBe(2) // each writer owned its own tmp file+ expect(new Set(tmps).size).toBe(2) // each write owned its own tmp fileconst final = JSON.parse(await fs.readFile(settingsPath, 'utf-8'))- expect([9, 100]).toContain(final.fontSize) // one COMPLETE snapshot won, not a blend of both+ expect(final.fontSize).toBe(100) // one COMPLETE snapshot won — and FIFO makes it the last call// …and nothing is left for the next writer to inherit.expect(await tmpsLeft()).toEqual([])})+ it('overlapping saves land in call order — the disk and the cache agree afterwards', async () => {+ const settingsPath = path.join(dir, 'settings.json')+ // Slow down only the FIRST settings write: unserialized, the second save completes and renames+ // first, and the delayed first rename lands LAST — the disk says 9 while the cache (and every+ // listener) says 100, and they disagree until the next boot re-reads the file. Serialized,+ // the second save waits its turn and the last CALL wins both.+ const realWriteFile = fs.writeFile+ let delayed = false+ vi.spyOn(fs, 'writeFile').mockImplementation((async (p: any, ...rest: any[]) => {+ if (String(p).startsWith(settingsPath) && !delayed) {+ delayed = true+ await new Promise((r) => setTimeout(r, 50))+ }+ return (realWriteFile as any)(p, ...rest)+ }) as any)++ const store = new SettingsStore()+ store.registerIpc()+ const save = (fontSize: number): Promise<void> =>+ fake.handlers[IPC.settingsSave]({ ...DEFAULT_SETTINGS, fontSize }) as Promise<void>+ await Promise.all([save(9), save(100)])+ vi.restoreAllMocks()++ const final = JSON.parse(await fs.readFile(settingsPath, 'utf-8'))+ expect(final.fontSize).toBe(100) // the LAST save wins the disk…+ expect(store.get().fontSize).toBe(100) // …and memory agrees with it+ })+it('a failed rename removes its own temp, rejects the save, and fires no listener', async () => {const store = new SettingsStore()const fired: number[] = []diff --git a/src/core/settings-store.ts b/src/core/settings-store.tsindex 8be57b5f0..f2d497414 100644--- a/src/core/settings-store.ts+++ b/src/core/settings-store.ts@@ -43,6 +43,12 @@ let writeSeq = 0export class SettingsStore {private cache: Settings = DEFAULT_SETTINGSprivate listeners = new Set<(s: Settings) => void>()+ /** In-flight save chain: saves run FIFO (same idiom as WorkspaceStore.saveChain). The handler+ * has overlapping callers in both builds (the renderer's coalesced timer save, the+ * `beforeunload` flush, concurrent WS frames on the Server Edition); unordered, the last RENAME+ * wins the disk while the last CALL wins the cache — and they can disagree until next boot.+ * Each caller still sees only ITS OWN save's failure. */+ private saveChain: Promise<unknown> = Promise.resolve()private get filePath(): string {return path.join(platform().userDataDir, 'settings.json')@@ -72,7 +78,15 @@ export class SettingsStore {registerIpc(): void {platform().handle(IPC.settingsLoad, () => this.cache)- platform().handle(IPC.settingsSave, async (settings: Settings) => {+ platform().handle(IPC.settingsSave, (settings: Settings) => {+ const run = this.saveChain.then(() => this.saveNow(settings))+ this.saveChain = run.catch(() => {})+ return run+ })+ }++ private async saveNow(settings: Settings): Promise<void> {+ {this.cache = mergeSettings(settings)// Atomic write (temp + rename) so a mid-write crash can't corrupt settings.json. The temp// name is unique per call because nothing serializes this handler and its callers overlap:@@ -109,6 +123,6 @@ export class SettingsStore {// A listener must never break a settings save (or its siblings).}}- })+ }}}diff --git a/src/core/usage/provider-cookie.test.ts b/src/core/usage/provider-cookie.test.tsindex d19f8ed83..609d65b83 100644--- a/src/core/usage/provider-cookie.test.ts+++ b/src/core/usage/provider-cookie.test.ts@@ -25,45 +25,20 @@ describe('provider cookie atomic write', () => {const tmpsLeft = async (): Promise<string[]> =>(await fs.readdir(dir)).filter((f) => f.endsWith('.tmp'))- // Nothing serializes `usage:set-provider-cookie`: it is reachable from the preload bridge and,- // on the Server Edition, from any WS client's frame (src/renderer/bridge/ws-bridge.ts over the- // concurrent dispatch in src/server/ws.ts). One fixed `${file}.tmp` name means two writers share- // a single tmp file: one writer's rename publishes the other's half-written credential, or moves- // the file out from under it entirely and the loser's rename fails.- it('two overlapping cookie writes never share a tmp file (no torn write, no leftovers)', async () => {+ // `usage:set-provider-cookie` writes are serialized per provider by the writeChain, so their+ // writes arrive one after the other — uniqueness is carried by the `<pid>.<seq>` name alone.+ // That name is what protects writers that bypass the chain (a second server process on the same+ // data dir) and the crash window between tmp-write and rename, so it stays pinned here.+ it('overlapping cookie writes never reuse a tmp name (no torn write, no leftovers)', async () => {// Payloads that differ in LENGTH and in every byte: a spliced result then keeps a tail of the// longer write and fails JSON.parse, instead of quietly parsing as the shorter one.const long = 'a'.repeat(4096)const short = 'b'.repeat(17)- // Hold every cookie writer between its tmp write and its rename, so BOTH tmp files are on disk- // before either rename runs — the overlap window a real crash tears open.const tmps: string[] = []- let open!: () => void- let timer!: ReturnType<typeof setTimeout>- // If a future change serializes the writers, the second write never arrives and the barrier- // would hang to an opaque 5s vitest timeout. Fail loudly, naming what this test pins.- const bothWritten = Promise.race([- new Promise<void>((r) => (open = r)),- new Promise<never>((_, reject) => {- timer = setTimeout(- () => reject(new Error('second concurrent tmp write never arrived — writers appear ' +- 'serialized; this test pins the unique-tmp-name design')),- 2000- )- })- ])const realWriteFile = fs.writeFilevi.spyOn(fs, 'writeFile').mockImplementation((async (p: any, ...rest: any[]) => {- const out = await (realWriteFile as any)(p, ...rest)- if (String(p).startsWith(cookiePath)) {- tmps.push(String(p))- if (tmps.length >= 2) {- clearTimeout(timer)- open()- }- await bothWritten- }- return out+ if (String(p).startsWith(cookiePath)) tmps.push(String(p))+ return (realWriteFile as any)(p, ...rest)}) as any)await Promise.all([@@ -72,13 +47,38 @@ describe('provider cookie atomic write', () => {])vi.restoreAllMocks()- expect(new Set(tmps).size).toBe(2) // each writer owned its own tmp file+ expect(new Set(tmps).size).toBe(2) // each write owned its own tmp fileconst final = JSON.parse(await fs.readFile(cookiePath, 'utf-8'))- expect([long, short]).toContain(final.cookie) // one COMPLETE credential won, not a splice+ expect(final.cookie).toBe(short) // one COMPLETE credential won — FIFO makes it the last call// …and no tmp survives: a leaked one here is a live cookie nothing will ever overwrite.expect(await tmpsLeft()).toEqual([])})+ it('a clear is never undone by an in-flight set — writes run in call order per provider', async () => {+ // Park the set's rename: unserialized, the clear's rm runs while the set sits between its tmp+ // write and its rename — then the parked rename lands and resurrects the credential the UI+ // just reported cleared. Chained per provider, the clear waits its turn and the last call is+ // the last word.+ const realRename = fs.rename+ let delayed = false+ vi.spyOn(fs, 'rename').mockImplementation((async (a: any, b: any) => {+ if (String(b).startsWith(cookiePath) && !delayed) {+ delayed = true+ await new Promise((r) => setTimeout(r, 50))+ }+ return (realRename as any)(a, b)+ }) as any)++ await Promise.all([+ writeProviderCookie('minimax', 'secret'),+ writeProviderCookie('minimax', '')+ ])+ vi.restoreAllMocks()++ expect(await readProviderCookie('minimax')).toBeNull() // cleared means CLEARED+ expect(existsSync(cookiePath)).toBe(false)+ })+it('sweeps orphan temps left by dead writers, but never one bearing our own pid', async () => {const legacy = `${cookiePath}.tmp` // a build from before per-call tmp namesconst foreign = `${cookiePath}.${process.pid + 1}.7.tmp` // a run that died before its renamediff --git a/src/core/usage/provider-cookie.ts b/src/core/usage/provider-cookie.tsindex b6e093694..c5be2a7c2 100644--- a/src/core/usage/provider-cookie.ts+++ b/src/core/usage/provider-cookie.ts@@ -91,7 +91,20 @@ async function sweepStaleTmp(target: string): Promise<void> {* name lets one writer's rename publish the other's half-written cookie — or move the file out* from under it, so the loser's rename fails.*/-export async function writeProviderCookie(provider: CookieProvider, cookie: string): Promise<void> {+export function writeProviderCookie(provider: CookieProvider, cookie: string): Promise<void> {+ // FIFO per provider (the WorkspaceStore.saveChain idiom): without it a clear's rm can run while+ // an earlier set sits between tmp-write and rename — the parked rename then resurrects the+ // credential the UI just reported cleared. Unique tmp names cannot fix that; only ordering can.+ // Each caller still sees only its own write's failure.+ const prev = writeChains.get(provider) ?? Promise.resolve()+ const run = prev.then(() => writeCookieNow(provider, cookie))+ writeChains.set(provider, run.catch(() => {}))+ return run+}++const writeChains = new Map<CookieProvider, Promise<unknown>>()++async function writeCookieNow(provider: CookieProvider, cookie: string): Promise<void> {const target = file(provider)// Both paths sweep: clearing a cookie that leaves an orphan temp behind has not cleared anything.await sweepStaleTmp(target)diff --git a/src/main/github-control.test.ts b/src/main/github-control.test.tsindex 02fcafc8d..e2c27c71c 100644--- a/src/main/github-control.test.ts+++ b/src/main/github-control.test.ts@@ -83,58 +83,56 @@ describe('ElectronGitHubSecretStore atomic write', () => {// as wide as a round trip to github.com. One fixed `${file}.tmp` name means two writers share a// single tmp file: one writer's rename publishes the other's half-written PAT, or moves the file// out from under it entirely and the loser's rename fails.- it('two overlapping token saves never share a tmp file (no torn write, no leftovers)', async () => {+ it('overlapping token saves never reuse a tmp name (no torn write, no leftovers)', async () => {const store = new ElectronGitHubSecretStore(userDataDir, safeStorage())- // Payloads that differ in LENGTH and in every byte: a spliced result then keeps a tail of the- // longer write and fails JSON.parse, instead of quietly parsing as the shorter one.+ // The store's chain serializes its own mutations, so the writes arrive one after the other —+ // uniqueness is carried by the `<pid>.<seq>` name alone. That name is what protects writers+ // the chain cannot see (a second app process on the same userDataDir) and the crash window+ // between tmp-write and rename, so it stays pinned here.const long = `github_pat_${'a'.repeat(600)}`const short = `github_pat_${'b'.repeat(7)}`- // Hold every writer between its tmp write and its rename, so BOTH tmp files are on disk before- // either rename runs — the overlap window a real crash tears open.const tmps: string[] = []- let open!: () => void- let timer!: ReturnType<typeof setTimeout>- // If a future change serializes the writers, the second write never arrives and the barrier- // would hang to an opaque 5s vitest timeout. Fail loudly, naming what this test pins.- const bothWritten = Promise.race([- new Promise<void>((r) => (open = r)),- new Promise<never>((_, reject) => {- timer = setTimeout(- () => reject(new Error('second concurrent tmp write never arrived — writers appear ' +- 'serialized; this test pins the unique-tmp-name design')),- 2000- )- })- ])const realWriteFile = fs.writeFilevi.spyOn(fs, 'writeFile').mockImplementation((async (p: any, ...rest: any[]) => {- const out = await (realWriteFile as any)(p, ...rest)- if (String(p).startsWith(tokenFile())) {- tmps.push(String(p))- if (tmps.length >= 2) {- clearTimeout(timer)- open()- }- await bothWritten- }- return out+ if (String(p).startsWith(tokenFile())) tmps.push(String(p))+ return (realWriteFile as any)(p, ...rest)}) as any)- // allSettled, not all: with a shared name the LOSER's rename fails (ENOENT — the winner already- // moved the file away), and letting that reject here would report the symptom before the cause.- const settled = await Promise.allSettled([store.save(long), store.save(short)])+ await Promise.all([store.save(long), store.save(short)])vi.restoreAllMocks()- expect(new Set(tmps).size).toBe(2) // each writer owned its own tmp file- expect(settled.map((r) => r.status)).toEqual(['fulfilled', 'fulfilled']) // …so neither lost it- // One COMPLETE document won — parsing at all proves it is not a prefix of the other.+ expect(new Set(tmps).size).toBe(2) // each write owned its own tmp file+ // One COMPLETE document won — parsing at all proves it is not a prefix of the other — and+ // FIFO makes it the last call.expect(JSON.parse(await fs.readFile(tokenFile(), 'utf-8'))).toMatchObject({ version: 1, kind: 'safe-storage' })- expect([long, short]).toContain(await store.readForHost())+ expect(await store.readForHost()).toBe(short)// …and no tmp survives: a leaked one here is a live PAT at 0600 that nothing overwrites.expect(await tmpsLeft()).toEqual([])})+ it('a clear is never undone by an in-flight save — mutations run in call order', async () => {+ const store = new ElectronGitHubSecretStore(userDataDir, safeStorage())+ // Park the save's rename: unserialized, the clear's rm runs while the save sits between its+ // tmp write and its rename — then the parked rename lands and resurrects the PAT the UI just+ // reported cleared. Chained, the clear waits its turn and the last call is the last word.+ const realRename = fs.rename+ let delayed = false+ vi.spyOn(fs, 'rename').mockImplementation((async (a: any, b: any) => {+ if (String(b).startsWith(tokenFile()) && !delayed) {+ delayed = true+ await new Promise((r) => setTimeout(r, 50))+ }+ return (realRename as any)(a, b)+ }) as any)++ await Promise.all([store.save(`github_pat_${'c'.repeat(30)}`), store.clear()])+ vi.restoreAllMocks()++ expect(await store.readForHost()).toBeNull() // cleared means CLEARED+ expect(existsSync(tokenFile())).toBe(false)+ })+it('sweeps orphan temps left by dead writers, but never one bearing our own pid', async () => {const store = new ElectronGitHubSecretStore(userDataDir, safeStorage())const legacy = `${tokenFile()}.tmp` // a build from before per-call tmp namesdiff --git a/src/main/github-control.ts b/src/main/github-control.tsindex 5276de578..3e6ad74de 100644--- a/src/main/github-control.ts+++ b/src/main/github-control.ts@@ -68,13 +68,11 @@ async function sweepStaleTmp(target: string): Promise<void> {async function atomicWrite(file: string, document: TokenDocument): Promise<void> {await fs.mkdir(path.dirname(file), { recursive: true })await sweepStaleTmp(file)- // The temp name is unique per call because nothing serializes `IPC.githubControlSaveToken`: the- // handler is reachable from the preload bridge (src/preload/index.ts) AND from a remote client- // over the ws bridge (src/renderer/bridge/ws-bridge.ts), and GitHubHostController.saveToken- // awaits a NETWORK validateToken before it reaches this write (src/core/github/host.ts), so two- // saves overlap for as long as a round trip to github.com. With a shared name one writer's- // rename publishes the other's half-written PAT, or moves the file out from under it entirely- // and the loser's rename fails.+ // The store's per-instance chain orders this write against its sibling mutations; the per-call+ // temp name covers the writers the chain cannot see — a second app process on the same+ // userDataDir (every process's counter starts at 0, hence the pid) and a crash between+ // tmp-write and rename. With a shared name one writer's rename publishes the other's+ // half-written PAT, or moves the file out from under it entirely and the loser's rename fails.const temporary = `${file}.${process.pid}.${++writeSeq}.tmp`try {await fs.writeFile(temporary, JSON.stringify(document), { encoding: 'utf-8', mode: 0o600 })@@ -91,11 +89,23 @@ async function atomicWrite(file: string, document: TokenDocument): Promise<void>}export class ElectronGitHubSecretStore implements GitHubSecretStore {+ /** Mutations run FIFO (the WorkspaceStore.saveChain idiom): a clear's rm must never land inside+ * an in-flight save's write-to-rename window — the parked rename would resurrect the PAT the+ * UI just reported cleared — and save's read-modify-write of the document kind stays+ * consistent. Each caller still sees only its own mutation's failure. */+ private chain: Promise<unknown> = Promise.resolve()+constructor(private readonly userDataDir: string,private readonly safeStorage: SafeStorageLike) {}+ private chained<T>(fn: () => Promise<T>): Promise<T> {+ const run = this.chain.then(fn)+ this.chain = run.catch(() => {})+ return run+ }+get availability(): GitHubSecretAvailability {return this.canEncrypt() ? 'encrypted' : 'restricted-file'}@@ -104,7 +114,11 @@ export class ElectronGitHubSecretStore implements GitHubSecretStore {return path.join(this.userDataDir, FILE_NAME)}- async save(token: string): Promise<void> {+ save(token: string): Promise<void> {+ return this.chained(() => this.saveNow(token))+ }++ private async saveNow(token: string): Promise<void> {if (!validToken(token)) throw new GitHubSecretError('invalid-token')const current = await this.readDocument()if (current?.kind === 'safe-storage' && !this.canEncrypt()) {@@ -120,10 +134,12 @@ export class ElectronGitHubSecretStore implements GitHubSecretStore {await atomicWrite(this.filePath, document)}- async clear(): Promise<void> {- // Sweep here too: clearing a token that leaves an orphan temp behind has not cleared anything.- await sweepStaleTmp(this.filePath)- await fs.rm(this.filePath, { force: true })+ clear(): Promise<void> {+ return this.chained(async () => {+ // Sweep here too: clearing a token that leaves an orphan temp behind has not cleared anything.+ await sweepStaleTmp(this.filePath)+ await fs.rm(this.filePath, { force: true })+ })}async readForHost(): Promise<string | null> {diff --git a/src/main/pairing-service.atomic-write.test.ts b/src/main/pairing-service.atomic-write.test.tsindex 360cec702..98dae87eb 100644--- a/src/main/pairing-service.atomic-write.test.ts+++ b/src/main/pairing-service.atomic-write.test.ts@@ -2,11 +2,13 @@// ~/.ssh/authorized_keys.//// The service serializes its two entry points through one mutate chain (pinned in-// pairing-service.test.ts), but `writeAgentJson` / `removeAuthorizedKeysForDevice` are module-level-// functions nothing structurally forces through that chain, and a crash between tmp-write and-// rename is possible regardless. Both files were once written through a fixed `<file>.tmp`, where-// one writer's rename could publish the other's half-written file, or move the tmp out from under-// it and make the loser's rename fail — unique per-call names are the defense this file pins.+// pairing-service.test.ts), and `writeAgentJson` / `removeAuthorizedKeysForDevice` live inside the+// factory below `serialize`, so no code path outside the closure can reach them unchained. What+// the chain cannot see: the host agent is a separate PROCESS writing the same files, and a crash+// between tmp-write and rename is possible regardless. Both files were once written through a+// fixed `<file>.tmp`, where one writer's rename could publish the other's half-written file, or+// move the tmp out from under it and make the loser's rename fail — unique per-call names are the+// defense this file pins.//// agent.json is the credential case: each device entry carries the `agentToken` bearer the phone// uses on the host-agent WebSocket, so a temp left behind IS a leaked credential — hence thediff --git a/src/main/pairing-service.ts b/src/main/pairing-service.tsindex 30c3a1f25..a2fba4617 100644--- a/src/main/pairing-service.ts+++ b/src/main/pairing-service.ts@@ -235,43 +235,6 @@ async function sweepStaleAgentTmp(): Promise<void> {}}-/**- * Write agent.json atomically (0600), creating ~/.nodeterm (0700) if needed.- *- * The temp name is unique per call because nothing serializes the writers: `persistDevice` runs- * when the phone POSTs its key to the open pairing listener (an inbound HTTP request) while- * `revokeDevice` runs from a renderer IPC — independent event sources — and two rapid revokes- * interleave with each other. With one shared `agent.json.tmp`, a writer's rename publishes the- * other's half-written file, or moves the file out from under it so the loser's rename fails. The- * pid covers the other direction: the host agent is a separate PROCESS writing into this same- * ~/.nodeterm, and every process's counter starts at 0.- */-async function writeAgentJson(obj: Record<string, unknown>): Promise<void> {- await fs.mkdir(AGENT_DIR, { recursive: true, mode: 0o700 })- await fs.chmod(AGENT_DIR, 0o700).catch(() => {})- await sweepStaleAgentTmp()- const tmp = `${AGENT_JSON_PATH}.${process.pid}.${++writeSeq}.tmp`- try {- await fs.writeFile(tmp, JSON.stringify(obj, null, 2) + '\n', { mode: 0o600 })- await fs.chmod(tmp, 0o600).catch(() => {})- await fs.rename(tmp, AGENT_JSON_PATH)- } catch (e) {- // A unique name never self-heals the way the fixed one did (the next write just reused it), and- // here a leaked temp IS a leaked credential: only this cleanup — or a later run's sweep above,- // once this pid is dead — will ever collect it. The error still propagates.- await fs.rm(tmp, { force: true }).catch(() => {})- throw e- }- await fs.chmod(AGENT_JSON_PATH, 0o600).catch(() => {})-}--/** Persist a device into agent.json, preserving all other fields the host agent wrote. */-async function persistDevice(entry: DeviceEntry): Promise<void> {- const obj = await readAgentJson()- const devices = upsertDevice(readDevices(obj), entry)- await writeAgentJson({ ...obj, devices })-}-/** Detect the machine's display name (macOS ComputerName, else hostname). */async function computerName(): Promise<string> {if (process.platform === 'darwin') {@@ -329,40 +292,6 @@ async function appendAuthorizedKey(keyLine: string): Promise<void> {await fs.chmod(AUTH_KEYS_PATH, 0o600)}-/**- * Delete every authorized_keys line stamped for `deviceId`, rewriting the file atomically (0600).- *- * Unique temp name for the same reason as writeAgentJson: two `revokeDevice` calls from the- * renderer IPC overlap with nothing serializing them, and a shared `authorized_keys.tmp` lets one- * writer's rename publish the other's half-written key file — a spliced line is a key sshd rejects,- * i.e. the keys that were supposed to SURVIVE the revoke stop working — or steal the tmp so the- * loser's rename fails. No orphan sweep here (unlike agent.json above): these are PUBLIC keys, so a- * stray temp is litter rather than a credential.- */-async function removeAuthorizedKeysForDevice(deviceId: string): Promise<void> {- let content: string- try {- content = await fs.readFile(AUTH_KEYS_PATH, 'utf8')- } catch {- return // no file → nothing to revoke- }- const next = filterAuthorizedKeys(content, deviceId)- if (next === content) return- const tmp = `${AUTH_KEYS_PATH}.${process.pid}.${++writeSeq}.tmp`- try {- await fs.writeFile(tmp, next, { mode: 0o600 })- await fs.chmod(tmp, 0o600).catch(() => {})- await fs.rename(tmp, AUTH_KEYS_PATH)- } catch (e) {- // A unique name never self-heals the way the fixed one did (the next write just reused it), so- // a failed write has to remove its own temp — otherwise every failed revoke leaves another- // orphan copy of the user's key file in ~/.ssh forever. The error still propagates.- await fs.rm(tmp, { force: true }).catch(() => {})- throw e- }- await fs.chmod(AUTH_KEYS_PATH, 0o600).catch(() => {})-}-/** Read the whole request body (capped), rejecting oversized payloads. */function readBody(req: IncomingMessage): Promise<string> {return new Promise((resolve, reject) => {@@ -405,6 +334,75 @@ export function createPairingService(relayDeps?: PairingRelayDeps): PairingServireturn run}+ /**+ * Write agent.json atomically (0600), creating ~/.nodeterm (0700) if needed.+ *+ * Lives INSIDE the factory, below `serialize`, so no code path outside this closure can reach+ * it unchained — the same by-construction guarantee as GitHubControlStore's private write().+ * Overlapping entry points (the pairing POST, renderer revokes) are ordered by the chain; the+ * per-call temp name covers the writers the chain cannot see — the host agent is a separate+ * PROCESS writing this same ~/.nodeterm (`writeSeq` stays module-level so a second service+ * instance in THIS process keeps counting instead of restarting into colliding names), and a+ * crash between tmp-write and rename.+ */+ async function writeAgentJson(obj: Record<string, unknown>): Promise<void> {+ await fs.mkdir(AGENT_DIR, { recursive: true, mode: 0o700 })+ await fs.chmod(AGENT_DIR, 0o700).catch(() => {})+ await sweepStaleAgentTmp()+ const tmp = `${AGENT_JSON_PATH}.${process.pid}.${++writeSeq}.tmp`+ try {+ await fs.writeFile(tmp, JSON.stringify(obj, null, 2) + '\n', { mode: 0o600 })+ await fs.chmod(tmp, 0o600).catch(() => {})+ await fs.rename(tmp, AGENT_JSON_PATH)+ } catch (e) {+ // A unique name never self-heals the way the fixed one did (the next write just reused it),+ // and here a leaked temp IS a leaked credential: only this cleanup — or a later run's sweep,+ // once this pid is dead — will ever collect it. The error still propagates.+ await fs.rm(tmp, { force: true }).catch(() => {})+ throw e+ }+ await fs.chmod(AGENT_JSON_PATH, 0o600).catch(() => {})+ }++ /** Persist a device into agent.json, preserving all other fields the host agent wrote. */+ async function persistDevice(entry: DeviceEntry): Promise<void> {+ const obj = await readAgentJson()+ const devices = upsertDevice(readDevices(obj), entry)+ await writeAgentJson({ ...obj, devices })+ }++ /**+ * Delete every authorized_keys line stamped for `deviceId`, rewriting the file atomically+ * (0600). In the closure below `serialize` for the same by-construction reason as+ * writeAgentJson; the per-call temp name covers the chain-invisible writers and the crash+ * window — a spliced line is a key sshd rejects, i.e. the keys that were supposed to SURVIVE+ * the revoke stop working. No orphan sweep here (unlike agent.json): these are PUBLIC keys, so+ * a stray temp is litter rather than a credential.+ */+ async function removeAuthorizedKeysForDevice(deviceId: string): Promise<void> {+ let content: string+ try {+ content = await fs.readFile(AUTH_KEYS_PATH, 'utf8')+ } catch {+ return // no file → nothing to revoke+ }+ const next = filterAuthorizedKeys(content, deviceId)+ if (next === content) return+ const tmp = `${AUTH_KEYS_PATH}.${process.pid}.${++writeSeq}.tmp`+ try {+ await fs.writeFile(tmp, next, { mode: 0o600 })+ await fs.chmod(tmp, 0o600).catch(() => {})+ await fs.rename(tmp, AUTH_KEYS_PATH)+ } catch (e) {+ // A unique name never self-heals the way the fixed one did (the next write just reused it),+ // so a failed write has to remove its own temp — otherwise every failed revoke leaves+ // another orphan copy of the user's key file in ~/.ssh forever. The error still propagates.+ await fs.rm(tmp, { force: true }).catch(() => {})+ throw e+ }+ await fs.chmod(AUTH_KEYS_PATH, 0o600).catch(() => {})+ }+const cleanup = (): void => {if (timer) {clearTimeout(timer)diff --git a/src/server/github-control.test.ts b/src/server/github-control.test.tsindex daacf4004..17dd09b25 100644--- a/src/server/github-control.test.ts+++ b/src/server/github-control.test.ts@@ -50,57 +50,55 @@ describe('ServerGitHubSecretStore atomic write', () => {// trip to github.com. One fixed `${file}.tmp` name means two writers share a single tmp file: one// writer's rename publishes the other's half-written PAT, or moves the file out from under it// entirely and the loser's rename fails.- it('two overlapping token saves never share a tmp file (no torn write, no leftovers)', async () => {+ it('overlapping token saves never reuse a tmp name (no torn write, no leftovers)', async () => {const store = new ServerGitHubSecretStore(userDataDir)- // Payloads that differ in LENGTH and in every byte: a spliced result then keeps a tail of the- // longer write and fails JSON.parse, instead of quietly parsing as the shorter one.+ // The store's chain serializes its own mutations, so the writes arrive one after the other —+ // uniqueness is carried by the `<pid>.<seq>` name alone. That name is what protects writers+ // the chain cannot see (a second server process on the same data dir) and the crash window+ // between tmp-write and rename, so it stays pinned here.const long = `github_pat_${'a'.repeat(600)}`const short = `github_pat_${'b'.repeat(7)}`- // Hold every writer between its tmp write and its rename, so BOTH tmp files are on disk before- // either rename runs — the overlap window a real crash tears open.const tmps: string[] = []- let open!: () => void- let timer!: ReturnType<typeof setTimeout>- // If a future change serializes the writers, the second write never arrives and the barrier- // would hang to an opaque 5s vitest timeout. Fail loudly, naming what this test pins.- const bothWritten = Promise.race([- new Promise<void>((r) => (open = r)),- new Promise<never>((_, reject) => {- timer = setTimeout(- () => reject(new Error('second concurrent tmp write never arrived — writers appear ' +- 'serialized; this test pins the unique-tmp-name design')),- 2000- )- })- ])const realWriteFile = fs.writeFilevi.spyOn(fs, 'writeFile').mockImplementation((async (p: any, ...rest: any[]) => {- const out = await (realWriteFile as any)(p, ...rest)- if (String(p).startsWith(tokenFile())) {- tmps.push(String(p))- if (tmps.length >= 2) {- clearTimeout(timer)- open()- }- await bothWritten- }- return out+ if (String(p).startsWith(tokenFile())) tmps.push(String(p))+ return (realWriteFile as any)(p, ...rest)}) as any)- // allSettled, not all: with a shared name the LOSER's rename fails (ENOENT — the winner already- // moved the file away), and letting that reject here would report the symptom before the cause.- const settled = await Promise.allSettled([store.save(long), store.save(short)])+ await Promise.all([store.save(long), store.save(short)])vi.restoreAllMocks()- expect(new Set(tmps).size).toBe(2) // each writer owned its own tmp file- expect(settled.map((r) => r.status)).toEqual(['fulfilled', 'fulfilled']) // …so neither lost it- // One COMPLETE document won — parsing at all proves it is not a prefix of the other.+ expect(new Set(tmps).size).toBe(2) // each write owned its own tmp file+ // One COMPLETE document won — parsing at all proves it is not a prefix of the other — and+ // FIFO makes it the last call.expect(JSON.parse(await fs.readFile(tokenFile(), 'utf-8'))).toMatchObject({ version: 1 })- expect([long, short]).toContain(await store.readForHost())+ expect(await store.readForHost()).toBe(short)// …and no tmp survives: a leaked one here is a live PAT at 0600 that nothing overwrites.expect(await tmpsLeft()).toEqual([])})+ it('a clear is never undone by an in-flight save — mutations run in call order', async () => {+ const store = new ServerGitHubSecretStore(userDataDir)+ // Park the save's rename: unserialized, the clear's rm runs while the save sits between its+ // tmp write and its rename — then the parked rename lands and resurrects the PAT the UI just+ // reported cleared. Chained, the clear waits its turn and the last call is the last word.+ const realRename = fs.rename+ let delayed = false+ vi.spyOn(fs, 'rename').mockImplementation((async (a: any, b: any) => {+ if (String(b).startsWith(tokenFile()) && !delayed) {+ delayed = true+ await new Promise((r) => setTimeout(r, 50))+ }+ return (realRename as any)(a, b)+ }) as any)++ await Promise.all([store.save(`github_pat_${'c'.repeat(30)}`), store.clear()])+ vi.restoreAllMocks()++ expect(await store.readForHost()).toBeNull() // cleared means CLEARED+ expect(existsSync(tokenFile())).toBe(false)+ })+it('sweeps orphan temps left by dead writers, but never one bearing our own pid', async () => {const store = new ServerGitHubSecretStore(userDataDir)const legacy = `${tokenFile()}.tmp` // a build from before per-call tmp namesdiff --git a/src/server/github-control.ts b/src/server/github-control.tsindex 9a2b0f366..5c20578df 100644--- a/src/server/github-control.ts+++ b/src/server/github-control.ts@@ -56,23 +56,36 @@ async function sweepStaleTmp(target: string): Promise<void> {export class ServerGitHubSecretStore implements GitHubSecretStore {readonly availability = 'restricted-file' as const+ /** Mutations run FIFO (the WorkspaceStore.saveChain idiom): a clear's rm must never land inside+ * an in-flight save's write-to-rename window — the parked rename would resurrect the PAT the+ * UI just reported cleared. Each caller still sees only its own mutation's failure. */+ private chain: Promise<unknown> = Promise.resolve()+constructor(private readonly userDataDir: string) {}+ private chained<T>(fn: () => Promise<T>): Promise<T> {+ const run = this.chain.then(fn)+ this.chain = run.catch(() => {})+ return run+ }+private get filePath(): string {return path.join(this.userDataDir, FILE_NAME)}- async save(token: string): Promise<void> {+ save(token: string): Promise<void> {+ return this.chained(() => this.saveNow(token))+ }++ private async saveNow(token: string): Promise<void> {if (!validToken(token)) throw new ServerGitHubSecretError('invalid-token')await fs.mkdir(this.userDataDir, { recursive: true })await sweepStaleTmp(this.filePath)- // The temp name is unique per call because nothing serializes `IPC.githubControlSaveToken`: it- // is registered through `platform.handle` and reached over the concurrent WS dispatch in- // src/server/ws.ts with no queue in front of it, and GitHubHostController.saveToken awaits a- // NETWORK validateToken before it reaches this write (src/core/github/host.ts), so two saves- // overlap for as long as a round trip to github.com. With a shared name one writer's rename- // publishes the other's half-written PAT, or moves the file out from under it entirely and the- // loser's rename fails.+ // The store's per-instance chain orders this write against its sibling mutations; the per-call+ // temp name covers the writers the chain cannot see — a second `nodeterm-server --data-dir X`+ // process on the same dir (every process's counter starts at 0, hence the pid) and a crash+ // between tmp-write and rename. With a shared name one writer's rename publishes the other's+ // half-written PAT, or moves the file out from under it entirely and the loser's rename fails.const temporary = `${this.filePath}.${process.pid}.${++writeSeq}.tmp`try {await fs.writeFile(temporary, JSON.stringify({ version: 1, token }), {@@ -91,10 +104,12 @@ export class ServerGitHubSecretStore implements GitHubSecretStore {await fs.chmod(this.filePath, 0o600)}- async clear(): Promise<void> {- // Sweep here too: clearing a token that leaves an orphan temp behind has not cleared anything.- await sweepStaleTmp(this.filePath)- await fs.rm(this.filePath, { force: true })+ clear(): Promise<void> {+ return this.chained(async () => {+ // Sweep here too: clearing a token that leaves an orphan temp behind has not cleared anything.+ await sweepStaleTmp(this.filePath)+ await fs.rm(this.filePath, { force: true })+ })}async readForHost(): Promise<string | null> {