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(workspace): headless folder adoption by real path for team bootstrap
review8c5fe83723f6
diff --git a/src/core/workspace-store.adopt.test.ts b/src/core/workspace-store.adopt.test.tsnew file mode 100644index 000000000..34fb9bcaf--- /dev/null+++ b/src/core/workspace-store.adopt.test.ts@@ -0,0 +1,124 @@+import { describe, it, expect, beforeEach, afterEach } from 'vitest'+import fs from 'node:fs'+import os from 'node:os'+import path from 'node:path'+import { initPlatform, resetPlatformForTests } from './platform'+import { fakePlatform } from './platform-fake'+import { WorkspaceStore } from './workspace-store'+import type { Project } from '../shared/types'++let dir: string+let store: WorkspaceStore+beforeEach(() => {+ dir = fs.mkdtempSync(path.join(os.tmpdir(), 'nt-adopt-'))+ const userData = path.join(dir, 'data')+ fs.mkdirSync(userData)+ initPlatform(fakePlatform({ userDataDir: userData }))+ store = new WorkspaceStore()+})+afterEach(() => {+ resetPlatformForTests()+ fs.rmSync(dir, { recursive: true, force: true })+})++const folder = (name: string): string => {+ const f = path.join(dir, name)+ fs.mkdirSync(f, { recursive: true })+ return f+}+const writeProjectFile = (cwd: string, nodes: unknown[]): void => {+ fs.mkdirSync(path.join(cwd, '.nodeterm'), { recursive: true })+ fs.writeFileSync(+ path.join(cwd, '.nodeterm', 'project.json'),+ JSON.stringify({ version: 1, name: 'Shared', color: '#0a84ff', rev: 3, nodes })+ )+}+const emptyProject = (id: string, name: string, cwd: string): Project =>+ ({ id, name, color: '#7aa2f7', cwd, viewport: { x: 0, y: 0, zoom: 1 }, nodes: [] })++describe('WorkspaceStore.adoptFolder', () => {+ it('a folder with no project file becomes an empty project named after the folder, saved', async () => {+ const f = folder('alpha')+ const r = await store.adoptFolder(f, { home: dir })+ expect(r.created).toBe(true)+ expect(r.projectName).toBe('alpha')+ const ws = await store.load({ sideline: false })+ expect(ws.projects.map((p) => p.id)).toContain(r.projectId)+ expect(await store.readProjectContent(r.projectId)).not.toBeNull() // the authority can read it now+ })++ it('an existing project.json keeps its node ids and content, gets a fresh project id, and its ~ cwds expand', async () => {+ const f = folder('beta')+ writeProjectFile(f, [+ { id: 'term-a.1', kind: 'terminal', position: { x: 1, y: 2 }, title: 'A', color: '#fff', cwd: '~/beta', sshRemoteTmux: true, agentId: 'claude' }+ ])+ const r = await store.adoptFolder(f, { home: '/home/u' })+ expect(r.created).toBe(true)+ expect(r.projectId).toMatch(/^project-/)+ const p = (await store.load({ sideline: false })).projects.find((x) => x.id === r.projectId)!+ expect(p.nodes.map((n) => n.id)).toEqual(['term-a.1'])+ expect(p.nodes[0].cwd).toBe('/home/u/beta')+ expect(p.nodes[0].sshRemoteTmux).toBeUndefined()+ expect(p.cwd).toBe(fs.realpathSync(f))+ })++ // Symlinks need a privilege a stock Windows account does not hold; the real-path rule itself is+ // platform-neutral, and the feature it serves (a Linux host's server) never runs there.+ it.skipIf(process.platform === 'win32')('the same folder again — by any path that resolves to it — reuses the id (created:false)', async () => {+ const f = folder('gamma')+ const link = path.join(dir, 'gamma-link')+ fs.symlinkSync(f, link)+ const a = await store.adoptFolder(f, { home: dir })+ const b = await store.adoptFolder(link, { home: dir })+ expect(b).toEqual({ projectId: a.projectId, projectName: a.projectName, created: false })+ expect((await store.load({ sideline: false })).projects.filter((p) => p.cwd === fs.realpathSync(f))).toHaveLength(1)+ })++ // Same reason as above. The other direction: the index holds the folder by a symlinked path (a+ // browser opened it that way), and the real path must still find it.+ it.skipIf(process.platform === 'win32')('reuses a project the index already holds under a path that resolves to the same folder', async () => {+ const f = folder('theta')+ const link = path.join(dir, 'theta-link')+ fs.symlinkSync(f, link)+ await store.save({ version: 2, activeProjectId: 'p-l', projects: [emptyProject('p-l', 'theta', link)] })+ const r = await store.adoptFolder(f, { home: dir })+ expect(r).toEqual({ projectId: 'p-l', projectName: 'theta', created: false })+ expect((await store.load({ sideline: false })).projects).toHaveLength(1)+ })++ it('runs on the save chain: a save queued before it is part of the workspace it writes', async () => {+ const a = folder('zeta')+ const b = folder('eta')+ const saving = store.save({ version: 2, activeProjectId: 'p-a', projects: [emptyProject('p-a', 'zeta', a)] })+ const r = await store.adoptFolder(b, { home: dir })+ await saving+ const ids = (await store.load({ sideline: false })).projects.map((p) => p.id)+ expect(ids).toEqual(['p-a', r.projectId])+ })++ it('E_BAD_CWD for a relative, missing or non-directory path', async () => {+ await expect(store.adoptFolder('rel/x', { home: dir })).rejects.toMatchObject({ code: 'E_BAD_CWD' })+ await expect(store.adoptFolder(path.join(dir, 'nope'), { home: dir })).rejects.toMatchObject({ code: 'E_BAD_CWD' })+ const file = path.join(dir, 'file.txt')+ fs.writeFileSync(file, 'x')+ await expect(store.adoptFolder(file, { home: dir })).rejects.toMatchObject({ code: 'E_BAD_CWD' })+ })++ it('E_ADOPT_FAILED for a corrupt project file, which is left in place (never sidelined, never adopted empty)', async () => {+ const f = folder('delta')+ fs.mkdirSync(path.join(f, '.nodeterm'))+ fs.writeFileSync(path.join(f, '.nodeterm', 'project.json'), '{ not json')+ await expect(store.adoptFolder(f, { home: dir })).rejects.toMatchObject({ code: 'E_ADOPT_FAILED' })+ expect(fs.readFileSync(path.join(f, '.nodeterm', 'project.json'), 'utf8')).toBe('{ not json')+ })++ it('a closed adopted project is reopened when adopted again', async () => {+ const f = folder('eps')+ const a = await store.adoptFolder(f, { home: dir })+ const ws = await store.load({ sideline: false })+ ws.projects.find((p) => p.id === a.projectId)!.closed = true+ await store.save(ws)+ await store.adoptFolder(f, { home: dir })+ expect((await store.load({ sideline: false })).projects.find((p) => p.id === a.projectId)!.closed).toBeFalsy()+ })+})diff --git a/src/core/workspace-store.ts b/src/core/workspace-store.tsindex 89dc5bdab..3d2a581c7 100644--- a/src/core/workspace-store.ts+++ b/src/core/workspace-store.ts@@ -37,6 +37,18 @@ import {import { appendProjectNode, removeProjectNode, type RemoteNodeInput } from './project-node-append'import { editProjectCardLabels, ensureProjectBoard, setProjectCardColumn, type CardLabelEdit } from './project-kanban-write'import { boardLabels, cardMeta } from '../shared/kanban-labels'+import { localizeAdoptedNode } from '../shared/adopt-cwd'+import { clampProjectName, folderName } from '../shared/project-name'+import { SYSTEM_NODE_COLORS } from '../shared/node-colors'+import { codedError } from './relay/admin-error'++/** What `WorkspaceStore.adoptFolder` did: the project now holding the folder, and whether this call+ * added it (`created: false` = an existing project already held the same real directory). */+export interface AdoptFolderResult {+ projectId: string+ projectName: string+ created: boolean+}/*** The seam a content authority (the Server Edition's canvas authority, `core/canvas-authority.ts`)@@ -1640,6 +1652,76 @@ export class WorkspaceStore {}}+ /**+ * HEADLESS adoption (`team bootstrap`): add the folder at `cwd` as a project of this core and+ * save it, so the canvas authority can read it before it is shared. One project per REAL path:+ * an entry whose folder resolves to the same directory is reused, never duplicated, because the+ * desktop names the folder by whatever path it holds and a symlink must not mint a second+ * project. A reused project that was closed is reopened. A folder with a project file is adopted+ * with `probeFolder` semantics (fresh project id, node ids kept — they are tmux session names).+ * One without becomes an empty project named after the folder. A file that is present but cannot+ * be read is a refusal, never an empty project: that would overwrite the only copy on the next+ * save (see `projectFileState`). Nothing here sidelines a corrupt file either — it is left in+ * place for the user to fix.+ *+ * `home` expands the SSH project's `~` node cwds (`localizeAdoptedNode`). The server runs as the+ * same user the desktop logged in as, so the home is the same.+ *+ * The whole read-modify-write runs ON `saveChain`: a save queued meanwhile would otherwise write+ * an index built before this project existed over the one that adds it.+ */+ adoptFolder(cwd: string, opts: { home: string }): Promise<AdoptFolderResult> {+ const run = this.saveChain.then(() => this.adoptFolderNow(cwd, opts))+ this.saveChain = run.catch(() => {})+ return run+ }++ private async adoptFolderNow(cwd: string, opts: { home: string }): Promise<AdoptFolderResult> {+ if (!path.isAbsolute(cwd)) throw codedError('E_BAD_CWD', `Not an absolute path: ${cwd}`)+ let real: string+ try {+ real = await fs.realpath(cwd)+ if (!(await fs.stat(real)).isDirectory()) throw new Error('not a directory')+ } catch {+ throw codedError('E_BAD_CWD', `Not a directory on this host: ${cwd}`)+ }+ // `load` does not queue on `saveChain`, so calling it from this chain step cannot deadlock.+ // Read-only (no sideline): adoption must not rename some OTHER project's conflict-marked file.+ const workspace = structuredClone(await this.load({ sideline: false }))+ for (const p of workspace.projects) {+ if (!p.cwd || p.ssh) continue+ const theirs = await fs.realpath(p.cwd).catch(() => p.cwd as string)+ if (theirs !== real) continue+ if (p.closed) {+ p.closed = false+ delete p.closedAt+ await this.saveNow(workspace, false)+ }+ return { projectId: p.id, projectName: p.name, created: false }+ }+ const state = await this.projectFileState(real)+ if (state === 'unreadable') throw codedError('E_ADOPT_FAILED', `Could not read ${projectFilePath(real)}.`)+ let project: Project+ if (state === 'present') {+ const probed = await this.probeFolder(real)+ if (!probed) throw codedError('E_ADOPT_FAILED', `${projectFilePath(real)} is not a project file this server can read.`)+ project = { ...probed, nodes: probed.nodes.map((n) => localizeAdoptedNode(n, opts.home)) }+ } else {+ project = {+ id: freshProjectId(),+ name: clampProjectName(folderName(real)) || 'Project',+ color: SYSTEM_NODE_COLORS[workspace.projects.length % SYSTEM_NODE_COLORS.length],+ cwd: real,+ viewport: { x: 0, y: 0, zoom: 1 },+ nodes: []+ }+ }+ workspace.projects.push(project)+ if (!workspace.activeProjectId) workspace.activeProjectId = project.id+ await this.saveNow(workspace, false)+ return { projectId: project.id, projectName: project.name, created: true }+ }+localRefPaths(): string[] {return (this.index?.entries ?? []).filter((e) => e.cwd).map((e) => projectFilePath(e.cwd!))}diff --git a/src/shared/adopt-cwd.test.ts b/src/shared/adopt-cwd.test.tsnew file mode 100644index 000000000..62f2dca45--- /dev/null+++ b/src/shared/adopt-cwd.test.ts@@ -0,0 +1,37 @@+import { describe, it, expect } from 'vitest'+import { expandHomeCwd, localizeAdoptedNode } from './adopt-cwd'+import type { CanvasNodeState } from './types'++const node = (o: Partial<CanvasNodeState>): CanvasNodeState =>+ ({ id: 'term-1', kind: 'terminal', position: { x: 0, y: 0 }, title: 'T', color: '#fff', ...o }) as CanvasNodeState++describe('expandHomeCwd', () => {+ it('expands ~ and ~/x against home, leaves everything else alone', () => {+ expect(expandHomeCwd('~', '/home/u')).toBe('/home/u')+ expect(expandHomeCwd('~/p/x', '/home/u')).toBe('/home/u/p/x')+ expect(expandHomeCwd('~/', '/home/u')).toBe('/home/u')+ expect(expandHomeCwd('/srv/x', '/home/u')).toBe('/srv/x')+ expect(expandHomeCwd('~other/x', '/home/u')).toBe('~other/x') // another user's home is not ours to guess+ expect(expandHomeCwd('./rel', '/home/u')).toBe('./rel')+ })+})++describe('localizeAdoptedNode', () => {+ it('drops the SSH-session flags so a local core spawns it locally, and expands its cwd', () => {+ const out = localizeAdoptedNode(+ node({ cwd: '~/proj', sshRemoteTmux: true, ssh: { host: 'h', user: 'u' } as never }),+ '/home/u'+ )+ expect(out.cwd).toBe('/home/u/proj')+ expect(out.sshRemoteTmux).toBeUndefined()+ expect(out.ssh).toBeUndefined()+ })+ it('keeps a plain `ssh <host>` node (no sshRemoteTmux): its ssh is a pty program, not a session', () => {+ const ssh = { host: 'h', user: 'u' } as never+ expect(localizeAdoptedNode(node({ ssh }), '/home/u').ssh).toBe(ssh)+ })+ it('returns the same object when nothing changes', () => {+ const n = node({ cwd: '/abs' })+ expect(localizeAdoptedNode(n, '/home/u')).toBe(n)+ })+})diff --git a/src/shared/adopt-cwd.ts b/src/shared/adopt-cwd.tsnew file mode 100644index 000000000..53b495589--- /dev/null+++ b/src/shared/adopt-cwd.ts@@ -0,0 +1,25 @@+// Making an SSH project's canvas fit for a LOCAL core. When a project moves from a desktop's SSH+// project to the nodeterm-server running on that same host, as that same user, its nodes still+// carry the SSH project's view of the world:+// - a cwd of `~/x`, because an SSH project's cwd is `remoteCwd` and the remote shell expanded+// `~` itself;+// - `sshRemoteTmux`, which makes a core REFUSE to spawn locally (`requireRemote`).+// Both are rewritten here. The server runs as the SSH login user, so `~` is that user's home.+import type { CanvasNodeState } from './types'++export function expandHomeCwd(cwd: string, home: string): string {+ if (cwd === '~' || cwd === '~/') return home+ if (cwd.startsWith('~/')) return `${home.replace(/\/+$/, '')}/${cwd.slice(2)}`+ return cwd+}++export function localizeAdoptedNode(node: CanvasNodeState, home: string): CanvasNodeState {+ const cwd = typeof node.cwd === 'string' ? expandHomeCwd(node.cwd, home) : node.cwd+ const remoteSession = node.sshRemoteTmux === true+ if (cwd === node.cwd && !remoteSession) return node+ // A remote-session node's `ssh` names the host its tmux ran on, and that host is now this one.+ // A plain `ssh <host>` terminal (no `sshRemoteTmux`) keeps its `ssh`: there it is the program the+ // local pty runs, which is just as valid on the server.+ const { sshRemoteTmux: _flag, ssh, ...rest } = node+ return { ...rest, ...(remoteSession || ssh === undefined ? {} : { ssh }), ...(cwd === undefined ? {} : { cwd }) }+}