Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
152 changes: 152 additions & 0 deletions docs/delete-workspace-windows-unregistered.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,152 @@
# Delete Windows Workspace Without False Unregistered Error

## Problem

GitHub issue [#5864](https://github.com/stablyai/orca/issues/5864) reports that Orca on Windows v0.14.80 fails to delete a workspace created from a project `+` button:

`Error invoking remote method 'worktrees:remove': Error: Refusing to delete unregistered worktree path: C:/Users/andy/orca/workspaces/ops-tools/packaging-improvements-2`

Relevant flow:

- Renderer delete calls local IPC for local targets in `src/renderer/src/store/slices/worktrees.ts`.
- Preload exposes that as `worktrees:remove` in `src/preload/index.ts`.
- IPC delete lists Git worktrees, matches the requested path, and throws the unregistered error if no registered entry matches in `src/main/ipc/worktrees.ts`.
- Runtime RPC delete has the same registered-worktree gate in `src/main/runtime/orca-runtime.ts`.
- Windows create/list coverage exists in `src/main/ipc/worktrees-windows.test.ts`, but Windows delete coverage is missing.

## Root Cause

Delete is right to refuse arbitrary paths. This bug is a false negative in the proof step: Orca asks Git for the authoritative registered worktree list, but the list does not contain an entry equivalent to the project-created target.

Do not fix this by adding another path-normalization layer after the list. `findRegisteredDeletableWorktree` delegates to `areWorktreePathsEqual`, which already treats `C:/...`, `C:\...`, and drive-case variants as equal while keeping POSIX/WSL paths distinct. `git/worktree.removeWorktree` has a similar comparator for its fallback branch lookup.

The credible failure surfaces are before or around that comparator:

- Delete may list through a different local runtime than create/list/selector resolution, especially for project runtime settings on Windows.
- `listWorktrees` currently returns `[]` for several Git/list failures. In delete, that collapses "could not prove registration" into the misleading unregistered-path error.
- Runtime selector/list resolution calls `listRepoWorktreesForResolution(repo)`, which currently omits local project runtime options.
- Runtime removal validates a registered row, but then calls `removeWorktree` without `knownRemovedWorktree`, allowing the Git helper to rescan under the supplied options.
- Some runtime cleanup paths still omit or recompute local runtime options instead of using the option set captured for the delete.

Implementation must start with a failing regression. If an equivalent Windows row is present in the registered list under the right options, deletion should succeed without further path comparator changes.

## Non-goals

- Do not allow deletion of existing unregistered directories.
- Do not bypass the main-worktree, nested-worktree, local dirty-worktree, archive-hook, branch-preservation, or concurrent-delete guards.
- Do not change delete dialog UI/copy.
- Do not change SSH provider semantics.
- Do not add a broad path abstraction or metadata migration.

## Design

1. Capture one repo-scoped local Git option set for the delete.
- For local repos, use the repo's project runtime options from `getLocalProjectWorktreeGitOptions(store, repo)`. This is already repo-scoped and surfaces repair-required project runtimes before any Git command.
- Do not use `getLocalGitOptionsForRegisteredWorktree` for delete. It scans all repos and uses native `path.resolve`, which is not a safe Windows-equivalence test on macOS/Linux test hosts.
- Do not choose options from a worktree path alone. The parsed `repoId` is the authority for local runtime selection; exact-ID fallback after selector failure should still use the owning repo's project runtime options.
- Keep SSH paths on the existing provider branch.

2. Make the authoritative Git list strict enough for delete.
- Delete must distinguish "Git listed zero matching worktrees" from "Git listing failed." A selected-runtime Git/list failure should surface the underlying failure, not turn into `Refusing to delete unregistered worktree path`.
- If this requires a strict list API beside `listWorktrees`, keep it narrow and delete-only; do not change polling/list UI behavior that intentionally tolerates transient Git failures.
- The registered row returned by Git remains the canonical removal target after `findRegisteredDeletableWorktree` succeeds.

3. Thread the captured option set through the full local removal path.
- `listWorktrees`, archive hooks, orphan proof reads, missing-path checks, clean preflight, `git worktree remove`, branch cleanup, recursive orphan cleanup, filesystem delete, push-target cleanup, and `git worktree prune` must all use the same captured options.
- Do not recompute project runtime options later in the operation. A project runtime setting change during an in-flight delete must not split one deletion across two runtimes.
- IPC already passes `knownRemovedWorktree` to `removeWorktree`; keep that behavior.
- Runtime removal must also pass `knownRemovedWorktree` so branch cleanup uses the validated row and avoids a second list.
- Replace current runtime cleanup call sites that omit `localWorktreeGitOptions` for push-target remote cleanup.
- Replace prune calls that recompute `getLocalProjectGitExecOptions(...)` with `{ cwd: repo.path, ...localWorktreeGitOptions }`.

4. Fix runtime resolution/listing.
- Update `listRepoWorktreesForResolution(repo)` to call `listRepoWorktrees(repo, getLocalProjectWorktreeGitOptions(store, repo))` for local repos.
- Runtime exact-ID deletes should re-list Git under the captured options before destructive work; selector caches are convenience only, not delete authority.
- Runtime archive hooks should use the captured options rather than `this.getLocalGitExecutionOptionArgs(repo)[0]`.

## Data Flow

- Delete action -> `removeWorktree(worktreeId, force)` in renderer.
- Local target -> `window.api.worktrees.remove({ worktreeId, force, skipArchive })`.
- Main parses `repoId` and `worktreePath`.
- Main resolves the repo and captures one local Git option set for that repo.
- Main strictly lists registered Git worktrees with those options.
- Main matches requested path to registered path with `areWorktreePathsEqual` via `findRegisteredDeletableWorktree`.
- Main uses the registered canonical path for hooks, preflight, watcher close, Git removal, orphan cleanup, metadata cleanup, and sidebar refresh. PTY teardown remains keyed by the exact worktree ID.

Runtime RPC follows the same rule after selector resolution, and exact-ID fallback must still re-list Git before destructive work.

## Edge Cases

- `C:/...`, `C:\...`, and drive-letter case variants refer to the same Windows worktree.
- POSIX WSL paths and Windows paths must not compare equal unless `listWorktrees` translated them through the selected WSL options.
- UNC paths, drive-letter paths, and `/mnt/<drive>` paths need explicit tests because Node path behavior is platform-specific on macOS/Linux test hosts.
- Main worktree deletion is still rejected.
- Parent worktree deletion is still rejected if another registered worktree is nested inside it.
- Existing unregistered directories are still rejected, even with `force`.
- Already-missing Orca-known worktrees still clean metadata only.
- Orphaned Orca-created worktree directories still require proof through the `.git` file before recursive deletion.
- Multi-window IPC deletes coalesce only for the same exact worktree ID and options. Equivalent Windows paths with different IDs, or IPC/runtime deletes racing each other, must degrade to safe missing/orphan handling or a protected error.
- External Git mutation between list and `git worktree remove` is handled by the existing missing/orphan branches; keep those branches under the same captured runtime options.
- Project runtime setting changes during an in-flight delete affect only later deletes.
- SSH deletes still use SSH Git/filesystem providers and do not touch local paths.

## Test Plan

- Unit:
- `pnpm vitest run src/main/ipc/worktrees-windows.test.ts`
- `pnpm vitest run src/main/ipc/worktrees.test.ts --testNamePattern "local worktree removal|selected WSL project runtime|unregistered delete|contains another registered|already-missing"`
- `pnpm vitest run src/main/runtime/orca-runtime.test.ts --testNamePattern "worktree removal|selected WSL project runtime|unregistered delete|contains another registered|already-missing"`
- Required new coverage:
- IPC Windows delete regression: request path uses `C:/...`, Git registered row uses backslashes and/or different drive-case, delete succeeds, hooks/preflight/removal use the canonical registered path, `knownRemovedWorktree` is passed, metadata is removed, and `worktrees:changed` emits.
- Runtime Windows delete regression with the same path mismatch. Assert selector/list resolution and final removal both use selected project runtime options, and `knownRemovedWorktree` is passed.
- Strict-list failure regression: a selected-runtime list failure rejects with the list failure, not the unregistered-path error.
- Negative Windows/WSL mismatch: POSIX `/mnt/c/...` or WSL-native paths must not match unrelated Windows paths unless translated by the selected WSL options.
- Runtime cleanup regressions for already-missing/orphan/push-target cleanup under selected WSL options.
- Integration/e2e:
- Electron smoke with a disposable local repo/worktree: delete succeeds, row disappears, no new delete UI regressions.
- Real Windows validation is preferred. macOS/Linux unit tests can cover comparator and option plumbing, but they cannot fully prove Node and Git path behavior on Windows.
- Full checks:
- `pnpm typecheck`
- `pnpm lint`

## UI Quality Bar

No intentional UI change. Existing delete dialog, progress state, toast behavior, and sidebar row removal should remain visually unchanged and follow `docs/STYLEGUIDE.md`.

## Review Screenshots

No design screenshots are required for a backend-only fix. If the PR needs Electron smoke evidence, attach only:

1. Disposable workspace delete confirmation before confirming.
2. Sidebar after successful deletion with the row gone.

Do not spend review time manufacturing a protected/error screenshot; cover that with unit tests.

## Rollout

1. Add focused Windows-path delete regression tests.
2. Add strict delete listing or equivalent failure propagation.
3. Update runtime selector/list resolution to use local project runtime options.
4. Thread captured options and `knownRemovedWorktree` through IPC/runtime delete paths.
5. Run focused tests, typecheck, lint.
6. Electron-validate the unchanged delete UI on a disposable workspace and collect screenshots only if required.

## Lightweight Eng Review

- Scope: delete-only; no renderer changes, no new deletion authority, and no broad path-normalization rewrite.
- Architecture/data flow: local IPC and runtime RPC both keep Git as the authority. The fix is to ask Git through the correct project runtime, treat list failures as failures, then use Git's registered row as the canonical removal target.
- Failure modes covered:
- Windows slash/drive-case mismatches.
- Wrong or failed local project runtime listing.
- Runtime selector resolution using host listings.
- Runtime branch cleanup rescanning instead of using the validated row.
- Metadata absent or stale during already-missing cleanup.
- Existing unregistered directory remains protected.
- Main and nested registered worktrees remain protected.
- SSH paths stay provider-owned.
- Performance/blast radius: no material concern if the delete path performs one strict authoritative list and passes `knownRemovedWorktree` to avoid the helper rescan.
- Feasibility: this is not a "one comparator call" fix. The current APIs make `listWorktrees` failures look like empty lists, and runtime selector resolution currently omits local runtime options.
- UI quality bar: no UI-visible design change; Electron should judge that existing delete dialog, progress, toast, and row removal still look unchanged against `docs/STYLEGUIDE.md`.
- Required review screenshots: none for the backend fix; optional disposable-workspace smoke screenshots only if the PR process asks for visual evidence.
- Residual risks: true Windows filesystem/Git spelling behavior still depends on a Windows runner or user validation; macOS/Linux tests cannot fully model it.
3 changes: 2 additions & 1 deletion src/main/browser/cdp-bridge-integration.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,8 @@ vi.mock('electron', () => ({
}))

vi.mock('../git/worktree', () => ({
listWorktrees: vi.fn().mockResolvedValue([])
listWorktrees: vi.fn().mockResolvedValue([]),
listWorktreesStrict: vi.fn().mockResolvedValue([])
}))

import { BrowserManager } from './browser-manager'
Expand Down
11 changes: 11 additions & 0 deletions src/main/git/worktree.ts
Original file line number Diff line number Diff line change
Expand Up @@ -492,6 +492,17 @@ export async function listWorktrees(
}
}

export async function listWorktreesStrict(
repoPath: string,
options: GitWorktreeExecOptions = {}
): Promise<GitWorktreeInfo[]> {
const worktrees = (await readWorktreeList(repoPath, options)).map((worktree) => {
const translatedPath = translateWorktreePath(worktree.path, repoPath, options)
return translatedPath === worktree.path ? worktree : { ...worktree, path: translatedPath }
})
return annotateSparseCheckoutStatus(worktrees)
}
Comment on lines +495 to +504

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Add a short “Why” comment for strict error propagation (Line 495).

listWorktreesStrict is design-driven and intentionally differs from listWorktrees by surfacing failures; please add a 1–2 line comment stating that reason so future changes don’t reintroduce silent fallback behavior.

Source: Coding guidelines


async function annotateSparseCheckoutStatus(
worktrees: GitWorktreeInfo[]
): Promise<GitWorktreeInfo[]> {
Expand Down
3 changes: 2 additions & 1 deletion src/main/ipc/filesystem.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -132,7 +132,8 @@ vi.mock('../git/check-ignored-paths', () => ({
}))

vi.mock('../git/worktree', () => ({
listWorktrees: listWorktreesMock
listWorktrees: listWorktreesMock,
listWorktreesStrict: listWorktreesMock
}))

vi.mock('../providers/ssh-filesystem-dispatch', () => ({
Expand Down
80 changes: 78 additions & 2 deletions src/main/ipc/worktrees-windows.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ const {
handleMock,
removeHandlerMock,
listWorktreesMock,
assertWorktreeCleanForRemovalMock,
addWorktreeMock,
removeWorktreeMock,
getGitUsernameMock,
Expand All @@ -22,11 +23,16 @@ const {
hasHooksFileMock,
loadHooksMock,
computeWorktreePathMock,
ensurePathWithinWorkspaceMock
ensurePathWithinWorkspaceMock,
killAllProcessesForWorktreeMock,
clearProviderPtyStateMock,
getLocalPtyProviderMock,
deleteWorktreeHistoryDirMock
} = vi.hoisted(() => ({
handleMock: vi.fn(),
removeHandlerMock: vi.fn(),
listWorktreesMock: vi.fn(),
assertWorktreeCleanForRemovalMock: vi.fn(),
addWorktreeMock: vi.fn(),
removeWorktreeMock: vi.fn(),
getGitUsernameMock: vi.fn(),
Expand All @@ -45,7 +51,11 @@ const {
hasHooksFileMock: vi.fn(),
loadHooksMock: vi.fn(),
computeWorktreePathMock: vi.fn(),
ensurePathWithinWorkspaceMock: vi.fn()
ensurePathWithinWorkspaceMock: vi.fn(),
killAllProcessesForWorktreeMock: vi.fn(),
clearProviderPtyStateMock: vi.fn(),
getLocalPtyProviderMock: vi.fn(),
deleteWorktreeHistoryDirMock: vi.fn()
}))

vi.mock('electron', () => ({
Expand All @@ -57,6 +67,8 @@ vi.mock('electron', () => ({

vi.mock('../git/worktree', () => ({
listWorktrees: listWorktreesMock,
listWorktreesStrict: listWorktreesMock,
assertWorktreeCleanForRemoval: assertWorktreeCleanForRemovalMock,
addWorktree: addWorktreeMock,
removeWorktree: removeWorktreeMock
}))
Expand Down Expand Up @@ -93,6 +105,19 @@ vi.mock('../hooks', () => ({
shouldRunSetupForCreate: shouldRunSetupForCreateMock
}))

vi.mock('../runtime/worktree-teardown', () => ({
killAllProcessesForWorktree: killAllProcessesForWorktreeMock
}))

vi.mock('./pty', () => ({
clearProviderPtyState: clearProviderPtyStateMock,
getLocalPtyProvider: getLocalPtyProviderMock
}))

vi.mock('../terminal-history', () => ({
deleteWorktreeHistoryDir: deleteWorktreeHistoryDirMock
}))

vi.mock('./worktree-logic', async (importOriginal) => {
const actual = (await importOriginal()) as Record<string, unknown>
return {
Expand Down Expand Up @@ -129,6 +154,7 @@ describe('registerWorktreeHandlers – Windows path handling', () => {
handleMock.mockReset()
removeHandlerMock.mockReset()
listWorktreesMock.mockReset()
assertWorktreeCleanForRemovalMock.mockReset()
addWorktreeMock.mockReset()
removeWorktreeMock.mockReset()
getGitUsernameMock.mockReset()
Expand All @@ -148,6 +174,10 @@ describe('registerWorktreeHandlers – Windows path handling', () => {
loadHooksMock.mockReset()
computeWorktreePathMock.mockReset()
ensurePathWithinWorkspaceMock.mockReset()
killAllProcessesForWorktreeMock.mockReset()
clearProviderPtyStateMock.mockReset()
getLocalPtyProviderMock.mockReset()
deleteWorktreeHistoryDirMock.mockReset()
mainWindow.webContents.send.mockReset()
store.getRepos.mockReset()
store.getRepo.mockReset()
Expand Down Expand Up @@ -205,6 +235,13 @@ describe('registerWorktreeHandlers – Windows path handling', () => {
computeWorktreePathMock.mockReturnValue('C:\\workspaces\\improve-dashboard')
ensurePathWithinWorkspaceMock.mockReturnValue('C:\\workspaces\\improve-dashboard')
listWorktreesMock.mockResolvedValue([])
assertWorktreeCleanForRemovalMock.mockResolvedValue(undefined)
killAllProcessesForWorktreeMock.mockResolvedValue({
runtimeStopped: 0,
providerStopped: 0,
registryStopped: 0
})
getLocalPtyProviderMock.mockReturnValue({})

// Why: createLocalWorktree routes `git fetch` through
// `runtime.fetchRemoteWithCache` (§3.3 Lifecycle). Stub it for path tests.
Expand Down Expand Up @@ -308,4 +345,43 @@ describe('registerWorktreeHandlers – Windows path handling', () => {
}
])
})

it('deletes a Windows worktree when the requested path uses different separators and drive casing', async () => {
const registeredWorktree = {
path: 'c:\\workspaces\\Improve-Dashboard',
head: 'feature-head',
branch: 'refs/heads/improve-dashboard',
isBare: false,
isMainWorktree: false
}
listWorktreesMock.mockResolvedValue([
{
path: 'C:\\repo',
head: 'main-head',
branch: 'refs/heads/main',
isBare: false,
isMainWorktree: true
},
registeredWorktree
])
removeWorktreeMock.mockResolvedValue({})

await handlers['worktrees:remove'](null, {
worktreeId: 'repo-1::C:/workspaces/improve-dashboard'
})

expect(assertWorktreeCleanForRemovalMock).toHaveBeenCalledWith(registeredWorktree.path, false)
expect(removeWorktreeMock).toHaveBeenCalledWith(
'C:\\repo',
registeredWorktree.path,
false,
expect.objectContaining({
knownRemovedWorktree: registeredWorktree
})
)
expect(store.removeWorktreeMeta).toHaveBeenCalledWith('repo-1::C:/workspaces/improve-dashboard')
expect(mainWindow.webContents.send).toHaveBeenCalledWith('worktrees:changed', {
repoId: 'repo-1'
})
})
})
17 changes: 17 additions & 0 deletions src/main/ipc/worktrees.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -112,6 +112,7 @@ vi.mock('electron', () => ({

vi.mock('../git/worktree', () => ({
listWorktrees: listWorktreesMock,
listWorktreesStrict: listWorktreesMock,
parseWorktreeList: parseWorktreeListMock,
assertWorktreeCleanForRemoval: assertWorktreeCleanForRemovalMock,
addWorktree: addWorktreeMock,
Expand Down Expand Up @@ -6232,6 +6233,22 @@ describe('registerWorktreeHandlers', () => {
)
})

it('surfaces selected-runtime list failures during local worktree removal', async () => {
mockSelectedWslProjectRuntime()
const listError = new Error('wsl git list failed')
listWorktreesMock.mockRejectedValue(listError)

await expect(
handlers['worktrees:remove'](null, {
worktreeId: 'repo-1::/workspace/feature-wt'
})
).rejects.toThrow('wsl git list failed')

expect(listWorktreesMock).toHaveBeenCalledWith('/workspace/repo', { wslDistro: 'Ubuntu' })
expect(assertWorktreeCleanForRemovalMock).not.toHaveBeenCalled()
expect(removeWorktreeMock).not.toHaveBeenCalled()
})

it('fails dirty non-force deletes before PTY teardown', async () => {
mockKnownFeatureWorktree()
getEffectiveHooksMock.mockReturnValue(null)
Expand Down
Loading
Loading