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: validate and cap closedSessions at the file trust boundary
Mina Sameh1ac3a15853b0
diff --git a/src/core/workspace-files.closed-history.test.ts b/src/core/workspace-files.closed-history.test.tsindex 5d1a9b8a4..a06d3616b 100644--- a/src/core/workspace-files.closed-history.test.ts+++ b/src/core/workspace-files.closed-history.test.ts@@ -1,5 +1,6 @@import { describe, it, expect } from 'vitest'import { projectToFile, fileToProject, validClosedSessions } from './workspace-files'+import { CLOSED_SESSIONS_CAP } from '../shared/types'import type { ClosedSessionEntry, Project } from '../shared/types'const closedEntry = (id: string, over: Partial<ClosedSessionEntry['node']> = {}): ClosedSessionEntry => ({@@ -67,4 +68,53 @@ describe('closedSessions round trip', () => {expect(validClosedSessions('nope')).toBe(false)expect(validClosedSessions(undefined)).toBe(false)})++ // 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', () => {+ 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', () => {+ const bad = closedEntry('e1')+ const { position: _dropped, ...node } = bad.node+ expect(validClosedSessions([{ ...bad, node }])).toBe(false)+ })++ // 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', () => {+ 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()+ })++ // 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}`))++ const file = projectToFile(project({ closedSessions: many }), 1, 'now')+ expect(file.closedSessions).toHaveLength(CLOSED_SESSIONS_CAP)++ // 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')+ })})diff --git a/src/core/workspace-files.ts b/src/core/workspace-files.tsindex fb0b9be45..f89e471a6 100644--- a/src/core/workspace-files.ts+++ b/src/core/workspace-files.ts@@ -7,6 +7,7 @@ import {stripSharedNodeExec,type LocalNodeExecMap} from '../shared/node-exec'+import { CLOSED_SESSIONS_CAP } from '../shared/types'import type { BridgeLink, CanvasNodeState, ClosedSessionEntry, NavStop, Project, ProjectKanban, Viewport, Workspace } from '../shared/types'import { projectCapabilityFields, readProjectCapabilities } from '../shared/project-capabilities'import { loadedAgentBrowserPartition } from '../shared/browser-partition'@@ -258,8 +259,11 @@ 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.map((e) => ({+ ? p.closedSessions.slice(0, CLOSED_SESSIONS_CAP).map((e) => ({...e,node: sanitizeNodeTriggers(stripSharedNodeExec(p.cwd ? toPortableNodes([e.node], p.cwd) : [e.node])@@ -302,21 +306,40 @@ export function validKanban(k: unknown): k is ProjectKanban {)}-/** Tolerant-reader guard for `closedSessions`, same shallow-shape rule as `validKanban`: anything- * that isn't an array of `{id, closedAt, node}` objects is dropped rather than trusted, so a- * legacy/hand-edited file degrades to no history instead of crashing. */+/** A `{x, y}` point, checked at the boundary because the file is hostile input. */+function validPoint(p: unknown): p is { x: number; y: number } {+ return (+ !!p &&+ typeof p === 'object' &&+ typeof (p as { x: unknown }).x === 'number' &&+ typeof (p as { y: unknown }).y === 'number'+ )+}++/**+ * Tolerant-reader guard for `closedSessions`, same "drop it rather than trust it" rule as+ * `validKanban`: a legacy/hand-edited/hostile file degrades to no history instead of crashing.+ *+ * The POSITION fields are not optional politeness — they are the crash. `recreateNodeFromSnapshot`+ * assigns `node.position = reattach ? snapshot.position : snapshot.absolutePosition` UNGUARDED, so+ * an entry missing either one hands React Flow a node with `position: undefined`, and+ * `adoptUserNodes` dereferences `position.x` — a white-screen renderer crash from a file anyone can+ * commit. `kind` is checked for the sibling failure: a garbage kind reaches `buildBase`'s switch,+ * returns null, and the row silently consumes itself and vanishes (`buildBase` already `return+ * null`s for anything unknown, so a non-empty string is enough here — no NodeKind enum copy).+ */export function validClosedSessions(x: unknown): x is ClosedSessionEntry[] {return (Array.isArray(x) &&- x.every(- (e) =>- !!e &&- typeof e === 'object' &&- typeof (e as ClosedSessionEntry).id === 'string' &&- typeof (e as ClosedSessionEntry).closedAt === 'number' &&- !!(e as ClosedSessionEntry).node &&- typeof (e as ClosedSessionEntry).node === 'object'- )+ x.every((e) => {+ if (!e || typeof e !== 'object') return false+ const entry = e as ClosedSessionEntry+ if (typeof entry.id !== 'string' || typeof entry.closedAt !== 'number') return false+ if (!validPoint(entry.absolutePosition)) return false+ const node = entry.node as CanvasNodeState | undefined+ if (!node || typeof node !== 'object') return false+ return typeof node.kind === 'string' && node.kind.length > 0 && validPoint(node.position)+ }))}@@ -381,9 +404,12 @@ 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.map((e) => ({+ closedSessions: f.closedSessions.slice(0, CLOSED_SESSIONS_CAP).map((e) => ({...e,node: sanitizeNodeTriggers(sanitizeBrowserPartitions(diff --git a/src/renderer/lib/closedHistory.test.ts b/src/renderer/lib/closedHistory.test.tsindex dde8ae093..391576c9f 100644--- a/src/renderer/lib/closedHistory.test.ts+++ b/src/renderer/lib/closedHistory.test.ts@@ -67,6 +67,29 @@ describe('stateToReopenSnapshot', () => {expect(snap.extent).toBeUndefined()expect(snap.data.text).toBe('hi')})++ // Belt-and-braces behind validClosedSessions (which is what actually rejects these at the file+ // boundary). recreateNodeFromSnapshot assigns node.position from one of these two UNGUARDED and+ // React Flow dereferences position.x, so any path that reaches here with an entry the validator+ // never saw must land the node at a real point, not white-screen the renderer.+ it('falls back rather than emitting an undefined position when one point is missing', () => {+ const node = {+ id: 'n1', kind: 'terminal', position: { x: 3, y: 4 },+ size: { width: 1, height: 1 }, title: 't', color: '#fff', group: null+ }+ const noAbs = { id: 'e1', closedAt: 1, node } as unknown as ClosedSessionEntry+ expect(stateToReopenSnapshot(noAbs).absolutePosition).toEqual({ x: 3, y: 4 })++ const { position: _dropped, ...positionless } = node+ const noPos = {+ id: 'e1', closedAt: 1, node: positionless, absolutePosition: { x: 7, y: 8 }+ } as unknown as ClosedSessionEntry+ expect(stateToReopenSnapshot(noPos).position).toEqual({ x: 7, y: 8 })++ const neither = { id: 'e1', closedAt: 1, node: positionless } as unknown as ClosedSessionEntry+ expect(stateToReopenSnapshot(neither).position).toEqual({ x: 0, y: 0 })+ expect(stateToReopenSnapshot(neither).absolutePosition).toEqual({ x: 0, y: 0 })+ })})describe('mergeClosedHistory', () => {diff --git a/src/renderer/lib/closedHistory.ts b/src/renderer/lib/closedHistory.tsindex f2776477b..23f645258 100644--- a/src/renderer/lib/closedHistory.ts+++ b/src/renderer/lib/closedHistory.ts@@ -9,7 +9,8 @@ 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()`/`crypto.randomUUID`.+ * 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.*/export function buildClosedSessionEntries(deletedIds: ReadonlySet<string>,@@ -36,13 +37,21 @@ export function buildClosedSessionEntries(* already accepts. `CanvasNodeState` and `NodeData` share field names for everything both* track (by construction of `nodeStatesToFlow`/`flowToNodeStates`), so this is a direct field* copy, not a lossy remap.+ *+ * The position fallbacks are belt-and-braces behind `validClosedSessions`, which is what actually+ * rejects a positionless entry at the file boundary. They exist because+ * `recreateNodeFromSnapshot` assigns `node.position` from one of these two UNGUARDED, and React+ * Flow dereferences `position.x` — so any path that ever reaches here with an entry the validator+ * did not see (an inline index project, a future caller) lands the node at the origin instead of+ * white-screening the renderer.*/export function stateToReopenSnapshot(entry: ClosedSessionEntry): ReopenNodeSnapshot {const n = entry.node+ const origin = { x: 0, y: 0 }return {type: n.kind as RestorableNodeKind,- position: n.position,- absolutePosition: entry.absolutePosition,+ position: n.position ?? entry.absolutePosition ?? origin,+ absolutePosition: entry.absolutePosition ?? n.position ?? origin,...(n.parentId ? { parentId: n.parentId, extent: 'parent' as const } : {}),size: n.size,data: {diff --git a/src/renderer/state/projects.closedHistory.test.ts b/src/renderer/state/projects.closedHistory.test.tsindex b534e45ec..0ff8b1592 100644--- a/src/renderer/state/projects.closedHistory.test.ts+++ b/src/renderer/state/projects.closedHistory.test.ts@@ -1,5 +1,6 @@import { describe, it, expect } from 'vitest'import { useProjects } from './projects'+import { CLOSED_SESSIONS_CAP } from '@shared/types'import type { ClosedSessionEntry } from '@shared/types'const entry = (id: string, closedAt = 1): ClosedSessionEntry => ({@@ -35,9 +36,11 @@ describe('recordClosedSessions', () => {expect(useProjects.getState().getProject('p1')?.closedSessions?.map((e) => e.id)).toEqual(['b', 'a'])setup()- const many = Array.from({ length: 25 }, (_, i) => entry(`e${i}`))+ const many = Array.from({ length: CLOSED_SESSIONS_CAP + 5 }, (_, i) => entry(`e${i}`))useProjects.getState().recordClosedSessions('p1', many)- expect(useProjects.getState().getProject('p1')?.closedSessions).toHaveLength(20)+ expect(useProjects.getState().getProject('p1')?.closedSessions).toHaveLength(+ CLOSED_SESSIONS_CAP+ )})it('is a no-op for an unknown project', () => {diff --git a/src/renderer/state/projects.ts b/src/renderer/state/projects.tsindex e19e7886b..4682c102d 100644--- a/src/renderer/state/projects.ts+++ b/src/renderer/state/projects.ts@@ -11,6 +11,7 @@ import type {Viewport,Workspace} from '@shared/types'+import { CLOSED_SESSIONS_CAP } from '@shared/types'import { collisionSeed, derivedProjectId } from '@shared/project-id'import type { ProjectCapability } from '@shared/project-capabilities'import type { ProjectIcon } from '@shared/project-icon'@@ -146,8 +147,8 @@ interface ProjectsState {/** Restores a closed project and makes it active. No-op if the id is unknown. */reopenProject(id: string): void- /** Records freshly deleted sessions into the project's history (newest-first, capped at 20).- * No-op if `entries` is empty or the project no longer exists. */+ /** Records freshly deleted sessions into the project's history (newest-first, capped at+ * `CLOSED_SESSIONS_CAP`). No-op if `entries` is empty or the project no longer exists. */recordClosedSessions(projectId: string, entries: ClosedSessionEntry[]): void/** Removes and returns the matching closed-session entry, or `undefined` if it's already gone* (e.g. discarded from another surface first). */@@ -605,7 +606,13 @@ export const useProjects = create<ProjectsState>((set, get) => ({projects: s.projects.map((p) =>p.id !== projectId? p- : { ...p, closedSessions: [...entries, ...(p.closedSessions ?? [])].slice(0, 20) }+ : {+ ...p,+ closedSessions: [...entries, ...(p.closedSessions ?? [])].slice(+ 0,+ CLOSED_SESSIONS_CAP+ )+ })}))},diff --git a/src/shared/types.ts b/src/shared/types.tsindex 18b2f99fc..b13d3be71 100644--- a/src/shared/types.ts+++ b/src/shared/types.ts@@ -424,6 +424,17 @@ export interface ClosedSessionEntry {absolutePosition: { x: number; y: number }}+/**+ * 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.+ */+export const CLOSED_SESSIONS_CAP = 20+/*** A snapshot of one canvas's nodes in the form sent over the remote mirror wire.* Reuses the persisted node shape (`CanvasNodeState`) so host and client agree on layout.