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
feat(project-settings): ssh settings IO + offline cache reconcile
enesc15c9a22ef37
diff --git a/src/core/workspace-store.settings.test.ts b/src/core/workspace-store.settings.test.tsindex 3756064ab..1e4402fbc 100644--- a/src/core/workspace-store.settings.test.ts+++ b/src/core/workspace-store.settings.test.ts@@ -164,3 +164,94 @@ describe('project settings — local leg', () => {expect(s?.shared).toBeNull()})})++const remoteFs = new Map<string, string>()+const fakeIO = {+ read: async () => ({ status: 'absent' as const }),+ write: async () => true,+ readSettings: async (_id: string, ssh: { remoteCwd: string }) => {+ const c = remoteFs.get(ssh.remoteCwd + '/.nodeterm/settings.json')+ return c === undefined ? { status: 'absent' as const } : { status: 'ok' as const, content: c }+ },+ writeSettings: async (_id: string, ssh: { remoteCwd: string }, content: string) => {+ remoteFs.set(ssh.remoteCwd + '/.nodeterm/settings.json', content); return true+ }+}+const sshProject = () => project({ id: 'ps1', cwd: undefined, ssh: { server: { host: 'h', user: 'u' }, remoteCwd: '/srv/app' } })++describe('project settings — ssh leg', () => {+ beforeEach(() => remoteFs.clear())+ it('write lands in the cache AND on the remote; read adopts the higher remote rev', async () => {+ const store = new WorkspaceStore(fakeIO)+ await store.save(ws([sshProject()]))+ expect(await store.writeProjectSettings('ps1', { setup: { setupScript: 'make' } })).toBe(true)+ expect(remoteFs.get('/srv/app/.nodeterm/settings.json')).toContain('make')+ remoteFs.set('/srv/app/.nodeterm/settings.json', JSON.stringify(+ { version: 1, rev: 9, savedAt: 't', setup: { setupScript: 'newer-remote' } }))+ const s = await store.readProjectSettings('ps1')+ expect(s?.shared?.setup?.setupScript).toBe('newer-remote')+ })+ it('remote read failure serves the cache (offline)', async () => {+ const store = new WorkspaceStore({ ...fakeIO, readSettings: async () => ({ status: 'error' as const }) })+ await store.save(ws([sshProject()]))+ await store.writeProjectSettings('ps1', { setup: { setupScript: 'cached' } })+ const s = await store.readProjectSettings('ps1')+ expect(s?.shared?.setup?.setupScript).toBe('cached')+ })+ it('an absent remote file is healed from the cache on read', async () => {+ const store = new WorkspaceStore(fakeIO)+ await store.save(ws([sshProject()]))+ await store.writeProjectSettings('ps1', { setup: { setupScript: 'mine' } })+ remoteFs.clear()+ await store.readProjectSettings('ps1')+ expect(remoteFs.get('/srv/app/.nodeterm/settings.json')).toContain('mine')+ })+ it('settings cache survives a store reload via the index entry', async () => {+ const store = new WorkspaceStore(fakeIO)+ await store.save(ws([sshProject()]))+ await store.writeProjectSettings('ps1', { setup: { setupScript: 'persisted' } })+ const store2 = new WorkspaceStore({ ...fakeIO, readSettings: async () => ({ status: 'error' as const }) })+ await store2.load()+ const s = await store2.readProjectSettings('ps1')+ expect(s?.shared?.setup?.setupScript).toBe('persisted')+ })++ it('an offline edit (cache newer than the remote) is pushed back and wins the read', async () => {+ const store = new WorkspaceStore(fakeIO)+ await store.save(ws([sshProject()]))+ await store.writeProjectSettings('ps1', { setup: { setupScript: 'a' } }) // rev 1+ await store.writeProjectSettings('ps1', { setup: { setupScript: 'offline-edit' } }) // rev 2+ remoteFs.set('/srv/app/.nodeterm/settings.json', JSON.stringify(+ { version: 1, rev: 1, savedAt: 't', setup: { setupScript: 'stale-remote' } }))+ const s = await store.readProjectSettings('ps1')+ expect(s?.shared?.setup?.setupScript).toBe('offline-edit')+ expect(remoteFs.get('/srv/app/.nodeterm/settings.json')).toContain('offline-edit')+ })++ it('a conflict-marked remote file is reported as such and never overwritten', async () => {+ const store = new WorkspaceStore(fakeIO)+ await store.save(ws([sshProject()]))+ const conflicted = '<<<<<<< a\n{}\n=======\n{}\n>>>>>>> b\n'+ remoteFs.set('/srv/app/.nodeterm/settings.json', conflicted)+ const s = await store.readProjectSettings('ps1')+ expect(s?.conflict).toBe(true)+ expect(s?.shared).toBeNull()+ expect(remoteFs.get('/srv/app/.nodeterm/settings.json')).toBe(conflicted)+ })++ it('a remote write failure still keeps the edit (cache-first) and reports success', async () => {+ const store = new WorkspaceStore({ ...fakeIO, writeSettings: async () => false })+ await store.save(ws([sshProject()]))+ expect(await store.writeProjectSettings('ps1', { setup: { setupScript: 'kept' } })).toBe(true)+ const idx = JSON.parse(await fs.readFile(path.join(userData, 'workspace.json'), 'utf-8'))+ expect(idx.entries[0].settingsCache.setup.setupScript).toBe('kept')+ })++ 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()]))+ expect(await store.writeProjectSettings('ps1', { setup: { setupScript: 'no-io' } })).toBe(true)+ const s = await store.readProjectSettings('ps1')+ expect(s?.shared?.setup?.setupScript).toBe('no-io')+ })+})diff --git a/src/core/workspace-store.ts b/src/core/workspace-store.tsindex e22e0a146..12b57ff37 100644--- a/src/core/workspace-store.ts+++ b/src/core/workspace-store.ts@@ -14,7 +14,8 @@ import {} from './workspace-files'import { readProjectSettingsFile, writeProjectSettingsFile } from './project-settings-files'import {- parseProjectSettingsFile, sanitizeProjectLocalSettings,+ parseProjectSettingsFile, sameProjectSettingsContent, sanitizeProjectLocalSettings,+ sanitizeProjectSettingsDoc, serializeProjectSettingsFile,type ProjectLocalSettings, type ProjectSettingsDoc, type ProjectSettingsFileV1} from '../shared/project-settings'import { readProjectCapabilities, type ProjectCapability } from '../shared/project-capabilities'@@ -31,6 +32,11 @@ export type RemoteReadResult = { status: 'ok'; content: string } | { status: 'abexport interface RemoteWorkspaceIO {read(projectId: string, ssh: NonNullable<Project['ssh']>): Promise<RemoteReadResult>write(projectId: string, ssh: NonNullable<Project['ssh']>, content: string): Promise<boolean>+ /** `.nodeterm/settings.json` on the same host. Optional: an IO that predates the settings leg (or+ * a test fake that only cares about project.json) simply leaves the project on its offline cache,+ * which is exactly the disconnected behaviour. */+ readSettings?(projectId: string, ssh: NonNullable<Project['ssh']>): Promise<RemoteReadResult>+ writeSettings?(projectId: string, ssh: NonNullable<Project['ssh']>, content: string): Promise<boolean>}const projectFilePath = (cwd: string): string => path.join(cwd, PROJECT_DIR, PROJECT_FILE)@@ -41,7 +47,9 @@ const projectFilePath = (cwd: string): string => path.join(cwd, PROJECT_DIR, PROexport interface ProjectSettingsState {shared: ProjectSettingsFileV1 | nulllocal: ProjectLocalSettings | undefined- /** Shared file exists but is git-conflict-marked; `shared` is null until the user resolves it. */+ /** The shared file exists but is git-conflict-marked, so it is left untouched for the user to+ * resolve. `shared` is null for a local ref; for an ssh project the last-known-good offline cache+ * is still served alongside the flag (it is the only readable copy of that document). */conflict?: true}@@ -457,8 +465,7 @@ export class WorkspaceStore {const e = this.index?.entries.find((x) => x.id === projectId)if (!e) return nullconst 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 }+ if (e.ssh) return this.readSshSettings(projectId, e.ssh, 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)@@ -474,6 +481,105 @@ export class WorkspaceStore {return { shared: null, local } // absent / invalid (sidelined) / unreadable}+ /**+ * The ssh half of `readProjectSettings`: reconcile the host's settings.json against the offline+ * cache, then answer with whichever is authoritative. Same rules the project.json mirror lives by:+ *+ * - no settings IO / read `error` → serve the cache. A failed read is never evidence of absence,+ * so nothing is pushed and nothing is dropped; the project stays usable offline.+ * - `absent` → the host has no file; heal it from the cache (the mirror direction) and serve the+ * cache. Without a cache there is simply no shared document yet.+ * - `ok` → the bytes are HOSTILE INPUT (a git-shared file on a machine we do not control) and go+ * through `parseProjectSettingsFile` alone. The higher rev wins, ties to the host, so a+ * teammate's push is adopted rather than fought over, while a STRICTLY newer cache (this+ * machine edited while disconnected) is pushed back instead of being silently overwritten.+ * - `conflict`/`invalid` → the remote copy cannot be trusted and must not be clobbered; the cache+ * is served as the last known good, with `conflict` flagged so a caller can say "resolve this".+ */+ private async readSshSettings(+ projectId: string,+ ssh: NonNullable<Project['ssh']>,+ local: ProjectLocalSettings | undefined+ ): Promise<ProjectSettingsState> {+ const cached = this.settingsCacheByProject.get(projectId) ?? null+ const res = await this.remoteIO?.readSettings?.(projectId, ssh)+ if (!res || res.status === 'error') return { shared: cached, local }+ if (res.status === 'absent') {+ if (cached) await this.pushSshSettings(projectId, ssh, cached)+ return { shared: cached, local }+ }+ const parsed = parseProjectSettingsFile(res.content)+ if (parsed.status === 'conflict') return { shared: cached, local, conflict: true }+ if (parsed.status === 'invalid') return { shared: cached, local }+ const file = parsed.file+ if (cached && file.rev < cached.rev) {+ // Offline edits outrank the host's older copy — push them rather than letting the next read+ // adopt a document the user already replaced here.+ await this.pushSshSettings(projectId, ssh, cached)+ return { shared: cached, local }+ }+ this.lastSharedSettings.set(projectId, file)+ // Only persist when the cache actually moved: a read is the common case, and rewriting+ // workspace.json on every panel open would be a disk write per glance.+ if (!cached || cached.rev !== file.rev || !sameProjectSettingsContent(cached, file)) {+ this.settingsCacheByProject.set(projectId, file)+ await this.persistIndexNow().catch(() => {})+ }+ return { shared: file, local }+ }++ /** Best-effort mirror of one settings document to the host. A failure is not an error anywhere:+ * the cache is the durable copy and the next read reconciles (heal / push again). */+ private async pushSshSettings(+ projectId: string,+ ssh: NonNullable<Project['ssh']>,+ file: ProjectSettingsFileV1+ ): Promise<boolean> {+ const io = this.remoteIO+ if (!io?.writeSettings) return false+ try {+ return await io.writeSettings(projectId, ssh, serializeProjectSettingsFile(file))+ } catch {+ return false+ }+ }++ /**+ * The ssh half of `writeProjectSettings`, CACHE-FIRST: the rev-bumped document lands in the+ * offline cache and workspace.json BEFORE it is offered to the host, so a connection that dies+ * mid-save loses a round trip, never the user's edit. The remote write is then best-effort —+ * `true` here means "this edit is safely recorded", and an unreachable host is reconciled by the+ * next read (which heals an absent file and pushes a cache that outranks the remote).+ *+ * The doc is sanitized on the way in because this cache is served straight from memory and+ * 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.+ */+ private async writeSshSettings(+ projectId: string,+ ssh: NonNullable<Project['ssh']>,+ doc: ProjectSettingsDoc+ ): Promise<boolean> {+ // `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+ const next: ProjectSettingsFileV1 = {+ ...sanitizeProjectSettingsDoc(doc),+ version: 1,+ rev: (prev?.rev ?? 0) + 1,+ savedAt: new Date().toISOString()+ }+ this.settingsCacheByProject.set(projectId, next)+ this.lastSharedSettings.set(projectId, next)+ try {+ await this.persistIndexNow()+ } catch {+ return false // the edit is live in this session, but it did not durably land+ }+ await this.pushSshSettings(projectId, ssh, next)+ return true+ }+/*** 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@@ -486,14 +592,18 @@ export class WorkspaceStore {* refuses to parse. Same rule the project.json path already lives by: never write a file this* store has not looked at.*+ * An ssh project takes the cache-first remote leg instead (`writeSshSettings`).+ ** False = there is nowhere to write it, or writing would destroy something: an unknown id, an- * inline canvas (no folder), an ssh project (Task 7 gives it the remote leg), a conflicted file- * (the user's to resolve — untouched), an unreadable one (a failed read is never evidence of- * absence, so it may not be clobbered either), or a write that failed.+ * inline canvas (no folder), a conflicted file (the user's to resolve — untouched), an unreadable+ * one (a failed read is never evidence of absence, so it may not be clobbered either), or a write+ * that 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+ if (!e) return false+ if (e.ssh) return this.writeSshSettings(projectId, e.ssh, doc)+ if (!e.cwd) return falselet prev = this.lastSharedSettings.get(projectId) ?? nullif (!prev) {const read = await readProjectSettingsFile(e.cwd)diff --git a/src/main/remote-workspace-io.test.ts b/src/main/remote-workspace-io.test.tsindex fb7d9a87a..08d71a20f 100644--- a/src/main/remote-workspace-io.test.ts+++ b/src/main/remote-workspace-io.test.ts@@ -79,6 +79,57 @@ describe('write', () => {})})+/** The read fake above is declared param-less, so its recorded arguments need a cast to be read. */+const readPaths = (fs: ReturnType<typeof fakeFs>['fs']): string[] =>+ (fs.readTextChecked.mock.calls as unknown as [SshFsRef, string][]).map((c) => c[1])++describe('settings IO', () => {+ it('targets <remoteCwd>/.nodeterm/settings.json, not project.json', async () => {+ const { fs, sshFs } = fakeFs()+ const io = makeRemoteWorkspaceIO(() => ref, sshFs)+ await io.readSettings!('p1', ssh)+ await io.writeSettings!('p1', ssh, 'body')+ // project.json's own path is unchanged by the refactor.+ await io.read('p1', ssh)+ expect(readPaths(fs)).toEqual(['~/app/.nodeterm/settings.json', '~/app/.nodeterm/project.json'])+ expect(fs.writeText.mock.calls[0][1]).toBe('~/app/.nodeterm/settings.json')+ })++ it('is NOT throttled: settings are cold, so two writes in a row both hit the wire', async () => {+ const { fs, sshFs } = fakeFs()+ const io = makeRemoteWorkspaceIO(() => ref, sshFs)+ expect(await io.writeSettings!('p1', ssh, 'c1')).toBe(true)+ expect(await io.writeSettings!('p1', ssh, 'c2')).toBe(true)+ expect(fs.writeText.mock.calls.map((c) => c[2])).toEqual(['c1', 'c2'])+ })++ it('disconnected → read errors (never absent) and the write is a quiet no-op', async () => {+ const { fs, sshFs } = fakeFs()+ const io = makeRemoteWorkspaceIO(() => null, sshFs)+ expect(await io.readSettings!('p1', ssh)).toEqual({ status: 'error' })+ expect(await io.writeSettings!('p1', ssh, 'c1')).toBe(false)+ expect(fs.writeText).not.toHaveBeenCalled()+ })++ it('a throwing settings write reports false instead of rejecting', async () => {+ const { fs, sshFs } = fakeFs()+ const io = makeRemoteWorkspaceIO(() => ref, sshFs)+ fs.writeText.mockRejectedValueOnce(new Error('conn reset'))+ expect(await io.writeSettings!('p1', ssh, 'c1')).toBe(false)+ })++ it('a settings write does not disturb project.json throttling', async () => {+ const { fs, sshFs } = fakeFs()+ const io = makeRemoteWorkspaceIO(() => ref, sshFs)+ await io.write('p1', ssh, 'p1-immediate')+ await io.writeSettings!('p1', ssh, 'settings')+ await io.write('p1', ssh, 'p1-trailing') // still inside the 5s window+ expect(fs.writeText.mock.calls.map((c) => c[2])).toEqual(['p1-immediate', 'settings'])+ await vi.advanceTimersByTimeAsync(5000)+ expect(fs.writeText.mock.calls.map((c) => c[2])).toEqual(['p1-immediate', 'settings', 'p1-trailing'])+ })+})+describe('flush', () => {it('fires every pending trailing write immediately (quit path: masters die right after)', async () => {const { fs, sshFs } = fakeFs()diff --git a/src/main/remote-workspace-io.ts b/src/main/remote-workspace-io.tsindex c2a7a26e2..032092de7 100644--- a/src/main/remote-workspace-io.ts+++ b/src/main/remote-workspace-io.ts@@ -2,6 +2,7 @@ import path from 'path'import type { Project } from '../shared/types'import type { RemoteReadResult, RemoteWorkspaceIO } from '../core/workspace-store'import { PROJECT_DIR, PROJECT_FILE } from '../core/workspace-files'+import { PROJECT_SETTINGS_FILE } from '../shared/project-settings'import type { SshFs, SshFsRef } from './ssh-fs'/** Resolves an SSH project's live control master; null while disconnected. */@@ -21,6 +22,10 @@ export interface RemoteWorkspaceIOWithFlush extends RemoteWorkspaceIO {* round-trip per keystroke burst is still too chatty — spec says ~5 s). A throttled write is* acked optimistically; if the trailing run later fails, `onDropped` reports it back so the* store re-owes the mirror instead of believing it landed.+ *+ * The settings pair (`readSettings`/`writeSettings`, `.nodeterm/settings.json`) rides the same+ * connection but NOT the throttle — see `writeSettings`. `flush()` therefore still covers only+ * project.json's pending writes: a settings write has already been on the wire when it returns.*/export function makeRemoteWorkspaceIO(resolveRef: RefResolver,@@ -31,14 +36,14 @@ export function makeRemoteWorkspaceIO(const pending = new Map<string, { timer: ReturnType<typeof setTimeout>; run: () => Promise<void> }>()const WRITE_THROTTLE_MS = 5000- const remotePath = (ssh: NonNullable<Project['ssh']>): string =>- path.posix.join(ssh.remoteCwd, PROJECT_DIR, PROJECT_FILE)+ const remotePath = (ssh: NonNullable<Project['ssh']>, file: string): string =>+ path.posix.join(ssh.remoteCwd, PROJECT_DIR, file)return {async read(projectId, ssh): Promise<RemoteReadResult> {const ref = resolveRef(projectId)if (!ref) return { status: 'error' }- return sshFs.readTextChecked(ref, remotePath(ssh))+ return sshFs.readTextChecked(ref, remotePath(ssh, PROJECT_FILE))},async write(projectId, ssh, content) {const run = async (): Promise<boolean> => {@@ -48,7 +53,7 @@ export function makeRemoteWorkspaceIO(const ref = resolveRef(projectId)if (!ref) return falsetry {- return await sshFs.writeText(ref, remotePath(ssh), content)+ return await sshFs.writeText(ref, remotePath(ssh, PROJECT_FILE), content)} catch {return false}@@ -74,6 +79,25 @@ export function makeRemoteWorkspaceIO(pending.set(projectId, { timer: setTimeout(() => void fire(), WRITE_THROTTLE_MS - since), run: fire })return true},+ async readSettings(projectId, ssh): Promise<RemoteReadResult> {+ const ref = resolveRef(projectId)+ if (!ref) return { status: 'error' }+ return sshFs.readTextChecked(ref, remotePath(ssh, PROJECT_SETTINGS_FILE))+ },+ // Deliberately NOT throttled, and deliberately not sharing project.json's throttle bookkeeping:+ // the 5 s window exists for canvas churn (a node dragged across the screen), while a settings+ // save is a cold, user-initiated act. Delaying or reordering one behind a canvas write would+ // make "Save" mean "maybe, in five seconds" — so this goes straight to the wire and reports the+ // real outcome. The store's cache-first write already makes a false here non-fatal.+ async writeSettings(projectId, ssh, content) {+ const ref = resolveRef(projectId)+ if (!ref) return false+ try {+ return await sshFs.writeText(ref, remotePath(ssh, PROJECT_SETTINGS_FILE), content)+ } catch {+ return false+ }+ },async flush() {const flushed = [...pending.values()]for (const p of flushed) clearTimeout(p.timer)