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(worktree): pure helpers for path, porcelain, safety, merge strategy
enese0aae1c91a7b
diff --git a/src/shared/worktree.test.ts b/src/shared/worktree.test.tsnew file mode 100644index 000000000..8ff7e7942--- /dev/null+++ b/src/shared/worktree.test.ts@@ -0,0 +1,83 @@+import { describe, it, expect } from 'vitest'+import {+ sanitizeWorktreeBranch,+ computeWorktreePath,+ parseWorktreePorcelain,+ isDangerousWorktreeRemovalPath,+ decideMergeStrategy,+ isValidGitRef+} from './worktree'++describe('isValidGitRef', () => {+ it('accepts a normal branch name', () => {+ expect(isValidGitRef('feature/x')).toBe(true)+ })+ it('rejects flag-injection and whitespace', () => {+ expect(isValidGitRef('--force')).toBe(false)+ expect(isValidGitRef('a b')).toBe(false)+ expect(isValidGitRef('')).toBe(false)+ })+})++describe('sanitizeWorktreeBranch', () => {+ it('replaces spaces and illegal chars with dashes', () => {+ expect(sanitizeWorktreeBranch('My Feature!')).toBe('my-feature')+ })+ it('strips leading dashes (flag-injection guard)', () => {+ expect(sanitizeWorktreeBranch('--force')).toBe('force')+ })+})++describe('computeWorktreePath', () => {+ it('builds <userData>/worktrees/<repo>/<branch> with a flattened branch', () => {+ expect(computeWorktreePath('/u', 'myrepo', 'feature/x')).toBe('/u/worktrees/myrepo/feature-x')+ })+})++describe('parseWorktreePorcelain', () => {+ it('parses git worktree list --porcelain blocks', () => {+ const out = [+ 'worktree /repo', 'HEAD abc123', 'branch refs/heads/main', '',+ 'worktree /wt/x', 'HEAD def456', 'branch refs/heads/feature/x', '',+ 'worktree /bare', 'bare', ''+ ].join('\n')+ const entries = parseWorktreePorcelain(out)+ expect(entries).toEqual([+ { path: '/repo', head: 'abc123', branch: 'main', isBare: false },+ { path: '/wt/x', head: 'def456', branch: 'feature/x', isBare: false },+ { path: '/bare', head: null, branch: null, isBare: true }+ ])+ })+})++describe('isDangerousWorktreeRemovalPath', () => {+ const home = '/Users/me'+ it('refuses the repo root itself', () => {+ expect(isDangerousWorktreeRemovalPath('/repo', '/repo', home)).toBe(true)+ })+ it('refuses a path that contains the repo', () => {+ expect(isDangerousWorktreeRemovalPath('/repo', '/repo/sub', home)).toBe(true)+ })+ it('refuses home and filesystem root', () => {+ expect(isDangerousWorktreeRemovalPath(home, '/repo', home)).toBe(true)+ expect(isDangerousWorktreeRemovalPath('/', '/repo', home)).toBe(true)+ })+ it('allows a normal sibling worktree dir', () => {+ expect(isDangerousWorktreeRemovalPath('/Users/me/worktrees/r/feature-x', '/repo', home)).toBe(false)+ })+})++describe('decideMergeStrategy', () => {+ it('fetch-updates when base is not checked out anywhere', () => {+ expect(decideMergeStrategy({ baseCheckedOutPath: null, baseDirty: false }))+ .toEqual({ kind: 'fetch-update' })+ })+ it('merges in place when base checkout is clean', () => {+ expect(decideMergeStrategy({ baseCheckedOutPath: '/repo', baseDirty: false }))+ .toEqual({ kind: 'merge-in-place', path: '/repo' })+ })+ it('blocks when base checkout is dirty', () => {+ const r = decideMergeStrategy({ baseCheckedOutPath: '/repo', baseDirty: true })+ expect(r.kind).toBe('blocked')+ })+})diff --git a/src/shared/worktree.ts b/src/shared/worktree.tsindex 1e3077677..1d856d5cc 100644--- a/src/shared/worktree.ts+++ b/src/shared/worktree.ts@@ -10,3 +10,88 @@ export interface GroupWorktree {/** Whether this app created the worktree (gates safe directory deletion). */createdByApp: boolean}++export interface WorktreeEntry {+ path: string+ branch: string | null+ head: string | null+ isBare: boolean+}++/**+ * 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.+ */+export function isValidGitRef(name: string): boolean {+ const n = name.trim()+ if (!n || n.startsWith('-')) return false+ return !/[\s~^:?*[\\]|\.\.|^\/|\/$|@\{/.test(n)+}++/** Flatten a branch name into a filesystem-safe, flag-safe slug. */+export function sanitizeWorktreeBranch(input: string): string {+ return input+ .trim()+ .toLowerCase()+ .replace(/[^a-z0-9/_-]+/g, '-') // illegal chars -> dash+ .replace(/^[-/]+/, '') // no leading dash (flag injection) or slash+ .replace(/-+/g, '-')+ .replace(/(^-|-$)/g, '')+}++/** Default on-disk location: <userData>/worktrees/<repo>/<branch-flattened>. */+export function computeWorktreePath(userDataDir: string, repoName: string, branch: string): string {+ const flat = branch.replace(/\//g, '-')+ return `${userDataDir}/worktrees/${repoName}/${flat}`+}++/** Parse `git worktree list --porcelain` into structured entries. */+export function parseWorktreePorcelain(out: string): WorktreeEntry[] {+ const entries: WorktreeEntry[] = []+ let cur: Partial<WorktreeEntry> | null = null+ for (const raw of out.split('\n')) {+ const line = raw.trimEnd()+ if (line.startsWith('worktree ')) {+ if (cur) entries.push({ path: cur.path!, branch: cur.branch ?? null, head: cur.head ?? null, isBare: cur.isBare ?? false })+ cur = { path: line.slice('worktree '.length), isBare: false }+ } else if (!cur) {+ continue+ } else if (line.startsWith('HEAD ')) {+ cur.head = line.slice('HEAD '.length)+ } else if (line.startsWith('branch ')) {+ cur.branch = line.slice('branch '.length).replace(/^refs\/heads\//, '')+ } else if (line === 'bare') {+ cur.isBare = true+ }+ }+ if (cur) entries.push({ path: cur.path!, branch: cur.branch ?? null, head: cur.head ?? null, isBare: cur.isBare ?? false })+ return entries+}++const isAncestorPath = (parent: string, child: string): boolean => {+ const p = parent.replace(/\/+$/, '')+ const c = child.replace(/\/+$/, '')+ return c === p || c.startsWith(p + '/')+}++/** Refuse removals that would nuke the repo, home, or filesystem root. */+export function isDangerousWorktreeRemovalPath(worktreePath: string, repoPath: string, homeDir: string): boolean {+ const wt = (worktreePath || '').replace(/\/+$/, '')+ if (!wt) return true+ if (wt === '/' || wt === repoPath.replace(/\/+$/, '') || wt === homeDir.replace(/\/+$/, '')) return true+ // worktree is an ancestor of the repo or of home → dangerous.+ if (isAncestorPath(wt, repoPath) || isAncestorPath(wt, homeDir)) return true+ return false+}++/** Choose how to land a branch onto its base without corrupting a live checkout. */+export function decideMergeStrategy(args: { baseCheckedOutPath: string | null; baseDirty: boolean }):+ | { kind: 'fetch-update' }+ | { kind: 'merge-in-place'; path: string }+ | { kind: 'blocked'; reason: string } {+ if (args.baseCheckedOutPath === null) return { kind: 'fetch-update' }+ if (args.baseDirty) {+ return { kind: 'blocked', reason: 'The base branch checkout has uncommitted changes. Commit or stash them first.' }+ }+ return { kind: 'merge-in-place', path: args.baseCheckedOutPath }+}