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(relay): team bootstrap — team, owner, adopted project and share in one idempotent verb
review5fc53a783ecb
diff --git a/src/core/relay/hosted-service.test.ts b/src/core/relay/hosted-service.test.tsindex 8cce38e15..e205200ca 100644--- a/src/core/relay/hosted-service.test.ts+++ b/src/core/relay/hosted-service.test.ts@@ -61,6 +61,10 @@ afterEach(() => {type WorldOpts = Partial<Pick<HostedServiceDeps, 'now' | 'monotonicNow' | 'projectsOfNode' | 'nodeOfSession' | 'killPeer' | 'onSharedChange'>> & {recordTimers?: booleandataDir?: string+ /** The fake API's HTTP status for a host-token mint (default 200; a 403 is a refusal). */+ mintStatus?: number+ /** A host-token mint answers only once this settles: holds the first listener back. */+ mintGate?: Promise<void>}function world(opts: WorldOpts = {}) {@@ -107,6 +111,8 @@ function world(opts: WorldOpts = {}) {fetch: (async (u: string | URL | Request) => {if (String(u).endsWith('/v1/relay/challenge')) { challenges++; return new Response('{}', { status: 404 }) }mints+++ if (opts.mintGate) await opts.mintGate+ if (opts.mintStatus !== undefined && opts.mintStatus !== 200) return new Response('{}', { status: opts.mintStatus })return new Response(JSON.stringify({ pairingToken: 'T', hostId: 'H', exp: 0 }), { status: 200 })}) as typeof fetch,transport: () => { const { hostT, peerT } = transportPair(); peersT.push(peerT); return hostT },@@ -1048,3 +1054,54 @@ describe('hosted service — the canvas authority seam (docs/hosted-team-relay.mexpect(w.casts).not.toContain(IPC.workspaceSave)})})++describe('hosted service — waitForHosting (the first verdict `team bootstrap` waits for)', () => {+ it("answers 'up' once an idle listener is registered", async () => {+ const w = world()+ await w.svc.init()+ expect(await w.svc.start()).toBe('started')+ expect(await w.svc.waitForHosting(15_000)).toBe('up')+ })++ it('answers { refused } with the scheduler reason when the backend refuses to mint', async () => {+ const w = world({ mintStatus: 403 })+ await w.svc.init()+ expect(await w.svc.start()).toBe('started')+ const r = await w.svc.waitForHosting(15_000)+ expect(r).toMatchObject({ refused: expect.stringMatching(/refused|403/) })+ expect(w.svc.status().scheduler?.state).toBe('backend-refused')+ })++ it("answers 'starting' when nothing is decided within the wait, and 'up' on a later wait", async () => {+ // The in-process mint and open finish inside a millisecond, so the mint is held to keep the+ // first listener from opening. 300 ms spans more than one poll.+ let release!: () => void+ const w = world({ mintGate: new Promise<void>((r) => (release = r)) })+ await w.svc.init()+ expect(await w.svc.start()).toBe('started')+ expect(await w.svc.waitForHosting(300)).toBe('starting')+ expect(w.svc.status().scheduler?.idle).toBe(0)+ const waiting = w.svc.waitForHosting(15_000)+ release()+ expect(await waiting).toBe('up')+ })++ it('answers { refused } when hosting is not running at all', async () => {+ const w = world()+ expect(await w.svc.waitForHosting(1000)).toMatchObject({ refused: expect.any(String) })+ await w.svc.init()+ expect(await w.svc.waitForHosting(1000)).toMatchObject({ refused: expect.stringMatching(/not running/) })+ })+})++describe('hosted service — roleOf', () => {+ it('reports a member role, null for a stranger', async () => {+ const w = world()+ await w.svc.init()+ await w.svc.start()+ const k = pub(genKeyPair())+ expect(w.svc.roleOf(k)).toBeNull()+ await w.svc.addOwner(k, 'Me')+ expect(w.svc.roleOf(k)).toBe('owner')+ })+})diff --git a/src/core/relay/hosted-service.ts b/src/core/relay/hosted-service.tsindex ab624d490..90bd6037c 100644--- a/src/core/relay/hosted-service.ts+++ b/src/core/relay/hosted-service.ts@@ -78,6 +78,12 @@ export type PendingClosedReason = HostedPendingClosedReasonexport type HostedStartResult = 'started' | 'no-team' | 'host-key-unreadable' | 'stopped'/** `not-running`: the key was rotated on a service that was not hosting, and hosting stays off. */export type HostedRotateResult = HostedStartResult | 'not-running'+/** Hosting's first verdict: a listener is open (`up`), the backend refused to mint (`refused`, with+ * the scheduler's reason), or neither within the wait (`starting`). */+export type HostingWait = 'up' | 'starting' | { refused: string }++/** How often `waitForHosting` re-reads the scheduler's status. */+const HOSTING_WAIT_POLL_MS = 250export interface HostedServiceDeps {dataDir: string@@ -139,6 +145,12 @@ export interface HostedService {/** Replace the host key. Every teammate needs a new join code. A hosting service restarts on the* new key and answers the start result; one that was not hosting stays off ('not-running'). */rotateKey(): Promise<HostedRotateResult>+ /** Wait (bounded) for hosting's first verdict: an idle listener registered ('up'), the backend+ * refused to mint ({ refused: why }), or neither yet ('starting'). `start()` answers 'started'+ * before any mint, so this is the only way to learn a refusal synchronously. */+ waitForHosting(timeoutMs: number): Promise<HostingWait>+ /** This key's role in the team, or null for a non-member. Read from the team store on every call. */+ roleOf(pubkeyB64: string): TeamRole | null}/** One relay listener and, once a peer bridges, its session. */@@ -656,6 +668,31 @@ export function createHostedService(deps: HostedServiceDeps): HostedService {if (!wasHosting) return 'not-running'return startNow(my)})+ },+ waitForHosting(timeoutMs) {+ const verdict = (): HostingWait | null => {+ if (!scheduler) return { refused: 'Hosting is not running on this server.' }+ const s = scheduler.status()+ if (s.state === 'backend-refused') {+ return { refused: s.lastError ?? 'The nodeterm API refused to issue relay tokens.' }+ }+ if (s.idle > 0 || s.bridged > 0) return 'up'+ return null+ }+ // Polled on the deps-injected timers, so a test's fake timers drive it like every other wait here.+ return new Promise<HostingWait>((resolve) => {+ const deadline = monoNow() + timeoutMs+ const tick = (): void => {+ const v = verdict()+ if (v !== null) return resolve(v)+ if (monoNow() >= deadline) return resolve('starting')+ setT(tick, Math.min(HOSTING_WAIT_POLL_MS, Math.max(0, deadline - monoNow())))+ }+ tick()+ })+ },+ roleOf(pubkeyB64) {+ return memberRole(pubkeyB64) ?? null}}return apidiff --git a/src/core/relay/team-admin.test.ts b/src/core/relay/team-admin.test.tsindex 79c4d08d3..a4d037eb7 100644--- a/src/core/relay/team-admin.test.ts+++ b/src/core/relay/team-admin.test.ts@@ -12,6 +12,7 @@ import {ownerKeyProblem,ownerLabelProblem,projectIdProblem,+ adoptCwdProblem,parseAdminRequest,ADMIN_REQUEST_MAX,adminErrorCode,@@ -181,6 +182,38 @@ describe('validation helpers (platform-neutral)', () => {expect(parseAdminRequest([1])).toMatch(/bad request/)})+ it('a bootstrap request is refused with a stable code per field, or parsed whole', () => {+ const k = validKey()+ expect(parseAdminRequest({ cmd: 'bootstrap', ownerKey: k, ownerLabel: 'Mac', adoptCwd: '/srv/p' })).toEqual({+ cmd: 'bootstrap',+ ownerKey: k,+ ownerLabel: 'Mac',+ adoptCwd: '/srv/p'+ })+ expect(parseAdminRequest({ cmd: 'bootstrap', ownerKey: k, adoptCwd: '/srv/p' })).toMatchObject({ code: 'E_BAD_REQUEST' })+ expect(parseAdminRequest({ cmd: 'bootstrap', ownerKey: 'K', ownerLabel: '', adoptCwd: '/srv/p' })).toMatchObject({+ code: 'E_BAD_KEY',+ refused: expect.stringMatching(/32 bytes/)+ })+ expect(parseAdminRequest({ cmd: 'bootstrap', ownerKey: k, ownerLabel: 'a\nb', adoptCwd: '/srv/p' })).toMatchObject({+ code: 'E_BAD_REQUEST',+ refused: expect.stringMatching(/control/)+ })+ expect(parseAdminRequest({ cmd: 'bootstrap', ownerKey: k, ownerLabel: '', adoptCwd: 'srv/p' })).toMatchObject({+ code: 'E_BAD_CWD',+ refused: expect.stringMatching(/absolute/)+ })+ })++ it('the folder to adopt is an absolute, bounded, control-free path', () => {+ expect(adoptCwdProblem('/home/u/proj')).toBeNull()+ expect(adoptCwdProblem('~/proj')).toMatch(/absolute/)+ expect(adoptCwdProblem('')).toMatch(/absolute/)+ expect(adoptCwdProblem('/' + 'x'.repeat(4096))).toMatch(/too long/)+ expect(adoptCwdProblem('/a\nb')).toMatch(/control/)+ expect(adoptCwdProblem('/a\u202eb')).toMatch(/control/)+ })+it('a socket path longer than a unix socket allows is refused by name, per platform', () => {expect(socketPathProblem('/s/' + 'x'.repeat(104), 'linux')).toBeNull() // 107 bytesexpect(socketPathProblem('/s/' + 'x'.repeat(105), 'linux')).toMatch(/108 bytes.*107/)@@ -256,7 +289,7 @@ describe.skipIf(process.platform === 'win32')('team admin socket (unix socket, Pexpect(await callTeamAdmin(other, { cmd: 'remove', pubkey: 'K' })).toEqual({ ok: false, error: expect.stringMatching(/No team member/) })})- it('with no team on this server it serves only init, status and info', async () => {+ it('with no team on this server it serves only init, status, info and bootstrap', async () => {const dataDir = tmp()const { svc, calls } = fakeService()await boot(dataDir, svc)@@ -448,6 +481,82 @@ describe.skipIf(process.platform === 'win32')('team admin socket (unix socket, Pexpect(calls).toEqual(['init'])})+ it('bootstrap is served without a team (it creates one) and returns the bootstrap result', async () => {+ const dataDir = tmp()+ const { svc, calls } = fakeService()+ Object.assign(svc, {+ waitForHosting: async () => 'up',+ roleOf: () => null,+ sharedProjectIds: () => new Set<string>()+ })+ const adopted: string[] = []+ const admin = await startTeamAdmin(dataDir, svc, {+ adoptFolder: async (cwd) => {+ adopted.push(cwd)+ return { projectId: 'project-9', projectName: 'p', created: true }+ }+ })+ closers.push(() => admin.close())+ const k = validKey()+ const r = await callTeamAdmin(dataDir, { cmd: 'bootstrap', ownerKey: k, ownerLabel: 'Mac', adoptCwd: '/srv/p' })+ expect(r).toEqual({+ ok: true,+ result: {+ hostId: 'H',+ projectId: 'project-9',+ projectName: 'p',+ joinCode: 'nodeterm://join/CODE',+ hosting: 'up',+ created: { team: true, owner: true, project: true, share: true }+ }+ })+ expect(calls).toEqual(['init', 'start', `owner:${k}:Mac`, 'share:project-9:true'])+ expect(adopted).toEqual(['/srv/p'])+ })++ it('bootstrap refuses a bad key with E_BAD_KEY and a relative folder with E_BAD_CWD, before touching the service', async () => {+ const dataDir = tmp()+ const { svc, calls } = fakeService()+ const admin = await startTeamAdmin(dataDir, svc, { adoptFolder: async () => ({ projectId: 'x', projectName: 'x', created: true }) })+ closers.push(() => admin.close())+ expect(await callTeamAdmin(dataDir, { cmd: 'bootstrap', ownerKey: 'nope', ownerLabel: '', adoptCwd: '/a' })).toMatchObject({+ ok: false,+ code: 'E_BAD_KEY'+ })+ expect(await callTeamAdmin(dataDir, { cmd: 'bootstrap', ownerKey: validKey(), ownerLabel: '', adoptCwd: 'a/b' })).toMatchObject({+ ok: false,+ code: 'E_BAD_CWD'+ })+ expect(JSON.parse(await rawExchange(dataDir, '{"cmd":"bootstrap","ownerKey":7}\n'))).toMatchObject({+ ok: false,+ code: 'E_BAD_REQUEST'+ })+ expect(calls).toEqual([])+ expect(fs.existsSync(path.join(relayDir(dataDir), 'team.json'))).toBe(false)+ })++ it('bootstrap without an adoptFolder op answers E_UNSUPPORTED', async () => {+ const dataDir = tmp()+ const { svc, calls } = fakeService()+ await boot(dataDir, svc)+ expect(await callTeamAdmin(dataDir, { cmd: 'bootstrap', ownerKey: validKey(), ownerLabel: '', adoptCwd: '/a' })).toMatchObject({+ ok: false,+ code: 'E_UNSUPPORTED'+ })+ expect(calls).toEqual([])+ })++ it('a bootstrap whose hosting does not start answers E_HOSTING_OFF', async () => {+ const dataDir = tmp()+ const { svc } = fakeService({ start: 'host-key-unreadable' })+ const admin = await startTeamAdmin(dataDir, svc, { adoptFolder: async () => ({ projectId: 'x', projectName: 'x', created: true }) })+ closers.push(() => admin.close())+ expect(await callTeamAdmin(dataDir, { cmd: 'bootstrap', ownerKey: validKey(), ownerLabel: '', adoptCwd: '/a' })).toMatchObject({+ ok: false,+ code: 'E_HOSTING_OFF'+ })+ })+it('close() removes the socket and does not hang on a connection that never sends a request', async () => {const dataDir = tmp()const admin = await startTeamAdmin(dataDir, fakeService().svc)diff --git a/src/core/relay/team-admin.ts b/src/core/relay/team-admin.tsindex a335d02ed..f1f4a90ee 100644--- a/src/core/relay/team-admin.ts+++ b/src/core/relay/team-admin.ts@@ -8,8 +8,9 @@// Unix sockets are POSIX. The Server Edition targets Linux; on Windows both ends refuse by name// rather than failing with an obscure error (the platform rule: degrade explicitly, never silently).//-// With no hosted team on this server, the channel serves `init`, `status` and `info` only: every-// other verb would create team state (a team.json, a host key) on a server that never asked to host.+// With no hosted team on this server, the channel serves `init`, `status`, `info` and `bootstrap`+// only: every other verb would create team state (a team.json, a host key) on a server that never+// asked to host. `bootstrap` is `init` plus an owner, an adopted folder and its share, in one call.import net from 'node:net'import path from 'node:path'import { chmodSync, lstatSync, rmSync } from 'node:fs'@@ -18,6 +19,7 @@ import { TeamStore, TEAM_LABEL_MAX, TEAM_PROJECT_ID_MAX } from './team-store'import { loadHostKey } from './host-key'import { publicKeyFromB64, publicKeyToB64 } from './e2ee'import { ADMIN_ERROR_CODE_RE, adminErrorCode } from './admin-error'+import { runBootstrap } from './team-bootstrap'import type {HostedInfo,HostedRotateResult,@@ -25,6 +27,7 @@ import type {HostedStartResult,HostedStatus} from './hosted-service'+import type { AdoptFolderResult } from '../workspace-store'export { codedError, adminErrorCode, ADMIN_ERROR_CODE_RE } from './admin-error'@@ -36,7 +39,20 @@ export type AdminRequest =| { cmd: 'status' }| { cmd: 'share'; projectId: string; on: boolean }| { cmd: 'rotate-key' }+ | { cmd: 'bootstrap'; ownerKey: string; ownerLabel: string; adoptCwd: string }export type AdminReply = { ok: true; result: unknown } | { ok: false; error: string; code?: string }+/** A request refused with a stable code (`parseAdminRequest`), so a remote caller can branch on it. */+export interface AdminRefusal {+ refused: string+ code: string+}++/** What the admin socket needs from the rest of the server beyond the hosted service. A server with+ * no workspace passes none, and the verbs that need one answer `E_UNSUPPORTED`. */+export interface TeamAdminOps {+ /** Adopt a folder into this core's workspace (saved before it returns) — `team bootstrap`. */+ adoptFolder?(cwd: string): Promise<AdoptFolderResult>+}/** `init`'s answer. The address and join code are present only when hosting is running. */export interface AdminInitResult {@@ -172,9 +188,22 @@ export function projectIdProblem(id: string): string | null {return null}-/** A well-formed request, or the reason it is not. The server's own check: the CLI is one client,- * but anything running as this user can write to the socket. */-export function parseAdminRequest(raw: unknown): AdminRequest | string {+/** The longest folder path `bootstrap` accepts (Linux's PATH_MAX). */+const ADOPT_CWD_MAX = 4096++/** Why `cwd` cannot be the folder bootstrap adopts, or null. Absolute POSIX path, bounded, no+ * control characters — the server resolves and checks it on disk itself. */+export function adoptCwdProblem(cwd: string): string | null {+ if (!cwd.startsWith('/')) return 'The folder to adopt must be an absolute path.'+ if (cwd.length > ADOPT_CWD_MAX) return 'The folder path is too long.'+ if (CONTROL_RE.test(cwd)) return 'The folder path contains control characters.'+ return null+}++/** A well-formed request, or the reason it is not (a bare string, or a refusal carrying a stable+ * code). The server's own check: the CLI is one client, but anything running as this user can+ * write to the socket. */+export function parseAdminRequest(raw: unknown): AdminRequest | string | AdminRefusal {if (raw === null || typeof raw !== 'object' || Array.isArray(raw)) return 'bad request: expected a JSON object'const o = raw as Record<string, unknown>switch (o.cmd) {@@ -201,6 +230,18 @@ export function parseAdminRequest(raw: unknown): AdminRequest | string {if (typeof o.on !== 'boolean') return 'bad request: share needs on (a boolean)'return projectIdProblem(o.projectId) ?? { cmd: 'share', projectId: o.projectId, on: o.on }}+ case 'bootstrap': {+ if (typeof o.ownerKey !== 'string' || typeof o.ownerLabel !== 'string' || typeof o.adoptCwd !== 'string') {+ return { refused: 'bad request: bootstrap needs ownerKey, ownerLabel and adoptCwd strings', code: 'E_BAD_REQUEST' }+ }+ const keyProblem = ownerKeyProblem(o.ownerKey)+ if (keyProblem) return { refused: keyProblem, code: 'E_BAD_KEY' }+ const labelProblem = ownerLabelProblem(o.ownerLabel)+ if (labelProblem) return { refused: labelProblem, code: 'E_BAD_REQUEST' }+ const cwdProblem = adoptCwdProblem(o.adoptCwd)+ if (cwdProblem) return { refused: cwdProblem, code: 'E_BAD_CWD' }+ return { cmd: 'bootstrap', ownerKey: o.ownerKey, ownerLabel: o.ownerLabel, adoptCwd: o.adoptCwd }+ }default:return `bad request: unknown command ${JSON.stringify(typeof o.cmd === 'string' ? o.cmd.slice(0, 40) : o.cmd)}`}@@ -248,9 +289,16 @@ async function handle(relayDir: string,svc: HostedService,req: AdminRequest,- closing: () => boolean+ closing: () => boolean,+ ops: TeamAdminOps): Promise<AdminReply> {- if (req.cmd !== 'init' && req.cmd !== 'status' && req.cmd !== 'info' && !(await teamIsSetUp(relayDir, svc))) {+ if (+ req.cmd !== 'init' &&+ req.cmd !== 'status' &&+ req.cmd !== 'info' &&+ req.cmd !== 'bootstrap' &&+ !(await teamIsSetUp(relayDir, svc))+ ) {return fail(NO_TEAM)}switch (req.cmd) {@@ -292,10 +340,21 @@ async function handle(const result: AdminRotateResult = { result: r, ...address(svc, r === 'started') }return ok(result)}+ case 'bootstrap': {+ if (!ops.adoptFolder) return fail('This server cannot adopt folders (no workspace).', 'E_UNSUPPORTED')+ const adopt = ops.adoptFolder+ return ok(await runBootstrap({ svc, adoptFolder: (cwd) => adopt(cwd), closing }, req))+ }}}-async function answer(relayDir: string, svc: HostedService, line: string, closing: () => boolean): Promise<AdminReply> {+async function answer(+ relayDir: string,+ svc: HostedService,+ line: string,+ closing: () => boolean,+ ops: TeamAdminOps+): Promise<AdminReply> {if (closing()) return fail(SHUTTING_DOWN)let raw: unknowntry {@@ -305,8 +364,9 @@ async function answer(relayDir: string, svc: HostedService, line: string, closin}const req = parseAdminRequest(raw)if (typeof req === 'string') return fail(req)+ if ('refused' in req) return fail(req.refused, req.code)try {- return await handle(relayDir, svc, req, closing)+ return await handle(relayDir, svc, req, closing, ops)} catch (err) {return fail(err instanceof Error ? err.message : String(err), adminErrorCode(err))}@@ -357,7 +417,11 @@ async function clearStaleSocket(sock: string): Promise<void> {throw new AdminSocketBusyError(`Could not tell whether ${sock} is still in use (${verdict}); not replacing it.`)}-export async function startTeamAdmin(dataDir: string, svc: HostedService): Promise<{ close(): Promise<void> }> {+export async function startTeamAdmin(+ dataDir: string,+ svc: HostedService,+ ops: TeamAdminOps = {}+): Promise<{ close(): Promise<void> }> {const sock = adminSocketPath(dataDir)const problem = socketPathProblem(sock)if (problem) throw new Error(problem)@@ -388,7 +452,7 @@ export async function startTeamAdmin(dataDir: string, svc: HostedService): Promiif (nl < 0) returntaken = truec.setTimeout(0)- void answer(relayDir, svc, buf.slice(0, nl), isClosing).then((reply) => {+ void answer(relayDir, svc, buf.slice(0, nl), isClosing, ops).then((reply) => {if (!c.destroyed) c.end(JSON.stringify(reply) + '\n')})})diff --git a/src/core/relay/team-bootstrap.test.ts b/src/core/relay/team-bootstrap.test.tsnew file mode 100644index 000000000..97e9025c1--- /dev/null+++ b/src/core/relay/team-bootstrap.test.ts@@ -0,0 +1,109 @@+import { describe, it, expect } from 'vitest'+import { runBootstrap, type BootstrapDeps } from './team-bootstrap'+import type { HostedService, HostingWait } from './hosted-service'+import type { TeamRole } from './team-store'++const KEY = 'A'.repeat(43) + '=' // the test never decodes it — runBootstrap trusts the parsed request+const INFO = { relayEndpoint: 'wss://r', hostId: 'H', hostPublicKeyB64: 'P', hostDeviceId: 'D', label: 'box' }++function deps(+ o: {+ created?: boolean+ start?: string+ wait?: HostingWait+ role?: TeamRole | null+ shared?: string[]+ adopt?: { projectId: string; projectName: string; created: boolean } | Error+ closing?: boolean+ } = {}+): { d: BootstrapDeps; calls: string[] } {+ const calls: string[] = []+ const shared = new Set(o.shared ?? [])+ const svc = {+ init: async () => (calls.push('init'), { created: o.created ?? true }),+ start: async () => (calls.push('start'), o.start ?? 'started'),+ waitForHosting: async () => (calls.push('wait'), o.wait ?? 'up'),+ roleOf: () => o.role ?? null,+ addOwner: async (_k: string, l: string) => void calls.push(`owner:${l}`),+ share: async (p: string) => void (calls.push(`share:${p}`), shared.add(p)),+ sharedProjectIds: () => shared,+ info: () => INFO,+ joinCode: () => 'nodeterm://join/CODE'+ } as unknown as HostedService+ const d: BootstrapDeps = {+ svc,+ adoptFolder: async (cwd) => {+ calls.push(`adopt:${cwd}`)+ if (o.adopt instanceof Error) throw o.adopt+ return o.adopt ?? { projectId: 'project-1', projectName: 'proj', created: true }+ },+ closing: () => o.closing ?? false+ }+ return { d, calls }+}+const REQ = { ownerKey: KEY, ownerLabel: 'Mac', adoptCwd: '/home/u/proj' }++describe('runBootstrap', () => {+ it('a fresh host: init, start, wait, owner, adopt, share — in that order — and the join code', async () => {+ const { d, calls } = deps()+ expect(await runBootstrap(d, REQ)).toEqual({+ hostId: 'H',+ projectId: 'project-1',+ projectName: 'proj',+ joinCode: 'nodeterm://join/CODE',+ hosting: 'up',+ created: { team: true, owner: true, project: true, share: true }+ })+ expect(calls).toEqual(['init', 'start', 'wait', 'owner:Mac', 'adopt:/home/u/proj', 'share:project-1'])+ })++ it('a re-run on a set-up host changes nothing: every created flag false, no second share', async () => {+ const { d, calls } = deps({+ created: false,+ role: 'owner',+ shared: ['project-1'],+ adopt: { projectId: 'project-1', projectName: 'proj', created: false }+ })+ const r = await runBootstrap(d, REQ)+ expect(r.created).toEqual({ team: false, owner: false, project: false, share: false })+ expect(calls).not.toContain('share:project-1')+ expect(calls.some((c) => c.startsWith('owner:'))).toBe(false)+ })++ it('an existing editor is promoted (created.owner true)', async () => {+ const { d } = deps({ role: 'editor' })+ expect((await runBootstrap(d, REQ)).created.owner).toBe(true)+ })++ it('E_HOSTING_OFF when start does not start, before anything else changes', async () => {+ const { d, calls } = deps({ start: 'host-key-unreadable' })+ await expect(runBootstrap(d, REQ)).rejects.toMatchObject({ code: 'E_HOSTING_OFF' })+ expect(calls).toEqual(['init', 'start'])+ })++ it('E_HOSTING_OFF with the scheduler reason when the backend refuses, nothing adopted or shared', async () => {+ const { d, calls } = deps({ wait: { refused: 'refused (403)' } })+ await expect(runBootstrap(d, REQ)).rejects.toMatchObject({+ code: 'E_HOSTING_OFF',+ message: expect.stringContaining('refused (403)')+ })+ expect(calls.some((c) => c.startsWith('adopt') || c.startsWith('share') || c.startsWith('owner'))).toBe(false)+ })++ it("'starting' is still a success: the desktop's join retries", async () => {+ const { d } = deps({ wait: 'starting' })+ expect((await runBootstrap(d, REQ)).hosting).toBe('starting')+ })++ it('an adopt failure propagates its code and nothing is shared', async () => {+ const { d, calls } = deps({ adopt: Object.assign(new Error('bad'), { code: 'E_ADOPT_FAILED' }) })+ await expect(runBootstrap(d, REQ)).rejects.toMatchObject({ code: 'E_ADOPT_FAILED' })+ expect(calls.some((c) => c.startsWith('share'))).toBe(false)+ })++ it('a server shutting down after init does not start hosting', async () => {+ const { d, calls } = deps({ closing: true })+ await expect(runBootstrap(d, REQ)).rejects.toThrow(/shutting down/)+ expect(calls).toEqual(['init'])+ })+})diff --git a/src/core/relay/team-bootstrap.ts b/src/core/relay/team-bootstrap.tsnew file mode 100644index 000000000..a237bfd80--- /dev/null+++ b/src/core/relay/team-bootstrap.ts@@ -0,0 +1,55 @@+// `team bootstrap`: everything a desktop's "Share with team" needs from this server, in one+// idempotent admin verb. The order is the safety property: hosting must be proven to start BEFORE a+// project is adopted or shared (or an owner written), so a host that cannot host changes nothing but+// its (harmless) team file. A re-run on a set-up host changes nothing and reports every `created`+// flag false.+//+// `codedError` comes from the admin-error leaf, never from team-admin.ts: team-admin.ts imports this+// module, and the leaf keeps that a one-way edge.+import type { HostedService } from './hosted-service'+import type { AdoptFolderResult } from '../workspace-store'+import type { BootstrapResult } from '../../shared/share-team'+import { codedError } from './admin-error'++/** How long bootstrap waits for the relay's first verdict before answering 'starting'. */+export const BOOTSTRAP_HOSTING_WAIT_MS = 15_000++export interface BootstrapDeps {+ svc: HostedService+ adoptFolder(cwd: string): Promise<AdoptFolderResult>+ /** The admin channel is closing: the server is going away, so hosting must not be started. */+ closing(): boolean+ hostingWaitMs?: number+}++export async function runBootstrap(+ deps: BootstrapDeps,+ req: { ownerKey: string; ownerLabel: string; adoptCwd: string }+): Promise<BootstrapResult> {+ const { svc } = deps+ const { created: team } = await svc.init()+ // The admin closes BEFORE the server stops hosting: a `start()` issued after that stop would bring+ // a scheduler up on a server that is going away (the same rule `team init` follows).+ if (deps.closing()) throw new Error('The nodeterm server is shutting down. Hosting was not started.')+ const start = await svc.start()+ if (start !== 'started') throw codedError('E_HOSTING_OFF', `Hosting did not start (${start}). See \`team status\`.`)+ const wait = await svc.waitForHosting(deps.hostingWaitMs ?? BOOTSTRAP_HOSTING_WAIT_MS)+ if (typeof wait === 'object') throw codedError('E_HOSTING_OFF', `Hosting could not start: ${wait.refused}`)+ // An editor (or a stranger) is promoted; an existing owner is left exactly as it is.+ const owner = svc.roleOf(req.ownerKey) !== 'owner'+ if (owner) await svc.addOwner(req.ownerKey, req.ownerLabel)+ const adopted = await deps.adoptFolder(req.adoptCwd)+ const share = !svc.sharedProjectIds().has(adopted.projectId)+ if (share) await svc.share(adopted.projectId, true)+ const info = svc.info()+ const joinCode = svc.joinCode()+ if (!info || !joinCode) throw codedError('E_HOSTING_OFF', 'Hosting stopped before a join code could be issued.')+ return {+ hostId: info.hostId,+ projectId: adopted.projectId,+ projectName: adopted.projectName,+ joinCode,+ hosting: wait,+ created: { team, owner, project: adopted.created, share }+ }+}diff --git a/src/server/index.ts b/src/server/index.tsindex 1fd489c27..8eeadf2c4 100644--- a/src/server/index.ts+++ b/src/server/index.ts@@ -984,7 +984,12 @@ export async function startServer(// unix socket, or Windows, disables administration — it must not take the rest of the Server// Edition down with it.let otherServerHere = false- const teamAdmin = await startTeamAdmin(config.dataDir, hosted).catch((err: unknown) => {+ const teamAdmin = await startTeamAdmin(config.dataDir, hosted, {+ // `team bootstrap`: adopt the folder into THIS core's workspace (saved before it is shared, so+ // the canvas authority can read it). The server runs as the SSH login user, so its home is the+ // one an SSH project's `~` cwds meant.+ adoptFolder: (cwd) => workspaceStore.adoptFolder(cwd, { home: os.homedir() })+ }).catch((err: unknown) => {if ((err as { code?: unknown } | null)?.code === 'E_ADMIN_SOCKET_BUSY') otherServerHere = trueconsole.error(`[hosted-team] team admin socket disabled: ${err instanceof Error ? err.message : String(err)}`)return { close: async (): Promise<void> => {} }diff --git a/src/server/team-cli.test.ts b/src/server/team-cli.test.tsindex d0cd7b73c..0deb97a79 100644--- a/src/server/team-cli.test.ts+++ b/src/server/team-cli.test.ts@@ -2,7 +2,7 @@ import { describe, it, expect, afterEach } from 'vitest'import fs from 'node:fs'import os from 'node:os'import path from 'node:path'-import { parseTeamArgv, runTeamCli, describeStatus, teamArgv } from './team-cli'+import { parseTeamArgv, runTeamCli, describeStatus, teamArgv, TEAM_USAGE } from './team-cli'import { startTeamAdmin, adminSocketPath, type AdminStatusResult } from '../core/relay/team-admin'import { genKeyPair, publicKeyToB64 } from '../core/relay/e2ee'import type { HostedService, HostedStatus } from '../core/relay/hosted-service'@@ -51,6 +51,32 @@ describe('team argv', () => {it('share names a bad project id', () => {expect(parseTeamArgv(['share', 'x'.repeat(129)])).toEqual({ error: expect.stringMatching(/128/) })})++ it('bootstrap needs an owner key and an absolute folder; the label is optional', () => {+ expect(parseTeamArgv(['bootstrap', '--owner-key', KEY, '--adopt', '/srv/p'])).toEqual({+ cmd: 'bootstrap',+ ownerKey: KEY,+ ownerLabel: '',+ adoptCwd: '/srv/p'+ })+ expect(parseTeamArgv(['bootstrap', '--owner-key', KEY, '--adopt=/srv/p', '--owner-label', 'Mac', '--json'])).toEqual({+ cmd: 'bootstrap',+ ownerKey: KEY,+ ownerLabel: 'Mac',+ adoptCwd: '/srv/p'+ })+ expect(parseTeamArgv(['bootstrap', '--owner-key', KEY])).toEqual({ error: expect.stringMatching(/needs --owner-key/) })+ expect(parseTeamArgv(['bootstrap', '--adopt', '/srv/p'])).toEqual({ error: expect.stringMatching(/needs --owner-key/) })+ expect(parseTeamArgv(['bootstrap', '--owner-key', KEY, '--adopt', 'srv/p'])).toEqual({ error: expect.stringMatching(/absolute/) })+ expect(parseTeamArgv(['bootstrap', '--owner-key', 'K', '--adopt', '/srv/p'])).toEqual({ error: expect.stringMatching(/32 bytes/) })+ expect(parseTeamArgv(['bootstrap', '--owner-key', KEY, '--adopt', '/srv/p', 'extra'])).toEqual({+ error: expect.stringMatching(/takes no arguments/)+ })+ })++ it('`team --help` lists bootstrap at the row start a remote probe greps for', () => {+ expect(TEAM_USAGE).toMatch(/^ {2}bootstrap /m)+ })})describe('teamArgv (main.cjs dispatch)', () => {@@ -381,6 +407,45 @@ describe.skipIf(process.platform === 'win32')('runTeamCli over the admin socketexpect(j.code).toBe(0)})+ it('bootstrap --json prints the bootstrap result as one JSON document; without --json, a summary', async () => {+ const dataDir = tmp()+ const f = fake()+ Object.assign(f.svc, {+ waitForHosting: async () => 'starting',+ roleOf: () => null,+ sharedProjectIds: () => new Set<string>()+ })+ const admin = await startTeamAdmin(dataDir, f.svc, {+ adoptFolder: async () => ({ projectId: 'project-9', projectName: 'proj', created: true })+ })+ closers.push(() => admin.close())+ const argv = ['bootstrap', '--owner-key', KEY, '--owner-label', 'Mac', '--adopt', '/srv/proj']+ const json = await run([...argv, '--json'], dataDir)+ expect(json.code).toBe(0)+ expect(JSON.parse(json.out)).toEqual({+ hostId: 'HOSTID',+ projectId: 'project-9',+ projectName: 'proj',+ joinCode: 'nodeterm://join/CODE',+ hosting: 'starting',+ created: { team: true, owner: true, project: true, share: true }+ })+ const human = await run(argv, dataDir)+ expect(human.code).toBe(0)+ expect(human.out).toMatch(/Created the team/)+ expect(human.out).toMatch(/Project proj \(project-9\) is shared with the team/)+ expect(human.out).toMatch(/Hosting: starting/)+ expect(human.out).toContain('nodeterm://join/CODE')+ expect(f.calls).toEqual([`owner:${KEY}:Mac`, 'share:project-9:true', `owner:${KEY}:Mac`, 'share:project-9:true'])+ })++ it('a bootstrap refusal under --json is one JSON line on stdout carrying its code', async () => {+ const { dataDir } = await served({}, false) // no adoptFolder op: E_UNSUPPORTED+ const r = await run(['bootstrap', '--owner-key', KEY, '--adopt', '/srv/proj', '--json'], dataDir)+ expect(r.code).toBe(1)+ expect(JSON.parse(r.out)).toEqual({ ok: false, error: expect.stringMatching(/cannot adopt/), code: 'E_UNSUPPORTED' })+ })+it('a refused --json verb prints {"ok":false,…} on stdout and the human line on stderr', async () => {const dataDir = tmp()fs.mkdirSync(path.join(dataDir, 'relay'), { recursive: true, mode: 0o700 })diff --git a/src/server/team-cli.ts b/src/server/team-cli.tsindex 1dc78540c..e8a5aa931 100644--- a/src/server/team-cli.ts+++ b/src/server/team-cli.ts@@ -7,6 +7,7 @@import path from 'node:path'import {CONTROL_RE,+ adoptCwdProblem,callTeamAdmin,ownerKeyProblem,ownerLabelProblem,@@ -33,6 +34,11 @@ const safeJson = (v: unknown): string =>const USAGE_ROWS: Array<[string, string]> = [['init', 'create the host key and the team, and start hosting'],+ // The desktop's Share with team probes for this verb by grepping `team --help` for `^ bootstrap `.+ [+ 'bootstrap --owner-key <key> --adopt <dir> [--owner-label <name>] [--json]',+ 'set up the team, an owner and a shared project in one step'+ ],['add-owner <device-key> [--label <name>]', 'make a device an owner (its 44-character public key)'],['remove <device-key> [--force]', 'remove a member and cut its live sessions'],['share <projectId>', 'show a project to non-editors'],@@ -54,6 +60,7 @@ interface CommandSpec {}const COMMANDS: Record<string, CommandSpec> = {init: { positionals: 0, flags: {} },+ bootstrap: { positionals: 0, flags: { 'owner-key': 'value', 'owner-label': 'value', adopt: 'value', json: 'bool' } },'add-owner': { positionals: 1, flags: { label: 'value' } },remove: { positionals: 1, flags: { force: 'bool' } },share: { positionals: 1, flags: {} },@@ -115,6 +122,14 @@ export function parseTeamArgv(argv: string[]): AdminRequest | { error: string }const problem = ownerKeyProblem(pubkey) ?? ownerLabelProblem(label)return problem ? { error: problem } : { cmd, pubkey, label }}+ case 'bootstrap': {+ const ownerKey = typeof flags['owner-key'] === 'string' ? flags['owner-key'] : ''+ const adoptCwd = typeof flags.adopt === 'string' ? flags.adopt : ''+ const ownerLabel = typeof flags['owner-label'] === 'string' ? flags['owner-label'] : ''+ if (!ownerKey || !adoptCwd) return usageError('bootstrap needs --owner-key <key> and --adopt <dir>')+ const problem = ownerKeyProblem(ownerKey) ?? ownerLabelProblem(ownerLabel) ?? adoptCwdProblem(adoptCwd)+ return problem ? { error: problem } : { cmd: 'bootstrap', ownerKey, ownerLabel, adoptCwd }+ }case 'remove':return flags.force ? { cmd, pubkey: positionals[0], force: true } : { cmd, pubkey: positionals[0] }case 'share':@@ -272,8 +287,8 @@ export function describeStatus(result: AdminStatusResult): string[] {}/** Render a successful reply. The exit code is 1 when the command did its part but the outcome it- * exists for did not happen (hosting did not start, there is no address yet). Only `info` and- * `status` take `--json`. */+ * exists for did not happen (hosting did not start, there is no address yet). Only `info`,+ * `status` and `bootstrap` take `--json`. */function render(req: AdminRequest, result: unknown, json: boolean): { lines: string[]; code: number } {switch (req.cmd) {case 'init': {@@ -317,6 +332,19 @@ function render(req: AdminRequest, result: unknown, json: boolean): { lines: str}case 'status':return { lines: json ? [safeJson(result)] : describeStatus(result as AdminStatusResult), code: 0 }+ case 'bootstrap': {+ if (json) return { lines: [safeJson(result)], code: 0 }+ const r = obj(result)+ const created = obj(r.created)+ const lines = [+ created.team === true ? 'Created the team.' : 'The team already existed.',+ `Project ${str(r.projectName, '?')} (${str(r.projectId, '?')}) is shared with the team.`,+ r.hosting === 'up' ? 'Hosting: ON.' : 'Hosting: starting — teammates can join in a moment.',+ 'Join code (give it to teammates; an owner approves each new device):',+ ` ${str(r.joinCode, '?')}`+ ]+ return { lines, code: 0 }+ }case 'rotate-key': {const r = obj(result) as Partial<AdminRotateResult>if (r.result === 'not-running') {diff --git a/src/shared/share-team.ts b/src/shared/share-team.tsnew file mode 100644index 000000000..ce44bad98--- /dev/null+++ b/src/shared/share-team.ts@@ -0,0 +1,14 @@+// Wire shapes shared by the desktop's "Share with team" flow and the Server Edition's `team` admin+// verbs. Everything here crosses an ssh exec channel as JSON, so every reader is strict.++/** `team bootstrap --json`'s answer: the team's address, the project it adopted and shared, the+ * join code, and what this call changed (every `created` flag false on a re-run). */+export interface BootstrapResult {+ hostId: string+ projectId: string+ projectName: string+ joinCode: string+ /** `starting` is still a success: no relay verdict arrived within the wait, and a join retries. */+ hosting: 'up' | 'starting'+ created: { team: boolean; owner: boolean; project: boolean; share: boolean }+}