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): mirror SSH project files to the server + reconcile on connect

enesa42b0ec2cee7
diff --git a/src/core/workspace-store.test.ts b/src/core/workspace-store.test.ts
index 891ad52c1..d4094398e 100644
--- a/src/core/workspace-store.test.ts
+++ b/src/core/workspace-store.test.ts
@@ -182,3 +182,52 @@ describe('readLocalRefByPath', () => {
expect(await store.readLocalRefByPath(path.join(projRoot, 'nope/project.json'))).toBeNull()
})
})
+
+describe('refreshSshProject', () => {
+ const sshConn = { server: { host: 'h', user: 'u' } as any, remoteCwd: '~/app' }
+ const remoteFileOf = async (store: WorkspaceStore, p: Project) => {
+ // seed: one ssh project saved → cache rev 1
+ await store.save(ws([p]))
+ }
+
+ it('remote rev > cache rev → adopts remote and reports it', async () => {
+ const remote: Record<string, string> = {}
+ const io = {
+ read: async (id: string) => remote[id] ?? null,
+ write: async (id: string, _s: any, c: string) => ((remote[id] = c), true)
+ }
+ const store = new WorkspaceStore(io)
+ const p = project({ id: 'ps', ssh: sshConn, cwd: undefined })
+ await remoteFileOf(store, p) // cache rev 1, mirrored to remote
+ const newer = JSON.parse(remote['ps'])
+ newer.rev = 5; newer.name = 'server-renamed'
+ remote['ps'] = JSON.stringify(newer)
+ const adopted = await store.refreshSshProject('ps')
+ expect(adopted).toMatchObject({ id: 'ps', name: 'server-renamed' })
+ })
+
+ it('cache rev >= remote rev → pushes the cache up instead and returns null', async () => {
+ const remote: Record<string, string> = {}
+ const writes: string[] = []
+ const io = {
+ read: async (id: string) => remote[id] ?? null,
+ write: async (id: string, _s: any, c: string) => (writes.push(id), (remote[id] = c), true)
+ }
+ const store = new WorkspaceStore(io)
+ await remoteFileOf(store, project({ id: 'ps', ssh: sshConn, cwd: undefined }))
+ const older = JSON.parse(remote['ps'])
+ older.rev = 0
+ remote['ps'] = JSON.stringify(older)
+ expect(await store.refreshSshProject('ps')).toBeNull()
+ expect(writes.filter((w) => w === 'ps').length).toBeGreaterThanOrEqual(2) // seed + push-up
+ })
+
+ it('no remote file yet → pushes the cache up (first machine wins)', async () => {
+ const remote: Record<string, string> = {}
+ const io = { read: async () => null, write: async (id: string, _s: any, c: string) => ((remote[id] = c), true) }
+ const store = new WorkspaceStore(io)
+ await remoteFileOf(store, project({ id: 'ps', ssh: sshConn, cwd: undefined }))
+ expect(await store.refreshSshProject('ps')).toBeNull()
+ expect(remote['ps']).toContain('"id": "ps"')
+ })
+})
diff --git a/src/core/workspace-store.ts b/src/core/workspace-store.ts
index 0b6fddbcf..9c7945131 100644
--- a/src/core/workspace-store.ts
+++ b/src/core/workspace-store.ts
@@ -223,8 +223,30 @@ export class WorkspaceStore {
return e ? this.readLocalRef(e.id) : null
}
- /** SSH refresh-on-connect — wired in Task 8. */
- async refreshSshProject(_projectId: string): Promise<Project | null> {
+ /**
+ * Called when an SSH project's connection comes up. Reconciles the server's
+ * .nodeterm/project.json with our cached copy by rev: higher remote rev → adopt
+ * remote (returned; caller broadcasts it); otherwise → push our cache up.
+ */
+ async refreshSshProject(projectId: string): Promise<Project | null> {
+ const e = this.index?.entries.find((x) => x.id === projectId && x.ssh)
+ if (!e?.ssh || !this.remoteIO) return null
+ const raw = await this.remoteIO.read(projectId, e.ssh)
+ let remote: ProjectFileV1 | null = null
+ if (raw) {
+ try {
+ const parsed = JSON.parse(raw) as ProjectFileV1
+ if (parsed?.version === 1 && Array.isArray(parsed.nodes)) remote = parsed
+ } catch { /* corrupt remote file → treat as absent, our cache pushes up */ }
+ }
+ const cacheRev = e.cache?.rev ?? 0
+ if (remote && remote.rev > cacheRev) {
+ e.cache = remote
+ this.revs.set(projectId, remote.rev)
+ await writeAtomic(this.indexPath, JSON.stringify(this.index))
+ return fileToProject(remote, { ssh: e.ssh, closed: e.closed })
+ }
+ if (e.cache) void this.remoteIO.write(projectId, e.ssh, serializeProjectFile(e.cache))
return null
}
}
diff --git a/src/main/index.ts b/src/main/index.ts
index db31d11cc..7389b864e 100644
--- a/src/main/index.ts
+++ b/src/main/index.ts
@@ -62,6 +62,7 @@ import { initRemoteClient } from './remote/client-service'
import { initSshProject } from './remote-ssh/ssh-project'
import { setGitRemoteResolver, type GitRemoteRef } from '../core/remote-ssh/remote-git'
import { SshFs } from './ssh-fs'
+import { makeRemoteWorkspaceIO } from './remote-workspace-io'
import {
registerMediaScheme,
initMediaProtocol,
@@ -98,7 +99,18 @@ function isSafeExternalUrl(url: unknown): url is string {
const settingsStore = new SettingsStore()
const sshStore = new SshStore()
const ptyManager = new PtyManager()
-const workspaceStore = new WorkspaceStore()
+// Set once the app window is ready; used by the quit hooks to tear down SSH-project masters and
+// (via the closures below) to resolve a live SSH project's ControlMaster for remote workspace IO.
+let sshProjectManager: ReturnType<typeof initSshProject> | undefined
+// Remote SSH IO for the workspace store: mirrors each SSH project's <remoteCwd>/.nodeterm/project.json
+// over that project's live master. Resolves the ref lazily — the manager is created after the window
+// is ready — and fails open (no-op) while the project is disconnected.
+const workspaceSshFs = new SshFs((args, stdin) =>
+ sshProjectManager ? sshProjectManager.sshRun(args, stdin) : Promise.resolve({ code: 1, stdout: '' })
+)
+const workspaceStore = new WorkspaceStore(
+ makeRemoteWorkspaceIO((projectId) => sshProjectManager?.refForProject(projectId) ?? null, workspaceSshFs)
+)
// Watch each local ref's project.json for outside edits (git pull, a teammate's commit).
// Self-writes match the store's last-written cache and are ignored. Re-synced after every
// store load/save via onPersist; disposed on quit next to ptyManager.killAll().
@@ -116,8 +128,6 @@ const gitService = new GitService()
// One driver for all chat nodes. Resolves the live window at send time (getMainWindow) so
// pushes survive a macOS close→dock-reopen; disposed on quit next to ptyManager.killAll().
const chatDriver = new ChatDriver(getMainWindow, sendToMain)
-// Set once the app window is ready; used by the quit hooks to tear down SSH-project masters.
-let sshProjectManager: ReturnType<typeof initSshProject> | undefined
// Markers delimiting the `projects.list` relay blob. The iOS client splits on these exact
// strings to recover [workspace.json | newline-joined tmux session names | agent-status.json],
@@ -887,7 +897,14 @@ app.whenReady().then(async () => {
// Reconcile from persisted settings on launch (starts hosting if enabled + Pro).
standingHost.syncFromSettings()
initRemoteClient(win, { isPackaged: app.isPackaged })
- sshProjectManager = initSshProject(win)
+ sshProjectManager = initSshProject(win, (projectId) => {
+ // On (re)connect, reconcile the server's .nodeterm/project.json with our offline cache by rev.
+ // A non-null result means the remote won → adopt it in the renderer (Task 7's listener does the
+ // silent replace / conflict bar). null means our cache was pushed up instead — nothing to send.
+ void workspaceStore.refreshSshProject(projectId).then((adopted) => {
+ if (adopted) sendToMain(IPC.workspaceExternalChange, adopted)
+ })
+ })
// Route git-service + commit-message git ops over the active SSH project's master only — and only
// for that project's exact remoteCwd. Any other cwd (a local project, or a different connected
// project) resolves to undefined, so the local path stays byte-identical.
diff --git a/src/main/remote-ssh/ssh-project.ts b/src/main/remote-ssh/ssh-project.ts
index fafe0e550..175584467 100644
--- a/src/main/remote-ssh/ssh-project.ts
+++ b/src/main/remote-ssh/ssh-project.ts
@@ -411,7 +411,10 @@ export class SshProjectManager {
}
}
-export function initSshProject(win: BrowserWindow): SshProjectManager {
+export function initSshProject(
+ win: BrowserWindow,
+ onConnected?: (projectId: string) => void
+): SshProjectManager {
const ssh = sshBin()
const scp = scpBin()
const mgr = new SshProjectManager({
@@ -440,9 +443,13 @@ export function initSshProject(win: BrowserWindow): SshProjectManager {
if (!win.isDestroyed()) win.webContents.send(IPC.sshProjectStatus, e)
}
})
- ipcMain.handle(IPC.sshConnectProject, (_e, projectId: string, conn: SshConnection, remoteCwd?: string) =>
- mgr.connect(projectId, conn, remoteCwd)
- )
+ ipcMain.handle(IPC.sshConnectProject, async (_e, projectId: string, conn: SshConnection, remoteCwd?: string) => {
+ const res = await mgr.connect(projectId, conn, remoteCwd)
+ // Connection is up (master in the map) → reconcile the remote project file with our cache.
+ // Only fires on a successful connect; a throw above propagates without calling back.
+ onConnected?.(projectId)
+ return res
+ })
ipcMain.handle(IPC.sshDisconnectProject, (_e, projectId: string) => mgr.disconnect(projectId))
ipcMain.handle(IPC.sshKillSessions, (_e, projectId: string, nodeIds: string[]) =>
mgr.killSessions(projectId, nodeIds)
diff --git a/src/main/remote-workspace-io.ts b/src/main/remote-workspace-io.ts
new file mode 100644
index 000000000..bfc2437e9
--- /dev/null
+++ b/src/main/remote-workspace-io.ts
@@ -0,0 +1,53 @@
+import path from 'path'
+import type { Project } from '../shared/types'
+import type { RemoteWorkspaceIO } from '../core/workspace-store'
+import { PROJECT_DIR, PROJECT_FILE } from '../core/workspace-files'
+import type { SshFs, SshFsRef } from './ssh-fs'
+
+/** Resolves an SSH project's live control master; null while disconnected. */
+type RefResolver = (projectId: string) => SshFsRef | null
+
+/**
+ * Remote .nodeterm IO over the project's existing ControlMaster. Fail-open: while the
+ * project is disconnected every call is a quiet no-op (read null / write false) — the
+ * cache in workspace.json keeps the project usable offline. Writes are throttled per
+ * project (the renderer already debounces at 800 ms; a remote round-trip per keystroke
+ * burst is still too chatty — spec says ~5 s).
+ */
+export function makeRemoteWorkspaceIO(resolveRef: RefResolver, sshFs: SshFs): RemoteWorkspaceIO {
+ const lastWrite = new Map<string, number>()
+ const pending = new Map<string, ReturnType<typeof setTimeout>>()
+ const WRITE_THROTTLE_MS = 5000
+
+ const remotePath = (ssh: NonNullable<Project['ssh']>): string =>
+ path.posix.join(ssh.remoteCwd, PROJECT_DIR, PROJECT_FILE)
+
+ return {
+ async read(projectId, ssh) {
+ const ref = resolveRef(projectId)
+ if (!ref) return null
+ const text = await sshFs.readText(ref, remotePath(ssh))
+ return text || null
+ },
+ async write(projectId, ssh, content) {
+ const ref = resolveRef(projectId)
+ if (!ref) return false
+ const run = async () => {
+ lastWrite.set(projectId, Date.now())
+ await sshFs.writeText(ref, remotePath(ssh), content)
+ }
+ const since = Date.now() - (lastWrite.get(projectId) ?? 0)
+ if (since >= WRITE_THROTTLE_MS) {
+ // Cancel any pending trailing write so a stale older payload can't fire AFTER this newer
+ // one and clobber the final state (final-state-wins).
+ clearTimeout(pending.get(projectId))
+ pending.delete(projectId)
+ await run()
+ } else {
+ clearTimeout(pending.get(projectId))
+ pending.set(projectId, setTimeout(() => void run(), WRITE_THROTTLE_MS - since))
+ }
+ return true
+ }
+ }
+}