From 82023dbe1b1a76af4b6b4a03ee8d40bcfa194d0a Mon Sep 17 00:00:00 2001 From: Federico Pedraza <77793780+federicoPedraza@users.noreply.github.com> Date: Mon, 4 May 2026 18:19:20 -0300 Subject: [PATCH] feat(worktrees): add experimental symlinks for shared paths on worktree creation (#1029) Co-authored-by: Orca Co-authored-by: federico-ntb Co-authored-by: Jinwoo-H --- .../runtime-home-service.test.ts | 1 + src/main/codex-accounts/service.test.ts | 1 + src/main/ipc/repos.ts | 13 + src/main/ipc/worktree-remote.ts | 16 ++ src/main/ipc/worktree-symlinks.test.ts | 227 ++++++++++++++++++ src/main/ipc/worktree-symlinks.ts | 108 +++++++++ src/main/ipc/worktrees.ts | 15 ++ .../components/settings/ExperimentalPane.tsx | 41 ++++ .../components/settings/RepositoryPane.tsx | 23 ++ .../settings/WorktreeSymlinksSection.tsx | 201 ++++++++++++++++ .../settings/experimental-search.ts | 17 ++ src/renderer/src/store/slices/repos.ts | 1 + src/shared/constants.ts | 3 +- src/shared/types.ts | 12 + 14 files changed, 678 insertions(+), 1 deletion(-) create mode 100644 src/main/ipc/worktree-symlinks.test.ts create mode 100644 src/main/ipc/worktree-symlinks.ts create mode 100644 src/renderer/src/components/settings/WorktreeSymlinksSection.tsx diff --git a/src/main/codex-accounts/runtime-home-service.test.ts b/src/main/codex-accounts/runtime-home-service.test.ts index 65d304f71..8399055b7 100644 --- a/src/main/codex-accounts/runtime-home-service.test.ts +++ b/src/main/codex-accounts/runtime-home-service.test.ts @@ -96,6 +96,7 @@ function createSettings(overrides: Partial = {}): GlobalSettings experimentalAgentDashboard: false, experimentalMobile: false, experimentalSidekick: false, + experimentalWorktreeSymlinks: false, terminalWindowsShell: 'powershell.exe', terminalWindowsPowerShellImplementation: 'powershell.exe', enableGitHubAttribution: true, diff --git a/src/main/codex-accounts/service.test.ts b/src/main/codex-accounts/service.test.ts index cff5f956d..51de5333e 100644 --- a/src/main/codex-accounts/service.test.ts +++ b/src/main/codex-accounts/service.test.ts @@ -90,6 +90,7 @@ function createSettings(overrides: Partial = {}): GlobalSettings experimentalAgentDashboard: false, experimentalMobile: false, experimentalSidekick: false, + experimentalWorktreeSymlinks: false, terminalWindowsShell: 'powershell.exe', terminalWindowsPowerShellImplementation: 'powershell.exe', enableGitHubAttribution: true, diff --git a/src/main/ipc/repos.ts b/src/main/ipc/repos.ts index 252ee4748..bf18216a8 100644 --- a/src/main/ipc/repos.ts +++ b/src/main/ipc/repos.ts @@ -406,6 +406,7 @@ export function registerRepoHandlers(mainWindow: BrowserWindow, store: Store): v | 'hookSettings' | 'worktreeBaseRef' | 'kind' + | 'symlinkPaths' | 'issueSourcePreference' > > @@ -427,6 +428,18 @@ export function registerRepoHandlers(mainWindow: BrowserWindow, store: Store): v ) { delete updates.issueSourcePreference } + // Why: `symlinkPaths` is consumed by `createWorktreeSymlinks` which + // calls `.trim()` on each entry. A renderer bug or preload-version skew + // that persists a non-`string[]` value (e.g. `[42, null]`, a bare + // string) would throw inside the worktree-create path with no UI + // signal. Strip invalid shapes at the boundary the same way + // `issueSourcePreference` is validated above. + if ('symlinkPaths' in updates && updates.symlinkPaths !== undefined) { + const v = updates.symlinkPaths as unknown + if (!Array.isArray(v) || !v.every((e) => typeof e === 'string')) { + delete updates.symlinkPaths + } + } const updated = store.updateRepo(args.repoId, updates) if (updated) { notifyReposChanged(mainWindow) diff --git a/src/main/ipc/worktree-remote.ts b/src/main/ipc/worktree-remote.ts index 49385ef2f..cb37a482a 100644 --- a/src/main/ipc/worktree-remote.ts +++ b/src/main/ipc/worktree-remote.ts @@ -37,6 +37,7 @@ import { areWorktreePathsEqual } from './worktree-logic' import { invalidateAuthorizedRootsCache } from './filesystem-auth' +import { createWorktreeSymlinks } from './worktree-symlinks' import { normalizeSparseDirectories } from './sparse-checkout-directories' export function notifyWorktreesChanged(mainWindow: BrowserWindow, repoId: string): void { @@ -212,6 +213,12 @@ export async function createRemoteWorktree( const meta = store.setWorktreeMeta(worktreeId, metaUpdates) const worktree = mergeWorktree(repo.id, created, meta) + // Why: `experimentalWorktreeSymlinks` is intentionally not wired up for + // remote (SSH) worktrees. Creating symlinks on the remote host would + // require a new relay method and authorization surface; the feature is + // local-only until that protocol work is in scope. Remote repos with + // `symlinkPaths` configured have them silently ignored here. + notifyWorktreesChanged(mainWindow, repo.id) return { worktree } } @@ -452,6 +459,15 @@ export async function createLocalWorktree( // adds 100ms+ to every create. invalidateAuthorizedRootsCache() + // Why: create user-configured symlinks from the primary checkout into the + // new worktree before any setup script runs, so scripts that reuse shared + // state (e.g. `node_modules`, `.env`) see the links already in place. + // Gated on the experimental flag so disabling the feature globally skips + // the work even when a repo still has paths configured. + if (settings.experimentalWorktreeSymlinks && repo.symlinkPaths && repo.symlinkPaths.length > 0) { + await createWorktreeSymlinks(repo.path, created.path, repo.symlinkPaths) + } + // Why: the worktree's own `orca.yaml` (at the tip of the base branch) is // authoritative for what runs post-creation. The repo-level trust already // granted by the user in the pre-create flow covers execution of that diff --git a/src/main/ipc/worktree-symlinks.test.ts b/src/main/ipc/worktree-symlinks.test.ts new file mode 100644 index 000000000..155655c15 --- /dev/null +++ b/src/main/ipc/worktree-symlinks.test.ts @@ -0,0 +1,227 @@ +import { + mkdtempSync, + mkdirSync, + writeFileSync, + statSync, + lstatSync, + readlinkSync, + rmSync, + symlinkSync, + existsSync +} from 'fs' +import { tmpdir } from 'os' +import { join } from 'path' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { createWorktreeSymlinks, removeWorktreeSymlinks } from './worktree-symlinks' + +describe('createWorktreeSymlinks', () => { + let root: string + let primary: string + let worktree: string + let warn: ReturnType + let error: ReturnType + + beforeEach(() => { + root = mkdtempSync(join(tmpdir(), 'orca-symlinks-')) + primary = join(root, 'primary') + worktree = join(root, 'worktree') + mkdirSync(primary, { recursive: true }) + mkdirSync(worktree, { recursive: true }) + warn = vi.spyOn(console, 'warn').mockImplementation(() => {}) + error = vi.spyOn(console, 'error').mockImplementation(() => {}) + }) + + afterEach(() => { + warn.mockRestore() + error.mockRestore() + rmSync(root, { recursive: true, force: true }) + }) + + it('symlinks a file from primary into the worktree at the same relative path', async () => { + writeFileSync(join(primary, '.env'), 'SECRET=1\n') + await createWorktreeSymlinks(primary, worktree, ['.env']) + + const linkStat = lstatSync(join(worktree, '.env')) + expect(linkStat.isSymbolicLink()).toBe(true) + expect(readlinkSync(join(worktree, '.env'))).toBe(join(primary, '.env')) + // Following the link yields the primary's contents. + expect(statSync(join(worktree, '.env')).isFile()).toBe(true) + }) + + it('symlinks a directory from primary into the worktree', async () => { + mkdirSync(join(primary, 'node_modules')) + writeFileSync(join(primary, 'node_modules', 'marker'), 'installed') + await createWorktreeSymlinks(primary, worktree, ['node_modules']) + + expect(lstatSync(join(worktree, 'node_modules')).isSymbolicLink()).toBe(true) + expect(statSync(join(worktree, 'node_modules', 'marker')).isFile()).toBe(true) + }) + + it('creates parent directories lazily for nested paths', async () => { + mkdirSync(join(primary, 'apps', 'web'), { recursive: true }) + writeFileSync(join(primary, 'apps', 'web', '.env'), 'X=1\n') + await createWorktreeSymlinks(primary, worktree, ['apps/web/.env']) + + expect(lstatSync(join(worktree, 'apps', 'web', '.env')).isSymbolicLink()).toBe(true) + }) + + it('skips entries whose source is missing in the primary checkout', async () => { + await createWorktreeSymlinks(primary, worktree, ['node_modules']) + // No link created, no throw. + expect(() => lstatSync(join(worktree, 'node_modules'))).toThrow() + expect(error).not.toHaveBeenCalled() + }) + + it('preserves a pre-existing target in the worktree (no clobber)', async () => { + writeFileSync(join(primary, '.env'), 'FROM_PRIMARY=1\n') + writeFileSync(join(worktree, '.env'), 'FROM_WORKTREE=1\n') + + await createWorktreeSymlinks(primary, worktree, ['.env']) + + // The pre-existing regular file stays; no symlink was created. + expect(lstatSync(join(worktree, '.env')).isSymbolicLink()).toBe(false) + expect(statSync(join(worktree, '.env')).isFile()).toBe(true) + }) + + it('does not escape the primary checkout via a leading-slash path', async () => { + // Why: the helper strips leading slashes (so `/etc/passwd` becomes the + // relative `etc/passwd`). No file is created outside the worktree, and the + // resolved source — which falls inside `primary/etc/passwd` — is missing, + // so the entry is silently skipped rather than linking to `/etc/passwd`. + await createWorktreeSymlinks(primary, worktree, ['/etc/passwd']) + + expect(() => lstatSync(join(worktree, 'etc', 'passwd'))).toThrow() + expect(error).not.toHaveBeenCalled() + }) + + it('rejects parent-directory traversal', async () => { + await createWorktreeSymlinks(primary, worktree, ['../secrets']) + + expect(warn).toHaveBeenCalledWith( + expect.stringContaining('[worktree-symlinks] Skipping unsafe path "../secrets"') + ) + }) + + it('rejects nested traversal via ..', async () => { + await createWorktreeSymlinks(primary, worktree, ['safe/../../escape']) + + expect(warn).toHaveBeenCalledWith( + expect.stringContaining('[worktree-symlinks] Skipping unsafe path "safe/../../escape"') + ) + }) + + it('rejects traversal using backslash separators (Windows form)', async () => { + // Why: users configuring paths on Windows (or pasting a mixed-separator + // value) could bypass a POSIX-only split. The guard normalizes across + // `/` and `\` so `..\escape` and `foo\..\..\escape` both get rejected. + await createWorktreeSymlinks(primary, worktree, ['..\\escape']) + await createWorktreeSymlinks(primary, worktree, ['foo\\..\\..\\escape']) + + expect(warn).toHaveBeenCalledWith( + expect.stringContaining('[worktree-symlinks] Skipping unsafe path "..\\escape"') + ) + expect(warn).toHaveBeenCalledWith( + expect.stringContaining('[worktree-symlinks] Skipping unsafe path "foo\\..\\..\\escape"') + ) + }) + + it('strips a leading slash then treats the remainder as a relative path', async () => { + writeFileSync(join(primary, '.env'), 'X=1\n') + await createWorktreeSymlinks(primary, worktree, ['/.env']) + + // Leading slash is stripped in the helper; the remaining `.env` is a valid relative path. + expect(lstatSync(join(worktree, '.env')).isSymbolicLink()).toBe(true) + expect(warn).not.toHaveBeenCalled() + }) + + it('skips empty and whitespace-only entries', async () => { + // The helper logs an "unsafe path" warn for these; nothing gets linked. + await createWorktreeSymlinks(primary, worktree, ['', ' ']) + expect(error).not.toHaveBeenCalled() + }) + + it('continues processing later entries after one fails', async () => { + writeFileSync(join(primary, '.env'), 'X=1\n') + writeFileSync(join(primary, 'config.json'), '{}') + + await createWorktreeSymlinks(primary, worktree, [ + '../escape', // rejected + 'missing-source', // no source, skipped + '.env', // succeeds + 'config.json' // succeeds + ]) + + expect(lstatSync(join(worktree, '.env')).isSymbolicLink()).toBe(true) + expect(lstatSync(join(worktree, 'config.json')).isSymbolicLink()).toBe(true) + }) + + it('is a no-op for an empty paths list', async () => { + await createWorktreeSymlinks(primary, worktree, []) + expect(warn).not.toHaveBeenCalled() + expect(error).not.toHaveBeenCalled() + }) +}) + +describe('removeWorktreeSymlinks', () => { + let root: string + let primary: string + let worktree: string + let error: ReturnType + + beforeEach(() => { + root = mkdtempSync(join(tmpdir(), 'orca-unlink-')) + primary = join(root, 'primary') + worktree = join(root, 'worktree') + mkdirSync(primary, { recursive: true }) + mkdirSync(worktree, { recursive: true }) + error = vi.spyOn(console, 'error').mockImplementation(() => {}) + }) + + afterEach(() => { + error.mockRestore() + rmSync(root, { recursive: true, force: true }) + }) + + it('unlinks configured symlinks from the worktree', async () => { + writeFileSync(join(primary, '.env'), 'SECRET=1\n') + mkdirSync(join(primary, 'node_modules')) + symlinkSync(join(primary, '.env'), join(worktree, '.env'), 'file') + symlinkSync(join(primary, 'node_modules'), join(worktree, 'node_modules'), 'dir') + + await removeWorktreeSymlinks(worktree, ['.env', 'node_modules']) + + expect(existsSync(join(worktree, '.env'))).toBe(false) + expect(existsSync(join(worktree, 'node_modules'))).toBe(false) + // Source is untouched. + expect(statSync(join(primary, '.env')).isFile()).toBe(true) + expect(statSync(join(primary, 'node_modules')).isDirectory()).toBe(true) + }) + + it('leaves a regular file at the configured path alone', async () => { + // Why: a user who created a real file at `.env` (instead of symlinking) + // must not lose it just because `.env` is in the configured list. + writeFileSync(join(worktree, '.env'), 'USER_WROTE_THIS=1\n') + + await removeWorktreeSymlinks(worktree, ['.env']) + + expect(lstatSync(join(worktree, '.env')).isSymbolicLink()).toBe(false) + expect(statSync(join(worktree, '.env')).isFile()).toBe(true) + }) + + it('ignores missing entries', async () => { + await removeWorktreeSymlinks(worktree, ['.env', 'node_modules']) + expect(error).not.toHaveBeenCalled() + }) + + it('rejects unsafe paths without touching the filesystem', async () => { + // Parent-dir traversal is silently skipped; no unlink attempted. + writeFileSync(join(root, 'outside-file'), 'DO_NOT_DELETE') + await removeWorktreeSymlinks(worktree, ['../outside-file']) + expect(existsSync(join(root, 'outside-file'))).toBe(true) + }) + + it('is a no-op for an empty paths list', async () => { + await removeWorktreeSymlinks(worktree, []) + expect(error).not.toHaveBeenCalled() + }) +}) diff --git a/src/main/ipc/worktree-symlinks.ts b/src/main/ipc/worktree-symlinks.ts new file mode 100644 index 000000000..67f4bc2c2 --- /dev/null +++ b/src/main/ipc/worktree-symlinks.ts @@ -0,0 +1,108 @@ +import { symlink, mkdir, stat, lstat, unlink } from 'fs/promises' +import { dirname, isAbsolute, resolve } from 'path' + +/** Create filesystem symlinks from the primary checkout into a freshly-created + * worktree for each configured path. Failures on individual paths are logged + * and skipped so a missing/stale entry never blocks worktree creation. + * + * Each entry is interpreted relative to `primaryPath` and placed at the same + * relative location inside `worktreePath`. Nested paths (e.g. + * `apps/web/.env`) are supported — parent directories are created lazily. */ +export async function createWorktreeSymlinks( + primaryPath: string, + worktreePath: string, + paths: readonly string[] +): Promise { + for (const rawPath of paths) { + // Why: strip leading separators (both `/` and `\`) before the guard so + // Windows-style input like `\foo` is normalized the same way POSIX `/foo` + // is, and the traversal check below sees the already-relative form. + const rel = rawPath.trim().replace(/^[\\/]+/, '') + // Why: split on both separators so a Windows-authored `..\escape` is + // rejected the same way POSIX `../escape` is. `path.isAbsolute` catches + // drive-letter absolutes (`C:\...`); the split catches relative + // backslash traversal that `.split('/')` would otherwise miss. + if (!rel || isAbsolute(rel) || rel.split(/[\\/]/).includes('..')) { + // Users can only configure paths relative to the repo root; absolute + // paths and `..` traversal are not supported. + console.warn(`[worktree-symlinks] Skipping unsafe path "${rawPath}"`) + continue + } + + const source = resolve(primaryPath, rel) + const target = resolve(worktreePath, rel) + + let sourceIsDirectory = false + try { + const s = await stat(source) + sourceIsDirectory = s.isDirectory() + } catch { + // Source doesn't exist in primary checkout — nothing to link to. This is + // a common case for fresh clones where `node_modules` hasn't been + // installed yet; silently skip rather than leaving a dangling symlink. + continue + } + + try { + // Why: if a file/dir already exists at the target location (e.g. + // git-tracked sibling with the same name), leave it alone rather than + // clobber something the user didn't mean to replace. + await stat(target) + continue + } catch { + // Target does not exist — proceed with symlink creation. + } + + try { + await mkdir(dirname(target), { recursive: true }) + // Why: Windows requires an explicit `type` ('dir' vs 'file' vs + // 'junction') for `fs.symlink`. On POSIX the argument is ignored, so + // passing it unconditionally is safe and removes a Windows-only + // failure mode when Node can't auto-detect from the source. + await symlink(source, target, sourceIsDirectory ? 'dir' : 'file') + } catch (error) { + console.error( + `[worktree-symlinks] Failed to symlink "${rel}" (${source} -> ${target}):`, + error + ) + } + } +} + +/** Remove previously-created symlinks from a worktree before deletion. + * + * Why: `git worktree remove` refuses to delete a worktree that has modified + * or untracked files. A symlink pointing at the primary's `node_modules` + * looks "untracked" to git, so users would hit "It has changed files. Use + * Force Delete" on every deletion once they've configured this feature. + * Unlink the known symlinks up front so the non-force path keeps working. + * + * Safety: only removes entries that are actually symbolic links. A regular + * file or directory at the same path is left alone — we never want to clobber + * something the user created that happens to share a name with a configured + * entry. Missing entries (ENOENT) are silently ignored. */ +export async function removeWorktreeSymlinks( + worktreePath: string, + paths: readonly string[] +): Promise { + for (const rawPath of paths) { + const rel = rawPath.trim().replace(/^[\\/]+/, '') + if (!rel || isAbsolute(rel) || rel.split(/[\\/]/).includes('..')) { + continue + } + const target = resolve(worktreePath, rel) + try { + const s = await lstat(target) + if (!s.isSymbolicLink()) { + continue + } + } catch { + continue + } + try { + await unlink(target) + } catch (error) { + console.error(`[worktree-symlinks] Failed to unlink "${rel}" (${target}):`, error) + } + } +} diff --git a/src/main/ipc/worktrees.ts b/src/main/ipc/worktrees.ts index 1cf22e79e..e16dd8252 100644 --- a/src/main/ipc/worktrees.ts +++ b/src/main/ipc/worktrees.ts @@ -37,6 +37,7 @@ import { rebuildAuthorizedRootsCache, ensureAuthorizedRootsCache } from './files import type { OrcaRuntimeService } from '../runtime/orca-runtime' import { killAllProcessesForWorktree } from '../runtime/worktree-teardown' import { getLocalPtyProvider } from './pty' +import { removeWorktreeSymlinks } from './worktree-symlinks' export function registerWorktreeHandlers( mainWindow: BrowserWindow, @@ -312,6 +313,20 @@ export function registerWorktreeHandlers( } } + // Why: `git worktree remove` (non-force) refuses to delete a worktree + // that has untracked files, and a symlink pointing into the primary + // checkout looks untracked to git. Unlink the user-configured symlinks + // first so the normal delete path keeps working — otherwise every + // deletion would require the Force Delete toast once the feature is on. + const settings = store.getSettings() + if ( + settings.experimentalWorktreeSymlinks && + repo.symlinkPaths && + repo.symlinkPaths.length > 0 + ) { + await removeWorktreeSymlinks(worktreePath, repo.symlinkPaths) + } + try { await removeWorktree(repo.path, worktreePath, args.force ?? false) } catch (error) { diff --git a/src/renderer/src/components/settings/ExperimentalPane.tsx b/src/renderer/src/components/settings/ExperimentalPane.tsx index 8046ab172..fb5ffc08c 100644 --- a/src/renderer/src/components/settings/ExperimentalPane.tsx +++ b/src/renderer/src/components/settings/ExperimentalPane.tsx @@ -73,6 +73,9 @@ export function ExperimentalPane({ const showOrchestration = matchesSettingsSearch(searchQuery, [ EXPERIMENTAL_PANE_SEARCH_ENTRIES[3] ]) + const showWorktreeSymlinks = matchesSettingsSearch(searchQuery, [ + EXPERIMENTAL_PANE_SEARCH_ENTRIES[3] + ]) const [orchestrationEnabled, setOrchestrationEnabled] = useState(() => { return localStorage.getItem('orca.orchestration.enabled') === '1' @@ -387,6 +390,44 @@ export function ExperimentalPane({ ) : null} + {showWorktreeSymlinks ? ( + +
+
+ +

+ Allows for automatic symlinks of certain folders or files that must be connected to + created worktrees. +

+
+ +
+
+ ) : null} + {hiddenExperimentalUnlocked ? : null} ) diff --git a/src/renderer/src/components/settings/RepositoryPane.tsx b/src/renderer/src/components/settings/RepositoryPane.tsx index 8d266a9fe..4a48cc879 100644 --- a/src/renderer/src/components/settings/RepositoryPane.tsx +++ b/src/renderer/src/components/settings/RepositoryPane.tsx @@ -10,6 +10,7 @@ import { Trash2 } from 'lucide-react' import { DEFAULT_REPO_HOOK_SETTINGS } from './SettingsConstants' import { BaseRefPicker } from './BaseRefPicker' import { RepositoryHooksSection } from './RepositoryHooksSection' +import { WorktreeSymlinksSection } from './WorktreeSymlinksSection' import { SparsePresetSettingsSection } from './SparsePresetSettingsSection' import { SearchableSetting } from './SearchableSetting' import { matchesSettingsSearch, type SettingsSearchEntry } from './settings-search' @@ -68,6 +69,21 @@ export function getRepositoryPaneSearchEntries(repo: Repo): SettingsSearchEntry[ ...(isFolder ? [] : [ + { + title: 'Worktree Symlinks', + description: + 'Paths to symlink from the primary checkout into newly created worktrees.', + keywords: [ + repo.displayName, + 'symlink', + 'symlinks', + 'worktree', + 'link', + 'shared', + 'env', + 'node_modules' + ] + }, { title: 'orca.yaml hooks', description: 'Shared setup and archive hook commands for this repository.', @@ -117,6 +133,7 @@ export function RepositoryPane({ }: RepositoryPaneProps): React.JSX.Element { const isFolder = isFolderRepo(repo) const searchQuery = useAppStore((state) => state.settingsSearchQuery) + const symlinksEnabled = useAppStore((state) => state.settings?.experimentalWorktreeSymlinks) const [confirmingRemove, setConfirmingRemove] = useState(null) const [copiedTemplate, setCopiedTemplate] = useState(false) @@ -190,6 +207,7 @@ export function RepositoryPane({ 'Custom GitHub Issue Command' ].includes(entry.title) ) + const symlinkEntries = allEntries.filter((entry) => entry.title === 'Worktree Symlinks') const visibleSections = [ matchesSettingsSearch(searchQuery, identityEntries) ? ( @@ -287,6 +305,11 @@ export function RepositoryPane({ ) : null} ) : null, + !isFolder && + symlinksEnabled && + matchesSettingsSearch(searchQuery, symlinkEntries) ? ( + + ) : null, !isFolder && matchesSettingsSearch(searchQuery, sparsePresetEntries) ? ( ) : null, diff --git a/src/renderer/src/components/settings/WorktreeSymlinksSection.tsx b/src/renderer/src/components/settings/WorktreeSymlinksSection.tsx new file mode 100644 index 000000000..59a7fcc62 --- /dev/null +++ b/src/renderer/src/components/settings/WorktreeSymlinksSection.tsx @@ -0,0 +1,201 @@ +import { useEffect, useMemo, useState } from 'react' +import { File, Folder, Link2, Plus, X } from 'lucide-react' +import type { Repo } from '../../../../shared/types' +import { Button } from '../ui/button' +import { Command, CommandEmpty, CommandInput, CommandItem, CommandList } from '../ui/command' +import { Popover, PopoverContent, PopoverTrigger } from '../ui/popover' +import { cn } from '@/lib/utils' +import { SearchableSetting } from './SearchableSetting' + +type WorktreeSymlinksSectionProps = { + repo: Repo + updateRepo: (repoId: string, updates: Partial) => void +} + +type DirEntry = { name: string; isDirectory: boolean } + +const MAX_SUGGESTIONS = 50 + +export function WorktreeSymlinksSection({ + repo, + updateRepo +}: WorktreeSymlinksSectionProps): React.JSX.Element { + const [open, setOpen] = useState(false) + const [query, setQuery] = useState('') + const [entries, setEntries] = useState([]) + + const paths = repo.symlinkPaths ?? [] + const queryTrimmed = query.trim().replace(/^\/+/, '') + + useEffect(() => { + let cancelled = false + void window.api.fs + .readDir({ dirPath: repo.path, connectionId: repo.connectionId ?? undefined }) + .then((list) => { + if (cancelled) { + return + } + setEntries(list.map((entry) => ({ name: entry.name, isDirectory: entry.isDirectory }))) + }) + .catch(() => { + // Non-fatal: without entries the combobox still works as a free-text + // input — the user can type any path and commit it. + }) + return () => { + cancelled = true + } + }, [repo.path, repo.connectionId]) + + const filtered = useMemo(() => { + const q = queryTrimmed.toLowerCase() + const base = q ? entries.filter((e) => e.name.toLowerCase().includes(q)) : entries + return base.slice(0, MAX_SUGGESTIONS) + }, [queryTrimmed, entries]) + + const hasExactMatch = filtered.some((e) => e.name === queryTrimmed) + const showLiteralItem = queryTrimmed.length > 0 && !hasExactMatch && !paths.includes(queryTrimmed) + + const commit = (rawName: string): void => { + const trimmed = rawName.trim().replace(/^\/+/, '') + if (!trimmed || paths.includes(trimmed)) { + setQuery('') + return + } + updateRepo(repo.id, { symlinkPaths: [...paths, trimmed] }) + setQuery('') + setOpen(false) + } + + const handleRemove = (path: string): void => { + updateRepo(repo.id, { symlinkPaths: paths.filter((p) => p !== path) }) + } + + return ( + +
+
+

Worktree Symlinks

+

+ When a new worktree is created, each path listed here will be symlinked from the primary + checkout. +

+
+ + + + + + + + + No matches. Keep typing to add a custom path. + {showLiteralItem ? ( + commit(queryTrimmed)} + className="items-center gap-2 px-3 py-2" + > + + + Add{' '} + + {queryTrimmed} + + + + ) : null} + {filtered.map((entry) => { + const alreadyAdded = paths.includes(entry.name) + return ( + commit(entry.name)} + className={cn('items-center gap-2 px-3 py-2', alreadyAdded && 'opacity-50')} + > + {entry.isDirectory ? ( + + ) : ( + + )} + {entry.name} + {alreadyAdded ? ( + + added + + ) : null} + + ) + })} + + + + +
+ + {paths.length === 0 ? ( +
+ No symlink paths configured for this repository. +
+ ) : ( +
+
+
+ +
+
+
+

Linked paths

+ + {paths.length === 1 ? '1 path' : `${paths.length} paths`} + +
+
+ {paths.map((path) => ( + + {path} + + + ))} +
+
+
+
+ )} +
+ ) +} diff --git a/src/renderer/src/components/settings/experimental-search.ts b/src/renderer/src/components/settings/experimental-search.ts index 9066f3879..70382a48a 100644 --- a/src/renderer/src/components/settings/experimental-search.ts +++ b/src/renderer/src/components/settings/experimental-search.ts @@ -69,5 +69,22 @@ export const EXPERIMENTAL_PANE_SEARCH_ENTRIES: SettingsSearchEntry[] = [ 'worker', 'coordinator' ] + }, + { + title: 'Symlinks on worktrees', + description: + 'Automatically symlink configured files or folders into newly created worktrees so shared state (envs, caches, installs) stays connected.', + keywords: [ + 'experimental', + 'worktree', + 'worktrees', + 'symlink', + 'symlinks', + 'link', + 'links', + 'shared', + 'env', + 'node_modules' + ] } ] diff --git a/src/renderer/src/store/slices/repos.ts b/src/renderer/src/store/slices/repos.ts index f203a36b6..dceeb8c43 100644 --- a/src/renderer/src/store/slices/repos.ts +++ b/src/renderer/src/store/slices/repos.ts @@ -23,6 +23,7 @@ export type RepoSlice = { | 'hookSettings' | 'worktreeBaseRef' | 'kind' + | 'symlinkPaths' | 'issueSourcePreference' > > diff --git a/src/shared/constants.ts b/src/shared/constants.ts index 81b2b4d47..79321ead5 100644 --- a/src/shared/constants.ts +++ b/src/shared/constants.ts @@ -202,7 +202,8 @@ export function getDefaultSettings(homedir: string): GlobalSettings { experimentalMobile: false, // Why: off by default — opt-in cosmetic joke feature. Leaving the default // false keeps the overlay unmounted for users who never enable it. - experimentalSidekick: false + experimentalSidekick: false, + experimentalWorktreeSymlinks: false } } diff --git a/src/shared/types.ts b/src/shared/types.ts index a10f9a333..25b13e3a5 100644 --- a/src/shared/types.ts +++ b/src/shared/types.ts @@ -37,6 +37,12 @@ export type Repo = { * identically to `'auto'`; writers leave it undefined on creation so * existing persisted records stay forward-compatible. */ issueSourcePreference?: IssueSourcePreference + /** Paths (relative to the primary checkout) that should be symlinked into + * newly created worktrees of this repo. Consumed only when the global + * `experimentalWorktreeSymlinks` flag is on — the per-repo list is the + * "what to link", the global flag is the "whether to link at all" switch. + * Undefined/empty means no symlinks are created for this repo. */ + symlinkPaths?: string[] } export type SetupRunPolicy = 'ask' | 'run-by-default' | 'skip-by-default' @@ -1158,6 +1164,12 @@ export type GlobalSettings = { * off never mount the overlay. Toggling takes effect immediately in the * current session (no relaunch) because it is purely renderer-side. */ experimentalSidekick: boolean + /** Experimental: when creating a worktree, automatically symlink a + * user-configured set of files/folders from the primary checkout (e.g. + * `.env`, `node_modules`) into the new worktree. Opt-in while the + * configuration surface and edge cases (conflicts with existing paths, + * cleanup on worktree delete) are still being worked out. */ + experimentalWorktreeSymlinks: boolean /** Anonymous product-telemetry state. Optional because the one-shot * migration in `Store.load()` is what populates it on first boot of the * telemetry release; before migration runs, the field is absent. After