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(project-settings): WorkspaceStore settings APIs + machine-local overlay persistence

enesd305bd6ccfce
diff --git a/src/core/workspace-files.ts b/src/core/workspace-files.ts
index 1a5abc605..aaa13aed1 100644
--- a/src/core/workspace-files.ts
+++ b/src/core/workspace-files.ts
@@ -137,6 +137,20 @@ export interface IndexEntryV3 {
* shell / advanced ssh args still survive a restart. Inline (`project`) entries need none: they
* live in this same machine-local file already. */
localExec?: LocalNodeExecMap
+ /**
+ * MACHINE-LOCAL settings overlay for this entry — the half of the project settings that is NOT
+ * git-shared (`.nodeterm/settings.json` is the shared half). Same rule as `localExec`: it lives in
+ * userData because a shell, a launch command or an env var this user chose for THIS checkout is
+ * not something a repo may carry — and, read the other way, a repo may not put values here.
+ * Re-sanitized on every load (`sanitizeProjectLocalSettings`): workspace.json is hand-editable,
+ * so what comes back out of it is input, not state we wrote.
+ */
+ localSettings?: import('../shared/project-settings').ProjectLocalSettings
+ /** The last shared settings.json seen for an SSH entry — the settings twin of `cache`, used while
+ * the server is unreachable. Never set for a local/inline entry (their shared doc is one disk
+ * read away). Validated on load by re-parsing it, exactly like a file read off the remote host:
+ * what sits in workspace.json is no more trusted than what sits on the server. */
+ settingsCache?: import('../shared/project-settings').ProjectSettingsFileV1
/**
* The one-time exec migration has run for this entry: its project file has been searched once for
* the exec values it carried from BEFORE the trust boundary existed (a jump host's `ProxyCommand`
diff --git a/src/core/workspace-store.settings.test.ts b/src/core/workspace-store.settings.test.ts
new file mode 100644
index 000000000..b074fb680
--- /dev/null
+++ b/src/core/workspace-store.settings.test.ts
@@ -0,0 +1,139 @@
+import { describe, it, expect, beforeEach, afterEach } from 'vitest'
+import { promises as fs } from 'fs'
+import os from 'os'
+import path from 'path'
+import { initPlatform, resetPlatformForTests } from './platform'
+import { fakePlatform } from './platform-fake'
+import { WorkspaceStore } from './workspace-store'
+import type { Project, Workspace } from '../shared/types'
+
+let userData: string
+let projRoot: string
+let fake: ReturnType<typeof fakePlatform>
+
+const project = (over: Partial<Project> = {}): Project => ({
+ id: 'p1', name: 'foo', color: '#7aa2f7', viewport: { x: 0, y: 0, zoom: 1 },
+ nodes: [{ id: 'term-1', kind: 'terminal', position: { x: 0, y: 0 }, size: { width: 1, height: 1 }, title: 't', color: '#fff', group: null }],
+ ...over
+})
+const ws = (projects: Project[], active = projects[0]?.id ?? ''): Workspace =>
+ ({ version: 2, activeProjectId: active, projects })
+
+beforeEach(async () => {
+ userData = await fs.mkdtemp(path.join(os.tmpdir(), 'nt-ws-'))
+ projRoot = await fs.mkdtemp(path.join(os.tmpdir(), 'nt-proj-'))
+ fake = fakePlatform({ userDataDir: userData })
+ initPlatform(fake)
+})
+afterEach(async () => {
+ resetPlatformForTests()
+ await fs.rm(userData, { recursive: true, force: true })
+ await fs.rm(projRoot, { recursive: true, force: true })
+})
+
+describe('project settings — local leg', () => {
+ it('write → read round-trips through the store', async () => {
+ const store = new WorkspaceStore()
+ await store.save(ws([project({ cwd: projRoot })]))
+ expect(await store.writeProjectSettings('p1', { terminal: { shell: '/bin/zsh' } })).toBe(true)
+ const s = await store.readProjectSettings('p1')
+ expect(s?.shared?.terminal?.shell).toBe('/bin/zsh')
+ const onDisk = JSON.parse(await fs.readFile(path.join(projRoot, '.nodeterm', 'settings.json'), 'utf-8'))
+ expect(onDisk.rev).toBe(1)
+ })
+
+ it('local overlay persists across store instances without a canvas save', async () => {
+ const store = new WorkspaceStore()
+ await store.save(ws([project({ cwd: projRoot })]))
+ await store.updateLocalProjectSettings('p1', { ignoreShared: { setup: true } })
+ const store2 = new WorkspaceStore()
+ await store2.load()
+ const s = await store2.readProjectSettings('p1')
+ expect(s?.local).toEqual({ ignoreShared: { setup: true } })
+ })
+
+ it('a canvas save does not drop the overlay (survives splitWorkspace round trip)', async () => {
+ const store = new WorkspaceStore()
+ const w = ws([project({ cwd: projRoot })])
+ await store.save(w)
+ await store.updateLocalProjectSettings('p1', { terminal: { shell: '/bin/fish' } })
+ await store.save(w) // canvas autosave rebuilds the index
+ const idx = JSON.parse(await fs.readFile(path.join(userData, 'workspace.json'), 'utf-8'))
+ expect(idx.entries[0].localSettings).toEqual({ terminal: { shell: '/bin/fish' } })
+ })
+
+ it('clearing the overlay removes it from the index', async () => {
+ const store = new WorkspaceStore()
+ await store.save(ws([project({ cwd: projRoot })]))
+ const idxPath = path.join(userData, 'workspace.json')
+ await store.updateLocalProjectSettings('p1', { terminal: { shell: '/bin/fish' } })
+ const set = JSON.parse(await fs.readFile(idxPath, 'utf-8'))
+ expect(set.entries[0].localSettings).toEqual({ terminal: { shell: '/bin/fish' } })
+ await store.updateLocalProjectSettings('p1', undefined)
+ const idx = JSON.parse(await fs.readFile(idxPath, 'utf-8'))
+ expect(idx.entries[0].localSettings).toBeUndefined()
+ const s = await store.readProjectSettings('p1')
+ expect(s?.local).toBeUndefined()
+ })
+
+ it('a git-conflicted settings.json reads as conflict with shared null', async () => {
+ const store = new WorkspaceStore()
+ await store.save(ws([project({ cwd: projRoot })]))
+ await fs.mkdir(path.join(projRoot, '.nodeterm'), { recursive: true })
+ await fs.writeFile(path.join(projRoot, '.nodeterm', 'settings.json'),
+ '<<<<<<< a\n{}\n=======\n{}\n>>>>>>> b\n', 'utf-8')
+ const s = await store.readProjectSettings('p1')
+ expect(s?.conflict).toBe(true)
+ expect(s?.shared).toBeNull()
+ })
+
+ it('an inline (cwd-less) project has no shared doc and cannot be written to', async () => {
+ const store = new WorkspaceStore()
+ await store.save(ws([project({ id: 'inline1', name: 'inline' })]))
+ await store.updateLocalProjectSettings('inline1', { terminal: { theme: 'dark' } })
+ const s = await store.readProjectSettings('inline1')
+ expect(s?.shared).toBeNull()
+ expect(s?.local).toEqual({ terminal: { theme: 'dark' } })
+ expect(await store.writeProjectSettings('inline1', { terminal: { shell: '/bin/zsh' } })).toBe(false)
+ })
+
+ it('returns null for an unknown project id', async () => {
+ const store = new WorkspaceStore()
+ await store.save(ws([project({ cwd: projRoot })]))
+ expect(await store.readProjectSettings('nope')).toBeNull()
+ expect(await store.writeProjectSettings('nope', {})).toBe(false)
+ expect(await store.updateLocalProjectSettings('nope', {})).toBe(false)
+ })
+
+ it('a hostile localSettings shape in workspace.json is sanitized on load', async () => {
+ const store = new WorkspaceStore()
+ await store.save(ws([project({ cwd: projRoot })]))
+ const idxPath = path.join(userData, 'workspace.json')
+ const idx = JSON.parse(await fs.readFile(idxPath, 'utf-8'))
+ // JSON.parse (not an object literal): only the parser creates `__proto__` as a real OWN
+ // property — a literal would set the prototype and the key would never reach the file.
+ idx.entries[0].localSettings = JSON.parse('{"agents":{"env":{"__proto__":"x","OK":"v"}},"bogus":1}')
+ const rawIndex = JSON.stringify(idx)
+ expect(rawIndex).toContain('__proto__') // the hostile key really is on disk
+ await fs.writeFile(idxPath, rawIndex, 'utf-8')
+ const store2 = new WorkspaceStore()
+ await store2.load()
+ const s = await store2.readProjectSettings('p1')
+ expect(s?.local).toEqual({ agents: { env: { OK: 'v' } } })
+ })
+
+ it('a hostile settingsCache in workspace.json is rejected on load', async () => {
+ const store = new WorkspaceStore()
+ await store.save(ws([
+ project({ id: 'ssh1', name: 'remote', ssh: { server: { host: 'h', user: 'u' }, remoteCwd: '~/x' } })
+ ]))
+ const idxPath = path.join(userData, 'workspace.json')
+ const idx = JSON.parse(await fs.readFile(idxPath, 'utf-8'))
+ idx.entries[0].settingsCache = { version: 2, rev: 'nope', terminal: { shell: '/bin/evil' } }
+ await fs.writeFile(idxPath, JSON.stringify(idx), 'utf-8')
+ const store2 = new WorkspaceStore()
+ await store2.load()
+ const s = await store2.readProjectSettings('ssh1')
+ expect(s?.shared).toBeNull()
+ })
+})
diff --git a/src/core/workspace-store.ts b/src/core/workspace-store.ts
index cba17a7c1..a651d72cd 100644
--- a/src/core/workspace-store.ts
+++ b/src/core/workspace-store.ts
@@ -12,6 +12,11 @@ import {
serializeProjectFile, splitWorkspace, validKanban,
type IndexEntryV3, type ProjectFileV1, type WorkspaceIndexV3
} from './workspace-files'
+import { readProjectSettingsFile, writeProjectSettingsFile } from './project-settings-files'
+import {
+ parseProjectSettingsFile, sanitizeProjectLocalSettings,
+ type ProjectLocalSettings, type ProjectSettingsDoc, type ProjectSettingsFileV1
+} from '../shared/project-settings'
import { readProjectCapabilities, type ProjectCapability } from '../shared/project-capabilities'
import type { CapabilityAckMap } from './project-capability-consent'
import { hoistLegacyNodeExec, type LocalNodeExecMap } from '../shared/node-exec'
@@ -30,6 +35,16 @@ export interface RemoteWorkspaceIO {
const projectFilePath = (cwd: string): string => path.join(cwd, PROJECT_DIR, PROJECT_FILE)
+/** What one project's settings look like right now: the git-shared document (null when there is
+ * none, or it cannot be trusted/read) plus this machine's own overlay. `resolveProjectSettings`
+ * turns the pair into effective values; this type only reports what each side says. */
+export interface ProjectSettingsState {
+ shared: ProjectSettingsFileV1 | null
+ local: ProjectLocalSettings | undefined
+ /** Shared file exists but is git-conflict-marked; `shared` is null until the user resolves it. */
+ conflict?: true
+}
+
/** A parsed project file together with the exact bytes it was parsed from. `lastWritten` must
* record `raw` — see the field it caches. */
interface ProjectFileRead {
@@ -127,6 +142,18 @@ export class WorkspaceStore {
* node we never had, and the tie is broken toward rescuing (a resurrected node is visible and
* deletable again; a deleted session node is gone with no trace of where it went). */
private clearedNodes = new Map<string, Set<string>>()
+ /** project id -> this machine's settings overlay, already sanitized. The map — not the index
+ * entry — is the live copy: `splitWorkspace` rebuilds entries from the renderer's Workspace,
+ * which has never carried machine-local state, so every save would otherwise drop the overlay
+ * (the same reason `localExec`/`cache` are re-attached below). Absent = no overlay. */
+ private localSettingsByProject = new Map<string, ProjectLocalSettings>()
+ /** ssh project id -> last shared settings.json seen on that host (offline copy). Only entries that
+ * round-tripped through `parseProjectSettingsFile` are in here. */
+ private settingsCacheByProject = new Map<string, ProjectSettingsFileV1>()
+ /** project id -> the shared settings file as last read/written, i.e. the rev source for the NEXT
+ * write. Runtime-only: a write that has not read first starts at rev 1, which is the same thing
+ * a fresh file means. */
+ private lastSharedSettings = new Map<string, ProjectSettingsFileV1>()
/** Last index written/loaded — lets readLocalRef/refresh resolve entries without a full load. */
private index: WorkspaceIndexV3 | null = null
/** Optional hook fired after every load()/save() — the watcher re-syncs its watch set (Task 5). */
@@ -276,6 +303,8 @@ export class WorkspaceStore {
}
}
await this.repairDuplicateIds(built, sideline)
+ // AFTER the repair: it re-keys entries in place, and the maps are keyed by project id.
+ this.adoptSettingsFromIndex(index)
const projects = built.map((b) => b.project)
const active = projects.some((p) => p.id === index.activeProjectId && !p.unavailable)
? index.activeProjectId
@@ -379,6 +408,130 @@ export class WorkspaceStore {
if (!e.execMigrated) this.execUnmigrated.add(e.id)
}
+ /**
+ * Loads the settings halves out of a just-read index into the two runtime maps.
+ *
+ * workspace.json is hand-editable (and, on Server Edition, sits next to other users' reach), so
+ * neither field is trusted on the way in: the overlay goes through the same sanitizer a settings
+ * file gets, and a cached SHARED file is accepted only if it still parses as one — the parser is
+ * reused as the validator so there is exactly one definition of "a valid settings file",
+ * wherever the bytes came from.
+ */
+ private adoptSettingsFromIndex(index: WorkspaceIndexV3): void {
+ this.localSettingsByProject.clear()
+ this.settingsCacheByProject.clear()
+ for (const e of index.entries) {
+ const local = sanitizeProjectLocalSettings(e.localSettings)
+ if (local && Object.keys(local).length) this.localSettingsByProject.set(e.id, local)
+ if (!e.ssh || !e.settingsCache) continue
+ const parsed = parseProjectSettingsFile(JSON.stringify(e.settingsCache))
+ if (parsed.status === 'ok') this.settingsCacheByProject.set(e.id, parsed.file)
+ }
+ }
+
+ /** Writes the maps back onto an index about to be persisted — the machine-local half that
+ * `splitWorkspace` cannot know about. Runs on every index write, so an entry the maps no longer
+ * cover loses the field rather than keeping a stale copy of it. */
+ private applySettingsToIndex(index: WorkspaceIndexV3): void {
+ for (const e of index.entries) {
+ const local = this.localSettingsByProject.get(e.id)
+ if (local) e.localSettings = local
+ else delete e.localSettings
+ // Only an ssh entry has anywhere to cache: a local ref's shared file is one disk read away,
+ // and an inline canvas has no shared file at all.
+ const cached = e.ssh ? this.settingsCacheByProject.get(e.id) : undefined
+ if (cached) e.settingsCache = cached
+ else delete e.settingsCache
+ }
+ }
+
+ /**
+ * The shared + local settings of one project. `null` means the id names no entry (never "no
+ * settings" — an entry with neither file nor overlay answers `{shared: null, local: undefined}`).
+ *
+ * The shared doc is read from disk on every call rather than cached: `.nodeterm/settings.json` is
+ * a git-tracked file a checkout/merge/teammate rewrites behind our back, and a settings read is
+ * rare enough (a panel opening, a launch) that a stale answer would cost more than the read does.
+ */
+ async readProjectSettings(projectId: string): Promise<ProjectSettingsState | null> {
+ const e = this.index?.entries.find((x) => x.id === projectId)
+ if (!e) return null
+ const local = this.localSettingsByProject.get(projectId)
+ // SSH: the offline cache is all this task can answer with — the remote read lands in Task 7.
+ if (e.ssh) return { shared: this.settingsCacheByProject.get(projectId) ?? null, local }
+ // An inline canvas has no folder, so there is no shared document to have.
+ if (!e.cwd) return { shared: null, local }
+ const read = await readProjectSettingsFile(e.cwd)
+ if (read.status === 'ok') {
+ // The rev source for the next write — a write that skipped the read would restart at rev 1
+ // and lose the counter a remote/offline comparison depends on.
+ this.lastSharedSettings.set(projectId, read.file)
+ return { shared: read.file, local }
+ }
+ // conflict: the file exists but is mid-merge; it is left untouched for the user to resolve and
+ // reported as such, so a caller shows "resolve this" instead of "this project has no settings".
+ if (read.status === 'conflict') return { shared: null, local, conflict: true }
+ return { shared: null, local } // absent / invalid (sidelined) / unreadable
+ }
+
+ /**
+ * Whole-document write of the GIT-SHARED settings file. Whole-document on purpose: a per-field
+ * patch grammar would have to merge against a file that another writer (a teammate's commit, the
+ * user's editor) may have changed since the caller read it, and silently merging into a file the
+ * caller never saw is how the shared half stops meaning what the repo says.
+ *
+ * False = there is nowhere to write it: an unknown id, an inline canvas (no folder), an ssh
+ * project (Task 7 gives it the remote leg), or the write itself failed.
+ */
+ async writeProjectSettings(projectId: string, doc: ProjectSettingsDoc): Promise<boolean> {
+ const e = this.index?.entries.find((x) => x.id === projectId)
+ if (!e || e.ssh || !e.cwd) return false
+ try {
+ const written = await writeProjectSettingsFile(
+ e.cwd, doc, this.lastSharedSettings.get(projectId) ?? null, new Date().toISOString()
+ )
+ this.lastSharedSettings.set(projectId, written)
+ return true
+ } catch {
+ // Folder gone / read-only checkout: the caller is told the doc did not land, exactly like a
+ // failed project.json write leaves the entry stale rather than pretending it saved.
+ return false
+ }
+ }
+
+ /**
+ * Replaces this machine's overlay for one project (undefined = clear it) and persists the index
+ * NOW, without waiting for a canvas save: a settings edit is often the only thing the user did in
+ * that session, and an overlay that lives only in memory until the next node is dragged is an
+ * overlay that quietly disappears when the app quits.
+ */
+ async updateLocalProjectSettings(
+ projectId: string,
+ local: ProjectLocalSettings | undefined
+ ): Promise<boolean> {
+ const e = this.index?.entries.find((x) => x.id === projectId)
+ if (!e) return false
+ const clean = local === undefined ? undefined : sanitizeProjectLocalSettings(local)
+ if (clean && Object.keys(clean).length) this.localSettingsByProject.set(projectId, clean)
+ else this.localSettingsByProject.delete(projectId)
+ await this.persistIndexNow()
+ return true
+ }
+
+ /** Rewrites the CURRENT index with the settings maps applied. On `saveChain` like every other
+ * index write, so it can neither interleave with a save's own rewrite nor invent entries: it
+ * persists exactly what `this.index` already holds (and does nothing before the first load). */
+ private persistIndexNow(): Promise<void> {
+ const run = this.saveChain.then(async () => {
+ const index = this.index
+ if (!index) return
+ this.applySettingsToIndex(index)
+ await writeAtomic(this.indexPath, JSON.stringify(index))
+ })
+ this.saveChain = run.catch(() => {})
+ return run
+ }
+
/**
* Reads + parses one project file. Only the authoritative loadV3 path passes `sideline: true`,
* which renames an unparsable/wrong-shape file to `.corrupt-<ts>` so a later save can't overwrite
@@ -460,6 +613,11 @@ export class WorkspaceStore {
entry.localApprovalId = previous?.localApprovalId || randomUUID()
}
+ // The settings overlay / ssh settings cache ride every index write, like `localExec` and
+ // `cache`: `splitWorkspace` builds entries from the renderer's Workspace, which carries no
+ // machine-local state, so without this each autosave would erase them from disk.
+ this.applySettingsToIndex(index)
+
// An unavailable placeholder carries no real data. splitWorkspace already dropped its file
// and cache; here we restore the machine-local payload (ssh offline cache) from the previous
// index so the index rewrite doesn't drop a good cache we still can't reach.