Skip to content

Node-based terminal manager for AI coding agents — tmux-backed terminals and parallel agent sessions as draggable nodes on an infinite pan/zoom canvas. macOS, Linux, and a browser Server Edition.

fix(projects): probe before binding a folder, and stop pretending a cwd-less canvas has one

enes2d37a7098f85
diff --git a/CLAUDE.md b/CLAUDE.md
index 7e3596bd7..44f831f9f 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -196,6 +196,36 @@ Persistence has two layers:
are set aside as `project.json.corrupt-<ts>`. "Open folder…" adopts an existing
`.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.
+ **A cwd-less canvas is a supported, first-class project, not a degraded one** — "New project" on
+ the welcome screen creates exactly that, and the whole `Project` (nodes, viewport, kanban,
+ closedSessions, per-node `shell`) rides `IndexEntryV3.project` verbatim, so it survives a restart
+ intact. It is the correct fallback layer and `localStorage` is not: the index is in `userData`
+ (backed up with the app's data, atomic-written, one store for all three shells), while
+ localStorage is renderer-origin state that the Server Edition would shard per browser profile.
+ What inline genuinely lacks is a SECOND copy: a folder project's canvas also lives in
+ `<cwd>/.nodeterm/project.json`, so a corrupt index costs it nothing (`Open folder…` adopts it
+ back), whereas an inline canvas exists ONLY inside the index — and therefore only inside the
+ `workspace.json.corrupt-<ts>` sideline, with no UI path back. The corrupt-index note must say
+ that plainly; it used to promise "No project data was lost — each project's canvas is still in
+ its own folder", which is true for refs and false for exactly the projects that just vanished.
+ **Binding a folder to an existing project is a WRITE, so probe before you bind.** "Set folder…"
+ (tab ⌄) promotes an inline canvas to a ref, and the next autosave writes that folder's
+ `project.json` — over whatever was already there. It used to bind unconditionally, so pointing a
+ scratch project at a repo whose canvas a teammate had committed replaced it (rev 40 → rev 1, their
+ nodes gone, no sideline copy, nothing on screen). The two entrances to "attach a folder" now agree:
+ `openOrAdoptFolder` probes and ADOPTS, and `setProjectFolder` runs the pure
+ `renderer/lib/setProjectFolder.ts` — an occupied OR unreadable `project.json` refuses the bind with
+ its reason (a failed read is never evidence of absence, #385), and a folder another project already
+ owns routes to that project, REOPENING it when it is closed rather than switching to a hidden tab.
+ The store's own "never blind-write" guard does not cover this: it only refuses an EMPTY candidate
+ over a populated file, and this candidate has nodes.
+ **Features that need a folder degrade explicitly, never silently.** Explorer, Source Control and
+ Project Settings already say so in words; the add menus now do too — "New file…" and "New
+ worktree…" stay in the list DISABLED with `NEW_FILE_NO_CWD_HINT` / `WORKTREE_NO_CWD_HINT`
+ (`lib/addMenuSpec`) instead of vanishing, and `openWorktreeDialog` refuses a cwd-less project at
+ the same choke point it refuses an SSH one (the palette has no disabled state). The worktree
+ dialog's "This project is not a git repository." was the wrong cause for a project that has no
+ folder to be a repository at all.
**An `unavailable` placeholder used to be a DEAD END** (issue #385): a save deliberately emits a
header-only ref for it and never a file, so a `project.json` the user deleted was never
recreated, every later load re-minted the placeholder, and nothing cleared the flag for a LOCAL
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index f0d2e3c49..8c61799c1 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -219,6 +219,21 @@ reply carries it (`queued` / `queuedIds`), because a user who cannot see the fai
orchestrator that is told "opened" both act on a session that is not there. If you add a bounded
retry anywhere, ask what the clock actually starts on and where its exhaustion becomes visible.
+**Pointing a project at a folder is a WRITE — probe before you bind.** A project's canvas is
+written to `<cwd>/.nodeterm/project.json`, so the moment a project gains a `cwd` the next autosave
+owns that file. "Open folder…" always probed and adopted; "Set folder…" (tab ⌄) used to bind
+unconditionally, which overwrote a canvas a teammate had committed to that repo — their nodes gone,
+no backup, nothing on screen. Both entrances now share the rule (`renderer/lib/setProjectFolder.ts`):
+an occupied *or unreadable* project file refuses the bind and says why. The store's "never
+blind-write" guard will not save you — it only refuses an EMPTY canvas over a populated file.
+
+**A project with no folder is a real project — degrade explicitly, never silently.** "New project"
+creates a cwd-less canvas that persists inline in `workspace.json`, so every folder-shaped feature
+meets one. Keep the affordance and disable it with its reason (`NEW_FILE_NO_CWD_HINT`,
+`WORKTREE_NO_CWD_HINT`, the Explorer/Source Control notes); a row that simply vanishes teaches
+nothing, and a message that names the wrong cause ("not a git repository" for a project that has no
+folder to be one) sends the user hunting a problem that does not exist.
+
**Agent features attach to base harness capabilities, not frontend allowlists.** A custom agent can
inherit a builtin harness, so add the capability and its one shared leaf (`src/shared/agents`) and
let every UI ask the helper. Repeating Claude/Codex/etc. cases in menus breaks that inheritance and
diff --git a/src/renderer/canvas/Canvas.tsx b/src/renderer/canvas/Canvas.tsx
index 1cb4e2c7f..9096bdf65 100644
--- a/src/renderer/canvas/Canvas.tsx
+++ b/src/renderer/canvas/Canvas.tsx
@@ -152,6 +152,7 @@ import {
contentAddItemsToMenuItems,
type AddHandlers
} from '../lib/addMenuSpec'
+import { planSetProjectFolder } from '../lib/setProjectFolder'
import { transferConversationItems } from '../lib/transferItems'
import { reopenVariants } from '../lib/reopenVariants'
import { modelsForAgent } from '@shared/agents/model-gateway'
@@ -612,6 +613,11 @@ interface PendingPeerState {
*/
const WORKTREE_SSH_HINT = 'Not supported in SSH projects yet'
const WORKTREE_SSH_NOTICE = 'Worktrees are not supported in SSH projects yet.'
+/** The cwd-less twin of WORKTREE_SSH_NOTICE. The disabled MENU rows carry
+ * `WORKTREE_NO_CWD_HINT` (lib/addMenuSpec); this is the sentence for the surfaces that have no
+ * disabled state — the command palette, and any control-verb path that reaches the dialog. */
+const WORKTREE_NO_CWD_NOTICE =
+ 'This project has no folder, so it has no git repository to add a worktree to. Set one first (tab ⌄ → “Set folder…”).'
const FOCUS_NO_TARGET_NOTICE = 'Select a terminal or agent node to focus.'
// The webview's file loader renders off the LOCAL disk and has no remote counterpart, so a host
@@ -2576,11 +2582,17 @@ export function Canvas() {
}, [])
// Same strip, same one-shot rule: the workspace list came up empty because the index file was
- // unreadable. Nothing was lost — say where the backup is and how to get the projects back.
+ // unreadable. Say where the backup is and how to get the projects back — and do NOT promise more
+ // than is true. The old copy read "No project data was lost — each project's canvas is still in
+ // its own folder", which holds for a FOLDER project (its canvas is in `<cwd>/.nodeterm/
+ // project.json`, so "Open folder…" adopts it straight back) and is false for a cwd-less one: that
+ // canvas lived only inside the index, i.e. only inside the backup this note names. Telling a user
+ // whose scratch project just vanished that nothing was lost is the worst of both — it is wrong,
+ // and it stops them keeping the one file that still has their nodes in it.
useEffect(() => {
return api.workspace.onCorruptRecovered((backupFile) => {
setMigrationNote(
- `The workspace index was corrupted and has been backed up as ${backupFile}. No project data was lost — each project's canvas is still in its own folder. Use “Open folder…” to add them back.`
+ `The workspace index was corrupted and has been backed up as ${backupFile} (in the app's data folder). Projects with a folder are safe — their canvas is in <folder>/.nodeterm/project.json, so “Open folder…” adds them back. A project with no folder lived only in the index: keep that backup, it is the only copy of its canvas.`
)
})
}, [])
@@ -5090,10 +5102,19 @@ export function Canvas() {
// The single choke point for opening the dialog — the menus already render their rows
// disabled on an SSH project, but the command palette has no disabled state, so refuse HERE
// and say why. Silently doing nothing is the one outcome that is not allowed.
- if (useProjects.getState().getProject(projectId)?.ssh) {
+ const target = useProjects.getState().getProject(projectId)
+ if (target?.ssh) {
setNotice({ kind: 'error', text: WORKTREE_SSH_NOTICE })
return
}
+ // Same choke point, second reason: a cwd-less project has no repo to add a worktree TO. The
+ // dialog used to open anyway and say "This project is not a git repository." — which names
+ // the wrong cause (there is no folder to be a repository) and leaves the user looking for a
+ // git problem that does not exist. The menus render the row disabled; the palette cannot.
+ if (!target?.cwd) {
+ setNotice({ kind: 'error', text: WORKTREE_NO_CWD_NOTICE })
+ return
+ }
setWorktreeError(null)
setWorktreeDialog({ groupId, at, projectId })
// Fresh branch list for the Base / existing-branch dropdown. Clear first so a previous repo's
@@ -11375,22 +11396,43 @@ export function Canvas() {
[persist]
)
+ // Reopen a previously closed project and make it active — the active-project effect reloads its
+ // serialized nodes, whose TerminalNodes reattach to the surviving tmux sessions (or cold-restore).
+ const reopenProject = useCallback(
+ (id: string) => {
+ commitActiveToStore()
+ useProjects.getState().reopenProject(id)
+ setWelcomeOpen(false)
+ void writeDisk()
+ },
+ [commitActiveToStore, writeDisk]
+ )
+
const setProjectFolder = useCallback(
async (id: string) => {
const folder = await window.nodeTerminal.dialog.selectFolder()
if (!folder) return
- // Folder ↔ project is deduped like "Open folder…": if another project already owns this cwd,
- // don't point a second tab at it (two same-cwd tabs collapse to one file on save) — just
- // switch to the existing one.
- const existing = useProjects.getState().projects.find((p) => p.cwd === folder && p.id !== id)
- if (existing) {
- switchProject(existing.id)
+ // Binding a folder makes the next autosave WRITE `<folder>/.nodeterm/project.json`. Ask the
+ // folder what is already there first — this used to bind unconditionally, and a folder that
+ // carried a teammate's committed canvas had it overwritten by this project's nodes at rev 1,
+ // with no sideline copy. "Open folder…" never had that bug because it probes and adopts; the
+ // refusal + the dedupe (a closed owner is REOPENED, not switched to behind a hidden tab) are
+ // the pure `planSetProjectFolder`. See lib/setProjectFolder.ts.
+ const fileState = await api.workspace.projectFileState(folder)
+ const plan = planSetProjectFolder(folder, id, useProjects.getState().projects, fileState)
+ if (plan.kind === 'occupied') {
+ setNotice({ kind: 'error', text: plan.reason })
+ return
+ }
+ if (plan.kind === 'switch') {
+ if (plan.reopen) reopenProject(plan.projectId)
+ else switchProject(plan.projectId)
return
}
useProjects.getState().setProjectCwd(id, folder)
void persist()
},
- [persist, switchProject]
+ [persist, switchProject, reopenProject]
)
const setProjectDefaultAccount = useCallback(
@@ -11542,18 +11584,6 @@ export function Canvas() {
]
)
- // Reopen a previously closed project and make it active — the active-project effect reloads its
- // serialized nodes, whose TerminalNodes reattach to the surviving tmux sessions (or cold-restore).
- const reopenProject = useCallback(
- (id: string) => {
- commitActiveToStore()
- useProjects.getState().reopenProject(id)
- setWelcomeOpen(false)
- void writeDisk()
- },
- [commitActiveToStore, writeDisk]
- )
-
// ---- presence travel ("go to where my teammate is", from the facepile) ----
// A peer may be working in a project we have CLOSED — the facepile shows off-project peers on
// purpose. A closed project still lives in the store (`closed: true`), so `setActive` alone would
diff --git a/src/renderer/lib/addMenuSpec.test.tsx b/src/renderer/lib/addMenuSpec.test.tsx
index c11d4d19d..45df08c1d 100644
--- a/src/renderer/lib/addMenuSpec.test.tsx
+++ b/src/renderer/lib/addMenuSpec.test.tsx
@@ -3,6 +3,9 @@ import {
CONTENT_ADD_ITEMS,
contentAddItemsToMenuItems,
contentAddItemsToDockRows,
+ NEW_FILE_NO_CWD_HINT,
+ WORKTREE_NO_CWD_HINT,
+ WORKTREE_SSH_HINT,
type AddItem,
type AddHandlers
} from './addMenuSpec'
@@ -66,12 +69,37 @@ describe('contentAddItemsToMenuItems', () => {
])
})
- it('hides "New file…" when the project has no cwd', () => {
+ // A cwd-less project is a supported, persisted canvas — the folder-shaped rows must degrade
+ // EXPLICITLY (the SSH worktree row's rule), not vanish. Hiding them left the user with no row and
+ // no reason, and the fix ("Set folder…") one menu away with nothing pointing at it.
+ it('DISABLES "New file…" with its reason when the project has no cwd — never hides it', () => {
const items = contentAddItemsToMenuItems(CONTENT_ADD_ITEMS, handlers(), {
hasCwd: false,
isSshProject: false
})
- expect(items.some((i) => 'label' in i && i.label === 'New file…')).toBe(false)
+ const newFile = items.find((i) => 'label' in i && i.label === 'New file…')
+ expect(newFile).toBeDefined()
+ expect(newFile && 'disabled' in newFile && newFile.disabled).toBe(true)
+ expect(newFile && 'hint' in newFile && newFile.hint).toBe(NEW_FILE_NO_CWD_HINT)
+ })
+
+ it('disables "New worktree…" with its own reason on a cwd-less project', () => {
+ const items = contentAddItemsToMenuItems(CONTENT_ADD_ITEMS, handlers(), {
+ hasCwd: false,
+ isSshProject: false
+ })
+ const worktree = items.find((i) => 'label' in i && i.label === 'New worktree…')
+ expect(worktree && 'disabled' in worktree && worktree.disabled).toBe(true)
+ expect(worktree && 'hint' in worktree && worktree.hint).toBe(WORKTREE_NO_CWD_HINT)
+ })
+
+ it('keeps the SSH reason on an SSH project that also has no cwd — the stronger one wins', () => {
+ const items = contentAddItemsToMenuItems(CONTENT_ADD_ITEMS, handlers(), {
+ hasCwd: false,
+ isSshProject: true
+ })
+ const worktree = items.find((i) => 'label' in i && i.label === 'New worktree…')
+ expect(worktree && 'hint' in worktree && worktree.hint).toBe(WORKTREE_SSH_HINT)
})
it('disables "New worktree…" on an SSH project and surfaces the hint', () => {
@@ -130,11 +158,15 @@ describe('contentAddItemsToDockRows', () => {
expect(rows.some((r) => r.kind === 'remote')).toBe(false)
})
- it('hides "new-file" when there is no cwd', () => {
+ it('DISABLES "new-file" with its reason when there is no cwd — the Dock keeps the row too', () => {
const rows = contentAddItemsToDockRows(CONTENT_ADD_ITEMS, handlers(), {
hasCwd: false,
isSshProject: false
})
- expect(rows.some((r) => r.kind === 'new-file')).toBe(false)
+ const newFile = rows.find((r) => r.kind === 'new-file')
+ expect(newFile).toBeDefined()
+ expect(newFile?.disabled).toBe(true)
+ expect(newFile?.hint).toBe(NEW_FILE_NO_CWD_HINT)
+ expect(rows.find((r) => r.kind === 'worktree')?.hint).toBe(WORKTREE_NO_CWD_HINT)
})
})
diff --git a/src/renderer/lib/addMenuSpec.tsx b/src/renderer/lib/addMenuSpec.tsx
index c5f4737a5..0e5cf832f 100644
--- a/src/renderer/lib/addMenuSpec.tsx
+++ b/src/renderer/lib/addMenuSpec.tsx
@@ -109,6 +109,19 @@ export interface AddHandlers {
/** The SSH worktree hint shown on the disabled row — kept here so every surface shows the same one. */
export const WORKTREE_SSH_HINT = 'Not supported in SSH projects yet'
+/**
+ * The two rows that need a project FOLDER, shown disabled with their reason rather than hidden.
+ *
+ * A cwd-less project (the "New project" card on the welcome screen) is a supported, persisted
+ * canvas — its nodes live inline in `workspace.json` — so the folder-shaped features around it must
+ * degrade EXPLICITLY, the same rule the SSH worktree row already follows and the same one the
+ * Explorer, Source Control and Project Settings panels already state in words. "New file…" simply
+ * vanished before, which teaches nothing: the row was gone and so was the reason, and the folder
+ * that would fix it is one menu away.
+ */
+export const NEW_FILE_NO_CWD_HINT = 'This project has no folder — set one first (tab ⌄ → “Set folder…”)'
+export const WORKTREE_NO_CWD_HINT = NEW_FILE_NO_CWD_HINT
+
/**
* Map the canonical content list to {@link MenuItem}s for the `ContextMenu` component.
*
@@ -156,10 +169,15 @@ export function contentAddItemsToMenuItems(
out.push({ label: 'Open file…', icon: <IconEditor />, onClick: () => void handlers.openFile(at) })
break
case 'new-file':
- // "New file…" needs a project folder to create into — hidden when the project has no cwd.
- if (ctx.hasCwd) {
- out.push({ label: 'New file…', icon: <IconEditor />, onClick: () => void handlers.newFile(at) })
- }
+ // "New file…" creates UNDER the project folder, so a cwd-less project cannot run it — the
+ // row stays, disabled, and names the reason (NEW_FILE_NO_CWD_HINT).
+ out.push({
+ label: 'New file…',
+ icon: <IconEditor />,
+ disabled: !ctx.hasCwd,
+ hint: ctx.hasCwd ? undefined : NEW_FILE_NO_CWD_HINT,
+ onClick: () => void handlers.newFile(at)
+ })
break
case 'spawn-team':
out.push({ label: 'Spawn a team…', icon: <IconGroup />, onClick: () => handlers.spawnTeam(at) })
@@ -168,8 +186,12 @@ export function contentAddItemsToMenuItems(
out.push({
label: 'New worktree…',
icon: <IconBranch />,
- disabled: ctx.isSshProject,
- hint: ctx.isSshProject ? WORKTREE_SSH_HINT : undefined,
+ disabled: ctx.isSshProject || !ctx.hasCwd,
+ hint: ctx.isSshProject
+ ? WORKTREE_SSH_HINT
+ : ctx.hasCwd
+ ? undefined
+ : WORKTREE_NO_CWD_HINT,
onClick: () => handlers.worktree(at)
})
break
@@ -234,9 +256,14 @@ export function contentAddItemsToDockRows(
out.push({ kind: 'open-file', label: 'Open file…', icon: <IconEditor />, onClick: () => void handlers.openFile() })
break
case 'new-file':
- if (ctx.hasCwd) {
- out.push({ kind: 'new-file', label: 'New file…', icon: <IconEditor />, onClick: () => void handlers.newFile() })
- }
+ out.push({
+ kind: 'new-file',
+ label: 'New file…',
+ icon: <IconEditor />,
+ disabled: !ctx.hasCwd,
+ hint: ctx.hasCwd ? undefined : NEW_FILE_NO_CWD_HINT,
+ onClick: () => void handlers.newFile()
+ })
break
case 'spawn-team':
out.push({ kind: 'spawn-team', label: 'Spawn a team…', icon: <IconGroup />, onClick: () => handlers.spawnTeam() })
@@ -246,8 +273,12 @@ export function contentAddItemsToDockRows(
kind: 'worktree',
label: 'Worktree…',
icon: <IconBranch />,
- disabled: ctx.isSshProject,
- hint: ctx.isSshProject ? WORKTREE_SSH_HINT : undefined,
+ disabled: ctx.isSshProject || !ctx.hasCwd,
+ hint: ctx.isSshProject
+ ? WORKTREE_SSH_HINT
+ : ctx.hasCwd
+ ? undefined
+ : WORKTREE_NO_CWD_HINT,
onClick: () => handlers.worktree()
})
break
diff --git a/src/renderer/lib/setProjectFolder.test.ts b/src/renderer/lib/setProjectFolder.test.ts
new file mode 100644
index 000000000..3aef5f5c0
--- /dev/null
+++ b/src/renderer/lib/setProjectFolder.test.ts
@@ -0,0 +1,51 @@
+import { describe, it, expect } from 'vitest'
+import { planSetProjectFolder, folderOccupiedNotice, folderUnreadableNotice } from './setProjectFolder'
+
+const p = (id: string, cwd?: string, closed?: boolean) => ({ id, cwd, closed })
+
+describe('planSetProjectFolder', () => {
+ it('binds a folder that holds no project file', () => {
+ expect(planSetProjectFolder('/repo', 'p1', [p('p1')], 'absent')).toEqual({ kind: 'bind' })
+ })
+
+ it('REFUSES a folder that already holds a canvas — the overwrite this module exists to stop', () => {
+ expect(planSetProjectFolder('/repo', 'p1', [p('p1')], 'present')).toEqual({
+ kind: 'occupied',
+ reason: folderOccupiedNotice('/repo')
+ })
+ })
+
+ it('refuses an unreadable project file too: a failed read is not evidence of absence (#385)', () => {
+ expect(planSetProjectFolder('/repo', 'p1', [p('p1')], 'unreadable')).toEqual({
+ kind: 'occupied',
+ reason: folderUnreadableNotice('/repo')
+ })
+ })
+
+ it('routes to the project that already owns the folder instead of minting a second entry', () => {
+ const plan = planSetProjectFolder('/repo', 'p1', [p('p1'), p('p2', '/repo')], 'present')
+ expect(plan).toEqual({ kind: 'switch', projectId: 'p2', reopen: false })
+ })
+
+ it('asks for a REOPEN when the owner is closed — switching would land on an invisible tab', () => {
+ const plan = planSetProjectFolder('/repo', 'p1', [p('p1'), p('p2', '/repo', true)], 'absent')
+ expect(plan).toEqual({ kind: 'switch', projectId: 'p2', reopen: true })
+ })
+
+ it('does not treat the project being pointed at its OWN folder as a foreign owner', () => {
+ expect(planSetProjectFolder('/repo', 'p1', [p('p1', '/repo')], 'present')).toEqual({
+ kind: 'occupied',
+ reason: folderOccupiedNotice('/repo')
+ })
+ })
+
+ it('prefers the existing owner over the occupied refusal — the file is that project’s own', () => {
+ const plan = planSetProjectFolder('/repo', 'p1', [p('p2', '/repo')], 'present')
+ expect(plan.kind).toBe('switch')
+ })
+
+ it('names the folder in both refusals, so the message is actionable', () => {
+ expect(folderOccupiedNotice('/a/b')).toContain('/a/b')
+ expect(folderUnreadableNotice('/a/b')).toContain('/a/b')
+ })
+})
diff --git a/src/renderer/lib/setProjectFolder.ts b/src/renderer/lib/setProjectFolder.ts
new file mode 100644
index 000000000..f6b006234
--- /dev/null
+++ b/src/renderer/lib/setProjectFolder.ts
@@ -0,0 +1,61 @@
+import type { Project } from '@shared/types'
+
+/**
+ * "Set folder…" (tab ⌄) points an EXISTING project — typically a cwd-less "New project" — at a
+ * directory. That single act promotes the project from an INLINE canvas (stored verbatim inside
+ * `workspace.json`) to a REF whose canvas is written to `<cwd>/.nodeterm/project.json`.
+ *
+ * It is therefore a WRITE into a folder we may never have read, and until this module existed it
+ * did exactly that: the very next autosave overwrote whatever canvas the folder already held. A
+ * teammate's committed `project.json` (rev 40, its own nodes) came back as this project's canvas at
+ * rev 1, with no sideline copy and nothing on screen to say it had happened. "Open folder…" never
+ * had the bug — it probes and ADOPTS (`openOrAdoptFolder`) — so the two entrances to the same
+ * "attach a folder" idea disagreed, and the destructive one was the one a scratch project leads to.
+ *
+ * The decision is pure and lives here so both the refusal and its reason are testable, and so the
+ * rule reads as one thing rather than as three branches inside a Canvas callback.
+ */
+export type SetProjectFolderPlan =
+ /** Another project in this workspace already owns the folder — go there instead of pointing a
+ * second tab at one file (two same-cwd tabs collapse on save). `reopen` when that project is
+ * closed: switching to a closed project would land on a tab the user cannot see. */
+ | { kind: 'switch'; projectId: string; reopen: boolean }
+ /** The folder already carries a canvas (or one we could not read). Binding would overwrite it,
+ * so refuse and say so; the user's route is "Open folder…", which adopts it as its own project. */
+ | { kind: 'occupied'; reason: string }
+ /** The folder is free (no project file): bind it. */
+ | { kind: 'bind' }
+
+/** Shown when the folder already holds a canvas. Names the file, because the user's next question
+ * is "which folder?" and the answer has to be actionable without opening a terminal. */
+export const folderOccupiedNotice = (folder: string): string =>
+ `${folder} already contains a nodeterm canvas (.nodeterm/project.json). ` +
+ `Setting it as this project's folder would overwrite it — use “Open folder…” to open that canvas instead.`
+
+/** Shown when the file is there but unreadable (permissions, a stalled mount). A failed read is
+ * never evidence of absence (issue #385), so this refuses for the same reason the present case
+ * does, and says which of the two it is. */
+export const folderUnreadableNotice = (folder: string): string =>
+ `${folder} has a .nodeterm/project.json that could not be read. ` +
+ `Setting it as this project's folder would overwrite it, so nothing was changed.`
+
+/**
+ * @param folder the directory the user picked.
+ * @param projectId the project being pointed at it.
+ * @param projects every project in the workspace, CLOSED ONES INCLUDED — a closed project still
+ * owns its folder on disk, and treating its folder as free is how the second
+ * entry gets minted for one `project.json`.
+ * @param fileState `workspace.projectFileState(folder)` — 'present' | 'absent' | 'unreadable'.
+ */
+export function planSetProjectFolder(
+ folder: string,
+ projectId: string,
+ projects: Pick<Project, 'id' | 'cwd' | 'closed'>[],
+ fileState: 'present' | 'absent' | 'unreadable'
+): SetProjectFolderPlan {
+ const existing = projects.find((p) => p.cwd === folder && p.id !== projectId)
+ if (existing) return { kind: 'switch', projectId: existing.id, reopen: !!existing.closed }
+ if (fileState === 'present') return { kind: 'occupied', reason: folderOccupiedNotice(folder) }
+ if (fileState === 'unreadable') return { kind: 'occupied', reason: folderUnreadableNotice(folder) }
+ return { kind: 'bind' }
+}