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(worktree): the SSH gate guards the field an SSH-project terminal actually carries
enes1b621fef8106
diff --git a/src/renderer/canvas/Canvas.tsx b/src/renderer/canvas/Canvas.tsxindex cdaa738d2..baca21d4f 100644--- a/src/renderer/canvas/Canvas.tsx+++ b/src/renderer/canvas/Canvas.tsx@@ -94,6 +94,7 @@ import type { NormalizedAgentEvent } from '@shared/agents/normalize'import {computeWorktreePath,displacedByWorktree,+ isRemoteSessionNode,resolveBaseRef,sanitizeWorktreeBranch,worktreeFromCreate,@@ -867,7 +868,10 @@ export function Canvas() {// Worktree facts are per project: drop the previous project's (reset also clears its// statuses), then re-resolve from this project's cwd. SSH projects are skipped — local git// cannot reason about a remote path. Fire-and-forget: the store is epoch-guarded + fails open.- useWorktrees.getState().reset()+ // The project id scopes the strike streaks, which SURVIVE the switch (a dead worktree does not+ // come back to life while the user works in another tab) — so it is passed even for the projects+ // that never refresh (SSH, no cwd), which must not inherit the last project's scope.+ useWorktrees.getState().reset(project.id)if (project.cwd && !project.ssh) {void useWorktrees.getState().refresh(project.cwd, boundGroups(flow))}@@ -1408,13 +1412,20 @@ export function Canvas() {// A STALE binding (the worktree directory was deleted outside the app) must never be handed out:// the terminal would spawn into a directory that no longer exists and fail at launch. Fall back// to the group's own cwd / the project instead, so the node still opens somewhere real.- const cwdForNewNodeIn = useCallback((parentId: string | undefined): string | undefined => {- if (!parentId) return undefined- const parent = nodesRef.current.find((n) => n.id === parentId)- const stale = useWorktrees.getState().staleGroupIds.includes(parentId)- if (parent?.data.worktree && !stale) return parent.data.worktree.path- return parent?.data.cwd || undefined- }, [])+ // On an SSH project a worktree path is not handed out either: it was computed from the LOCAL data+ // dir and means nothing on the host (only a legacy / hand-edited binding can even exist there —+ // worktrees are unsupported in SSH projects in v1). This also keeps the two ↪ guards below honest,+ // since both decide by comparing against what this returns.+ const cwdForNewNodeIn = useCallback(+ (parentId: string | undefined): string | undefined => {+ if (!parentId) return undefined+ const parent = nodesRef.current.find((n) => n.id === parentId)+ const stale = useWorktrees.getState().staleGroupIds.includes(parentId)+ if (parent?.data.worktree && !stale && !isSshProject) return parent.data.worktree.path+ return parent?.data.cwd || undefined+ },+ [isSshProject]+ )// Reparent a freshly-created node into a group (parentId + extent 'parent', position made// relative to the group frame). Mirrors how `groupSelectedNodes` parents its children.@@ -2277,11 +2288,13 @@ export function Canvas() {const onWorktreeAction = useCallback((groupId: string, action: 'merge' | 'remove' | 'unbind') => {// A binding can only predate the SSH gate (hand-edited project file, or a project that became- // an SSH project), but it can still exist — and merge/remove would run LOCAL git against a- // path that lives on the remote host. Refuse them, out loud. `unbind` is still allowed: on an- // SSH project nothing is ever stale (the store never refreshes), so it only drops the binding- // and touches no disk — it is exactly the escape hatch such a group needs.- if (action !== 'unbind' && useProjects.getState().getProject(activeProjectId ?? '')?.ssh) {+ // an SSH project), but it can still exist — and merge/remove would run against the LOCAL+ // filesystem for a project whose git and terminals live on the remote host. Refuse them, out+ // loud. `unbind` stays allowed: it touches no disk at all (it only drops the binding, and+ // resets the children's cwd off a path that means nothing here), so it is exactly the escape+ // hatch such a group needs — and the ONLY worktree action an SSH project offers.+ const sshProject = !!useProjects.getState().getProject(activeProjectId ?? '')?.ssh+ if (action !== 'unbind' && sshProject) {setNotice({ kind: 'error', text: WORKTREE_SSH_NOTICE })return}@@ -2293,7 +2306,12 @@ export function Canvas() {// registered worktree". Prune that registration on the way out. `pruneOnly` guarantees a// directory that still exists is never touched, so a wrongly-stale group cannot delete a// live checkout.- if (wt && useWorktrees.getState().staleGroupIds.includes(groupId)) {+ // …but only for a LOCAL project. An SSH project's groups no longer poll (GroupNode gates+ // the status poll on it), so they cannot go stale — and if a leftover staleness ever did+ // reach here, the prune would run local git against a remote path and the cwd reset would+ // rewrite REMOTE cwds from a local verdict. Plain unbind is the whole of what we can+ // honestly do there.+ if (!sshProject && wt && useWorktrees.getState().staleGroupIds.includes(groupId)) {// Unbind is the DOCUMENTED RECOVERY PATH for a worktree deleted outside the app — the// only action a stale group offers — so it owes the children the same cwd reset Remove// gives them. Without it they keep `data.cwd = <dead worktree path>`, persisted to@@ -2375,6 +2393,11 @@ export function Canvas() {| string| undefinedif (!wtPath) return+ // Never open the confirm for a session that does not live on this machine (see the confirm).+ if (isSshProject || isRemoteSessionNode(node?.data)) {+ setNotice({ kind: 'error', text: WORKTREE_SSH_NOTICE })+ return+ }if (cwdForNewNodeIn(parentId) !== wtPath) {// Stale binding: the button should already be hidden, so this is the belt to that braces.setNotice({@@ -2385,7 +2408,7 @@ export function Canvas() {}setMoveTarget(nodeId)},- [cwdForNewNodeIn]+ [cwdForNewNodeIn, isSshProject])const confirmMoveIntoWorktree = useCallback(async () => {@@ -2396,11 +2419,17 @@ export function Canvas() {const parent = nodesRef.current.find((p) => p.id === node?.parentId)const wtPath = parent?.data.worktree?.path as string | undefinedif (!node || !wtPath || node.data.cwd === wtPath) return- // A remote terminal's session lives on the SSH host; the worktree path was computed locally, so- // respawning it there would drop the session into a directory that does not exist on that host.- // This refusal used to be silent — the confirm closed and nothing happened, which reads as a- // bug. Say why (worktrees are local-only in v1).- if (node.data.remote) {+ // A session that runs on another machine must never be moved into a LOCAL worktree: `destroy`+ // would end its REMOTE tmux session (running processes and all) and respawn it in a directory+ // that does not exist on that host — pty-manager falls back to the host's $HOME and the dead+ // path is persisted to project.json. Worktrees are local-only in v1; say so instead of failing+ // silently (the confirm closing with nothing happening reads as a bug).+ //+ // The question is the PROJECT's (does its git — and its tmux — run over ssh?) and the NODE's+ // (`isRemoteSessionNode`: relay `data.remote` OR an SSH project's `data.ssh`/`data.sshRemoteTmux`).+ // Guarding `data.remote` alone asked only about relay nodes, which cannot occur in an SSH project+ // at all — so the one node kind this exists to protect walked straight through it.+ if (isSshProject || isRemoteSessionNode(node.data)) {setNotice({ kind: 'error', text: WORKTREE_SSH_NOTICE })return}@@ -2447,7 +2476,7 @@ export function Canvas() {))markDirty()- }, [moveTarget, setNodes, markDirty, cwdForNewNodeIn])+ }, [moveTarget, setNodes, markDirty, cwdForNewNodeIn, isSshProject])// Bridge the move-into-worktree handler to TerminalNode (React Flow owns the instances).useEffect(() => {diff --git a/src/renderer/nodes/GroupNode.tsx b/src/renderer/nodes/GroupNode.tsxindex a9ed12ec6..666a9b6c9 100644--- a/src/renderer/nodes/GroupNode.tsx+++ b/src/renderer/nodes/GroupNode.tsx@@ -1,6 +1,7 @@import { useEffect, useState } from 'react'import { NodeResizer, useReactFlow, type NodeProps } from '@xyflow/react'import { NODE_COLORS, ungroupNodes, type CanvasNode } from '../state/workspace'+import { useProjects } from '../state/projects'import { useWorktrees, WORKTREE_STATUS_THROTTLE_MS } from '../state/worktrees'export type WorktreeAction = 'merge' | 'remove' | 'unbind'@@ -34,7 +35,14 @@ export function GroupNode({ id, data, selected }: NodeProps<CanvasNode>) {const status = useWorktrees((s) => (wt ? s.statusByPath[wt.path] : undefined))const stale = useWorktrees((s) => (wt ? s.staleGroupIds.includes(id) : false))- const wtPath = wt?.path+ // On an SSH project the poll is OFF, not merely useless: `git status <path>` would be answered by+ // the LOCAL filesystem for a project whose checkout lives on the host (remote git routing is+ // exact-cwd, and a worktree path is never the project's remoteCwd), so the chip would report a+ // local directory's branch — or, far worse, strike the group out and unlock the stale-Unbind path,+ // which rewrites the children's cwds. Worktrees are unsupported in SSH projects (v1): the honest+ // behaviour is no facts at all, not local facts about a remote checkout.+ const sshProject = useProjects((s) => !!s.projects.find((p) => p.id === s.activeProjectId)?.ssh)+ const wtPath = sshProject ? undefined : wt?.path// Asking once per render is NOT enough to make the chip live: nothing re-renders a group frame// while the user works inside its terminals, so the dirty count would freeze at whatever it was// when the node last happened to render (verified — it sat at "0 changed" until the canvas wasdiff --git a/src/renderer/nodes/TerminalNode.tsx b/src/renderer/nodes/TerminalNode.tsxindex 9986c7af6..aa983c1bb 100644--- a/src/renderer/nodes/TerminalNode.tsx+++ b/src/renderer/nodes/TerminalNode.tsx@@ -41,6 +41,7 @@ import { useAgentNodes } from '../state/agentNodes'import { useProjects } from '../state/projects'import { useSshConn } from '../state/sshConn'import { useWorktrees } from '../state/worktrees'+import { isRemoteSessionNode } from '@shared/worktree'import { accountChipLabel, COLLAPSED_HEIGHT, NODE_COLORS, type CanvasNode } from '../state/workspace'import { hasHooks, canRecur, canContextLink, hasUsage, canChat, canResume, canRename, resumeCommand, withPermissionMode, agentConfig, type AgentId } from '@shared/agents/config'import { ensureActivePermissionMode } from '../state/permissionMode'@@ -269,8 +270,20 @@ export function TerminalNode({ id, data, selected, parentId }: NodeProps<CanvasN? ((getNode(parentId) as CanvasNode | undefined)?.data.worktree?.path as string | undefined): undefinedconst parentWtStale = useWorktrees((s) => (parentId ? s.staleGroupIds.includes(parentId) : false))+ // …and a session that runs on ANOTHER MACHINE must not offer it either. Worktrees are local-only+ // in v1, so ↪ would end this node's REMOTE tmux session and respawn it in a local path that does+ // not exist on the host. Both halves of "remote" are asked: the project (its terminals and its git+ // run over ssh — a local project that LATER became an SSH one still carries the old binding, and+ // its worktree directory may well still exist locally, so nothing else here would notice) and the+ // node (`isRemoteSessionNode` — an SSH-project terminal carries `data.ssh`/`data.sshRemoteTmux`,+ // never `data.remote`). The affordance is absent, not merely refused on click.+ const sshProject = useProjects((s) => !!s.projects.find((p) => p.id === s.activeProjectId)?.ssh)+ const remoteSession = sshProject || isRemoteSessionNode(data)const canMoveIntoWorktree =- !!parentWtPath && !parentWtStale && (data.cwd as string | undefined) !== parentWtPath+ !!parentWtPath &&+ !parentWtStale &&+ !remoteSession &&+ (data.cwd as string | undefined) !== parentWtPathconst status = useAgentStatus((s) => s.byId[id])// Use the chat panel only for a chat-capable agent with a known session; otherwise the// markdown-of-output view (computed in the capture effect below) is shown as a fallback.diff --git a/src/shared/worktree.test.ts b/src/shared/worktree.test.tsindex 18853bd76..c93db69f5 100644--- a/src/shared/worktree.test.ts+++ b/src/shared/worktree.test.ts@@ -8,6 +8,7 @@ import {parseWorktreePorcelain,isDangerousWorktreeRemovalPath,decideMergeStrategy,+ isRemoteSessionNode,isValidGitRef,resolveBaseRef,worktreeFromCreate,@@ -23,6 +24,38 @@ const entry = (path: string, branch: string | null): WorktreeEntry => ({isBare: false})+// Worktrees are local-only in v1, and the gate that keeps a remote session out of one used to ask+// about `data.remote` — a field ONLY a relay node (`createRemoteTerminalNode`) carries, and one that+// can never occur inside an SSH project. So the exact node the gate exists to protect — an+// SSH-PROJECT terminal, created by `createTerminalNode(…, project.ssh)` with `data.ssh` ++// `data.sshRemoteTmux` — walked straight through it: ↪ destroyed its REMOTE tmux session (running+// processes and all) and respawned it in a local path that does not exist on the host.+describe('isRemoteSessionNode', () => {+ it('is true for an SSH-project terminal (data.ssh + data.sshRemoteTmux — never data.remote)', () => {+ expect(+ isRemoteSessionNode({+ ssh: { host: 'box', user: 'me' },+ sshRemoteTmux: true+ })+ ).toBe(true)+ })++ it('is true for a relay-bound remote terminal (data.remote)', () => {+ expect(isRemoteSessionNode({ remote: { connectionId: 'c1' } })).toBe(true)+ })++ it('is true when only one of the two SSH markers survived a hand-edited project file', () => {+ expect(isRemoteSessionNode({ ssh: { host: 'box', user: 'me' } })).toBe(true)+ expect(isRemoteSessionNode({ sshRemoteTmux: true })).toBe(true)+ })++ it('is false for a plain local terminal (nothing changes for the local case)', () => {+ expect(isRemoteSessionNode({})).toBe(false)+ expect(isRemoteSessionNode(undefined)).toBe(false)+ expect(isRemoteSessionNode({ ssh: undefined, remote: undefined, sshRemoteTmux: false })).toBe(false)+ })+})+describe('isValidGitRef', () => {it('accepts a normal branch name', () => {expect(isValidGitRef('feature/x')).toBe(true)diff --git a/src/shared/worktree.ts b/src/shared/worktree.tsindex 0934db976..6136305b3 100644--- a/src/shared/worktree.ts+++ b/src/shared/worktree.ts@@ -24,6 +24,39 @@ export interface WorktreeEntry {prunable?: boolean}+/** `git worktree list`, plus WHETHER GIT COULD BE READ AT ALL — see `worktree-ops.listWorktrees`. */+export interface WorktreeListResult {+ ok: boolean+ entries: WorktreeEntry[]+}++/** The node fields that can say "this session does not run on this machine". */+interface RemoteNodeLike {+ /** Relay-bound node (`createRemoteTerminalNode`) — not persisted. */+ remote?: unknown+ /** SSH-PROJECT terminal (`createTerminalNode(..., project.ssh)`) — the connection it runs on. */+ ssh?: unknown+ /** SSH-PROJECT terminal: its tmux server lives on the host, not here. */+ sshRemoteTmux?: unknown+}++/**+ * Does this node's session live on a REMOTE host?+ *+ * Worktrees are local-only in v1: the path is computed from the LOCAL data dir and `git worktree`+ * runs against the LOCAL filesystem. A node whose tmux session is on another machine must therefore+ * never be moved into one — its session would be destroyed and respawned into a directory that does+ * not exist there, and the dead path would be persisted to `project.json`.+ *+ * THREE different fields mean "remote", and guarding only one is how the exact node this protects+ * slipped through: `data.remote` is set ONLY by `createRemoteTerminalNode` (relay nodes, never+ * persisted, never inside an SSH project), while an SSH-PROJECT terminal carries `data.ssh` ++ * `data.sshRemoteTmux` and NEVER `data.remote`. Ask about all of them.+ */+export function isRemoteSessionNode(data: RemoteNodeLike | undefined): boolean {+ return !!(data && (data.remote || data.ssh || data.sshRemoteTmux))+}+/*** Reject refs that could smuggle CLI flags (leading `-`) or are not valid git refs.* Electron-free port of git-service.ts's `isValidRef` so worktree-ops can validate too.