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): close the defects an adversarial pass found in this branch's own fixes
albaneselorenzo50e00d7ba128
diff --git a/src/renderer/canvas/Canvas.tsx b/src/renderer/canvas/Canvas.tsxindex 84f58f1f5..f7bd5212e 100644--- a/src/renderer/canvas/Canvas.tsx+++ b/src/renderer/canvas/Canvas.tsx@@ -493,7 +493,6 @@ import {createDinoNode,createTriggerNode,createFilesNode,- sshBindingForCwd,createDiffNode,createEditorNode,createGroupNode,@@ -3601,11 +3600,16 @@ export function Canvas() {console.info(`[nodeterm] node-create agent=- project=${targetProjectId} group=${groupId ?? '-'} cwd=${cwd ?? '-'}`)- // In an SSH project the node is stamped remote (runs over the project's master) and- // `createTerminalNode` roots it at `ssh.remoteCwd`, which silently discards a caller's- // "here" — see `sshBindingForCwd` for the whole reasoning. With no override this is- // byte-identical to before.- const ssh = sshBindingForCwd(project?.ssh, cwdOverride)+ // In an SSH project the node is stamped remote and `createTerminalNode` roots it at+ // `ssh.remoteCwd`, silently discarding a caller's "here" — which is exactly the trap+ // `nodeSshFor` was written for ("passing the project's ssh unchanged silently REPLACES the+ // caller's cwd"). `addTerminal` simply never used it.+ //+ // `cwdOverride`, NOT the resolved `cwd`: an SSH project can still carry a local+ // `project.cwd`, and `scmCwd` falls back to it, so passing the resolved value would launder+ // a path from this machine into `remoteCwd`. With no override this is byte-identical to+ // passing `project?.ssh` straight through.+ const ssh = nodeSshFor(project?.ssh, cwdOverride)setNodes((ns) => {const node = createTerminalNode(ns.length, cwd, center ?? emptyNodePos(), initialCommand, ssh)return [...ns, groupId ? parentInto(node, groupId) : node]diff --git a/src/renderer/lib/filesNode.test.ts b/src/renderer/lib/filesNode.test.tsindex bdac92919..7a3595228 100644--- a/src/renderer/lib/filesNode.test.ts+++ b/src/renderer/lib/filesNode.test.ts@@ -133,6 +133,35 @@ describe('classifyEmptyListing', () => {expect(classifyEmptyListing('/', [])).toBe('empty')})+ // Every case below would name-match FAIL and be reported as a deletion. Each is a readable+ // directory, so `unknown` (which renders as "empty") is the only honest answer.++ // The one that shipped: an SSH project's remoteCwd DEFAULTS to `~`. `ls ~` works, but+ // parentDir('~') is '/' and '/' has no entry named '~' — so an empty remote HOME reported+ // "Could not read this folder."+ it('never calls a non-absolute path missing — `~` is an SSH project default, not a deletion', () => {+ expect(classifyEmptyListing('~', [{ name: 'bin' }, { name: 'etc' }])).toBe('unknown')+ expect(classifyEmptyListing('~/src', [{ name: 'bin' }])).toBe('unknown')+ expect(classifyEmptyListing('relative/dir', [{ name: 'bin' }])).toBe('unknown')+ })++ // Both listing legs strip `.git` on purpose, so a node pointed at one can never find itself.+ it('never calls a .git directory missing — both listing legs filter it out', () => {+ expect(classifyEmptyListing('/repo/.git', [{ name: 'src' }, { name: 'README.md' }])).toBe('unknown')+ })++ it('never calls a dot segment missing — readdir and `ls -A` do not emit them', () => {+ expect(classifyEmptyListing('/repo/.', [{ name: 'src' }])).toBe('unknown')+ expect(classifyEmptyListing('/repo/..', [{ name: 'src' }])).toBe('unknown')+ })++ // APFS/NTFS list a directory fine under the wrong case, but readdir answers with the on-disk+ // spelling. "Missing" has to be the conclusion we are SURE of.+ it('accepts a case-folded match on a case-insensitive filesystem', () => {+ expect(classifyEmptyListing('/repo/Docs', [{ name: 'docs' }])).toBe('empty')+ expect(classifyEmptyListing('/repo/docs', [{ name: 'DOCS' }])).toBe('empty')+ })+// A symlinked directory can list as a non-dir entry depending on the leg; matching on `dir`// would call it missing. Name matching is what keeps that false alarm out.it('matches by name, not by entry kind', () => {diff --git a/src/renderer/lib/filesNode.ts b/src/renderer/lib/filesNode.tsindex ccd74e1b9..41d1dc4a2 100644--- a/src/renderer/lib/filesNode.ts+++ b/src/renderer/lib/filesNode.ts@@ -57,10 +57,15 @@ export function breadcrumbs(path: string, max = 3): Crumb[] {* `fileMissing`, because a directory can be re-pointed and a dead file cannot.** `null` means LEAVE IT ALONE, and that is the interesting answer: with no fallback directory- * there is nowhere honest to send it, and writing `undefined` is worse than doing nothing —- * `FilesNode` reads `data.cwd || '/'`, so the node would silently begin listing the filesystem- * ROOT. Left on the dead path, the parent-listing probe says "Could not read this folder", which- * is the truth.+ * there is nowhere honest to send it, and writing `undefined` is worse than doing nothing — the+ * node would lose the only thing it knows about itself. Left on the dead path, the parent-listing+ * probe usually says "Could not read this folder", which is the truth.+ *+ * Two honest caveats. The branch is near-unreachable in practice (a worktree binding cannot exist+ * without a project cwd, so a fallback almost always exists). And "usually": `git worktree remove`+ * deletes the worktree but not the now-empty `<repo>.worktrees/` container, so removing the LAST+ * one leaves the probe with an empty parent — `unknown`, which still renders as "empty". Doing+ * nothing is still better than writing a path we cannot justify.** The title rides along while `titleAuto` holds. This is the one cwd write that does NOT go* through `navigate` — the only other place that pairs the two — so without it the node moves to@@ -112,10 +117,32 @@ export function classifyEmptyListing(/** The parent's entries, or `null` when the parent was not asked or could not be read. */parentEntries: readonly { name: string }[] | null): EmptyListingVerdict {+ const trimmed = cwd.replace(/\/+$/, '')const name = folderTitle(cwd)- if (name === '/' || !cwd.replace(/\/+$/, '')) return 'empty' // root: no parent, always exists+ if (name === '/' || !trimmed) return 'empty' // root: no parent, always exists++ // Below are the paths whose parent listing CANNOT answer the question. Each of them would+ // otherwise fail to name-match and be reported as `missing` — a false "your folder is gone" on a+ // directory that is perfectly readable, which is the one error this whole classifier exists to+ // avoid making.+ //+ // - Not `/`-absolute. `~` is the big one: an SSH project's `remoteCwd` DEFAULTS to `~`+ // (SshSection), `ls ~` works fine on the host, but `parentDir('~')` is `/` and `/` has no+ // entry called `~`. So an empty remote HOME reported "Could not read this folder."+ // - `.` / `..` segments — `readdir` and `ls -A` never emit them.+ // - `.git`, which BOTH listing legs strip on purpose (`core/fs-ops.ts`, `main/ssh-fs.ts`), so a+ // node pointed at one can never find itself in its parent.+ if (!trimmed.startsWith('/') || name === '.' || name === '..' || name === '.git') return 'unknown'+if (!parentEntries || parentEntries.length === 0) return 'unknown'- return parentEntries.some((e) => e.name === name) ? 'empty' : 'missing'+ if (parentEntries.some((e) => e.name === name)) return 'empty'+ // A case-insensitive filesystem (APFS, NTFS) lists a directory fine under a cwd whose case+ // differs from the on-disk spelling, and `readdir` answers with the on-disk one. Treat that as+ // present: a case-folded match is weaker evidence of existence, but "missing" needs to be the+ // conclusion we are SURE of.+ const lower = name.toLowerCase()+ if (parentEntries.some((e) => e.name.toLowerCase() === lower)) return 'empty'+ return 'missing'}/** Join a directory and an entry name. Trailing slashes on the dir are absorbed, so the rootdiff --git a/src/renderer/nodes/FilesNode.tsx b/src/renderer/nodes/FilesNode.tsxindex 72281d301..396c7588f 100644--- a/src/renderer/nodes/FilesNode.tsx+++ b/src/renderer/nodes/FilesNode.tsx@@ -12,7 +12,13 @@* through the node's own session api — which is the local core for a local project and the PEER's* core for a relay tab, so a relay tab browses the machine its terminals are actually on. Getting* this from `useSession()` rather than `window.nodeTerminal` is the whole reason a relay tab works- * here for free.+ * here for free — **while `data.sshFs` is false.** When it is set, `sshFs(projectId)` reaches+ * `window.nodeTerminal.sshFs`, i.e. THIS machine's preload, not the session's. That is inherited+ * (`createEditorNode`/`createVideoNode` stamp and share the flag the same way) and it matters more+ * here than for them: `sshFs` is written into the git-shared `project.json`, so a teammate who+ * clones the repo locally gets a node flagged remote with a perfectly valid local cwd, and the+ * unresolvable ref fails open to `[]` — a directory full of files reported as empty. Fixing it+ * means routing `sshFs` through the session api for every consumer, which is its own change.** **Opening is delegated, not reimplemented.** A file dispatches `nodeterm:open-file` — the event* `TerminalNode`'s Cmd+click links already use — so editor / image / video routing stays in@@ -80,7 +86,18 @@ export function FilesNode({ id, data, selected }: NodeProps<CanvasNode>) {const [version, setVersion] = useState(0)const collapsed = !!data.collapsed- const cwd = (data.cwd as string) || '/'+ /**+ * The directory this node shows. It used to fall back to `'/'`, which meant a node with no `cwd`+ * silently listed the FILESYSTEM ROOT — reachable with no bug on our side, because+ * `.nodeterm/project.json` is git-shared, hand-editable input and nothing validates a files+ * node's `cwd` on load. It is also the same failure `displacedFilesPatch` refuses on the WRITE+ * side; guarding one end and not the other left the hole open under the commit named after it.+ *+ * No silent fallback now: with no cwd there is nothing to list and the node says so. `''` is+ * inert for the rest of the component because the effect below never lists it, and reaching the+ * root then takes a deliberate click on a crumb rather than happening by itself.+ */+ const cwd = typeof data.cwd === 'string' ? data.cwd.trim() : ''/** Null whenever the rows on screen do not belong to the directory being shown — i.e. the* "Loading…" state, which is now reachable on every navigation and not just the first mount. */const entries = listing && listing.cwd === cwd ? listing.entries : null@@ -98,6 +115,13 @@ export function FilesNode({ id, data, selected }: NodeProps<CanvasNode>) {useEffect(() => {let live = truesetError('')+ if (!cwd) {+ // Nothing to list, and listing `'/'` instead would be the silent root-browse this guard+ // exists to stop. Name the state rather than showing an empty directory.+ setListing({ cwd, entries: [] })+ setError('This file manager has no folder.')+ return+ }void (async () => {let list: DirEntry[]try {@@ -112,10 +136,21 @@ export function FilesNode({ id, data, selected }: NodeProps<CanvasNode>) {return}if (!live) return- setListing({ cwd, entries: list })- if (list.length > 0) return+ if (list.length > 0) {+ setListing({ cwd, entries: list })+ return+ }// Empty is ambiguous under the fail-open `FsApi` contract, so ask the parent who is right.- // A second listing, no new IPC, and only a definite absence is allowed to raise the error.+ // Only a definite absence is allowed to raise the error.+ //+ // This is a SECOND `fs.list` — no new IPC *channel*, but a real extra round trip, and on an+ // SSH project a real extra remote command. It is bounded (exactly one, never recursive),+ // fails open, and is skipped entirely whenever the directory has any content, so it costs+ // nothing on the common path.+ //+ // Nothing is published until the verdict is in: setting the empty listing first made a+ // deleted folder render "This folder is empty." for one paint and then correct itself. While+ // we are still deciding, "Loading…" is the true answer.const parent = parentDir(cwd)let parentEntries: DirEntry[] | null = nulltry {@@ -124,6 +159,7 @@ export function FilesNode({ id, data, selected }: NodeProps<CanvasNode>) {parentEntries = null // could not ask ⇒ claim nothing}if (!live) return+ setListing({ cwd, entries: list })if (classifyEmptyListing(cwd, parentEntries) === 'missing') {setError('Could not read this folder.')}diff --git a/src/renderer/state/workspace.placement.test.ts b/src/renderer/state/workspace.placement.test.tsindex d597b180c..9549b7c35 100644--- a/src/renderer/state/workspace.placement.test.ts+++ b/src/renderer/state/workspace.placement.test.ts@@ -1,7 +1,7 @@import { afterEach, describe, expect, it } from 'vitest'import { DEFAULT_SETTINGS } from '@shared/types'import { useSettings } from './settings'-import { createStickyNode, createTerminalNode } from './workspace'+import { createFilesNode, createStickyNode, createTerminalNode } from './workspace'const GRID = 20@@ -61,4 +61,17 @@ describe('new node placement with snap-to-grid', () => {expect(node.width as number).toBeGreaterThanOrEqual(160)expect(node.height as number).toBeGreaterThanOrEqual(120)})++ // A factory that reaches for `placeAt` instead of `placeNode` silently opts out of snapping,+ // and this file only covered terminal + sticky — which is exactly why the file-manager node+ // shipped off-grid past a green suite. Position AND size, because React Flow resizes by adding+ // a grid multiple to the START size: an unsnapped box can never be dragged onto the grid later.+ it('snaps a file-manager node like every other kind', () => {+ settings({ snapToGrid: true, gridSize: GRID })+ const node = createFilesNode(0, '/repo/src', cursor)++ expect([node.position.x % GRID, node.position.y % GRID]).toEqual([0, 0])+ expect([(node.width as number) % GRID, (node.height as number) % GRID]).toEqual([0, 0])+ expect(node.style).toEqual({ width: node.width, height: node.height })+ })})diff --git a/src/renderer/state/workspace.test.ts b/src/renderer/state/workspace.test.tsindex e42f60edc..fbfd8d141 100644--- a/src/renderer/state/workspace.test.ts+++ b/src/renderer/state/workspace.test.ts@@ -20,7 +20,6 @@ import {reparentNode,resolveNewNodeAccount,selectedRootIds,- sshBindingForCwd,ungroupNodes} from './workspace'import type { CanvasNode } from './workspace'@@ -1080,32 +1079,3 @@ describe('createAgentNode prompt injection', () => {expect(createAgentNode('gemini', 0, undefined, undefined, 'do X').data.initialCommand).toBe("gemini 'do X'")})})--describe('sshBindingForCwd', () => {- const ssh = { server: { host: 'h', user: 'u' }, remoteCwd: '/srv/app' } as never-- // The bug: "New terminal here" on an SSH project opened at the project root, because- // createTerminalNode does `cwd: ssh ? ssh.remoteCwd : cwd` and threw the request away.- it('rebinds remoteCwd to the directory the caller actually named', () => {- expect(sshBindingForCwd(ssh, '/srv/app/src/renderer')).toMatchObject({- remoteCwd: '/srv/app/src/renderer'- })- })-- it('leaves the binding alone when no directory was named', () => {- expect(sshBindingForCwd(ssh, undefined)).toBe(ssh)- })-- // An SSH project can still carry a LOCAL project.cwd. Promoting a resolved cwd instead of an- // explicit override would root remote terminals at a path from the wrong machine, so the- // trigger is the override and nothing else.- it('never invents a binding for a local project', () => {- expect(sshBindingForCwd(undefined, '/home/me/work')).toBeUndefined()- })-- it('does not mutate the project\'s own binding', () => {- const before = { ...(ssh as object) }- sshBindingForCwd(ssh, '/elsewhere')- expect(ssh).toEqual(before)- })-})diff --git a/src/renderer/state/workspace.ts b/src/renderer/state/workspace.tsindex 70663eaf5..66dd376f4 100644--- a/src/renderer/state/workspace.ts+++ b/src/renderer/state/workspace.ts@@ -302,26 +302,6 @@ export function nodeSshFor(return { server: projectSsh.server, remoteCwd: cwd || projectSsh.remoteCwd }}-/**- * The ssh binding a terminal should be created with when the caller named a directory.- *- * `createTerminalNode` roots a remote node at `ssh.remoteCwd` and ignores its `cwd` argument- * (`cwd: ssh ? ssh.remoteCwd : cwd`). That is right for a plain "new terminal" and wrong for- * every caller that meant a SPECIFIC directory — a file manager's "New terminal here", a Source- * Control action scoped to a checkout — because on an SSH project the request was discarded in- * silence and the terminal opened at the project root.- *- * Keyed on an EXPLICIT override, never on a resolved cwd: an SSH project can still carry a local- * `project.cwd`, and promoting that to `remoteCwd` would root remote terminals at a path from the- * wrong machine. With no override the binding is returned untouched.- */-export function sshBindingForCwd(- ssh: Project['ssh'] | undefined,- cwdOverride: string | undefined-): Project['ssh'] | undefined {- return ssh && cwdOverride ? { ...ssh, remoteCwd: cwdOverride } : ssh-}-export function createTerminalNode(index: number,cwd?: string,@@ -1058,10 +1038,12 @@ export function createFilesNode(return {id: nextId('files'),type: 'files',- position: placeAt(center, index, FILES_SIZE.width, FILES_SIZE.height),- width: FILES_SIZE.width,- height: FILES_SIZE.height,- style: { width: FILES_SIZE.width, height: FILES_SIZE.height },+ // `placeNode`, not `placeAt`: it snaps POSITION AND SIZE to `settings.gridSize` when+ // snap-to-grid is on, which is what every other factory does. `placeAt` alone left a new file+ // manager sitting off-grid beside snapped neighbours, and off-grid in SIZE too — React Flow+ // resizes by adding a grid multiple to the start size, so an unsnapped box can never be+ // dragged onto the grid afterwards.+ ...placeNode('files', center, index, FILES_SIZE.width, FILES_SIZE.height),data: {title: folderTitle(cwd),color: '#ffd60a',