Skip to content

Beautiful, AI-native markdown IDE and LLM wiki

fix(open-knowledge): worktree groups expand inline (Radix flyout broken on Electron) (#2339)

Andrew Mikofalvy554e42e43596
diff --git a/.changeset/worktree-selector.md b/.changeset/worktree-selector.md
new file mode 100644
index 000000000..f84503bc6
--- /dev/null
+++ b/.changeset/worktree-selector.md
@@ -0,0 +1,5 @@
+---
+"@inkeep/open-knowledge": patch
+---
+
+You can now work on several branches of a project at once, each in its own window. The project switcher in the sidebar footer groups your recent projects by repository: a project with open worktrees expands inline to show them (the current window's project is expanded by default), and typing in the search box matches projects, open worktrees, and the current project's branches. Opening a branch that has no worktree yet creates one on demand. "New worktree" lets you start a fresh branch or check out an existing one, and your worktrees also show up in the Cmd-K command palette. Worktrees are stored inside the project under `.ok/worktrees/` and kept out of git status automatically, so each window stays fully isolated (its own editor and server) without touching your working copy.
diff --git a/packages/app/package.json b/packages/app/package.json
index 7e1e21bb7..5cbea7dc4 100644
--- a/packages/app/package.json
+++ b/packages/app/package.json
@@ -44,14 +44,14 @@
{
"name": "main app bundle (gzipped)",
"path": "dist/assets/index-*.js",
- "limit": "450 kB",
+ "limit": "454 kB",
"gzip": true,
"running": false
},
{
"name": "all JS chunks combined (gzipped)",
"path": "dist/assets/*.js",
- "limit": "3 MB",
+ "limit": "3.05 MB",
"gzip": true,
"running": false
},
diff --git a/packages/app/src/components/CommandPalette.dom.test.tsx b/packages/app/src/components/CommandPalette.dom.test.tsx
index 3bf433a15..d2992e635 100644
--- a/packages/app/src/components/CommandPalette.dom.test.tsx
+++ b/packages/app/src/components/CommandPalette.dom.test.tsx
@@ -183,6 +183,13 @@ mock.module('@/components/command-palette-tag-search', () => ({
fetchDocsForTag: mock(() => Promise.resolve([])),
}));
+let worktreeModelMock: import('@inkeep/open-knowledge-core').WorktreeSelectorModel | null = null;
+mock.module('@/hooks/use-worktrees', () => ({
+ useWorktrees: () => worktreeModelMock,
+}));
+const refreshWorktreesMock = mock(() => {});
+mock.module('@/lib/worktree-store', () => ({ refreshWorktrees: refreshWorktreesMock }));
+
function recent(name: string, path = `/projects/${name.toLowerCase()}`) {
return { name, path: path.replaceAll(' ', '-') };
}
@@ -209,6 +216,15 @@ function createBridge() {
navigator: {
open: mock(() => Promise.resolve()),
},
+ worktree: {
+ create: mock(() =>
+ Promise.resolve({
+ ok: true as const,
+ path: '/projects/current/.ok/worktrees/feature-x',
+ created: true,
+ }),
+ ),
+ },
};
}
@@ -247,6 +263,8 @@ describe('CommandPalette DOM behavior', () => {
createProjectDialogProps = [];
commandDialogProps = [];
refreshInstallStatesCalls = 0;
+ worktreeModelMock = null;
+ refreshWorktreesMock.mockClear();
window.location.hash = '';
globalThis.fetch = mock(() =>
Promise.resolve(new Response(JSON.stringify({ results: [] }), { status: 200 })),
@@ -541,6 +559,64 @@ describe('CommandPalette DOM behavior', () => {
expect(screen.queryByTestId('command-palette-search-preparing')).toBeNull(),
);
});
+
+ test('surfaces worktrees of the current project — opens an existing one and creates one on demand', async () => {
+ worktreeModelMock = {
+ mainRoot: '/projects/current',
+ currentBranch: 'main',
+ entries: [
+ {
+ branch: 'main',
+ worktreePath: '/projects/current',
+ isCurrent: true,
+ isMain: true,
+ locked: false,
+ },
+ {
+ branch: 'dev',
+ worktreePath: '/projects/current/.ok/worktrees/dev',
+ isCurrent: false,
+ isMain: false,
+ locked: false,
+ },
+ {
+ branch: 'feature-x',
+ worktreePath: null,
+ isCurrent: false,
+ isMain: false,
+ locked: false,
+ },
+ ],
+ };
+ const { bridge } = await renderPalette();
+
+ expect(screen.queryByTestId('command-palette-worktree-main')).toBeNull();
+
+ fireEvent.click(screen.getByTestId('command-palette-worktree-dev'));
+ await waitFor(() => {
+ expect(bridge?.project.open).toHaveBeenCalledWith({
+ path: '/projects/current/.ok/worktrees/dev',
+ target: 'new-window',
+ entryPoint: 'worktree',
+ });
+ });
+
+ fireEvent.click(screen.getByTestId('command-palette-worktree-feature-x'));
+ await waitFor(() => {
+ expect(bridge?.worktree.create).toHaveBeenCalledWith({
+ branch: 'feature-x',
+ createBranch: false,
+ });
+ });
+ await waitFor(() => {
+ expect(bridge?.project.open).toHaveBeenCalledWith({
+ path: '/projects/current/.ok/worktrees/feature-x',
+ target: 'new-window',
+ entryPoint: 'worktree',
+ });
+ });
+ expect(refreshWorktreesMock).toHaveBeenCalled();
+ });
});
describe('NavigationItem path subtitle', () => {
diff --git a/packages/app/src/components/CommandPalette.tsx b/packages/app/src/components/CommandPalette.tsx
index b2b1b8cee..76ab0c652 100644
--- a/packages/app/src/components/CommandPalette.tsx
+++ b/packages/app/src/components/CommandPalette.tsx
@@ -1,14 +1,15 @@
// biome-ignore-all lint/plugin/no-raw-html-interactive-element: pre-rule backlog — file uses raw <button>/<input>/<textarea> awaiting shadcn migration; tracked at https://github.com/inkeep/open-knowledge/blob/main/biome-plugins/README.md#no-raw-html-interactive-elementgrit
-import { SHOW_INSTALL_SKILL } from '@inkeep/open-knowledge-core';
+import { SHOW_INSTALL_SKILL, type WorktreeSelectorEntry } from '@inkeep/open-knowledge-core';
import { Plural, Trans, useLingui } from '@lingui/react/macro';
import {
- Box,
Download,
FilePlus2,
FileText,
+ Folder,
FolderOpen,
FolderPlus,
+ GitBranch,
Hash,
LayoutGrid,
Loader2,
@@ -75,6 +76,7 @@ import { useDocumentContext } from '@/editor/DocumentContext';
import type { TagSummaryEntry } from '@/editor/extensions/tag-suggestion';
import { useIsEmbedded } from '@/hooks/use-is-embedded';
import { useSemanticSearchStatus } from '@/hooks/use-semantic-search-status';
+import { useWorktrees } from '@/hooks/use-worktrees';
import type { OkDesktopBridge, RecentProjectEntry } from '@/lib/desktop-bridge-types';
import { hashFromDocName } from '@/lib/doc-hash';
import { runWithToast as runWithToastBase } from '@/lib/error-state';
@@ -84,8 +86,10 @@ import { useSingleFileMode } from '@/lib/single-file-mode';
import { SETTINGS_OPEN_HASH } from '@/lib/use-settings-route';
import { useWorkspace } from '@/lib/use-workspace';
import { cn } from '@/lib/utils.ts';
+import { refreshWorktrees } from '@/lib/worktree-store';
import { buildHandoffInput, useHandoffDispatch } from './handoff/useHandoffDispatch';
import { useInstalledAgents } from './handoff/useInstalledAgents';
+import { basenameOf } from './project-switcher-recents';
const COMMAND_PALETTE_SEARCH_TIMEOUT_MS = 3000;
const COMMAND_PALETTE_SEARCH_WARMING_POLL_MS = 600;
@@ -310,6 +314,11 @@ export function CommandPalette({ bridge = null, open, onOpenChange }: CommandPal
const visibleRecents = filterOmnibarRecents(recentNavigation, validRecentKeys);
const currentPath = bridge?.config.projectPath ?? null;
const switchableProjects = bridge ? projectRecents.filter((row) => row.path !== currentPath) : [];
+ const worktreeModel = useWorktrees();
+ const switchableWorktrees =
+ bridge && worktreeModel
+ ? worktreeModel.entries.filter((entry) => entry.branch !== null && !entry.isCurrent)
+ : [];
const initialCreateDir = resolveCreateInitialDir(activeTarget, activeDocName);
const fallbackSearchResults =
trimmedDeferredQuery === ''
@@ -521,6 +530,31 @@ export function CommandPalette({ bridge = null, open, onOpenChange }: CommandPal
}, fallback);
};
+ const openWorktreeEntry = (entry: WorktreeSelectorEntry) => {
+ if (!bridge) return;
+ const existingPath = entry.worktreePath;
+ if (existingPath !== null) {
+ runAction(
+ () =>
+ bridge.project.open({ path: existingPath, target: 'new-window', entryPoint: 'worktree' }),
+ t`Failed to open worktree.`,
+ );
+ return;
+ }
+ const branch = entry.branch;
+ if (branch === null) return;
+ runAction(async () => {
+ const result = await bridge.worktree.create({ branch, createBranch: false });
+ if (!result.ok) throw new Error(result.reason);
+ refreshWorktrees();
+ await bridge.project.open({
+ path: result.path,
+ target: 'new-window',
+ entryPoint: 'worktree',
+ });
+ }, t`Failed to open worktree.`);
+ };
+
function rememberNavigation(entry: WorkspaceEntry | OmnibarRecentEntry) {
const nextEntry = {
kind: entry.kind,
@@ -604,6 +638,12 @@ export function CommandPalette({ bridge = null, open, onOpenChange }: CommandPal
switchableProjects.some((row) =>
matchesCommandQuery(`${row.name} ${row.path}`, deferredQuery, ['open recent project']),
));
+ const matchedWorktrees = switchableWorktrees.filter(
+ (entry) =>
+ trimmedDeferredQuery === '' ||
+ matchesCommandQuery(entry.branch ?? '', deferredQuery, ['worktree branch']),
+ );
+ const showWorktrees = !inExclusiveMode && bridge !== null && matchedWorktrees.length > 0;
const isEmbedded = useIsEmbedded();
const showAgentGroup =
!inExclusiveMode &&
@@ -1259,40 +1299,73 @@ export function CommandPalette({ bridge = null, open, onOpenChange }: CommandPal
]),
)
.slice(0, 10)
- .map((row) => (
- <CommandItem
- key={row.path}
- value={`${row.name} ${row.path} recent project`}
- disabled={row.missing}
- onSelect={() =>
- runAction(
- () =>
- bridge.project.open({
- path: row.path,
- target: 'new-window',
- entryPoint: 'recents',
- }),
- t`Failed to open project.`,
- )
- }
- data-testid={`command-palette-recent-${row.path}`}
- className="items-start"
- >
- <Box className="mt-0.5" />
- <div className="flex min-w-0 flex-col gap-1">
- <span className="truncate font-medium">{row.name}</span>
- <span className="truncate text-muted-foreground text-xs">
- {row.path}
- {row.missing ? (
- <>
- {' '}
- <Trans>(missing)</Trans>
- </>
+ .map((row) => {
+ const isWorktree = row.isLinkedWorktree === true;
+ const RowIcon = isWorktree ? GitBranch : Folder;
+ const worktreeOf =
+ isWorktree && row.mainRoot !== undefined ? basenameOf(row.mainRoot) : null;
+ return (
+ <CommandItem
+ key={row.path}
+ value={`${row.name} ${row.path} recent project`}
+ disabled={row.missing}
+ onSelect={() =>
+ runAction(
+ () =>
+ bridge.project.open({
+ path: row.path,
+ target: 'new-window',
+ entryPoint: 'recents',
+ }),
+ t`Failed to open project.`,
+ )
+ }
+ data-testid={`command-palette-recent-${row.path}`}
+ className="items-start"
+ >
+ <RowIcon className="mt-0.5" />
+ <div className="flex min-w-0 flex-col gap-1">
+ <span className="truncate font-medium">{row.name}</span>
+ {worktreeOf !== null ? (
+ <span className="truncate text-muted-foreground text-xs">
+ <Trans>worktree of {worktreeOf}</Trans>
+ </span>
) : null}
- </span>
- </div>
- </CommandItem>
- ))}
+ <span className="truncate text-muted-foreground text-xs">
+ {row.path}
+ {row.missing ? (
+ <>
+ {' '}
+ <Trans>(missing)</Trans>
+ </>
+ ) : null}
+ </span>
+ </div>
+ </CommandItem>
+ );
+ })}
+ </CommandGroup>
+ ) : null}
+
+ {showWorktrees && bridge ? (
+ <CommandGroup heading={t`Worktrees`}>
+ {matchedWorktrees.slice(0, 10).map((entry) => (
+ <CommandItem
+ key={entry.branch}
+ value={`${entry.branch} worktree branch`}
+ onSelect={() => openWorktreeEntry(entry)}
+ data-testid={`command-palette-worktree-${entry.branch}`}
+ className="items-start"
+ >
+ <GitBranch className="mt-0.5" />
+ <div className="flex min-w-0 flex-col gap-1">
+ <span className="truncate font-medium">{entry.branch}</span>
+ <span className="truncate text-muted-foreground text-xs">
+ {entry.worktreePath ?? t`Create worktree`}
+ </span>
+ </div>
+ </CommandItem>
+ ))}
</CommandGroup>
) : null}
diff --git a/packages/app/src/components/EditorPane.tsx b/packages/app/src/components/EditorPane.tsx
index 2402d66e7..f357eb0a4 100644
--- a/packages/app/src/components/EditorPane.tsx
+++ b/packages/app/src/components/EditorPane.tsx
@@ -8,6 +8,7 @@ import { type EditorModeValue, useEditorMode } from '@/editor/use-editor-mode';
import { useGitSyncStatus } from '@/hooks/use-git-sync-status';
import { useInstalledClis } from '@/hooks/use-installed-clis';
import { useNoPushPermissionToast } from '@/hooks/use-no-push-permission-toast';
+import { useWorktreeAutoSyncNotice } from '@/hooks/use-worktree-autosync-notice';
import { useConfigContext } from '@/lib/config-provider';
import { resolveDefaultCli } from '@/lib/default-cli-resolver';
import { matchesKeyboardShortcut } from '@/lib/keyboard-shortcuts';
@@ -192,6 +193,8 @@ export function EditorPane({ onOpenSearch }: EditorPaneProps = {}) {
useNoPushPermissionToast(syncStatus?.pausedReason);
+ useWorktreeAutoSyncNotice();
+
function handleModeChange(mode: EditorModeValue) {
setEditorMode(mode);
setPersistedMode(mode);
diff --git a/packages/app/src/components/NavigatorApp.dom.test.tsx b/packages/app/src/components/NavigatorApp.dom.test.tsx
index 4d504ee31..b42fc4f34 100644
--- a/packages/app/src/components/NavigatorApp.dom.test.tsx
+++ b/packages/app/src/components/NavigatorApp.dom.test.tsx
@@ -200,4 +200,61 @@ describe('NavigatorApp launcher runtime behavior', () => {
});
});
});
+
+ test('labels a linked-worktree recent with its branch over its base project, leaving plain projects unchanged', async () => {
+ const bridge = createBridge();
+ bridge.project.listRecent = mock(() =>
+ Promise.resolve([
+ {
+ path: '/Users/x/pnw-fishing/.ok/worktrees/dev',
+ name: 'dev',
+ isLinkedWorktree: true,
+ mainRoot: '/Users/x/pnw-fishing',
+ branch: 'dev',
+ },
+ { path: '/Users/x/plain-notes', name: 'Plain Notes' },
+ ]),
+ );
+ await renderNavigator(bridge);
+
+ const list = await screen.findByTestId('nav-recent-list');
+ expect(list.textContent).toContain('dev');
+ expect(list.textContent).toContain('pnw-fishing');
+ expect(list.textContent).toContain('Plain Notes');
+ expect(list.textContent).toContain('/Users/x/plain-notes');
+ });
+
+ test('gives worktree and plain-project recents distinct icon tiles', async () => {
+ const bridge = createBridge();
+ bridge.project.listRecent = mock(() =>
+ Promise.resolve([
+ {
+ path: '/Users/x/pnw-fishing/.ok/worktrees/dev',
+ name: 'dev',
+ isLinkedWorktree: true,
+ mainRoot: '/Users/x/pnw-fishing',
+ branch: 'dev',
+ },
+ { path: '/Users/x/plain-notes', name: 'Plain Notes' },
+ ]),
+ );
+ await renderNavigator(bridge);
+
+ const list = await screen.findByTestId('nav-recent-list');
+ const rows = list.querySelectorAll('li');
+ expect(rows.length).toBe(2);
+
+ const [worktreeRow, plainRow] = rows;
+ if (!worktreeRow || !plainRow) throw new Error('expected two recent rows');
+
+ expect(worktreeRow.querySelector('svg.lucide-git-branch')).not.toBeNull();
+ expect(worktreeRow.querySelector('svg.lucide-folder')).toBeNull();
+ expect(worktreeRow.textContent).toContain('dev');
+ expect(worktreeRow.textContent).toContain('worktree of pnw-fishing');
+
+ expect(plainRow.querySelector('svg.lucide-folder')).not.toBeNull();
+ expect(plainRow.querySelector('svg.lucide-git-branch')).toBeNull();
+ expect(plainRow.textContent).toContain('Plain Notes');
+ expect(plainRow.textContent).toContain('/Users/x/plain-notes');
+ });
});
diff --git a/packages/app/src/components/NavigatorApp.tsx b/packages/app/src/components/NavigatorApp.tsx
index 40376673c..f8c7260c5 100644
--- a/packages/app/src/components/NavigatorApp.tsx
+++ b/packages/app/src/components/NavigatorApp.tsx
@@ -1,5 +1,5 @@
import { Trans, useLingui } from '@lingui/react/macro';
-import { FolderOpenIcon, GitBranch, Loader2Icon, PlusIcon, XIcon } from 'lucide-react';
+import { Folder, FolderOpenIcon, GitBranch, Loader2Icon, PlusIcon, XIcon } from 'lucide-react';
import { useTheme } from 'next-themes';
import { type ComponentType, useEffect, useState } from 'react';
import { useThemeBridge } from '@/hooks/use-theme-bridge';
@@ -26,6 +26,7 @@ import { CreateProjectDialog } from './CreateProjectDialog';
import { GithubIcon } from './icons/github';
import { OkIcon } from './icons/ok';
import { McpConsentDialog } from './McpConsentDialog';
+import { basenameOf } from './project-switcher-recents';
import { ShareReceiveDialog } from './ShareReceiveDialog';
import { Badge } from './ui/badge';
import { Button } from './ui/button';
@@ -374,6 +375,7 @@ function RecentRow({
}) {
const { t } = useLingui();
const { name: projectName } = project;
+ const isWorktree = project.isLinkedWorktree === true;
return (
<li className="group flex items-center justify-between rounded-lg hover:bg-accent">
<Button
@@ -382,21 +384,52 @@ function RecentRow({
onClick={onOpen}
disabled={project.missing}
className={cn(
- 'h-auto min-w-0 flex-1 justify-between gap-2 py-3.5 pl-4 pr-2 text-left hover:bg-transparent',
+ 'h-auto min-w-0 flex-1 justify-between gap-3 py-3.5 pl-4 pr-2 text-left hover:bg-transparent',
project.missing && 'opacity-50',
)}
>
- <div className="flex flex-col gap-1 truncate">
- <span className="font-medium text-sm text-gray-700 dark:text-foreground">
- {project.name}
+ <div className="flex min-w-0 items-center gap-3">
+ <span
+ aria-hidden="true"
+ className={cn(
+ 'flex size-8 shrink-0 items-center justify-center rounded-lg',
+ isWorktree
+ ? 'bg-green-600/10 text-green-600 dark:bg-green-400/10 dark:text-green-400'
+ : 'bg-muted text-muted-foreground',
+ )}
+ >
+ {isWorktree ? <GitBranch className="size-4" /> : <Folder className="size-4" />}
</span>
- <span className="truncate w-full text-muted-foreground text-xs">{project.path}</span>
+ <div className="flex min-w-0 flex-col gap-1 truncate">
+ {isWorktree ? (
+ <>
+ <span className="truncate font-medium text-sm text-gray-700 dark:text-foreground">
+ {project.branch ?? branch ?? project.name}
+ </span>
+ <span
+ className="truncate w-full text-muted-foreground text-xs"
+ title={project.mainRoot ?? ''}
+ >
+ <Trans>worktree of {basenameOf(project.mainRoot ?? '')}</Trans>
+ </span>
+ </>
+ ) : (
+ <>
+ <span className="font-medium text-sm text-gray-700 dark:text-foreground">
+ {project.name}
+ </span>
+ <span className="truncate w-full text-muted-foreground text-xs">
+ {project.path}
+ </span>
+ </>
+ )}
+ </div>
</div>
{project.missing ? (
<Badge className="text-2xs rounded-sm" variant="warning">
<Trans>Missing</Trans>
</Badge>
- ) : branch !== null ? (
+ ) : branch !== null && !isWorktree ? (
<span
className="flex max-w-[40%] items-center gap-1 text-muted-foreground text-xs"
data-testid={`nav-recent-branch-${project.path}`}
diff --git a/packages/app/src/components/NewWorktreeDialog.dom.test.tsx b/packages/app/src/components/NewWorktreeDialog.dom.test.tsx
new file mode 100644
index 000000000..1fc8ecd36
--- /dev/null
+++ b/packages/app/src/components/NewWorktreeDialog.dom.test.tsx
@@ -0,0 +1,724 @@
+import { beforeEach, describe, expect, mock, test } from 'bun:test';
+import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';
+import { NewWorktreeDialog } from './NewWorktreeDialog';
+
+const refreshWorktrees = mock(() => {});
+mock.module('@/lib/worktree-store', () => ({ refreshWorktrees }));
+
+function createBridge(createResult: unknown) {
+ return {
+ worktree: { create: mock(() => Promise.resolve(createResult)) },
+ project: { open: mock(() => Promise.resolve()) },
+ };
+}
+
+const noop = () => {};
+
+describe('NewWorktreeDialog', () => {
+ beforeEach(() => {
+ cleanup();
+ refreshWorktrees.mockClear();
+ });
+
+ test('creates a new branch worktree and opens it (entryPoint worktree)', async () => {
+ const bridge = createBridge({
+ ok: true,
+ path: '/repo/.ok/worktrees/my-feature',
+ created: true,
+ });
+ render(
+ <NewWorktreeDialog
+ open={true}
+ onOpenChange={noop}
+ bridge={bridge as never}
+ currentBranch="main"
+ />,
+ );
+ const input = await screen.findByTestId('new-worktree-branch');
+ fireEvent.change(input, { target: { value: 'my-feature' } });
+ fireEvent.click(screen.getByTestId('new-worktree-create'));
+
+ await waitFor(() => expect(bridge.worktree.create).toHaveBeenCalledTimes(1));
+ expect(bridge.worktree.create).toHaveBeenCalledWith({
+ branch: 'my-feature',
+ createBranch: true,
+ baseBranch: 'main',
+ });
+ await waitFor(() =>
+ expect(bridge.project.open).toHaveBeenCalledWith({
+ path: '/repo/.ok/worktrees/my-feature',
+ target: 'new-window',
+ entryPoint: 'worktree',
+ }),
+ );
+ });
+
+ test('pre-fills the branch field from initialBranchName on open (create mode) and submits it', async () => {
+ const bridge = createBridge({
+ ok: true,
+ path: '/repo/.ok/worktrees/pre-seeded',
+ created: true,
+ });
+ render(
+ <NewWorktreeDialog
+ open={true}
+ onOpenChange={noop}
+ bridge={bridge as never}
+ currentBranch="main"
+ branches={['main', 'dev']}
+ initialBranchName="pre-seeded"
+ />,
+ );
+ const input = (await screen.findByTestId('new-worktree-branch')) as HTMLInputElement;
+ expect(input.value).toBe('pre-seeded');
+ expect(screen.getByTestId('new-worktree-mode-create').textContent).toContain('pre-seeded');
+
+ fireEvent.click(screen.getByTestId('new-worktree-create'));
+ await waitFor(() => expect(bridge.worktree.create).toHaveBeenCalledTimes(1));
+ expect(bridge.worktree.create).toHaveBeenCalledWith({
+ branch: 'pre-seeded',
+ createBranch: true,
+ baseBranch: 'main',
+ });
+ });
+
+ test('a seeded name matching an existing branch opens straight into checkout mode', async () => {
+ const bridge = createBridge({ ok: true, path: '/repo/.ok/worktrees/dev', created: false });
+ render(
+ <NewWorktreeDialog
+ open={true}
+ onOpenChange={noop}
+ bridge={bridge as never}
+ currentBranch="main"
+ branches={['main', 'dev', 'release']}
+ initialBranchName="dev"
+ />,
+ );
+ await screen.findByTestId('new-worktree-branch');
+ expect(screen.getByTestId('new-worktree-mode-checkout').textContent).toContain(
+ 'Existing branch',
+ );
+ expect(screen.getByTestId('new-worktree-create').textContent).toContain('Check out');
+ });
+
+ test('without initialBranchName the field opens empty (default)', async () => {
+ const bridge = createBridge({ ok: true, path: '/x', created: true });
+ render(
+ <NewWorktreeDialog
+ open={true}
+ onOpenChange={noop}
+ bridge={bridge as never}
+ currentBranch="main"
+ />,
+ );
+ const input = (await screen.findByTestId('new-worktree-branch')) as HTMLInputElement;
+ expect(input.value).toBe('');
+ });
+
+ test('surfaces a branch-exists failure inline without opening a window', async () => {
+ const bridge = createBridge({ ok: false, reason: 'branch-exists' });
+ render(
+ <NewWorktreeDialog
+ open={true}
+ onOpenChange={noop}
+ bridge={bridge as never}
+ currentBranch="main"
+ />,
+ );
+ fireEvent.change(await screen.findByTestId('new-worktree-branch'), {
+ target: { value: 'dev' },
+ });
+ fireEvent.click(screen.getByTestId('new-worktree-create'));
+ const err = await screen.findByTestId('new-worktree-error');
+ expect(err.textContent).toContain('already exists');
+ expect(bridge.project.open).not.toHaveBeenCalled();
+ });
+
+ test('checks out an existing branch (createBranch false, no base) and refreshes the cache', async () => {
+ const bridge = createBridge({
+ ok: true,
+ path: '/repo/.ok/worktrees/dev',
+ created: false,
+ });
+ render(
+ <NewWorktreeDialog
+ open={true}
+ onOpenChange={noop}
+ bridge={bridge as never}
+ currentBranch="main"
+ branches={['main', 'dev', 'release']}
+ />,
+ );
+ const input = await screen.findByTestId('new-worktree-branch');
+ fireEvent.change(input, { target: { value: 'dev' } });
+
+ expect(screen.getByTestId('new-worktree-create').textContent).toContain('Check out');
+
+ fireEvent.click(screen.getByTestId('new-worktree-create'));
+ await waitFor(() => expect(bridge.worktree.create).toHaveBeenCalledTimes(1));
+ expect(bridge.worktree.create).toHaveBeenCalledWith({
+ branch: 'dev',
+ createBranch: false,
+ baseBranch: undefined,
+ });
+ await waitFor(() =>
+ expect(bridge.project.open).toHaveBeenCalledWith({
+ path: '/repo/.ok/worktrees/dev',
+ target: 'new-window',
+ entryPoint: 'worktree',
+ }),
+ );
+ expect(refreshWorktrees).toHaveBeenCalled();
+ });
+
+ test('shows existing branches as a styled suggestion list; clicking one fills the field', async () => {
+ const bridge = createBridge({ ok: true, path: '/x', created: true });
+ render(
+ <NewWorktreeDialog
+ open={true}
+ onOpenChange={noop}
+ bridge={bridge as never}
+ currentBranch="main"
+ branches={['main', 'release/1.x', 'dev']}
+ />,
+ );
+ const list = await screen.findByTestId('new-worktree-branch-list');
+ expect(list.querySelector('datalist')).toBeNull();
+ expect(screen.getByTestId('new-worktree-branch-option-release/1.x')).not.toBeNull();
+
+ fireEvent.change(screen.getByTestId('new-worktree-branch'), { target: { value: 'rel' } });
+ expect(screen.queryByTestId('new-worktree-branch-option-dev')).toBeNull();
+ fireEvent.click(screen.getByTestId('new-worktree-branch-option-release/1.x'));
+ expect((screen.getByTestId('new-worktree-branch') as HTMLInputElement).value).toBe(
+ 'release/1.x',
+ );
+ expect(screen.getByTestId('new-worktree-create').textContent).toContain('Check out');
+ });
+
+ test('suggestions use a prefix match, not substring — unrelated branches are excluded', async () => {
+ const bridge = createBridge({ ok: true, path: '/x', created: true });
+ render(
+ <NewWorktreeDialog
+ open={true}
+ onOpenChange={noop}
+ bridge={bridge as never}
+ currentBranch="main"
+ branches={['main', 'claude/xenodochial-germain-895b95', 'dev']}
+ />,
+ );
+ fireEvent.change(await screen.findByTestId('new-worktree-branch'), {
+ target: { value: 'mai' },
+ });
+ const list = await screen.findByTestId('new-worktree-branch-list');
+ expect(list.querySelectorAll('[data-testid^="new-worktree-branch-option-"]')).toHaveLength(1);
+ expect(screen.getByTestId('new-worktree-branch-option-main')).not.toBeNull();
+ expect(
+ screen.queryByTestId('new-worktree-branch-option-claude/xenodochial-germain-895b95'),
+ ).toBeNull();
+ });
+
+ test('the suggestion list dismisses once the input exactly matches an existing branch', async () => {
+ const bridge = createBridge({ ok: true, path: '/x', created: false });
+ render(
+ <NewWorktreeDialog
+ open={true}
+ onOpenChange={noop}
+ bridge={bridge as never}
+ currentBranch="main"
+ branches={['main', 'main-2']}
+ />,
+ );
+ const input = await screen.findByTestId('new-worktree-branch');
+
+ fireEvent.change(input, { target: { value: 'mai' } });
+ expect(await screen.findByTestId('new-worktree-branch-list')).not.toBeNull();
+
+ fireEvent.change(input, { target: { value: 'main' } });
+ expect(screen.queryByTestId('new-worktree-branch-list')).toBeNull();
+
+ expect(screen.queryByTestId('new-worktree-base-trigger')).toBeNull();
+ });
+
+ test('the create button is disabled until a branch name is entered', async () => {
+ const bridge = createBridge({ ok: true, path: '/x', created: true });
+ render(
+ <NewWorktreeDialog
+ open={true}
+ onOpenChange={noop}
+ bridge={bridge as never}
+ currentBranch={null}
+ />,
+ );
+ const button = (await screen.findByTestId('new-worktree-create')) as HTMLButtonElement;
+ expect(button.disabled).toBe(true);
+ fireEvent.change(screen.getByTestId('new-worktree-branch'), { target: { value: 'x' } });
+ await waitFor(() => expect(button.disabled).toBe(false));
+ });
+
+ test('the base-branch selector defaults to currentBranch and creating passes it as the base', async () => {
+ const bridge = createBridge({
+ ok: true,
+ path: '/repo/.ok/worktrees/my-feature',
+ created: true,
+ });
+ render(
+ <NewWorktreeDialog
+ open={true}
+ onOpenChange={noop}
+ bridge={bridge as never}
+ currentBranch="main"
+ branches={['main', 'dev', 'release']}
+ />,
+ );
+ const trigger = await screen.findByTestId('new-worktree-base-trigger');
+ expect(trigger.textContent).toContain('main');
+
+ fireEvent.change(screen.getByTestId('new-worktree-branch'), {
+ target: { value: 'my-feature' },
+ });
+ fireEvent.click(screen.getByTestId('new-worktree-create'));
+ await waitFor(() => expect(bridge.worktree.create).toHaveBeenCalledTimes(1));
+ expect(bridge.worktree.create).toHaveBeenCalledWith({
+ branch: 'my-feature',
+ createBranch: true,
+ baseBranch: 'main',
+ });
+ });
+
+ test('selecting a different base branch passes the chosen base to create', async () => {
+ const bridge = createBridge({
+ ok: true,
+ path: '/repo/.ok/worktrees/my-feature',
+ created: true,
+ });
+ render(
+ <NewWorktreeDialog
+ open={true}
+ onOpenChange={noop}
+ bridge={bridge as never}
+ currentBranch="main"
+ branches={['main', 'dev', 'release']}
+ />,
+ );
+ fireEvent.change(await screen.findByTestId('new-worktree-branch'), {
+ target: { value: 'my-feature' },
+ });
+
+ fireEvent.click(screen.getByTestId('new-worktree-base-trigger'));
+ fireEvent.click(await screen.findByTestId('new-worktree-base-option-dev'));
+
+ await waitFor(() =>
+ expect(screen.getByTestId('new-worktree-base-trigger').textContent).toContain('dev'),
+ );
+ expect(screen.getByTestId('new-worktree-mode-create').textContent).toContain('dev');
+
+ fireEvent.click(screen.getByTestId('new-worktree-create'));
+ await waitFor(() => expect(bridge.worktree.create).toHaveBeenCalledTimes(1));
+ expect(bridge.worktree.create).toHaveBeenCalledWith({
+ branch: 'my-feature',
+ createBranch: true,
+ baseBranch: 'dev',
+ });
+ });
+
+ test('typing a new branch name shows the create indicator, not the checkout one', async () => {
+ const bridge = createBridge({ ok: true, path: '/x', created: true });
+ render(
+ <NewWorktreeDialog
+ open={true}
+ onOpenChange={noop}
+ bridge={bridge as never}
+ currentBranch="main"
+ branches={['main', 'dev', 'release']}
+ />,
+ );
+ const input = await screen.findByTestId('new-worktree-branch');
+ fireEvent.change(input, { target: { value: 'my-feature' } });
+
+ const indicator = await screen.findByTestId('new-worktree-mode-create');
+ expect(indicator.textContent).toContain('New branch');
+ expect(screen.queryByTestId('new-worktree-mode-checkout')).toBeNull();
+ });
+
+ test('typing an existing branch name shows the checkout indicator, not the create one', async () => {
+ const bridge = createBridge({ ok: true, path: '/x', created: false });
+ render(
+ <NewWorktreeDialog
+ open={true}
+ onOpenChange={noop}
+ bridge={bridge as never}
+ currentBranch="main"
+ branches={['main', 'dev', 'release']}
+ />,
+ );
+ const input = await screen.findByTestId('new-worktree-branch');
+ fireEvent.change(input, { target: { value: 'dev' } });
+
+ const indicator = await screen.findByTestId('new-worktree-mode-checkout');
+ expect(indicator.textContent).toContain('Existing branch');
+ expect(screen.queryByTestId('new-worktree-mode-create')).toBeNull();
+ });
+
+ test('an empty branch field shows neither mode indicator', async () => {
+ const bridge = createBridge({ ok: true, path: '/x', created: true });
+ render(
+ <NewWorktreeDialog
+ open={true}
+ onOpenChange={noop}
+ bridge={bridge as never}
+ currentBranch="main"
+ branches={['main', 'dev', 'release']}
+ />,
+ );
+ await screen.findByTestId('new-worktree-branch');
+ expect(screen.queryByTestId('new-worktree-mode-create')).toBeNull();
+ expect(screen.queryByTestId('new-worktree-mode-checkout')).toBeNull();
+ });
+
+ test('a branch that already has a worktree shows the existing-worktree indicator and "Open worktree" button (not plain checkout)', async () => {
+ const bridge = createBridge({ ok: true, path: '/repo/.ok/worktrees/dev', created: false });
+ render(
+ <NewWorktreeDialog
+ open={true}
+ onOpenChange={noop}
+ bridge={bridge as never}
+ currentBranch="main"
+ branches={['main', 'dev', 'release']}
+ existingWorktreeBranches={new Set(['dev'])}
+ />,
+ );
+ const input = await screen.findByTestId('new-worktree-branch');
+ fireEvent.change(input, { target: { value: 'dev' } });
+
+ const indicator = await screen.findByTestId('new-worktree-mode-existing-worktree');
+ expect(indicator.textContent).toContain('already has a worktree');
+ expect(screen.queryByTestId('new-worktree-mode-checkout')).toBeNull();
+ expect(screen.queryByTestId('new-worktree-mode-create')).toBeNull();
+
+ const button = screen.getByTestId('new-worktree-create');
+ expect(button.textContent).toContain('Open worktree');
+ expect(button.textContent).not.toContain('Check out');
+ });
+
+ test('a branch WITHOUT a worktree still shows plain checkout even when other branches have one', async () => {
+ const bridge = createBridge({ ok: true, path: '/repo/.ok/worktrees/release', created: false });
+ render(
+ <NewWorktreeDialog
+ open={true}
+ onOpenChange={noop}
+ bridge={bridge as never}
+ currentBranch="main"
+ branches={['main', 'dev', 'release']}
+ existingWorktreeBranches={new Set(['dev'])}
+ />,
+ );
+ const input = await screen.findByTestId('new-worktree-branch');
+ fireEvent.change(input, { target: { value: 'release' } });
+
+ const indicator = await screen.findByTestId('new-worktree-mode-checkout');
+ expect(indicator.textContent).toContain('Existing branch');
+ expect(screen.queryByTestId('new-worktree-mode-existing-worktree')).toBeNull();
+ expect(screen.getByTestId('new-worktree-create').textContent).toContain('Check out');
+ });
+
+ test('a NEW branch name still shows create even when existingWorktreeBranches is provided', async () => {
+ const bridge = createBridge({ ok: true, path: '/x', created: true });
+ render(
+ <NewWorktreeDialog
+ open={true}
+ onOpenChange={noop}
+ bridge={bridge as never}
+ currentBranch="main"
+ branches={['main', 'dev', 'release']}
+ existingWorktreeBranches={new Set(['dev'])}
+ />,
+ );
+ const input = await screen.findByTestId('new-worktree-branch');
+ fireEvent.change(input, { target: { value: 'my-feature' } });
+
+ const indicator = await screen.findByTestId('new-worktree-mode-create');
+ expect(indicator.textContent).toContain('New branch');
+ expect(screen.queryByTestId('new-worktree-mode-existing-worktree')).toBeNull();
+ expect(screen.getByTestId('new-worktree-create').textContent).toContain('Create');
+ });
+
+ test('opening an existing-worktree branch still calls create (createBranch false, no base) and opens its path', async () => {
+ const onOpenChange = mock(() => {});
+ const bridge = createBridge({ ok: true, path: '/repo/.ok/worktrees/dev', created: false });
+ render(
+ <NewWorktreeDialog
+ open={true}
+ onOpenChange={onOpenChange}
+ bridge={bridge as never}
+ currentBranch="main"
+ branches={['main', 'dev', 'release']}
+ existingWorktreeBranches={new Set(['dev'])}
+ />,
+ );
+ const input = await screen.findByTestId('new-worktree-branch');
+ fireEvent.change(input, { target: { value: 'dev' } });
+
+ expect(screen.queryByTestId('new-worktree-base-trigger')).toBeNull();
+
+ fireEvent.click(screen.getByTestId('new-worktree-create'));
+ await waitFor(() => expect(bridge.worktree.create).toHaveBeenCalledTimes(1));
+ expect(bridge.worktree.create).toHaveBeenCalledWith({
+ branch: 'dev',
+ createBranch: false,
+ baseBranch: undefined,
+ });
+ await waitFor(() =>
+ expect(bridge.project.open).toHaveBeenCalledWith({
+ path: '/repo/.ok/worktrees/dev',
+ target: 'new-window',
+ entryPoint: 'worktree',
+ }),
+ );
+ expect(refreshWorktrees).toHaveBeenCalled();
+ });
+
+ test('checkout mode hides the base selector and sends an undefined base', async () => {
+ const bridge = createBridge({ ok: true, path: '/repo/.ok/worktrees/dev', created: false });
+ render(
+ <NewWorktreeDialog
+ open={true}
+ onOpenChange={noop}
+ bridge={bridge as never}
+ currentBranch="main"
+ branches={['main', 'dev', 'release']}
+ />,
+ );
+ const input = await screen.findByTestId('new-worktree-branch');
+ expect(screen.queryByTestId('new-worktree-base-trigger')).not.toBeNull();
+
+ fireEvent.change(input, { target: { value: 'dev' } });
+ expect(screen.queryByTestId('new-worktree-base-trigger')).toBeNull();
+
+ fireEvent.click(screen.getByTestId('new-worktree-create'));
+ await waitFor(() => expect(bridge.worktree.create).toHaveBeenCalledTimes(1));
+ expect(bridge.worktree.create).toHaveBeenCalledWith({
+ branch: 'dev',
+ createBranch: false,
+ baseBranch: undefined,
+ });
+ });
+
+ test('a remote-only branch name shows the remote-checkout indicator and sends remoteRef', async () => {
+ const bridge = createBridge({
+ ok: true,
+ path: '/repo/.ok/worktrees/feature-x',
+ created: true,
+ });
+ render(
+ <NewWorktreeDialog
+ open={true}
+ onOpenChange={noop}
+ bridge={bridge as never}
+ currentBranch="main"
+ branches={['main', 'dev']}
+ remoteBranches={['origin/main', 'origin/dev', 'origin/feature-x']}
+ />,
+ );
+ fireEvent.change(await screen.findByTestId('new-worktree-branch'), {
+ target: { value: 'feature-x' },
+ });
+
+ const indicator = await screen.findByTestId('new-worktree-mode-remote-checkout');
+ expect(indicator.textContent).toContain('Remote branch');
+ expect(indicator.textContent).toContain('origin/feature-x');
+ expect(screen.queryByTestId('new-worktree-mode-create')).toBeNull();
+ expect(screen.queryByTestId('new-worktree-mode-checkout')).toBeNull();
+ expect(screen.queryByTestId('new-worktree-base-trigger')).toBeNull();
+ expect(screen.getByTestId('new-worktree-create').textContent).toContain(
+ 'Check out remote branch',
+ );
+
+ fireEvent.click(screen.getByTestId('new-worktree-create'));
+ await waitFor(() => expect(bridge.worktree.create).toHaveBeenCalledTimes(1));
+ expect(bridge.worktree.create).toHaveBeenCalledWith({
+ branch: 'feature-x',
+ createBranch: true,
+ remoteRef: 'origin/feature-x',
+ });
+ await waitFor(() =>
+ expect(bridge.project.open).toHaveBeenCalledWith({
+ path: '/repo/.ok/worktrees/feature-x',
+ target: 'new-window',
+ entryPoint: 'worktree',
+ }),
+ );
+ });
+
+ test('a name that is a local branch takes local checkout even when a remote ref matches', async () => {
+ const bridge = createBridge({ ok: true, path: '/repo/.ok/worktrees/dev', created: false });
+ render(
+ <NewWorktreeDialog
+ open={true}
+ onOpenChange={noop}
+ bridge={bridge as never}
+ currentBranch="main"
+ branches={['main', 'dev']}
+ remoteBranches={['origin/main', 'origin/dev']}
+ />,
+ );
+ fireEvent.change(await screen.findByTestId('new-worktree-branch'), {
+ target: { value: 'dev' },
+ });
+ expect(await screen.findByTestId('new-worktree-mode-checkout')).not.toBeNull();
+ expect(screen.queryByTestId('new-worktree-mode-remote-checkout')).toBeNull();
+
+ fireEvent.click(screen.getByTestId('new-worktree-create'));
+ await waitFor(() => expect(bridge.worktree.create).toHaveBeenCalledTimes(1));
+ expect(bridge.worktree.create).toHaveBeenCalledWith({ branch: 'dev', createBranch: false });
+ });
+
+ test('selecting a remote base option sends baseRef (no-track) instead of baseBranch', async () => {
+ const bridge = createBridge({
+ ok: true,
+ path: '/repo/.ok/worktrees/my-feature',
+ created: true,
+ });
+ render(
+ <NewWorktreeDialog
+ open={true}
+ onOpenChange={noop}
+ bridge={bridge as never}
+ currentBranch="main"
+ branches={['main', 'dev']}
+ remoteBranches={['origin/main', 'origin/dev']}
+ />,
+ );
+ fireEvent.change(await screen.findByTestId('new-worktree-branch'), {
+ target: { value: 'my-feature' },
+ });
+ fireEvent.click(screen.getByTestId('new-worktree-base-trigger'));
+ fireEvent.click(await screen.findByTestId('new-worktree-base-option-origin/main'));
+ await waitFor(() =>
+ expect(screen.getByTestId('new-worktree-base-trigger').textContent).toContain('origin/main'),
+ );
+ expect(screen.getByTestId('new-worktree-mode-create').textContent).toContain('origin/main');
+
+ fireEvent.click(screen.getByTestId('new-worktree-create'));
+ await waitFor(() => expect(bridge.worktree.create).toHaveBeenCalledTimes(1));
+ expect(bridge.worktree.create).toHaveBeenCalledWith({
+ branch: 'my-feature',
+ createBranch: true,
+ baseRef: 'origin/main',
+ });
+ });
+
+ test('renders the N-behind-origin hint on a local base option that is behind', async () => {
+ const bridge = createBridge({ ok: true, path: '/x', created: true });
+ render(
+ <NewWorktreeDialog
+ open={true}
+ onOpenChange={noop}
+ bridge={bridge as never}
+ currentBranch="main"
+ branches={['main', 'dev']}
+ remoteBranches={['origin/main', 'origin/dev']}
+ behindByBranch={
+ new Map([
+ ['main', 3],
+ ['dev', 0],
+ ])
+ }
+ />,
+ );
+ fireEvent.change(await screen.findByTestId('new-worktree-branch'), {
+ target: { value: 'my-feature' },
+ });
+ fireEvent.click(screen.getByTestId('new-worktree-base-trigger'));
+ const behindHint = await screen.findByTestId('new-worktree-base-behind-main');
+ expect(behindHint.textContent).toContain('3 behind origin');
+ expect(screen.queryByTestId('new-worktree-base-behind-dev')).toBeNull();
+ });
+
+ test('typing in the base Popover search filters options by substring across local and remote', async () => {
+ const bridge = createBridge({ ok: true, path: '/x', created: true });
+ render(
+ <NewWorktreeDialog
+ open={true}
+ onOpenChange={noop}
+ bridge={bridge as never}
+ currentBranch="main"
+ branches={['main', 'test-2', 'test-3', 'claude/foo']}
+ remoteBranches={['origin/main', 'origin/test-2']}
+ />,
+ );
+ fireEvent.change(await screen.findByTestId('new-worktree-branch'), {
+ target: { value: 'my-feature' },
+ });
+ await new Promise((resolve) => requestAnimationFrame(resolve));
+ fireEvent.click(screen.getByTestId('new-worktree-base-trigger'));
+ const search = await screen.findByTestId('new-worktree-base-search');
+
+ fireEvent.change(search, { target: { value: 'test' } });
+ expect(screen.getByTestId('new-worktree-base-option-test-2')).not.toBeNull();
+ expect(screen.getByTestId('new-worktree-base-option-test-3')).not.toBeNull();
+ expect(screen.getByTestId('new-worktree-base-option-origin/test-2')).not.toBeNull();
+ expect(screen.queryByTestId('new-worktree-base-option-main')).toBeNull();
+ expect(screen.queryByTestId('new-worktree-base-option-claude/foo')).toBeNull();
+ expect(screen.queryByTestId('new-worktree-base-option-origin/main')).toBeNull();
+ });
+
+ test('a base Popover query with no matches shows the empty-state row', async () => {
+ const bridge = createBridge({ ok: true, path: '/x', created: true });
+ render(
+ <NewWorktreeDialog
+ open={true}
+ onOpenChange={noop}
+ bridge={bridge as never}
+ currentBranch="main"
+ branches={['main', 'dev']}
+ remoteBranches={['origin/main', 'origin/dev']}
+ />,
+ );
+ fireEvent.change(await screen.findByTestId('new-worktree-branch'), {
+ target: { value: 'my-feature' },
+ });
+ await new Promise((resolve) => requestAnimationFrame(resolve));
+ fireEvent.click(screen.getByTestId('new-worktree-base-trigger'));
+ fireEvent.change(await screen.findByTestId('new-worktree-base-search'), {
+ target: { value: 'nonexistent-branch' },
+ });
+ expect(await screen.findByText('No matching branches.')).not.toBeNull();
+ expect(screen.queryByTestId('new-worktree-base-option-main')).toBeNull();
+ });
+
+ test('selecting a filtered base option applies the base and resets the query', async () => {
+ const bridge = createBridge({
+ ok: true,
+ path: '/repo/.ok/worktrees/my-feature',
+ created: true,
+ });
+ render(
+ <NewWorktreeDialog
+ open={true}
+ onOpenChange={noop}
+ bridge={bridge as never}
+ currentBranch="main"
+ branches={['main', 'dev', 'release']}
+ />,
+ );
+ fireEvent.change(await screen.findByTestId('new-worktree-branch'), {
+ target: { value: 'my-feature' },
+ });
+ await new Promise((resolve) => requestAnimationFrame(resolve));
+ fireEvent.click(screen.getByTestId('new-worktree-base-trigger'));
+ fireEvent.change(await screen.findByTestId('new-worktree-base-search'), {
+ target: { value: 'dev' },
+ });
+ fireEvent.click(await screen.findByTestId('new-worktree-base-option-dev'));
+
+ await waitFor(() =>
+ expect(screen.getByTestId('new-worktree-base-trigger').textContent).toContain('dev'),
+ );
+ expect(screen.queryByTestId('new-worktree-base-list')).toBeNull();
+
+ fireEvent.click(screen.getByTestId('new-worktree-base-trigger'));
+ expect(await screen.findByTestId('new-worktree-base-option-main')).not.toBeNull();
+ expect(screen.getByTestId('new-worktree-base-option-release')).not.toBeNull();
+ expect((screen.getByTestId('new-worktree-base-search') as HTMLInputElement).value).toBe('');
+ });
+});
diff --git a/packages/app/src/components/NewWorktreeDialog.tsx b/packages/app/src/components/NewWorktreeDialog.tsx
new file mode 100644
index 000000000..12b8057d3
--- /dev/null
+++ b/packages/app/src/components/NewWorktreeDialog.tsx
@@ -0,0 +1,543 @@
+import { stripRemotePrefix } from '@inkeep/open-knowledge-core';
+import type { MessageDescriptor } from '@lingui/core';
+import { msg } from '@lingui/core/macro';
+import { Trans, useLingui } from '@lingui/react/macro';
+import { Check, ChevronsUpDown, Cloud, FolderOpen, GitBranch, Plus, Search } from 'lucide-react';
+import { useEffect, useId, useRef, useState } from 'react';
+import { toast } from 'sonner';
+import { Button } from '@/components/ui/button';
+import {
+ Dialog,
+ DialogBody,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+} from '@/components/ui/dialog';
+import { Input } from '@/components/ui/input';
+import { InputGroup, InputGroupAddon, InputGroupInput } from '@/components/ui/input-group';
+import { Label } from '@/components/ui/label';
+import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover';
+import type { OkDesktopBridge } from '@/lib/desktop-bridge-types';
+import { refreshWorktrees } from '@/lib/worktree-store';
+
+interface NewWorktreeDialogProps {
+ open: boolean;
+ onOpenChange: (open: boolean) => void;
+ bridge: OkDesktopBridge;
+ currentBranch: string | null;
+ initialBranchName?: string;
+ branches?: readonly string[];
+ existingWorktreeBranches?: ReadonlySet<string>;
+ remoteBranches?: readonly string[];
+ behindByBranch?: ReadonlyMap<string, number>;
+}
+
+type LocalBaseChoice = { readonly kind: 'local'; readonly name: string };
+type RemoteBaseChoice = { readonly kind: 'remote'; readonly ref: string };
+type BaseChoice = LocalBaseChoice | RemoteBaseChoice;
+type BaseSelection = BaseChoice | null;
+
+function baseSelectionLabel(sel: BaseSelection): string | null {
+ if (sel === null) return null;
+ return sel.kind === 'local' ? sel.name : sel.ref;
+}
+
+function findRemoteRef(name: string, remoteBranches: readonly string[]): string | null {
+ if (name.length === 0) return null;
+ const preferred = `origin/${name}`;
+ if (remoteBranches.includes(preferred)) return preferred;
+ return remoteBranches.find((ref) => stripRemotePrefix(ref) === name) ?? null;
+}
+
+function createErrorCopy(reason: string): MessageDescriptor {
+ switch (reason) {
+ case 'branch-exists':
+ return msg`A branch with that name already exists. Open its worktree from the switcher instead.`;
+ case 'already-checked-out':
+ return msg`That branch is already open in another worktree.`;
+ case 'path-exists':
+ return msg`A worktree folder for that branch already exists.`;
+ case 'invalid-branch':
+ return msg`Enter a valid branch name (no spaces, no leading dot, no "..").`;
+ case 'no-git':
+ return msg`This project isn't a git repository, so worktrees aren't available.`;
+ default:
+ return msg`Couldn't create the worktree. Try a different name.`;
+ }
+}
+
+export function NewWorktreeDialog({
+ open,
+ onOpenChange,
+ bridge,
+ currentBranch,
+ branches = [],
+ existingWorktreeBranches,
+ remoteBranches = [],
+ behindByBranch,
+ initialBranchName = '',
+}: NewWorktreeDialogProps) {
+ const { t } = useLingui();
+ const formId = useId();
+ const nameInputId = useId();
+ const baseTriggerId = useId();
+ const baseLabelId = useId();
+ const captionId = useId();
+ const errorId = useId();
+ const [branch, setBranch] = useState('');
+ const [base, setBase] = useState<BaseSelection>(
+ currentBranch !== null ? { kind: 'local', name: currentBranch } : null,
+ );
+ const [baseOpen, setBaseOpen] = useState(false);
+ const [baseQuery, setBaseQuery] = useState('');
+ const [busy, setBusy] = useState(false);
+ const [error, setError] = useState<MessageDescriptor | null>(null);
+ const inputRef = useRef<HTMLInputElement | null>(null);
+ const baseSearchRef = useRef<HTMLInputElement | null>(null);
+
+ useEffect(() => {
+ if (!open) return;
+ setBranch(initialBranchName);
+ setBase(currentBranch !== null ? { kind: 'local', name: currentBranch } : null);
+ setBaseOpen(false);
+ setBaseQuery('');
+ setBusy(false);
+ setError(null);
+ const raf = requestAnimationFrame(() => inputRef.current?.focus());
+ return () => cancelAnimationFrame(raf);
+ }, [open, currentBranch, initialBranchName]);
+
+ const trimmed = branch.trim();
+ const canSubmit = !busy && trimmed.length > 0;
+ const isLocalBranch = trimmed.length > 0 && branches.includes(trimmed);
+ const remoteCheckoutRef = isLocalBranch ? null : findRemoteRef(trimmed, remoteBranches);
+ const isRemoteCheckout = remoteCheckoutRef !== null;
+ const isCheckout = isLocalBranch || isRemoteCheckout;
+ const isExistingWorktree = isLocalBranch && (existingWorktreeBranches?.has(trimmed) ?? false);
+ const suggestions = branches.filter((b) => b.toLowerCase().startsWith(trimmed.toLowerCase()));
+ const showSuggestions = !busy && suggestions.length > 0 && !isCheckout;
+
+ const localBaseNames =
+ currentBranch !== null && !branches.includes(currentBranch)
+ ? [currentBranch, ...branches]
+ : branches;
+ const localBaseOptions: LocalBaseChoice[] = localBaseNames.map((name) => ({
+ kind: 'local',
+ name,
+ }));
+ const remoteBaseOptions: RemoteBaseChoice[] = remoteBranches.map((ref) => ({
+ kind: 'remote',
+ ref,
+ }));
+ const currentBaseLabel = baseSelectionLabel(base);
+ const trimmedBaseQuery = baseQuery.trim().toLowerCase();
+ const filteredLocalBaseOptions =
+ trimmedBaseQuery === ''
+ ? localBaseOptions
+ : localBaseOptions.filter((opt) => opt.name.toLowerCase().includes(trimmedBaseQuery));
+ const filteredRemoteBaseOptions =
+ trimmedBaseQuery === ''
+ ? remoteBaseOptions
+ : remoteBaseOptions.filter((opt) => opt.ref.toLowerCase().includes(trimmedBaseQuery));
+ const hasNoBaseMatches =
+ trimmedBaseQuery !== '' &&
+ filteredLocalBaseOptions.length === 0 &&
+ filteredRemoteBaseOptions.length === 0;
+
+ async function onSubmit(e: React.SyntheticEvent<HTMLFormElement, SubmitEvent>) {
+ e.preventDefault();
+ if (!canSubmit) return;
+ setBusy(true);
+ setError(null);
+ try {
+ const request = isRemoteCheckout
+ ? { branch: trimmed, createBranch: true, remoteRef: remoteCheckoutRef }
+ : isLocalBranch
+ ? { branch: trimmed, createBranch: false }
+ : {
+ branch: trimmed,
+ createBranch: true,
+ baseBranch: base?.kind === 'local' ? base.name : undefined,
+ baseRef: base?.kind === 'remote' ? base.ref : undefined,
+ };
+ const result = await bridge.worktree.create(request);
+ if (!result.ok) {
+ setError(createErrorCopy(result.reason));
+ setBusy(false);
+ return;
+ }
+ refreshWorktrees();
+ onOpenChange(false);
+ await bridge.project.open({
+ path: result.path,
+ target: 'new-window',
+ entryPoint: 'worktree',
+ });
+ } catch (err) {
+ console.warn('[NewWorktreeDialog] worktree create/open failed:', err);
+ toast.error(t`Couldn't open the worktree. Try again.`);
+ setBusy(false);
+ }
+ }
+
+ return (
+ <Dialog
+ open={open}
+ onOpenChange={(next) => {
+ if (busy) return;
+ onOpenChange(next);
+ }}
+ >
+ <DialogContent className="sm:max-w-md" data-testid="new-worktree-dialog">
+ <DialogHeader>
+ <DialogTitle>
+ <Trans>New worktree</Trans>
+ </DialogTitle>
+ <DialogDescription>
+ <Trans>Create a new branch, or check out an existing one, in its own window.</Trans>
+ </DialogDescription>
+ </DialogHeader>
+
+ <DialogBody>
+ <form id={formId} onSubmit={onSubmit} className="flex flex-col gap-2">
+ <Label htmlFor={nameInputId}>
+ <Trans>Branch name</Trans>
+ </Label>
+ <Input
+ id={nameInputId}
+ ref={inputRef}
+ value={branch}
+ placeholder={t`my-feature`}
+ onChange={(e) => {
+ setBranch(e.target.value);
+ if (error !== null) setError(null);
+ }}
+ disabled={busy}
+ autoComplete="off"
+ autoCorrect="off"
+ spellCheck={false}
+ aria-invalid={error !== null}
+ aria-describedby={error !== null ? `${captionId} ${errorId}` : captionId}
+ data-testid="new-worktree-branch"
+ />
+ {trimmed.length > 0 ? (
+ <p
+ id={captionId}
+ className="flex items-start gap-1.5 text-1sm text-muted-foreground"
+ data-testid={
+ isExistingWorktree
+ ? 'new-worktree-mode-existing-worktree'
+ : isRemoteCheckout
+ ? 'new-worktree-mode-remote-checkout'
+ : isLocalBranch
+ ? 'new-worktree-mode-checkout'
+ : 'new-worktree-mode-create'
+ }
+ >
+ {isExistingWorktree ? (
+ <FolderOpen
+ aria-hidden="true"
+ className="mt-0.5 size-3.5 shrink-0 text-amber-600 dark:text-amber-400"
+ />
+ ) : isRemoteCheckout ? (
+ <Cloud
+ aria-hidden="true"
+ className="mt-0.5 size-3.5 shrink-0 text-violet-600 dark:text-violet-400"
+ />
+ ) : isLocalBranch ? (
+ <Check
+ aria-hidden="true"
+ className="mt-0.5 size-3.5 shrink-0 text-blue-600 dark:text-blue-400"
+ />
+ ) : (
+ <Plus
+ aria-hidden="true"
+ className="mt-0.5 size-3.5 shrink-0 text-green-600 dark:text-green-400"
+ />
+ )}
+ {/* The sentence lives in ONE span so it's a single flex item that
+ flows/wraps normally — without this wrapper each text run + <code>
+ becomes its own flex item and the words scramble across columns. */}
+ <span className="min-w-0 flex-1">
+ {isExistingWorktree ? (
+ <Trans>
+ Branch <code className="font-mono break-words">{trimmed}</code> already has a
+ worktree — it'll open in its own window.
+ </Trans>
+ ) : isRemoteCheckout ? (
+ <Trans>
+ Remote branch{' '}
+ <code className="font-mono break-words">{remoteCheckoutRef}</code> will be
+ checked out as a new local tracking branch{' '}
+ <code className="font-mono break-words">{trimmed}</code>, in its own window
+ under <code className="font-mono">.ok/worktrees/</code>.
+ </Trans>
+ ) : isLocalBranch ? (
+ <Trans>
+ Existing branch <code className="font-mono break-words">{trimmed}</code> will
+ be checked out into its own window, under{' '}
+ <code className="font-mono">.ok/worktrees/</code>.
+ </Trans>
+ ) : currentBaseLabel !== null ? (
+ <Trans>
+ New branch <code className="font-mono break-words">{trimmed}</code> will be
+ created from <code className="font-mono break-words">{currentBaseLabel}</code>
+ , in its own worktree under <code className="font-mono">.ok/worktrees/</code>.
+ </Trans>
+ ) : (
+ <Trans>
+ New branch <code className="font-mono break-words">{trimmed}</code> will be
+ created from the current commit, in its own worktree under{' '}
+ <code className="font-mono">.ok/worktrees/</code>.
+ </Trans>
+ )}
+ </span>
+ </p>
+ ) : null}
+ {showSuggestions ? (
+ <div
+ className="max-h-40 overflow-y-auto rounded-md border bg-popover p-1 shadow-xs"
+ data-testid="new-worktree-branch-list"
+ >
+ {suggestions.map((b) => (
+ <Button
+ key={b}
+ type="button"
+ variant="ghost"
+ size="sm"
+ tabIndex={-1}
+ onClick={() => {
+ setBranch(b);
+ if (error !== null) setError(null);
+ inputRef.current?.focus();
+ }}
+ data-testid={`new-worktree-branch-option-${b}`}
+ className="h-8 w-full justify-start gap-2 font-normal"
+ >
+ <GitBranch
+ aria-hidden="true"
+ className="size-3.5 shrink-0 text-muted-foreground"
+ />
+ <span className="min-w-0 flex-1 truncate text-left">{b}</span>
+ </Button>
+ ))}
+ </div>
+ ) : null}
+ {/* Base-branch selector: only meaningful when creating a new branch.
+ Checkout mode reuses an existing branch's history, so there's no
+ base to choose. A shadcn Popover (not Radix Select/DropdownMenu):
+ this Electron renderer delivers no real `pointerdown`, so those
+ may not open — Popover opens on click, verified on this renderer. */}
+ {!isCheckout ? (
+ <div className="mt-1 flex flex-col gap-2">
+ <Label id={baseLabelId} htmlFor={baseTriggerId}>
+ <Trans>Base branch</Trans>
+ </Label>
+ <Popover
+ open={baseOpen}
+ onOpenChange={(next) => {
+ setBaseOpen(next);
+ if (!next) setBaseQuery('');
+ }}
+ >
+ <PopoverTrigger asChild>
+ <Button
+ id={baseTriggerId}
+ type="button"
+ variant="outline"
+ role="combobox"
+ aria-expanded={baseOpen}
+ aria-haspopup="listbox"
+ aria-labelledby={`${baseLabelId} ${baseTriggerId}`}
+ aria-label={t`Base branch`}
+ disabled={busy}
+ data-testid="new-worktree-base-trigger"
+ className="w-full justify-between font-normal"
+ >
+ <span className="flex min-w-0 items-center gap-2">
+ {base?.kind === 'remote' ? (
+ <Cloud
+ aria-hidden="true"
+ className="size-3.5 shrink-0 text-muted-foreground"
+ />
+ ) : (
+ <GitBranch
+ aria-hidden="true"
+ className="size-3.5 shrink-0 text-muted-foreground"
+ />
+ )}
+ <span className="min-w-0 truncate text-left">
+ {currentBaseLabel !== null ? (
+ currentBaseLabel
+ ) : (
+ <Trans>Current commit</Trans>
+ )}
+ </span>
+ </span>
+ <ChevronsUpDown
+ aria-hidden="true"
+ className="ml-2 size-4 shrink-0 opacity-50"
+ />
+ </Button>
+ </PopoverTrigger>
+ <PopoverContent
+ align="start"
+ className="w-[var(--radix-popover-trigger-width)] p-1"
+ onWheel={(e) => {
+ e.stopPropagation();
+ }}
+ onTouchMove={(e) => {
+ e.stopPropagation();
+ }}
+ onOpenAutoFocus={(e) => {
+ e.preventDefault();
+ baseSearchRef.current?.focus();
+ }}
+ >
+ <InputGroup className="mb-1 h-8">
+ <InputGroupInput
+ ref={baseSearchRef}
+ aria-label={t`Search branches`}
+ placeholder={t`Search branches...`}
+ value={baseQuery}
+ onChange={(e) => setBaseQuery(e.target.value)}
+ onKeyDown={(e) => e.stopPropagation()}
+ data-testid="new-worktree-base-search"
+ />
+ <InputGroupAddon>
+ <Search aria-hidden="true" />
+ </InputGroupAddon>
+ </InputGroup>
+ <div
+ role="listbox"
+ aria-label={t`Base branch`}
+ className="max-h-56 overflow-y-auto"
+ data-testid="new-worktree-base-list"
+ >
+ {hasNoBaseMatches ? (
+ <p className="px-2 py-1.5 text-1sm text-muted-foreground">
+ <Trans>No matching branches.</Trans>
+ </p>
+ ) : null}
+ {filteredLocalBaseOptions.map((opt) => {
+ const name = opt.name;
+ const behind = behindByBranch?.get(name);
+ const selected = base?.kind === 'local' && base.name === name;
+ return (
+ <Button
+ key={`local:${name}`}
+ type="button"
+ role="option"
+ aria-selected={selected}
+ variant="ghost"
+ size="sm"
+ onClick={() => {
+ setBase(opt);
+ setBaseOpen(false);
+ setBaseQuery('');
+ }}
+ data-testid={`new-worktree-base-option-${name}`}
+ className="h-8 w-full justify-start gap-2 font-normal"
+ >
+ <GitBranch
+ aria-hidden="true"
+ className="size-3.5 shrink-0 text-muted-foreground"
+ />
+ <span className="min-w-0 flex-1 truncate text-left">{name}</span>
+ {/* "N behind origin" hint: only when the branch has an
+ upstream AND has diverged (>0). Nudges toward the
+ fresh origin/<x> base below without shouting. */}
+ {behind !== undefined && behind > 0 ? (
+ <span
+ className="shrink-0 text-xs text-amber-600 dark:text-amber-400"
+ data-testid={`new-worktree-base-behind-${name}`}
+ >
+ <Trans>{behind} behind origin</Trans>
+ </span>
+ ) : null}
+ </Button>
+ );
+ })}
+ {filteredRemoteBaseOptions.map((opt) => {
+ const ref = opt.ref;
+ const selected = base?.kind === 'remote' && base.ref === ref;
+ return (
+ <Button
+ key={`remote:${ref}`}
+ type="button"
+ role="option"
+ aria-selected={selected}
+ variant="ghost"
+ size="sm"
+ onClick={() => {
+ setBase(opt);
+ setBaseOpen(false);
+ setBaseQuery('');
+ }}
+ data-testid={`new-worktree-base-option-${ref}`}
+ className="h-8 w-full justify-start gap-2 font-normal"
+ >
+ <Cloud
+ aria-hidden="true"
+ className="size-3.5 shrink-0 text-muted-foreground"
+ />
+ <span className="min-w-0 flex-1 truncate text-left">{ref}</span>
+ <span className="shrink-0 text-xs text-muted-foreground">
+ <Trans>remote</Trans>
+ </span>
+ </Button>
+ );
+ })}
+ </div>
+ </PopoverContent>
+ </Popover>
+ </div>
+ ) : null}
+ {error !== null ? (
+ <p
+ id={errorId}
+ role="alert"
+ className="text-1sm text-destructive"
+ data-testid="new-worktree-error"
+ >
+ {t(error)}
+ </p>
+ ) : null}
+ </form>
+ </DialogBody>
+
+ <DialogFooter>
+ <Button
+ type="button"
+ variant="outline"
+ onClick={() => onOpenChange(false)}
+ disabled={busy}
+ data-testid="new-worktree-cancel"
+ >
+ <Trans>Cancel</Trans>
+ </Button>
+ <Button
+ type="submit"
+ form={formId}
+ disabled={!canSubmit}
+ data-testid="new-worktree-create"
+ >
+ {busy ? (
+ <Trans>Working</Trans>
+ ) : isExistingWorktree ? (
+ <Trans>Open worktree</Trans>
+ ) : isRemoteCheckout ? (
+ <Trans>Check out remote branch</Trans>
+ ) : isLocalBranch ? (
+ <Trans>Check out worktree</Trans>
+ ) : (
+ <Trans>Create worktree</Trans>
+ )}
+ </Button>
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
+ );
+}
diff --git a/packages/app/src/components/ProjectSwitcher.dom.test.tsx b/packages/app/src/components/ProjectSwitcher.dom.test.tsx
index cc556891b..b02056ffc 100644
--- a/packages/app/src/components/ProjectSwitcher.dom.test.tsx
+++ b/packages/app/src/components/ProjectSwitcher.dom.test.tsx
@@ -69,6 +69,63 @@ mock.module('./CreateProjectDialog', () => ({
},
}));
+let newWorktreeProps: Array<{
+ open: boolean;
+ branches?: readonly string[];
+ existingWorktreeBranches?: ReadonlySet<string>;
+ remoteBranches?: readonly string[];
+ behindByBranch?: ReadonlyMap<string, number>;
+ initialBranchName?: string;
+}> = [];
+mock.module('./NewWorktreeDialog', () => ({
+ NewWorktreeDialog: (props: {
+ open: boolean;
+ branches?: readonly string[];
+ existingWorktreeBranches?: ReadonlySet<string>;
+ remoteBranches?: readonly string[];
+ behindByBranch?: ReadonlyMap<string, number>;
+ initialBranchName?: string;
+ }) => {
+ newWorktreeProps.push(props);
+ return (
+ <div
+ data-testid="new-worktree-dialog"
+ data-open={String(props.open)}
+ data-initial-name={props.initialBranchName ?? ''}
+ />
+ );
+ },
+}));
+
+mock.module('@/hooks/use-current-branch', () => ({
+ useCurrentBranch: () => 'main',
+}));
+mock.module('@/hooks/use-worktrees', () => ({
+ useWorktrees: () => ({
+ mainRoot: '/projects/current',
+ currentBranch: 'main',
+ entries: [
+ {
+ branch: 'omega-branch',
+ worktreePath: null,
+ isCurrent: false,
+ isMain: false,
+ locked: false,
+ behind: 4,
+ },
+ {
+ branch: 'has-worktree',
+ worktreePath: '/projects/current/.ok/worktrees/has-worktree',
+ isCurrent: false,
+ isMain: false,
+ locked: false,
+ behind: 0,
+ },
+ ],
+ remoteBranches: ['origin/main', 'origin/omega-branch', 'origin/remote-only-x'],
+ }),
+}));
+
function recent(name: string, path = `/projects/${name.toLowerCase()}`) {
return { name, path: path.replaceAll(' ', '-') };
}
@@ -85,6 +142,13 @@ function createBridge() {
recent('Current', '/projects/current'),
...Array.from({ length: 10 }, (_, index) => recent(`Project ${index + 1}`)),
recent('Omega', '/archive/omega-project'),
+ {
+ name: 'omega-wt',
+ path: '/archive/omega-wt',
+ branch: 'omega-branch',
+ isLinkedWorktree: true,
+ mainRoot: '/archive/omega-project',
+ },
]),
),
open: mock(() => Promise.resolve()),
@@ -95,9 +159,21 @@ function createBridge() {
navigator: {
open: mock(() => Promise.resolve()),
},
+ worktree: {
+ list: mock(() => Promise.resolve({ ok: false as const, reason: 'no-git' as const })),
+ create: mock(() => Promise.resolve({ ok: false as const, reason: 'no-git' as const })),
+ },
+ onMenuAction: mock((cb: (action: string) => void) => {
+ menuActionCb = cb;
+ return () => {
+ menuActionCb = null;
+ };
+ }),
};
}
+let menuActionCb: ((action: string) => void) | null = null;
+
async function openMenu() {
fireEvent.click(screen.getByTestId('project-switcher-trigger'));
act(() => {
@@ -114,6 +190,9 @@ describe('ProjectSwitcher dropdown behavior', () => {
lastDropdownOpenChange = null;
keydownBubbleCount = 0;
createDialogProps = [];
+ newWorktreeProps = [];
+ menuActionCb = null;
+ (window as unknown as { okDesktop?: unknown }).okDesktop = undefined;
});
test('renders footer actions in order and routes each action through the expected bridge entry point', async () => {
@@ -128,9 +207,11 @@ describe('ProjectSwitcher dropdown behavior', () => {
const newProjectIndex = menuText.indexOf('New project');
const switchProjectIndex = menuText.indexOf('Switch project');
const openFolderIndex = menuText.indexOf('Open folder');
+ const newWorktreeIndex = menuText.indexOf('New worktree');
expect(newProjectIndex).toBeGreaterThan(-1);
expect(switchProjectIndex).toBeGreaterThan(newProjectIndex);
expect(openFolderIndex).toBeGreaterThan(switchProjectIndex);
+ expect(newWorktreeIndex).toBeGreaterThan(openFolderIndex);
for (const testId of [
'project-switcher-new-project',
@@ -168,13 +249,15 @@ describe('ProjectSwitcher dropdown behavior', () => {
expect(createDialogProps.at(-1)?.bridge).toBe(bridge);
});
- test('search filters before the ten-item slice, announces empty results, stops typeahead bubbling, and clears on close', async () => {
+ test('search matches projects only (not worktrees/branches), announces empty results, stops typeahead bubbling, and clears on close', async () => {
const bridge = createBridge();
render(<ProjectSwitcher bridge={bridge as never} />);
await openMenu();
const search = screen.getByTestId('project-switcher-search') as HTMLInputElement;
+ expect(search.placeholder).toBe('Search projects...');
+ expect(search.getAttribute('aria-label')).toBe('Search projects');
fireEvent.keyDown(search, { key: 'O' });
expect(keydownBubbleCount).toBe(0);
@@ -185,6 +268,8 @@ describe('ProjectSwitcher dropdown behavior', () => {
expect(screen.getByTestId('project-switcher-recent-/archive/omega-project')).not.toBeNull();
});
expect(screen.queryByTestId('project-switcher-recent-/projects/project-1')).toBeNull();
+ expect(screen.queryByTestId('project-switcher-worktree-/archive/omega-wt')).toBeNull();
+ expect(screen.queryByTestId('project-switcher-branch-omega-branch')).toBeNull();
fireEvent.change(search, { target: { value: 'does-not-exist' } });
@@ -199,4 +284,162 @@ describe('ProjectSwitcher dropdown behavior', () => {
expect((screen.getByTestId('project-switcher-search') as HTMLInputElement).value).toBe('');
});
});
+
+ test('the top-level "New worktree…" item opens the New Worktree dialog EMPTY (no pre-fill)', async () => {
+ const bridge = createBridge();
+ render(<ProjectSwitcher bridge={bridge as never} />);
+ await openMenu();
+
+ fireEvent.click(screen.getByTestId('project-switcher-new-worktree'));
+ const dialog = await waitFor(() => {
+ const el = screen.getByTestId('new-worktree-dialog');
+ expect(el.getAttribute('data-open')).toBe('true');
+ return el;
+ });
+ expect(dialog.getAttribute('data-initial-name')).toBe('');
+ expect(newWorktreeProps.at(-1)?.initialBranchName).toBe('');
+ });
+
+ test('the flyout "Create worktree …" action opens the dialog PRE-FILLED with the typed name', async () => {
+ const bridge = createBridge();
+ bridge.project.listRecent = mock(() =>
+ Promise.resolve([
+ {
+ name: 'current',
+ path: '/projects/current',
+ gitCommonDir: '/projects/current/.git',
+ mainRoot: '/projects/current',
+ isLinkedWorktree: false,
+ branch: 'main',
+ lastOpenedAt: '2026-07-01',
+ },
+ {
+ name: 'has-worktree',
+ path: '/projects/current/.ok/worktrees/has-worktree',
+ gitCommonDir: '/projects/current/.git',
+ mainRoot: '/projects/current',
+ isLinkedWorktree: true,
+ branch: 'has-worktree',
+ lastOpenedAt: '2026-07-01',
+ },
+ ]),
+ );
+ render(<ProjectSwitcher bridge={bridge as never} />);
+ await openMenu();
+
+ fireEvent.click(screen.getByTestId('project-switcher-toggle-/projects/current'));
+ const searchBox = (await screen.findByTestId(
+ 'project-switcher-flyout-search-/projects/current',
+ )) as HTMLInputElement;
+ fireEvent.change(searchBox, { target: { value: 'shiny-feature' } });
+
+ const createOption = await screen.findByTestId('project-switcher-flyout-create');
+ fireEvent.click(createOption);
+
+ const dialog = await waitFor(() => {
+ const el = screen.getByTestId('new-worktree-dialog');
+ expect(el.getAttribute('data-open')).toBe('true');
+ return el;
+ });
+ expect(dialog.getAttribute('data-initial-name')).toBe('shiny-feature');
+ expect(newWorktreeProps.at(-1)?.initialBranchName).toBe('shiny-feature');
+ });
+
+ test('threads branches and the already-has-a-worktree set from the cached model to the dialog', async () => {
+ const bridge = createBridge();
+ render(<ProjectSwitcher bridge={bridge as never} />);
+ await openMenu();
+
+ fireEvent.click(screen.getByTestId('project-switcher-new-worktree'));
+ await waitFor(() =>
+ expect(screen.getByTestId('new-worktree-dialog').getAttribute('data-open')).toBe('true'),
+ );
+
+ const props = newWorktreeProps.at(-1);
+ expect(props?.branches).toContain('omega-branch');
+ expect(props?.branches).toContain('has-worktree');
+ expect(props?.existingWorktreeBranches?.has('has-worktree')).toBe(true);
+ expect(props?.existingWorktreeBranches?.has('omega-branch')).toBe(false);
+ expect(props?.remoteBranches).toEqual([
+ 'origin/main',
+ 'origin/omega-branch',
+ 'origin/remote-only-x',
+ ]);
+ expect(props?.behindByBranch?.get('omega-branch')).toBe(4);
+ expect(props?.behindByBranch?.get('has-worktree')).toBe(0);
+ });
+
+ test('File menu "new-worktree" action opens the New Worktree dialog; "switch-worktree" opens the dropdown', async () => {
+ const bridge = createBridge();
+ render(<ProjectSwitcher bridge={bridge as never} />);
+ expect(menuActionCb).not.toBeNull();
+
+ act(() => menuActionCb?.('new-worktree'));
+ await waitFor(() =>
+ expect(screen.getByTestId('new-worktree-dialog').getAttribute('data-open')).toBe('true'),
+ );
+
+ act(() => menuActionCb?.('switch-worktree'));
+ await waitFor(() => {
+ expect(screen.getByTestId('project-switcher-search')).not.toBeNull();
+ });
+ });
+
+ test('on the Electron host, a row selection within the open-click guard window is swallowed, then works after it', async () => {
+ (window as unknown as { okDesktop?: unknown }).okDesktop = {};
+ const bridge = createBridge();
+ render(<ProjectSwitcher bridge={bridge as never} />);
+ await openMenu();
+
+ fireEvent.click(screen.getByTestId('project-switcher-recent-/projects/project-1'));
+ expect(bridge.project.open).not.toHaveBeenCalled();
+
+ await new Promise((resolve) => setTimeout(resolve, 450));
+ fireEvent.click(screen.getByTestId('project-switcher-recent-/projects/project-1'));
+ await waitFor(() => expect(bridge.project.open).toHaveBeenCalledTimes(1));
+ });
+
+ test('does not flash "No recent projects." while the first listRecent is in flight, then resolves cleanly', async () => {
+ let resolveList: (value: Array<{ name: string; path: string }>) => void = () => {};
+ const pending = new Promise<Array<{ name: string; path: string }>>((resolve) => {
+ resolveList = resolve;
+ });
+ const bridge = createBridge();
+ bridge.project.listRecent = mock(() => pending);
+ render(<ProjectSwitcher bridge={bridge as never} />);
+
+ fireEvent.click(screen.getByTestId('project-switcher-trigger'));
+ act(() => {
+ lastDropdownOpenChange?.(true);
+ });
+
+ expect(screen.queryByText('No recent projects.')).toBeNull();
+ expect(screen.queryByTestId('project-switcher-search')).toBeNull();
+ expect(screen.getByTestId('project-switcher-new-project')).not.toBeNull();
+
+ await act(async () => {
+ resolveList([recent('Current', '/projects/current'), recent('Project 1')]);
+ await pending;
+ });
+ await waitFor(() => {
+ expect(screen.getByTestId('project-switcher-search')).not.toBeNull();
+ });
+ expect(screen.queryByText('No recent projects.')).toBeNull();
+ });
+
+ test('shows "No recent projects." only once loaded AND genuinely empty', async () => {
+ const bridge = createBridge();
+ bridge.project.listRecent = mock(() => Promise.resolve([]));
+ render(<ProjectSwitcher bridge={bridge as never} />);
+
+ fireEvent.click(screen.getByTestId('project-switcher-trigger'));
+ act(() => {
+ lastDropdownOpenChange?.(true);
+ });
+
+ await waitFor(() => {
+ expect(screen.queryByText('No recent projects.')).not.toBeNull();
+ });
+ expect(screen.queryByTestId('project-switcher-search')).toBeNull();
+ });
});
diff --git a/packages/app/src/components/ProjectSwitcher.tsx b/packages/app/src/components/ProjectSwitcher.tsx
index be4cb9b38..2ac7fe28b 100644
--- a/packages/app/src/components/ProjectSwitcher.tsx
+++ b/packages/app/src/components/ProjectSwitcher.tsx
@@ -12,10 +12,13 @@ import {
import { InputGroup, InputGroupAddon, InputGroupInput } from '@/components/ui/input-group';
import { SidebarMenuButton } from '@/components/ui/sidebar';
import { useCurrentBranch } from '@/hooks/use-current-branch';
+import { useWorktrees } from '@/hooks/use-worktrees';
import type { OkDesktopBridge, RecentProjectEntry } from '@/lib/desktop-bridge-types';
import { runWithToast as runWithToastBase } from '@/lib/error-state';
import { cn } from '@/lib/utils';
import { CreateProjectDialog } from './CreateProjectDialog';
+import { NewWorktreeDialog } from './NewWorktreeDialog';
+import { RecentProjectsMenu } from './RecentProjectsMenu';
export const runWithToast = (
fn: () => Promise<void>,
@@ -23,24 +26,48 @@ export const runWithToast = (
toastApi?: { error(msg: string): void },
): Promise<void> => runWithToastBase(fn, fallback, toastApi, 'ProjectSwitcher');
+const SELECT_GUARD_MS = 350;
+
interface ProjectSwitcherProps {
bridge: OkDesktopBridge;
}
export function ProjectSwitcher({ bridge }: ProjectSwitcherProps) {
const { t } = useLingui();
- const [recents, setRecents] = useState<RecentProjectEntry[]>([]);
+ const [recents, setRecents] = useState<RecentProjectEntry[] | null>(null);
const [open, setOpen] = useState(false);
const [search, setSearch] = useState('');
const [createProjectOpen, setCreateProjectOpen] = useState(false);
+ const [newWorktreeOpen, setNewWorktreeOpen] = useState(false);
+ const [newWorktreeInitialName, setNewWorktreeInitialName] = useState('');
+ const [flyoutPath, setFlyoutPath] = useState<string | null>(null);
const branch = useCurrentBranch();
+ const worktreeModel = useWorktrees();
const isElectronHost = typeof window !== 'undefined' && window.okDesktop != null;
const sawPointerDownRef = useRef(false);
+ const withinOpenGuardRef = useRef(false);
+ const openGuardTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
const handleOpenChange = (next: boolean): void => {
+ if (next) {
+ withinOpenGuardRef.current = true;
+ if (openGuardTimerRef.current !== null) clearTimeout(openGuardTimerRef.current);
+ openGuardTimerRef.current = setTimeout(() => {
+ withinOpenGuardRef.current = false;
+ }, SELECT_GUARD_MS);
+ }
setOpen(next);
- if (!next) setSearch('');
+ if (!next) {
+ setSearch('');
+ setFlyoutPath(null);
+ }
+ };
+
+ const guardStaleSelect = (event: Event): boolean => {
+ if (!isElectronHost || !withinOpenGuardRef.current) return false;
+ event.preventDefault();
+ return true;
};
useEffect(() => {
@@ -55,16 +82,21 @@ export function ProjectSwitcher({ bridge }: ProjectSwitcherProps) {
};
}, [open, bridge, t]);
- const openProject = (path: string) => {
- setOpen(false);
- void runWithToast(
- () => bridge.project.open({ path, target: 'new-window', entryPoint: 'recents' }),
- t`Failed to open project.`,
- );
- };
+ useEffect(() => {
+ return bridge.onMenuAction((action) => {
+ if (action === 'new-worktree') {
+ setOpen(false);
+ setFlyoutPath(null);
+ setNewWorktreeInitialName('');
+ setNewWorktreeOpen(true);
+ } else if (action === 'switch-worktree') {
+ setOpen(true);
+ }
+ });
+ }, [bridge]);
const onOpenFolder = () => {
- setOpen(false);
+ handleOpenChange(false);
void runWithToast(async () => {
const path = await bridge.dialog.openFolder();
if (!path) return;
@@ -73,24 +105,29 @@ export function ProjectSwitcher({ bridge }: ProjectSwitcherProps) {
};
const onSwitchProject = () => {
- setOpen(false);
+ handleOpenChange(false);
void runWithToast(() => bridge.navigator.open(), t`Failed to open Project Navigator.`);
};
const onCreateProject = () => {
- setOpen(false);
+ handleOpenChange(false);
setCreateProjectOpen(true);
};
- const currentPath = bridge.config.projectPath;
- const switchable = recents.filter((r) => r.path !== currentPath);
+ const openNewWorktreeWith = (name: string) => {
+ handleOpenChange(false);
+ setNewWorktreeInitialName(name);
+ setNewWorktreeOpen(true);
+ };
+ const currentPath = bridge.config.projectPath;
const query = search.trim().toLowerCase();
- const filtered = query
- ? switchable.filter(
- (r) => r.name.toLowerCase().includes(query) || r.path.toLowerCase().includes(query),
- )
- : switchable;
+ const isSearching = query !== '';
+ const loadedRecents = recents ?? [];
+ const menuRecents = isSearching
+ ? loadedRecents.filter((r) => !r.isLinkedWorktree)
+ : loadedRecents;
+ const menuWorktreeModel = isSearching ? null : worktreeModel;
return (
<>
@@ -154,9 +191,14 @@ export function ProjectSwitcher({ bridge }: ProjectSwitcherProps) {
className="min-w-[260px]"
data-testid="project-switcher-menu"
>
- {switchable.length === 0 ? (
+ {/* Three states, not two: while `recents` is null the first fetch is
+ still in flight — render nothing here (just the pinned footer actions
+ below) rather than the empty label, so first open doesn't flash "No
+ recent projects." before the list arrives. The label is only correct
+ once loaded (`recents !== null`) AND empty. */}
+ {recents === null ? null : recents.length === 0 ? (
<DropdownMenuLabel className="font-normal text-muted-foreground text-xs">
- <Trans>No other recent projects.</Trans>
+ <Trans>No recent projects.</Trans>
</DropdownMenuLabel>
) : (
<>
@@ -164,10 +206,13 @@ export function ProjectSwitcher({ bridge }: ProjectSwitcherProps) {
swallow keystrokes meant for the filter field. */}
<InputGroup className="mb-1 h-8 border-0 shadow-none has-[[data-slot=input-group-control]:focus-visible]:ring-0">
<InputGroupInput
- aria-label={t`Search recent projects`}
- placeholder={t`Search recent projects...`}
+ aria-label={t`Search projects`}
+ placeholder={t`Search projects...`}
value={search}
- onChange={(e) => setSearch(e.target.value)}
+ onChange={(e) => {
+ if (e.target.value !== '') setFlyoutPath(null);
+ setSearch(e.target.value);
+ }}
onKeyDown={(e) => e.stopPropagation()}
data-testid="project-switcher-search"
/>
@@ -176,56 +221,79 @@ export function ProjectSwitcher({ bridge }: ProjectSwitcherProps) {
</InputGroupAddon>
</InputGroup>
<DropdownMenuSeparator />
- {filtered.length === 0 ? (
- <DropdownMenuLabel
- className="font-normal text-muted-foreground text-xs"
- role="status"
- aria-live="polite"
- >
- <Trans>No matching projects.</Trans>
- </DropdownMenuLabel>
- ) : (
- <div className="max-h-64 overflow-x-hidden overflow-y-auto overscroll-contain subtle-scrollbar scroll-fade-mask">
- {filtered.slice(0, 10).map((row) => (
- <DropdownMenuItem
- key={row.path}
- disabled={row.missing}
- onSelect={() => openProject(row.path)}
- className="flex w-full min-w-0 flex-col items-start gap-0.5"
- data-testid={`project-switcher-recent-${row.path}`}
- >
- <span className="w-full truncate font-medium text-sm" title={row.name}>
- {row.name}
- </span>
- <span
- className="w-full truncate text-muted-foreground text-xs"
- title={row.path}
- >
- {row.path}
- {row.missing ? t` (missing)` : ''}
- </span>
- </DropdownMenuItem>
- ))}
- </div>
- )}
+ {/* Only the items list scrolls — the search field above and the
+ New / Switch / Open actions below stay pinned. Each group row's
+ worktree Popover flyout portals out of this wrapper, so the
+ scroll clip doesn't cut it off. overscroll-contain stops scroll
+ chaining to the page behind the dropdown at the list edges. */}
+ <div className="max-h-64 overflow-x-hidden overflow-y-auto overscroll-contain subtle-scrollbar scroll-fade-mask">
+ <RecentProjectsMenu
+ bridge={bridge}
+ recents={menuRecents}
+ currentPath={currentPath}
+ query={query}
+ worktreeModel={menuWorktreeModel}
+ closeMenu={() => handleOpenChange(false)}
+ guardStaleSelect={guardStaleSelect}
+ flyoutPath={flyoutPath}
+ setFlyoutPath={setFlyoutPath}
+ openNewWorktreeWith={openNewWorktreeWith}
+ />
+ </div>
</>
)}
<DropdownMenuSeparator />
- <DropdownMenuItem onSelect={onCreateProject} data-testid="project-switcher-new-project">
+ <DropdownMenuItem
+ onSelect={(e) => {
+ if (guardStaleSelect(e)) return;
+ onCreateProject();
+ }}
+ data-testid="project-switcher-new-project"
+ >
<Plus aria-hidden="true" className="text-muted-foreground" />
<Trans>New project</Trans>
</DropdownMenuItem>
<DropdownMenuItem
- onSelect={onSwitchProject}
+ onSelect={(e) => {
+ if (guardStaleSelect(e)) return;
+ onSwitchProject();
+ }}
data-testid="project-switcher-switch-project"
>
<LayoutGrid aria-hidden="true" className="text-muted-foreground" />
<Trans>Switch project</Trans>
</DropdownMenuItem>
- <DropdownMenuItem onSelect={onOpenFolder} data-testid="project-switcher-open-folder">
+ <DropdownMenuItem
+ onSelect={(e) => {
+ if (guardStaleSelect(e)) return;
+ onOpenFolder();
+ }}
+ data-testid="project-switcher-open-folder"
+ >
<FolderOpen aria-hidden="true" className="text-muted-foreground" />
<Trans>Open folder</Trans>
</DropdownMenuItem>
+ {/* "New worktree" sits at the bottom of the project-selection menu:
+ the per-project worktree flyouts are the primary worktree affordance
+ now, so the standalone create action is a secondary, last-position
+ entry. Gated on the current project being a git repo (a branch). */}
+ {branch !== null ? (
+ <>
+ <DropdownMenuSeparator />
+ <DropdownMenuItem
+ onSelect={(e) => {
+ if (guardStaleSelect(e)) return;
+ handleOpenChange(false);
+ setNewWorktreeInitialName('');
+ setNewWorktreeOpen(true);
+ }}
+ data-testid="project-switcher-new-worktree"
+ >
+ <GitBranch aria-hidden="true" className="text-muted-foreground" />
+ <Trans>New worktree</Trans>
+ </DropdownMenuItem>
+ </>
+ ) : null}
</DropdownMenuContent>
</DropdownMenu>
<CreateProjectDialog
@@ -233,6 +301,31 @@ export function ProjectSwitcher({ bridge }: ProjectSwitcherProps) {
onOpenChange={setCreateProjectOpen}
bridge={bridge}
/>
+ <NewWorktreeDialog
+ open={newWorktreeOpen}
+ onOpenChange={setNewWorktreeOpen}
+ bridge={bridge}
+ currentBranch={branch}
+ initialBranchName={newWorktreeInitialName}
+ branches={worktreeModel?.entries
+ .map((entry) => entry.branch)
+ .filter((b): b is string => b !== null)}
+ existingWorktreeBranches={
+ new Set(
+ worktreeModel?.entries
+ .filter((entry) => entry.branch !== null && entry.worktreePath !== null)
+ .map((entry) => entry.branch as string),
+ )
+ }
+ remoteBranches={worktreeModel?.remoteBranches}
+ behindByBranch={
+ new Map(
+ worktreeModel?.entries
+ .filter((entry) => entry.branch !== null && entry.behind !== undefined)
+ .map((entry) => [entry.branch as string, entry.behind as number]),
+ )
+ }
+ />
</>
);
}
diff --git a/packages/app/src/components/RecentProjectsMenu.dom.test.tsx b/packages/app/src/components/RecentProjectsMenu.dom.test.tsx
new file mode 100644
index 000000000..22e61a1ce
--- /dev/null
+++ b/packages/app/src/components/RecentProjectsMenu.dom.test.tsx
@@ -0,0 +1,804 @@
+import { beforeEach, describe, expect, mock, test } from 'bun:test';
+import type { WorktreeSelectorModel } from '@inkeep/open-knowledge-core';
+import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';
+import {
+ cloneElement,
+ createContext,
+ isValidElement,
+ type ReactElement,
+ type ReactNode,
+ use,
+ useEffect,
+ useState,
+} from 'react';
+import type { RecentProjectEntry } from '@/lib/desktop-bridge-types';
+import { RecentProjectsMenu } from './RecentProjectsMenu';
+
+type ItemProps = {
+ children?: ReactNode;
+ disabled?: boolean;
+ onSelect?: (e?: unknown) => void;
+ [key: string]: unknown;
+};
+
+mock.module('@/components/ui/dropdown-menu', () => ({
+ DropdownMenuItem: ({ children, onSelect, ...props }: ItemProps) => (
+ <div
+ role="menuitem"
+ tabIndex={-1}
+ onClick={(e) => onSelect?.(e as unknown as Event)}
+ onKeyDown={() => {}}
+ {...props}
+ >
+ {children}
+ </div>
+ ),
+ DropdownMenuLabel: ({ children, ...props }: ItemProps) => <div {...props}>{children}</div>,
+}));
+mock.module('@/components/ui/button', () => ({
+ Button: ({
+ children,
+ onClick,
+ onMouseDown,
+ ...props
+ }: ItemProps & {
+ onClick?: (e: unknown) => void;
+ onMouseDown?: (e: unknown) => void;
+ }) => (
+ <button
+ type="button"
+ onClick={(e) => onClick?.(e)}
+ onMouseDown={(e) => onMouseDown?.(e)}
+ {...props}
+ >
+ {children}
+ </button>
+ ),
+}));
+
+const PopoverStateContext = createContext<{ open: boolean; onOpenChange: (o: boolean) => void }>({
+ open: false,
+ onOpenChange: () => {},
+});
+mock.module('@/components/ui/popover', () => ({
+ Popover: ({
+ children,
+ open,
+ onOpenChange,
+ }: {
+ children?: ReactNode;
+ open?: boolean;
+ onOpenChange?: (o: boolean) => void;
+ }) => (
+ <PopoverStateContext value={{ open: !!open, onOpenChange: onOpenChange ?? (() => {}) }}>
+ {children}
+ </PopoverStateContext>
+ ),
+ PopoverTrigger: ({ children }: { children?: ReactNode }) => {
+ const { open, onOpenChange } = use(PopoverStateContext);
+ if (!isValidElement(children)) return <>{children}</>;
+ const child = children as ReactElement<{ onClick?: (e: unknown) => void }>;
+ return cloneElement(child, {
+ onClick: (e: unknown) => {
+ child.props.onClick?.(e);
+ onOpenChange(!open);
+ },
+ });
+ },
+ PopoverContent: ({
+ children,
+ side: _side,
+ align: _align,
+ sideOffset: _sideOffset,
+ onPointerDownOutside: _onPointerDownOutside,
+ onFocusOutside: _onFocusOutside,
+ onOpenAutoFocus,
+ ...props
+ }: ItemProps & { onOpenAutoFocus?: (e: Event) => void }) => {
+ const { open } = use(PopoverStateContext);
+ useEffect(() => {
+ if (open) onOpenAutoFocus?.(new Event('focus'));
+ }, [open, onOpenAutoFocus]);
+ if (!open) return null;
+ return <div {...props}>{children}</div>;
+ },
+}));
+
+mock.module('@/components/ui/input-group', () => ({
+ InputGroup: ({ children, ...props }: ItemProps) => <div {...props}>{children}</div>,
+ InputGroupAddon: ({ children }: { children?: ReactNode }) => <span>{children}</span>,
+ InputGroupInput: (props: React.InputHTMLAttributes<HTMLInputElement>) => <input {...props} />,
+}));
+
+const refreshWorktrees = mock(() => {});
+mock.module('@/lib/worktree-store', () => ({ refreshWorktrees }));
+const toastError = mock((_msg: string) => {});
+mock.module('sonner', () => ({ toast: { error: toastError, success: mock(() => {}) } }));
+
+function main(path: string, commonDir: string): RecentProjectEntry {
+ return {
+ path,
+ name: path.split('/').pop() ?? path,
+ lastOpenedAt: '2026-07-01',
+ gitCommonDir: commonDir,
+ mainRoot: path,
+ isLinkedWorktree: false,
+ branch: 'main',
+ };
+}
+function worktree(
+ path: string,
+ commonDir: string,
+ mainRoot: string,
+ branch: string,
+ lastOpenedAt = '2026-07-01',
+): RecentProjectEntry {
+ return {
+ path,
+ name: path.split('/').pop() ?? path,
+ lastOpenedAt,
+ gitCommonDir: commonDir,
+ mainRoot,
+ isLinkedWorktree: true,
+ branch,
+ };
+}
+function nonGit(path: string): RecentProjectEntry {
+ return { path, name: path.split('/').pop() ?? path, lastOpenedAt: '2026-07-01' };
+}
+
+function model(
+ entries: WorktreeSelectorModel['entries'],
+ mainRoot = '/repo',
+): WorktreeSelectorModel {
+ return { mainRoot, currentBranch: 'main', entries, remoteBranches: [] };
+}
+
+function createBridge() {
+ return {
+ project: { open: mock(() => Promise.resolve()) },
+ worktree: {
+ create: mock(() =>
+ Promise.resolve({
+ ok: true as const,
+ path: '/repo/.ok/worktrees/feature-x',
+ created: true,
+ }),
+ ),
+ },
+ };
+}
+
+const noGuard = () => false;
+
+function Host({
+ bridge,
+ recents,
+ currentPath,
+ query,
+ worktreeModel,
+ closeMenu,
+ openNewWorktreeWith,
+}: {
+ bridge: ReturnType<typeof createBridge>;
+ recents: RecentProjectEntry[];
+ currentPath: string;
+ query: string;
+ worktreeModel: WorktreeSelectorModel | null;
+ closeMenu: () => void;
+ openNewWorktreeWith: (name: string) => void;
+}) {
+ const [flyoutPath, setFlyoutPath] = useState<string | null>(null);
+ return (
+ <RecentProjectsMenu
+ bridge={bridge as never}
+ recents={recents}
+ currentPath={currentPath}
+ query={query}
+ worktreeModel={worktreeModel}
+ closeMenu={closeMenu}
+ guardStaleSelect={noGuard}
+ flyoutPath={flyoutPath}
+ setFlyoutPath={setFlyoutPath}
+ openNewWorktreeWith={openNewWorktreeWith}
+ />
+ );
+}
+
+function renderMenu(
+ overrides: Partial<{
+ bridge: ReturnType<typeof createBridge>;
+ recents: RecentProjectEntry[];
+ currentPath: string;
+ query: string;
+ worktreeModel: WorktreeSelectorModel | null;
+ closeMenu: () => void;
+ openNewWorktreeWith: (name: string) => void;
+ }> = {},
+) {
+ const bridge = overrides.bridge ?? createBridge();
+ const closeMenu = overrides.closeMenu ?? mock(() => {});
+ const openNewWorktreeWith = overrides.openNewWorktreeWith ?? mock((_name: string) => {});
+ render(
+ <Host
+ bridge={bridge}
+ recents={overrides.recents ?? []}
+ currentPath={overrides.currentPath ?? '/other'}
+ query={overrides.query ?? ''}
+ worktreeModel={overrides.worktreeModel ?? null}
+ closeMenu={closeMenu}
+ openNewWorktreeWith={openNewWorktreeWith}
+ />,
+ );
+ return { bridge, closeMenu, openNewWorktreeWith };
+}
+
+describe('RecentProjectsMenu — grouped browse (no query)', () => {
+ beforeEach(cleanup);
+
+ test('project rows carry NO folder icon (switcher stays focused on names)', () => {
+ renderMenu({ recents: [nonGit('/notes')] });
+ const row = screen.getByTestId('project-switcher-recent-/notes');
+ expect(row.querySelector('svg')).toBeNull();
+ });
+
+ test('the expander opens the worktree flyout (does not open the project)', async () => {
+ const { bridge } = renderMenu({
+ recents: [
+ main('/repo', '/repo/.git'),
+ worktree('/repo/.ok/worktrees/dev', '/repo/.git', '/repo', 'dev'),
+ ],
+ });
+
+ const groupRow = screen.getByTestId('project-switcher-group-/repo');
+ expect(groupRow.textContent).toContain('/repo');
+ expect(screen.queryByTestId('project-switcher-flyout-/repo')).toBeNull();
+
+ const toggle = screen.getByTestId('project-switcher-toggle-/repo');
+ expect(toggle.querySelectorAll('svg').length).toBe(1);
+ expect(toggle.textContent).toContain('1 worktree');
+ expect(toggle.textContent).not.toContain('1 worktrees');
+
+ fireEvent.click(screen.getByTestId('project-switcher-toggle-/repo'));
+ await waitFor(() => {
+ expect(screen.getByTestId('project-switcher-flyout-/repo')).not.toBeNull();
+ });
+ expect(bridge.project.open).not.toHaveBeenCalled();
+ });
+
+ test('hovering the expander opens the flyout (hover-open, not click-only) without opening the project', async () => {
+ const { bridge } = renderMenu({
+ recents: [
+ main('/repo', '/repo/.git'),
+ worktree('/repo/.ok/worktrees/dev', '/repo/.git', '/repo', 'dev'),
+ ],
+ });
+ expect(screen.queryByTestId('project-switcher-flyout-/repo')).toBeNull();
+ fireEvent.mouseEnter(screen.getByTestId('project-switcher-toggle-/repo'));
+ await waitFor(() => {
+ expect(screen.getByTestId('project-switcher-flyout-/repo')).not.toBeNull();
+ });
+ expect(bridge.project.open).not.toHaveBeenCalled();
+ });
+
+ test('keyboard: ArrowRight on the group row opens its flyout; ArrowLeft and Escape close it (a11y C7)', async () => {
+ const { bridge } = renderMenu({
+ recents: [
+ main('/repo', '/repo/.git'),
+ worktree('/repo/.ok/worktrees/dev', '/repo/.git', '/repo', 'dev'),
+ ],
+ });
+ const row = screen.getByTestId('project-switcher-group-/repo');
+ expect(screen.queryByTestId('project-switcher-flyout-/repo')).toBeNull();
+
+ fireEvent.keyDown(row, { key: 'ArrowRight' });
+ await waitFor(() => {
+ expect(screen.getByTestId('project-switcher-flyout-/repo')).not.toBeNull();
+ });
+ expect(bridge.project.open).not.toHaveBeenCalled();
+
+ await waitFor(() => {
+ expect(document.activeElement).toBe(
+ screen.getByTestId('project-switcher-flyout-search-/repo'),
+ );
+ });
+
+ fireEvent.keyDown(row, { key: 'ArrowLeft' });
+ await waitFor(() => {
+ expect(screen.queryByTestId('project-switcher-flyout-/repo')).toBeNull();
+ });
+
+ fireEvent.keyDown(row, { key: 'ArrowRight' });
+ await waitFor(() => {
+ expect(screen.getByTestId('project-switcher-flyout-/repo')).not.toBeNull();
+ });
+ fireEvent.keyDown(row, { key: 'Escape' });
+ await waitFor(() => {
+ expect(screen.queryByTestId('project-switcher-flyout-/repo')).toBeNull();
+ });
+ });
+
+ test('the flyout lists the default (main) first, then the opened worktree; opening one opens its window', async () => {
+ const { bridge } = renderMenu({
+ recents: [
+ main('/repo', '/repo/.git'),
+ worktree('/repo/.ok/worktrees/dev', '/repo/.git', '/repo', 'dev'),
+ ],
+ });
+ fireEvent.click(screen.getByTestId('project-switcher-toggle-/repo'));
+
+ const mainEntry = await screen.findByTestId('project-switcher-flyout-entry-/repo');
+ expect(mainEntry.textContent).toContain('main');
+ expect(mainEntry.textContent).toContain('default');
+ const devEntry = screen.getByTestId('project-switcher-flyout-entry-/repo/.ok/worktrees/dev');
+ expect(devEntry.textContent).toContain('dev');
+
+ expect(mainEntry.querySelector('svg')).toBeNull();
+ expect(devEntry.querySelector('svg')).toBeNull();
+ const flyoutSearch = screen.getByTestId('project-switcher-flyout-search-/repo');
+ expect(flyoutSearch.parentElement?.querySelectorAll('svg').length).toBe(1);
+
+ fireEvent.click(devEntry);
+ await waitFor(() => {
+ expect(bridge.project.open).toHaveBeenCalledWith({
+ path: '/repo/.ok/worktrees/dev',
+ target: 'new-window',
+ entryPoint: 'worktree',
+ });
+ });
+ });
+
+ test('opened worktrees sort by recency (most-recently-opened first)', async () => {
+ renderMenu({
+ recents: [
+ main('/repo', '/repo/.git'),
+ worktree('/repo/.ok/worktrees/older', '/repo/.git', '/repo', 'older', '2026-06-01'),
+ worktree('/repo/.ok/worktrees/newer', '/repo/.git', '/repo', 'newer', '2026-06-30'),
+ ],
+ });
+ expect(screen.getByTestId('project-switcher-toggle-/repo').textContent).toContain(
+ '2 worktrees',
+ );
+ fireEvent.click(screen.getByTestId('project-switcher-toggle-/repo'));
+
+ const flyout = await screen.findByTestId('project-switcher-flyout-/repo');
+ const ids = [...flyout.querySelectorAll('[data-testid^="project-switcher-flyout-entry-"]')].map(
+ (el) => el.getAttribute('data-testid'),
+ );
+ expect(ids).toEqual([
+ 'project-switcher-flyout-entry-/repo',
+ 'project-switcher-flyout-entry-/repo/.ok/worktrees/newer',
+ 'project-switcher-flyout-entry-/repo/.ok/worktrees/older',
+ ]);
+ });
+
+ test('the flyout search filters that project’s worktrees + branches; a create-on-demand branch creates its worktree', async () => {
+ const { bridge } = renderMenu({
+ recents: [
+ main('/repo', '/repo/.git'),
+ worktree('/repo/.ok/worktrees/dev', '/repo/.git', '/repo', 'dev'),
+ ],
+ currentPath: '/repo',
+ worktreeModel: model([
+ { branch: 'main', worktreePath: '/repo', isCurrent: true, isMain: true, locked: false },
+ {
+ branch: 'dev',
+ worktreePath: '/repo/.ok/worktrees/dev',
+ isCurrent: false,
+ isMain: false,
+ locked: false,
+ },
+ { branch: 'feature-x', worktreePath: null, isCurrent: false, isMain: false, locked: false },
+ ]),
+ });
+ fireEvent.click(screen.getByTestId('project-switcher-toggle-/repo'));
+ await screen.findByTestId('project-switcher-flyout-/repo');
+
+ const createRow = screen.getByTestId('project-switcher-flyout-entry-branch:feature-x');
+ expect(createRow.textContent).toContain('feature-x');
+ expect(createRow.textContent).toContain('create worktree');
+
+ const searchBox = screen.getByTestId(
+ 'project-switcher-flyout-search-/repo',
+ ) as HTMLInputElement;
+ expect(searchBox.placeholder).toBe('Search worktrees');
+ fireEvent.change(searchBox, { target: { value: 'feature' } });
+ await waitFor(() => {
+ expect(
+ screen.queryByTestId('project-switcher-flyout-entry-/repo/.ok/worktrees/dev'),
+ ).toBeNull();
+ });
+ expect(screen.getByTestId('project-switcher-flyout-entry-branch:feature-x')).not.toBeNull();
+
+ fireEvent.click(screen.getByTestId('project-switcher-flyout-entry-branch:feature-x'));
+ await waitFor(() => {
+ expect(bridge.worktree.create).toHaveBeenCalledWith({
+ branch: 'feature-x',
+ createBranch: false,
+ });
+ });
+ await waitFor(() => {
+ expect(bridge.project.open).toHaveBeenCalledWith({
+ path: '/repo/.ok/worktrees/feature-x',
+ target: 'new-window',
+ entryPoint: 'worktree',
+ });
+ });
+ expect(refreshWorktrees).toHaveBeenCalled();
+ });
+
+ test('the current project flyout offers "Create worktree <query>" when nothing matches; clicking it opens the pre-filled dialog', async () => {
+ const openNewWorktreeWith = mock((_name: string) => {});
+ renderMenu({
+ recents: [
+ main('/repo', '/repo/.git'),
+ worktree('/repo/.ok/worktrees/dev', '/repo/.git', '/repo', 'dev'),
+ ],
+ currentPath: '/repo',
+ worktreeModel: model([
+ { branch: 'main', worktreePath: '/repo', isCurrent: true, isMain: true, locked: false },
+ {
+ branch: 'dev',
+ worktreePath: '/repo/.ok/worktrees/dev',
+ isCurrent: false,
+ isMain: false,
+ locked: false,
+ },
+ ]),
+ openNewWorktreeWith,
+ });
+ fireEvent.click(screen.getByTestId('project-switcher-toggle-/repo'));
+ await screen.findByTestId('project-switcher-flyout-/repo');
+
+ const searchBox = screen.getByTestId(
+ 'project-switcher-flyout-search-/repo',
+ ) as HTMLInputElement;
+ fireEvent.change(searchBox, { target: { value: ' new-thing ' } });
+ await waitFor(() => {
+ expect(screen.getByText('No matching worktrees or branches.')).not.toBeNull();
+ });
+ const createOption = screen.getByTestId('project-switcher-flyout-create');
+ expect(createOption.textContent).toContain('Create worktree');
+ expect(createOption.textContent).toContain('new-thing');
+
+ fireEvent.click(createOption);
+ expect(openNewWorktreeWith).toHaveBeenCalledWith('new-thing');
+ });
+
+ test('the create option is absent when the query is only whitespace (nothing to name)', async () => {
+ renderMenu({
+ recents: [
+ main('/repo', '/repo/.git'),
+ worktree('/repo/.ok/worktrees/dev', '/repo/.git', '/repo', 'dev'),
+ ],
+ currentPath: '/repo',
+ worktreeModel: model([
+ { branch: 'main', worktreePath: '/repo', isCurrent: true, isMain: true, locked: false },
+ {
+ branch: 'dev',
+ worktreePath: '/repo/.ok/worktrees/dev',
+ isCurrent: false,
+ isMain: false,
+ locked: false,
+ },
+ ]),
+ });
+ fireEvent.click(screen.getByTestId('project-switcher-toggle-/repo'));
+ await screen.findByTestId('project-switcher-flyout-/repo');
+ const searchBox = screen.getByTestId(
+ 'project-switcher-flyout-search-/repo',
+ ) as HTMLInputElement;
+ fireEvent.change(searchBox, { target: { value: ' ' } });
+ expect(screen.queryByTestId('project-switcher-flyout-create')).toBeNull();
+ });
+
+ test('a NON-current project flyout does NOT offer the create option (creation anchors to the current project)', async () => {
+ renderMenu({
+ recents: [
+ main('/repo', '/repo/.git'),
+ worktree('/repo/.ok/worktrees/dev', '/repo/.git', '/repo', 'dev'),
+ ],
+ currentPath: '/elsewhere',
+ worktreeModel: model(
+ [
+ {
+ branch: 'other-branch',
+ worktreePath: null,
+ isCurrent: false,
+ isMain: false,
+ locked: false,
+ },
+ ],
+ '/elsewhere',
+ ),
+ });
+ fireEvent.click(screen.getByTestId('project-switcher-toggle-/repo'));
+ await screen.findByTestId('project-switcher-flyout-/repo');
+ const searchBox = screen.getByTestId(
+ 'project-switcher-flyout-search-/repo',
+ ) as HTMLInputElement;
+ fireEvent.change(searchBox, { target: { value: 'zzz-no-match' } });
+ await waitFor(() => {
+ expect(screen.getByText('No matching worktrees or branches.')).not.toBeNull();
+ });
+ expect(screen.queryByTestId('project-switcher-flyout-create')).toBeNull();
+ });
+
+ test('a non-current project flyout shows only its opened worktrees (no branch model)', async () => {
+ renderMenu({
+ recents: [
+ main('/repo', '/repo/.git'),
+ worktree('/repo/.ok/worktrees/dev', '/repo/.git', '/repo', 'dev'),
+ ],
+ currentPath: '/elsewhere',
+ worktreeModel: model(
+ [
+ {
+ branch: 'other-branch',
+ worktreePath: null,
+ isCurrent: false,
+ isMain: false,
+ locked: false,
+ },
+ ],
+ '/elsewhere',
+ ),
+ });
+ fireEvent.click(screen.getByTestId('project-switcher-toggle-/repo'));
+ const flyout = await screen.findByTestId('project-switcher-flyout-/repo');
+ expect(flyout.textContent).not.toContain('other-branch');
+ expect(screen.getByTestId('project-switcher-flyout-entry-/repo')).not.toBeNull();
+ expect(
+ screen.getByTestId('project-switcher-flyout-entry-/repo/.ok/worktrees/dev'),
+ ).not.toBeNull();
+ });
+
+ test('clicking the project name opens the bare project (root), not the flyout', async () => {
+ const { bridge } = renderMenu({
+ recents: [
+ main('/repo', '/repo/.git'),
+ worktree('/repo/.ok/worktrees/dev', '/repo/.git', '/repo', 'dev'),
+ ],
+ });
+ fireEvent.click(screen.getByTestId('project-switcher-group-/repo'));
+ await waitFor(() => {
+ expect(bridge.project.open).toHaveBeenCalledWith({
+ path: '/repo',
+ target: 'new-window',
+ entryPoint: 'recents',
+ });
+ });
+ });
+
+ test('a non-git recent is a flat row that opens with the recents entry point', async () => {
+ const { bridge } = renderMenu({ recents: [nonGit('/notes')] });
+ expect(screen.queryByTestId('project-switcher-group-/notes')).toBeNull();
+ fireEvent.click(screen.getByTestId('project-switcher-recent-/notes'));
+ await waitFor(() => {
+ expect(bridge.project.open).toHaveBeenCalledWith({
+ path: '/notes',
+ target: 'new-window',
+ entryPoint: 'recents',
+ });
+ });
+ });
+
+ test('the current project row no-ops on select and just closes the menu', async () => {
+ const { bridge, closeMenu } = renderMenu({
+ recents: [nonGit('/notes')],
+ currentPath: '/notes',
+ });
+ fireEvent.click(screen.getByTestId('project-switcher-recent-/notes'));
+ expect(bridge.project.open).not.toHaveBeenCalled();
+ expect(closeMenu).toHaveBeenCalled();
+ });
+
+ test('a repo present only via a worktree synthesizes the project row', async () => {
+ renderMenu({
+ recents: [worktree('/repo/.ok/worktrees/dev', '/repo/.git', '/repo', 'dev')],
+ });
+ const groupRow = screen.getByTestId('project-switcher-group-/repo');
+ expect(groupRow.textContent).toContain('/repo');
+ fireEvent.click(screen.getByTestId('project-switcher-toggle-/repo'));
+ await screen.findByTestId('project-switcher-flyout-/repo');
+ expect(
+ screen.getByTestId('project-switcher-flyout-entry-/repo/.ok/worktrees/dev'),
+ ).not.toBeNull();
+ expect(screen.queryByTestId('project-switcher-flyout-entry-/repo')).toBeNull();
+ });
+});
+
+describe('RecentProjectsMenu — flyout keyboard navigation (item 29)', () => {
+ beforeEach(cleanup);
+
+ function openThreeRowFlyout() {
+ const utils = renderMenu({
+ recents: [
+ main('/repo', '/repo/.git'),
+ worktree('/repo/.ok/worktrees/older', '/repo/.git', '/repo', 'older', '2026-06-01'),
+ worktree('/repo/.ok/worktrees/newer', '/repo/.git', '/repo', 'newer', '2026-06-30'),
+ ],
+ });
+ fireEvent.keyDown(screen.getByTestId('project-switcher-group-/repo'), { key: 'ArrowRight' });
+ return utils;
+ }
+
+ const row = (key: string) => screen.getByTestId(`project-switcher-flyout-entry-${key}`);
+
+ test('ArrowDown from the search input moves focus to the first entry row', async () => {
+ openThreeRowFlyout();
+ const search = await screen.findByTestId('project-switcher-flyout-search-/repo');
+ await waitFor(() => expect(document.activeElement).toBe(search));
+
+ fireEvent.keyDown(search, { key: 'ArrowDown' });
+ expect(document.activeElement).toBe(row('/repo'));
+ });
+
+ test('ArrowDown / ArrowUp rove through the entry rows and clamp at the ends', async () => {
+ openThreeRowFlyout();
+ const search = await screen.findByTestId('project-switcher-flyout-search-/repo');
+ await waitFor(() => expect(document.activeElement).toBe(search));
+
+ fireEvent.keyDown(search, { key: 'ArrowDown' });
+ expect(document.activeElement).toBe(row('/repo'));
+
+ fireEvent.keyDown(row('/repo'), { key: 'ArrowDown' });
+ expect(document.activeElement).toBe(row('/repo/.ok/worktrees/newer'));
+ fireEvent.keyDown(row('/repo/.ok/worktrees/newer'), { key: 'ArrowDown' });
+ expect(document.activeElement).toBe(row('/repo/.ok/worktrees/older'));
+
+ fireEvent.keyDown(row('/repo/.ok/worktrees/older'), { key: 'ArrowDown' });
+ expect(document.activeElement).toBe(row('/repo/.ok/worktrees/older'));
+
+ fireEvent.keyDown(row('/repo/.ok/worktrees/older'), { key: 'ArrowUp' });
+ expect(document.activeElement).toBe(row('/repo/.ok/worktrees/newer'));
+ fireEvent.keyDown(row('/repo/.ok/worktrees/newer'), { key: 'ArrowUp' });
+ expect(document.activeElement).toBe(row('/repo'));
+ });
+
+ test('ArrowUp from the first entry row returns focus to the search input', async () => {
+ openThreeRowFlyout();
+ const search = await screen.findByTestId('project-switcher-flyout-search-/repo');
+ await waitFor(() => expect(document.activeElement).toBe(search));
+
+ fireEvent.keyDown(search, { key: 'ArrowDown' });
+ expect(document.activeElement).toBe(row('/repo'));
+
+ fireEvent.keyDown(row('/repo'), { key: 'ArrowUp' });
+ expect(document.activeElement).toBe(search);
+ });
+
+ test('Enter on a focused entry row opens that worktree (same action as a click)', async () => {
+ const { bridge } = openThreeRowFlyout();
+ const search = await screen.findByTestId('project-switcher-flyout-search-/repo');
+ await waitFor(() => expect(document.activeElement).toBe(search));
+
+ fireEvent.keyDown(search, { key: 'ArrowDown' });
+ fireEvent.keyDown(row('/repo'), { key: 'ArrowDown' });
+ expect(document.activeElement).toBe(row('/repo/.ok/worktrees/newer'));
+
+ fireEvent.keyDown(row('/repo/.ok/worktrees/newer'), { key: 'Enter' });
+ await waitFor(() => {
+ expect(bridge.project.open).toHaveBeenCalledWith({
+ path: '/repo/.ok/worktrees/newer',
+ target: 'new-window',
+ entryPoint: 'worktree',
+ });
+ });
+ });
+
+ test('typing in the search still filters the list, and ArrowDown enters the filtered rows', async () => {
+ openThreeRowFlyout();
+ const search = (await screen.findByTestId(
+ 'project-switcher-flyout-search-/repo',
+ )) as HTMLInputElement;
+ await waitFor(() => expect(document.activeElement).toBe(search));
+
+ fireEvent.change(search, { target: { value: 'newer' } });
+ await waitFor(() => {
+ expect(
+ screen.queryByTestId('project-switcher-flyout-entry-/repo/.ok/worktrees/older'),
+ ).toBeNull();
+ });
+ fireEvent.keyDown(search, { key: 'ArrowDown' });
+ expect(document.activeElement).toBe(row('/repo/.ok/worktrees/newer'));
+ });
+});
+
+describe('RecentProjectsMenu — search (cross-project)', () => {
+ beforeEach(cleanup);
+
+ test('project search rows carry NO folder icon', () => {
+ renderMenu({ recents: [main('/repo', '/repo/.git')], query: 'repo' });
+ const row = screen.getByTestId('project-switcher-recent-/repo');
+ expect(row.querySelector('svg')).toBeNull();
+ });
+
+ test('matches an opened worktree by branch name and opens it as a worktree', async () => {
+ const { bridge } = renderMenu({
+ recents: [
+ main('/repo', '/repo/.git'),
+ worktree('/repo/.ok/worktrees/dev', '/repo/.git', '/repo', 'dev'),
+ ],
+ query: 'dev',
+ });
+ const row = screen.getByTestId('project-switcher-worktree-/repo/.ok/worktrees/dev');
+ expect(row.textContent).toContain('dev');
+ expect(row.textContent).toContain('repo');
+ fireEvent.click(row);
+ await waitFor(() => {
+ expect(bridge.project.open).toHaveBeenCalledWith({
+ path: '/repo/.ok/worktrees/dev',
+ target: 'new-window',
+ entryPoint: 'worktree',
+ });
+ });
+ });
+
+ test('matches an un-opened branch from the cached model and creates its worktree on demand', async () => {
+ const { bridge } = renderMenu({
+ query: 'feature',
+ worktreeModel: model([
+ { branch: 'feature-x', worktreePath: null, isCurrent: false, isMain: false, locked: false },
+ ]),
+ });
+ expect(screen.getByTestId('project-switcher-branch-feature-x').textContent).toContain('repo');
+ fireEvent.click(screen.getByTestId('project-switcher-branch-feature-x'));
+ await waitFor(() => {
+ expect(bridge.worktree.create).toHaveBeenCalledWith({
+ branch: 'feature-x',
+ createBranch: false,
+ });
+ });
+ await waitFor(() => {
+ expect(bridge.project.open).toHaveBeenCalledWith({
+ path: '/repo/.ok/worktrees/feature-x',
+ target: 'new-window',
+ entryPoint: 'worktree',
+ });
+ });
+ expect(refreshWorktrees).toHaveBeenCalled();
+ });
+
+ test('does not double-list a branch already shown as an opened worktree', () => {
+ renderMenu({
+ recents: [worktree('/repo/.ok/worktrees/dev', '/repo/.git', '/repo', 'dev')],
+ query: 'dev',
+ worktreeModel: model([
+ {
+ branch: 'dev',
+ worktreePath: '/repo/.ok/worktrees/dev',
+ isCurrent: false,
+ isMain: false,
+ locked: false,
+ },
+ ]),
+ });
+ expect(screen.getByTestId('project-switcher-worktree-/repo/.ok/worktrees/dev')).not.toBeNull();
+ expect(screen.queryByTestId('project-switcher-branch-dev')).toBeNull();
+ });
+
+ test('announces when nothing matches', () => {
+ renderMenu({ recents: [main('/repo', '/repo/.git')], query: 'zzz-nothing' });
+ expect(screen.getByRole('status').textContent).toBe('No matching projects.');
+ });
+
+ test('a failed create-on-demand toasts and does not open a window', async () => {
+ toastError.mockClear();
+ const bridge = createBridge();
+ bridge.worktree.create = mock(() =>
+ Promise.resolve({ ok: false as const, reason: 'branch-exists' as const }),
+ );
+ renderMenu({
+ bridge,
+ query: 'feature',
+ worktreeModel: model([
+ { branch: 'feature-x', worktreePath: null, isCurrent: false, isMain: false, locked: false },
+ ]),
+ });
+ fireEvent.click(screen.getByTestId('project-switcher-branch-feature-x'));
+ await waitFor(() => expect(bridge.worktree.create).toHaveBeenCalledTimes(1));
+ await waitFor(() => expect(toastError).toHaveBeenCalled());
+ expect(bridge.project.open).not.toHaveBeenCalled();
+ });
+});
diff --git a/packages/app/src/components/RecentProjectsMenu.tsx b/packages/app/src/components/RecentProjectsMenu.tsx
new file mode 100644
index 000000000..a06a9cb25
--- /dev/null
+++ b/packages/app/src/components/RecentProjectsMenu.tsx
@@ -0,0 +1,638 @@
+import type { WorktreeSelectorEntry, WorktreeSelectorModel } from '@inkeep/open-knowledge-core';
+import { Plural, Trans, useLingui } from '@lingui/react/macro';
+import { Check, ChevronRight, GitBranch, Plus } from 'lucide-react';
+import type * as React from 'react';
+import { useRef, useState } from 'react';
+import { toast } from 'sonner';
+import { Button } from '@/components/ui/button';
+import { DropdownMenuItem, DropdownMenuLabel } from '@/components/ui/dropdown-menu';
+import { InputGroup, InputGroupAddon, InputGroupInput } from '@/components/ui/input-group';
+import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover';
+import type { OkDesktopBridge, RecentProjectEntry } from '@/lib/desktop-bridge-types';
+import { cn } from '@/lib/utils';
+import { refreshWorktrees } from '@/lib/worktree-store';
+import {
+ basenameOf,
+ buildWorktreeFlyoutEntries,
+ groupRecentsByRepo,
+ type RecentRepoGroup,
+ type WorktreeFlyoutEntry,
+} from './project-switcher-recents';
+
+interface RecentProjectsMenuProps {
+ bridge: OkDesktopBridge;
+ recents: readonly RecentProjectEntry[];
+ currentPath: string;
+ query: string;
+ worktreeModel: WorktreeSelectorModel | null;
+ closeMenu: () => void;
+ guardStaleSelect: (event: Event) => boolean;
+ flyoutPath: string | null;
+ setFlyoutPath: (path: string | null) => void;
+ openNewWorktreeWith: (name: string) => void;
+}
+
+export function RecentProjectsMenu({
+ bridge,
+ recents,
+ currentPath,
+ query,
+ worktreeModel,
+ closeMenu,
+ guardStaleSelect,
+ flyoutPath,
+ setFlyoutPath,
+ openNewWorktreeWith,
+}: RecentProjectsMenuProps) {
+ const { t } = useLingui();
+
+ function openPath(path: string, entryPoint: 'recents' | 'worktree'): void {
+ closeMenu();
+ void bridge.project.open({ path, target: 'new-window', entryPoint }).catch((err) => {
+ console.warn('[RecentProjectsMenu] project.open failed:', err);
+ toast.error(t`Failed to open.`);
+ });
+ }
+
+ async function createAndOpenBranch(branch: string): Promise<void> {
+ try {
+ const result = await bridge.worktree.create({ branch, createBranch: false });
+ if (!result.ok) {
+ toast.error(t`Couldn't open a worktree for that branch.`);
+ return;
+ }
+ refreshWorktrees();
+ await bridge.project.open({
+ path: result.path,
+ target: 'new-window',
+ entryPoint: 'worktree',
+ });
+ } catch (err) {
+ console.warn('[RecentProjectsMenu] create/open branch failed:', err);
+ toast.error(t`Failed to open worktree.`);
+ }
+ }
+
+ function onPickEntry(entry: RecentProjectEntry): void {
+ if (entry.path === currentPath) {
+ closeMenu();
+ return;
+ }
+ openPath(entry.path, entry.isLinkedWorktree ? 'worktree' : 'recents');
+ }
+
+ function onPickFlyoutEntry(entry: WorktreeFlyoutEntry): void {
+ if (entry.path !== null) {
+ if (entry.path === currentPath) {
+ closeMenu();
+ return;
+ }
+ openPath(entry.path, entry.isMain ? 'recents' : 'worktree');
+ return;
+ }
+ if (entry.branch !== null) {
+ closeMenu();
+ void createAndOpenBranch(entry.branch);
+ }
+ }
+
+ if (query !== '') {
+ return (
+ <SearchResults
+ recents={recents}
+ currentPath={currentPath}
+ query={query}
+ worktreeModel={worktreeModel}
+ onPickEntry={onPickEntry}
+ onPickBranch={(branch) => {
+ closeMenu();
+ void createAndOpenBranch(branch);
+ }}
+ guardStaleSelect={guardStaleSelect}
+ />
+ );
+ }
+
+ const groups = groupRecentsByRepo(recents);
+ return (
+ <>
+ {groups.map((group) => (
+ <GroupRow
+ key={group.project.path}
+ group={group}
+ currentPath={currentPath}
+ worktreeModel={worktreeModel}
+ flyoutOpen={flyoutPath === group.project.path}
+ setFlyoutOpen={(next) => setFlyoutPath(next ? group.project.path : null)}
+ onPickProject={() => {
+ if (group.project.path === currentPath) {
+ closeMenu();
+ return;
+ }
+ openPath(group.project.path, 'recents');
+ }}
+ onPickFlyoutEntry={onPickFlyoutEntry}
+ guardStaleSelect={guardStaleSelect}
+ openNewWorktreeWith={openNewWorktreeWith}
+ />
+ ))}
+ </>
+ );
+}
+
+function GroupRow({
+ group,
+ currentPath,
+ worktreeModel,
+ flyoutOpen,
+ setFlyoutOpen,
+ onPickProject,
+ onPickFlyoutEntry,
+ guardStaleSelect,
+ openNewWorktreeWith,
+}: {
+ group: RecentRepoGroup;
+ currentPath: string;
+ worktreeModel: WorktreeSelectorModel | null;
+ flyoutOpen: boolean;
+ setFlyoutOpen: (open: boolean) => void;
+ onPickProject: () => void;
+ onPickFlyoutEntry: (entry: WorktreeFlyoutEntry) => void;
+ guardStaleSelect: (event: Event) => boolean;
+ openNewWorktreeWith: (name: string) => void;
+}) {
+ const projectIsCurrent = group.project.path === currentPath;
+
+ if (group.worktrees.length === 0) {
+ return (
+ <DropdownMenuItem
+ onSelect={(e) => {
+ if (guardStaleSelect(e)) return;
+ onPickProject();
+ }}
+ className="flex w-full min-w-0 flex-col items-start gap-0.5"
+ data-testid={`project-switcher-recent-${group.project.path}`}
+ data-current={projectIsCurrent ? 'true' : undefined}
+ >
+ <ProjectLabel
+ name={group.project.name}
+ path={group.project.path}
+ current={projectIsCurrent}
+ />
+ </DropdownMenuItem>
+ );
+ }
+
+ const containsCurrent = projectIsCurrent || group.worktrees.some((w) => w.path === currentPath);
+ return (
+ <FlyoutGroup
+ group={group}
+ currentPath={currentPath}
+ containsCurrent={containsCurrent}
+ worktreeModel={worktreeModel}
+ flyoutOpen={flyoutOpen}
+ setFlyoutOpen={setFlyoutOpen}
+ onPickProject={onPickProject}
+ onPickFlyoutEntry={onPickFlyoutEntry}
+ guardStaleSelect={guardStaleSelect}
+ openNewWorktreeWith={openNewWorktreeWith}
+ />
+ );
+}
+
+function FlyoutGroup({
+ group,
+ currentPath,
+ containsCurrent,
+ worktreeModel,
+ flyoutOpen,
+ setFlyoutOpen,
+ onPickProject,
+ onPickFlyoutEntry,
+ guardStaleSelect,
+ openNewWorktreeWith,
+}: {
+ group: RecentRepoGroup;
+ currentPath: string;
+ containsCurrent: boolean;
+ worktreeModel: WorktreeSelectorModel | null;
+ flyoutOpen: boolean;
+ setFlyoutOpen: (open: boolean) => void;
+ onPickProject: () => void;
+ onPickFlyoutEntry: (entry: WorktreeFlyoutEntry) => void;
+ guardStaleSelect: (event: Event) => boolean;
+ openNewWorktreeWith: (name: string) => void;
+}) {
+ const { t } = useLingui();
+ const projectIsCurrent = group.project.path === currentPath;
+
+ return (
+ <Popover open={flyoutOpen} onOpenChange={setFlyoutOpen}>
+ <DropdownMenuItem
+ onSelect={(e) => {
+ if (guardStaleSelect(e)) return;
+ onPickProject();
+ }}
+ onKeyDown={(e) => {
+ if (e.key === 'ArrowRight') {
+ e.preventDefault();
+ setFlyoutOpen(true);
+ } else if ((e.key === 'ArrowLeft' || e.key === 'Escape') && flyoutOpen) {
+ e.preventDefault();
+ e.stopPropagation();
+ setFlyoutOpen(false);
+ }
+ }}
+ className="flex w-full min-w-0 items-start gap-2"
+ data-testid={`project-switcher-group-${group.project.path}`}
+ data-flyout-open={flyoutOpen ? 'true' : undefined}
+ data-current={containsCurrent ? 'true' : undefined}
+ >
+ {/* Two lines (name + path), matching the flat rows — the path
+ disambiguates same-named checkouts. No folder icon: the switcher stays
+ focused on project names, reclaiming the horizontal space. */}
+ <span className="flex min-w-0 flex-1 flex-col gap-0.5">
+ <span className="truncate font-medium text-sm" title={group.project.name}>
+ {group.project.name}
+ </span>
+ <span className="truncate text-muted-foreground text-xs" title={group.project.path}>
+ {group.project.path}
+ </span>
+ </span>
+ {projectIsCurrent ? (
+ <Check
+ aria-label={t`Current`}
+ className="mt-0.5 size-3.5 shrink-0 text-muted-foreground"
+ />
+ ) : null}
+ {/* Separate click target: worktree icon + count + chevron opens the
+ side-flyout. The PopoverTrigger IS this button. stopPropagation keeps
+ the row's open-project select from also firing. tabIndex=-1 keeps it
+ out of the menu's roving focus. */}
+ <PopoverTrigger asChild>
+ <Button
+ type="button"
+ variant="ghost"
+ size="sm"
+ tabIndex={-1}
+ aria-label={flyoutOpen ? t`Hide worktrees` : t`Show worktrees`}
+ aria-expanded={flyoutOpen}
+ onMouseDown={(e) => {
+ e.stopPropagation();
+ }}
+ onClick={(e) => {
+ e.stopPropagation();
+ }}
+ onMouseEnter={() => {
+ setFlyoutOpen(true);
+ }}
+ data-testid={`project-switcher-toggle-${group.project.path}`}
+ className="-my-1 -mr-1 h-auto shrink-0 gap-1 rounded-md px-1.5 py-1 text-muted-foreground hover:bg-accent-foreground/15 hover:text-foreground hover:ring-1 hover:ring-border hover:ring-inset"
+ >
+ {/* Worktree count + pluralized label ("3 worktrees" / "1 worktree").
+ The digit stays tabular-nums so the count column doesn't jitter.
+ No leading icon here — "worktrees" already says what this is. */}
+ <span className="text-xs">
+ <span className="tabular-nums">{group.worktrees.length}</span>{' '}
+ <Plural value={group.worktrees.length} one="worktree" other="worktrees" />
+ </span>
+ <ChevronRight aria-hidden="true" className="size-3.5" />
+ </Button>
+ </PopoverTrigger>
+ </DropdownMenuItem>
+ <WorktreeFlyout
+ group={group}
+ currentPath={currentPath}
+ worktreeModel={worktreeModel}
+ onPickFlyoutEntry={onPickFlyoutEntry}
+ guardStaleSelect={guardStaleSelect}
+ openNewWorktreeWith={openNewWorktreeWith}
+ />
+ </Popover>
+ );
+}
+
+function WorktreeFlyout({
+ group,
+ currentPath,
+ worktreeModel,
+ onPickFlyoutEntry,
+ guardStaleSelect,
+ openNewWorktreeWith,
+}: {
+ group: RecentRepoGroup;
+ currentPath: string;
+ worktreeModel: WorktreeSelectorModel | null;
+ onPickFlyoutEntry: (entry: WorktreeFlyoutEntry) => void;
+ guardStaleSelect: (event: Event) => boolean;
+ openNewWorktreeWith: (name: string) => void;
+}) {
+ const { t } = useLingui();
+ const [flyoutQuery, setFlyoutQuery] = useState('');
+ const searchRef = useRef<HTMLInputElement | null>(null);
+ const listRef = useRef<HTMLDivElement | null>(null);
+
+ function focusableRows(): HTMLElement[] {
+ const container = listRef.current;
+ if (container === null) return [];
+ return [...container.querySelectorAll<HTMLElement>('[role="menuitem"]')];
+ }
+ function focusRowAt(index: number): void {
+ const rows = focusableRows();
+ rows[index]?.focus();
+ }
+ function onRowKeyDown(e: React.KeyboardEvent, onEnter: () => void): void {
+ if (e.key === 'ArrowDown') {
+ e.preventDefault();
+ const rows = focusableRows();
+ const i = rows.indexOf(e.currentTarget as HTMLElement);
+ focusRowAt(Math.min(i + 1, rows.length - 1));
+ } else if (e.key === 'ArrowUp') {
+ e.preventDefault();
+ const rows = focusableRows();
+ const i = rows.indexOf(e.currentTarget as HTMLElement);
+ if (i <= 0) searchRef.current?.focus();
+ else focusRowAt(i - 1);
+ } else if (e.key === 'Enter') {
+ e.preventDefault();
+ onEnter();
+ }
+ }
+
+ const entries = buildWorktreeFlyoutEntries(group, worktreeModel, currentPath);
+ const q = flyoutQuery.trim().toLowerCase();
+ const visible =
+ q === '' ? entries : entries.filter((e) => (e.branch ?? '').toLowerCase().includes(q));
+ const isCurrentProject =
+ worktreeModel !== null && worktreeModel.mainRoot === group.project.mainRoot;
+ const typedName = flyoutQuery.trim();
+ const canCreate = isCurrentProject && typedName.length > 0;
+
+ return (
+ <PopoverContent
+ side="right"
+ align="start"
+ sideOffset={4}
+ className="flex max-h-80 w-96 flex-col gap-1 overflow-hidden p-1"
+ onPointerDownOutside={(e) => e.preventDefault()}
+ onFocusOutside={(e) => e.preventDefault()}
+ onOpenAutoFocus={(e) => {
+ e.preventDefault();
+ searchRef.current?.focus();
+ }}
+ data-testid={`project-switcher-flyout-${group.project.path}`}
+ >
+ <InputGroup className="mb-0.5 h-8 shrink-0 border-0 shadow-none has-[[data-slot=input-group-control]:focus-visible]:ring-0">
+ <InputGroupInput
+ ref={searchRef}
+ aria-label={t`Search worktrees and branches`}
+ placeholder={t`Search worktrees`}
+ value={flyoutQuery}
+ onChange={(e) => setFlyoutQuery(e.target.value)}
+ onKeyDown={(e) => {
+ if (e.key === 'ArrowDown') {
+ e.preventDefault();
+ focusRowAt(0);
+ }
+ e.stopPropagation();
+ }}
+ data-testid={`project-switcher-flyout-search-${group.project.path}`}
+ />
+ {/* GitBranch here (not the search magnifier) — the placeholder text
+ already says "Search worktrees"; this is the one worktree-context
+ icon for the whole flyout, replacing the per-row icon below. */}
+ <InputGroupAddon>
+ <GitBranch aria-hidden="true" />
+ </InputGroupAddon>
+ </InputGroup>
+ <div
+ ref={listRef}
+ className="min-h-0 flex-1 overflow-x-hidden overflow-y-auto overscroll-contain subtle-scrollbar"
+ >
+ {visible.length === 0 ? (
+ <>
+ <DropdownMenuLabel
+ className="font-normal text-muted-foreground text-xs"
+ role="status"
+ aria-live="polite"
+ >
+ {t`No matching worktrees or branches.`}
+ </DropdownMenuLabel>
+ {/* No match, but a name was typed — offer to create a worktree with
+ it. Only for the current project (creation anchors to the current
+ window). Closes the switcher + opens the pre-filled dialog. */}
+ {canCreate ? (
+ <DropdownMenuItem
+ onSelect={(e) => {
+ if (guardStaleSelect(e)) return;
+ openNewWorktreeWith(typedName);
+ }}
+ onKeyDown={(e) => onRowKeyDown(e, () => openNewWorktreeWith(typedName))}
+ className="flex items-center gap-2"
+ data-testid="project-switcher-flyout-create"
+ >
+ <Plus aria-hidden="true" className="size-3.5 shrink-0" />
+ <span className="min-w-0 flex-1 truncate text-sm" title={typedName}>
+ <Trans>
+ Create worktree{' '}
+ <span className="font-medium">
+ “<span className="font-mono">{typedName}</span>”
+ </span>
+ </Trans>
+ </span>
+ </DropdownMenuItem>
+ ) : null}
+ </>
+ ) : (
+ visible.map((entry) => {
+ const key = entry.path ?? `branch:${entry.branch}`;
+ const label = entry.branch ?? t`(detached)`;
+ return (
+ <DropdownMenuItem
+ key={key}
+ onSelect={(e) => {
+ if (guardStaleSelect(e)) return;
+ onPickFlyoutEntry(entry);
+ }}
+ onKeyDown={(e) => onRowKeyDown(e, () => onPickFlyoutEntry(entry))}
+ className="flex items-center gap-2"
+ data-testid={`project-switcher-flyout-entry-${key}`}
+ data-current={entry.isCurrent ? 'true' : undefined}
+ >
+ <span className="min-w-0 flex-1 truncate text-sm" title={label}>
+ {label}
+ </span>
+ {entry.isMain ? (
+ <span className="shrink-0 text-muted-foreground text-xs">{t`default`}</span>
+ ) : !entry.opened ? (
+ <span
+ className="shrink-0 text-muted-foreground text-xs"
+ title={t`Create a worktree from this branch`}
+ >
+ {t`create worktree`}
+ </span>
+ ) : null}
+ {entry.isCurrent ? <CurrentCheck /> : null}
+ </DropdownMenuItem>
+ );
+ })
+ )}
+ </div>
+ </PopoverContent>
+ );
+}
+
+function SearchResults({
+ recents,
+ currentPath,
+ query,
+ worktreeModel,
+ onPickEntry,
+ onPickBranch,
+ guardStaleSelect,
+}: {
+ recents: readonly RecentProjectEntry[];
+ currentPath: string;
+ query: string;
+ worktreeModel: WorktreeSelectorModel | null;
+ onPickEntry: (entry: RecentProjectEntry) => void;
+ onPickBranch: (branch: string) => void;
+ guardStaleSelect: (event: Event) => boolean;
+}) {
+ const { t } = useLingui();
+ const matches = (text: string): boolean => text.toLowerCase().includes(query);
+
+ const projectMatches = recents.filter(
+ (r) => !r.isLinkedWorktree && (matches(r.name) || matches(r.path)),
+ );
+ const openedWorktreeMatches = recents.filter(
+ (r) => r.isLinkedWorktree === true && (matches(r.branch ?? '') || matches(r.path)),
+ );
+ const openedWorktreePaths = new Set(openedWorktreeMatches.map((w) => w.path));
+ const branchMatches: WorktreeSelectorEntry[] = (worktreeModel?.entries ?? []).filter(
+ (e) =>
+ e.branch !== null &&
+ matches(e.branch) &&
+ (e.worktreePath === null || !openedWorktreePaths.has(e.worktreePath)) &&
+ e.worktreePath !== currentPath,
+ );
+
+ if (
+ projectMatches.length === 0 &&
+ openedWorktreeMatches.length === 0 &&
+ branchMatches.length === 0
+ ) {
+ return (
+ <DropdownMenuLabel
+ className="font-normal text-muted-foreground text-xs"
+ role="status"
+ aria-live="polite"
+ >
+ {t`No matching projects.`}
+ </DropdownMenuLabel>
+ );
+ }
+
+ return (
+ <>
+ {projectMatches.map((r) => (
+ <DropdownMenuItem
+ key={r.path}
+ onSelect={(e) => {
+ if (guardStaleSelect(e)) return;
+ onPickEntry(r);
+ }}
+ className="flex w-full min-w-0 flex-col items-start gap-0.5"
+ data-testid={`project-switcher-recent-${r.path}`}
+ >
+ <ProjectLabel name={r.name} path={r.path} current={r.path === currentPath} />
+ </DropdownMenuItem>
+ ))}
+ {openedWorktreeMatches.map((r) => (
+ <DropdownMenuItem
+ key={r.path}
+ onSelect={(e) => {
+ if (guardStaleSelect(e)) return;
+ onPickEntry(r);
+ }}
+ className="flex items-start gap-2"
+ data-testid={`project-switcher-worktree-${r.path}`}
+ data-current={r.path === currentPath ? 'true' : undefined}
+ >
+ <GitBranch aria-hidden="true" className="mt-0.5 size-3.5 shrink-0" />
+ <WorktreeResultLabel
+ branch={r.branch ?? r.name}
+ project={r.mainRoot !== undefined ? basenameOf(r.mainRoot) : null}
+ />
+ </DropdownMenuItem>
+ ))}
+ {branchMatches.map((e) => (
+ <DropdownMenuItem
+ key={`branch:${e.branch}`}
+ onSelect={(ev) => {
+ if (guardStaleSelect(ev)) return;
+ if (e.branch !== null) onPickBranch(e.branch);
+ }}
+ className="flex items-start gap-2"
+ data-testid={`project-switcher-branch-${e.branch}`}
+ >
+ <GitBranch aria-hidden="true" className="mt-0.5 size-3.5 shrink-0 opacity-40" />
+ <WorktreeResultLabel
+ branch={e.branch ?? ''}
+ project={worktreeModel !== null ? basenameOf(worktreeModel.mainRoot) : null}
+ hint={t`create worktree`}
+ />
+ </DropdownMenuItem>
+ ))}
+ </>
+ );
+}
+
+function WorktreeResultLabel({
+ branch,
+ project,
+ hint,
+}: {
+ branch: string;
+ project: string | null;
+ hint?: string;
+}) {
+ return (
+ <span className="flex min-w-0 flex-1 flex-col gap-0.5">
+ <span className="flex w-full min-w-0 items-center gap-1.5">
+ <span className="min-w-0 flex-1 truncate text-sm">{branch}</span>
+ {hint !== undefined ? (
+ <span className="shrink-0 text-muted-foreground text-xs">{hint}</span>
+ ) : null}
+ </span>
+ {project !== null ? (
+ <span className="truncate text-muted-foreground text-xs" title={project}>
+ {project}
+ </span>
+ ) : null}
+ </span>
+ );
+}
+
+function ProjectLabel({ name, path, current }: { name: string; path: string; current: boolean }) {
+ return (
+ <span className="flex w-full min-w-0 flex-col gap-0.5">
+ <span className={cn('flex w-full items-center gap-1.5', current && 'font-medium')}>
+ <span className="truncate font-medium text-sm" title={name}>
+ {name}
+ </span>
+ {current ? (
+ <Check aria-hidden="true" className="size-3.5 shrink-0 text-muted-foreground" />
+ ) : null}
+ </span>
+ <span className="w-full truncate text-muted-foreground text-xs" title={path}>
+ {path}
+ </span>
+ </span>
+ );
+}
+
+function CurrentCheck() {
+ const { t } = useLingui();
+ return <Check aria-label={t`Current`} className="size-3.5 shrink-0 text-muted-foreground" />;
+}
diff --git a/packages/app/src/components/project-switcher-recents.test.ts b/packages/app/src/components/project-switcher-recents.test.ts
new file mode 100644
index 000000000..0fc215aed
--- /dev/null
+++ b/packages/app/src/components/project-switcher-recents.test.ts
@@ -0,0 +1,215 @@
+import { describe, expect, test } from 'bun:test';
+import type { WorktreeSelectorModel } from '@inkeep/open-knowledge-core';
+import type { RecentProjectEntry } from '@/lib/desktop-bridge-types';
+import {
+ basenameOf,
+ buildWorktreeFlyoutEntries,
+ groupRecentsByRepo,
+} from './project-switcher-recents.ts';
+
+function main(path: string, commonDir: string): RecentProjectEntry {
+ return {
+ path,
+ name: path.split('/').pop() ?? path,
+ lastOpenedAt: '2026-07-01',
+ gitCommonDir: commonDir,
+ mainRoot: path,
+ isLinkedWorktree: false,
+ branch: 'main',
+ };
+}
+function worktree(
+ path: string,
+ commonDir: string,
+ mainRoot: string,
+ branch: string,
+ lastOpenedAt = '2026-07-01',
+): RecentProjectEntry {
+ return {
+ path,
+ name: path.split('/').pop() ?? path,
+ lastOpenedAt,
+ gitCommonDir: commonDir,
+ mainRoot,
+ isLinkedWorktree: true,
+ branch,
+ };
+}
+function nonGit(path: string): RecentProjectEntry {
+ return { path, name: path.split('/').pop() ?? path, lastOpenedAt: '2026-07-01' };
+}
+
+function model(
+ entries: WorktreeSelectorModel['entries'],
+ mainRoot = '/repo',
+): WorktreeSelectorModel {
+ return { mainRoot, currentBranch: 'main', entries, remoteBranches: [] };
+}
+
+describe('basenameOf', () => {
+ test('handles / and \\ and trailing slashes', () => {
+ expect(basenameOf('/a/b/test')).toBe('test');
+ expect(basenameOf('/a/b/test/')).toBe('test');
+ expect(basenameOf('C:\\a\\b\\test')).toBe('test');
+ expect(basenameOf('solo')).toBe('solo');
+ });
+});
+
+describe('groupRecentsByRepo', () => {
+ test('groups a repo main + its linked worktrees under one group', () => {
+ const groups = groupRecentsByRepo([
+ main('/repo', '/repo/.git'),
+ worktree('/repo/.ok/worktrees/dev', '/repo/.git', '/repo', 'dev'),
+ worktree('/repo/.ok/worktrees/feat', '/repo/.git', '/repo', 'feat'),
+ ]);
+ expect(groups).toHaveLength(1);
+ expect(groups[0]?.project.path).toBe('/repo');
+ expect(groups[0]?.projectSynthesized).toBe(false);
+ expect(groups[0]?.worktrees.map((w) => w.branch)).toEqual(['dev', 'feat']);
+ });
+
+ test('non-git recents become singleton groups with no worktrees', () => {
+ const groups = groupRecentsByRepo([nonGit('/notes'), nonGit('/scratch')]);
+ expect(groups).toHaveLength(2);
+ expect(groups.every((g) => g.worktrees.length === 0)).toBe(true);
+ expect(groups.map((g) => g.project.path)).toEqual(['/notes', '/scratch']);
+ });
+
+ test('synthesizes the project row when only a worktree is in recents', () => {
+ const groups = groupRecentsByRepo([
+ worktree('/repo/.ok/worktrees/dev', '/repo/.git', '/repo', 'dev'),
+ ]);
+ expect(groups).toHaveLength(1);
+ expect(groups[0]?.project.path).toBe('/repo');
+ expect(groups[0]?.project.name).toBe('repo');
+ expect(groups[0]?.projectSynthesized).toBe(true);
+ expect(groups[0]?.worktrees).toHaveLength(1);
+ });
+
+ test('preserves recents order across groups', () => {
+ const groups = groupRecentsByRepo([
+ main('/alpha', '/alpha/.git'),
+ nonGit('/notes'),
+ main('/beta', '/beta/.git'),
+ worktree('/alpha/.ok/worktrees/x', '/alpha/.git', '/alpha', 'x'),
+ ]);
+ expect(groups.map((g) => g.project.path)).toEqual(['/alpha', '/notes', '/beta']);
+ expect(groups[0]?.worktrees).toHaveLength(1);
+ });
+
+ test('two different repos stay separate', () => {
+ const groups = groupRecentsByRepo([
+ main('/a', '/a/.git'),
+ worktree('/a/.ok/worktrees/x', '/a/.git', '/a', 'x'),
+ main('/b', '/b/.git'),
+ ]);
+ expect(groups).toHaveLength(2);
+ });
+});
+
+describe('buildWorktreeFlyoutEntries', () => {
+ test('pins main first, then opened worktrees by recency (newest first)', () => {
+ const [group] = groupRecentsByRepo([
+ main('/repo', '/repo/.git'),
+ worktree('/repo/.ok/worktrees/older', '/repo/.git', '/repo', 'older', '2026-06-01'),
+ worktree('/repo/.ok/worktrees/newer', '/repo/.git', '/repo', 'newer', '2026-06-30'),
+ ]);
+ if (group === undefined) throw new Error('group');
+ const entries = buildWorktreeFlyoutEntries(group, null, '/other');
+ expect(entries.map((e) => e.path)).toEqual([
+ '/repo',
+ '/repo/.ok/worktrees/newer',
+ '/repo/.ok/worktrees/older',
+ ]);
+ expect(entries[0]?.isMain).toBe(true);
+ expect(entries[0]?.branch).toBe('main');
+ });
+
+ test('flags the current entry', () => {
+ const [group] = groupRecentsByRepo([
+ main('/repo', '/repo/.git'),
+ worktree('/repo/.ok/worktrees/dev', '/repo/.git', '/repo', 'dev'),
+ ]);
+ if (group === undefined) throw new Error('group');
+ const entries = buildWorktreeFlyoutEntries(group, null, '/repo/.ok/worktrees/dev');
+ expect(entries.find((e) => e.path === '/repo/.ok/worktrees/dev')?.isCurrent).toBe(true);
+ expect(entries.find((e) => e.isMain)?.isCurrent).toBe(false);
+ });
+
+ test('a synthesized project row contributes no pinned main entry', () => {
+ const [group] = groupRecentsByRepo([
+ worktree('/repo/.ok/worktrees/dev', '/repo/.git', '/repo', 'dev'),
+ ]);
+ if (group === undefined) throw new Error('group');
+ const entries = buildWorktreeFlyoutEntries(group, null, '/other');
+ expect(entries.some((e) => e.isMain)).toBe(false);
+ expect(entries.map((e) => e.path)).toEqual(['/repo/.ok/worktrees/dev']);
+ });
+
+ test('merges the current project’s un-opened branches (create-on-demand) after opened worktrees', () => {
+ const [group] = groupRecentsByRepo([
+ main('/repo', '/repo/.git'),
+ worktree('/repo/.ok/worktrees/dev', '/repo/.git', '/repo', 'dev'),
+ ]);
+ if (group === undefined) throw new Error('group');
+ const entries = buildWorktreeFlyoutEntries(
+ group,
+ model([
+ { branch: 'main', worktreePath: '/repo', isCurrent: false, isMain: true, locked: false },
+ {
+ branch: 'dev',
+ worktreePath: '/repo/.ok/worktrees/dev',
+ isCurrent: false,
+ isMain: false,
+ locked: false,
+ },
+ { branch: 'zeta', worktreePath: null, isCurrent: false, isMain: false, locked: false },
+ { branch: 'alpha', worktreePath: null, isCurrent: false, isMain: false, locked: false },
+ ]),
+ '/other',
+ );
+ expect(entries.map((e) => e.branch)).toEqual(['main', 'dev', 'alpha', 'zeta']);
+ const alpha = entries.find((e) => e.branch === 'alpha');
+ expect(alpha?.opened).toBe(false);
+ expect(alpha?.path).toBeNull();
+ });
+
+ test('does not merge a branch model belonging to a different project', () => {
+ const [group] = groupRecentsByRepo([
+ main('/repo', '/repo/.git'),
+ worktree('/repo/.ok/worktrees/dev', '/repo/.git', '/repo', 'dev'),
+ ]);
+ if (group === undefined) throw new Error('group');
+ const entries = buildWorktreeFlyoutEntries(
+ group,
+ model(
+ [{ branch: 'leak', worktreePath: null, isCurrent: false, isMain: false, locked: false }],
+ '/elsewhere',
+ ),
+ '/other',
+ );
+ expect(entries.some((e) => e.branch === 'leak')).toBe(false);
+ });
+
+ test('does not double-list a branch already present as an opened worktree', () => {
+ const [group] = groupRecentsByRepo([
+ main('/repo', '/repo/.git'),
+ worktree('/repo/.ok/worktrees/dev', '/repo/.git', '/repo', 'dev'),
+ ]);
+ if (group === undefined) throw new Error('group');
+ const entries = buildWorktreeFlyoutEntries(
+ group,
+ model([
+ {
+ branch: 'dev',
+ worktreePath: '/repo/.ok/worktrees/dev',
+ isCurrent: false,
+ isMain: false,
+ locked: false,
+ },
+ ]),
+ '/other',
+ );
+ expect(entries.filter((e) => e.branch === 'dev')).toHaveLength(1);
+ });
+});
diff --git a/packages/app/src/components/project-switcher-recents.ts b/packages/app/src/components/project-switcher-recents.ts
new file mode 100644
index 000000000..45ce10efe
--- /dev/null
+++ b/packages/app/src/components/project-switcher-recents.ts
@@ -0,0 +1,132 @@
+import type { WorktreeSelectorModel } from '@inkeep/open-knowledge-core';
+import type { RecentProjectEntry } from '@/lib/desktop-bridge-types';
+
+export interface RecentRepoGroup {
+ readonly project: RecentProjectEntry;
+ readonly worktrees: readonly RecentProjectEntry[];
+ readonly projectSynthesized: boolean;
+}
+
+export interface WorktreeFlyoutEntry {
+ readonly branch: string | null;
+ readonly path: string | null;
+ readonly opened: boolean;
+ readonly isMain: boolean;
+ readonly isCurrent: boolean;
+}
+
+export function buildWorktreeFlyoutEntries(
+ group: RecentRepoGroup,
+ worktreeModel: WorktreeSelectorModel | null,
+ currentPath: string,
+): WorktreeFlyoutEntry[] {
+ const entries: WorktreeFlyoutEntry[] = [];
+ const seenPaths = new Set<string>();
+ const seenBranches = new Set<string>();
+
+ const isCurrentModel =
+ worktreeModel !== null && worktreeModel.mainRoot === group.project.mainRoot;
+
+ if (!group.projectSynthesized) {
+ entries.push({
+ branch: group.project.branch ?? null,
+ path: group.project.path,
+ opened: true,
+ isMain: true,
+ isCurrent: group.project.path === currentPath,
+ });
+ seenPaths.add(group.project.path);
+ if (group.project.branch != null) seenBranches.add(group.project.branch);
+ }
+
+ const openedByRecency = [...group.worktrees].sort((a, b) =>
+ b.lastOpenedAt.localeCompare(a.lastOpenedAt),
+ );
+ for (const wt of openedByRecency) {
+ if (seenPaths.has(wt.path)) continue;
+ entries.push({
+ branch: wt.branch ?? null,
+ path: wt.path,
+ opened: true,
+ isMain: false,
+ isCurrent: wt.path === currentPath,
+ });
+ seenPaths.add(wt.path);
+ if (wt.branch != null) seenBranches.add(wt.branch);
+ }
+
+ if (isCurrentModel) {
+ const modelExtras = worktreeModel.entries
+ .filter(
+ (e) =>
+ e.branch !== null &&
+ !seenBranches.has(e.branch) &&
+ (e.worktreePath === null || !seenPaths.has(e.worktreePath)),
+ )
+ .sort((a, b) => (a.branch ?? '').localeCompare(b.branch ?? ''));
+ for (const e of modelExtras) {
+ entries.push({
+ branch: e.branch,
+ path: e.worktreePath,
+ opened: e.worktreePath !== null,
+ isMain: e.isMain,
+ isCurrent: e.isCurrent,
+ });
+ if (e.branch != null) seenBranches.add(e.branch);
+ if (e.worktreePath != null) seenPaths.add(e.worktreePath);
+ }
+ }
+
+ return entries.sort((a, b) => rankFlyout(a) - rankFlyout(b));
+}
+
+function rankFlyout(e: WorktreeFlyoutEntry): number {
+ if (e.isMain) return 0;
+ if (e.opened) return 1;
+ return 2;
+}
+
+export function basenameOf(path: string): string {
+ const segments = path.split(/[/\\]/).filter((s) => s.length > 0);
+ return segments.length > 0 ? (segments[segments.length - 1] ?? path) : path;
+}
+
+interface GroupBuilder {
+ project: RecentProjectEntry | null;
+ mainRoot: string;
+ worktrees: RecentProjectEntry[];
+}
+
+export function groupRecentsByRepo(recents: readonly RecentProjectEntry[]): RecentRepoGroup[] {
+ const builders: GroupBuilder[] = [];
+ const gitGroupIndex = new Map<string, number>();
+
+ for (const entry of recents) {
+ const commonDir = entry.gitCommonDir;
+ const mainRoot = entry.mainRoot;
+ if (commonDir === undefined || mainRoot === undefined) {
+ builders.push({ project: entry, mainRoot: entry.path, worktrees: [] });
+ continue;
+ }
+ let idx = gitGroupIndex.get(commonDir);
+ if (idx === undefined) {
+ idx = builders.length;
+ gitGroupIndex.set(commonDir, idx);
+ builders.push({ project: null, mainRoot, worktrees: [] });
+ }
+ const builder = builders[idx];
+ if (builder === undefined) continue;
+ if (entry.isLinkedWorktree) builder.worktrees.push(entry);
+ else if (builder.project === null) builder.project = entry;
+ }
+
+ return builders.map((builder) => {
+ const synthesized = builder.project === null;
+ const project = builder.project ?? {
+ path: builder.mainRoot,
+ name: basenameOf(builder.mainRoot),
+ lastOpenedAt: '',
+ };
+ return { project, worktrees: builder.worktrees, projectSynthesized: synthesized };
+ });
+}
diff --git a/packages/app/src/hooks/use-worktree-autosync-notice.dom.test.tsx b/packages/app/src/hooks/use-worktree-autosync-notice.dom.test.tsx
new file mode 100644
index 000000000..6479c80a5
--- /dev/null
+++ b/packages/app/src/hooks/use-worktree-autosync-notice.dom.test.tsx
@@ -0,0 +1,54 @@
+import { beforeEach, describe, expect, mock, test } from 'bun:test';
+import { cleanup, render, waitFor } from '@testing-library/react';
+import { useWorktreeAutoSyncNotice } from './use-worktree-autosync-notice';
+
+const toast = mock((_node: unknown) => {});
+mock.module('sonner', () => ({ toast }));
+
+let ctx: {
+ projectLocalConfig: unknown;
+ projectLocalSynced: boolean;
+ projectLocalBinding: { patch: ReturnType<typeof mock> } | null;
+};
+mock.module('@/lib/config-provider', () => ({ useConfigContext: () => ctx }));
+
+function Probe() {
+ useWorktreeAutoSyncNotice();
+ return null;
+}
+
+const patch = mock(() => ({ ok: true }));
+
+beforeEach(() => {
+ cleanup();
+ toast.mockClear();
+ patch.mockClear();
+ ctx = { projectLocalConfig: null, projectLocalSynced: true, projectLocalBinding: { patch } };
+});
+
+describe('useWorktreeAutoSyncNotice', () => {
+ test('fires one toast for an inherited worktree and clears the flag', async () => {
+ ctx.projectLocalConfig = {
+ autoSync: { enabled: true, inheritedNoticePending: true, inheritedFrom: 'my-repo' },
+ };
+ render(<Probe />);
+ await waitFor(() => expect(toast).toHaveBeenCalledTimes(1));
+ expect(patch).toHaveBeenCalledWith({ autoSync: { inheritedNoticePending: null } });
+ });
+
+ test('does nothing when the flag is not set', () => {
+ ctx.projectLocalConfig = { autoSync: { enabled: true } };
+ render(<Probe />);
+ expect(toast).not.toHaveBeenCalled();
+ expect(patch).not.toHaveBeenCalled();
+ });
+
+ test('waits for the project-local binding to sync before firing', () => {
+ ctx.projectLocalSynced = false;
+ ctx.projectLocalConfig = {
+ autoSync: { enabled: false, inheritedNoticePending: true, inheritedFrom: 'my-repo' },
+ };
+ render(<Probe />);
+ expect(toast).not.toHaveBeenCalled();
+ });
+});
diff --git a/packages/app/src/hooks/use-worktree-autosync-notice.tsx b/packages/app/src/hooks/use-worktree-autosync-notice.tsx
new file mode 100644
index 000000000..a7bc9b6b3
--- /dev/null
+++ b/packages/app/src/hooks/use-worktree-autosync-notice.tsx
@@ -0,0 +1,37 @@
+import { Trans } from '@lingui/react/macro';
+import { useEffect, useRef } from 'react';
+import { toast } from 'sonner';
+import { useConfigContext } from '@/lib/config-provider';
+
+interface InheritedAutoSync {
+ enabled?: boolean | null;
+ inheritedNoticePending?: unknown;
+ inheritedFrom?: unknown;
+}
+
+export function useWorktreeAutoSyncNotice(): void {
+ const { projectLocalConfig, projectLocalSynced, projectLocalBinding } = useConfigContext();
+ const shownRef = useRef(false);
+
+ useEffect(() => {
+ if (!projectLocalSynced || shownRef.current || projectLocalBinding === null) return;
+ const autoSync = projectLocalConfig?.autoSync as InheritedAutoSync | undefined;
+ if (autoSync?.inheritedNoticePending !== true) return;
+
+ shownRef.current = true;
+ const project = typeof autoSync.inheritedFrom === 'string' ? autoSync.inheritedFrom : '';
+ toast(
+ autoSync.enabled === true ? (
+ <Trans>
+ Auto-sync is on for this worktree, inherited from {project}. Change it in Settings → Sync.
+ </Trans>
+ ) : (
+ <Trans>
+ Auto-sync is off for this worktree, inherited from {project}. Change it in Settings →
+ Sync.
+ </Trans>
+ ),
+ );
+ projectLocalBinding.patch({ autoSync: { inheritedNoticePending: null } });
+ }, [projectLocalSynced, projectLocalConfig, projectLocalBinding]);
+}
diff --git a/packages/app/src/hooks/use-worktrees.ts b/packages/app/src/hooks/use-worktrees.ts
new file mode 100644
index 000000000..4303ad31d
--- /dev/null
+++ b/packages/app/src/hooks/use-worktrees.ts
@@ -0,0 +1,6 @@
+import { useSyncExternalStore } from 'react';
+import { getWorktreesSnapshot, subscribeToWorktrees } from '@/lib/worktree-store';
+
+export function useWorktrees() {
+ return useSyncExternalStore(subscribeToWorktrees, getWorktreesSnapshot, getWorktreesSnapshot);
+}
diff --git a/packages/app/src/lib/desktop-bridge-types.ts b/packages/app/src/lib/desktop-bridge-types.ts
index 3577a118d..ab82a7495 100644
--- a/packages/app/src/lib/desktop-bridge-types.ts
+++ b/packages/app/src/lib/desktop-bridge-types.ts
@@ -7,6 +7,9 @@ import type {
OkFolderState,
RecentProjectEntry,
TerminalCli,
+ WorktreeCreateRequest,
+ WorktreeCreateResult,
+ WorktreeListResult,
} from '@inkeep/open-knowledge-core';
export type { OkFolderState, RecentProjectEntry };
@@ -152,7 +155,9 @@ type OkMenuAction =
| 'toggle-doc-panel'
| 'toggle-terminal'
| 'new-terminal'
- | 'kill-terminal';
+ | 'kill-terminal'
+ | 'new-worktree'
+ | 'switch-worktree';
type OkUnsubscribe = () => void;
@@ -163,7 +168,8 @@ export type OkProjectEntryPoint =
| 'recents'
| 'deep-link'
| 'drag-drop'
- | 'share-receive';
+ | 'share-receive'
+ | 'worktree';
interface ProjectSessionState {
openTabs: string[];
@@ -613,6 +619,11 @@ export interface OkDesktopBridge {
close(): Promise<void>;
};
+ worktree: {
+ list(): Promise<WorktreeListResult>;
+ create(request: WorktreeCreateRequest): Promise<WorktreeCreateResult>;
+ };
+
sharing: {
status(): Promise<OkSharingStatusResult>;
setMode(mode: 'shared' | 'local-only'): Promise<OkSharingSetModeResult>;
diff --git a/packages/app/src/lib/worktree-store.test.ts b/packages/app/src/lib/worktree-store.test.ts
new file mode 100644
index 000000000..b50f079f4
--- /dev/null
+++ b/packages/app/src/lib/worktree-store.test.ts
@@ -0,0 +1,102 @@
+import { describe, expect, mock, test } from 'bun:test';
+import type { WorktreeSelectorModel } from '@inkeep/open-knowledge-core';
+import { createWorktreeStore } from './worktree-store.ts';
+
+function model(mainRoot: string): WorktreeSelectorModel {
+ return { mainRoot, currentBranch: 'main', entries: [], remoteBranches: [] };
+}
+
+const flush = () => new Promise((r) => setTimeout(r, 0));
+
+describe('createWorktreeStore', () => {
+ test('fetches once on first subscribe and caches the snapshot', async () => {
+ const fetchModel = mock(() => Promise.resolve(model('/repo')));
+ const store = createWorktreeStore({ fetchModel });
+ expect(store.getSnapshot()).toBeNull();
+
+ const unsub = store.subscribe(() => {});
+ await flush();
+ expect(fetchModel).toHaveBeenCalledTimes(1);
+ expect(store.getSnapshot()?.mainRoot).toBe('/repo');
+
+ store.subscribe(() => {});
+ await flush();
+ expect(fetchModel).toHaveBeenCalledTimes(1);
+ unsub();
+ });
+
+ test('notifies subscribers when the model arrives', async () => {
+ const fetchModel = mock(() => Promise.resolve(model('/repo')));
+ const store = createWorktreeStore({ fetchModel });
+ const listener = mock(() => {});
+ store.subscribe(listener);
+ await flush();
+ expect(listener).toHaveBeenCalled();
+ });
+
+ test('refresh re-fetches and updates the snapshot', async () => {
+ let next = model('/repo');
+ const fetchModel = mock(() => Promise.resolve(next));
+ const store = createWorktreeStore({ fetchModel });
+ store.subscribe(() => {});
+ await flush();
+ expect(store.getSnapshot()?.mainRoot).toBe('/repo');
+
+ next = model('/repo2');
+ store.refresh();
+ await flush();
+ expect(fetchModel).toHaveBeenCalledTimes(2);
+ expect(store.getSnapshot()?.mainRoot).toBe('/repo2');
+ });
+
+ test('keeps the prior cache when a fetch resolves null (transient failure)', async () => {
+ let result: WorktreeSelectorModel | null = model('/repo');
+ const fetchModel = mock(() => Promise.resolve(result));
+ const store = createWorktreeStore({ fetchModel });
+ store.subscribe(() => {});
+ await flush();
+ expect(store.getSnapshot()?.mainRoot).toBe('/repo');
+
+ result = null;
+ store.refresh();
+ await flush();
+ expect(store.getSnapshot()?.mainRoot).toBe('/repo');
+ });
+
+ test('coalesces a refresh that arrives while the initial load is still in-flight', async () => {
+ let resolveFirst: ((m: WorktreeSelectorModel) => void) | null = null;
+ let call = 0;
+ const fetchModel = mock(() => {
+ call += 1;
+ if (call === 1) {
+ return new Promise<WorktreeSelectorModel>((r) => {
+ resolveFirst = r;
+ });
+ }
+ return Promise.resolve(model('/repo-after-create'));
+ });
+ const store = createWorktreeStore({ fetchModel });
+ store.subscribe(() => {});
+ await flush();
+ store.refresh();
+ resolveFirst?.(model('/repo'));
+ await flush();
+ await flush();
+ expect(fetchModel).toHaveBeenCalledTimes(2);
+ expect(store.getSnapshot()?.mainRoot).toBe('/repo-after-create');
+ });
+
+ test('a rejected fetch keeps the prior snapshot', async () => {
+ let shouldThrow = false;
+ const fetchModel = mock(() =>
+ shouldThrow ? Promise.reject(new Error('ipc down')) : Promise.resolve(model('/repo')),
+ );
+ const store = createWorktreeStore({ fetchModel });
+ store.subscribe(() => {});
+ await flush();
+ shouldThrow = true;
+ store.refresh();
+ await flush();
+ expect(store.getSnapshot()?.mainRoot).toBe('/repo');
+ });
+});
diff --git a/packages/app/src/lib/worktree-store.ts b/packages/app/src/lib/worktree-store.ts
new file mode 100644
index 000000000..6e9d792d5
--- /dev/null
+++ b/packages/app/src/lib/worktree-store.ts
@@ -0,0 +1,79 @@
+import type { WorktreeSelectorModel } from '@inkeep/open-knowledge-core';
+
+export interface WorktreeStore {
+ getSnapshot(): WorktreeSelectorModel | null;
+ subscribe(listener: () => void): () => void;
+ refresh(): void;
+}
+
+interface WorktreeStoreDeps {
+ fetchModel: () => Promise<WorktreeSelectorModel | null>;
+}
+
+export function createWorktreeStore(deps: WorktreeStoreDeps): WorktreeStore {
+ let model: WorktreeSelectorModel | null = null;
+ let bootstrapped = false;
+ let inFlight = false;
+ let reloadQueued = false;
+ const listeners = new Set<() => void>();
+
+ function emit(): void {
+ for (const listener of listeners) listener();
+ }
+
+ async function load(): Promise<void> {
+ if (inFlight) {
+ reloadQueued = true;
+ return;
+ }
+ inFlight = true;
+ try {
+ const next = await deps.fetchModel();
+ if (next !== null && next !== model) {
+ model = next;
+ emit();
+ }
+ } catch {
+ } finally {
+ inFlight = false;
+ if (reloadQueued) {
+ reloadQueued = false;
+ void load();
+ }
+ }
+ }
+
+ return {
+ getSnapshot: () => model,
+ subscribe(listener) {
+ listeners.add(listener);
+ if (!bootstrapped) {
+ bootstrapped = true;
+ void load();
+ }
+ return () => {
+ listeners.delete(listener);
+ };
+ },
+ refresh() {
+ void load();
+ },
+ };
+}
+
+async function fetchWorktreeModel(): Promise<WorktreeSelectorModel | null> {
+ const bridge = typeof window !== 'undefined' ? window.okDesktop : undefined;
+ if (!bridge) return null;
+ const result = await bridge.worktree.list();
+ return result.ok ? result.model : null;
+}
+
+const productionStore: WorktreeStore =
+ typeof window === 'undefined'
+ ? // SSR / non-browser: nothing to fetch. Consumers render their empty state.
+ { getSnapshot: () => null, subscribe: () => () => {}, refresh: () => {} }
+ : createWorktreeStore({ fetchModel: fetchWorktreeModel });
+
+export const subscribeToWorktrees = productionStore.subscribe;
+export const getWorktreesSnapshot = productionStore.getSnapshot;
+export const refreshWorktrees = productionStore.refresh;
diff --git a/packages/app/src/locales/en/messages.json b/packages/app/src/locales/en/messages.json
index 649741115..d786f133b 100644
--- a/packages/app/src/locales/en/messages.json
+++ b/packages/app/src/locales/en/messages.json
@@ -24,9 +24,11 @@
],
"-r_Kx7": ["Create skill"],
"-slrNR": ["Toggle a task list."],
+ "-uaQnI": ["No matching worktrees or branches."],
"-wePNM": [
"Search matches file names, paths, and folders. Open a file to search its body (⌘F)."
],
+ "-zA2E7": ["Couldn't create the worktree. Try a different name."],
"-zy2Nq": ["Type"],
"0-31GV": ["Removing"],
"02P3hL": ["Upload failed: ", ["message"]],
@@ -106,7 +108,6 @@
"2XQ8Ww": ["Open preview when agent edits"],
"2YOwme": ["Restarted — now running v", ["appRuntime"], "."],
"2YZwPB": ["Forward-links response did not match expected shape."],
- "2Znqb1": [" (missing)"],
"2bVHbB": ["Available in every project on this computer."],
"2fkdnR": ["Nothing to undo on this file"],
"2hYmUH": ["[email protected]"],
@@ -201,6 +202,11 @@
"4uNLmk": ["Pulling"],
"4v2Yyz": ["Select every visible file-tree row when focus is in the Files sidebar."],
"4xtLTl": ["Hidden folder “", ["basename"], "”"],
+ "4zEZS5": [
+ "Auto-sync is on for this worktree, inherited from ",
+ ["project"],
+ ". Change it in Settings → Sync."
+ ],
"4zGlN_": ["Paste image URL or click upload"],
"5-FeN2": ["Share URL"],
"54Y6Fg": ["Could not load templates. Try again later."],
@@ -260,11 +266,13 @@
],
"5wV2qQ": ["and more"],
"5y_9lO": ["Waiting for authorization"],
+ "6-wLTJ": [["behind"], " behind origin"],
"62Pc08": ["Install for Claude Chat & Cowork (Desktop App)"],
"636K3K": ["Delete adjacent chip"],
"67f-3g": ["Duplicate succeeded but the sidebar may be out of date — refresh to resync"],
"6Aih4U": ["Offline"],
"6EKG_c": ["What agents match on to decide when to use the skill."],
+ "6HCOwA": ["Failed to open."],
"6LbUG7": ["The repository is private and your GitHub account doesn't have access to it."],
"6MnZEC": ["Terminal failed to load"],
"6O626z": ["No headings match \"", ["trimmedAnchorQuery"], "\""],
@@ -346,13 +354,13 @@
{ "one": ["#", " unresolved hunk"], "other": ["#", " unresolved hunks"] }
]
],
+ "8Gzz2G": ["worktree of ", ["worktreeOf"]],
"8IP5jY": ["Each selected tool gets an OpenKnowledge MCP entry."],
"8Jm2EP": ["Toggle heading levels 1 through 6."],
"8OGgNM": ["Open or close visual-editor find."],
"8OxKZy": ["Move succeeded but the sidebar may be out of date — refresh to resync"],
"8PmoQF": ["Open the insert menu in an empty or active text position."],
"8RtNI0": ["Failed to load documents"],
- "8S1E33": ["Search recent projects..."],
"8XQRON": ["Loading repositories"],
"8_brI5": ["Name is required"],
"8cS0nH": ["Config sharing unavailable: ", ["0"], "."],
@@ -422,6 +430,11 @@
"ATGYL1": ["Email address"],
"AVW-K9": ["Failed to load orphan pages"],
"AWOSPo": ["Zoom in"],
+ "AaaESH": [
+ "Auto-sync is off for this worktree, inherited from ",
+ ["project"],
+ ". Change it in Settings → Sync."
+ ],
"AcK_r0": ["Claude CLI"],
"AdcGcG": ["Applying your change"],
"AddR83": ["Could not create project. Try again or pick a different location."],
@@ -431,6 +444,7 @@
"This project lives only on this computer. Connect it to GitHub to back it up and share it with other people."
],
"Aif3E7": ["Enable semantic search"],
+ "Aj1D9r": ["Hide worktrees"],
"Am78jY": ["Drag ", ["keyName"], " to reorder"],
"Aq-O0x": ["status"],
"AqnqMJ": ["API key set"],
@@ -468,6 +482,7 @@
"Bdha5y": ["Publishing..."],
"BeWTQy": ["Loading starter packs"],
"BgV29F": ["Visual editor find input focused"],
+ "Bn9-El": ["default"],
"Bv5a9_": ["Selection statistics"],
"Bx4EXG": ["Actions for ", ["label"]],
"By-7Pn": ["Toggle a bullet list."],
@@ -477,6 +492,7 @@
"C7XjNB": ["Global Skill"],
"C9TBvF": ["No Outgoing"],
"CCTop_": ["Recent"],
+ "CFnavk": ["This project isn't a git repository, so worktrees aren't available."],
"CKyk7Q": ["Go back"],
"COr1Y7": [
"Pick <0>openknowledge.skill</0> from your <1>Downloads</1> folder. It enables automatically."
@@ -494,6 +510,7 @@
"Ck9XRt": ["Couldn't save the key — please try again."],
"CmeH9S": ["Add property to ", ["keyName"]],
"CvsD6Y": ["via ", ["viaTags"]],
+ "D12vtS": ["(detached)"],
"D4H2N6": ["Remove ", ["tag"]],
"D8OV7J": ["Only collaborators"],
"DDTdLl": ["Code block settings"],
@@ -503,6 +520,7 @@
"DId6MT": ["Project-level pages with no outgoing graph edges."],
"DPfwMq": ["Done"],
"DVh_Tb": ["Failed to clean up after trash"],
+ "DXd9LM": ["New worktree"],
"D_WKe_": ["Click an agent's avatar in the presence bar to view their session."],
"DbILZA": ["No matches. Some files are excluded from search (hidden or ignored files)."],
"DeDYLr": ["Unrecognized wiki link"],
@@ -523,6 +541,7 @@
"Dub54T": [
"Preview browsers can't auto-copy. Use Cmd/Ctrl+C on the URL above, or open OK in the desktop app."
],
+ "Dvwa0U": ["Create a worktree from this branch"],
"Dw1T_W": ["Rename ", ["label"]],
"E1Da_b": [
"This permanently removes ",
@@ -558,6 +577,7 @@
"Ea1prf": ["Choose which editors every skill in this project installs into."],
"EarrCe": ["Search emoji"],
"EbZT7P": ["Toggle the left file sidebar."],
+ "EbjWsS": ["Current commit"],
"EcM3k7": ["Failed to clean up pending ", ["kind"]],
"EcR0fl": ["Checking for installed agents"],
"EdQY6l": ["None"],
@@ -665,12 +685,10 @@
"H-vDm3": ["Relaunching to install the update…"],
"H0WlWQ": ["Grid of rows and columns with a header row."],
"H86f9p": ["Collapse"],
- "H8Ng4Z": ["Search recent projects"],
"HCn0Ay": ["Toggle strikethrough formatting."],
"HGNCsl": ["Connection lost — keep this tab open, your edits will sync when reconnected"],
"HIb0vl": ["Network error — please try again"],
"HM56Bx": ["Creating..."],
- "HNnVG1": ["No other recent projects."],
"HPTPGr": ["Create a new spec file for my user story"],
"HXFyWD": ["Split diff"],
"HdkSiO": ["New file"],
@@ -678,6 +696,7 @@
"Hl89Qd": ["Loading templates"],
"HlmZBk": ["Documents response did not match expected shape."],
"Hnl9nT": ["Set where pasted and dropped files are stored for this project."],
+ "Hp1l6f": ["Current"],
"HpK_8d": ["Reload"],
"HptUxX": ["Number"],
"HqiZvw": [
@@ -699,6 +718,7 @@
"IRv9cH": ["Cloned ", ["repoName"], "."],
"IWGfGF": ["Checking your GitHub connection"],
"IX7-sq": ["Something went wrong opening \"", ["docName"], "\"."],
+ "IX_uXB": ["my-feature"],
"IajAbS": ["Add a starter pack"],
"If0crP": ["Open with AI ", ["targetDisplayName"], ", ", ["hint"]],
"IgTwLt": ["Open this document in the editor and collapse the graph."],
@@ -825,6 +845,7 @@
}
]
],
+ "LwMxXg": ["Failed to open worktree."],
"M1OfV9": ["Next source diagnostic"],
"M3ytY_": [
"This looks like a drive root (e.g., C:\\). Scaffolding here will scan an entire drive."
@@ -840,6 +861,7 @@
"MQIM_Y": ["Couldn't copy. Select the URL above to copy it manually."],
"MTs6g3": ["Couldn't reconnect after server restart"],
"MUBR8r": ["Rename succeeded but the tabstrip may be out of date — refresh to resync"],
+ "MUrVEo": ["No recent projects."],
"MV-Dkb": ["Found ", ["countDisplay"], " markdown files"],
"MVxpbf": ["Find and replace"],
"MWrUEd": ["Undo all"],
@@ -873,6 +895,7 @@
"N55YNr": [
"Choose whether this project's OpenKnowledge setup, including its AI-tool connections, is saved with the project so teammates get it too, or kept only on your computer."
],
+ "NEzPEh": ["Create a new branch, or check out an existing one, in its own window."],
"NIWAux": ["No docs registered under #", ["tagDocsName"], "."],
"NJyQi_": ["Branch ", ["shareBranch"], " no longer exists on the remote."],
"NKkZXl": ["Initialize and open"],
@@ -971,6 +994,11 @@
"Q6hhn8": ["Preferences"],
"Q7W-mC": ["Same folder as current file"],
"Q8A-U_": ["Connected to"],
+ "QAi7Q9": [
+ "Branch <0>",
+ ["trimmed"],
+ "</0> already has a worktree — it'll open in its own window."
+ ],
"QDZbvN": [["diffDays"], "d ago"],
"QJaG-9": ["Choose CLI for new chat"],
"QNxpRm": ["Dock terminal to the right"],
@@ -1012,6 +1040,7 @@
"We'll build <0>openknowledge.skill</0>, save it to <1>~/Downloads</1>, and open the Claude Desktop App for you."
],
"RSqaSd": ["Project root"],
+ "RVZJWQ": ["Search projects..."],
"RXNu_r": ["Shared via git with everyone working on this project."],
"RY6Bq1": ["Open shared ", ["targetNoun"]],
"RaPMZv": ["Keyboard shortcuts available in the editor and workspace."],
@@ -1047,8 +1076,10 @@
"ScwcF2": ["A project already exists at this location. Pick a different parent folder."],
"Sfh6zL": ["The file on disk, and the id agents use. It can't be changed later."],
"SgKLfA": ["Not connected to GitHub."],
+ "Sh3Qkg": ["No matching branches."],
"SiUUCS": ["Next match"],
"SkMZlS": ["Couldn't remove <0>", ["targetGitPath"], "</0>: ", ["removeGitError"]],
+ "Skr_7L": ["Search worktrees"],
"Sq8lf2": ["Editors to install skills into"],
"SrOuyg": ["Document panels"],
"T-4cw2": [
@@ -1094,6 +1125,7 @@
"UYcGIW": ["Connecting — waiting for collab server"],
"Ua78MH": ["no response"],
"UaDyeb": ["Hide selection preview"],
+ "UaRsDu": ["Show worktrees"],
"Uci-Ph": ["Ordered List"],
"Ud0Pj9": [
"<0>Mirror source removed.</0> The doc <1>",
@@ -1175,6 +1207,7 @@
"X7u0xR": [["0"], " templates available"],
"X8kjQX": ["Re-authenticate with GitHub"],
"X9VpsP": ["Loading folder contents"],
+ "XAyxsa": ["Check out remote branch"],
"XDzAnp": ["Opens in a new tab"],
"XH30C4": ["document"],
"XJOV1Y": ["Activity"],
@@ -1182,6 +1215,7 @@
"XPqe3B": ["Create new tag #", ["tagValue"]],
"XRuL0i": ["Create page"],
"XU0OXn": ["Enable auto-sync"],
+ "XV5sC0": ["Open worktree"],
"XW18jo": ["Page headings response did not match success schema"],
"XYlJJT": ["Setting up"],
"XcGbim": ["Show hidden files"],
@@ -1265,6 +1299,7 @@
"ZWolSV": [
"You picked the filesystem root (/). Scaffolding here will scan every file on this machine — make sure that's what you want."
],
+ "ZWwYwM": ["Base branch"],
"ZWxfrc": ["cleared folder properties"],
"ZWyHmq": ["This project"],
"ZhhOwV": ["Quote"],
@@ -1340,6 +1375,11 @@
"az8lvo": ["Off"],
"b3Thhd": ["Upload failed"],
"b4AQFK": ["Open activity panel for ", ["tooltipName"], ", editing ", ["realCurrentDoc"]],
+ "b4VvP-": [
+ "Existing branch <0>",
+ ["trimmed"],
+ "</0> will be checked out into its own window, under <1>.ok/worktrees/</1>."
+ ],
"b4itZn": ["Working"],
"b5aNbi": ["The ", ["targetNoun"], " could not be opened — try navigating to it manually."],
"bBE5tC": ["Detected on this machine"],
@@ -1347,12 +1387,14 @@
"bD8I7O": ["Complete"],
"bGa3Fk": ["Uploading file"],
"bH382I": ["Edit this HTML — the preview updates live."],
+ "bSD4im": ["Search worktrees and branches"],
"bS_boY": ["Replace current match"],
"bUUVED": ["Asset"],
"bWLmRK": ["Could not fetch branch. Check your connection."],
"bcDHUM": [["descriptorLabel"], " — render error, source editable below"],
"bcjYUA": ["Fold or unfold source"],
"bkQRMh": ["Paragraph"],
+ "blFttG": ["Search projects"],
"bmC18N": ["Clearing local collaboration data for \"", ["docName"], "\" before reconnecting."],
"brCtGB": ["History unavailable"],
"bultyE": [
@@ -1396,6 +1438,14 @@
"dD7NPy": ["Outline"],
"dDpCOp": ["Rename succeeded but the sidebar may be out of date — refresh to resync"],
"dEgA5A": ["Cancel"],
+ "dGAdpH": [
+ "New branch <0>",
+ ["trimmed"],
+ "</0> will be created from <1>",
+ ["currentBaseLabel"],
+ "</1>, in its own worktree under <2>.ok/worktrees/</2>."
+ ],
+ "dIYSqk": ["remote"],
"dJw2_7": ["Saved with the project for your team."],
"dN20LW": [
"Semantic search is on, but no API key is set — search falls back to keyword matching. Add one in <0>Settings → Account</0> (it's stored once for your whole machine)."
@@ -1475,6 +1525,7 @@
"fj5YiP": ["Downloads a fresh copy from GitHub."],
"fo0VXg": ["Uninstall"],
"fqSfXY": ["Replace"],
+ "fuJZKk": ["Search branches"],
"fwhX-N": ["Indent or outdent source"],
"g3UF2V": ["Accept"],
"g4XBm0": ["Small section heading."],
@@ -1485,6 +1536,7 @@
],
"gBbxn_": ["Checking sign-in status"],
"gGVP4q": ["Click <0>+</0> <1/> <2>Create skill</2> <3/> <4>Upload skill</4>."],
+ "gHSAWT": ["Create worktree <0>“<1>", ["typedName"], "</1>”</0>"],
"gITz7o": [
"Move the cursor or extend selection through CodeMirror's standard source-editor navigation keymap."
],
@@ -1533,6 +1585,7 @@
"hHMv6l": ["Delete block"],
"hIQkLb": ["New chat"],
"hLy8b1": ["Updated to Version ", ["version"]],
+ "hQXiDc": ["Search branches..."],
"hSBIG-": ["A title, description, tags — anything that describes this folder."],
"hSySVc": ["Install handoff failed: ", ["msg"]],
"hXUWyd": ["Value is required"],
@@ -1567,6 +1620,7 @@
"iKZkk1": ["Property value"],
"iMkWoF": ["Turn on"],
"iNFKkm": ["No diff."],
+ "iO8V-7": ["Create worktree"],
"iOHg1t": ["Open embedded URL in new tab"],
"iSQTsg": ["Ordered list"],
"iSnkwB": ["Failed to open cloned project."],
@@ -1578,6 +1632,7 @@
"idD8Ev": ["Saved"],
"ig5vUe": ["Failed to load file"],
"iilQXA": ["Folder duplicated"],
+ "ij5sBu": [["0", "plural", { "one": ["worktree"], "other": ["worktrees"] }]],
"ijLc3m": ["Bullet list"],
"ipn17C": [
"The <0>type</0> every document created from this template gets (e.g. <1>research-note</1>). Keeps new docs Open Knowledge Format–conformant."
@@ -1669,6 +1724,7 @@
"lb_UU4": ["Sync now"],
"lbkOif": ["Undo or redo visual-editor changes through TipTap collaboration history."],
"lhjq3G": ["Reset ", ["labelText"], " to default"],
+ "ljHjfg": ["That branch is already open in another worktree."],
"lkYioO": ["Show or hide document panel"],
"ll2yNl": ["Content directory"],
"lond3p": ["Shows above the code body. Round-trips as `title=\"...\"` in markdown."],
@@ -1694,6 +1750,7 @@
"mWVJRX": ["Collapsible section with a clickable summary."],
"mY8U64": ["Teach agents a repeatable task. You can edit the body after creating."],
"mYGY3B": ["Date"],
+ "mYzDD_": ["A worktree folder for that branch already exists."],
"mZ1r4i": ["Create a document from ", ["label"]],
"maDWIB": ["Mirror source <0>api-spec</0>"],
"makN88": ["No patterns yet. Type a folder or file name below to start hiding files."],
@@ -1748,9 +1805,11 @@
"nbfdhU": ["Integrations"],
"ndeI89": ["Use Cmd/Ctrl+C to copy the link below, or open OK in the desktop app."],
"neRy3o": ["Split list item"],
+ "nfoduq": ["create worktree"],
"nft48x": [
"Stored at <0>.ok/templates/</0> in this project. Available in every folder (folder-scoped templates can override by filename)."
],
+ "ng2Ibo": ["Branch name"],
"nh3wwx": ["Embeddings provider key"],
"njBeMm": ["Both"],
"njU86j": ["Property \"", ["trimmed"], "\" already exists"],
@@ -1778,6 +1837,13 @@
],
"o9CrsQ": ["research-note"],
"oAFVKX": ["Failed to update the project sync default — ", ["detail"]],
+ "oAGN8p": [
+ "Remote branch <0>",
+ ["remoteCheckoutRef"],
+ "</0> will be checked out as a new local tracking branch <1>",
+ ["trimmed"],
+ "</1>, in its own window under <2>.ok/worktrees/</2>."
+ ],
"oBXkm2": ["Delete code block"],
"oCHfGC": ["Level"],
"oCZkaG": ["Copy path"],
@@ -1863,6 +1929,7 @@
"qpQwGC": ["Describe what you're working on and the agent sets it up for you."],
"qvWGzP": ["Collapse all"],
"qyLmWw": ["Source editor search panel"],
+ "r-OJYm": ["Enter a valid branch name (no spaces, no leading dot, no \"..\")."],
"r2huLx": ["Undo, redo, or undo selection changes through CodeMirror history."],
"r4R7AZ": ["Network error during cleanup"],
"r51jLC": ["File saved & Claude Desktop App opened"],
@@ -1938,17 +2005,24 @@
"On — your search queries and the text of matching pages are sent to your embeddings provider (OpenAI by default) to compute embeddings."
],
"sxTdZI": ["Loading paths…"],
+ "sxjyRq": ["Worktrees"],
"sxkWRg": ["Advanced"],
"t-JXbf": ["Notion-style inline row for a downloadable file. Drag-drop also works."],
"t18QYR": ["Unpin ", ["accessibleLabel"]],
"t2TkQ3": ["Sync paused — resolve conflicts to resume."],
"t422_7": ["Uninstall everywhere"],
+ "t4sFKC": [
+ "New branch <0>",
+ ["trimmed"],
+ "</0> will be created from the current commit, in its own worktree under <1>.ok/worktrees/</1>."
+ ],
"tAPZEx": ["Below"],
"tHKQ6j": ["Renaming"],
"tP5DDk": ["Apply link"],
"tUvUfp": ["Use a folder you already have."],
"tW_yvQ": ["Expand ", ["docName"]],
"t_YqKh": ["Remove"],
+ "teD0H9": ["Couldn't open a worktree for that branch."],
"tfDRzk": ["Save"],
"tfi40B": ["Failed to create page"],
"tgWuMB": ["Modified"],
@@ -1970,6 +2044,7 @@
"uFOL2y": [
"No project skills yet. Author one to teach agents a repeatable task scoped to this knowledge base."
],
+ "uGaIIS": ["Check out worktree"],
"uH_S-u": [["loadErrorTitle"], ": ", ["message"]],
"uKRYiW": ["Sync status unavailable — server error."],
"uL_Wx8": ["The terminal stopped unexpectedly."],
@@ -2010,6 +2085,7 @@
],
"v7hK0U": ["Use lowercase letters, digits, and hyphens only."],
"v7lbnC": ["Find next match"],
+ "vAYoCZ": ["Couldn't open the worktree. Try again."],
"vDXqVv": ["Insert a markdown hard break."],
"vEJDlt": ["The file is in your Trash; the file-watcher will reconcile."],
"vGeNNQ": ["Copy a prompt and paste it into your agent to set up your project."],
@@ -2056,6 +2132,9 @@
"wndeIl": ["Project-level pages with neither incoming nor outgoing graph edges."],
"wtcxiD": ["Share this setup with your team?"],
"wvbc1r": ["Couldn't open document"],
+ "wzq9Rv": [
+ "A branch with that name already exists. Open its worktree from the switcher instead."
+ ],
"x-5mJ1": ["Install on all"],
"x2fr_j": ["Graph"],
"x3-2ta": [
@@ -2090,6 +2169,7 @@
"xc4g25": ["Parse failed"],
"xeXS4P": ["Or use a starter pack"],
"xeiujy": ["Text"],
+ "xf-VIX": ["worktree of ", ["0"]],
"xhlFsx": ["Inherited — set a value here to replace it."],
"xiv-dW": ["No files yet."],
"xloBjn": ["Relative Path"],
diff --git a/packages/app/src/locales/en/messages.po b/packages/app/src/locales/en/messages.po
index 2dd0f8439..cdcddddc0 100644
--- a/packages/app/src/locales/en/messages.po
+++ b/packages/app/src/locales/en/messages.po
@@ -13,10 +13,6 @@ msgstr ""
"Language-Team: \n"
"Plural-Forms: \n"
-#: src/components/ProjectSwitcher.tsx
-msgid " (missing)"
-msgstr " (missing)"
-
#: src/components/settings/SettingsDialogBody.tsx
msgid " or "
msgstr " or "
@@ -62,6 +58,10 @@ msgstr "\"frontmatter\" is a reserved property name"
msgid "(a worktree of {0})"
msgstr "(a worktree of {0})"
+#: src/components/RecentProjectsMenu.tsx
+msgid "(detached)"
+msgstr "(detached)"
+
#: src/editor/components/PreviewBlockedNotice.tsx
msgid "(inline)"
msgstr "(inline)"
@@ -125,6 +125,11 @@ msgstr "{0, plural, one {# request blocked by the preview's security policy} oth
msgid "{0, plural, one {# use} other {# uses}}"
msgstr "{0, plural, one {# use} other {# uses}}"
+#. placeholder {0}: group.worktrees.length
+#: src/components/RecentProjectsMenu.tsx
+msgid "{0, plural, one {worktree} other {worktrees}}"
+msgstr "{0, plural, one {worktree} other {worktrees}}"
+
#. placeholder {0}: templates.length
#: src/components/empty-state/CreateView.tsx
msgid "{0} templates available"
@@ -179,6 +184,10 @@ msgstr "{behind, plural, one {# commit behind} other {# commits behind}}"
msgid "{behind} behind"
msgstr "{behind} behind"
+#: src/components/NewWorktreeDialog.tsx
+msgid "{behind} behind origin"
+msgstr "{behind} behind origin"
+
#: src/components/EditorFooter.tsx
msgid "{chars, plural, one {char} other {chars}}"
msgstr "{chars, plural, one {char} other {chars}}"
@@ -443,6 +452,10 @@ msgstr "<0>Mirror source removed.</0> The doc <1>{src}</1> is no longer availabl
msgid "📝 or assets/icon.png"
msgstr "📝 or assets/icon.png"
+#: src/components/NewWorktreeDialog.tsx
+msgid "A branch with that name already exists. Open its worktree from the switcher instead."
+msgstr "A branch with that name already exists. Open its worktree from the switcher instead."
+
#: src/components/CreateProjectDialog.tsx
msgid "A folder named <0>{sanitized}</0> already has files here. Pick a different name."
msgstr "A folder named <0>{sanitized}</0> already has files here. Pick a different name."
@@ -508,6 +521,10 @@ msgstr "A template named <0>{trimmedSlug}</0> already exists here. Saving create
msgid "A title, description, tags — anything that describes this folder."
msgstr "A title, description, tags — anything that describes this folder."
+#: src/components/NewWorktreeDialog.tsx
+msgid "A worktree folder for that branch already exists."
+msgstr "A worktree folder for that branch already exists."
+
#: src/editor/slash-command/items.tsx
msgid "Above"
msgstr "Above"
@@ -789,10 +806,18 @@ msgstr "Auto-sync is off — you don't have permission to push to this repo"
msgid "Auto-sync is off — your edits stay local until you commit and push manually."
msgstr "Auto-sync is off — your edits stay local until you commit and push manually."
+#: src/hooks/use-worktree-autosync-notice.tsx
+msgid "Auto-sync is off for this worktree, inherited from {project}. Change it in Settings → Sync."
+msgstr "Auto-sync is off for this worktree, inherited from {project}. Change it in Settings → Sync."
+
#: src/components/settings/SettingsDialogBody.tsx
msgid "Auto-sync is on — your commits push and remote changes pull on intervals."
msgstr "Auto-sync is on — your commits push and remote changes pull on intervals."
+#: src/hooks/use-worktree-autosync-notice.tsx
+msgid "Auto-sync is on for this worktree, inherited from {project}. Change it in Settings → Sync."
+msgstr "Auto-sync is on for this worktree, inherited from {project}. Change it in Settings → Sync."
+
#: src/components/AutoSyncEnableWarning.tsx
msgid "Auto-sync periodically fetches, pulls, and pushes commits to your remote git repository so your edits stay in sync across machines."
msgstr "Auto-sync periodically fetches, pulls, and pushes commits to your remote git repository so your edits stay in sync across machines."
@@ -834,6 +859,10 @@ msgstr "Backlinks"
msgid "Backlinks response did not match expected shape."
msgstr "Backlinks response did not match expected shape."
+#: src/components/NewWorktreeDialog.tsx
+msgid "Base branch"
+msgstr "Base branch"
+
#: src/components/TemplateBody.tsx
msgid "Becomes the document's content when someone creates a doc from this template. Type <0>{dateToken}</0> or <1>{userToken}</1> to fill in today's date or the author's name automatically."
msgstr "Becomes the document's content when someone creates a doc from this template. Type <0>{dateToken}</0> or <1>{userToken}</1> to fill in today's date or the author's name automatically."
@@ -903,6 +932,14 @@ msgstr "Branch {shareBranch} no longer exists on the remote."
msgid "Branch <0>{shareBranch}</0> is checked out in:"
msgstr "Branch <0>{shareBranch}</0> is checked out in:"
+#: src/components/NewWorktreeDialog.tsx
+msgid "Branch <0>{trimmed}</0> already has a worktree — it'll open in its own window."
+msgstr "Branch <0>{trimmed}</0> already has a worktree — it'll open in its own window."
+
+#: src/components/NewWorktreeDialog.tsx
+msgid "Branch name"
+msgstr "Branch name"
+
#: src/components/ShareBranchSwitchDialog.tsx
msgid "Branch switch failed — try opening the {targetNoun} manually."
msgstr "Branch switch failed — try opening the {targetNoun} manually."
@@ -981,6 +1018,7 @@ msgstr "Can't nest projects. An OpenKnowledge project already exists at <0>{root
#: src/components/NewItemDialog.tsx
#: src/components/NewSkillDialog.tsx
#: src/components/NewTemplateDialog.tsx
+#: src/components/NewWorktreeDialog.tsx
#: src/components/PublishToGitHubDialog.tsx
#: src/components/SeedDialog.tsx
#: src/components/settings/SearchSection.tsx
@@ -1004,6 +1042,14 @@ msgstr "Cancelled"
msgid "Cannot upload: no document is open"
msgstr "Cannot upload: no document is open"
+#: src/components/NewWorktreeDialog.tsx
+msgid "Check out remote branch"
+msgstr "Check out remote branch"
+
+#: src/components/NewWorktreeDialog.tsx
+msgid "Check out worktree"
+msgstr "Check out worktree"
+
#: src/components/PropertyWidgets.tsx
msgid "Checkbox"
msgstr "Checkbox"
@@ -1682,6 +1728,10 @@ msgstr "Couldn't create skill: {0}"
msgid "Couldn't create template: {error}"
msgstr "Couldn't create template: {error}"
+#: src/components/NewWorktreeDialog.tsx
+msgid "Couldn't create the worktree. Try a different name."
+msgstr "Couldn't create the worktree. Try a different name."
+
#: src/components/SkillDeleteDialog.tsx
msgid "Couldn't delete skill: {error}"
msgstr "Couldn't delete skill: {error}"
@@ -1746,6 +1796,10 @@ msgstr "Couldn't move skill: {0}"
msgid "Couldn't move to Trash"
msgstr "Couldn't move to Trash"
+#: src/components/RecentProjectsMenu.tsx
+msgid "Couldn't open a worktree for that branch."
+msgstr "Couldn't open a worktree for that branch."
+
#: src/components/DocumentErrorBoundary.tsx
msgid "Couldn't open document"
msgstr "Couldn't open document"
@@ -1754,6 +1808,10 @@ msgstr "Couldn't open document"
msgid "Couldn't open the terminal — please try again."
msgstr "Couldn't open the terminal — please try again."
+#: src/components/NewWorktreeDialog.tsx
+msgid "Couldn't open the worktree. Try again."
+msgstr "Couldn't open the worktree. Try again."
+
#: src/components/ConnectingBanner.tsx
msgid "Couldn't reach collab server — {errorDetail}. Try <0>ok status</0> or check <1>.ok/local/last-spawn-error.log</1>."
msgstr "Couldn't reach collab server — {errorDetail}. Try <0>ok status</0> or check <1>.ok/local/last-spawn-error.log</1>."
@@ -1860,6 +1918,10 @@ msgstr "Create a file from the current document or folder context."
msgid "Create a folder from the current document or folder context."
msgstr "Create a folder from the current document or folder context."
+#: src/components/NewWorktreeDialog.tsx
+msgid "Create a new branch, or check out an existing one, in its own window."
+msgstr "Create a new branch, or check out an existing one, in its own window."
+
#: src/lib/keyboard-shortcuts.ts
msgid "Create a new list item from the current list item."
msgstr "Create a new list item from the current list item."
@@ -1872,6 +1934,10 @@ msgstr "Create a new OpenKnowledge project in the folder of your choice."
msgid "Create a new spec file for my user story"
msgstr "Create a new spec file for my user story"
+#: src/components/RecentProjectsMenu.tsx
+msgid "Create a worktree from this branch"
+msgstr "Create a worktree from this branch"
+
#: src/components/NewItemDialog.tsx
msgid "Create in <0>{dirDisplay}</0>"
msgstr "Create in <0>{dirDisplay}</0>"
@@ -1913,6 +1979,19 @@ msgstr "Create with {0}"
msgid "Create with {0} CLI"
msgstr "Create with {0} CLI"
+#: src/components/RecentProjectsMenu.tsx
+msgid "create worktree"
+msgstr "create worktree"
+
+#: src/components/CommandPalette.tsx
+#: src/components/NewWorktreeDialog.tsx
+msgid "Create worktree"
+msgstr "Create worktree"
+
+#: src/components/RecentProjectsMenu.tsx
+msgid "Create worktree <0>“<1>{typedName}</1>”</0>"
+msgstr "Create worktree <0>“<1>{typedName}</1>”</0>"
+
#: src/components/FileTree.tsx
#: src/components/OnboardingCard.tsx
msgid "Create your first file"
@@ -1954,6 +2033,14 @@ msgstr "Creating page: {linkTitle}."
msgid "Creating..."
msgstr "Creating..."
+#: src/components/RecentProjectsMenu.tsx
+msgid "Current"
+msgstr "Current"
+
+#: src/components/NewWorktreeDialog.tsx
+msgid "Current commit"
+msgstr "Current commit"
+
#: src/editor/extensions/WikiLinkPropPanel.tsx
msgid "Custom display text"
msgstr "Custom display text"
@@ -1970,6 +2057,10 @@ msgstr "Customize how the editor looks and behaves."
msgid "Date"
msgstr "Date"
+#: src/components/RecentProjectsMenu.tsx
+msgid "default"
+msgstr "default"
+
#: src/components/settings/SettingsDialogBody.tsx
msgid "Default location for new attachments"
msgstr "Default location for new attachments"
@@ -2464,10 +2555,18 @@ msgstr "Enter a repository URL or owner/repo"
msgid "Enter a title for this template."
msgstr "Enter a title for this template."
+#: src/components/NewWorktreeDialog.tsx
+msgid "Enter a valid branch name (no spaces, no leading dot, no \"..\")."
+msgstr "Enter a valid branch name (no spaces, no leading dot, no \"..\")."
+
#: src/components/ShareReceiveDialog.tsx
msgid "Error:"
msgstr "Error:"
+#: src/components/NewWorktreeDialog.tsx
+msgid "Existing branch <0>{trimmed}</0> will be checked out into its own window, under <1>.ok/worktrees/</1>."
+msgstr "Existing branch <0>{trimmed}</0> will be checked out into its own window, under <1>.ok/worktrees/</1>."
+
#: src/components/DiffView.tsx
msgid "Exit merge"
msgstr "Exit merge"
@@ -2679,10 +2778,18 @@ msgstr "Failed to open Project Navigator."
#: src/components/CommandPalette.tsx
#: src/components/NavigatorApp.tsx
-#: src/components/ProjectSwitcher.tsx
msgid "Failed to open project."
msgstr "Failed to open project."
+#: src/components/CommandPalette.tsx
+#: src/components/RecentProjectsMenu.tsx
+msgid "Failed to open worktree."
+msgstr "Failed to open worktree."
+
+#: src/components/RecentProjectsMenu.tsx
+msgid "Failed to open."
+msgstr "Failed to open."
+
#: src/components/LinksPanel.tsx
msgid "Failed to parse backlinks error response (HTTP {status})"
msgstr "Failed to parse backlinks error response (HTTP {status})"
@@ -3131,6 +3238,10 @@ msgstr "Hide this file"
msgid "Hide thumbnails"
msgstr "Hide thumbnails"
+#: src/components/RecentProjectsMenu.tsx
+msgid "Hide worktrees"
+msgstr "Hide worktrees"
+
#: src/lib/keyboard-shortcuts.ts
msgid "Highlight"
msgstr "Highlight"
@@ -3820,6 +3931,10 @@ msgstr "moved template"
msgid "Multi-page PDF viewer with toolbar controls (thumbnails, page nav, zoom)."
msgstr "Multi-page PDF viewer with toolbar controls (thumbnails, page nav, zoom)."
+#: src/components/NewWorktreeDialog.tsx
+msgid "my-feature"
+msgstr "my-feature"
+
#: src/components/SubscribeForm.tsx
@@ -3907,6 +4022,14 @@ msgstr "New"
msgid "New {0} chat"
msgstr "New {0} chat"
+#: src/components/NewWorktreeDialog.tsx
+msgid "New branch <0>{trimmed}</0> will be created from <1>{currentBaseLabel}</1>, in its own worktree under <2>.ok/worktrees/</2>."
+msgstr "New branch <0>{trimmed}</0> will be created from <1>{currentBaseLabel}</1>, in its own worktree under <2>.ok/worktrees/</2>."
+
+#: src/components/NewWorktreeDialog.tsx
+msgid "New branch <0>{trimmed}</0> will be created from the current commit, in its own worktree under <1>.ok/worktrees/</1>."
+msgstr "New branch <0>{trimmed}</0> will be created from the current commit, in its own worktree under <1>.ok/worktrees/</1>."
+
#: src/components/TerminalNewChatButton.tsx
msgid "New chat"
msgstr "New chat"
@@ -3973,6 +4096,11 @@ msgstr "New template"
msgid "New terminal"
msgstr "New terminal"
+#: src/components/NewWorktreeDialog.tsx
+#: src/components/ProjectSwitcher.tsx
+msgid "New worktree"
+msgstr "New worktree"
+
#: src/editor/find-replace/FindReplaceBar.tsx
msgid "Next match"
msgstr "Next match"
@@ -4088,6 +4216,10 @@ msgstr "No location selected. Use Browse to choose a folder."
msgid "No matches. Some files are excluded from search (hidden or ignored files)."
msgstr "No matches. Some files are excluded from search (hidden or ignored files)."
+#: src/components/NewWorktreeDialog.tsx
+msgid "No matching branches."
+msgstr "No matching branches."
+
#: src/components/CommandPalette.tsx
msgid "No matching commands."
msgstr "No matching commands."
@@ -4100,7 +4232,7 @@ msgstr "No matching docs"
msgid "No matching paths"
msgstr "No matching paths"
-#: src/components/ProjectSwitcher.tsx
+#: src/components/RecentProjectsMenu.tsx
msgid "No matching projects."
msgstr "No matching projects."
@@ -4108,9 +4240,9 @@ msgstr "No matching projects."
msgid "No matching repositories."
msgstr "No matching repositories."
-#: src/components/ProjectSwitcher.tsx
-msgid "No other recent projects."
-msgstr "No other recent projects."
+#: src/components/RecentProjectsMenu.tsx
+msgid "No matching worktrees or branches."
+msgstr "No matching worktrees or branches."
#: src/components/GraphPanel.tsx
msgid "No Outgoing"
@@ -4152,6 +4284,10 @@ msgstr "No project skills yet. Author one to teach agents a repeatable task scop
msgid "No project templates yet. Create one to make it available everywhere in this project. Folder-scoped templates live on each folder's overview page."
msgstr "No project templates yet. Create one to make it available everywhere in this project. Folder-scoped templates live on each folder's overview page."
+#: src/components/ProjectSwitcher.tsx
+msgid "No recent projects."
+msgstr "No recent projects."
+
#: src/components/CloneDialog.tsx
msgid "No repositories found on your GitHub account."
msgstr "No repositories found on your GitHub account."
@@ -4529,6 +4665,10 @@ msgstr "Open with AI {targetDisplayName}"
msgid "Open with AI {targetDisplayName}, {hint}"
msgstr "Open with AI {targetDisplayName}, {hint}"
+#: src/components/NewWorktreeDialog.tsx
+msgid "Open worktree"
+msgstr "Open worktree"
+
#: src/lib/keyboard-shortcuts.ts
msgid "Open, navigate, accept, or dismiss CodeMirror completion suggestions."
msgstr "Open, navigate, accept, or dismiss CodeMirror completion suggestions."
@@ -5044,6 +5184,14 @@ msgstr "Release notes"
msgid "Reload"
msgstr "Reload"
+#: src/components/NewWorktreeDialog.tsx
+msgid "remote"
+msgstr "remote"
+
+#: src/components/NewWorktreeDialog.tsx
+msgid "Remote branch <0>{remoteCheckoutRef}</0> will be checked out as a new local tracking branch <1>{trimmed}</1>, in its own window under <2>.ok/worktrees/</2>."
+msgstr "Remote branch <0>{remoteCheckoutRef}</0> will be checked out as a new local tracking branch <1>{trimmed}</1>, in its own window under <2>.ok/worktrees/</2>."
+
#: src/editor/extensions/InternalLinkPropPanel.tsx
#: src/editor/extensions/WikiLinkPropPanel.tsx
msgid "Remove"
@@ -5430,6 +5578,14 @@ msgstr "Search \"{semanticSubmitQuery}\" by meaning"
msgid "Search ({searchShortcut})"
msgstr "Search ({searchShortcut})"
+#: src/components/NewWorktreeDialog.tsx
+msgid "Search branches"
+msgstr "Search branches"
+
+#: src/components/NewWorktreeDialog.tsx
+msgid "Search branches..."
+msgstr "Search branches..."
+
#: src/components/CommandPalette.tsx
msgid "Search by meaning"
msgstr "Search by meaning"
@@ -5459,12 +5615,12 @@ msgid "Search matches file names, paths, and folders. Open a file to search its
msgstr "Search matches file names, paths, and folders. Open a file to search its body (⌘F)."
#: src/components/ProjectSwitcher.tsx
-msgid "Search recent projects"
-msgstr "Search recent projects"
+msgid "Search projects"
+msgstr "Search projects"
#: src/components/ProjectSwitcher.tsx
-msgid "Search recent projects..."
-msgstr "Search recent projects..."
+msgid "Search projects..."
+msgstr "Search projects..."
#: src/components/settings/SearchSection.tsx
msgid "Search settings not yet loaded — try again in a moment"
@@ -5474,6 +5630,14 @@ msgstr "Search settings not yet loaded — try again in a moment"
msgid "Search templates"
msgstr "Search templates"
+#: src/components/RecentProjectsMenu.tsx
+msgid "Search worktrees"
+msgstr "Search worktrees"
+
+#: src/components/RecentProjectsMenu.tsx
+msgid "Search worktrees and branches"
+msgstr "Search worktrees and branches"
+
#: src/components/CommandPalette.tsx
msgid "Searching"
msgstr "Searching"
@@ -5778,6 +5942,10 @@ msgstr "Show terminal"
msgid "Show thumbnails"
msgstr "Show thumbnails"
+#: src/components/RecentProjectsMenu.tsx
+msgid "Show worktrees"
+msgstr "Show worktrees"
+
#: src/components/CommandPalette.tsx
msgid "Showing results for \"{semanticResultsLabel}\""
msgstr "Showing results for \"{semanticResultsLabel}\""
@@ -6247,6 +6415,10 @@ msgstr "Text"
msgid "Thanks for subscribing. Watch your inbox for product updates."
msgstr "Thanks for subscribing. Watch your inbox for product updates."
+#: src/components/NewWorktreeDialog.tsx
+msgid "That branch is already open in another worktree."
+msgstr "That branch is already open in another worktree."
+
#: src/components/ShareReceiveDialog.tsx
msgid "That folder isn't an OpenKnowledge project yet. Initialize it and open?"
msgstr "That folder isn't an OpenKnowledge project yet. Initialize it and open?"
@@ -6443,6 +6615,10 @@ msgstr "This project is running a different, incompatible build of OpenKnowledge
msgid "This project is running an older version of OpenKnowledge (v{0}) than this app (v{1})."
msgstr "This project is running an older version of OpenKnowledge (v{0}) than this app (v{1})."
+#: src/components/NewWorktreeDialog.tsx
+msgid "This project isn't a git repository, so worktrees aren't available."
+msgstr "This project isn't a git repository, so worktrees aren't available."
+
#: src/components/settings/SettingsDialogBody.tsx
msgid "This project lives only on this computer. Connect it to GitHub to back it up and share it with other people."
msgstr "This project lives only on this computer. Connect it to GitHub to back it up and share it with other people."
@@ -7023,6 +7199,7 @@ msgid "Word wrap"
msgstr "Word wrap"
#: src/components/McpConsentDialogBody.tsx
+#: src/components/NewWorktreeDialog.tsx
#: src/components/SkillEditorActions.tsx
msgid "Working"
msgstr "Working"
@@ -7035,6 +7212,19 @@ msgstr "Workspace"
msgid "Workspace Command Palette"
msgstr "Workspace Command Palette"
+#. placeholder {0}: basenameOf(project.mainRoot ?? '')
+#: src/components/NavigatorApp.tsx
+msgid "worktree of {0}"
+msgstr "worktree of {0}"
+
+#: src/components/CommandPalette.tsx
+msgid "worktree of {worktreeOf}"
+msgstr "worktree of {worktreeOf}"
+
+#: src/components/CommandPalette.tsx
+msgid "Worktrees"
+msgstr "Worktrees"
+
#: src/components/settings/SettingsDialogBody.tsx
msgid "Wrap long lines in the markdown source editor."
msgstr "Wrap long lines in the markdown source editor."
diff --git a/packages/app/src/locales/pseudo/messages.json b/packages/app/src/locales/pseudo/messages.json
index 7edc8952b..ada925450 100644
--- a/packages/app/src/locales/pseudo/messages.json
+++ b/packages/app/src/locales/pseudo/messages.json
@@ -24,9 +24,11 @@
],
"-r_Kx7": ["Ćŕēàţē śķĩĺĺ"],
"-slrNR": ["Ţōĝĝĺē à ţàśķ ĺĩśţ."],
+ "-uaQnI": ["Ńō ḿàţćĥĩńĝ ŵōŕķţŕēēś ōŕ ƀŕàńćĥēś."],
"-wePNM": [
"Śēàŕćĥ ḿàţćĥēś ƒĩĺē ńàḿēś, ƥàţĥś, àńď ƒōĺďēŕś. Ōƥēń à ƒĩĺē ţō śēàŕćĥ ĩţś ƀōďŷ (⌘Ƒ)."
],
+ "-zA2E7": ["Ćōũĺďń'ţ ćŕēàţē ţĥē ŵōŕķţŕēē. Ţŕŷ à ďĩƒƒēŕēńţ ńàḿē."],
"-zy2Nq": ["Ţŷƥē"],
"0-31GV": ["Ŕēḿōvĩńĝ"],
"02P3hL": ["Ũƥĺōàď ƒàĩĺēď: ", ["message"]],
@@ -106,7 +108,6 @@
"2XQ8Ww": ["Ōƥēń ƥŕēvĩēŵ ŵĥēń àĝēńţ ēďĩţś"],
"2YOwme": ["Ŕēśţàŕţēď — ńōŵ ŕũńńĩńĝ v", ["appRuntime"], "."],
"2YZwPB": ["Ƒōŕŵàŕď-ĺĩńķś ŕēśƥōńśē ďĩď ńōţ ḿàţćĥ ēxƥēćţēď śĥàƥē."],
- "2Znqb1": [" (ḿĩśśĩńĝ)"],
"2bVHbB": ["Àvàĩĺàƀĺē ĩń ēvēŕŷ ƥŕōĴēćţ ōń ţĥĩś ćōḿƥũţēŕ."],
"2fkdnR": ["Ńōţĥĩńĝ ţō ũńďō ōń ţĥĩś ƒĩĺē"],
"2hYmUH": ["ḿŷ@ēḿàĩĺ.ćōḿ"],
@@ -201,6 +202,11 @@
"4uNLmk": ["Ƥũĺĺĩńĝ"],
"4v2Yyz": ["Śēĺēćţ ēvēŕŷ vĩśĩƀĺē ƒĩĺē-ţŕēē ŕōŵ ŵĥēń ƒōćũś ĩś ĩń ţĥē Ƒĩĺēś śĩďēƀàŕ."],
"4xtLTl": ["Ĥĩďďēń ƒōĺďēŕ “", ["basename"], "”"],
+ "4zEZS5": [
+ "Àũţō-śŷńć ĩś ōń ƒōŕ ţĥĩś ŵōŕķţŕēē, ĩńĥēŕĩţēď ƒŕōḿ ",
+ ["project"],
+ ". Ćĥàńĝē ĩţ ĩń Śēţţĩńĝś → Śŷńć."
+ ],
"4zGlN_": ["Ƥàśţē ĩḿàĝē ŨŔĹ ōŕ ćĺĩćķ ũƥĺōàď"],
"5-FeN2": ["Śĥàŕē ŨŔĹ"],
"54Y6Fg": ["Ćōũĺď ńōţ ĺōàď ţēḿƥĺàţēś. Ţŕŷ àĝàĩń ĺàţēŕ."],
@@ -260,11 +266,13 @@
],
"5wV2qQ": ["àńď ḿōŕē"],
"5y_9lO": ["Ŵàĩţĩńĝ ƒōŕ àũţĥōŕĩźàţĩōń"],
+ "6-wLTJ": [["behind"], " ƀēĥĩńď ōŕĩĝĩń"],
"62Pc08": ["Ĩńśţàĺĺ ƒōŕ Ćĺàũďē Ćĥàţ & Ćōŵōŕķ (Ďēśķţōƥ Àƥƥ)"],
"636K3K": ["Ďēĺēţē àďĴàćēńţ ćĥĩƥ"],
"67f-3g": ["Ďũƥĺĩćàţē śũććēēďēď ƀũţ ţĥē śĩďēƀàŕ ḿàŷ ƀē ōũţ ōƒ ďàţē — ŕēƒŕēśĥ ţō ŕēśŷńć"],
"6Aih4U": ["Ōƒƒĺĩńē"],
"6EKG_c": ["Ŵĥàţ àĝēńţś ḿàţćĥ ōń ţō ďēćĩďē ŵĥēń ţō ũśē ţĥē śķĩĺĺ."],
+ "6HCOwA": ["Ƒàĩĺēď ţō ōƥēń."],
"6LbUG7": ["Ţĥē ŕēƥōśĩţōŕŷ ĩś ƥŕĩvàţē àńď ŷōũŕ ĜĩţĤũƀ àććōũńţ ďōēśń'ţ ĥàvē àććēśś ţō ĩţ."],
"6MnZEC": ["Ţēŕḿĩńàĺ ƒàĩĺēď ţō ĺōàď"],
"6O626z": ["Ńō ĥēàďĩńĝś ḿàţćĥ \"", ["trimmedAnchorQuery"], "\""],
@@ -346,13 +354,13 @@
{ "one": ["#", " ũńŕēśōĺvēď ĥũńķ"], "other": ["#", " ũńŕēśōĺvēď ĥũńķś"] }
]
],
+ "8Gzz2G": ["ŵōŕķţŕēē ōƒ ", ["worktreeOf"]],
"8IP5jY": ["Ēàćĥ śēĺēćţēď ţōōĺ ĝēţś àń ŌƥēńĶńōŵĺēďĝē ḾĆƤ ēńţŕŷ."],
"8Jm2EP": ["Ţōĝĝĺē ĥēàďĩńĝ ĺēvēĺś 1 ţĥŕōũĝĥ 6."],
"8OGgNM": ["Ōƥēń ōŕ ćĺōśē vĩśũàĺ-ēďĩţōŕ ƒĩńď."],
"8OxKZy": ["Ḿōvē śũććēēďēď ƀũţ ţĥē śĩďēƀàŕ ḿàŷ ƀē ōũţ ōƒ ďàţē — ŕēƒŕēśĥ ţō ŕēśŷńć"],
"8PmoQF": ["Ōƥēń ţĥē ĩńśēŕţ ḿēńũ ĩń àń ēḿƥţŷ ōŕ àćţĩvē ţēxţ ƥōśĩţĩōń."],
"8RtNI0": ["Ƒàĩĺēď ţō ĺōàď ďōćũḿēńţś"],
- "8S1E33": ["Śēàŕćĥ ŕēćēńţ ƥŕōĴēćţś..."],
"8XQRON": ["Ĺōàďĩńĝ ŕēƥōśĩţōŕĩēś"],
"8_brI5": ["Ńàḿē ĩś ŕēǫũĩŕēď"],
"8cS0nH": ["Ćōńƒĩĝ śĥàŕĩńĝ ũńàvàĩĺàƀĺē: ", ["0"], "."],
@@ -422,6 +430,11 @@
"ATGYL1": ["Ēḿàĩĺ àďďŕēśś"],
"AVW-K9": ["Ƒàĩĺēď ţō ĺōàď ōŕƥĥàń ƥàĝēś"],
"AWOSPo": ["Źōōḿ ĩń"],
+ "AaaESH": [
+ "Àũţō-śŷńć ĩś ōƒƒ ƒōŕ ţĥĩś ŵōŕķţŕēē, ĩńĥēŕĩţēď ƒŕōḿ ",
+ ["project"],
+ ". Ćĥàńĝē ĩţ ĩń Śēţţĩńĝś → Śŷńć."
+ ],
"AcK_r0": ["Ćĺàũďē ĆĹĨ"],
"AdcGcG": ["Àƥƥĺŷĩńĝ ŷōũŕ ćĥàńĝē"],
"AddR83": ["Ćōũĺď ńōţ ćŕēàţē ƥŕōĴēćţ. Ţŕŷ àĝàĩń ōŕ ƥĩćķ à ďĩƒƒēŕēńţ ĺōćàţĩōń."],
@@ -431,6 +444,7 @@
"Ţĥĩś ƥŕōĴēćţ ĺĩvēś ōńĺŷ ōń ţĥĩś ćōḿƥũţēŕ. Ćōńńēćţ ĩţ ţō ĜĩţĤũƀ ţō ƀàćķ ĩţ ũƥ àńď śĥàŕē ĩţ ŵĩţĥ ōţĥēŕ ƥēōƥĺē."
],
"Aif3E7": ["Ēńàƀĺē śēḿàńţĩć śēàŕćĥ"],
+ "Aj1D9r": ["Ĥĩďē ŵōŕķţŕēēś"],
"Am78jY": ["Ďŕàĝ ", ["keyName"], " ţō ŕēōŕďēŕ"],
"Aq-O0x": ["śţàţũś"],
"AqnqMJ": ["ÀƤĨ ķēŷ śēţ"],
@@ -468,6 +482,7 @@
"Bdha5y": ["Ƥũƀĺĩśĥĩńĝ..."],
"BeWTQy": ["Ĺōàďĩńĝ śţàŕţēŕ ƥàćķś"],
"BgV29F": ["Vĩśũàĺ ēďĩţōŕ ƒĩńď ĩńƥũţ ƒōćũśēď"],
+ "Bn9-El": ["ďēƒàũĺţ"],
"Bv5a9_": ["Śēĺēćţĩōń śţàţĩśţĩćś"],
"Bx4EXG": ["Àćţĩōńś ƒōŕ ", ["label"]],
"By-7Pn": ["Ţōĝĝĺē à ƀũĺĺēţ ĺĩśţ."],
@@ -477,6 +492,7 @@
"C7XjNB": ["Ĝĺōƀàĺ Śķĩĺĺ"],
"C9TBvF": ["Ńō Ōũţĝōĩńĝ"],
"CCTop_": ["Ŕēćēńţ"],
+ "CFnavk": ["Ţĥĩś ƥŕōĴēćţ ĩśń'ţ à ĝĩţ ŕēƥōśĩţōŕŷ, śō ŵōŕķţŕēēś àŕēń'ţ àvàĩĺàƀĺē."],
"CKyk7Q": ["Ĝō ƀàćķ"],
"COr1Y7": [
"Ƥĩćķ <0>ōƥēńķńōŵĺēďĝē.śķĩĺĺ</0> ƒŕōḿ ŷōũŕ <1>Ďōŵńĺōàďś</1> ƒōĺďēŕ. Ĩţ ēńàƀĺēś àũţōḿàţĩćàĺĺŷ."
@@ -494,6 +510,7 @@
"Ck9XRt": ["Ćōũĺďń'ţ śàvē ţĥē ķēŷ — ƥĺēàśē ţŕŷ àĝàĩń."],
"CmeH9S": ["Àďď ƥŕōƥēŕţŷ ţō ", ["keyName"]],
"CvsD6Y": ["vĩà ", ["viaTags"]],
+ "D12vtS": ["(ďēţàćĥēď)"],
"D4H2N6": ["Ŕēḿōvē ", ["tag"]],
"D8OV7J": ["Ōńĺŷ ćōĺĺàƀōŕàţōŕś"],
"DDTdLl": ["Ćōďē ƀĺōćķ śēţţĩńĝś"],
@@ -503,6 +520,7 @@
"DId6MT": ["ƤŕōĴēćţ-ĺēvēĺ ƥàĝēś ŵĩţĥ ńō ōũţĝōĩńĝ ĝŕàƥĥ ēďĝēś."],
"DPfwMq": ["Ďōńē"],
"DVh_Tb": ["Ƒàĩĺēď ţō ćĺēàń ũƥ àƒţēŕ ţŕàśĥ"],
+ "DXd9LM": ["Ńēŵ ŵōŕķţŕēē"],
"D_WKe_": ["Ćĺĩćķ àń àĝēńţ'ś àvàţàŕ ĩń ţĥē ƥŕēśēńćē ƀàŕ ţō vĩēŵ ţĥēĩŕ śēśśĩōń."],
"DbILZA": ["Ńō ḿàţćĥēś. Śōḿē ƒĩĺēś àŕē ēxćĺũďēď ƒŕōḿ śēàŕćĥ (ĥĩďďēń ōŕ ĩĝńōŕēď ƒĩĺēś)."],
"DeDYLr": ["Ũńŕēćōĝńĩźēď ŵĩķĩ ĺĩńķ"],
@@ -523,6 +541,7 @@
"Dub54T": [
"Ƥŕēvĩēŵ ƀŕōŵśēŕś ćàń'ţ àũţō-ćōƥŷ. Ũśē Ćḿď/Ćţŕĺ+Ć ōń ţĥē ŨŔĹ àƀōvē, ōŕ ōƥēń ŌĶ ĩń ţĥē ďēśķţōƥ àƥƥ."
],
+ "Dvwa0U": ["Ćŕēàţē à ŵōŕķţŕēē ƒŕōḿ ţĥĩś ƀŕàńćĥ"],
"Dw1T_W": ["Ŕēńàḿē ", ["label"]],
"E1Da_b": [
"Ţĥĩś ƥēŕḿàńēńţĺŷ ŕēḿōvēś ",
@@ -558,6 +577,7 @@
"Ea1prf": ["Ćĥōōśē ŵĥĩćĥ ēďĩţōŕś ēvēŕŷ śķĩĺĺ ĩń ţĥĩś ƥŕōĴēćţ ĩńśţàĺĺś ĩńţō."],
"EarrCe": ["Śēàŕćĥ ēḿōĴĩ"],
"EbZT7P": ["Ţōĝĝĺē ţĥē ĺēƒţ ƒĩĺē śĩďēƀàŕ."],
+ "EbjWsS": ["Ćũŕŕēńţ ćōḿḿĩţ"],
"EcM3k7": ["Ƒàĩĺēď ţō ćĺēàń ũƥ ƥēńďĩńĝ ", ["kind"]],
"EcR0fl": ["Ćĥēćķĩńĝ ƒōŕ ĩńśţàĺĺēď àĝēńţś"],
"EdQY6l": ["Ńōńē"],
@@ -665,12 +685,10 @@
"H-vDm3": ["Ŕēĺàũńćĥĩńĝ ţō ĩńśţàĺĺ ţĥē ũƥďàţē…"],
"H0WlWQ": ["Ĝŕĩď ōƒ ŕōŵś àńď ćōĺũḿńś ŵĩţĥ à ĥēàďēŕ ŕōŵ."],
"H86f9p": ["Ćōĺĺàƥśē"],
- "H8Ng4Z": ["Śēàŕćĥ ŕēćēńţ ƥŕōĴēćţś"],
"HCn0Ay": ["Ţōĝĝĺē śţŕĩķēţĥŕōũĝĥ ƒōŕḿàţţĩńĝ."],
"HGNCsl": ["Ćōńńēćţĩōń ĺōśţ — ķēēƥ ţĥĩś ţàƀ ōƥēń, ŷōũŕ ēďĩţś ŵĩĺĺ śŷńć ŵĥēń ŕēćōńńēćţēď"],
"HIb0vl": ["Ńēţŵōŕķ ēŕŕōŕ — ƥĺēàśē ţŕŷ àĝàĩń"],
"HM56Bx": ["Ćŕēàţĩńĝ..."],
- "HNnVG1": ["Ńō ōţĥēŕ ŕēćēńţ ƥŕōĴēćţś."],
"HPTPGr": ["Ćŕēàţē à ńēŵ śƥēć ƒĩĺē ƒōŕ ḿŷ ũśēŕ śţōŕŷ"],
"HXFyWD": ["Śƥĺĩţ ďĩƒƒ"],
"HdkSiO": ["Ńēŵ ƒĩĺē"],
@@ -678,6 +696,7 @@
"Hl89Qd": ["Ĺōàďĩńĝ ţēḿƥĺàţēś"],
"HlmZBk": ["Ďōćũḿēńţś ŕēśƥōńśē ďĩď ńōţ ḿàţćĥ ēxƥēćţēď śĥàƥē."],
"Hnl9nT": ["Śēţ ŵĥēŕē ƥàśţēď àńď ďŕōƥƥēď ƒĩĺēś àŕē śţōŕēď ƒōŕ ţĥĩś ƥŕōĴēćţ."],
+ "Hp1l6f": ["Ćũŕŕēńţ"],
"HpK_8d": ["Ŕēĺōàď"],
"HptUxX": ["Ńũḿƀēŕ"],
"HqiZvw": [
@@ -699,6 +718,7 @@
"IRv9cH": ["Ćĺōńēď ", ["repoName"], "."],
"IWGfGF": ["Ćĥēćķĩńĝ ŷōũŕ ĜĩţĤũƀ ćōńńēćţĩōń"],
"IX7-sq": ["Śōḿēţĥĩńĝ ŵēńţ ŵŕōńĝ ōƥēńĩńĝ \"", ["docName"], "\"."],
+ "IX_uXB": ["ḿŷ-ƒēàţũŕē"],
"IajAbS": ["Àďď à śţàŕţēŕ ƥàćķ"],
"If0crP": ["Ōƥēń ŵĩţĥ ÀĨ ", ["targetDisplayName"], ", ", ["hint"]],
"IgTwLt": ["Ōƥēń ţĥĩś ďōćũḿēńţ ĩń ţĥē ēďĩţōŕ àńď ćōĺĺàƥśē ţĥē ĝŕàƥĥ."],
@@ -825,6 +845,7 @@
}
]
],
+ "LwMxXg": ["Ƒàĩĺēď ţō ōƥēń ŵōŕķţŕēē."],
"M1OfV9": ["Ńēxţ śōũŕćē ďĩàĝńōśţĩć"],
"M3ytY_": [
"Ţĥĩś ĺōōķś ĺĩķē à ďŕĩvē ŕōōţ (ē.ĝ., Ć:\\). Śćàƒƒōĺďĩńĝ ĥēŕē ŵĩĺĺ śćàń àń ēńţĩŕē ďŕĩvē."
@@ -840,6 +861,7 @@
"MQIM_Y": ["Ćōũĺďń'ţ ćōƥŷ. Śēĺēćţ ţĥē ŨŔĹ àƀōvē ţō ćōƥŷ ĩţ ḿàńũàĺĺŷ."],
"MTs6g3": ["Ćōũĺďń'ţ ŕēćōńńēćţ àƒţēŕ śēŕvēŕ ŕēśţàŕţ"],
"MUBR8r": ["Ŕēńàḿē śũććēēďēď ƀũţ ţĥē ţàƀśţŕĩƥ ḿàŷ ƀē ōũţ ōƒ ďàţē — ŕēƒŕēśĥ ţō ŕēśŷńć"],
+ "MUrVEo": ["Ńō ŕēćēńţ ƥŕōĴēćţś."],
"MV-Dkb": ["Ƒōũńď ", ["countDisplay"], " ḿàŕķďōŵń ƒĩĺēś"],
"MVxpbf": ["Ƒĩńď àńď ŕēƥĺàćē"],
"MWrUEd": ["Ũńďō àĺĺ"],
@@ -873,6 +895,7 @@
"N55YNr": [
"Ćĥōōśē ŵĥēţĥēŕ ţĥĩś ƥŕōĴēćţ'ś ŌƥēńĶńōŵĺēďĝē śēţũƥ, ĩńćĺũďĩńĝ ĩţś ÀĨ-ţōōĺ ćōńńēćţĩōńś, ĩś śàvēď ŵĩţĥ ţĥē ƥŕōĴēćţ śō ţēàḿḿàţēś ĝēţ ĩţ ţōō, ōŕ ķēƥţ ōńĺŷ ōń ŷōũŕ ćōḿƥũţēŕ."
],
+ "NEzPEh": ["Ćŕēàţē à ńēŵ ƀŕàńćĥ, ōŕ ćĥēćķ ōũţ àń ēxĩśţĩńĝ ōńē, ĩń ĩţś ōŵń ŵĩńďōŵ."],
"NIWAux": ["Ńō ďōćś ŕēĝĩśţēŕēď ũńďēŕ #", ["tagDocsName"], "."],
"NJyQi_": ["ßŕàńćĥ ", ["shareBranch"], " ńō ĺōńĝēŕ ēxĩśţś ōń ţĥē ŕēḿōţē."],
"NKkZXl": ["Ĩńĩţĩàĺĩźē àńď ōƥēń"],
@@ -971,6 +994,11 @@
"Q6hhn8": ["Ƥŕēƒēŕēńćēś"],
"Q7W-mC": ["Śàḿē ƒōĺďēŕ àś ćũŕŕēńţ ƒĩĺē"],
"Q8A-U_": ["Ćōńńēćţēď ţō"],
+ "QAi7Q9": [
+ "ßŕàńćĥ <0>",
+ ["trimmed"],
+ "</0> àĺŕēàďŷ ĥàś à ŵōŕķţŕēē — ĩţ'ĺĺ ōƥēń ĩń ĩţś ōŵń ŵĩńďōŵ."
+ ],
"QDZbvN": [["diffDays"], "ď àĝō"],
"QJaG-9": ["Ćĥōōśē ĆĹĨ ƒōŕ ńēŵ ćĥàţ"],
"QNxpRm": ["Ďōćķ ţēŕḿĩńàĺ ţō ţĥē ŕĩĝĥţ"],
@@ -1012,6 +1040,7 @@
"Ŵē'ĺĺ ƀũĩĺď <0>ōƥēńķńōŵĺēďĝē.śķĩĺĺ</0>, śàvē ĩţ ţō <1>~/Ďōŵńĺōàďś</1>, àńď ōƥēń ţĥē Ćĺàũďē Ďēśķţōƥ Àƥƥ ƒōŕ ŷōũ."
],
"RSqaSd": ["ƤŕōĴēćţ ŕōōţ"],
+ "RVZJWQ": ["Śēàŕćĥ ƥŕōĴēćţś..."],
"RXNu_r": ["Śĥàŕēď vĩà ĝĩţ ŵĩţĥ ēvēŕŷōńē ŵōŕķĩńĝ ōń ţĥĩś ƥŕōĴēćţ."],
"RY6Bq1": ["Ōƥēń śĥàŕēď ", ["targetNoun"]],
"RaPMZv": ["Ķēŷƀōàŕď śĥōŕţćũţś àvàĩĺàƀĺē ĩń ţĥē ēďĩţōŕ àńď ŵōŕķśƥàćē."],
@@ -1047,8 +1076,10 @@
"ScwcF2": ["À ƥŕōĴēćţ àĺŕēàďŷ ēxĩśţś àţ ţĥĩś ĺōćàţĩōń. Ƥĩćķ à ďĩƒƒēŕēńţ ƥàŕēńţ ƒōĺďēŕ."],
"Sfh6zL": ["Ţĥē ƒĩĺē ōń ďĩśķ, àńď ţĥē ĩď àĝēńţś ũśē. Ĩţ ćàń'ţ ƀē ćĥàńĝēď ĺàţēŕ."],
"SgKLfA": ["Ńōţ ćōńńēćţēď ţō ĜĩţĤũƀ."],
+ "Sh3Qkg": ["Ńō ḿàţćĥĩńĝ ƀŕàńćĥēś."],
"SiUUCS": ["Ńēxţ ḿàţćĥ"],
"SkMZlS": ["Ćōũĺďń'ţ ŕēḿōvē <0>", ["targetGitPath"], "</0>: ", ["removeGitError"]],
+ "Skr_7L": ["Śēàŕćĥ ŵōŕķţŕēēś"],
"Sq8lf2": ["Ēďĩţōŕś ţō ĩńśţàĺĺ śķĩĺĺś ĩńţō"],
"SrOuyg": ["Ďōćũḿēńţ ƥàńēĺś"],
"T-4cw2": [
@@ -1094,6 +1125,7 @@
"UYcGIW": ["Ćōńńēćţĩńĝ — ŵàĩţĩńĝ ƒōŕ ćōĺĺàƀ śēŕvēŕ"],
"Ua78MH": ["ńō ŕēśƥōńśē"],
"UaDyeb": ["Ĥĩďē śēĺēćţĩōń ƥŕēvĩēŵ"],
+ "UaRsDu": ["Śĥōŵ ŵōŕķţŕēēś"],
"Uci-Ph": ["Ōŕďēŕēď Ĺĩśţ"],
"Ud0Pj9": [
"<0>Ḿĩŕŕōŕ śōũŕćē ŕēḿōvēď.</0> Ţĥē ďōć <1>",
@@ -1175,6 +1207,7 @@
"X7u0xR": [["0"], " ţēḿƥĺàţēś àvàĩĺàƀĺē"],
"X8kjQX": ["Ŕē-àũţĥēńţĩćàţē ŵĩţĥ ĜĩţĤũƀ"],
"X9VpsP": ["Ĺōàďĩńĝ ƒōĺďēŕ ćōńţēńţś"],
+ "XAyxsa": ["Ćĥēćķ ōũţ ŕēḿōţē ƀŕàńćĥ"],
"XDzAnp": ["Ōƥēńś ĩń à ńēŵ ţàƀ"],
"XH30C4": ["ďōćũḿēńţ"],
"XJOV1Y": ["Àćţĩvĩţŷ"],
@@ -1182,6 +1215,7 @@
"XPqe3B": ["Ćŕēàţē ńēŵ ţàĝ #", ["tagValue"]],
"XRuL0i": ["Ćŕēàţē ƥàĝē"],
"XU0OXn": ["Ēńàƀĺē àũţō-śŷńć"],
+ "XV5sC0": ["Ōƥēń ŵōŕķţŕēē"],
"XW18jo": ["Ƥàĝē ĥēàďĩńĝś ŕēśƥōńśē ďĩď ńōţ ḿàţćĥ śũććēśś śćĥēḿà"],
"XYlJJT": ["Śēţţĩńĝ ũƥ"],
"XcGbim": ["Śĥōŵ ĥĩďďēń ƒĩĺēś"],
@@ -1265,6 +1299,7 @@
"ZWolSV": [
"Ŷōũ ƥĩćķēď ţĥē ƒĩĺēśŷśţēḿ ŕōōţ (/). Śćàƒƒōĺďĩńĝ ĥēŕē ŵĩĺĺ śćàń ēvēŕŷ ƒĩĺē ōń ţĥĩś ḿàćĥĩńē — ḿàķē śũŕē ţĥàţ'ś ŵĥàţ ŷōũ ŵàńţ."
],
+ "ZWwYwM": ["ßàśē ƀŕàńćĥ"],
"ZWxfrc": ["ćĺēàŕēď ƒōĺďēŕ ƥŕōƥēŕţĩēś"],
"ZWyHmq": ["Ţĥĩś ƥŕōĴēćţ"],
"ZhhOwV": ["Ǫũōţē"],
@@ -1340,6 +1375,11 @@
"az8lvo": ["Ōƒƒ"],
"b3Thhd": ["Ũƥĺōàď ƒàĩĺēď"],
"b4AQFK": ["Ōƥēń àćţĩvĩţŷ ƥàńēĺ ƒōŕ ", ["tooltipName"], ", ēďĩţĩńĝ ", ["realCurrentDoc"]],
+ "b4VvP-": [
+ "Ēxĩśţĩńĝ ƀŕàńćĥ <0>",
+ ["trimmed"],
+ "</0> ŵĩĺĺ ƀē ćĥēćķēď ōũţ ĩńţō ĩţś ōŵń ŵĩńďōŵ, ũńďēŕ <1>.ōķ/ŵōŕķţŕēēś/</1>."
+ ],
"b4itZn": ["Ŵōŕķĩńĝ"],
"b5aNbi": ["Ţĥē ", ["targetNoun"], " ćōũĺď ńōţ ƀē ōƥēńēď — ţŕŷ ńàvĩĝàţĩńĝ ţō ĩţ ḿàńũàĺĺŷ."],
"bBE5tC": ["Ďēţēćţēď ōń ţĥĩś ḿàćĥĩńē"],
@@ -1347,12 +1387,14 @@
"bD8I7O": ["Ćōḿƥĺēţē"],
"bGa3Fk": ["Ũƥĺōàďĩńĝ ƒĩĺē"],
"bH382I": ["Ēďĩţ ţĥĩś ĤŢḾĹ — ţĥē ƥŕēvĩēŵ ũƥďàţēś ĺĩvē."],
+ "bSD4im": ["Śēàŕćĥ ŵōŕķţŕēēś àńď ƀŕàńćĥēś"],
"bS_boY": ["Ŕēƥĺàćē ćũŕŕēńţ ḿàţćĥ"],
"bUUVED": ["Àśśēţ"],
"bWLmRK": ["Ćōũĺď ńōţ ƒēţćĥ ƀŕàńćĥ. Ćĥēćķ ŷōũŕ ćōńńēćţĩōń."],
"bcDHUM": [["descriptorLabel"], " — ŕēńďēŕ ēŕŕōŕ, śōũŕćē ēďĩţàƀĺē ƀēĺōŵ"],
"bcjYUA": ["Ƒōĺď ōŕ ũńƒōĺď śōũŕćē"],
"bkQRMh": ["Ƥàŕàĝŕàƥĥ"],
+ "blFttG": ["Śēàŕćĥ ƥŕōĴēćţś"],
"bmC18N": ["Ćĺēàŕĩńĝ ĺōćàĺ ćōĺĺàƀōŕàţĩōń ďàţà ƒōŕ \"", ["docName"], "\" ƀēƒōŕē ŕēćōńńēćţĩńĝ."],
"brCtGB": ["Ĥĩśţōŕŷ ũńàvàĩĺàƀĺē"],
"bultyE": [
@@ -1396,6 +1438,14 @@
"dD7NPy": ["Ōũţĺĩńē"],
"dDpCOp": ["Ŕēńàḿē śũććēēďēď ƀũţ ţĥē śĩďēƀàŕ ḿàŷ ƀē ōũţ ōƒ ďàţē — ŕēƒŕēśĥ ţō ŕēśŷńć"],
"dEgA5A": ["Ćàńćēĺ"],
+ "dGAdpH": [
+ "Ńēŵ ƀŕàńćĥ <0>",
+ ["trimmed"],
+ "</0> ŵĩĺĺ ƀē ćŕēàţēď ƒŕōḿ <1>",
+ ["currentBaseLabel"],
+ "</1>, ĩń ĩţś ōŵń ŵōŕķţŕēē ũńďēŕ <2>.ōķ/ŵōŕķţŕēēś/</2>."
+ ],
+ "dIYSqk": ["ŕēḿōţē"],
"dJw2_7": ["Śàvēď ŵĩţĥ ţĥē ƥŕōĴēćţ ƒōŕ ŷōũŕ ţēàḿ."],
"dN20LW": [
"Śēḿàńţĩć śēàŕćĥ ĩś ōń, ƀũţ ńō ÀƤĨ ķēŷ ĩś śēţ — śēàŕćĥ ƒàĺĺś ƀàćķ ţō ķēŷŵōŕď ḿàţćĥĩńĝ. Àďď ōńē ĩń <0>Śēţţĩńĝś → Àććōũńţ</0> (ĩţ'ś śţōŕēď ōńćē ƒōŕ ŷōũŕ ŵĥōĺē ḿàćĥĩńē)."
@@ -1475,6 +1525,7 @@
"fj5YiP": ["Ďōŵńĺōàďś à ƒŕēśĥ ćōƥŷ ƒŕōḿ ĜĩţĤũƀ."],
"fo0VXg": ["Ũńĩńśţàĺĺ"],
"fqSfXY": ["Ŕēƥĺàćē"],
+ "fuJZKk": ["Śēàŕćĥ ƀŕàńćĥēś"],
"fwhX-N": ["Ĩńďēńţ ōŕ ōũţďēńţ śōũŕćē"],
"g3UF2V": ["Àććēƥţ"],
"g4XBm0": ["Śḿàĺĺ śēćţĩōń ĥēàďĩńĝ."],
@@ -1485,6 +1536,7 @@
],
"gBbxn_": ["Ćĥēćķĩńĝ śĩĝń-ĩń śţàţũś"],
"gGVP4q": ["Ćĺĩćķ <0>+</0> <1/> <2>Ćŕēàţē śķĩĺĺ</2> <3/> <4>Ũƥĺōàď śķĩĺĺ</4>."],
+ "gHSAWT": ["Ćŕēàţē ŵōŕķţŕēē <0>“<1>", ["typedName"], "</1>”</0>"],
"gITz7o": [
"Ḿōvē ţĥē ćũŕśōŕ ōŕ ēxţēńď śēĺēćţĩōń ţĥŕōũĝĥ ĆōďēḾĩŕŕōŕ'ś śţàńďàŕď śōũŕćē-ēďĩţōŕ ńàvĩĝàţĩōń ķēŷḿàƥ."
],
@@ -1533,6 +1585,7 @@
"hHMv6l": ["Ďēĺēţē ƀĺōćķ"],
"hIQkLb": ["Ńēŵ ćĥàţ"],
"hLy8b1": ["Ũƥďàţēď ţō Vēŕśĩōń ", ["version"]],
+ "hQXiDc": ["Śēàŕćĥ ƀŕàńćĥēś..."],
"hSBIG-": ["À ţĩţĺē, ďēśćŕĩƥţĩōń, ţàĝś — àńŷţĥĩńĝ ţĥàţ ďēśćŕĩƀēś ţĥĩś ƒōĺďēŕ."],
"hSySVc": ["Ĩńśţàĺĺ ĥàńďōƒƒ ƒàĩĺēď: ", ["msg"]],
"hXUWyd": ["Vàĺũē ĩś ŕēǫũĩŕēď"],
@@ -1567,6 +1620,7 @@
"iKZkk1": ["Ƥŕōƥēŕţŷ vàĺũē"],
"iMkWoF": ["Ţũŕń ōń"],
"iNFKkm": ["Ńō ďĩƒƒ."],
+ "iO8V-7": ["Ćŕēàţē ŵōŕķţŕēē"],
"iOHg1t": ["Ōƥēń ēḿƀēďďēď ŨŔĹ ĩń ńēŵ ţàƀ"],
"iSQTsg": ["Ōŕďēŕēď ĺĩśţ"],
"iSnkwB": ["Ƒàĩĺēď ţō ōƥēń ćĺōńēď ƥŕōĴēćţ."],
@@ -1578,6 +1632,7 @@
"idD8Ev": ["Śàvēď"],
"ig5vUe": ["Ƒàĩĺēď ţō ĺōàď ƒĩĺē"],
"iilQXA": ["Ƒōĺďēŕ ďũƥĺĩćàţēď"],
+ "ij5sBu": [["0", "plural", { "one": ["ŵōŕķţŕēē"], "other": ["ŵōŕķţŕēēś"] }]],
"ijLc3m": ["ßũĺĺēţ ĺĩśţ"],
"ipn17C": [
"Ţĥē <0>ţŷƥē</0> ēvēŕŷ ďōćũḿēńţ ćŕēàţēď ƒŕōḿ ţĥĩś ţēḿƥĺàţē ĝēţś (ē.ĝ. <1>ŕēśēàŕćĥ-ńōţē</1>). Ķēēƥś ńēŵ ďōćś Ōƥēń Ķńōŵĺēďĝē Ƒōŕḿàţ–ćōńƒōŕḿàńţ."
@@ -1669,6 +1724,7 @@
"lb_UU4": ["Śŷńć ńōŵ"],
"lbkOif": ["Ũńďō ōŕ ŕēďō vĩśũàĺ-ēďĩţōŕ ćĥàńĝēś ţĥŕōũĝĥ ŢĩƥŢàƥ ćōĺĺàƀōŕàţĩōń ĥĩśţōŕŷ."],
"lhjq3G": ["Ŕēśēţ ", ["labelText"], " ţō ďēƒàũĺţ"],
+ "ljHjfg": ["Ţĥàţ ƀŕàńćĥ ĩś àĺŕēàďŷ ōƥēń ĩń àńōţĥēŕ ŵōŕķţŕēē."],
"lkYioO": ["Śĥōŵ ōŕ ĥĩďē ďōćũḿēńţ ƥàńēĺ"],
"ll2yNl": ["Ćōńţēńţ ďĩŕēćţōŕŷ"],
"lond3p": ["Śĥōŵś àƀōvē ţĥē ćōďē ƀōďŷ. Ŕōũńď-ţŕĩƥś àś `ţĩţĺē=\"...\"` ĩń ḿàŕķďōŵń."],
@@ -1694,6 +1750,7 @@
"mWVJRX": ["Ćōĺĺàƥśĩƀĺē śēćţĩōń ŵĩţĥ à ćĺĩćķàƀĺē śũḿḿàŕŷ."],
"mY8U64": ["Ţēàćĥ àĝēńţś à ŕēƥēàţàƀĺē ţàśķ. Ŷōũ ćàń ēďĩţ ţĥē ƀōďŷ àƒţēŕ ćŕēàţĩńĝ."],
"mYGY3B": ["Ďàţē"],
+ "mYzDD_": ["À ŵōŕķţŕēē ƒōĺďēŕ ƒōŕ ţĥàţ ƀŕàńćĥ àĺŕēàďŷ ēxĩśţś."],
"mZ1r4i": ["Ćŕēàţē à ďōćũḿēńţ ƒŕōḿ ", ["label"]],
"maDWIB": ["Ḿĩŕŕōŕ śōũŕćē <0>àƥĩ-śƥēć</0>"],
"makN88": ["Ńō ƥàţţēŕńś ŷēţ. Ţŷƥē à ƒōĺďēŕ ōŕ ƒĩĺē ńàḿē ƀēĺōŵ ţō śţàŕţ ĥĩďĩńĝ ƒĩĺēś."],
@@ -1748,9 +1805,11 @@
"nbfdhU": ["Ĩńţēĝŕàţĩōńś"],
"ndeI89": ["Ũśē Ćḿď/Ćţŕĺ+Ć ţō ćōƥŷ ţĥē ĺĩńķ ƀēĺōŵ, ōŕ ōƥēń ŌĶ ĩń ţĥē ďēśķţōƥ àƥƥ."],
"neRy3o": ["Śƥĺĩţ ĺĩśţ ĩţēḿ"],
+ "nfoduq": ["ćŕēàţē ŵōŕķţŕēē"],
"nft48x": [
"Śţōŕēď àţ <0>.ōķ/ţēḿƥĺàţēś/</0> ĩń ţĥĩś ƥŕōĴēćţ. Àvàĩĺàƀĺē ĩń ēvēŕŷ ƒōĺďēŕ (ƒōĺďēŕ-śćōƥēď ţēḿƥĺàţēś ćàń ōvēŕŕĩďē ƀŷ ƒĩĺēńàḿē)."
],
+ "ng2Ibo": ["ßŕàńćĥ ńàḿē"],
"nh3wwx": ["Ēḿƀēďďĩńĝś ƥŕōvĩďēŕ ķēŷ"],
"njBeMm": ["ßōţĥ"],
"njU86j": ["Ƥŕōƥēŕţŷ \"", ["trimmed"], "\" àĺŕēàďŷ ēxĩśţś"],
@@ -1778,6 +1837,13 @@
],
"o9CrsQ": ["ŕēśēàŕćĥ-ńōţē"],
"oAFVKX": ["Ƒàĩĺēď ţō ũƥďàţē ţĥē ƥŕōĴēćţ śŷńć ďēƒàũĺţ — ", ["detail"]],
+ "oAGN8p": [
+ "Ŕēḿōţē ƀŕàńćĥ <0>",
+ ["remoteCheckoutRef"],
+ "</0> ŵĩĺĺ ƀē ćĥēćķēď ōũţ àś à ńēŵ ĺōćàĺ ţŕàćķĩńĝ ƀŕàńćĥ <1>",
+ ["trimmed"],
+ "</1>, ĩń ĩţś ōŵń ŵĩńďōŵ ũńďēŕ <2>.ōķ/ŵōŕķţŕēēś/</2>."
+ ],
"oBXkm2": ["Ďēĺēţē ćōďē ƀĺōćķ"],
"oCHfGC": ["Ĺēvēĺ"],
"oCZkaG": ["Ćōƥŷ ƥàţĥ"],
@@ -1863,6 +1929,7 @@
"qpQwGC": ["Ďēśćŕĩƀē ŵĥàţ ŷōũ'ŕē ŵōŕķĩńĝ ōń àńď ţĥē àĝēńţ śēţś ĩţ ũƥ ƒōŕ ŷōũ."],
"qvWGzP": ["Ćōĺĺàƥśē àĺĺ"],
"qyLmWw": ["Śōũŕćē ēďĩţōŕ śēàŕćĥ ƥàńēĺ"],
+ "r-OJYm": ["Ēńţēŕ à vàĺĩď ƀŕàńćĥ ńàḿē (ńō śƥàćēś, ńō ĺēàďĩńĝ ďōţ, ńō \"..\")."],
"r2huLx": ["Ũńďō, ŕēďō, ōŕ ũńďō śēĺēćţĩōń ćĥàńĝēś ţĥŕōũĝĥ ĆōďēḾĩŕŕōŕ ĥĩśţōŕŷ."],
"r4R7AZ": ["Ńēţŵōŕķ ēŕŕōŕ ďũŕĩńĝ ćĺēàńũƥ"],
"r51jLC": ["Ƒĩĺē śàvēď & Ćĺàũďē Ďēśķţōƥ Àƥƥ ōƥēńēď"],
@@ -1938,17 +2005,24 @@
"Ōń — ŷōũŕ śēàŕćĥ ǫũēŕĩēś àńď ţĥē ţēxţ ōƒ ḿàţćĥĩńĝ ƥàĝēś àŕē śēńţ ţō ŷōũŕ ēḿƀēďďĩńĝś ƥŕōvĩďēŕ (ŌƥēńÀĨ ƀŷ ďēƒàũĺţ) ţō ćōḿƥũţē ēḿƀēďďĩńĝś."
],
"sxTdZI": ["Ĺōàďĩńĝ ƥàţĥś…"],
+ "sxjyRq": ["Ŵōŕķţŕēēś"],
"sxkWRg": ["Àďvàńćēď"],
"t-JXbf": ["Ńōţĩōń-śţŷĺē ĩńĺĩńē ŕōŵ ƒōŕ à ďōŵńĺōàďàƀĺē ƒĩĺē. Ďŕàĝ-ďŕōƥ àĺśō ŵōŕķś."],
"t18QYR": ["Ũńƥĩń ", ["accessibleLabel"]],
"t2TkQ3": ["Śŷńć ƥàũśēď — ŕēśōĺvē ćōńƒĺĩćţś ţō ŕēśũḿē."],
"t422_7": ["Ũńĩńśţàĺĺ ēvēŕŷŵĥēŕē"],
+ "t4sFKC": [
+ "Ńēŵ ƀŕàńćĥ <0>",
+ ["trimmed"],
+ "</0> ŵĩĺĺ ƀē ćŕēàţēď ƒŕōḿ ţĥē ćũŕŕēńţ ćōḿḿĩţ, ĩń ĩţś ōŵń ŵōŕķţŕēē ũńďēŕ <1>.ōķ/ŵōŕķţŕēēś/</1>."
+ ],
"tAPZEx": ["ßēĺōŵ"],
"tHKQ6j": ["Ŕēńàḿĩńĝ"],
"tP5DDk": ["Àƥƥĺŷ ĺĩńķ"],
"tUvUfp": ["Ũśē à ƒōĺďēŕ ŷōũ àĺŕēàďŷ ĥàvē."],
"tW_yvQ": ["Ēxƥàńď ", ["docName"]],
"t_YqKh": ["Ŕēḿōvē"],
+ "teD0H9": ["Ćōũĺďń'ţ ōƥēń à ŵōŕķţŕēē ƒōŕ ţĥàţ ƀŕàńćĥ."],
"tfDRzk": ["Śàvē"],
"tfi40B": ["Ƒàĩĺēď ţō ćŕēàţē ƥàĝē"],
"tgWuMB": ["Ḿōďĩƒĩēď"],
@@ -1970,6 +2044,7 @@
"uFOL2y": [
"Ńō ƥŕōĴēćţ śķĩĺĺś ŷēţ. Àũţĥōŕ ōńē ţō ţēàćĥ àĝēńţś à ŕēƥēàţàƀĺē ţàśķ śćōƥēď ţō ţĥĩś ķńōŵĺēďĝē ƀàśē."
],
+ "uGaIIS": ["Ćĥēćķ ōũţ ŵōŕķţŕēē"],
"uH_S-u": [["loadErrorTitle"], ": ", ["message"]],
"uKRYiW": ["Śŷńć śţàţũś ũńàvàĩĺàƀĺē — śēŕvēŕ ēŕŕōŕ."],
"uL_Wx8": ["Ţĥē ţēŕḿĩńàĺ śţōƥƥēď ũńēxƥēćţēďĺŷ."],
@@ -2010,6 +2085,7 @@
],
"v7hK0U": ["Ũśē ĺōŵēŕćàśē ĺēţţēŕś, ďĩĝĩţś, àńď ĥŷƥĥēńś ōńĺŷ."],
"v7lbnC": ["Ƒĩńď ńēxţ ḿàţćĥ"],
+ "vAYoCZ": ["Ćōũĺďń'ţ ōƥēń ţĥē ŵōŕķţŕēē. Ţŕŷ àĝàĩń."],
"vDXqVv": ["Ĩńśēŕţ à ḿàŕķďōŵń ĥàŕď ƀŕēàķ."],
"vEJDlt": ["Ţĥē ƒĩĺē ĩś ĩń ŷōũŕ Ţŕàśĥ; ţĥē ƒĩĺē-ŵàţćĥēŕ ŵĩĺĺ ŕēćōńćĩĺē."],
"vGeNNQ": ["Ćōƥŷ à ƥŕōḿƥţ àńď ƥàśţē ĩţ ĩńţō ŷōũŕ àĝēńţ ţō śēţ ũƥ ŷōũŕ ƥŕōĴēćţ."],
@@ -2056,6 +2132,9 @@
"wndeIl": ["ƤŕōĴēćţ-ĺēvēĺ ƥàĝēś ŵĩţĥ ńēĩţĥēŕ ĩńćōḿĩńĝ ńōŕ ōũţĝōĩńĝ ĝŕàƥĥ ēďĝēś."],
"wtcxiD": ["Śĥàŕē ţĥĩś śēţũƥ ŵĩţĥ ŷōũŕ ţēàḿ?"],
"wvbc1r": ["Ćōũĺďń'ţ ōƥēń ďōćũḿēńţ"],
+ "wzq9Rv": [
+ "À ƀŕàńćĥ ŵĩţĥ ţĥàţ ńàḿē àĺŕēàďŷ ēxĩśţś. Ōƥēń ĩţś ŵōŕķţŕēē ƒŕōḿ ţĥē śŵĩţćĥēŕ ĩńśţēàď."
+ ],
"x-5mJ1": ["Ĩńśţàĺĺ ōń àĺĺ"],
"x2fr_j": ["Ĝŕàƥĥ"],
"x3-2ta": [
@@ -2090,6 +2169,7 @@
"xc4g25": ["Ƥàŕśē ƒàĩĺēď"],
"xeXS4P": ["Ōŕ ũśē à śţàŕţēŕ ƥàćķ"],
"xeiujy": ["Ţēxţ"],
+ "xf-VIX": ["ŵōŕķţŕēē ōƒ ", ["0"]],
"xhlFsx": ["Ĩńĥēŕĩţēď — śēţ à vàĺũē ĥēŕē ţō ŕēƥĺàćē ĩţ."],
"xiv-dW": ["Ńō ƒĩĺēś ŷēţ."],
"xloBjn": ["Ŕēĺàţĩvē Ƥàţĥ"],
diff --git a/packages/app/src/locales/pseudo/messages.po b/packages/app/src/locales/pseudo/messages.po
index bf3cfbbf6..4b22ab14e 100644
--- a/packages/app/src/locales/pseudo/messages.po
+++ b/packages/app/src/locales/pseudo/messages.po
@@ -13,10 +13,6 @@ msgstr ""
"Language-Team: \n"
"Plural-Forms: \n"
-#: src/components/ProjectSwitcher.tsx
-msgid " (missing)"
-msgstr ""
-
#: src/components/settings/SettingsDialogBody.tsx
msgid " or "
msgstr ""
@@ -62,6 +58,10 @@ msgstr ""
msgid "(a worktree of {0})"
msgstr ""
+#: src/components/RecentProjectsMenu.tsx
+msgid "(detached)"
+msgstr ""
+
#: src/editor/components/PreviewBlockedNotice.tsx
msgid "(inline)"
msgstr ""
@@ -125,6 +125,11 @@ msgstr ""
msgid "{0, plural, one {# use} other {# uses}}"
msgstr ""
+#. placeholder {0}: group.worktrees.length
+#: src/components/RecentProjectsMenu.tsx
+msgid "{0, plural, one {worktree} other {worktrees}}"
+msgstr ""
+
#. placeholder {0}: templates.length
#: src/components/empty-state/CreateView.tsx
msgid "{0} templates available"
@@ -179,6 +184,10 @@ msgstr ""
msgid "{behind} behind"
msgstr ""
+#: src/components/NewWorktreeDialog.tsx
+msgid "{behind} behind origin"
+msgstr ""
+
#: src/components/EditorFooter.tsx
msgid "{chars, plural, one {char} other {chars}}"
msgstr ""
@@ -438,6 +447,10 @@ msgstr ""
msgid "📝 or assets/icon.png"
msgstr ""
+#: src/components/NewWorktreeDialog.tsx
+msgid "A branch with that name already exists. Open its worktree from the switcher instead."
+msgstr ""
+
#: src/components/CreateProjectDialog.tsx
msgid "A folder named <0>{sanitized}</0> already has files here. Pick a different name."
msgstr ""
@@ -503,6 +516,10 @@ msgstr ""
msgid "A title, description, tags — anything that describes this folder."
msgstr ""
+#: src/components/NewWorktreeDialog.tsx
+msgid "A worktree folder for that branch already exists."
+msgstr ""
+
#: src/editor/slash-command/items.tsx
msgid "Above"
msgstr ""
@@ -784,10 +801,18 @@ msgstr ""
msgid "Auto-sync is off — your edits stay local until you commit and push manually."
msgstr ""
+#: src/hooks/use-worktree-autosync-notice.tsx
+msgid "Auto-sync is off for this worktree, inherited from {project}. Change it in Settings → Sync."
+msgstr ""
+
#: src/components/settings/SettingsDialogBody.tsx
msgid "Auto-sync is on — your commits push and remote changes pull on intervals."
msgstr ""
+#: src/hooks/use-worktree-autosync-notice.tsx
+msgid "Auto-sync is on for this worktree, inherited from {project}. Change it in Settings → Sync."
+msgstr ""
+
#: src/components/AutoSyncEnableWarning.tsx
msgid "Auto-sync periodically fetches, pulls, and pushes commits to your remote git repository so your edits stay in sync across machines."
msgstr ""
@@ -829,6 +854,10 @@ msgstr ""
msgid "Backlinks response did not match expected shape."
msgstr ""
+#: src/components/NewWorktreeDialog.tsx
+msgid "Base branch"
+msgstr ""
+
#: src/components/TemplateBody.tsx
msgid "Becomes the document's content when someone creates a doc from this template. Type <0>{dateToken}</0> or <1>{userToken}</1> to fill in today's date or the author's name automatically."
msgstr ""
@@ -898,6 +927,14 @@ msgstr ""
msgid "Branch <0>{shareBranch}</0> is checked out in:"
msgstr ""
+#: src/components/NewWorktreeDialog.tsx
+msgid "Branch <0>{trimmed}</0> already has a worktree — it'll open in its own window."
+msgstr ""
+
+#: src/components/NewWorktreeDialog.tsx
+msgid "Branch name"
+msgstr ""
+
#: src/components/ShareBranchSwitchDialog.tsx
msgid "Branch switch failed — try opening the {targetNoun} manually."
msgstr ""
@@ -976,6 +1013,7 @@ msgstr ""
#: src/components/NewItemDialog.tsx
#: src/components/NewSkillDialog.tsx
#: src/components/NewTemplateDialog.tsx
+#: src/components/NewWorktreeDialog.tsx
#: src/components/PublishToGitHubDialog.tsx
#: src/components/SeedDialog.tsx
#: src/components/settings/SearchSection.tsx
@@ -999,6 +1037,14 @@ msgstr ""
msgid "Cannot upload: no document is open"
msgstr ""
+#: src/components/NewWorktreeDialog.tsx
+msgid "Check out remote branch"
+msgstr ""
+
+#: src/components/NewWorktreeDialog.tsx
+msgid "Check out worktree"
+msgstr ""
+
#: src/components/PropertyWidgets.tsx
msgid "Checkbox"
msgstr ""
@@ -1677,6 +1723,10 @@ msgstr ""
msgid "Couldn't create template: {error}"
msgstr ""
+#: src/components/NewWorktreeDialog.tsx
+msgid "Couldn't create the worktree. Try a different name."
+msgstr ""
+
#: src/components/SkillDeleteDialog.tsx
msgid "Couldn't delete skill: {error}"
msgstr ""
@@ -1741,6 +1791,10 @@ msgstr ""
msgid "Couldn't move to Trash"
msgstr ""
+#: src/components/RecentProjectsMenu.tsx
+msgid "Couldn't open a worktree for that branch."
+msgstr ""
+
#: src/components/DocumentErrorBoundary.tsx
msgid "Couldn't open document"
msgstr ""
@@ -1749,6 +1803,10 @@ msgstr ""
msgid "Couldn't open the terminal — please try again."
msgstr ""
+#: src/components/NewWorktreeDialog.tsx
+msgid "Couldn't open the worktree. Try again."
+msgstr ""
+
#: src/components/ConnectingBanner.tsx
msgid "Couldn't reach collab server — {errorDetail}. Try <0>ok status</0> or check <1>.ok/local/last-spawn-error.log</1>."
msgstr ""
@@ -1855,6 +1913,10 @@ msgstr ""
msgid "Create a folder from the current document or folder context."
msgstr ""
+#: src/components/NewWorktreeDialog.tsx
+msgid "Create a new branch, or check out an existing one, in its own window."
+msgstr ""
+
#: src/lib/keyboard-shortcuts.ts
msgid "Create a new list item from the current list item."
msgstr ""
@@ -1867,6 +1929,10 @@ msgstr ""
msgid "Create a new spec file for my user story"
msgstr ""
+#: src/components/RecentProjectsMenu.tsx
+msgid "Create a worktree from this branch"
+msgstr ""
+
#: src/components/NewItemDialog.tsx
msgid "Create in <0>{dirDisplay}</0>"
msgstr ""
@@ -1908,6 +1974,19 @@ msgstr ""
msgid "Create with {0} CLI"
msgstr ""
+#: src/components/RecentProjectsMenu.tsx
+msgid "create worktree"
+msgstr ""
+
+#: src/components/CommandPalette.tsx
+#: src/components/NewWorktreeDialog.tsx
+msgid "Create worktree"
+msgstr ""
+
+#: src/components/RecentProjectsMenu.tsx
+msgid "Create worktree <0>“<1>{typedName}</1>”</0>"
+msgstr ""
+
#: src/components/FileTree.tsx
#: src/components/OnboardingCard.tsx
msgid "Create your first file"
@@ -1949,6 +2028,14 @@ msgstr ""
msgid "Creating..."
msgstr ""
+#: src/components/RecentProjectsMenu.tsx
+msgid "Current"
+msgstr ""
+
+#: src/components/NewWorktreeDialog.tsx
+msgid "Current commit"
+msgstr ""
+
#: src/editor/extensions/WikiLinkPropPanel.tsx
msgid "Custom display text"
msgstr ""
@@ -1965,6 +2052,10 @@ msgstr ""
msgid "Date"
msgstr ""
+#: src/components/RecentProjectsMenu.tsx
+msgid "default"
+msgstr ""
+
#: src/components/settings/SettingsDialogBody.tsx
msgid "Default location for new attachments"
msgstr ""
@@ -2459,10 +2550,18 @@ msgstr ""
msgid "Enter a title for this template."
msgstr ""
+#: src/components/NewWorktreeDialog.tsx
+msgid "Enter a valid branch name (no spaces, no leading dot, no \"..\")."
+msgstr ""
+
#: src/components/ShareReceiveDialog.tsx
msgid "Error:"
msgstr ""
+#: src/components/NewWorktreeDialog.tsx
+msgid "Existing branch <0>{trimmed}</0> will be checked out into its own window, under <1>.ok/worktrees/</1>."
+msgstr ""
+
#: src/components/DiffView.tsx
msgid "Exit merge"
msgstr ""
@@ -2674,10 +2773,18 @@ msgstr ""
#: src/components/CommandPalette.tsx
#: src/components/NavigatorApp.tsx
-#: src/components/ProjectSwitcher.tsx
msgid "Failed to open project."
msgstr ""
+#: src/components/CommandPalette.tsx
+#: src/components/RecentProjectsMenu.tsx
+msgid "Failed to open worktree."
+msgstr ""
+
+#: src/components/RecentProjectsMenu.tsx
+msgid "Failed to open."
+msgstr ""
+
#: src/components/LinksPanel.tsx
msgid "Failed to parse backlinks error response (HTTP {status})"
msgstr ""
@@ -3126,6 +3233,10 @@ msgstr ""
msgid "Hide thumbnails"
msgstr ""
+#: src/components/RecentProjectsMenu.tsx
+msgid "Hide worktrees"
+msgstr ""
+
#: src/lib/keyboard-shortcuts.ts
msgid "Highlight"
msgstr ""
@@ -3815,6 +3926,10 @@ msgstr ""
msgid "Multi-page PDF viewer with toolbar controls (thumbnails, page nav, zoom)."
msgstr ""
+#: src/components/NewWorktreeDialog.tsx
+msgid "my-feature"
+msgstr ""
+
#: src/components/SubscribeForm.tsx
msgstr ""
@@ -3902,6 +4017,14 @@ msgstr ""
msgid "New {0} chat"
msgstr ""
+#: src/components/NewWorktreeDialog.tsx
+msgid "New branch <0>{trimmed}</0> will be created from <1>{currentBaseLabel}</1>, in its own worktree under <2>.ok/worktrees/</2>."
+msgstr ""
+
+#: src/components/NewWorktreeDialog.tsx
+msgid "New branch <0>{trimmed}</0> will be created from the current commit, in its own worktree under <1>.ok/worktrees/</1>."
+msgstr ""
+
#: src/components/TerminalNewChatButton.tsx
msgid "New chat"
msgstr ""
@@ -3968,6 +4091,11 @@ msgstr ""
msgid "New terminal"
msgstr ""
+#: src/components/NewWorktreeDialog.tsx
+#: src/components/ProjectSwitcher.tsx
+msgid "New worktree"
+msgstr ""
+
#: src/editor/find-replace/FindReplaceBar.tsx
msgid "Next match"
msgstr ""
@@ -4083,6 +4211,10 @@ msgstr ""
msgid "No matches. Some files are excluded from search (hidden or ignored files)."
msgstr ""
+#: src/components/NewWorktreeDialog.tsx
+msgid "No matching branches."
+msgstr ""
+
#: src/components/CommandPalette.tsx
msgid "No matching commands."
msgstr ""
@@ -4095,7 +4227,7 @@ msgstr ""
msgid "No matching paths"
msgstr ""
-#: src/components/ProjectSwitcher.tsx
+#: src/components/RecentProjectsMenu.tsx
msgid "No matching projects."
msgstr ""
@@ -4103,8 +4235,8 @@ msgstr ""
msgid "No matching repositories."
msgstr ""
-#: src/components/ProjectSwitcher.tsx
-msgid "No other recent projects."
+#: src/components/RecentProjectsMenu.tsx
+msgid "No matching worktrees or branches."
msgstr ""
#: src/components/GraphPanel.tsx
@@ -4147,6 +4279,10 @@ msgstr ""
msgid "No project templates yet. Create one to make it available everywhere in this project. Folder-scoped templates live on each folder's overview page."
msgstr ""
+#: src/components/ProjectSwitcher.tsx
+msgid "No recent projects."
+msgstr ""
+
#: src/components/CloneDialog.tsx
msgid "No repositories found on your GitHub account."
msgstr ""
@@ -4524,6 +4660,10 @@ msgstr ""
msgid "Open with AI {targetDisplayName}, {hint}"
msgstr ""
+#: src/components/NewWorktreeDialog.tsx
+msgid "Open worktree"
+msgstr ""
+
#: src/lib/keyboard-shortcuts.ts
msgid "Open, navigate, accept, or dismiss CodeMirror completion suggestions."
msgstr ""
@@ -5039,6 +5179,14 @@ msgstr ""
msgid "Reload"
msgstr ""
+#: src/components/NewWorktreeDialog.tsx
+msgid "remote"
+msgstr ""
+
+#: src/components/NewWorktreeDialog.tsx
+msgid "Remote branch <0>{remoteCheckoutRef}</0> will be checked out as a new local tracking branch <1>{trimmed}</1>, in its own window under <2>.ok/worktrees/</2>."
+msgstr ""
+
#: src/editor/extensions/InternalLinkPropPanel.tsx
#: src/editor/extensions/WikiLinkPropPanel.tsx
msgid "Remove"
@@ -5425,6 +5573,14 @@ msgstr ""
msgid "Search ({searchShortcut})"
msgstr ""
+#: src/components/NewWorktreeDialog.tsx
+msgid "Search branches"
+msgstr ""
+
+#: src/components/NewWorktreeDialog.tsx
+msgid "Search branches..."
+msgstr ""
+
#: src/components/CommandPalette.tsx
msgid "Search by meaning"
msgstr ""
@@ -5454,11 +5610,11 @@ msgid "Search matches file names, paths, and folders. Open a file to search its
msgstr ""
#: src/components/ProjectSwitcher.tsx
-msgid "Search recent projects"
+msgid "Search projects"
msgstr ""
#: src/components/ProjectSwitcher.tsx
-msgid "Search recent projects..."
+msgid "Search projects..."
msgstr ""
#: src/components/settings/SearchSection.tsx
@@ -5469,6 +5625,14 @@ msgstr ""
msgid "Search templates"
msgstr ""
+#: src/components/RecentProjectsMenu.tsx
+msgid "Search worktrees"
+msgstr ""
+
+#: src/components/RecentProjectsMenu.tsx
+msgid "Search worktrees and branches"
+msgstr ""
+
#: src/components/CommandPalette.tsx
msgid "Searching"
msgstr ""
@@ -5773,6 +5937,10 @@ msgstr ""
msgid "Show thumbnails"
msgstr ""
+#: src/components/RecentProjectsMenu.tsx
+msgid "Show worktrees"
+msgstr ""
+
#: src/components/CommandPalette.tsx
msgid "Showing results for \"{semanticResultsLabel}\""
msgstr ""
@@ -6242,6 +6410,10 @@ msgstr ""
msgid "Thanks for subscribing. Watch your inbox for product updates."
msgstr ""
+#: src/components/NewWorktreeDialog.tsx
+msgid "That branch is already open in another worktree."
+msgstr ""
+
#: src/components/ShareReceiveDialog.tsx
msgid "That folder isn't an OpenKnowledge project yet. Initialize it and open?"
msgstr ""
@@ -6438,6 +6610,10 @@ msgstr ""
msgid "This project is running an older version of OpenKnowledge (v{0}) than this app (v{1})."
msgstr ""
+#: src/components/NewWorktreeDialog.tsx
+msgid "This project isn't a git repository, so worktrees aren't available."
+msgstr ""
+
#: src/components/settings/SettingsDialogBody.tsx
msgid "This project lives only on this computer. Connect it to GitHub to back it up and share it with other people."
msgstr ""
@@ -7018,6 +7194,7 @@ msgid "Word wrap"
msgstr ""
#: src/components/McpConsentDialogBody.tsx
+#: src/components/NewWorktreeDialog.tsx
#: src/components/SkillEditorActions.tsx
msgid "Working"
msgstr ""
@@ -7030,6 +7207,19 @@ msgstr ""
msgid "Workspace Command Palette"
msgstr ""
+#. placeholder {0}: basenameOf(project.mainRoot ?? '')
+#: src/components/NavigatorApp.tsx
+msgid "worktree of {0}"
+msgstr ""
+
+#: src/components/CommandPalette.tsx
+msgid "worktree of {worktreeOf}"
+msgstr ""
+
+#: src/components/CommandPalette.tsx
+msgid "Worktrees"
+msgstr ""
+
#: src/components/settings/SettingsDialogBody.tsx
msgid "Wrap long lines in the markdown source editor."
msgstr ""
diff --git a/packages/app/tests/stress/fixtures/handoff-mocks.ts b/packages/app/tests/stress/fixtures/handoff-mocks.ts
index 72380fbee..fb4631794 100644
--- a/packages/app/tests/stress/fixtures/handoff-mocks.ts
+++ b/packages/app/tests/stress/fixtures/handoff-mocks.ts
@@ -269,6 +269,10 @@ export async function installHandoffMocks(page: Page, cfg: HandoffMockConfig): P
}),
close: async () => {},
},
+ worktree: {
+ list: async () => ({ ok: false as const, reason: 'no-git' as const }),
+ create: async () => ({ ok: false as const, reason: 'no-git' as const }),
+ },
sharing: {
status: async () =>
({
diff --git a/packages/core/src/desktop-bridge.ts b/packages/core/src/desktop-bridge.ts
index 9170a46b6..5a5675ffc 100644
--- a/packages/core/src/desktop-bridge.ts
+++ b/packages/core/src/desktop-bridge.ts
@@ -1,6 +1,11 @@
import type { CreateNewBannerKind } from './constants/create-new-banner.ts';
import type { EditorId } from './constants/editors.ts';
import type { OkFolderState } from './constants/folder-state.ts';
+import type {
+ WorktreeCreateRequest,
+ WorktreeCreateResult,
+ WorktreeListResult,
+} from './git/worktree-selector-model.ts';
import type { TerminalCli } from './handoff/terminal-launch.ts';
import type { LocalOpOkInitResponse } from './schemas/api/local-op.ts';
import type { BranchInfoResponse, CheckoutResponse } from './schemas/api/share.ts';
@@ -42,7 +47,9 @@ type OkMenuAction =
| 'toggle-doc-panel'
| 'toggle-terminal'
| 'new-terminal'
- | 'kill-terminal';
+ | 'kill-terminal'
+ | 'new-worktree'
+ | 'switch-worktree';
type OkUnsubscribe = () => void;
@@ -61,7 +68,8 @@ type OkProjectEntryPoint =
| 'recents'
| 'deep-link'
| 'drag-drop'
- | 'share-receive';
+ | 'share-receive'
+ | 'worktree';
interface OkProjectOpenRequest {
path: string;
@@ -601,6 +609,11 @@ export interface OkDesktopBridge {
close(): Promise<void>;
};
+ worktree: {
+ list(): Promise<WorktreeListResult>;
+ create(request: WorktreeCreateRequest): Promise<WorktreeCreateResult>;
+ };
+
sharing: {
status(): Promise<OkSharingStatusResult>;
setMode(mode: 'shared' | 'local-only'): Promise<OkSharingSetModeResult>;
diff --git a/packages/core/src/git/branch-list-parser.test.ts b/packages/core/src/git/branch-list-parser.test.ts
new file mode 100644
index 000000000..6285c3478
--- /dev/null
+++ b/packages/core/src/git/branch-list-parser.test.ts
@@ -0,0 +1,29 @@
+import { describe, expect, test } from 'bun:test';
+import { parseBranchList } from './branch-list-parser.ts';
+
+describe('parseBranchList', () => {
+ test('empty stdout yields empty array', () => {
+ expect(parseBranchList('')).toEqual([]);
+ expect(parseBranchList('\n\n')).toEqual([]);
+ });
+
+ test('parses one branch per line, preserving order', () => {
+ expect(parseBranchList('main\nfeat/foo\nrelease-1\n')).toEqual([
+ 'main',
+ 'feat/foo',
+ 'release-1',
+ ]);
+ });
+
+ test('tolerates missing trailing newline, CRLF, and surrounding whitespace', () => {
+ expect(parseBranchList('main\r\n feat/bar ')).toEqual(['main', 'feat/bar']);
+ });
+
+ test('drops blank lines and de-duplicates', () => {
+ expect(parseBranchList('main\n\nmain\ndev\n')).toEqual(['main', 'dev']);
+ });
+
+ test('keeps slash-namespaced branch names intact', () => {
+ expect(parseBranchList('feat/a/b\nfix/c')).toEqual(['feat/a/b', 'fix/c']);
+ });
+});
diff --git a/packages/core/src/git/branch-list-parser.ts b/packages/core/src/git/branch-list-parser.ts
new file mode 100644
index 000000000..6d2e449f5
--- /dev/null
+++ b/packages/core/src/git/branch-list-parser.ts
@@ -0,0 +1,13 @@
+export function parseBranchList(stdout: string): string[] {
+ if (stdout.length === 0) return [];
+
+ const seen = new Set<string>();
+ const branches: string[] = [];
+ for (const rawLine of stdout.split('\n')) {
+ const branch = rawLine.replace(/\r$/, '').trim();
+ if (branch.length === 0 || seen.has(branch)) continue;
+ seen.add(branch);
+ branches.push(branch);
+ }
+ return branches;
+}
diff --git a/packages/core/src/git/worktree-path.test.ts b/packages/core/src/git/worktree-path.test.ts
new file mode 100644
index 000000000..b292490f7
--- /dev/null
+++ b/packages/core/src/git/worktree-path.test.ts
@@ -0,0 +1,35 @@
+import { describe, expect, test } from 'bun:test';
+import { WORKTREES_PARENT_DIR, worktreeRelativeDir } from './worktree-path.ts';
+
+describe('worktreeRelativeDir', () => {
+ test('places a simple branch under .ok/worktrees/', () => {
+ expect(worktreeRelativeDir('feature-x')).toBe(`${WORKTREES_PARENT_DIR}/feature-x`);
+ });
+
+ test('keeps slash-namespaced branches as nested dirs', () => {
+ expect(worktreeRelativeDir('feat/foo')).toBe(`${WORKTREES_PARENT_DIR}/feat/foo`);
+ });
+
+ test('trims surrounding whitespace', () => {
+ expect(worktreeRelativeDir(' dev ')).toBe(`${WORKTREES_PARENT_DIR}/dev`);
+ });
+
+ test('rejects empty / whitespace-only', () => {
+ expect(worktreeRelativeDir('')).toBeNull();
+ expect(worktreeRelativeDir(' ')).toBeNull();
+ });
+
+ test('rejects path-escape attempts', () => {
+ expect(worktreeRelativeDir('../evil')).toBeNull();
+ expect(worktreeRelativeDir('a/../../b')).toBeNull();
+ expect(worktreeRelativeDir('/abs')).toBeNull();
+ expect(worktreeRelativeDir('trailing/')).toBeNull();
+ expect(worktreeRelativeDir('a//b')).toBeNull();
+ expect(worktreeRelativeDir('.')).toBeNull();
+ });
+
+ test('rejects backslash and NUL', () => {
+ expect(worktreeRelativeDir('a\\b')).toBeNull();
+ expect(worktreeRelativeDir('a\0b')).toBeNull();
+ });
+});
diff --git a/packages/core/src/git/worktree-path.ts b/packages/core/src/git/worktree-path.ts
new file mode 100644
index 000000000..497c31011
--- /dev/null
+++ b/packages/core/src/git/worktree-path.ts
@@ -0,0 +1,13 @@
+export const WORKTREES_PARENT_DIR = '.ok/worktrees';
+
+export function worktreeRelativeDir(branch: string): string | null {
+ const trimmed = branch.trim();
+ if (trimmed.length === 0) return null;
+ if (trimmed.startsWith('/') || trimmed.endsWith('/')) return null;
+ const segments = trimmed.split('/');
+ for (const seg of segments) {
+ if (seg.length === 0 || seg === '.' || seg === '..') return null;
+ if (seg.includes('\\') || seg.includes('\0')) return null;
+ }
+ return `${WORKTREES_PARENT_DIR}/${trimmed}`;
+}
diff --git a/packages/core/src/git/worktree-selector-model.test.ts b/packages/core/src/git/worktree-selector-model.test.ts
new file mode 100644
index 000000000..f6fdfc6b2
--- /dev/null
+++ b/packages/core/src/git/worktree-selector-model.test.ts
@@ -0,0 +1,140 @@
+import { describe, expect, test } from 'bun:test';
+import type { BridgeWorktreeEntry } from './worktree-list-parser.ts';
+import { buildWorktreeSelectorModel } from './worktree-selector-model.ts';
+
+function wt(partial: Partial<BridgeWorktreeEntry> & { path: string }): BridgeWorktreeEntry {
+ return {
+ branch: null,
+ headSha: 'abc123',
+ locked: false,
+ prunable: false,
+ ...partial,
+ };
+}
+
+describe('buildWorktreeSelectorModel', () => {
+ test('main root is the first worktree entry', () => {
+ const model = buildWorktreeSelectorModel({
+ worktrees: [
+ wt({ path: '/repo', branch: 'main' }),
+ wt({ path: '/repo/.ok/worktrees/dev', branch: 'dev' }),
+ ],
+ branches: ['main', 'dev'],
+ currentProjectPath: '/repo',
+ });
+ expect(model.mainRoot).toBe('/repo');
+ });
+
+ test('every local branch yields an entry; worktree-backed branches carry their path', () => {
+ const model = buildWorktreeSelectorModel({
+ worktrees: [
+ wt({ path: '/repo', branch: 'main' }),
+ wt({ path: '/repo/.ok/worktrees/dev', branch: 'dev' }),
+ ],
+ branches: ['main', 'dev', 'feature-x'],
+ currentProjectPath: '/repo',
+ });
+ const byBranch = new Map(model.entries.map((e) => [e.branch, e]));
+ expect(byBranch.get('main')?.worktreePath).toBe('/repo');
+ expect(byBranch.get('dev')?.worktreePath).toBe('/repo/.ok/worktrees/dev');
+ expect(byBranch.get('feature-x')?.worktreePath).toBeNull();
+ });
+
+ test('flags the current window and the main worktree', () => {
+ const model = buildWorktreeSelectorModel({
+ worktrees: [
+ wt({ path: '/repo', branch: 'main' }),
+ wt({ path: '/repo/.ok/worktrees/dev', branch: 'dev' }),
+ ],
+ branches: ['main', 'dev'],
+ currentProjectPath: '/repo/.ok/worktrees/dev',
+ });
+ const main = model.entries.find((e) => e.branch === 'main');
+ const dev = model.entries.find((e) => e.branch === 'dev');
+ expect(main?.isMain).toBe(true);
+ expect(main?.isCurrent).toBe(false);
+ expect(dev?.isCurrent).toBe(true);
+ expect(dev?.isMain).toBe(false);
+ expect(model.currentBranch).toBe('dev');
+ });
+
+ test('orders current first, then main, then worktree-backed, then plain branches', () => {
+ const model = buildWorktreeSelectorModel({
+ worktrees: [
+ wt({ path: '/repo', branch: 'main' }),
+ wt({ path: '/repo/.ok/worktrees/zeta', branch: 'zeta' }),
+ ],
+ branches: ['main', 'zeta', 'alpha', 'beta'],
+ currentProjectPath: '/repo/.ok/worktrees/zeta',
+ });
+ expect(model.entries.map((e) => e.branch)).toEqual(['zeta', 'main', 'alpha', 'beta']);
+ });
+
+ test('ignores prunable worktrees', () => {
+ const model = buildWorktreeSelectorModel({
+ worktrees: [
+ wt({ path: '/repo', branch: 'main' }),
+ wt({ path: '/gone', branch: 'ghost', prunable: true }),
+ ],
+ branches: ['main', 'ghost'],
+ currentProjectPath: '/repo',
+ });
+ expect(model.entries.find((e) => e.branch === 'ghost')?.worktreePath).toBeNull();
+ });
+
+ test('includes a detached-HEAD worktree not present in the branch list', () => {
+ const model = buildWorktreeSelectorModel({
+ worktrees: [
+ wt({ path: '/repo', branch: 'main' }),
+ wt({ path: '/repo/.ok/worktrees/detached', branch: null }),
+ ],
+ branches: ['main'],
+ currentProjectPath: '/repo/.ok/worktrees/detached',
+ });
+ const detached = model.entries.find((e) => e.worktreePath === '/repo/.ok/worktrees/detached');
+ expect(detached?.branch).toBeNull();
+ expect(detached?.isCurrent).toBe(true);
+ });
+
+ test('falls back to currentProjectPath as mainRoot when no worktrees reported', () => {
+ const model = buildWorktreeSelectorModel({
+ worktrees: [],
+ branches: ['main'],
+ currentProjectPath: '/repo',
+ });
+ expect(model.mainRoot).toBe('/repo');
+ });
+
+ test('remoteBranches defaults to [] when the caller supplies none', () => {
+ const model = buildWorktreeSelectorModel({
+ worktrees: [wt({ path: '/repo', branch: 'main' })],
+ branches: ['main'],
+ currentProjectPath: '/repo',
+ });
+ expect(model.remoteBranches).toEqual([]);
+ });
+
+ test('remoteBranches keeps the full remote ref list (incl. refs with a matching local branch) deduped + ordered', () => {
+ const model = buildWorktreeSelectorModel({
+ worktrees: [wt({ path: '/repo', branch: 'main' })],
+ branches: ['main', 'dev'],
+ currentProjectPath: '/repo',
+ remoteBranches: ['origin/main', 'origin/dev', 'origin/feature-x', 'origin/feature-x'],
+ });
+ expect(model.remoteBranches).toEqual(['origin/main', 'origin/dev', 'origin/feature-x']);
+ });
+
+ test('per-branch behind counts thread onto the matching entry; unknown branches carry no behind field', () => {
+ const model = buildWorktreeSelectorModel({
+ worktrees: [wt({ path: '/repo', branch: 'main' })],
+ branches: ['main', 'dev', 'no-upstream'],
+ currentProjectPath: '/repo',
+ behind: { main: 3, dev: 0 },
+ });
+ const byBranch = new Map(model.entries.map((e) => [e.branch, e]));
+ expect(byBranch.get('main')?.behind).toBe(3);
+ expect(byBranch.get('dev')?.behind).toBe(0);
+ expect(byBranch.get('no-upstream')?.behind).toBeUndefined();
+ expect('behind' in (byBranch.get('no-upstream') ?? {})).toBe(false);
+ });
+});
diff --git a/packages/core/src/git/worktree-selector-model.ts b/packages/core/src/git/worktree-selector-model.ts
new file mode 100644
index 000000000..ef1007f2a
--- /dev/null
+++ b/packages/core/src/git/worktree-selector-model.ts
@@ -0,0 +1,130 @@
+import type { BridgeWorktreeEntry } from './worktree-list-parser.ts';
+
+export interface WorktreeSelectorEntry {
+ readonly branch: string | null;
+ readonly worktreePath: string | null;
+ readonly isCurrent: boolean;
+ readonly isMain: boolean;
+ readonly locked: boolean;
+ readonly behind?: number;
+}
+
+export interface WorktreeSelectorModel {
+ readonly mainRoot: string;
+ readonly currentBranch: string | null;
+ readonly entries: readonly WorktreeSelectorEntry[];
+ readonly remoteBranches: readonly string[];
+}
+
+export type WorktreeListResult =
+ | { readonly ok: true; readonly model: WorktreeSelectorModel }
+ | { readonly ok: false; readonly reason: 'no-git' };
+
+export interface WorktreeCreateRequest {
+ readonly branch: string;
+ readonly baseBranch?: string | null;
+ readonly baseRef?: string | null;
+ readonly remoteRef?: string | null;
+ readonly createBranch: boolean;
+}
+
+export type WorktreeCreateResult =
+ | { readonly ok: true; readonly path: string; readonly created: boolean }
+ | {
+ readonly ok: false;
+ readonly reason:
+ | 'invalid-branch'
+ | 'branch-exists'
+ | 'already-checked-out'
+ | 'path-exists'
+ | 'no-git'
+ | 'error';
+ readonly message?: string;
+ };
+
+export interface BuildWorktreeSelectorModelInput {
+ readonly worktrees: readonly BridgeWorktreeEntry[];
+ readonly branches: readonly string[];
+ readonly currentProjectPath: string;
+ readonly remoteBranches?: readonly string[];
+ readonly behind?: Readonly<Record<string, number>>;
+}
+
+export function buildWorktreeSelectorModel(
+ input: BuildWorktreeSelectorModelInput,
+): WorktreeSelectorModel {
+ const liveWorktrees = input.worktrees.filter((w) => !w.prunable);
+ const mainRoot = liveWorktrees[0]?.path ?? input.currentProjectPath;
+
+ const behind = input.behind ?? {};
+ const remoteBranches: string[] = [];
+ const seenRemote = new Set<string>();
+ for (const ref of input.remoteBranches ?? []) {
+ if (ref.length === 0 || seenRemote.has(ref)) continue;
+ seenRemote.add(ref);
+ remoteBranches.push(ref);
+ }
+
+ const worktreeByBranch = new Map<string, BridgeWorktreeEntry>();
+ for (const w of liveWorktrees) {
+ if (w.branch !== null && !worktreeByBranch.has(w.branch)) {
+ worktreeByBranch.set(w.branch, w);
+ }
+ }
+
+ const isCurrentPath = (p: string): boolean => p === input.currentProjectPath;
+
+ const entries: WorktreeSelectorEntry[] = [];
+
+ for (const branch of input.branches) {
+ const wt = worktreeByBranch.get(branch) ?? null;
+ const behindCount = behind[branch];
+ entries.push({
+ branch,
+ worktreePath: wt?.path ?? null,
+ isCurrent: wt !== null && isCurrentPath(wt.path),
+ isMain: wt !== null && wt.path === mainRoot,
+ locked: wt?.locked ?? false,
+ ...(behindCount !== undefined ? { behind: behindCount } : {}),
+ });
+ }
+
+ const branchPaths = new Set(
+ entries.map((e) => e.worktreePath).filter((p): p is string => p !== null),
+ );
+ for (const w of liveWorktrees) {
+ if (w.branch === null && !branchPaths.has(w.path)) {
+ entries.push({
+ branch: null,
+ worktreePath: w.path,
+ isCurrent: isCurrentPath(w.path),
+ isMain: w.path === mainRoot,
+ locked: w.locked,
+ });
+ }
+ }
+
+ const currentBranch = entries.find((e) => e.isCurrent)?.branch ?? null;
+
+ entries.sort(compareEntries);
+
+ return { mainRoot, currentBranch, entries, remoteBranches };
+}
+
+export function stripRemotePrefix(ref: string): string {
+ const slash = ref.indexOf('/');
+ return slash === -1 ? ref : ref.slice(slash + 1);
+}
+
+function compareEntries(a: WorktreeSelectorEntry, b: WorktreeSelectorEntry): number {
+ const rank = (e: WorktreeSelectorEntry): number => {
+ if (e.isCurrent) return 0;
+ if (e.isMain) return 1;
+ if (e.worktreePath !== null) return 2;
+ return 3;
+ };
+ const ra = rank(a);
+ const rb = rank(b);
+ if (ra !== rb) return ra - rb;
+ return (a.branch ?? '').localeCompare(b.branch ?? '');
+}
diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts
index f00e3c2a5..5414c5482 100644
--- a/packages/core/src/index.ts
+++ b/packages/core/src/index.ts
@@ -366,10 +366,22 @@ export {
serializeFrontmatterMap,
withFences,
} from './frontmatter/yaml-codec.ts';
+export { parseBranchList } from './git/branch-list-parser.ts';
export {
type BridgeWorktreeEntry,
parseWorktreeListPorcelain,
} from './git/worktree-list-parser.ts';
+export { WORKTREES_PARENT_DIR, worktreeRelativeDir } from './git/worktree-path.ts';
+export {
+ type BuildWorktreeSelectorModelInput,
+ buildWorktreeSelectorModel,
+ stripRemotePrefix,
+ type WorktreeCreateRequest,
+ type WorktreeCreateResult,
+ type WorktreeListResult,
+ type WorktreeSelectorEntry,
+ type WorktreeSelectorModel,
+} from './git/worktree-selector-model.ts';
export {
type AssembleHandoffPromptInput,
assembleHandoffPrompt,
diff --git a/packages/core/src/sharing/receive-flow.ts b/packages/core/src/sharing/receive-flow.ts
index 710d0df5b..13e843bd0 100644
--- a/packages/core/src/sharing/receive-flow.ts
+++ b/packages/core/src/sharing/receive-flow.ts
@@ -17,6 +17,10 @@ export interface RecentProjectEntry {
lastOpenedAt: string;
missing?: boolean;
gitRemoteUrl?: string;
+ gitCommonDir?: string;
+ mainRoot?: string;
+ isLinkedWorktree?: boolean;
+ branch?: string | null;
}
export interface ExpectedShareRepo {
diff --git a/packages/desktop/src/main/index.ts b/packages/desktop/src/main/index.ts
index 9fc3c87ec..5b8113b5b 100644
--- a/packages/desktop/src/main/index.ts
+++ b/packages/desktop/src/main/index.ts
@@ -264,6 +264,12 @@ import {
WindowManager,
} from './window-manager.ts';
import { WINDOW_MIN_SIZE } from './window-min-size.ts';
+import {
+ classifyRecentGit,
+ classifyRecentGitAsync,
+ readWorktreeBranchAsync,
+} from './worktree-recents.ts';
+import { createWorktree, listWorktreeSelector } from './worktree-service.ts';
const VIBRANCY_DEFAULT: VibrancyMaterial = 'sidebar';
@@ -1164,6 +1170,10 @@ async function openProject(
tryCloseNavigator(navigatorWindow, { projectPath });
const gitRemoteUrl = readCanonicalGitHubRemoteUrl(resolvedProjectDir) ?? undefined;
appState = addRecentProject(appState, resolvedProjectDir, ctx.projectName, gitRemoteUrl);
+ if (entryPoint === 'worktree') {
+ const mainRoot = classifyRecentGit(resolvedProjectDir).mainRoot;
+ if (mainRoot !== null) appState = { ...appState, lastOpenedProject: mainRoot };
+ }
saveAppState(appState);
refreshApplicationMenu();
}
@@ -1363,6 +1373,8 @@ async function runApplicationMenuRefresh(): Promise<void> {
onNewFolder: () => sendMenuActionToFocused('new-folder'),
onNewFromTemplate: () => sendMenuActionToFocused('new-from-template'),
onNewProject: () => sendMenuActionToFocused('new-project'),
+ onNewWorktree: () => sendMenuActionToFocused('new-worktree'),
+ onSwitchWorktree: () => sendMenuActionToFocused('switch-worktree'),
onRename: () => sendMenuActionToFocused('rename'),
onDuplicate: () => sendMenuActionToFocused('duplicate'),
onMoveToTrash: () => sendMenuActionToFocused('move-to-trash'),
@@ -2120,7 +2132,23 @@ function registerIpcHandlers() {
});
handle('ok:project:list-recent', async () => {
- return annotateMissing(appState) as RecentProject[];
+ return Promise.all(
+ annotateMissing(appState).map(async (entry): Promise<RecentProject> => {
+ if (entry.missing) return entry;
+ const [git, branch] = await Promise.all([
+ classifyRecentGitAsync(entry.path),
+ readWorktreeBranchAsync(entry.path),
+ ]);
+ if (git.gitCommonDir === null) return entry;
+ return {
+ ...entry,
+ gitCommonDir: git.gitCommonDir,
+ mainRoot: git.mainRoot ?? undefined,
+ isLinkedWorktree: git.isLinkedWorktree,
+ branch,
+ };
+ }),
+ );
});
handle('ok:project:remove-recent', async (_event, projectPath) => {
@@ -2210,6 +2238,39 @@ function registerIpcHandlers() {
return undefined;
});
+ handle('ok:worktree:dispatch', async (event, request) => {
+ const win = BrowserWindow.fromWebContents(event.sender);
+ const ctx =
+ win && wm ? wm.getContextForBrowserWindow(win as unknown as BrowserWindowLike) : null;
+ const projectPath = ctx?.projectPath ?? null;
+ if (!projectPath) {
+ logIpcError({
+ event: 'ipc.error',
+ channel: 'ok:worktree:dispatch',
+ reason: 'no-git',
+ handler: 'worktreeDispatch',
+ });
+ return { ok: false, reason: 'no-git' };
+ }
+ let anchor: string;
+ try {
+ anchor = realpathSync(projectPath);
+ } catch {
+ anchor = projectPath;
+ }
+ if (request.kind === 'list') {
+ return listWorktreeSelector(anchor, anchor);
+ }
+ return createWorktree({
+ anchorPath: anchor,
+ branch: request.branch,
+ baseBranch: request.baseBranch,
+ baseRef: request.baseRef,
+ remoteRef: request.remoteRef,
+ createBranch: request.createBranch,
+ });
+ });
+
handle('ok:share:validate-folder', async (_event, request) => {
return validateLocalFolderForShare(request.folderPath, {
owner: request.owner,
diff --git a/packages/desktop/src/main/menu.ts b/packages/desktop/src/main/menu.ts
index 7842c2e09..1329524d4 100644
--- a/packages/desktop/src/main/menu.ts
+++ b/packages/desktop/src/main/menu.ts
@@ -26,6 +26,8 @@ export interface MenuDeps {
onNewFolder?(): void;
onNewFromTemplate?(): void;
onNewProject?(): void;
+ onNewWorktree?(): void;
+ onSwitchWorktree?(): void;
onRename?(): void;
onDuplicate?(): void;
onMoveToTrash?(): void;
@@ -162,6 +164,17 @@ export function buildMenuTemplate(deps: MenuDeps): MenuItemConstructorOptions[]
},
},
{ type: 'separator' },
+ {
+ label: 'New worktree…',
+ enabled: deps.onNewWorktree !== undefined,
+ click: () => deps.onNewWorktree?.(),
+ },
+ {
+ label: 'Switch worktree…',
+ enabled: deps.onSwitchWorktree !== undefined,
+ click: () => deps.onSwitchWorktree?.(),
+ },
+ { type: 'separator' },
{
label: MENU_LABELS.duplicate,
accelerator: 'CmdOrCtrl+D',
diff --git a/packages/desktop/src/main/worktree-autosync-inherit.test.ts b/packages/desktop/src/main/worktree-autosync-inherit.test.ts
new file mode 100644
index 000000000..164e0408e
--- /dev/null
+++ b/packages/desktop/src/main/worktree-autosync-inherit.test.ts
@@ -0,0 +1,69 @@
+import { afterEach, describe, expect, test } from 'bun:test';
+import { existsSync, mkdtempSync, readFileSync, realpathSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { basename, join } from 'node:path';
+import { resolveConfigPath, writeConfigPatch } from '@inkeep/open-knowledge-core/server';
+import { parse as parseYaml } from 'yaml';
+import { resolveRootAutoSync, seedWorktreeAutoSync } from './worktree-autosync-inherit.ts';
+
+const dirs: string[] = [];
+function tmp(): string {
+ const d = realpathSync(mkdtempSync(join(tmpdir(), 'wt-autosync-')));
+ dirs.push(d);
+ return d;
+}
+afterEach(() => {
+ for (const d of dirs) rmSync(d, { recursive: true, force: true });
+ dirs.length = 0;
+});
+
+describe('resolveRootAutoSync', () => {
+ test('per-machine enabled wins over the committed default', async () => {
+ const root = tmp();
+ await writeConfigPatch({
+ cwd: root,
+ scope: 'project-local',
+ patch: { autoSync: { enabled: true } },
+ });
+ await writeConfigPatch({
+ cwd: root,
+ scope: 'project',
+ patch: { autoSync: { default: false } },
+ });
+ expect(resolveRootAutoSync(root)).toBe(true);
+ });
+
+ test('falls back to the committed default when per-machine is unset', async () => {
+ const root = tmp();
+ await writeConfigPatch({ cwd: root, scope: 'project', patch: { autoSync: { default: true } } });
+ expect(resolveRootAutoSync(root)).toBe(true);
+ });
+
+ test('null when neither is answered', () => {
+ expect(resolveRootAutoSync(tmp())).toBeNull();
+ });
+});
+
+describe('seedWorktreeAutoSync', () => {
+ test('seeds the worktree enabled + arms the one-time notice from the root setting', async () => {
+ const root = tmp();
+ const wt = tmp();
+ await writeConfigPatch({
+ cwd: root,
+ scope: 'project-local',
+ patch: { autoSync: { enabled: false } },
+ });
+ await seedWorktreeAutoSync(wt, root);
+ const parsed = parseYaml(readFileSync(resolveConfigPath('project-local', wt), 'utf-8'));
+ expect(parsed.autoSync.enabled).toBe(false);
+ expect(parsed.autoSync.inheritedNoticePending).toBe(true);
+ expect(parsed.autoSync.inheritedFrom).toBe(basename(root));
+ });
+
+ test('no-op when the root is unanswered — the worktree prompts normally', async () => {
+ const root = tmp();
+ const wt = tmp();
+ await seedWorktreeAutoSync(wt, root);
+ expect(existsSync(resolveConfigPath('project-local', wt))).toBe(false);
+ });
+});
diff --git a/packages/desktop/src/main/worktree-autosync-inherit.ts b/packages/desktop/src/main/worktree-autosync-inherit.ts
new file mode 100644
index 000000000..169e9b9a9
--- /dev/null
+++ b/packages/desktop/src/main/worktree-autosync-inherit.ts
@@ -0,0 +1,52 @@
+import { existsSync, readFileSync } from 'node:fs';
+import { basename } from 'node:path';
+import { resolveConfigPath, writeConfigPatch } from '@inkeep/open-knowledge-core/server';
+import { parse as parseYaml } from 'yaml';
+import { getLogger } from './desktop-logger.ts';
+
+function isObject(v: unknown): v is Record<string, unknown> {
+ return typeof v === 'object' && v !== null && !Array.isArray(v);
+}
+
+function readAutoSyncBool(path: string, key: 'enabled' | 'default'): boolean | null {
+ if (!existsSync(path)) return null;
+ let parsed: unknown;
+ try {
+ parsed = parseYaml(readFileSync(path, 'utf-8'));
+ } catch {
+ return null;
+ }
+ if (!isObject(parsed)) return null;
+ const autoSync = parsed.autoSync;
+ if (!isObject(autoSync)) return null;
+ const value = autoSync[key];
+ return typeof value === 'boolean' ? value : null;
+}
+
+export function resolveRootAutoSync(mainRoot: string): boolean | null {
+ const enabled = readAutoSyncBool(resolveConfigPath('project-local', mainRoot), 'enabled');
+ if (enabled !== null) return enabled;
+ return readAutoSyncBool(resolveConfigPath('project', mainRoot), 'default');
+}
+
+export async function seedWorktreeAutoSync(worktreePath: string, mainRoot: string): Promise<void> {
+ const inherited = resolveRootAutoSync(mainRoot);
+ if (inherited === null) return;
+ const result = await writeConfigPatch({
+ cwd: worktreePath,
+ scope: 'project-local',
+ patch: {
+ autoSync: {
+ enabled: inherited,
+ inheritedNoticePending: true,
+ inheritedFrom: basename(mainRoot),
+ },
+ },
+ });
+ if (!result.ok) {
+ getLogger('worktree-autosync').warn(
+ { worktreePath, reason: result.error.code },
+ 'failed to seed inherited autoSync.enabled',
+ );
+ }
+}
diff --git a/packages/desktop/src/main/worktree-recents.test.ts b/packages/desktop/src/main/worktree-recents.test.ts
new file mode 100644
index 000000000..798da7a63
--- /dev/null
+++ b/packages/desktop/src/main/worktree-recents.test.ts
@@ -0,0 +1,261 @@
+import { afterEach, beforeEach, describe, expect, test } from 'bun:test';
+import { execFile } from 'node:child_process';
+import { mkdirSync, mkdtempSync, realpathSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { promisify } from 'node:util';
+import {
+ classifyRecentGit,
+ classifyRecentGitAsync,
+ clearRecentGitCache,
+ readWorktreeBranch,
+ readWorktreeBranchAsync,
+} from './worktree-recents.ts';
+
+const execFileAsync = promisify(execFile);
+const GIT_ENV = { ...process.env, LANG: 'C', LC_ALL: 'C', GIT_CONFIG_GLOBAL: '/dev/null' };
+
+async function git(cwd: string, ...args: string[]): Promise<void> {
+ await execFileAsync('git', args, { cwd, env: GIT_ENV });
+}
+
+interface Handle {
+ readonly root: string;
+ readonly mainRepo: string;
+ readonly worktree: string;
+ cleanup(): void;
+}
+
+async function makeRepoWithWorktree(): Promise<Handle> {
+ const root = realpathSync(mkdtempSync(join(tmpdir(), 'wt-recents-test-')));
+ const mainRepo = join(root, 'main');
+ mkdirSync(mainRepo);
+ await git(mainRepo, 'init', '--initial-branch=main', '.');
+ await git(mainRepo, 'config', 'user.email', '[email protected]');
+ await git(mainRepo, 'config', 'user.name', 'Test');
+ writeFileSync(join(mainRepo, 'README.md'), '# main\n');
+ await git(mainRepo, 'add', '-A');
+ await git(mainRepo, 'commit', '-m', 'initial');
+ const worktree = join(root, 'wt', 'feature');
+ mkdirSync(join(root, 'wt'), { recursive: true });
+ await git(mainRepo, 'worktree', 'add', '-b', 'feature', worktree);
+ return {
+ root,
+ mainRepo,
+ worktree,
+ cleanup: () => rmSync(root, { recursive: true, force: true }),
+ };
+}
+
+describe('classifyRecentGit', () => {
+ let handle: Handle | null = null;
+ beforeEach(() => clearRecentGitCache());
+ afterEach(() => {
+ handle?.cleanup();
+ handle = null;
+ });
+
+ test('main worktree: same repo, not linked', async () => {
+ handle = await makeRepoWithWorktree();
+ const info = classifyRecentGit(handle.mainRepo);
+ expect(info.gitCommonDir).toBe(join(handle.mainRepo, '.git'));
+ expect(info.mainRoot).toBe(handle.mainRepo);
+ expect(info.isLinkedWorktree).toBe(false);
+ });
+
+ test('linked worktree: shares the main repo common-dir + main root, flagged linked', async () => {
+ handle = await makeRepoWithWorktree();
+ const info = classifyRecentGit(handle.worktree);
+ expect(info.gitCommonDir).toBe(join(handle.mainRepo, '.git'));
+ expect(info.mainRoot).toBe(handle.mainRepo);
+ expect(info.isLinkedWorktree).toBe(true);
+ });
+
+ test('main + linked worktree share the same gitCommonDir (grouping key)', async () => {
+ handle = await makeRepoWithWorktree();
+ const main = classifyRecentGit(handle.mainRepo);
+ const linked = classifyRecentGit(handle.worktree);
+ expect(main.gitCommonDir).toBe(linked.gitCommonDir);
+ });
+
+ test('non-git dir → empty classification', () => {
+ const tmp = realpathSync(mkdtempSync(join(tmpdir(), 'wt-recents-nogit-')));
+ try {
+ const info = classifyRecentGit(tmp);
+ expect(info.gitCommonDir).toBeNull();
+ expect(info.mainRoot).toBeNull();
+ expect(info.isLinkedWorktree).toBe(false);
+ } finally {
+ rmSync(tmp, { recursive: true, force: true });
+ }
+ });
+
+ test('non-absolute path → empty', () => {
+ expect(classifyRecentGit('relative/path').gitCommonDir).toBeNull();
+ });
+
+ test('result is memoized per path (cache hit after clear + recompute)', async () => {
+ handle = await makeRepoWithWorktree();
+ const first = classifyRecentGit(handle.mainRepo);
+ const second = classifyRecentGit(handle.mainRepo);
+ expect(first).toBe(second);
+ });
+});
+
+describe('readWorktreeBranch', () => {
+ let handle: Handle | null = null;
+ afterEach(() => {
+ handle?.cleanup();
+ handle = null;
+ });
+
+ test('main worktree returns its branch', async () => {
+ handle = await makeRepoWithWorktree();
+ expect(readWorktreeBranch(handle.mainRepo)).toBe('main');
+ });
+
+ test('linked worktree returns its branch', async () => {
+ handle = await makeRepoWithWorktree();
+ expect(readWorktreeBranch(handle.worktree)).toBe('feature');
+ });
+
+ test('resolves up from a SUBDIRECTORY of a worktree (the OK-subtree case)', async () => {
+ handle = await makeRepoWithWorktree();
+ const subdir = join(handle.worktree, 'public', 'open-knowledge');
+ mkdirSync(subdir, { recursive: true });
+ expect(readWorktreeBranch(subdir)).toBe('feature');
+ });
+
+ test('detached HEAD → null', async () => {
+ handle = await makeRepoWithWorktree();
+ await git(handle.worktree, 'checkout', '--detach', 'HEAD');
+ expect(readWorktreeBranch(handle.worktree)).toBeNull();
+ });
+
+ test('non-git dir → null', () => {
+ const tmp = realpathSync(mkdtempSync(join(tmpdir(), 'wt-branch-nogit-')));
+ try {
+ expect(readWorktreeBranch(tmp)).toBeNull();
+ } finally {
+ rmSync(tmp, { recursive: true, force: true });
+ }
+ });
+
+ test('non-absolute path → null', () => {
+ expect(readWorktreeBranch('relative/path')).toBeNull();
+ });
+});
+
+describe('classifyRecentGitAsync', () => {
+ let handle: Handle | null = null;
+ beforeEach(() => clearRecentGitCache());
+ afterEach(() => {
+ handle?.cleanup();
+ handle = null;
+ });
+
+ test('main worktree: same repo, not linked', async () => {
+ handle = await makeRepoWithWorktree();
+ const info = await classifyRecentGitAsync(handle.mainRepo);
+ expect(info.gitCommonDir).toBe(join(handle.mainRepo, '.git'));
+ expect(info.mainRoot).toBe(handle.mainRepo);
+ expect(info.isLinkedWorktree).toBe(false);
+ });
+
+ test('linked worktree: shares common-dir + main root, flagged linked', async () => {
+ handle = await makeRepoWithWorktree();
+ const info = await classifyRecentGitAsync(handle.worktree);
+ expect(info.gitCommonDir).toBe(join(handle.mainRepo, '.git'));
+ expect(info.mainRoot).toBe(handle.mainRepo);
+ expect(info.isLinkedWorktree).toBe(true);
+ });
+
+ test('non-git dir → empty classification', async () => {
+ const tmp = realpathSync(mkdtempSync(join(tmpdir(), 'wt-recents-async-nogit-')));
+ try {
+ const info = await classifyRecentGitAsync(tmp);
+ expect(info.gitCommonDir).toBeNull();
+ expect(info.mainRoot).toBeNull();
+ expect(info.isLinkedWorktree).toBe(false);
+ } finally {
+ rmSync(tmp, { recursive: true, force: true });
+ }
+ });
+
+ test('non-absolute path → empty', async () => {
+ expect((await classifyRecentGitAsync('relative/path')).gitCommonDir).toBeNull();
+ });
+
+ test('matches the sync variant for the same path', async () => {
+ handle = await makeRepoWithWorktree();
+ const sync = classifyRecentGit(handle.worktree);
+ clearRecentGitCache();
+ const async = await classifyRecentGitAsync(handle.worktree);
+ expect(async).toEqual(sync);
+ });
+
+ test('shares the memo with the sync variant (sync populate → async cache hit)', async () => {
+ handle = await makeRepoWithWorktree();
+ const seeded = classifyRecentGit(handle.mainRepo);
+ const fromAsync = await classifyRecentGitAsync(handle.mainRepo);
+ expect(fromAsync).toBe(seeded);
+ });
+
+ test('result is memoized across async calls (same object identity)', async () => {
+ handle = await makeRepoWithWorktree();
+ const first = await classifyRecentGitAsync(handle.mainRepo);
+ const second = await classifyRecentGitAsync(handle.mainRepo);
+ expect(first).toBe(second);
+ });
+});
+
+describe('readWorktreeBranchAsync', () => {
+ let handle: Handle | null = null;
+ afterEach(() => {
+ handle?.cleanup();
+ handle = null;
+ });
+
+ test('main worktree returns its branch', async () => {
+ handle = await makeRepoWithWorktree();
+ expect(await readWorktreeBranchAsync(handle.mainRepo)).toBe('main');
+ });
+
+ test('linked worktree returns its branch', async () => {
+ handle = await makeRepoWithWorktree();
+ expect(await readWorktreeBranchAsync(handle.worktree)).toBe('feature');
+ });
+
+ test('resolves up from a SUBDIRECTORY of a worktree (the OK-subtree case)', async () => {
+ handle = await makeRepoWithWorktree();
+ const subdir = join(handle.worktree, 'public', 'open-knowledge');
+ mkdirSync(subdir, { recursive: true });
+ expect(await readWorktreeBranchAsync(subdir)).toBe('feature');
+ });
+
+ test('detached HEAD → null', async () => {
+ handle = await makeRepoWithWorktree();
+ await git(handle.worktree, 'checkout', '--detach', 'HEAD');
+ expect(await readWorktreeBranchAsync(handle.worktree)).toBeNull();
+ });
+
+ test('non-git dir → null', async () => {
+ const tmp = realpathSync(mkdtempSync(join(tmpdir(), 'wt-branch-async-nogit-')));
+ try {
+ expect(await readWorktreeBranchAsync(tmp)).toBeNull();
+ } finally {
+ rmSync(tmp, { recursive: true, force: true });
+ }
+ });
+
+ test('non-absolute path → null', async () => {
+ expect(await readWorktreeBranchAsync('relative/path')).toBeNull();
+ });
+
+ test('matches the sync variant for the same path', async () => {
+ handle = await makeRepoWithWorktree();
+ expect(await readWorktreeBranchAsync(handle.worktree)).toBe(
+ readWorktreeBranch(handle.worktree),
+ );
+ });
+});
diff --git a/packages/desktop/src/main/worktree-recents.ts b/packages/desktop/src/main/worktree-recents.ts
new file mode 100644
index 000000000..838cd3377
--- /dev/null
+++ b/packages/desktop/src/main/worktree-recents.ts
@@ -0,0 +1,139 @@
+import { execFile, execFileSync } from 'node:child_process';
+import { realpathSync } from 'node:fs';
+import { basename, dirname, isAbsolute, resolve } from 'node:path';
+import { promisify } from 'node:util';
+
+const GIT_ENV = { ...process.env, LANG: 'C', LC_ALL: 'C' } as const;
+
+const execFileAsync = promisify(execFile);
+
+export interface RecentGitInfo {
+ readonly gitCommonDir: string | null;
+ readonly mainRoot: string | null;
+ readonly isLinkedWorktree: boolean;
+}
+
+const EMPTY: RecentGitInfo = { gitCommonDir: null, mainRoot: null, isLinkedWorktree: false };
+
+const cache = new Map<string, RecentGitInfo>();
+
+export function clearRecentGitCache(): void {
+ cache.clear();
+}
+
+export function readWorktreeBranch(projectPath: string): string | null {
+ if (!isAbsolute(projectPath)) return null;
+ try {
+ const out = String(
+ execFileSync('git', ['symbolic-ref', '--quiet', '--short', 'HEAD'], {
+ cwd: projectPath,
+ env: GIT_ENV,
+ }),
+ ).trim();
+ return out.length > 0 ? out : null;
+ } catch {
+ return null;
+ }
+}
+
+export async function readWorktreeBranchAsync(projectPath: string): Promise<string | null> {
+ if (!isAbsolute(projectPath)) return null;
+ try {
+ const { stdout } = await execFileAsync('git', ['symbolic-ref', '--quiet', '--short', 'HEAD'], {
+ cwd: projectPath,
+ env: GIT_ENV,
+ });
+ const out = stdout.trim();
+ return out.length > 0 ? out : null;
+ } catch {
+ return null;
+ }
+}
+
+export function classifyRecentGit(projectPath: string): RecentGitInfo {
+ if (!isAbsolute(projectPath)) return EMPTY;
+ let key: string;
+ try {
+ key = realpathSync(projectPath);
+ } catch {
+ return EMPTY;
+ }
+ const cached = cache.get(key);
+ if (cached !== undefined) return cached;
+
+ const info = computeRecentGit(key);
+ cache.set(key, info);
+ return info;
+}
+
+export async function classifyRecentGitAsync(projectPath: string): Promise<RecentGitInfo> {
+ if (!isAbsolute(projectPath)) return EMPTY;
+ let key: string;
+ try {
+ key = realpathSync(projectPath);
+ } catch {
+ return EMPTY;
+ }
+ const cached = cache.get(key);
+ if (cached !== undefined) return cached;
+
+ const info = await computeRecentGitAsync(key);
+ cache.set(key, info);
+ return info;
+}
+
+const REV_PARSE_ARGS = [
+ 'rev-parse',
+ '--path-format=absolute',
+ '--show-toplevel',
+ '--git-common-dir',
+] as const;
+
+function computeRecentGit(realPath: string): RecentGitInfo {
+ let out: string;
+ try {
+ out = String(execFileSync('git', [...REV_PARSE_ARGS], { cwd: realPath, env: GIT_ENV }));
+ } catch {
+ return EMPTY;
+ }
+ return parseRevParse(out);
+}
+
+async function computeRecentGitAsync(realPath: string): Promise<RecentGitInfo> {
+ let out: string;
+ try {
+ const { stdout } = await execFileAsync('git', [...REV_PARSE_ARGS], {
+ cwd: realPath,
+ env: GIT_ENV,
+ });
+ out = stdout;
+ } catch {
+ return EMPTY;
+ }
+ return parseRevParse(out);
+}
+
+function parseRevParse(out: string): RecentGitInfo {
+ const [topLevelRaw, commonDirRaw] = out.split('\n');
+ const topLevel = topLevelRaw?.trim();
+ const commonDir = commonDirRaw?.trim();
+ if (!topLevel || !commonDir) return EMPTY;
+
+ const mainRoot = basename(commonDir) === '.git' ? dirname(commonDir) : topLevel;
+ const isLinkedWorktree = realpathEq(topLevel, mainRoot) === false;
+ return { gitCommonDir: commonDir, mainRoot, isLinkedWorktree };
+}
+
+function realpathEq(a: string, b: string): boolean {
+ const ra = safeRealpath(a);
+ const rb = safeRealpath(b);
+ return resolve(ra) === resolve(rb);
+}
+
+function safeRealpath(p: string): string {
+ try {
+ return realpathSync(p);
+ } catch {
+ return p;
+ }
+}
diff --git a/packages/desktop/src/main/worktree-service.test.ts b/packages/desktop/src/main/worktree-service.test.ts
new file mode 100644
index 000000000..11f7ca6eb
--- /dev/null
+++ b/packages/desktop/src/main/worktree-service.test.ts
@@ -0,0 +1,391 @@
+import { afterEach, describe, expect, test } from 'bun:test';
+import { execFile } from 'node:child_process';
+import { existsSync, mkdirSync, mkdtempSync, realpathSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { promisify } from 'node:util';
+import { clearRecentGitCache } from './worktree-recents.ts';
+import { createWorktree, listWorktreeSelector } from './worktree-service.ts';
+
+const execFileAsync = promisify(execFile);
+const GIT_ENV = { ...process.env, LANG: 'C', LC_ALL: 'C', GIT_CONFIG_GLOBAL: '/dev/null' };
+
+async function git(cwd: string, ...args: string[]): Promise<string> {
+ const { stdout } = await execFileAsync('git', args, { cwd, env: GIT_ENV });
+ return String(stdout);
+}
+
+interface Handle {
+ readonly root: string;
+ readonly mainRepo: string;
+ cleanup(): void;
+}
+
+/** A clean main repo on `main` with a committed README + `.ok/config.yml` so a
+ * worktree checked out from it carries the OK config (mirrors production). */
+async function makeRepo(extraBranches: string[] = []): Promise<Handle> {
+ const root = realpathSync(mkdtempSync(join(tmpdir(), 'wt-svc-test-')));
+ const mainRepo = join(root, 'main');
+ mkdirSync(mainRepo);
+ await git(mainRepo, 'init', '--initial-branch=main', '.');
+ await git(mainRepo, 'config', 'user.email', '[email protected]');
+ await git(mainRepo, 'config', 'user.name', 'Test');
+ mkdirSync(join(mainRepo, '.ok'));
+ writeFileSync(join(mainRepo, '.ok', 'config.yml'), 'version: 1\n');
+ writeFileSync(join(mainRepo, 'README.md'), '# main\n');
+ await git(mainRepo, 'add', '-A');
+ await git(mainRepo, 'commit', '-m', 'initial');
+ for (const b of extraBranches) await git(mainRepo, 'branch', b);
+ return { root, mainRepo, cleanup: () => rmSync(root, { recursive: true, force: true }) };
+}
+
+async function addBareRemote(mainRepo: string, pushBranches: string[]): Promise<string> {
+ const bare = join(mainRepo, '..', 'origin.git');
+ await git(mainRepo, 'init', '--bare', '--initial-branch=main', bare);
+ await git(mainRepo, 'remote', 'add', 'origin', bare);
+ for (const b of pushBranches) await git(mainRepo, 'push', 'origin', b);
+ await git(mainRepo, 'fetch', 'origin');
+ return bare;
+}
+
+describe('worktree-service', () => {
+ let handle: Handle | null = null;
+ afterEach(() => {
+ handle?.cleanup();
+ handle = null;
+ clearRecentGitCache();
+ });
+
+ test('listWorktreeSelector returns every branch, flags current + main', async () => {
+ handle = await makeRepo(['dev', 'feature-x']);
+ const res = await listWorktreeSelector(handle.mainRepo, handle.mainRepo);
+ expect(res.ok).toBe(true);
+ if (!res.ok) return;
+ expect(res.model.mainRoot).toBe(handle.mainRepo);
+ const byBranch = new Map(res.model.entries.map((e) => [e.branch, e]));
+ expect(byBranch.get('main')?.isMain).toBe(true);
+ expect(byBranch.get('main')?.isCurrent).toBe(true);
+ expect(byBranch.get('dev')?.worktreePath).toBeNull();
+ expect(byBranch.get('feature-x')?.worktreePath).toBeNull();
+ });
+
+ test('createWorktree (existing branch) checks it out under .ok/worktrees/ and carries the OK config', async () => {
+ handle = await makeRepo(['dev']);
+ const res = await createWorktree({
+ anchorPath: handle.mainRepo,
+ branch: 'dev',
+ createBranch: false,
+ });
+ expect(res.ok).toBe(true);
+ if (!res.ok) return;
+ expect(res.created).toBe(true);
+ expect(res.path).toBe(join(handle.mainRepo, '.ok', 'worktrees', 'dev'));
+ expect(existsSync(join(res.path, 'README.md'))).toBe(true);
+ expect(existsSync(join(res.path, '.ok', 'config.yml'))).toBe(true);
+ const status = await git(handle.mainRepo, 'status', '--porcelain');
+ expect(status).not.toContain('.ok/worktrees');
+ });
+
+ test('createWorktree (-b) creates a new branch + worktree from HEAD', async () => {
+ handle = await makeRepo();
+ const res = await createWorktree({
+ anchorPath: handle.mainRepo,
+ branch: 'brand-new',
+ createBranch: true,
+ });
+ expect(res.ok).toBe(true);
+ if (!res.ok) return;
+ expect(res.created).toBe(true);
+ const branches = await git(handle.mainRepo, 'branch', '--list', 'brand-new');
+ expect(branches).toContain('brand-new');
+ });
+
+ test('createWorktree returns the existing path (created:false) when the branch already has a worktree', async () => {
+ handle = await makeRepo(['dev']);
+ const first = await createWorktree({
+ anchorPath: handle.mainRepo,
+ branch: 'dev',
+ createBranch: false,
+ });
+ expect(first.ok).toBe(true);
+ const second = await createWorktree({
+ anchorPath: handle.mainRepo,
+ branch: 'dev',
+ createBranch: false,
+ });
+ expect(second.ok).toBe(true);
+ if (!second.ok || !first.ok) return;
+ expect(second.created).toBe(false);
+ expect(second.path).toBe(first.path);
+ });
+
+ test('createWorktree from inside a linked worktree still anchors under the MAIN root', async () => {
+ handle = await makeRepo(['dev', 'other']);
+ const dev = await createWorktree({
+ anchorPath: handle.mainRepo,
+ branch: 'dev',
+ createBranch: false,
+ });
+ expect(dev.ok).toBe(true);
+ if (!dev.ok) return;
+ const other = await createWorktree({
+ anchorPath: dev.path,
+ branch: 'other',
+ createBranch: false,
+ });
+ expect(other.ok).toBe(true);
+ if (!other.ok) return;
+ expect(other.path).toBe(join(handle.mainRepo, '.ok', 'worktrees', 'other'));
+ });
+
+ test('createWorktree rejects a path-escaping branch name', async () => {
+ handle = await makeRepo();
+ const res = await createWorktree({
+ anchorPath: handle.mainRepo,
+ branch: '../evil',
+ createBranch: false,
+ });
+ expect(res.ok).toBe(false);
+ if (res.ok) return;
+ expect(res.reason).toBe('invalid-branch');
+ });
+
+ test('listWorktreeSelector on a non-git dir returns no-git', async () => {
+ const tmp = realpathSync(mkdtempSync(join(tmpdir(), 'wt-svc-nogit-')));
+ try {
+ const res = await listWorktreeSelector(tmp, tmp);
+ expect(res.ok).toBe(false);
+ if (res.ok) return;
+ expect(res.reason).toBe('no-git');
+ } finally {
+ rmSync(tmp, { recursive: true, force: true });
+ }
+ });
+
+ test('listWorktreeSelector flags isCurrent when the anchor is a subdirectory of the worktree', async () => {
+ handle = await makeRepo(['dev']);
+ const contentDir = join(handle.mainRepo, 'public', 'ok');
+ mkdirSync(contentDir, { recursive: true });
+ const res = await listWorktreeSelector(contentDir, contentDir);
+ expect(res.ok).toBe(true);
+ if (!res.ok) return;
+ expect(res.model.mainRoot).toBe(handle.mainRepo);
+ const main = res.model.entries.find((e) => e.branch === 'main');
+ expect(main?.isCurrent).toBe(true);
+ expect(res.model.currentBranch).toBe('main');
+ });
+
+ test('listWorktreeSelector prefers the deepest containing worktree for a nested anchor', async () => {
+ handle = await makeRepo(['dev']);
+ const dev = await createWorktree({
+ anchorPath: handle.mainRepo,
+ branch: 'dev',
+ createBranch: false,
+ });
+ expect(dev.ok).toBe(true);
+ if (!dev.ok) return;
+ const sub = join(dev.path, 'public', 'ok');
+ mkdirSync(sub, { recursive: true });
+ const res = await listWorktreeSelector(sub, sub);
+ expect(res.ok).toBe(true);
+ if (!res.ok) return;
+ const byBranch = new Map(res.model.entries.map((e) => [e.branch, e]));
+ expect(byBranch.get('dev')?.isCurrent).toBe(true);
+ expect(byBranch.get('main')?.isCurrent).toBe(false);
+ expect(res.model.currentBranch).toBe('dev');
+ });
+
+ test('createWorktree does not let a dash-prefixed branch inject a git flag (checkout arm)', async () => {
+ handle = await makeRepo();
+ const res = await createWorktree({
+ anchorPath: handle.mainRepo,
+ branch: '--detach',
+ createBranch: false,
+ });
+ expect(res.ok).toBe(false);
+ if (res.ok) return;
+ expect(res.reason).toBe('error');
+ const list = await git(handle.mainRepo, 'worktree', 'list', '--porcelain');
+ expect(list).not.toContain('detached');
+ expect(list).not.toContain('.ok/worktrees/--detach');
+ });
+
+ test('createWorktree guards a dash-prefixed baseBranch in the create arm', async () => {
+ handle = await makeRepo();
+ const res = await createWorktree({
+ anchorPath: handle.mainRepo,
+ branch: 'brand-new',
+ baseBranch: '--detach',
+ createBranch: true,
+ });
+ expect(res.ok).toBe(false);
+ if (res.ok) return;
+ expect(res.reason).toBe('error');
+ const branches = await git(handle.mainRepo, 'branch', '--list', 'brand-new');
+ expect(branches).not.toContain('brand-new');
+ });
+
+ test('createWorktree classifies a duplicate-branch create as branch-exists', async () => {
+ handle = await makeRepo(['dev']);
+ const res = await createWorktree({
+ anchorPath: handle.mainRepo,
+ branch: 'dev',
+ createBranch: true,
+ });
+ expect(res.ok).toBe(false);
+ if (res.ok) return;
+ expect(res.reason).toBe('branch-exists');
+ });
+
+ test('createWorktree classifies a pre-existing target dir as path-exists', async () => {
+ handle = await makeRepo(['dev']);
+ const target = join(handle.mainRepo, '.ok', 'worktrees', 'dev');
+ mkdirSync(target, { recursive: true });
+ writeFileSync(join(target, 'squatter.txt'), 'in the way\n');
+ const res = await createWorktree({
+ anchorPath: handle.mainRepo,
+ branch: 'dev',
+ createBranch: false,
+ });
+ expect(res.ok).toBe(false);
+ if (res.ok) return;
+ expect(res.reason).toBe('path-exists');
+ });
+
+ test('createWorktree surfaces an unrecognized git failure as error with a message', async () => {
+ handle = await makeRepo();
+ const res = await createWorktree({
+ anchorPath: handle.mainRepo,
+ branch: 'does-not-exist-branch',
+ createBranch: false,
+ });
+ expect(res.ok).toBe(false);
+ if (res.ok) return;
+ expect(res.reason).toBe('error');
+ expect(typeof res.message).toBe('string');
+ expect((res.message ?? '').length).toBeGreaterThan(0);
+ });
+
+ test('listWorktreeSelector surfaces origin/<x> remote refs and drops origin/HEAD', async () => {
+ handle = await makeRepo(['dev', 'feature-x']);
+ await addBareRemote(handle.mainRepo, ['main', 'dev', 'feature-x']);
+ await git(handle.mainRepo, 'remote', 'set-head', 'origin', 'main');
+ const res = await listWorktreeSelector(handle.mainRepo, handle.mainRepo);
+ expect(res.ok).toBe(true);
+ if (!res.ok) return;
+ const remotes = res.model.remoteBranches;
+ expect(remotes).toContain('origin/main');
+ expect(remotes).toContain('origin/dev');
+ expect(remotes).toContain('origin/feature-x');
+ expect(remotes).not.toContain('origin/HEAD');
+ expect(remotes).not.toContain('origin');
+ });
+
+ test('listWorktreeSelector computes per-branch behind-origin counts (no network)', async () => {
+ handle = await makeRepo(['dev']);
+ await addBareRemote(handle.mainRepo, ['main', 'dev']);
+ const scratch = join(handle.root, 'scratch');
+ await git(handle.root, 'clone', join(handle.mainRepo, '..', 'origin.git'), scratch);
+ await git(scratch, 'config', 'user.email', '[email protected]');
+ await git(scratch, 'config', 'user.name', 'Test');
+ writeFileSync(join(scratch, 'a.txt'), 'a\n');
+ await git(scratch, 'add', '-A');
+ await git(scratch, 'commit', '-m', 'a');
+ writeFileSync(join(scratch, 'b.txt'), 'b\n');
+ await git(scratch, 'add', '-A');
+ await git(scratch, 'commit', '-m', 'b');
+ await git(scratch, 'push', 'origin', 'main');
+ await git(handle.mainRepo, 'fetch', 'origin');
+
+ const res = await listWorktreeSelector(handle.mainRepo, handle.mainRepo);
+ expect(res.ok).toBe(true);
+ if (!res.ok) return;
+ const byBranch = new Map(res.model.entries.map((e) => [e.branch, e]));
+ expect(byBranch.get('main')?.behind).toBe(2);
+ expect(byBranch.get('dev')?.behind).toBe(0);
+ });
+
+ test('createWorktree (remoteRef) creates a local tracking branch off origin/<x> with remote content', async () => {
+ handle = await makeRepo();
+ await addBareRemote(handle.mainRepo, ['main']);
+ const scratch = join(handle.root, 'scratch');
+ await git(handle.root, 'clone', join(handle.mainRepo, '..', 'origin.git'), scratch);
+ await git(scratch, 'config', 'user.email', '[email protected]');
+ await git(scratch, 'config', 'user.name', 'Test');
+ await git(scratch, 'checkout', '-b', 'feature-x');
+ writeFileSync(join(scratch, 'remote-only.txt'), 'from remote\n');
+ await git(scratch, 'add', '-A');
+ await git(scratch, 'commit', '-m', 'remote-only feature');
+ await git(scratch, 'push', 'origin', 'feature-x');
+ await git(handle.mainRepo, 'fetch', 'origin');
+
+ const localBefore = await git(handle.mainRepo, 'branch', '--list', 'feature-x');
+ expect(localBefore.trim()).toBe('');
+
+ const res = await createWorktree({
+ anchorPath: handle.mainRepo,
+ branch: 'feature-x',
+ remoteRef: 'origin/feature-x',
+ createBranch: true,
+ });
+ expect(res.ok).toBe(true);
+ if (!res.ok) return;
+ expect(res.created).toBe(true);
+ expect(res.path).toBe(join(handle.mainRepo, '.ok', 'worktrees', 'feature-x'));
+ expect(existsSync(join(res.path, 'remote-only.txt'))).toBe(true);
+ const upstream = await git(
+ res.path,
+ 'rev-parse',
+ '--abbrev-ref',
+ '--symbolic-full-name',
+ '@{upstream}',
+ );
+ expect(upstream.trim()).toBe('origin/feature-x');
+ });
+
+ test('createWorktree (baseRef, --no-track) bases a new branch on origin/<x> without tracking it', async () => {
+ handle = await makeRepo();
+ await addBareRemote(handle.mainRepo, ['main']);
+ const scratch = join(handle.root, 'scratch');
+ await git(handle.root, 'clone', join(handle.mainRepo, '..', 'origin.git'), scratch);
+ await git(scratch, 'config', 'user.email', '[email protected]');
+ await git(scratch, 'config', 'user.name', 'Test');
+ writeFileSync(join(scratch, 'fresh.txt'), 'fresh from origin\n');
+ await git(scratch, 'add', '-A');
+ await git(scratch, 'commit', '-m', 'fresh commit on origin/main');
+ await git(scratch, 'push', 'origin', 'main');
+ await git(handle.mainRepo, 'fetch', 'origin');
+
+ const res = await createWorktree({
+ anchorPath: handle.mainRepo,
+ branch: 'my-feature',
+ baseRef: 'origin/main',
+ createBranch: true,
+ });
+ expect(res.ok).toBe(true);
+ if (!res.ok) return;
+ expect(existsSync(join(res.path, 'fresh.txt'))).toBe(true);
+ let upstreamErr = '';
+ try {
+ await git(res.path, 'rev-parse', '--abbrev-ref', '--symbolic-full-name', '@{upstream}');
+ } catch (e) {
+ upstreamErr = String((e as { stderr?: string }).stderr ?? e);
+ }
+ expect(upstreamErr).not.toBe('');
+ const branchList = await git(handle.mainRepo, 'branch', '--list', 'my-feature');
+ expect(branchList).toContain('my-feature');
+ });
+
+ test('createWorktree (remoteRef) rejects a path-escaping branch name before spawning git', async () => {
+ handle = await makeRepo();
+ const res = await createWorktree({
+ anchorPath: handle.mainRepo,
+ branch: '../evil',
+ remoteRef: 'origin/evil',
+ createBranch: true,
+ });
+ expect(res.ok).toBe(false);
+ if (res.ok) return;
+ expect(res.reason).toBe('invalid-branch');
+ });
+});
diff --git a/packages/desktop/src/main/worktree-service.ts b/packages/desktop/src/main/worktree-service.ts
new file mode 100644
index 000000000..21cc2e7c9
--- /dev/null
+++ b/packages/desktop/src/main/worktree-service.ts
@@ -0,0 +1,236 @@
+import { execFile, execFileSync } from 'node:child_process';
+import { appendFileSync, readFileSync, realpathSync } from 'node:fs';
+import { isAbsolute, join, sep } from 'node:path';
+import { promisify } from 'node:util';
+import {
+ buildWorktreeSelectorModel,
+ parseBranchList,
+ stripRemotePrefix,
+ WORKTREES_PARENT_DIR,
+ type WorktreeCreateRequest,
+ type WorktreeCreateResult,
+ type WorktreeListResult,
+ worktreeRelativeDir,
+} from '@inkeep/open-knowledge-core';
+import { listGitWorktrees } from './list-git-worktrees.ts';
+import { seedWorktreeAutoSync } from './worktree-autosync-inherit.ts';
+import { clearRecentGitCache } from './worktree-recents.ts';
+
+const execFileAsync = promisify(execFile);
+
+/** English-stable git env — mirrors `list-git-worktrees.ts` so stderr
+ * classification survives a non-English host locale. */
+const GIT_ENV = { ...process.env, LANG: 'C', LC_ALL: 'C' } as const;
+
+export type { WorktreeCreateResult, WorktreeListResult };
+
+export interface CreateWorktreeArgs extends WorktreeCreateRequest {
+ readonly anchorPath: string;
+}
+
+export async function listWorktreeSelector(
+ anchorPath: string,
+ currentProjectPath: string,
+): Promise<WorktreeListResult> {
+ const worktrees = await listGitWorktrees(anchorPath);
+ if (worktrees.length === 0) return { ok: false, reason: 'no-git' };
+ const branches = await listLocalBranches(anchorPath);
+ const remoteBranches = await listRemoteBranches(anchorPath);
+ const behind = await computeBehindCounts(anchorPath, branches, remoteBranches);
+ const resolvedCurrent = resolveAnchorToplevel(currentProjectPath, worktrees);
+ const model = buildWorktreeSelectorModel({
+ worktrees,
+ branches,
+ remoteBranches,
+ behind,
+ currentProjectPath: resolvedCurrent,
+ });
+ return { ok: true, model };
+}
+
+function resolveAnchorToplevel(
+ anchorPath: string,
+ worktrees: readonly { readonly path: string; readonly prunable: boolean }[],
+): string {
+ let anchor = anchorPath;
+ try {
+ anchor = realpathSync(anchorPath);
+ } catch {}
+ let best: string | null = null;
+ for (const w of worktrees) {
+ if (w.prunable) continue;
+ const isSelfOrAncestor = anchor === w.path || anchor.startsWith(w.path + sep);
+ if (isSelfOrAncestor && (best === null || w.path.length > best.length)) {
+ best = w.path;
+ }
+ }
+ return best ?? anchorPath;
+}
+
+export async function createWorktree(args: CreateWorktreeArgs): Promise<WorktreeCreateResult> {
+ const rel = worktreeRelativeDir(args.branch);
+ if (rel === null || !isAbsolute(args.anchorPath)) {
+ return { ok: false, reason: 'invalid-branch' };
+ }
+
+ const worktrees = await listGitWorktrees(args.anchorPath);
+ if (worktrees.length === 0) return { ok: false, reason: 'no-git' };
+ const mainRoot = worktrees[0]?.path;
+ if (mainRoot === undefined) return { ok: false, reason: 'no-git' };
+
+ const existing = worktrees.find((w) => !w.prunable && w.branch === args.branch.trim());
+ if (existing) return { ok: true, path: existing.path, created: false };
+
+ const worktreePath = join(mainRoot, rel);
+
+ ensureWorktreesExcluded(args.anchorPath);
+
+ const addArgs = buildAddArgs(args, worktreePath);
+
+ try {
+ await execFileAsync('git', addArgs, { cwd: args.anchorPath, env: GIT_ENV });
+ } catch (err) {
+ return { ok: false, ...classifyAddError(err) };
+ }
+
+ clearRecentGitCache();
+ try {
+ await seedWorktreeAutoSync(worktreePath, mainRoot);
+ } catch {}
+ return { ok: true, path: worktreePath, created: true };
+}
+
+function buildAddArgs(args: CreateWorktreeArgs, worktreePath: string): string[] {
+ const branch = args.branch.trim();
+ const remoteRef = args.remoteRef?.trim();
+ if (remoteRef) {
+ return ['worktree', 'add', '--track', '-b', branch, worktreePath, remoteRef];
+ }
+ if (args.createBranch) {
+ const baseRef = args.baseRef?.trim();
+ if (baseRef) {
+ return ['worktree', 'add', '-b', branch, worktreePath, baseRef, '--no-track'];
+ }
+ return [
+ 'worktree',
+ 'add',
+ '-b',
+ branch,
+ worktreePath,
+ ...(args.baseBranch ? ['--', args.baseBranch] : []),
+ ];
+ }
+ return ['worktree', 'add', worktreePath, '--', branch];
+}
+
+async function listLocalBranches(anchorPath: string): Promise<string[]> {
+ if (!isAbsolute(anchorPath)) return [];
+ try {
+ const { stdout } = await execFileAsync(
+ 'git',
+ ['for-each-ref', '--format=%(refname:short)', 'refs/heads/'],
+ { cwd: anchorPath, env: GIT_ENV },
+ );
+ return parseBranchList(String(stdout));
+ } catch {
+ return [];
+ }
+}
+
+async function listRemoteBranches(anchorPath: string): Promise<string[]> {
+ if (!isAbsolute(anchorPath)) return [];
+ try {
+ const { stdout } = await execFileAsync(
+ 'git',
+ ['for-each-ref', '--format=%(refname:short)', 'refs/remotes/'],
+ { cwd: anchorPath, env: GIT_ENV },
+ );
+ return parseBranchList(String(stdout)).filter(
+ (ref) => ref.includes('/') && stripRemotePrefix(ref) !== 'HEAD',
+ );
+ } catch {
+ return [];
+ }
+}
+
+async function computeBehindCounts(
+ anchorPath: string,
+ branches: readonly string[],
+ remoteBranches: readonly string[],
+): Promise<Record<string, number>> {
+ if (!isAbsolute(anchorPath)) return {};
+ const remoteRefSet = new Set(remoteBranches);
+ const out: Record<string, number> = {};
+ await Promise.all(
+ branches.map(async (branch) => {
+ const upstream = `origin/${branch}`;
+ if (!remoteRefSet.has(upstream)) return;
+ try {
+ const { stdout } = await execFileAsync(
+ 'git',
+ ['rev-list', '--count', `${branch}..${upstream}`],
+ { cwd: anchorPath, env: GIT_ENV },
+ );
+ const n = Number.parseInt(String(stdout).trim(), 10);
+ if (Number.isFinite(n) && n >= 0) out[branch] = n;
+ } catch {}
+ }),
+ );
+ return out;
+}
+
+function ensureWorktreesExcluded(anchorPath: string): void {
+ try {
+ const commonDir = execFileSyncTrim(
+ 'git',
+ ['rev-parse', '--path-format=absolute', '--git-common-dir'],
+ anchorPath,
+ );
+ if (commonDir === null) return;
+ const excludePath = join(commonDir, 'info', 'exclude');
+ const line = `/${WORKTREES_PARENT_DIR}/`;
+ let current = '';
+ try {
+ current = readFileSync(excludePath, 'utf-8');
+ } catch {}
+ if (current.split('\n').some((l) => l.trim() === line)) return;
+ const prefix = current.length > 0 && !current.endsWith('\n') ? '\n' : '';
+ appendFileSync(excludePath, `${prefix}${line}\n`);
+ } catch {}
+}
+
+function execFileSyncTrim(cmd: string, cmdArgs: string[], cwd: string): string | null {
+ try {
+ return String(execFileSync(cmd, cmdArgs, { cwd, env: GIT_ENV })).trim();
+ } catch {
+ return null;
+ }
+}
+
+interface ExecErr {
+ stderr?: string | Buffer;
+ message?: string;
+}
+
+interface AddErrorClassification {
+ readonly reason: 'branch-exists' | 'already-checked-out' | 'path-exists' | 'error';
+ readonly message?: string;
+}
+
+function classifyAddError(err: unknown): AddErrorClassification {
+ const e = typeof err === 'object' && err !== null ? (err as ExecErr) : null;
+ const stderrRaw = e?.stderr;
+ const raw: string =
+ stderrRaw !== undefined && stderrRaw !== null
+ ? Buffer.isBuffer(stderrRaw)
+ ? stderrRaw.toString('utf-8')
+ : String(stderrRaw)
+ : String(e?.message ?? err);
+ const stderr = raw.toLowerCase();
+ if (stderr.includes('already checked out')) return { reason: 'already-checked-out' };
+ if (stderr.includes('already exists') && stderr.includes('branch')) {
+ return { reason: 'branch-exists' };
+ }
+ if (stderr.includes('already exists')) return { reason: 'path-exists' };
+ return { reason: 'error', message: raw.replace(/\s+/g, ' ').slice(0, 300) };
+}
diff --git a/packages/desktop/src/preload/index.ts b/packages/desktop/src/preload/index.ts
index 46fcd335e..0926a7f50 100644
--- a/packages/desktop/src/preload/index.ts
+++ b/packages/desktop/src/preload/index.ts
@@ -1,3 +1,8 @@
+import type {
+ WorktreeCreateRequest,
+ WorktreeCreateResult,
+ WorktreeListResult,
+} from '@inkeep/open-knowledge-core';
import { contextBridge, type IpcRendererEvent, ipcRenderer, webUtils } from 'electron';
import type {
OkDesktopBridge,
@@ -333,6 +338,15 @@ const bridge: OkDesktopBridge = {
close: () => invoke('ok:project:close'),
},
+ worktree: {
+ list: () => invoke('ok:worktree:dispatch', { kind: 'list' }) as Promise<WorktreeListResult>,
+ create: (request: WorktreeCreateRequest) =>
+ invoke('ok:worktree:dispatch', {
+ kind: 'create',
+ ...request,
+ }) as Promise<WorktreeCreateResult>,
+ },
+
sharing: {
status: async () => {
const result = await invoke('ok:sharing:dispatch', { kind: 'status' });
diff --git a/packages/desktop/src/shared/bridge-contract.ts b/packages/desktop/src/shared/bridge-contract.ts
index f28bdbabe..5b4d97b0a 100644
--- a/packages/desktop/src/shared/bridge-contract.ts
+++ b/packages/desktop/src/shared/bridge-contract.ts
@@ -7,6 +7,9 @@ import type {
LocalOpOkInitResponse,
OkFolderState,
TerminalCli,
+ WorktreeCreateRequest,
+ WorktreeCreateResult,
+ WorktreeListResult,
} from '@inkeep/open-knowledge-core';
export type { BridgeWorktreeEntry };
@@ -110,7 +113,9 @@ export type OkMenuAction =
| 'toggle-doc-panel'
| 'toggle-terminal'
| 'new-terminal'
- | 'kill-terminal';
+ | 'kill-terminal'
+ | 'new-worktree'
+ | 'switch-worktree';
type OkUnsubscribe = () => void;
@@ -588,6 +593,11 @@ export interface OkDesktopBridge {
close(): Promise<void>;
};
+ worktree: {
+ list(): Promise<WorktreeListResult>;
+ create(request: WorktreeCreateRequest): Promise<WorktreeCreateResult>;
+ };
+
sharing: {
status(): Promise<OkSharingStatusResult>;
setMode(mode: 'shared' | 'local-only'): Promise<OkSharingSetModeResult>;
diff --git a/packages/desktop/src/shared/entry-point.ts b/packages/desktop/src/shared/entry-point.ts
index 00d19d9f0..64f9ffbff 100644
--- a/packages/desktop/src/shared/entry-point.ts
+++ b/packages/desktop/src/shared/entry-point.ts
@@ -5,7 +5,8 @@ export type EntryPoint =
| 'recents'
| 'deep-link'
| 'drag-drop'
- | 'share-receive';
+ | 'share-receive'
+ | 'worktree';
const ENTRY_POINT_VALUES: ReadonlySet<EntryPoint> = new Set([
'create-new',
@@ -15,6 +16,7 @@ const ENTRY_POINT_VALUES: ReadonlySet<EntryPoint> = new Set([
'deep-link',
'drag-drop',
'share-receive',
+ 'worktree',
]);
export function isEntryPoint(value: unknown): value is EntryPoint {
diff --git a/packages/desktop/src/shared/ipc-channels.ts b/packages/desktop/src/shared/ipc-channels.ts
index cfba65cfd..7b279ce00 100644
--- a/packages/desktop/src/shared/ipc-channels.ts
+++ b/packages/desktop/src/shared/ipc-channels.ts
@@ -6,6 +6,9 @@ import type {
LocalOpOkInitResponse,
OkFolderState,
TerminalCli,
+ WorktreeCreateRequest,
+ WorktreeCreateResult,
+ WorktreeListResult,
} from '@inkeep/open-knowledge-core';
import type {
FindEnclosingGitRootResult,
@@ -66,6 +69,10 @@ export interface RecentProject {
lastOpenedAt: string;
missing?: boolean;
gitRemoteUrl?: string;
+ gitCommonDir?: string;
+ mainRoot?: string;
+ isLinkedWorktree?: boolean;
+ branch?: string | null;
}
interface ProjectOpenRequest {
@@ -337,6 +344,10 @@ export interface RequestChannels {
args: [request: { projectPath: string }];
result: LocalOpOkInitResponse;
};
+ 'ok:worktree:dispatch': {
+ args: [request: { kind: 'list' } | ({ kind: 'create' } & WorktreeCreateRequest)];
+ result: WorktreeListResult | WorktreeCreateResult;
+ };
'ok:project:close': { args: []; result: undefined };
'ok:project:restart-server': { args: [projectPath: string]; result: OkServerRestartOutcome };
'ok:share:validate-folder': {
diff --git a/packages/desktop/tests/integration/ipc-channel-count-ratchet.test.ts b/packages/desktop/tests/integration/ipc-channel-count-ratchet.test.ts
index 3a5bb7feb..2b42d2962 100644
--- a/packages/desktop/tests/integration/ipc-channel-count-ratchet.test.ts
+++ b/packages/desktop/tests/integration/ipc-channel-count-ratchet.test.ts
@@ -5,7 +5,7 @@ import { join } from 'node:path';
const SRC_PATH = join(__dirname, '..', '..', 'src', 'shared', 'ipc-channels.ts');
const CHANNELS_SRC = readFileSync(SRC_PATH, 'utf-8');
-const REQUEST_CHANNEL_CAP = 75;
+const REQUEST_CHANNEL_CAP = 76;
function extractInterfaceBody(src: string, interfaceName: string): string {
const re = new RegExp(`(^|\\n)export\\s+interface\\s+${interfaceName}\\s*\\{`);
diff --git a/packages/desktop/tests/integration/m1-smoke.test.ts b/packages/desktop/tests/integration/m1-smoke.test.ts
index 4c2b241ae..75dd7b604 100644
--- a/packages/desktop/tests/integration/m1-smoke.test.ts
+++ b/packages/desktop/tests/integration/m1-smoke.test.ts
@@ -439,10 +439,12 @@ describe('M1 smoke', () => {
expect(desktopMembers.size).toBeGreaterThan(0);
expect(coreMembers.size).toBeGreaterThan(0);
expect(appMembers.size).toBeGreaterThan(0);
- expect(desktopMembers.size).toBe(26);
+ expect(desktopMembers.size).toBe(28);
expect(desktopMembers).toEqual(coreMembers);
expect(desktopMembers).toEqual(appMembers);
expect(desktopMembers.has('toggle-show-hidden-files')).toBe(true);
+ expect(desktopMembers.has('new-worktree')).toBe(true);
+ expect(desktopMembers.has('switch-worktree')).toBe(true);
});
test('M1 invariant: EntryPoint / OkProjectEntryPoint literal-union drift catcher', async () => {
@@ -477,7 +479,7 @@ describe('M1 smoke', () => {
expect(coreMembers.size).toBeGreaterThan(0);
expect(appMembers.size).toBeGreaterThan(0);
- expect(desktopMembers.size).toBe(7);
+ expect(desktopMembers.size).toBe(8);
expect(desktopMembers).toEqual(coreMembers);
expect(desktopMembers).toEqual(appMembers);
diff --git a/packages/desktop/tests/main/menu.test.ts b/packages/desktop/tests/main/menu.test.ts
index 2f155b956..e2eb34089 100644
--- a/packages/desktop/tests/main/menu.test.ts
+++ b/packages/desktop/tests/main/menu.test.ts
@@ -157,6 +157,32 @@ describe('buildMenuTemplate', () => {
expect(findByLabel(template, 'New Project…')).toBeUndefined();
});
+ describe('Worktree items (SPEC: worktree = window)', () => {
+ test('New worktree… / Switch worktree… are disabled when their deps are unwired', () => {
+ const template = buildMenuTemplate(makeDeps());
+ expect(findByLabel(template, 'New worktree…')?.enabled).toBe(false);
+ expect(findByLabel(template, 'Switch worktree…')?.enabled).toBe(false);
+ });
+
+ test('New worktree… click dispatches deps.onNewWorktree()', () => {
+ const onNewWorktree = mock(() => {});
+ const template = buildMenuTemplate(makeDeps({ onNewWorktree }));
+ const item = findByLabel(template, 'New worktree…');
+ expect(item?.enabled).toBe(true);
+ (item?.click as () => void)?.();
+ expect(onNewWorktree).toHaveBeenCalledTimes(1);
+ });
+
+ test('Switch worktree… click dispatches deps.onSwitchWorktree()', () => {
+ const onSwitchWorktree = mock(() => {});
+ const template = buildMenuTemplate(makeDeps({ onSwitchWorktree }));
+ const item = findByLabel(template, 'Switch worktree…');
+ expect(item?.enabled).toBe(true);
+ (item?.click as () => void)?.();
+ expect(onSwitchWorktree).toHaveBeenCalledTimes(1);
+ });
+ });
+
test('top-level menus include File / Edit / View / Terminal / Window / Help', () => {
const template = buildMenuTemplate(makeDeps());
const topLabels = template.map((t) => t.label);
diff --git a/packages/server/src/init-project.test.ts b/packages/server/src/init-project.test.ts
index 68d2929c6..ad705d4ad 100644
--- a/packages/server/src/init-project.test.ts
+++ b/packages/server/src/init-project.test.ts
@@ -74,6 +74,7 @@ describe('initContent', () => {
const gitignore = readFileSync(join(okDir, '.gitignore'), 'utf-8');
expect(gitignore).toContain('local/');
+ expect(gitignore).toContain('worktrees/');
const configYml = readFileSync(join(okDir, 'config.yml'), 'utf-8');
expect(configYml).toContain('OpenKnowledge — project configuration');
@@ -126,7 +127,7 @@ describe('initContent', () => {
const after = readFileSync(join(okDir, '.gitignore'), 'utf-8');
expect(after).toBe(
- `cache/\nserver.lock\nui.lock\nsync-state.json\nlocal/\nprincipal.json\nstate.json\nlast-spawn-error.log\n`,
+ `cache/\nserver.lock\nui.lock\nsync-state.json\nlocal/\nworktrees/\nprincipal.json\nstate.json\nlast-spawn-error.log\n`,
);
expect(result.updated).toContain('.gitignore');
expect(result.created).not.toContain('.gitignore');
diff --git a/packages/server/src/init-project.ts b/packages/server/src/init-project.ts
index b101af15e..b232ea6eb 100644
--- a/packages/server/src/init-project.ts
+++ b/packages/server/src/init-project.ts
@@ -145,6 +145,12 @@ const OK_GITIGNORE_CONTENT = `# .ok/local/ holds per-machine runtime state. Anyt
# manifests, telemetry, error logs) are auto-ignored — no edit needed here.
${LOCAL_DIR}/
+# .ok/worktrees/ holds git worktrees created from the desktop worktree
+# selector — per-machine checkouts, never committed (WORKTREES_PARENT_DIR in
+# @inkeep/open-knowledge-core). Worktree creation also appends this path to
+# .git/info/exclude so projects whose committed rule predates it stay clean.
+worktrees/
+
# Per-machine runtime state at the .ok/ root. Contains PII (principal email,
# UUID), hostnames, and absolute filesystem paths — never commit. The only
# file at .ok/ root that SHOULD be committed is \`config.yml\` (project