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(server): add opt-in headless canvas control

freshjuicez69b5e377a0ba
diff --git a/src/core/agents/pane-ownership.ts b/src/core/agents/pane-ownership.ts
index 6f02db67d..1a5aebd15 100644
--- a/src/core/agents/pane-ownership.ts
+++ b/src/core/agents/pane-ownership.ts
@@ -34,8 +34,8 @@
* This is scoped to tmux-pane messaging ownership but is intentionally feature-neutral: S8 PR 4's
* BrowserControlLedger and messaging PR 7's deliver-on-idle queue want the same "who really spawned
* this node" answer and can consume `paneOwnerProject` directly. It lives in `src/core` (no
- * electron, no main import) so it ships on both shells; the Server Edition never records or reads it
- * because messaging does not exist there (`setControlHandler` is never called).
+ * electron, no main import) so it ships on both shells; the opt-in Server Edition control runtime
+ * now records and reads it through the same PtyManager and messaging service as desktop.
*/
/** nodeId → owning projectId (machine-local entry id), for panes freshly spawned THIS run. */
diff --git a/src/core/canvas-sync.ts b/src/core/canvas-sync.ts
index 67a566c62..61b4d388c 100644
--- a/src/core/canvas-sync.ts
+++ b/src/core/canvas-sync.ts
@@ -87,6 +87,20 @@ let registeredOn: CorePlatform | null = null
*/
let seq = 0
+/**
+ * Publish a mutation originated by the core itself (for example a headless Server Edition
+ * control request). It takes the same validation, execution-field sanitization and total-order
+ * stamp as a browser cast, then fans out to every connected canvas. Disk persistence remains the
+ * caller's responsibility; this function is only the live convergence leg.
+ */
+export function publishCanvasMutation(projectId: string, mutation: CanvasMutation): boolean {
+ if (!isRefId(projectId) || !isCanvasMutation(mutation)) return false
+ const p = platform()
+ const stamped = stampMutation(sanitizeInboundMutation(mutation), ++seq)
+ for (const id of p.clientIds()) p.sendTo(id, IPC.canvasMut, projectId, stamped)
+ return true
+}
+
/** Install the `canvas:mut` reflector. Call once at boot, after initPlatform(). */
export function initCanvasSync(): void {
const p = platform()
diff --git a/src/core/pty-manager.ts b/src/core/pty-manager.ts
index 96c9a3d1f..86ac94e73 100644
--- a/src/core/pty-manager.ts
+++ b/src/core/pty-manager.ts
@@ -1870,6 +1870,19 @@ export class PtyManager {
return tomb
}
+ /**
+ * Create or attach a node session without a renderer initiating the request.
+ *
+ * Client id 0 is reserved by both shells (ServerPlatform starts real websocket clients at 1;
+ * Electron webContents ids are positive). Keeping the synthetic subscriber in the ordinary
+ * ledger means a browser that opens later takes the proven co-attach path, while output sent to
+ * id 0 is simply dropped by a platform with no such UI. All spawn policy, node-auth env,
+ * account scoping, project env and ownership recording still run through `create` unchanged.
+ */
+ createHeadless(options: PtyCreateOptions): Promise<PtyCreateResult> {
+ return this.create(0, options)
+ }
+
private async create(clientId: ClientId, options: PtyCreateOptions): Promise<PtyCreateResult> {
const key = options.persistKey
if (!key) return this.spawnNew(clientId, options)
diff --git a/src/renderer/bridge/ws-bridge.ts b/src/renderer/bridge/ws-bridge.ts
index 695c6e14c..5d1ddceca 100644
--- a/src/renderer/bridge/ws-bridge.ts
+++ b/src/renderer/bridge/ws-bridge.ts
@@ -295,13 +295,12 @@ export function buildRealApi(
onMigrated: (cb) => client.subscribe(IPC.workspaceMigrated, cb as Listener),
// REAL: core broadcasts IPC.workspaceCorruptRecovered from the load path (workspace-store.ts).
onCorruptRecovered: (cb) => client.subscribe(IPC.workspaceCorruptRecovered, cb as Listener),
- // Deliberate degrade: the external-change WATCHER (core/workspace-watcher.ts) is only started
- // by the desktop shell (src/main/index.ts), so the server never broadcasts
- // IPC.workspaceExternalChange and there is nothing to subscribe to. Effect in the browser:
- // an outside edit (git pull / a teammate's push) is not picked up until reload — no silent
- // data loss (the store's own rev reconciliation still guards writes). Booting the watcher in
- // src/server is the follow-up.
- onExternalChange: () => () => {}
+ // The server still does not run WorkspaceWatcher (outside edits remain reload-on-demand), but
+ // core-originated mutations do broadcast this channel: remote-node adoption already did, and
+ // Server Edition canvas control uses it for persisted bridge/rope changes that are wider than
+ // the node-only canvas:mut vocabulary. Subscribe to what actually exists instead of dropping
+ // those updates just because the filesystem-watcher producer is absent.
+ onExternalChange: (cb) => client.subscribe(IPC.workspaceExternalChange, cb as Listener)
}
// REAL: WorkspaceStore (core) registers the project-settings:* channels too — same
diff --git a/src/renderer/lib/pendingLaunch.test.ts b/src/renderer/lib/pendingLaunch.test.ts
index bdc20e1eb..39865c564 100644
--- a/src/renderer/lib/pendingLaunch.test.ts
+++ b/src/renderer/lib/pendingLaunch.test.ts
@@ -8,6 +8,14 @@ const armed = (id: string, after: string[], command = `echo ${id}`): ArmedNode =
const plain = (id: string): ArmedNode => ({ id, data: {} })
describe('launchesToFire', () => {
+ it('leaves server-owned launches to the headless scheduler', () => {
+ const node: ArmedNode = {
+ id: 'c',
+ data: { pendingLaunch: { after: [], command: 'echo c', executor: 'server' } }
+ }
+ expect(launchesToFire([node], {}, new Set(['c']))).toEqual([])
+ })
+
const live = new Set(['a', 'b', 'c'])
it('fires when every dep has reported done', () => {
diff --git a/src/renderer/lib/pendingLaunch.ts b/src/renderer/lib/pendingLaunch.ts
index 1bbd8de73..209a3ef1b 100644
--- a/src/renderer/lib/pendingLaunch.ts
+++ b/src/renderer/lib/pendingLaunch.ts
@@ -66,7 +66,7 @@ export function launchesToFire(
const out: LaunchToFire[] = []
for (const n of nodes) {
const p = n.data.pendingLaunch
- if (!p || !p.command) continue
+ if (!p || !p.command || p.executor === 'server') continue
if (p.awaitSetupGroup && !(setupDone?.(p.awaitSetupGroup) ?? true)) continue
if (p.after.every((d) => depSatisfied(d, status, live))) out.push({ id: n.id, command: p.command })
}
diff --git a/src/server/agent-status.ts b/src/server/agent-status.ts
index 16c66be94..4e21f3623 100644
--- a/src/server/agent-status.ts
+++ b/src/server/agent-status.ts
@@ -44,6 +44,9 @@ export interface WireAgentStatusOptions {
hooks?: HookLike
subagentTail?: SubagentTail
contextTail?: ContextTail
+ /** One tap on the normalized, mirror-enriched stream for in-process consumers such as the
+ * Server Edition delivery queue and `--after` scheduler. */
+ onEvent?: (event: NormalizedAgentEvent) => void
}
/**
@@ -149,6 +152,7 @@ export function wireAgentStatus(
// keys off the same single source of truth as the mirror/phone. Then broadcast the enriched one.
const enriched = recordAgentEvent(e) ?? e
platform.broadcast(IPC.agentStatus, enriched)
+ opts.onEvent?.(enriched)
})
// Security: hook POSTs can be forged, so a forged POST could set transcript_path to an
diff --git a/src/server/canvas-control.test.ts b/src/server/canvas-control.test.ts
new file mode 100644
index 000000000..5c344f85a
--- /dev/null
+++ b/src/server/canvas-control.test.ts
@@ -0,0 +1,130 @@
+import fs from 'node:fs'
+import os from 'node:os'
+import path from 'node:path'
+
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+
+import { resetMessageFlow } from '../core/agents/agent-message-flow'
+import {
+ recordFreshSpawnOwner,
+ resetPaneOwnershipForTests
+} from '../core/agents/pane-ownership'
+import { fakePlatform } from '../core/platform-fake'
+import { initPlatform, resetPlatformForTests } from '../core/platform'
+import type { PtyManager } from '../core/pty-manager'
+import type { WorkspaceStore } from '../core/workspace-store'
+import { DEFAULT_SETTINGS, type Settings, type Workspace } from '../shared/types'
+import { initServerCanvasControl, type ServerCanvasControl } from './canvas-control'
+
+describe('initServerCanvasControl', () => {
+ let dataDir = ''
+ let runtime: ServerCanvasControl | null = null
+
+ beforeEach(() => {
+ dataDir = fs.mkdtempSync(path.join(os.tmpdir(), 'nodeterm-server-control-'))
+ resetPlatformForTests()
+ initPlatform(fakePlatform({ userDataDir: dataDir }))
+ resetPaneOwnershipForTests()
+ resetMessageFlow()
+ })
+
+ afterEach(() => {
+ runtime?.stop()
+ runtime = null
+ resetPaneOwnershipForTests()
+ resetPlatformForTests()
+ fs.rmSync(dataDir, { recursive: true, force: true })
+ })
+
+ it('installs only under temp data when integrations are gated, and enforces messaging switch off', async () => {
+ const workspace: Workspace = {
+ version: 2,
+ activeProjectId: 'p1',
+ projects: [
+ {
+ id: 'p1',
+ name: 'Project',
+ color: '#0a84ff',
+ viewport: { x: 0, y: 0, zoom: 1 },
+ nodes: [
+ {
+ id: 'source',
+ kind: 'terminal',
+ position: { x: 0, y: 0 },
+ size: { width: 640, height: 440 },
+ title: 'Source',
+ color: '#d97757',
+ group: null,
+ agentId: 'claude'
+ },
+ {
+ id: 'target',
+ kind: 'terminal',
+ position: { x: 700, y: 0 },
+ size: { width: 640, height: 440 },
+ title: 'Target',
+ color: '#10a37f',
+ group: null,
+ agentId: 'codex'
+ }
+ ]
+ }
+ ]
+ }
+ const store = {
+ load: vi.fn(async () => workspace),
+ save: vi.fn(async () => undefined),
+ persistedCanvases: () => [{ id: 'p1', nodes: workspace.projects[0].nodes }],
+ // No strict true flag and no machine-local `kept` ack: capability is off by default.
+ capabilityProjectFor: () => ({})
+ } as unknown as WorkspaceStore
+ const paneOwner = vi.fn(async () => null)
+ const sendEnvelope = vi.fn(async () => true)
+ const pty = {
+ createHeadless: vi.fn(async () => ({ sessionId: 'unused', fresh: true })),
+ sendText: vi.fn(async () => true),
+ paneOwner,
+ sendEnvelope,
+ hasLiveSession: () => true
+ } as unknown as PtyManager
+ const settings = (): Settings => ({ ...DEFAULT_SETTINGS })
+
+ runtime = await initServerCanvasControl({
+ workspaceStore: store,
+ ptyManager: pty,
+ settings,
+ boardLog: { append: async () => false },
+ cliCaps: async () => ({
+ version: null,
+ autoPermissionMode: false,
+ fullscreenTui: false,
+ sessionIdFlag: false
+ }),
+ installAgentIntegrations: false
+ })
+
+ const shim = path.join(dataDir, 'canvas-control', 'nodeterm.sh')
+ expect(fs.readFileSync(shim, 'utf8')).toContain('NODETERM_CANVAS_CONTROL')
+ expect(fs.statSync(shim).mode & 0o111).not.toBe(0)
+ const accountDir = path.join(dataDir, 'test-account')
+ runtime.installSkillInto(accountDir)
+ expect(
+ fs.readFileSync(path.join(accountDir, 'skills', 'manage-nodeterm-canvas', 'SKILL.md'), 'utf8')
+ ).toContain(shim)
+
+ // Prove ownership so the next gate reached is specifically the per-project capability switch.
+ recordFreshSpawnOwner('target', 'p1')
+ const reply = await runtime.handler({
+ verb: 'send',
+ nodeId: 'source',
+ args: { node: 'target', text: 'hello' },
+ verified: true
+ })
+ expect(reply).toMatchObject({
+ ok: false,
+ error: expect.stringContaining('notPermitted (switch-off)')
+ })
+ expect(paneOwner).not.toHaveBeenCalled()
+ expect(sendEnvelope).not.toHaveBeenCalled()
+ })
+})
diff --git a/src/server/canvas-control.ts b/src/server/canvas-control.ts
new file mode 100644
index 000000000..ab49f986b
--- /dev/null
+++ b/src/server/canvas-control.ts
@@ -0,0 +1,185 @@
+import fs from 'node:fs'
+import os from 'node:os'
+import path from 'node:path'
+
+import {
+ createDeliveryQueue,
+ deliverFromControl,
+ messagingEnabledVia,
+ onMessagingAgentEvent,
+ type AgentMessagingDeps
+} from '../core/agents/agent-messaging'
+import { paneOwnerProject } from '../core/agents/pane-ownership'
+import {
+ mirrorEntry,
+ nodeState
+} from '../core/agent-status-mirror'
+import type { BoardLogHandlers } from '../core/board-log-handlers'
+import {
+ CONTROL_SHIM_SCRIPT,
+ buildCanvasControlInstructions,
+ buildCanvasSkillBody,
+ mergeCanvasControlBlock
+} from '../core/canvas-control-core'
+import { claudeCliCaps, type ClaudeCliCaps } from '../core/claude-cli'
+import { installHooksIntoLocalAccounts } from '../core/claude-accounts-service'
+import { platform } from '../core/platform'
+import type { PtyManager } from '../core/pty-manager'
+import type { WorkspaceStore } from '../core/workspace-store'
+import type { NormalizedAgentEvent } from '../shared/agents/normalize'
+import { IPC } from '../shared/ipc'
+import type { Project, Settings } from '../shared/types'
+import {
+ createServerEditionControlHandler,
+ type ServerEditionControlActions
+} from './control-unsupported'
+import { HeadlessNodeFactory } from './headless-node-factory'
+
+export interface ServerCanvasControlDeps {
+ workspaceStore: WorkspaceStore
+ ptyManager: PtyManager
+ settings(): Settings
+ boardLog: BoardLogHandlers
+ cliCaps?: () => Promise<ClaudeCliCaps>
+ /** The server's installHooks gate. False keeps every real agent config directory untouched. */
+ installAgentIntegrations?: boolean
+}
+
+export interface ServerCanvasControl {
+ handler: ReturnType<typeof createServerEditionControlHandler>
+ onAgentEvent(event: NormalizedAgentEvent): void
+ installSkillInto(configDir: string): void
+ stop(): void
+}
+
+function canvasControlDir(): string {
+ return path.join(platform().userDataDir, 'canvas-control')
+}
+
+function shimPath(): string {
+ return path.join(canvasControlDir(), 'nodeterm.sh')
+}
+
+function skillPathIn(configDir: string): string {
+ return path.join(configDir, 'skills', 'manage-nodeterm-canvas', 'SKILL.md')
+}
+
+function writeShim(): void {
+ const dir = canvasControlDir()
+ fs.mkdirSync(dir, { recursive: true })
+ fs.writeFileSync(shimPath(), CONTROL_SHIM_SCRIPT, 'utf8')
+ try {
+ fs.chmodSync(shimPath(), 0o755)
+ } catch {
+ /* best effort on filesystems without POSIX modes */
+ }
+ // Same upgrade sweep as desktop: the POSIX shim replaced this Electron-as-Node script.
+ try {
+ fs.rmSync(path.join(dir, 'canvas-control-cli.mjs'), { force: true })
+ } catch {
+ /* best effort */
+ }
+}
+
+function installInstructions(file: string, body: string): void {
+ try {
+ let existing = ''
+ try {
+ existing = fs.readFileSync(file, 'utf8')
+ } catch {
+ /* first install */
+ }
+ fs.mkdirSync(path.dirname(file), { recursive: true })
+ fs.writeFileSync(file, mergeCanvasControlBlock(existing, body), 'utf8')
+ } catch (error) {
+ console.warn('[server-canvas-control] instruction install failed', file, error)
+ }
+}
+
+/**
+ * Boot the Server Edition canvas runtime and install its discovery surface.
+ *
+ * The shim itself always lives under the configured server dataDir, never under a hard-coded
+ * `~/.nodeterm-server`. Writes to real Claude/Codex/Gemini homes are separately controlled by the
+ * existing `installHooks` gate, exactly like `initServerContextLink`.
+ */
+export async function initServerCanvasControl(
+ deps: ServerCanvasControlDeps
+): Promise<ServerCanvasControl> {
+ try {
+ writeShim()
+ } catch (error) {
+ // The HTTP runtime remains useful even if discovery files cannot be written; fail open and loud.
+ console.warn('[server-canvas-control] shim install failed', error)
+ }
+
+ const skillBody = buildCanvasSkillBody(shimPath())
+ const instructions = buildCanvasControlInstructions(shimPath())
+ const installSkillInto = (configDir: string): void => {
+ const file = skillPathIn(configDir)
+ try {
+ fs.mkdirSync(path.dirname(file), { recursive: true })
+ fs.writeFileSync(file, skillBody, 'utf8')
+ } catch (error) {
+ console.warn('[server-canvas-control] skill install failed', file, error)
+ }
+ }
+
+ if (deps.installAgentIntegrations !== false) {
+ installSkillInto(path.join(os.homedir(), '.claude'))
+ installInstructions(path.join(os.homedir(), '.codex', 'AGENTS.md'), instructions)
+ installInstructions(path.join(os.homedir(), '.gemini', 'GEMINI.md'), instructions)
+ // Managed accounts resolve skills relative to their own CLAUDE_CONFIG_DIR.
+ installHooksIntoLocalAccounts(deps.settings().claudeAccounts ?? [], installSkillInto)
+ }
+
+ const factory = new HeadlessNodeFactory({
+ workspaceStore: deps.workspaceStore,
+ ptyManager: deps.ptyManager,
+ settings: deps.settings,
+ cliCaps: deps.cliCaps ?? claudeCliCaps,
+ stateOf: nodeState,
+ agentIdOf: (nodeId) => mirrorEntry(nodeId)?.agentId,
+ publishProject: (project: Project) => platform().broadcast(IPC.workspaceExternalChange, project)
+ })
+
+ const messaging: AgentMessagingDeps = {
+ paneOwner: (nodeId) => deps.ptyManager.paneOwner(nodeId),
+ sendEnvelope: (nodeId, envelope) => deps.ptyManager.sendEnvelope(nodeId, envelope),
+ hasLiveSession: (nodeId) => deps.ptyManager.hasLiveSession(nodeId),
+ mirrorEntry,
+ projects: () => deps.workspaceStore.persistedCanvases(),
+ isRemoteNode: () => false,
+ messagingEnabled: messagingEnabledVia((projectId) =>
+ deps.workspaceStore.capabilityProjectFor(projectId)),
+ paneOwnerProject,
+ customAgents: () => deps.settings().customAgents,
+ appendBoardLog: (projectId, entry) => deps.boardLog.append(projectId, entry)
+ }
+ const queue = createDeliveryQueue(messaging)
+ messaging.queue = queue
+
+ const actions: ServerEditionControlActions = {
+ openTerminal: (sourceNodeId, args, verified) =>
+ factory.openTerminal(sourceNodeId, args, verified),
+ openAgent: (sourceNodeId, args, verified) => factory.openAgent(sourceNodeId, args, verified),
+ sticky: (sourceNodeId, args) => factory.sticky(sourceNodeId, args),
+ deliver: async (input) => (await deliverFromControl(input, messaging)).reply
+ }
+
+ // Re-adopt any durable server-owned `--after` launch with no browser connected.
+ await factory.start()
+
+ return {
+ handler: createServerEditionControlHandler(actions),
+ onAgentEvent: (event) => {
+ onMessagingAgentEvent(event, queue)
+ factory.onAgentEvent(event)
+ },
+ installSkillInto,
+ stop: () => {
+ factory.stop()
+ queue.resetForTests()
+ }
+ }
+}
diff --git a/src/server/config.test.ts b/src/server/config.test.ts
index 444772c78..a0208aadc 100644
--- a/src/server/config.test.ts
+++ b/src/server/config.test.ts
@@ -41,6 +41,19 @@ describe('resolveConfig', () => {
expect(() => resolveConfig({ NODETERM_HOST: '0.0.0.0', NODETERM_HEADLESS: '1' }, [])).not.toThrow()
})
+ it('server canvas control is opt-in, with argv taking precedence over env', () => {
+ expect(resolveConfig({}, []).canvasControl).toBe(false)
+ expect(resolveConfig({ NODETERM_SERVER_CANVAS_CONTROL: '1' }, []).canvasControl).toBe(true)
+ expect(resolveConfig({ NODETERM_SERVER_CANVAS_CONTROL: 'true' }, []).canvasControl).toBe(true)
+ expect(resolveConfig({}, ['--canvas-control']).canvasControl).toBe(true)
+ expect(
+ resolveConfig({ NODETERM_SERVER_CANVAS_CONTROL: '1' }, ['--canvas-control', 'false'])
+ .canvasControl
+ ).toBe(false)
+ // The per-session discovery bit is not the server's authority switch.
+ expect(resolveConfig({ NODETERM_CANVAS_CONTROL: '1' }, []).canvasControl).toBe(false)
+ })
+
it('proxy trust: off by default', () => {
expect(resolveConfig({}, []).trustProxy).toBeUndefined()
})
diff --git a/src/server/config.ts b/src/server/config.ts
index 2743864e5..88c411e9d 100644
--- a/src/server/config.ts
+++ b/src/server/config.ts
@@ -32,6 +32,15 @@ export type ServerConfig = {
* the run, which is exactly how a machine ends up with hooks that quietly do nothing.
*/
installHooks?: boolean
+ /**
+ * Enable the Server Edition `/control/*` canvas runtime. Defaults OFF so an upgrade cannot
+ * silently grant agents a new local execution surface. Environment:
+ * NODETERM_SERVER_CANVAS_CONTROL=1;
+ * CLI: --canvas-control. Hook endpoint authentication and per-project capability gates still
+ * apply when enabled. The server-process env name is deliberately distinct from the
+ * per-session NODETERM_CANVAS_CONTROL discovery bit injected by HookServer.
+ */
+ canvasControl?: boolean
/**
* Reverse-proxy SSO trust (issue #29): requests whose TCP peer is inside `nets` and
* which carry `header` (non-empty) are authenticated without a session cookie.
@@ -96,6 +105,16 @@ export function resolveConfig(env: NodeJS.ProcessEnv, argv: string[]): ServerCon
// truthy spellings the install script + systemd unit emit.
const headlessEnv = (env.NODETERM_HEADLESS || '').trim().toLowerCase()
const headless = headlessEnv === '1' || headlessEnv === 'true'
+ const truthy = (value: unknown): boolean => {
+ if (value === true) return true
+ if (typeof value !== 'string') return false
+ const normalized = value.trim().toLowerCase()
+ return normalized === '1' || normalized === 'true' || normalized === 'yes'
+ }
+ const canvasControl =
+ args['canvas-control'] !== undefined
+ ? truthy(args['canvas-control'])
+ : truthy(env.NODETERM_SERVER_CANVAS_CONTROL)
// Headless binds nothing, so the "plain HTTP on a public interface" hazard the loopback refusal
// guards against does not apply — a stray NODETERM_HOST must not fail a headless boot.
@@ -127,5 +146,15 @@ export function resolveConfig(env: NodeJS.ProcessEnv, argv: string[]): ServerCon
)
}
- return { port, host, dataDir, rendererDir, insecureHttp, passwordSeed, trustProxy, headless }
+ return {
+ port,
+ host,
+ dataDir,
+ rendererDir,
+ insecureHttp,
+ passwordSeed,
+ trustProxy,
+ headless,
+ canvasControl
+ }
}
diff --git a/src/server/control-unsupported.test.ts b/src/server/control-unsupported.test.ts
index fd526c28a..6a0c3315b 100644
--- a/src/server/control-unsupported.test.ts
+++ b/src/server/control-unsupported.test.ts
@@ -6,7 +6,7 @@
* assertions here are about what the caller can conclude — a stable machine name, and prose that
* contains the literal "do not retry" — not merely about a status code.
*/
-import { describe, it, expect, beforeAll, afterAll } from 'vitest'
+import { describe, it, expect, beforeAll, afterAll, vi } from 'vitest'
import fs from 'fs'
import os from 'os'
import path from 'path'
@@ -20,6 +20,7 @@ import {
CONTROL_UNSUPPORTED_ERROR,
CONTROL_UNSUPPORTED_SENTENCE,
controlUnsupportedMessage,
+ createServerEditionControlHandler,
serverEditionControlHandler
} from './control-unsupported'
@@ -170,6 +171,88 @@ describe('the Server Edition wires it at boot', () => {
})
})
+describe('the enabled Server Edition handler parses and dispatches the v1 surface', () => {
+ const actions = () => ({
+ openTerminal: vi.fn(async () => ({ ok: true as const, result: { id: 'term-new' } })),
+ openAgent: vi.fn(async () => ({ ok: true as const, result: { id: 'agent-new' } })),
+ sticky: vi.fn(async () => ({ ok: true as const, result: { id: 'sticky-new' } })),
+ deliver: vi.fn(async () => ({ ok: true as const, message: 'queued' }))
+ })
+
+ it('shares parser validation and forwards source identity to an open', async () => {
+ const a = actions()
+ const handler = createServerEditionControlHandler(a)
+ await expect(
+ handler({
+ verb: 'open-terminal',
+ nodeId: 'term-source',
+ args: { count: '2', after: 'term-upstream' },
+ verified: true
+ })
+ ).resolves.toMatchObject({ ok: true })
+ expect(a.openTerminal).toHaveBeenCalledWith(
+ 'term-source',
+ { count: '2', after: 'term-upstream' },
+ true
+ )
+
+ await expect(
+ handler({ verb: 'open-agent', nodeId: 'term-source', args: {}, verified: true })
+ ).resolves.toEqual({ ok: false, error: 'open-agent requires --agent <id>' })
+ expect(a.openAgent).not.toHaveBeenCalled()
+ })
+
+ it('routes messaging without trusting a notify body', async () => {
+ const a = actions()
+ const handler = createServerEditionControlHandler(a)
+ await handler({
+ verb: 'send',
+ nodeId: 'term-source',
+ args: { node: 'term-target', text: 'hello' },
+ verified: true
+ })
+ await handler({
+ verb: 'notify',
+ nodeId: 'term-source',
+ args: { node: 'term-target' },
+ verified: true
+ })
+ await handler({
+ verb: 'reply',
+ nodeId: 'term-source',
+ args: { node: 'term-target', text: 'ack' },
+ verified: true
+ })
+ expect(a.deliver).toHaveBeenNthCalledWith(1, {
+ verb: 'send',
+ sourceNodeId: 'term-source',
+ targetNodeId: 'term-target',
+ body: 'hello'
+ })
+ expect(a.deliver).toHaveBeenNthCalledWith(2, {
+ verb: 'notify',
+ sourceNodeId: 'term-source',
+ targetNodeId: 'term-target',
+ body: ''
+ })
+ expect(a.deliver).toHaveBeenNthCalledWith(3, {
+ verb: 'reply',
+ sourceNodeId: 'term-source',
+ targetNodeId: 'term-target',
+ body: 'ack'
+ })
+ })
+
+ it('keeps every deferred or unknown verb a clean permanent edition refusal', async () => {
+ const handler = createServerEditionControlHandler(actions())
+ for (const verb of ['list', 'browser', 'open-project', 'not-a-verb']) {
+ const reply = await handler({ verb, nodeId: 'term-source', args: {}, verified: true })
+ expect(reply, verb).toMatchObject({ ok: false, error: CONTROL_UNSUPPORTED_ERROR })
+ expect(reply.message, verb).toContain('do not retry')
+ }
+ })
+})
+
/**
* The reply shape this refusal needed: a FAILURE may now carry a machine name in `error` and a
* sentence in `message`, and the text dialect prefers the sentence. Every pre-existing handler
diff --git a/src/server/control-unsupported.ts b/src/server/control-unsupported.ts
index b5f468022..dc8b622c7 100644
--- a/src/server/control-unsupported.ts
+++ b/src/server/control-unsupported.ts
@@ -1,3 +1,6 @@
+import { parseControlRequest } from '../core/canvas-control-core'
+import type { ServerControlReply } from './headless-node-factory'
+
/**
* The Server Edition's answer to `/control/*`: a NAMED, permanent refusal.
*
@@ -48,8 +51,9 @@ export function controlUnsupportedMessage(verb: string): string {
}
/**
- * What `src/server/index.ts` hands to `hookServer.setControlHandler`. Never resolves `ok: true`:
- * there is nothing on this host for a control verb to act on.
+ * What `src/server/index.ts` hands to `hookServer.setControlHandler` while the feature flag is
+ * OFF. This preserves the pre-Phase-1 response byte-for-byte, which is both the safe upgrade
+ * default and the explicit rollback path.
*/
export async function serverEditionControlHandler({ verb }: { verb: string }): Promise<{
ok: false
@@ -58,3 +62,92 @@ export async function serverEditionControlHandler({ verb }: { verb: string }): P
}> {
return { ok: false, error: CONTROL_UNSUPPORTED_ERROR, message: controlUnsupportedMessage(verb) }
}
+
+export interface ServerEditionControlActions {
+ openTerminal(
+ sourceNodeId: string,
+ args: Record<string, string>,
+ verified: boolean
+ ): Promise<ServerControlReply>
+ openAgent(
+ sourceNodeId: string,
+ args: Record<string, string>,
+ verified: boolean
+ ): Promise<ServerControlReply>
+ sticky(sourceNodeId: string, args: Record<string, string>): Promise<ServerControlReply>
+ deliver(input: {
+ verb: 'send' | 'reply' | 'notify'
+ sourceNodeId: string
+ targetNodeId: string
+ body: string
+ }): Promise<ServerControlReply>
+}
+
+const SERVER_V1_VERBS: ReadonlySet<string> = new Set([
+ 'open-terminal',
+ 'open-agent',
+ 'send',
+ 'reply',
+ 'notify',
+ 'sticky'
+])
+
+/** A permanent, verb-specific refusal used only while canvas control itself is enabled. */
+export function unsupportedServerVerbMessage(verb: string): string {
+ const why = verb === 'browser' ? ` ${BROWSER_UNSUPPORTED_CLAUSE}` : ''
+ return (
+ `${CONTROL_UNSUPPORTED_ERROR}: The "${verb}" canvas-control verb is not supported by ` +
+ `nodeterm Server Edition v1. This is not a temporary failure — do not retry.${why}`
+ )
+}
+
+/**
+ * Build the real Server Edition handler. Authentication remains entirely in HookServer: this
+ * callback receives only requests that passed the app bearer, per-node verdict and the
+ * verified-only gate for messaging/sticky. Parsing is shared with desktop; dispatch is deliberately
+ * small and exhaustive so every deferred verb receives a named permanent edition refusal.
+ */
+export function createServerEditionControlHandler(actions: ServerEditionControlActions): (req: {
+ verb: string
+ nodeId: string
+ args: Record<string, string>
+ verified: boolean
+}) => Promise<ServerControlReply> {
+ return async ({ verb, nodeId, args, verified }) => {
+ if (!SERVER_V1_VERBS.has(verb)) {
+ return {
+ ok: false,
+ error: CONTROL_UNSUPPORTED_ERROR,
+ message: unsupportedServerVerbMessage(verb)
+ }
+ }
+ const command = parseControlRequest(verb, args)
+ if ('error' in command) return { ok: false, error: command.error }
+
+ switch (command.verb) {
+ case 'open-terminal':
+ return actions.openTerminal(nodeId, command.args, verified)
+ case 'open-agent':
+ return actions.openAgent(nodeId, command.args, verified)
+ case 'sticky':
+ return actions.sticky(nodeId, command.args)
+ case 'send':
+ case 'reply':
+ case 'notify':
+ return actions.deliver({
+ verb: command.verb,
+ sourceNodeId: nodeId,
+ targetNodeId: command.args.node,
+ body: command.verb === 'notify' ? '' : command.args.text
+ })
+ default:
+ // `SERVER_V1_VERBS` and this switch are kept separate on purpose: the parser's wider
+ // ControlVerb union can grow without silently making a new server action reachable.
+ return {
+ ok: false,
+ error: CONTROL_UNSUPPORTED_ERROR,
+ message: unsupportedServerVerbMessage(verb)
+ }
+ }
+ }
+}
diff --git a/src/server/headless-node-factory.test.ts b/src/server/headless-node-factory.test.ts
new file mode 100644
index 000000000..a3e60d926
--- /dev/null
+++ b/src/server/headless-node-factory.test.ts
@@ -0,0 +1,248 @@
+import fs from 'node:fs'
+import os from 'node:os'
+import path from 'node:path'
+
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+
+import { fakePlatform } from '../core/platform-fake'
+import { initPlatform, resetPlatformForTests } from '../core/platform'
+import { WorkspaceStore } from '../core/workspace-store'
+import type { AgentState } from '../shared/agents/normalize'
+import {
+ DEFAULT_SETTINGS,
+ type CanvasNodeState,
+ type PtyCreateOptions,
+ type PtyCreateResult,
+ type Settings,
+ type Workspace
+} from '../shared/types'
+import { HeadlessNodeFactory, type HeadlessPty } from './headless-node-factory'
+
+class FakePty implements HeadlessPty {
+ readonly creates: PtyCreateOptions[] = []
+ readonly sends: Array<{ nodeId: string; text: string }> = []
+
+ async createHeadless(options: PtyCreateOptions): Promise<PtyCreateResult> {
+ this.creates.push(options)
+ return { sessionId: `pty-${options.persistKey}`, fresh: true, persistent: true }
+ }
+
+ async sendText(nodeId: string, text: string): Promise<boolean> {
+ this.sends.push({ nodeId, text })
+ return true
+ }
+}
+
+const terminal = (
+ id: string,
+ title: string,
+ agentId: 'claude' | 'codex' | 'gemini' = 'claude',
+ x = 20
+): CanvasNodeState => ({
+ id,
+ kind: 'terminal',
+ position: { x, y: 30 },
+ size: { width: 640, height: 440 },
+ title,
+ color: '#d97757',
+ group: null,
+ tags: [],
+ agentId
+})
+
+describe('HeadlessNodeFactory', () => {
+ let dataDir = ''
+ let projectDir = ''
+ let store: WorkspaceStore
+ let pty: FakePty
+ let states: Record<string, AgentState | undefined>
+ let published: CanvasNodeState[]
+ let factory: HeadlessNodeFactory
+
+ const settings = (): Settings => ({
+ ...DEFAULT_SETTINGS,
+ // Makes command expectations independent of the local Claude version probe.
+ claudePermissionMode: 'manual'
+ })
+
+ beforeEach(async () => {
+ dataDir = fs.mkdtempSync(path.join(os.tmpdir(), 'nodeterm-headless-factory-'))
+ projectDir = path.join(dataDir, 'project')
+ fs.mkdirSync(projectDir, { recursive: true })
+ resetPlatformForTests()
+ initPlatform(fakePlatform({ userDataDir: dataDir }))
+ store = new WorkspaceStore()
+ pty = new FakePty()
+ states = {}
+ published = []
+ const initial: Workspace = {
+ version: 2,
+ activeProjectId: 'project-1',
+ projects: [
+ {
+ id: 'project-1',
+ name: 'Test',
+ color: '#0a84ff',
+ cwd: projectDir,
+ viewport: { x: 0, y: 0, zoom: 1 },
+ nodes: [terminal('term-source', 'Director'), terminal('term-upstream', 'Upstream', 'codex', 80)],
+ bridges: [],
+ ropes: []
+ }
+ ]
+ }
+ await store.save(initial)
+ factory = new HeadlessNodeFactory({
+ workspaceStore: store,
+ ptyManager: pty,
+ settings,
+ cliCaps: async () => ({
+ version: null,
+ autoPermissionMode: false,
+ fullscreenTui: false,
+ sessionIdFlag: false
+ }),
+ stateOf: (id) => states[id],
+ publishNode: (_projectId, node) => published.push(node),
+ publishProject: vi.fn()
+ })
+ })
+
+ afterEach(() => {
+ factory.stop()
+ resetPlatformForTests()
+ fs.rmSync(dataDir, { recursive: true, force: true })
+ })
+
+ it('creates a terminal PTY, persists both workspace index and project file, and publishes it', async () => {
+ const reply = await factory.openTerminal(
+ 'term-source',
+ { cwd: projectDir, cmd: 'printf hello' },
+ true
+ )
+ expect(reply).toMatchObject({ ok: true, result: { id: expect.stringMatching(/^term-/) } })
+ const id = (reply.result as { id: string }).id
+
+ expect(pty.creates).toEqual([
+ expect.objectContaining({
+ cwd: projectDir,
+ cols: 120,
+ rows: 36,
+ persistKey: id,
+ ownerProjectId: 'project-1'
+ })
+ ])
+ expect(pty.sends).toEqual([{ nodeId: id, text: 'printf hello' }])
+ expect(published.map((node) => node.id)).toEqual([id])
+
+ expect(fs.existsSync(path.join(dataDir, 'workspace.json'))).toBe(true)
+ const projectFile = path.join(projectDir, '.nodeterm', 'project.json')
+ expect(fs.existsSync(projectFile)).toBe(true)
+ const raw = JSON.parse(fs.readFileSync(projectFile, 'utf8')) as { nodes: CanvasNodeState[] }
+ const created = raw.nodes.find((node) => node.id === id)
+ // Local project files store cwd portably; WorkspaceStore resolves it back to absolute on load.
+ expect(created).toMatchObject({ kind: 'terminal', cwd: '.' })
+ expect(created!.position.x).toBeGreaterThan(terminal('x', 'x').position.x)
+
+ const reloaded = await new WorkspaceStore().load({ sideline: false })
+ expect(reloaded.projects[0].nodes.find((node) => node.id === id)).toMatchObject({
+ cwd: projectDir
+ })
+ })
+
+ it.each([
+ ['claude', "claude 'do work'"],
+ ['codex', "codex 'do work' --ask-for-approval untrusted"],
+ ['gemini', "gemini 'do work'"]
+ ] as const)('assembles the %s launch through the shared command builder', async (agent, command) => {
+ const reply = await factory.openAgent(
+ 'term-source',
+ { agent, prompt: 'do work' },
+ true
+ )
+ expect(reply.ok).toBe(true)
+ const id = (reply.result as { id: string }).id
+ expect(pty.creates.at(-1)).toMatchObject({
+ persistKey: id,
+ ownerProjectId: 'project-1',
+ agentId: agent
+ })
+ expect(pty.sends.at(-1)).toEqual({ nodeId: id, text: command })
+ })
+
+ it('persists --after without launching, then flushes exactly once on the idle state', async () => {
+ states['term-upstream'] = 'working'
+ const reply = await factory.openAgent(
+ 'term-source',
+ { agent: 'claude', prompt: 'consume result', after: 'term-upstream' },
+ true
+ )
+ expect(reply.ok).toBe(true)
+ const id = (reply.result as { id: string }).id
+ expect(pty.sends).toEqual([])
+
+ let workspace = await store.load({ sideline: false })
+ expect(workspace.projects[0].nodes.find((node) => node.id === id)?.pendingLaunch).toEqual({
+ after: ['term-upstream'],
+ command: "claude 'consume result'",
+ executor: 'server'
+ })
+ expect(workspace.projects[0].bridges).toEqual(
+ expect.arrayContaining([
+ expect.objectContaining({ source: 'term-source', target: id }),
+ expect.objectContaining({ source: id, target: 'term-upstream' })
+ ])
+ )
+
+ states['term-upstream'] = 'done'
+ await factory.refreshArmed()
+ await factory.refreshArmed()
+ expect(pty.sends).toEqual([{ nodeId: id, text: "claude 'consume result'" }])
+ workspace = await store.load({ sideline: false })
+ expect(workspace.projects[0].nodes.find((node) => node.id === id)?.pendingLaunch).toBeUndefined()
+ })
+
+ it('creates and updates a persisted sticky with lineage and an accountable byline', async () => {
+ const createdReply = await factory.sticky('term-source', {
+ node: 'Round status',
+ create: 'yes',
+ text: 'Round 1 complete'
+ })
+ expect(createdReply).toMatchObject({
+ ok: true,
+ result: { id: expect.stringMatching(/^sticky-/), created: true, mode: 'replace' }
+ })
+ const id = (createdReply.result as { id: string }).id
+
+ let workspace = await store.load({ sideline: false })
+ expect(workspace.projects[0].nodes.find((node) => node.id === id)).toMatchObject({
+ kind: 'sticky',
+ title: 'Round status',
+ text: 'Round 1 complete',
+ textUpdatedBy: 'Director'
+ })
+ expect(workspace.projects[0].ropes).toEqual(
+ expect.arrayContaining([expect.objectContaining({ source: 'term-source', target: id })])
+ )
+
+ const updatedReply = await factory.sticky('term-source', {
+ node: id,
+ append: 'Round 2 ready'
+ })
+ expect(updatedReply).toMatchObject({
+ ok: true,
+ result: { id, created: false, mode: 'append' }
+ })
+ workspace = await store.load({ sideline: false })
+ expect(workspace.projects[0].nodes.find((node) => node.id === id)?.text).toBe(
+ 'Round 1 complete\nRound 2 ready'
+ )
+ expect(published.filter((node) => node.id === id)).toHaveLength(2)
+ })
+
+ it('refuses a non-v1 agent before a node or PTY is created', async () => {
+ const reply = await factory.openAgent('term-source', { agent: 'grok' }, true)
+ expect(reply).toMatchObject({ ok: false, error: expect.stringContaining('claude|codex|gemini') })
+ expect(pty.creates).toEqual([])
+ })
+})
diff --git a/src/server/headless-node-factory.ts b/src/server/headless-node-factory.ts
new file mode 100644
index 000000000..51fb8ef54
--- /dev/null
+++ b/src/server/headless-node-factory.ts
@@ -0,0 +1,597 @@
+import { randomBytes, randomUUID } from 'node:crypto'
+
+import { publishCanvasMutation } from '../core/canvas-sync'
+import { gateProjectTarget } from '../core/project-grants'
+import { applyStickyWrite, parseStickyArgs, resolveStickyRef } from '../shared/sticky-write'
+import type { WorkspaceStore } from '../core/workspace-store'
+import {
+ AGENT_CONFIG,
+ canContextLink,
+ canControlCanvas,
+ gatePermissionMode,
+ hasHooks,
+ resolvePermissionMode,
+ supportsSessionIdFlag,
+ type AgentId,
+ type BuiltinAgentId
+} from '../shared/agents/config'
+import { assembleLaunchCommand } from '../shared/agents/launch'
+import type { AgentState, NormalizedAgentEvent } from '../shared/agents/normalize'
+import { oneLine } from '../shared/one-line'
+import type {
+ BridgeLink,
+ CanvasNodeState,
+ ClaudeCliCaps,
+ Project,
+ PtyCreateOptions,
+ PtyCreateResult,
+ Settings,
+ Workspace
+} from '../shared/types'
+
+export interface ServerControlReply {
+ ok: boolean
+ message?: string
+ result?: unknown
+ error?: string
+}
+
+/** The PtyManager surface the headless factory uses, kept narrow for deterministic tests. */
+export interface HeadlessPty {
+ createHeadless(options: PtyCreateOptions): Promise<PtyCreateResult>
+ sendText(nodeId: string, text: string, opts?: { enter?: boolean }): Promise<boolean>
+}
+
+/** WorkspaceStore's mutation surface, also narrow so tests can use the real store or a fake. */
+export type HeadlessWorkspace = Pick<WorkspaceStore, 'load' | 'save'>
+
+export interface HeadlessNodeFactoryDeps {
+ workspaceStore: HeadlessWorkspace
+ ptyManager: HeadlessPty
+ settings(): Settings
+ cliCaps(): Promise<ClaudeCliCaps>
+ /** Hook-mirror lookups. A stored agentId wins; these cover a plain terminal running an agent. */
+ stateOf(nodeId: string): AgentState | undefined
+ agentIdOf?(nodeId: string): string | undefined
+ env?: Record<string, string | undefined>
+ now?: () => number
+ publishNode?: (projectId: string, node: CanvasNodeState) => void
+ publishProject?: (project: Project) => void
+ schedule?: (cb: () => void, ms: number) => ReturnType<typeof setTimeout>
+ clearSchedule?: (timer: ReturnType<typeof setTimeout>) => void
+}
+
+const TERMINAL_LIMIT = 8
+const AGENT_LIMIT = 5
+const TERMINAL_COLS = 120
+const TERMINAL_ROWS = 36
+const NODE_COLORS = ['#0a84ff', '#32d74b', '#ffd60a', '#ff453a', '#bf5af2', '#6ac4dc', '#ff9f0a']
+const TERMINAL_SIZE = { width: 640, height: 440 }
+const STICKY_SIZE = { width: 240, height: 200 }
+const H_GAP = 80
+const V_GAP = 36
+const AFTER_RETRY_MS = 500
+const AFTER_RETRY_LIMIT = 5
+const SERVER_AGENTS: ReadonlySet<string> = new Set(['claude', 'codex', 'gemini'])
+
+function token(): string {
+ return randomBytes(4).toString('hex')
+}
+
+function nextId(prefix: 'term' | 'sticky'): string {
+ return `${prefix}-${Date.now().toString(36)}-${token()}`
+}
+
+function edgeId(prefix: string, source: string, target: string): string {
+ return `${prefix}-${source}-${target}-${token()}`
+}
+
+function parseCount(raw: string | undefined, max: number): number {
+ return Math.max(1, Math.min(max, Number.parseInt(raw || '1', 10) || 1))
+}
+
+function terminalSize(settings: Settings): { width: number; height: number } {
+ const clamp = (value: unknown, min: number, max: number, fallback: number): number => {
+ const n = typeof value === 'number' && Number.isFinite(value) ? Math.round(value) : fallback
+ return Math.min(max, Math.max(min, n))
+ }
+ return {
+ width: clamp(settings.defaultNodeWidth, 280, 2400, TERMINAL_SIZE.width),
+ height: clamp(settings.defaultNodeHeight, 160, 1600, TERMINAL_SIZE.height)
+ }
+}
+
+function unsupportedFlags(
+ args: Record<string, string>,
+ allowed: ReadonlySet<string>
+): string | undefined {
+ const unknown = Object.keys(args).find((key) => !allowed.has(key))
+ return unknown ? `--${unknown} is not supported by Server Edition canvas control` : undefined
+}
+
+function sourceProject(workspace: Workspace, nodeId: string): { project: Project; node: CanvasNodeState } | null {
+ const matches: Array<{ project: Project; node: CanvasNodeState }> = []
+ for (const project of workspace.projects) {
+ const node = project.nodes.find((candidate) => candidate.id === nodeId)
+ if (node) matches.push({ project, node })
+ }
+ return matches.length === 1 ? matches[0] : null
+}
+
+function effectiveAgentId(
+ node: CanvasNodeState,
+ runtimeAgentId: ((nodeId: string) => string | undefined) | undefined
+): AgentId {
+ return (node.agentId || runtimeAgentId?.(node.id) || 'claude') as AgentId
+}
+
+function sourceCanControl(
+ node: CanvasNodeState,
+ runtimeAgentId: ((nodeId: string) => string | undefined) | undefined
+): boolean {
+ return canControlCanvas(effectiveAgentId(node, runtimeAgentId))
+}
+
+function absolutePosition(project: Project, node: CanvasNodeState): { x: number; y: number } {
+ let x = node.position.x
+ let y = node.position.y
+ let parent = node.parentId
+ const seen = new Set<string>()
+ while (parent && !seen.has(parent)) {
+ seen.add(parent)
+ const p = project.nodes.find((candidate) => candidate.id === parent)
+ if (!p) break
+ x += p.position.x
+ y += p.position.y
+ parent = p.parentId
+ }
+ return { x, y }
+}
+
+function placeRight(
+ project: Project,
+ source: CanvasNodeState,
+ index: number,
+ size: { width: number; height: number }
+): { x: number; y: number } {
+ const origin = absolutePosition(project, source)
+ const sourceWidth = source.size?.width || TERMINAL_SIZE.width
+ const column = Math.floor(index / 3)
+ const row = index % 3
+ return {
+ x: origin.x + sourceWidth + H_GAP + column * (size.width + H_GAP),
+ y: origin.y + row * (size.height + V_GAP)
+ }
+}
+
+function addEdge(list: BridgeLink[], source: string, target: string, prefix: string): void {
+ if (source === target) return
+ if (list.some((edge) =>
+ (edge.source === source && edge.target === target) ||
+ (edge.source === target && edge.target === source))) return
+ list.push({ id: edgeId(prefix, source, target), source, target })
+}
+
+function ptyOptions(project: Project, node: CanvasNodeState): PtyCreateOptions {
+ return {
+ cwd: node.cwd || project.cwd,
+ cols: TERMINAL_COLS,
+ rows: TERMINAL_ROWS,
+ persistKey: node.id,
+ ownerProjectId: project.id,
+ ...(node.agentId ? { agentId: node.agentId } : {}),
+ ...(node.agentModel ? { agentModel: node.agentModel } : {}),
+ ...(node.accountId ? { accountId: node.accountId } : {})
+ }
+}
+
+/**
+ * Server-side canvas authoring and launch scheduler.
+ *
+ * Every workspace read/modify/save transaction is serialized. That is important even on one
+ * Node event loop: WorkspaceStore.load/save both await filesystem operations, so two simultaneous
+ * `/control/open-agent` calls would otherwise read the same snapshot and the later save would
+ * erase the earlier node. PTY creation happens after the node is durable, matching the renderer's
+ * recoverable failure direction: a spawn error leaves a visible, reopenable node instead of an
+ * invisible tmux session.
+ */
+export class HeadlessNodeFactory {
+ private serial: Promise<unknown> = Promise.resolve()
+ private attached = new Set<string>()
+ private retryCount = new Map<string, number>()
+ private retryTimers = new Map<string, ReturnType<typeof setTimeout>>()
+ private stopped = false
+
+ constructor(private readonly deps: HeadlessNodeFactoryDeps) {}
+
+ private runExclusive<T>(work: () => Promise<T>): Promise<T> {
+ const run = this.serial.then(work, work)
+ this.serial = run.then(
+ () => undefined,
+ () => undefined
+ )
+ return run
+ }
+
+ private publish(project: Project, nodes: readonly CanvasNodeState[]): void {
+ this.deps.publishProject?.(project)
+ const publish = this.deps.publishNode ?? ((projectId: string, node: CanvasNodeState) => {
+ publishCanvasMutation(projectId, { op: 'upsert', node })
+ })
+ for (const node of nodes) publish(project.id, node)
+ }
+
+ private async attach(project: Project, node: CanvasNodeState): Promise<PtyCreateResult> {
+ if (this.attached.has(node.id)) {
+ return { sessionId: node.id, fresh: false }
+ }
+ const result = await this.deps.ptyManager.createHeadless(ptyOptions(project, node))
+ if (result.sessionId) this.attached.add(node.id)
+ return result
+ }
+
+ private resolveTarget(
+ workspace: Workspace,
+ source: { project: Project; node: CanvasNodeState },
+ verb: string,
+ args: Record<string, string>,
+ verified: boolean
+ ): Project | ServerControlReply {
+ const targetId = args.project || source.project.id
+ const target = workspace.projects.find((project) => project.id === targetId)
+ const gate = gateProjectTarget({
+ verified,
+ verb,
+ targetProjectId: args.project || undefined,
+ callerProjectId: source.project.id,
+ targetIsSsh: target ? !!target.ssh : undefined,
+ // `open-project` is not part of Server Edition v1, so this runtime never mints a grant.
+ granted: false
+ })
+ if (gate !== 'allow') return { ok: false, error: gate.refuse }
+ if (!target) return { ok: false, error: 'project-target-refused: target project is unavailable' }
+ if (target.ssh) {
+ return {
+ ok: false,
+ error: 'project-target-ssh-unsupported: Server Edition v1 only creates local sessions'
+ }
+ }
+ return target
+ }
+
+ private resolveAfter(
+ project: Project,
+ raw: string | undefined,
+ verb: string
+ ): string[] | ServerControlReply {
+ if (!raw) return []
+ const ids = [...new Set(raw.split(',').map((id) => id.trim()).filter(Boolean))]
+ for (const id of ids) {
+ const node = project.nodes.find((candidate) => candidate.id === id)
+ if (!node) return { ok: false, error: `${verb}: --after names no existing node (${id})` }
+ const agentId = effectiveAgentId(node, this.deps.agentIdOf)
+ if (!hasHooks(agentId)) {
+ return {
+ ok: false,
+ error: `${verb}: --after ${id} is not an agent session that reports when it is done`
+ }
+ }
+ }
+ return ids
+ }
+
+ async openTerminal(
+ sourceNodeId: string,
+ args: Record<string, string>,
+ verified: boolean
+ ): Promise<ServerControlReply> {
+ return this.open(sourceNodeId, 'open-terminal', args, verified)
+ }
+
+ async openAgent(
+ sourceNodeId: string,
+ args: Record<string, string>,
+ verified: boolean
+ ): Promise<ServerControlReply> {
+ return this.open(sourceNodeId, 'open-agent', args, verified)
+ }
+
+ private open(
+ sourceNodeId: string,
+ verb: 'open-terminal' | 'open-agent',
+ args: Record<string, string>,
+ verified: boolean
+ ): Promise<ServerControlReply> {
+ return this.runExclusive(async () => {
+ const flagError = unsupportedFlags(
+ args,
+ verb === 'open-terminal'
+ ? new Set(['count', 'cwd', 'cmd', 'after', 'project'])
+ : new Set(['agent', 'count', 'cwd', 'prompt', 'after', 'project', 'model'])
+ )
+ if (flagError) return { ok: false, error: `${verb}: ${flagError}` }
+
+ const workspace = await this.deps.workspaceStore.load({ sideline: false })
+ const source = sourceProject(workspace, sourceNodeId)
+ if (!source) return { ok: false, error: 'source node is not in exactly one saved project' }
+ if (!sourceCanControl(source.node, this.deps.agentIdOf)) {
+ return { ok: false, error: 'source node is not a control-capable agent' }
+ }
+ const target = this.resolveTarget(workspace, source, verb, args, verified)
+ if ('ok' in target) return target
+ const after = this.resolveAfter(target, args.after, verb)
+ if (!Array.isArray(after)) return after
+
+ const settings = this.deps.settings()
+ const nodeSize = terminalSize(settings)
+ const caps = verb === 'open-agent' ? await this.deps.cliCaps() : null
+ const agentId = args.agent as BuiltinAgentId | undefined
+ if (verb === 'open-agent' && (!agentId || !SERVER_AGENTS.has(agentId))) {
+ return {
+ ok: false,
+ error: 'open-agent: Server Edition v1 supports --agent claude|codex|gemini'
+ }
+ }
+
+ const count = parseCount(args.count, verb === 'open-terminal' ? TERMINAL_LIMIT : AGENT_LIMIT)
+ const created: CanvasNodeState[] = []
+ const commands = new Map<string, string>()
+ const ropes = [...(target.ropes ?? [])]
+ const bridges = [...(target.bridges ?? [])]
+ const startIndex = target.nodes.length
+ const cwd = args.cwd || (target.id === source.project.id ? source.node.cwd : undefined) || target.cwd
+
+ for (let i = 0; i < count; i++) {
+ let command = args.cmd
+ let title = `Terminal ${startIndex + i + 1}`
+ let color = NODE_COLORS[(startIndex + i) % NODE_COLORS.length]
+ let mintedSessionId: string | undefined
+ let permissionMode
+ if (verb === 'open-agent') {
+ const config = AGENT_CONFIG[agentId as BuiltinAgentId]
+ title = config.label
+ color = config.color
+ const resolvedMode = resolvePermissionMode(target, settings)
+ permissionMode = agentId === 'claude'
+ ? gatePermissionMode(resolvedMode, caps?.autoPermissionMode === true)
+ : resolvedMode
+ const sessionIdFlagSupported = supportsSessionIdFlag(
+ agentId as AgentId,
+ caps?.sessionIdFlag === true
+ )
+ mintedSessionId = sessionIdFlagSupported ? randomUUID() : undefined
+ command = assembleLaunchCommand(
+ {
+ agentId: agentId as AgentId,
+ initialPrompt: args.prompt,
+ permissionMode,
+ sessionId: mintedSessionId,
+ sessionIdFlagSupported,
+ launchCmdOverride: settings.agentLaunchCommands?.[agentId as BuiltinAgentId],
+ sharedIdentity: false,
+ model: args.model
+ },
+ this.deps.env ?? process.env
+ ).command
+ }
+
+ const id = nextId('term')
+ // Match the desktop's `armAfter`: if every dependency is already done, launch now rather
+ // than persisting a wait that has no future edge left to wake it.
+ const mustWait = after.some((depId) => this.deps.stateOf(depId) !== 'done')
+ const pendingLaunch = command && mustWait
+ ? { after, command, executor: 'server' as const }
+ : undefined
+ const node: CanvasNodeState = {
+ id,
+ kind: 'terminal',
+ position: placeRight(target, source.node, i, nodeSize),
+ size: { ...nodeSize },
+ title,
+ ...(verb === 'open-agent' ? { titleAuto: true } : {}),
+ color,
+ group: null,
+ tags: [],
+ cwd,
+ ...(verb === 'open-agent' ? { agentId: agentId as AgentId } : {}),
+ ...(args.model && verb === 'open-agent' ? { agentModel: args.model } : {}),
+ ...(mintedSessionId ? { agentSessionId: mintedSessionId } : {}),
+ ...(source.node.accountId && verb === 'open-agent' &&
+ (agentId === 'claude' || agentId === 'codex')
+ ? { accountId: source.node.accountId }
+ : {}),
+ ...(pendingLaunch ? { pendingLaunch } : {})
+ }
+ created.push(node)
+ if (command && !pendingLaunch) commands.set(id, command)
+ addEdge(ropes, source.node.id, id, 'ctrl')
+
+ if (verb === 'open-agent') {
+ const sourceAgent = effectiveAgentId(source.node, this.deps.agentIdOf)
+ if (canContextLink(sourceAgent) && canContextLink(agentId as AgentId)) {
+ addEdge(bridges, source.node.id, id, 'link')
+ }
+ for (const depId of after) {
+ const dep = target.nodes.find((candidate) => candidate.id === depId)
+ if (dep && canContextLink(effectiveAgentId(dep, this.deps.agentIdOf)) &&
+ canContextLink(agentId as AgentId)) addEdge(bridges, id, depId, 'link')
+ }
+ }
+ }
+
+ target.nodes.push(...created)
+ target.ropes = ropes
+ target.bridges = bridges
+ await this.deps.workspaceStore.save(workspace)
+ this.publish(target, created)
+
+ const failed: string[] = []
+ for (const node of created) {
+ try {
+ const result = await this.attach(target, node)
+ if (!result.sessionId) {
+ failed.push(node.id)
+ continue
+ }
+ const command = commands.get(node.id)
+ if (command && !(await this.deps.ptyManager.sendText(node.id, command))) failed.push(node.id)
+ } catch {
+ failed.push(node.id)
+ }
+ }
+
+ const ids = created.map((node) => node.id)
+ if (failed.length) {
+ return {
+ ok: false,
+ error:
+ `launch-failed: node(s) ${failed.join(', ')} were persisted but their PTY or initial ` +
+ 'command could not be started; do not repeat the open request',
+ result: { ids, id: ids[0], after, failed }
+ }
+ }
+ return {
+ ok: true,
+ message:
+ `opened ${count} ${verb === 'open-agent' ? `${agentId} session` : 'terminal'}(s): ` +
+ ids.join(', ') +
+ (after.length ? `; waiting for ${after.join(', ')} before running` : ''),
+ result: { ids, id: ids[0], after }
+ }
+ })
+ }
+
+ sticky(sourceNodeId: string, args: Record<string, string>): Promise<ServerControlReply> {
+ return this.runExclusive(async () => {
+ const parsed = parseStickyArgs(args)
+ if ('error' in parsed) return { ok: false, error: `sticky: ${parsed.error}` }
+ const workspace = await this.deps.workspaceStore.load({ sideline: false })
+ const source = sourceProject(workspace, sourceNodeId)
+ if (!source) return { ok: false, error: 'source node is not in exactly one saved project' }
+ if (!sourceCanControl(source.node, this.deps.agentIdOf)) {
+ return { ok: false, error: 'source node is not a control-capable agent' }
+ }
+
+ const candidates = source.project.nodes.map((node) => ({
+ id: node.id,
+ sticky: node.kind === 'sticky',
+ title: node.title
+ }))
+ const resolved = resolveStickyRef(candidates, parsed.ref)
+ if ('error' in resolved) return { ok: false, error: `sticky: ${resolved.error}` }
+
+ let node: CanvasNodeState | undefined
+ let created = false
+ if ('id' in resolved) node = source.project.nodes.find((candidate) => candidate.id === resolved.id)
+ else if (parsed.create) {
+ created = true
+ node = {
+ id: nextId('sticky'),
+ kind: 'sticky',
+ position: placeRight(source.project, source.node, 0, STICKY_SIZE),
+ size: { ...STICKY_SIZE },
+ title: oneLine(parsed.ref) || 'Note',
+ color: '#ffd60a',
+ group: null,
+ text: ''
+ }
+ source.project.nodes.push(node)
+ const ropes = [...(source.project.ropes ?? [])]
+ addEdge(ropes, source.node.id, node.id, 'ctrl')
+ source.project.ropes = ropes
+ } else {
+ return {
+ ok: false,
+ error: `sticky: no note named "${parsed.ref}"; pass --create yes to create it`
+ }
+ }
+ if (!node) return { ok: false, error: 'sticky: note disappeared while resolving it' }
+
+ const write = applyStickyWrite(node.text ?? '', parsed.write)
+ if ('error' in write) return { ok: false, error: `sticky: ${write.error}` }
+ node.text = write.text
+ node.textUpdatedAt = (this.deps.now ?? Date.now)()
+ node.textUpdatedBy = source.node.title || source.node.id
+ await this.deps.workspaceStore.save(workspace)
+ this.publish(source.project, [node])
+ return {
+ ok: true,
+ message: `${created ? 'created' : 'updated'} sticky ${node.id} (${write.mode})`,
+ result: { id: node.id, created, mode: write.mode }
+ }
+ })
+ }
+
+ /** Reattach persisted server-owned armed nodes at boot, then fire anything already satisfied. */
+ start(): Promise<void> {
+ return this.refreshArmed()
+ }
+
+ onAgentEvent(event: Pick<NormalizedAgentEvent, 'nodeId' | 'state'>): void {
+ if (!this.stopped && event?.nodeId && event.state === 'done') void this.refreshArmed()
+ }
+
+ refreshArmed(): Promise<void> {
+ return this.runExclusive(async () => {
+ if (this.stopped) return
+ const workspace = await this.deps.workspaceStore.load({ sideline: false })
+ const changedByProject = new Map<Project, CanvasNodeState[]>()
+
+ for (const project of workspace.projects) {
+ for (const node of project.nodes) {
+ const pending = node.pendingLaunch
+ if (!pending || pending.executor !== 'server' || !pending.command) continue
+ try {
+ const result = await this.attach(project, node)
+ if (!result.sessionId) continue
+ } catch {
+ this.scheduleRetry(node.id)
+ continue
+ }
+
+ const ready = pending.after.every((depId) => {
+ const stillExists = project.nodes.some((candidate) => candidate.id === depId)
+ return !stillExists || this.deps.stateOf(depId) === 'done'
+ })
+ if (!ready) continue
+ if (!(await this.deps.ptyManager.sendText(node.id, pending.command))) {
+ this.scheduleRetry(node.id)
+ continue
+ }
+ node.pendingLaunch = undefined
+ this.retryCount.delete(node.id)
+ const timer = this.retryTimers.get(node.id)
+ if (timer) (this.deps.clearSchedule ?? clearTimeout)(timer)
+ this.retryTimers.delete(node.id)
+ const list = changedByProject.get(project) ?? []
+ list.push(node)
+ changedByProject.set(project, list)
+ }
+ }
+
+ if (changedByProject.size) {
+ await this.deps.workspaceStore.save(workspace)
+ for (const [project, nodes] of changedByProject) this.publish(project, nodes)
+ }
+ })
+ }
+
+ private scheduleRetry(nodeId: string): void {
+ if (this.stopped || this.retryTimers.has(nodeId)) return
+ const count = (this.retryCount.get(nodeId) ?? 0) + 1
+ this.retryCount.set(nodeId, count)
+ if (count > AFTER_RETRY_LIMIT) return
+ const schedule = this.deps.schedule ?? ((cb: () => void, ms: number) => setTimeout(cb, ms))
+ const timer = schedule(() => {
+ this.retryTimers.delete(nodeId)
+ void this.refreshArmed()
+ }, AFTER_RETRY_MS)
+ this.retryTimers.set(nodeId, timer)
+ }
+
+ stop(): void {
+ this.stopped = true
+ for (const timer of this.retryTimers.values()) (this.deps.clearSchedule ?? clearTimeout)(timer)
+ this.retryTimers.clear()
+ }
+}
diff --git a/src/server/index.ts b/src/server/index.ts
index b83b224d7..0c8122f60 100644
--- a/src/server/index.ts
+++ b/src/server/index.ts
@@ -48,6 +48,7 @@ import { registerLogHandlers } from '../core/log-handlers'
import os from 'os'
import { hookServer } from '../core/agents/hook-server'
import { serverEditionControlHandler } from './control-unsupported'
+import { initServerCanvasControl, type ServerCanvasControl } from './canvas-control'
import { refreshNodeTokens } from '../core/agents/node-token-service'
import { armServerNodeIdentity } from './node-identity-arm'
import {
@@ -336,7 +337,7 @@ export async function startServer(
// Board-log: same CorePlatform registrar as desktop, but the Server Edition has no SSH projects
// (terminals are local), so the router only ever resolves a local folder cwd or unsupported —
// an SSH-ref project answers `{ entries: [], unsupported: true }` (v1: no remote board log here).
- registerBoardLogHandlers(platform, {
+ const boardLog = registerBoardLogHandlers(platform, {
route: (projectId: string): BoardLogRoute => {
const cwd = workspaceStore.localCwdForProject(projectId)
return cwd ? { kind: 'local', cwd } : { kind: 'unsupported' }
@@ -406,7 +407,12 @@ export async function startServer(
// missing/corrupt file simply yields no block.
const installMeta = readInstallMeta(config.dataDir)
setMirrorServerProvider(() => installMeta)
- const { contextTail, geminiContextTail } = wireAgentStatus(platform)
+ // Set after the initial workspace load when the opt-in flag is on. The status listener is wired
+ // now so the runtime, once present, consumes the exact same normalized stream as the UI/mirror.
+ let canvasControl: ServerCanvasControl | null = null
+ const { contextTail, geminiContextTail } = wireAgentStatus(platform, {
+ onEvent: (event) => canvasControl?.onAgentEvent(event)
+ })
// The ⌘M chat view + the find-bar's transcript index. Registered HERE rather than with the rest
// of the handlers because the hook-fed path authority is the tail created just above. No remote
// leg: the Server Edition runs ON the host whose transcripts it reads, so local resolution is
@@ -519,14 +525,14 @@ export async function startServer(
}
// Managed Claude accounts each carry their OWN settings.json (Claude Code resolves it relative
// to CLAUDE_CONFIG_DIR), so the hook has to be re-installed there as well or a managed account
- // reports no agent status at all. Same loop the desktop runs, minus the canvas skill: canvas
- // control is not wired on this edition. Per-account fail-open lives inside the helper.
+ // reports no agent status at all. Canvas-control adds its skill in its own opt-in initializer;
+ // this baseline hook pass stays unchanged when the feature flag is off.
installHooksIntoLocalAccounts(settingsStore.get().claudeAccounts ?? [])
}
await hookServer.start()
- // Canvas control does not exist on this edition, and saying so BY NAME is the whole point: the
- // null handler answered `control unavailable`, which reads to an agent like a transient outage,
- // and an agent retries an outage. See `control-unsupported.ts`.
+ // Safe default and rollback path. The opt-in runtime replaces this handler only after its
+ // workspace-backed services are ready; a failed initialization therefore degrades to the same
+ // named permanent refusal rather than a half-wired execution surface.
hookServer.setControlHandler(serverEditionControlHandler)
// ---- Node identity (src/core/agents/node-auth-secret.ts) ------------------------------------
@@ -572,6 +578,24 @@ export async function startServer(
console.warn('[nodeterm-server] context-link initial workspace load failed', e)
})
+ if (config.canvasControl === true) {
+ try {
+ canvasControl = await initServerCanvasControl({
+ workspaceStore,
+ ptyManager,
+ settings: () => settingsStore.get(),
+ boardLog,
+ installAgentIntegrations: config.installHooks !== false
+ })
+ hookServer.setControlHandler(canvasControl.handler)
+ } catch (error) {
+ console.warn(
+ '[nodeterm-server] Server Edition canvas control failed to initialize; keeping it disabled',
+ error
+ )
+ }
+ }
+
// Session budget (docs/SERVER.md): reap long-idle DETACHED nt- tmux sessions under memory
// pressure (10%-of-RAM watermark) or past a count cap, on BOTH the local socket and the
// SSH-remote socket (`nodeterm-rmt`) — a host serving SSH projects accumulates sessions there,
@@ -674,6 +698,7 @@ export async function startServer(
sessionReaper.stop()
pressure.stop()
ptyPressure.stop()
+ canvasControl?.stop()
await contextLink.stop()
await ptyManager.killAll()
// Same native hazard as the desktop app: a whisper transcribe still running when the
@@ -729,6 +754,7 @@ export async function startServer(
sessionReaper.stop()
pressure.stop()
ptyPressure.stop()
+ canvasControl?.stop()
await contextLink.stop()
await ptyManager.killAll()
// Same native hazard as the desktop app: a whisper transcribe still running when the node
diff --git a/src/shared/agents/launch.ts b/src/shared/agents/launch.ts
index ecf6b1416..1c0007690 100644
--- a/src/shared/agents/launch.ts
+++ b/src/shared/agents/launch.ts
@@ -1,12 +1,12 @@
// Pure command assembly — the ONE place an agent's launch / resume command line is built.
//
-// Used by the renderer only: fresh node creation (`workspace.ts createAgentNode`), cold-restore /
-// wake / variant resume (`TerminalNode.tsx`), and the Settings command preview
-// (`CustomAgentsSection.tsx`). Pure: the environment is an explicit parameter, and every caller
-// passes the SAME boot-time snapshot (src/renderer/lib/agentEnv.ts) — one assembler, one env, so
-// the preview cannot drift from the real launch by construction. There is deliberately no
-// main/server preview IPC: an endpoint that expands ${env:…} for a caller-supplied agent record
-// is an environment-variable oracle for relay peers (the #171/#190 review).
+// Used by the renderer for fresh node creation, cold restore, wake, variant resume and Settings
+// preview, and by Server Edition's headless node factory for fresh launches. Pure: the environment
+// is an explicit parameter. Renderer callers pass the SAME boot-time snapshot
+// (`src/renderer/lib/agentEnv.ts`), so its preview cannot drift from its launch by construction;
+// the server passes its own process environment directly and exposes no preview endpoint. There is
+// deliberately no main/server preview IPC: expanding ${env:…} for a caller-supplied agent record
+// would be an environment-variable oracle for relay peers (the #171/#190 review).
//
// Inheritance: a custom agent with a `baseAgent` resolves its prompt convention, separator, and
// capability flags through that base harness (`capabilityAgentId`), so a claude-compatible proxy
diff --git a/src/shared/types.ts b/src/shared/types.ts
index 4ccd6b1b0..3afe2cbbf 100644
--- a/src/shared/types.ts
+++ b/src/shared/types.ts
@@ -295,6 +295,12 @@ export interface PendingLaunch {
after: string[]
/** Delivered to the node's shell once the wait is over (agent CLI + prompt, or a plain command). */
command: string
+ /**
+ * Which core process owns delivery. Absent is the historical renderer-owned path. Server
+ * Edition headless opens stamp `server`, so a connected browser can render the armed state and
+ * dependency edges without racing the server to type the command into the same pane.
+ */
+ executor?: 'server'
/**
* Also wait for this worktree GROUP's project setup script to finish (`waitForSetup`). Set when
* the node is opened into a frame whose checkout is still being prepared — running a command in a