feat(worktrees): add experimental symlinks for shared paths on worktree creation (#1029)
Co-authored-by: Orca <help@stably.ai> Co-authored-by: federico-ntb <federico@notchatbot.com> Co-authored-by: Jinwoo-H <jinwoo0825@gmail.com>
This commit is contained in:
co-authored by
Orca
federico-ntb
Jinwoo-H
parent
9f1ccf44d0
commit
82023dbe1b
@@ -96,6 +96,7 @@ function createSettings(overrides: Partial<GlobalSettings> = {}): GlobalSettings
|
||||
experimentalAgentDashboard: false,
|
||||
experimentalMobile: false,
|
||||
experimentalSidekick: false,
|
||||
experimentalWorktreeSymlinks: false,
|
||||
terminalWindowsShell: 'powershell.exe',
|
||||
terminalWindowsPowerShellImplementation: 'powershell.exe',
|
||||
enableGitHubAttribution: true,
|
||||
|
||||
@@ -90,6 +90,7 @@ function createSettings(overrides: Partial<GlobalSettings> = {}): GlobalSettings
|
||||
experimentalAgentDashboard: false,
|
||||
experimentalMobile: false,
|
||||
experimentalSidekick: false,
|
||||
experimentalWorktreeSymlinks: false,
|
||||
terminalWindowsShell: 'powershell.exe',
|
||||
terminalWindowsPowerShellImplementation: 'powershell.exe',
|
||||
enableGitHubAttribution: true,
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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<typeof vi.spyOn>
|
||||
let error: ReturnType<typeof vi.spyOn>
|
||||
|
||||
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<typeof vi.spyOn>
|
||||
|
||||
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()
|
||||
})
|
||||
})
|
||||
@@ -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<void> {
|
||||
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<void> {
|
||||
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)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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) {
|
||||
|
||||
@@ -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<boolean>(() => {
|
||||
return localStorage.getItem('orca.orchestration.enabled') === '1'
|
||||
@@ -387,6 +390,44 @@ export function ExperimentalPane({
|
||||
</SearchableSetting>
|
||||
) : null}
|
||||
|
||||
{showWorktreeSymlinks ? (
|
||||
<SearchableSetting
|
||||
title="Symlinks on worktrees"
|
||||
description="Automatically symlink configured files or folders into newly created worktrees."
|
||||
keywords={EXPERIMENTAL_PANE_SEARCH_ENTRIES[3].keywords}
|
||||
className="space-y-3 px-1 py-2"
|
||||
>
|
||||
<div className="flex items-start justify-between gap-4">
|
||||
<div className="min-w-0 shrink space-y-0.5">
|
||||
<Label>Symlinks on worktrees</Label>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Allows for automatic symlinks of certain folders or files that must be connected to
|
||||
created worktrees.
|
||||
</p>
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
role="switch"
|
||||
aria-checked={settings.experimentalWorktreeSymlinks}
|
||||
onClick={() =>
|
||||
updateSettings({
|
||||
experimentalWorktreeSymlinks: !settings.experimentalWorktreeSymlinks
|
||||
})
|
||||
}
|
||||
className={`relative inline-flex h-5 w-9 shrink-0 cursor-pointer items-center rounded-full border border-transparent transition-colors ${
|
||||
settings.experimentalWorktreeSymlinks ? 'bg-foreground' : 'bg-muted-foreground/30'
|
||||
}`}
|
||||
>
|
||||
<span
|
||||
className={`inline-block h-3.5 w-3.5 transform rounded-full bg-background shadow-sm transition-transform ${
|
||||
settings.experimentalWorktreeSymlinks ? 'translate-x-4' : 'translate-x-0.5'
|
||||
}`}
|
||||
/>
|
||||
</button>
|
||||
</div>
|
||||
</SearchableSetting>
|
||||
) : null}
|
||||
|
||||
{hiddenExperimentalUnlocked ? <HiddenExperimentalGroup /> : null}
|
||||
</div>
|
||||
)
|
||||
|
||||
@@ -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<string | null>(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}
|
||||
</section>
|
||||
) : null,
|
||||
!isFolder &&
|
||||
symlinksEnabled &&
|
||||
matchesSettingsSearch(searchQuery, symlinkEntries) ? (
|
||||
<WorktreeSymlinksSection key="symlinks" repo={repo} updateRepo={updateRepo} />
|
||||
) : null,
|
||||
!isFolder && matchesSettingsSearch(searchQuery, sparsePresetEntries) ? (
|
||||
<SparsePresetSettingsSection key="sparse-presets" repoId={repo.id} />
|
||||
) : null,
|
||||
|
||||
@@ -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<Repo>) => 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<DirEntry[]>([])
|
||||
|
||||
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 (
|
||||
<SearchableSetting
|
||||
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'
|
||||
]}
|
||||
className="space-y-4"
|
||||
>
|
||||
<div className="flex items-start justify-between gap-4">
|
||||
<div className="space-y-1">
|
||||
<h3 className="text-sm font-semibold">Worktree Symlinks</h3>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
When a new worktree is created, each path listed here will be symlinked from the primary
|
||||
checkout.
|
||||
</p>
|
||||
</div>
|
||||
<Popover open={open} onOpenChange={setOpen}>
|
||||
<PopoverTrigger asChild>
|
||||
<Button type="button" variant="outline" size="sm">
|
||||
<Plus className="size-3.5" />
|
||||
Add Path
|
||||
</Button>
|
||||
</PopoverTrigger>
|
||||
<PopoverContent align="end" className="w-72 p-0">
|
||||
<Command shouldFilter={false}>
|
||||
<CommandInput
|
||||
placeholder="Type a path (e.g. .env or node_modules)…"
|
||||
value={query}
|
||||
onValueChange={setQuery}
|
||||
/>
|
||||
<CommandList>
|
||||
<CommandEmpty>No matches. Keep typing to add a custom path.</CommandEmpty>
|
||||
{showLiteralItem ? (
|
||||
<CommandItem
|
||||
value={`__literal__:${queryTrimmed}`}
|
||||
onSelect={() => commit(queryTrimmed)}
|
||||
className="items-center gap-2 px-3 py-2"
|
||||
>
|
||||
<Plus className="size-3.5 text-muted-foreground" />
|
||||
<span className="text-xs">
|
||||
Add{' '}
|
||||
<code className="rounded bg-muted px-1 py-0.5 text-[11px]">
|
||||
{queryTrimmed}
|
||||
</code>
|
||||
</span>
|
||||
</CommandItem>
|
||||
) : null}
|
||||
{filtered.map((entry) => {
|
||||
const alreadyAdded = paths.includes(entry.name)
|
||||
return (
|
||||
<CommandItem
|
||||
key={entry.name}
|
||||
value={entry.name}
|
||||
disabled={alreadyAdded}
|
||||
onSelect={() => commit(entry.name)}
|
||||
className={cn('items-center gap-2 px-3 py-2', alreadyAdded && 'opacity-50')}
|
||||
>
|
||||
{entry.isDirectory ? (
|
||||
<Folder className="size-3.5 text-muted-foreground" />
|
||||
) : (
|
||||
<File className="size-3.5 text-muted-foreground" />
|
||||
)}
|
||||
<span className="truncate text-xs">{entry.name}</span>
|
||||
{alreadyAdded ? (
|
||||
<span className="ml-auto text-[10px] uppercase tracking-wide text-muted-foreground">
|
||||
added
|
||||
</span>
|
||||
) : null}
|
||||
</CommandItem>
|
||||
)
|
||||
})}
|
||||
</CommandList>
|
||||
</Command>
|
||||
</PopoverContent>
|
||||
</Popover>
|
||||
</div>
|
||||
|
||||
{paths.length === 0 ? (
|
||||
<div className="rounded-xl border border-dashed border-border/60 bg-background/60 px-4 py-6 text-sm text-muted-foreground">
|
||||
No symlink paths configured for this repository.
|
||||
</div>
|
||||
) : (
|
||||
<div className="rounded-xl border border-border/50 bg-background/70 px-4 py-3 shadow-sm">
|
||||
<div className="flex items-start gap-3">
|
||||
<div className="mt-0.5 flex size-8 shrink-0 items-center justify-center rounded-lg border border-border/50 bg-muted/30">
|
||||
<Link2 className="size-4 text-muted-foreground" />
|
||||
</div>
|
||||
<div className="min-w-0 flex-1 space-y-2">
|
||||
<div className="flex flex-wrap items-center gap-x-2 gap-y-1">
|
||||
<h4 className="text-sm font-medium">Linked paths</h4>
|
||||
<span className="text-[11px] text-muted-foreground">
|
||||
{paths.length === 1 ? '1 path' : `${paths.length} paths`}
|
||||
</span>
|
||||
</div>
|
||||
<div className="flex flex-wrap gap-1.5">
|
||||
{paths.map((path) => (
|
||||
<span
|
||||
key={path}
|
||||
title={path}
|
||||
className="inline-flex min-w-0 max-w-full items-center gap-1 truncate rounded-md border border-border/50 bg-muted/35 py-1 pl-2 pr-1 font-mono text-[11px] text-foreground/80"
|
||||
>
|
||||
<span className="truncate">{path}</span>
|
||||
<Button
|
||||
size="icon-xs"
|
||||
variant="ghost"
|
||||
onClick={() => handleRemove(path)}
|
||||
aria-label={`Remove ${path}`}
|
||||
className="size-4 shrink-0 rounded-sm"
|
||||
>
|
||||
<X className="size-3" />
|
||||
</Button>
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</SearchableSetting>
|
||||
)
|
||||
}
|
||||
@@ -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'
|
||||
]
|
||||
}
|
||||
]
|
||||
|
||||
@@ -23,6 +23,7 @@ export type RepoSlice = {
|
||||
| 'hookSettings'
|
||||
| 'worktreeBaseRef'
|
||||
| 'kind'
|
||||
| 'symlinkPaths'
|
||||
| 'issueSourcePreference'
|
||||
>
|
||||
>
|
||||
|
||||
@@ -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
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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
|
||||
|
||||
Reference in New Issue
Block a user