Beautiful, AI-native markdown IDE and LLM wiki
TypeScript 2nd-brainagent-skillsclaudecodexcompany-braindocsknowledge-knowledge-baseknowledge-managementllmllm-wikillm-wiki-karpathymarkdownmarkdown-editormdmdxnotespkmsecond-brainskills
feat(open-knowledge): open share links in a worktree by default (#2585)
Andrew Mikofalvye43009469715
diff --git a/.changeset/share-links-open-in-worktree.md b/.changeset/share-links-open-in-worktree.mdnew file mode 100644index 000000000..3fbc33297--- /dev/null+++ b/.changeset/share-links-open-in-worktree.md@@ -0,0 +1,7 @@+---+"@inkeep/open-knowledge": minor+---++Share links for a branch you don't have checked out now default to opening in a worktree. The branch-mismatch dialog's primary action, "Open in worktree", creates (or reuses) the branch's worktree under `.ok/worktrees/<branch>` and opens it in its own window at the shared doc or folder — your current checkout, branch, and uncommitted changes stay exactly where they were. Switching the current window's branch is still available as "Switch to `<branch>`", with unchanged behavior including the post-checkout navigation gate.++This also un-dead-ends the dirty-conflict case: where uncommitted changes used to block the share entirely ("commit or stash, then open the link again"), the worktree action now works immediately. The share branch resolves wherever it lives — an existing local branch, a remote-tracking ref, or never fetched, in which case a bounded `git fetch origin <branch>` (15s cap, no credential prompts) runs first. Failures stay honest: a branch deleted upstream dismisses the dialog with the existing "no longer exists" notice, a connection failure keeps it open so you can retry or pick another action, and the new window inherits the target-existence check, so a stale branch shows the honest missing-target panel instead of silently creating an empty doc. New worktrees appear in the worktree switcher immediately.diff --git a/packages/app/package.json b/packages/app/package.jsonindex 684594050..7afaf69d8 100644--- a/packages/app/package.json+++ b/packages/app/package.json@@ -51,7 +51,7 @@{"name": "all JS chunks combined (gzipped)","path": "dist/assets/*.js",- "limit": "3.08 MB",+ "limit": "3.09 MB","gzip": true,"running": false},diff --git a/packages/app/src/components/ShareBranchSwitchDialog.dom.test.tsx b/packages/app/src/components/ShareBranchSwitchDialog.dom.test.tsxindex 00dc4e236..808401a14 100644--- a/packages/app/src/components/ShareBranchSwitchDialog.dom.test.tsx+++ b/packages/app/src/components/ShareBranchSwitchDialog.dom.test.tsx@@ -12,7 +12,11 @@*/import { afterEach, beforeEach, describe, expect, mock, test } from 'bun:test';-import type { BranchInfoResponse, CheckoutResponse } from '@inkeep/open-knowledge-core';+import type {+ BranchInfoResponse,+ CheckoutResponse,+ WorktreeCreateResult,+} from '@inkeep/open-knowledge-core';import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';import type { ReactNode } from 'react';import type { OkDesktopBridge, OkShareReceivedPayload } from '@/lib/desktop-bridge-types';@@ -63,6 +67,12 @@ mock.module('sonner', () => ({toast: { error: toastError, info: mock(() => {}), success: mock(() => {}) },}));+// The worktree leg refreshes the window's cached worktree model on create+// success. Spy at the module seam (same pattern as NewWorktreeDialog.dom.test)+// so the production store never boots against the absent test bridge.+const refreshWorktrees = mock(() => {});+mock.module('@/lib/worktree-store', () => ({ refreshWorktrees }));+const { createShareReceiveStore } = await import('@/lib/share/receive-store');const { missDialogStore } = await import('@/lib/share/miss-dialog-store');const { ShareBranchSwitchDialog } = await import('./ShareBranchSwitchDialog');@@ -73,6 +83,7 @@ interface BridgeMock {fetchTargetStatus: ReturnType<typeof mock>;awaitBranchSwitched: ReturnType<typeof mock>;open: ReturnType<typeof mock>;+ checkout: ReturnType<typeof mock>;}function makeBridge(overrides: Partial<BridgeMock> = {}): {@@ -97,6 +108,9 @@ function makeBridge(overrides: Partial<BridgeMock> = {}): {fetchTargetStatus: overrides.fetchTargetStatus ?? mock(async () => null),awaitBranchSwitched: overrides.awaitBranchSwitched ?? mock(async () => ({ ok: true as const })),open: overrides.open ?? mock(async () => undefined),+ checkout:+ overrides.checkout ??+ mock(async () => ({ ok: true as const, path: '/repo/.ok/worktrees/branch', created: true })),};const bridge = {project: {@@ -106,6 +120,9 @@ function makeBridge(overrides: Partial<BridgeMock> = {}): {awaitBranchSwitched: calls.awaitBranchSwitched,open: calls.open,},+ worktree: {+ checkout: calls.checkout,+ },} as unknown as OkDesktopBridge;return { bridge, calls };}@@ -817,3 +834,409 @@ describe('ShareBranchSwitchDialog — verdict pivot (FR9)', () => {expect(calls.fetchTargetStatus).not.toHaveBeenCalled();});});++describe('ShareBranchSwitchDialog — worktree leg', () => {+ beforeEach(() => {+ refreshWorktrees.mockClear();+ });+ afterEach(() => {+ cleanup();+ toastError.mockReset();+ });++ /**+ * Branch-info fixture spanning the ready-variant matrix: the variant derives+ * from shareTargetExists × whether conflictFiles is non-empty.+ */+ function branchInfoFor(fixture: {+ shareTargetExists: boolean;+ conflictFiles?: readonly string[];+ }): BranchInfoResponse {+ const files = fixture.conflictFiles ?? [];+ return {+ ok: true,+ currentBranch: 'main',+ currentHeadSha: 'aaaaaaa',+ detached: false,+ shareTargetExists: fixture.shareTargetExists,+ dirtyConflicts:+ files.length > 0 ? { conflicts: true, files: [...files] } : { conflicts: false, files: [] },+ };+ }++ /**+ * Installs the payload and renders the dialog. Returns `emit` so a test can+ * deliver a second share payload mid-flow — the store overwrites its+ * snapshot, which is the dialog's per-payload reset trigger.+ */+ function renderDialog(+ bridge: OkDesktopBridge,+ store: ReturnType<typeof createShareReceiveStore>,+ payload = projectBranchSwitchPayload(),+ ) {+ let emitShare: (p: OkShareReceivedPayload) => void = () => {};+ const fakeBridgeForStore = {+ onShareReceived: (cb: (p: OkShareReceivedPayload) => void) => {+ emitShare = cb;+ cb(payload);+ return () => {};+ },+ } as unknown as OkDesktopBridge;+ store.install({ bridge: fakeBridgeForStore });+ render(<ShareBranchSwitchDialog bridge={bridge} store={store} />);+ return { payload, emit: (p: OkShareReceivedPayload) => emitShare(p) };+ }++ async function findEnabledWorktreeButton(): Promise<HTMLButtonElement> {+ const btn = (await screen.findByTestId('share-branch-switch-worktree')) as HTMLButtonElement;+ await waitFor(() => {+ expect(btn.disabled).toBe(false);+ });+ return btn;+ }++ const variantFixtures = [+ { kind: 'A', label: 'target on current branch, clean tree', shareTargetExists: true },+ { kind: 'B', label: 'target missing, clean tree', shareTargetExists: false },+ {+ kind: 'C',+ label: 'target on current branch, dirty conflicts',+ shareTargetExists: true,+ conflictFiles: ['docs/notes.md'],+ },+ {+ kind: 'D',+ label: 'target missing, dirty conflicts',+ shareTargetExists: false,+ conflictFiles: ['docs/notes.md'],+ },+ ] as const;++ for (const fixture of variantFixtures) {+ test(`Open in worktree renders enabled in variant ${fixture.kind} (${fixture.label})`, async () => {+ const store = createShareReceiveStore();+ const { bridge } = makeBridge({+ fetchBranchInfo: mock(async () => branchInfoFor(fixture)),+ });+ renderDialog(bridge, store);+ await findEnabledWorktreeButton();+ });+ }++ test('variant D routes the dead end to the worktree action: new copy, switch disabled with the conflict list', async () => {+ const store = createShareReceiveStore();+ const { bridge } = makeBridge({+ fetchBranchInfo: mock(async () =>+ branchInfoFor({+ shareTargetExists: false,+ conflictFiles: ['docs/notes.md', 'package.json'],+ }),+ ),+ });+ renderDialog(bridge, store);++ await findEnabledWorktreeButton();++ // Body copy points at the enabled worktree action instead of the old+ // commit-or-stash-then-retry dead end.+ expect(screen.getByTestId('share-branch-switch-dialog').textContent).toContain(+ 'open it in a worktree to leave your changes untouched',+ );++ const switchBtn = screen.getByTestId('share-branch-switch-switch') as HTMLButtonElement;+ expect(switchBtn.disabled).toBe(true);+ const describedBy = switchBtn.getAttribute('aria-describedby');+ expect(describedBy).toBe('share-receive-branch-conflict-files');+ const conflictList = document.getElementById(describedBy ?? '');+ expect(conflictList?.textContent).toContain('docs/notes.md');+ expect(conflictList?.textContent).toContain('package.json');++ // No current-branch copy of the target exists in variant D.+ expect(screen.queryByTestId('share-branch-switch-open-current')).toBeNull();+ });++ test('a checkout that locates an existing worktree (created:false) still opens that window', async () => {+ const store = createShareReceiveStore();+ const existingPath = '/Users/alice/projects/open-knowledge/.ok/worktrees/feat-branch-x';+ const { bridge, calls } = makeBridge({+ checkout: mock(async () => ({ ok: true as const, path: existingPath, created: false })),+ });+ renderDialog(bridge, store);++ const worktreeBtn = await findEnabledWorktreeButton();+ await act(async () => {+ fireEvent.click(worktreeBtn);+ await Promise.resolve();+ });++ await waitFor(() => {+ expect(calls.open).toHaveBeenCalledTimes(1);+ });+ const openArg = calls.open.mock.calls[0]?.[0] as Record<string, unknown>;+ expect(openArg.path).toBe(existingPath);+ expect(openArg.target).toBe('new-window');+ expect(store.getSnapshot()).toBeNull();+ });++ test('an open() rejection after a successful create surfaces the toast; the worktree persists in the switcher', async () => {+ const store = createShareReceiveStore();+ const worktreePath = '/Users/alice/projects/open-knowledge/.ok/worktrees/feat-branch-x';+ const { bridge, calls } = makeBridge({+ checkout: mock(async () => ({ ok: true as const, path: worktreePath, created: true })),+ open: mock(async () => {+ throw new Error('window spawn failed');+ }),+ });+ renderDialog(bridge, store);++ const worktreeBtn = await findEnabledWorktreeButton();+ await act(async () => {+ fireEvent.click(worktreeBtn);+ await Promise.resolve();+ });++ await waitFor(() => {+ expect(calls.open).toHaveBeenCalledTimes(1);+ });+ // store.dismiss() runs synchronously before the open settles, so by the+ // time the rejection lands the snapshot is already null and the catch's+ // toast is the user's only signal — pin both.+ expect(store.getSnapshot()).toBeNull();+ await waitFor(() => {+ expect(toastError).toHaveBeenCalledWith(+ `Could not open ${worktreePath}. Try opening it manually.`,+ );+ });+ // The worktree exists on disk regardless of the failed window spawn; the+ // cache refresh already ran, so the switcher/palette list it.+ expect(refreshWorktrees).toHaveBeenCalledTimes(1);+ });++ test('a folder share rides the worktree leg with its target kind passed through', async () => {+ const store = createShareReceiveStore();+ const base = projectBranchSwitchPayload();+ const payload = {+ ...base,+ share: { ...base.share, target: { kind: 'folder' as const, folderPath: 'docs' } },+ };+ const { bridge, calls } = makeBridge();+ renderDialog(bridge, store, payload);++ const worktreeBtn = await findEnabledWorktreeButton();+ await act(async () => {+ fireEvent.click(worktreeBtn);+ await Promise.resolve();+ });++ await waitFor(() => {+ expect(calls.open).toHaveBeenCalledTimes(1);+ });+ const openArg = calls.open.mock.calls[0]?.[0] as Record<string, unknown>;+ expect(openArg.pendingDeepLinkTarget).toEqual({ kind: 'folder', path: 'docs' });+ expect(openArg.pendingBranch).toBe(payload.share.branch);+ });++ test('Open in worktree checks out the share branch and opens its window at the shared target — no CC1 wait', async () => {+ const store = createShareReceiveStore();+ const worktreePath = '/Users/alice/projects/open-knowledge/.ok/worktrees/feat-branch-x';+ const { bridge, calls } = makeBridge({+ checkout: mock(async () => ({ ok: true as const, path: worktreePath, created: true })),+ });+ const payload = projectBranchSwitchPayload();+ const fakeBridgeForStore = {+ onShareReceived: (cb: (p: OkShareReceivedPayload) => void) => {+ cb(payload);+ return () => {};+ },+ } as unknown as OkDesktopBridge;+ store.install({ bridge: fakeBridgeForStore });+ render(<ShareBranchSwitchDialog bridge={bridge} store={store} />);++ const worktreeBtn = await screen.findByTestId('share-branch-switch-worktree');+ expect((worktreeBtn as HTMLButtonElement).disabled).toBe(false);+ await act(async () => {+ fireEvent.click(worktreeBtn);+ await Promise.resolve();+ });++ expect(calls.checkout).toHaveBeenCalledTimes(1);+ expect(calls.checkout).toHaveBeenCalledWith({ branch: payload.share.branch });++ // Success opens the worktree window directly; the CC1 branch-switched gate+ // belongs to the same-window switch leg only.+ await waitFor(() => {+ expect(calls.open).toHaveBeenCalledTimes(1);+ });+ expect(calls.awaitBranchSwitched).not.toHaveBeenCalled();++ // Exact payload pin: path from the create result, its own window, worktree+ // entry point, deep-link target passthrough, and the share branch.+ expect(calls.open.mock.calls[0]?.[0]).toEqual({+ path: worktreePath,+ target: 'new-window',+ entryPoint: 'worktree',+ pendingDeepLinkTarget: { kind: 'doc', path: 'docs/notes.md' },+ pendingBranch: payload.share.branch,+ });++ // The anchor window's cached worktree model refreshes so the switcher and+ // palette list the new worktree.+ expect(refreshWorktrees).toHaveBeenCalledTimes(1);++ // Dialog dismissed after dispatch.+ expect(store.getSnapshot()).toBeNull();+ });++ test('mid-create shows in-place progress with actions disabled and Cancel live; dismissal ignores the late result', async () => {+ const store = createShareReceiveStore();+ let resolveCheckout: (result: WorktreeCreateResult) => void = () => {};+ const { bridge, calls } = makeBridge({+ checkout: mock(+ () =>+ new Promise<WorktreeCreateResult>((resolve) => {+ resolveCheckout = resolve;+ }),+ ),+ });+ renderDialog(bridge, store);++ const worktreeBtn = await findEnabledWorktreeButton();+ await act(async () => {+ fireEvent.click(worktreeBtn);+ await Promise.resolve();+ });++ const status = screen.getByTestId('share-branch-switch-creating-worktree');+ expect(status.getAttribute('role')).toBe('status');++ expect(worktreeBtn.disabled).toBe(true);+ const switchBtn = screen.getByTestId('share-branch-switch-switch') as HTMLButtonElement;+ expect(switchBtn.disabled).toBe(true);+ const openCurrentBtn = screen.getByTestId(+ 'share-branch-switch-open-current',+ ) as HTMLButtonElement;+ expect(openCurrentBtn.disabled).toBe(true);+ const cancelBtn = screen.getByTestId('share-branch-switch-cancel') as HTMLButtonElement;+ expect(cancelBtn.disabled).toBe(false);++ await act(async () => {+ fireEvent.click(cancelBtn);+ await Promise.resolve();+ });+ expect(store.getSnapshot()).toBeNull();++ // The create resolving after dismissal is stale: no window, no cache+ // refresh, no toast.+ await act(async () => {+ resolveCheckout({ ok: true, path: '/repo/.ok/worktrees/feat-branch-x', created: true });+ await Promise.resolve();+ });+ expect(calls.open).not.toHaveBeenCalled();+ expect(refreshWorktrees).not.toHaveBeenCalled();+ expect(toastError).not.toHaveBeenCalled();+ });++ test('a fetch failure keeps the dialog open with the connection toast so the user can retry', async () => {+ const store = createShareReceiveStore();+ const { bridge, calls } = makeBridge({+ checkout: mock(async () => ({ ok: false as const, reason: 'fetch-failed' as const })),+ });+ renderDialog(bridge, store);++ const worktreeBtn = await findEnabledWorktreeButton();+ await act(async () => {+ fireEvent.click(worktreeBtn);+ await Promise.resolve();+ });++ await waitFor(() => {+ expect(toastError).toHaveBeenCalledWith('Could not fetch branch. Check your connection.');+ });+ // Stay-open: the same dialog re-enables its actions for a retry or a+ // different choice.+ expect(store.getSnapshot()).not.toBeNull();+ expect(screen.getByTestId('share-branch-switch-dialog')).toBeDefined();+ await waitFor(() => {+ expect(+ (screen.getByTestId('share-branch-switch-worktree') as HTMLButtonElement).disabled,+ ).toBe(false);+ });+ expect(calls.open).not.toHaveBeenCalled();+ });++ test('a branch deleted upstream dismisses the dialog with the no-longer-exists toast', async () => {+ const store = createShareReceiveStore();+ const { bridge, calls } = makeBridge({+ checkout: mock(async () => ({ ok: false as const, reason: 'branch-not-found' as const })),+ });+ renderDialog(bridge, store);++ const worktreeBtn = await findEnabledWorktreeButton();+ await act(async () => {+ fireEvent.click(worktreeBtn);+ await Promise.resolve();+ });++ await waitFor(() => {+ expect(toastError).toHaveBeenCalledWith(+ 'Branch feat/branch-x no longer exists on the remote.',+ );+ });+ await waitFor(() => {+ expect(store.getSnapshot()).toBeNull();+ });+ expect(calls.open).not.toHaveBeenCalled();+ expect(refreshWorktrees).not.toHaveBeenCalled();+ });++ test('a second share arriving mid-create supersedes the in-flight create and ignores its result', async () => {+ const store = createShareReceiveStore();+ let resolveCheckout: (result: WorktreeCreateResult) => void = () => {};+ const { bridge, calls } = makeBridge({+ checkout: mock(+ () =>+ new Promise<WorktreeCreateResult>((resolve) => {+ resolveCheckout = resolve;+ }),+ ),+ });+ const { emit } = renderDialog(bridge, store);++ const worktreeBtn = await findEnabledWorktreeButton();+ await act(async () => {+ fireEvent.click(worktreeBtn);+ await Promise.resolve();+ });+ expect(screen.getByTestId('share-branch-switch-creating-worktree')).toBeDefined();++ const second = projectBranchSwitchPayload();+ second.share.branch = 'feat/branch-y';+ await act(async () => {+ emit(second);+ await Promise.resolve();+ });++ // The dialog re-arms for the new payload.+ await waitFor(() => {+ expect(+ (screen.getByTestId('share-branch-switch-worktree') as HTMLButtonElement).disabled,+ ).toBe(false);+ });+ expect(screen.getByTestId('share-branch-switch-metadata-branch').textContent).toContain(+ 'feat/branch-y',+ );++ // The superseded create resolving now is stale: nothing may fire, and the+ // new payload's dialog must stay up untouched.+ await act(async () => {+ resolveCheckout({ ok: true, path: '/repo/.ok/worktrees/feat-branch-x', created: true });+ await Promise.resolve();+ });+ expect(calls.open).not.toHaveBeenCalled();+ expect(refreshWorktrees).not.toHaveBeenCalled();+ expect(toastError).not.toHaveBeenCalled();+ expect(store.getSnapshot()).not.toBeNull();+ expect(screen.getByTestId('share-branch-switch-dialog')).toBeDefined();+ expect(calls.checkout).toHaveBeenCalledTimes(1);+ });+});diff --git a/packages/app/src/components/ShareBranchSwitchDialog.tsx b/packages/app/src/components/ShareBranchSwitchDialog.tsxindex 978b677c1..01b544a10 100644--- a/packages/app/src/components/ShareBranchSwitchDialog.tsx+++ b/packages/app/src/components/ShareBranchSwitchDialog.tsx@@ -10,13 +10,20 @@* alone — dismissal waits for the CC1 `branch-switched` broadcast via* `bridge.project.awaitBranchSwitched`.*+ * That CC1 gate covers the switch leg only. The primary "Open in worktree"+ * action opens the share branch in its OWN window (`worktree.checkout` →+ * `project.open`) and never recycles this window's checkout, so on create+ * success it dispatches directly — same posture as the pivot path. Do not+ * wire the CC1 wait into that leg.+ ** Cancel discipline: this window IS the editor; Cancel only dismisses the* store (no window close), so the user remains in the project on its* current branch.*/+import type { WorktreeCreateResult } from '@inkeep/open-knowledge-core';import { Trans, useLingui } from '@lingui/react/macro';-import { GitBranch, Loader2, MapPin } from 'lucide-react';+import { AppWindow, GitBranch, Loader2, MapPin } from 'lucide-react';import { useEffect, useRef, useState, useSyncExternalStore } from 'react';import { toast } from 'sonner';@@ -40,18 +47,23 @@ import {applyBranchInfo,applyCheckoutOutcome,applyVerdict,+ applyWorktreeCheckoutOutcome,type BranchSwitchDialogState,type CheckoutSideEffectReason,formatCurrentLabel,initialBranchSwitchState,+ markCreatingWorktree,markSwitching,markVerdictPending,selectBranchSwitchVariant,shouldProbeTargetStatus,+ type VerdictCellKind,+ type WorktreeCheckoutSideEffectReason,} from '@/lib/share/branch-switch-flow';import { missDialogStore } from '@/lib/share/miss-dialog-store';import { formatReceiveLog } from '@/lib/share/receive-flow';import { type ShareReceiveStore, shareReceiveStore } from '@/lib/share/receive-store';+import { refreshWorktrees } from '@/lib/worktree-store';export interface ShareBranchSwitchDialogProps {bridge: OkDesktopBridge;@@ -204,6 +216,16 @@ export function ShareBranchSwitchDialog({store.dismiss();}, [branchSwitchState, active, store]);+ // Receive-log breadcrumb: one line per resolved verdict cell, so the+ // stale-ref cohort stays countable on session inspection (actions taken from+ // a cell log `verdict_cell` alongside `branch_dialog_action` separately).+ // Fires once per resolution object — re-renders reuse the same state object,+ // and each verdict entry (including a later ff-diverged re-entry) is a new one.+ useEffect(() => {+ if (branchSwitchState.phase !== 'verdict') return;+ console.log(formatReceiveLog({ verdict_cell: branchSwitchState.resolution.kind }));+ }, [branchSwitchState]);+// CC1-driven post-checkout navigation gate. After Switch resolves// `{ok:true}` the state transitions to `awaiting-cc1-recycle`; we poll// server-info (the late-join backstop for the CC1 `branch-switched`@@ -302,12 +324,17 @@ export function ShareBranchSwitchDialog({// checkout so the doc lands); the plain switch and the diverged cell pass it// off. `pendingDoc` is the post-switch navigation target — the original path,// or `renamedTo` when a rename was accepted.- function runSwitch(pendingDoc: string, fastForward: boolean): void {+ function runSwitch(+ pendingDoc: string,+ fastForward: boolean,+ verdictCell?: VerdictCellKind,+ ): void {console.log(formatReceiveLog({branch_dialog_action: 'switch',branch_action: 'switch',branch: shareBranch,+ verdict_cell: verdictCell,}),);setBranchSwitchState((prev) => markSwitching(prev, pendingDoc));@@ -362,18 +389,18 @@ export function ShareBranchSwitchDialog({// a plain switch (no fast-forward — the receive flow never merges).function handleSwitchAndUpdate(): void {if (branchSwitchState.phase !== 'verdict') return;- runSwitch(shareTargetPath(share.target), true);+ runSwitch(shareTargetPath(share.target), true, branchSwitchState.resolution.kind);}function handleOpenRenamed(): void {if (branchSwitchState.phase !== 'verdict') return;if (branchSwitchState.resolution.kind !== 'renamed') return;- runSwitch(branchSwitchState.resolution.renamedTo, true);+ runSwitch(branchSwitchState.resolution.renamedTo, true, branchSwitchState.resolution.kind);}function handlePlainSwitchFromVerdict(): void {if (branchSwitchState.phase !== 'verdict') return;- runSwitch(shareTargetPath(share.target), false);+ runSwitch(shareTargetPath(share.target), false, branchSwitchState.resolution.kind);}function handleOpenCurrent(): void {@@ -403,6 +430,128 @@ export function ShareBranchSwitchDialog({store.dismiss();}+ // Toast copy per worktree-checkout failure reason. Mirrors the worktree-create+ // error vocabulary (NewWorktreeDialog's inline copy), adapted where that copy+ // assumes a typed-name form field. Exhaustive so a new create-failure reason+ // is a compile error here instead of a silent generic toast.+ function showWorktreeFailureToast(reason: WorktreeCheckoutSideEffectReason): void {+ switch (reason) {+ case 'branch-not-found':+ toast.error(t`Branch ${shareBranch} no longer exists on the remote.`);+ return;+ case 'fetch-failed':+ toast.error(t`Could not fetch branch. Check your connection.`);+ return;+ case 'already-checked-out':+ toast.error(t`That branch is already open in another worktree.`);+ return;+ case 'branch-exists':+ toast.error(+ t`A branch named ${shareBranch} already exists. Open its worktree from the switcher instead.`,+ );+ return;+ case 'path-exists':+ toast.error(t`A worktree folder for ${shareBranch} already exists.`);+ return;+ case 'no-git':+ toast.error(t`This project isn't a git repository, so worktrees aren't available.`);+ return;+ case 'invalid-branch':+ toast.error(t`${shareBranch} isn't a valid branch name.`);+ return;+ case 'proxy-null':+ case 'error':+ toast.error(t`Could not open ${shareBranch} in a worktree. Try again.`);+ return;+ default: {+ const _exhaustive: never = reason;+ throw new Error(`Unhandled worktree failure reason: ${String(_exhaustive)}`);+ }+ }+ }++ // Apply a worktree-checkout result (or IPC rejection as `null`) through the+ // pure reducer. The updater's identity guard makes a late result a no-op —+ // after a Cancel or a second share payload's reset, nothing below fires+ // because neither branch's capture variable gets set.+ function applyWorktreeOutcome(result: WorktreeCreateResult | null): void {+ let failureReason: WorktreeCheckoutSideEffectReason | null = null;+ let shouldDismiss = false;+ let openPath: string | null = null;+ setBranchSwitchState((prev) => {+ const { state: next, sideEffect } = applyWorktreeCheckoutOutcome(prev, result);+ if (sideEffect) {+ failureReason = sideEffect.reason;+ shouldDismiss = next.phase === 'dismissed';+ }+ if (next.phase === 'opening-worktree') {+ openPath = next.path;+ }+ return next;+ });+ if (failureReason !== null) {+ console.log(+ formatReceiveLog({+ branch_dialog_action: `open-worktree-failed:${failureReason}`,+ branch: shareBranch,+ }),+ );+ showWorktreeFailureToast(failureReason);+ }+ if (openPath !== null) {+ // The anchor window's cached worktree model is stale now (a worktree was+ // created or located) — refresh so this window's switcher + palette show it.+ refreshWorktrees();+ const target = openPath;+ void bridge.project+ .open({+ path: target,+ target: 'new-window',+ entryPoint: 'worktree',+ pendingDeepLinkTarget: {+ kind: share.target.kind,+ path: shareTargetPath(share.target),+ },+ pendingBranch: shareBranch,+ })+ .catch((err) => {+ // The dialog dismisses synchronously below; without a toast a reject+ // here strands the user with no new window and no signal. The+ // worktree itself persists, reachable from the switcher.+ console.warn(+ '[receive] worktree-open-failed branch_dialog_action=open-worktree',+ err instanceof Error ? err.message : err,+ );+ toast.error(t`Could not open ${target}. Try opening it manually.`);+ });+ store.dismiss();+ }+ if (shouldDismiss) store.dismiss();+ }++ function handleOpenWorktree(): void {+ if (branchSwitchState.phase !== 'ready') return;+ console.log(+ formatReceiveLog({+ branch_dialog_action: 'open-worktree',+ branch: shareBranch,+ }),+ );+ setBranchSwitchState(markCreatingWorktree);+ void bridge.worktree+ .checkout({ branch: shareBranch })+ .then((result) => {+ applyWorktreeOutcome(result);+ })+ .catch((err) => {+ console.warn(+ '[receive] worktree-checkout rejected branch_dialog_action=open-worktree',+ err instanceof Error ? err.message : err,+ );+ applyWorktreeOutcome(null);+ });+ }+function handlePivot(): void {if (branchSwitchState.phase !== 'branch-in-other-worktree') return;const target = branchSwitchState.otherWorktreePath;@@ -433,22 +582,34 @@ export function ShareBranchSwitchDialog({// Cancel: this window IS the editor; closing it would close the user's// session. store.dismiss() leaves the editor open on its current branch.function handleCancel(): void {- console.log(formatReceiveLog({ branch_dialog_action: 'cancel' }));+ console.log(+ formatReceiveLog({+ branch_dialog_action: 'cancel',+ verdict_cell:+ branchSwitchState.phase === 'verdict' ? branchSwitchState.resolution.kind : undefined,+ }),+ );store.dismiss();}const variant =- branchSwitchState.phase === 'ready' || branchSwitchState.phase === 'switching'+ branchSwitchState.phase === 'ready' ||+ branchSwitchState.phase === 'switching' ||+ branchSwitchState.phase === 'creating-worktree'? selectBranchSwitchVariant(branchSwitchState.info): null;const currentLabel =- branchSwitchState.phase === 'ready' || branchSwitchState.phase === 'switching'+ branchSwitchState.phase === 'ready' ||+ branchSwitchState.phase === 'switching' ||+ branchSwitchState.phase === 'creating-worktree'? formatCurrentLabel(branchSwitchState.info): (payloadCurrentBranch ?? 'HEAD');const switching =branchSwitchState.phase === 'switching' || branchSwitchState.phase === 'awaiting-cc1-recycle';+ const creating = branchSwitchState.phase === 'creating-worktree';const openCurrentLabel = t`Open in current branch`;- const switchLabel = t`Open in ${shareBranch}`;+ const switchLabel = t`Switch to ${shareBranch}`;+ const worktreeLabel = t`Open in worktree`;const conflictListId = 'share-receive-branch-conflict-files';const isLoading = branchSwitchState.phase === 'loading';const isError = branchSwitchState.phase === 'error';@@ -603,8 +764,8 @@ export function ShareBranchSwitchDialog({<code className="rounded-sm bg-muted px-1 py-0.5 text-foreground/80">{shareBranch}</code>- . You have uncommitted changes that prevent switching. Commit or stash your changes,- then open the share link again.+ . You have uncommitted changes that prevent switching here — open it in a worktree+ to leave your changes untouched.</Trans></p>) : variant?.kind === 'B' ? (@@ -667,6 +828,17 @@ export function ShareBranchSwitchDialog({<Trans>Switching branches</Trans></p>) : null}+ {creating ? (+ <p+ className="mt-3 flex items-center gap-2 text-sm text-muted-foreground"+ data-testid="share-branch-switch-creating-worktree"+ role="status"+ aria-live="polite"+ >+ <Loader2 className="h-4 w-4 animate-spin" aria-hidden="true" />+ <Trans>Opening worktree</Trans>+ </p>+ ) : null}</DialogBody><DialogFooter className="sm:justify-between"><Button@@ -714,7 +886,7 @@ export function ShareBranchSwitchDialog({variant="outline"className="font-mono uppercase"onClick={handleOpenCurrent}- disabled={switching}+ disabled={switching || creating}data-testid="share-branch-switch-open-current"><MapPin className="size-3.5" aria-hidden />@@ -722,9 +894,10 @@ export function ShareBranchSwitchDialog({</Button>) : null}<Button+ variant="outline"onClick={handleSwitch}- disabled={!variant?.switchEnabled || switching}- aria-disabled={!variant?.switchEnabled || switching}+ disabled={!variant?.switchEnabled || switching || creating}+ aria-disabled={!variant?.switchEnabled || switching || creating}aria-describedby={variant && !variant.switchEnabled && variant.conflictingFiles.length > 0? conflictListId@@ -744,6 +917,23 @@ export function ShareBranchSwitchDialog({</>)}</Button>+ <Button+ onClick={handleOpenWorktree}+ disabled={!variant || switching || creating}+ data-testid="share-branch-switch-worktree"+ >+ {creating ? (+ <>+ <Loader2 className="size-3.5 animate-spin" aria-hidden="true" />+ {worktreeLabel}+ </>+ ) : (+ <>+ <AppWindow className="size-3.5" aria-hidden />+ {worktreeLabel}+ </>+ )}+ </Button></div>)}</DialogFooter>diff --git a/packages/app/src/lib/desktop-bridge-types.ts b/packages/app/src/lib/desktop-bridge-types.tsindex 09a11c87d..45c591a2e 100644--- a/packages/app/src/lib/desktop-bridge-types.ts+++ b/packages/app/src/lib/desktop-bridge-types.ts@@ -1125,7 +1125,9 @@ export interface OkDesktopBridge {/*** Worktree selector (worktree = window). `list` enumerates the current* project's local branches + their worktrees; `create` creates or locates a- * branch's worktree under `<mainRoot>/.ok/worktrees/`. The renderer opens the+ * branch's worktree under `<mainRoot>/.ok/worktrees/`; `checkout` is the+ * share-receive arm (resolves where the branch lives — fetching from+ * `origin` when needed — then create-or-locates). The renderer opens the* worktree window via `project.open({ entryPoint: 'worktree' })`. Canonical* contract in `packages/desktop/src/shared/bridge-contract.ts`. Renderer* consumers: `ProjectSwitcher` + `NewWorktreeDialog`.@@ -1133,6 +1135,7 @@ export interface OkDesktopBridge {worktree: {list(): Promise<WorktreeListResult>;create(request: WorktreeCreateRequest): Promise<WorktreeCreateResult>;+ checkout(request: { branch: string }): Promise<WorktreeCreateResult>;};/**diff --git a/packages/app/src/lib/share/branch-switch-flow.test.ts b/packages/app/src/lib/share/branch-switch-flow.test.tsindex 23d283283..c83266c36 100644--- a/packages/app/src/lib/share/branch-switch-flow.test.ts+++ b/packages/app/src/lib/share/branch-switch-flow.test.ts@@ -6,10 +6,12 @@ import {applyBranchInfo,applyCheckoutOutcome,applyVerdict,+ applyWorktreeCheckoutOutcome,type BranchSwitchDialogState,classifyCheckoutOutcome,formatCurrentLabel,initialBranchSwitchState,+ markCreatingWorktree,markSwitching,markVerdictPending,selectBranchSwitchVariant,@@ -624,3 +626,180 @@ describe('applyCheckoutOutcome — ff-diverged transition', () => {expect(result.sideEffect).toBeUndefined();});});++describe('markCreatingWorktree (worktree leg)', () => {+ test('ready → creating-worktree, preserving info for the stay-open failure fallback', () => {+ const ready: BranchSwitchDialogState = { phase: 'ready', info: cleanInfo() };+ expect(markCreatingWorktree(ready)).toEqual({+ phase: 'creating-worktree',+ info: cleanInfo(),+ });+ });+});++describe('applyWorktreeCheckoutOutcome (worktree leg)', () => {+ const creating: BranchSwitchDialogState = { phase: 'creating-worktree', info: cleanInfo() };++ test('successful create transitions to opening-worktree carrying the worktree path (no toast)', () => {+ const result = applyWorktreeCheckoutOutcome(creating, {+ ok: true,+ path: '/repo/.ok/worktrees/feat-x',+ created: true,+ });+ expect(result.state).toEqual({+ phase: 'opening-worktree',+ path: '/repo/.ok/worktrees/feat-x',+ });+ expect(result.sideEffect).toBeUndefined();+ });++ test('locate (created: false) also transitions to opening-worktree — the existing window opens, no duplicate', () => {+ const result = applyWorktreeCheckoutOutcome(creating, {+ ok: true,+ path: '/repo/.ok/worktrees/feat-x',+ created: false,+ });+ expect(result.state).toEqual({+ phase: 'opening-worktree',+ path: '/repo/.ok/worktrees/feat-x',+ });+ expect(result.sideEffect).toBeUndefined();+ });++ test('fetch-failed stays open: back to ready with the connection-toast signal (user can retry)', () => {+ const result = applyWorktreeCheckoutOutcome(creating, { ok: false, reason: 'fetch-failed' });+ expect(result.state).toEqual({ phase: 'ready', info: cleanInfo() });+ expect(result.sideEffect).toEqual({ kind: 'toast', reason: 'fetch-failed' });+ });++ test('branch-not-found dismisses with the branch-gone toast signal (terminal, mirrors the switch leg)', () => {+ const result = applyWorktreeCheckoutOutcome(creating, {+ ok: false,+ reason: 'branch-not-found',+ });+ expect(result.state).toEqual({ phase: 'dismissed', reason: 'branch-not-found' });+ expect(result.sideEffect).toEqual({ kind: 'toast', reason: 'branch-not-found' });+ });++ test('every other create refusal stays open with a reason-specific toast signal', () => {+ const reasons = [+ 'invalid-branch',+ 'branch-exists',+ 'already-checked-out',+ 'path-exists',+ 'no-git',+ 'error',+ ] as const;+ for (const reason of reasons) {+ const result = applyWorktreeCheckoutOutcome(creating, { ok: false, reason });+ expect(result.state).toEqual({ phase: 'ready', info: cleanInfo() });+ expect(result.sideEffect).toEqual({ kind: 'toast', reason });+ }+ });++ test('null (IPC rejection) stays open with the proxy-null toast signal', () => {+ const result = applyWorktreeCheckoutOutcome(creating, null);+ expect(result.state).toEqual({ phase: 'ready', info: cleanInfo() });+ expect(result.sideEffect).toEqual({ kind: 'toast', reason: 'proxy-null' });+ });+});++describe('worktree leg — stale-result and cross-phase identity guards', () => {+ test('a checkout result landing in any non-create phase is identity with no ghost toast', () => {+ // Dismiss-mid-create and second-share supersession both land here: the+ // per-payload reset rewinds to loading before a late result arrives, and+ // ready / dismissed / opening-worktree cover a dialog that already moved+ // on. None may mutate state or fire a toast.+ const wrongPhases: BranchSwitchDialogState[] = [+ { phase: 'loading' },+ { phase: 'ready', info: cleanInfo() },+ { phase: 'verdict-pending', info: cleanInfo() },+ { phase: 'verdict', info: cleanInfo(), resolution: { kind: 'on-origin' } },+ { phase: 'switching', info: cleanInfo(), pendingDoc: 'docs/foo.md' },+ { phase: 'awaiting-cc1-recycle', pendingDoc: 'docs/foo.md' },+ {+ phase: 'branch-in-other-worktree',+ info: cleanInfo(),+ otherWorktreePath: '/tmp/wt/feat-bar',+ pendingDoc: 'docs/foo.md',+ },+ { phase: 'opening-worktree', path: '/repo/.ok/worktrees/feat-x' },+ { phase: 'error' },+ { phase: 'dismissed', reason: 'branch-not-found' },+ ];+ for (const state of wrongPhases) {+ const lateSuccess = applyWorktreeCheckoutOutcome(state, {+ ok: true,+ path: '/repo/.ok/worktrees/feat-x',+ created: true,+ });+ expect(lateSuccess.state).toBe(state);+ expect(lateSuccess.sideEffect).toBeUndefined();++ const lateFailure = applyWorktreeCheckoutOutcome(state, {+ ok: false,+ reason: 'fetch-failed',+ });+ expect(lateFailure.state).toBe(state);+ expect(lateFailure.sideEffect).toBeUndefined();++ const lateNull = applyWorktreeCheckoutOutcome(state, null);+ expect(lateNull.state).toBe(state);+ expect(lateNull.sideEffect).toBeUndefined();+ }+ });++ test('markCreatingWorktree only fires from ready — identity everywhere else, including verdict cells', () => {+ const nonReady: BranchSwitchDialogState[] = [+ { phase: 'loading' },+ { phase: 'verdict-pending', info: cleanInfo() },+ { phase: 'verdict', info: cleanInfo(), resolution: { kind: 'diverged' } },+ { phase: 'switching', info: cleanInfo(), pendingDoc: 'docs/foo.md' },+ { phase: 'awaiting-cc1-recycle', pendingDoc: 'docs/foo.md' },+ {+ phase: 'branch-in-other-worktree',+ info: cleanInfo(),+ otherWorktreePath: '/tmp/wt/feat-bar',+ pendingDoc: 'docs/foo.md',+ },+ { phase: 'creating-worktree', info: cleanInfo() },+ { phase: 'opening-worktree', path: '/repo/.ok/worktrees/feat-x' },+ { phase: 'error' },+ { phase: 'dismissed', reason: 'branch-not-found' },+ ];+ for (const state of nonReady) {+ expect(markCreatingWorktree(state)).toBe(state);+ }+ });++ test('creating-worktree ignores unrelated late transitions (branch-info, verdict, switch-leg checkout)', () => {+ const creating: BranchSwitchDialogState = { phase: 'creating-worktree', info: cleanInfo() };+ expect(applyBranchInfo(creating, cleanInfo())).toBe(creating);+ expect(applyBranchInfo(creating, null)).toBe(creating);+ expect(markSwitching(creating, 'docs/foo.md')).toBe(creating);+ expect(markVerdictPending(creating)).toBe(creating);+ expect(applyVerdict(creating, { verdict: 'on-origin' })).toBe(creating);+ const lateCheckout = applyCheckoutOutcome(creating, { ok: true });+ expect(lateCheckout.state).toBe(creating);+ expect(lateCheckout.sideEffect).toBeUndefined();+ });++ test('opening-worktree is a reducer terminal — every transition is identity', () => {+ // The component opens the window and dismisses from here; only the+ // per-payload reset may replace this state. A late branch-info, verdict,+ // or checkout response must not yank the dialog back mid-open.+ const opening: BranchSwitchDialogState = {+ phase: 'opening-worktree',+ path: '/repo/.ok/worktrees/feat-x',+ };+ expect(applyBranchInfo(opening, cleanInfo())).toBe(opening);+ expect(applyBranchInfo(opening, null)).toBe(opening);+ expect(markSwitching(opening, 'docs/foo.md')).toBe(opening);+ expect(markVerdictPending(opening)).toBe(opening);+ expect(applyVerdict(opening, null)).toBe(opening);+ expect(markCreatingWorktree(opening)).toBe(opening);+ const lateCheckout = applyCheckoutOutcome(opening, null);+ expect(lateCheckout.state).toBe(opening);+ expect(lateCheckout.sideEffect).toBeUndefined();+ });+});diff --git a/packages/app/src/lib/share/branch-switch-flow.ts b/packages/app/src/lib/share/branch-switch-flow.tsindex 7c6eb9936..ff936f49f 100644--- a/packages/app/src/lib/share/branch-switch-flow.ts+++ b/packages/app/src/lib/share/branch-switch-flow.ts@@ -8,6 +8,9 @@* to the share's branch.* - `CheckoutResponse` from `POST /api/git/checkout` — outcome of the* server-side checkout call once the user clicks "Switch".+ * - `WorktreeCreateResult` from the desktop bridge's `worktree.checkout` —+ * outcome of the share-scoped worktree create-or-locate once the user+ * clicks "Open in worktree".** The state-matrix logic lives here so it's testable without mounting a* React tree. The dialog component renders the variant returned by@@ -19,12 +22,19 @@* settled before the doc opens. `classifyCheckoutOutcome` returns* `'await-cc1'` for this case; the dialog then waits on that signal before* opening the doc.+ *+ * That CC1 gate covers the switch leg only — it exists because a same-window+ * checkout recycles the CRDT session under the open doc. The worktree leg+ * (`markCreatingWorktree` / `applyWorktreeCheckoutOutcome`) opens the share+ * branch in its OWN window and never touches the anchor window's checkout, so+ * on success it opens directly with no CC1 wait, like the pivot leg.*/import type {BranchInfoResponse,CheckoutResponse,ShareTargetStatusResponse,+ WorktreeCreateResult,} from '@inkeep/open-knowledge-core';/**@@ -259,6 +269,13 @@ type VerdictResolution =| { readonly kind: 'never-on-branch' }| { readonly kind: 'diverged' };+/**+ * Verdict-cell kinds, exported for the receive-log vocabulary+ * (`ReceiveLogFields.verdict_cell`) so verdict-cell renders and their actions+ * are countable in session logs without duplicating the resolution union.+ */+export type VerdictCellKind = VerdictResolution['kind'];+export type BranchSwitchDialogState =| { readonly phase: 'loading' }| { readonly phase: 'ready'; readonly info: BranchInfoResponse }@@ -301,6 +318,29 @@ export type BranchSwitchDialogState =readonly otherWorktreePath: string;readonly pendingDoc: string;}+ | {+ /**+ * "Open in worktree" was clicked; the bridge's `worktree.checkout`+ * call is in flight. `info` is preserved so failures can fall back to+ * `ready` (retry / pick another action) without re-fetching+ * branch-info. Dismissal mid-create is safe: a late result is ignored+ * by the phase guard on `applyWorktreeCheckoutOutcome`, and a create+ * that completes anyway just leaves the worktree on disk, reachable+ * from the worktree switcher.+ */+ readonly phase: 'creating-worktree';+ readonly info: BranchInfoResponse;+ }+ | {+ /**+ * Worktree create-or-locate succeeded. The dialog opens `path` in a+ * new window and dismisses — directly, with NO CC1 `branch-switched`+ * wait: that gate exists for same-window checkout recycles, and this+ * leg never touches the anchor window's checkout (pivot precedent).+ */+ readonly phase: 'opening-worktree';+ readonly path: string;+ }| { readonly phase: 'error' }| { readonly phase: 'dismissed'; readonly reason: 'branch-not-found' };@@ -337,6 +377,20 @@ export function markSwitching(return { phase: 'switching', info: state.info, pendingDoc };}+/**+ * Transition to `creating-worktree` when the user clicks "Open in worktree".+ * Fires from `ready` only — the worktree action is a ready-phase affordance,+ * enabled in every variant including the dirty-conflict cells, because+ * worktree creation never touches the root working tree. The verdict cells+ * keep their own checkout-based actions and don't offer it. From every other+ * phase this is an identity no-op so a delayed click can't race a checkout+ * or create already in flight.+ */+export function markCreatingWorktree(state: BranchSwitchDialogState): BranchSwitchDialogState {+ if (state.phase !== 'ready') return state;+ return { phase: 'creating-worktree', info: state.info };+}+/*** True when the branch-switch dialog should replace its plain-switch offer* with a fetch-backed verdict. Fires only on the "switch to recover" variant@@ -499,3 +553,73 @@ export function applyCheckoutOutcome(sideEffect: { kind: 'toast', reason: outcome.reason },};}++/**+ * Discriminated reason for the toast side-effect the dialog renders when+ * `applyWorktreeCheckoutOutcome` leaves `creating-worktree` on a failure.+ * Derived from the bridge's failure union so a new create-failure reason+ * automatically widens this vocabulary (and the receive-log failure variants+ * built on it) instead of silently vanishing. `proxy-null` mirrors the switch+ * leg: the IPC call itself rejected, so there is no typed reason to surface.+ */+export type WorktreeCheckoutSideEffectReason =+ | 'proxy-null'+ | Extract<WorktreeCreateResult, { ok: false }>['reason'];++/**+ * Pair of `{state, sideEffect?}` returned by `applyWorktreeCheckoutOutcome`,+ * mirroring `ApplyCheckoutOutcomeResult`: the reducer stays pure and the+ * dialog component fires `toast(...)` from the typed signal.+ */+export interface ApplyWorktreeCheckoutOutcomeResult {+ readonly state: BranchSwitchDialogState;+ readonly sideEffect?: {+ readonly kind: 'toast';+ readonly reason: WorktreeCheckoutSideEffectReason;+ };+}++/**+ * Apply a `worktree.checkout` result (or IPC rejection, passed as `null`) to+ * the dialog state:+ *+ * - `{ok: true}` → `opening-worktree` (dialog opens the worktree path+ * in a new window and dismisses; no toast). Applies+ * to locate too (`created: false`) — an existing+ * worktree's window opens instead of a duplicate.+ * - `branch-not-found` → `dismissed` + toast (terminal: the branch is gone+ * upstream, same semantics as the switch leg)+ * - other failures → `ready` + toast keyed on the reason, so the dialog+ * stays open for a retry or another action+ * (`fetch-failed` maps to the connection copy)+ * - `null` → `ready` + proxy-null toast+ *+ * Only callable from `creating-worktree` — identity (no side effect) from+ * every other phase, so a result landing after dismissal, or after a second+ * share payload reset the dialog, can't mutate state or fire a ghost toast.+ */+export function applyWorktreeCheckoutOutcome(+ state: BranchSwitchDialogState,+ result: WorktreeCreateResult | null,+): ApplyWorktreeCheckoutOutcomeResult {+ if (state.phase !== 'creating-worktree') return { state };+ if (result === null) {+ return {+ state: { phase: 'ready', info: state.info },+ sideEffect: { kind: 'toast', reason: 'proxy-null' },+ };+ }+ if (result.ok) {+ return { state: { phase: 'opening-worktree', path: result.path } };+ }+ if (result.reason === 'branch-not-found') {+ return {+ state: { phase: 'dismissed', reason: 'branch-not-found' },+ sideEffect: { kind: 'toast', reason: 'branch-not-found' },+ };+ }+ return {+ state: { phase: 'ready', info: state.info },+ sideEffect: { kind: 'toast', reason: result.reason },+ };+}diff --git a/packages/app/src/lib/share/receive-flow.test.ts b/packages/app/src/lib/share/receive-flow.test.tsindex b47b00825..57fd7623a 100644--- a/packages/app/src/lib/share/receive-flow.test.ts+++ b/packages/app/src/lib/share/receive-flow.test.ts@@ -201,4 +201,38 @@ describe('formatReceiveLog', () => {formatReceiveLog({ branch_dialog_action: 'branch-switch-complete', branch: 'feat/x' }),).toBe('[receive] branch=feat/x branch_dialog_action=branch-switch-complete');});++ test('emits the worktree-leg action and its reason-suffixed failure variants', () => {+ expect(formatReceiveLog({ branch_dialog_action: 'open-worktree', branch: 'feat/x' })).toBe(+ '[receive] branch=feat/x branch_dialog_action=open-worktree',+ );+ expect(+ formatReceiveLog({+ branch_dialog_action: 'open-worktree-failed:fetch-failed',+ branch: 'feat/x',+ }),+ ).toBe('[receive] branch=feat/x branch_dialog_action=open-worktree-failed:fetch-failed');+ expect(+ formatReceiveLog({ branch_dialog_action: 'open-worktree-failed:branch-not-found' }),+ ).toBe('[receive] branch_dialog_action=open-worktree-failed:branch-not-found');+ });++ test('emits verdict_cell so verdict-cell renders are countable', () => {+ expect(formatReceiveLog({ verdict_cell: 'on-origin', branch: 'feat/x' })).toBe(+ '[receive] branch=feat/x verdict_cell=on-origin',+ );+ expect(formatReceiveLog({ verdict_cell: 'never-on-branch' })).toBe(+ '[receive] verdict_cell=never-on-branch',+ );+ });++ test('a verdict-cell action is countable via the branch_dialog_action + verdict_cell pair', () => {+ expect(+ formatReceiveLog({+ branch_dialog_action: 'switch',+ branch: 'feat/x',+ verdict_cell: 'renamed',+ }),+ ).toBe('[receive] branch=feat/x branch_dialog_action=switch verdict_cell=renamed');+ });});diff --git a/packages/app/src/lib/share/receive-flow.ts b/packages/app/src/lib/share/receive-flow.tsindex 9bdae5d42..994e60277 100644--- a/packages/app/src/lib/share/receive-flow.ts+++ b/packages/app/src/lib/share/receive-flow.ts@@ -15,6 +15,7 @@ import type {OkShareReceivedPayload,ShareFolderValidationResult,} from '@/lib/desktop-bridge-types';+import type { VerdictCellKind, WorktreeCheckoutSideEffectReason } from './branch-switch-flow';export {type BranchMatchOutcome,@@ -127,6 +128,12 @@ export type BranchAction = 'switch' | 'fallback' | 'fetch-failed' | 'open-curren* `branch-switch-timeout` are the terminal outcomes after dismissal gates* on the CC1 `branch-switched` broadcast — dismissal MUST NOT fire on* checkout HTTP 200 alone.+ *+ * `open-worktree` is the worktree-leg click; its failure variants carry the+ * toast reason as a suffix (`open-worktree-failed:fetch-failed`, ...) so+ * failure classes stay countable without a second field. A `switch` logged+ * together with `verdict_cell` records a verdict-cell action — see+ * `ReceiveLogFields.verdict_cell`.*/export type BranchDialogAction =| 'switch'@@ -134,7 +141,9 @@ export type BranchDialogAction =| 'cancel'| 'pivot-to-other-worktree'| 'branch-switch-complete'- | 'branch-switch-timeout';+ | 'branch-switch-timeout'+ | 'open-worktree'+ | `open-worktree-failed:${WorktreeCheckoutSideEffectReason}`;export interface ReceiveLogFields {readonly q2_path?: 'clone' | 'local';@@ -151,6 +160,13 @@ export interface ReceiveLogFields {readonly doc_check?: CheckTargetExistsResult;/** User-visible action taken on the branch-switch dialog. */readonly branch_dialog_action?: BranchDialogAction;+ /**+ * Verdict cell the stale-ref recovery flow resolved to. Logged alone when+ * the cell renders; logged alongside `branch_dialog_action` when the user+ * acts from that cell — the pair makes the verdict-cell cohort and its+ * per-cell action distribution countable on session inspection.+ */+ readonly verdict_cell?: VerdictCellKind;}/**@@ -171,5 +187,6 @@ export function formatReceiveLog(fields: ReceiveLogFields): string {if (fields.branch_dialog_action !== undefined) {parts.push(`branch_dialog_action=${fields.branch_dialog_action}`);}+ if (fields.verdict_cell !== undefined) parts.push(`verdict_cell=${fields.verdict_cell}`);return parts.join(' ');}diff --git a/packages/app/src/locales/en/messages.json b/packages/app/src/locales/en/messages.jsonindex a4727578a..729aa7506 100644--- a/packages/app/src/locales/en/messages.json+++ b/packages/app/src/locales/en/messages.json@@ -560,6 +560,13 @@"DId6MT": ["Project-level pages with no outgoing graph edges."],"DJd000": ["Activate the previous editor tab."],"DPfwMq": ["Done"],+ "DTI-fp": [+ "This ",+ ["targetNoun"],+ " only exists on branch <0>",+ ["shareBranch"],+ "</0>. You have uncommitted changes that prevent switching here — open it in a worktree to leave your changes untouched."+ ],"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."],@@ -814,6 +821,7 @@"JWsZlx": ["Open a project to edit."],"JZ8cO6": ["Light, dark, or follow the OS."],"Jejur6": ["Couldn't load document"],+ "JfPuv7": [["shareBranch"], " isn't a valid branch name."],"Jhj_lh": ["Modify the link target, anchor, and display label."],"JkCD2u": ["Sync paused — you don't have permission to push to this repo"],"JmfgFc": ["(a worktree of ", ["0"], ")"],@@ -1068,6 +1076,7 @@"PR9FSv": ["Move to the next visual-editor find result."],"PRnH8G": ["of ", ["0"]],"PVUn_c": ["Open folder"],+ "PZtgO0": ["Opening worktree"],"P_bX4O": ["How to set up"],"PdA9NZ": [["ahead"], " ahead"],"PdJZ5p": ["No skills yet."],@@ -1261,6 +1270,7 @@"VIwCaD": ["Entry"],"VM7H66": ["This file is binary and can't be shown as text."],"VNgKZz": ["Advanced settings"],+ "VTulZj": ["Open in worktree"],"VU3Nrn": ["Missing"],"VUijjF": ["Embed an image with optional alt text."],"VYd_YA": ["Open an existing project folder from disk."],@@ -1292,6 +1302,7 @@],"W8vpBM": ["starter pack"],"W9_Bub": ["Local changes overlap with incoming sync"],+ "WALN45": ["Switch to ", ["shareBranch"]],"WHPvOb": ["All files are hidden by view filters."],"WL6puM": ["Path resolves outside project"],"WMIKXK": [@@ -1348,13 +1359,6 @@"Xl-UUg": ["guides/install or https://example.com"],"XmJfZT": ["name"],"XnlF3W": ["Add the next matching source selection."],- "XnoA1k": [- "This ",- ["targetNoun"],- " only exists on branch <0>",- ["shareBranch"],- "</0>. You have uncommitted changes that prevent switching. Commit or stash your changes, then open the share link again."- ],"XopE_I": ["Failed to parse backlinks error response (HTTP ", ["status"], ")"],"XpIZmv": ["Fenced code block with monospace text."],"XqNHcm": ["Couldn't update skill targets: ", ["0"]],@@ -1458,7 +1462,6 @@["currentLabel"],"</1>."],- "_BthEY": ["Open in ", ["shareBranch"]],"_NX6gG": ["Managing project AI tools is unavailable in this build."],"_PACVa": ["Release notes"],"_PBJRl": ["Add at least one letter or number."],@@ -1554,6 +1557,7 @@"cF9DyA": ["Reconnecting after server restart"],"cIptmH": ["In the Claude Desktop App"],"cKjLuT": ["(project + user)"],+ "cN1Gcp": ["A worktree folder for ", ["shareBranch"], " already exists."],"cOSAfL": ["No repositories found on your GitHub account."],"cOrTMo": ["Your share link is ready below."],"cRHuuI": ["Couldn't copy path"],@@ -1631,6 +1635,7 @@"e4PbgC": ["Duplicate the file-tree item copied from the Files sidebar."],"e8L17t": ["A non-empty folder already exists at this path. Pick a different folder."],"e8zRrb": ["Show Files"],+ "e8zYa8": ["Could not open ", ["shareBranch"], " in a worktree. Try again."],"eBIT9h": ["Paste failed.", ["restoreSuffix"]],"eFJkVt": ["Clone failed: ", ["cloneError"]],"eG8Jsg": ["Toggle source tab focus mode"],@@ -1729,6 +1734,11 @@"gwykHF": ["This doc hasn't synced to GitHub yet. The link will work after the next sync."],"h-AdvS": ["The folders and templates are already here, so there's nothing to add."],"h06R3C": ["No pages are missing outgoing graph links."],+ "h3QZcB": [+ "A branch named ",+ ["shareBranch"],+ " already exists. Open its worktree from the switcher instead."+ ],"h6EvY-": ["This will replace the current document content with the version from <0>",["relative"],diff --git a/packages/app/src/locales/en/messages.po b/packages/app/src/locales/en/messages.poindex 77a7b7f06..f0b05ff89 100644--- a/packages/app/src/locales/en/messages.po+++ b/packages/app/src/locales/en/messages.po@@ -409,6 +409,10 @@ msgstr "{seconds}s ago"msgid "{settingsDescriptorLabel} properties"msgstr "{settingsDescriptorLabel} properties"+#: src/components/ShareBranchSwitchDialog.tsx+msgid "{shareBranch} isn't a valid branch name."+msgstr "{shareBranch} isn't a valid branch name."+#: src/components/CreatedItemsList.tsxmsgid "{skillCount, plural, one {skill} other {skills}}"msgstr "{skillCount, plural, one {skill} other {skills}}"@@ -504,6 +508,10 @@ msgstr "<0>ok</0> won't run in external terminals until you add it later from thmsgid "📝 or assets/icon.png"msgstr "📝 or assets/icon.png"+#: src/components/ShareBranchSwitchDialog.tsx+msgid "A branch named {shareBranch} already exists. Open its worktree from the switcher instead."+msgstr "A branch named {shareBranch} already exists. Open its worktree from the switcher instead."+#: src/components/NewWorktreeDialog.tsxmsgid "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."@@ -581,6 +589,10 @@ msgstr "A template named <0>{trimmedSlug}</0> already exists here. Saving createmsgid "A title, description, tags — anything that describes this folder."msgstr "A title, description, tags — anything that describes this folder."+#: src/components/ShareBranchSwitchDialog.tsx+msgid "A worktree folder for {shareBranch} already exists."+msgstr "A worktree folder for {shareBranch} already exists."+#: src/components/NewWorktreeDialog.tsxmsgid "A worktree folder for that branch already exists."msgstr "A worktree folder for that branch already exists."@@ -1844,6 +1856,10 @@ msgstr "Could not load templates. Try again later."msgid "Could not move \"{targetName}\" to the Trash. Do you want to permanently delete instead?"msgstr "Could not move \"{targetName}\" to the Trash. Do you want to permanently delete instead?"+#: src/components/ShareBranchSwitchDialog.tsx+msgid "Could not open {shareBranch} in a worktree. Try again."+msgstr "Could not open {shareBranch} in a worktree. Try again."+#: src/components/ShareBranchSwitchDialog.tsxmsgid "Could not open {target}. Try opening it manually."msgstr "Could not open {target}. Try opening it manually."@@ -4981,14 +4997,14 @@ msgstr "Open folder on disk"msgid "Open graph"msgstr "Open graph"-#: src/components/ShareBranchSwitchDialog.tsx-msgid "Open in {shareBranch}"-msgstr "Open in {shareBranch}"-#: src/components/ShareBranchSwitchDialog.tsxmsgid "Open in current branch"msgstr "Open in current branch"+#: src/components/ShareBranchSwitchDialog.tsx+msgid "Open in worktree"+msgstr "Open in worktree"+#: src/components/share-receive-miss-content.tsx#: src/components/ShareBranchSwitchDialog.tsxmsgid "Open it there"@@ -5112,6 +5128,10 @@ msgstr "Open, navigate, accept, or dismiss CodeMirror completion suggestions."msgid "Opening {openingLabel}…"msgstr "Opening {openingLabel}…"+#: src/components/ShareBranchSwitchDialog.tsx+msgid "Opening worktree"+msgstr "Opening worktree"+#: src/components/ShareReceiveDialog.tsxmsgid "Opening..."msgstr "Opening..."@@ -6766,6 +6786,10 @@ msgstr "Switch and update branch"msgid "Switch project"msgstr "Switch project"+#: src/components/ShareBranchSwitchDialog.tsx+msgid "Switch to {shareBranch}"+msgstr "Switch to {shareBranch}"+#: src/components/settings/SharingSection.tsxmsgid "Switch to local-only refused"msgstr "Switch to local-only refused"@@ -7013,6 +7037,7 @@ msgid "Thanks for subscribing. Watch your inbox for product updates."msgstr "Thanks for subscribing. Watch your inbox for product updates."#: src/components/NewWorktreeDialog.tsx+#: src/components/ShareBranchSwitchDialog.tsxmsgid "That branch is already open in another worktree."msgstr "That branch is already open in another worktree."@@ -7147,8 +7172,8 @@ msgid "This {targetNoun} moved to <0>{0}</0>. Open it there?"msgstr "This {targetNoun} moved to <0>{0}</0>. Open it there?"#: src/components/ShareBranchSwitchDialog.tsx-msgid "This {targetNoun} only exists on branch <0>{shareBranch}</0>. You have uncommitted changes that prevent switching. Commit or stash your changes, then open the share link again."-msgstr "This {targetNoun} only exists on branch <0>{shareBranch}</0>. You have uncommitted changes that prevent switching. Commit or stash your changes, then open the share link again."+msgid "This {targetNoun} only exists on branch <0>{shareBranch}</0>. You have uncommitted changes that prevent switching here — open it in a worktree to leave your changes untouched."+msgstr "This {targetNoun} only exists on branch <0>{shareBranch}</0>. You have uncommitted changes that prevent switching here — open it in a worktree to leave your changes untouched."#: src/components/ShareBranchSwitchDialog.tsxmsgid "This {targetNoun} was added to branch <0>{shareBranch}</0> recently. Switch and update to open it."@@ -7271,6 +7296,7 @@ msgid "This project is running an older version of OpenKnowledge (v{0}) than thimsgstr "This project is running an older version of OpenKnowledge (v{0}) than this app (v{1})."#: src/components/NewWorktreeDialog.tsx+#: src/components/ShareBranchSwitchDialog.tsxmsgid "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."diff --git a/packages/app/src/locales/pseudo/messages.json b/packages/app/src/locales/pseudo/messages.jsonindex 295bfc4f9..d5a2313c1 100644--- a/packages/app/src/locales/pseudo/messages.json+++ b/packages/app/src/locales/pseudo/messages.json@@ -560,6 +560,13 @@"DId6MT": ["ƤŕōĴēćţ-ĺēvēĺ ƥàĝēś ŵĩţĥ ńō ōũţĝōĩńĝ ĝŕàƥĥ ēďĝēś."],"DJd000": ["Àćţĩvàţē ţĥē ƥŕēvĩōũś ēďĩţōŕ ţàƀ."],"DPfwMq": ["Ďōńē"],+ "DTI-fp": [+ "Ţĥĩś ",+ ["targetNoun"],+ " ōńĺŷ ēxĩśţś ōń ƀŕàńćĥ <0>",+ ["shareBranch"],+ "</0>. Ŷōũ ĥàvē ũńćōḿḿĩţţēď ćĥàńĝēś ţĥàţ ƥŕēvēńţ śŵĩţćĥĩńĝ ĥēŕē — ōƥēń ĩţ ĩń à ŵōŕķţŕēē ţō ĺēàvē ŷōũŕ ćĥàńĝēś ũńţōũćĥēď."+ ],"DVh_Tb": ["Ƒàĩĺēď ţō ćĺēàń ũƥ àƒţēŕ ţŕàśĥ"],"DXd9LM": ["Ńēŵ ŵōŕķţŕēē"],"D_WKe_": ["Ćĺĩćķ àń àĝēńţ'ś àvàţàŕ ĩń ţĥē ƥŕēśēńćē ƀàŕ ţō vĩēŵ ţĥēĩŕ śēśśĩōń."],@@ -814,6 +821,7 @@"JWsZlx": ["Ōƥēń à ƥŕōĴēćţ ţō ēďĩţ."],"JZ8cO6": ["Ĺĩĝĥţ, ďàŕķ, ōŕ ƒōĺĺōŵ ţĥē ŌŚ."],"Jejur6": ["Ćōũĺďń'ţ ĺōàď ďōćũḿēńţ"],+ "JfPuv7": [["shareBranch"], " ĩśń'ţ à vàĺĩď ƀŕàńćĥ ńàḿē."],"Jhj_lh": ["Ḿōďĩƒŷ ţĥē ĺĩńķ ţàŕĝēţ, àńćĥōŕ, àńď ďĩśƥĺàŷ ĺàƀēĺ."],"JkCD2u": ["Śŷńć ƥàũśēď — ŷōũ ďōń'ţ ĥàvē ƥēŕḿĩśśĩōń ţō ƥũśĥ ţō ţĥĩś ŕēƥō"],"JmfgFc": ["(à ŵōŕķţŕēē ōƒ ", ["0"], ")"],@@ -1068,6 +1076,7 @@"PR9FSv": ["Ḿōvē ţō ţĥē ńēxţ vĩśũàĺ-ēďĩţōŕ ƒĩńď ŕēśũĺţ."],"PRnH8G": ["ōƒ ", ["0"]],"PVUn_c": ["Ōƥēń ƒōĺďēŕ"],+ "PZtgO0": ["Ōƥēńĩńĝ ŵōŕķţŕēē"],"P_bX4O": ["Ĥōŵ ţō śēţ ũƥ"],"PdA9NZ": [["ahead"], " àĥēàď"],"PdJZ5p": ["Ńō śķĩĺĺś ŷēţ."],@@ -1261,6 +1270,7 @@"VIwCaD": ["Ēńţŕŷ"],"VM7H66": ["Ţĥĩś ƒĩĺē ĩś ƀĩńàŕŷ àńď ćàń'ţ ƀē śĥōŵń àś ţēxţ."],"VNgKZz": ["Àďvàńćēď śēţţĩńĝś"],+ "VTulZj": ["Ōƥēń ĩń ŵōŕķţŕēē"],"VU3Nrn": ["Ḿĩśśĩńĝ"],"VUijjF": ["Ēḿƀēď àń ĩḿàĝē ŵĩţĥ ōƥţĩōńàĺ àĺţ ţēxţ."],"VYd_YA": ["Ōƥēń àń ēxĩśţĩńĝ ƥŕōĴēćţ ƒōĺďēŕ ƒŕōḿ ďĩśķ."],@@ -1292,6 +1302,7 @@],"W8vpBM": ["śţàŕţēŕ ƥàćķ"],"W9_Bub": ["Ĺōćàĺ ćĥàńĝēś ōvēŕĺàƥ ŵĩţĥ ĩńćōḿĩńĝ śŷńć"],+ "WALN45": ["Śŵĩţćĥ ţō ", ["shareBranch"]],"WHPvOb": ["Àĺĺ ƒĩĺēś àŕē ĥĩďďēń ƀŷ vĩēŵ ƒĩĺţēŕś."],"WL6puM": ["Ƥàţĥ ŕēśōĺvēś ōũţśĩďē ƥŕōĴēćţ"],"WMIKXK": [@@ -1348,13 +1359,6 @@"Xl-UUg": ["ĝũĩďēś/ĩńśţàĺĺ ōŕ ĥţţƥś://ēxàḿƥĺē.ćōḿ"],"XmJfZT": ["ńàḿē"],"XnlF3W": ["Àďď ţĥē ńēxţ ḿàţćĥĩńĝ śōũŕćē śēĺēćţĩōń."],- "XnoA1k": [- "Ţĥĩś ",- ["targetNoun"],- " ōńĺŷ ēxĩśţś ōń ƀŕàńćĥ <0>",- ["shareBranch"],- "</0>. Ŷōũ ĥàvē ũńćōḿḿĩţţēď ćĥàńĝēś ţĥàţ ƥŕēvēńţ śŵĩţćĥĩńĝ. Ćōḿḿĩţ ōŕ śţàśĥ ŷōũŕ ćĥàńĝēś, ţĥēń ōƥēń ţĥē śĥàŕē ĺĩńķ àĝàĩń."- ],"XopE_I": ["Ƒàĩĺēď ţō ƥàŕśē ƀàćķĺĩńķś ēŕŕōŕ ŕēśƥōńśē (ĤŢŢƤ ", ["status"], ")"],"XpIZmv": ["Ƒēńćēď ćōďē ƀĺōćķ ŵĩţĥ ḿōńōśƥàćē ţēxţ."],"XqNHcm": ["Ćōũĺďń'ţ ũƥďàţē śķĩĺĺ ţàŕĝēţś: ", ["0"]],@@ -1458,7 +1462,6 @@["currentLabel"],"</1>."],- "_BthEY": ["Ōƥēń ĩń ", ["shareBranch"]],"_NX6gG": ["Ḿàńàĝĩńĝ ƥŕōĴēćţ ÀĨ ţōōĺś ĩś ũńàvàĩĺàƀĺē ĩń ţĥĩś ƀũĩĺď."],"_PACVa": ["Ŕēĺēàśē ńōţēś"],"_PBJRl": ["Àďď àţ ĺēàśţ ōńē ĺēţţēŕ ōŕ ńũḿƀēŕ."],@@ -1554,6 +1557,7 @@"cF9DyA": ["Ŕēćōńńēćţĩńĝ àƒţēŕ śēŕvēŕ ŕēśţàŕţ"],"cIptmH": ["Ĩń ţĥē Ćĺàũďē Ďēśķţōƥ Àƥƥ"],"cKjLuT": ["(ƥŕōĴēćţ + ũśēŕ)"],+ "cN1Gcp": ["À ŵōŕķţŕēē ƒōĺďēŕ ƒōŕ ", ["shareBranch"], " àĺŕēàďŷ ēxĩśţś."],"cOSAfL": ["Ńō ŕēƥōśĩţōŕĩēś ƒōũńď ōń ŷōũŕ ĜĩţĤũƀ àććōũńţ."],"cOrTMo": ["Ŷōũŕ śĥàŕē ĺĩńķ ĩś ŕēàďŷ ƀēĺōŵ."],"cRHuuI": ["Ćōũĺďń'ţ ćōƥŷ ƥàţĥ"],@@ -1631,6 +1635,7 @@"e4PbgC": ["Ďũƥĺĩćàţē ţĥē ƒĩĺē-ţŕēē ĩţēḿ ćōƥĩēď ƒŕōḿ ţĥē Ƒĩĺēś śĩďēƀàŕ."],"e8L17t": ["À ńōń-ēḿƥţŷ ƒōĺďēŕ àĺŕēàďŷ ēxĩśţś àţ ţĥĩś ƥàţĥ. Ƥĩćķ à ďĩƒƒēŕēńţ ƒōĺďēŕ."],"e8zRrb": ["Śĥōŵ Ƒĩĺēś"],+ "e8zYa8": ["Ćōũĺď ńōţ ōƥēń ", ["shareBranch"], " ĩń à ŵōŕķţŕēē. Ţŕŷ àĝàĩń."],"eBIT9h": ["Ƥàśţē ƒàĩĺēď.", ["restoreSuffix"]],"eFJkVt": ["Ćĺōńē ƒàĩĺēď: ", ["cloneError"]],"eG8Jsg": ["Ţōĝĝĺē śōũŕćē ţàƀ ƒōćũś ḿōďē"],@@ -1729,6 +1734,11 @@"gwykHF": ["Ţĥĩś ďōć ĥàśń'ţ śŷńćēď ţō ĜĩţĤũƀ ŷēţ. Ţĥē ĺĩńķ ŵĩĺĺ ŵōŕķ àƒţēŕ ţĥē ńēxţ śŷńć."],"h-AdvS": ["Ţĥē ƒōĺďēŕś àńď ţēḿƥĺàţēś àŕē àĺŕēàďŷ ĥēŕē, śō ţĥēŕē'ś ńōţĥĩńĝ ţō àďď."],"h06R3C": ["Ńō ƥàĝēś àŕē ḿĩśśĩńĝ ōũţĝōĩńĝ ĝŕàƥĥ ĺĩńķś."],+ "h3QZcB": [+ "À ƀŕàńćĥ ńàḿēď ",+ ["shareBranch"],+ " àĺŕēàďŷ ēxĩśţś. Ōƥēń ĩţś ŵōŕķţŕēē ƒŕōḿ ţĥē śŵĩţćĥēŕ ĩńśţēàď."+ ],"h6EvY-": ["Ţĥĩś ŵĩĺĺ ŕēƥĺàćē ţĥē ćũŕŕēńţ ďōćũḿēńţ ćōńţēńţ ŵĩţĥ ţĥē vēŕśĩōń ƒŕōḿ <0>",["relative"],diff --git a/packages/app/src/locales/pseudo/messages.po b/packages/app/src/locales/pseudo/messages.poindex 727ddc036..e9ef21558 100644--- a/packages/app/src/locales/pseudo/messages.po+++ b/packages/app/src/locales/pseudo/messages.po@@ -409,6 +409,10 @@ msgstr ""msgid "{settingsDescriptorLabel} properties"msgstr ""+#: src/components/ShareBranchSwitchDialog.tsx+msgid "{shareBranch} isn't a valid branch name."+msgstr ""+#: src/components/CreatedItemsList.tsxmsgid "{skillCount, plural, one {skill} other {skills}}"msgstr ""@@ -499,6 +503,10 @@ msgstr ""msgid "📝 or assets/icon.png"msgstr ""+#: src/components/ShareBranchSwitchDialog.tsx+msgid "A branch named {shareBranch} already exists. Open its worktree from the switcher instead."+msgstr ""+#: src/components/NewWorktreeDialog.tsxmsgid "A branch with that name already exists. Open its worktree from the switcher instead."msgstr ""@@ -576,6 +584,10 @@ msgstr ""msgid "A title, description, tags — anything that describes this folder."msgstr ""+#: src/components/ShareBranchSwitchDialog.tsx+msgid "A worktree folder for {shareBranch} already exists."+msgstr ""+#: src/components/NewWorktreeDialog.tsxmsgid "A worktree folder for that branch already exists."msgstr ""@@ -1839,6 +1851,10 @@ msgstr ""msgid "Could not move \"{targetName}\" to the Trash. Do you want to permanently delete instead?"msgstr ""+#: src/components/ShareBranchSwitchDialog.tsx+msgid "Could not open {shareBranch} in a worktree. Try again."+msgstr ""+#: src/components/ShareBranchSwitchDialog.tsxmsgid "Could not open {target}. Try opening it manually."msgstr ""@@ -4977,11 +4993,11 @@ msgid "Open graph"msgstr ""#: src/components/ShareBranchSwitchDialog.tsx-msgid "Open in {shareBranch}"+msgid "Open in current branch"msgstr ""#: src/components/ShareBranchSwitchDialog.tsx-msgid "Open in current branch"+msgid "Open in worktree"msgstr ""#: src/components/share-receive-miss-content.tsx@@ -5107,6 +5123,10 @@ msgstr ""msgid "Opening {openingLabel}…"msgstr ""+#: src/components/ShareBranchSwitchDialog.tsx+msgid "Opening worktree"+msgstr ""+#: src/components/ShareReceiveDialog.tsxmsgid "Opening..."msgstr ""@@ -6761,6 +6781,10 @@ msgstr ""msgid "Switch project"msgstr ""+#: src/components/ShareBranchSwitchDialog.tsx+msgid "Switch to {shareBranch}"+msgstr ""+#: src/components/settings/SharingSection.tsxmsgid "Switch to local-only refused"msgstr ""@@ -7008,6 +7032,7 @@ msgid "Thanks for subscribing. Watch your inbox for product updates."msgstr ""#: src/components/NewWorktreeDialog.tsx+#: src/components/ShareBranchSwitchDialog.tsxmsgid "That branch is already open in another worktree."msgstr ""@@ -7142,7 +7167,7 @@ msgid "This {targetNoun} moved to <0>{0}</0>. Open it there?"msgstr ""#: src/components/ShareBranchSwitchDialog.tsx-msgid "This {targetNoun} only exists on branch <0>{shareBranch}</0>. You have uncommitted changes that prevent switching. Commit or stash your changes, then open the share link again."+msgid "This {targetNoun} only exists on branch <0>{shareBranch}</0>. You have uncommitted changes that prevent switching here — open it in a worktree to leave your changes untouched."msgstr ""#: src/components/ShareBranchSwitchDialog.tsx@@ -7266,6 +7291,7 @@ msgid "This project is running an older version of OpenKnowledge (v{0}) than thimsgstr ""#: src/components/NewWorktreeDialog.tsx+#: src/components/ShareBranchSwitchDialog.tsxmsgid "This project isn't a git repository, so worktrees aren't available."msgstr ""diff --git a/packages/app/tests/stress/fixtures/handoff-mocks.ts b/packages/app/tests/stress/fixtures/handoff-mocks.tsindex b2dbd75dc..a16527191 100644--- a/packages/app/tests/stress/fixtures/handoff-mocks.ts+++ b/packages/app/tests/stress/fixtures/handoff-mocks.ts@@ -430,6 +430,7 @@ export async function installHandoffMocks(page: Page, cfg: HandoffMockConfig): Pworktree: {list: async () => ({ ok: false as const, reason: 'no-git' as const }),create: async () => ({ ok: false as const, reason: 'no-git' as const }),+ checkout: 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.tsindex 5a1809d45..5eefd0da2 100644--- a/packages/core/src/desktop-bridge.ts+++ b/packages/core/src/desktop-bridge.ts@@ -1310,13 +1310,16 @@ export interface OkDesktopBridge {* Worktree selector (worktree = window). `list` enumerates the* sender window's project's local branches + their worktrees; `create`* creates (or locates) the worktree for a branch under- * `<mainRoot>/.ok/worktrees/`. Opening a worktree window reuses+ * `<mainRoot>/.ok/worktrees/`; `checkout` is the share-receive arm+ * (resolves where the branch lives — fetching from `origin` when+ * needed — then create-or-locates). Opening a worktree window reuses* `project.open({ entryPoint: 'worktree' })`. Canonical JSDoc in* `packages/desktop/src/shared/bridge-contract.ts`.*/worktree: {list(): Promise<WorktreeListResult>;create(request: WorktreeCreateRequest): Promise<WorktreeCreateResult>;+ checkout(request: { branch: string }): Promise<WorktreeCreateResult>;};/**diff --git a/packages/core/src/git/worktree-selector-model.ts b/packages/core/src/git/worktree-selector-model.tsindex 8a65a94f2..418297d1b 100644--- a/packages/core/src/git/worktree-selector-model.ts+++ b/packages/core/src/git/worktree-selector-model.ts@@ -117,6 +117,10 @@ export interface WorktreeCreateRequest {* IPC-facing result of creating/locating a worktree. `created: false` means the* branch already had a worktree and `path` points at it (open that window* instead). The failure reasons map git's refusal modes to actionable copy.+ * `branch-not-found` / `fetch-failed` arise only from the share-scoped+ * `checkout` operation, whose branch resolution may `git fetch` from `origin`+ * (branch gone upstream vs. a retryable network/timeout failure); the other+ * failure reasons come from validation and `git worktree add`.*/export type WorktreeCreateResult =| { readonly ok: true; readonly path: string; readonly created: boolean }@@ -128,6 +132,8 @@ export type WorktreeCreateResult =| 'already-checked-out'| 'path-exists'| 'no-git'+ | 'branch-not-found'+ | 'fetch-failed'| 'error';readonly message?: string;};diff --git a/packages/desktop/src/main/index.ts b/packages/desktop/src/main/index.tsindex faea42d0c..b3b1fc4d8 100644--- a/packages/desktop/src/main/index.ts+++ b/packages/desktop/src/main/index.ts@@ -356,7 +356,11 @@ import {classifyRecentGitAsync,readWorktreeBranchAsync,} from './worktree-recents.ts';-import { createWorktree, listWorktreeSelector } from './worktree-service.ts';+import {+ checkoutShareBranchWorktree,+ createWorktree,+ listWorktreeSelector,+} from './worktree-service.ts';// Modern macOS chrome treatment. Three architectural facts the field set// encodes:@@ -3936,6 +3940,9 @@ function registerIpcHandlers() {if (request.kind === 'list') {return listWorktreeSelector(anchor, anchor);}+ if (request.kind === 'checkout') {+ return checkoutShareBranchWorktree({ anchorPath: anchor, branch: request.branch });+ }return createWorktree({anchorPath: anchor,branch: request.branch,diff --git a/packages/desktop/src/main/worktree-service.test.ts b/packages/desktop/src/main/worktree-service.test.tsindex 2d3663a23..9c1d83b22 100644--- a/packages/desktop/src/main/worktree-service.test.ts+++ b/packages/desktop/src/main/worktree-service.test.ts@@ -16,7 +16,11 @@ import { addOkPathsToGitExclude, getOkArtifactPaths } from '@inkeep/open-knowledimport { initContent } from '@inkeep/open-knowledge-server';import { discoverProject } from './folder-admission.ts';import { clearRecentGitCache } from './worktree-recents.ts';-import { createWorktree, listWorktreeSelector } from './worktree-service.ts';+import {+ checkoutShareBranchWorktree,+ createWorktree,+ listWorktreeSelector,+} from './worktree-service.ts';import { seedWorktreeProjectSetup } from './worktree-setup-inherit.ts';const execFileAsync = promisify(execFile);@@ -71,6 +75,24 @@ async function addBareRemote(mainRepo: string, pushBranches: string[]): Promise<return bare;}+/** The root-checkout state the share-checkout leg must never disturb: commit,+ * current branch, and working-tree status. Remote-tracking refs and FETCH_HEAD+ * are deliberately NOT captured — a fetch writes those by design, and they are+ * invisible to the user's working copy. */+interface RepoSnapshot {+ readonly head: string;+ readonly branch: string;+ readonly status: string;+}++async function repoSnapshot(repo: string): Promise<RepoSnapshot> {+ return {+ head: (await git(repo, 'rev-parse', 'HEAD')).trim(),+ branch: (await git(repo, 'rev-parse', '--abbrev-ref', 'HEAD')).trim(),+ status: await git(repo, 'status', '--porcelain'),+ };+}+describe('worktree-service', () => {let handle: Handle | null = null;afterEach(() => {@@ -476,6 +498,242 @@ describe('worktree-service', () => {});});+// ---------------------------------------------------------------------------+// Share-receive checkout — branch resolution (local ref → remote-tracking ref+// → bounded fetch) + failure classes, all against real git with a bare origin+// on the same filesystem. Every test also pins the feature's headline promise:+// the receiver's main repo (HEAD, current branch, working-tree status) is+// never touched, whichever resolution mode ran.+// ---------------------------------------------------------------------------++describe('worktree-service — share-branch checkout', () => {+ let handle: Handle | null = null;+ afterEach(() => {+ handle?.cleanup();+ handle = null;+ clearRecentGitCache();+ });++ // local-ref mode: an existing local branch is checked out into its worktree+ // WITHOUT any fetch — makeRepo configures no remote at all, so an attempted+ // fetch would fail the create — and the main repo's HEAD, current branch,+ // and dirty state stay untouched.+ test('checkoutShareBranchWorktree (local ref) checks out into a worktree, main repo untouched', async () => {+ handle = await makeRepo(['share-me']);+ // Uncommitted work in the receiver's main repo — the state the worktree leg+ // must never disturb.+ writeFileSync(join(handle.mainRepo, 'wip.txt'), 'uncommitted work\n');+ const headBefore = (await git(handle.mainRepo, 'rev-parse', 'HEAD')).trim();+ const statusBefore = await git(handle.mainRepo, 'status', '--porcelain');+ expect(statusBefore).toContain('wip.txt');++ const res = await checkoutShareBranchWorktree({+ anchorPath: handle.mainRepo,+ branch: 'share-me',+ });+ expect(res.ok).toBe(true);+ if (!res.ok) return;+ expect(res.created).toBe(true);+ expect(res.path).toBe(join(handle.mainRepo, '.ok', 'worktrees', 'share-me'));+ const wtBranch = await git(res.path, 'rev-parse', '--abbrev-ref', 'HEAD');+ expect(wtBranch.trim()).toBe('share-me');++ expect((await git(handle.mainRepo, 'rev-parse', 'HEAD')).trim()).toBe(headBefore);+ expect((await git(handle.mainRepo, 'rev-parse', '--abbrev-ref', 'HEAD')).trim()).toBe('main');+ expect(await git(handle.mainRepo, 'status', '--porcelain')).toBe(statusBefore);+ });++ // remote-tracking-only mode: no local ref, but origin/<b> is known from an+ // earlier fetch. The remote URL is broken AFTER setup, so if this mode+ // wrongly reached for the network the create would fail — success proves the+ // resolution used the existing remote-tracking ref alone.+ test('checkoutShareBranchWorktree (remote-tracking only) creates a tracking worktree without fetching', async () => {+ handle = await makeRepo(['remote-only']);+ await addBareRemote(handle.mainRepo, ['main', 'remote-only']);+ await git(handle.mainRepo, 'branch', '-D', 'remote-only');+ await git(handle.mainRepo, 'remote', 'set-url', 'origin', join(handle.root, 'gone.git'));+ // Sanity: only the remote-tracking ref remains.+ expect((await git(handle.mainRepo, 'branch', '--list', 'remote-only')).trim()).toBe('');+ expect(+ (await git(handle.mainRepo, 'branch', '-r', '--list', 'origin/remote-only')).trim(),+ ).not.toBe('');+ writeFileSync(join(handle.mainRepo, 'wip.txt'), 'uncommitted work\n');+ const before = await repoSnapshot(handle.mainRepo);++ const res = await checkoutShareBranchWorktree({+ anchorPath: handle.mainRepo,+ branch: 'remote-only',+ });+ expect(res.ok).toBe(true);+ if (!res.ok) return;+ expect(res.created).toBe(true);+ expect(res.path).toBe(join(handle.mainRepo, '.ok', 'worktrees', 'remote-only'));+ expect((await git(res.path, 'rev-parse', '--abbrev-ref', 'HEAD')).trim()).toBe('remote-only');+ // The new local branch tracks the remote ref it was cut from.+ const upstream = await git(+ res.path,+ 'rev-parse',+ '--abbrev-ref',+ '--symbolic-full-name',+ '@{upstream}',+ );+ expect(upstream.trim()).toBe('origin/remote-only');+ expect(await repoSnapshot(handle.mainRepo)).toEqual(before);+ });++ // never-fetched mode: the branch exists ONLY on the bare origin (pushed from+ // a scratch clone after the main repo's last fetch), so resolution must+ // fetch first. The default fetch refspec materializes the remote-tracking+ // ref, and the worktree's new local branch tracks it.+ test('checkoutShareBranchWorktree (never fetched) fetches the branch and creates a tracking worktree', 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', 'never-fetched');+ writeFileSync(join(scratch, 'remote-only.txt'), 'from remote\n');+ await git(scratch, 'add', '-A');+ await git(scratch, 'commit', '-m', 'remote-only commit');+ await git(scratch, 'push', 'origin', 'never-fetched');+ // Sanity: the main repo knows nothing of the branch — no local ref and no+ // remote-tracking ref.+ expect((await git(handle.mainRepo, 'branch', '--list', 'never-fetched')).trim()).toBe('');+ expect(+ (await git(handle.mainRepo, 'branch', '-r', '--list', 'origin/never-fetched')).trim(),+ ).toBe('');+ writeFileSync(join(handle.mainRepo, 'wip.txt'), 'uncommitted work\n');+ const before = await repoSnapshot(handle.mainRepo);++ const res = await checkoutShareBranchWorktree({+ anchorPath: handle.mainRepo,+ branch: 'never-fetched',+ });+ expect(res.ok).toBe(true);+ if (!res.ok) return;+ expect(res.created).toBe(true);+ expect(res.path).toBe(join(handle.mainRepo, '.ok', 'worktrees', 'never-fetched'));+ // The worktree holds the remote commit's content — the fetch actually ran.+ expect(existsSync(join(res.path, 'remote-only.txt'))).toBe(true);+ // The fetch materialized the remote-tracking ref; the local branch tracks it.+ expect(+ (await git(handle.mainRepo, 'branch', '-r', '--list', 'origin/never-fetched')).trim(),+ ).not.toBe('');+ const upstream = await git(+ res.path,+ 'rev-parse',+ '--abbrev-ref',+ '--symbolic-full-name',+ '@{upstream}',+ );+ expect(upstream.trim()).toBe('origin/never-fetched');+ expect(await repoSnapshot(handle.mainRepo)).toEqual(before);+ });++ // create-or-locate: a second share for the same branch must find the first+ // share's worktree, not attempt a duplicate.+ test('checkoutShareBranchWorktree (second share, same branch) returns the existing worktree with created:false', async () => {+ handle = await makeRepo(['share-me']);+ writeFileSync(join(handle.mainRepo, 'wip.txt'), 'uncommitted work\n');+ const first = await checkoutShareBranchWorktree({+ anchorPath: handle.mainRepo,+ branch: 'share-me',+ });+ expect(first.ok).toBe(true);+ if (!first.ok) return;+ expect(first.created).toBe(true);+ const before = await repoSnapshot(handle.mainRepo);++ const second = await checkoutShareBranchWorktree({+ anchorPath: handle.mainRepo,+ branch: 'share-me',+ });+ expect(second.ok).toBe(true);+ if (!second.ok) return;+ expect(second.created).toBe(false);+ expect(second.path).toBe(first.path);+ expect(await repoSnapshot(handle.mainRepo)).toEqual(before);+ });++ // fetch-leg failure, terminal class: the branch never existed on origin, so+ // git reports "couldn't find remote ref" and the checkout returns the+ // terminal branch-not-found — with nothing created locally.+ test('checkoutShareBranchWorktree classifies a branch absent from origin as branch-not-found', async () => {+ handle = await makeRepo();+ await addBareRemote(handle.mainRepo, ['main']);+ writeFileSync(join(handle.mainRepo, 'wip.txt'), 'uncommitted work\n');+ const before = await repoSnapshot(handle.mainRepo);++ const res = await checkoutShareBranchWorktree({+ anchorPath: handle.mainRepo,+ branch: 'ghost',+ });+ expect(res.ok).toBe(false);+ if (res.ok) return;+ expect(res.reason).toBe('branch-not-found');+ // The failed resolution created nothing: no worktree dir, no local branch.+ expect(existsSync(join(handle.mainRepo, '.ok', 'worktrees', 'ghost'))).toBe(false);+ expect((await git(handle.mainRepo, 'branch', '--list', 'ghost')).trim()).toBe('');+ expect(await repoSnapshot(handle.mainRepo)).toEqual(before);+ });++ // fetch-leg failure, retryable class: origin's URL points at a path that+ // doesn't exist (a network-down stand-in), so the fetch fails without+ // matching the branch-gone discriminator, and the stderr is surfaced for+ // diagnostics.+ test('checkoutShareBranchWorktree classifies an unreachable origin as fetch-failed', async () => {+ handle = await makeRepo();+ await git(handle.mainRepo, 'remote', 'add', 'origin', join(handle.root, 'missing.git'));+ writeFileSync(join(handle.mainRepo, 'wip.txt'), 'uncommitted work\n');+ const before = await repoSnapshot(handle.mainRepo);++ const res = await checkoutShareBranchWorktree({+ anchorPath: handle.mainRepo,+ branch: 'any-branch',+ });+ expect(res.ok).toBe(false);+ if (res.ok) return;+ expect(res.reason).toBe('fetch-failed');+ expect(typeof res.message).toBe('string');+ expect((res.message ?? '').length).toBeGreaterThan(0);+ expect(existsSync(join(handle.mainRepo, '.ok', 'worktrees', 'any-branch'))).toBe(false);+ expect(await repoSnapshot(handle.mainRepo)).toEqual(before);+ });++ // fetch-leg hang: an ext:: transport that just sleeps stands in for a+ // stalled network. The injected bound must kill the fetch (classified+ // retryable) long before the transport would give up on its own. The elapsed+ // LOWER bound proves the transport genuinely hung — an instant transport+ // failure would classify identically but wouldn't exercise the kill. The+ // orphaned sleep self-expires without holding the test process open.+ test('checkoutShareBranchWorktree kills a hanging fetch at the injected timeout (fetch-failed)', async () => {+ handle = await makeRepo();+ // ext:: transports are disallowed by default on modern git; opt in via+ // repo config so the service's plain `git fetch` spawn (no -c flags)+ // honors it. git-remote-ext splits the address on spaces with no shell,+ // so `ext::sleep 60` runs `sleep` with argument `60`.+ await git(handle.mainRepo, 'config', 'protocol.ext.allow', 'always');+ await git(handle.mainRepo, 'remote', 'add', 'origin', 'ext::sleep 60');+ writeFileSync(join(handle.mainRepo, 'wip.txt'), 'uncommitted work\n');+ const before = await repoSnapshot(handle.mainRepo);++ const t0 = Date.now();+ const res = await checkoutShareBranchWorktree({+ anchorPath: handle.mainRepo,+ branch: 'any-branch',+ fetchTimeoutMs: 500,+ });+ const elapsed = Date.now() - t0;+ expect(res.ok).toBe(false);+ if (res.ok) return;+ expect(res.reason).toBe('fetch-failed');+ expect(elapsed).toBeGreaterThanOrEqual(450);+ expect(elapsed).toBeLessThan(10_000);+ expect(await repoSnapshot(handle.mainRepo)).toEqual(before);+ });+});+// ---------------------------------------------------------------------------// Inherited OK setup — the worktree opens `managed` (no consent dialog), with// full parity, for both shared and local-only roots. Real git throughout: thediff --git a/packages/desktop/src/main/worktree-service.ts b/packages/desktop/src/main/worktree-service.tsindex 49a00a1bd..674db9008 100644--- a/packages/desktop/src/main/worktree-service.ts+++ b/packages/desktop/src/main/worktree-service.ts@@ -27,6 +27,8 @@ import { isAbsolute, join, sep } from 'node:path';import { promisify } from 'node:util';import {buildWorktreeSelectorModel,+ isBranchNotFoundGitError,+ isValidBranchName,parseBranchList,stripRemotePrefix,WORKTREES_PARENT_DIR,@@ -46,6 +48,18 @@ const execFileAsync = promisify(execFile);* classification survives a non-English host locale. */const GIT_ENV = { ...process.env, LANG: 'C', LC_ALL: 'C' } as const;+/** Fetch spawn env: `GIT_ENV` plus `GIT_TERMINAL_PROMPT=0`, mirroring the+ * server's git discipline — desktop main has no terminal to answer a+ * credential prompt, so a credentialed remote must fail fast (into the+ * `fetch-failed` arm) instead of stalling until the timeout kill. */+const FETCH_GIT_ENV = { ...GIT_ENV, GIT_TERMINAL_PROMPT: '0' } as const;++/** Default bound for the share-checkout fetch — matches the server's+ * fast-forward fetch bound so a stalled network degrades to a typed+ * `fetch-failed` instead of an indefinite hang. Injectable per call so tests+ * can exercise the bound without waiting 15s. */+const SHARE_FETCH_TIMEOUT_MS = 15_000;+export type { WorktreeCreateResult, WorktreeListResult };export interface CreateWorktreeArgs extends WorktreeCreateRequest {@@ -190,6 +204,141 @@ export async function createWorktree(args: CreateWorktreeArgs): Promise<Worktreereturn { ok: true, path: worktreePath, created: true };}+export interface ShareBranchCheckoutArgs {+ /** A path inside the repo (the focused window's project) — the git anchor. */+ readonly anchorPath: string;+ /** The share payload's branch — an EXISTING branch to locate; this arm never+ * invents one (contrast `createWorktree`'s create modes). */+ readonly branch: string;+ /** Override for the fetch bound; defaults to `SHARE_FETCH_TIMEOUT_MS`. */+ readonly fetchTimeoutMs?: number;+}++/**+ * Create (or locate) the worktree for a share link's branch, resolving where+ * the branch lives first:+ *+ * 1. local `refs/heads/<branch>` exists → check it out as-is (a stale local+ * ref is accepted; a shared doc missing from it surfaces through the open+ * path's target-existence probe rather than an eager fetch here).+ * 2. only `refs/remotes/origin/<branch>` exists → new local tracking branch+ * off that ref.+ * 3. neither → `git fetch origin <branch>` (bounded + prompt-free), then the+ * tracking arm. With the default refspec the fetch materializes the+ * remote-tracking ref; a repo whose fetch refspec doesn't cover the+ * branch (e.g. a --single-branch clone) writes only FETCH_HEAD and falls+ * into the generic add-error arm.+ *+ * Every arm delegates to `createWorktree`, so path convention, seeding, and+ * create-or-locate reuse are identical to selector-created worktrees — and the+ * anchor repo's working tree, HEAD, and existing local branches are never+ * touched (the fetch writes only remote-tracking refs and FETCH_HEAD).+ *+ * Fetch failures split on core's branch-not-found classifier: branch gone from+ * `origin` → `branch-not-found` (terminal); anything else, including the+ * timeout kill → `fetch-failed` (retryable). Failures are values, never throws.+ */+export async function checkoutShareBranchWorktree(+ args: ShareBranchCheckoutArgs,+): Promise<WorktreeCreateResult> {+ const branch = args.branch.trim();+ // Revalidate at the IPC seam before the first git spawn: the fetch arm+ // passes `branch` as a bare positional (no `--` guard — mirrors the server's+ // fetch), so a dash-prefixed or otherwise malformed name must never reach+ // it. `isValidBranchName` is the same predicate the server applied to the+ // share payload; `worktreeRelativeDir` screens path escapes.+ if (+ !isValidBranchName(branch) ||+ worktreeRelativeDir(branch) === null ||+ !isAbsolute(args.anchorPath)+ ) {+ return { ok: false, reason: 'invalid-branch' };+ }+ // Screen non-git anchors before the ref probes so the failure classifies as+ // `no-git` rather than a misleading `fetch-failed` out of the fetch arm.+ const worktrees = await listGitWorktrees(args.anchorPath);+ if (worktrees.length === 0) return { ok: false, reason: 'no-git' };++ if (await refExists(args.anchorPath, `refs/heads/${branch}`)) {+ return createWorktree({ anchorPath: args.anchorPath, branch, createBranch: false });+ }+ const remoteRef = `origin/${branch}`;+ if (!(await refExists(args.anchorPath, `refs/remotes/${remoteRef}`))) {+ const failure = await fetchShareBranch(+ args.anchorPath,+ branch,+ args.fetchTimeoutMs ?? SHARE_FETCH_TIMEOUT_MS,+ );+ if (failure !== null) return failure;+ }+ return createWorktree({+ anchorPath: args.anchorPath,+ branch,+ remoteRef,+ createBranch: true,+ });+}++/** True iff the exact, fully-qualified ref exists (`git show-ref --verify`+ * exits 0). Any failure — including a non-repo cwd — reads as "no ref"+ * (fail-soft, per the module contract). Exit 1 is the expected missing-ref+ * case; anything else (spawn failure, permission denial, timeout kill) is+ * warn-logged so a local-filesystem fault stays distinguishable from the+ * network failure the caller would otherwise misattribute it to. The timeout+ * bounds a stalled .git so the IPC handler can't hang on a local probe. */+async function refExists(anchorPath: string, ref: string): Promise<boolean> {+ try {+ await execFileAsync('git', ['show-ref', '--verify', '--quiet', ref], {+ cwd: anchorPath,+ env: GIT_ENV,+ timeout: 5_000,+ });+ return true;+ } catch (err) {+ const code = (err as { code?: number | string }).code;+ if (code !== 1) {+ console.warn(+ `[worktree-service] refExists unexpected failure ref=${ref} error=${gitErrorText(err).replace(/\s+/g, ' ').slice(0, 200)}`,+ );+ }+ return false;+ }+}++/**+ * `git fetch origin <branch>`, bounded and prompt-free. Returns `null` on+ * success, else the classified failure: `branch-not-found` when origin reports+ * the ref gone, `fetch-failed` for everything else (unreachable remote, auth+ * refusal, timeout kill), with the collapsed truncated stderr as diagnostics.+ */+async function fetchShareBranch(+ anchorPath: string,+ branch: string,+ timeoutMs: number,+): Promise<Extract<WorktreeCreateResult, { ok: false }> | null> {+ try {+ await execFileAsync('git', ['fetch', 'origin', branch], {+ cwd: anchorPath,+ env: FETCH_GIT_ENV,+ timeout: timeoutMs,+ });+ return null;+ } catch (err) {+ if (isBranchNotFoundGitError(err)) return { ok: false, reason: 'branch-not-found' };+ // A timeout kill, an auth refusal, and an unreachable remote all classify+ // `fetch-failed`; prefix the kill metadata so session-log triage can tell+ // the elapsed-timeout case apart without correlating wall-clock times.+ const killed = (err as { killed?: boolean }).killed === true;+ const signal = (err as { signal?: string }).signal;+ const raw = gitErrorText(err).replace(/\s+/g, ' ').slice(0, 280);+ return {+ ok: false,+ reason: 'fetch-failed',+ message: killed ? `[timeout signal=${signal ?? 'SIGTERM'}] ${raw}` : raw,+ };+ }+}+/*** Assemble the `git worktree add` argv for the four create modes. Precedence:*@@ -372,18 +521,23 @@ interface AddErrorClassification {readonly message?: string;}-function classifyAddError(err: unknown): AddErrorClassification {+/** Raw error text of a failed git spawn: stderr when present (Buffer or+ * string), else the error message. Buffer.isBuffer narrows the stable+ * `stderrRaw` local, so no non-null assertion is needed (biome's --unsafe fix+ * rewrites `!` → `?.`, which would otherwise reintroduce a possibly-undefined+ * value). */+function gitErrorText(err: unknown): string {const e = typeof err === 'object' && err !== null ? (err as ExecErr) : null;const stderrRaw = e?.stderr;- // Buffer.isBuffer narrows the stable `stderrRaw` local, so no non-null- // assertion is needed (biome's --unsafe fix rewrites `!` → `?.`, which would- // otherwise reintroduce a possibly-undefined `raw`).- const raw: string =- stderrRaw !== undefined && stderrRaw !== null- ? Buffer.isBuffer(stderrRaw)- ? stderrRaw.toString('utf-8')- : String(stderrRaw)- : String(e?.message ?? err);+ return stderrRaw !== undefined && stderrRaw !== null+ ? Buffer.isBuffer(stderrRaw)+ ? stderrRaw.toString('utf-8')+ : String(stderrRaw)+ : String(e?.message ?? err);+}++function classifyAddError(err: unknown): AddErrorClassification {+ const raw = gitErrorText(err);const stderr = raw.toLowerCase();if (stderr.includes('already checked out')) return { reason: 'already-checked-out' };if (stderr.includes('already exists') && stderr.includes('branch')) {diff --git a/packages/desktop/src/preload/index.ts b/packages/desktop/src/preload/index.tsindex 440e9ceff..cc45a1907 100644--- a/packages/desktop/src/preload/index.ts+++ b/packages/desktop/src/preload/index.ts@@ -436,16 +436,22 @@ const bridge: OkDesktopBridge = {},worktree: {- // One discriminated channel (`ok:worktree:dispatch`) backs both methods,- // respecting the hand-rolled-channel cap. Each method knows its branch, so- // it casts the union result to its own arm (the shapes overlap only on the- // shared `no-git` failure, so a runtime discriminant would be noise).+ // One discriminated channel (`ok:worktree:dispatch`) backs all three+ // methods, respecting the hand-rolled-channel cap. Each method knows its+ // branch, so it casts the union result to its own arm (the shapes overlap+ // only on the shared `no-git` failure, so a runtime discriminant would be+ // noise).list: () => invoke('ok:worktree:dispatch', { kind: 'list' }) as Promise<WorktreeListResult>,create: (request: WorktreeCreateRequest) =>invoke('ok:worktree:dispatch', {kind: 'create',...request,}) as Promise<WorktreeCreateResult>,+ checkout: (request: { branch: string }) =>+ invoke('ok:worktree:dispatch', {+ kind: 'checkout',+ branch: request.branch,+ }) as Promise<WorktreeCreateResult>,},sharing: {diff --git a/packages/desktop/src/shared/bridge-contract.ts b/packages/desktop/src/shared/bridge-contract.tsindex 80c8972e5..6116bec2f 100644--- a/packages/desktop/src/shared/bridge-contract.ts+++ b/packages/desktop/src/shared/bridge-contract.ts@@ -1504,10 +1504,22 @@ export interface OkDesktopBridge {* 'new-window', entryPoint: 'worktree' })` — this surface is git-only.* Backed by `ok:worktree:dispatch` (one consolidated channel, discriminated* on `kind`, per the `ok:sharing:dispatch` precedent).+ *+ * `checkout` is the share-receive arm: unlike `create` (whose caller picked+ * the branch from the selector model and therefore knows where it lives),+ * a share payload names a branch the receiver may never have fetched. Main+ * resolves it — existing local ref → plain checkout; remote-tracking ref+ * only → new tracking branch off `origin/<branch>`; neither → bounded+ * `git fetch origin <branch>`, then the tracking checkout — and delegates+ * to the same create-or-locate path (an existing worktree is located, not+ * refused). The receiver's root checkout is never touched. Failures extend+ * the create result union: `branch-not-found` (branch gone from origin —+ * terminal) and `fetch-failed` (network/timeout — retryable).*/worktree: {list(): Promise<WorktreeListResult>;create(request: WorktreeCreateRequest): Promise<WorktreeCreateResult>;+ checkout(request: { branch: string }): Promise<WorktreeCreateResult>;};/**diff --git a/packages/desktop/src/shared/ipc-channels.ts b/packages/desktop/src/shared/ipc-channels.tsindex fb5878a46..04c6de2a8 100644--- a/packages/desktop/src/shared/ipc-channels.ts+++ b/packages/desktop/src/shared/ipc-channels.ts@@ -940,11 +940,22 @@ export interface RequestChannels {* locate) the worktree for `branch` under `<mainRoot>/.ok/worktrees/`.* Opening the worktree window reuses the existing `ok:project:open`* path (entryPoint `'worktree'`) — this channel is git-only.- * The renderer's `bridge.worktree.{list,create}` recovers per-operation- * typing from the discriminated result.+ * - `{ kind: 'checkout', branch }` → share-receive arm: resolve where an+ * EXISTING `branch` lives (local ref → plain checkout; remote-tracking+ * ref only → new tracking branch; neither → bounded+ * `git fetch origin <branch>` first), then create or locate its+ * worktree the same way. Failures add `branch-not-found` /+ * `fetch-failed` to the create result union.+ * The renderer's `bridge.worktree.{list,create,checkout}` recovers+ * per-operation typing from the discriminated result.*/'ok:worktree:dispatch': {- args: [request: { kind: 'list' } | ({ kind: 'create' } & WorktreeCreateRequest)];+ args: [+ request:+ | { kind: 'list' }+ | ({ kind: 'create' } & WorktreeCreateRequest)+ | { kind: 'checkout'; branch: string },+ ];result: WorktreeListResult | WorktreeCreateResult;};/** Request main to close the current project's window. */