Skip to content

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.

perf(pty): keep scrollback snapshots correct on failed writes and quit

enes3570a2870915
diff --git a/src/core/pty-manager.snapshot-cadence.test.ts b/src/core/pty-manager.snapshot-cadence.test.ts
index 3bf7fd4ce..04aab3fae 100644
--- a/src/core/pty-manager.snapshot-cadence.test.ts
+++ b/src/core/pty-manager.snapshot-cadence.test.ts
@@ -36,10 +36,20 @@ vi.mock('child_process', () => {
return { execFile, execFileSync: (): string => '' }
})
-const store = vi.hoisted(() => ({ writes: [] as Array<{ key: string; text: string }> }))
+/** Every write ATTEMPT is recorded; `failNext` makes the next one report failure (the store never
+ * throws — it resolves false, see scrollback-store.ts). */
+const store = vi.hoisted(() => ({
+ writes: [] as Array<{ key: string; text: string }>,
+ failNext: false
+}))
vi.mock('./scrollback-store', () => ({
writeScrollback: async (key: string, text: string) => {
store.writes.push({ key, text })
+ if (store.failNext) {
+ store.failNext = false
+ return false
+ }
+ return true
},
readScrollback: async () => '',
deleteScrollback: async () => {}
@@ -58,6 +68,7 @@ interface Internals {
snapshotTick(): void
snapshotScrollback(k: string): Promise<boolean>
destroySession(clientId: null, persistKey: string): Promise<void>
+ killAll(): Promise<void>
}
async function manager(keys: string[]): Promise<Internals> {
@@ -88,6 +99,7 @@ beforeEach(() => {
tmux.fail = false
tmux.text = 'PANE SNAPSHOT'
store.writes.length = 0
+ store.failNext = false
})
afterEach(() => resetPlatformForTests())
@@ -215,4 +227,32 @@ describe('snapshot digest skip', () => {
await mgr.snapshotScrollback('gone')
expect(store.writes.map((w) => w.key)).toEqual(['gone', 'gone'])
})
+
+ it('a failed write is not remembered, so an identical capture writes again', async () => {
+ const mgr = await manager(['a'])
+ store.failNext = true
+ await mgr.snapshotScrollback('a')
+ await mgr.snapshotScrollback('a')
+ await mgr.snapshotScrollback('a')
+ // attempt 1 failed, attempt 2 landed, attempt 3 is the identical capture that is skipped
+ expect(store.writes.map((w) => w.text)).toEqual(['PANE SNAPSHOT', 'PANE SNAPSHOT'])
+ })
+})
+
+describe('quit while a periodic capture is queued', () => {
+ it('killAll still captures a session whose periodic capture has not run yet', async () => {
+ const mgr = await manager(['a', 'b'])
+ for (const s of mgr.sessions.values()) s.proc = { resume: () => {}, kill: () => {} }
+ tmux.hold = true
+ mgr.snapshotTick() // queues a, then b behind it; both dirty bits are now cleared
+ await new Promise((r) => setImmediate(r))
+ expect(tmux.captures).toEqual(['nt-a']) // b is queued, not yet run
+ tmux.hold = false
+ await mgr.killAll()
+ // Both get their final quit capture — b's queued periodic one may never run before exit.
+ expect(tmux.captures.filter((t) => t === 'nt-b')).toHaveLength(1)
+ expect(tmux.captures.filter((t) => t === 'nt-a')).toHaveLength(2)
+ tmux.held.shift()!.cb(null, { stdout: 'A', stderr: '' })
+ await settle(mgr)
+ })
})
diff --git a/src/core/pty-manager.ts b/src/core/pty-manager.ts
index 783837d42..5c6a22792 100644
--- a/src/core/pty-manager.ts
+++ b/src/core/pty-manager.ts
@@ -4248,8 +4248,10 @@ export class PtyManager {
private async writeScrollbackIfChanged(persistKey: string, text: string): Promise<void> {
const digest = createHash('sha1').update(text).digest('hex')
if (this.lastSnapshotDigest.get(persistKey) === digest) return
- await writeScrollback(persistKey, text)
- this.lastSnapshotDigest.set(persistKey, digest)
+ // Only a write that LANDED may be remembered: recording the digest of a failed one (ENOSPC, a
+ // rename that exhausted its retries on Windows) would skip every later identical capture —
+ // detach/quit's final ones included — for the rest of the run.
+ if (await writeScrollback(persistKey, text)) this.lastSnapshotDigest.set(persistKey, digest)
}
/**
@@ -5430,8 +5432,10 @@ export class PtyManager {
for (const session of this.sessions.values()) {
if (session.flushTimer) clearTimeout(session.flushTimer)
// Final scrollback snapshot on quit so a reboot can replay it. Skipped for sessions with
- // no output since the last periodic capture (unchanged pane content).
- if (session.persistKey && session.outputSinceSnapshot)
+ // no output since the last periodic capture (unchanged pane content) — but NOT for one whose
+ // periodic capture is still queued on `snapshotChain`: the tick cleared the dirty bit when it
+ // QUEUED, the chain is not awaited here, and the process may exit before that link runs.
+ if (session.persistKey && (session.outputSinceSnapshot || session.snapshotQueued))
finals.push(
this.snapshotScrollback(session.persistKey, session.sshRemote, !!session.sessionHost)
)
diff --git a/src/core/scrollback-store.test.ts b/src/core/scrollback-store.test.ts
new file mode 100644
index 000000000..c7a08de79
--- /dev/null
+++ b/src/core/scrollback-store.test.ts
@@ -0,0 +1,39 @@
+import { describe, it, expect, beforeEach, afterEach } from 'vitest'
+import fs from 'fs'
+import os from 'os'
+import path from 'path'
+import { initPlatform, resetPlatformForTests } from './platform'
+import { fakePlatform } from './platform-fake'
+import { writeScrollback, readScrollback } from './scrollback-store'
+
+// The boolean result is load-bearing: pty-manager remembers the digest of a snapshot only when
+// this reports that it LANDED (Task 8 fix round 1). The store must still never throw.
+describe('writeScrollback result', () => {
+ let root: string
+ beforeEach(() => {
+ root = fs.mkdtempSync(path.join(os.tmpdir(), 'nt-sb-'))
+ })
+ afterEach(() => {
+ resetPlatformForTests()
+ fs.rmSync(root, { recursive: true, force: true })
+ })
+
+ it('resolves true when the snapshot landed', async () => {
+ initPlatform(fakePlatform({ userDataDir: root }))
+ expect(await writeScrollback('node-1', 'hello')).toBe(true)
+ expect(await readScrollback('node-1')).toBe('hello')
+ })
+
+ it('resolves false (never throws) when the write fails', async () => {
+ // userData is a regular FILE, so creating the snapshot directory under it fails.
+ const file = path.join(root, 'not-a-dir')
+ fs.writeFileSync(file, '')
+ initPlatform(fakePlatform({ userDataDir: file }))
+ expect(await writeScrollback('node-1', 'hello')).toBe(false)
+ })
+
+ it('resolves false for empty data (nothing written)', async () => {
+ initPlatform(fakePlatform({ userDataDir: root }))
+ expect(await writeScrollback('node-1', '')).toBe(false)
+ })
+})
diff --git a/src/core/scrollback-store.ts b/src/core/scrollback-store.ts
index 5d86f0a0f..c8fbac0ea 100644
--- a/src/core/scrollback-store.ts
+++ b/src/core/scrollback-store.ts
@@ -38,8 +38,10 @@ function trailing(data: string): Buffer {
// All async (fs.promises): snapshots fire per session on a 15s timer and in bursts when many
// nodes detach at once (project switch / quit) — sync writes here blocked the main event loop,
// which stalls PTY streaming and all IPC.
-export async function writeScrollback(persistKey: string, data: string): Promise<void> {
- if (!data) return
+/** Never throws. Resolves true only when the snapshot actually landed on disk — a caller that
+ * remembers what it wrote (pty-manager's digest skip) must not remember a failed write. */
+export async function writeScrollback(persistKey: string, data: string): Promise<boolean> {
+ if (!data) return false
const file = snapshotPath(persistKey)
// Unique tmp per call: overlapping writes for the same key (timer tick + detach snapshot)
// must not interleave into one tmp file and rename a torn write into place.
@@ -48,9 +50,11 @@ export async function writeScrollback(persistKey: string, data: string): Promise
await fs.promises.mkdir(dir(), { recursive: true })
await fs.promises.writeFile(tmp, trailing(data))
await renameAtomic(tmp, file)
+ return true
} catch {
// best-effort: a failed snapshot just means no cold-restore replay for this node
await fs.promises.rm(tmp, { force: true }).catch(() => {})
+ return false
}
}