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(project-settings): canonical write candidate + universal read-before-write + trust getRecord

enes8620b2002c7c
diff --git a/src/core/project-settings-files.ts b/src/core/project-settings-files.ts
index 4c929bdb0..8168e29b3 100644
--- a/src/core/project-settings-files.ts
+++ b/src/core/project-settings-files.ts
@@ -3,6 +3,7 @@ import path from 'path'
import {
parseProjectSettingsFile,
sameProjectSettingsContent,
+ sanitizeProjectSettingsDoc,
serializeProjectSettingsFile,
PROJECT_SETTINGS_FILE,
type ProjectSettingsDoc,
@@ -52,10 +53,21 @@ export async function writeProjectSettingsFile(
prev: ProjectSettingsFileV1 | null,
savedAt: string
): Promise<ProjectSettingsFileV1> {
- // `doc` spreads FIRST: a caller may pass back a previously-read ProjectSettingsFileV1 (it
- // structurally satisfies ProjectSettingsDoc), and its stale version/rev/savedAt must never win
- // over the bookkeeping this function computes — that would silently defeat rev monotonicity.
- const candidate: ProjectSettingsFileV1 = { ...doc, version: 1, rev: (prev?.rev ?? 0) + 1, savedAt }
+ // CANONICAL SHAPE — bookkeeping first, then the sanitized doc, i.e. exactly what
+ // `parseProjectSettingsFile` builds. Two properties ride on that:
+ // - `sameProjectSettingsContent` compares JSON.stringify output, which is key-ORDER sensitive.
+ // `prev` almost always comes from a parse (every save reads first), so a doc-first candidate
+ // would compare unequal to identical content and bump rev + rewrite a git-tracked file on
+ // every no-op save.
+ // - sanitizing here (not only at the callers) means a passed-back ProjectSettingsFileV1 — which
+ // structurally satisfies ProjectSettingsDoc — loses its stale version/rev/savedAt instead of
+ // overwriting the bookkeeping below, and no unsanitized byte ever reaches the user's repo.
+ const candidate: ProjectSettingsFileV1 = {
+ version: 1,
+ rev: (prev?.rev ?? 0) + 1,
+ savedAt,
+ ...sanitizeProjectSettingsDoc(doc)
+ }
if (prev && sameProjectSettingsContent(prev, candidate)) return prev
const file = projectSettingsPath(cwd)
await fs.mkdir(path.dirname(file), { recursive: true })
diff --git a/src/core/project-trust-store.test.ts b/src/core/project-trust-store.test.ts
index 567e5e6a5..ede5a11e3 100644
--- a/src/core/project-trust-store.test.ts
+++ b/src/core/project-trust-store.test.ts
@@ -39,6 +39,17 @@ describe('ProjectTrustStore', () => {
expect(await store.isTrusted(key, 'setup', hashTrustContent('npm ci && evil'))).toBe(false)
expect(await store.isTrusted(key, 'agents', hashTrustContent('npm ci'))).toBe(false)
})
+ it('getRecord answers the stored approval, or null when there is none', async () => {
+ const key = localTrustKey('/proj')
+ const hash = hashTrustContent('npm ci')
+ const store = new ProjectTrustStore()
+ expect(await store.getRecord(key, 'setup')).toBeNull()
+ await store.record(key, 'setup', hash, '2026-08-19T00:00:00Z')
+ expect(await store.getRecord(key, 'setup')).toEqual({ contentHash: hash, approvedAt: '2026-08-19T00:00:00Z' })
+ expect(await store.getRecord(key, 'agents')).toBeNull() // another family is not this one
+ expect(await store.getRecord(localTrustKey('/other'), 'setup')).toBeNull()
+ })
+
it('revoke drops one family or the whole key', async () => {
const key = localTrustKey('/proj')
const h = hashTrustContent('x')
diff --git a/src/core/project-trust-store.ts b/src/core/project-trust-store.ts
index b9fe208de..cb7c88e43 100644
--- a/src/core/project-trust-store.ts
+++ b/src/core/project-trust-store.ts
@@ -84,6 +84,25 @@ export class ProjectTrustStore {
return store[key]?.[family]?.contentHash === contentHash
}
+ /**
+ * The stored approval for one family, or null when there is none. For DIALOG COPY only — "you
+ * approved this on <date>, and it has changed since" — never as the basis of a grant: a caller
+ * deciding whether something may RUN asks `isTrusted`, which compares the hash itself.
+ *
+ * Mirrors `isTrusted`'s posture on a read failure (catch → null, nothing cached) rather than
+ * `record`/`revoke`'s (propagate): the same fail-closed answer as "no approval on file", which
+ * for this caller costs a re-prompt, never an unearned yes.
+ */
+ async getRecord(key: string, family: ProjectTrustFamily): Promise<ProjectTrustRecord | null> {
+ let store: TrustFile
+ try {
+ store = await this.load()
+ } catch {
+ return null
+ }
+ return store[key]?.[family] ?? null
+ }
+
async record(key: string, family: ProjectTrustFamily, contentHash: string, approvedAt: string): Promise<void> {
return this.mutate((store) => {
store[key] = { ...store[key], [family]: { contentHash, approvedAt } }
diff --git a/src/core/workspace-store.settings.test.ts b/src/core/workspace-store.settings.test.ts
index 3b2d8bec2..b595fd15f 100644
--- a/src/core/workspace-store.settings.test.ts
+++ b/src/core/workspace-store.settings.test.ts
@@ -58,6 +58,32 @@ describe('project settings — local leg', () => {
expect(onDisk.terminal.shell).toBe('/bin/bash')
})
+ it('re-saving identical content neither bumps rev nor rewrites the bytes', async () => {
+ const store = new WorkspaceStore()
+ await store.save(ws([project({ cwd: projRoot })]))
+ await store.writeProjectSettings('p1', { terminal: { shell: '/bin/zsh' } })
+ const file = path.join(projRoot, '.nodeterm', 'settings.json')
+ await store.readProjectSettings('p1') // the panel always reads before it saves
+ const before = await fs.readFile(file, 'utf-8')
+ expect(await store.writeProjectSettings('p1', { terminal: { shell: '/bin/zsh' } })).toBe(true)
+ // A no-op save must not churn a git-tracked file: same bytes, same rev.
+ expect(await fs.readFile(file, 'utf-8')).toBe(before)
+ expect(JSON.parse(before).rev).toBe(1)
+ })
+
+ it('re-reads before every write, so a file conflicted since the last read is left alone', async () => {
+ const store = new WorkspaceStore()
+ await store.save(ws([project({ cwd: projRoot })]))
+ await store.writeProjectSettings('p1', { terminal: { shell: '/bin/zsh' } })
+ await store.readProjectSettings('p1') // warms the rev source
+ const file = path.join(projRoot, '.nodeterm', 'settings.json')
+ // …and then a git pull leaves conflict markers behind our back.
+ const conflicted = '<<<<<<< a\n{}\n=======\n{}\n>>>>>>> b\n'
+ await fs.writeFile(file, conflicted, 'utf-8')
+ expect(await store.writeProjectSettings('p1', { terminal: { shell: '/bin/bash' } })).toBe(false)
+ expect(await fs.readFile(file, 'utf-8')).toBe(conflicted)
+ })
+
it('refuses to write over a git-conflicted settings.json, leaving the bytes untouched', async () => {
const store = new WorkspaceStore()
await store.save(ws([project({ cwd: projRoot })]))
@@ -250,9 +276,13 @@ describe('project settings — ssh leg', () => {
it('a write landing mid-read is not downgraded by the older doc that read was already fetching', async () => {
let release!: () => void
const gate = new Promise<void>((r) => { release = r })
+ // The FIRST call is the cold write's own read-before-write (the host has no file yet); only the
+ // read under test — the one racing the second write — waits on the gate.
+ let coldPreflight = true
const store = new WorkspaceStore({
...fakeIO,
readSettings: async () => {
+ if (coldPreflight) { coldPreflight = false; return { status: 'absent' as const } }
await gate
return { status: 'ok' as const, content: JSON.stringify(
{ version: 1, rev: 1, savedAt: 't', setup: { setupScript: 'remote-rev1' } }) }
@@ -302,6 +332,22 @@ describe('project settings — ssh leg', () => {
expect(s?.shared?.rev).toBe(4)
})
+ it('a cold store reads the host before its first ssh write, and refuses a conflict-marked file', async () => {
+ const writes: string[] = []
+ const conflicted = '<<<<<<< a\n{}\n=======\n{}\n>>>>>>> b\n'
+ const store = new WorkspaceStore({
+ ...fakeIO,
+ readSettings: async () => ({ status: 'ok' as const, content: conflicted }),
+ writeSettings: async (_id: string, _ssh: { remoteCwd: string }, content: string) => {
+ writes.push(content); return true
+ }
+ })
+ await store.save(ws([sshProject()]))
+ // Nothing has been read this run, so the runtime conflict flag is cold — the write must look.
+ expect(await store.writeProjectSettings('ps1', { setup: { setupScript: 'nope' } })).toBe(false)
+ expect(writes).toEqual([])
+ })
+
it('an ssh project with no remote IO at all still reads and writes its cache', async () => {
const store = new WorkspaceStore()
await store.save(ws([sshProject()]))
diff --git a/src/core/workspace-store.ts b/src/core/workspace-store.ts
index c97d90051..da1cfc1be 100644
--- a/src/core/workspace-store.ts
+++ b/src/core/workspace-store.ts
@@ -158,10 +158,12 @@ export class WorkspaceStore {
/** 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>()
- /** ssh project ids whose settings.json was git-conflict-marked on the last read, so a write must
- * refuse instead of picking a side of the merge (the local leg refuses the same way, straight off
- * the file). Cleared as soon as a read finds the file parsing again — or gone. Runtime-only: a
- * fresh run's first read re-establishes it before any write can be issued from the panel. */
+ /** ssh project ids whose settings.json was git-conflict-marked on the last read: `writeSshSettings`
+ * refuses while an id is in here instead of picking a side of the merge (the local leg refuses
+ * the same way, straight off the file it re-reads). Cleared as soon as a read finds the file
+ * parsing again — or gone. Runtime-only, and deliberately NOT relied on to be populated: a write
+ * that finds both settings maps cold does its own read first, because "a read established this
+ * flag before any write" is an assumption about panel order, not something this store enforces. */
private settingsConflictByProject = new Set<string>()
/** 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
@@ -573,10 +575,16 @@ export class WorkspaceStore {
* persisted into workspace.json; running it through the same sanitizer a read applies keeps one
* definition of "a valid settings file" whichever side the bytes came from.
*
- * REFUSES while the last read found the host's file git-conflict-marked, exactly like the local
- * leg refuses a conflicted settings.json: a conflicted file is the user's to resolve, and pushing
- * over it would silently pick a side of a merge nobody has looked at. The flag clears itself the
- * moment a read finds the file parsing (or gone).
+ * REFUSES a git-conflict-marked host file, exactly like the local leg refuses a conflicted
+ * settings.json: a conflicted file is the user's to resolve, and pushing over it would silently
+ * pick a side of a merge nobody has looked at. Two mechanisms enforce that, because the ssh leg
+ * cannot afford the local leg's read-before-every-write (a round trip per save):
+ * - WARM (this run has a cache or a last-read doc): the runtime flag a read left behind, which
+ * clears itself the moment a read finds the file parsing again — or gone.
+ * - COLD (neither map knows this project, so no read has ever compared): one read here, or the
+ * refusal would be a promise nothing checks — the first save of a session would blind-write
+ * the mirror over a merge. `absent` writes rev 1 as before; a read `error` proceeds
+ * cache-first, since being unable to reach the host is exactly what the cache exists for.
*/
private async writeSshSettings(
projectId: string,
@@ -584,14 +592,39 @@ export class WorkspaceStore {
doc: ProjectSettingsDoc
): Promise<boolean> {
if (this.settingsConflictByProject.has(projectId)) return false
- // `doc` spreads FIRST for the same reason writeProjectSettingsFile does it: a caller may hand
- // back a document it read, and its stale rev must not defeat monotonicity.
- const prev = this.settingsCacheByProject.get(projectId) ?? this.lastSharedSettings.get(projectId) ?? null
+ let prev = this.settingsCacheByProject.get(projectId) ?? this.lastSharedSettings.get(projectId) ?? null
+ if (!prev && this.remoteIO?.readSettings) {
+ // A throwing IO is an unreachable host, not a verdict on the file — same fail-open shape as
+ // `pushSshSettings`, and the cache-first write below is what makes that survivable.
+ let cold: RemoteReadResult = { status: 'error' }
+ try {
+ cold = await this.remoteIO.readSettings(projectId, ssh)
+ } catch { /* offline: fall through to the cache-first write */ }
+ if (cold.status === 'ok') {
+ const parsed = parseProjectSettingsFile(cold.content)
+ if (parsed.status === 'conflict') {
+ this.settingsConflictByProject.add(projectId)
+ return false
+ }
+ // `invalid` is left as prev=null: the host's bytes are unusable as a rev source, and the
+ // cache-first write is what gives the user a readable file again.
+ if (parsed.status === 'ok') {
+ prev = parsed.file
+ this.lastSharedSettings.set(projectId, parsed.file)
+ this.settingsConflictByProject.delete(projectId)
+ }
+ }
+ }
+ // Canonical shape (bookkeeping first, then the sanitized doc) — the same order
+ // `parseProjectSettingsFile` produces, so a cache built here compares equal to the identical
+ // document read back from the host instead of looking like a change. Sanitizing on the way in
+ // keeps one definition of "a valid settings file" whichever side the bytes came from, and drops
+ // the stale version/rev/savedAt of a document a caller hands straight back.
const next: ProjectSettingsFileV1 = {
- ...sanitizeProjectSettingsDoc(doc),
version: 1,
rev: (prev?.rev ?? 0) + 1,
- savedAt: new Date().toISOString()
+ savedAt: new Date().toISOString(),
+ ...sanitizeProjectSettingsDoc(doc)
}
this.settingsCacheByProject.set(projectId, next)
this.lastSharedSettings.set(projectId, next)
@@ -610,11 +643,13 @@ export class WorkspaceStore {
* 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.
*
- * READS FIRST when this run has never read the file. Without that, a fresh process writes with
- * `prev = null` — rev restarts at 1 over a file that was at rev N, and, worse, the write lands on
- * whatever is there, including the git-conflict-marked file `readProjectSettings` deliberately
- * refuses to parse. Same rule the project.json path already lives by: never write a file this
- * store has not looked at.
+ * ALWAYS READS FIRST — not just when this run has never read the file. A remembered rev is not
+ * evidence of the file's current STATE: `.nodeterm/settings.json` is git-tracked, so between the
+ * panel's read and the user's save a pull/merge can leave conflict markers, and a write off the
+ * warm rev would overwrite them (the same file `readProjectSettings` deliberately refuses to
+ * parse). Without any read a fresh process is worse still — rev restarts at 1 over a file that was
+ * at rev N. Settings are cold (a panel save, not a keystroke), so one read per write is the ruled
+ * cost of never writing a file this store has not just looked at.
*
* An ssh project takes the cache-first remote leg instead (`writeSshSettings`).
*
@@ -631,16 +666,14 @@ export class WorkspaceStore {
if (!e) return false
if (e.ssh) return this.writeSshSettings(projectId, e.ssh, doc)
if (!e.cwd) return false
- let prev = this.lastSharedSettings.get(projectId) ?? null
- if (!prev) {
- const read = await readProjectSettingsFile(e.cwd)
- // absent → nothing to lose, start at rev 1. invalid → the read already sidelined the only
- // copy to `.corrupt-<ts>`, so this write destroys nothing either.
- if (read.status === 'conflict' || read.status === 'error') return false
- if (read.status === 'ok') {
- prev = read.file
- this.lastSharedSettings.set(projectId, read.file)
- }
+ const read = await readProjectSettingsFile(e.cwd)
+ // absent → nothing to lose, start at rev 1. invalid → the read already sidelined the only
+ // copy to `.corrupt-<ts>`, so this write destroys nothing either.
+ if (read.status === 'conflict' || read.status === 'error') return false
+ let prev: ProjectSettingsFileV1 | null = null
+ if (read.status === 'ok') {
+ prev = read.file
+ this.lastSharedSettings.set(projectId, read.file)
}
try {
const written = await writeProjectSettingsFile(