Node-based terminal manager for AI coding agents — tmux-backed terminals and parallel agent sessions as draggable nodes on an infinite pan/zoom canvas. macOS, Linux, and a browser Server Edition.
TypeScript adhdagent-orchestrationai-agentscanvasclaude-codecodexcoding-agentsdeveloper-toolselectrongeminilinuxmacosmultiplexeropencodeparallel-agentsterminalterminal-emulatorterminal-multiplexertmuxworkspace-manager
fix(canvas): a session your phone started can no longer be deleted by the desktop
enes2f468a212c37
diff --git a/src/main/index.ts b/src/main/index.tsindex 6c62f43d8..5bfa83917 100644--- a/src/main/index.ts+++ b/src/main/index.ts@@ -2,7 +2,7 @@ import { join, resolve, posix } from 'path'import { startSessionNameSweep, displayNodeTitle } from '../core/session-name-sweep'import { readAgentSessionName, type AgentSessionNameDeps } from '../core/agent-session-name'import { readFile } from 'fs/promises'-import { statSync } from 'fs'+import { existsSync, statSync } from 'fs'import { homedir, hostname } from 'os'import { randomUUID } from 'crypto'import { app, BrowserWindow, clipboard, dialog, ipcMain, Notification, powerMonitor, safeStorage, shell, systemPreferences, webContents } from 'electron'@@ -109,13 +109,16 @@ import { createRemoteContextTail } from './remote-context-tail'import { createRemoteSubagentTail } from './remote-subagent-tail'import { RemoteFile, type RemoteFileRef } from './remote-ssh/remote-file'import {+ checkMasterArgs,childArgs,+ controlPathFor,parseRemoteSessionNames,remoteListSessionsArgs,remotePaneCommandArgs} from '../core/remote-ssh/control-master'+import { planRemoteWorkspacePoll } from './remote-workspace-poll'import { sessionName } from '../core/tmux-naming'-import { posixQuote } from '../shared/ssh'+import { posixQuote, type SshConnection } from '../shared/ssh'import { buildHandoff, type HandoffRemote } from './handoff'import { initContextLink, setNodeTranscript } from '../core/context-link'import { transcriptPathOf } from '../core/context-link-core'@@ -2285,12 +2288,49 @@ app.whenReady().then(async () => {// the live canvas without a reconnect. Read-only unless a mirror write is owed// (pushIfStanding:false), one `cat` per project per tick over the ControlMaster. The in-flight// set keeps a hung read from stacking a second poll on the same project.+ //+ // A project only HAS a master because the renderer's active-project effect connected it, which+ // left every background / never-opened SSH tab permanently unpolled: a session the phone+ // registered into one of them showed up only when the user happened to click that tab. So each+ // tick also sweeps the unconnected ones — REUSE-ONLY (see remote-workspace-poll.ts): a master+ // that is already running is adopted, a host with no live socket is never dialed.{const REMOTE_WORKSPACE_POLL_MS = 15_000+ /** How long a cached ssh endpoint map may be reused before it is re-read from the index. */+ const SSH_ENDPOINT_TTL_MS = 5 * 60_000const inFlight = new Set<string>()+ let endpoints = new Map<string, { conn: SshConnection; remoteCwd: string }>()+ let endpointsAt = 0+ /** The project's connection spec, from the workspace index. Loaded lazily and only when an+ * adoption candidate exists, so a workspace with no orphan sockets never pays for it. */+ const endpointFor = async (+ projectId: string+ ): Promise<{ conn: SshConnection; remoteCwd: string } | undefined> => {+ if (Date.now() - endpointsAt > SSH_ENDPOINT_TTL_MS) {+ try {+ // sideline:false — a read-only caller must never rename a mid-merge project.json.+ const workspace = await workspaceStore.load({ sideline: false })+ endpoints = new Map(+ workspace.projects+ .filter((p) => p.ssh)+ .map((p) => [p.id, { conn: p.ssh!.server, remoteCwd: p.ssh!.remoteCwd }] as const)+ )+ endpointsAt = Date.now()+ } catch { /* keep the previous map: a failed read is not evidence the endpoints changed */ }+ }+ return endpoints.get(projectId)+ }setInterval(() => {- for (const projectId of workspaceStore.sshProjectIds()) {- if (inFlight.has(projectId) || !sshProjectManager?.refForProject(projectId)) continue+ const mgr = sshProjectManager+ if (!mgr) return+ const plan = planRemoteWorkspacePoll({+ sshProjectIds: workspaceStore.sshProjectIds(),+ hasLiveRef: (projectId) => !!mgr.refForProject(projectId),+ busy: (projectId) => inFlight.has(projectId),+ // Reuse-only gate: no socket file ⇒ no master to adopt ⇒ this project is left alone.+ hasControlSocket: (projectId) => existsSync(controlPathFor(projectId))+ })+ for (const projectId of plan.poll) {inFlight.add(projectId)void workspaceStore.refreshSshProject(projectId, { pushIfStanding: false })@@ -2300,6 +2340,24 @@ app.whenReady().then(async () => {.catch(() => { /* fail-open: the next tick retries */ }).finally(() => inFlight.delete(projectId))}+ for (const projectId of plan.adopt) {+ inFlight.add(projectId)+ void (async () => {+ const endpoint = await endpointFor(projectId)+ if (!endpoint) return+ // Ask the socket itself before touching connect(): a leftover file whose master is gone+ // would otherwise send connect() down the DIAL path — the one thing this sweep must not+ // do. `-O check` speaks to the local mux socket only; with no master it fails at once+ // without opening a connection.+ const { code } = await mgr.sshRun(checkMasterArgs(endpoint.conn, controlPathFor(projectId)))+ if (code !== 0) return+ // Live master → connect() takes its reuse branch (no new auth, no passphrase prompt) and+ // registers the ref, so the NEXT tick simply polls this project like any other.+ await mgr.connect(projectId, endpoint.conn, endpoint.remoteCwd)+ })()+ .catch(() => { /* fail-open: the next tick retries */ })+ .finally(() => inFlight.delete(projectId))+ }}, REMOTE_WORKSPACE_POLL_MS)}// Route git-service + commit-message git ops over the active SSH project's master only — and onlydiff --git a/src/main/remote-workspace-poll.test.ts b/src/main/remote-workspace-poll.test.tsnew file mode 100644index 000000000..7d8c0f5f3--- /dev/null+++ b/src/main/remote-workspace-poll.test.ts@@ -0,0 +1,48 @@+import { describe, it, expect } from 'vitest'+import { planRemoteWorkspacePoll } from './remote-workspace-poll'++const plan = (+ ids: string[],+ opts: { refs?: string[]; busy?: string[]; sockets?: string[] } = {}+): ReturnType<typeof planRemoteWorkspacePoll> =>+ planRemoteWorkspacePoll({+ sshProjectIds: ids,+ hasLiveRef: (id) => (opts.refs ?? []).includes(id),+ busy: (id) => (opts.busy ?? []).includes(id),+ hasControlSocket: (id) => (opts.sockets ?? []).includes(id)+ })++describe('planRemoteWorkspacePoll', () => {+ it('polls every connected project, active tab or not', () => {+ expect(plan(['a', 'b'], { refs: ['a', 'b'] })).toEqual({ poll: ['a', 'b'], adopt: [] })+ })++ it('skips a project whose read is still in flight', () => {+ expect(plan(['a', 'b'], { refs: ['a', 'b'], busy: ['a'] }).poll).toEqual(['b'])+ })++ it('adopts a running master for a project this run never connected', () => {+ // The field failure: an SSH project sitting in a background tab (or untouched since launch) has+ // no ref, so it was skipped forever and the session the phone registered into it stayed+ // invisible until the user clicked that tab.+ expect(plan(['a'], { sockets: ['a'] })).toEqual({ poll: [], adopt: ['a'] })+ })++ it('NEVER offers a project with no control socket — a poll must not dial a host', () => {+ // Dialing would be a real TCP + auth per host per tick, and can raise a passphrase prompt.+ expect(plan(['a', 'b'], { sockets: ['b'] })).toEqual({ poll: [], adopt: ['b'] })+ })++ it('does not re-attempt an adoption that is still running', () => {+ expect(plan(['a'], { sockets: ['a'], busy: ['a'] })).toEqual({ poll: [], adopt: [] })+ })++ it('never puts one project in both lists', () => {+ const p = plan(['a'], { refs: ['a'], sockets: ['a'] })+ expect(p).toEqual({ poll: ['a'], adopt: [] })+ })++ it('is empty for a workspace with no ssh projects', () => {+ expect(plan([])).toEqual({ poll: [], adopt: [] })+ })+})diff --git a/src/main/remote-workspace-poll.ts b/src/main/remote-workspace-poll.tsnew file mode 100644index 000000000..f2bb9c973--- /dev/null+++ b/src/main/remote-workspace-poll.ts@@ -0,0 +1,46 @@+/** What the connected-SSH-project workspace poll should do this tick.+ *+ * The poll is how a session the phone registered into an SSH project's+ * `<remoteCwd>/.nodeterm/project.json` reaches the desktop canvas — the file lives on the host, so+ * nothing local can watch it. Reading it needs that project's ControlMaster, and `connect()` is+ * only ever called from the renderer's ACTIVE-project effect. A project sitting in a background+ * tab (or never opened since launch) therefore had NO ref, was skipped every tick, and the phone's+ * node only appeared when the user happened to click that tab.+ *+ * Dialing every SSH project to close that gap is not acceptable: a connect is a real TCP + auth,+ * it can raise a passphrase prompt, and it would fire for every host in the workspace at launch,+ * including ones that are simply down. So the sweep is REUSE-ONLY: a project with no live ref is+ * offered for adoption only when its ControlMaster socket already exists on disk — a master that+ * outlived the last app run under ControlPersist, or one this run opened and dropped from its map.+ * `connect()` takes its orphan-adopt branch there (an `-O check`, no new auth, no prompt); if the+ * socket is dead the caller's own `-O check` says so and we leave it alone. Nothing here ever+ * causes a project with no socket to be dialed.+ */+export interface RemoteWorkspacePollPlan {+ /** Projects to read this tick (a live master is already in hand). */+ poll: string[]+ /** Projects to try to ADOPT an already-running master for, so they join `poll` next tick. */+ adopt: string[]+}++export interface RemoteWorkspacePollInput {+ /** Every ssh entry in the workspace index, active tab or not. */+ sshProjectIds: string[]+ /** Does this project have a ControlMaster this app run is holding? */+ hasLiveRef: (projectId: string) => boolean+ /** Is a read — or an adoption attempt — already running for it? Keeps a hung ssh from stacking. */+ busy: (projectId: string) => boolean+ /** Does the project's ControlPath socket exist on disk? The gate that makes adoption reuse-only. */+ hasControlSocket: (projectId: string) => boolean+}++export function planRemoteWorkspacePoll(input: RemoteWorkspacePollInput): RemoteWorkspacePollPlan {+ const plan: RemoteWorkspacePollPlan = { poll: [], adopt: [] }+ for (const projectId of input.sshProjectIds) {+ if (input.busy(projectId)) continue+ if (input.hasLiveRef(projectId)) plan.poll.push(projectId)+ else if (input.hasControlSocket(projectId)) plan.adopt.push(projectId)+ // No ref and no socket: nothing to reuse. Never dialed — see the header.+ }+ return plan+}diff --git a/src/renderer/canvas/Canvas.tsx b/src/renderer/canvas/Canvas.tsxindex dd11df5d3..bc01569b9 100644--- a/src/renderer/canvas/Canvas.tsx+++ b/src/renderer/canvas/Canvas.tsx@@ -132,6 +132,11 @@ import { markMobileLaunchSeen, shouldShowMobileLaunch } from '../lib/mobileLauncimport type { DictationTarget } from '../components/DictationOverlay'import { describeOs, REPO_URL } from '../lib/bugReport'import { shouldReleasePaneFocus } from '../lib/paneFocus'+import {+ adoptedNodesNotice,+ decideExternalChange,+ mergeIncomingNodes+} from '../lib/externalChange'import { viewportAtZoom1 } from '../lib/zoomReset'import { isSpaceRelease, spacePanKeydown } from '../lib/spacePan'import { UpdateCard } from '../components/UpdateCard'@@ -707,9 +712,12 @@ export function Canvas() {// give the debounced-autosave effect a dependency that CHANGES in that case — `dirty` stays true// throughout, so without it the effect would never re-arm. Rare, so a re-render costs nothing.const [resaveTick, setResaveTick] = useState(0)- // The active project's .nodeterm file changed on disk while we have unsaved local edits- // (the user must pick a side). One-shot v2→v3 migration note (dismissible strip).- const [conflict, setConflict] = useState<Project | null>(null)+ // The active project's .nodeterm file changed on disk while we have unsaved local edits AND it+ // changed something we also hold (the user must pick a side for that half). `added` counts the+ // nodes that arrived with it and were already adopted onto the canvas — they are never part of+ // the choice (see adoptIncomingNodes), only of the sentence, so the bar cannot imply that+ // "Keep my version" would throw a live session away. One-shot v2→v3 migration note (dismissible strip).+ const [conflict, setConflict] = useState<{ project: Project; added: number } | null>(null)const [migrationNote, setMigrationNote] = useState<string | null>(null)// A local edit team-sync cannot carry (a node over MUTATION_MAX_BYTES — in practice a sticky// whose body someone pasted a document into). The reflector refuses it SILENTLY, so the user is@@ -1978,7 +1986,31 @@ export function Canvas() {useProjects.getState().requestReload()}, [])- // Outside edits to a project's .nodeterm file (git pull / sync / teammate / another machine).+ /** Put nodes that arrived from ANOTHER device onto the live canvas immediately.+ *+ * 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+ * appends the session it started straight into project.json (`appendProjectNode`) and then+ * forgets about it. Leaving it parked behind the conflict bar meant "Keep my version" — or just+ * switching tabs, which drops the bar and lets the next whole-workspace save write our 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)+ // 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]+ )++ // Outside edits to a project's .nodeterm file (git pull / sync / teammate / another machine /+ // the phone registering a session it started).useEffect(() => {return api.workspace.onExternalChange((project) => {const { activeProjectId: current } = useProjects.getState()@@ -1987,16 +2019,41 @@ export function Canvas() {useProjects.getState().replaceProject(project)return}- if (!dirtyRef.current) {- // Active but no unsaved local edits: reload in place.+ // `base` is our last-known DISK state (the store copy is written by a load or a commit+save);+ // React Flow holds the live, possibly dirty canvas. Both are needed to tell "the file only+ // grew a node" from "the file and I disagree about the same nodes".+ const decision = decideExternalChange({+ dirty: dirtyRef.current,+ base: useProjects.getState().getProject(project.id),+ incoming: project,+ liveNodeIds: nodesRef.current.map((n) => n.id)+ })+ if (decision.kind === 'reload') {+ // Active but no unsaved local edits: reload in place (the incoming file already carries any+ // added nodes, so nothing extra to adopt).useProjects.getState().replaceProject(project)reloadActiveProject()return}- // Active with unsaved local edits: let the user pick a side.- setConflict(project)+ // Dirty. Whatever happens to the overlapping half, the sessions registered elsewhere are ours+ // to keep — they are the only part of this payload nobody can produce a second time.+ adoptIncomingNodes(decision.added)+ if (decision.kind === 'conflict') {+ // Something we also hold changed on disk: let the user pick a side for THAT half. The bar+ // keeps its documented meaning (the discarded disk side is re-fetchable — a git pull, a+ // teammate's commit), and it now names what already landed on the canvas behind it.+ setConflict({ project, added: decision.added.length })+ return+ }+ if (decision.kind === 'merge') {+ // Purely additive: the store's baseline can safely move to the disk version (it differs+ // from our last save only by the nodes we just adopted). No bar — there is nothing to+ // choose between.+ useProjects.getState().replaceProject(project)+ }+ // 'ignore': a self-write echo / a change we already hold. Nothing to do, and above all no bar.})- }, [reloadActiveProject])+ }, [reloadActiveProject, adoptIncomingNodes])// 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.@@ -2024,6 +2081,14 @@ export function Canvas() {// switches projects first, drop it: commitActiveToStore already preserved the local edits in// the store, so the next save keeps our version — resolving the stale bar against a different// active project would be wrong.+ //+ // Dropping it IS an implicit "keep mine", and that was a data-loss path while an incoming node+ // could sit behind the bar. It no longer can: nodes registered from another device are adopted+ // onto the canvas before the bar is ever raised (see adoptIncomingNodes), so what a switch+ // discards is only the overlapping half — a git pull / a teammate's commit, which is still in the+ // remote and re-fetchable. Parking the bar across the switch would not have saved anything+ // either: `writeDisk` saves the WHOLE workspace from the store, so the overwrite happens at the+ // next save of ANY project, not at the moment the bar disappears.useEffect(() => {setConflict(null)}, [activeProjectId])@@ -8483,8 +8548,9 @@ export function Canvas() {)}{conflict && (<ConflictBar+ addedCount={conflict.added}onReload={() => {- useProjects.getState().replaceProject(conflict)+ useProjects.getState().replaceProject(conflict.project)// The canvas now matches disk exactly → no local unsaved edits. Clear dirty so the// re-armed autosave (conflict just went null) can't turn around and overwrite the// just-reloaded disk version.diff --git a/src/renderer/components/ConflictBar.tsx b/src/renderer/components/ConflictBar.tsxindex c150725da..78f4cc08e 100644--- a/src/renderer/components/ConflictBar.tsx+++ b/src/renderer/components/ConflictBar.tsx@@ -1,16 +1,26 @@+import { conflictBarMessage } from '../lib/externalChange'+/** Non-blocking strip shown when the active project's .nodeterm file changed on disk* while there are unsaved local edits. Reload = take the disk version; Keep mine =- * overwrite disk with the in-memory canvas on the next save. */+ * overwrite disk with the in-memory canvas on the next save.+ *+ * It only ever covers the OVERLAPPING half of an outside change: nodes that arrived from another+ * device (a session the phone registered) are adopted onto the canvas before this bar is raised,+ * because nothing re-emits them and either button would otherwise be able to delete a running+ * session. `addedCount` is how many did — the message says so, so the user is not asked to weigh+ * a choice against something that is no longer at stake. */export function ConflictBar({+ addedCount = 0,onReload,onKeepMine}: {+ addedCount?: numberonReload(): voidonKeepMine(): void}): JSX.Element {return (<div className="conflict-bar">- <span>Project file changed on disk (git pull or another machine).</span>+ <span>{conflictBarMessage(addedCount)}</span><button onClick={onReload}>Reload from disk</button><button onClick={onKeepMine}>Keep my version</button></div>diff --git a/src/renderer/lib/externalChange.test.ts b/src/renderer/lib/externalChange.test.tsnew file mode 100644index 000000000..f60e2b383--- /dev/null+++ b/src/renderer/lib/externalChange.test.ts@@ -0,0 +1,199 @@+import { describe, it, expect } from 'vitest'+import {+ adoptedNodesNotice,+ canonicalJson,+ conflictBarMessage,+ decideExternalChange,+ mergeIncomingNodes+} from './externalChange'+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+})++/** The phone's registration: our canvas plus one node id nobody here has ever seen. */+const phoneNode = node('term-mmm-9f2a', { title: 'Mobile session', agentId: 'claude' })++describe('decideExternalChange', () => {+ it('reloads wholesale when there are no unsaved local edits (unchanged behavior)', () => {+ const base = project([node('term-a-1')])+ const incoming = project([node('term-a-1'), phoneNode])+ expect(+ decideExternalChange({ dirty: false, base, incoming, liveNodeIds: ['term-a-1'] }).kind+ ).toBe('reload')+ })++ it('MERGES a phone registration that lands while the canvas is dirty — no bar', () => {+ // The field failure: this used to park behind the conflict bar, and "Keep my version" (or just+ // switching tabs) then wrote our canvas over disk, deleting a node whose tmux session is live.+ const base = project([node('term-a-1')])+ const incoming = project([node('term-a-1'), phoneNode])+ const decision = decideExternalChange({+ dirty: true,+ base,+ incoming,+ liveNodeIds: ['term-a-1']+ })+ expect(decision.kind).toBe('merge')+ expect(decision.added.map((n) => n.id)).toEqual(['term-mmm-9f2a'])+ })++ it('still adopts the new session when the rest of the file DID conflict', () => {+ // A git pull that both moved an existing node and carried the phone's registration: the+ // overlapping half is the user's choice, the added node is nobody's to lose.+ const base = project([node('term-a-1')])+ const incoming = project([node('term-a-1', { position: { x: 900, y: 40 } }), phoneNode])+ const decision = decideExternalChange({+ dirty: true,+ base,+ incoming,+ liveNodeIds: ['term-a-1']+ })+ expect(decision.kind).toBe('conflict')+ expect(decision.added.map((n) => n.id)).toEqual(['term-mmm-9f2a'])+ })++ it('conflicts when a shared field other than the nodes changed on disk', () => {+ const base = project([node('term-a-1')])+ const incoming = project([node('term-a-1')], { name: 'Renamed elsewhere' })+ expect(+ decideExternalChange({ dirty: true, base, incoming, liveNodeIds: ['term-a-1'] }).kind+ ).toBe('conflict')+ })++ it('conflicts when a node we hold was DELETED on disk', () => {+ const base = project([node('term-a-1'), node('term-a-2')])+ const incoming = project([node('term-a-1'), phoneNode])+ const decision = decideExternalChange({+ dirty: true,+ base,+ incoming,+ liveNodeIds: ['term-a-1', 'term-a-2']+ })+ expect(decision.kind).toBe('conflict')+ // …and the phone's node still rides along.+ expect(decision.added.map((n) => n.id)).toEqual(['term-mmm-9f2a'])+ })++ it('never resurrects a node deleted locally but still listed on disk', () => {+ // Present in base, gone from the live canvas (unsaved delete): adding it back would undo the+ // user's edit, which is exactly the destruction this fix exists to prevent, mirrored.+ const base = project([node('term-a-1'), node('term-a-2')])+ const incoming = project([node('term-a-1'), node('term-a-2')])+ const decision = decideExternalChange({+ dirty: true,+ base,+ incoming,+ liveNodeIds: ['term-a-1']+ })+ expect(decision.added).toEqual([])+ expect(decision.kind).toBe('ignore')+ })++ it('does not re-add a node the canvas already holds (the SSH poll re-delivers the same file)', () => {+ const base = project([node('term-a-1')])+ const incoming = project([node('term-a-1'), phoneNode])+ const decision = decideExternalChange({+ dirty: true,+ base,+ incoming,+ liveNodeIds: ['term-a-1', 'term-mmm-9f2a']+ })+ expect(decision.added).toEqual([])+ expect(decision.kind).toBe('ignore')+ })++ it('conflicts when we have no baseline to classify against', () => {+ const incoming = project([phoneNode])+ const decision = decideExternalChange({+ dirty: true,+ base: undefined,+ incoming,+ liveNodeIds: []+ })+ expect(decision.kind).toBe('conflict')+ expect(decision.added.map((n) => n.id)).toEqual(['term-mmm-9f2a'])+ })++ it('ignores a machine-local difference (viewport) — it never came from the shared file', () => {+ const base = project([node('term-a-1')])+ const incoming = project([node('term-a-1'), phoneNode], {+ viewport: { x: -40, y: 12, zoom: 0.75 }+ })+ expect(+ decideExternalChange({ dirty: true, base, incoming, liveNodeIds: ['term-a-1'] }).kind+ ).toBe('merge')+ })++ it('treats key order as irrelevant when comparing nodes', () => {+ const base = project([node('term-a-1')])+ // Same node, keys emitted in the opposite order (two serializers, one shape).+ const reordered = Object.fromEntries(+ Object.entries(node('term-a-1')).reverse()+ ) as unknown as CanvasNodeState+ const incoming = project([reordered, phoneNode])+ expect(+ decideExternalChange({ dirty: true, base, incoming, liveNodeIds: ['term-a-1'] }).kind+ ).toBe('merge')+ })+})++describe('canonicalJson', () => {+ it('sorts object keys at every depth', () => {+ expect(canonicalJson({ b: 1, a: { d: 2, c: 3 } })).toBe(canonicalJson({ a: { c: 3, d: 2 }, b: 1 }))+ })+ it('keeps array order significant', () => {+ expect(canonicalJson([1, 2])).not.toBe(canonicalJson([2, 1]))+ })+})++describe('mergeIncomingNodes', () => {+ it('appends only the ids the canvas does not already hold', () => {+ const current = [{ id: 'a' }, { id: 'b' }]+ expect(mergeIncomingNodes(current, [{ id: 'b' }, { id: 'c' }])).toEqual([+ { id: 'a' },+ { id: 'b' },+ { id: 'c' }+ ])+ })+ it('returns the SAME array when there is nothing new (no needless re-render)', () => {+ const current = [{ id: 'a' }]+ expect(mergeIncomingNodes(current, [{ id: 'a' }])).toBe(current)+ })+})++describe('conflict copy', () => {+ it('keeps the historical sentence when nothing was added', () => {+ expect(conflictBarMessage(0)).toBe('Project file changed on disk (git pull or another machine).')+ })+ it('names what arrived, and says it is already on the canvas', () => {+ const msg = conflictBarMessage(1)+ expect(msg).toContain('1 new session')+ expect(msg).toContain('added to this canvas')+ })+ it('pluralizes', () => {+ expect(conflictBarMessage(2)).toContain('2 new sessions')+ expect(conflictBarMessage(2)).toContain('were added to this canvas')+ expect(adoptedNodesNotice(1)).toContain('1 new session')+ expect(adoptedNodesNotice(3)).toContain('3 new sessions')+ expect(adoptedNodesNotice(3)).toContain('were added to this canvas')+ })+})diff --git a/src/renderer/lib/externalChange.ts b/src/renderer/lib/externalChange.tsnew file mode 100644index 000000000..e60524910--- /dev/null+++ b/src/renderer/lib/externalChange.ts@@ -0,0 +1,124 @@+/** What to do with an outside edit to the active project's `.nodeterm/project.json`.+ *+ * Two very different things arrive on the SAME broadcast (`workspaceExternalChange`):+ *+ * 1. A **git pull / another machine** rewrote the file. The disk side and the local side can+ * genuinely disagree about the same nodes, so the user has to pick — that is the conflict bar,+ * and it is re-fetchable: whatever is discarded is still in the remote/branch.+ * 2. The **phone registered a session it just started** (`appendProjectNode`, or the SSH poll+ * picking that up). That is purely ADDITIVE — a node id nothing here has ever seen, backed by+ * a tmux session that is already running. Nothing re-emits it: parking it behind a bar and+ * then answering "Keep my version" (or merely switching projects, which drops the bar and lets+ * the next whole-workspace save write our canvas over disk) DELETES a live session, headless.+ *+ * So an incoming node we do not have is adopted ALWAYS — in the merge case and in the conflict+ * case alike. It cannot collide with a local edit (no local node carries that id), and it is the+ * only part of the payload nobody can produce a second time. The bar then decides only the REST,+ * keeping its documented meaning ("the disk side is re-fetchable") intact.+ */+import type { CanvasNodeState, Project } from '@shared/types'++export type ExternalChangeDecision =+ /** No unsaved local edits: take the disk version wholesale (the pre-existing behavior). */+ | { kind: 'reload'; added: CanvasNodeState[] }+ /** Dirty, and the file differs from our last-known disk state ONLY by added nodes. */+ | { kind: 'merge'; added: CanvasNodeState[] }+ /** Dirty, and something we also hold changed on disk: adopt `added`, ask about the rest. */+ | { kind: 'conflict'; added: CanvasNodeState[] }+ /** Dirty, and nothing we care about differs (a self-write echo, a rev-only touch). */+ | { kind: 'ignore'; added: CanvasNodeState[] }++export interface ExternalChangeInput {+ /** Are there unsaved canvas edits? (`dirtyRef` — the whole reason a bar exists.) */+ dirty: boolean+ /** Our last-known DISK state for this project: the projects-store copy, which is written by+ * a load or a commit+save. Missing (unknown project) ⇒ we cannot classify ⇒ conflict. */+ base: Project | undefined+ /** The version that just landed from disk / the SSH poll. */+ incoming: Project+ /** Node ids React Flow currently holds — including ones created locally and not yet saved. */+ liveNodeIds: Iterable<string>+}++/** Fields that are allowed to differ without meaning "the disk side changed something of ours":+ * `nodes` is compared separately; `viewport`/`defaultAccountId` are machine-local (they come from+ * our own index, not the shared file); `id` is the join key; the rest are runtime-only flags. */+const NOT_SHARED_STATE: ReadonlySet<string> = new Set([+ 'id',+ 'nodes',+ 'viewport',+ 'defaultAccountId',+ 'closed',+ 'unavailable',+ 'remote'+])++/** Stable JSON (object keys sorted at every depth) so two structurally equal values compare equal+ * regardless of the order the serializers happened to emit their keys in. */+export function canonicalJson(value: unknown): string {+ return JSON.stringify(value, (_key, v: unknown) =>+ v && typeof v === 'object' && !Array.isArray(v)+ ? Object.fromEntries(+ Object.entries(v as Record<string, unknown>).sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))+ )+ : v+ )+}++function projectShell(project: Project): string {+ return canonicalJson(+ Object.fromEntries(Object.entries(project).filter(([k]) => !NOT_SHARED_STATE.has(k)))+ )+}++export function decideExternalChange(input: ExternalChangeInput): ExternalChangeDecision {+ const { dirty, base, incoming } = input+ const live = new Set(input.liveNodeIds)+ const baseNodes = new Map((base?.nodes ?? []).map((n) => [n.id, n]))+ // A node is "added" only when NEITHER the canvas nor our last-known disk state has its id. The+ // base check is what keeps a locally DELETED (not yet saved) node from being resurrected by the+ // file that still lists it.+ const added = incoming.nodes.filter((n) => !live.has(n.id) && !baseNodes.has(n.id))++ if (!dirty) return { kind: 'reload', added }+ if (!base) return { kind: 'conflict', added }++ const incomingNodes = new Map(incoming.nodes.map((n) => [n.id, n]))+ const nodesUntouched = [...baseNodes].every(([id, node]) => {+ const other = incomingNodes.get(id)+ return !!other && canonicalJson(node) === canonicalJson(other)+ })+ const additiveOnly = nodesUntouched && projectShell(base) === projectShell(incoming)+ if (!additiveOnly) return { kind: 'conflict', added }+ return added.length ? { kind: 'merge', added } : { kind: 'ignore', added }+}++/** Append incoming nodes to the live canvas, skipping any id it already holds (the SSH poll+ * re-delivers the same file until the next save, and a double-added node would be a duplicate+ * React Flow id — two views onto one tmux session). Generic over the canvas node shape so the+ * helper stays pure and testable. */+export function mergeIncomingNodes<T extends { id: string }>(current: T[], incoming: T[]): T[] {+ const have = new Set(current.map((n) => n.id))+ const fresh = incoming.filter((n) => !have.has(n.id))+ return fresh.length ? [...current, ...fresh] : current+}++/** The conflict strip's sentence. Derived from what actually arrived so the bar cannot claim+ * something vague while a real session sits on the canvas behind it. */+export function conflictBarMessage(addedCount: number): string {+ if (addedCount <= 0) return 'Project file changed on disk (git pull or another machine).'+ const s = addedCount === 1 ? '' : 's'+ const verb = addedCount === 1 ? 'was' : 'were'+ return (+ `${addedCount} new session${s} registered from another device (your phone, or another machine) ` ++ `${verb} added to this canvas. Other parts of the project file also changed on disk — ` ++ `choose which version of those to keep.`+ )+}++/** The one-off note shown when an incoming session was adopted with no bar at all. */+export function adoptedNodesNotice(addedCount: number): string {+ const s = addedCount === 1 ? '' : 's'+ const verb = addedCount === 1 ? 'was' : 'were'+ return `${addedCount} new session${s} registered from another device (your phone, or another machine) ${verb} added to this canvas.`+}