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(workspace): a git-shared project.json must not give two folders one project id
enes13fd49d9e449
diff --git a/src/core/project-node-append.test.ts b/src/core/project-node-append.test.tsindex 840df0c02..684e589b5 100644--- a/src/core/project-node-append.test.ts+++ b/src/core/project-node-append.test.ts@@ -108,12 +108,19 @@ describe('appendProjectNode', () => {expect(appendProjectNode(baseFile([sibling]), { id: 'term-aaa-1' }, NOW)).toBeNull()})- it('refuses an id that is not a safe term-<ts36>-<n> shape (it becomes a tmux session name)', () => {- for (const bad of ['x', 'term-a b-1', "term-a'b-1", 'term--1', 'sticky-abc-1', 'term-abc-']) {+ it('refuses an id that is not a safe term-<ts36>-<token> shape (it becomes a tmux session name)', () => {+ for (const bad of [+ 'x', 'term-a b-1', "term-a'b-1", 'term--1', 'sticky-abc-1', 'term-abc-',+ 'term-abc-../x', 'term-abc-A1', 'term-abc-1-2', `term-abc-${'a'.repeat(17)}`+ ]) {expect(appendProjectNode(baseFile([]), { id: bad }, NOW)).toBeNull()}})+ it('accepts the random-token tail the desktop now mints (the counter was a collision generator)', () => {+ expect(appendProjectNode(baseFile([]), { id: 'term-m1a2b3c-4f8a2c1b' }, NOW)).not.toBeNull()+ })+it('sanitizes title/agentId: non-strings dropped, title capped', () => {const f = JSON.parse(appendProjectNode(baseFile([]), { id: 'term-c-1', title: 'x'.repeat(500), agentId: 123 as never }, NOW)!diff --git a/src/core/project-node-append.ts b/src/core/project-node-append.tsindex 18d2f8e0a..eb40e9c6d 100644--- a/src/core/project-node-append.ts+++ b/src/core/project-node-append.ts@@ -17,9 +17,15 @@ export interface RemoteNodeInput {agentId?: string}-/** The desktop id shape (`term-<base36 ms>-<n>`). Anything else is refused — the id is- * interpolated into tmux session names, so the alphabet stays strictly boring. */-const SAFE_NODE_ID = /^term-[a-z0-9]+-\d{1,6}$/+/** The desktop id shape (`term-<base36 ms>-<token>`). Anything else is refused — the id is+ * interpolated into tmux session names, so the alphabet stays strictly boring.+ *+ * The tail was `\d{1,6}` while the desktop minted a monotonic counter. That counter restarted at+ * zero on every renderer start (and every HMR reload), so it was a collision generator and is now+ * a random hex token — and this guard, which is what the PHONE's ids are checked against, would+ * have refused every id the phone mints once nodeterm-ios adopts the same shape. Widened to the+ * same boring alphabet; an empty tail (`term-abc-`) is still refused. */+const SAFE_NODE_ID = /^term-[a-z0-9]+-[a-z0-9]{1,16}$/const TITLE_MAX = 120diff --git a/src/core/workspace-files.test.ts b/src/core/workspace-files.test.tsindex 2092f0cf9..923094da6 100644--- a/src/core/workspace-files.test.ts+++ b/src/core/workspace-files.test.ts@@ -103,6 +103,68 @@ describe('splitWorkspace', () => {expect(index.entries[1].project!.unavailable).toBeUndefined()})+ it('two DIFFERENT folders under one id → two entries, two files, neither clobbering the other', () => {+ // The last-resort guard for a duplicate id that reached save without going through the+ // store's load repair (a hand-edited index, a runtime collision). Keying only by cwd let both+ // entries keep the id, and every id-keyed lookup downstream resolved to the first one.+ const collided: Workspace = {+ version: 2, activeProjectId: 'dup',+ projects: [+ project({ id: 'dup', name: 'first', cwd: '/a/foo', nodes: [node({ id: 'term-a' })] }),+ project({ id: 'dup', name: 'second', cwd: '/a/bar', nodes: [node({ id: 'term-b' })] })+ ]+ }+ const { index, files } = splitWorkspace(collided, () => 1, '2026-07-11T00:00:00.000Z')+ expect(index.entries).toHaveLength(2)+ expect(index.entries[0].id).toBe('dup') // first holder keeps it+ expect(index.entries[1].id).not.toBe('dup')+ expect(files.size).toBe(2)+ expect(files.get('/a/foo')!.id).toBe('dup')+ expect(files.get('/a/bar')!.id).toBe(index.entries[1].id)+ expect(files.get('/a/foo')!.nodes.map((n) => n.id)).toEqual(['term-a'])+ expect(files.get('/a/bar')!.nodes.map((n) => n.id)).toEqual(['term-b'])+ })++ it('the re-key is deterministic (same input, same index) — a save loop must not churn the file', () => {+ const collided: Workspace = {+ version: 2, activeProjectId: 'dup',+ projects: [project({ id: 'dup', cwd: '/a/foo' }), project({ id: 'dup', cwd: '/a/bar' })]+ }+ const once = splitWorkspace(collided, () => 1, '2026-07-11T00:00:00.000Z')+ const twice = splitWorkspace(collided, () => 1, '2026-07-11T00:00:00.000Z')+ expect(twice.index.entries[1].id).toBe(once.index.entries[1].id)+ })++ it('same id AND same cwd still takes the inline escape hatch (no second file)', () => {+ const collided: Workspace = {+ version: 2, activeProjectId: 'dup',+ projects: [+ project({ id: 'dup', name: 'first', cwd: '/a/foo' }),+ project({ id: 'dup', name: 'second', cwd: '/a/foo' })+ ]+ }+ const { index, files } = splitWorkspace(collided, () => 1, '2026-07-11T00:00:00.000Z')+ expect(files.size).toBe(1)+ expect(index.entries[1].project).toBeTruthy()+ expect(index.entries[1].id).not.toBe('dup')+ expect(index.entries[1].project!.id).toBe(index.entries[1].id)+ })++ it('two ssh entries under one id get distinct ids and distinct caches', () => {+ const sshOf = (remoteCwd: string) => ({ server: { host: 'h', user: 'u' } as any, remoteCwd })+ const collided: Workspace = {+ version: 2, activeProjectId: 'dup',+ projects: [+ project({ id: 'dup', name: 'first', ssh: sshOf('~/one') }),+ project({ id: 'dup', name: 'second', ssh: sshOf('~/two') })+ ]+ }+ const { index } = splitWorkspace(collided, () => 1, '2026-07-11T00:00:00.000Z')+ expect(index.entries[0].id).toBe('dup')+ expect(index.entries[1].id).not.toBe('dup')+ expect(index.entries[1].cache!.id).toBe(index.entries[1].id)+ })+it('never persists the runtime unavailable flag inline', () => {const { index } = splitWorkspace({ version: 2, activeProjectId: 'x', projects: [project({ id: 'x', unavailable: true })] },diff --git a/src/core/workspace-files.ts b/src/core/workspace-files.tsindex e13008344..ba1bf9cd4 100644--- a/src/core/workspace-files.ts+++ b/src/core/workspace-files.ts@@ -1,5 +1,6 @@import path from 'path'import type { AgentPermissionMode } from '../shared/agents/config'+import { collisionSeed, derivedProjectId } from '../shared/project-id'import {applyLocalNodeExec,localNodeExec,@@ -177,11 +178,24 @@ export function splitWorkspace(): { index: WorkspaceIndexV3; files: Map<string, ProjectFileV1> } {const entries: IndexEntryV3[] = []const files = new Map<string, ProjectFileV1>()- for (const p of ws.projects) {+ const seenIds = new Set<string>()+ for (const incoming of ws.projects) {// A relay tab is a LIVE connection to another machine's project, not a workspace on this// disk — it has no disk representation at all. Drop it entirely (no ref, no inline, no// cache) BEFORE the unavailable handling, so it leaks in none of the branches below.- if (p.remote) continue+ if (incoming.remote) continue+ // Two entries may never share an id. The index is keyed by it — which folder's project.json a+ // save writes, and every id-keyed lookup that reads the index back (ssh control paths,+ // board-log + approval routing, presence, agent status) resolves only the FIRST match. The+ // load-time repair (WorkspaceStore.repairDuplicateIds) is where a corrupt store is normally+ // healed; this is the last resort for a duplicate that reaches save some other way — a+ // hand-edited index, a runtime collision — and it uses the same deterministic derivation, so+ // both paths agree on the id instead of fighting over it.+ const id = seenIds.has(incoming.id)+ ? derivedProjectId(incoming.id, collisionSeed(incoming), (candidate) => seenIds.has(candidate))+ : incoming.id+ seenIds.add(id)+ const p = id === incoming.id ? incoming : { ...incoming, id }const header = { id: p.id, name: p.name, color: p.color, ...(p.closed ? { closed: true } : {}) }if (p.unavailable) {// Placeholder (folder missing / server unreachable at load): its nodes:[] is not realdiff --git a/src/core/workspace-store.test.ts b/src/core/workspace-store.test.tsindex 288fd03bd..c99019028 100644--- a/src/core/workspace-store.test.ts+++ b/src/core/workspace-store.test.ts@@ -1056,3 +1056,201 @@ describe('save corruption hardening', () => {expect(index.entries).toEqual([])})})++// THE duplicate-id bug (field report: ~1500 React "two children with the same key,+// 'project-ms4zdpc0-1'" warnings from TabBar). `.nodeterm/project.json` is a GIT-SHARED file — the+// migration banner asks users to commit it — so `git worktree add`, a branch checkout, `reset+// --hard` or a `stash pop` re-materialises one committed project id into a SECOND folder. Two tabs+// then answer to one id, and `commitCanvas` (which maps by id) writes the ACTIVE canvas into BOTH+// projects, so the next save flushes it into the other folder's project.json. Silent cross-folder+// data loss on every autosave, plus co-attached tmux sessions and a delete that kills both.+//+// The ssh branch has defended against exactly this since the "reset bug" fix (see 'ssh lineage+// safety' above): a DIFFERENT lineage is adopted RE-KEYED to our entry id. These tests pin the+// same rule for local folder refs, plus the repair for a store that is already corrupt.+describe('a git-shared project.json must not give two folders one project id', () => {+ let otherRoot: string+ beforeEach(async () => {+ otherRoot = await fs.mkdtemp(path.join(os.tmpdir(), 'nt-proj2-'))+ })+ afterEach(async () => {+ await fs.rm(otherRoot, { recursive: true, force: true })+ })++ const projectFile = (over: Record<string, unknown> = {}): string =>+ JSON.stringify({+ version: 1, rev: 3, savedAt: 'then', id: 'project-ms4zdpc0-1', name: 'one', color: '#7aa2f7',+ viewport: { x: 0, y: 0, zoom: 1 },+ nodes: [{+ id: 'term-a', kind: 'terminal', position: { x: 0, y: 0 }, size: { width: 1, height: 1 },+ title: 'a', color: '#fff', group: null+ }],+ ...over+ }, null, 2)++ /** Both folders carry the SAME committed id — a worktree/checkout of a repo that ships its+ * canvas — and the index (written by an earlier save) records that one id twice. */+ const seedCollision = async (over: Record<string, unknown> = {}): Promise<void> => {+ await fs.mkdir(path.join(projRoot, '.nodeterm'), { recursive: true })+ await fs.mkdir(path.join(otherRoot, '.nodeterm'), { recursive: true })+ await fs.writeFile(path.join(projRoot, '.nodeterm/project.json'), projectFile())+ await fs.writeFile(+ path.join(otherRoot, '.nodeterm/project.json'),+ projectFile({ name: 'two', nodes: [{+ id: 'term-b', kind: 'terminal', position: { x: 9, y: 9 }, size: { width: 1, height: 1 },+ title: 'b', color: '#fff', group: null+ }], ...over })+ )+ await fs.writeFile(path.join(userData, 'workspace.json'), JSON.stringify({+ version: 3,+ activeProjectId: 'project-ms4zdpc0-1',+ entries: [+ { id: 'project-ms4zdpc0-1', name: 'one', color: '#7aa2f7', cwd: projRoot },+ { id: 'project-ms4zdpc0-1', name: 'two', color: '#7aa2f7', cwd: otherRoot }+ ]+ }))+ }++ const readIndex = async () =>+ JSON.parse(await fs.readFile(path.join(userData, 'workspace.json'), 'utf-8'))++ it('loads two colliding folders as two projects with DIFFERENT ids, each keeping its own cwd and canvas', async () => {+ await seedCollision()+ const loaded = await new WorkspaceStore().load()+ expect(loaded.projects).toHaveLength(2)+ const [a, b] = loaded.projects+ expect(a.id).not.toBe(b.id)+ expect(new Set(loaded.projects.map((p) => p.id)).size).toBe(2)+ // First holder keeps the id; the loser is re-keyed. Neither canvas moved folders.+ expect(a).toMatchObject({ id: 'project-ms4zdpc0-1', cwd: projRoot, name: 'one' })+ expect(a.nodes.map((n) => n.id)).toEqual(['term-a'])+ expect(b).toMatchObject({ cwd: otherRoot, name: 'two' })+ expect(b.nodes.map((n) => n.id)).toEqual(['term-b'])+ // The active project still resolves (the surviving holder of the active id).+ expect(loaded.activeProjectId).toBe('project-ms4zdpc0-1')+ })++ it('REPAIRS the corrupt store on disk: the loser project.json AND its index entry are re-keyed', async () => {+ await seedCollision()+ const loaded = await new WorkspaceStore().load()+ const newId = loaded.projects[1].id++ const file = JSON.parse(await fs.readFile(path.join(otherRoot, '.nodeterm/project.json'), 'utf-8'))+ expect(file.id).toBe(newId)+ expect(file.nodes.map((n: { id: string }) => n.id)).toEqual(['term-b']) // canvas untouched+ expect(file.rev).toBeGreaterThan(3) // a changed file must outrank the copy it diverged from+ // The winner's file is left completely alone.+ expect(JSON.parse(await fs.readFile(path.join(projRoot, '.nodeterm/project.json'), 'utf-8')).id)+ .toBe('project-ms4zdpc0-1')++ const index = await readIndex()+ expect(index.entries.map((e: { id: string }) => e.id)).toEqual(['project-ms4zdpc0-1', newId])+ })++ it('the repair is IDEMPOTENT: a second (and third) load returns the same ids and rewrites nothing', async () => {+ await seedCollision()+ const first = (await new WorkspaceStore().load()).projects.map((p) => p.id)+ expect(new Set(first).size).toBe(2)+ const fileAfterRepair = await fs.readFile(path.join(otherRoot, '.nodeterm/project.json'), 'utf-8')+ const indexAfterRepair = await fs.readFile(path.join(userData, 'workspace.json'), 'utf-8')++ const second = (await new WorkspaceStore().load()).projects.map((p) => p.id)+ const third = (await new WorkspaceStore().load()).projects.map((p) => p.id)+ expect(new Set(second).size).toBe(2)+ expect(second).toEqual(first)+ expect(third).toEqual(first)+ // Converges: no churn in the user's repo (and no git diff) on every boot.+ expect(await fs.readFile(path.join(otherRoot, '.nodeterm/project.json'), 'utf-8')).toBe(fileAfterRepair)+ expect(await fs.readFile(path.join(userData, 'workspace.json'), 'utf-8')).toBe(indexAfterRepair)+ })++ it('a save after the repair keeps both canvases in their own folders (no cross-folder overwrite)', async () => {+ await seedCollision()+ const store = new WorkspaceStore()+ const loaded = await store.load()+ await store.save(loaded)+ const a = JSON.parse(await fs.readFile(path.join(projRoot, '.nodeterm/project.json'), 'utf-8'))+ const b = JSON.parse(await fs.readFile(path.join(otherRoot, '.nodeterm/project.json'), 'utf-8'))+ expect(a.nodes.map((n: { id: string }) => n.id)).toEqual(['term-a'])+ expect(b.nodes.map((n: { id: string }) => n.id)).toEqual(['term-b'])+ expect(a.id).not.toBe(b.id)+ })++ it('announces the repair once per project, naming the folder (a silent edit of the user\'s data is worse)', async () => {+ await seedCollision()+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})+ await new WorkspaceStore().load()+ const lines = warn.mock.calls.map((c) => c.join(' ')).filter((l) => l.includes('project id'))+ expect(lines).toHaveLength(1)+ expect(lines[0]).toContain(otherRoot)+ expect(lines[0]).toContain('project-ms4zdpc0-1')+ warn.mockRestore()+ })++ it('a read-only load (sideline: false — the relay blob) repairs in memory but never touches the disk', async () => {+ await seedCollision()+ const before = await fs.readFile(path.join(otherRoot, '.nodeterm/project.json'), 'utf-8')+ const indexBefore = await fs.readFile(path.join(userData, 'workspace.json'), 'utf-8')+ const loaded = await new WorkspaceStore().load({ sideline: false })+ expect(new Set(loaded.projects.map((p) => p.id)).size).toBe(2) // the phone never sees a dup+ expect(await fs.readFile(path.join(otherRoot, '.nodeterm/project.json'), 'utf-8')).toBe(before)+ expect(await fs.readFile(path.join(userData, 'workspace.json'), 'utf-8')).toBe(indexBefore)+ })++ it('THE PREVENTION: the index entry — not the git-shared file — owns the project id', async () => {+ // One project, saved normally. Then a branch checkout drops a DIFFERENT committed id into its+ // project.json (this is how the second folder gets the first folder's id in the first place).+ const store = new WorkspaceStore()+ await store.save(ws([project({ id: 'mine', cwd: projRoot })]))+ const file = JSON.parse(await fs.readFile(path.join(projRoot, '.nodeterm/project.json'), 'utf-8'))+ await fs.writeFile(+ path.join(projRoot, '.nodeterm/project.json'),+ JSON.stringify({ ...file, id: 'theirs', name: 'renamed-upstream' }, null, 2)+ )++ const next = new WorkspaceStore()+ const loaded = await next.load()+ // Our tab keeps ITS identity (node ids — tmux session names — and every id-keyed lookup that+ // hangs off it), while the file's CONTENT is adopted. Exactly the ssh branch's rule.+ expect(loaded.projects[0]).toMatchObject({ id: 'mine', name: 'renamed-upstream', cwd: projRoot })+ // …and the file is re-keyed on the next save, not left disagreeing with the index.+ await next.save(loaded)+ expect(JSON.parse(await fs.readFile(path.join(projRoot, '.nodeterm/project.json'), 'utf-8')))+ .toMatchObject({ id: 'mine', name: 'renamed-upstream' })+ })++ it('readLocalRef (the watcher\'s re-read after a checkout) comes back under the ENTRY id too', async () => {+ const store = new WorkspaceStore()+ await store.save(ws([project({ id: 'mine', cwd: projRoot })]))+ await store.load()+ const file = JSON.parse(await fs.readFile(path.join(projRoot, '.nodeterm/project.json'), 'utf-8'))+ await fs.writeFile(+ path.join(projRoot, '.nodeterm/project.json'),+ JSON.stringify({ ...file, id: 'theirs', rev: 99 }, null, 2)+ )+ // A project handed to replaceProject() under a foreign id would silently match nothing.+ await expect(store.readLocalRef('mine')).resolves.toMatchObject({ id: 'mine', cwd: projRoot })+ })++ it('leaves a healthy store completely alone (no re-key, no rewrite, no warning)', async () => {+ const store = new WorkspaceStore()+ await store.save(ws([project({ id: 'a', cwd: projRoot }), project({ id: 'b', cwd: otherRoot })]))+ const before = await fs.readFile(path.join(otherRoot, '.nodeterm/project.json'), 'utf-8')+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})+ const loaded = await new WorkspaceStore().load()+ expect(loaded.projects.map((p) => p.id)).toEqual(['a', 'b'])+ expect(await fs.readFile(path.join(otherRoot, '.nodeterm/project.json'), 'utf-8')).toBe(before)+ expect(warn).not.toHaveBeenCalled()+ warn.mockRestore()+ })++ it('two same-CWD tabs (the inline escape hatch) still round-trip — that dedupe is by cwd, not id', async () => {+ const store = new WorkspaceStore()+ await store.save(ws([+ project({ id: 'a', name: 'first', cwd: projRoot }),+ project({ id: 'b', name: 'second', cwd: projRoot })+ ]))+ const loaded = await new WorkspaceStore().load()+ expect(loaded.projects.map((p) => p.id).sort()).toEqual(['a', 'b'])+ })+})diff --git a/src/core/workspace-store.ts b/src/core/workspace-store.tsindex c77595170..c9dcbf0f9 100644--- a/src/core/workspace-store.ts+++ b/src/core/workspace-store.ts@@ -13,6 +13,7 @@ import {type IndexEntryV3, type ProjectFileV1, type WorkspaceIndexV3} from './workspace-files'import { hoistLegacyNodeExec, type LocalNodeExecMap } from '../shared/node-exec'+import { collisionSeed, derivedProjectId } from '../shared/project-id'import { appendProjectNode, type RemoteNodeInput } from './project-node-append'/** Checked remote read: `absent` (no file — safe to push our cache) is NOT `error` (connection@@ -34,6 +35,15 @@ interface ProjectFileRead {raw: string}+/** One index entry paired with the project loadV3 built from it (and, for a local ref, the file it+ * was built from). The uniqueness pass needs all three: it re-keys the project the renderer sees,+ * the entry that persists that identity, and the project.json the id was wrongly read from. */+interface LoadedEntry {+ entry: IndexEntryV3+ project: Project+ file?: ProjectFileV1+}+let tmpSeq = 0async function writeAtomic(filePath: string, content: string): Promise<void> {// Unique per write: writers that bypass each other's queue (a second app instance, the SSH@@ -199,49 +209,155 @@ export class WorkspaceStore {private async loadV3(index: WorkspaceIndexV3, sideline: boolean): Promise<Workspace> {for (const entry of index.entries) entry.localApprovalId ||= randomUUID()this.index = index- const projects: Project[] = []+ const built: LoadedEntry[] = []for (const e of index.entries) {if (e.project) {// Inline projects are stored verbatim in the index (no fileToProject pass), so apply the// same kanban shape guard here — a v1/hand-edited board would otherwise crash the render.const { kanban, ...rest } = e.project- projects.push(validKanban(kanban) ? e.project : rest)+ built.push({ entry: e, project: validKanban(kanban) ? e.project : rest })} else if (e.cwd) {if (sideline) await sweepStaleTmp(projectFilePath(e.cwd))const read = await this.readProjectFile(e.cwd, sideline)if (read) {- const p = read.file+ const p = this.entryKeyed(e, read.file)this.revs.set(p.id, p.rev)this.lastWritten.set(projectFilePath(e.cwd), read.raw)- projects.push(- fileToProject(p, { cwd: e.cwd, closed: e.closed, localExec: this.execOverlay(e, p) })- )+ built.push({+ entry: e,+ file: p,+ project: fileToProject(p, {+ cwd: e.cwd,+ closed: e.closed,+ localExec: this.execOverlay(e, p)+ })+ })} else {this.deferExecMigration(e)- projects.push(unavailableProject(e))+ built.push({ entry: e, project: unavailableProject(e) })}} else if (e.ssh) {if (e.cache) {this.revs.set(e.id, e.cache.rev)- projects.push(- fileToProject(e.cache, {+ built.push({+ entry: e,+ project: fileToProject(e.cache, {ssh: e.ssh,closed: e.closed,localExec: this.execOverlay(e, e.cache)})- )+ })} else {this.deferExecMigration(e)- projects.push(unavailableProject(e))+ built.push({ entry: e, project: unavailableProject(e) })}}}+ await this.repairDuplicateIds(built, sideline)+ const projects = built.map((b) => b.project)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 }}+ /**+ * The project file as it must be USED: keyed by the INDEX ENTRY's id, not by the id the file+ * carries. The generalisation of the ssh branch's DIFFERENT-lineage rule (see `reconcileSsh`:+ * "a re-added folder, a second machine, a git checkout … Adoption re-keys the file to OUR entry+ * id") to the local-folder branch, which never got it.+ *+ * `<cwd>/.nodeterm/project.json` is a SHARED document — the migration banner asks users to commit+ * it so the canvas travels with the repo — so its `id` is not evidence of identity: `git worktree+ * add`, a branch checkout, `reset --hard` or a `stash pop` re-materialise one committed id into a+ * SECOND folder, and both tabs then answer to it. The index entry is machine-local and per-folder,+ * so it is the only id that can be trusted to be OURS and unique.+ *+ * The file's CONTENT is adopted unchanged (nodes keep their ids — they are tmux session names —+ * so terminals reattach); only the key changes. `lastWritten` still records the RAW on-disk bytes,+ * which is what marks the file for a re-key on the next save: its id no longer matches the+ * candidate splitWorkspace builds, so `sameProjectContent` sees a change and rewrites it.+ */+ private entryKeyed(e: IndexEntryV3, f: ProjectFileV1): ProjectFileV1 {+ return f.id === e.id ? f : { ...f, id: e.id }+ }++ /**+ * The backstop: after every entry is loaded, no two projects may still share an id.+ *+ * `entryKeyed` fixes a file that drifted from ITS entry, but it cannot fix a store that is+ * ALREADY corrupt — once two entries were saved under one id (both folders' files carried it at+ * the last save), the entry ids agree with the files and with each other, and nothing downstream+ * notices: `splitWorkspace` dedupes by CWD, so both entries survive every save; `commitCanvas`+ * maps by id, so the active canvas is written into BOTH projects and the next save flushes it+ * into the other folder's project.json. That is silent cross-folder data loss on every autosave,+ * so the repair cannot wait for the user to notice — and it must be persisted, or every restart+ * re-inherits the same corrupt index.+ *+ * First holder keeps the id; the rest are re-keyed by `derivedProjectId`, which is DETERMINISTIC+ * in (id, folder) — a random id would rewrite the user's project.json (and every teammate's git+ * diff) on every boot, whereas this converges: the second load finds no collision at all.+ *+ * Loud on purpose (one line per repaired project, naming the folder): this edits files in the+ * user's own repo, and a silent repair of someone's data is worse than a noisy one.+ */+ private async repairDuplicateIds(built: LoadedEntry[], sideline: boolean): Promise<void> {+ const seen = new Set<string>()+ let repaired = false+ for (const b of built) {+ if (!seen.has(b.project.id)) {+ seen.add(b.project.id)+ continue+ }+ const old = b.project.id+ const seed = collisionSeed({+ cwd: b.entry.cwd,+ ssh: b.entry.ssh,+ name: b.project.name+ })+ const next = derivedProjectId(old, seed, (id) => seen.has(id) || built.some((o) => o.project.id === id))+ seen.add(next)+ repaired = true+ console.warn(+ `[workspace] two projects claimed the project id "${old}" — a git-shared ` ++ `.nodeterm/project.json copied into a second folder (worktree/checkout). Re-keyed ` ++ `${b.entry.cwd ?? b.entry.ssh?.remoteCwd ?? `inline canvas "${b.project.name}"`} to "${next}".`+ )+ b.entry.id = next+ b.project = { ...b.project, id: next }+ if (b.entry.project) b.entry.project = { ...b.entry.project, id: next }+ if (b.entry.cache) {+ b.entry.cache = { ...b.entry.cache, id: next }+ this.revs.set(next, b.entry.cache.rev)+ }+ if (!b.file || !b.entry.cwd) continue+ this.revs.set(next, b.file.rev)+ // Read-only loads (the relay blob a phone can trigger) repair in memory only — the caller+ // must never see a duplicate id, but a probe may not write to disk. Same rule as `sideline`.+ if (!sideline) continue+ // Bumped rev: the re-keyed file has genuinely diverged from the copy it was cloned from, and+ // must outrank it wherever the two meet again.+ const rekeyed: ProjectFileV1 = { ...b.file, id: next, rev: b.file.rev + 1 }+ const filePath = projectFilePath(b.entry.cwd)+ const content = serializeProjectFile(rekeyed)+ try {+ await writeAtomic(filePath, content)+ this.lastWritten.set(filePath, content)+ this.revs.set(next, rekeyed.rev)+ b.file = rekeyed+ } catch {+ // Read-only folder / unmounted disk: the in-memory repair still stands for this run, and+ // the next save (or the next load) retries it. Never fail a load over it.+ }+ }+ // The re-keyed ENTRIES are the half that makes the repair survive a restart — without this the+ // next boot reads the old index and repairs again (harmlessly, but forever).+ if (!repaired || !sideline) return+ try {+ await writeAtomic(this.indexPath, JSON.stringify(this.index))+ } catch { /* the next save writes it anyway */ }+ }+/*** The machine-local exec overlay for one ref'd entry — plus the ONE-TIME migration (see* `IndexEntryV3.execMigrated` / `hoistLegacyNodeExec`).@@ -479,9 +595,12 @@ export class WorkspaceStore {if (!e?.cwd) return nullconst read = await this.readProjectFile(e.cwd, false)if (!read) return null- this.revs.set(read.file.id, read.file.rev)+ // The watcher's re-read after a git checkout is exactly where a foreign id arrives; the project+ // must come back under OUR entry id or `replaceProject` (which matches by id) silently drops it.+ const file = this.entryKeyed(e, read.file)+ this.revs.set(file.id, file.rev)this.lastWritten.set(projectFilePath(e.cwd), read.raw)- return fileToProject(read.file, { cwd: e.cwd, closed: e.closed, localExec: e.localExec })+ return fileToProject(file, { cwd: e.cwd, closed: e.closed, localExec: e.localExec })}/** Maps a watched file path back to its project and re-reads it. */@@ -630,7 +749,9 @@ export class WorkspaceStore {const f = JSON.parse(raw) as ProjectFileV1// Node cwds are stored portable ("./sub"); resolve them the way `fileToProject` does, so// a caller sees the same absolute paths the desktop's renderer would have handed it.- out.push({ id: f.id, nodes: resolveNodes(f.nodes, e.cwd), bridges: f.bridges })+ // Keyed by the ENTRY id (see `entryKeyed`) — the map's consumers look projects up by the+ // id the renderer knows, which is never the git-shared file's.+ out.push({ id: e.id, nodes: resolveNodes(f.nodes, e.cwd), bridges: f.bridges })} catch {// Corrupt cached content: skip this entry, keep scanning the others.}@@ -702,7 +823,7 @@ export class WorkspaceStore {// appendProjectNode only returns a string it produced from a valid ProjectFileV1, so this parse// cannot realistically fail — but a throw here would turn a landed write into a `false`.try {- const parsed = JSON.parse(updated) as ProjectFileV1+ const parsed = this.entryKeyed(e, JSON.parse(updated) as ProjectFileV1)this.revs.set(parsed.id, parsed.rev)platform().broadcast(IPC.workspaceExternalChange,diff --git a/src/renderer/canvas/Canvas.tsx b/src/renderer/canvas/Canvas.tsxindex d96b8f880..535f3729b 100644--- a/src/renderer/canvas/Canvas.tsx+++ b/src/renderer/canvas/Canvas.tsx@@ -3346,9 +3346,16 @@ export function Canvas() {const cloneRepo = useCallback(() => setCloneDialogOpen(true), [])const onRepoCloned = useCallback(- (clonedPath: string, name: string) => {+ async (clonedPath: string, name: string) => {commitActiveToStore()- const project = useProjects.getState().addProject(name, clonedPath)+ // A cloned repo may SHIP its canvas: `.nodeterm/project.json` is a git-shared file (the+ // migration banner asks users to commit it). Minting a brand-new empty project for the folder+ // both ignored that canvas and pointed a fresh id at a file that already had one — the exact+ // id/file mismatch this fix is about. Same probe→adopt path as "Open folder…".+ const probed = await api.workspace.probeFolder(clonedPath)+ const project = probed+ ? useProjects.getState().adoptProject({ ...probed, closed: false })+ : useProjects.getState().addProject(name, clonedPath)useProjects.getState().setActive(project.id)// The welcome screen stays up behind the clone dialog; dismiss it now that a// project actually exists (no-op when the dialog was opened elsewhere).diff --git a/src/renderer/state/projects.ts b/src/renderer/state/projects.tsindex cdd26d2ec..0d6b9f0f7 100644--- a/src/renderer/state/projects.ts+++ b/src/renderer/state/projects.ts@@ -9,6 +9,7 @@ import type {Viewport,Workspace} from '@shared/types'+import { collisionSeed, derivedProjectId } from '@shared/project-id'import { applyCanvasMutation, createProject, reorderGroupWithinParent } from './workspace'interface ProjectsState {@@ -178,6 +179,31 @@ function repositionState(}}+/**+ * Defense in depth for the ONE invariant this store cannot survive without: no two projects share+ * an id. Every mutator here (`commitCanvas`, `deleteProject`, `closeProject`, `renameNode`, …)+ * either maps by id — writing one canvas into BOTH projects — or filters by id, hitting both. The+ * tab bar keys its children by id, which is how the bug announced itself: ~1500 React "two children+ * with the same key" warnings.+ *+ * The store in main repairs the persisted index and re-keys the file (see+ * `WorkspaceStore.repairDuplicateIds`); this is the renderer's own guard for anything that reaches+ * hydrate some other way (a relay `projects.list` blob, a downgraded/older host). It uses the SAME+ * derivation, so when both run they agree on the id rather than fighting over it.+ */+function withUniqueIds(projects: Project[]): Project[] {+ const seen = new Set<string>()+ return projects.map((p) => {+ if (!seen.has(p.id)) {+ seen.add(p.id)+ return p+ }+ const id = derivedProjectId(p.id, collisionSeed(p), (c) => seen.has(c))+ seen.add(id)+ return { ...p, id }+ })+}+/** Returns `projects` with one project's nodes transformed; other projects untouched. */function mapProjectNodes(projects: Project[],@@ -193,7 +219,7 @@ export const useProjects = create<ProjectsState>((set, get) => ({reloadNonce: 0,hydrate(ws) {- set({ projects: ws.projects, activeProjectId: ws.activeProjectId })+ set({ projects: withUniqueIds(ws.projects), activeProjectId: ws.activeProjectId })},requestReload() {@@ -250,8 +276,14 @@ export const useProjects = create<ProjectsState>((set, get) => ({const taken = get().projects.some((p) => p.id === project.id)// A copied folder carries the original's project id; derive a fresh one. Node ids are// deliberately kept (they are tmux session names — see the spec's accepted limitation).+ // Deterministic in (id, folder), not random: adopting the same folder twice must land on the+ // same id, so the store's own repair and this path never disagree about what a tab is called.const adopted = taken- ? { ...project, id: `${project.id}-${Math.random().toString(36).slice(2, 8)}` }+ ? {+ ...project,+ id: derivedProjectId(project.id, collisionSeed(project), (c) =>+ get().projects.some((p) => p.id === c))+ }: projectset((s) => ({ projects: [...s.projects, adopted], activeProjectId: adopted.id }))return adopteddiff --git a/src/renderer/state/workspace.node-ids.test.ts b/src/renderer/state/workspace.node-ids.test.tsnew file mode 100644index 000000000..d8ac35ec5--- /dev/null+++ b/src/renderer/state/workspace.node-ids.test.ts@@ -0,0 +1,139 @@+import { describe, it, expect, vi, beforeEach } from 'vitest'+import type { Project } from '@shared/types'++// The ids the canvas mints are tmux session names and persistence keys. `nextId` used a+// module-level `let idCounter = 0`, which restarted at zero on every renderer start AND on every+// HMR reload — `term-<ms36>-1` was minted over and over, and only millisecond resolution kept two+// nodes from co-attaching to one terminal. These tests pin the replacement.++/** Re-imports the module with a fresh module registry — a renderer restart / HMR reload. */+async function freshModule(): Promise<typeof import('./workspace')> {+ vi.resetModules()+ return import('./workspace')+}++const SAFE = /^[A-Za-z0-9._-]+$/++beforeEach(() => {+ vi.resetModules()+})++describe('minted node/project ids', () => {+ it('never repeats across a simulated module reload', async () => {+ // The clock is FROZEN, so the `Date.now()` segment cannot do the work: this pins the tail+ // itself. A module-level counter restarts at 0 on every reload and repeats immediately.+ const now = vi.spyOn(Date, 'now').mockReturnValue(1_770_000_000_000)+ try {+ const seen = new Set<string>()+ for (let reload = 0; reload < 20; reload++) {+ const { createProject } = await freshModule()+ for (let i = 0; i < 25; i++) {+ const id = createProject(i).id+ expect(seen.has(id)).toBe(false)+ seen.add(id)+ }+ }+ expect(seen.size).toBe(500)+ } finally {+ now.mockRestore()+ }+ })++ it('stays inside the safe charset (tmux session names) and keeps its prefix', async () => {+ const { createProject } = await freshModule()+ for (let i = 0; i < 50; i++) {+ const id = createProject(i).id+ expect(id).toMatch(SAFE)+ expect(id.startsWith('project-')).toBe(true)+ expect(id.length).toBeLessThan(40)+ }+ })++ it('does not repeat within one tick (bulk duplicate / "spawn a team")', async () => {+ const { createProject } = await freshModule()+ const ids = Array.from({ length: 2000 }, (_, i) => createProject(i).id)+ expect(new Set(ids).size).toBe(2000)+ })++ // The relay's `projects.registerNode` guard (core/project-node-append `SAFE_NODE_ID`, whose twin+ // lives in nodeterm-ios) refuses anything outside this shape — a phone-registered session would+ // silently never appear. Pinned here as a literal because the renderer bundle may not import core.+ it('node ids keep the shape the relay id guard accepts', async () => {+ const { createTerminalNode } = await freshModule()+ for (let i = 0; i < 20; i++) {+ expect(createTerminalNode(i).id).toMatch(/^term-[a-z0-9]+-[a-z0-9]{1,16}$/)+ }+ })+})++describe('duplicateNode', () => {+ it('mints a fresh id for every copy, even in one tick', async () => {+ const { duplicateNode } = await freshModule()+ const node = {+ id: 'term-abc-1', type: 'terminal', position: { x: 0, y: 0 },+ data: {}+ } as unknown as import('./workspace').CanvasNode+ const ids = Array.from({ length: 200 }, () => duplicateNode(node).id)+ expect(new Set(ids).size).toBe(200)+ expect(ids.every((id) => SAFE.test(id))).toBe(true)+ })+})++// The consequence the ids exist to prevent: `commitCanvas` maps by id, so two projects under one+// id both receive the ACTIVE canvas — and the next save flushes it into the other folder's+// project.json. Cross-folder data loss, on every autosave.+describe('commitCanvas can never write one canvas into two projects', () => {+ const project = (over: Partial<Project>): Project => ({+ id: 'project-dup', name: 'p', color: '#fff', viewport: { x: 0, y: 0, zoom: 1 },+ nodes: [], ...over+ })++ it('hydrate re-keys a duplicate, so a commit lands in exactly one project', async () => {+ const { useProjects } = await import('./projects')+ useProjects.getState().hydrate({+ version: 2,+ activeProjectId: 'project-dup',+ projects: [+ project({ cwd: '/root/nodeterm-ios', nodes: [{ id: 'term-a' } as never] }),+ project({ cwd: '/root/nodeterm-ios-keyux', nodes: [{ id: 'term-b' } as never] })+ ]+ })+ const ids = useProjects.getState().projects.map((p) => p.id)+ expect(new Set(ids).size).toBe(2)+ expect(ids[0]).toBe('project-dup') // first holder keeps it++ useProjects.getState().commitCanvas(ids[0], [{ id: 'term-new' } as never], { x: 1, y: 2, zoom: 3 })+ const [first, second] = useProjects.getState().projects+ expect(first.nodes.map((n) => n.id)).toEqual(['term-new'])+ // The OTHER folder's canvas is untouched — this is the data loss.+ expect(second.nodes.map((n) => n.id)).toEqual(['term-b'])+ expect(second.viewport).toEqual({ x: 0, y: 0, zoom: 1 })+ expect(second.cwd).toBe('/root/nodeterm-ios-keyux')+ })++ it('the re-key is deterministic — a re-hydrate of the same workspace gives the same ids', async () => {+ const { useProjects } = await import('./projects')+ const ws = {+ version: 2 as const,+ activeProjectId: 'project-dup',+ projects: [project({ cwd: '/a' }), project({ cwd: '/b' }), project({ cwd: '/c' })]+ }+ useProjects.getState().hydrate(ws)+ const first = useProjects.getState().projects.map((p) => p.id)+ useProjects.getState().hydrate(ws)+ expect(useProjects.getState().projects.map((p) => p.id)).toEqual(first)+ expect(new Set(first).size).toBe(3)+ })++ it('deleteProject removes exactly one of two once-colliding projects', async () => {+ const { useProjects } = await import('./projects')+ useProjects.getState().hydrate({+ version: 2,+ activeProjectId: 'project-dup',+ projects: [project({ cwd: '/a' }), project({ cwd: '/b' })]+ })+ const ids = useProjects.getState().projects.map((p) => p.id)+ useProjects.getState().deleteProject(ids[0])+ expect(useProjects.getState().projects.map((p) => p.id)).toEqual([ids[1]])+ })+})diff --git a/src/renderer/state/workspace.ts b/src/renderer/state/workspace.tsindex ff454223a..486d55761 100644--- a/src/renderer/state/workspace.ts+++ b/src/renderer/state/workspace.ts@@ -135,9 +135,31 @@ export function shellSingleQuote(s: string): string {return `'${s.replace(/'/g, `'\\''`)}'`}-let idCounter = 0+/**+ * 8 hex characters of CSPRNG — the unique tail of every node and project id.+ *+ * It replaces a module-level `let idCounter = 0`, which was a latent collision generator: the+ * counter restarted at 0 on every renderer start AND on every HMR reload, so `term-<ms36>-1` was+ * minted again and again and only `Date.now()` (millisecond resolution) kept the ids apart. A node+ * id IS the tmux session name and the persistence key, so a repeat means two nodes co-attached to+ * one terminal.+ *+ * Kept inside `[A-Za-z0-9._-]` and short, because these ids become tmux session names and are+ * charset-validated on several paths (tmux-naming, hook-server, codex-identity-proxy,+ * project-node-append). No `Math.random()`: bulk flows (duplicate, "spawn a team") mint many ids in+ * one tick, which is exactly where a weak generator repeats.+ */+function randomToken(): string {+ const c = globalThis.crypto as Crypto | undefined+ if (c?.getRandomValues) {+ return Array.from(c.getRandomValues(new Uint8Array(4)), (b) => b.toString(16).padStart(2, '0')).join('')+ }+ // Non-browser, non-Node-19 fallback (never taken in the app or in tests): still 8 chars.+ return Math.floor(Math.random() * 0x100000000).toString(16).padStart(8, '0')+}+function nextId(prefix: string): string {- return `${prefix}-${Date.now().toString(36)}-${++idCounter}`+ return `${prefix}-${Date.now().toString(36)}-${randomToken()}`}/** Stagger placement so new nodes don't overlap. */diff --git a/src/shared/project-id.test.ts b/src/shared/project-id.test.tsnew file mode 100644index 000000000..5777aa98a--- /dev/null+++ b/src/shared/project-id.test.ts@@ -0,0 +1,52 @@+import { describe, it, expect } from 'vitest'+import { collisionSeed, derivedProjectId, shortHash } from './project-id'++const never = (): boolean => false++describe('shortHash', () => {+ it('is deterministic and stays inside the safe id charset', () => {+ expect(shortHash('/home/enes/repo')).toBe(shortHash('/home/enes/repo'))+ for (const s of ['', '/a', '/home/mustafa/mustafa', 'ünïcødé/ようこそ', 'x'.repeat(500)]) {+ expect(shortHash(s)).toMatch(/^[a-z0-9]+$/)+ expect(shortHash(s).length).toBeLessThanOrEqual(7)+ }+ })++ it('separates the folders that actually collide in the field', () => {+ expect(shortHash('/root/nodeterm-ios')).not.toBe(shortHash('/root/nodeterm-ios-keyux'))+ expect(shortHash('/home/mustafa/mustafa')).not.toBe(shortHash('/home/projects/mustafa'))+ })+})++describe('derivedProjectId', () => {+ it('keeps the base id as a prefix and appends the seed hash', () => {+ const id = derivedProjectId('project-ms4zdpc0-1', '/root/nodeterm-ios', never)+ expect(id.startsWith('project-ms4zdpc0-1-')).toBe(true)+ expect(id).toMatch(/^[A-Za-z0-9._-]+$/)+ })++ it('CONVERGES: the same (id, seed) always derives the same id — the repair may not churn the file', () => {+ const a = derivedProjectId('p1', '/two', never)+ const b = derivedProjectId('p1', '/two', never)+ expect(a).toBe(b)+ })++ it('re-derives (still deterministically) when the derived id is itself taken', () => {+ const collide = derivedProjectId('p1', '/two', never)+ const salted = derivedProjectId('p1', '/two', (id) => id === collide)+ expect(salted).not.toBe(collide)+ expect(derivedProjectId('p1', '/two', (id) => id === collide)).toBe(salted)+ })++ it('gives two different folders two different ids', () => {+ expect(derivedProjectId('p1', '/a', never)).not.toBe(derivedProjectId('p1', '/b', never))+ })+})++describe('collisionSeed', () => {+ it('is the folder, then the server folder, then the name', () => {+ expect(collisionSeed({ cwd: '/a', ssh: { remoteCwd: '~/b' }, name: 'n' })).toBe('/a')+ expect(collisionSeed({ ssh: { remoteCwd: '~/b' }, name: 'n' })).toBe('~/b')+ expect(collisionSeed({ name: 'n' })).toBe('n')+ })+})diff --git a/src/shared/project-id.ts b/src/shared/project-id.tsnew file mode 100644index 000000000..2f9d448c3--- /dev/null+++ b/src/shared/project-id.ts@@ -0,0 +1,66 @@+/**+ * The ONE rule for keeping project ids unique.+ *+ * A project id is machine-local identity, but `<cwd>/.nodeterm/project.json` — which carries an+ * `id` field — is a GIT-SHARED document (the migration banner tells users to commit it so the+ * canvas travels with the repo). So `git worktree add`, a branch checkout, `reset --hard` or a+ * `stash pop` can re-materialise one committed id into a SECOND folder, and two tabs then answer+ * to one id. Everything downstream is keyed by that id — the canvas commit, tmux session names,+ * delete/close, ssh control paths, board-log + approval routing — so a collision is not a render+ * glitch, it is cross-folder data loss.+ *+ * Both halves of the fix need the same derivation, in two runtimes (main's store repairs the+ * on-disk index/files, the renderer's store defends its own array), so it lives in `shared` and+ * uses no crypto: identical input must give an identical id in every process, on every boot.+ */++/** 32-bit FNV-1a, base36 — short, deterministic, and inside the `[A-Za-z0-9._-]` charset that node+ * ids (tmux session names) and project ids are allowed to use. */+export function shortHash(input: string): string {+ let h = 0x811c9dc5+ for (let i = 0; i < input.length; i++) {+ h ^= input.charCodeAt(i)+ // FNV prime 16777619, in 32-bit arithmetic that survives JS doubles.+ h = Math.imul(h, 0x01000193) >>> 0+ }+ return h.toString(36)+}++/**+ * The replacement id for a project that LOST an id collision (the first holder keeps the id).+ *+ * Deterministic in `(baseId, seed)` — never random — because the repair is written to the user's+ * disk: a repeated load must converge on the id it already wrote instead of churning+ * `project.json` (and every teammate's git diff) on every boot. `seed` is the thing that actually+ * distinguishes the two projects: the folder for a local ref, the endpoint for an ssh one.+ *+ * `isTaken` closes the last gap — a derived id that itself collides (two folders hashing the+ * same, or a third copy) is re-derived with a salt, still deterministically.+ */+export function derivedProjectId(+ baseId: string,+ seed: string,+ isTaken: (id: string) => boolean+): string {+ let candidate = `${baseId}-${shortHash(seed)}`+ for (let salt = 1; isTaken(candidate) && salt < 1000; salt++) {+ candidate = `${baseId}-${shortHash(`${seed}#${salt}`)}`+ }+ return candidate+}++/**+ * What actually distinguishes two projects that ended up sharing an id: the folder, the server+ * folder, or — inline canvases have neither — the name.+ *+ * Every re-keying site derives from THIS one function (the store's load-time repair, the index+ * writer in `splitWorkspace`, the renderer's `hydrate` guard, `adoptProject`), so when two of them+ * see the same collision they land on the same id instead of fighting over it across a save.+ */+export function collisionSeed(p: {+ cwd?: string+ ssh?: { remoteCwd?: string }+ name: string+}): string {+ return p.cwd ?? p.ssh?.remoteCwd ?? p.name+}