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.

feat(workspace): move a folder project's storage between its folder and app data

Brandon Bridges313639545ebf
diff --git a/src/core/git-tracked.ts b/src/core/git-tracked.ts
new file mode 100644
index 000000000..e9fb427d5
--- /dev/null
+++ b/src/core/git-tracked.ts
@@ -0,0 +1,23 @@
+import { execFile } from 'child_process'
+import { promisify } from 'util'
+import { gitEnv } from './git-env'
+
+const run = promisify(execFile)
+
+/**
+ * Does git track `file` in the repository holding `folder`? `true` / `false`, or `'unknown'` when
+ * it could not be told (git missing, a broken repository): callers that would DELETE a file treat
+ * unknown like tracked and ask first, because a deletion git sees is a change in the user's repo.
+ * A folder that is not a repository at all is a definite `false`.
+ */
+export async function gitTracksFile(folder: string, file: string): Promise<boolean | 'unknown'> {
+ try {
+ await run('git', ['ls-files', '--error-unmatch', '--', file], { cwd: folder, env: gitEnv(), timeout: 10_000 })
+ return true
+ } catch (e) {
+ const err = e as { code?: unknown; stderr?: string }
+ if (err.code === 1) return false // ran in a repository; the path is not tracked
+ if (/not a git repository/i.test(err.stderr ?? '')) return false
+ return 'unknown'
+ }
+}
diff --git a/src/core/relay/access-policy.ts b/src/core/relay/access-policy.ts
index 0489f68b1..30bc70d5e 100644
--- a/src/core/relay/access-policy.ts
+++ b/src/core/relay/access-policy.ts
@@ -311,6 +311,9 @@ export const EDITOR_ONLY: ReadonlySet<string> = new Set<string>([
IPC.workspaceClaimLaunch,
IPC.workspaceProbeFolder,
IPC.workspaceProjectFileState,
+ // Moving a project's storage (issue #1145): both write and delete files on the host.
+ IPC.workspaceReleaseFolderFiles,
+ IPC.workspacePrepareFolderStorage,
IPC.projectSettingsRead,
IPC.projectSettingsWriteShared,
IPC.projectSettingsUpdateLocal,
diff --git a/src/core/relay/scoped-guest-policy.ts b/src/core/relay/scoped-guest-policy.ts
index a35be6cf9..8c95120d5 100644
--- a/src/core/relay/scoped-guest-policy.ts
+++ b/src/core/relay/scoped-guest-policy.ts
@@ -438,6 +438,9 @@ export const SCOPED: Readonly<Record<string, Check>> = Object.freeze({
export const SCOPED_REFUSED: ReadonlySet<string> = new Set<string>([
// A whole-workspace write from a peer would replace the host's other projects.
IPC.workspaceSave,
+ // Moving a project's storage writes and deletes host files (issue #1145); host-only.
+ IPC.workspaceReleaseFolderFiles,
+ IPC.workspacePrepareFolderStorage,
// Host-only (shared/host-control.ts): a peer's launch claim would make the host's own viewers
// stand down from a launch (#1173). A relay tab never sends it.
IPC.workspaceClaimLaunch,
diff --git a/src/core/workspace-store.folder-data.test.ts b/src/core/workspace-store.folder-data.test.ts
index f649adcc4..bba3b97d5 100644
--- a/src/core/workspace-store.folder-data.test.ts
+++ b/src/core/workspace-store.folder-data.test.ts
@@ -6,6 +6,7 @@
// the side a move departs from.
import { describe, it, expect, beforeEach, afterEach } from 'vitest'
import { promises as fs } from 'fs'
+import { execFileSync } from 'child_process'
import os from 'os'
import path from 'path'
import { initPlatform, resetPlatformForTests } from './platform'
@@ -288,3 +289,91 @@ describe('moving a folder project between the two locations', () => {
expect(await exists(folderFile())).toBe(true)
})
})
+
+describe('the move steps', () => {
+ const settingsIn = (root: string) => path.join(root, '.nodeterm', 'settings.json')
+ const appRoot = () => path.join(userData, 'project-files', 'project-p1')
+ const seedFolder = async () => {
+ await fs.mkdir(path.join(folder, '.nodeterm'), { recursive: true })
+ await fs.writeFile(settingsIn(folder), JSON.stringify({ version: 1, rev: 3, savedAt: '', terminal: { shell: '/bin/zsh' } }))
+ }
+
+ it('release: carries settings into app data and removes the folder files', async () => {
+ const store = new WorkspaceStore()
+ await seedFolder()
+ await store.save(ws([project({ storeInAppData: undefined })]))
+ expect(await exists(folderFile())).toBe(true)
+
+ await store.save(ws([project()]))
+ const res = await store.releaseFolderFiles('project-p1', false)
+ expect(res).toEqual({ ok: true, removed: [folderFile(), settingsIn(folder)], kept: [] })
+ expect(await exists(path.join(folder, '.nodeterm'))).toBe(false)
+ expect(JSON.parse(await fs.readFile(settingsIn(appRoot()), 'utf-8')).terminal.shell).toBe('/bin/zsh')
+ expect((await store.readProjectSettings('project-p1'))?.shared?.terminal?.shell).toBe('/bin/zsh')
+ })
+
+ it('release: keeps files git tracks unless told to remove them', async () => {
+ execFileSync('git', ['init', '-q'], { cwd: folder })
+ const store = new WorkspaceStore()
+ await store.save(ws([project({ storeInAppData: undefined })]))
+ execFileSync('git', ['add', '.nodeterm/project.json'], { cwd: folder })
+
+ await store.save(ws([project()]))
+ expect(await store.releaseFolderFiles('project-p1', false)).toEqual({ ok: true, removed: [], kept: [folderFile()] })
+ expect(await exists(folderFile())).toBe(true)
+ expect(await store.releaseFolderFiles('project-p1', true)).toEqual({ ok: true, removed: [folderFile()], kept: [] })
+ expect(await exists(folderFile())).toBe(false)
+ })
+
+ it('release: refused for a project whose canvas is still in its folder', async () => {
+ const store = new WorkspaceStore()
+ await store.save(ws([project({ storeInAppData: undefined })]))
+ expect(await store.releaseFolderFiles('project-p1', true)).toEqual({ ok: false, reason: 'not-app-data' })
+ expect(await exists(folderFile())).toBe(true)
+ })
+
+ it('a round trip with an unchanged canvas writes the folder file again before the data file goes', async () => {
+ const store = new WorkspaceStore()
+ await store.save(ws([project({ storeInAppData: undefined })]))
+ await store.save(ws([project()]))
+ await store.releaseFolderFiles('project-p1', false)
+ expect(await exists(folderFile())).toBe(false)
+
+ expect(await store.prepareFolderStorage('project-p1')).toEqual({ ok: true })
+ await store.save(ws([project({ storeInAppData: undefined })]))
+ expect(ids(JSON.parse(await fs.readFile(folderFile(), 'utf-8')).nodes)).toEqual(['term-1'])
+ expect(await exists(dataFile('project-p1'))).toBe(false)
+ })
+
+ it('prepare: refuses a folder that already holds a canvas or settings', async () => {
+ const store = new WorkspaceStore()
+ await store.save(ws([project()]))
+ await fs.mkdir(path.join(folder, '.nodeterm'))
+ await fs.writeFile(folderFile(), foreignFile('term-foreign'))
+ expect(await store.prepareFolderStorage('project-p1')).toEqual({ ok: false, reason: 'occupied' })
+
+ await fs.rm(folderFile())
+ await fs.writeFile(settingsIn(folder), JSON.stringify({ version: 1, rev: 1, savedAt: '' }))
+ expect(await store.prepareFolderStorage('project-p1')).toEqual({ ok: false, reason: 'settings-occupied' })
+ })
+
+ it('prepare + save: the settings follow the canvas into the folder, and leave app data', async () => {
+ const store = new WorkspaceStore()
+ await store.save(ws([project()]))
+ await store.writeProjectSettings('project-p1', { terminal: { shell: '/bin/fish' } })
+
+ expect(await store.prepareFolderStorage('project-p1')).toEqual({ ok: true })
+ expect(JSON.parse(await fs.readFile(settingsIn(folder), 'utf-8')).terminal.shell).toBe('/bin/fish')
+ await store.save(ws([project({ storeInAppData: undefined })]))
+ expect(await exists(settingsIn(appRoot()))).toBe(false)
+ expect((await store.readProjectSettings('project-p1'))?.shared?.terminal?.shell).toBe('/bin/fish')
+ })
+
+ it('a move back that skipped prepare keeps the app-data settings', async () => {
+ const store = new WorkspaceStore()
+ await store.save(ws([project()]))
+ await store.writeProjectSettings('project-p1', { terminal: { shell: '/bin/fish' } })
+ await store.save(ws([project({ storeInAppData: undefined })]))
+ expect(await exists(settingsIn(appRoot()))).toBe(true)
+ })
+})
diff --git a/src/core/workspace-store.ts b/src/core/workspace-store.ts
index 28090c601..fbdb0b2eb 100644
--- a/src/core/workspace-store.ts
+++ b/src/core/workspace-store.ts
@@ -21,7 +21,9 @@ import {
sanitizeLinks,
type IndexEntryV3, type ProjectFileV1, type WorkspaceIndexV3
} from './workspace-files'
-import { readProjectSettingsFile, writeProjectSettingsFile } from './project-settings-files'
+import { projectSettingsPath, readProjectSettingsFile, writeProjectSettingsFile } from './project-settings-files'
+import { gitTracksFile } from './git-tracked'
+import type { PrepareFolderStorageResult, ReleaseFolderFilesResult } from '../shared/project-storage'
import {
parseProjectSettingsFile, sameProjectSettingsContent, sanitizeProjectLocalSettings,
sanitizeProjectSettingsDoc, serializeProjectSettingsFile,
@@ -450,6 +452,13 @@ export class WorkspaceStore {
platform().handle(IPC.workspaceProbeFolder, (folder: string) => this.probeFolder(folder))
platform().handle(IPC.workspaceProjectFileState, (cwd: unknown) =>
typeof cwd === 'string' && cwd ? this.projectFileState(cwd) : 'unreadable')
+ // Issue #1145. Host-only for every peer (core/relay/access-policy.ts): both write files.
+ platform().handle(IPC.workspaceReleaseFolderFiles, (projectId: unknown, removeTracked: unknown) =>
+ typeof projectId === 'string'
+ ? this.releaseFolderFiles(projectId, removeTracked === true)
+ : { ok: false, reason: 'not-app-data' })
+ platform().handle(IPC.workspacePrepareFolderStorage, (projectId: unknown) =>
+ typeof projectId === 'string' ? this.prepareFolderStorage(projectId) : { ok: false, reason: 'not-app-data' })
platform().handle(IPC.projectSettingsRead, (projectId: unknown) =>
typeof projectId === 'string' ? this.readProjectSettings(projectId) : null)
platform().handle(IPC.projectSettingsWriteShared, (projectId: unknown, doc: ProjectSettingsDoc) =>
@@ -1775,6 +1784,13 @@ export class WorkspaceStore {
// A project that only moved its canvas keeps its rev: it continues in the new location, and
// resetting it would send the folder's next write out as rev 1 over the rev N just written.
if (!nextById.has(e.id)) this.revs.delete(e.id)
+ // A folder-data-ref that moved back into its folder: its app-data settings were carried into
+ // the folder by `prepareFolderStorage`. Removed only once the folder demonstrably has them —
+ // a move that skipped the carry must not lose the project's settings.
+ const moved = nextById.get(e.id)
+ if (moved?.cwd && isFolderDataRef(e) && (await readProjectSettingsFile(moved.cwd)).status === 'ok') {
+ await fs.rm(projectSettingsPath(appDataProjectRoot(e.id)), { force: true }).catch(() => undefined)
+ }
}
}
@@ -1811,6 +1827,102 @@ export class WorkspaceStore {
* read is never evidence of absence — so the errno is the answer, and anything that is not a
* definite ENOENT reports `unreadable`, the side that changes nothing. See issue #385.
*/
+ /**
+ * The second half of "Store in app data" (issue #1145), run once the move's save has landed:
+ * carry the folder's settings.json into the project's app-data root (when it has none of its
+ * own), then remove `.nodeterm/project.json` and `settings.json` from the folder, so a later
+ * "Open folder…", a worktree or an older build cannot adopt the stale copy as a second project.
+ *
+ * Refused unless the entry IS a folder-data-ref whose data file this store has written or read —
+ * the canvas must demonstrably be in app data before its folder copy goes. A file git tracks (or
+ * that could not be checked) is KEPT unless `removeTracked`: deleting it is a change in the
+ * user's repo, which the caller asks about first. A settings file that could not be carried over
+ * is kept too. Queued on `saveChain`, after any save in flight.
+ */
+ releaseFolderFiles(projectId: string, removeTracked: boolean): Promise<ReleaseFolderFilesResult> {
+ const run = this.saveChain.then(() => this.releaseFolderFilesNow(projectId, removeTracked))
+ this.saveChain = run.catch(() => {})
+ return run
+ }
+
+ private async releaseFolderFilesNow(projectId: string, removeTracked: boolean): Promise<ReleaseFolderFilesResult> {
+ const e = this.index?.entries.find((x) => x.id === projectId)
+ if (!e || !isFolderDataRef(e) || !e.cwd) return { ok: false, reason: 'not-app-data' }
+ if (!isInlineProjectFileId(e.id) || !this.lastWritten.has(inlineFilePath(e.id))) {
+ return { ok: false, reason: 'not-saved' }
+ }
+ const cwd = e.cwd
+ const candidates: string[] = []
+ if ((await this.projectFileState(cwd)) === 'present') candidates.push(projectFilePath(cwd))
+
+ const folderSettings = await readProjectSettingsFile(cwd)
+ if (folderSettings.status === 'ok') {
+ const root = appDataProjectRoot(e.id)
+ const own = await readProjectSettingsFile(root)
+ let carried = own.status === 'ok'
+ if (own.status === 'absent') {
+ try {
+ const written = await writeProjectSettingsFile(root, folderSettings.file, null, new Date().toISOString())
+ this.lastSharedSettings.set(e.id, written)
+ carried = true
+ } catch { /* not carried: the folder's copy stays below */ }
+ }
+ if (carried) candidates.push(projectSettingsPath(cwd))
+ }
+
+ const removed: string[] = []
+ const kept: string[] = []
+ for (const file of candidates) {
+ const tracked = await gitTracksFile(cwd, file)
+ if (tracked !== false && !removeTracked) {
+ kept.push(file)
+ continue
+ }
+ try {
+ await fs.rm(file, { force: true })
+ removed.push(file)
+ // Forget it as ours, or a move back with an unchanged canvas would skip the folder write as
+ // "unchanged" and the sweep would then delete the data file: the only copy.
+ this.lastWritten.delete(file)
+ this.lastWrittenParsed.delete(file)
+ } catch {
+ kept.push(file)
+ }
+ }
+ // An emptied `.nodeterm/` goes too; one still holding images or a board log stays.
+ if (removed.length) await fs.rmdir(path.join(cwd, PROJECT_DIR)).catch(() => undefined)
+ return { ok: true, removed, kept }
+ }
+
+ /**
+ * The first half of "Store in folder" (issue #1145), run before the move's save: refuse when the
+ * folder already holds a project.json (the save would overwrite that canvas — the same
+ * probe-before-bind rule as "Set folder…") or a settings.json (this project's own would be lost),
+ * and an unreadable file is never taken for an absent one. Otherwise carry the project's
+ * app-data settings into the folder, so they are there the moment the canvas is.
+ */
+ async prepareFolderStorage(projectId: string): Promise<PrepareFolderStorageResult> {
+ const e = this.index?.entries.find((x) => x.id === projectId)
+ if (!e || !isFolderDataRef(e) || !e.cwd) return { ok: false, reason: 'not-app-data' }
+ const state = await this.projectFileState(e.cwd)
+ if (state === 'present') return { ok: false, reason: 'occupied' }
+ if (state === 'unreadable') return { ok: false, reason: 'unreadable' }
+ const folderSettings = await readProjectSettingsFile(e.cwd)
+ if (folderSettings.status === 'ok' || folderSettings.status === 'conflict') return { ok: false, reason: 'settings-occupied' }
+ if (folderSettings.status === 'error') return { ok: false, reason: 'unreadable' }
+ if (isInlineProjectFileId(e.id)) {
+ const own = await readProjectSettingsFile(appDataProjectRoot(e.id))
+ if (own.status === 'ok') {
+ try {
+ await writeProjectSettingsFile(e.cwd, own.file, null, new Date().toISOString())
+ } catch {
+ return { ok: false, reason: 'unreadable' }
+ }
+ }
+ }
+ return { ok: true }
+ }
+
async projectFileState(cwd: string): Promise<'present' | 'absent' | 'unreadable'> {
try {
await fs.stat(projectFilePath(cwd))
diff --git a/src/preload/index.ts b/src/preload/index.ts
index bb08a0483..0f331d099 100644
--- a/src/preload/index.ts
+++ b/src/preload/index.ts
@@ -170,6 +170,9 @@ const api: NodeTerminalApi = {
ipcRenderer.invoke(IPC.workspaceClaimLaunch, nodeId, command, manual),
probeFolder: (folder: string) => ipcRenderer.invoke(IPC.workspaceProbeFolder, folder),
projectFileState: (folder: string) => ipcRenderer.invoke(IPC.workspaceProjectFileState, folder),
+ releaseFolderFiles: (projectId: string, removeTracked: boolean) =>
+ ipcRenderer.invoke(IPC.workspaceReleaseFolderFiles, projectId, removeTracked),
+ prepareFolderStorage: (projectId: string) => ipcRenderer.invoke(IPC.workspacePrepareFolderStorage, projectId),
onMigrated: (cb: (kind: WorkspaceMigrationKind) => void) => {
// Older mains broadcast no payload; that was the v2→v3 migration.
const h = (_e: unknown, kind?: WorkspaceMigrationKind) => cb(kind ?? 'v2')
diff --git a/src/renderer/bridge/ws-bridge.ts b/src/renderer/bridge/ws-bridge.ts
index 494de01a7..87f16c97e 100644
--- a/src/renderer/bridge/ws-bridge.ts
+++ b/src/renderer/bridge/ws-bridge.ts
@@ -381,6 +381,15 @@ export function buildRealApi(
client.request(IPC.workspaceProjectFileState, folder) as ReturnType<
WorkspaceApi['projectFileState']
>,
+ // REAL: core registers both (issue #1145), and the Server Edition stores projects the same way.
+ releaseFolderFiles: (projectId: string, removeTracked: boolean) =>
+ client.request(IPC.workspaceReleaseFolderFiles, projectId, removeTracked) as ReturnType<
+ WorkspaceApi['releaseFolderFiles']
+ >,
+ prepareFolderStorage: (projectId: string) =>
+ client.request(IPC.workspacePrepareFolderStorage, projectId) as ReturnType<
+ WorkspaceApi['prepareFolderStorage']
+ >,
// REAL: core broadcasts IPC.workspaceMigrated after a v2→v3 migration (workspace-store.ts).
onMigrated: (cb) => client.subscribe(IPC.workspaceMigrated, cb as Listener),
// REAL: core broadcasts IPC.workspaceCorruptRecovered from the load path (workspace-store.ts).
diff --git a/src/shared/ipc.ts b/src/shared/ipc.ts
index 86249e1a2..4111ebbf0 100644
--- a/src/shared/ipc.ts
+++ b/src/shared/ipc.ts
@@ -486,6 +486,10 @@ export const IPC = {
/** Is a folder's .nodeterm/project.json present / absent / unreadable — the distinction
* `probeFolder`'s null collapses. Recovery of an `unavailable` project needs it (issue #385). */
workspaceProjectFileState: 'workspace:project-file-state',
+ /** "Store in app data", second half (issue #1145): carry settings over, remove the folder files. */
+ workspaceReleaseFolderFiles: 'workspace:release-folder-files',
+ /** "Store in folder", first half (issue #1145): refuse an occupied folder, carry settings in. */
+ workspacePrepareFolderStorage: 'workspace:prepare-folder-storage',
projectSettingsRead: 'project-settings:read',
projectSettingsWriteShared: 'project-settings:write-shared',
projectSettingsUpdateLocal: 'project-settings:update-local',
diff --git a/src/shared/project-storage.ts b/src/shared/project-storage.ts
new file mode 100644
index 000000000..18695909d
--- /dev/null
+++ b/src/shared/project-storage.ts
@@ -0,0 +1,40 @@
+// Where a folder project's canvas is stored (issue #1145): in the folder
+// (`<cwd>/.nodeterm/project.json`, git-shareable — the default) or in app data
+// (`userData/inline-projects/<id>.json`, nothing written into the folder). See the folder-data-ref
+// kind in core/workspace-files.ts and `Project.storeInAppData`.
+
+/** The global default for folder projects added from now on. */
+export type NewProjectStorage = 'folder' | 'appData'
+
+export const NEW_PROJECT_STORAGE_DEFAULT: NewProjectStorage = 'folder'
+
+export function isNewProjectStorage(v: unknown): v is NewProjectStorage {
+ return v === 'folder' || v === 'appData'
+}
+
+/**
+ * After a project's canvas has moved into app data: its folder files, removed or kept.
+ * `kept` lists the files git tracks (or that could not be checked): deleting one shows up as a
+ * change in the user's repo, so it is only done when the caller confirms with `removeTracked`.
+ */
+export type ReleaseFolderFilesResult =
+ | { ok: true; removed: string[]; kept: string[] }
+ | { ok: false; reason: 'not-app-data' | 'not-saved' }
+
+/**
+ * Before a project's canvas moves back into its folder: the folder must not already hold a canvas
+ * or settings of its own (the next save would overwrite them), and an unreadable file is never
+ * taken for an absent one.
+ */
+export type PrepareFolderStorageResult =
+ | { ok: true }
+ | { ok: false; reason: 'not-app-data' | 'occupied' | 'unreadable' | 'settings-occupied' }
+
+export const PREPARE_FOLDER_STORAGE_REFUSALS: Record<Exclude<PrepareFolderStorageResult, { ok: true }>['reason'], string> = {
+ 'not-app-data': 'This project already stores its canvas in its folder.',
+ occupied:
+ 'The folder already has a .nodeterm/project.json. Delete it first, or use “Open folder…” to open that canvas instead.',
+ unreadable: 'The folder’s .nodeterm/project.json could not be read, so nothing was changed.',
+ 'settings-occupied':
+ 'The folder already has a .nodeterm/settings.json. Delete it first so this project’s own settings are not lost.'
+}
diff --git a/src/shared/types.ts b/src/shared/types.ts
index aec89b979..50b1afd17 100644
--- a/src/shared/types.ts
+++ b/src/shared/types.ts
@@ -1492,6 +1492,13 @@ export interface WorkspaceApi {
/** Whether <folder>/.nodeterm/project.json is `present`, definitely `absent`, or `unreadable`
* (any non-ENOENT error). Never guesses absence from a failed read — see issue #385. */
projectFileState(folder: string): Promise<'present' | 'absent' | 'unreadable'>
+ /** "Store in app data", second half (issue #1145): once the move's save has landed, carry the
+ * folder's settings into app data and remove its `.nodeterm` files (git-tracked ones only with
+ * `removeTracked`). See `WorkspaceStore.releaseFolderFiles`. */
+ releaseFolderFiles(projectId: string, removeTracked: boolean): Promise<import('./project-storage').ReleaseFolderFilesResult>
+ /** "Store in folder", first half (issue #1145): refuse a folder that already holds a canvas or
+ * settings, else carry this project's settings in. See `WorkspaceStore.prepareFolderStorage`. */
+ prepareFolderStorage(projectId: string): Promise<import('./project-storage').PrepareFolderStorageResult>
/** Fired once after an on-disk migration: `v2` = a v2→v3 migration wrote .nodeterm/ dirs into the
* project folders; `exec` = the custom shell / advanced ssh args of already-open projects moved
* out of the shared project file into this machine's own workspace index (@shared/node-exec). */