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): the shared canvas file carries content, not machine identity
Claude Code02723887f30f
diff --git a/CLAUDE.md b/CLAUDE.mdindex 16f4540ef..019ce901b 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -135,7 +135,16 @@ Persistence has two layers:`core/workspace-watcher.ts` → silent reload, or a Reload/Keep-mine conflict bar when dirty.Unreadable refs render as greyed **unavailable** tabs (never dropped); corrupt project filesare set aside as `project.json.corrupt-<ts>`. "Open folder…" adopts an existing- `.nodeterm/project.json` (fresh project id on collision; node ids — tmux names — kept).+ `.nodeterm/project.json` — the probe MINTS the project id (node ids — tmux names — kept), and+ re-opening the folder is answered by the cwd lookup, not a second adoption.+ **The shared file carries content, not identity**: no project `id`, no `viewport`, no+ `defaultAccountId` — those are machine-local and ride the index entry (`IndexEntryV3`), beside+ `localApprovalId`/`localExec`. Two folders holding the same committed canvas (worktree, branch+ checkout) are two independent projects, and the committed file is byte-identical on every+ machine. The file still carries a machine-INDEPENDENT legacy `id` (`legacyFileId`, derived from+ the canvas name) for one release, because a pre-change build sidelines an id-less file to+ `.corrupt-<ts>` inside the user's repo; it is ignored on read. Residual: node ids are still+ shared, so two worktrees still attach the same tmux sessions.**SSH mirror safety** (the ".nodeterm reset itself" bug — 12 fresh project ids and 45 orphanedtmux sessions in one field report): remote writes are atomic (`cat > f.tmp && mv`, `sshWriteArgs`);a mirror is never blind-written before the entry has read-compared the server file oncediff --git a/src/core/workspace-files.test.ts b/src/core/workspace-files.test.tsindex 923094da6..2c1f6d1fb 100644--- a/src/core/workspace-files.test.ts+++ b/src/core/workspace-files.test.ts@@ -1,9 +1,10 @@import { describe, it, expect } from 'vitest'import type { CanvasNodeState, Project, Workspace } from '../shared/types'import {- toPortableNodes, resolveNodes, projectToFile, fileToProject,+ toPortableNodes, resolveNodes, projectToFile, fileToProject, framingViewport,sameProjectContent, splitWorkspace, serializeProjectFile} from './workspace-files'+import { legacyFileId } from '../shared/project-id'import type { ProjectFileV1 } from './workspace-files'const node = (over: Partial<CanvasNodeState> = {}): CanvasNodeState => ({@@ -46,8 +47,18 @@ describe('projectToFile / fileToProject round-trip', () => {expect(f.version).toBe(1); expect(f.rev).toBe(3)expect((f as any).cwd).toBeUndefined(); expect((f as any).closed).toBeUndefined()expect(f.nodes[0].cwd).toBe('./x')- const back = fileToProject(f, { cwd: '/new/root', closed: true })- expect(back).toMatchObject({ id: 'p1', cwd: '/new/root', closed: true, defaultAccountId: 'acct1', dinoHighScore: 7 })+ // Machine-local: identity, camera and account come from the index entry, never the file.+ expect(f.id).not.toBe('p1')+ expect(f.viewport).toEqual(framingViewport(f.nodes)) // content-derived, not this user's camera+ expect(f.defaultAccountId).toBeUndefined()+ const back = fileToProject(f, {+ id: 'p1', cwd: '/new/root', closed: true,+ viewport: { x: 5, y: 6, zoom: 2 }, defaultAccountId: 'acct1'+ })+ expect(back).toMatchObject({+ id: 'p1', cwd: '/new/root', closed: true, defaultAccountId: 'acct1', dinoHighScore: 7,+ viewport: { x: 5, y: 6, zoom: 2 }+ })expect(back.nodes[0]).toMatchObject({ cwd: '/new/root/x', agentId: 'claude', accountId: 'acct1' })expect(back.unavailable).toBeUndefined()})@@ -78,9 +89,12 @@ describe('splitWorkspace', () => {expect(index.activeProjectId).toBe('p1')expect(index.entries[0]).toMatchObject({ id: 'p1', name: 'foo', cwd: '/a/foo' })expect(index.entries[0].project).toBeUndefined()- expect(files.get('/a/foo')!.id).toBe('p1')+ // The id lives in the ENTRY; the file gets only the machine-independent legacy field.+ expect(files.get('/a/foo')!.id).not.toBe('p1')+ expect(files.get('/a/foo')!.id).toBe(legacyFileId('foo'))expect(index.entries[1].project!.id).toBe('p2')expect(index.entries[2].ssh!.remoteCwd).toBe('~/app')+ // …except the ssh mirror, whose id `reconcileSsh` still reads as a lineage marker.expect(index.entries[2].cache!.id).toBe('p3')expect(files.has('~/app')).toBe(false) // ssh files are not local writes})@@ -94,7 +108,7 @@ describe('splitWorkspace', () => {}const { index, files } = splitWorkspace(shared, () => 1, '2026-07-11T00:00:00.000Z')expect(files.size).toBe(1) // only the first claims the file- expect(files.get('/a/foo')!.id).toBe('a')+ expect(files.get('/a/foo')!.name).toBe('first')expect(index.entries[0]).toMatchObject({ id: 'a', cwd: '/a/foo' })expect(index.entries[0].project).toBeUndefined()// The second is kept verbatim inline — no file, nothing lost.@@ -119,8 +133,9 @@ describe('splitWorkspace', () => {expect(index.entries[0].id).toBe('dup') // first holder keeps itexpect(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)+ // Neither file names a project any more — only the folder they sit in does.+ expect(files.get('/a/foo')!.id).not.toBe('dup')+ expect(files.get('/a/bar')!.id).not.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'])})@@ -219,13 +234,13 @@ describe('permission mode persistence', () => {it('round-trips a project permission-mode override', () => {const file = projectToFile({ ...base, defaultPermissionMode: 'plan' }, 1, 'now')expect(file.defaultPermissionMode).toBe('plan')- expect(fileToProject(file, {}).defaultPermissionMode).toBe('plan')+ expect(fileToProject(file, { id: 'p1' }).defaultPermissionMode).toBe('plan')})it('omits the key entirely when there is no override', () => {const file = projectToFile(base, 1, 'now')expect('defaultPermissionMode' in file).toBe(false)- expect(fileToProject(file, {}).defaultPermissionMode).toBeUndefined()+ expect(fileToProject(file, { id: 'p1' }).defaultPermissionMode).toBeUndefined()})})@@ -246,14 +261,14 @@ describe('exec-enabling node fields never travel in the shared project file', ()it('fileToProject with no local overlay drops what the FILE claimed (adopted/cloned folder)', () => {const f = { ...projectToFile(project({ nodes: [] }), 1, 'now'), nodes: hostileNodes }- const p = fileToProject(f, { cwd: '/a/b' })+ const p = fileToProject(f, { id: 'p1', cwd: '/a/b' })expect(p.nodes[0].shell).toBeUndefined()expect(p.nodes[1].ssh?.extraArgs).toBeUndefined()})it("fileToProject restores only THIS machine's values (from the local index entry)", () => {const f = { ...projectToFile(project({ nodes: [] }), 1, 'now'), nodes: hostileNodes }- const p = fileToProject(f, { cwd: '/a/b', localExec: { n1: { shell: '/bin/zsh' } } })+ const p = fileToProject(f, { id: 'p1', cwd: '/a/b', localExec: { n1: { shell: '/bin/zsh' } } })expect(p.nodes[0].shell).toBe('/bin/zsh')expect(p.nodes[1].ssh?.extraArgs).toBeUndefined()})@@ -283,7 +298,7 @@ describe('exec-enabling node fields never travel in the shared project file', ()expect(file.nodes[0].shell).toBeUndefined()expect(file.nodes[1].ssh?.extraArgs).toBeUndefined()// and the round trip through the index restores them for the local user- const back = fileToProject(file, { cwd: '/a/b', localExec: index.entries[0].localExec })+ const back = fileToProject(file, { id: 'p1', cwd: '/a/b', localExec: index.entries[0].localExec })expect(back.nodes[0].shell).toBe('/bin/zsh')expect(back.nodes[1].ssh?.extraArgs).toBe('-o ProxyCommand=corp %h')})@@ -319,12 +334,12 @@ describe('kanban board persistence', () => {it('rides the project file round-trip', () => {const f = projectToFile(project({ kanban: board }), 1, '2026-07-18T00:00:00.000Z')expect(f.kanban).toEqual(board)- expect(fileToProject(f, {}).kanban).toEqual(board)+ expect(fileToProject(f, { id: 'p1' }).kanban).toEqual(board)})it('absent stays absent — no key is written (lazy default rule)', () => {const f = projectToFile(project(), 1, '2026-07-18T00:00:00.000Z')expect('kanban' in f).toBe(false)- expect('kanban' in fileToProject(f, {})).toBe(false)+ expect('kanban' in fileToProject(f, { id: 'p1' })).toBe(false)})it('board edits break content equality (rev bumps) and survive splitWorkspace (both shells + ssh cache)', () => {const a = projectToFile(project({ kanban: board }), 1, '2026-01-01T00:00:00.000Z')@@ -339,8 +354,87 @@ describe('kanban board persistence', () => {const evil1 = { ...f, kanban: {} } as unknown as ProjectFileV1const evil2 = { ...f, kanban: { columns: 42, assignments: [] } } as unknown as ProjectFileV1const v1shape = { ...f, kanban: { columns: [], cards: [] } } as unknown as ProjectFileV1- expect('kanban' in fileToProject(evil1, {})).toBe(false)- expect('kanban' in fileToProject(evil2, {})).toBe(false)- expect('kanban' in fileToProject(v1shape, {})).toBe(false)+ expect('kanban' in fileToProject(evil1, { id: 'p1' })).toBe(false)+ expect('kanban' in fileToProject(evil2, { id: 'p1' })).toBe(false)+ expect('kanban' in fileToProject(v1shape, { id: 'p1' })).toBe(false)+ })+})++describe('the shared file carries content, not machine identity', () => {+ const p = project({+ id: 'project-mridky20-11', cwd: '/a/foo', name: 'shared', defaultAccountId: 'acct-1',+ viewport: { x: -400, y: 90, zoom: 0.6 }, dinoHighScore: 12,+ kanban: { columns: [], assignments: [] }+ })++ it('drops the id, the camera and the account — keeps everything a team shares', () => {+ const f = projectToFile(p, 1, 'now')+ expect(f.id).not.toBe('project-mridky20-11')+ expect(f.viewport).not.toEqual(p.viewport) // not this user's camera; a frame for the nodes+ expect(f.viewport).toEqual(framingViewport(f.nodes))+ expect(f.defaultAccountId).toBeUndefined()+ // Content a team WANTS: two people opening this repo should see the same board, the same+ // canvas, under the same name and color.+ expect(f).toMatchObject({ name: 'shared', color: p.color, dinoHighScore: 12 })+ expect(f.kanban).toEqual({ columns: [], assignments: [] })+ })++ it('the legacy id is derived from the canvas name, so every machine writes the same bytes', () => {+ const mine = projectToFile(p, 1, 'now')+ const theirs = projectToFile({ ...p, id: 'project-other-9', cwd: '/elsewhere/foo' }, 1, 'now')+ expect(theirs.id).toBe(mine.id)+ expect(serializeProjectFile(theirs)).toBe(serializeProjectFile(mine))+ })++ it('fileToProject takes identity from the caller and ignores what the file claims', () => {+ const f = { ...projectToFile(p, 1, 'now'), id: 'project-someone-else' }+ expect(fileToProject(f, { id: 'ours', cwd: '/a/foo' }).id).toBe('ours')+ })++ it('a legacy file\'s camera/account are read once (the upgrade path), the entry then wins', () => {+ const legacy = {+ ...projectToFile(p, 1, 'now'),+ viewport: { x: 1, y: 2, zoom: 3 },+ defaultAccountId: 'acct-legacy'+ }+ expect(fileToProject(legacy, { id: 'ours' })).toMatchObject({+ viewport: { x: 1, y: 2, zoom: 3 }, defaultAccountId: 'acct-legacy'+ })+ expect(fileToProject(legacy, {+ id: 'ours', viewport: { x: 9, y: 9, zoom: 9 }, defaultAccountId: 'acct-ours'+ })).toMatchObject({ viewport: { x: 9, y: 9, zoom: 9 }, defaultAccountId: 'acct-ours' })+ })++ it('splitWorkspace keeps the camera + account in the machine-local index entry', () => {+ const { index } = splitWorkspace(+ { version: 2, activeProjectId: p.id, projects: [p] }, () => 1, 'now'+ )+ expect(index.entries[0]).toMatchObject({+ id: 'project-mridky20-11', cwd: '/a/foo',+ viewport: { x: -400, y: 90, zoom: 0.6 }, defaultAccountId: 'acct-1'+ })+ })++ it('an unavailable ref writes NO camera (a placeholder must not forget where the user was)', () => {+ const { index } = splitWorkspace(+ { version: 2, activeProjectId: p.id, projects: [{ ...p, unavailable: true, nodes: [] }] },+ () => 1, 'now'+ )+ expect(index.entries[0].viewport).toBeUndefined()+ })+})++describe('framingViewport', () => {+ it('puts the top-left node just inside the corner of an adopted canvas', () => {+ const vp = framingViewport([node({ position: { x: 4000, y: 2000 } })])+ expect(vp.zoom).toBe(1)+ expect(vp.x + 4000).toBe(80)+ expect(vp.y + 2000).toBe(80)+ })+ it('an empty canvas (and a canvas of only children) stays at the origin', () => {+ expect(framingViewport([])).toEqual({ x: 0, y: 0, zoom: 1 })+ // A child's position is relative to its frame, so it can't anchor the camera.+ expect(framingViewport([node({ parentId: 'group-1', position: { x: 10, y: 10 } })]))+ .toEqual({ x: 0, y: 0, zoom: 1 })})})diff --git a/src/core/workspace-files.ts b/src/core/workspace-files.tsindex ba1bf9cd4..0eb2d0039 100644--- a/src/core/workspace-files.ts+++ b/src/core/workspace-files.ts@@ -1,6 +1,6 @@import path from 'path'import type { AgentPermissionMode } from '../shared/agents/config'-import { collisionSeed, derivedProjectId } from '../shared/project-id'+import { collisionSeed, derivedProjectId, legacyFileId } from '../shared/project-id'import {applyLocalNodeExec,localNodeExec,@@ -12,22 +12,58 @@ import type { BridgeLink, CanvasNodeState, Project, ProjectKanban, Viewport, Worexport const PROJECT_DIR = '.nodeterm'export const PROJECT_FILE = 'project.json'-/** On-disk shape of <cwd>/.nodeterm/project.json. No `cwd` field — the containing- * folder IS the cwd (that's what makes the folder relocatable). Node cwds inside- * the root are stored relative ("./sub"). Session/account state is included by- * design: the file is a single shared document (see the spec). */+/**+ * On-disk shape of <cwd>/.nodeterm/project.json — a GIT-SHARED document (users are asked to+ * commit it so the canvas travels with the repo).+ *+ * It carries CONTENT ONLY. Nothing in here may be state two machines opening the same repo would+ * legitimately disagree about, because git copies this file verbatim: `git worktree add`, a branch+ * checkout, `reset --hard` or a `stash pop` re-materialise every field into a second folder. That+ * is how one machine's project `id` came to name two folders — two tabs answering to one id, the+ * active canvas written into both, then flushed into the other folder's file (field corruption,+ * 2026-08). Machine-local state lives in the machine-local index instead (`IndexEntryV3`).+ *+ * No `cwd` field — the containing folder IS the cwd (that's what makes the folder relocatable).+ * Node cwds inside the root are stored relative ("./sub").+ */export interface ProjectFileV1 {version: 1/** Monotonic save counter; picks a winner when an offline cache and the file diverge (SSH). */rev: numbersavedAt: string- id: string+ /**+ * LEGACY, and never identity. Written as a machine-INDEPENDENT value (`legacyFileId`) purely so+ * a build older than this one still accepts the file instead of sidelining it to `.corrupt-<ts>`+ * inside the user's repo; ignored on read — the index entry says who this project is. Optional+ * because a newer writer may already have dropped it, and because the SSH branch still puts its+ * entry id here as an opaque lineage marker (see `splitWorkspace` / `reconcileSsh`).+ */+ id?: stringname: stringcolor: string- viewport: Viewport+ /**+ * NOT a camera any more — a SUGGESTED one, derived from where the canvas's own nodes sit+ * (`framingViewport`).+ *+ * This user's actual camera is machine-local (a pan is not an edit two people share, yet it+ * dirtied the committed file on every gesture) and rides `IndexEntryV3.viewport`. What is+ * written here is a function of the content, so it is identical on every machine, and it is+ * still written at all because a pre-change build REQUIRES the field — without it that build+ * renders the project with `viewport.zoom` undefined and takes the canvas down.+ *+ * On read it is a fallback only: the index entry wins, and a pre-change file's real camera is+ * inherited once on the way into the index.+ */+ viewport?: Viewportnodes: CanvasNodeState[]bridges?: BridgeLink[]ropes?: BridgeLink[]+ /**+ * LEGACY (read-only), same rule as `viewport`: a managed Claude account id names a credential+ * dir under THIS machine's userData ({userData}/claude-accounts/<id>), so a teammate's copy of+ * the file pointed at an account that does not exist for them. It rides+ * `IndexEntryV3.defaultAccountId` now; still read once for a file this machine has not seen.+ */defaultAccountId?: stringdefaultPermissionMode?: AgentPermissionModedinoHighScore?: number@@ -39,12 +75,23 @@ export interface ProjectFileV1 {* unavailable ref still renders a labeled grey tab. `cache` (ssh only) is the last* ProjectFileV1 seen/written — used while the server is unreachable. */export interface IndexEntryV3 {+ /**+ * THE project id — this machine's, and the only authority for it. It is minted here (a new+ * project, or `probeFolder`'s adoption of a folder) and never read back out of the shared+ * project file, which is what makes two copies of one canvas two independent projects.+ */id: string/** Stable machine-local trust identity. Never copied into the shared project file. */localApprovalId?: stringname: stringcolor: stringclosed?: boolean+ /** MACHINE-LOCAL camera for a ref'd project (local folder or ssh). Where this user is looking is+ * not something a repo shares — the file's copy churned the git diff on every pan. */+ viewport?: Viewport+ /** MACHINE-LOCAL default managed Claude account for a ref'd project: the id names a credential+ * dir in THIS machine's userData, so it is meaningless in anyone else's checkout. */+ defaultAccountId?: stringcwd?: stringssh?: Project['ssh']cache?: ProjectFileV1@@ -97,7 +144,28 @@ export function resolveNodes(nodes: CanvasNodeState[], root: string): CanvasNode})}-export function projectToFile(p: Project, rev: number, savedAt: string): ProjectFileV1 {+/**+ * The project as it is written to the SHARED file: content only.+ *+ * Dropped on the way out, because a second machine opening the same repo would legitimately+ * disagree about them: the project `id` (identity — see `IndexEntryV3.id`), the `viewport` (this+ * user's camera) and `defaultAccountId` (a credential dir under this userData). Kept, because a+ * team genuinely shares them: name, color, nodes, bridges/ropes, the kanban board, the permission+ * default, the dino record.+ *+ * The two fields a pre-change build cannot do without are still emitted, as machine-INDEPENDENT+ * stand-ins: `id` (`legacyFileId`, derived from the name — it refuses a file without one) and+ * `viewport` (`framingViewport`, derived from the nodes — it dereferences the field unguarded).+ * Both are functions of content, so every machine writes the same bytes. Override `id` only where+ * the file is NOT a git-copied artifact and something still reads it as a lineage marker (the ssh+ * mirror; see `splitWorkspace`).+ */+export function projectToFile(+ p: Project,+ rev: number,+ savedAt: string,+ id: string = legacyFileId(p.name)+): ProjectFileV1 {// The project file is a SHARED document (git, or the remote host). Exec-enabling node fields// (`shell`, `ssh.extraArgs`) never leave this machine in it — they ride the machine-local index// entry instead (`localNodeExec` / `IndexEntryV3.localExec`). See @shared/node-exec.@@ -106,14 +174,13 @@ export function projectToFile(p: Project, rev: number, savedAt: string): Projectversion: 1,rev,savedAt,- id: p.id,+ id,name: p.name,color: p.color,- viewport: p.viewport,+ viewport: framingViewport(nodes),nodes,...(p.bridges ? { bridges: p.bridges } : {}),...(p.ropes ? { ropes: p.ropes } : {}),- ...(p.defaultAccountId ? { defaultAccountId: p.defaultAccountId } : {}),...(p.defaultPermissionMode ? { defaultPermissionMode: p.defaultPermissionMode } : {}),...(p.dinoHighScore ? { dinoHighScore: p.dinoHighScore } : {}),...(p.kanban ? { kanban: p.kanban } : {})@@ -132,29 +199,45 @@ export function validKanban(k: unknown): k is ProjectKanban {)}+/**+ * The shared file plus this machine's own half of the project.+ *+ * `base.id` is REQUIRED and never defaulted from the file: identity comes from the index entry+ * (or, for a folder that has none yet, from `probeFolder` minting one). Making it a parameter is+ * the structural version of that rule — there is no code path left that can accidentally adopt a+ * git-shared id.+ */export function fileToProject(f: ProjectFileV1,base: {+ /** This machine's id for the project (index entry, or freshly minted on adoption). */+ id: stringcwd?: stringssh?: Project['ssh']closed?: boolean+ /** This machine's camera. Falls back to the file's legacy one (a pre-change file, or a+ * teammate's) and then to a frame that puts the canvas on screen. */+ viewport?: Viewport+ /** This machine's default managed account; falls back to the file's legacy value. */+ defaultAccountId?: string/** 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`. */localExec?: LocalNodeExecMap}): Project {+ const defaultAccountId = base.defaultAccountId ?? f.defaultAccountIdreturn {- id: f.id,+ id: base.id,name: f.name,color: f.color,- viewport: f.viewport,+ viewport: base.viewport ?? f.viewport ?? framingViewport(f.nodes),// applyLocalNodeExec DROPS whatever the file carried in the exec fields (it is not ours) and// re-attaches only what this machine typed. See @shared/node-exec.nodes: applyLocalNodeExec(base.cwd ? resolveNodes(f.nodes, base.cwd) : f.nodes, base.localExec),...(f.bridges ? { bridges: f.bridges } : {}),...(f.ropes ? { ropes: f.ropes } : {}),- ...(f.defaultAccountId ? { defaultAccountId: f.defaultAccountId } : {}),+ ...(defaultAccountId ? { defaultAccountId } : {}),...(f.defaultPermissionMode ? { defaultPermissionMode: f.defaultPermissionMode } : {}),...(f.dinoHighScore ? { dinoHighScore: f.dinoHighScore } : {}),...(validKanban(f.kanban) ? { kanban: f.kanban } : {}),@@ -164,7 +247,32 @@ export function fileToProject(}}-/** Content equality ignoring the bookkeeping fields — decides whether a save must bump rev + rewrite. */+/**+ * The camera for a canvas nobody on this machine has ever framed (an adopted folder, a teammate's+ * committed canvas): zoom 1, panned so the top-left node sits just inside the corner.+ *+ * Without it a shared canvas whose nodes live at x=4000 opened onto empty space — the file no+ * longer carries the author's camera, so the default {0,0,1} would have been a blank screen and+ * "commit it to share the canvas" would have been a lie.+ */+export function framingViewport(nodes: CanvasNodeState[]): Viewport {+ const rooted = nodes.filter((n) => !n.parentId)+ if (!rooted.length) return { x: 0, y: 0, zoom: 1 }+ const minX = Math.min(...rooted.map((n) => n.position.x))+ const minY = Math.min(...rooted.map((n) => n.position.y))+ return { x: 80 - minX, y: 80 - minY, zoom: 1 }+}++/**+ * Content equality ignoring the bookkeeping fields — decides whether a save must bump rev ++ * rewrite.+ *+ * The legacy `id` (and a pre-change file's `viewport` / `defaultAccountId`) IS compared, because a+ * file still carrying a machine's project id must be rewritten exactly once — that is the+ * migration that scrubs the identity out of the repo. Both sides agree from then on+ * (`legacyFileId` is derived from the name, so it is the same on every machine), which is what+ * keeps the answer "unchanged" on every later save.+ */export function sameProjectContent(a: ProjectFileV1, b: ProjectFileV1): boolean {const strip = ({ rev: _r, savedAt: _s, ...rest }: ProjectFileV1) => restreturn JSON.stringify(strip(a)) === JSON.stringify(strip(b))@@ -197,6 +305,16 @@ export function splitWorkspace(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 } : {}) }+ // The machine-local half of a REF'd project (a folder or an ssh endpoint), which used to ride+ // the shared file: this user's camera and this machine's default managed account. Deliberately+ // NOT added to the `unavailable` branch below — a placeholder's viewport is the {0,0,1} of an+ // empty stand-in, and writing it would forget where the user actually was; `WorkspaceStore.save`+ // restores both from the previous entry instead, exactly as it does for `cache`/`localExec`.+ // Inline entries need none of this: they store the whole Project verbatim.+ const localState = {+ ...(p.viewport ? { viewport: p.viewport } : {}),+ ...(p.defaultAccountId ? { defaultAccountId: p.defaultAccountId } : {})+ }if (p.unavailable) {// Placeholder (folder missing / server unreachable at load): its nodes:[] is not real// data. Emit a header-only ref preserving the ref shape — NEVER a file and NEVER an ssh@@ -216,13 +334,19 @@ export function splitWorkspace(if (p.ssh) {entries.push({...header,+ ...localState,...localRef,ssh: p.ssh,- cache: projectToFile(p, revOf(p.id), savedAt)+ // The ssh mirror keeps the ENTRY id in its `id` field. That file is not a git-copied+ // artifact — it is one folder on one host — and `reconcileSsh` reads the id as the marker+ // that tells a DIFFERENT lineage (another machine's project, a re-added folder) from our+ // own, which is what stops an empty newborn canvas from clobbering a populated server+ // file. It is no longer identity even there: `fileToProject` is handed `e.id` regardless.+ cache: projectToFile(p, revOf(p.id), savedAt, p.id)})} else if (p.cwd && !files.has(p.cwd)) {files.set(p.cwd, projectToFile(p, revOf(p.id), savedAt))- entries.push({ ...header, ...localRef, cwd: p.cwd })+ entries.push({ ...header, ...localState, ...localRef, cwd: p.cwd })} else if (p.cwd) {// Another project already claimed this cwd (two tabs on one folder). Keying `files` by cwd// would collapse them last-wins, and reload would resurrect BOTH entries from the one filediff --git a/src/core/workspace-store.test.ts b/src/core/workspace-store.test.tsindex a00a35c9a..76ddb775c 100644--- a/src/core/workspace-store.test.ts+++ b/src/core/workspace-store.test.ts@@ -56,7 +56,8 @@ describe('save → load round trip (v3)', () => {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 })+ expect(file).toMatchObject({ version: 1, rev: 1, name: 'foo' })+ expect(file.id).not.toBe('p1') // the file names no project — the index doesconst 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)@@ -91,7 +92,7 @@ describe('v2 → v3 migration', () => {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((await fs.readFile(path.join(projRoot, '.nodeterm/project.json'), 'utf-8'))).toContain('"term-1"')expect(fake.sent.some((s) => s.channel === 'workspace:migrated')).toBe(true)})@@ -366,7 +367,10 @@ describe('probeFolder', () => {const store = new WorkspaceStore()await store.save(ws([project({ cwd: projRoot })]))const probed = await store.probeFolder(projRoot)- expect(probed).toMatchObject({ id: 'p1', cwd: projRoot })+ // A probe ADOPTS a folder, so it mints an id — the file has none to hand out.+ expect(probed).toMatchObject({ name: 'foo', cwd: projRoot })+ expect(probed!.id).not.toBe('p1')+ expect(probed!.nodes.map((n) => n.id)).toEqual(['term-1'])expect(await store.probeFolder(path.join(projRoot, 'nope'))).toBeNull()})@@ -1130,18 +1134,15 @@ describe('a git-shared project.json must not give two folders one project 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 () => {+ it('REPAIRS the corrupt store in the INDEX, and touches neither folder\'s file', async () => {await seedCollision()+ const before = await fs.readFile(path.join(otherRoot, '.nodeterm/project.json'), 'utf-8')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')+ // The id is a machine-local mistake; the files hold content, and content did not change.+ expect(await fs.readFile(path.join(otherRoot, '.nodeterm/project.json'), 'utf-8')).toBe(before)+ expect(loaded.projects[1].nodes.map((n) => n.id)).toEqual(['term-b'])const index = await readIndex()expect(index.entries.map((e: { id: string }) => e.id)).toEqual(['project-ms4zdpc0-1', newId])@@ -1213,10 +1214,13 @@ describe('a git-shared project.json must not give two folders one project id', (// 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.+ // …and the next save scrubs the foreign id instead of replacing it with OURS: what lands is+ // the machine-independent legacy field, so the committed file stops naming anybody's project.await next.save(loaded)- expect(JSON.parse(await fs.readFile(path.join(projRoot, '.nodeterm/project.json'), 'utf-8')))- .toMatchObject({ id: 'mine', name: 'renamed-upstream' })+ const written = JSON.parse(await fs.readFile(path.join(projRoot, '.nodeterm/project.json'), 'utf-8'))+ expect(written.name).toBe('renamed-upstream')+ expect(written.id).not.toBe('theirs')+ expect(written.id).not.toBe('mine')})it('readLocalRef (the watcher\'s re-read after a checkout) comes back under the ENTRY id too', async () => {@@ -1291,7 +1295,8 @@ describe('a git-shared project.json must not give two folders one project id', (const fileB = JSON.parse(await fs.readFile(path.join(otherRoot, '.nodeterm/project.json'), 'utf-8'))expect(fileA.nodes.map((n: { id: string }) => n.id)).toEqual(['term-a', 'term-new'])expect(fileB.nodes.map((n: { id: string }) => n.id)).toEqual(['term-a'])- expect(fileA.id).not.toBe(fileB.id)+ // The two files are told apart by their CONTENT and their folder — never by an id.+ expect(fileA.id).toBe(fileB.id)})// The repair writes each project file first and the index last, so a crash (or a kill, or a power@@ -1326,42 +1331,36 @@ describe('a git-shared project.json must not give two folders one project id', (// Whichever write landed last, the file is intact JSON keyed to the entry that owns it.const index = await readIndex()const file = JSON.parse(await fs.readFile(path.join(otherRoot, '.nodeterm/project.json'), 'utf-8'))- expect(file.id).toBe(index.entries[1].id)expect(file.nodes.map((n: { id: string }) => n.id)).toEqual(['term-b'])})// A read-only folder (EROFS, a mounted share, a permissions mistake) must not fail the load or// lose the repair — the in-memory ids are still unique and the ENTRY re-key still persists, so// the file is simply re-keyed by a later save instead.- it('a project.json write failure still yields unique ids, and the entry re-key persists', async () => {+ it('a READ-ONLY repo still repairs — the fix lives entirely in userData', async () => {+ // The repair used to need a write inside the user's repo, so a read-only checkout (or a+ // permissions problem) left it half-done. It is now an index edit and nothing else.await seedCollision()const loserFile = path.join(otherRoot, '.nodeterm/project.json')- // Block only the loser's file write; every other rename (the index, the winner) goes through.+ const before = await fs.readFile(loserFile, 'utf-8')const rename = vi.spyOn(fs, 'rename').mockImplementation(async (from, to) => {- if (String(to) === loserFile) {+ if (String(to).startsWith(otherRoot)) {throw Object.assign(new Error('EROFS: read-only file system'), { code: 'EROFS' })}await fs.copyFile(String(from), String(to))await fs.rm(String(from), { force: true })})-const loaded = await new WorkspaceStore().load()const ids = loaded.projects.map((p) => p.id)expect(new Set(ids).size).toBe(2)expect(loaded.projects[1].nodes.map((n) => n.id)).toEqual(['term-b'])- expect(JSON.parse(await fs.readFile(loserFile, 'utf-8')).id).toBe('project-ms4zdpc0-1') // unwrittenrename.mockRestore()- // The index DID record the new identity, so the next load has no collision at all — and the- // file, which still disagrees with its entry, is re-keyed by the next save.expect((await readIndex()).entries.map((e: { id: string }) => e.id)).toEqual(ids)+ expect(await fs.readFile(loserFile, 'utf-8')).toBe(before)const next = new WorkspaceStore()const again = await next.load()- expect(again.projects.map((p) => p.id)).toEqual(ids)- await next.save(again)- const healed = JSON.parse(await fs.readFile(loserFile, 'utf-8'))- expect(healed.id).toBe(ids[1])- expect(healed.nodes.map((n: { id: string }) => n.id)).toEqual(['term-b'])+ expect(again.projects.map((p) => p.id)).toEqual(ids) // no second repair, no churn})it('a THREE-way collision splits into three ids, each keyed to its own folder', async () => {@@ -1387,9 +1386,13 @@ describe('a git-shared project.json must not give two folders one project id', (expect(loaded.projects.map((p) => p.cwd)).toEqual([projRoot, otherRoot, thirdRoot])expect(loaded.projects.map((p) => p.nodes.map((n) => n.id))).toEqual([['term-a'], ['term-b'], ['term-c']])+ // Each folder keeps its own canvas, and the repair rewrote none of them (it is an index+ // edit now — the pre-change `id` these fixtures still carry is inert).for (const [i, root] of [projRoot, otherRoot, thirdRoot].entries()) {- expect(JSON.parse(await fs.readFile(path.join(root, '.nodeterm/project.json'), 'utf-8')).id)- .toBe(ids[i])+ const file = JSON.parse(await fs.readFile(path.join(root, '.nodeterm/project.json'), 'utf-8'))+ expect(file.id).toBe('project-ms4zdpc0-1')+ expect(file.nodes.map((n: { id: string }) => n.id))+ .toEqual(loaded.projects[i].nodes.map((n) => n.id))}// Idempotent at three, too.expect((await new WorkspaceStore().load()).projects.map((p) => p.id)).toEqual(ids)@@ -1408,3 +1411,220 @@ describe('a git-shared project.json must not give two folders one project id', (expect(loaded.projects.map((p) => p.id).sort()).toEqual(['a', 'b'])})})++// The completion of the fix above: #192 made a shared id SURVIVABLE (the index entry became the+// authority, and a collision was repaired). This is the cause itself — a git-shared document may+// not carry machine identity at all, so `git worktree add` / a checkout has nothing to copy.+describe('the shared project file carries content, not machine identity', () => {+ 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 readFile = async (root: string) =>+ JSON.parse(await fs.readFile(path.join(root, '.nodeterm/project.json'), 'utf-8'))++ it('a saved project.json carries none of it: not the project id, not the camera, not the account', async () => {+ const store = new WorkspaceStore()+ await store.save(ws([project({+ id: 'project-ms4zdpc0-1',+ cwd: projRoot,+ viewport: { x: -1200, y: 340, zoom: 0.75 },+ defaultAccountId: 'acct-9f3c'+ })]))+ const raw = await fs.readFile(path.join(projRoot, '.nodeterm/project.json'), 'utf-8')+ expect(raw).not.toContain('project-ms4zdpc0-1') // this machine's project id+ expect(raw).not.toContain('acct-9f3c') // a config dir under THIS userData+ // The `viewport` that survives is derived from the canvas, not from where THIS user looked:+ // it frames the nodes, identically on every machine (a pre-change build requires the field).+ expect(JSON.parse(raw).viewport).toEqual({ x: 80, y: 80, zoom: 1 })+ // …and the machine-local half is remembered in the machine-local index.+ const index = JSON.parse(await fs.readFile(path.join(userData, 'workspace.json'), 'utf-8'))+ expect(index.entries[0]).toMatchObject({+ id: 'project-ms4zdpc0-1',+ cwd: projRoot,+ viewport: { x: -1200, y: 340, zoom: 0.75 },+ defaultAccountId: 'acct-9f3c'+ })+ // The canvas itself is still there — this is a file worth committing.+ expect(JSON.parse(raw).nodes.map((n: { id: string }) => n.id)).toEqual(['term-1'])+ })++ it('two machines writing the SAME canvas produce byte-identical files (nothing to churn in git)', async () => {+ // Only Date is faked (the store stamps `savedAt` with it); the fs promises below still resolve.+ vi.useFakeTimers({ toFake: ['Date'] })+ vi.setSystemTime(new Date('2026-08-14T00:00:00.000Z'))+ const mine = new WorkspaceStore()+ await mine.save(ws([project({+ id: 'project-mine-1', cwd: projRoot,+ viewport: { x: 10, y: 20, zoom: 2 }, defaultAccountId: 'acct-mine'+ })]))+ const theirs = new WorkspaceStore()+ await theirs.save(ws([project({+ id: 'project-theirs-7', cwd: otherRoot,+ viewport: { x: -900, y: 5, zoom: 0.5 }, defaultAccountId: 'acct-theirs'+ })]))+ expect(await fs.readFile(path.join(otherRoot, '.nodeterm/project.json'), 'utf-8'))+ .toBe(await fs.readFile(path.join(projRoot, '.nodeterm/project.json'), 'utf-8'))+ vi.useRealTimers()+ })++ it('load → save → load leaves the committed file byte-identical (no churn per boot)', async () => {+ const store = new WorkspaceStore()+ await store.save(ws([project({ id: 'p1', cwd: projRoot })]))+ const written = await fs.readFile(path.join(projRoot, '.nodeterm/project.json'), 'utf-8')+ const next = new WorkspaceStore()+ const loaded = await next.load()+ await next.save(loaded)+ expect(await fs.readFile(path.join(projRoot, '.nodeterm/project.json'), 'utf-8')).toBe(written)+ const third = new WorkspaceStore()+ await third.save(await third.load())+ expect(await fs.readFile(path.join(projRoot, '.nodeterm/project.json'), 'utf-8')).toBe(written)+ })++ it('THE WORKTREE CASE: two byte-identical files open as two projects, each keeping its own canvas', async () => {+ // What `git worktree add` actually produces: the same committed bytes in two folders. With no+ // id in them, nothing even suggests they are one project — only the index says who is who.+ const store = new WorkspaceStore()+ await store.save(ws([project({ id: 'a', name: 'repo', cwd: projRoot })]))+ const bytes = await fs.readFile(path.join(projRoot, '.nodeterm/project.json'), 'utf-8')+ await fs.mkdir(path.join(otherRoot, '.nodeterm'), { recursive: true })+ await fs.writeFile(path.join(otherRoot, '.nodeterm/project.json'), bytes)+ await fs.writeFile(path.join(userData, 'workspace.json'), JSON.stringify({+ version: 3,+ activeProjectId: 'a',+ entries: [+ { id: 'a', name: 'repo', color: '#7aa2f7', cwd: projRoot },+ { id: 'b', name: 'repo (worktree)', color: '#7aa2f7', cwd: otherRoot }+ ]+ }))+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})+ const next = new WorkspaceStore()+ const loaded = await next.load()+ expect(loaded.projects.map((p) => p.id)).toEqual(['a', 'b']) // no collision, no repair+ expect(warn).not.toHaveBeenCalled()+ warn.mockRestore()+ // Each canvas stays in its own folder across a save.+ await next.save(ws([+ { ...loaded.projects[0], nodes: [] },+ loaded.projects[1]+ ], 'a'))+ expect((await readFile(projRoot)).nodes).toEqual([])+ expect((await readFile(otherRoot)).nodes.map((n: { id: string }) => n.id)).toEqual(['term-1'])+ })++ it('a file written by an OLD build is read fine — its id is IGNORED, never adopted', async () => {+ await fs.mkdir(path.join(projRoot, '.nodeterm'), { recursive: true })+ await fs.writeFile(path.join(projRoot, '.nodeterm/project.json'), JSON.stringify({+ version: 1, rev: 4, savedAt: 'then', id: 'project-someone-else-3', name: 'shared',+ color: '#7aa2f7', viewport: { x: 7, y: 8, zoom: 3 },+ nodes: [{ id: 'term-a', kind: 'terminal', position: { x: 0, y: 0 },+ size: { width: 1, height: 1 }, title: 'a', color: '#fff', group: null }]+ }, null, 2))+ await fs.writeFile(path.join(userData, 'workspace.json'), JSON.stringify({+ version: 3, activeProjectId: 'mine',+ entries: [{ id: 'mine', name: 'shared', color: '#7aa2f7', cwd: projRoot }]+ }))+ const store = new WorkspaceStore()+ const loaded = await store.load()+ expect(loaded.projects[0]).toMatchObject({ id: 'mine', name: 'shared', cwd: projRoot })+ expect(loaded.projects[0].nodes.map((n) => n.id)).toEqual(['term-a'])+ // The old file's camera is the only thing we DO take from it: as this machine's starting+ // viewport, once, on the way into the index.+ expect(loaded.projects[0].viewport).toEqual({ x: 7, y: 8, zoom: 3 })+ await store.save(loaded)+ expect((await readFile(projRoot)).id).not.toBe('project-someone-else-3')+ expect((await readFile(projRoot)).id).not.toBe('mine')+ expect((await readFile(projRoot)).viewport).toEqual({ x: 80, y: 80, zoom: 1 }) // not {7,8,3}+ const index = JSON.parse(await fs.readFile(path.join(userData, 'workspace.json'), 'utf-8'))+ expect(index.entries[0].viewport).toEqual({ x: 7, y: 8, zoom: 3 })+ })++ it('still carries an `id` an OLD build can read — machine-independent, so it never churns', async () => {+ // Compatibility, one release: a build that predates this change REFUSES a project.json with no+ // `id` and sidelines it to `.corrupt-<ts>` — inside the user's repo. So the field stays, derived+ // from the canvas's own name, identical on every machine, and ignored by this build.+ const store = new WorkspaceStore()+ await store.save(ws([project({ id: 'project-mine-1', name: 'shared', cwd: projRoot })]))+ const file = await readFile(projRoot)+ expect(file.version).toBe(1)+ expect(typeof file.id).toBe('string')+ expect(file.id).not.toBe('project-mine-1')+ // …and the other field that build dereferences unguarded.+ expect(file.viewport).toMatchObject({ zoom: 1 })+ })++ it('adoption (a folder with no index entry) mints a fresh id — the file no longer names one', async () => {+ await fs.mkdir(path.join(projRoot, '.nodeterm'), { recursive: true })+ await fs.writeFile(path.join(projRoot, '.nodeterm/project.json'), JSON.stringify({+ version: 1, rev: 2, savedAt: 'then', id: 'project-theirs-9', name: 'cloned',+ color: '#7aa2f7',+ nodes: [{ id: 'term-a', kind: 'terminal', position: { x: 400, y: 300 },+ size: { width: 1, height: 1 }, title: 'a', color: '#fff', group: null }]+ }, null, 2))+ const store = new WorkspaceStore()+ const probed = await store.probeFolder(projRoot)+ expect(probed).toBeTruthy()+ expect(probed!.id).not.toBe('project-theirs-9')+ expect(probed!.id).toMatch(/^project-[a-z0-9-]+$/)+ expect(probed!.cwd).toBe(projRoot)+ expect(probed!.nodes.map((n) => n.id)).toEqual(['term-a'])+ // A second probe of the same folder is a different candidate id — which is exactly why the+ // caller must key by cwd (it does; see projects.openFolderProject) and never probe twice.+ const again = await store.probeFolder(projRoot)+ expect(again!.id).not.toBe(probed!.id)+ // The minted id is what the index remembers, and a reload comes back under it.+ await store.save(ws([{ ...probed!, closed: false }]))+ const index = JSON.parse(await fs.readFile(path.join(userData, 'workspace.json'), 'utf-8'))+ expect(index.entries.map((e: { id: string }) => e.id)).toEqual([probed!.id])+ const reloaded = await new WorkspaceStore().load()+ expect(reloaded.projects.map((p) => p.id)).toEqual([probed!.id])+ expect(reloaded.projects[0].nodes.map((n) => n.id)).toEqual(['term-a'])+ })++ it('an adopted canvas with no camera is framed onto its nodes, not left staring at the origin', async () => {+ await fs.mkdir(path.join(projRoot, '.nodeterm'), { recursive: true })+ await fs.writeFile(path.join(projRoot, '.nodeterm/project.json'), JSON.stringify({+ version: 1, rev: 2, savedAt: 'then', name: 'cloned', color: '#7aa2f7',+ nodes: [{ id: 'term-a', kind: 'terminal', position: { x: 4000, y: 2000 },+ size: { width: 1, height: 1 }, title: 'a', color: '#fff', group: null }]+ }, null, 2))+ const probed = await new WorkspaceStore().probeFolder(projRoot)+ expect(probed!.viewport.zoom).toBe(1)+ // The node lands on screen instead of 4000px off it.+ expect(probed!.viewport.x + 4000).toBeGreaterThan(0)+ expect(probed!.viewport.x + 4000).toBeLessThan(400)+ expect(probed!.viewport.y + 2000).toBeGreaterThan(0)+ expect(probed!.viewport.y + 2000).toBeLessThan(400)+ })++ it('a duplicate-id repair no longer writes to the user\'s repo at all (the index owns the id)', async () => {+ // A store corrupted BEFORE this fix: both entries under one id. The repair still runs — but it+ // has nothing to fix in the files, because they no longer claim an identity.+ await fs.mkdir(path.join(projRoot, '.nodeterm'), { recursive: true })+ await fs.mkdir(path.join(otherRoot, '.nodeterm'), { recursive: true })+ const bytes = JSON.stringify({+ version: 1, rev: 3, savedAt: 'then', id: 'project-legacy', name: 'one', color: '#7aa2f7',+ nodes: [{ id: 'term-a', kind: 'terminal', position: { x: 0, y: 0 },+ size: { width: 1, height: 1 }, title: 'a', color: '#fff', group: null }]+ }, null, 2)+ await fs.writeFile(path.join(projRoot, '.nodeterm/project.json'), bytes)+ await fs.writeFile(path.join(otherRoot, '.nodeterm/project.json'), bytes)+ await fs.writeFile(path.join(userData, 'workspace.json'), JSON.stringify({+ version: 3, activeProjectId: 'dup',+ entries: [+ { id: 'dup', name: 'one', color: '#7aa2f7', cwd: projRoot },+ { id: 'dup', name: 'two', color: '#7aa2f7', cwd: otherRoot }+ ]+ }))+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})+ const loaded = await new WorkspaceStore().load()+ expect(new Set(loaded.projects.map((p) => p.id)).size).toBe(2)+ warn.mockRestore()+ expect(await fs.readFile(path.join(projRoot, '.nodeterm/project.json'), 'utf-8')).toBe(bytes)+ expect(await fs.readFile(path.join(otherRoot, '.nodeterm/project.json'), 'utf-8')).toBe(bytes)+ })+})diff --git a/src/core/workspace-store.ts b/src/core/workspace-store.tsindex c9dcbf0f9..688c99a43 100644--- a/src/core/workspace-store.ts+++ b/src/core/workspace-store.ts@@ -13,7 +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 { collisionSeed, derivedProjectId, freshProjectId } 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@@ -220,15 +220,21 @@ export class WorkspaceStore {if (sideline) await sweepStaleTmp(projectFilePath(e.cwd))const read = await this.readProjectFile(e.cwd, sideline)if (read) {- const p = this.entryKeyed(e, read.file)- this.revs.set(p.id, p.rev)+ const p = read.file+ this.revs.set(e.id, p.rev)this.lastWritten.set(projectFilePath(e.cwd), read.raw)built.push({entry: e,file: p,project: fileToProject(p, {+ // The ENTRY's id, always. The file's own `id` is a legacy compatibility field that+ // git copies verbatim into every worktree — reading it is what let one machine's+ // project id name two folders.+ id: e.id,cwd: e.cwd,closed: e.closed,+ viewport: e.viewport,+ defaultAccountId: e.defaultAccountId,localExec: this.execOverlay(e, p)})})@@ -242,8 +248,11 @@ export class WorkspaceStore {built.push({entry: e,project: fileToProject(e.cache, {+ id: e.id,ssh: e.ssh,closed: e.closed,+ viewport: e.viewport,+ defaultAccountId: e.defaultAccountId,localExec: this.execOverlay(e, e.cache)})})@@ -261,45 +270,29 @@ export class WorkspaceStore {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.+ * The shared file no longer carries an id to copy, so nothing can corrupt a store this way any+ * more — but the stores corrupted BEFORE that are still on disk, and they cannot heal+ * themselves: once two entries were saved under one id (both folders' files carried it at the+ * last save), 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.+ *+ * It repairs the INDEX only. Re-keying the loser's project.json (what this did while the file+ * was the id's home) is now both pointless and wrong: the id in there is a legacy compatibility+ * field nothing reads, and writing to a git-shared file to fix a machine-local mistake is the+ * habit this whole change is removing.** 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.+ * in (id, folder) — a random id would give the two folders new names 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.+ * Loud on purpose (one line per repaired project, naming the folder): the user's tabs quietly+ * change identity, 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>()@@ -330,25 +323,9 @@ export class WorkspaceStore {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 rev is tracked per project id, so it has to follow the re-key. The file itself is not+ // touched: it holds this project's CONTENT, and the content did not change.+ if (b.file) this.revs.set(next, b.file.rev)}// 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).@@ -407,7 +384,10 @@ export class WorkspaceStore {try {const parsed = JSON.parse(raw) as ProjectFileV1// `raw` travels with the parse so callers can record the BYTES on disk in `lastWritten`.- if (parsed?.version === 1 && typeof parsed.id === 'string' && Array.isArray(parsed.nodes)) return { file: parsed, raw }+ // A missing `id` is NOT a wrong shape: the file stopped carrying identity, and the version+ // that still demanded one sidelines every modern file it meets (which is precisely why we+ // keep writing the legacy field for a release — see `legacyFileId`).+ if (parsed?.version === 1 && Array.isArray(parsed.nodes)) return { file: parsed, raw }// parses but isn't a ProjectFileV1 — sideline it too, so a later save can't overwrite the only copy.} catch { /* not JSON — sideline below */ }if (sideline) {@@ -488,10 +468,23 @@ export class WorkspaceStore {// splitWorkspace could not carry them — restoring them keeps the user's own custom shell /// ssh args for when the ref becomes readable again.if (old?.localExec) e.localExec = old.localExec+ // …and for the rest of the machine-local half. A placeholder's viewport is the {0,0,1} of+ // an empty stand-in canvas: persisting it would forget where the user was looking the+ // moment a folder is briefly unmounted.+ if (old?.viewport) e.viewport = old.viewport+ if (old?.defaultAccountId) e.defaultAccountId = old.defaultAccountId}}+ // Which project each pending file belongs to. `files` is keyed by cwd and the candidate no+ // longer carries an id (that is the point), while `revs` is keyed by PROJECT id — so the two+ // are joined here, through the index entry that owns the folder. At most one ref entry exists+ // per cwd (splitWorkspace's second tab on a folder becomes an inline entry, no cwd at all).+ const projectIdForCwd = new Map(+ index.entries.filter((e) => e.cwd).map((e) => [e.cwd!, e.id] as const)+ )for (const [cwd, candidate] of files) {+ const projectId = projectIdForCwd.get(cwd) ?? cwdconst file = projectFilePath(cwd)const prev = this.lastWritten.get(file)const prevParsed = prev ? (JSON.parse(prev) as ProjectFileV1) : null@@ -503,13 +496,13 @@ export class WorkspaceStore {// disk stays authoritative; the next load returns its truth.continue}- const next: ProjectFileV1 = { ...candidate, rev: (this.revs.get(candidate.id) ?? 0) + 1 }+ const next: ProjectFileV1 = { ...candidate, rev: (this.revs.get(projectId) ?? 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)+ this.revs.set(projectId, next.rev)} catch { /* folder gone (unmounted disk): the entry simply stays stale → unavailable next load */ }}@@ -574,12 +567,22 @@ export class WorkspaceStore {this.onPersist?.()}+ /**+ * The ADOPTION path: a folder with no index entry (Open folder…, a fresh clone). It is the one+ * place that must MINT an id — the file used to supply one, which is exactly how a worktree's+ * copy handed a second folder the first's identity.+ *+ * Minting cannot be idempotent (two folders holding the same canvas must become two projects),+ * so re-opening a folder is kept to one project by the CALLER, which looks the folder up by cwd+ * before it probes (`projects.openFolderProject` / `addProjectFromFolder`). Once adopted, the+ * index entry owns the id for good.+ */async probeFolder(folder: string): Promise<Project | null> {const read = await this.readProjectFile(folder, false)// No `localExec`: this folder is being ADOPTED (its project.json may have been cloned from// anywhere), so its nodes come up with no custom shell and no extra ssh args — the safe// defaults. Only values this machine typed itself are ever restored (@shared/node-exec).- return read ? fileToProject(read.file, { cwd: folder }) : null+ return read ? fileToProject(read.file, { id: freshProjectId(), cwd: folder }) : null}localRefPaths(): string[] {@@ -595,12 +598,19 @@ export class WorkspaceStore {if (!e?.cwd) return nullconst read = await this.readProjectFile(e.cwd, false)if (!read) return null- // 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)+ // The watcher's re-read after a git checkout is exactly where a foreign file arrives; the+ // project must come back under OUR entry id or `replaceProject` (which matches by id) silently+ // drops it. Same for the camera: a teammate's committed viewport must not yank this user's.+ this.revs.set(e.id, read.file.rev)this.lastWritten.set(projectFilePath(e.cwd), read.raw)- return fileToProject(file, { cwd: e.cwd, closed: e.closed, localExec: e.localExec })+ return fileToProject(read.file, {+ id: e.id,+ cwd: e.cwd,+ closed: e.closed,+ viewport: e.viewport,+ defaultAccountId: e.defaultAccountId,+ localExec: e.localExec+ })}/** Maps a watched file path back to its project and re-reads it. */@@ -741,7 +751,7 @@ export class WorkspaceStore {if (e.project) {out.push({ id: e.project.id, nodes: e.project.nodes, bridges: e.project.bridges })} else if (e.cache) {- out.push({ id: e.cache.id, nodes: e.cache.nodes, bridges: e.cache.bridges })+ out.push({ id: e.id, nodes: e.cache.nodes, bridges: e.cache.bridges })} else if (e.cwd) {const raw = this.lastWritten.get(projectFilePath(e.cwd))if (!raw) continue@@ -749,8 +759,8 @@ 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.- // 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.+ // Keyed by the ENTRY id — the map's consumers look projects up by the id the renderer+ // knows, which is never the git-shared file's (it no longer has one).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.@@ -823,11 +833,18 @@ 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 = this.entryKeyed(e, JSON.parse(updated) as ProjectFileV1)- this.revs.set(parsed.id, parsed.rev)+ const parsed = JSON.parse(updated) as ProjectFileV1+ this.revs.set(e.id, parsed.rev)platform().broadcast(IPC.workspaceExternalChange,- fileToProject(parsed, { cwd: e.cwd, closed: e.closed, localExec: e.localExec })+ fileToProject(parsed, {+ id: e.id,+ cwd: e.cwd,+ closed: e.closed,+ viewport: e.viewport,+ defaultAccountId: e.defaultAccountId,+ localExec: e.localExec+ }))} catch { /* the file is written and cached; the next load/poll surfaces the node */ }return true@@ -896,7 +913,10 @@ export class WorkspaceStore {this.revs.set(e.id, adopted.rev)if (owed) this.unmirrored.add(e.id)else this.unmirrored.delete(e.id) // pure adopt: the server copy IS the truth now — nothing owed- return fileToProject(adopted, { ssh: e.ssh, closed: e.closed, localExec: e.localExec })+ return fileToProject(adopted, {+ id: e.id, ssh: e.ssh, closed: e.closed,+ viewport: e.viewport, defaultAccountId: e.defaultAccountId, localExec: e.localExec+ })}// Our cache stood. Before it clobbers the server, merge in any remote-only session nodes (the// phone's drifted append) so the push carries them instead of erasing them.@@ -907,7 +927,10 @@ export class WorkspaceStore {e.cache = { ...e.cache, nodes: [...e.cache.nodes, ...rescued], rev: Math.max(cacheRev, remote.rev) + 1 }this.revs.set(e.id, e.cache.rev)this.unmirrored.add(e.id) // the merged set must land on the server- merged = fileToProject(e.cache, { ssh: e.ssh, closed: e.closed, localExec: e.localExec })+ merged = fileToProject(e.cache, {+ id: e.id, ssh: e.ssh, closed: e.closed,+ viewport: e.viewport, defaultAccountId: e.defaultAccountId, localExec: e.localExec+ })}}if (e.cache && (pushIfStanding || this.unmirrored.has(e.id))) {diff --git a/src/renderer/canvas/Canvas.tsx b/src/renderer/canvas/Canvas.tsxindex 753a08413..feb4f0550 100644--- a/src/renderer/canvas/Canvas.tsx+++ b/src/renderer/canvas/Canvas.tsx@@ -1999,7 +1999,7 @@ export function Canvas() {setMigrationNote(kind === 'exec'? 'Custom shells and advanced SSH options (e.g. a ProxyCommand jump host) are no longer stored in the shared .nodeterm/project.json — a cloned repo could use them to run code. They still work here: they moved to this machine only, and your teammates no longer receive them.'- : 'Projects now live in a .nodeterm folder inside each project directory — commit it to share the canvas, or add it to .gitignore.'+ : 'Projects now live in a .nodeterm folder inside each project directory. It holds the canvas only — no ids, camera or accounts from this machine — so committing it shares the canvas cleanly, or add it to .gitignore.')})}, [])@@ -3356,8 +3356,8 @@ export function Canvas() {commitActiveToStore()// 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…".+ // ignored that canvas entirely, so a clone came up blank. Same probe→adopt path as "Open+ // folder…" — the probe reads the canvas and mints this machine's id for it.//// The probe may NOT be allowed to fail the clone: `onCloned` is typed `=> void` and the// dialog does not await it, so a rejected IPC would leave the freshly cloned repo with nodiff --git a/src/renderer/state/projects.test.ts b/src/renderer/state/projects.test.tsindex 6fd6c9252..3467ee558 100644--- a/src/renderer/state/projects.test.ts+++ b/src/renderer/state/projects.test.ts@@ -44,6 +44,38 @@ describe('openFolderProject', () => {})})+describe('adopting a folder whose canvas is shared (no id in the file)', () => {+ // The file names no project any more, so `probeFolder` mints one per adoption. Re-opening the+ // same folder must therefore be answered by the CWD lookup, never by a second adoption — that+ // lookup is the only thing standing between "open my repo again" and a duplicate tab.+ const probed = (id: string) => ({+ id, name: 'my-app', color: '#7aa2f7', cwd: '/Users/me/dev/my-app',+ viewport: { x: 0, y: 0, zoom: 1 },+ nodes: [{+ id: 'term-a', kind: 'terminal' as const, position: { x: 0, y: 0 },+ size: { width: 1, height: 1 }, title: 'a', color: '#fff', group: null+ }]+ })++ it('re-opening the same folder yields ONE project, keyed by cwd', () => {+ const first = useProjects.getState().adoptProject(probed('project-minted-1'))+ expect(first.id).toBe('project-minted-1')+ const again = useProjects.getState().openFolderProject('/Users/me/dev/my-app')+ expect(again.id).toBe(first.id)+ expect(useProjects.getState().projects).toHaveLength(1)+ expect(useProjects.getState().projects[0].nodes.map((n) => n.id)).toEqual(['term-a'])+ })++ it('a SECOND folder holding the same canvas becomes its own project', () => {+ const a = useProjects.getState().adoptProject(probed('project-minted-1'))+ const b = useProjects.getState()+ .adoptProject({ ...probed('project-minted-2'), cwd: '/Users/me/dev/my-app-worktree' })+ expect(b.id).not.toBe(a.id)+ expect(useProjects.getState().projects.map((p) => p.cwd))+ .toEqual(['/Users/me/dev/my-app', '/Users/me/dev/my-app-worktree'])+ })+})+describe('toWorkspace', () => {// Tripwire for Stage 4a: a project's session binding is RUNTIME-ONLY (resolved by// src/renderer/session/session.ts `sessionForProject`). The persisted workspace shape mustdiff --git a/src/renderer/state/projects.ts b/src/renderer/state/projects.tsindex 0d6b9f0f7..bfda03d21 100644--- a/src/renderer/state/projects.ts+++ b/src/renderer/state/projects.ts@@ -47,8 +47,9 @@ interface ProjectsState {* a fresh empty project for a folder that already has one: its first mirror write used to* clobber the server's .nodeterm/project.json. Activates and returns it. */openSshProject(label: string, ssh: NonNullable<Project['ssh']>): Project- /** Registers a probed project (from a folder's .nodeterm file). If the id collides with an- * existing project, derives a fresh project id (node ids untouched). Activates it. */+ /** Registers a probed project (from a folder's .nodeterm file). The probe already minted the id+ * — the shared file carries none — so this only defends against a collision with an existing+ * project (node ids untouched). Activates it. */adoptProject(project: Project): Project/** Replaces one project's data wholesale (external file change). Keeps activeProjectId. */replaceProject(project: Project): void@@ -274,10 +275,11 @@ export const useProjects = create<ProjectsState>((set, get) => ({adoptProject(project) {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.+ // `probeFolder` mints the id (the folder's project.json no longer names one), so a collision+ // here means the id was minted against a store this renderer had not hydrated yet — 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, so this path and the+ // store's own repair never disagree about what a tab is called.const adopted = taken? {...project,diff --git a/src/shared/project-id.ts b/src/shared/project-id.tsindex 2f9d448c3..907aaa8e4 100644--- a/src/shared/project-id.ts+++ b/src/shared/project-id.ts@@ -1,17 +1,20 @@/*** 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+ * A project id is machine-local identity, and `<cwd>/.nodeterm/project.json` is a GIT-SHARED+ * document (the migration banner tells users to commit it so the canvas travels with the repo).+ * While that file CARRIED an id, `git worktree add`, a branch checkout, `reset --hard` or a+ * `stash pop` re-materialised one committed id into a SECOND folder, and two tabs then answered* 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.+ * The cause is gone: the shared file no longer carries identity at all (see `projectToFile` —+ * only a machine-INDEPENDENT legacy `id` remains, for one release, so an older build can still+ * read the file). What stays here is the repair for stores already corrupted by it, which needs+ * the same derivation in two runtimes (main's store repairs the on-disk index, 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@@ -64,3 +67,36 @@ export function collisionSeed(p: {}): string {return p.cwd ?? p.ssh?.remoteCwd ?? p.name}++/**+ * The `id` a git-shared project.json is written with — COMPATIBILITY ONLY, and deliberately not+ * this machine's project id.+ *+ * A build that predates this change refuses a project.json without a string `id` and sidelines it+ * to `.corrupt-<ts>` — a rename inside the user's own repo, and a canvas that vanishes for a+ * teammate still on the App Store build. So the field stays for one release. It is derived from+ * the canvas's own NAME, which means every machine that holds this file writes the same value:+ * committing the file produces no per-machine churn, and a worktree copy carries no identity+ * anything can adopt (this build ignores the field entirely).+ *+ * Drop this — and the field — one release after the version that introduced it.+ */+export function legacyFileId(name: string): string {+ return `project-${shortHash(name)}`+}++/**+ * A brand-new project id, minted where nothing else can supply one: the ADOPTION path (a folder+ * whose project.json we just read but which has no index entry yet). Random, not derived — two+ * folders that share a canvas byte-for-byte must still become two projects.+ *+ * Same shape/alphabet as the renderer's `nextId('project')`, so ids from both minters are+ * interchangeable everywhere they are interpolated (control paths, log routing).+ */+export function freshProjectId(): string {+ const c = globalThis.crypto as Crypto | undefined+ const token = c?.getRandomValues+ ? Array.from(c.getRandomValues(new Uint8Array(4)), (b) => b.toString(16).padStart(2, '0')).join('')+ : Math.floor(Math.random() * 0x100000000).toString(16).padStart(8, '0')+ return `project-${Date.now().toString(36)}-${token}`+}