Node-based terminal manager for AI coding agents — tmux-backed terminals and parallel agent sessions as draggable nodes on an infinite pan/zoom canvas. macOS, Linux, and a browser Server Edition.
TypeScript adhdagent-orchestrationai-agentscanvasclaude-codecodexcoding-agentsdeveloper-toolselectrongeminilinuxmacosmultiplexeropencodeparallel-agentsterminalterminal-emulatorterminal-multiplexertmuxworkspace-manager
feat(workspace): v3 index + per-project .nodeterm files with v2 migration
enes99229131d8e9
diff --git a/src/core/workspace-store.test.ts b/src/core/workspace-store.test.tsnew file mode 100644index 000000000..44ae52b04--- /dev/null+++ b/src/core/workspace-store.test.ts@@ -0,0 +1,128 @@+import { describe, it, expect, beforeEach, afterEach } from 'vitest'+import { promises as fs } from 'fs'+import os from 'os'+import path from 'path'+import { initPlatform, resetPlatformForTests } from './platform'+import { fakePlatform } from './platform-fake'+import { WorkspaceStore } from './workspace-store'+import type { Project, Workspace } from '../shared/types'++let userData: string+let projRoot: string+let fake: ReturnType<typeof fakePlatform>++const project = (over: Partial<Project> = {}): Project => ({+ id: 'p1', name: 'foo', color: '#7aa2f7', viewport: { x: 0, y: 0, zoom: 1 },+ nodes: [{ id: 'term-1', kind: 'terminal', position: { x: 0, y: 0 }, size: { width: 1, height: 1 }, title: 't', color: '#fff', group: null }],+ ...over+})+const ws = (projects: Project[], active = projects[0]?.id ?? ''): Workspace =>+ ({ version: 2, activeProjectId: active, projects })++beforeEach(async () => {+ userData = await fs.mkdtemp(path.join(os.tmpdir(), 'nt-ws-'))+ projRoot = await fs.mkdtemp(path.join(os.tmpdir(), 'nt-proj-'))+ fake = fakePlatform({ userDataDir: userData })+ initPlatform(fake)+})+afterEach(async () => {+ resetPlatformForTests()+ await fs.rm(userData, { recursive: true, force: true })+ await fs.rm(projRoot, { recursive: true, force: true })+})++describe('save → load round trip (v3)', () => {+ it('writes <cwd>/.nodeterm/project.json + a v3 index, and loads it back assembled', async () => {+ const store = new WorkspaceStore()+ await store.save(ws([project({ cwd: projRoot }), project({ id: 'p2', name: 'inline' })]))+ const file = JSON.parse(await fs.readFile(path.join(projRoot, '.nodeterm/project.json'), 'utf-8'))+ expect(file).toMatchObject({ version: 1, id: 'p1', rev: 1 })+ const index = JSON.parse(await fs.readFile(path.join(userData, 'workspace.json'), 'utf-8'))+ expect(index.version).toBe(3)+ expect(index.entries[0].cwd).toBe(projRoot)+ expect(index.entries[0].project).toBeUndefined()+ const loaded = await new WorkspaceStore().load()+ expect(loaded.version).toBe(2) // in-memory contract stays v2-shaped+ expect(loaded.projects[0]).toMatchObject({ id: 'p1', cwd: projRoot })+ expect(loaded.projects[0].nodes[0].id).toBe('term-1')+ expect(loaded.projects[1]).toMatchObject({ id: 'p2', name: 'inline' })+ })++ it('does not rewrite (or bump rev of) an unchanged project file', async () => {+ const store = new WorkspaceStore()+ const w = ws([project({ cwd: projRoot })])+ await store.save(w)+ const p = path.join(projRoot, '.nodeterm/project.json')+ const first = await fs.readFile(p, 'utf-8')+ await store.save(w)+ expect(await fs.readFile(p, 'utf-8')).toBe(first) // same rev, same bytes+ await store.save(ws([{ ...w.projects[0], name: 'renamed' }]))+ expect(JSON.parse(await fs.readFile(p, 'utf-8'))).toMatchObject({ rev: 2, name: 'renamed' })+ })+})++describe('v2 → v3 migration', () => {+ it('assembles a v2 file on load, then the first save migrates: project files + v3 index + .bak + broadcast', async () => {+ const legacy = ws([project({ cwd: projRoot })])+ await fs.writeFile(path.join(userData, 'workspace.json'), JSON.stringify(legacy))+ const store = new WorkspaceStore()+ const loaded = await store.load()+ expect(loaded.projects[0].id).toBe('p1')+ await store.save(loaded)+ expect(JSON.parse(await fs.readFile(path.join(userData, 'workspace.json'), 'utf-8')).version).toBe(3)+ expect(JSON.parse(await fs.readFile(path.join(userData, 'workspace.v2.bak'), 'utf-8')).version).toBe(2)+ expect((await fs.readFile(path.join(projRoot, '.nodeterm/project.json'), 'utf-8'))).toContain('"id": "p1"')+ expect(fake.sent.some((s) => s.channel === 'workspace:migrated')).toBe(true)+ })++ it('is idempotent: loading + saving v3 again writes no .bak twice and keeps data', async () => {+ const store = new WorkspaceStore()+ await store.save(ws([project({ cwd: projRoot })]))+ await fs.rm(path.join(userData, 'workspace.v2.bak'), { force: true })+ const again = new WorkspaceStore()+ await again.save(await again.load())+ await expect(fs.access(path.join(userData, 'workspace.v2.bak'))).rejects.toThrow()+ })+})++describe('unavailable & corrupt refs', () => {+ it('marks a ref with a missing folder unavailable (kept, greyed) instead of dropping it', async () => {+ const store = new WorkspaceStore()+ await store.save(ws([project({ cwd: projRoot })]))+ await fs.rm(projRoot, { recursive: true, force: true })+ const loaded = await new WorkspaceStore().load()+ expect(loaded.projects[0]).toMatchObject({ id: 'p1', name: 'foo', unavailable: true, nodes: [] })+ })++ it('sets aside a corrupt project file and marks the project unavailable', async () => {+ const store = new WorkspaceStore()+ await store.save(ws([project({ cwd: projRoot })]))+ const p = path.join(projRoot, '.nodeterm/project.json')+ await fs.writeFile(p, '{ not json')+ const loaded = await new WorkspaceStore().load()+ expect(loaded.projects[0].unavailable).toBe(true)+ const dir = await fs.readdir(path.join(projRoot, '.nodeterm'))+ expect(dir.some((f) => f.startsWith('project.json.corrupt-'))).toBe(true)+ })+})++describe('probeFolder', () => {+ it('returns the assembled project when the folder has a project file, else null', async () => {+ const store = new WorkspaceStore()+ await store.save(ws([project({ cwd: projRoot })]))+ const probed = await store.probeFolder(projRoot)+ expect(probed).toMatchObject({ id: 'p1', cwd: projRoot })+ expect(await store.probeFolder(path.join(projRoot, 'nope'))).toBeNull()+ })+})++describe('readLocalRefByPath', () => {+ it('maps a watched project.json path back to its project; unknown path → null', async () => {+ const store = new WorkspaceStore()+ await store.save(ws([project({ cwd: projRoot })]))+ const filePath = path.join(projRoot, '.nodeterm/project.json')+ const p = await store.readLocalRefByPath(filePath)+ expect(p).toMatchObject({ id: 'p1', cwd: projRoot })+ expect(await store.readLocalRefByPath(path.join(projRoot, 'nope/project.json'))).toBeNull()+ })+})diff --git a/src/core/workspace-store.ts b/src/core/workspace-store.tsindex cefb206ed..1378dbfcc 100644--- a/src/core/workspace-store.ts+++ b/src/core/workspace-store.ts@@ -3,77 +3,250 @@ import path from 'path'import { IPC } from '../shared/ipc'import { platform } from './platform'import {- DEFAULT_PROJECT_ID,- EMPTY_WORKSPACE,- type Workspace,- type WorkspaceV1+ DEFAULT_PROJECT_ID, EMPTY_WORKSPACE,+ type Project, type Workspace, type WorkspaceV1} from '../shared/types'+import {+ PROJECT_DIR, PROJECT_FILE, fileToProject, projectToFile, sameProjectContent,+ serializeProjectFile, splitWorkspace,+ type ProjectFileV1, type WorkspaceIndexV3+} from './workspace-files'++/** Remote file access for SSH projects (implemented in src/main over SshFs — src/core stays electron-free). */+export interface RemoteWorkspaceIO {+ read(projectId: string, ssh: NonNullable<Project['ssh']>): Promise<string | null>+ write(projectId: string, ssh: NonNullable<Project['ssh']>, content: string): Promise<boolean>+}++const projectFilePath = (cwd: string): string => path.join(cwd, PROJECT_DIR, PROJECT_FILE)++async function writeAtomic(filePath: string, content: string): Promise<void> {+ const tmp = `${filePath}.tmp`+ await fs.writeFile(tmp, content, 'utf-8')+ await fs.rename(tmp, filePath)+}/**- * Stores the workspace JSON in the user's userData directory.- * A single file (workspace.json) holds all projects.+ * v3 persistence: workspace.json is an index (refs + inline canvases); each local+ * project's data lives in <cwd>/.nodeterm/project.json (source of truth). The+ * renderer contract is unchanged: load() returns / save() takes an assembled+ * v2-shaped Workspace.*/export class WorkspaceStore {- private get filePath(): string {+ /** file path -> exact content we last wrote (skip-unchanged + watcher self-write suppression). */+ private lastWritten = new Map<string, string>()+ /** project id -> rev of the last written/loaded file. */+ private revs = new Map<string, number>()+ /** Raw v2 file content, kept until the first save backs it up (migration). */+ private pendingV2Backup: string | null = null+ /** Last index written/loaded — lets readLocalRef/refresh resolve entries without a full load. */+ private index: WorkspaceIndexV3 | null = null+ /** Optional hook fired after every load()/save() — the watcher re-syncs its watch set (Task 5). */+ onPersist?: () => void++ constructor(private remoteIO?: RemoteWorkspaceIO) {}++ private get indexPath(): string {return path.join(platform().userDataDir, 'workspace.json')}registerIpc(): void {platform().handle(IPC.workspaceLoad, () => this.load())platform().handle(IPC.workspaceSave, (workspace: Workspace) => this.save(workspace))+ platform().handle(IPC.workspaceProbeFolder, (folder: string) => this.probeFolder(folder))}async load(): Promise<Workspace> {+ const result = await this.loadInner()+ this.onPersist?.()+ return result+ }++ private async loadInner(): Promise<Workspace> {+ let raw: string+ try {+ raw = await fs.readFile(this.indexPath, 'utf-8')+ } catch {+ return EMPTY_WORKSPACE+ }+ let parsed: unknowntry {- const raw = await fs.readFile(this.filePath, 'utf-8')- return migrate(JSON.parse(raw))+ parsed = JSON.parse(raw)} catch {- // Missing or corrupt file -> return an empty workspace.return EMPTY_WORKSPACE}+ const anyParsed = parsed as { version?: number }+ if (anyParsed?.version === 3) return this.loadV3(parsed as WorkspaceIndexV3)+ // v1/v2: assemble in memory now; the first save() performs the actual migration.+ const legacy = migrateLegacy(parsed)+ if (legacy.projects.length) this.pendingV2Backup = raw+ return legacy+ }++ private async loadV3(index: WorkspaceIndexV3): Promise<Workspace> {+ this.index = index+ const projects: Project[] = []+ for (const e of index.entries) {+ if (e.project) {+ projects.push(e.project)+ } else if (e.cwd) {+ const p = await this.readProjectFile(e.cwd)+ if (p) {+ this.revs.set(p.id, p.rev)+ this.lastWritten.set(projectFilePath(e.cwd), serializeProjectFile(p))+ projects.push(fileToProject(p, { cwd: e.cwd, closed: e.closed }))+ } else {+ projects.push(unavailableProject(e))+ }+ } else if (e.ssh) {+ if (e.cache) {+ this.revs.set(e.id, e.cache.rev)+ projects.push(fileToProject(e.cache, { ssh: e.ssh, closed: e.closed }))+ } else {+ projects.push(unavailableProject(e))+ }+ }+ }+ const active = projects.some((p) => p.id === index.activeProjectId && !p.unavailable)+ ? index.activeProjectId+ : (projects.find((p) => !p.closed && !p.unavailable)?.id ?? '')+ return { version: 2, activeProjectId: active, projects }+ }++ /** Reads + parses one project file; a corrupt file is set aside (never overwritten). */+ private async readProjectFile(cwd: string): Promise<ProjectFileV1 | null> {+ const file = projectFilePath(cwd)+ let raw: string+ try {+ raw = await fs.readFile(file, 'utf-8')+ } catch {+ return null+ }+ try {+ const parsed = JSON.parse(raw) as ProjectFileV1+ if (parsed?.version !== 1 || typeof parsed.id !== 'string' || !Array.isArray(parsed.nodes)) return null+ return parsed+ } catch {+ try {+ await fs.rename(file, `${file}.corrupt-${Date.now()}`)+ } catch { /* best effort — never destroy data */ }+ return null+ }}async save(workspace: Workspace): Promise<void> {- // Atomic write: a crash/kill mid-write to the real file would truncate it, and a- // corrupt workspace.json silently loads as empty (total layout loss). Write to a- // temp file then rename (atomic on the same filesystem).- // Compact stringify (no pretty-print): the save runs on an 800ms debounce and serializes- // EVERY project's nodes — indentation roughly doubled both the string-build cost and the- // bytes written, for a file nobody reads by hand.- const tmp = `${this.filePath}.tmp`- await fs.writeFile(tmp, JSON.stringify(workspace), 'utf-8')- await fs.rename(tmp, this.filePath)+ const savedAt = new Date().toISOString()+ const { index, files } = splitWorkspace(workspace, (id) => this.revs.get(id) ?? 0, savedAt)++ for (const [cwd, candidate] of files) {+ const file = projectFilePath(cwd)+ const prev = this.lastWritten.get(file)+ const prevParsed = prev ? (JSON.parse(prev) as ProjectFileV1) : null+ if (prevParsed && sameProjectContent(prevParsed, candidate)) continue+ const next: ProjectFileV1 = { ...candidate, rev: (this.revs.get(candidate.id) ?? 0) + 1 }+ const content = serializeProjectFile(next)+ try {+ await fs.mkdir(path.dirname(file), { recursive: true })+ await writeAtomic(file, content)+ this.lastWritten.set(file, content)+ this.revs.set(next.id, next.rev)+ } catch { /* folder gone (unmounted disk): the entry simply stays stale → unavailable next load */ }+ }++ // ssh caches: bump rev on change so a later remote write can win; mirror write in Task 8.+ for (const e of index.entries) {+ if (!e.ssh || !e.cache) continue+ const prevRev = this.revs.get(e.id) ?? 0+ const changedSinceLoad = !this.index?.entries.some(+ (old) => old.id === e.id && old.cache && sameProjectContent(old.cache, e.cache!)+ )+ e.cache.rev = changedSinceLoad ? prevRev + 1 : prevRev+ this.revs.set(e.id, e.cache.rev)+ if (this.remoteIO && changedSinceLoad) {+ void this.remoteIO.write(e.id, e.ssh, serializeProjectFile(e.cache))+ }+ }++ // Compact index, atomic — same reasoning as the old single-file store.+ await writeAtomic(this.indexPath, JSON.stringify(index))+ this.index = index++ if (this.pendingV2Backup !== null) {+ const bak = this.pendingV2Backup+ this.pendingV2Backup = null+ try {+ await fs.writeFile(path.join(platform().userDataDir, 'workspace.v2.bak'), bak, 'utf-8')+ } catch { /* backup is best-effort */ }+ platform().broadcast(IPC.workspaceMigrated)+ }++ this.onPersist?.()+ }++ async probeFolder(folder: string): Promise<Project | null> {+ const f = await this.readProjectFile(folder)+ return f ? fileToProject(f, { cwd: folder }) : null+ }++ localRefPaths(): string[] {+ return (this.index?.entries ?? []).filter((e) => e.cwd).map((e) => projectFilePath(e.cwd!))+ }++ isSelfWrite(filePath: string, content: string): boolean {+ return this.lastWritten.get(filePath) === content+ }++ async readLocalRef(projectId: string): Promise<Project | null> {+ const e = this.index?.entries.find((x) => x.id === projectId && x.cwd)+ if (!e?.cwd) return null+ const f = await this.readProjectFile(e.cwd)+ if (!f) return null+ this.revs.set(f.id, f.rev)+ this.lastWritten.set(projectFilePath(e.cwd), serializeProjectFile(f))+ return fileToProject(f, { cwd: e.cwd, closed: e.closed })+ }++ /** Maps a watched file path back to its project and re-reads it. */+ async readLocalRefByPath(filePath: string): Promise<Project | null> {+ const e = this.index?.entries.find((x) => x.cwd && projectFilePath(x.cwd) === filePath)+ return e ? this.readLocalRef(e.id) : null+ }++ /** SSH refresh-on-connect — wired in Task 8. */+ async refreshSshProject(_projectId: string): Promise<Project | null> {+ return null}}-/** Normalize any on-disk shape (v1 single canvas, v2 projects) into a valid v2 workspace. */-function migrate(parsed: unknown): Workspace {- const ws = parsed as Partial<Workspace> & Partial<WorkspaceV1>+/** A labeled grey placeholder for a ref whose file can't be read right now. */+function unavailableProject(e: { id: string; name: string; color: string; closed?: boolean; cwd?: string; ssh?: Project['ssh'] }): Project {+ return {+ id: e.id, name: e.name, color: e.color,+ viewport: { x: 0, y: 0, zoom: 1 }, nodes: [],+ ...(e.cwd ? { cwd: e.cwd } : {}), ...(e.ssh ? { ssh: e.ssh } : {}),+ ...(e.closed ? { closed: true } : {}),+ unavailable: true+ }+}- // v2: keep as-is, including an empty project list (→ welcome screen).+/** Normalize legacy on-disk shapes (v1 single canvas, v2 projects) into a v2-shaped workspace. */+function migrateLegacy(parsed: unknown): Workspace {+ const ws = parsed as Partial<Workspace> & Partial<WorkspaceV1>if (ws?.version === 2 && Array.isArray(ws.projects)) {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 }}-- // v1: a single canvas -> wrap it in one default project.if (ws?.version === 1 && Array.isArray(ws.nodes)) {return {version: 2,activeProjectId: DEFAULT_PROJECT_ID,- projects: [- {- id: DEFAULT_PROJECT_ID,- name: 'Project 1',- color: '#7aa2f7',- viewport: ws.viewport ?? { x: 0, y: 0, zoom: 1 },- nodes: ws.nodes- }- ]+ projects: [{+ id: DEFAULT_PROJECT_ID, name: 'Project 1', color: '#7aa2f7',+ viewport: ws.viewport ?? { x: 0, y: 0, zoom: 1 }, nodes: ws.nodes+ }]}}-return EMPTY_WORKSPACE}