Skip to content

Beautiful, AI-native markdown IDE and LLM wiki

feat(desktop): auto-isolate dev instances per git worktree (#2660)

Andrew Mikofalvy19e06a3975d5
diff --git a/.changeset/dev-instance-branch-naming.md b/.changeset/dev-instance-branch-naming.md
new file mode 100644
index 000000000..37a61464d
--- /dev/null
+++ b/.changeset/dev-instance-branch-naming.md
@@ -0,0 +1,5 @@
+---
+"@inkeep/open-knowledge-desktop": patch
+---
+
+Dev: desktop `dev` launches now auto-isolate per git worktree/branch. Each launch derives its instance name from the checkout (branch name, or worktree directory on a detached HEAD) and relocates `userData` to a named sibling, so running `dev` from two worktrees at once no longer loses the single-instance lock. The instance name is shown in a branch badge in the editor top toolbar and as a Dock badge, alongside the existing menu-bar name and window titles. The default branch (`main`/`master`) is skipped; `OK_INSTANCE=<name>` overrides the derived name and `OK_AUTO_INSTANCE=0` disables auto-derivation. Unpackaged builds only; packaged releases are unaffected.
diff --git a/packages/app/src/components/EditorHeader.tsx b/packages/app/src/components/EditorHeader.tsx
index c3c7ed385..f9dfddb17 100644
--- a/packages/app/src/components/EditorHeader.tsx
+++ b/packages/app/src/components/EditorHeader.tsx
@@ -19,6 +19,7 @@ import { PresenceBar } from '@/presence/PresenceBar';
import { BetaBadge } from './BetaBadge';
import { EditorTabs } from './EditorTabs';
import { HelpPopover } from './HelpPopover';
+import { InstanceBadge } from './InstanceBadge';
import { PublishToGitHubDialog } from './PublishToGitHubDialog';
import { SettingsButton } from './SettingsButton';
import { ShareButton } from './ShareButton';
@@ -191,6 +192,7 @@ export function EditorHeader({ onSignIn, onSetIdentity, onOpenSearch }: EditorHe
<SyncStatusBadge onSignIn={onSignIn} onSetIdentity={onSetIdentity} />
<PresenceBar />
<Separator orientation="vertical" className="h-4 shrink-0 data-vertical:self-center" />
+ <InstanceBadge />
<BetaBadge />
{/* Settings is unavailable in single-file mode (config editing is inert). */}
{!singleFile && <SettingsButton />}
diff --git a/packages/app/src/components/InstanceBadge.dom.test.tsx b/packages/app/src/components/InstanceBadge.dom.test.tsx
new file mode 100644
index 000000000..55339a25d
--- /dev/null
+++ b/packages/app/src/components/InstanceBadge.dom.test.tsx
@@ -0,0 +1,55 @@
+import { afterEach, describe, expect, mock, test } from 'bun:test';
+import { cleanup, render, screen } from '@testing-library/react';
+import type { ReactNode } from 'react';
+import { renderLinguiTemplate } from '@/test-utils/lingui-mock';
+
+mock.module('@lingui/react/macro', () => ({
+ useLingui: () => ({ t: renderLinguiTemplate }),
+}));
+
+// Tooltip is decorative chrome; pass its parts through so the badge renders
+// without a TooltipProvider ancestor.
+mock.module('@/components/ui/tooltip', () => ({
+ Tooltip: ({ children }: { children: ReactNode }) => <>{children}</>,
+ TooltipTrigger: ({ children }: { children: ReactNode }) => <>{children}</>,
+ TooltipContent: ({ children }: { children: ReactNode }) => <>{children}</>,
+}));
+
+function setOkDesktop(value: { instanceLabel: string | null } | undefined): void {
+ (window as unknown as { okDesktop?: { instanceLabel: string | null } }).okDesktop = value;
+}
+
+async function renderInstanceBadge(className?: string) {
+ const { InstanceBadge } = await import('./InstanceBadge');
+ return render(<InstanceBadge className={className} />);
+}
+
+describe('InstanceBadge runtime behavior', () => {
+ afterEach(() => {
+ cleanup();
+ setOkDesktop(undefined);
+ });
+
+ test('renders nothing without a desktop host (web / CLI distribution)', async () => {
+ setOkDesktop(undefined);
+ await renderInstanceBadge();
+ expect(screen.queryByTestId('instance-badge')).toBeNull();
+ });
+
+ test('renders nothing when the host reports no instance label (default install)', async () => {
+ setOkDesktop({ instanceLabel: null });
+ await renderInstanceBadge();
+ expect(screen.queryByTestId('instance-badge')).toBeNull();
+ });
+
+ test('renders the branch label for a named parallel instance', async () => {
+ setOkDesktop({ instanceLabel: 'theming-as-plugin' });
+ await renderInstanceBadge('ml-1');
+
+ const badge = screen.getByTestId('instance-badge');
+ expect(badge.textContent).toContain('theming-as-plugin');
+ expect(badge.getAttribute('aria-label')).toBe('Dev instance: theming-as-plugin');
+ expect(badge.getAttribute('data-variant')).toBe('secondary');
+ expect(badge.classList.contains('ml-1')).toBe(true);
+ });
+});
diff --git a/packages/app/src/components/InstanceBadge.tsx b/packages/app/src/components/InstanceBadge.tsx
new file mode 100644
index 000000000..88d3014b2
--- /dev/null
+++ b/packages/app/src/components/InstanceBadge.tsx
@@ -0,0 +1,41 @@
+/**
+ * Visible-in-window-chrome reminder of which named parallel dev instance this
+ * window belongs to — the git branch / worktree the build was launched from.
+ * Renders nothing unless the desktop host reports an `instanceLabel` (only set
+ * when the launch relocated `userData` to a named sibling: auto-derived from
+ * the git checkout or an explicit `OK_INSTANCE`). So it is invisible for the
+ * default install, in web / CLI distribution, and for plain dev on the default
+ * branch — exactly the launches that are NOT parallel instances.
+ */
+
+import { useLingui } from '@lingui/react/macro';
+import { GitBranch } from 'lucide-react';
+import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip';
+import { Badge } from './ui/badge';
+
+interface InstanceBadgeProps {
+ /** Optional layout overrides — the badge component itself stays size-agnostic. */
+ readonly className?: string;
+}
+
+export function InstanceBadge({ className }: InstanceBadgeProps) {
+ const { t } = useLingui();
+ const label = typeof window !== 'undefined' ? (window.okDesktop?.instanceLabel ?? null) : null;
+ if (!label) return null;
+ return (
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <Badge
+ variant="secondary"
+ aria-label={t`Dev instance: ${label}`}
+ data-testid="instance-badge"
+ className={className}
+ >
+ <GitBranch aria-hidden="true" />
+ <span className="max-w-40 truncate">{label}</span>
+ </Badge>
+ </TooltipTrigger>
+ <TooltipContent>{t`Dev instance: ${label} (isolated from other worktrees)`}</TooltipContent>
+ </Tooltip>
+ );
+}
diff --git a/packages/app/src/lib/desktop-bridge-types.ts b/packages/app/src/lib/desktop-bridge-types.ts
index 9a8bf50c9..3c9b08632 100644
--- a/packages/app/src/lib/desktop-bridge-types.ts
+++ b/packages/app/src/lib/desktop-bridge-types.ts
@@ -1434,6 +1434,14 @@ export interface OkDesktopBridge {
readonly platform: 'darwin' | 'win32' | 'linux';
readonly appVersion: string;
+ /**
+ * Named parallel dev-instance label (branch/worktree) when this launch
+ * relocated `userData` to a named sibling — auto-derived from the git
+ * checkout or an explicit `OK_INSTANCE`. Null for the default install and in
+ * web / CLI distribution. Drives the header branch badge. Lockstep with the
+ * main-side `OkDesktopBridge` (`packages/desktop/src/shared/bridge-contract.ts`).
+ */
+ readonly instanceLabel: string | null;
/**
* Resolve a dropped `File` to its absolute filesystem path via Electron
* `webUtils.getPathForFile` (renderer-side, no IPC). Returns null for a File
diff --git a/packages/app/src/locales/en/messages.json b/packages/app/src/locales/en/messages.json
index 1113695a1..480e11de0 100644
--- a/packages/app/src/locales/en/messages.json
+++ b/packages/app/src/locales/en/messages.json
@@ -1693,6 +1693,7 @@
"bwil08": ["Building <0>openknowledge.skill</0> and opening the Claude Desktop App"],
"c1LZZH": ["Link copied."],
"c4fVUV": ["Fix"],
+ "c5PTFE": ["Dev instance: ", ["label"], " (isolated from other worktrees)"],
"c5f7sm": ["Code block language: ", ["currentLabel"], ". Click to change."],
"c5rF4v": ["What is this knowledge base for?"],
"c863eW": ["Could not switch to ", ["shareBranch"], ". Try switching manually."],
@@ -1974,6 +1975,7 @@
"iNFKkm": ["No diff."],
"iO8V-7": ["Create worktree"],
"iOHg1t": ["Open embedded URL in new tab"],
+ "iRdfLr": ["Dev instance: ", ["label"]],
"iSLIjg": ["Connect"],
"iSQTsg": ["Ordered list"],
"iSnkwB": ["Failed to open cloned project."],
diff --git a/packages/app/src/locales/en/messages.po b/packages/app/src/locales/en/messages.po
index cdbdf39fb..c614b78cf 100644
--- a/packages/app/src/locales/en/messages.po
+++ b/packages/app/src/locales/en/messages.po
@@ -2645,6 +2645,14 @@ msgstr "Detected on this machine"
msgid "Detecting"
msgstr "Detecting"
+#: src/components/InstanceBadge.tsx
+msgid "Dev instance: {label}"
+msgstr "Dev instance: {label}"
+
+#: src/components/InstanceBadge.tsx
+msgid "Dev instance: {label} (isolated from other worktrees)"
+msgstr "Dev instance: {label} (isolated from other worktrees)"
+
#: src/components/MermaidFileViewer.tsx
msgid "Diagram"
msgstr "Diagram"
diff --git a/packages/app/src/locales/pseudo/messages.json b/packages/app/src/locales/pseudo/messages.json
index e375fafb5..915923f24 100644
--- a/packages/app/src/locales/pseudo/messages.json
+++ b/packages/app/src/locales/pseudo/messages.json
@@ -1693,6 +1693,7 @@
"bwil08": ["ßũĩĺďĩńĝ <0>ōƥēńķńōŵĺēďĝē.śķĩĺĺ</0> àńď ōƥēńĩńĝ ţĥē Ćĺàũďē Ďēśķţōƥ Àƥƥ"],
"c1LZZH": ["Ĺĩńķ ćōƥĩēď."],
"c4fVUV": ["Ƒĩx"],
+ "c5PTFE": ["Ďēv ĩńśţàńćē: ", ["label"], " (ĩśōĺàţēď ƒŕōḿ ōţĥēŕ ŵōŕķţŕēēś)"],
"c5f7sm": ["Ćōďē ƀĺōćķ ĺàńĝũàĝē: ", ["currentLabel"], ". Ćĺĩćķ ţō ćĥàńĝē."],
"c5rF4v": ["Ŵĥàţ ĩś ţĥĩś ķńōŵĺēďĝē ƀàśē ƒōŕ?"],
"c863eW": ["Ćōũĺď ńōţ śŵĩţćĥ ţō ", ["shareBranch"], ". Ţŕŷ śŵĩţćĥĩńĝ ḿàńũàĺĺŷ."],
@@ -1974,6 +1975,7 @@
"iNFKkm": ["Ńō ďĩƒƒ."],
"iO8V-7": ["Ćŕēàţē ŵōŕķţŕēē"],
"iOHg1t": ["Ōƥēń ēḿƀēďďēď ŨŔĹ ĩń ńēŵ ţàƀ"],
+ "iRdfLr": ["Ďēv ĩńśţàńćē: ", ["label"]],
"iSLIjg": ["Ćōńńēćţ"],
"iSQTsg": ["Ōŕďēŕēď ĺĩśţ"],
"iSnkwB": ["Ƒàĩĺēď ţō ōƥēń ćĺōńēď ƥŕōĴēćţ."],
diff --git a/packages/app/src/locales/pseudo/messages.po b/packages/app/src/locales/pseudo/messages.po
index 9b29af1ca..f92ee32fa 100644
--- a/packages/app/src/locales/pseudo/messages.po
+++ b/packages/app/src/locales/pseudo/messages.po
@@ -2640,6 +2640,14 @@ msgstr ""
msgid "Detecting"
msgstr ""
+#: src/components/InstanceBadge.tsx
+msgid "Dev instance: {label}"
+msgstr ""
+
+#: src/components/InstanceBadge.tsx
+msgid "Dev instance: {label} (isolated from other worktrees)"
+msgstr ""
+
#: src/components/MermaidFileViewer.tsx
msgid "Diagram"
msgstr ""
diff --git a/packages/app/tests/stress/fixtures/handoff-mocks.ts b/packages/app/tests/stress/fixtures/handoff-mocks.ts
index 7e0ede041..d3bed056f 100644
--- a/packages/app/tests/stress/fixtures/handoff-mocks.ts
+++ b/packages/app/tests/stress/fixtures/handoff-mocks.ts
@@ -613,6 +613,7 @@ export async function installHandoffMocks(page: Page, cfg: HandoffMockConfig): P
},
platform: 'darwin' as const,
appVersion: 'test-0.0.0',
+ instanceLabel: null,
getPathForFile: () => null,
} satisfies OkDesktopBridge;
diff --git a/packages/core/src/desktop-bridge.ts b/packages/core/src/desktop-bridge.ts
index 2ecdeedf0..04ce5775d 100644
--- a/packages/core/src/desktop-bridge.ts
+++ b/packages/core/src/desktop-bridge.ts
@@ -1673,6 +1673,13 @@ export interface OkDesktopBridge {
readonly platform: 'darwin' | 'win32' | 'linux';
/** Electron app version (from main's `app.getVersion()`). */
readonly appVersion: string;
+ /**
+ * Named parallel dev-instance label (branch/worktree) when this launch
+ * relocated `userData` to a named sibling — auto-derived from the git
+ * checkout or an explicit `OK_INSTANCE`. Null for the default install and in
+ * web / CLI distribution. Drives the header branch badge.
+ */
+ readonly instanceLabel: string | null;
/**
* Resolve a dropped `File` to its absolute filesystem path via Electron
diff --git a/packages/desktop/src/main/auto-instance.test.ts b/packages/desktop/src/main/auto-instance.test.ts
new file mode 100644
index 000000000..2cafc609f
--- /dev/null
+++ b/packages/desktop/src/main/auto-instance.test.ts
@@ -0,0 +1,112 @@
+import { describe, expect, test } from 'bun:test';
+import {
+ deriveAutoInstanceName,
+ type GitInstanceContext,
+ resolveEffectiveInstanceName,
+} from './auto-instance.ts';
+
+describe('deriveAutoInstanceName', () => {
+ test('uses the branch name for a normal feature branch', () => {
+ expect(deriveAutoInstanceName({ branch: 'theming-as-plugin', worktreeDir: '/repo' })).toBe(
+ 'theming-as-plugin',
+ );
+ });
+
+ test('returns the branch verbatim (slash sanitizing happens downstream)', () => {
+ expect(deriveAutoInstanceName({ branch: 'feat/foo', worktreeDir: '/repo' })).toBe('feat/foo');
+ });
+
+ test('skips the repo default branch so plain dev on main is unchanged', () => {
+ expect(deriveAutoInstanceName({ branch: 'main', worktreeDir: '/repo' })).toBeNull();
+ expect(deriveAutoInstanceName({ branch: 'master', worktreeDir: '/repo' })).toBeNull();
+ });
+
+ test('falls back to the worktree dir basename on detached HEAD', () => {
+ expect(deriveAutoInstanceName({ branch: 'HEAD', worktreeDir: '/Users/me/wt/spike-a' })).toBe(
+ 'spike-a',
+ );
+ expect(deriveAutoInstanceName({ branch: null, worktreeDir: '/Users/me/wt/spike-b' })).toBe(
+ 'spike-b',
+ );
+ });
+
+ test('returns null when neither branch nor worktree dir is usable', () => {
+ expect(deriveAutoInstanceName({ branch: null, worktreeDir: null })).toBeNull();
+ expect(deriveAutoInstanceName({ branch: 'HEAD', worktreeDir: null })).toBeNull();
+ });
+});
+
+describe('resolveEffectiveInstanceName', () => {
+ const gitOn = (ctx: GitInstanceContext) => ({ readGit: () => ctx });
+
+ test('explicit OK_INSTANCE wins over git derivation', () => {
+ expect(
+ resolveEffectiveInstanceName(
+ { OK_INSTANCE: 'work' },
+ '/repo',
+ gitOn({ branch: 'feat/x', worktreeDir: '/repo' }),
+ ),
+ ).toEqual({ name: 'work', source: 'env' });
+ });
+
+ test('explicit OK_INSTANCE isolates even on the default branch', () => {
+ expect(
+ resolveEffectiveInstanceName(
+ { OK_INSTANCE: 'main' },
+ '/repo',
+ gitOn({ branch: 'main', worktreeDir: '/repo' }),
+ ),
+ ).toEqual({ name: 'main', source: 'env' });
+ });
+
+ test('blank OK_INSTANCE falls through to git derivation', () => {
+ expect(
+ resolveEffectiveInstanceName(
+ { OK_INSTANCE: ' ' },
+ '/repo',
+ gitOn({ branch: 'feat/x', worktreeDir: '/repo' }),
+ ),
+ ).toEqual({ name: 'feat/x', source: 'git' });
+ });
+
+ test('derives from git when OK_INSTANCE is unset', () => {
+ expect(
+ resolveEffectiveInstanceName(
+ {},
+ '/repo',
+ gitOn({ branch: 'theming-as-plugin', worktreeDir: '/repo' }),
+ ),
+ ).toEqual({ name: 'theming-as-plugin', source: 'git' });
+ });
+
+ test('OK_AUTO_INSTANCE=0/false/off disables auto-derivation', () => {
+ for (const off of ['0', 'false', 'off', 'OFF']) {
+ expect(
+ resolveEffectiveInstanceName(
+ { OK_AUTO_INSTANCE: off },
+ '/repo',
+ gitOn({ branch: 'feat/x', worktreeDir: '/repo' }),
+ ),
+ ).toBeNull();
+ }
+ });
+
+ test('returns null on the default branch with no explicit override', () => {
+ expect(
+ resolveEffectiveInstanceName({}, '/repo', gitOn({ branch: 'main', worktreeDir: '/repo' })),
+ ).toBeNull();
+ });
+
+ test('autoDeriveEnabled: false disables git derivation (E2E smoke) but explicit still wins', () => {
+ const ctx = { branch: 'feat/x', worktreeDir: '/repo' };
+ expect(
+ resolveEffectiveInstanceName({}, '/repo', { ...gitOn(ctx), autoDeriveEnabled: false }),
+ ).toBeNull();
+ expect(
+ resolveEffectiveInstanceName({ OK_INSTANCE: 'work' }, '/repo', {
+ ...gitOn(ctx),
+ autoDeriveEnabled: false,
+ }),
+ ).toEqual({ name: 'work', source: 'env' });
+ });
+});
diff --git a/packages/desktop/src/main/auto-instance.ts b/packages/desktop/src/main/auto-instance.ts
new file mode 100644
index 000000000..04367dd49
--- /dev/null
+++ b/packages/desktop/src/main/auto-instance.ts
@@ -0,0 +1,119 @@
+/**
+ * Auto-derive a dev-instance name from the git checkout so each worktree /
+ * feature branch runs as its own isolated OpenKnowledge desktop instance
+ * without the developer setting `OK_INSTANCE` by hand. The derived name feeds
+ * the same `OK_INSTANCE` machinery (`instance-isolation.ts` relocates
+ * `userData`; `instance-identity.ts` surfaces the label in the menu bar +
+ * window titles), so two `bun run dev` launches from different worktrees no
+ * longer collide on the single-instance lock.
+ *
+ * Split into a pure derivation (`deriveAutoInstanceName`, Electron- and
+ * git-free, unit-testable) and a thin best-effort git reader
+ * (`readGitInstanceContext`). Dev-only: the caller gates on `!app.isPackaged`,
+ * lets an explicit `OK_INSTANCE` win, and honors an `OK_AUTO_INSTANCE=0`
+ * opt-out.
+ */
+import { execFileSync } from 'node:child_process';
+import { basename } from 'node:path';
+
+/**
+ * Branch names treated as the repo's default line — no auto-instance for
+ * these, so a plain `bun run dev` on `main` keeps the classic shared
+ * `OpenKnowledge` `userData` (and its recents / consent state) rather than
+ * silently migrating to a `main`-labelled sibling. Only feature branches and
+ * worktrees (always on a non-default branch) get their own instance.
+ */
+const DEFAULT_BRANCH_NAMES = new Set(['main', 'master']);
+
+export interface GitInstanceContext {
+ /** Current branch name, or null when detached / not a git checkout. */
+ readonly branch: string | null;
+ /** Absolute path of the worktree root, or null when unavailable. */
+ readonly worktreeDir: string | null;
+}
+
+function runGit(args: readonly string[], dir: string): string | null {
+ try {
+ const out = execFileSync('git', ['-C', dir, ...args], {
+ encoding: 'utf8',
+ timeout: 2_000,
+ // Silence git's stderr — a non-repo / missing-git failure is expected
+ // and handled via the null return, not surfaced to the desktop log.
+ stdio: ['ignore', 'pipe', 'ignore'],
+ }).trim();
+ return out.length > 0 ? out : null;
+ } catch {
+ return null;
+ }
+}
+
+/**
+ * Read the branch + worktree root of the git checkout containing `dir`.
+ * Best-effort: any git failure (not a repo, git missing, timeout) yields
+ * nulls so the caller falls back to the default `userData`.
+ */
+function readGitInstanceContext(dir: string): GitInstanceContext {
+ return {
+ branch: runGit(['rev-parse', '--abbrev-ref', 'HEAD'], dir),
+ worktreeDir: runGit(['rev-parse', '--show-toplevel'], dir),
+ };
+}
+
+/**
+ * Derive the auto-instance name from a git context. Prefers the branch name —
+ * what a developer recognizes, and what git guarantees is unique across
+ * simultaneously-running worktrees (a branch can be checked out in only one
+ * worktree at a time). Falls back to the worktree directory basename when HEAD
+ * is detached (`git rev-parse --abbrev-ref HEAD` prints `HEAD`), so a
+ * tag / SHA checkout still gets a stable per-worktree instance.
+ *
+ * Returns null for the default branch (see {@link DEFAULT_BRANCH_NAMES}) or
+ * when nothing usable is available — signalling the caller to leave `userData`
+ * at the default install location. The returned raw name is sanitized
+ * downstream by `deriveInstanceUserDataDir` (path-segment safety).
+ */
+export function deriveAutoInstanceName(ctx: GitInstanceContext): string | null {
+ const branch = ctx.branch;
+ if (branch && branch !== 'HEAD') {
+ if (DEFAULT_BRANCH_NAMES.has(branch)) return null;
+ return branch;
+ }
+ if (ctx.worktreeDir) {
+ const base = basename(ctx.worktreeDir);
+ return base.length > 0 ? base : null;
+ }
+ return null;
+}
+
+/**
+ * Resolve the effective dev-instance name from the environment + a lazily-read
+ * git context. Encapsulates the precedence so `index.ts` stays declarative:
+ *
+ * 1. explicit `OK_INSTANCE` (non-empty, trimmed) always wins — including on
+ * the default branch, so `OK_INSTANCE=main` still isolates on purpose;
+ * 2. `OK_AUTO_INSTANCE` in {`0`,`false`,`off`} disables auto-derivation
+ * (→ default `userData`), as does `opts.autoDeriveEnabled: false` (the
+ * caller sets this for automated launches like the E2E desktop smoke, so
+ * no git subprocess runs on the launch path and `userData` is never
+ * relocated out from under a test);
+ * 3. otherwise derive from git via `opts.readGit(appDir)`.
+ *
+ * `opts.readGit` is injected so the whole precedence chain is unit-testable
+ * without spawning git. Returns null to leave `userData` untouched.
+ */
+export function resolveEffectiveInstanceName(
+ env: { readonly OK_INSTANCE?: string; readonly OK_AUTO_INSTANCE?: string },
+ appDir: string,
+ opts: {
+ readonly readGit?: (dir: string) => GitInstanceContext;
+ readonly autoDeriveEnabled?: boolean;
+ } = {},
+): { name: string; source: 'env' | 'git' } | null {
+ const explicit = env.OK_INSTANCE?.trim();
+ if (explicit) return { name: explicit, source: 'env' };
+ if (opts.autoDeriveEnabled === false) return null;
+ if (/^(0|false|off)$/i.test(env.OK_AUTO_INSTANCE ?? '')) return null;
+ const readGit = opts.readGit ?? readGitInstanceContext;
+ const derived = deriveAutoInstanceName(readGit(appDir));
+ return derived ? { name: derived, source: 'git' } : null;
+}
diff --git a/packages/desktop/src/main/index.ts b/packages/desktop/src/main/index.ts
index e54bcf5ee..8c647a758 100644
--- a/packages/desktop/src/main/index.ts
+++ b/packages/desktop/src/main/index.ts
@@ -136,6 +136,7 @@ import { buildAboutPanelOptions } from './about-panel.ts';
import { appendOkIgnoreSync } from './append-okignore.ts';
import { openAssetSafely, revealAssetSafely } from './asset-allowlist.ts';
import { popAssetMenu } from './asset-menu.ts';
+import { resolveEffectiveInstanceName } from './auto-instance.ts';
import {
bootAutoUpdater,
channelFromVersion,
@@ -4719,9 +4720,23 @@ function registerProjectIntegrationsSettingsIpc(): void {
*/
const ICON_PNG_PATH = join(__dirname, '..', '..', 'build', 'icon.png');
-function installDockIcon() {
+function installDockIcon(instanceLabel: string | null) {
if (process.platform !== 'darwin') return;
if (app.isPackaged) return; // packaged build uses the bundle's .icns
+ // Differentiate parallel dev instances on the Dock. macOS reads the Dock
+ // tile *name* (hover tooltip) from the running bundle's Info.plist, which in
+ // dev is Electron's own — `app.setName()` renames the menu bar but not the
+ // Dock tile, and there is no runtime API to rename it for an unpackaged app.
+ // A badge is the only way to put the instance label onto the Dock icon at
+ // runtime; the OK icon already identifies it as OpenKnowledge. No-op for the
+ // default install (label null). See electron/electron#3391, #19892.
+ if (instanceLabel) {
+ try {
+ app.dock?.setBadge(instanceLabel);
+ } catch (err) {
+ console.warn('[main] dock badge set failed', { err: (err as Error).message });
+ }
+ }
if (!existsSync(ICON_PNG_PATH)) {
console.warn('[main] skipping dock icon — build/icon.png missing');
return;
@@ -4847,26 +4862,40 @@ installStdioBrokenPipeGuard(process, {
// Dev-only parallel-instance isolation. Electron keys the single-instance lock
// on `userData` (and Chromium storage + recents live there), so two desktop
// processes sharing one `userData` can't coexist — the second fails
-// `requestSingleInstanceLock()` and quits. `OK_INSTANCE=<name>` relocates this
-// launch's `userData` to a named sibling dir, giving each instance its own lock
-// + isolated storage. Must run before `requestSingleInstanceLock()` and any
-// `userData` read; packaged builds ignore it so releases are never affected.
-if (!app.isPackaged && process.env.OK_INSTANCE) {
- const relocatedUserData = deriveInstanceUserDataDir(
- app.getPath('userData'),
- process.env.OK_INSTANCE,
- );
- if (relocatedUserData) {
- mkdirSync(relocatedUserData, { recursive: true });
- app.setPath('userData', relocatedUserData);
- getRootDesktopLogger().info(
- {
- event: 'desktop.parallel-instance',
- instance: process.env.OK_INSTANCE,
- userData: relocatedUserData,
- },
- 'relocated userData for parallel dev instance',
- );
+// `requestSingleInstanceLock()` and quits. Relocating this launch's `userData`
+// to a named sibling dir gives each instance its own lock + isolated storage.
+//
+// The instance name is `OK_INSTANCE` when set, else auto-derived from the git
+// checkout (branch name, or worktree dir on detached HEAD) so two `bun run dev`
+// launches from different worktrees isolate automatically — no env needed. The
+// repo default branch (main/master) is skipped so plain dev on main keeps the
+// classic shared `userData`; `OK_AUTO_INSTANCE=0` disables auto-derivation.
+// Must run before `requestSingleInstanceLock()` and any `userData` read;
+// packaged builds ignore it so releases are never affected.
+if (!app.isPackaged) {
+ // Auto-derivation is for humans running `bun run dev` from a worktree; keep it
+ // out of the E2E desktop smoke, which drives an unpackaged build on a feature
+ // branch. Deriving there would run git on the launch path and relocate
+ // `userData` on every smoke launch. Explicit `OK_INSTANCE` still wins, so a
+ // test can opt into isolation on purpose.
+ const resolved = resolveEffectiveInstanceName(process.env, app.getAppPath(), {
+ autoDeriveEnabled: process.env.OK_DESKTOP_E2E_SMOKE !== '1',
+ });
+ if (resolved) {
+ const relocatedUserData = deriveInstanceUserDataDir(app.getPath('userData'), resolved.name);
+ if (relocatedUserData) {
+ mkdirSync(relocatedUserData, { recursive: true });
+ app.setPath('userData', relocatedUserData);
+ getRootDesktopLogger().info(
+ {
+ event: 'desktop.parallel-instance',
+ instance: resolved.name,
+ source: resolved.source,
+ userData: relocatedUserData,
+ },
+ 'relocated userData for parallel dev instance',
+ );
+ }
}
}
@@ -5140,7 +5169,7 @@ function bootPrimaryInstance(): void {
nativeTheme.themeSource = source;
},
refreshApplicationMenu,
- installDockIcon,
+ installDockIcon: () => installDockIcon(instanceLabel),
log: { warn: (msg, obj) => console.warn(msg, obj) },
appVersion: app.getVersion(),
maxSupportedSchemaVersion: MAX_SUPPORTED_SCHEMA_VERSION,
diff --git a/packages/desktop/src/main/window-manager.ts b/packages/desktop/src/main/window-manager.ts
index e700ea91d..ff517d3ca 100644
--- a/packages/desktop/src/main/window-manager.ts
+++ b/packages/desktop/src/main/window-manager.ts
@@ -91,6 +91,16 @@ export function setWindowInstanceLabel(label: string | null): void {
windowInstanceLabel = label;
}
+/**
+ * `--ok-instance-label` preload arg for the current named instance, spread into
+ * each editor window's `additionalArguments` so the renderer can show the
+ * branch/worktree badge in the header. Present only for a named parallel
+ * instance; the default install omits it (preload coerces absent → null).
+ */
+function instanceLabelArgs(): string[] {
+ return windowInstanceLabel ? [`--ok-instance-label=${windowInstanceLabel}`] : [];
+}
+
/**
* Editor window title format — `<projectName> — OpenKnowledge`, plus a
* ` (<instance>)` suffix when this is a named parallel instance. The em dash
@@ -1718,6 +1728,7 @@ export class WindowManager {
`--ok-project-name=${projectName}`,
`--ok-mode=editor`,
`--ok-app-version=${this.deps.appVersion}`,
+ ...instanceLabelArgs(),
// Startup instrumentation (Plan A): carry main's `ok.app-startup`
// traceparent so the renderer parents its startup span into the launch
// trace. Appended only when present (OTel enabled in main).
@@ -2036,6 +2047,7 @@ export class WindowManager {
// a fresh temp dir (no session/tab restore), so a drop had no safety net.
`--ok-initial-doc=${opts.docName}`,
`--ok-app-version=${this.deps.appVersion}`,
+ ...instanceLabelArgs(),
],
title: formatEditorTitle(projectName),
});
@@ -2363,6 +2375,7 @@ export class WindowManager {
`--ok-project-name=${projectName}`,
`--ok-mode=editor`,
`--ok-app-version=${this.deps.appVersion}`,
+ ...instanceLabelArgs(),
...(this.deps.startup?.traceparent !== undefined
? [`--ok-startup-traceparent=${this.deps.startup.traceparent}`]
: []),
diff --git a/packages/desktop/src/preload/index.ts b/packages/desktop/src/preload/index.ts
index 77f0a82d4..0192c49b2 100644
--- a/packages/desktop/src/preload/index.ts
+++ b/packages/desktop/src/preload/index.ts
@@ -771,6 +771,11 @@ const bridge: OkDesktopBridge = {
platform: process.platform as 'darwin' | 'win32' | 'linux',
appVersion: parseArg('app-version') ?? '0.0.0',
+ // Named parallel dev instance (branch/worktree). Present only when this launch
+ // relocated `userData` to a named sibling (auto-derived from git or explicit
+ // `OK_INSTANCE`); the default install omits the flag → null. Surfaced as the
+ // header branch badge so concurrent dev instances are tellable apart.
+ instanceLabel: parseArg('instance-label') ?? null,
// Resolve a dropped File to its on-disk path. `webUtils.getPathForFile` is a
// renderer-side call (no IPC) and the only way to recover the path since
diff --git a/packages/desktop/src/shared/bridge-contract.ts b/packages/desktop/src/shared/bridge-contract.ts
index b04867680..c485ca2b1 100644
--- a/packages/desktop/src/shared/bridge-contract.ts
+++ b/packages/desktop/src/shared/bridge-contract.ts
@@ -2033,6 +2033,14 @@ export interface OkDesktopBridge {
readonly platform: 'darwin' | 'win32' | 'linux';
readonly appVersion: string;
+ /**
+ * Named parallel dev-instance label (branch/worktree) when this launch
+ * relocated `userData` to a named sibling — auto-derived from the git
+ * checkout or an explicit `OK_INSTANCE`. Null for the default install and in
+ * web / CLI distribution. Drives the header branch badge. Lockstep with the
+ * app-side `OkDesktopBridge` (`packages/app/src/lib/desktop-bridge-types.ts`).
+ */
+ readonly instanceLabel: string | null;
/**
* Resolve a dropped `File` to its absolute filesystem path via Electron
diff --git a/turbo.json b/turbo.json
index a179d7728..4052556e0 100644
--- a/turbo.json
+++ b/turbo.json
@@ -13,7 +13,7 @@
"dependsOn": ["^build"],
"cache": false,
"persistent": true,
- "passThroughEnv": ["OK_INSTANCE"]
+ "passThroughEnv": ["OK_INSTANCE", "OK_AUTO_INSTANCE"]
},
"build:desktop:dir": {
"dependsOn": ["build:desktop"],