diff --git a/docs/non-git-folder-support-plan.md b/docs/non-git-folder-support-plan.md new file mode 100644 index 000000000..027787015 --- /dev/null +++ b/docs/non-git-folder-support-plan.md @@ -0,0 +1,365 @@ +# Non-Git Folder Support Plan + +## Summary + +Orca should support opening non-git folders in a limited "folder mode" so users can still use: + +- terminal +- file explorer +- editor +- search +- quick open + +Git-dependent features should remain unavailable in this mode: + +- creating worktrees +- removing git worktrees +- source control +- branch/base-ref workflows +- pull request and checks integrations + +The recommended implementation is to model a non-git folder as a repo with exactly one synthetic worktree representing the folder itself. + +## Product Model + +### Repo Types + +Introduce two repo modes: + +- `git` +- `folder` + +This can be stored directly on `Repo`, for example as `kind: 'git' | 'folder'`. + +Why: Orca currently assumes every connected repo can enumerate git worktrees and branch metadata. Making repo type explicit lets the UI and IPC handlers suppress git-only functionality without scattered heuristics. + +### Synthetic Worktree for Folder Mode + +For a non-git folder, Orca should synthesize exactly one worktree-like entry: + +- `path = repo.path` +- `displayName = repo.displayName` +- `isMainWorktree = true` +- `branch = ''` +- `head = ''` +- `isBare = false` + +The worktree ID can remain `${repo.id}::${repo.path}` to preserve the existing store shape. + +This ID contract should be treated as stable for folder mode. + +Why: much of the app is worktree-centric. Reusing the existing worktree abstraction is less invasive than teaching the editor, terminal, explorer, quick-open, and selection state to operate without any worktree at all. + +## User Experience + +### On Add / Load Attempt + +When a selected folder is not a git repo, Orca should show a confirmation dialog instead of hard-failing: + +- Title: `Open as Folder?` +- Body: `This folder is not a Git repository. Orca can open it for editing, terminal, and search, but Git-based features like worktrees, source control, pull requests, and checks will be unavailable.` +- Actions: + - `Open Folder` + - `Cancel` + - optional: `Initialize Git Instead` + +Why: users need to understand the capability downgrade before the folder is added to the workspace. + +### Left Sidebar + +A folder-mode repo should appear in the same left sidebar structure as existing repos, with one row underneath it: + +- repo row +- one synthetic worktree row representing the folder + +Recommended indicator: + +- repo badge or row badge: `Folder` or `Non-Git` + +The synthetic row should use a folder-specific subtitle treatment instead of an empty branch slot. + +Recommendation: + +- primary label: folder display name +- subtitle: `Folder` or a short path label + +Do not style this as an error. It is a supported limited mode, not a broken state. + +### Disabled / Hidden Git Features + +Git-only features should either be hidden or disabled with an explanation. + +Recommended behavior: + +- `Create Worktree`: disabled or hidden for folder-mode repos +- `Delete Worktree`: do not reuse worktree-delete semantics for folder-mode rows +- Source Control tab: show inline empty state explaining git is required +- Checks tab: show inline empty state explaining a git branch / PR context is required +- branch/base-ref settings: hidden or disabled with explanation + +Why: silent disappearance can feel broken. When users intentionally open a folder, the app should explain why a git surface is unavailable. + +### Remove vs Delete Semantics + +Folder mode must not reuse the current worktree deletion flow. + +Recommendation: + +- folder-mode row action: `Remove Folder from Orca` +- git worktree row action: `Delete Worktree` + +Why: for real git worktrees, the current delete flow can remove filesystem content as part of worktree cleanup. Reusing that path for a synthetic folder row would be unsafe because users may intend to disconnect the folder from Orca, not delete the folder tree from disk. + +### Settings Page + +Keep folder-mode entries in the existing `Repositories` settings list, but show a type label: + +- `Git` +- `Folder` + +For folder-mode entries, keep generic settings: + +- display name +- badge color +- remove from Orca + +Hide or disable git-specific settings: + +- default worktree base +- base ref picker/search +- branch-related settings +- PR/check-related settings + +Recommended note near the top of a folder-mode settings card: + +`Opened as folder. Git features are unavailable for this workspace.` + +Why: the Settings page is where users will verify what Orca thinks this connected root is. The settings surface must stay consistent with the sidebar and runtime behavior. + +The settings view should also skip eager git-specific checks for folder-mode repos, including hook-related checks unless folder hooks are explicitly supported. + +## Functional Scope + +### Should Work in Folder Mode + +- add folder to Orca +- select the folder entry in the sidebar +- open terminal in that folder +- browse files +- read and edit files +- search files +- quick open files +- open external files within the authorized folder root +- restore terminal/editor session state against the synthetic worktree across app restarts + +### Should Not Work in Folder Mode + +- create additional worktrees +- remove git worktrees +- branch naming flows +- base branch selection +- git status / diff / stage / unstage / discard +- conflict and rebase state +- PR linking based on branch identity +- checks derived from PR head / branch +- git polling / refresh loops for source-control state + +## Implementation Outline + +### 1. Add Repo Type + +Update the shared repo type to distinguish git repos from folder-mode repos. + +Potential shape: + +```ts +type Repo = { + id: string + path: string + displayName: string + badgeColor: string + addedAt: number + kind?: 'git' | 'folder' + gitUsername?: string + worktreeBaseRef?: string + hookSettings?: RepoHookSettings +} +``` + +Why: existing persisted data may not have this field, so `git` should be treated as the default for backward compatibility. + +### 2. Change Add-Repo Flow + +Current behavior rejects non-git folders. + +New behavior: + +- detect whether selected path is git +- if yes, add as `kind: 'git'` +- if no, ask for confirmation and add as `kind: 'folder'` if accepted + +This applies to: + +- renderer add flow +- main-process `repos:add` +- runtime/CLI add flow if it should support folders too + +### 3. Synthesize a Worktree for Folder Repos + +Update worktree listing so folder-mode repos return a single synthetic worktree instead of `[]`. + +This should apply to: + +- `worktrees:list` +- `worktrees:listAll` +- any runtime-managed worktree listing APIs + +Why: the app currently gates most of the workspace UI on `activeWorktreeId`. Returning no worktrees leaves the app stuck on the landing state even though the filesystem APIs could operate on the folder. + +The synthetic worktree ID must be deterministic across restarts so session restore can reattach tabs, active selection, and terminal state correctly. + +### 4. Suppress Git-Only Mutations + +Guard git-only IPC and UI entry points for folder-mode repos: + +- worktree creation +- worktree removal +- source control actions +- base ref queries/search +- branch-based PR/check flows where appropriate +- git status polling / conflict polling / branch compare refresh loops + +These guards should fail clearly with a user-facing explanation when reached. + +This must cover all create-worktree entry points, not just one visible button: + +- landing page CTA +- keyboard shortcut +- add-worktree dialog repo picker / submit path +- any runtime or CLI create path that remains exposed + +### 5. Update Sidebar and Settings Presentation + +Add a neutral repo-type indicator in: + +- left sidebar +- settings repo cards + +Ensure git-only controls are hidden or disabled for folder mode. + +### 6. Handle Search / Quick Open Fallbacks + +Quick open and text search currently fall back to git-based commands when `rg` is unavailable. + +Folder-mode support needs one of these decisions: + +1. Require `rg` for folder mode and surface a clear error when it is unavailable. +2. Add non-git filesystem fallbacks for file listing and text search. + +Recommendation: start with option 1 if we want a smaller implementation. + +Why: the product value of folder mode is mainly unlocked on machines where `rg` exists. Non-git fallback walkers/searchers can be added later if needed. + +If option 1 is chosen, the product should surface this clearly as a limitation rather than failing silently into empty quick-open or search results. + +## Open Questions + +### Hooks + +Should `orca.yaml` hooks work for folder-mode repos? + +Recommendation: do not include them in the initial scope unless there is a strong use case. + +Reasoning: current hook behavior is designed around worktree creation/archive lifecycle, which folder mode does not have. + +### CLI Semantics + +Should the runtime/CLI also allow adding folder-mode repos, or should folder mode be UI-only at first? + +Recommendation: keep CLI behavior aligned with the UI if feasible, but this can be phased. + +If folder mode is UI-only initially, runtime and CLI commands should fail with an explicit folder-mode / unsupported message rather than the generic `Not a valid git repository`. + +### Naming + +Should the product call these `folders`, `workspaces`, or still `repositories`? + +Recommendation: keep the top-level Settings section as `Repositories`, but label each entry as `Git` or `Folder`. + +## Recommended Initial Scope + +Ship the smallest coherent version: + +- allow adding non-git folders +- show one synthetic worktree row per folder +- allow terminal, explorer, editor, search, and quick open +- show a persistent `Folder` indicator +- disable or hide git-only functionality +- document that worktrees, source control, PRs, and checks are unavailable + +This provides immediate utility without trying to redefine Orca's core worktree-oriented architecture. + +## Risks and Gaps + +### Unsafe Deletion Path + +The current worktree delete path should not be reused for folder mode. + +Why: deleting a synthetic folder row via worktree removal semantics could remove the real folder contents from disk instead of just disconnecting it from Orca. + +### Incomplete Create-Worktree Suppression + +Worktree creation must be blocked at every entry point. + +Why: if only one button is hidden, users can still reach the flow through shortcuts, the landing page, dialogs, or runtime/CLI paths and hit confusing git-only failures. + +### Background Git Polling + +Folder mode must opt out of git polling loops. + +Why: repeated git status/conflict polling against a non-git folder would create noisy logs, unnecessary subprocess churn, and avoidable UI work. + +### Stable Synthetic Identity + +Synthetic worktree IDs must remain deterministic. + +Why: session restore keys open tabs, active selection, and terminal reattachment off worktree identity. + +### Sidebar Presentation + +Folder rows need intentional presentation rather than inheriting blank branch UI. + +Why: a technically valid row with no branch text will look unfinished and make the mode feel accidental. + +### Settings / Hooks Ambiguity + +Folder-mode settings must not eagerly present or execute git-specific controls/checks. + +Why: the settings surface is the canonical place where users verify the capabilities of a connected root. + +### Runtime / CLI Divergence + +Folder support needs an explicit cross-surface decision. + +Why: allowing folders in the UI but rejecting them in runtime/CLI without a clear explanation will create inconsistent product behavior. + +### `rg` as a Practical Requirement + +Folder mode depends on `rg` unless non-git fallbacks are added for quick-open and search. + +Why: current fallback implementations use `git ls-files` and `git grep`, which do not work for non-git folders. + +## Test Checklist + +- add-folder confirmation flow +- persisted repo kind / backward compatibility +- synthetic worktree listing for folder repos +- deterministic synthetic worktree ID across restarts +- folder-mode session restore +- folder row uses `Remove Folder from Orca`, not worktree delete semantics +- create-worktree entry points are all gated for folder repos +- git polling is suppressed for folder repos +- settings sections are gated by repo kind +- folder sidebar row renders a non-branch subtitle +- runtime/CLI behavior is explicit for folder repos +- `rg`-missing behavior is covered for folder mode diff --git a/src/main/ipc/filesystem-auth.ts b/src/main/ipc/filesystem-auth.ts index bbaab70fa..987c03e47 100644 --- a/src/main/ipc/filesystem-auth.ts +++ b/src/main/ipc/filesystem-auth.ts @@ -1,7 +1,7 @@ import { realpath } from 'fs/promises' import { resolve, relative, dirname, basename, isAbsolute } from 'path' import type { Store } from '../persistence' -import { listWorktrees } from '../git/worktree' +import { listRepoWorktrees } from '../repo-worktrees' export const PATH_ACCESS_DENIED_MESSAGE = 'Access denied: path resolves outside allowed directories. If this blocks a legitimate workflow, please file a GitHub issue.' @@ -68,7 +68,7 @@ export async function rebuildAuthorizedRootsCache(store: Store): Promise { try { nextRoots.add(await normalizeExistingPath(repo.path)) - const worktrees = await listWorktrees(repo.path) + const worktrees = await listRepoWorktrees(repo) for (const worktree of worktrees) { nextRoots.add(await normalizeExistingPath(worktree.path)) } diff --git a/src/main/ipc/repos.ts b/src/main/ipc/repos.ts index 4026fe356..a1f7c24df 100644 --- a/src/main/ipc/repos.ts +++ b/src/main/ipc/repos.ts @@ -3,6 +3,7 @@ import { dialog, ipcMain } from 'electron' import { randomUUID } from 'crypto' import type { Store } from '../persistence' import type { Repo } from '../../shared/types' +import { isFolderRepo } from '../../shared/repo-kind' import { REPO_COLORS } from '../../shared/constants' import { rebuildAuthorizedRootsCache } from './filesystem-auth' import { @@ -29,8 +30,9 @@ export function registerRepoHandlers(mainWindow: BrowserWindow, store: Store): v return store.getRepos() }) - ipcMain.handle('repos:add', async (_event, args: { path: string }) => { - if (!isGitRepo(args.path)) { + ipcMain.handle('repos:add', async (_event, args: { path: string; kind?: 'git' | 'folder' }) => { + const repoKind = args.kind === 'folder' ? 'folder' : 'git' + if (repoKind === 'git' && !isGitRepo(args.path)) { throw new Error(`Not a valid git repository: ${args.path}`) } @@ -45,7 +47,8 @@ export function registerRepoHandlers(mainWindow: BrowserWindow, store: Store): v path: args.path, displayName: getRepoName(args.path), badgeColor: REPO_COLORS[store.getRepos().length % REPO_COLORS.length], - addedAt: Date.now() + addedAt: Date.now(), + kind: repoKind } store.addRepo(repo) @@ -67,7 +70,7 @@ export function registerRepoHandlers(mainWindow: BrowserWindow, store: Store): v args: { repoId: string updates: Partial< - Pick + Pick > } ) => { @@ -91,7 +94,7 @@ export function registerRepoHandlers(mainWindow: BrowserWindow, store: Store): v ipcMain.handle('repos:getGitUsername', (_event, args: { repoId: string }) => { const repo = store.getRepo(args.repoId) - if (!repo) { + if (!repo || isFolderRepo(repo)) { return '' } return getGitUsername(repo.path) @@ -99,7 +102,7 @@ export function registerRepoHandlers(mainWindow: BrowserWindow, store: Store): v ipcMain.handle('repos:getBaseRefDefault', async (_event, args: { repoId: string }) => { const repo = store.getRepo(args.repoId) - if (!repo) { + if (!repo || isFolderRepo(repo)) { return 'origin/main' } return getBaseRefDefault(repo.path) @@ -109,7 +112,7 @@ export function registerRepoHandlers(mainWindow: BrowserWindow, store: Store): v 'repos:searchBaseRefs', async (_event, args: { repoId: string; query: string; limit?: number }) => { const repo = store.getRepo(args.repoId) - if (!repo) { + if (!repo || isFolderRepo(repo)) { return [] } return searchBaseRefs(repo.path, args.query, args.limit ?? 25) diff --git a/src/main/ipc/worktree-logic.ts b/src/main/ipc/worktree-logic.ts index dff0d3742..b7945f36e 100644 --- a/src/main/ipc/worktree-logic.ts +++ b/src/main/ipc/worktree-logic.ts @@ -111,7 +111,8 @@ export function shouldSetDisplayName( export function mergeWorktree( repoId: string, git: GitWorktreeInfo, - meta: WorktreeMeta | undefined + meta: WorktreeMeta | undefined, + defaultDisplayName?: string ): Worktree { const branchShort = git.branch.replace(/^refs\/heads\//, '') return { @@ -122,7 +123,7 @@ export function mergeWorktree( branch: git.branch, isBare: git.isBare, isMainWorktree: git.isMainWorktree, - displayName: meta?.displayName || branchShort || basename(git.path), + displayName: meta?.displayName || branchShort || defaultDisplayName || basename(git.path), comment: meta?.comment || '', linkedIssue: meta?.linkedIssue ?? null, linkedPR: meta?.linkedPR ?? null, diff --git a/src/main/ipc/worktrees.test.ts b/src/main/ipc/worktrees.test.ts index 26faf9b07..8dfbd05c4 100644 --- a/src/main/ipc/worktrees.test.ts +++ b/src/main/ipc/worktrees.test.ts @@ -1,3 +1,4 @@ +/* eslint-disable max-lines */ import { beforeEach, describe, expect, it, vi } from 'vitest' const { @@ -206,6 +207,42 @@ describe('registerWorktreeHandlers', () => { expect(addWorktreeMock).not.toHaveBeenCalled() }) + it('lists a synthetic worktree for folder-mode repos', async () => { + store.getRepos.mockReturnValue([ + { + id: 'repo-1', + path: '/workspace/folder', + displayName: 'folder', + badgeColor: '#000', + addedAt: 0, + kind: 'folder' + } + ]) + store.getRepo.mockReturnValue({ + id: 'repo-1', + path: '/workspace/folder', + displayName: 'folder', + badgeColor: '#000', + addedAt: 0, + kind: 'folder' + }) + + const listed = await handlers['worktrees:list'](null, { repoId: 'repo-1' }) + + expect(listed).toEqual([ + expect.objectContaining({ + id: 'repo-1::/workspace/folder', + repoId: 'repo-1', + path: '/workspace/folder', + displayName: 'folder', + branch: '', + head: '', + isMainWorktree: true + }) + ]) + expect(listWorktreesMock).not.toHaveBeenCalled() + }) + it('rejects worktree creation when the branch name already belongs to a PR', async () => { getPRForBranchMock.mockResolvedValue({ number: 3127, diff --git a/src/main/ipc/worktrees.ts b/src/main/ipc/worktrees.ts index 9a0cc2597..b070656d6 100644 --- a/src/main/ipc/worktrees.ts +++ b/src/main/ipc/worktrees.ts @@ -3,6 +3,7 @@ import { ipcMain } from 'electron' import { execFileSync } from 'child_process' import { rm } from 'fs/promises' import type { Store } from '../persistence' +import { isFolderRepo } from '../../shared/repo-kind' import type { CreateWorktreeArgs, CreateWorktreeResult, @@ -12,6 +13,7 @@ import type { import { getPRForBranch } from '../github/client' import { listWorktrees, addWorktree, removeWorktree } from '../git/worktree' import { getGitUsername, getDefaultBaseRef, getBranchConflictKind } from '../git/repo' +import { listRepoWorktrees } from '../repo-worktrees' import { createSetupRunnerScript, getEffectiveHooks, @@ -54,11 +56,11 @@ export function registerWorktreeHandlers(mainWindow: BrowserWindow, store: Store const allWorktrees: Worktree[] = [] for (const repo of repos) { - const gitWorktrees = await listWorktrees(repo.path) + const gitWorktrees = await listRepoWorktrees(repo) for (const gw of gitWorktrees) { const worktreeId = `${repo.id}::${gw.path}` const meta = store.getWorktreeMeta(worktreeId) - allWorktrees.push(mergeWorktree(repo.id, gw, meta)) + allWorktrees.push(mergeWorktree(repo.id, gw, meta, repo.displayName)) } } @@ -75,11 +77,11 @@ export function registerWorktreeHandlers(mainWindow: BrowserWindow, store: Store return [] } - const gitWorktrees = await listWorktrees(repo.path) + const gitWorktrees = await listRepoWorktrees(repo) return gitWorktrees.map((gw) => { const worktreeId = `${repo.id}::${gw.path}` const meta = store.getWorktreeMeta(worktreeId) - return mergeWorktree(repo.id, gw, meta) + return mergeWorktree(repo.id, gw, meta, repo.displayName) }) }) @@ -90,6 +92,9 @@ export function registerWorktreeHandlers(mainWindow: BrowserWindow, store: Store if (!repo) { throw new Error(`Repo not found: ${args.repoId}`) } + if (isFolderRepo(repo)) { + throw new Error('Folder mode does not support creating worktrees.') + } const settings = store.getSettings() @@ -206,6 +211,9 @@ export function registerWorktreeHandlers(mainWindow: BrowserWindow, store: Store if (!repo) { throw new Error(`Repo not found: ${repoId}`) } + if (isFolderRepo(repo)) { + throw new Error('Folder mode does not support deleting worktrees.') + } // Run archive hook before removal const hooks = getEffectiveHooks(repo) @@ -272,7 +280,7 @@ export function registerWorktreeHandlers(mainWindow: BrowserWindow, store: Store ipcMain.handle('hooks:check', (_event, args: { repoId: string }) => { const repo = store.getRepo(args.repoId) - if (!repo) { + if (!repo || isFolderRepo(repo)) { return { hasHooks: false, hooks: null } } diff --git a/src/main/persistence.ts b/src/main/persistence.ts index 133e55e6f..ff0d73465 100644 --- a/src/main/persistence.ts +++ b/src/main/persistence.ts @@ -3,6 +3,7 @@ import { readFileSync, writeFileSync, mkdirSync, existsSync, renameSync } from ' import { join, dirname } from 'path' import { homedir } from 'os' import type { PersistedState, Repo, WorktreeMeta, GlobalSettings } from '../shared/types' +import { isFolderRepo } from '../shared/repo-kind' import { getGitUsername } from './git/repo' import { getDefaultPersistedState, @@ -146,7 +147,9 @@ export class Store { updateRepo( id: string, - updates: Partial> + updates: Partial< + Pick + > ): Repo | null { const repo = this.state.repos.find((r) => r.id === id) if (!repo) { @@ -158,16 +161,18 @@ export class Store { } private hydrateRepo(repo: Repo): Repo { - const gitUsername = - this.gitUsernameCache.get(repo.path) ?? - (() => { - const username = getGitUsername(repo.path) - this.gitUsernameCache.set(repo.path, username) - return username - })() + const gitUsername = isFolderRepo(repo) + ? '' + : (this.gitUsernameCache.get(repo.path) ?? + (() => { + const username = getGitUsername(repo.path) + this.gitUsernameCache.set(repo.path, username) + return username + })()) return { ...repo, + kind: isFolderRepo(repo) ? 'folder' : 'git', gitUsername, hookSettings: { ...getDefaultRepoHookSettings(), diff --git a/src/main/repo-worktrees.test.ts b/src/main/repo-worktrees.test.ts new file mode 100644 index 000000000..8e3c613ef --- /dev/null +++ b/src/main/repo-worktrees.test.ts @@ -0,0 +1,76 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest' + +const { listWorktreesMock } = vi.hoisted(() => ({ + listWorktreesMock: vi.fn() +})) + +vi.mock('./git/worktree', () => ({ + listWorktrees: listWorktreesMock +})) + +import { createFolderWorktree, listRepoWorktrees } from './repo-worktrees' + +describe('repo-worktrees', () => { + beforeEach(() => { + listWorktreesMock.mockReset() + }) + + it('creates a stable synthetic worktree for folder repos', () => { + expect( + createFolderWorktree({ + id: 'repo-1', + path: '/workspace/folder', + displayName: 'folder', + badgeColor: '#000', + addedAt: 0, + kind: 'folder' + }) + ).toEqual({ + path: '/workspace/folder', + head: '', + branch: '', + isBare: false, + isMainWorktree: true + }) + }) + + it('returns the synthetic folder worktree instead of shelling out to git', async () => { + const result = await listRepoWorktrees({ + id: 'repo-1', + path: '/workspace/folder', + displayName: 'folder', + badgeColor: '#000', + addedAt: 0, + kind: 'folder' + }) + + expect(result).toEqual([ + { + path: '/workspace/folder', + head: '', + branch: '', + isBare: false, + isMainWorktree: true + } + ]) + expect(listWorktreesMock).not.toHaveBeenCalled() + }) + + it('delegates to git worktree listing for git repos', async () => { + listWorktreesMock.mockResolvedValue([ + { path: '/workspace/repo', head: 'abc', branch: '', isBare: false, isMainWorktree: true } + ]) + + const result = await listRepoWorktrees({ + id: 'repo-1', + path: '/workspace/repo', + displayName: 'repo', + badgeColor: '#000', + addedAt: 0, + kind: 'git' + }) + + expect(listWorktreesMock).toHaveBeenCalledWith('/workspace/repo') + expect(result).toHaveLength(1) + }) +}) diff --git a/src/main/repo-worktrees.ts b/src/main/repo-worktrees.ts new file mode 100644 index 000000000..5ccb91123 --- /dev/null +++ b/src/main/repo-worktrees.ts @@ -0,0 +1,23 @@ +import type { GitWorktreeInfo, Repo } from '../shared/types' +import { listWorktrees } from './git/worktree' +import { isFolderRepo } from '../shared/repo-kind' + +export function createFolderWorktree(repo: Repo): GitWorktreeInfo { + return { + path: repo.path, + head: '', + branch: '', + isBare: false, + // Why: folder mode has no linked worktree graph. Treat the folder itself + // as the single primary worktree so the rest of Orca's worktree-first UI + // can keep using one stable workspace identity. + isMainWorktree: true + } +} + +export async function listRepoWorktrees(repo: Repo): Promise { + if (isFolderRepo(repo)) { + return [createFolderWorktree(repo)] + } + return await listWorktrees(repo.path) +} diff --git a/src/main/runtime/orca-runtime.ts b/src/main/runtime/orca-runtime.ts index 83ad8ff91..eb4110d67 100644 --- a/src/main/runtime/orca-runtime.ts +++ b/src/main/runtime/orca-runtime.ts @@ -5,6 +5,7 @@ import { execFileSync } from 'child_process' import { randomUUID } from 'crypto' import { rm } from 'fs/promises' import type { CreateWorktreeResult, Repo } from '../../shared/types' +import { isFolderRepo } from '../../shared/repo-kind' import type { RuntimeGraphStatus, RuntimeRepoSearchRefs, @@ -22,13 +23,19 @@ import type { RuntimeSyncWindowGraph, RuntimeWorktreeListResult } from '../../shared/runtime-types' -import { listWorktrees } from '../git/worktree' import { getPRForBranch } from '../github/client' -import { getGitUsername, getDefaultBaseRef, getBranchConflictKind } from '../git/repo' -import { addWorktree, removeWorktree } from '../git/worktree' +import { + getGitUsername, + getDefaultBaseRef, + getBranchConflictKind, + isGitRepo, + getRepoName, + searchBaseRefs +} from '../git/repo' +import { listWorktrees, addWorktree, removeWorktree } from '../git/worktree' import { createSetupRunnerScript, getEffectiveHooks, runHook } from '../hooks' import { REPO_COLORS } from '../../shared/constants' -import { isGitRepo, getRepoName, searchBaseRefs } from '../git/repo' +import { listRepoWorktrees } from '../repo-worktrees' import type { Store } from '../persistence' import { computeBranchName, @@ -456,11 +463,11 @@ export class OrcaRuntimeService { return this.store?.getRepos() ?? [] } - async addRepo(path: string): Promise { + async addRepo(path: string, kind: 'git' | 'folder' = 'git'): Promise { if (!this.store) { throw new Error('runtime_unavailable') } - if (!isGitRepo(path)) { + if (kind === 'git' && !isGitRepo(path)) { throw new Error(`Not a valid git repository: ${path}`) } @@ -474,7 +481,8 @@ export class OrcaRuntimeService { path, displayName: getRepoName(path), badgeColor: REPO_COLORS[this.store.getRepos().length % REPO_COLORS.length], - addedAt: Date.now() + addedAt: Date.now(), + kind } this.store.addRepo(repo) this.invalidateResolvedWorktreeCache() @@ -491,6 +499,9 @@ export class OrcaRuntimeService { throw new Error('runtime_unavailable') } const repo = await this.resolveRepoSelector(repoSelector) + if (isFolderRepo(repo)) { + throw new Error('Folder mode does not support base refs.') + } const updated = this.store.updateRepo(repo.id, { worktreeBaseRef: baseRef }) if (!updated) { throw new Error('repo_not_found') @@ -509,6 +520,12 @@ export class OrcaRuntimeService { throw new Error('invalid_limit') } const repo = await this.resolveRepoSelector(repoSelector) + if (isFolderRepo(repo)) { + return { + refs: [], + truncated: false + } + } const refs = await searchBaseRefs(repo.path, query, limit + 1) return { refs: refs.slice(0, limit), @@ -549,6 +566,9 @@ export class OrcaRuntimeService { } const repo = await this.resolveRepoSelector(args.repoSelector) + if (isFolderRepo(repo)) { + throw new Error('Folder mode does not support creating worktrees.') + } const settings = this.store.getSettings() const requestedName = args.name const sanitizedName = sanitizeWorktreeName(args.name) @@ -678,6 +698,9 @@ export class OrcaRuntimeService { if (!repo) { throw new Error('repo_not_found') } + if (isFolderRepo(repo)) { + throw new Error('Folder mode does not support deleting worktrees.') + } const hooks = getEffectiveHooks(repo) if (hooks?.scripts.archive) { @@ -868,10 +891,10 @@ export class OrcaRuntimeService { const metaById = this.store.getAllWorktreeMeta() const worktrees: ResolvedWorktree[] = [] for (const repo of this.store.getRepos()) { - const gitWorktrees = await listWorktrees(repo.path) + const gitWorktrees = await listRepoWorktrees(repo) for (const gitWorktree of gitWorktrees) { const worktreeId = `${repo.id}::${gitWorktree.path}` - const merged = mergeWorktree(repo.id, gitWorktree, metaById[worktreeId]) + const merged = mergeWorktree(repo.id, gitWorktree, metaById[worktreeId], repo.displayName) worktrees.push({ id: merged.id, repoId: repo.id, diff --git a/src/preload/index.d.ts b/src/preload/index.d.ts index e309d4ec0..d8bdc5bbd 100644 --- a/src/preload/index.d.ts +++ b/src/preload/index.d.ts @@ -27,11 +27,13 @@ import type { RuntimeStatus, RuntimeSyncWindowGraph } from '../../shared/runtime type ReposApi = { list: () => Promise - add: (args: { path: string }) => Promise + add: (args: { path: string; kind?: 'git' | 'folder' }) => Promise remove: (args: { repoId: string }) => Promise update: (args: { repoId: string - updates: Partial> + updates: Partial< + Pick + > }) => Promise pickFolder: () => Promise getGitUsername: (args: { repoId: string }) => Promise diff --git a/src/preload/index.ts b/src/preload/index.ts index a11b20e63..167461c77 100644 --- a/src/preload/index.ts +++ b/src/preload/index.ts @@ -97,7 +97,8 @@ const api = { repos: { list: (): Promise => ipcRenderer.invoke('repos:list'), - add: (args: { path: string }): Promise => ipcRenderer.invoke('repos:add', args), + add: (args: { path: string; kind?: 'git' | 'folder' }): Promise => + ipcRenderer.invoke('repos:add', args), remove: (args: { repoId: string }): Promise => ipcRenderer.invoke('repos:remove', args), diff --git a/src/renderer/src/App.tsx b/src/renderer/src/App.tsx index 4e94ffc8d..28505acb8 100644 --- a/src/renderer/src/App.tsx +++ b/src/renderer/src/App.tsx @@ -1,6 +1,7 @@ /* eslint-disable max-lines */ import { useEffect } from 'react' import { DEFAULT_WORKTREE_CARD_PROPERTIES } from '../../shared/constants' +import { isGitRepoKind } from '../../shared/repo-kind' import { Minimize2, PanelLeft, PanelRight } from 'lucide-react' import { TOGGLE_TERMINAL_PANE_EXPAND_EVENT } from '@/constants/terminal' @@ -430,7 +431,7 @@ function App(): React.JSX.Element { // Cmd/Ctrl+N — create worktree if (!e.altKey && !e.shiftKey && e.key.toLowerCase() === 'n') { - if (repos.length === 0) { + if (!repos.some((repo) => isGitRepoKind(repo))) { return } e.preventDefault() @@ -468,7 +469,7 @@ function App(): React.JSX.Element { activeView, activeWorktreeId, openModal, - repos.length, + repos, toggleSidebar, toggleRightSidebar, setRightSidebarTab, diff --git a/src/renderer/src/components/Landing.tsx b/src/renderer/src/components/Landing.tsx index f927737f7..5cac0dd33 100644 --- a/src/renderer/src/components/Landing.tsx +++ b/src/renderer/src/components/Landing.tsx @@ -2,6 +2,7 @@ import { useEffect, useMemo, useState } from 'react' import { AlertTriangle, ExternalLink, FolderPlus, GitBranchPlus, Star } from 'lucide-react' import { cn } from '../lib/utils' import { useAppStore } from '../store' +import { isGitRepoKind } from '../../../shared/repo-kind' import logo from '../../../../resources/logo.svg' type ShortcutItem = { @@ -119,7 +120,7 @@ export default function Landing(): React.JSX.Element { const addRepo = useAppStore((s) => s.addRepo) const openModal = useAppStore((s) => s.openModal) - const canCreateWorktree = repos.length > 0 + const canCreateWorktree = repos.some((repo) => isGitRepoKind(repo)) const [preflightIssues, setPreflightIssues] = useState([]) @@ -137,7 +138,8 @@ export default function Landing(): React.JSX.Element { issues.push({ id: 'git', title: 'Git is not installed', - description: 'Orca requires Git to manage repositories and worktrees.', + description: + 'Git is required for Git repositories, source control, and worktree management.', fixLabel: 'Install Git', fixUrl: 'https://git-scm.com/downloads' }) @@ -212,7 +214,7 @@ export default function Landing(): React.JSX.Element { + + + + + ) +}) + +export default NonGitFolderDialog diff --git a/src/renderer/src/components/sidebar/RemoveFolderDialog.tsx b/src/renderer/src/components/sidebar/RemoveFolderDialog.tsx new file mode 100644 index 000000000..4e51d1e64 --- /dev/null +++ b/src/renderer/src/components/sidebar/RemoveFolderDialog.tsx @@ -0,0 +1,62 @@ +import React, { useCallback } from 'react' +import { + Dialog, + DialogContent, + DialogDescription, + DialogFooter, + DialogHeader, + DialogTitle +} from '@/components/ui/dialog' +import { Button } from '@/components/ui/button' +import { useAppStore } from '@/store' + +const RemoveFolderDialog = React.memo(function RemoveFolderDialog() { + const activeModal = useAppStore((s) => s.activeModal) + const modalData = useAppStore((s) => s.modalData) + const closeModal = useAppStore((s) => s.closeModal) + const removeRepo = useAppStore((s) => s.removeRepo) + + const isOpen = activeModal === 'confirm-remove-folder' + const repoId = typeof modalData.repoId === 'string' ? modalData.repoId : '' + const displayName = typeof modalData.displayName === 'string' ? modalData.displayName : '' + + const handleConfirm = useCallback(() => { + if (repoId) { + void removeRepo(repoId) + } + closeModal() + }, [closeModal, removeRepo, repoId]) + + const handleOpenChange = useCallback( + (open: boolean) => { + if (!open) { + closeModal() + } + }, + [closeModal] + ) + + return ( + + + + Remove Folder + + Remove {displayName} from + Orca? The folder will not be deleted from disk. + + + + + + + + + ) +}) + +export default RemoveFolderDialog diff --git a/src/renderer/src/components/sidebar/SidebarHeader.tsx b/src/renderer/src/components/sidebar/SidebarHeader.tsx index 960b08cff..f1a9e2865 100644 --- a/src/renderer/src/components/sidebar/SidebarHeader.tsx +++ b/src/renderer/src/components/sidebar/SidebarHeader.tsx @@ -3,6 +3,7 @@ import { Plus, SlidersHorizontal } from 'lucide-react' import { useAppStore } from '@/store' import { Button } from '@/components/ui/button' import { Tooltip, TooltipTrigger, TooltipContent } from '@/components/ui/tooltip' +import { isGitRepoKind } from '../../../../shared/repo-kind' import { DropdownMenu, DropdownMenuContent, @@ -36,7 +37,7 @@ const newWorktreeShortcutLabel = isMac ? '⌘N' : 'Ctrl+N' const SidebarHeader = React.memo(function SidebarHeader() { const openModal = useAppStore((s) => s.openModal) const repos = useAppStore((s) => s.repos) - const canCreateWorktree = repos.length > 0 + const canCreateWorktree = repos.some((repo) => isGitRepoKind(repo)) const worktreeCardProperties = useAppStore((s) => s.worktreeCardProperties) const toggleWorktreeCardProperty = useAppStore((s) => s.toggleWorktreeCardProperty) @@ -121,7 +122,7 @@ const SidebarHeader = React.memo(function SidebarHeader() { {canCreateWorktree ? `New worktree (${newWorktreeShortcutLabel})` - : 'Add a repo to create worktrees'} + : 'Add a Git repo to create worktrees'} diff --git a/src/renderer/src/components/sidebar/WorktreeCard.tsx b/src/renderer/src/components/sidebar/WorktreeCard.tsx index 569ae6037..7e6365966 100644 --- a/src/renderer/src/components/sidebar/WorktreeCard.tsx +++ b/src/renderer/src/components/sidebar/WorktreeCard.tsx @@ -9,6 +9,7 @@ import StatusIndicator from './StatusIndicator' import WorktreeContextMenu from './WorktreeContextMenu' import { cn } from '@/lib/utils' import { detectAgentStatusFromTitle } from '@/lib/agent-status' +import { getRepoKindLabel, isFolderRepo } from '../../../../shared/repo-kind' import type { Worktree, Repo, @@ -135,6 +136,7 @@ const WorktreeCard = React.memo(function WorktreeCard({ const tabs = useAppStore((s) => s.tabsByWorktree[worktree.id] ?? EMPTY_TABS) const branch = branchDisplayName(worktree.branch) + const isFolder = repo ? isFolderRepo(repo) : false const prCacheKey = repo && branch ? `${repo.path}::${branch}` : '' const issueCacheKey = repo && worktree.linkedIssue ? `${repo.path}::${worktree.linkedIssue}` : '' @@ -175,15 +177,15 @@ const WorktreeCard = React.memo(function WorktreeCard({ // This preference is purely presentational, so background refreshes would // spend rate limit budget on data the user cannot see. useEffect(() => { - if (repo && !worktree.isBare && prCacheKey && (showPR || showCI)) { + if (repo && !isFolder && !worktree.isBare && prCacheKey && (showPR || showCI)) { fetchPRForBranch(repo.path, branch) } - }, [repo, worktree.isBare, fetchPRForBranch, branch, prCacheKey, showPR, showCI]) + }, [repo, isFolder, worktree.isBare, fetchPRForBranch, branch, prCacheKey, showPR, showCI]) // Same rationale for issues: once that section is hidden, polling only burns // GitHub calls and keeps stale-but-invisible data warm for no user benefit. useEffect(() => { - if (!repo || !worktree.linkedIssue || !issueCacheKey || !showIssue) { + if (!repo || isFolder || !worktree.linkedIssue || !issueCacheKey || !showIssue) { return } @@ -195,7 +197,7 @@ const WorktreeCard = React.memo(function WorktreeCard({ }, 5 * 60_000) // 5 minutes return () => clearInterval(interval) - }, [repo, worktree.linkedIssue, fetchIssue, issueCacheKey, showIssue]) + }, [repo, isFolder, worktree.linkedIssue, fetchIssue, issueCacheKey, showIssue]) // Stable click handler – ignore clicks that are really text selections const handleClick = useCallback(() => { @@ -329,7 +331,14 @@ const WorktreeCard = React.memo(function WorktreeCard({ )} - {isPrimaryBranch(worktree.branch) ? ( + {isFolder ? ( + + {repo ? getRepoKindLabel(repo) : 'Folder'} + + ) : isPrimaryBranch(worktree.branch) ? ( s.updateWorktreeMeta) const openModal = useAppStore((s) => s.openModal) + const repos = useAppStore((s) => s.repos) const shutdownWorktreeTerminals = useAppStore((s) => s.shutdownWorktreeTerminals) const activeWorktreeId = useAppStore((s) => s.activeWorktreeId) const setActiveWorktree = useAppStore((s) => s.setActiveWorktree) @@ -38,6 +40,8 @@ const WorktreeContextMenu = React.memo(function WorktreeContextMenu({ worktree, const [menuOpen, setMenuOpen] = useState(false) const [menuPoint, setMenuPoint] = useState({ x: 0, y: 0 }) const isDeleting = deleteState?.isDeleting ?? false + const repo = repos.find((entry) => entry.id === worktree.repoId) + const isFolder = repo ? isFolderRepo(repo) : false useEffect(() => { const closeMenu = (): void => setMenuOpen(false) @@ -96,9 +100,26 @@ const WorktreeContextMenu = React.memo(function WorktreeContextMenu({ worktree, const handleDelete = useCallback(() => { setMenuOpen(false) + if (isFolder) { + // Why: folder mode reuses the worktree row UI for a synthetic root entry, + // but users still expect "remove" to disconnect the folder from Orca, + // not to run git-style delete semantics against the real folder on disk. + openModal('confirm-remove-folder', { + repoId: worktree.repoId, + displayName: worktree.displayName + }) + return + } clearWorktreeDeleteState(worktree.id) openModal('delete-worktree', { worktreeId: worktree.id }) - }, [worktree.id, clearWorktreeDeleteState, openModal]) + }, [ + worktree.id, + worktree.repoId, + worktree.displayName, + clearWorktreeDeleteState, + isFolder, + openModal + ]) return ( <> @@ -157,7 +178,7 @@ const WorktreeContextMenu = React.memo(function WorktreeContextMenu({ worktree, - {isDeleting ? 'Deleting…' : 'Delete'} + {isDeleting ? 'Deleting…' : isFolder ? 'Remove Folder from Orca' : 'Delete'} diff --git a/src/renderer/src/components/sidebar/WorktreeList.tsx b/src/renderer/src/components/sidebar/WorktreeList.tsx index a56a9e7a4..bfc2f4f2b 100644 --- a/src/renderer/src/components/sidebar/WorktreeList.tsx +++ b/src/renderer/src/components/sidebar/WorktreeList.tsx @@ -7,6 +7,7 @@ import { Button } from '@/components/ui/button' import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip' import { cn } from '@/lib/utils' import type { Worktree, Repo } from '../../../../shared/types' +import { isGitRepoKind } from '../../../../shared/repo-kind' import { buildWorktreeComparator } from './smart-sort' import { matchesSearch, type Row, buildRows, getGroupKeyForWorktree } from './worktree-list-groups' import { estimateRowHeight } from './worktree-list-estimate' @@ -437,16 +438,19 @@ const WorktreeList = React.memo(function WorktreeList() { onClick={(event) => { event.preventDefault() event.stopPropagation() - if (row.repo) { + if (row.repo && isGitRepoKind(row.repo)) { handleCreateForRepo(row.repo.id) } }} + disabled={row.repo ? !isGitRepoKind(row.repo) : false} > - Create worktree for {row.label} + {row.repo && !isGitRepoKind(row.repo) + ? `${row.label} is opened as a folder` + : `Create worktree for ${row.label}`} ) : null} diff --git a/src/renderer/src/components/sidebar/index.tsx b/src/renderer/src/components/sidebar/index.tsx index 9b3f9dba2..d99430903 100644 --- a/src/renderer/src/components/sidebar/index.tsx +++ b/src/renderer/src/components/sidebar/index.tsx @@ -11,6 +11,8 @@ import SidebarToolbar from './SidebarToolbar' import AddWorktreeDialog from './AddWorktreeDialog' import WorktreeMetaDialog from './WorktreeMetaDialog' import DeleteWorktreeDialog from './DeleteWorktreeDialog' +import NonGitFolderDialog from './NonGitFolderDialog' +import RemoveFolderDialog from './RemoveFolderDialog' const MIN_WIDTH = 220 const MAX_WIDTH = 500 @@ -73,6 +75,8 @@ export default function Sidebar(): React.JSX.Element { + + ) } diff --git a/src/renderer/src/store/slices/repos.ts b/src/renderer/src/store/slices/repos.ts index 9443ecb59..a40a05b60 100644 --- a/src/renderer/src/store/slices/repos.ts +++ b/src/renderer/src/store/slices/repos.ts @@ -2,6 +2,7 @@ import type { StateCreator } from 'zustand' import { toast } from 'sonner' import type { AppState } from '../types' import type { Repo } from '../../../../shared/types' +import { isGitRepoKind } from '../../../../shared/repo-kind' const ERROR_TOAST_DURATION = 60_000 @@ -10,10 +11,13 @@ export type RepoSlice = { activeRepoId: string | null fetchRepos: () => Promise addRepo: () => Promise + addNonGitFolder: (path: string) => Promise removeRepo: (repoId: string) => Promise updateRepo: ( repoId: string, - updates: Partial> + updates: Partial< + Pick + > ) => Promise setActiveRepo: (repoId: string | null) => void } @@ -44,7 +48,22 @@ export const createRepoSlice: StateCreator = (set, if (!path) { return null } - const repo = await window.api.repos.add({ path }) + let repo: Repo + try { + repo = await window.api.repos.add({ path }) + } catch (err) { + const message = err instanceof Error ? err.message : String(err) + if (!message.includes('Not a valid git repository')) { + throw err + } + // Why: folder mode is a capability downgrade, not a silent fallback. + // Show an in-app confirmation dialog so users understand that worktrees, + // SCM, PRs, and checks will be unavailable for this root. The dialog's + // OK handler calls addNonGitFolder to complete the flow. + const { openModal } = get() + openModal('confirm-non-git-folder', { folderPath: path }) + return null + } const alreadyAdded = get().repos.some((r) => r.id === repo.id) set((s) => { if (s.repos.some((r) => r.id === repo.id)) { @@ -55,24 +74,43 @@ export const createRepoSlice: StateCreator = (set, if (alreadyAdded) { toast.info('Repo already added', { description: repo.displayName }) } else { - toast.success('Repo added', { description: repo.displayName }) + toast.success(isGitRepoKind(repo) ? 'Repo added' : 'Folder added', { + description: repo.displayName + }) } return repo } catch (err) { console.error('Failed to add repo:', err) const message = err instanceof Error ? err.message : String(err) const duration = ERROR_TOAST_DURATION - if (message.includes('Not a valid git repository')) { - toast.error('Not a git repository', { - description: 'Only git repositories can be added. Initialize one with git init first.', - duration - }) + toast.error('Failed to add repo', { + description: message, + duration + }) + return null + } + }, + + addNonGitFolder: async (path) => { + try { + const repo = await window.api.repos.add({ path, kind: 'folder' }) + const alreadyAdded = get().repos.some((r) => r.id === repo.id) + set((s) => { + if (s.repos.some((r) => r.id === repo.id)) { + return s + } + return { repos: [...s.repos, repo] } + }) + if (alreadyAdded) { + toast.info('Repo already added', { description: repo.displayName }) } else { - toast.error('Failed to add repo', { - description: message, - duration - }) + toast.success('Folder added', { description: repo.displayName }) } + return repo + } catch (err) { + console.error('Failed to add folder:', err) + const message = err instanceof Error ? err.message : String(err) + toast.error('Failed to add folder', { description: message, duration: ERROR_TOAST_DURATION }) return null } }, diff --git a/src/renderer/src/store/slices/ui.ts b/src/renderer/src/store/slices/ui.ts index 7acaeaa38..74268f6fb 100644 --- a/src/renderer/src/store/slices/ui.ts +++ b/src/renderer/src/store/slices/ui.ts @@ -29,7 +29,13 @@ export type UISlice = { } | null openSettingsTarget: (target: NonNullable) => void clearSettingsTarget: () => void - activeModal: 'none' | 'create-worktree' | 'edit-meta' | 'delete-worktree' + activeModal: + | 'none' + | 'create-worktree' + | 'edit-meta' + | 'delete-worktree' + | 'confirm-non-git-folder' + | 'confirm-remove-folder' modalData: Record openModal: (modal: UISlice['activeModal'], data?: Record) => void closeModal: () => void diff --git a/src/shared/repo-kind.ts b/src/shared/repo-kind.ts new file mode 100644 index 000000000..b5c3946ce --- /dev/null +++ b/src/shared/repo-kind.ts @@ -0,0 +1,17 @@ +import type { Repo } from './types' + +export function getRepoKind(repo: Pick): 'git' | 'folder' { + return repo.kind === 'folder' ? 'folder' : 'git' +} + +export function isFolderRepo(repo: Pick): boolean { + return getRepoKind(repo) === 'folder' +} + +export function isGitRepoKind(repo: Pick): boolean { + return getRepoKind(repo) === 'git' +} + +export function getRepoKindLabel(repo: Pick): string { + return isFolderRepo(repo) ? 'Folder' : 'Git' +} diff --git a/src/shared/types.ts b/src/shared/types.ts index f94a0855c..e7beeaa33 100644 --- a/src/shared/types.ts +++ b/src/shared/types.ts @@ -1,12 +1,15 @@ /* eslint-disable max-lines */ // ─── Repo ──────────────────────────────────────────────────────────── +export type RepoKind = 'git' | 'folder' + export type Repo = { id: string path: string displayName: string badgeColor: string addedAt: number + kind?: RepoKind gitUsername?: string worktreeBaseRef?: string hookSettings?: RepoHookSettings