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.

fix(server): clean up headless canvas nodes

freshjuicez4207e8d9de4c
diff --git a/src/core/canvas-control-core.ts b/src/core/canvas-control-core.ts
index be689a8e4..510595685 100644
--- a/src/core/canvas-control-core.ts
+++ b/src/core/canvas-control-core.ts
@@ -337,7 +337,9 @@ export function buildCanvasControlInstructions(shimPath: string): string {
'- `branch --node <id>` — branch a Claude node\'s conversation (Claude nodes only).',
'- `rename --node <id> --title "New Name"` — rename any node (terminals, groups, stickies…).',
'- `write --node <id> --text "..."` / `close --node <id>` — type into / close a node.',
- ' Both ask the user to confirm a dialog and may be denied.',
+ ' Desktop asks the user to confirm both. Server Edition close is narrower: only nodes this',
+ ' caller opened during the current server run can be closed, and those close without a dialog;',
+ ' every other target receives a named ownership refusal.',
'- `send --node <id> --text "..."` / `reply --node <id> --text "..."` — deliver a message into',
' another AGENT node in this project (no confirm dialog: verified-only, gated by the project\'s',
' agent-messaging switch — off by default — and rate-limited). A busy target is not interrupted',
@@ -690,7 +692,9 @@ Verbs:
branch and a new node opens resuming the original. Target must be a Claude agent node.
- \`rename --node <id> --title "New Name"\` — rename any node (terminals, groups, stickies…).
- \`write --node <id> --text "..."\` — type text into a terminal node. (Asks the user to confirm.)
-- \`close --node <id>\` — close a node. (Asks the user to confirm.)
+- \`close --node <id>\` — close a node. Desktop asks the user to confirm. Server Edition closes
+ only nodes this caller opened during the current server run, without a dialog; every other
+ target receives a named ownership refusal.
- \`send --node <id> --text "..."\` — deliver a message INTO another agent node's session, in this
project only. No confirm dialog; instead it is verified-only, gated by the project's
agent-messaging switch (Settings → Agents, OFF by default), and rate-limited. Delivery lands when
@@ -733,7 +737,8 @@ ${messagingGuidanceLines().join('\n')}
${browserGuidanceLines().join('\n')}
Notes:
-- \`write\` and \`close\` require the user to approve a confirmation dialog; they may be denied.
+- \`write\` requires the user to approve a confirmation dialog. Desktop \`close\` does too;
+ Server Edition uses the process-local ownership rule described above instead.
- \`board\` and \`assign\` act on the CURRENTLY OPEN project's board — the same one you see when you
toggle the kanban view. They need no confirmation.
- If the CLI says canvas control is unavailable, you are not in a controllable nodeterm session — do not retry.
diff --git a/src/renderer/bridge/ws-bridge.ts b/src/renderer/bridge/ws-bridge.ts
index 5d1ddceca..ade8bcd03 100644
--- a/src/renderer/bridge/ws-bridge.ts
+++ b/src/renderer/bridge/ws-bridge.ts
@@ -295,11 +295,10 @@ 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),
- // 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.
+ // Server Edition runs the shared WorkspaceWatcher and broadcasts outside file edits here.
+ // Core-originated mutations use the same 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.
onExternalChange: (cb) => client.subscribe(IPC.workspaceExternalChange, cb as Listener)
}
diff --git a/src/server/canvas-control.test.ts b/src/server/canvas-control.test.ts
index 2c885a71c..adab27939 100644
--- a/src/server/canvas-control.test.ts
+++ b/src/server/canvas-control.test.ts
@@ -98,6 +98,7 @@ describe('initServerCanvasControl', () => {
const pty = {
createHeadless: vi.fn(async () => ({ sessionId: 'unused', fresh: true })),
sendText: vi.fn(async () => true),
+ destroySession: vi.fn(async () => undefined),
paneOwner,
sendEnvelope,
hasLiveSession: () => true
@@ -208,6 +209,7 @@ describe('initServerCanvasControl', () => {
} as never))
return true
}),
+ destroySession: vi.fn(async () => undefined),
paneOwner: vi.fn(async () => ({
tty: '/dev/pts/9',
panePid: 100,
diff --git a/src/server/canvas-control.ts b/src/server/canvas-control.ts
index f001a0663..21d86f03a 100644
--- a/src/server/canvas-control.ts
+++ b/src/server/canvas-control.ts
@@ -167,6 +167,7 @@ export async function initServerCanvasControl(
openTerminal: (sourceNodeId, args, verified) =>
factory.openTerminal(sourceNodeId, args, verified),
openAgent: (sourceNodeId, args, verified) => factory.openAgent(sourceNodeId, args, verified),
+ close: (sourceNodeId, args, verified) => factory.close(sourceNodeId, args, verified),
sticky: (sourceNodeId, args) => factory.sticky(sourceNodeId, args),
deliver: async (input) => (await deliverFromControl(input, messaging)).reply
}
diff --git a/src/server/control-unsupported.test.ts b/src/server/control-unsupported.test.ts
index 6a0c3315b..c63e3ca9c 100644
--- a/src/server/control-unsupported.test.ts
+++ b/src/server/control-unsupported.test.ts
@@ -175,6 +175,7 @@ describe('the enabled Server Edition handler parses and dispatches the v1 surfac
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' } })),
+ close: vi.fn(async () => ({ ok: true as const, result: { id: 'closed' } })),
sticky: vi.fn(async () => ({ ok: true as const, result: { id: 'sticky-new' } })),
deliver: vi.fn(async () => ({ ok: true as const, message: 'queued' }))
})
@@ -200,6 +201,20 @@ describe('the enabled Server Edition handler parses and dispatches the v1 surfac
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()
+
+ await expect(
+ handler({
+ verb: 'close',
+ nodeId: 'term-source',
+ args: { node: 'term-new,term-other' },
+ verified: true
+ })
+ ).resolves.toMatchObject({ ok: true })
+ expect(a.close).toHaveBeenCalledWith(
+ 'term-source',
+ { node: 'term-new,term-other' },
+ true
+ )
})
it('routes messaging without trusting a notify body', async () => {
diff --git a/src/server/control-unsupported.ts b/src/server/control-unsupported.ts
index dc8b622c7..3b717057e 100644
--- a/src/server/control-unsupported.ts
+++ b/src/server/control-unsupported.ts
@@ -74,6 +74,11 @@ export interface ServerEditionControlActions {
args: Record<string, string>,
verified: boolean
): Promise<ServerControlReply>
+ close(
+ 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'
@@ -86,6 +91,7 @@ export interface ServerEditionControlActions {
const SERVER_V1_VERBS: ReadonlySet<string> = new Set([
'open-terminal',
'open-agent',
+ 'close',
'send',
'reply',
'notify',
@@ -129,6 +135,8 @@ export function createServerEditionControlHandler(actions: ServerEditionControlA
return actions.openTerminal(nodeId, command.args, verified)
case 'open-agent':
return actions.openAgent(nodeId, command.args, verified)
+ case 'close':
+ return actions.close(nodeId, command.args, verified)
case 'sticky':
return actions.sticky(nodeId, command.args)
case 'send':
diff --git a/src/server/headless-node-factory.test.ts b/src/server/headless-node-factory.test.ts
index 7b1f99956..edc73c504 100644
--- a/src/server/headless-node-factory.test.ts
+++ b/src/server/headless-node-factory.test.ts
@@ -21,9 +21,18 @@ import { HeadlessNodeFactory, type HeadlessPty } from './headless-node-factory'
class FakePty implements HeadlessPty {
readonly creates: PtyCreateOptions[] = []
readonly sends: Array<{ nodeId: string; text: string }> = []
+ readonly destroys: Array<{
+ clientId: number | null
+ nodeId: string
+ everySocket: boolean | undefined
+ wasLive: boolean
+ }> = []
+ readonly live = new Set<string>()
+ readonly alreadyDead = new Set<string>()
async createHeadless(options: PtyCreateOptions): Promise<PtyCreateResult> {
this.creates.push(options)
+ if (options.persistKey) this.live.add(options.persistKey)
return { sessionId: `pty-${options.persistKey}`, fresh: true, persistent: true }
}
@@ -31,6 +40,21 @@ class FakePty implements HeadlessPty {
this.sends.push({ nodeId, text })
return true
}
+
+ async destroySession(
+ clientId: number | null,
+ nodeId: string,
+ opts?: { everySocket?: boolean }
+ ): Promise<void> {
+ const wasLive = this.live.delete(nodeId)
+ this.destroys.push({ clientId, nodeId, everySocket: opts?.everySocket, wasLive })
+ this.alreadyDead.add(nodeId)
+ }
+
+ killOutOfBand(nodeId: string): void {
+ this.live.delete(nodeId)
+ this.alreadyDead.add(nodeId)
+ }
}
const terminal = (
@@ -57,6 +81,8 @@ describe('HeadlessNodeFactory', () => {
let pty: FakePty
let states: Record<string, AgentState | undefined>
let published: CanvasNodeState[]
+ let removed: string[]
+ let publishedProjects: Workspace['projects']
let factory: HeadlessNodeFactory
const settings = (): Settings => ({
@@ -75,6 +101,8 @@ describe('HeadlessNodeFactory', () => {
pty = new FakePty()
states = {}
published = []
+ removed = []
+ publishedProjects = []
const initial: Workspace = {
version: 2,
activeProjectId: 'project-1',
@@ -104,7 +132,8 @@ describe('HeadlessNodeFactory', () => {
}),
stateOf: (id) => states[id],
publishNode: (_projectId, node) => published.push(node),
- publishProject: vi.fn()
+ publishRemoval: (_projectId, nodeId) => removed.push(nodeId),
+ publishProject: (project) => publishedProjects.push(structuredClone(project))
})
})
@@ -150,6 +179,113 @@ describe('HeadlessNodeFactory', () => {
})
})
+ it('lets a verified caller close its own spawn, killing the pane before persisted edge removal and fanout', async () => {
+ const opened = await factory.openAgent(
+ 'term-source',
+ { agent: 'claude', prompt: 'owned work' },
+ true
+ )
+ const id = (opened.result as { id: string }).id
+ const closed = await factory.close('term-source', { node: id }, true)
+
+ expect(closed).toMatchObject({ ok: true, result: { ids: [id] } })
+ expect(pty.destroys).toEqual([
+ { clientId: null, nodeId: id, everySocket: true, wasLive: true }
+ ])
+ expect(removed).toEqual([id])
+
+ const workspace = await new WorkspaceStore().load({ sideline: false })
+ const project = workspace.projects[0]
+ expect(project.nodes.some((node) => node.id === id)).toBe(false)
+ expect(project.ropes?.some((edge) => edge.source === id || edge.target === id)).toBe(false)
+ expect(project.bridges?.some((edge) => edge.source === id || edge.target === id)).toBe(false)
+ expect(publishedProjects.at(-1)?.nodes.some((node) => node.id === id)).toBe(false)
+
+ const projectFile = JSON.parse(
+ fs.readFileSync(path.join(projectDir, '.nodeterm', 'project.json'), 'utf8')
+ ) as {
+ nodes: CanvasNodeState[]
+ ropes?: Array<{ source: string; target: string }>
+ bridges?: Array<{ source: string; target: string }>
+ }
+ expect(projectFile.nodes.some((node) => node.id === id)).toBe(false)
+ expect(projectFile.ropes?.some((edge) => edge.source === id || edge.target === id)).toBe(false)
+ expect(projectFile.bridges?.some((edge) => edge.source === id || edge.target === id)).toBe(false)
+ })
+
+ it('refuses a different caller without killing or removing the owned spawn', async () => {
+ const opened = await factory.openTerminal('term-source', {}, true)
+ const id = (opened.result as { id: string }).id
+
+ await expect(factory.close('term-upstream', { node: id }, true)).resolves.toMatchObject({
+ ok: false,
+ error: expect.stringContaining('close-not-owner')
+ })
+ expect(pty.destroys).toEqual([])
+ expect((await store.load({ sideline: false })).projects[0].nodes.some((node) => node.id === id))
+ .toBe(true)
+ expect(removed).toEqual([])
+ })
+
+ it('closes a persisted owned node cleanly when its pane was already killed out of band', async () => {
+ const opened = await factory.openTerminal('term-source', {}, true)
+ const id = (opened.result as { id: string }).id
+ pty.killOutOfBand(id)
+
+ await expect(factory.close('term-source', { node: id }, true)).resolves.toMatchObject({
+ ok: true,
+ result: { ids: [id] }
+ })
+ expect(pty.destroys.at(-1)).toEqual({
+ clientId: null,
+ nodeId: id,
+ everySocket: true,
+ wasLive: false
+ })
+ expect((await store.load({ sideline: false })).projects[0].nodes.some((node) => node.id === id))
+ .toBe(false)
+ })
+
+ it('requires verified node identity before applying the process-local ownership ledger', async () => {
+ const opened = await factory.openTerminal('term-source', {}, true)
+ const id = (opened.result as { id: string }).id
+
+ await expect(factory.close('term-source', { node: id }, false)).resolves.toMatchObject({
+ ok: false,
+ error: expect.stringContaining('close-identity-refused')
+ })
+ expect(pty.destroys).toEqual([])
+ })
+
+ it('places repeated spawns in the first free deterministic slots without overlapping busy nodes', async () => {
+ const workspace = await store.load({ sideline: false })
+ // Slot zero to the right of the source is already busy before any control request arrives.
+ workspace.projects[0].nodes.push(terminal('term-busy-slot', 'Busy slot', 'gemini', 740))
+ await store.save(workspace)
+
+ const spawnedIds: string[] = []
+ for (let i = 0; i < 5; i++) {
+ const reply = await factory.openTerminal('term-source', {}, true)
+ spawnedIds.push((reply.result as { id: string }).id)
+ }
+
+ const nodes = (await store.load({ sideline: false })).projects[0].nodes
+ const overlap = (a: CanvasNodeState, b: CanvasNodeState): boolean =>
+ a.position.x < b.position.x + b.size.width &&
+ a.position.x + a.size.width > b.position.x &&
+ a.position.y < b.position.y + b.size.height &&
+ a.position.y + a.size.height > b.position.y
+ for (const id of spawnedIds) {
+ const node = nodes.find((candidate) => candidate.id === id)!
+ expect(nodes.filter((candidate) => candidate.id !== id).some((candidate) => overlap(node, candidate)), id)
+ .toBe(false)
+ }
+ expect(new Set(spawnedIds.map((id) => {
+ const node = nodes.find((candidate) => candidate.id === id)!
+ return `${node.position.x},${node.position.y}`
+ })).size).toBe(spawnedIds.length)
+ })
+
it.each([
['claude', "claude 'do work'"],
['codex', "codex 'do work' --ask-for-approval untrusted"],
diff --git a/src/server/headless-node-factory.ts b/src/server/headless-node-factory.ts
index 48c06ee03..0d7df6960 100644
--- a/src/server/headless-node-factory.ts
+++ b/src/server/headless-node-factory.ts
@@ -40,6 +40,11 @@ export interface ServerControlReply {
export interface HeadlessPty {
createHeadless(options: PtyCreateOptions): Promise<PtyCreateResult>
sendText(nodeId: string, text: string, opts?: { enter?: boolean }): Promise<boolean>
+ destroySession(
+ clientId: number | null,
+ persistKey: string,
+ opts?: { everySocket?: boolean }
+ ): Promise<void>
}
/** WorkspaceStore's mutation surface, also narrow so tests can use the real store or a fake. */
@@ -56,6 +61,7 @@ export interface HeadlessNodeFactoryDeps {
env?: Record<string, string | undefined>
now?: () => number
publishNode?: (projectId: string, node: CanvasNodeState) => void
+ publishRemoval?: (projectId: string, nodeId: string) => void
publishProject?: (project: Project) => void
schedule?: (cb: () => void, ms: number) => ReturnType<typeof setTimeout>
clearSchedule?: (timer: ReturnType<typeof setTimeout>) => void
@@ -151,16 +157,40 @@ function absolutePosition(project: Project, node: CanvasNodeState): { x: number;
function placeRight(
project: Project,
source: CanvasNodeState,
- index: number,
- size: { width: number; height: number }
+ size: { width: number; height: number },
+ reserved: readonly CanvasNodeState[] = []
): { 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)
+ const occupied = [...project.nodes, ...reserved].map((node) => {
+ const position = absolutePosition(project, node)
+ return {
+ x: position.x,
+ y: position.y,
+ width: Math.max(1, node.size?.width || TERMINAL_SIZE.width),
+ height: Math.max(1, node.size?.height || TERMINAL_SIZE.height)
+ }
+ })
+
+ // Keep the existing compact three-row grid, but scan it rather than assuming this request's
+ // local index is globally free. Repeated requests therefore continue into the first available
+ // row/column instead of returning to slot zero and stacking nodes on top of one another.
+ for (let slot = 0; ; slot++) {
+ const column = Math.floor(slot / 3)
+ const row = slot % 3
+ const candidate = {
+ x: origin.x + sourceWidth + H_GAP + column * (size.width + H_GAP),
+ y: origin.y + row * (size.height + V_GAP),
+ width: size.width,
+ height: size.height
+ }
+ const collides = occupied.some((rect) =>
+ candidate.x < rect.x + rect.width &&
+ candidate.x + candidate.width > rect.x &&
+ candidate.y < rect.y + rect.height &&
+ candidate.y + candidate.height > rect.y
+ )
+ if (!collides) return { x: candidate.x, y: candidate.y }
}
}
@@ -198,6 +228,8 @@ function ptyOptions(project: Project, node: CanvasNodeState): PtyCreateOptions {
export class HeadlessNodeFactory {
private serial: Promise<unknown> = Promise.resolve()
private attached = new Set<string>()
+ /** Process-local proof that a caller created a node during THIS Server Edition run. */
+ private spawnedBy = new Map<string, { sourceNodeId: string; projectId: string }>()
/** Fresh server-spawned agents that have not emitted their first real working turn yet. */
private awaitingFirstWorking = new Set<string>()
private retryCount = new Map<string, number>()
@@ -223,6 +255,14 @@ export class HeadlessNodeFactory {
for (const node of nodes) publish(project.id, node)
}
+ private publishRemovals(project: Project, nodeIds: readonly string[]): void {
+ this.deps.publishProject?.(project)
+ const publish = this.deps.publishRemoval ?? ((projectId: string, nodeId: string) => {
+ publishCanvasMutation(projectId, { op: 'remove', id: nodeId })
+ })
+ for (const nodeId of nodeIds) publish(project.id, nodeId)
+ }
+
private async attach(project: Project, node: CanvasNodeState): Promise<PtyCreateResult> {
if (this.attached.has(node.id)) {
return { sessionId: node.id, fresh: false }
@@ -298,6 +338,89 @@ export class HeadlessNodeFactory {
return this.open(sourceNodeId, 'open-agent', args, verified)
}
+ close(
+ sourceNodeId: string,
+ args: Record<string, string>,
+ verified: boolean
+ ): Promise<ServerControlReply> {
+ return this.runExclusive(async () => {
+ const flagError = unsupportedFlags(args, new Set(['node']))
+ if (flagError) return { ok: false, error: `close: ${flagError}` }
+ if (!verified) {
+ return {
+ ok: false,
+ error: 'close-identity-refused: Server Edition close requires verified node identity'
+ }
+ }
+
+ 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 ids = [...new Set((args.node ?? '').split(',').map((id) => id.trim()).filter(Boolean))]
+ if (!ids.length) return { ok: false, error: 'close requires --node <id>' }
+
+ // Validate the WHOLE list before killing anything. A mixed owned/unowned request is one
+ // refusal, never a partial destructive success whose surviving ids the caller must guess.
+ for (const id of ids) {
+ const ownership = this.spawnedBy.get(id)
+ if (!ownership || ownership.sourceNodeId !== sourceNodeId) {
+ return {
+ ok: false,
+ error: `close-not-owner: ${sourceNodeId} did not spawn ${id} during this server run`
+ }
+ }
+ }
+
+ // Kill first: the durable canvas must never lose a node whose session outcome is unknown.
+ // `destroySession` treats a backend already absent as success, which is exactly the cleanup
+ // case for a pane the operator killed directly before asking its owner to close the node.
+ await Promise.all(
+ ids.map((id) => this.deps.ptyManager.destroySession(null, id, { everySocket: true }))
+ )
+
+ const removedByProject = new Map<Project, string[]>()
+ for (const id of ids) {
+ const projectId = this.spawnedBy.get(id)!.projectId
+ const project = workspace.projects.find((candidate) => candidate.id === projectId)
+ if (!project || !project.nodes.some((node) => node.id === id)) continue
+ project.nodes = project.nodes.filter((node) => node.id !== id)
+ if (project.ropes) {
+ project.ropes = project.ropes.filter((edge) => edge.source !== id && edge.target !== id)
+ }
+ if (project.bridges) {
+ project.bridges = project.bridges.filter((edge) => edge.source !== id && edge.target !== id)
+ }
+ const removed = removedByProject.get(project) ?? []
+ removed.push(id)
+ removedByProject.set(project, removed)
+ }
+
+ if (removedByProject.size) {
+ await this.deps.workspaceStore.save(workspace)
+ for (const [project, removed] of removedByProject) this.publishRemovals(project, removed)
+ }
+
+ for (const id of ids) {
+ this.spawnedBy.delete(id)
+ this.attached.delete(id)
+ this.awaitingFirstWorking.delete(id)
+ this.retryCount.delete(id)
+ const timer = this.retryTimers.get(id)
+ if (timer) (this.deps.clearSchedule ?? clearTimeout)(timer)
+ this.retryTimers.delete(id)
+ }
+ return {
+ ok: true,
+ message: `closed ${ids.length} owned node(s): ${ids.join(', ')}`,
+ result: { ids, id: ids[0] }
+ }
+ })
+ }
+
private open(
sourceNodeId: string,
verb: 'open-terminal' | 'open-agent',
@@ -404,7 +527,7 @@ export class HeadlessNodeFactory {
const node: CanvasNodeState = {
id,
kind: 'terminal',
- position: placeRight(target, source.node, i, nodeSize),
+ position: placeRight(target, source.node, nodeSize, created),
size: { ...nodeSize },
title,
...(verb === 'open-agent' ? { titleAuto: true } : {}),
@@ -442,6 +565,9 @@ export class HeadlessNodeFactory {
target.ropes = ropes
target.bridges = bridges
await this.deps.workspaceStore.save(workspace)
+ for (const node of created) {
+ this.spawnedBy.set(node.id, { sourceNodeId, projectId: target.id })
+ }
this.publish(target, created)
const failed: string[] = []
@@ -508,7 +634,7 @@ export class HeadlessNodeFactory {
node = {
id: nextId('sticky'),
kind: 'sticky',
- position: placeRight(source.project, source.node, 0, STICKY_SIZE),
+ position: placeRight(source.project, source.node, STICKY_SIZE),
size: { ...STICKY_SIZE },
title: oneLine(parsed.ref) || 'Note',
color: '#ffd60a',
@@ -533,6 +659,9 @@ export class HeadlessNodeFactory {
node.textUpdatedAt = (this.deps.now ?? Date.now)()
node.textUpdatedBy = source.node.title || source.node.id
await this.deps.workspaceStore.save(workspace)
+ if (created) {
+ this.spawnedBy.set(node.id, { sourceNodeId, projectId: source.project.id })
+ }
this.publish(source.project, [node])
return {
ok: true,
@@ -637,5 +766,6 @@ export class HeadlessNodeFactory {
this.stopped = true
for (const timer of this.retryTimers.values()) (this.deps.clearSchedule ?? clearTimeout)(timer)
this.retryTimers.clear()
+ this.spawnedBy.clear()
}
}
diff --git a/src/server/index.ts b/src/server/index.ts
index 0c8122f60..35ed2c076 100644
--- a/src/server/index.ts
+++ b/src/server/index.ts
@@ -88,6 +88,7 @@ import { presenceHub } from '../core/presence/hub'
import { initCanvasSync } from '../core/canvas-sync'
import { wireAgentStatus } from './agent-status'
import { initServerContextLink } from './context-link'
+import { createServerWorkspaceWatcher } from './workspace-external-watch'
import { registerTranscriptIpc } from '../core/transcript-ipc'
import { IPC } from '@shared/ipc'
import { WhisperModelStore } from '../core/speech/whisper-models'
@@ -564,9 +565,12 @@ export async function startServer(
canvases: () => workspaceStore.persistedCanvases(),
installAgentIntegrations: config.installHooks !== false
})
+ const workspaceWatcher = createServerWorkspaceWatcher(workspaceStore)
// Every load()/save() is a canvas change as far as links are concerned: a browser drawing a
- // bridge edge reaches us as the workspace save it triggers.
+ // bridge edge reaches us as the workspace save it triggers. It also refreshes the local-ref
+ // watcher set, so projects added or removed while the server runs get the same hand-edit path.
workspaceStore.onPersist = () => {
+ workspaceWatcher.sync()
contextLink.refresh()
refreshNodeTokens()
}
@@ -699,6 +703,7 @@ export async function startServer(
pressure.stop()
ptyPressure.stop()
canvasControl?.stop()
+ workspaceWatcher.dispose()
await contextLink.stop()
await ptyManager.killAll()
// Same native hazard as the desktop app: a whisper transcribe still running when the
@@ -755,6 +760,7 @@ export async function startServer(
pressure.stop()
ptyPressure.stop()
canvasControl?.stop()
+ workspaceWatcher.dispose()
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/server/workspace-external-watch.test.ts b/src/server/workspace-external-watch.test.ts
new file mode 100644
index 000000000..e227dc989
--- /dev/null
+++ b/src/server/workspace-external-watch.test.ts
@@ -0,0 +1,104 @@
+import { promises as 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, type FakePlatform } from '../core/platform-fake'
+import { initPlatform, resetPlatformForTests } from '../core/platform'
+import { WorkspaceStore } from '../core/workspace-store'
+import { IPC } from '../shared/ipc'
+import type { CanvasNodeState, Project, Workspace } from '../shared/types'
+import { createServerWorkspaceWatcher } from './workspace-external-watch'
+
+const node = (id: string, x: number): CanvasNodeState => ({
+ id,
+ kind: 'terminal',
+ position: { x, y: 0 },
+ size: { width: 640, height: 440 },
+ title: id,
+ color: '#0a84ff',
+ group: null
+})
+
+describe('Server Edition external workspace watcher', () => {
+ let dataDir = ''
+ let projectDir = ''
+ let fake: FakePlatform
+ let watcher: ReturnType<typeof createServerWorkspaceWatcher> | null = null
+
+ beforeEach(async () => {
+ dataDir = await fs.mkdtemp(path.join(os.tmpdir(), 'nodeterm-server-watch-data-'))
+ projectDir = await fs.mkdtemp(path.join(os.tmpdir(), 'nodeterm-server-watch-project-'))
+ fake = fakePlatform({ userDataDir: dataDir })
+ initPlatform(fake)
+ })
+
+ afterEach(async () => {
+ watcher?.dispose()
+ watcher = null
+ resetPlatformForTests()
+ await fs.rm(dataDir, { recursive: true, force: true })
+ await fs.rm(projectDir, { recursive: true, force: true })
+ })
+
+ it('adopts a hand-edited node/edge removal and broadcasts the complete project live', async () => {
+ const source = node('term-source', 0)
+ const removed = node('term-removed', 720)
+ const kept = node('term-kept', 1440)
+ const project: Project = {
+ id: 'project-1',
+ name: 'Project',
+ color: '#0a84ff',
+ cwd: projectDir,
+ viewport: { x: 0, y: 0, zoom: 1 },
+ nodes: [source, removed, kept],
+ bridges: [
+ { id: 'bridge-removed', source: source.id, target: removed.id },
+ { id: 'bridge-kept', source: source.id, target: kept.id }
+ ],
+ ropes: [
+ { id: 'rope-removed', source: source.id, target: removed.id },
+ { id: 'rope-kept', source: source.id, target: kept.id }
+ ]
+ }
+ const workspace: Workspace = {
+ version: 2,
+ activeProjectId: project.id,
+ projects: [project]
+ }
+ const store = new WorkspaceStore()
+ await store.save(workspace)
+ fake.sent.length = 0
+ watcher = createServerWorkspaceWatcher(store, { debounceMs: 20 })
+
+ const file = path.join(projectDir, '.nodeterm', 'project.json')
+ const edited = JSON.parse(await fs.readFile(file, 'utf8')) as {
+ rev: number
+ updatedAt: string
+ nodes: CanvasNodeState[]
+ bridges: Array<{ id: string; source: string; target: string }>
+ ropes: Array<{ id: string; source: string; target: string }>
+ }
+ edited.rev += 1
+ edited.updatedAt = new Date(Date.now() + 1_000).toISOString()
+ edited.nodes = edited.nodes.filter((candidate) => candidate.id !== removed.id)
+ edited.bridges = edited.bridges.filter(
+ (edge) => edge.source !== removed.id && edge.target !== removed.id
+ )
+ edited.ropes = edited.ropes.filter(
+ (edge) => edge.source !== removed.id && edge.target !== removed.id
+ )
+ await fs.writeFile(file, JSON.stringify(edited), 'utf8')
+
+ await vi.waitFor(() => {
+ expect(fake.sent.some((event) => event.channel === IPC.workspaceExternalChange)).toBe(true)
+ }, { timeout: 3_000, interval: 20 })
+
+ const event = fake.sent.filter((entry) => entry.channel === IPC.workspaceExternalChange).at(-1)!
+ const incoming = event.args[0] as Project
+ expect(incoming.nodes.map((candidate) => candidate.id)).toEqual([source.id, kept.id])
+ expect(incoming.bridges).toEqual([{ id: 'bridge-kept', source: source.id, target: kept.id }])
+ expect(incoming.ropes).toEqual([{ id: 'rope-kept', source: source.id, target: kept.id }])
+ })
+})
diff --git a/src/server/workspace-external-watch.ts b/src/server/workspace-external-watch.ts
new file mode 100644
index 000000000..b3b032b42
--- /dev/null
+++ b/src/server/workspace-external-watch.ts
@@ -0,0 +1,46 @@
+import { platform } from '../core/platform'
+import type { WorkspaceStore } from '../core/workspace-store'
+import { WorkspaceWatcher } from '../core/workspace-watcher'
+import { IPC } from '../shared/ipc'
+import type { Project } from '../shared/types'
+
+type WatchedWorkspaceStore = Pick<
+ WorkspaceStore,
+ 'localRefPaths' | 'isSelfWrite' | 'readLocalRefByPath'
+>
+
+export interface ServerWorkspaceWatcherOptions {
+ debounceMs?: number
+ publish?: (project: Project) => void
+}
+
+/**
+ * Give Server Edition the desktop's live hand-edit path without importing Electron: the shared
+ * watcher identifies a genuine outside write, WorkspaceStore adopts the complete project, and the
+ * existing workspace broadcast replaces the browser's clean canvas wholesale. A full Project is
+ * intentional here — unlike `canvas:mut`, it carries bridge and rope removals as well as nodes.
+ */
+export function createServerWorkspaceWatcher(
+ store: WatchedWorkspaceStore,
+ options: ServerWorkspaceWatcherOptions = {}
+): WorkspaceWatcher {
+ const publish = options.publish ?? ((project: Project) => {
+ platform().broadcast(IPC.workspaceExternalChange, project)
+ })
+ const watcher = new WorkspaceWatcher({
+ paths: () => store.localRefPaths(),
+ isSelfWrite: (filePath, content) => store.isSelfWrite(filePath, content),
+ onExternalChange: (filePath) => {
+ void store.readLocalRefByPath(filePath)
+ .then((changed) => {
+ if (changed) publish(changed)
+ })
+ .catch((error) => {
+ console.warn('[nodeterm-server] external workspace edit could not be adopted', error)
+ })
+ },
+ ...(options.debounceMs === undefined ? {} : { debounceMs: options.debounceMs })
+ })
+ watcher.sync()
+ return watcher
+}