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): canvas-control writes no longer raise the Reload/Keep-mine conflict bar

Howard Youngdahl2a8880badd46
diff --git a/CLAUDE.md b/CLAUDE.md
index 70e23f2ca..f201a3e4b 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -145,7 +145,10 @@ The codebase is split by Electron process boundary — keep code on the correct
channels (`registerTranscriptIpc` — the ⌘M chat view + the find-bar's transcript index; see the
⌘M bullet under Agent support). **Canvas control is opt-in**
(`NODETERM_SERVER_CANVAS_CONTROL=1` / `--canvas-control`): the Server shell installs its own shim
- and runs a serialized `HeadlessNodeFactory`; disabled remains the default. (The SDK **chat node**
+ and runs a serialized `HeadlessNodeFactory`; disabled remains the default. Its project writes
+ broadcast on `workspace:server-change`, NOT the outside-edit channel — they are this core's own
+ writes and are three-way merged by the renderer, never put behind the conflict bar (see the
+ workspace-store bullet). (The SDK **chat node**
— once listed here as deferred — was removed entirely, 2026-07; see the chat-node note in the
node-kinds list.)
- **`src/preload/`** — the only bridge. `index.ts` uses `contextBridge` to expose a
@@ -229,7 +232,21 @@ Persistence has two layers:
speak an assembled v2-shaped `Workspace`; all fan-out lives in `core/workspace-store.ts` +
pure `core/workspace-files.ts`. v2 files migrate on first save (backup `workspace.v2.bak`,
one-time renderer note). Outside edits (git pull/sync) are detected by
- `core/workspace-watcher.ts` → silent reload, or a Reload/Keep-mine conflict bar when dirty.
+ `core/workspace-watcher.ts` → silent reload, or a Reload/Keep-mine conflict bar when dirty; they
+ ride `workspace:external-change`, and so do the phone's `appendRemoteNode` and the SSH
+ reconcile, which really are "another device".
+ **A write this core made ITSELF rides `workspace:server-change` instead** — today that is Server
+ Edition headless canvas control (`server/canvas-control.ts`) — and the renderer three-way merges
+ it against the store baseline (`renderer/lib/serverChange.ts`: incoming nodes adopted silently,
+ ropes/bridges merged by id with server-added installed, server-removed dropped, local unsaved
+ edits kept, dangling edges pruned), never a bar and never a reload. It used to share the
+ outside-edit channel and that was a data-loss path, not a cosmetic one: `decideExternalChange`
+ compares the project shell, `ropes` included, so the one `ctrl-…` rope an `open-agent` appends
+ read as a conflict whenever the canvas was dirty — which it is throughout a spawn burst (the
+ paired `canvas:mut` marks it, spawns land 60–140 ms apart inside the 800 ms autosave debounce,
+ and **the bar itself suspends autosave**, so once raised it stayed raised). Answering "Keep my
+ version" then wrote the browser's edge state over the file, dropping the ropes the server had
+ just persisted and resurrecting cards it had removed.
Unreadable refs render as greyed **unavailable** tabs (never dropped); corrupt project files
are set aside as `project.json.corrupt-<ts>`. "Open folder…" adopts an existing
`.nodeterm/project.json` — the probe MINTS the project id (node ids — tmux names — kept), and
diff --git a/docs/SERVER.md b/docs/SERVER.md
index 9d1218468..5eee328cf 100644
--- a/docs/SERVER.md
+++ b/docs/SERVER.md
@@ -550,6 +550,20 @@ persisted queued command even when a tmux backend survived. A later explicit own
view is the only cold-spawn path. Plain terminals carry no agent identity or canvas-control grant;
missing `agentId` never means Claude.
+A canvas-control write is not an outside edit. The factory mutates the project, saves it, and
+broadcasts the whole thing on **`workspace:server-change`** — a channel of its own, separate from
+the `workspace:external-change` the workspace watcher uses for a git pull or a hand edit. It shared
+that channel until it was measured: the renderer classifies an outside edit by comparing the
+project shell, `ropes` included, so the single `ctrl-…` rope every `open-agent` appends read as a
+conflict whenever the canvas was dirty — which it is right through a spawn burst, because the
+paired `canvas:mut` marks it dirty, spawns arrive inside the autosave debounce, and the conflict
+bar suspends autosave, so the first one latched the bar on and every later write re-raised it.
+"Keep my version" then serialized the browser's own edges over the file and dropped the ropes this
+factory had just persisted. On the new channel the browser three-way merges instead
+(`renderer/lib/serverChange.ts`): nodes the server opened are adopted silently, ropes and bridges
+are merged against the last-known disk copy, and unsaved local edits survive. Nothing is asked of
+the user, because both sides of this merge are the same application.
+
Validate upgrades with a disposable `NODETERM_DATA_DIR` and port. Restarting a shared live Server
service is an explicit operator action; it is not part of a test, repair, or boot-rescue flow.
diff --git a/src/preload/index.ts b/src/preload/index.ts
index 266bddf6c..d9354caec 100644
--- a/src/preload/index.ts
+++ b/src/preload/index.ts
@@ -156,7 +156,12 @@ const api: NodeTerminalApi = {
const h = (_e: unknown, p: Project) => cb(p)
ipcRenderer.on(IPC.workspaceExternalChange, h)
return () => ipcRenderer.removeListener(IPC.workspaceExternalChange, h)
- }
+ },
+ // Deliberate no-op on the desktop shell: nothing here writes the project file on an agent's
+ // behalf. `HeadlessNodeFactory` is Server Edition only — the desktop's canvas-control verbs run
+ // through the renderer's own React Flow state, and its watcher path stays on onExternalChange.
+ // A real subscription would be dead wiring for a channel this main process never broadcasts.
+ onServerChange: (_cb: (project: Project) => void) => () => {}
},
projectSettings: {
read: (projectId: string) => ipcRenderer.invoke(IPC.projectSettingsRead, projectId),
diff --git a/src/renderer/bridge/ws-bridge.ts b/src/renderer/bridge/ws-bridge.ts
index a5e352375..442e9fff5 100644
--- a/src/renderer/bridge/ws-bridge.ts
+++ b/src/renderer/bridge/ws-bridge.ts
@@ -299,10 +299,13 @@ export function buildRealApi(
// REAL: core broadcasts IPC.workspaceCorruptRecovered from the load path (workspace-store.ts).
onCorruptRecovered: (cb) => client.subscribe(IPC.workspaceCorruptRecovered, cb as Listener),
// 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)
+ // Remote-node adoption (the phone appending a session it started) rides it too: that IS
+ // "another device", which is what this channel means.
+ onExternalChange: (cb) => client.subscribe(IPC.workspaceExternalChange, cb as Listener),
+ // REAL: Server Edition canvas control broadcasts its own persisted bridge/rope changes here —
+ // wider than the node-only canvas:mut vocabulary, but ours, so they must not travel the
+ // outside-edit channel and end up behind the conflict bar (see server/canvas-control.ts).
+ onServerChange: (cb) => client.subscribe(IPC.workspaceServerChange, cb as Listener)
}
// REAL: WorkspaceStore (core) registers the project-settings:* channels too — same
diff --git a/src/renderer/canvas/Canvas.tsx b/src/renderer/canvas/Canvas.tsx
index 929f1e845..12bf83e93 100644
--- a/src/renderer/canvas/Canvas.tsx
+++ b/src/renderer/canvas/Canvas.tsx
@@ -156,6 +156,7 @@ import {
decideExternalChange,
mergeIncomingNodes
} from '../lib/externalChange'
+import { planServerChange } from '../lib/serverChange'
import {
CONTENT_ADD_ITEMS,
contentAddItemsToMenuItems,
@@ -2648,7 +2649,27 @@ export function Canvas() {
useProjects.getState().requestReload()
}, [])
- /** Put nodes that arrived from ANOTHER device onto the live canvas immediately.
+ /** Land incoming nodes on the live canvas, and say nothing about it. Returns whether anything
+ * actually landed (so the caller can decide about dirty).
+ *
+ * Split out of `adoptIncomingNodes` because the server-change path below adopts by exactly these
+ * rules and must NOT show its notice: the node it is landing was opened by an agent in this
+ * browser's own canvas, seconds ago, at the user's request — "registered from another device"
+ * would be a lie. Two copies of the merge would drift apart; one merge with the sentence bolted
+ * on top of it cannot. */
+ const adoptNodesSilently = useCallback(
+ (added: CanvasNodeState[]): boolean => {
+ if (!added.length) return false
+ const next = mergeIncomingNodes(nodesRef.current, nodeStatesToFlow(added))
+ if (next === nodesRef.current) return false
+ nodesRef.current = next
+ setNodes(next)
+ return true
+ },
+ [setNodes]
+ )
+
+ /** Put nodes that arrived from ANOTHER device onto the live canvas immediately, and say so.
*
* Called for every external change while dirty — bar or no bar. An incoming node id nothing here
* holds cannot collide with a local edit, and unlike a git pull nobody re-emits it: the phone
@@ -2658,21 +2679,19 @@ export function Canvas() {
* over disk — deleted a node whose tmux session is still running, headless and unreachable. */
const adoptIncomingNodes = useCallback(
(added: CanvasNodeState[]) => {
- if (!added.length) return
- const next = mergeIncomingNodes(nodesRef.current, nodeStatesToFlow(added))
- if (next === nodesRef.current) return
- nodesRef.current = next
- setNodes(next)
+ if (!adoptNodesSilently(added)) return
// The adopted nodes only exist on disk in the version we did NOT take: count them as an edit
// so the next save writes them back out under our canvas too.
bumpDirty()
setNotice({ kind: 'info', text: adoptedNodesNotice(added.length) })
},
- [setNodes, bumpDirty]
+ [adoptNodesSilently, bumpDirty]
)
// Outside edits to a project's .nodeterm file (git pull / sync / teammate / another machine /
- // the phone registering a session it started).
+ // the phone registering a session it started). Writes THIS core made on an agent's behalf are
+ // not in here any more: Server Edition canvas control broadcasts them on `onServerChange`
+ // (below), because they are ours and there is nothing for the user to choose between.
useEffect(() => {
return api.workspace.onExternalChange((project) => {
const { activeProjectId: current } = useProjects.getState()
@@ -2717,6 +2736,52 @@ export function Canvas() {
})
}, [reloadActiveProject, adoptIncomingNodes])
+ // Writes this core made ITSELF: Server Edition headless canvas control (an agent ran
+ // `nodeterm open-agent`, `rename`, `close`…). Never a bar and never a reload — see
+ // lib/serverChange.ts for why the outside-edit classifier was the wrong instrument, and
+ // server/canvas-control.ts for the channel split.
+ useEffect(() => {
+ return api.workspace.onServerChange((project) => {
+ const { activeProjectId: current } = useProjects.getState()
+ if (project.id !== current) {
+ // Background project: the store copy IS that project until it is switched to, and it
+ // reloads into React Flow whole on the next switch.
+ useProjects.getState().replaceProject(project)
+ return
+ }
+ const plan = planServerChange({
+ base: useProjects.getState().getProject(project.id),
+ incoming: project,
+ liveNodeIds: nodesRef.current.map((n) => n.id),
+ liveRopes: controlEdgesRef.current.map((e) => ({
+ id: e.id,
+ source: e.source,
+ target: e.target
+ })),
+ liveBridges: linkEdgesRef.current.map((e) => ({
+ id: e.id,
+ source: e.source,
+ target: e.target
+ }))
+ })
+ const adopted = adoptNodesSilently(plan.added)
+ // Only when the merge actually moved something: a fresh array of identical edges re-renders
+ // every edge on the canvas (displayEdges recomputes colour and the waiting look per edge)
+ // for no change at all, and these arrive in bursts.
+ if (plan.ropesChanged)
+ setControlEdges(plan.ropes.map((r) => ropeEdge(r.id, r.source, r.target)))
+ if (plan.bridgesChanged)
+ setLinkEdges(plan.bridges.map((b) => ({ id: b.id, source: b.source, target: b.target })))
+ // The store copy is our disk baseline, and the server has already written this file — so it
+ // moves to the incoming version exactly as the 'merge' branch above does.
+ useProjects.getState().replaceProject(project)
+ // The merged canvas is not yet what is on disk (the server wrote its half, we hold the
+ // union), so it has to be saved. Both sides converge on the same state — the same "two
+ // clients saving one converged canvas is harmless" model the peer-mutation path relies on.
+ if (adopted || plan.ropesChanged || plan.bridgesChanged) bumpDirty()
+ })
+ }, [adoptNodesSilently, setControlEdges, setLinkEdges, bumpDirty])
+
// One-shot note after an on-disk migration (dismissible, non-blocking strip). Both kinds change
// where the user's data lives, so neither may happen silently.
useEffect(() => {
diff --git a/src/renderer/lib/serverChange.test.ts b/src/renderer/lib/serverChange.test.ts
new file mode 100644
index 000000000..9e0333997
--- /dev/null
+++ b/src/renderer/lib/serverChange.test.ts
@@ -0,0 +1,214 @@
+import { describe, it, expect } from 'vitest'
+import { planServerChange, type EdgeRef } from './serverChange'
+import type { CanvasNodeState, Project } from '@shared/types'
+
+const node = (id: string, over: Partial<CanvasNodeState> = {}): CanvasNodeState => ({
+ id,
+ kind: 'terminal',
+ position: { x: 100, y: 100 },
+ size: { width: 900, height: 560 },
+ title: id,
+ color: '#7aa2f7',
+ group: null,
+ ...over
+})
+
+const project = (nodes: CanvasNodeState[], over: Partial<Project> = {}): Project => ({
+ id: 'p1',
+ name: 'Project',
+ color: '#0a84ff',
+ cwd: '/work/p1',
+ viewport: { x: 0, y: 0, zoom: 1 },
+ nodes,
+ ...over
+})
+
+const rope = (id: string, source: string, target: string): EdgeRef => ({ id, source, target })
+
+/** The shape the real defect arrives in: the canvas already holds the caller and one earlier
+ * spawn, and the server has just written a second spawn plus its `ctrl-…` rope. */
+const caller = node('term-caller')
+const first = node('term-first')
+
+describe('planServerChange', () => {
+ it('installs a rope the server added, and adopts the node it points at', () => {
+ // The whole reason this path exists: `open-agent` appends BOTH a node and a rope, and the old
+ // external-change classifier saw the changed `ropes` array as a conflict.
+ const spawned = node('term-spawned')
+ const base = project([caller, first], { ropes: [rope('ctrl-1', caller.id, first.id)] })
+ const incoming = project([caller, first, spawned], {
+ ropes: [rope('ctrl-1', caller.id, first.id), rope('ctrl-2', caller.id, spawned.id)]
+ })
+
+ const plan = planServerChange({
+ base,
+ incoming,
+ liveNodeIds: [caller.id, first.id],
+ liveRopes: [rope('ctrl-1', caller.id, first.id)],
+ liveBridges: []
+ })
+
+ expect(plan.added.map((n) => n.id)).toEqual([spawned.id])
+ expect(plan.ropesChanged).toBe(true)
+ expect(plan.ropes.map((r) => r.id)).toEqual(['ctrl-1', 'ctrl-2'])
+ // Pruning runs against the canvas as it will be AFTER the adoption, or the rope the server
+ // wrote alongside its new node would be dropped on the very payload that introduced both.
+ expect(plan.ropes.at(-1)).toEqual(rope('ctrl-2', caller.id, spawned.id))
+ })
+
+ it('drops a rope the server removed', () => {
+ const base = project([caller, first], {
+ ropes: [rope('ctrl-1', caller.id, first.id), rope('ctrl-2', caller.id, first.id)]
+ })
+ const incoming = project([caller, first], { ropes: [rope('ctrl-1', caller.id, first.id)] })
+
+ const plan = planServerChange({
+ base,
+ incoming,
+ liveNodeIds: [caller.id, first.id],
+ liveRopes: [rope('ctrl-1', caller.id, first.id), rope('ctrl-2', caller.id, first.id)],
+ liveBridges: []
+ })
+
+ expect(plan.ropesChanged).toBe(true)
+ expect(plan.ropes.map((r) => r.id)).toEqual(['ctrl-1'])
+ })
+
+ it('keeps a rope the canvas added and has not saved yet', () => {
+ // Not in base ⇒ nobody but this canvas has ever seen it ⇒ the server's file cannot be evidence
+ // that it is gone. Dropping it would delete an edge the user just drew.
+ const base = project([caller, first], { ropes: [] })
+ const incoming = project([caller, first], { ropes: [] })
+
+ const plan = planServerChange({
+ base,
+ incoming,
+ liveNodeIds: [caller.id, first.id],
+ liveRopes: [rope('local-1', caller.id, first.id)],
+ liveBridges: []
+ })
+
+ expect(plan.ropes.map((r) => r.id)).toEqual(['local-1'])
+ expect(plan.ropesChanged).toBe(false)
+ })
+
+ it('leaves a locally deleted rope deleted even though the incoming file still lists it', () => {
+ // In base AND in incoming, absent from the canvas ⇒ the user deleted it since the last save.
+ // Re-adding it here would undo that edit silently.
+ const base = project([caller, first], { ropes: [rope('ctrl-1', caller.id, first.id)] })
+ const incoming = project([caller, first], { ropes: [rope('ctrl-1', caller.id, first.id)] })
+
+ const plan = planServerChange({
+ base,
+ incoming,
+ liveNodeIds: [caller.id, first.id],
+ liveRopes: [],
+ liveBridges: []
+ })
+
+ expect(plan.ropes).toEqual([])
+ expect(plan.ropesChanged).toBe(false)
+ })
+
+ it('prunes an incoming edge whose endpoint is not on the canvas', () => {
+ // The cross case: the server added a rope to a node this canvas deleted (and has not saved).
+ // React Flow would drop it at render anyway — but the next autosave would write it out.
+ const base = project([caller, first], { ropes: [] })
+ const incoming = project([caller, first], { ropes: [rope('ctrl-1', caller.id, first.id)] })
+
+ const plan = planServerChange({
+ base,
+ incoming,
+ liveNodeIds: [caller.id],
+ liveRopes: [],
+ liveBridges: []
+ })
+
+ expect(plan.ropes).toEqual([])
+ expect(plan.ropesChanged).toBe(false)
+ })
+
+ it('does not resurrect a node the canvas deleted but the file still lists', () => {
+ // Same base check `decideExternalChange` uses: "added" means neither the canvas nor our
+ // last-known disk state has the id.
+ const base = project([caller, first])
+ const incoming = project([caller, first])
+
+ const plan = planServerChange({
+ base,
+ incoming,
+ liveNodeIds: [caller.id],
+ liveRopes: [],
+ liveBridges: []
+ })
+
+ expect(plan.added).toEqual([])
+ })
+
+ it('treats an unknown project (no base) as empty: everything incoming is new', () => {
+ const spawned = node('term-spawned')
+ const incoming = project([caller, spawned], {
+ ropes: [rope('ctrl-1', caller.id, spawned.id)],
+ bridges: [{ id: 'bridge-1', source: caller.id, target: spawned.id }]
+ })
+
+ const plan = planServerChange({
+ base: undefined,
+ incoming,
+ liveNodeIds: [caller.id],
+ liveRopes: [],
+ liveBridges: []
+ })
+
+ expect(plan.added.map((n) => n.id)).toEqual([spawned.id])
+ expect(plan.ropes.map((r) => r.id)).toEqual(['ctrl-1'])
+ expect(plan.bridges.map((b) => b.id)).toEqual(['bridge-1'])
+ expect(plan.ropesChanged).toBe(true)
+ expect(plan.bridgesChanged).toBe(true)
+ })
+
+ it('reports no change when the merge lands on exactly what the canvas already holds', () => {
+ // `setControlEdges` on an identical set is a whole-canvas edge re-render (displayEdges
+ // recomputes colour and the waiting look per edge) for nothing, and these arrive in bursts.
+ const base = project([caller, first], { ropes: [rope('ctrl-1', caller.id, first.id)] })
+ const incoming = project([caller, first], { ropes: [rope('ctrl-1', caller.id, first.id)] })
+
+ const plan = planServerChange({
+ base,
+ incoming,
+ liveNodeIds: [caller.id, first.id],
+ liveRopes: [rope('ctrl-1', caller.id, first.id)],
+ liveBridges: []
+ })
+
+ expect(plan.ropesChanged).toBe(false)
+ expect(plan.bridgesChanged).toBe(false)
+ expect(plan.added).toEqual([])
+ })
+
+ it('applies the same rules to context bridges', () => {
+ // `link` writes bridges the same way `open-agent` writes ropes, so one drifting copy of these
+ // rules is exactly the bug class this merge exists to close.
+ const base = project([caller, first], {
+ bridges: [{ id: 'bridge-old', source: caller.id, target: first.id }]
+ })
+ const incoming = project([caller, first], {
+ bridges: [{ id: 'bridge-new', source: caller.id, target: first.id }]
+ })
+
+ const plan = planServerChange({
+ base,
+ incoming,
+ liveNodeIds: [caller.id, first.id],
+ liveRopes: [],
+ liveBridges: [
+ { id: 'bridge-old', source: caller.id, target: first.id },
+ { id: 'bridge-local', source: first.id, target: caller.id }
+ ]
+ })
+
+ // server-removed drops, local-unsaved survives, server-added lands — in that order.
+ expect(plan.bridges.map((b) => b.id)).toEqual(['bridge-local', 'bridge-new'])
+ expect(plan.bridgesChanged).toBe(true)
+ })
+})
diff --git a/src/renderer/lib/serverChange.ts b/src/renderer/lib/serverChange.ts
new file mode 100644
index 000000000..443642cd5
--- /dev/null
+++ b/src/renderer/lib/serverChange.ts
@@ -0,0 +1,125 @@
+/** What to do with a project THIS core wrote itself (`workspace:server-change`).
+ *
+ * Server Edition canvas control runs a headless factory: an agent asks for `open-agent`, the
+ * factory appends the node and its `ctrl-…` rope to `project.ropes`, saves the file, and tells the
+ * browser what it wrote. Those writes used to ride `workspace:external-change` — the OUTSIDE-edit
+ * channel — where `decideExternalChange` compares the whole project shell, `ropes` included. So a
+ * spawn that landed while the canvas was dirty was classified `conflict` and raised the bar; the
+ * canvas is dirty almost every time (the paired `canvas:mut` marks it, agents spawn in bursts
+ * inside the 800 ms autosave debounce, and the bar itself SUSPENDS autosave, so once up it stayed
+ * up). "Keep my version" then serialized the browser's own edges over the file and dropped the
+ * ropes the server had just persisted, resurrecting cards the server had removed.
+ *
+ * There is nothing to choose between here: both sides are this application. The disk copy is
+ * authoritative for what the server touched, the live canvas is authoritative for edits the user
+ * has made and not yet saved, and the two are disjoint in practice. So this is a three-way merge
+ * against `base` (the projects-store copy = our last-known DISK state, exactly what
+ * `decideExternalChange` uses it for), not a question.
+ *
+ * Pure — no React, no store — so the whole decision is unit-testable without a canvas.
+ */
+import type { CanvasNodeState, Project } from '@shared/types'
+
+/** The only part of a React Flow edge this merge reasons about. Ropes carry no stored colour or
+ * "waiting" flag (both are derived per render from the endpoints — see lib/edgeModel.ts), so an
+ * id and its two endpoints ARE the edge as far as persistence is concerned. */
+export interface EdgeRef {
+ id: string
+ source: string
+ target: string
+}
+
+export interface ServerChangeInput {
+ /** Our last-known DISK state for this project: the projects-store copy. `undefined` = a project
+ * we have never loaded, in which case there is no baseline and everything incoming is new. */
+ base: Project | undefined
+ /** What the server just wrote and persisted. */
+ incoming: Project
+ /** Node ids React Flow currently holds — including ones created locally and not yet saved. */
+ liveNodeIds: Iterable<string>
+ /** The live rope set (`controlEdgesRef`), id/source/target only. */
+ liveRopes: readonly EdgeRef[]
+ /** The live context-bridge set (`linkEdgesRef`). */
+ liveBridges: readonly EdgeRef[]
+}
+
+export interface ServerChangePlan {
+ /** Nodes to adopt onto the live canvas — silently: the user's own agent asked for these. */
+ added: CanvasNodeState[]
+ /** The merged rope set to install. */
+ ropes: EdgeRef[]
+ /** The merged bridge set to install. */
+ bridges: EdgeRef[]
+ /** `false` ⇒ the merge changed nothing, so do NOT call `setControlEdges`: a fresh array of
+ * structurally identical edges is a re-render (and a new `displayEdges` pass) for nothing. */
+ ropesChanged: boolean
+ bridgesChanged: boolean
+}
+
+const edgeRef = (e: EdgeRef): EdgeRef => ({ id: e.id, source: e.source, target: e.target })
+
+/** One merge, applied to ropes and to bridges alike — they are the same problem with two names,
+ * and a second copy of these five rules is a second place for them to drift. */
+function mergeEdges(
+ base: readonly EdgeRef[],
+ incoming: readonly EdgeRef[],
+ live: readonly EdgeRef[],
+ nodeIds: ReadonlySet<string>
+): { edges: EdgeRef[]; changed: boolean } {
+ const baseIds = new Set(base.map((e) => e.id))
+ const incomingIds = new Set(incoming.map((e) => e.id))
+ const liveIds = new Set(live.map((e) => e.id))
+
+ // In base but NOT in the file the server just wrote ⇒ the server removed it (it closed a node,
+ // or dropped a rope). Everything else the canvas holds stays: an edge live but not in base is a
+ // local addition nobody else has seen yet, and an edge in both base and incoming that the canvas
+ // no longer holds is a local DELETION — re-adding it would undo the user's edit.
+ const kept = live.filter((e) => !(baseIds.has(e.id) && !incomingIds.has(e.id)))
+ // In the file but not in base ⇒ the server added it. Skip any id the canvas somehow already
+ // holds: a duplicate React Flow edge id renders as one edge and breaks the next removal.
+ const additions = incoming.filter((e) => !baseIds.has(e.id) && !liveIds.has(e.id))
+
+ // An edge to a node that is not on the canvas is a dangling edge: React Flow drops it silently
+ // at render, but it would be SAVED by the next autosave, so prune it here where the pruning is
+ // visible. (The server's own removals arrive with their edges already gone; this catches the
+ // cross case — a node deleted locally while the server added a rope to it.)
+ const edges = [...kept, ...additions]
+ .filter((e) => nodeIds.has(e.source) && nodeIds.has(e.target))
+ .map(edgeRef)
+
+ const changed =
+ edges.length !== live.length || edges.some((e, i) => e.id !== live[i]!.id)
+ return { edges, changed }
+}
+
+export function planServerChange(input: ServerChangeInput): ServerChangePlan {
+ const { base, incoming } = input
+ const live = new Set(input.liveNodeIds)
+ const baseNodeIds = new Set((base?.nodes ?? []).map((n) => n.id))
+ // Same rule as `decideExternalChange`: a node counts as added only when NEITHER the canvas nor
+ // our last-known disk state has its id. The base check is what stops a node the user deleted
+ // locally (and has not saved yet) from being resurrected by the file that still lists it.
+ const added = incoming.nodes.filter((n) => !live.has(n.id) && !baseNodeIds.has(n.id))
+
+ // Edges are pruned against the canvas as it will be AFTER the adoption, not as it is now —
+ // otherwise the rope the server wrote with the node it just opened would be pruned as dangling
+ // on the very payload that introduced both.
+ const nodeIds = new Set(live)
+ for (const n of added) nodeIds.add(n.id)
+
+ const ropes = mergeEdges(base?.ropes ?? [], incoming.ropes ?? [], input.liveRopes, nodeIds)
+ const bridges = mergeEdges(
+ base?.bridges ?? [],
+ incoming.bridges ?? [],
+ input.liveBridges,
+ nodeIds
+ )
+
+ return {
+ added,
+ ropes: ropes.edges,
+ bridges: bridges.edges,
+ ropesChanged: ropes.changed,
+ bridgesChanged: bridges.changed
+ }
+}
diff --git a/src/server/canvas-control.test.ts b/src/server/canvas-control.test.ts
index 2ad89876b..6bcfd9b78 100644
--- a/src/server/canvas-control.test.ts
+++ b/src/server/canvas-control.test.ts
@@ -19,21 +19,24 @@ import {
recordFreshSpawnOwner,
resetPaneOwnershipForTests
} from '../core/agents/pane-ownership'
-import { fakePlatform } from '../core/platform-fake'
+import { fakePlatform, type 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 { IPC } from '../shared/ipc'
+import { DEFAULT_SETTINGS, type Project, type Settings, type Workspace } from '../shared/types'
import { initServerCanvasControl, type ServerCanvasControl } from './canvas-control'
describe('initServerCanvasControl', () => {
let dataDir = ''
let runtime: ServerCanvasControl | null = null
+ let fake: FakePlatform
beforeEach(() => {
dataDir = fs.mkdtempSync(path.join(os.tmpdir(), 'nodeterm-server-control-'))
resetPlatformForTests()
- initPlatform(fakePlatform({ userDataDir: dataDir }))
+ fake = fakePlatform({ userDataDir: dataDir })
+ initPlatform(fake)
resetPaneOwnershipForTests()
resetMessageFlow()
resetAgentMessageTraceForTests()
@@ -293,4 +296,76 @@ describe('initServerCanvasControl', () => {
expect(writes[1]).toEqual({ text: '', enter: true })
expect(legacySendEnvelope).not.toHaveBeenCalled()
})
+
+ it('publishes its own writes on server-change, never on the outside-edit channel', async () => {
+ // The defect this pins: `open-agent` appends a `ctrl-…` rope to `project.ropes`, and while
+ // that rode `workspace:external-change` the renderer ran it through `decideExternalChange`,
+ // which reads a changed `ropes` array as a CONFLICT whenever the canvas is dirty. The bar it
+ // raised suspends autosave, so a burst of spawns latched it on, and "Keep my version" then
+ // wrote the browser's edges over the ropes this factory had just persisted.
+ 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'
+ }
+ ]
+ }
+ ]
+ }
+ const store = {
+ load: vi.fn(async () => workspace),
+ save: vi.fn(async () => undefined),
+ persistedCanvases: () => [{ id: 'p1', nodes: workspace.projects[0].nodes }],
+ capabilityProjectFor: () => ({ agentMessaging: false, capabilityAck: {} })
+ } as unknown as WorkspaceStore
+ const pty = {
+ createHeadless: vi.fn(async () => ({ sessionId: 'unused', fresh: true })),
+ sendText: vi.fn(async () => true),
+ destroySession: vi.fn(async () => undefined),
+ paneOwner: vi.fn(async () => null),
+ sendEnvelope: vi.fn(async () => true),
+ hasLiveSession: () => true
+ } as unknown as PtyManager
+
+ runtime = await initServerCanvasControl({
+ workspaceStore: store,
+ ptyManager: pty,
+ settings: () => ({ ...DEFAULT_SETTINGS }),
+ boardLog: { append: async () => false },
+ installAgentIntegrations: false
+ })
+ fake.sent.length = 0
+
+ const opened = await runtime.handler({
+ verb: 'open-agent',
+ nodeId: 'source',
+ args: { agent: 'claude', prompt: 'spawn me' },
+ verified: true
+ })
+ expect(opened).toMatchObject({ ok: true })
+ const openedId = (opened.result as { id: string }).id
+
+ const server = fake.sent.filter((e) => e.channel === IPC.workspaceServerChange)
+ expect(server.length).toBeGreaterThan(0)
+ const published = server.at(-1)!.args[0] as Project
+ expect(published.id).toBe('p1')
+ expect(published.nodes.map((n) => n.id)).toContain(openedId)
+ // The one that must NOT happen: nothing this factory writes is an "another device" edit.
+ expect(fake.sent.filter((e) => e.channel === IPC.workspaceExternalChange)).toEqual([])
+ })
})
diff --git a/src/server/canvas-control.ts b/src/server/canvas-control.ts
index 8efe12347..b53dac00f 100644
--- a/src/server/canvas-control.ts
+++ b/src/server/canvas-control.ts
@@ -175,7 +175,14 @@ export async function initServerCanvasControl(
deps.codexSharedIdentity ?? (() => codexIdentityCaps().then((caps) => caps.shared)),
stateOf: nodeState,
agentIdOf: (nodeId) => mirrorEntry(nodeId)?.agentId,
- publishProject: (project: Project) => platform().broadcast(IPC.workspaceExternalChange, project)
+ // NOT `workspaceExternalChange`. That channel means "somebody else wrote this file" and the
+ // renderer answers it with `decideExternalChange`, which compares the whole project shell —
+ // and `ropes` is part of it, so every headless spawn (one appended `ctrl-…` rope) read as a
+ // conflict while the canvas was dirty, which it almost always is mid-burst. The bar that came
+ // up suspends autosave, so it latched on, and "Keep my version" then wrote the browser's edge
+ // state over the ropes this factory had just persisted. These writes are OURS; the renderer
+ // merges them (renderer/lib/serverChange.ts) and is never asked to choose.
+ publishProject: (project: Project) => platform().broadcast(IPC.workspaceServerChange, project)
})
const messaging: AgentMessagingDeps = {
diff --git a/src/server/workspace-external-watch.test.ts b/src/server/workspace-external-watch.test.ts
index e227dc989..224312637 100644
--- a/src/server/workspace-external-watch.test.ts
+++ b/src/server/workspace-external-watch.test.ts
@@ -100,5 +100,9 @@ describe('Server Edition external workspace watcher', () => {
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 }])
+ // This one IS an outside edit — a hand edit or a git pull — so it belongs on the channel the
+ // renderer answers with the conflict bar, and must never be swapped onto the server-write
+ // channel a later refactor might mistake it for (that one merges silently, no question asked).
+ expect(fake.sent.filter((entry) => entry.channel === IPC.workspaceServerChange)).toEqual([])
})
})
diff --git a/src/shared/ipc.ts b/src/shared/ipc.ts
index 853435342..fb322ceed 100644
--- a/src/shared/ipc.ts
+++ b/src/shared/ipc.ts
@@ -365,6 +365,10 @@ export const IPC = {
/** Payload: the `workspace.json.corrupt-<ts>` filename the unreadable index was preserved as. */
workspaceCorruptRecovered: 'workspace:corrupt-recovered',
workspaceExternalChange: 'workspace:external-change',
+ /** Server-originated project writes (Server Edition headless canvas control: an agent opened,
+ * renamed, moved or closed a node and this core saved the file itself). NOT an outside edit —
+ * the renderer three-way merges it instead of raising the conflict bar. */
+ workspaceServerChange: 'workspace:server-change',
githubIssuesSubscribe: 'githubIssues:subscribe',
githubIssuesUnsubscribe: 'githubIssues:unsubscribe',
githubIssuesQuery: 'githubIssues:query',
diff --git a/src/shared/types.ts b/src/shared/types.ts
index a84a89a55..609b10b9c 100644
--- a/src/shared/types.ts
+++ b/src/shared/types.ts
@@ -964,6 +964,9 @@ export interface WorkspaceApi {
onCorruptRecovered(cb: (backupFile: string) => void): () => void
/** Fired when a project file changed on disk outside the app (git pull, sync, teammate). */
onExternalChange(cb: (project: Project) => void): () => void
+ /** Fired when THIS core wrote the project itself (Server Edition headless canvas control: an agent
+ * opened, renamed, moved, closed…). Not an outside edit — the renderer merges it, never asks. */
+ onServerChange(cb: (project: Project) => void): () => void
}
export interface ProjectSettingsApi {