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
feat(worktrees): add path templates
Darren Kattan3e31e3dd5d16
diff --git a/CLAUDE.md b/CLAUDE.mdindex 4cb897c5e..1263ddf12 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -1630,6 +1630,13 @@ again; the grace window was never the thing that was wrong.worktrees listed for adoption. (Both git IPCs existed before this feature and had **zero**renderer callers, which is why it was unusable: the dialog's repo field was always empty and hadto be typed by hand. Don't re-strand them.)+ - **Default location** — `settings.worktreePathTemplate` is a machine-global Behavior setting,+ expanded only by `shared/worktree.computeWorktreePath` for both the dialog and canvas-control+ CLI. It is relative to the repo root and supports `$repoName` (`$reponame` /+ `$defaultFolderName` aliases) and `$branch` in bare or `${…}` form. If branch is omitted, its+ safe slug is appended automatically. The shipped `../${repoName}.worktrees/${branch}` keeps+ worktrees beside — not nested inside — the main checkout. There is no general project-settings+ surface today, so the setting is intentionally global rather than hidden in a one-off menu.- **One store, one poller** — `renderer/state/worktrees.ts` is the **only** caller of the worktree/status *read* IPCs (`git.repoRoot`, `git.worktreeList`, `git.status`); the group chip, thecreation dialog and the Source Control panel all read that store. Three independent pollers woulddiff --git a/src/renderer/bridge/relay-api.ts b/src/renderer/bridge/relay-api.tsindex 03f9716e4..32f45cbeb 100644--- a/src/renderer/bridge/relay-api.ts+++ b/src/renderer/bridge/relay-api.ts@@ -82,7 +82,7 @@ export function buildRelayApi(connectionId: string, transport?: FrameTransport):// ── CORE-BOUND: route to the REMOTE core over the relay RpcClient. ──workspace: real.workspace, // the host's canvas/project files- userDataDir: real.userDataDir, // the host's writable base — worktree default paths live there+ userDataDir: real.userDataDir, // the host's writable basefs: files.fs,git: files.git,files: files.files,diff --git a/src/renderer/canvas/Canvas.tsx b/src/renderer/canvas/Canvas.tsxindex 62384ba1a..dfa85f37c 100644--- a/src/renderer/canvas/Canvas.tsx+++ b/src/renderer/canvas/Canvas.tsx@@ -947,17 +947,6 @@ export function Canvas() {const worktreeOrphans = useWorktrees((s) => s.orphans)// git's order — entries[0] is the repo's main checkout, i.e. the real default branch.const worktreeEntries = useWorktrees((s) => s.entries)- // Writable base dir for the default worktree path (userData on desktop, the server's data dir- // in the browser), fetched once on mount. STATE, not a ref: a dialog opened before the promise- // resolves must re-render with the real base, or it would keep suggesting nothing.- const [userDataDir, setUserDataDir] = useState('')- useEffect(() => {- // The SESSION core's writable base, not this client's: a remote tab's worktree default path- // must live on the machine `git worktree add` runs on (the host — obligation c), so it comes- // from the session api (`api.userDataDir()`), re-resolved when the active session changes.- // For the local session `api` IS window.nodeTerminal, so this stays byte-identical.- void api.userDataDir().then(setUserDataDir)- }, [api])// Worktrees already bound to a group on THIS canvas. The store's orphan list is refreshed after// every mutation, but it is also filled asynchronously — filtering against the live nodes is the// guard that stops the dialog from offering a worktree a second group could bind to.@@ -7169,13 +7158,13 @@ export function Canvas() {bindGroupId = g.id}const baseRef = args.base?.trim() || resolveBaseRef(entries)- // Path from the SESSION core's userData (the HOST for a remote tab), not the local- // client's — the git worktree op below runs on `api.git`, so the path must live there.+ // Resolve from this session's repo root, so a relay tab still produces a path on the+ // same host/filesystem where the `api.git` operation below runs.const wtPath = await resolveWorktreePath({explicitPath: args.path,- userDataDir: api.userDataDir,repoRoot,- branch+ branch,+ template: useSettings.getState().settings.worktreePathTemplate})if (!wtPath) {reply({ ok: false, error: 'open-worktree: could not derive a worktree path — pass --path' })@@ -9463,9 +9452,9 @@ export function Canvas() {branches={worktreeBranches}defaultPath={(repoPath, branch) =>computeWorktreePath(- userDataDir,- repoPath.split('/').pop() || 'repo',- sanitizeWorktreeBranch(branch)+ repoPath,+ branch,+ settings.worktreePathTemplate)}busy={worktreeBusy}diff --git a/src/renderer/components/settings/sections/BehaviorSection.tsx b/src/renderer/components/settings/sections/BehaviorSection.tsxindex 64387cb72..0dc88f3eb 100644--- a/src/renderer/components/settings/sections/BehaviorSection.tsx+++ b/src/renderer/components/settings/sections/BehaviorSection.tsx@@ -6,7 +6,9 @@ import { Switch } from '@renderer/ui/Switch'import { NumberField } from '@renderer/ui/NumberField'import { Select } from '@renderer/ui/Select'import { SegmentedPill } from '@renderer/ui/SegmentedPill'+import { Input } from '@renderer/ui/Input'import { hintLabel } from '@shared/platform-utils'+import { DEFAULT_WORKTREE_PATH_TEMPLATE } from '@shared/worktree'const ROWS = {defaultView: {@@ -33,6 +35,10 @@ const ROWS = {title: 'Sidebar: group by',keywords: ['sidebar', 'sessions', 'group', 'status', 'project', 'attention']},+ worktreePath: {+ title: 'Worktree path template',+ keywords: ['worktree', 'git', 'path', 'folder', 'repo', 'branch', 'template']+ },wheelZoom: { title: 'Scroll wheel zooms', keywords: ['zoom', 'wheel', 'scroll', 'mouse', 'pan'] },trackpadPan: {title: 'Trackpad scroll pans',@@ -189,6 +195,23 @@ export function BehaviorSection({ isActive }: { isActive: boolean }): React.JSX.}/></SearchableRow>+ <SearchableRow {...ROWS.worktreePath}>+ <FieldRow+ label="Worktree path template"+ description={+ 'Resolved from the repository root. Supports $repoName (also $reponame or $defaultFolderName) and $branch; a missing branch is appended automatically.'+ }+ control={+ <Input+ className="w-80 font-mono"+ aria-label="Worktree path template"+ placeholder={DEFAULT_WORKTREE_PATH_TEMPLATE}+ value={settings.worktreePathTemplate}+ onChange={(e) => update({ worktreePathTemplate: e.target.value })}+ />+ }+ />+ </SearchableRow><SearchableRow {...ROWS.wheelZoom}><FieldRowlabel="Scroll wheel zooms"diff --git a/src/shared/default-settings.test.ts b/src/shared/default-settings.test.tsindex 2399b95a0..2d8f97b8e 100644--- a/src/shared/default-settings.test.ts+++ b/src/shared/default-settings.test.ts@@ -1,5 +1,6 @@import { describe, expect, it } from 'vitest'import { DEFAULT_SETTINGS } from './types'+import { DEFAULT_WORKTREE_PATH_TEMPLATE } from './worktree'describe('DEFAULT_SETTINGS', () => {it('enables git auto-fetch by default', () => {@@ -19,4 +20,8 @@ describe('DEFAULT_SETTINGS', () => {// { ...DEFAULT_SETTINGS, ...saved } hydration. Do not change without a decision.expect(DEFAULT_SETTINGS.claudePermissionMode).toBe('auto')})++ it('uses the shared worktree path template default', () => {+ expect(DEFAULT_SETTINGS.worktreePathTemplate).toBe(DEFAULT_WORKTREE_PATH_TEMPLATE)+ })})diff --git a/src/shared/types.ts b/src/shared/types.tsindex 033fcf8d4..fb43bd251 100644--- a/src/shared/types.ts+++ b/src/shared/types.ts@@ -1,5 +1,6 @@// Types shared across the main, preload, and renderer processes.+import { DEFAULT_WORKTREE_PATH_TEMPLATE } from './worktree'import type { CloneProgress } from './clone-url'import type { NormalizedAgentEvent } from './agents/normalize'import type { AgentId, AgentPermissionMode, BuiltinAgentId, PromptInjectionMode } from './agents/config'@@ -923,6 +924,10 @@ export interface Settings {/** Fallback view for projects the user hasn't explicitly toggled (canvas or the kanban board).* Personal machine-local preference; per-project explicit choices override it. */defaultProjectView: 'canvas' | 'kanban'+ /** New-worktree path template, resolved relative to the repository root. Supports `$repoName`+ * (`$reponame` and `$defaultFolderName` aliases) plus `$branch`; both `$x` and `${x}` forms.+ * A missing branch token is appended automatically. */+ worktreePathTemplate: string/** ms to dwell over a terminal before it takes pointer focus (pan-across guard). */panHoverDelay: numberdoubleClickFocus: boolean@@ -1148,6 +1153,7 @@ export const DEFAULT_SETTINGS: Settings = {sidebarCollapsedItems: {},sidebarGrouping: 'project',defaultProjectView: 'canvas',+ worktreePathTemplate: DEFAULT_WORKTREE_PATH_TEMPLATE,panHoverDelay: 600,doubleClickFocus: true,terminalMiddleClickPaste: false,diff --git a/src/shared/worktree.test.ts b/src/shared/worktree.test.tsindex 48427e234..aac0e425a 100644--- a/src/shared/worktree.test.ts+++ b/src/shared/worktree.test.ts@@ -75,44 +75,57 @@ describe('sanitizeWorktreeBranch', () => {})describe('computeWorktreePath', () => {- it('builds <userData>/worktrees/<repo>/<branch> with a flattened branch', () => {- expect(computeWorktreePath('/u', 'myrepo', 'feature/x')).toBe('/u/worktrees/myrepo/feature-x')+ it('defaults beside the repository and flattens the branch', () => {+ expect(computeWorktreePath('/src/myrepo', 'feature/x')).toBe(+ '/src/myrepo.worktrees/feature-x'+ )})- it('suggests NOTHING when the base dir is unknown (never a filesystem-root path)', () => {- // An empty base used to produce `/worktrees/<repo>/<branch>` — i.e. the filesystem root,- // which the Server Edition (running as root) would happily create.- expect(computeWorktreePath('', 'myrepo', 'x')).toBe('')- expect(computeWorktreePath(' ', 'myrepo', 'x')).toBe('')+ it('supports the requested aliases and appends a branch when the template omits it', () => {+ expect(computeWorktreePath('/src/MyRepo', 'Feature/X', '../$reponame.worktrees')).toBe(+ '/src/MyRepo.worktrees/feature-x'+ )+ expect(computeWorktreePath('/src/MyRepo', 'Feature/X', '../$defaultFolderName.worktrees')).toBe(+ '/src/MyRepo.worktrees/feature-x'+ )+ expect(computeWorktreePath('/src/MyRepo', 'Feature/X', './worktrees')).toBe(+ '/src/MyRepo/worktrees/feature-x'+ )})- it('drops a trailing slash on the base dir', () => {- expect(computeWorktreePath('/u/', 'r', 'b')).toBe('/u/worktrees/r/b')+ it('supports explicit branch tokens, absolute templates, and Windows-style input', () => {+ expect(computeWorktreePath('/src/repo/', 'topic/a', '/tmp/wt/$branch')).toBe(+ '/tmp/wt/topic-a'+ )+ expect(computeWorktreePath('C:\\src\\repo', 'topic/a', '..\\${repoName}.wt\\${branch}')).toBe(+ 'C:/src/repo.wt/topic-a'+ )+ })+ it('suggests nothing when the repository or branch is unknown', () => {+ expect(computeWorktreePath('', 'x')).toBe('')+ expect(computeWorktreePath(' ', 'x')).toBe('')+ expect(computeWorktreePath('/src/repo', '')).toBe('')})})describe('resolveWorktreePath', () => {- it('derives the default UNDER the session core userData (the host, for a remote tab)', async () => {- // The provider is the SESSION core's `userDataDir()` — a remote tab hands the HOST's base, so- // the worktree lands on the machine `git worktree add` runs on, not this client.+ it('derives the configured default relative to the session repository root', async () => {const p = await resolveWorktreePath({- userDataDir: () => Promise.resolve('/home/host/.config/nodeterm'),repoRoot: '/srv/repos/myapp',- branch: 'feature/x'+ branch: 'feature/x',+ template: './worktrees'})- expect(p).toBe('/home/host/.config/nodeterm/worktrees/myapp/feature-x')+ expect(p).toBe('/srv/repos/myapp/worktrees/feature-x')})- it('honors an explicit --path and never reads the userData provider', async () => {+ it('honors an explicit --path', async () => {const p = await resolveWorktreePath({explicitPath: ' /custom/wt ',- userDataDir: () => Promise.reject(new Error('provider must not be read when --path is given')),repoRoot: '/srv/repos/x',branch: 'b'})expect(p).toBe('/custom/wt')})- it('yields "" when the base dir is unknown and no --path was given', async () => {+ it('yields "" when the repository root is unknown and no --path was given', async () => {const p = await resolveWorktreePath({- userDataDir: () => Promise.resolve(''),- repoRoot: '/srv/repos/x',+ repoRoot: '',branch: 'b'})expect(p).toBe('')diff --git a/src/shared/worktree.ts b/src/shared/worktree.tsindex 22e72404d..c7b0bfeed 100644--- a/src/shared/worktree.ts+++ b/src/shared/worktree.ts@@ -41,10 +41,10 @@ interface RemoteNodeLike {/*** 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`.+ * Worktrees are local-only in v1: `git worktree` runs against the project's 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`.** An SSH-PROJECT terminal carries BOTH `data.ssh` (the connection it runs on) and* `data.sshRemoteTmux` (its tmux server lives on the host), and guarding only one is how the exact@@ -76,37 +76,87 @@ export function sanitizeWorktreeBranch(input: string): string {}/**- * Default on-disk location: <userData>/worktrees/<repo>/<branch-flattened>.- * An unknown base dir yields NO suggestion (empty string) rather than a root-relative- * `/worktrees/...` — the Server Edition often runs as root and `git worktree add` would- * cheerfully create that at the filesystem root. Callers must treat '' as "no default".+ * Global template for new worktrees. It deliberately lives NEXT TO the checkout instead of under+ * app data: the location is predictable from a shell/file picker, while keeping other worktrees+ * outside the main checkout avoids nested-repository tooling surprises.*/-export function computeWorktreePath(userDataDir: string, repoName: string, branch: string): string {- const base = userDataDir.trim().replace(/\/+$/, '')- if (!base) return ''- const flat = branch.replace(/\//g, '-')- return `${base}/worktrees/${repoName}/${flat}`+export const DEFAULT_WORKTREE_PATH_TEMPLATE = '../${repoName}.worktrees/${branch}'++const WORKTREE_TEMPLATE_TOKEN =+ /\$\{(repoName|reponame|defaultFolderName|branch)\}|\$(repoName|reponame|defaultFolderName|branch)\b/g+const WORKTREE_BRANCH_TOKEN = /\$\{branch\}|\$branch\b/++/** Browser-safe lexical path resolution (this shared module is bundled into the renderer). */+function resolvePathFromRepo(repoRoot: string, configuredPath: string): string {+ const root = repoRoot.trim().replace(/\\/g, '/').replace(/\/+$/, '')+ const configured = configuredPath.trim().replace(/\\/g, '/')+ if (!root || !configured) return ''++ const absolute = configured.startsWith('/') || /^[a-zA-Z]:\//.test(configured)+ const combined = absolute ? configured : `${root}/${configured}`+ const drive = combined.match(/^([a-zA-Z]:)\//)?.[1] ?? ''+ const rooted = combined.startsWith('/') || !!drive+ const body = drive ? combined.slice(drive.length + 1) : combined.replace(/^\/+/, '')+ const parts: string[] = []+ for (const part of body.split('/')) {+ if (!part || part === '.') continue+ if (part === '..') {+ if (parts.length) parts.pop()+ else if (!rooted) parts.push(part)+ continue+ }+ parts.push(part)+ }+ const prefix = drive ? `${drive}/` : rooted ? '/' : ''+ return `${prefix}${parts.join('/')}`}/**- * Resolve the on-disk worktree directory for a create: an explicit `--path` wins; otherwise the- * default under the SESSION CORE's writable base (`userDataDir()` — the HOST's userData for a- * remote tab, so the worktree lands on the machine `git worktree add` runs on, not this client).+ * Expand a worktree path template relative to the repository root.*- * `userDataDir` is injected (not read off any global) precisely so the path follows the session- * that runs the git op — the obligation-c fix. Async because the base dir is fetched from the core;- * a given `--path` short-circuits it, so the provider is never touched when the caller already knows- * the location. Returns '' when nothing can be derived (an unknown base and no `--path`).+ * Supported spellings intentionally include both `$name` and `${name}`. `$repoName`, the+ * lower-case `$reponame` spelling, and `$defaultFolderName` all mean the main checkout's folder+ * name; the latter is an explicit human-readable alias for users who think of that checkout as the+ * "default worktree". `$branch` is the filesystem-safe branch slug. When the template omits a+ * branch token, the slug is appended automatically, so concise bases such as `./worktrees` and+ * `../$reponame.worktrees` remain collision-safe.+ */+export function computeWorktreePath(+ repoRoot: string,+ branch: string,+ template = DEFAULT_WORKTREE_PATH_TEMPLATE+): string {+ const root = repoRoot.trim().replace(/[\\/]+$/, '')+ const repoName = root.split(/[\\/]/).pop() || ''+ const flatBranch = sanitizeWorktreeBranch(branch).replace(/\//g, '-')+ if (!root || !repoName || !flatBranch) return ''++ const source = template.trim() || DEFAULT_WORKTREE_PATH_TEMPLATE+ const hasBranchToken = WORKTREE_BRANCH_TOKEN.test(source)+ const expanded = source.replace(WORKTREE_TEMPLATE_TOKEN, (_match, braced, plain) => {+ const token = braced || plain+ return token === 'branch' ? flatBranch : repoName+ })+ const withBranch = hasBranchToken ? expanded : `${expanded.replace(/\/+$/, '')}/${flatBranch}`+ return resolvePathFromRepo(root, withBranch)+}++/**+ * Resolve the on-disk worktree directory for a create: an explicit `--path` wins; otherwise the+ * configured template relative to that session's repository root. A remote/relay tab therefore+ * still resolves on the host filesystem: its `repoRoot` comes from the same session core that runs+ * the git operation. Kept async for its existing callers/API even though template expansion itself+ * is synchronous.*/export async function resolveWorktreePath(args: {explicitPath?: string- userDataDir: () => Promise<string>repoRoot: stringbranch: string+ template?: string}): Promise<string> {const explicit = args.explicitPath?.trim()if (explicit) return explicit- return computeWorktreePath(await args.userDataDir(), args.repoRoot.split('/').pop() || 'repo', args.branch)+ return computeWorktreePath(args.repoRoot, args.branch, args.template)}/** Values the worktree dialog collects. Mapped to a `GroupWorktree` by `worktreeFromCreate`. */