Beautiful, AI-native markdown IDE and LLM wiki
TypeScript 2nd-brainagent-skillsclaudecodexcompany-braindocsknowledge-knowledge-baseknowledge-managementllmllm-wikillm-wiki-karpathymarkdownmarkdown-editormdmdxnotespkmsecond-brainskills
feat(open-knowledge): folder share links (#1491)
miles-kt-inkeepa43b947ff830
diff --git a/docs/content/features/share.mdx b/docs/content/features/share.mdxindex 76b3cd136..8b6078927 100644--- a/docs/content/features/share.mdx+++ b/docs/content/features/share.mdx@@ -1,13 +1,13 @@---title: Share links-description: Copy a link to any doc and send it to a teammate. Open Knowledge handles the GitHub round-trip, the deep link, and the branch on the other end.+description: Copy a link to any doc or folder and send it to a teammate. Open Knowledge handles the GitHub round-trip, the deep link, and the branch on the other end.----Every doc in Open Knowledge has a Share button in the editor toolbar. Click it and the app copies a `https://openknowledge.ai/d/…` URL to your clipboard. Anyone you send it to lands on a splash page that knows the project and file, and a single click opens the doc in their copy of Open Knowledge.+Open Knowledge has a Share button in the editor toolbar. Click it and the app copies a `https://openknowledge.ai/d/…` URL to your clipboard. Anyone you send it to lands on a splash page that knows the project and target, and a single click opens it in their copy of Open Knowledge.## Sending a share link-Click the Share button to copy a deep link to your file to clipboard. The sharing functionality is backed by GitHub and requires that your project has a remote origin.+Click the Share button to copy a deep link to the current doc or folder to your clipboard. The sharing functionality is backed by GitHub and requires that your project has a remote origin.### Without a remote@@ -22,30 +22,30 @@ If the push fails after the repo was created (auth lost mid-flow, network blip),## Opening a share link-The recipient clicks the URL and lands on a splash page showing the file name, the `owner/repo` path, and the branch from which the file was shared.+The recipient clicks the URL and lands on a splash page showing the target (file or folder) name, the `owner/repo` path, and the branch from which it was shared.Two CTAs sit on the splash page:-- **Open in Open Knowledge** fires the deep link and opens the Open Knowledge desktop app.+- **Open in Open Knowledge** fires the deep link and opens the Open Knowledge desktop app — on the shared doc, folder overview, or project root depending on what was shared.- **Download for macOS** downloads the arm64 DMG for users who do not yet have the desktop app.## What the desktop app does when it receives the linkThe deep link arrives at the desktop app's handler, which runs a three-question receive flow:-1. **Q1: Do you already have this repo?** The app scans recent projects for one whose `gitRemoteUrl` matches the share's `owner/repo`. A hit silently routes to that project (no dialog, the window just opens and focuses the doc).+1. **Q1: Do you already have this repo?** The app scans recent projects for one whose `gitRemoteUrl` matches the share's `owner/repo`. A hit silently routes to that project (no dialog, the window just opens and navigates to the shared doc, folder, or project root).2. **Q2: Clone or locate?** If Q1 misses, a dialog asks "Clone to a new folder" or "I already have it locally". The locate path lets you point at an existing folder.3. **Q3: Clone.** On the clone path, the app runs an auth check, asks where to put the folder, then runs `git clone -b <share-branch>` so the new checkout lands on the right branch before opening.### Receiving on a different branch-If you have the repo open locally but on a different branch, the app falls through to a branch-switch dialog instead of silently opening the wrong content. Behavior depends on whether the shared file exists on your current branch:+If you have the repo open locally but on a different branch, the app falls through to a branch-switch dialog instead of silently opening the wrong content. Behavior depends on whether the shared target (file or folder) exists on your current branch:-- **File exists on both branches.** The dialog offers `Open on <current-branch>` or `Switch to <share-branch> and open`.-- **File only on the share's branch.** The dialog offers `Switch to <share-branch> and open` plus Cancel.+- **Target exists on both branches.** The dialog offers `Open on <current-branch>` or `Switch to <share-branch> and open`.+- **Target only on the share's branch.** The dialog offers `Switch to <share-branch> and open` plus Cancel.### Receiving without push permission-If the shared repo is one your GitHub account can't push to (you're not a collaborator on a public repo, or you have read-only access on a private one), Open Knowledge skips the usual "Enable auto-sync?" prompt and shows the sync toggle as disabled with a clear inline reason instead of letting you turn on a sync that would just fail with a 403. The same disabled state with the same reason text appears in **Settings → Sync**. If the project owner grants you write access later, click the sync indicator to re-check; Open Knowledge will pick up the change without an app restart. See [GitHub sync: GitHub-side blockers](/docs/features/github-sync#github-side-blockers) for the full set of permission shapes the sync UI handles.+If the shared repo is one your GitHub account can't push to (you're not a collaborator on a public repo, or you have read-only access on a private one), Open Knowledge skips the usual "Enable auto-sync?" prompt. Sync is also disabled for the same reason in **Settings → Sync**. If the project owner grants you write access later, click the sync indicator to re-check; Open Knowledge will pick up the change without an app restart. See [GitHub sync: GitHub-side blockers](/docs/features/github-sync#github-side-blockers) for the full set of permission shapes the sync UI handles.See [GitHub sync](/docs/features/github-sync) for how to automatically sync changes to GitHub, and [Timeline and recovery](/docs/features/timeline-and-recovery) for per-doc history once the doc is open.diff --git a/docs/src/app/d/[encoded]/page.tsx b/docs/src/app/d/[encoded]/page.tsxindex 3334ede7d..595a5a642 100644--- a/docs/src/app/d/[encoded]/page.tsx+++ b/docs/src/app/d/[encoded]/page.tsx@@ -1,4 +1,10 @@-import { ArrowRightIcon, DownloadIcon, ExternalLinkIcon, GitBranchIcon } from 'lucide-react';+import {+ ArrowRightIcon,+ DownloadIcon,+ ExternalLinkIcon,+ FolderIcon,+ GitBranchIcon,+} from 'lucide-react';import type { Metadata } from 'next';import Image from 'next/image';import Link from 'next/link';@@ -65,7 +71,9 @@ export default async function SplashPage({ params }: SplashPageProps) {<section className="px-6 pt-32 pb-16 md:pt-44 md:pb-20"><div className="mx-auto max-w-3xl"><p className="mb-6 text-sm font-medium italic text-[var(--slide-accent-strong)]">- Shared via Open Knowledge+ {view.target === 'folder'+ ? 'Folder shared via Open Knowledge'+ : 'Shared via Open Knowledge'}</p><h1@@ -98,6 +106,16 @@ export default async function SplashPage({ params }: SplashPageProps) {{view.repoPath}</p>+ {view.target === 'folder' ? (+ <p+ className="mt-2 inline-flex items-center gap-2 text-sm text-[var(--slide-muted)]"+ data-testid="splash-folder-indicator"+ >+ <FolderIcon className="size-4" aria-hidden="true" />+ <span>Folder</span>+ </p>+ ) : null}+{view.isDefaultBranch ? null : (<pclassName="mt-2 inline-flex items-center gap-2 text-sm text-[var(--slide-muted)]"diff --git a/docs/src/lib/share-splash.test.ts b/docs/src/lib/share-splash.test.tsindex c6236377d..20589987d 100644--- a/docs/src/lib/share-splash.test.ts+++ b/docs/src/lib/share-splash.test.ts@@ -2,8 +2,8 @@ import { describe, expect, test } from 'bun:test';import { encodeShareUrl } from '@inkeep/open-knowledge-core';import { buildCustomSchemeUrl, buildSplashViewModel, SPLASH_DOWNLOAD_URL } from './share-splash.ts';-function encodeV1(blobUrl: string): string {- return encodeShareUrl(blobUrl);+function encodeV1(sharedUrl: string): string {+ return encodeShareUrl(sharedUrl);}function uint8ArrayToBase64Url(bytes: Uint8Array): string {@@ -23,18 +23,74 @@ describe('buildSplashViewModel', () => {expect(view).toEqual({kind: 'ok',+ target: 'doc',filename: 'marketing-playbook.md',owner: 'inkeep',repo: 'playbooks',repoPath: 'inkeep/playbooks',branch: 'main',isDefaultBranch: true,- blobUrl,+ sharedUrl: blobUrl,customSchemeUrl: `openknowledge://share?url=${encodeURIComponent(blobUrl)}`,githubUrl: blobUrl,});});+ test('decodes a folder (tree) share URL into a valid ok view with target=folder', () => {+ const treeUrl = 'https://github.com/inkeep/playbooks/tree/main/marketing/campaigns';+ const encoded = encodeV1(treeUrl);++ const view = buildSplashViewModel(encoded);++ expect(view).toEqual({+ kind: 'ok',+ target: 'folder',+ filename: 'campaigns',+ owner: 'inkeep',+ repo: 'playbooks',+ repoPath: 'inkeep/playbooks',+ branch: 'main',+ isDefaultBranch: true,+ sharedUrl: treeUrl,+ customSchemeUrl: `openknowledge://share?url=${encodeURIComponent(treeUrl)}`,+ githubUrl: treeUrl,+ });+ });++ test('decodes a repo/branch-root folder (empty tree path) and falls back to the repo name', () => {+ const treeUrl = 'https://github.com/inkeep/playbooks/tree/main';+ const view = buildSplashViewModel(encodeV1(treeUrl));+ expect(view.kind).toBe('ok');+ if (view.kind === 'ok') {+ expect(view.target).toBe('folder');+ expect(view.filename).toBe('playbooks');+ expect(view.repoPath).toBe('inkeep/playbooks');+ expect(view.sharedUrl).toBe(treeUrl);+ }+ });++ test('tolerates a trailing slash on a root-folder tree URL', () => {+ const treeUrl = 'https://github.com/inkeep/playbooks/tree/main/';+ const view = buildSplashViewModel(encodeV1(treeUrl));+ expect(view.kind).toBe('ok');+ if (view.kind === 'ok') {+ expect(view.target).toBe('folder');+ expect(view.filename).toBe('playbooks');+ }+ });++ test('decodes a folder share on a percent-encoded slash-bearing branch', () => {+ const treeUrl = 'https://github.com/inkeep/playbooks/tree/feat%2Fshare/docs/sub';+ const view = buildSplashViewModel(encodeV1(treeUrl));+ expect(view.kind).toBe('ok');+ if (view.kind === 'ok') {+ expect(view.target).toBe('folder');+ expect(view.branch).toBe('feat/share');+ expect(view.filename).toBe('sub');+ expect(view.isDefaultBranch).toBe(false);+ }+ });+test('preserves the filename VERBATIM — no title-case, no extension stripping (D29)', () => {const cases: Array<{ blobUrl: string; expectedFilename: string }> = [{@@ -131,9 +187,9 @@ describe('buildSplashViewModel', () => {expect(view).toEqual({ kind: 'invalid' });});- test('returns `invalid` when the decoded URL is not a /blob/ URL', () => {+ test('returns `invalid` when the decoded URL is neither a /blob/ nor /tree/ URL', () => {const view = buildSplashViewModel(- encodeV1('https://github.com/owner/repo/tree/main/README.md'),+ encodeV1('https://github.com/owner/repo/commits/main/README.md'),);expect(view).toEqual({ kind: 'invalid' });});@@ -156,7 +212,7 @@ describe('buildSplashViewModel', () => {const view = buildSplashViewModel(encoded);expect(view.kind).toBe('ok');if (view.kind === 'ok') {- expect(view.blobUrl).toBe(blobUrl);+ expect(view.sharedUrl).toBe(blobUrl);}});@@ -166,7 +222,7 @@ describe('buildSplashViewModel', () => {const view = buildSplashViewModel(encoded);expect(view.kind).toBe('ok');if (view.kind === 'ok') {- expect(view.blobUrl).toBe(blobUrl);+ expect(view.sharedUrl).toBe(blobUrl);}});});diff --git a/docs/src/lib/share-splash.ts b/docs/src/lib/share-splash.tsindex d1373ed53..65434d149 100644--- a/docs/src/lib/share-splash.ts+++ b/docs/src/lib/share-splash.ts@@ -2,7 +2,7 @@ const SHARE_URL_VERSION_V1 = 0x01;interface DecodedShare {version: number;- blobUrl: string;+ sharedUrl: string;}class UnsupportedShareVersionError extends Error {@@ -44,14 +44,14 @@ function decodeShareUrl(encoded: string): DecodedShare {}const decoder = new TextDecoder('utf-8', { fatal: true });- let blobUrl: string;+ let sharedUrl: string;try {- blobUrl = decoder.decode(bytes.subarray(1));+ sharedUrl = decoder.decode(bytes.subarray(1));} catch {throw new InvalidShareUrlError('Share payload body is not valid UTF-8');}- return { version, blobUrl };+ return { version, sharedUrl };}function base64UrlToUint8Array(input: string): Uint8Array {@@ -75,6 +75,17 @@ export interface ParsedGitHubBlobUrl {path: string;}+export interface ParsedGitHubTreeUrl {+ owner: string;+ repo: string;+ branch: string;+ path: string;+}++export type ParsedGitHubShareTarget =+ | { kind: 'doc'; owner: string; repo: string; branch: string; path: string }+ | { kind: 'folder'; owner: string; repo: string; branch: string; path: string };+function parseGitHubBlobUrl(input: string): ParsedGitHubBlobUrl | null {let url: URL;try {@@ -111,11 +122,61 @@ function parseGitHubBlobUrl(input: string): ParsedGitHubBlobUrl | null {return { owner, repo, branch, path: pathParts.join('/') };}+function parseGitHubTreeUrl(input: string): ParsedGitHubTreeUrl | null {+ let url: URL;+ try {+ url = new URL(input);+ } catch {+ return null;+ }++ if (url.hostname !== 'github.com' && url.hostname !== 'www.github.com') {+ return null;+ }++ const rawSegments = url.pathname.split('/');++ if (rawSegments.length < 5) return null;+ if (rawSegments[0] !== '') return null; // leading-slash hygiene+ if (rawSegments[3] !== 'tree') return null;++ const pathSegmentsRaw = rawSegments.slice(5);+ if (pathSegmentsRaw.length === 1 && pathSegmentsRaw[0] === '') pathSegmentsRaw.pop();++ let owner: string;+ let repo: string;+ let branch: string;+ let pathParts: string[];+ try {+ owner = decodeURIComponent(rawSegments[1]);+ repo = decodeURIComponent(rawSegments[2]);+ branch = decodeURIComponent(rawSegments[4]);+ pathParts = pathSegmentsRaw.map((s) => decodeURIComponent(s));+ } catch {+ return null;+ }++ if (!owner || !repo || !branch) return null;+ if (pathParts.some((p) => p.length === 0)) return null;++ return { owner, repo, branch, path: pathParts.join('/') };+}++function parseGitHubShareUrl(input: string): ParsedGitHubShareTarget | null {+ const blob = parseGitHubBlobUrl(input);+ if (blob) return { kind: 'doc', ...blob };++ const tree = parseGitHubTreeUrl(input);+ if (tree) return { kind: 'folder', ...tree };++ return null;+}+export const SPLASH_DOWNLOAD_URL ='https://github.com/inkeep/open-knowledge/releases/latest/download/Open-Knowledge-arm64.dmg';-export function buildCustomSchemeUrl(blobUrl: string): string {- return `openknowledge://share?url=${encodeURIComponent(blobUrl)}`;+export function buildCustomSchemeUrl(sharedUrl: string): string {+ return `openknowledge://share?url=${encodeURIComponent(sharedUrl)}`;}function isCommonDefaultBranch(branch: string): boolean {@@ -125,13 +186,14 @@ function isCommonDefaultBranch(branch: string): boolean {export type SplashView =| {kind: 'ok';+ target: 'doc' | 'folder';filename: string;owner: string;repo: string;repoPath: string;branch: string;isDefaultBranch: boolean;- blobUrl: string;+ sharedUrl: string;customSchemeUrl: string;githubUrl: string;}@@ -152,25 +214,27 @@ export function buildSplashViewModel(encoded: string): SplashView {return { kind: 'invalid' };}- const parsed = parseGitHubBlobUrl(decoded.blobUrl);+ const parsed = parseGitHubShareUrl(decoded.sharedUrl);if (!parsed) {return { kind: 'invalid' };}- const { owner, repo, branch, path } = parsed;- const segments = path.split('/');- const filename = segments[segments.length - 1] ?? path;+ const { kind, owner, repo, branch, path } = parsed;+ const segments = path.split('/').filter((s) => s.length > 0);+ const basename = segments[segments.length - 1];+ const filename = basename ?? repo;return {kind: 'ok',+ target: kind,filename,owner,repo,repoPath: `${owner}/${repo}`,branch,isDefaultBranch: isCommonDefaultBranch(branch),- blobUrl: decoded.blobUrl,- customSchemeUrl: buildCustomSchemeUrl(decoded.blobUrl),- githubUrl: decoded.blobUrl,+ sharedUrl: decoded.sharedUrl,+ customSchemeUrl: buildCustomSchemeUrl(decoded.sharedUrl),+ githubUrl: decoded.sharedUrl,};}diff --git a/packages/app/src/App.tsx b/packages/app/src/App.tsxindex d788e4dfc..080f27010 100644--- a/packages/app/src/App.tsx+++ b/packages/app/src/App.tsx@@ -25,7 +25,7 @@ import {} from '@/editor/DocumentContext';import { fetchApiConfig } from '@/lib/api-config';import { ConfigProvider } from '@/lib/config-provider';-import { assetPathFromHash, docNameFromHash } from '@/lib/doc-hash';+import { assetPathFromHash, docNameFromHash, isContentRootHash } from '@/lib/doc-hash';import { mark, ProfilerBoundary } from '@/lib/perf';import { isSettingsShortcut, SETTINGS_OPEN_HASH } from '@/lib/use-settings-route';@@ -102,6 +102,11 @@ function NavigationHandler() {});return;}+ if (isContentRootHash(window.location.hash)) {+ mark('ok/nav/hash-change', { docName: null, kind: 'folder' });+ openTargetTransition({ kind: 'folder', target: '', folderPath: '' });+ return;+ }const docName = docNameFromHash(window.location.hash);if (!docName) {mark('ok/nav/hash-change', { docName: null, kind: 'clear' });diff --git a/packages/app/src/components/EditorHeader.test.ts b/packages/app/src/components/EditorHeader.test.tsindex f0a3ecb9c..0eee8f277 100644--- a/packages/app/src/components/EditorHeader.test.ts+++ b/packages/app/src/components/EditorHeader.test.ts@@ -120,6 +120,31 @@ describe('EditorHeader — sparkle icon 3-scope dispatch (US-011 source-level)',expect(SRC).toMatch(/<OpenInAgentMenu[\s\S]*?input=\{menuHandoffInput\}/);});+ test('builds a shareInput: ShareTargetInput | null via an IIFE mirroring handoffInput (US-012)', () => {+ expect(SRC).toContain('buildDocShareInput');+ expect(SRC).toContain('buildFolderShareInput');+ expect(SRC).toMatch(/const\s+shareInput\s*:\s*ShareTargetInput\s*\|\s*null\s*=\s*\(\(\)\s*=>/);+ });++ test('folder-active routes shareInput to buildFolderShareInput with the folderPath', () => {+ expect(SRC).toMatch(+ /activeTarget\?\.kind\s*===\s*['"]folder['"][\s\S]{0,80}buildFolderShareInput\s*\(\s*activeTarget\.folderPath/,+ );+ });++ test('active-doc (non-folder) routes shareInput to buildDocShareInput; otherwise null', () => {+ expect(SRC).toMatch(+ /if\s*\(\s*activeDocName\s*\)[\s\S]{0,60}buildDocShareInput\s*\(\s*activeDocName/,+ );+ expect(SRC).toMatch(/return\s+null;[\s\S]{0,40}\}\)\(\);/);+ });++ test('ShareButton receives the shareInput prop (always-render-but-disable-when-null contract)', () => {+ expect(SRC).toMatch(+ /<ShareButton\s+input=\{shareInput\}\s+onClickWhenNoRemote=\{[\s\S]*?\}\s*\/>/,+ );+ });+test('Save-version control is NOT in the header (moved to the timeline pane)', () => {expect(SRC).not.toMatch(/Checkpoint version/);expect(SRC).not.toMatch(/onSaveVersion/);diff --git a/packages/app/src/components/EditorHeader.tsx b/packages/app/src/components/EditorHeader.tsxindex 4519447f9..ff7151952 100644--- a/packages/app/src/components/EditorHeader.tsx+++ b/packages/app/src/components/EditorHeader.tsx@@ -7,6 +7,11 @@ import { SidebarTrigger, useSidebar } from '@/components/ui/sidebar';import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip';import { useDocumentContext } from '@/editor/DocumentContext';import { formatShortcut } from '@/lib/keyboard-shortcuts';+import {+ buildDocShareInput,+ buildFolderShareInput,+ type ShareTargetInput,+} from '@/lib/share/run-share-action';import { useWorkspace } from '@/lib/use-workspace';import { cn } from '@/lib/utils';import { PresenceBar } from '@/presence/PresenceBar';@@ -64,6 +69,16 @@ export function EditorHeader({})();const menuHandoffInput = openInAgentMenuInput ?? handoffInput;+ const shareInput: ShareTargetInput | null = (() => {+ if (activeTarget?.kind === 'folder') {+ return buildFolderShareInput(activeTarget.folderPath);+ }+ if (activeDocName) {+ return buildDocShareInput(activeDocName);+ }+ return null;+ })();+const isElectronHost = typeof window !== 'undefined' && window.okDesktop != null;const isCollapsed = sidebarState === 'collapsed';@@ -143,7 +158,7 @@ export function EditorHeader({open={openInAgentMenuOpen}onOpenChange={onOpenInAgentMenuOpenChange}/>- <ShareButton onClickWhenNoRemote={() => setPublishOpen(true)} />+ <ShareButton input={shareInput} onClickWhenNoRemote={() => setPublishOpen(true)} /><PublishToGitHubDialog open={publishOpen} onOpenChange={setPublishOpen} /><SyncStatusBadge onSignIn={onSignIn} onSetIdentity={onSetIdentity} /><PresenceBar />diff --git a/packages/app/src/components/FolderOverview.tsx b/packages/app/src/components/FolderOverview.tsxindex ff0592f90..928d4efd1 100644--- a/packages/app/src/components/FolderOverview.tsx+++ b/packages/app/src/components/FolderOverview.tsx@@ -148,6 +148,7 @@ export function FolderOverview({ folderPath }: { folderPath: string }) {const data = buildFolderOverviewData(folderPath, { pages, pageTitles, pageMeta, folderPaths });const sorted = sortEntries(data.children, sortKey, sortDir);+ const heading = data.title || (folderPath === '' ? t`All files` : data.title);function handleSort(key: SortKey) {if (key === sortKey) {@@ -166,7 +167,7 @@ export function FolderOverview({ folderPath }: { folderPath: string }) {<div className="flex flex-wrap items-start justify-between gap-3"><div className="flex items-center gap-2"><FolderOpen className="size-5 text-muted-foreground" />- <h1 className="text-2xl font-light tracking-tight">{data.title}</h1>+ <h1 className="text-2xl font-light tracking-tight">{heading}</h1></div><Button onClick={() => setCreateDialogOpen(true)}><Plus className="size-4" />diff --git a/packages/app/src/components/PublishToGitHubDialog.tsx b/packages/app/src/components/PublishToGitHubDialog.tsxindex 921410552..afdf83730 100644--- a/packages/app/src/components/PublishToGitHubDialog.tsx+++ b/packages/app/src/components/PublishToGitHubDialog.tsx@@ -177,7 +177,7 @@ export function PublishToGitHubDialog({ open, onOpenChange }: PublishToGitHubDiavoid (async () => {try {const docPath = docNameToMarkdownPath(activeDocName);- const response = await requestShareConstructUrl(docPath);+ const response = await requestShareConstructUrl({ kind: 'doc', docPath });if (cancelled) return;if (response.ok) {setShareUrl(response.shareUrl);diff --git a/packages/app/src/components/ShareBranchSwitchDialog.dom.test.tsx b/packages/app/src/components/ShareBranchSwitchDialog.dom.test.tsxindex a1bfd81f1..51a1af48b 100644--- a/packages/app/src/components/ShareBranchSwitchDialog.dom.test.tsx+++ b/packages/app/src/components/ShareBranchSwitchDialog.dom.test.tsx@@ -67,7 +67,7 @@ function makeBridge(overrides: Partial<BridgeMock> = {}): {currentBranch: 'main',currentHeadSha: 'aaaaaaa',detached: false,- shareFileExists: true,+ shareTargetExists: true,dirtyConflicts: { conflicts: false, files: [] },}),),@@ -97,8 +97,8 @@ function projectBranchSwitchPayload(): Extract<owner: 'inkeep',repo: 'open-knowledge',branch: 'feat/branch-x',- path: 'docs/notes.md',- blobUrl: 'https://github.com/inkeep/open-knowledge/blob/feat/branch-x/docs/notes.md',+ sharedUrl: 'https://github.com/inkeep/open-knowledge/blob/feat/branch-x/docs/notes.md',+ target: { kind: 'doc', docPath: 'docs/notes.md' },},projectPath: '/Users/alice/projects/open-knowledge',currentBranch: 'main',@@ -129,8 +129,8 @@ describe('ShareBranchSwitchDialog — payload gating', () => {owner: 'inkeep',repo: 'open-knowledge',branch: 'main',- path: 'docs/x.md',- blobUrl: 'https://github.com/inkeep/open-knowledge/blob/main/docs/x.md',+ sharedUrl: 'https://github.com/inkeep/open-knowledge/blob/main/docs/x.md',+ target: { kind: 'doc', docPath: 'docs/x.md' },},});return () => {};@@ -160,7 +160,8 @@ describe('ShareBranchSwitchDialog — payload gating', () => {expect(calls.fetchBranchInfo).toHaveBeenCalledWith({projectPath: payload.projectPath,branch: payload.share.branch,- docPath: payload.share.path,+ kind: 'doc',+ path: 'docs/notes.md',});});});@@ -226,7 +227,7 @@ describe('ShareBranchSwitchDialog — Open-in-current dispatch', () => {const firstArg = calls.open.mock.calls[0]?.[0] as Record<string, unknown>;expect(firstArg).toBeDefined();expect(firstArg.path).toBe(payload.projectPath);- expect(firstArg.pendingDeepLinkDoc).toBe(payload.share.path);+ expect(firstArg.pendingDeepLinkTarget).toEqual({ kind: 'doc', path: 'docs/notes.md' });expect(firstArg.pendingBranch).toBeUndefined();expect(store.getSnapshot()).toBeNull();});@@ -307,7 +308,7 @@ describe('ShareBranchSwitchDialog — Switch path (runCheckout + CC1 gate)', ()});const openArg = calls.open.mock.calls[0]?.[0] as Record<string, unknown>;expect(openArg).toBeDefined();- expect(openArg.pendingDeepLinkDoc).toBe(payload.share.path);+ expect(openArg.pendingDeepLinkTarget).toEqual({ kind: 'doc', path: 'docs/notes.md' });expect(openArg.pendingBranch).toBe(payload.share.branch);});@@ -401,7 +402,7 @@ describe('ShareBranchSwitchDialog — Switch path (runCheckout + CC1 gate)', ()});await waitFor(() => {expect(toastError).toHaveBeenCalledWith(- 'Branch switch timed out — try opening the doc manually.',+ 'Branch switch timed out — try opening the document manually.',);});expect(calls.open).not.toHaveBeenCalled();diff --git a/packages/app/src/components/ShareBranchSwitchDialog.test.ts b/packages/app/src/components/ShareBranchSwitchDialog.test.tsindex a43de2084..82a9f01d3 100644--- a/packages/app/src/components/ShareBranchSwitchDialog.test.ts+++ b/packages/app/src/components/ShareBranchSwitchDialog.test.ts@@ -117,7 +117,7 @@ describe('ShareBranchSwitchDialog — branch-info + checkout wiring', () => {expect(timeoutIdx).toBeGreaterThan(completeIdx);const okBranchBody = SRC.slice(completeIdx, timeoutIdx);expect(okBranchBody).toMatch(/bridge\.project[\s\n.]+open\(/);- expect(okBranchBody).toContain('pendingDeepLinkDoc');+ expect(okBranchBody).toContain('pendingDeepLinkTarget');expect(okBranchBody).toContain('pendingBranch');});@@ -137,7 +137,7 @@ describe('ShareBranchSwitchDialog — open-current (OQ2 sibling) + cancel', () =expect(endIdx).toBeGreaterThan(idx);const body = SRC.slice(idx, endIdx);expect(body).toMatch(/bridge\.project[\s\n.]+open\(/);- expect(body).toContain('pendingDeepLinkDoc');+ expect(body).toContain('pendingDeepLinkTarget');expect(body).not.toContain('pendingBranch');});diff --git a/packages/app/src/components/ShareBranchSwitchDialog.tsx b/packages/app/src/components/ShareBranchSwitchDialog.tsxindex 4f06f1471..35a8a0dcb 100644--- a/packages/app/src/components/ShareBranchSwitchDialog.tsx+++ b/packages/app/src/components/ShareBranchSwitchDialog.tsx@@ -14,7 +14,11 @@ import {Dialog as DialogRoot,DialogTitle,} from '@/components/ui/dialog';-import type { OkDesktopBridge, OkShareReceivedPayload } from '@/lib/desktop-bridge-types';+import {+ type OkDesktopBridge,+ type OkShareReceivedPayload,+ shareTargetPath,+} from '@/lib/desktop-bridge-types';import {applyBranchInfo,applyCheckoutOutcome,@@ -56,6 +60,7 @@ export function ShareBranchSwitchDialog({const awaitBranchSwitchedStartedRef = useRef(false);const active = isBranchSwitchPayload(payload) ? payload : null;+ const targetNoun = active?.share.target.kind === 'folder' ? t`folder` : t`document`;// biome-ignore lint/correctness/useExhaustiveDependencies: payload is the reset trigger; effect body only resets state.useEffect(() => {@@ -73,7 +78,8 @@ export function ShareBranchSwitchDialog({.fetchBranchInfo({projectPath: active.projectPath,branch: active.share.branch,- docPath: active.share.path,+ kind: active.share.target.kind,+ path: shareTargetPath(active.share.target),}).then((info) => {setBranchSwitchState((prev) => applyBranchInfo(prev, info));@@ -119,7 +125,10 @@ export function ShareBranchSwitchDialog({path: active.projectPath,target: 'new-window',entryPoint: 'share-receive',- pendingDeepLinkDoc: active.share.path,+ pendingDeepLinkTarget: {+ kind: active.share.target.kind,+ path: shareTargetPath(active.share.target),+ },pendingBranch: shareBranch,}).catch((err) => {@@ -128,7 +137,7 @@ export function ShareBranchSwitchDialog({err instanceof Error ? err.message : err,);toast.error(- t`Branch switched but the document could not be opened — try navigating to it manually.`,+ t`Branch switched but the ${targetNoun} could not be opened — try navigating to it manually.`,);});store.dismiss();@@ -140,7 +149,7 @@ export function ShareBranchSwitchDialog({branch: shareBranch,}),);- toast.error(t`Branch switch timed out — try opening the doc manually.`);+ toast.error(t`Branch switch timed out — try opening the ${targetNoun} manually.`);store.dismiss();}).catch((err) => {@@ -149,7 +158,7 @@ export function ShareBranchSwitchDialog({'[receive] awaitBranchSwitched rejected',err instanceof Error ? err.message : err,);- toast.error(t`Branch switch failed — try opening the doc manually.`);+ toast.error(t`Branch switch failed — try opening the ${targetNoun} manually.`);store.dismiss();});return () => {@@ -173,7 +182,7 @@ export function ShareBranchSwitchDialog({branch: shareBranch,}),);- setBranchSwitchState((prev) => markSwitching(prev, share.path));+ setBranchSwitchState((prev) => markSwitching(prev, shareTargetPath(share.target)));void bridge.project.runCheckout({ projectPath, branch: shareBranch }).then((response) => {@@ -218,14 +227,14 @@ export function ShareBranchSwitchDialog({path: projectPath,target: 'new-window',entryPoint: 'share-receive',- pendingDeepLinkDoc: share.path,+ pendingDeepLinkTarget: { kind: share.target.kind, path: shareTargetPath(share.target) },}).catch((err) => {console.warn('[receive] warm-focus-dispatch-failed branch_action=open-current',err instanceof Error ? err.message : err,);- toast.error(t`The document could not be opened — try navigating to it manually.`);+ toast.error(t`The ${targetNoun} could not be opened — try navigating to it manually.`);});store.dismiss();}@@ -244,7 +253,7 @@ export function ShareBranchSwitchDialog({path: target,target: 'new-window',entryPoint: 'share-receive',- pendingDeepLinkDoc: share.path,+ pendingDeepLinkTarget: { kind: share.target.kind, path: shareTargetPath(share.target) },pendingBranch: shareBranch,}).catch((err) => {@@ -296,17 +305,18 @@ export function ShareBranchSwitchDialog({><DialogHeader><DialogTitle>- <Trans>Open shared document</Trans>+ <Trans>Open shared {targetNoun}</Trans></DialogTitle><DialogDescription className="sr-only"><Trans>- {share.owner}/{share.repo} — {share.path}+ {share.owner}/{share.repo} — {shareTargetPath(share.target)}</Trans></DialogDescription><ShareMetadataRowsowner={share.owner}repo={share.repo}- path={share.path}+ path={shareTargetPath(share.target)}+ kind={share.target.kind}branch={share.branch}testId="share-branch-switch-metadata"branchTestId="share-branch-switch-metadata-branch"@@ -354,7 +364,7 @@ export function ShareBranchSwitchDialog({) : variant?.kind === 'D' ? (<p className="text-sm text-muted-foreground"><Trans>- This doc only exists on branch{' '}+ This {targetNoun} only exists on branch{' '}<code className="rounded bg-muted px-1 py-0.5 text-foreground/80">{shareBranch}</code>@@ -365,7 +375,7 @@ export function ShareBranchSwitchDialog({) : variant?.kind === 'B' ? (<p className="text-sm text-muted-foreground"><Trans>- This doc was shared from branch{' '}+ This {targetNoun} was shared from branch{' '}<code className="rounded bg-muted px-1 py-0.5 text-foreground/80">{shareBranch}</code>@@ -379,7 +389,7 @@ export function ShareBranchSwitchDialog({) : (<p className="text-sm text-muted-foreground"><Trans>- This doc was shared from branch{' '}+ This {targetNoun} was shared from branch{' '}<code className="rounded bg-muted px-1 py-0.5 text-foreground/80">{shareBranch}</code>diff --git a/packages/app/src/components/ShareButton.dom.test.tsx b/packages/app/src/components/ShareButton.dom.test.tsxnew file mode 100644index 000000000..0d2761432--- /dev/null+++ b/packages/app/src/components/ShareButton.dom.test.tsx@@ -0,0 +1,73 @@+import { afterEach, beforeEach, describe, expect, mock, test } from 'bun:test';+import { cleanup, render, screen } from '@testing-library/react';+import type { ShareTargetInput } from '@/lib/share/run-share-action';++type WindowGlobals = { NodeFilter?: typeof NodeFilter };+type GlobalWithDomShims = typeof globalThis &+ WindowGlobals & { window?: WindowGlobals; ResizeObserver?: unknown };+const globalWithDomShims = globalThis as GlobalWithDomShims;+if (+ globalWithDomShims.NodeFilter === undefined &&+ globalWithDomShims.window?.NodeFilter !== undefined+) {+ globalWithDomShims.NodeFilter = globalWithDomShims.window.NodeFilter;+}+if (globalWithDomShims.ResizeObserver === undefined) {+ class NoopResizeObserver {+ observe() {}+ unobserve() {}+ disconnect() {}+ }+ globalWithDomShims.ResizeObserver = NoopResizeObserver;+}++mock.module('@/hooks/use-git-sync-status', () => ({+ useGitSyncStatusDetailed: () => ({+ status: { hasRemote: true },+ fetchError: null,+ }),+}));++const { ShareButton } = await import('./ShareButton');+const { TooltipProvider } = await import('@/components/ui/tooltip');++function renderShareButton(input: ShareTargetInput | null) {+ return render(+ <TooltipProvider>+ <ShareButton input={input} onClickWhenNoRemote={() => {}} />+ </TooltipProvider>,+ );+}++describe('ShareButton', () => {+ beforeEach(() => {+ if (typeof window !== 'undefined') window.location.hash = '';+ });+ afterEach(() => {+ cleanup();+ });++ test('renders an enabled button for a folder target', () => {+ renderShareButton({ kind: 'folder', folderRelativePath: 'guides' });++ const button = screen.getByTestId('share-button');+ expect(button).not.toBeNull();+ expect((button as HTMLButtonElement).disabled).toBe(false);+ });++ test('renders an enabled button for a doc target', () => {+ renderShareButton({ kind: 'doc', docName: 'notes' });++ const button = screen.getByTestId('share-button');+ expect(button).not.toBeNull();+ expect((button as HTMLButtonElement).disabled).toBe(false);+ });++ test('renders a DISABLED button (not absent) when input is null', () => {+ renderShareButton(null);++ const button = screen.queryByTestId('share-button');+ expect(button).not.toBeNull();+ expect((button as HTMLButtonElement).disabled).toBe(true);+ });+});diff --git a/packages/app/src/components/ShareButton.test.ts b/packages/app/src/components/ShareButton.test.tsindex afb633604..e33e6aa9b 100644--- a/packages/app/src/components/ShareButton.test.ts+++ b/packages/app/src/components/ShareButton.test.ts@@ -14,10 +14,11 @@ describe('ShareButton — load-bearing structural guards', () => {expect(SRC).toContain('runShareAction');});- test('reads activeDocName via useDocumentContext (single source of focused doc)', () => {- expect(SRC).toContain("from '@/editor/DocumentContext'");- expect(SRC).toContain('useDocumentContext');- expect(SRC).toContain('activeDocName');+ test('takes a discriminated ShareTargetInput (doc|folder) | null via props (not a self-read of activeDocName)', () => {+ expect(SRC).toContain('ShareTargetInput');+ expect(SRC).toContain("from '@/lib/share/run-share-action'");+ expect(SRC).toMatch(/input\s*:\s*ShareTargetInput\s*\|\s*null/);+ expect(SRC).not.toContain('useDocumentContext');});test('reads hasRemote via useGitSyncStatusDetailed (no extra fetch)', () => {@@ -54,8 +55,8 @@ describe('ShareButton — load-bearing structural guards', () => {expect(SRC).toContain('<Trans>Share</Trans>');});- test('Button carries an aria-label so the icon-bearing affordance is screen-reader navigable', () => {- expect(SRC).toMatch(/aria-label=\{t`Share doc`\}/);+ test('Button carries a kind-aware aria-label so the icon-bearing affordance is screen-reader navigable', () => {+ expect(SRC).toMatch(/aria-label=\{[\s\S]*?t`Share folder`[\s\S]*?t`Share doc`[\s\S]*?\}/);});test('renders the Share2 icon from lucide-react', () => {@@ -68,15 +69,10 @@ describe('ShareButton — load-bearing structural guards', () => {});test('busy flag disables the button so double-clicks cannot fire two requests', () => {- expect(SRC).toMatch(/disabled=\{busy\}/);expect(SRC).toMatch(/setBusy\(true\)/);expect(SRC).toMatch(/setBusy\(false\)/);});- test('returns null when no doc is focused (button has nothing to share)', () => {- expect(SRC).toMatch(/if \(!activeDocName\) return null;/);- });-test('no React Compiler escape hatches (forwardRef / memo / useMemo / useCallback)', () => {expect(SRC).not.toMatch(/\bforwardRef\b/);expect(SRC).not.toMatch(/\buseMemo\b/);diff --git a/packages/app/src/components/ShareButton.tsx b/packages/app/src/components/ShareButton.tsxindex 3b67fa611..5e29af846 100644--- a/packages/app/src/components/ShareButton.tsx+++ b/packages/app/src/components/ShareButton.tsx@@ -5,18 +5,17 @@ import { toast } from 'sonner';import { Button } from '@/components/ui/button';import { Input } from '@/components/ui/input';import { Popover, PopoverAnchor, PopoverContent } from '@/components/ui/popover';-import { useDocumentContext } from '@/editor/DocumentContext';import { useGitSyncStatusDetailed } from '@/hooks/use-git-sync-status';import { scheduleClipboardWrite } from '@/lib/share/clipboard-adapter';-import { runShareAction } from '@/lib/share/run-share-action';+import { runShareAction, type ShareTargetInput } from '@/lib/share/run-share-action';export interface ShareButtonProps {+ input: ShareTargetInput | null;onClickWhenNoRemote: () => void;}-export function ShareButton({ onClickWhenNoRemote }: ShareButtonProps) {+export function ShareButton({ input, onClickWhenNoRemote }: ShareButtonProps) {const { t } = useLingui();- const { activeDocName } = useDocumentContext();const { status } = useGitSyncStatusDetailed();const [busy, setBusy] = useState(false);const [clipboardFailedUrl, setClipboardFailedUrl] = useState<string | null>(null);@@ -28,19 +27,18 @@ export function ShareButton({ onClickWhenNoRemote }: ShareButtonProps) {fallbackInputRef.current.select();}, [clipboardFailedUrl]);- if (!activeDocName) return null;-const hasRemote = status?.hasRemote === true;+ const triggerDisabled = input === null;async function handleClick() {if (busy) return;- if (!activeDocName) return;+ if (input === null) return;setBusy(true);setClipboardFailedUrl(null);try {const result = await runShareAction({- docName: activeDocName,+ ...input,hasRemote,onClickWhenNoRemote,},@@ -78,9 +76,9 @@ export function ShareButton({ onClickWhenNoRemote }: ShareButtonProps) {<Buttonvariant="ghost"size="sm"- aria-label={t`Share doc`}+ aria-label={input?.kind === 'folder' ? t`Share folder` : t`Share doc`}onClick={handleClick}- disabled={busy}+ disabled={busy || triggerDisabled}className="gap-1.5 text-muted-foreground px-1.5"data-testid="share-button">diff --git a/packages/app/src/components/ShareMetadataRows.dom.test.tsx b/packages/app/src/components/ShareMetadataRows.dom.test.tsxnew file mode 100644index 000000000..57ff0e8a5--- /dev/null+++ b/packages/app/src/components/ShareMetadataRows.dom.test.tsx@@ -0,0 +1,84 @@+import { afterEach, describe, expect, test } from 'bun:test';+import { cleanup, render, screen, within } from '@testing-library/react';+import { ShareMetadataRows } from '@/components/share-metadata-rows';++describe('ShareMetadataRows', () => {+ afterEach(() => {+ cleanup();+ });++ test('doc target renders a File label row with the path value', () => {+ render(+ <ShareMetadataRows+ owner="acme"+ repo="kb"+ path="guides/notes.md"+ kind="doc"+ branch="main"+ testId="share-receive-metadata"+ branchTestId="share-receive-metadata-branch"+ />,+ );++ expect(screen.getByText('File')).not.toBeNull();+ expect(screen.queryByText('Folder')).toBeNull();+ expect(screen.getByTestId('share-receive-metadata-target').textContent).toBe('guides/notes.md');+ });++ test('folder target (non-empty path) renders a Folder label row with the path value', () => {+ render(+ <ShareMetadataRows+ owner="acme"+ repo="kb"+ path="guides"+ kind="folder"+ branch="main"+ testId="share-receive-metadata"+ branchTestId="share-receive-metadata-branch"+ />,+ );++ expect(screen.getByText('Folder')).not.toBeNull();+ expect(screen.queryByText('File')).toBeNull();+ expect(screen.getByTestId('share-receive-metadata-target').textContent).toBe('guides');+ });++ test('content-root folder share (empty path) suppresses the target row entirely', () => {+ render(+ <ShareMetadataRows+ owner="acme"+ repo="kb"+ path=""+ kind="folder"+ branch="main"+ testId="share-receive-metadata"+ branchTestId="share-receive-metadata-branch"+ />,+ );++ expect(screen.queryByText('File')).toBeNull();+ expect(screen.queryByText('Folder')).toBeNull();+ expect(screen.queryByTestId('share-receive-metadata-target')).toBeNull();+ expect(screen.getByText('Repository')).not.toBeNull();+ });++ test('non-content-root folder still renders its target row (pins the suppression boolean)', () => {+ const { container } = render(+ <ShareMetadataRows+ owner="acme"+ repo="kb"+ path="docs/onboarding"+ kind="folder"+ branch="main"+ testId="share-receive-metadata"+ branchTestId="share-receive-metadata-branch"+ />,+ );++ const metadata = within(container).getByTestId('share-receive-metadata');+ expect(within(metadata).getByText('Folder')).not.toBeNull();+ expect(within(metadata).getByTestId('share-receive-metadata-target').textContent).toBe(+ 'docs/onboarding',+ );+ });+});diff --git a/packages/app/src/components/ShareReceiveDialog.test.ts b/packages/app/src/components/ShareReceiveDialog.test.tsindex 00c722ab5..8568aafb2 100644--- a/packages/app/src/components/ShareReceiveDialog.test.ts+++ b/packages/app/src/components/ShareReceiveDialog.test.ts@@ -82,7 +82,7 @@ describe('ShareReceiveDialog — launcher-consent surface', () => {test('seeds the consent flow from payload.candidatePath + payload.share', () => {expect(SRC).toContain('initialConsentFlowState');expect(SRC).toContain('candidatePath:');- expect(SRC).toContain('docPath:');+ expect(SRC).toContain('targetPath:');});test('threads payload.parentProjectName so the "(a worktree of <name>)" caption renders', () => {@@ -95,7 +95,7 @@ describe('ShareReceiveDialog — launcher-consent surface', () => {expect(SRC).toContain("disabled={initializing || consentState.phase === 'error'}");});- test('Initialize handler runs okInit then dispatches bridge.project.open with pendingDeepLinkDoc + pendingBranch', () => {+ test('Initialize handler runs okInit then dispatches bridge.project.open with pendingDeepLinkTarget + pendingBranch', () => {expect(SRC).toMatch(/bridge\.project[\s\n.]+okInit\(/);expect(SRC).toMatch(/bridge\.project[\s\n.]+open\(/);const idx = SRC.indexOf('function handleConsentInitialize');@@ -103,7 +103,7 @@ describe('ShareReceiveDialog — launcher-consent surface', () => {const endIdx = SRC.indexOf('function handleConsentCancel', idx);expect(endIdx).toBeGreaterThan(idx);const handlerBody = SRC.slice(idx, endIdx);- expect(handlerBody).toContain('pendingDeepLinkDoc');+ expect(handlerBody).toContain('pendingDeepLinkTarget');expect(handlerBody).toContain('pendingBranch');});});diff --git a/packages/app/src/components/ShareReceiveDialog.tsx b/packages/app/src/components/ShareReceiveDialog.tsxindex ecd3ea910..abb03d8d2 100644--- a/packages/app/src/components/ShareReceiveDialog.tsx+++ b/packages/app/src/components/ShareReceiveDialog.tsx@@ -16,10 +16,11 @@ import {Dialog as DialogRoot,DialogTitle,} from '@/components/ui/dialog';-import type {- OkDesktopBridge,- OkLocalOpAuthStatusResponse,- OkShareReceivedPayload,+import {+ type OkDesktopBridge,+ type OkLocalOpAuthStatusResponse,+ type OkShareReceivedPayload,+ shareTargetPath,} from '@/lib/desktop-bridge-types';import {applyOkInitOutcome,@@ -141,7 +142,8 @@ function ShareReceiveDialogInner({initialConsentFlowState({candidatePath: payload.candidatePath,branch: payload.share.branch,- docPath: payload.share.path,+ targetPath: shareTargetPath(payload.share.target),+ targetKind: payload.share.target.kind,parentProjectName: payload.parentProjectName,}),);@@ -172,6 +174,7 @@ function ShareReceiveDialogInner({const launcherConsent = isLauncherConsentPayload(payload) ? payload : null;const share = launcherMiss?.share ?? launcherConsent?.share ?? null;const expected = share ? { owner: share.owner, repo: share.repo } : null;+ const targetNoun = share?.target.kind === 'folder' ? t`folder` : t`document`;async function handleCloneCtaClick(): Promise<void> {if (!launcherMiss || !expected) return;@@ -206,7 +209,10 @@ function ShareReceiveDialogInner({path: result.dir,target: 'new-window',entryPoint: 'share-receive',- pendingDeepLinkDoc: launcherMiss.share.path,+ pendingDeepLinkTarget: {+ kind: launcherMiss.share.target.kind,+ path: shareTargetPath(launcherMiss.share.target),+ },});} catch {toast.error(t`Cloned successfully, but could not open the project.`);@@ -250,7 +256,10 @@ function ShareReceiveDialogInner({path: folderPath,target: 'new-window',entryPoint: 'share-receive',- pendingDeepLinkDoc: launcherMiss.share.path,+ pendingDeepLinkTarget: {+ kind: launcherMiss.share.target.kind,+ path: shareTargetPath(launcherMiss.share.target),+ },});store.dismiss();} catch (err) {@@ -294,7 +303,7 @@ function ShareReceiveDialogInner({path: outcome.projectPath,target: 'new-window',entryPoint: 'share-receive',- pendingDeepLinkDoc: seed.docPath,+ pendingDeepLinkTarget: { kind: seed.targetKind, path: seed.targetPath },pendingBranch: seed.branch,});setConsentState((prev) =>@@ -361,17 +370,19 @@ function ShareReceiveDialogInner({><DialogHeader><DialogTitle>- <Trans>Open shared document</Trans>+ <Trans>Open shared {targetNoun}</Trans></DialogTitle><DialogDescription className="sr-only"><Trans>- {share.owner}/{share.repo} {share.path ? `— ${share.path}` : ''}+ {share.owner}/{share.repo}{' '}+ {shareTargetPath(share.target) ? `— ${shareTargetPath(share.target)}` : ''}</Trans></DialogDescription><ShareMetadataRowsowner={share.owner}repo={share.repo}- path={share.path}+ path={shareTargetPath(share.target)}+ kind={share.target.kind}branch={share.branch}testId="share-receive-metadata"branchTestId="share-receive-metadata-branch"@@ -464,16 +475,17 @@ function ShareReceiveDialogInner({<DialogContent className="sm:max-w-xl" data-testid="share-receive-dialog"><DialogHeader><DialogTitle>- <Trans>Open shared document</Trans>+ <Trans>Open shared {targetNoun}</Trans></DialogTitle><DialogDescription className="sr-only">{share.owner}/{share.repo}- {share.path ? ` — ${share.path}` : null}+ {shareTargetPath(share.target) ? ` — ${shareTargetPath(share.target)}` : null}</DialogDescription><ShareMetadataRowsowner={share.owner}repo={share.repo}- path={share.path}+ path={shareTargetPath(share.target)}+ kind={share.target.kind}branch={share.branch}testId="share-receive-metadata"branchTestId="share-receive-metadata-branch"diff --git a/packages/app/src/components/folder-overview-data.test.ts b/packages/app/src/components/folder-overview-data.test.tsindex 4baacfff9..0499f8ca8 100644--- a/packages/app/src/components/folder-overview-data.test.ts+++ b/packages/app/src/components/folder-overview-data.test.ts@@ -68,4 +68,34 @@ describe('buildFolderOverviewData', () => {expect(data.children[0]).toMatchObject({ kind: 'file', title: 'readme' });});++ test('content-root (empty folderPath) lists only top-level children', () => {+ const data = buildFolderOverviewData('', {+ pages: new Set(['intro', 'README', 'docs/a', 'docs/b', 'reports/q1/summary']),+ pageTitles: new Map([['intro', 'Intro']]),+ pageMeta: new Map([['intro', { size: 10, modified: '2026-05-01T00:00:00Z' }]]),+ folderPaths: new Set(['docs', 'reports', 'reports/q1']),+ });++ expect(data.children).toEqual([+ { kind: 'folder', path: 'docs', name: 'docs', title: 'docs' },+ { kind: 'folder', path: 'reports', name: 'reports', title: 'reports' },+ {+ kind: 'file',+ path: 'intro',+ name: 'intro',+ title: 'Intro',+ size: 10,+ modified: '2026-05-01T00:00:00Z',+ },+ {+ kind: 'file',+ path: 'README',+ name: 'README',+ title: 'README',+ size: 0,+ modified: '',+ },+ ]);+ });});diff --git a/packages/app/src/components/folder-overview-data.ts b/packages/app/src/components/folder-overview-data.tsindex 3a008d9be..d2e738b58 100644--- a/packages/app/src/components/folder-overview-data.ts+++ b/packages/app/src/components/folder-overview-data.ts@@ -50,7 +50,7 @@ export function buildFolderOverviewData(folderPaths: ReadonlySet<string>;},): FolderOverviewData {- const prefix = `${folderPath}/`;+ const prefix = folderPath === '' ? '' : `${folderPath}/`;const folders: FolderOverviewEntry[] = [...options.folderPaths].filter((path) => path.startsWith(prefix))diff --git a/packages/app/src/components/share-metadata-rows.tsx b/packages/app/src/components/share-metadata-rows.tsxindex 341f093c1..1be9d385a 100644--- a/packages/app/src/components/share-metadata-rows.tsx+++ b/packages/app/src/components/share-metadata-rows.tsx@@ -8,6 +8,7 @@ export interface ShareMetadataRowsProps {repo: string;path: string;branch: string;+ kind?: 'doc' | 'folder';testId: string;branchTestId: string;}@@ -17,6 +18,7 @@ export function ShareMetadataRows({repo,path,branch,+ kind = 'doc',testId,branchTestId,}: ShareMetadataRowsProps) {@@ -29,8 +31,10 @@ export function ShareMetadataRows({</span></ShareMetadataRow>{path ? (- <ShareMetadataRow label={<Trans>File</Trans>}>- <span className="font-mono">{path}</span>+ <ShareMetadataRow label={kind === 'folder' ? <Trans>Folder</Trans> : <Trans>File</Trans>}>+ <span className="font-mono" data-testid={`${testId}-target`}>+ {path}+ </span></ShareMetadataRow>) : null}{showBranch ? (diff --git a/packages/app/src/lib/desktop-bridge-types.ts b/packages/app/src/lib/desktop-bridge-types.tsindex ab6915f32..a4c04961d 100644--- a/packages/app/src/lib/desktop-bridge-types.ts+++ b/packages/app/src/lib/desktop-bridge-types.ts@@ -160,7 +160,15 @@ interface ProjectSessionState {updatedAt: string | null;}-export type CheckDocExistsResult = 'exists' | 'missing' | 'unreadable';+export type CheckTargetExistsResult = 'exists' | 'missing' | 'unreadable';++export type ShareTarget =+ | { readonly kind: 'doc'; readonly docPath: string }+ | { readonly kind: 'folder'; readonly folderPath: string };++export function shareTargetPath(target: ShareTarget): string {+ return target.kind === 'doc' ? target.docPath : target.folderPath;+}export interface HeadBranchInfo {readonly currentBranch: string | null;@@ -187,8 +195,8 @@ export interface OkSharePayloadFields {readonly owner: string;readonly repo: string;readonly branch: string;- readonly path: string;- readonly blobUrl: string;+ readonly sharedUrl: string;+ readonly target: ShareTarget;}/** Local copy — see canonical `OkShareReceivedPayload` in@@ -414,7 +422,13 @@ export interface OkDesktopBridge {onWhatsNew(cb: (info: OkWhatsNewInfo) => void): OkUnsubscribe;onUpdateStuckHint(cb: (info: OkUpdateStuckHintInfo) => void): OkUnsubscribe;onDeepLink(- cb: (evt: { doc: string; branch?: string | null; multiCandidate?: boolean }) => void,+ cb: (evt: {+ doc: string;+ kind: 'doc' | 'folder';+ branch?: string | null;+ multiCandidate?: boolean;+ targetMissing?: boolean;+ }) => void,): OkUnsubscribe;onShareReceived(cb: (payload: OkShareReceivedPayload) => void): OkUnsubscribe;onServerVersionDrift(cb: (info: OkServerVersionDriftInfo) => void): OkUnsubscribe;@@ -493,7 +507,7 @@ export interface OkDesktopBridge {path: string;target: 'new-window';entryPoint: OkProjectEntryPoint;- pendingDeepLinkDoc?: string;+ pendingDeepLinkTarget?: { kind: 'doc' | 'folder'; path: string };pendingBranch?: string | null;}): Promise<void>;createNew(args: {@@ -503,15 +517,17 @@ export interface OkDesktopBridge {sharing?: 'shared' | 'local-only';}): Promise<void>;recordCreateNewBannerShown(banner: CreateNewBannerKind): Promise<void>;- checkDocExists(request: {+ checkTargetExists(request: {projectPath: string;- docPath: string;- }): Promise<CheckDocExistsResult>;+ kind: 'doc' | 'folder';+ path: string;+ }): Promise<CheckTargetExistsResult>;readHeadBranch(projectPath: string): Promise<HeadBranchInfo>;fetchBranchInfo(request: {projectPath: string;branch: string;- docPath: string;+ kind: 'doc' | 'folder';+ path: string;}): Promise<BranchInfoResponse | null>;runCheckout(request: { projectPath: string; branch: string }): Promise<CheckoutResponse | null>;awaitBranchSwitched(request: {diff --git a/packages/app/src/lib/doc-hash.test.ts b/packages/app/src/lib/doc-hash.test.tsindex 79cd2f2b7..b8203b416 100644--- a/packages/app/src/lib/doc-hash.test.ts+++ b/packages/app/src/lib/doc-hash.test.ts@@ -3,9 +3,11 @@ import {anchorFromHash,assetPathFromHash,docNameFromHash,+ encodeShareTargetForHash,hashFromAssetPath,hashFromDocName,hashFromFolderPath,+ isContentRootHash,} from './doc-hash';describe('docNameFromHash', () => {@@ -135,6 +137,70 @@ describe('hashFromFolderPath', () => {});});+describe('encodeShareTargetForHash', () => {+ test('doc target → #/<doc> with no branch', () => {+ expect(encodeShareTargetForHash('doc', 'intro.md')).toBe('#/intro.md');+ });++ test('doc target → #/<doc>?branch=<branch> when branch present', () => {+ expect(encodeShareTargetForHash('doc', 'intro.md', 'main')).toBe('#/intro.md?branch=main');+ });++ test('doc target URL-encodes nested doc names (slash → %2F)', () => {+ expect(encodeShareTargetForHash('doc', 'notes/meeting')).toBe('#/notes%2Fmeeting');+ });++ test('doc target encodes slashed branch names', () => {+ expect(encodeShareTargetForHash('doc', 'docs/page.md', 'feat/foo')).toBe(+ '#/docs%2Fpage.md?branch=feat%2Ffoo',+ );+ });++ test('doc target treats null / empty branch as absent (back-compat)', () => {+ expect(encodeShareTargetForHash('doc', 'intro.md', null)).toBe('#/intro.md');+ expect(encodeShareTargetForHash('doc', 'intro.md', '')).toBe('#/intro.md');+ });++ test('folder target → trailing-slash folder hash', () => {+ expect(encodeShareTargetForHash('folder', 'docs/sub')).toBe('#/docs/sub/');+ });++ test('content-root folder target (empty path) → root hash #/', () => {+ expect(encodeShareTargetForHash('folder', '')).toBe('#/');+ });++ test('folder target ignores branch (no ?branch= appended)', () => {+ expect(encodeShareTargetForHash('folder', 'docs/sub', 'main')).toBe('#/docs/sub/');+ expect(encodeShareTargetForHash('folder', '', 'main')).toBe('#/');+ });+});++describe('isContentRootHash', () => {+ test('true for the bare root sentinel #/', () => {+ expect(isContentRootHash('#/')).toBe(true);+ });++ test('true for #/ with a trailing query', () => {+ expect(isContentRootHash('#/?anchor=x')).toBe(true);+ });++ test('false for an empty hash (clear, not root)', () => {+ expect(isContentRootHash('')).toBe(false);+ });++ test('false for a folder hash with a path segment', () => {+ expect(isContentRootHash('#/docs/sub/')).toBe(false);+ });++ test('false for a doc hash', () => {+ expect(isContentRootHash('#/intro.md')).toBe(false);+ });++ test('round-trips with hashFromFolderpath of the root', () => {+ expect(isContentRootHash(hashFromFolderPath(''))).toBe(true);+ });+});+describe('asset hash helpers', () => {test('round-trips nested asset paths', () => {const hash = hashFromAssetPath('docs/My Photo.png');diff --git a/packages/app/src/lib/doc-hash.ts b/packages/app/src/lib/doc-hash.tsindex 8d7830959..b0416537d 100644--- a/packages/app/src/lib/doc-hash.ts+++ b/packages/app/src/lib/doc-hash.ts@@ -51,6 +51,24 @@ export function hashFromFolderPath(folderPath: string, anchor?: string | null):return anchor ? `${base}#${encodeURIComponent(anchor)}` : base;}+export function encodeShareTargetForHash(+ kind: 'doc' | 'folder',+ path: string,+ branch?: string | null,+): string {+ if (kind === 'folder') return hashFromFolderPath(path);+ const base = `#/${encodeURIComponent(path)}`;+ if (branch === undefined || branch === null || branch === '') return base;+ return `${base}?branch=${encodeURIComponent(branch)}`;+}++export function isContentRootHash(hash: string): boolean {+ if (hash === '#/') return true;+ if (!hash.startsWith('#/')) return false;+ const rest = hash.slice(2);+ return rest.length > 0 && rest[0] === '?';+}+const ASSET_HASH_PREFIX = '#/__asset__/';function firstRouteDelimiterIndex(rest: string): number {diff --git a/packages/app/src/lib/install-deep-link-listener.test.ts b/packages/app/src/lib/install-deep-link-listener.test.tsindex 423bd8bed..f21b5440e 100644--- a/packages/app/src/lib/install-deep-link-listener.test.ts+++ b/packages/app/src/lib/install-deep-link-listener.test.ts@@ -2,7 +2,12 @@ import { describe, expect, mock, test } from 'bun:test';import type { OkDesktopBridge, OkDesktopConfig } from './desktop-bridge-types';import { deriveShareReceiveToast, installDeepLinkListener } from './install-deep-link-listener';-type DeepLinkPayload = { doc: string; branch?: string | null; multiCandidate?: boolean };+type DeepLinkPayload = {+ doc: string;+ kind?: 'doc' | 'folder';+ branch?: string | null;+ multiCandidate?: boolean;+};function makeBridge(overrides: Partial<OkDesktopBridge> = {}): OkDesktopBridge & {fireDeepLink: (evt: DeepLinkPayload) => void;@@ -158,6 +163,40 @@ describe('installDeepLinkListener (M4 US-007)', () => {bridge.fireDeepLink({ doc: 'page.md', branch: '日本語' });expect(setHash.mock.calls[0]?.[0]).toBe('#/page.md?branch=%E6%97%A5%E6%9C%AC%E8%AA%9E');});++ test('explicit kind:doc behaves identically to legacy (omitted kind)', () => {+ const bridge = makeBridge();+ const setHash = mock(() => {});+ installDeepLinkListener({ bridge, setHash });+ bridge.fireDeepLink({ doc: 'intro.md', kind: 'doc', branch: 'main' });+ expect(setHash.mock.calls[0]?.[0]).toBe('#/intro.md?branch=main');+ });+});++describe('installDeepLinkListener — folder + content-root shares (US-010)', () => {+ test('folder event navigates to the trailing-slash folder hash', () => {+ const bridge = makeBridge();+ const setHash = mock(() => {});+ installDeepLinkListener({ bridge, setHash });+ bridge.fireDeepLink({ doc: 'docs/sub', kind: 'folder' });+ expect(setHash.mock.calls[0]?.[0]).toBe('#/docs/sub/');+ });++ test('content-root folder event (empty doc) navigates to the root hash #/', () => {+ const bridge = makeBridge();+ const setHash = mock(() => {});+ installDeepLinkListener({ bridge, setHash });+ bridge.fireDeepLink({ doc: '', kind: 'folder' });+ expect(setHash.mock.calls[0]?.[0]).toBe('#/');+ });++ test('folder event does NOT append ?branch= (branch resolved upstream)', () => {+ const bridge = makeBridge();+ const setHash = mock(() => {});+ installDeepLinkListener({ bridge, setHash });+ bridge.fireDeepLink({ doc: 'docs/sub', kind: 'folder', branch: 'feat/x' });+ expect(setHash.mock.calls[0]?.[0]).toBe('#/docs/sub/');+ });});describe('deriveShareReceiveToast (FR9)', () => {diff --git a/packages/app/src/lib/install-deep-link-listener.ts b/packages/app/src/lib/install-deep-link-listener.tsindex 9dffead7e..48c892fdd 100644--- a/packages/app/src/lib/install-deep-link-listener.ts+++ b/packages/app/src/lib/install-deep-link-listener.ts@@ -1,5 +1,6 @@import { toast } from 'sonner';import type { OkDesktopBridge } from '@/lib/desktop-bridge-types';+import { encodeShareTargetForHash } from '@/lib/doc-hash';interface InstallDeepLinkListenerOptions {bridge: OkDesktopBridge | undefined;@@ -7,12 +8,6 @@ interface InstallDeepLinkListenerOptions {emitToast?: (message: string, opts: { description: string; duration: number }) => void;}-function encodeDocForHash(doc: string, branch?: string | null): string {- const base = `#/${encodeURIComponent(doc)}`;- if (branch === undefined || branch === null || branch === '') return base;- return `${base}?branch=${encodeURIComponent(branch)}`;-}-export function deriveShareReceiveToast(evt: { doc: string; branch?: string | null; multiCandidate?: boolean },projectPath: string,@@ -43,7 +38,20 @@ export function installDeepLinkListener(toast(message, toastOpts);});return bridge.onDeepLink((evt) => {- setHash(encodeDocForHash(evt.doc, evt.branch));+ const kind = evt.kind ?? 'doc';+ if (evt.targetMissing === true) {+ const label = kind === 'folder' ? 'folder' : 'file';+ const onBranch =+ evt.branch === undefined || evt.branch === null || evt.branch === ''+ ? ''+ : ` on branch ${evt.branch}`;+ emitToast(`This ${label} isn't in your local checkout${onBranch} yet`, {+ description: 'Pull the latest changes, then open the share link again.',+ duration: 5000,+ });+ return;+ }+ setHash(encodeShareTargetForHash(kind, evt.doc, kind === 'doc' ? evt.branch : undefined));const payload = deriveShareReceiveToast(evt, bridge.config.projectPath);if (payload !== null) {emitToast(payload.message, { description: payload.description, duration: 3000 });diff --git a/packages/app/src/lib/share/branch-switch-flow.test.ts b/packages/app/src/lib/share/branch-switch-flow.test.tsindex 9cebdc7bf..c2b8a8cb6 100644--- a/packages/app/src/lib/share/branch-switch-flow.test.ts+++ b/packages/app/src/lib/share/branch-switch-flow.test.ts@@ -18,7 +18,7 @@ const cleanInfo = (overrides: Partial<BranchInfoResponse> = {}): BranchInfoRespocurrentBranch: 'main',currentHeadSha: null,detached: false,- shareFileExists: true,+ shareTargetExists: true,dirtyConflicts: { conflicts: false, files: [] },branchIsLocal: true,...overrides,@@ -29,7 +29,7 @@ const detachedInfo = (overrides: Partial<BranchInfoResponse> = {}): BranchInfoRecurrentBranch: null,currentHeadSha: 'deadbee',detached: true,- shareFileExists: true,+ shareTargetExists: true,dirtyConflicts: { conflicts: false, files: [] },branchIsLocal: true,...overrides,@@ -47,7 +47,7 @@ describe('selectBranchSwitchVariant', () => {});test('variant B — file missing on current branch, clean tree', () => {- const variant = selectBranchSwitchVariant(cleanInfo({ shareFileExists: false }));+ const variant = selectBranchSwitchVariant(cleanInfo({ shareTargetExists: false }));expect(variant).toEqual({kind: 'B',openCurrentEnabled: false,@@ -73,7 +73,7 @@ describe('selectBranchSwitchVariant', () => {test('variant D — file missing on current, dirty conflict — only Cancel viable', () => {const variant = selectBranchSwitchVariant(cleanInfo({- shareFileExists: false,+ shareTargetExists: false,dirtyConflicts: { conflicts: true, files: ['x.md'] },}),);@@ -110,7 +110,7 @@ describe('BranchInfoResponseSchema (discriminated union)', () => {detached: false,currentBranch: 'main',currentHeadSha: null,- shareFileExists: true,+ shareTargetExists: true,dirtyConflicts: { conflicts: false, files: [] },branchIsLocal: true,};@@ -123,7 +123,7 @@ describe('BranchInfoResponseSchema (discriminated union)', () => {detached: true,currentBranch: null,currentHeadSha: 'deadbee',- shareFileExists: true,+ shareTargetExists: true,dirtyConflicts: { conflicts: false, files: [] },branchIsLocal: true,};@@ -136,7 +136,7 @@ describe('BranchInfoResponseSchema (discriminated union)', () => {detached: true,currentBranch: 'main',currentHeadSha: 'deadbee',- shareFileExists: true,+ shareTargetExists: true,dirtyConflicts: { conflicts: false, files: [] },branchIsLocal: true,};@@ -149,7 +149,7 @@ describe('BranchInfoResponseSchema (discriminated union)', () => {detached: false,currentBranch: 'main',currentHeadSha: 'deadbee',- shareFileExists: true,+ shareTargetExists: true,dirtyConflicts: { conflicts: false, files: [] },branchIsLocal: true,};diff --git a/packages/app/src/lib/share/branch-switch-flow.ts b/packages/app/src/lib/share/branch-switch-flow.tsindex a16bc1a15..25245a726 100644--- a/packages/app/src/lib/share/branch-switch-flow.ts+++ b/packages/app/src/lib/share/branch-switch-flow.ts@@ -27,16 +27,16 @@ export type BranchSwitchVariant =};export function selectBranchSwitchVariant(info: BranchInfoResponse): BranchSwitchVariant {- const fileExists = info.shareFileExists;+ const targetExists = info.shareTargetExists;const dirty = info.dirtyConflicts.conflicts;const files = info.dirtyConflicts.files;- if (fileExists && !dirty) {+ if (targetExists && !dirty) {return { kind: 'A', openCurrentEnabled: true, switchEnabled: true, conflictingFiles: files };}- if (!fileExists && !dirty) {+ if (!targetExists && !dirty) {return { kind: 'B', openCurrentEnabled: false, switchEnabled: true, conflictingFiles: files };}- if (fileExists && dirty) {+ if (targetExists && dirty) {return { kind: 'C', openCurrentEnabled: true, switchEnabled: false, conflictingFiles: files };}return { kind: 'D', openCurrentEnabled: false, switchEnabled: false, conflictingFiles: files };diff --git a/packages/app/src/lib/share/consent-flow.test.ts b/packages/app/src/lib/share/consent-flow.test.tsindex 9634e6f13..4b48f99bb 100644--- a/packages/app/src/lib/share/consent-flow.test.ts+++ b/packages/app/src/lib/share/consent-flow.test.ts@@ -12,7 +12,7 @@ import {const SEED: ConsentFlowSeed = {candidatePath: '/wt/feat-bar',branch: 'feat-bar',- docPath: 'docs/x.md',+ targetPath: 'docs/x.md',parentProjectName: 'agents-private',};diff --git a/packages/app/src/lib/share/consent-flow.ts b/packages/app/src/lib/share/consent-flow.tsindex 33c7e1fc7..2ca2d7418 100644--- a/packages/app/src/lib/share/consent-flow.ts+++ b/packages/app/src/lib/share/consent-flow.ts@@ -1,7 +1,8 @@export interface ConsentFlowSeed {readonly candidatePath: string;readonly branch: string;- readonly docPath: string;+ readonly targetPath: string;+ readonly targetKind: 'doc' | 'folder';readonly parentProjectName: string | null;}diff --git a/packages/app/src/lib/share/receive-flow.ts b/packages/app/src/lib/share/receive-flow.tsindex 9afbe6bc6..3b605939b 100644--- a/packages/app/src/lib/share/receive-flow.ts+++ b/packages/app/src/lib/share/receive-flow.ts@@ -3,7 +3,7 @@ import {type ExpectedShareRepo,} from '@inkeep/open-knowledge-core';import type {- CheckDocExistsResult,+ CheckTargetExistsResult,OkShareReceivedPayload,ShareFolderValidationResult,} from '@/lib/desktop-bridge-types';@@ -69,7 +69,7 @@ export interface ReceiveLogFields {readonly folder_validate?: ShareFolderValidationResult['kind'];readonly branch_action?: BranchAction;readonly branch?: string;- readonly doc_check?: CheckDocExistsResult;+ readonly doc_check?: CheckTargetExistsResult;readonly branch_dialog_action?: BranchDialogAction;}diff --git a/packages/app/src/lib/share/receive-store.test.ts b/packages/app/src/lib/share/receive-store.test.tsindex 71ec38b9c..87b3ba58b 100644--- a/packages/app/src/lib/share/receive-store.test.ts+++ b/packages/app/src/lib/share/receive-store.test.ts@@ -38,8 +38,8 @@ const sharePayload: OkShareReceivedPayload = {owner: 'a',repo: 'b',branch: 'main',- path: 'README.md',- blobUrl: 'https://github.com/a/b/blob/main/README.md',+ sharedUrl: 'https://github.com/a/b/blob/main/README.md',+ target: { kind: 'doc', docPath: 'README.md' },},};diff --git a/packages/app/src/lib/share/run-share-action.test.ts b/packages/app/src/lib/share/run-share-action.test.tsindex 8d2e2c0ac..92130973a 100644--- a/packages/app/src/lib/share/run-share-action.test.ts+++ b/packages/app/src/lib/share/run-share-action.test.ts@@ -116,27 +116,53 @@ describe('requestShareConstructUrl', () => {json: async () => ({ok: true,shareUrl: 'https://openknowledge.ai/d/AaaXX',- blobUrl: 'https://github.com/o/r/blob/main/a.md',+ sharedUrl: 'https://github.com/o/r/blob/main/a.md',branch: 'main',}),} as unknown as Response;}) as unknown as typeof fetch;- const result = await requestShareConstructUrl('a.md', stubFetch);+ const result = await requestShareConstructUrl({ kind: 'doc', docPath: 'a.md' }, stubFetch);expect(calls).toHaveLength(1);expect(calls[0].url).toBe('/api/share/construct-url');expect(calls[0].init?.method).toBe('POST');expect(calls[0].init?.headers).toMatchObject({ 'Content-Type': 'application/json' });- expect(JSON.parse(String(calls[0].init?.body))).toEqual({ docPath: 'a.md' });+ expect(JSON.parse(String(calls[0].init?.body))).toEqual({ kind: 'doc', docPath: 'a.md' });expect(result).toEqual({ok: true,shareUrl: 'https://openknowledge.ai/d/AaaXX',- blobUrl: 'https://github.com/o/r/blob/main/a.md',+ sharedUrl: 'https://github.com/o/r/blob/main/a.md',branch: 'main',});});+ test('POSTs the folder-variant body verbatim (folderPath, including the empty content-root sentinel)', async () => {+ const calls: Array<{ url: string; init: RequestInit | undefined }> = [];+ const stubFetch = (async (url: RequestInfo | URL, init?: RequestInit) => {+ calls.push({ url: String(url), init });+ return {+ ok: true,+ status: 200,+ json: async () => ({+ ok: true,+ shareUrl: 'https://openknowledge.ai/d/BbbYY',+ sharedUrl: 'https://github.com/o/r/tree/main/guides',+ branch: 'main',+ }),+ } as unknown as Response;+ }) as unknown as typeof fetch;++ await requestShareConstructUrl({ kind: 'folder', folderPath: 'guides' }, stubFetch);+ expect(JSON.parse(String(calls[0].init?.body))).toEqual({+ kind: 'folder',+ folderPath: 'guides',+ });++ await requestShareConstructUrl({ kind: 'folder', folderPath: '' }, stubFetch);+ expect(JSON.parse(String(calls[1].init?.body))).toEqual({ kind: 'folder', folderPath: '' });+ });+test('throws when transport returns non-2xx (so callers route to transport-error)', async () => {const stubFetch = (async () =>({@@ -145,9 +171,9 @@ describe('requestShareConstructUrl', () => {json: async () => ({ type: 'urn:ok:error:internal-server-error', detail: 'boom' }),}) as unknown as Response) as unknown as typeof fetch;- await expect(requestShareConstructUrl('a.md', stubFetch)).rejects.toThrow(- /construct-url transport 500/,- );+ await expect(+ requestShareConstructUrl({ kind: 'doc', docPath: 'a.md' }, stubFetch),+ ).rejects.toThrow(/construct-url transport 500/);});test('throws when response body fails schema validation', async () => {@@ -155,12 +181,12 @@ describe('requestShareConstructUrl', () => {({ok: true,status: 200,- json: async () => ({ ok: true /* missing shareUrl + blobUrl + branch */ }),+ json: async () => ({ ok: true /* missing shareUrl + sharedUrl + branch */ }),}) as unknown as Response) as unknown as typeof fetch;- await expect(requestShareConstructUrl('a.md', stubFetch)).rejects.toThrow(- /response shape mismatch/,- );+ await expect(+ requestShareConstructUrl({ kind: 'doc', docPath: 'a.md' }, stubFetch),+ ).rejects.toThrow(/response shape mismatch/);});test('parses the branch field on a branch-not-on-origin error response', async () => {@@ -175,7 +201,7 @@ describe('requestShareConstructUrl', () => {}),}) as unknown as Response) as unknown as typeof fetch;- const result = await requestShareConstructUrl('a.md', stubFetch);+ const result = await requestShareConstructUrl({ kind: 'doc', docPath: 'a.md' }, stubFetch);if (result.ok) throw new Error('expected error variant');expect(result.error).toBe('branch-not-on-origin');expect(result.branch).toBe('feat/sharing-virality-flow');@@ -187,7 +213,7 @@ describe('runShareAction — happy path', () => {const okResponse: ShareConstructUrlResponse = {ok: true,shareUrl: 'https://openknowledge.ai/d/Aaa',- blobUrl: 'https://github.com/o/r/blob/main/a.md',+ sharedUrl: 'https://github.com/o/r/blob/main/a.md',branch: 'main',};const deps = makeDeps({ fetchResponse: okResponse });@@ -195,6 +221,7 @@ describe('runShareAction — happy path', () => {const result = await runShareAction({+ kind: 'doc',docName: 'a',hasRemote: true,onClickWhenNoRemote: () => {@@ -220,32 +247,82 @@ describe('runShareAction — happy path', () => {const okResponse: ShareConstructUrlResponse = {ok: true,shareUrl: 'https://openknowledge.ai/d/Aaa',- blobUrl: 'https://github.com/o/r/blob/main/foo.md',+ sharedUrl: 'https://github.com/o/r/blob/main/foo.md',branch: 'main',};const deps = makeDeps({ fetchResponse: okResponse });- await runShareAction({ docName: 'foo', hasRemote: true, onClickWhenNoRemote: () => {} }, deps);+ await runShareAction(+ { kind: 'doc', docName: 'foo', hasRemote: true, onClickWhenNoRemote: () => {} },+ deps,+ );expect(deps.fetchCalls).toHaveLength(1);- expect(deps.fetchCalls[0].body).toEqual({ docPath: 'foo.md' });+ expect(deps.fetchCalls[0].body).toEqual({ kind: 'doc', docPath: 'foo.md' });});test('nested docName "docs/sub/page" maps to docPath "docs/sub/page.md"', async () => {const okResponse: ShareConstructUrlResponse = {ok: true,shareUrl: 'https://openknowledge.ai/d/Aaa',- blobUrl: 'https://github.com/o/r/blob/main/docs/sub/page.md',+ sharedUrl: 'https://github.com/o/r/blob/main/docs/sub/page.md',branch: 'main',};const deps = makeDeps({ fetchResponse: okResponse });await runShareAction(- { docName: 'docs/sub/page', hasRemote: true, onClickWhenNoRemote: () => {} },+ { kind: 'doc', docName: 'docs/sub/page', hasRemote: true, onClickWhenNoRemote: () => {} },deps,);- expect(deps.fetchCalls[0].body).toEqual({ docPath: 'docs/sub/page.md' });+ expect(deps.fetchCalls[0].body).toEqual({ kind: 'doc', docPath: 'docs/sub/page.md' });+ });++ test('folder input POSTs {kind:folder, folderPath} verbatim + folder-specific success toast', async () => {+ const okResponse: ShareConstructUrlResponse = {+ ok: true,+ shareUrl: 'https://openknowledge.ai/d/Fff',+ sharedUrl: 'https://github.com/o/r/tree/main/guides/onboarding',+ branch: 'main',+ };+ const deps = makeDeps({ fetchResponse: okResponse });++ const result = await runShareAction(+ {+ kind: 'folder',+ folderRelativePath: 'guides/onboarding',+ hasRemote: true,+ onClickWhenNoRemote: () => {},+ },+ deps,+ );++ expect(result).toEqual({+ kind: 'copied',+ shareUrl: 'https://openknowledge.ai/d/Fff',+ branch: 'main',+ });+ expect(deps.fetchCalls[0].body).toEqual({ kind: 'folder', folderPath: 'guides/onboarding' });+ expect(deps.successToasts).toEqual(['Folder share link copied.']);+ expect(deps.clipboardTexts).toEqual(['https://openknowledge.ai/d/Fff']);+ });++ test('content-root folder input POSTs the empty folderPath sentinel', async () => {+ const okResponse: ShareConstructUrlResponse = {+ ok: true,+ shareUrl: 'https://openknowledge.ai/d/Root',+ sharedUrl: 'https://github.com/o/r/tree/main',+ branch: 'main',+ };+ const deps = makeDeps({ fetchResponse: okResponse });++ await runShareAction(+ { kind: 'folder', folderRelativePath: '', hasRemote: true, onClickWhenNoRemote: () => {} },+ deps,+ );++ expect(deps.fetchCalls[0].body).toEqual({ kind: 'folder', folderPath: '' });+ expect(deps.successToasts).toEqual(['Folder share link copied.']);});});@@ -256,6 +333,7 @@ describe('runShareAction — no-remote routing', () => {const result = await runShareAction({+ kind: 'doc',docName: 'a',hasRemote: false,onClickWhenNoRemote: () => {@@ -281,6 +359,7 @@ describe('runShareAction — no-remote routing', () => {const result = await runShareAction({+ kind: 'doc',docName: 'a',hasRemote: true,onClickWhenNoRemote: () => {@@ -305,7 +384,7 @@ describe('runShareAction — business-error toasts', () => {});const result = await runShareAction(- { docName: 'a', hasRemote: true, onClickWhenNoRemote: () => {} },+ { kind: 'doc', docName: 'a', hasRemote: true, onClickWhenNoRemote: () => {} },deps,);@@ -329,7 +408,7 @@ describe('runShareAction — business-error toasts', () => {});const result = await runShareAction(- { docName: 'a', hasRemote: true, onClickWhenNoRemote: () => {} },+ { kind: 'doc', docName: 'a', hasRemote: true, onClickWhenNoRemote: () => {} },deps,);@@ -346,7 +425,10 @@ describe('runShareAction — business-error toasts', () => {fetchResponse: { ok: false, error: 'non-github-remote' },});- await runShareAction({ docName: 'a', hasRemote: true, onClickWhenNoRemote: () => {} }, deps);+ await runShareAction(+ { kind: 'doc', docName: 'a', hasRemote: true, onClickWhenNoRemote: () => {} },+ deps,+ );expect(deps.errorToasts).toEqual(['Sharing supports GitHub remotes only.']);});@@ -356,7 +438,10 @@ describe('runShareAction — business-error toasts', () => {fetchResponse: { ok: false, error: 'invalid-path' },});- await runShareAction({ docName: 'a', hasRemote: true, onClickWhenNoRemote: () => {} }, deps);+ await runShareAction(+ { kind: 'doc', docName: 'a', hasRemote: true, onClickWhenNoRemote: () => {} },+ deps,+ );expect(deps.errorToasts).toEqual(["Can't share this path."]);});@@ -367,7 +452,7 @@ describe('runShareAction — transport / clipboard failures', () => {const deps = makeDeps({ fetchThrows: new Error('network down') });const result = await runShareAction(- { docName: 'a', hasRemote: true, onClickWhenNoRemote: () => {} },+ { kind: 'doc', docName: 'a', hasRemote: true, onClickWhenNoRemote: () => {} },deps,);@@ -380,7 +465,7 @@ describe('runShareAction — transport / clipboard failures', () => {const okResponse: ShareConstructUrlResponse = {ok: true,shareUrl: 'https://openknowledge.ai/d/Aaa',- blobUrl: 'https://github.com/o/r/blob/main/a.md',+ sharedUrl: 'https://github.com/o/r/blob/main/a.md',branch: 'main',};const deps = makeDeps({@@ -389,7 +474,7 @@ describe('runShareAction — transport / clipboard failures', () => {});const result = await runShareAction(- { docName: 'a', hasRemote: true, onClickWhenNoRemote: () => {} },+ { kind: 'doc', docName: 'a', hasRemote: true, onClickWhenNoRemote: () => {} },deps,);@@ -406,7 +491,7 @@ describe('runShareAction — transport / clipboard failures', () => {const deps = makeDeps({ fetchStatus: 500 });const result = await runShareAction(- { docName: 'a', hasRemote: true, onClickWhenNoRemote: () => {} },+ { kind: 'doc', docName: 'a', hasRemote: true, onClickWhenNoRemote: () => {} },deps,);diff --git a/packages/app/src/lib/share/run-share-action.ts b/packages/app/src/lib/share/run-share-action.tsindex 560300efe..c4a943154 100644--- a/packages/app/src/lib/share/run-share-action.ts+++ b/packages/app/src/lib/share/run-share-action.ts@@ -1,5 +1,6 @@import type {ShareConstructUrlErrorCode,+ ShareConstructUrlRequest,ShareConstructUrlResponse,} from '@inkeep/open-knowledge-core';import { ShareConstructUrlResponseSchema } from '@inkeep/open-knowledge-core';@@ -7,6 +8,18 @@ import { docNameToMarkdownPath } from '@/lib/doc-paths';const SHARE_CONSTRUCT_URL_PATH = '/api/share/construct-url';+export type ShareTargetInput =+ | { kind: 'doc'; docName: string }+ | { kind: 'folder'; folderRelativePath: string };++export function buildDocShareInput(docName: string): ShareTargetInput {+ return { kind: 'doc', docName };+}++export function buildFolderShareInput(folderRelativePath: string): ShareTargetInput {+ return { kind: 'folder', folderRelativePath };+}+export interface ShareActionDeps {fetchFn?: typeof fetch;clipboardWrite: (text: string) => Promise<void>;@@ -15,11 +28,10 @@ export interface ShareActionDeps {logEvent: (msg: string) => void;}-export interface RunShareActionInput {- docName: string;+export type RunShareActionInput = {hasRemote: boolean;onClickWhenNoRemote: () => void;-}+} & ShareTargetInput;export type RunShareActionResult =| { kind: 'opened-wizard' }@@ -32,19 +44,19 @@ const TRANSPORT_ERROR_TOAST = 'Could not construct share URL.';const CLIPBOARD_ERROR_TOAST = 'Link ready but could not copy to clipboard.';export async function requestShareConstructUrl(- docPath: string,+ body: ShareConstructUrlRequest,fetchFn: typeof fetch = fetch,): Promise<ShareConstructUrlResponse> {const res = await fetchFn(SHARE_CONSTRUCT_URL_PATH, {method: 'POST',headers: { 'Content-Type': 'application/json' },- body: JSON.stringify({ docPath }),+ body: JSON.stringify(body),});if (!res.ok) {throw new Error(`construct-url transport ${res.status}`);}- const body = await res.json();- const parsed = ShareConstructUrlResponseSchema.safeParse(body);+ const responseBody = await res.json();+ const parsed = ShareConstructUrlResponseSchema.safeParse(responseBody);if (!parsed.success) {throw new Error('construct-url response shape mismatch');}@@ -77,11 +89,14 @@ export async function runShareAction(return { kind: 'opened-wizard' };}- const docPath = docNameToMarkdownPath(input.docName);+ const body: ShareConstructUrlRequest =+ input.kind === 'folder'+ ? { kind: 'folder', folderPath: input.folderRelativePath }+ : { kind: 'doc', docPath: docNameToMarkdownPath(input.docName) };let response: ShareConstructUrlResponse;try {- response = await requestShareConstructUrl(docPath, deps.fetchFn);+ response = await requestShareConstructUrl(body, deps.fetchFn);} catch {deps.toastError(TRANSPORT_ERROR_TOAST);return { kind: 'transport-error' };@@ -95,7 +110,7 @@ export async function runShareAction(deps.logEvent('[share] action=link-construct result=clipboard-failed');return { kind: 'clipboard-failed', shareUrl: response.shareUrl };}- deps.toastSuccess('Link copied.');+ deps.toastSuccess(input.kind === 'folder' ? 'Folder share link copied.' : 'Link copied.');deps.logEvent('[share] action=link-construct');return { kind: 'copied', shareUrl: response.shareUrl, branch: response.branch };}diff --git a/packages/app/src/locales/en/messages.json b/packages/app/src/locales/en/messages.jsonindex 4c21d11eb..82caeed6b 100644--- a/packages/app/src/locales/en/messages.json+++ b/packages/app/src/locales/en/messages.json@@ -140,6 +140,7 @@"3_6U6f": ["Connect to GitHub"],"3__SjS": ["breadcrumb"],"3a_Bd7": ["Open source doc: ", ["mirrorSrc"]],+ "3aeN7X": ["All files"],"3h5zMp": ["Something went wrong loading the settings panel."],"3iyGWF": ["Open recent project"],"3jod3l": ["Connect GitHub"],@@ -664,6 +665,7 @@"JmfgFc": ["(a worktree of ", ["0"], ")"],"Jqqevv": ["System error"],"JtD-Br": ["Page link"],+ "Jw6EC4": ["Branch switch failed — try opening the ", ["targetNoun"], " manually."],"K-a33w": ["Start writing to create this page"],"K-h9cT": ["Couldn't save the resolution for ", ["filePath"], "."],"K0N7zS": ["Config sharing status read failed"],@@ -700,6 +702,7 @@"L6Hhh6": ["(root)"],"L8fKuc": ["Run this in your terminal"],"L9Y9Om": ["Top linked pages"],+ "LBwUR6": ["Branch switch timed out — try opening the ", ["targetNoun"], " manually."],"LCUy_N": ["Session ended"],"LDuM35": ["Replace current match from field"],"LE7t79": ["Clone to a new folder"],@@ -892,6 +895,7 @@],"RPo77p": ["Open the Ask AI menu for the current selection."],"RSqaSd": ["Project root"],+ "RY6Bq1": ["Open shared ", ["targetNoun"]],"RaPMZv": ["Keyboard shortcuts available in the editor and workspace."],"Rah7yq": ["What should the AI do? (optional)"],"RfHNf8": ["Open activity panel for ", ["tooltipName"]],@@ -1005,6 +1009,7 @@" selected items? Folders and all files inside them will be deleted. This action cannot be undone."],"WPwDin": ["Open folder on disk"],+ "WR0y2O": ["Share folder"],"WRNXKp": ["Searching"],"WZ-vBy": ["Permanently deletes <0>",@@ -1029,6 +1034,7 @@"X8kjQX": ["Re-authenticate with GitHub"],"X9VpsP": ["Loading folder contents"],"XDzAnp": ["Opens in a new tab"],+ "XH30C4": ["document"],"XPJ0sN": [["settingsDescriptorLabel"], " properties"],"XPqe3B": ["Create new tag #", ["tagValue"]],"XRuL0i": ["Create page"],@@ -1043,6 +1049,13 @@"Chrome uses this to search from the page or focus the address bar. Open Knowledge overrides it while the app has focus."],"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."],"XtRoxT": ["Page ", ["pageNumber"]],@@ -1111,6 +1124,15 @@"_6IEmc": ["Open in Terminal, No workspace"],"_7UQ7y": ["Whole word"],"_8quCH": ["From template"],+ "_902BE": [+ "This ",+ ["targetNoun"],+ " was shared from branch <0>",+ ["shareBranch"],+ "</0>. You're currently on <1>",+ ["currentLabel"],+ "</1>."+ ],"_BthEY": ["Open in ", ["shareBranch"]],"_GBioJ": [["docName"],@@ -1163,6 +1185,7 @@"b3Thhd": ["Upload failed"],"b4AQFK": ["Open activity panel for ", ["tooltipName"], ", editing ", ["realCurrentDoc"]],"b4itZn": ["Working"],+ "b5aNbi": ["The ", ["targetNoun"], " could not be opened — try navigating to it manually."],"bBE5tC": ["Detected on this machine"],"bBcFK_": ["Open emoji picker for ", ["keyName"]],"bD8I7O": ["Complete"],@@ -1282,6 +1305,11 @@],"gJR87V": ["Could not create the project folder. Pick a different folder."],"gKi-a_": ["New project"],+ "gQV-9w": [+ "Branch switched but the ",+ ["targetNoun"],+ " could not be opened — try navigating to it manually."+ ],"gUlRQj": ["Orphans"],"gYz2ep": ["Expires in ", ["timeLabel"]],"gcV0dI": ["The folders and templates are in place; there's nothing left to scaffold."],@@ -1671,6 +1699,15 @@"sJK6pq": ["Permission denied"],"sJWhgo": ["Unknown component: ", ["unregisteredComponentName"]],"sOxZaS": ["Failed to load graph"],+ "sZ2IOu": [+ "This ",+ ["targetNoun"],+ " was shared from branch <0>",+ ["shareBranch"],+ "</0>. It doesn't exist on your current branch (<1>",+ ["currentLabel"],+ "</1>)."+ ],"saIASg": ["Second item"],"saYiIO": ["Path cannot contain null bytes"],"shNd9t": ["Slash command menu"],@@ -1719,6 +1756,7 @@"uWx2ZP": ["Last sync"],"uZAG7T": ["Auto-saved before a concurrent edit", ["sizeSuffix"]],"u_lS4C": ["Clone complete — opening project"],+ "ugoTXs": ["folder"],"uhJEA2": [["count",diff --git a/packages/app/src/locales/en/messages.po b/packages/app/src/locales/en/messages.poindex 4fd26c1fd..9b876cec2 100644--- a/packages/app/src/locales/en/messages.po+++ b/packages/app/src/locales/en/messages.po@@ -109,14 +109,14 @@ msgstr "{0} templates available"#. placeholder {0}: share.owner#. placeholder {1}: share.repo-#. placeholder {2}: share.path+#. placeholder {2}: shareTargetPath(share.target)#: src/components/ShareBranchSwitchDialog.tsxmsgid "{0}/{1} — {2}"msgstr "{0}/{1} — {2}"#. placeholder {0}: share.owner#. placeholder {1}: share.repo-#. placeholder {2}: share.path ? `— ${share.path}` : ''+#. placeholder {2}: shareTargetPath(share.target) ? `— ${shareTargetPath(share.target)}` : ''#: src/components/ShareReceiveDialog.tsxmsgid "{0}/{1} {2}"msgstr "{0}/{1} {2}"@@ -567,6 +567,10 @@ msgstr "Align left"msgid "Align right"msgstr "Align right"+#: src/components/FolderOverview.tsx+msgid "All files"+msgstr "All files"+#: src/components/DiffView.tsxmsgid "All hunks resolved"msgstr "All hunks resolved"@@ -787,16 +791,28 @@ msgid "Branch <0>{shareBranch}</0> is checked out in:"msgstr "Branch <0>{shareBranch}</0> is checked out in:"#: src/components/ShareBranchSwitchDialog.tsx-msgid "Branch switch failed — try opening the doc manually."-msgstr "Branch switch failed — try opening the doc manually."+msgid "Branch switch failed — try opening the {targetNoun} manually."+msgstr "Branch switch failed — try opening the {targetNoun} manually."++#: src/components/ShareBranchSwitchDialog.tsx+#~ msgid "Branch switch failed — try opening the doc manually."+#~ msgstr "Branch switch failed — try opening the doc manually."++#: src/components/ShareBranchSwitchDialog.tsx+msgid "Branch switch timed out — try opening the {targetNoun} manually."+msgstr "Branch switch timed out — try opening the {targetNoun} manually."++#: src/components/ShareBranchSwitchDialog.tsx+#~ msgid "Branch switch timed out — try opening the doc manually."+#~ msgstr "Branch switch timed out — try opening the doc manually."#: src/components/ShareBranchSwitchDialog.tsx-msgid "Branch switch timed out — try opening the doc manually."-msgstr "Branch switch timed out — try opening the doc manually."+msgid "Branch switched but the {targetNoun} could not be opened — try navigating to it manually."+msgstr "Branch switched but the {targetNoun} could not be opened — try navigating to it manually."#: src/components/ShareBranchSwitchDialog.tsx-msgid "Branch switched but the document could not be opened — try navigating to it manually."-msgstr "Branch switched but the document could not be opened — try navigating to it manually."+#~ msgid "Branch switched but the document could not be opened — try navigating to it manually."+#~ msgstr "Branch switched but the document could not be opened — try navigating to it manually."#: src/components/ui/breadcrumb.tsxmsgid "breadcrumb"@@ -1807,6 +1823,11 @@ msgstr "Do you want to permanently delete instead?"msgid "Docs tagged #{tagDocsName}"msgstr "Docs tagged #{tagDocsName}"+#: src/components/ShareBranchSwitchDialog.tsx+#: src/components/ShareReceiveDialog.tsx+msgid "document"+msgstr "document"+#: src/components/DocumentErrorBoundary.tsxmsgid "Document not found"msgstr "Document not found"@@ -2380,6 +2401,12 @@ msgstr "Fold or unfold source"msgid "Fold, unfold, fold all, or unfold all source ranges."msgstr "Fold, unfold, fold all, or unfold all source ranges."+#: src/components/ShareBranchSwitchDialog.tsx+#: src/components/ShareReceiveDialog.tsx+msgid "folder"+msgstr "folder"++#: src/components/share-metadata-rows.tsx#: src/editor/extensions/InternalLinkPropPanel.tsx#: src/editor/extensions/WikiLinkPropPanel.tsx#: src/editor/link-path-suggestions.tsx@@ -3842,8 +3869,13 @@ msgstr "Open recent project"#: src/components/ShareBranchSwitchDialog.tsx#: src/components/ShareReceiveDialog.tsx-msgid "Open shared document"-msgstr "Open shared document"+msgid "Open shared {targetNoun}"+msgstr "Open shared {targetNoun}"++#: src/components/ShareBranchSwitchDialog.tsx+#: src/components/ShareReceiveDialog.tsx+#~ msgid "Open shared document"+#~ msgstr "Open shared document"#: src/editor/extensions/JsxComponentView.tsxmsgid "Open source doc: {mirrorSrc}"@@ -4872,6 +4904,10 @@ msgstr "Share"msgid "Share doc"msgstr "Share doc"+#: src/components/ShareButton.tsx+msgid "Share folder"+msgstr "Share folder"+#: src/components/ConsentDialogBody.tsx#: src/components/CreateProjectDialog.tsxmsgid "Share OK config with my team?"@@ -5343,6 +5379,10 @@ msgstr "Text"msgid "That folder isn't an Open Knowledge project yet. Initialize it and open?"msgstr "That folder isn't an Open Knowledge project yet. Initialize it and open?"+#: src/components/ShareBranchSwitchDialog.tsx+msgid "The {targetNoun} could not be opened — try navigating to it manually."+msgstr "The {targetNoun} could not be opened — try navigating to it manually."+#: src/components/InstallInClaudeDesktopDialog.tsxmsgid "The Claude Desktop App didn't open the file. Is it installed? ({msg})"msgstr "The Claude Desktop App didn't open the file. Is it installed? ({msg})"@@ -5360,8 +5400,8 @@ msgid "The desktop app isn't responding. Refresh and try again."msgstr "The desktop app isn't responding. Refresh and try again."#: src/components/ShareBranchSwitchDialog.tsx-msgid "The document could not be opened — try navigating to it manually."-msgstr "The document could not be opened — try navigating to it manually."+#~ msgid "The document could not be opened — try navigating to it manually."+#~ msgstr "The document could not be opened — try navigating to it manually."#: src/components/FileTree.tsxmsgid "The file is in your Trash; the file-watcher will reconcile."@@ -5391,21 +5431,33 @@ msgstr "The properties block at the top of this doc has a formatting error. Switmsgid "Theme"msgstr "Theme"+#: 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."++#: src/components/ShareBranchSwitchDialog.tsx+msgid "This {targetNoun} was shared from branch <0>{shareBranch}</0>. It doesn't exist on your current branch (<1>{currentLabel}</1>)."+msgstr "This {targetNoun} was shared from branch <0>{shareBranch}</0>. It doesn't exist on your current branch (<1>{currentLabel}</1>)."++#: src/components/ShareBranchSwitchDialog.tsx+msgid "This {targetNoun} was shared from branch <0>{shareBranch}</0>. You're currently on <1>{currentLabel}</1>."+msgstr "This {targetNoun} was shared from branch <0>{shareBranch}</0>. You're currently on <1>{currentLabel}</1>."+#: src/components/ShareReceiveDialog.tsxmsgid "This branch is checked out in:"msgstr "This branch is checked out in:"#: src/components/ShareBranchSwitchDialog.tsx-msgid "This doc 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 doc 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 doc 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 doc 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."#: src/components/ShareBranchSwitchDialog.tsx-msgid "This doc was shared from branch <0>{shareBranch}</0>. It doesn't exist on your current branch (<1>{currentLabel}</1>)."-msgstr "This doc was shared from branch <0>{shareBranch}</0>. It doesn't exist on your current branch (<1>{currentLabel}</1>)."+#~ msgid "This doc was shared from branch <0>{shareBranch}</0>. It doesn't exist on your current branch (<1>{currentLabel}</1>)."+#~ msgstr "This doc was shared from branch <0>{shareBranch}</0>. It doesn't exist on your current branch (<1>{currentLabel}</1>)."#: src/components/ShareBranchSwitchDialog.tsx-msgid "This doc was shared from branch <0>{shareBranch}</0>. You're currently on <1>{currentLabel}</1>."-msgstr "This doc was shared from branch <0>{shareBranch}</0>. You're currently on <1>{currentLabel}</1>."+#~ msgid "This doc was shared from branch <0>{shareBranch}</0>. You're currently on <1>{currentLabel}</1>."+#~ msgstr "This doc was shared from branch <0>{shareBranch}</0>. You're currently on <1>{currentLabel}</1>."#: src/components/ShareReceiveDialog.tsx#~ msgid "This document doesn't exist on your local copy of branch <0>{currentBranchLabel}</0>. Your branch may be behind the remote — pull the latest changes from GitHub, then reopen this link."diff --git a/packages/app/src/locales/pseudo/messages.json b/packages/app/src/locales/pseudo/messages.jsonindex 88050f658..51ca0b5c6 100644--- a/packages/app/src/locales/pseudo/messages.json+++ b/packages/app/src/locales/pseudo/messages.json@@ -140,6 +140,7 @@"3_6U6f": ["Ćōńńēćţ ţō ĜĩţĤũƀ"],"3__SjS": ["ƀŕēàďćŕũḿƀ"],"3a_Bd7": ["Ōƥēń śōũŕćē ďōć: ", ["mirrorSrc"]],+ "3aeN7X": ["Àĺĺ ƒĩĺēś"],"3h5zMp": ["Śōḿēţĥĩńĝ ŵēńţ ŵŕōńĝ ĺōàďĩńĝ ţĥē śēţţĩńĝś ƥàńēĺ."],"3iyGWF": ["Ōƥēń ŕēćēńţ ƥŕōĴēćţ"],"3jod3l": ["Ćōńńēćţ ĜĩţĤũƀ"],@@ -664,6 +665,7 @@"JmfgFc": ["(à ŵōŕķţŕēē ōƒ ", ["0"], ")"],"Jqqevv": ["Śŷśţēḿ ēŕŕōŕ"],"JtD-Br": ["Ƥàĝē ĺĩńķ"],+ "Jw6EC4": ["ßŕàńćĥ śŵĩţćĥ ƒàĩĺēď — ţŕŷ ōƥēńĩńĝ ţĥē ", ["targetNoun"], " ḿàńũàĺĺŷ."],"K-a33w": ["Śţàŕţ ŵŕĩţĩńĝ ţō ćŕēàţē ţĥĩś ƥàĝē"],"K-h9cT": ["Ćōũĺďń'ţ śàvē ţĥē ŕēśōĺũţĩōń ƒōŕ ", ["filePath"], "."],"K0N7zS": ["Ćōńƒĩĝ śĥàŕĩńĝ śţàţũś ŕēàď ƒàĩĺēď"],@@ -700,6 +702,7 @@"L6Hhh6": ["(ŕōōţ)"],"L8fKuc": ["Ŕũń ţĥĩś ĩń ŷōũŕ ţēŕḿĩńàĺ"],"L9Y9Om": ["Ţōƥ ĺĩńķēď ƥàĝēś"],+ "LBwUR6": ["ßŕàńćĥ śŵĩţćĥ ţĩḿēď ōũţ — ţŕŷ ōƥēńĩńĝ ţĥē ", ["targetNoun"], " ḿàńũàĺĺŷ."],"LCUy_N": ["Śēśśĩōń ēńďēď"],"LDuM35": ["Ŕēƥĺàćē ćũŕŕēńţ ḿàţćĥ ƒŕōḿ ƒĩēĺď"],"LE7t79": ["Ćĺōńē ţō à ńēŵ ƒōĺďēŕ"],@@ -892,6 +895,7 @@],"RPo77p": ["Ōƥēń ţĥē Àśķ ÀĨ ḿēńũ ƒōŕ ţĥē ćũŕŕēńţ śēĺēćţĩōń."],"RSqaSd": ["ƤŕōĴēćţ ŕōōţ"],+ "RY6Bq1": ["Ōƥēń śĥàŕēď ", ["targetNoun"]],"RaPMZv": ["Ķēŷƀōàŕď śĥōŕţćũţś àvàĩĺàƀĺē ĩń ţĥē ēďĩţōŕ àńď ŵōŕķśƥàćē."],"Rah7yq": ["Ŵĥàţ śĥōũĺď ţĥē ÀĨ ďō? (ōƥţĩōńàĺ)"],"RfHNf8": ["Ōƥēń àćţĩvĩţŷ ƥàńēĺ ƒōŕ ", ["tooltipName"]],@@ -1005,6 +1009,7 @@" śēĺēćţēď ĩţēḿś? Ƒōĺďēŕś àńď àĺĺ ƒĩĺēś ĩńśĩďē ţĥēḿ ŵĩĺĺ ƀē ďēĺēţēď. Ţĥĩś àćţĩōń ćàńńōţ ƀē ũńďōńē."],"WPwDin": ["Ōƥēń ƒōĺďēŕ ōń ďĩśķ"],+ "WR0y2O": ["Śĥàŕē ƒōĺďēŕ"],"WRNXKp": ["Śēàŕćĥĩńĝ"],"WZ-vBy": ["Ƥēŕḿàńēńţĺŷ ďēĺēţēś <0>",@@ -1029,6 +1034,7 @@"X8kjQX": ["Ŕē-àũţĥēńţĩćàţē ŵĩţĥ ĜĩţĤũƀ"],"X9VpsP": ["Ĺōàďĩńĝ ƒōĺďēŕ ćōńţēńţś"],"XDzAnp": ["Ōƥēńś ĩń à ńēŵ ţàƀ"],+ "XH30C4": ["ďōćũḿēńţ"],"XPJ0sN": [["settingsDescriptorLabel"], " ƥŕōƥēŕţĩēś"],"XPqe3B": ["Ćŕēàţē ńēŵ ţàĝ #", ["tagValue"]],"XRuL0i": ["Ćŕēàţē ƥàĝē"],@@ -1043,6 +1049,13 @@"Ćĥŕōḿē ũśēś ţĥĩś ţō śēàŕćĥ ƒŕōḿ ţĥē ƥàĝē ōŕ ƒōćũś ţĥē àďďŕēśś ƀàŕ. Ōƥēń Ķńōŵĺēďĝē ōvēŕŕĩďēś ĩţ ŵĥĩĺē ţĥē àƥƥ ĥàś ƒōćũś."],"XnlF3W": ["Àďď ţĥē ńēxţ ḿàţćĥĩńĝ śōũŕćē śēĺēćţĩōń."],+ "XnoA1k": [+ "Ţĥĩś ",+ ["targetNoun"],+ " ōńĺŷ ēxĩśţś ōń ƀŕàńćĥ <0>",+ ["shareBranch"],+ "</0>. Ŷōũ ĥàvē ũńćōḿḿĩţţēď ćĥàńĝēś ţĥàţ ƥŕēvēńţ śŵĩţćĥĩńĝ. Ćōḿḿĩţ ōŕ śţàśĥ ŷōũŕ ćĥàńĝēś, ţĥēń ōƥēń ţĥē śĥàŕē ĺĩńķ àĝàĩń."+ ],"XopE_I": ["Ƒàĩĺēď ţō ƥàŕśē ƀàćķĺĩńķś ēŕŕōŕ ŕēśƥōńśē (ĤŢŢƤ ", ["status"], ")"],"XpIZmv": ["Ƒēńćēď ćōďē ƀĺōćķ ŵĩţĥ ḿōńōśƥàćē ţēxţ."],"XtRoxT": ["Ƥàĝē ", ["pageNumber"]],@@ -1111,6 +1124,15 @@"_6IEmc": ["Ōƥēń ĩń Ţēŕḿĩńàĺ, Ńō ŵōŕķśƥàćē"],"_7UQ7y": ["Ŵĥōĺē ŵōŕď"],"_8quCH": ["Ƒŕōḿ ţēḿƥĺàţē"],+ "_902BE": [+ "Ţĥĩś ",+ ["targetNoun"],+ " ŵàś śĥàŕēď ƒŕōḿ ƀŕàńćĥ <0>",+ ["shareBranch"],+ "</0>. Ŷōũ'ŕē ćũŕŕēńţĺŷ ōń <1>",+ ["currentLabel"],+ "</1>."+ ],"_BthEY": ["Ōƥēń ĩń ", ["shareBranch"]],"_GBioJ": [["docName"],@@ -1163,6 +1185,7 @@"b3Thhd": ["Ũƥĺōàď ƒàĩĺēď"],"b4AQFK": ["Ōƥēń àćţĩvĩţŷ ƥàńēĺ ƒōŕ ", ["tooltipName"], ", ēďĩţĩńĝ ", ["realCurrentDoc"]],"b4itZn": ["Ŵōŕķĩńĝ"],+ "b5aNbi": ["Ţĥē ", ["targetNoun"], " ćōũĺď ńōţ ƀē ōƥēńēď — ţŕŷ ńàvĩĝàţĩńĝ ţō ĩţ ḿàńũàĺĺŷ."],"bBE5tC": ["Ďēţēćţēď ōń ţĥĩś ḿàćĥĩńē"],"bBcFK_": ["Ōƥēń ēḿōĴĩ ƥĩćķēŕ ƒōŕ ", ["keyName"]],"bD8I7O": ["Ćōḿƥĺēţē"],@@ -1282,6 +1305,11 @@],"gJR87V": ["Ćōũĺď ńōţ ćŕēàţē ţĥē ƥŕōĴēćţ ƒōĺďēŕ. Ƥĩćķ à ďĩƒƒēŕēńţ ƒōĺďēŕ."],"gKi-a_": ["Ńēŵ ƥŕōĴēćţ"],+ "gQV-9w": [+ "ßŕàńćĥ śŵĩţćĥēď ƀũţ ţĥē ",+ ["targetNoun"],+ " ćōũĺď ńōţ ƀē ōƥēńēď — ţŕŷ ńàvĩĝàţĩńĝ ţō ĩţ ḿàńũàĺĺŷ."+ ],"gUlRQj": ["Ōŕƥĥàńś"],"gYz2ep": ["Ēxƥĩŕēś ĩń ", ["timeLabel"]],"gcV0dI": ["Ţĥē ƒōĺďēŕś àńď ţēḿƥĺàţēś àŕē ĩń ƥĺàćē; ţĥēŕē'ś ńōţĥĩńĝ ĺēƒţ ţō śćàƒƒōĺď."],@@ -1671,6 +1699,15 @@"sJK6pq": ["Ƥēŕḿĩśśĩōń ďēńĩēď"],"sJWhgo": ["Ũńķńōŵń ćōḿƥōńēńţ: ", ["unregisteredComponentName"]],"sOxZaS": ["Ƒàĩĺēď ţō ĺōàď ĝŕàƥĥ"],+ "sZ2IOu": [+ "Ţĥĩś ",+ ["targetNoun"],+ " ŵàś śĥàŕēď ƒŕōḿ ƀŕàńćĥ <0>",+ ["shareBranch"],+ "</0>. Ĩţ ďōēśń'ţ ēxĩśţ ōń ŷōũŕ ćũŕŕēńţ ƀŕàńćĥ (<1>",+ ["currentLabel"],+ "</1>)."+ ],"saIASg": ["Śēćōńď ĩţēḿ"],"saYiIO": ["Ƥàţĥ ćàńńōţ ćōńţàĩń ńũĺĺ ƀŷţēś"],"shNd9t": ["Śĺàśĥ ćōḿḿàńď ḿēńũ"],@@ -1719,6 +1756,7 @@"uWx2ZP": ["Ĺàśţ śŷńć"],"uZAG7T": ["Àũţō-śàvēď ƀēƒōŕē à ćōńćũŕŕēńţ ēďĩţ", ["sizeSuffix"]],"u_lS4C": ["Ćĺōńē ćōḿƥĺēţē — ōƥēńĩńĝ ƥŕōĴēćţ"],+ "ugoTXs": ["ƒōĺďēŕ"],"uhJEA2": [["count",diff --git a/packages/app/src/locales/pseudo/messages.po b/packages/app/src/locales/pseudo/messages.poindex 43fe7c8ec..e93f00d5b 100644--- a/packages/app/src/locales/pseudo/messages.po+++ b/packages/app/src/locales/pseudo/messages.po@@ -109,14 +109,14 @@ msgstr ""#. placeholder {0}: share.owner#. placeholder {1}: share.repo-#. placeholder {2}: share.path+#. placeholder {2}: shareTargetPath(share.target)#: src/components/ShareBranchSwitchDialog.tsxmsgid "{0}/{1} — {2}"msgstr ""#. placeholder {0}: share.owner#. placeholder {1}: share.repo-#. placeholder {2}: share.path ? `— ${share.path}` : ''+#. placeholder {2}: shareTargetPath(share.target) ? `— ${shareTargetPath(share.target)}` : ''#: src/components/ShareReceiveDialog.tsxmsgid "{0}/{1} {2}"msgstr ""@@ -562,6 +562,10 @@ msgstr ""msgid "Align right"msgstr ""+#: src/components/FolderOverview.tsx+msgid "All files"+msgstr ""+#: src/components/DiffView.tsxmsgid "All hunks resolved"msgstr ""@@ -782,17 +786,29 @@ msgid "Branch <0>{shareBranch}</0> is checked out in:"msgstr ""#: src/components/ShareBranchSwitchDialog.tsx-msgid "Branch switch failed — try opening the doc manually."+msgid "Branch switch failed — try opening the {targetNoun} manually."msgstr ""#: src/components/ShareBranchSwitchDialog.tsx-msgid "Branch switch timed out — try opening the doc manually."+#~ msgid "Branch switch failed — try opening the doc manually."+#~ msgstr ""++#: src/components/ShareBranchSwitchDialog.tsx+msgid "Branch switch timed out — try opening the {targetNoun} manually."msgstr ""#: src/components/ShareBranchSwitchDialog.tsx-msgid "Branch switched but the document could not be opened — try navigating to it manually."+#~ msgid "Branch switch timed out — try opening the doc manually."+#~ msgstr ""++#: src/components/ShareBranchSwitchDialog.tsx+msgid "Branch switched but the {targetNoun} could not be opened — try navigating to it manually."msgstr ""+#: src/components/ShareBranchSwitchDialog.tsx+#~ msgid "Branch switched but the document could not be opened — try navigating to it manually."+#~ msgstr ""+#: src/components/ui/breadcrumb.tsxmsgid "breadcrumb"msgstr ""@@ -1802,6 +1818,11 @@ msgstr ""msgid "Docs tagged #{tagDocsName}"msgstr ""+#: src/components/ShareBranchSwitchDialog.tsx+#: src/components/ShareReceiveDialog.tsx+msgid "document"+msgstr ""+#: src/components/DocumentErrorBoundary.tsxmsgid "Document not found"msgstr ""@@ -2375,6 +2396,12 @@ msgstr ""msgid "Fold, unfold, fold all, or unfold all source ranges."msgstr ""+#: src/components/ShareBranchSwitchDialog.tsx+#: src/components/ShareReceiveDialog.tsx+msgid "folder"+msgstr ""++#: src/components/share-metadata-rows.tsx#: src/editor/extensions/InternalLinkPropPanel.tsx#: src/editor/extensions/WikiLinkPropPanel.tsx#: src/editor/link-path-suggestions.tsx@@ -3837,9 +3864,14 @@ msgstr ""#: src/components/ShareBranchSwitchDialog.tsx#: src/components/ShareReceiveDialog.tsx-msgid "Open shared document"+msgid "Open shared {targetNoun}"msgstr ""+#: src/components/ShareBranchSwitchDialog.tsx+#: src/components/ShareReceiveDialog.tsx+#~ msgid "Open shared document"+#~ msgstr ""+#: src/editor/extensions/JsxComponentView.tsxmsgid "Open source doc: {mirrorSrc}"msgstr ""@@ -4867,6 +4899,10 @@ msgstr ""msgid "Share doc"msgstr ""+#: src/components/ShareButton.tsx+msgid "Share folder"+msgstr ""+#: src/components/ConsentDialogBody.tsx#: src/components/CreateProjectDialog.tsxmsgid "Share OK config with my team?"@@ -5338,6 +5374,10 @@ msgstr ""msgid "That folder isn't an Open Knowledge project yet. Initialize it and open?"msgstr ""+#: src/components/ShareBranchSwitchDialog.tsx+msgid "The {targetNoun} could not be opened — try navigating to it manually."+msgstr ""+#: src/components/InstallInClaudeDesktopDialog.tsxmsgid "The Claude Desktop App didn't open the file. Is it installed? ({msg})"msgstr ""@@ -5355,8 +5395,8 @@ msgid "The desktop app isn't responding. Refresh and try again."msgstr ""#: src/components/ShareBranchSwitchDialog.tsx-msgid "The document could not be opened — try navigating to it manually."-msgstr ""+#~ msgid "The document could not be opened — try navigating to it manually."+#~ msgstr ""#: src/components/FileTree.tsxmsgid "The file is in your Trash; the file-watcher will reconcile."@@ -5386,22 +5426,34 @@ msgstr ""msgid "Theme"msgstr ""-#: src/components/ShareReceiveDialog.tsx-msgid "This branch is checked out in:"+#: 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 ""#: src/components/ShareBranchSwitchDialog.tsx-msgid "This doc 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} was shared from branch <0>{shareBranch}</0>. It doesn't exist on your current branch (<1>{currentLabel}</1>)."msgstr ""#: src/components/ShareBranchSwitchDialog.tsx-msgid "This doc was shared from branch <0>{shareBranch}</0>. It doesn't exist on your current branch (<1>{currentLabel}</1>)."+msgid "This {targetNoun} was shared from branch <0>{shareBranch}</0>. You're currently on <1>{currentLabel}</1>."msgstr ""-#: src/components/ShareBranchSwitchDialog.tsx-msgid "This doc was shared from branch <0>{shareBranch}</0>. You're currently on <1>{currentLabel}</1>."+#: src/components/ShareReceiveDialog.tsx+msgid "This branch is checked out in:"msgstr ""+#: src/components/ShareBranchSwitchDialog.tsx+#~ msgid "This doc 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 ""++#: src/components/ShareBranchSwitchDialog.tsx+#~ msgid "This doc was shared from branch <0>{shareBranch}</0>. It doesn't exist on your current branch (<1>{currentLabel}</1>)."+#~ msgstr ""++#: src/components/ShareBranchSwitchDialog.tsx+#~ msgid "This doc was shared from branch <0>{shareBranch}</0>. You're currently on <1>{currentLabel}</1>."+#~ msgstr ""+#: src/components/ShareReceiveDialog.tsx#~ msgid "This document doesn't exist on your local copy of branch <0>{currentBranchLabel}</0>. Your branch may be behind the remote — pull the latest changes from GitHub, then reopen this link."#~ msgstr ""diff --git a/packages/app/tests/stress/fixtures/handoff-mocks.ts b/packages/app/tests/stress/fixtures/handoff-mocks.tsindex df6414fbb..a516f0659 100644--- a/packages/app/tests/stress/fixtures/handoff-mocks.ts+++ b/packages/app/tests/stress/fixtures/handoff-mocks.ts@@ -252,7 +252,7 @@ export async function installHandoffMocks(page: Page, cfg: HandoffMockConfig): Popen: async () => {},createNew: async () => {},recordCreateNewBannerShown: async () => {},- checkDocExists: async () => 'unreadable' as const,+ checkTargetExists: async () => 'unreadable' as const,readHeadBranch: async () => ({ currentBranch: null, headSha: null, detached: false }),fetchBranchInfo: async () => null,runCheckout: async () => null,diff --git a/packages/cli/src/github/url.test.ts b/packages/cli/src/github/url.test.tsindex 15dff2be7..ec5d22eea 100644--- a/packages/cli/src/github/url.test.ts+++ b/packages/cli/src/github/url.test.ts@@ -1,5 +1,5 @@import { describe, expect, test } from 'bun:test';-import { parseGitHubBlobUrl, parseGitUrl } from './url.ts';+import { parseGitHubBlobUrl, parseGitHubShareUrl, parseGitHubTreeUrl, parseGitUrl } from './url.ts';describe('parseGitUrl', () => {describe('https:// URLs', () => {@@ -370,7 +370,7 @@ describe('parseGitHubBlobUrl', () => {).toBeNull();});- test('malformed path (no /blob/ segment) returns null', () => {+ test('tree (folder) URL returns null from blob-only parser', () => {expect(parseGitHubBlobUrl('https://github.com/owner/repo/tree/main/README.md')).toBeNull();});@@ -425,3 +425,161 @@ describe('parseGitHubBlobUrl', () => {}});});++describe('parseGitHubTreeUrl', () => {+ test('happy path: tree URL with a folder path', () => {+ const result = parseGitHubTreeUrl(+ 'https://github.com/inkeep/open-knowledge/tree/main/docs/sub',+ );+ expect(result).toEqual({+ owner: 'inkeep',+ repo: 'open-knowledge',+ branch: 'main',+ path: 'docs/sub',+ });+ });++ test('root folder: tree/<branch> (no path, no trailing slash) -> path ""', () => {+ const result = parseGitHubTreeUrl('https://github.com/owner/repo/tree/main');+ expect(result).toEqual({ owner: 'owner', repo: 'repo', branch: 'main', path: '' });+ });++ test('root folder: tree/<branch>/ (trailing slash) -> path ""', () => {+ const result = parseGitHubTreeUrl('https://github.com/owner/repo/tree/main/');+ expect(result).toEqual({ owner: 'owner', repo: 'repo', branch: 'main', path: '' });+ });++ test('branch containing slash (percent-encoded) round-trips', () => {+ const result = parseGitHubTreeUrl(+ 'https://github.com/inkeep/open-knowledge/tree/feat%2Ffoo/docs',+ );+ expect(result).toEqual({+ owner: 'inkeep',+ repo: 'open-knowledge',+ branch: 'feat/foo',+ path: 'docs',+ });+ });++ test('%2F-encoded slashed branch at root round-trips', () => {+ const result = parseGitHubTreeUrl('https://github.com/owner/repo/tree/feat%2Ffoo');+ expect(result).toEqual({ owner: 'owner', repo: 'repo', branch: 'feat/foo', path: '' });+ });++ test('percent-encoded path segments round-trip', () => {+ const result = parseGitHubTreeUrl(+ 'https://github.com/owner/repo/tree/main/docs/Q4%20OKRs%20%E2%80%94%20Marketing',+ );+ expect(result).toEqual({+ owner: 'owner',+ repo: 'repo',+ branch: 'main',+ path: 'docs/Q4 OKRs — Marketing',+ });+ });++ test('accepts www.github.com host', () => {+ const result = parseGitHubTreeUrl('https://www.github.com/owner/repo/tree/main/docs');+ expect(result).toEqual({ owner: 'owner', repo: 'repo', branch: 'main', path: 'docs' });+ });++ test('ignores query string and fragment', () => {+ const result = parseGitHubTreeUrl('https://github.com/owner/repo/tree/main/docs?ref=x#frag');+ expect(result).toEqual({ owner: 'owner', repo: 'repo', branch: 'main', path: 'docs' });+ });++ test('blob URL returns null', () => {+ expect(parseGitHubTreeUrl('https://github.com/owner/repo/blob/main/README.md')).toBeNull();+ });++ test('non-github host returns null', () => {+ expect(parseGitHubTreeUrl('https://gitlab.com/owner/repo/tree/main/docs')).toBeNull();+ });++ test('subdomain spoofing returns null', () => {+ expect(+ parseGitHubTreeUrl('https://github.com.evil.example/owner/repo/tree/main/docs'),+ ).toBeNull();+ });++ test('empty intermediate path segment returns null', () => {+ expect(parseGitHubTreeUrl('https://github.com/owner/repo/tree/main/a//b')).toBeNull();+ });++ test('missing branch (path ends after /tree/) returns null', () => {+ expect(parseGitHubTreeUrl('https://github.com/owner/repo/tree/')).toBeNull();+ });++ test('not a URL returns null', () => {+ expect(parseGitHubTreeUrl('not-a-url')).toBeNull();+ });++ test('empty string returns null', () => {+ expect(parseGitHubTreeUrl('')).toBeNull();+ });+});++describe('parseGitHubShareUrl (dispatcher)', () => {+ test('blob URL dispatches to kind:"doc"', () => {+ const result = parseGitHubShareUrl(+ 'https://github.com/inkeep/open-knowledge/blob/main/README.md',+ );+ expect(result).toEqual({+ kind: 'doc',+ owner: 'inkeep',+ repo: 'open-knowledge',+ branch: 'main',+ path: 'README.md',+ });+ });++ test('tree URL with path dispatches to kind:"folder"', () => {+ const result = parseGitHubShareUrl('https://github.com/owner/repo/tree/main/docs/sub');+ expect(result).toEqual({+ kind: 'folder',+ owner: 'owner',+ repo: 'repo',+ branch: 'main',+ path: 'docs/sub',+ });+ });++ test('tree root URL dispatches to kind:"folder" with empty path', () => {+ const result = parseGitHubShareUrl('https://github.com/owner/repo/tree/main');+ expect(result).toEqual({+ kind: 'folder',+ owner: 'owner',+ repo: 'repo',+ branch: 'main',+ path: '',+ });+ });++ test('tree root URL with trailing slash dispatches to kind:"folder" with empty path', () => {+ const result = parseGitHubShareUrl('https://github.com/owner/repo/tree/main/');+ expect(result).toEqual({+ kind: 'folder',+ owner: 'owner',+ repo: 'repo',+ branch: 'main',+ path: '',+ });+ });++ test('%2F-encoded slashed branch on a tree URL round-trips', () => {+ const result = parseGitHubShareUrl('https://github.com/owner/repo/tree/feat%2Ffoo/docs');+ expect(result).toEqual({+ kind: 'folder',+ owner: 'owner',+ repo: 'repo',+ branch: 'feat/foo',+ path: 'docs',+ });+ });++ test('non-github / malformed input returns null', () => {+ expect(parseGitHubShareUrl('https://gitlab.com/owner/repo/tree/main/docs')).toBeNull();+ expect(parseGitHubShareUrl('not-a-url')).toBeNull();+ expect(parseGitHubShareUrl('')).toBeNull();+ });+});diff --git a/packages/cli/src/github/url.ts b/packages/cli/src/github/url.tsindex 4dfbc4f23..6b6e955d1 100644--- a/packages/cli/src/github/url.ts+++ b/packages/cli/src/github/url.ts@@ -12,6 +12,17 @@ export interface ParsedGitHubBlobUrl {path: string;}+export interface ParsedGitHubTreeUrl {+ owner: string;+ repo: string;+ branch: string;+ path: string;+}++export type ParsedGitHubShareTarget =+ | { kind: 'doc'; owner: string; repo: string; branch: string; path: string }+ | { kind: 'folder'; owner: string; repo: string; branch: string; path: string };+function stripPort(hostname: string): string {return hostname.replace(/:\d+$/, '');}@@ -95,3 +106,53 @@ export function parseGitHubBlobUrl(input: string): ParsedGitHubBlobUrl | null {return { owner, repo, branch, path: pathParts.join('/') };}++export function parseGitHubTreeUrl(input: string): ParsedGitHubTreeUrl | null {+ let url: URL;+ try {+ url = new URL(input);+ } catch {+ return null;+ }++ if (url.hostname !== 'github.com' && url.hostname !== 'www.github.com') {+ return null;+ }++ const rawSegments = url.pathname.split('/');++ if (rawSegments.length < 5) return null;+ if (rawSegments[0] !== '') return null; // leading-slash hygiene+ if (rawSegments[3] !== 'tree') return null;++ const pathSegmentsRaw = rawSegments.slice(5);+ if (pathSegmentsRaw.length === 1 && pathSegmentsRaw[0] === '') pathSegmentsRaw.pop();++ let owner: string;+ let repo: string;+ let branch: string;+ let pathParts: string[];+ try {+ owner = decodeURIComponent(rawSegments[1]);+ repo = decodeURIComponent(rawSegments[2]);+ branch = decodeURIComponent(rawSegments[4]);+ pathParts = pathSegmentsRaw.map((s) => decodeURIComponent(s));+ } catch {+ return null;+ }++ if (!owner || !repo || !branch) return null;+ if (pathParts.some((p) => p.length === 0)) return null;++ return { owner, repo, branch, path: pathParts.join('/') };+}++export function parseGitHubShareUrl(input: string): ParsedGitHubShareTarget | null {+ const blob = parseGitHubBlobUrl(input);+ if (blob) return { kind: 'doc', ...blob };++ const tree = parseGitHubTreeUrl(input);+ if (tree) return { kind: 'folder', ...tree };++ return null;+}diff --git a/packages/cli/src/index.ts b/packages/cli/src/index.tsindex fff4cccca..74699c05b 100644--- a/packages/cli/src/index.ts+++ b/packages/cli/src/index.ts@@ -45,7 +45,11 @@ export {} from './github/folder-validator.ts';export {type ParsedGitHubBlobUrl,+ type ParsedGitHubShareTarget,+ type ParsedGitHubTreeUrl,parseGitHubBlobUrl,+ parseGitHubShareUrl,+ parseGitHubTreeUrl,parseGitUrl,} from './github/url.ts';export type { IntegrationWriteOutcome } from './integrations/project-integration-writers.ts';diff --git a/packages/core/src/desktop-bridge.ts b/packages/core/src/desktop-bridge.tsindex 70be8e9b8..31241c4f2 100644--- a/packages/core/src/desktop-bridge.ts+++ b/packages/core/src/desktop-bridge.ts@@ -64,11 +64,11 @@ interface OkProjectOpenRequest {path: string;target: 'new-window';entryPoint: OkProjectEntryPoint;- pendingDeepLinkDoc?: string;+ pendingDeepLinkTarget?: { kind: 'doc' | 'folder'; path: string };pendingBranch?: string | null;}-export type OkCheckDocExistsResult = 'exists' | 'missing' | 'unreadable';+export type OkCheckTargetExistsResult = 'exists' | 'missing' | 'unreadable';export interface OkHeadBranchInfo {readonly currentBranch: string | null;@@ -89,14 +89,21 @@ interface OkUpdateStuckHintInfo {readonly downloadUrl: string;}+/** Kind-discriminated receiver target carried by `OkSharePayloadFields`.+ * Local copy — see canonical `ShareTarget` in+ * `packages/desktop/src/shared/bridge-contract.ts`. */+type ShareTarget =+ | { readonly kind: 'doc'; readonly docPath: string }+ | { readonly kind: 'folder'; readonly folderPath: string };+/** Local copy — see canonical `OkSharePayloadFields` in* `packages/desktop/src/shared/bridge-contract.ts`. */interface OkSharePayloadFields {readonly owner: string;readonly repo: string;readonly branch: string;- readonly path: string;- readonly blobUrl: string;+ readonly sharedUrl: string;+ readonly target: ShareTarget;}/** Local copy — see canonical `OkShareReceivedPayload` in@@ -406,7 +413,13 @@ export interface OkDesktopBridge {onWhatsNew(cb: (info: OkWhatsNewInfo) => void): OkUnsubscribe;onUpdateStuckHint(cb: (info: OkUpdateStuckHintInfo) => void): OkUnsubscribe;onDeepLink(- cb: (evt: { doc: string; branch?: string | null; multiCandidate?: boolean }) => void,+ cb: (evt: {+ doc: string;+ kind: 'doc' | 'folder';+ branch?: string | null;+ multiCandidate?: boolean;+ targetMissing?: boolean;+ }) => void,): OkUnsubscribe;onShareReceived(cb: (payload: OkShareReceivedPayload) => void): OkUnsubscribe;@@ -498,15 +511,17 @@ export interface OkDesktopBridge {sharing?: 'shared' | 'local-only';}): Promise<void>;recordCreateNewBannerShown(banner: CreateNewBannerKind): Promise<void>;- checkDocExists(request: {+ checkTargetExists(request: {projectPath: string;- docPath: string;- }): Promise<OkCheckDocExistsResult>;+ kind: 'doc' | 'folder';+ path: string;+ }): Promise<OkCheckTargetExistsResult>;readHeadBranch(projectPath: string): Promise<OkHeadBranchInfo>;fetchBranchInfo(request: {projectPath: string;branch: string;- docPath: string;+ kind: 'doc' | 'folder';+ path: string;}): Promise<BranchInfoResponse | null>;runCheckout(request: { projectPath: string; branch: string }): Promise<CheckoutResponse | null>;awaitBranchSwitched(request: {diff --git a/packages/core/src/schemas/api/share.ts b/packages/core/src/schemas/api/share.tsindex 2407dcf08..a9ebdd5d1 100644--- a/packages/core/src/schemas/api/share.ts+++ b/packages/core/src/schemas/api/share.ts@@ -1,11 +1,20 @@import type { StandardSchemaV1 } from '@standard-schema/spec';import { z } from 'zod';-export const ShareConstructUrlRequestSchema = z- .object({- docPath: z.string().min(1),- })- .loose() satisfies StandardSchemaV1;+export const ShareConstructUrlRequestSchema = z.discriminatedUnion('kind', [+ z+ .object({+ kind: z.literal('doc'),+ docPath: z.string().min(1),+ })+ .loose(),+ z+ .object({+ kind: z.literal('folder'),+ folderPath: z.string(),+ })+ .loose(),+]) satisfies StandardSchemaV1;export type ShareConstructUrlRequest = z.infer<typeof ShareConstructUrlRequestSchema>;export const ShareConstructUrlErrorCodeSchema = z.enum([@@ -22,7 +31,7 @@ export const ShareConstructUrlResponseSchema = z.discriminatedUnion('ok', [.object({ok: z.literal(true),shareUrl: z.string().min(1),- blobUrl: z.string().min(1),+ sharedUrl: z.string().min(1),branch: z.string().min(1),}).loose(),@@ -154,7 +163,7 @@ export function isBranchNotFoundGitError(error: unknown): boolean {}const BranchInfoSharedFields = {- shareFileExists: z.boolean(),+ shareTargetExists: z.boolean(),dirtyConflicts: z.object({conflicts: z.boolean(),diff --git a/packages/core/src/sharing/share-url.test.ts b/packages/core/src/sharing/share-url.test.tsindex e33a7d896..79fdf98df 100644--- a/packages/core/src/sharing/share-url.test.ts+++ b/packages/core/src/sharing/share-url.test.ts@@ -24,21 +24,21 @@ describe('encodeShareUrl', () => {describe('decodeShareUrl', () => {test('round-trips a simple blob URL through encode/decode', () => {- const blobUrl = 'https://github.com/a/b/blob/main/c.md';- const result = decodeShareUrl(encodeShareUrl(blobUrl));- expect(result).toEqual({ version: 1, blobUrl });+ const sharedUrl = 'https://github.com/a/b/blob/main/c.md';+ const result = decodeShareUrl(encodeShareUrl(sharedUrl));+ expect(result).toEqual({ version: 1, sharedUrl });});test('round-trips a long real-world GitHub blob URL with deep path', () => {- const blobUrl =+ const sharedUrl ='https://github.com/inkeep/open-knowledge/blob/feat%2Fsharing-virality-flow/packages/core/src/sharing/share-url.ts';- expect(decodeShareUrl(encodeShareUrl(blobUrl))).toEqual({ version: 1, blobUrl });+ expect(decodeShareUrl(encodeShareUrl(sharedUrl))).toEqual({ version: 1, sharedUrl });});test('round-trips a URL with unicode and spaces in the path', () => {- const blobUrl =+ const sharedUrl ='https://github.com/inkeep/playbooks/blob/main/docs/Q4%20OKRs%20%E2%80%94%20Marketing.md';- expect(decodeShareUrl(encodeShareUrl(blobUrl))).toEqual({ version: 1, blobUrl });+ expect(decodeShareUrl(encodeShareUrl(sharedUrl))).toEqual({ version: 1, sharedUrl });});test('throws UnsupportedShareVersionError when the version byte is not 0x01', () => {@@ -79,24 +79,24 @@ describe('decodeShareUrl', () => {});test('ignores arbitrary query parameters appended to the encoded payload (Axis 1)', () => {- const blobUrl = 'https://github.com/a/b/blob/main/c.md';- const encoded = encodeShareUrl(blobUrl);+ const sharedUrl = 'https://github.com/a/b/blob/main/c.md';+ const encoded = encodeShareUrl(sharedUrl);expect(decodeShareUrl(`${encoded}?utm_source=slack&ref=campaign`)).toEqual({version: 1,- blobUrl,+ sharedUrl,});});test('ignores an arbitrary fragment appended to the encoded payload (Axis 2)', () => {- const blobUrl = 'https://github.com/a/b/blob/main/c.md';- const encoded = encodeShareUrl(blobUrl);- expect(decodeShareUrl(`${encoded}#section-2`)).toEqual({ version: 1, blobUrl });+ const sharedUrl = 'https://github.com/a/b/blob/main/c.md';+ const encoded = encodeShareUrl(sharedUrl);+ expect(decodeShareUrl(`${encoded}#section-2`)).toEqual({ version: 1, sharedUrl });});test('ignores both query parameters and a fragment appended together', () => {- const blobUrl = 'https://github.com/a/b/blob/main/c.md';- const encoded = encodeShareUrl(blobUrl);- expect(decodeShareUrl(`${encoded}?utm=x#frag`)).toEqual({ version: 1, blobUrl });+ const sharedUrl = 'https://github.com/a/b/blob/main/c.md';+ const encoded = encodeShareUrl(sharedUrl);+ expect(decodeShareUrl(`${encoded}?utm=x#frag`)).toEqual({ version: 1, sharedUrl });});});diff --git a/packages/core/src/sharing/share-url.ts b/packages/core/src/sharing/share-url.tsindex 592679575..e062ca441 100644--- a/packages/core/src/sharing/share-url.ts+++ b/packages/core/src/sharing/share-url.ts@@ -2,7 +2,7 @@ const SHARE_URL_VERSION_V1 = 0x01;export interface DecodedShare {version: number;- blobUrl: string;+ sharedUrl: string;}export class UnsupportedShareVersionError extends Error {@@ -21,8 +21,8 @@ export class InvalidShareUrlError extends Error {}}-export function encodeShareUrl(blobUrl: string): string {- const blobBytes = new TextEncoder().encode(blobUrl);+export function encodeShareUrl(sharedUrl: string): string {+ const blobBytes = new TextEncoder().encode(sharedUrl);const bytes = new Uint8Array(1 + blobBytes.length);bytes[0] = SHARE_URL_VERSION_V1;bytes.set(blobBytes, 1);@@ -52,14 +52,14 @@ export function decodeShareUrl(encoded: string): DecodedShare {}const decoder = new TextDecoder('utf-8', { fatal: true });- let blobUrl: string;+ let sharedUrl: string;try {- blobUrl = decoder.decode(bytes.subarray(1));+ sharedUrl = decoder.decode(bytes.subarray(1));} catch {throw new InvalidShareUrlError('Share payload body is not valid UTF-8');}- return { version, blobUrl };+ return { version, sharedUrl };}function uint8ArrayToBase64Url(bytes: Uint8Array): string {diff --git a/packages/desktop/src/main/branch-info-proxy.test.ts b/packages/desktop/src/main/branch-info-proxy.test.tsindex 412b8394a..a520c2f98 100644--- a/packages/desktop/src/main/branch-info-proxy.test.ts+++ b/packages/desktop/src/main/branch-info-proxy.test.ts@@ -36,7 +36,7 @@ const validBranchInfo: BranchInfoResponse = {currentBranch: 'main',currentHeadSha: null,detached: false,- shareFileExists: true,+ shareTargetExists: true,dirtyConflicts: { conflicts: false, files: [] },branchIsLocal: true,};@@ -97,12 +97,63 @@ describe('proxyFetchBranchInfo', () => {});}) as typeof fetch;const result = await proxyFetchBranchInfo(- { projectPath: '/tmp/p', branch: 'feat/foo', docPath: 'docs/foo.md' },+ { projectPath: '/tmp/p', branch: 'feat/foo', kind: 'doc', path: 'docs/foo.md' },buildDeps({ fetch: fetchMock }),);expect(result).toEqual(validBranchInfo);});+ test('forwards kind=doc into the server query', async () => {+ let seenUrl = '';+ const fetchMock: typeof fetch = (async (input) => {+ seenUrl = String(input);+ return new Response(JSON.stringify(validBranchInfo), {+ status: 200,+ headers: { 'content-type': 'application/json' },+ });+ }) as typeof fetch;+ await proxyFetchBranchInfo(+ { projectPath: '/tmp/p', branch: 'main', kind: 'doc', path: 'docs/foo.md' },+ buildDeps({ fetch: fetchMock }),+ );+ expect(seenUrl).toMatch(/[?&]kind=doc(&|$)/);+ expect(seenUrl).toMatch(/path=docs%2Ffoo\.md/);+ });++ test('forwards kind=folder into the server query', async () => {+ let seenUrl = '';+ const fetchMock: typeof fetch = (async (input) => {+ seenUrl = String(input);+ return new Response(JSON.stringify(validBranchInfo), {+ status: 200,+ headers: { 'content-type': 'application/json' },+ });+ }) as typeof fetch;+ await proxyFetchBranchInfo(+ { projectPath: '/tmp/p', branch: 'main', kind: 'folder', path: 'docs/guides' },+ buildDeps({ fetch: fetchMock }),+ );+ expect(seenUrl).toMatch(/[?&]kind=folder(&|$)/);+ expect(seenUrl).toMatch(/path=docs%2Fguides/);+ });++ test('forwards kind=folder with an empty path for a content-root folder share', async () => {+ let seenUrl = '';+ const fetchMock: typeof fetch = (async (input) => {+ seenUrl = String(input);+ return new Response(JSON.stringify(validBranchInfo), {+ status: 200,+ headers: { 'content-type': 'application/json' },+ });+ }) as typeof fetch;+ await proxyFetchBranchInfo(+ { projectPath: '/tmp/p', branch: 'main', kind: 'folder', path: '' },+ buildDeps({ fetch: fetchMock }),+ );+ expect(seenUrl).toMatch(/[?&]kind=folder(&|$)/);+ expect(seenUrl).toMatch(/[?&]path=(&|$)/);+ });+test('sends client version headers (kind=desktop-main) on the branch-info GET', async () => {let seen: RequestInit | undefined;const fetchMock: typeof fetch = (async (_input, init) => {@@ -113,7 +164,7 @@ describe('proxyFetchBranchInfo', () => {});}) as typeof fetch;await proxyFetchBranchInfo(- { projectPath: '/tmp/p', branch: 'main', docPath: 'a.md' },+ { projectPath: '/tmp/p', branch: 'main', kind: 'doc', path: 'a.md' },buildDeps({ fetch: fetchMock }),);expect(headerOf(seen, 'x-ok-client-protocol')).toBe('1');@@ -123,7 +174,7 @@ describe('proxyFetchBranchInfo', () => {test('returns null when the server returns non-2xx', async () => {const result = await proxyFetchBranchInfo(- { projectPath: '/tmp/p', branch: 'main', docPath: 'a.md' },+ { projectPath: '/tmp/p', branch: 'main', kind: 'doc', path: 'a.md' },buildDeps({ fetch: (async () => new Response(null, { status: 500 })) as typeof fetch }),);expect(result).toBeNull();@@ -136,7 +187,7 @@ describe('proxyFetchBranchInfo', () => {headers: { 'content-type': 'application/json' },})) as typeof fetch;const result = await proxyFetchBranchInfo(- { projectPath: '/tmp/p', branch: 'main', docPath: 'a.md' },+ { projectPath: '/tmp/p', branch: 'main', kind: 'doc', path: 'a.md' },buildDeps({ fetch: fetchMock }),);expect(result).toBeNull();@@ -144,7 +195,7 @@ describe('proxyFetchBranchInfo', () => {test('returns null when the server lock never resolves', async () => {const result = await proxyFetchBranchInfo(- { projectPath: '/tmp/p', branch: 'main', docPath: 'a.md' },+ { projectPath: '/tmp/p', branch: 'main', kind: 'doc', path: 'a.md' },buildDeps({ readServerLock: () => null }),);expect(result).toBeNull();@@ -152,7 +203,7 @@ describe('proxyFetchBranchInfo', () => {test('returns null when fetch throws (network error / timeout)', async () => {const result = await proxyFetchBranchInfo(- { projectPath: '/tmp/p', branch: 'main', docPath: 'a.md' },+ { projectPath: '/tmp/p', branch: 'main', kind: 'doc', path: 'a.md' },buildDeps({fetch: (async () => {throw new Error('boom');@@ -351,7 +402,7 @@ describe('AbortSignal cancellation', () => {controller.abort();let fetchCalls = 0;const result = await proxyFetchBranchInfo(- { projectPath: '/tmp/p', branch: 'main', docPath: 'a.md' },+ { projectPath: '/tmp/p', branch: 'main', kind: 'doc', path: 'a.md' },buildDeps({fetch: (async () => {fetchCalls += 1;@@ -411,7 +462,7 @@ describe('AbortSignal cancellation', () => {headers: { 'content-type': 'application/json' },})) as typeof fetch;const result = await proxyFetchBranchInfo(- { projectPath: '/tmp/p', branch: 'main', docPath: 'a.md' },+ { projectPath: '/tmp/p', branch: 'main', kind: 'doc', path: 'a.md' },buildDeps({ fetch: fetchMock }),);expect(result).toEqual(validBranchInfo);diff --git a/packages/desktop/src/main/branch-info-proxy.ts b/packages/desktop/src/main/branch-info-proxy.tsindex be70ae5d7..c65523474 100644--- a/packages/desktop/src/main/branch-info-proxy.ts+++ b/packages/desktop/src/main/branch-info-proxy.ts@@ -63,14 +63,18 @@ function composeFetchSignal(timeoutMs: number, signal?: AbortSignal): AbortSigna}export async function proxyFetchBranchInfo(- request: { projectPath: string; branch: string; docPath: string },+ request: { projectPath: string; branch: string; kind: 'doc' | 'folder'; path: string },deps: BranchInfoProxyDeps,signal?: AbortSignal,): Promise<BranchInfoResponse | null> {const origin = await resolveProjectServerOrigin(request.projectPath, deps, signal);if (origin === null) return null;if (signal?.aborted) return null;- const params = new URLSearchParams({ branch: request.branch, path: request.docPath });+ const params = new URLSearchParams({+ branch: request.branch,+ kind: request.kind,+ path: request.path,+ });const url = `${origin}/api/git/branch-info?${params.toString()}`;const timeoutMs = deps.requestTimeoutMs ?? 5_000;let raw: unknown;diff --git a/packages/desktop/src/main/check-doc-exists.test.ts b/packages/desktop/src/main/check-doc-exists.test.tsdeleted file mode 100644index cab86a591..000000000--- a/packages/desktop/src/main/check-doc-exists.test.ts+++ /dev/null@@ -1,168 +0,0 @@-import { describe, expect, test } from 'bun:test';-import { chmodSync, mkdirSync, mkdtempSync, rmSync, symlinkSync, writeFileSync } from 'node:fs';-import { tmpdir } from 'node:os';-import { join } from 'node:path';--import { checkDocExists } from './check-doc-exists.ts';--describe('checkDocExists', () => {- function makeProject(): string {- return mkdtempSync(join(tmpdir(), 'ok-check-doc-exists-'));- }-- function cleanup(path: string): void {- rmSync(path, { recursive: true, force: true });- }-- test('returns exists for a regular file at a simple path', () => {- const project = makeProject();- try {- writeFileSync(join(project, 'README.md'), '# hi\n');- expect(checkDocExists(project, 'README.md')).toEqual('exists');- } finally {- cleanup(project);- }- });-- test('returns exists for a nested file via slashed path', () => {- const project = makeProject();- try {- mkdirSync(join(project, 'docs', 'guides'), { recursive: true });- writeFileSync(join(project, 'docs', 'guides', 'intro.md'), 'body\n');- expect(checkDocExists(project, 'docs/guides/intro.md')).toEqual('exists');- } finally {- cleanup(project);- }- });-- test('returns missing when the file does not exist (ENOENT)', () => {- const project = makeProject();- try {- expect(checkDocExists(project, 'README.md')).toEqual('missing');- } finally {- cleanup(project);- }- });-- test('returns missing when the path resolves to a directory', () => {- const project = makeProject();- try {- mkdirSync(join(project, 'docs'), { recursive: true });- expect(checkDocExists(project, 'docs')).toEqual('missing');- } finally {- cleanup(project);- }- });-- test('follows symlinks to a real file (returns exists)', () => {- const project = makeProject();- try {- writeFileSync(join(project, 'real.md'), '# real\n');- symlinkSync(join(project, 'real.md'), join(project, 'link.md'));- expect(checkDocExists(project, 'link.md')).toEqual('exists');- } finally {- cleanup(project);- }- });-- test('returns unreadable for non-absolute projectPath', () => {- expect(checkDocExists('relative/path', 'README.md')).toEqual('unreadable');- });-- test('returns unreadable for empty projectPath', () => {- expect(checkDocExists('', 'README.md')).toEqual('unreadable');- });-- test('returns unreadable for projectPath containing a NUL byte', () => {- expect(checkDocExists('/tmp/a\0b', 'README.md')).toEqual('unreadable');- });-- test('returns unreadable for projectPath that resolves to a different path (`..` escape)', () => {- expect(checkDocExists('/tmp/../etc', 'passwd')).toEqual('unreadable');- });-- test('returns unreadable for empty docPath', () => {- const project = makeProject();- try {- expect(checkDocExists(project, '')).toEqual('unreadable');- } finally {- cleanup(project);- }- });-- test('returns unreadable for absolute docPath', () => {- const project = makeProject();- try {- writeFileSync(join(project, 'README.md'), '# hi\n');- expect(checkDocExists(project, join(project, 'README.md'))).toEqual('unreadable');- } finally {- cleanup(project);- }- });-- test('returns unreadable for docPath with a NUL byte', () => {- const project = makeProject();- try {- expect(checkDocExists(project, 'a\0b.md')).toEqual('unreadable');- } finally {- cleanup(project);- }- });-- test('returns unreadable for docPath containing a `..` segment', () => {- const project = makeProject();- try {- writeFileSync(join(project, 'README.md'), '# hi\n');- expect(checkDocExists(project, 'docs/../README.md')).toEqual('unreadable');- } finally {- cleanup(project);- }- });-- test('returns unreadable for docPath that escapes the project root (`../`)', () => {- const project = makeProject();- try {- expect(checkDocExists(project, '../escape.md')).toEqual('unreadable');- } finally {- cleanup(project);- }- });-- test('does not confuse sibling-directory prefix matches with containment', () => {- const parent = mkdtempSync(join(tmpdir(), 'ok-check-doc-exists-parent-'));- try {- const project = join(parent, 'proj');- const sibling = join(parent, 'proj-evil');- mkdirSync(project);- mkdirSync(sibling);- writeFileSync(join(sibling, 'file.md'), 'no\n');- expect(checkDocExists(project, '../proj-evil/file.md')).toEqual('unreadable');- } finally {- cleanup(parent);- }- });-- test('returns missing when projectPath itself does not exist', () => {- expect(- checkDocExists('/tmp/definitely-does-not-exist-ok-test-12345/proj', 'README.md'),- ).toEqual('missing');- });-- test('handles unreadable directory (EACCES) as unreadable, not missing', () => {- if (process.platform === 'win32' || process.getuid?.() === 0) return;- const project = makeProject();- try {- mkdirSync(join(project, 'locked'), { recursive: true });- writeFileSync(join(project, 'locked', 'file.md'), '# hi\n');- chmodSync(join(project, 'locked'), 0o000);- try {- const result = checkDocExists(project, 'locked/file.md');- expect(result).not.toEqual('missing');- } finally {- chmodSync(join(project, 'locked'), 0o755);- }- } finally {- cleanup(project);- }- });-});diff --git a/packages/desktop/src/main/check-target-exists.test.ts b/packages/desktop/src/main/check-target-exists.test.tsnew file mode 100644index 000000000..ec75dcc34--- /dev/null+++ b/packages/desktop/src/main/check-target-exists.test.ts@@ -0,0 +1,235 @@+import { describe, expect, test } from 'bun:test';+import { chmodSync, mkdirSync, mkdtempSync, rmSync, symlinkSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';++import { checkTargetExists } from './check-target-exists.ts';++describe('checkTargetExists', () => {+ function makeProject(): string {+ return mkdtempSync(join(tmpdir(), 'ok-check-target-exists-'));+ }++ function cleanup(path: string): void {+ rmSync(path, { recursive: true, force: true });+ }++ describe('doc kind', () => {+ test('returns exists for a regular file at a simple path', () => {+ const project = makeProject();+ try {+ writeFileSync(join(project, 'README.md'), '# hi\n');+ expect(checkTargetExists(project, 'doc', 'README.md')).toEqual('exists');+ } finally {+ cleanup(project);+ }+ });++ test('returns exists for a nested file via slashed path', () => {+ const project = makeProject();+ try {+ mkdirSync(join(project, 'docs', 'guides'), { recursive: true });+ writeFileSync(join(project, 'docs', 'guides', 'intro.md'), 'body\n');+ expect(checkTargetExists(project, 'doc', 'docs/guides/intro.md')).toEqual('exists');+ } finally {+ cleanup(project);+ }+ });++ test('returns missing when the file does not exist (ENOENT)', () => {+ const project = makeProject();+ try {+ expect(checkTargetExists(project, 'doc', 'README.md')).toEqual('missing');+ } finally {+ cleanup(project);+ }+ });++ test('returns missing when a doc path resolves to a directory', () => {+ const project = makeProject();+ try {+ mkdirSync(join(project, 'docs'), { recursive: true });+ expect(checkTargetExists(project, 'doc', 'docs')).toEqual('missing');+ } finally {+ cleanup(project);+ }+ });++ test('follows symlinks to a real file (returns exists)', () => {+ const project = makeProject();+ try {+ writeFileSync(join(project, 'real.md'), '# real\n');+ symlinkSync(join(project, 'real.md'), join(project, 'link.md'));+ expect(checkTargetExists(project, 'doc', 'link.md')).toEqual('exists');+ } finally {+ cleanup(project);+ }+ });+ });++ describe('folder kind', () => {+ test('returns exists for a directory at a simple path', () => {+ const project = makeProject();+ try {+ mkdirSync(join(project, 'docs'), { recursive: true });+ expect(checkTargetExists(project, 'folder', 'docs')).toEqual('exists');+ } finally {+ cleanup(project);+ }+ });++ test('returns exists for a nested directory via slashed path', () => {+ const project = makeProject();+ try {+ mkdirSync(join(project, 'docs', 'guides'), { recursive: true });+ expect(checkTargetExists(project, 'folder', 'docs/guides')).toEqual('exists');+ } finally {+ cleanup(project);+ }+ });++ test('returns missing when the directory does not exist (ENOENT)', () => {+ const project = makeProject();+ try {+ expect(checkTargetExists(project, 'folder', 'docs')).toEqual('missing');+ } finally {+ cleanup(project);+ }+ });++ test('returns missing when a folder path resolves to a regular file', () => {+ const project = makeProject();+ try {+ writeFileSync(join(project, 'README.md'), '# hi\n');+ expect(checkTargetExists(project, 'folder', 'README.md')).toEqual('missing');+ } finally {+ cleanup(project);+ }+ });++ test('follows symlinks to a real directory (returns exists)', () => {+ const project = makeProject();+ try {+ mkdirSync(join(project, 'real-dir'), { recursive: true });+ symlinkSync(join(project, 'real-dir'), join(project, 'link-dir'));+ expect(checkTargetExists(project, 'folder', 'link-dir')).toEqual('exists');+ } finally {+ cleanup(project);+ }+ });+ });++ describe('path-shape gate (kind-agnostic)', () => {+ test('returns unreadable for non-absolute projectPath', () => {+ expect(checkTargetExists('relative/path', 'doc', 'README.md')).toEqual('unreadable');+ });++ test('returns unreadable for empty projectPath', () => {+ expect(checkTargetExists('', 'doc', 'README.md')).toEqual('unreadable');+ });++ test('returns unreadable for projectPath containing a NUL byte', () => {+ expect(checkTargetExists('/tmp/a\0b', 'doc', 'README.md')).toEqual('unreadable');+ });++ test('returns unreadable for projectPath that resolves to a different path (`..` escape)', () => {+ expect(checkTargetExists('/tmp/../etc', 'doc', 'passwd')).toEqual('unreadable');+ });++ test('returns unreadable for empty path (doc kind)', () => {+ const project = makeProject();+ try {+ expect(checkTargetExists(project, 'doc', '')).toEqual('unreadable');+ } finally {+ cleanup(project);+ }+ });++ test('returns unreadable for empty path (folder kind) — content-root is skipped upstream', () => {+ const project = makeProject();+ try {+ expect(checkTargetExists(project, 'folder', '')).toEqual('unreadable');+ } finally {+ cleanup(project);+ }+ });++ test('returns unreadable for absolute path', () => {+ const project = makeProject();+ try {+ writeFileSync(join(project, 'README.md'), '# hi\n');+ expect(checkTargetExists(project, 'doc', join(project, 'README.md'))).toEqual('unreadable');+ } finally {+ cleanup(project);+ }+ });++ test('returns unreadable for path with a NUL byte', () => {+ const project = makeProject();+ try {+ expect(checkTargetExists(project, 'doc', 'a\0b.md')).toEqual('unreadable');+ } finally {+ cleanup(project);+ }+ });++ test('returns unreadable for path containing a `..` segment', () => {+ const project = makeProject();+ try {+ writeFileSync(join(project, 'README.md'), '# hi\n');+ expect(checkTargetExists(project, 'doc', 'docs/../README.md')).toEqual('unreadable');+ } finally {+ cleanup(project);+ }+ });++ test('returns unreadable for path that escapes the project root (`../`)', () => {+ const project = makeProject();+ try {+ expect(checkTargetExists(project, 'doc', '../escape.md')).toEqual('unreadable');+ } finally {+ cleanup(project);+ }+ });++ test('does not confuse sibling-directory prefix matches with containment', () => {+ const parent = mkdtempSync(join(tmpdir(), 'ok-check-target-exists-parent-'));+ try {+ const project = join(parent, 'proj');+ const sibling = join(parent, 'proj-evil');+ mkdirSync(project);+ mkdirSync(sibling);+ writeFileSync(join(sibling, 'file.md'), 'no\n');+ expect(checkTargetExists(project, 'doc', '../proj-evil/file.md')).toEqual('unreadable');+ } finally {+ cleanup(parent);+ }+ });+ });++ describe('graceful-fail (kind-agnostic)', () => {+ test('returns missing when projectPath itself does not exist', () => {+ expect(+ checkTargetExists('/tmp/definitely-does-not-exist-ok-test-12345/proj', 'doc', 'README.md'),+ ).toEqual('missing');+ });++ test('handles unreadable directory (EACCES) as unreadable, not missing', () => {+ if (process.platform === 'win32' || process.getuid?.() === 0) return;+ const project = makeProject();+ try {+ mkdirSync(join(project, 'locked'), { recursive: true });+ writeFileSync(join(project, 'locked', 'file.md'), '# hi\n');+ chmodSync(join(project, 'locked'), 0o000);+ try {+ const result = checkTargetExists(project, 'doc', 'locked/file.md');+ expect(result).not.toEqual('missing');+ } finally {+ chmodSync(join(project, 'locked'), 0o755);+ }+ } finally {+ cleanup(project);+ }+ });+ });+});diff --git a/packages/desktop/src/main/check-doc-exists.ts b/packages/desktop/src/main/check-target-exists.tssimilarity index 52%rename from packages/desktop/src/main/check-doc-exists.tsrename to packages/desktop/src/main/check-target-exists.tsindex fb3328854..af63af305 100644--- a/packages/desktop/src/main/check-doc-exists.ts+++ b/packages/desktop/src/main/check-target-exists.ts@@ -1,7 +1,7 @@import { statSync } from 'node:fs';import { isAbsolute, join, resolve, sep } from 'node:path';-export type CheckDocExistsResult = 'exists' | 'missing' | 'unreadable';+export type CheckTargetExistsResult = 'exists' | 'missing' | 'unreadable';function isSafeProjectPath(projectPath: string): boolean {if (typeof projectPath !== 'string') return false;@@ -12,18 +12,20 @@ function isSafeProjectPath(projectPath: string): boolean {return true;}-function isSafeDocPath(docPath: string): boolean {- if (typeof docPath !== 'string') return false;- if (docPath.length === 0) return false;- if (docPath.includes('\0')) return false;- if (isAbsolute(docPath)) return false;- const segments = docPath.split(/[/\\]+/);- if (segments.some((s) => s === '..')) return false;+function isSafeTargetPath(path: string): boolean {+ if (typeof path !== 'string') return false;+ if (path.length === 0) return false;+ if (isAbsolute(path)) return false;+ if (path.includes('\\')) return false;+ // biome-ignore lint/suspicious/noControlCharactersInRegex: control chars are exactly what we want to reject+ if (/[\x00-\x1F\x7F]/.test(path)) return false;+ const segments = path.split('/');+ if (segments.some((s) => s === '' || s === '..' || s === '.git')) return false;return true;}-function joinContained(projectPath: string, docPath: string): string | null {- const joined = resolve(join(projectPath, docPath));+function joinContained(projectPath: string, path: string): string | null {+ const joined = resolve(join(projectPath, path));const projectResolved = resolve(projectPath);const projectWithSep = projectResolved.endsWith(sep) ? projectResolved : projectResolved + sep;if (joined === projectResolved) return joined;@@ -31,10 +33,14 @@ function joinContained(projectPath: string, docPath: string): string | null {return joined;}-export function checkDocExists(projectPath: string, docPath: string): CheckDocExistsResult {+export function checkTargetExists(+ projectPath: string,+ kind: 'doc' | 'folder',+ path: string,+): CheckTargetExistsResult {if (!isSafeProjectPath(projectPath)) return 'unreadable';- if (!isSafeDocPath(docPath)) return 'unreadable';- const fullPath = joinContained(projectPath, docPath);+ if (!isSafeTargetPath(path)) return 'unreadable';+ const fullPath = joinContained(projectPath, path);if (fullPath === null) return 'unreadable';let stat: ReturnType<typeof statSync>;try {@@ -50,6 +56,7 @@ export function checkDocExists(projectPath: string, docPath: string): CheckDocEx}return 'unreadable';}- if (!stat.isFile()) return 'missing';+ const matches = kind === 'folder' ? stat.isDirectory() : stat.isFile();+ if (!matches) return 'missing';return 'exists';}diff --git a/packages/desktop/src/main/index.ts b/packages/desktop/src/main/index.tsindex d88442d70..ae42e2298 100644--- a/packages/desktop/src/main/index.ts+++ b/packages/desktop/src/main/index.ts@@ -102,7 +102,7 @@ import {type BundleReplaceWatcherHandle,startBundleReplaceWatcher,} from './bundle-replace-detector.ts';-import { checkDocExists as checkDocExistsImpl } from './check-doc-exists.ts';+import { checkTargetExists as checkTargetExistsImpl } from './check-target-exists.ts';import { requestUserConsent, walkExceedsCap } from './consent-dialog.ts';import {CreateNewProjectError,@@ -642,16 +642,17 @@ const BOOT_BUDGET_FILE_CAP = 10_000;async function openProject(projectPath: string,entryPoint: EntryPoint,- pendingDeepLinkDoc?: string,+ pendingDeepLinkTarget?: { kind: 'doc' | 'folder'; path: string },pendingBranch?: string | null,pendingMultiCandidate?: boolean,pendingShareBranchSwitch?: ShareDeepLinkBranchSwitchPayload,+ pendingTargetMissing?: boolean,) {getLogger('project').info({projectName: basename(projectPath),entryPoint,- hasDeepLinkDoc: !!pendingDeepLinkDoc,+ hasDeepLinkTarget: !!pendingDeepLinkTarget,hasPendingBranch: !!pendingBranch,},'opening project',@@ -889,9 +890,10 @@ async function openProject(const ctx = await wm.createProjectWindow({projectPath: resolvedProjectDir,- pendingDeepLinkDoc,+ pendingDeepLinkTarget,pendingBranch,pendingMultiCandidate,+ pendingTargetMissing,pendingShareBranchSwitch,didEnsureGit,consentVersion: 1,@@ -939,19 +941,21 @@ async function openProject(async function openProjectOrFallbackToNavigator(projectPath: string,entryPoint: EntryPoint,- pendingDeepLinkDoc?: string,+ pendingDeepLinkTarget?: { kind: 'doc' | 'folder'; path: string },pendingBranch?: string | null,pendingMultiCandidate?: boolean,pendingShareBranchSwitch?: ShareDeepLinkBranchSwitchPayload,+ pendingTargetMissing?: boolean,) {try {await openProject(projectPath,entryPoint,- pendingDeepLinkDoc,+ pendingDeepLinkTarget,pendingBranch,pendingMultiCandidate,pendingShareBranchSwitch,+ pendingTargetMissing,);} catch (err) {const errorMessage = (err as Error).message;@@ -1653,13 +1657,14 @@ function registerIpcHandlers() {`ok:project:open rejected: invalid entryPoint '${String(request.entryPoint)}'`,);}- if (request.pendingDeepLinkDoc !== undefined && wm) {+ if (request.pendingDeepLinkTarget !== undefined && wm) {const existing = wm.focusWindowForProject(request.path) as| (BrowserWindowLike & { webContents: BrowserWindowLike['webContents'] })| null;if (existing) {sendToRenderer(existing.webContents, 'ok:deep-link', {- doc: request.pendingDeepLinkDoc,+ doc: request.pendingDeepLinkTarget.path,+ kind: request.pendingDeepLinkTarget.kind,branch: request.pendingBranch ?? null,multiCandidate: request.pendingMultiCandidate === true,});@@ -1669,7 +1674,7 @@ function registerIpcHandlers() {await openProjectOrFallbackToNavigator(request.path,request.entryPoint,- request.pendingDeepLinkDoc,+ request.pendingDeepLinkTarget,request.pendingBranch,request.pendingMultiCandidate,);@@ -1683,8 +1688,8 @@ function registerIpcHandlers() {});});- handle('ok:project:check-doc-exists', async (_event, request) => {- return checkDocExistsImpl(request.projectPath, request.docPath);+ handle('ok:project:check-target-exists', async (_event, request) => {+ return checkTargetExistsImpl(request.projectPath, request.kind, request.path);});handle('ok:project:read-head-branch', async (_event, projectPath) => {@@ -2117,10 +2122,11 @@ function bootPrimaryInstance(): void {await openProjectOrFallbackToNavigator(projectPath,'deep-link',- opts?.pendingDeepLinkDoc,+ opts?.pendingDeepLinkTarget,opts?.pendingBranch,opts?.pendingMultiCandidate,opts?.pendingShareBranchSwitch,+ opts?.pendingTargetMissing,);const ctx = wm?.getWindowFor(projectPath);if (!ctx) {@@ -2140,6 +2146,8 @@ function bootPrimaryInstance(): void {resolveShareTargetMain(share, {listRecent: () => annotateMissing(appState),}),+ checkShareTargetExists: (projectPath, kind, path) =>+ checkTargetExistsImpl(projectPath, kind, path),routeShareToNavigator: (payload) => {openNavigator(payload);},diff --git a/packages/desktop/src/main/url-scheme.test.ts b/packages/desktop/src/main/url-scheme.test.tsindex cdf6d8e4d..32b6d4566 100644--- a/packages/desktop/src/main/url-scheme.test.ts+++ b/packages/desktop/src/main/url-scheme.test.ts@@ -211,8 +211,8 @@ describe('parseShareUrl — universal-link happy path', () => {owner: 'inkeep',repo: 'playbooks',branch: 'main',- path: 'marketing.md',- blobUrl: 'https://github.com/inkeep/playbooks/blob/main/marketing.md',+ sharedUrl: 'https://github.com/inkeep/playbooks/blob/main/marketing.md',+ target: { kind: 'doc', docPath: 'marketing.md' },},});});@@ -229,18 +229,18 @@ describe('parseShareUrl — universal-link happy path', () => {const result = parseShareUrl(`https://openknowledge.ai/d/${encoded}`);expect(result).toMatchObject({kind: 'ok',- payload: { branch: 'feat/foo', path: 'docs/sub/page.md' },+ payload: { branch: 'feat/foo', target: { kind: 'doc', docPath: 'docs/sub/page.md' } },});});test('parses universal-link with unicode + spaces in path (per-segment encoded)', () => {- const blobUrl =+ const sharedUrl ='https://github.com/inkeep/playbooks/blob/main/docs/Q4%20OKRs%20%E2%80%94%20Marketing.md';- const encoded = encodeShareUrl(blobUrl);+ const encoded = encodeShareUrl(sharedUrl);const result = parseShareUrl(`https://openknowledge.ai/d/${encoded}`);expect(result).toMatchObject({kind: 'ok',- payload: { path: 'docs/Q4 OKRs — Marketing.md' },+ payload: { target: { kind: 'doc', docPath: 'docs/Q4 OKRs — Marketing.md' } },});});});@@ -302,10 +302,19 @@ describe('parseShareUrl — universal-link error states', () => {expect(result).toEqual({ kind: 'invalid', source: 'universal-link' });});- test('reports invalid for github URL that is not a /blob/ URL', () => {+ test('parses a github /tree/ URL as a folder target', () => {const encoded = encodeShareUrl('https://github.com/inkeep/playbooks/tree/main/docs');const result = parseShareUrl(`https://openknowledge.ai/d/${encoded}`);- expect(result).toEqual({ kind: 'invalid', source: 'universal-link' });+ expect(result).toMatchObject({+ kind: 'ok',+ source: 'universal-link',+ payload: {+ owner: 'inkeep',+ repo: 'playbooks',+ branch: 'main',+ target: { kind: 'folder', folderPath: 'docs' },+ },+ });});test('reports invalid for extra path segments after /d/<encoded>', () => {@@ -317,8 +326,8 @@ describe('parseShareUrl — universal-link error states', () => {describe('parseShareUrl — custom-scheme happy path', () => {test('parses openknowledge://share?url=<blob-url>', () => {- const blobUrl = 'https://github.com/inkeep/playbooks/blob/main/marketing.md';- const result = parseShareUrl(`openknowledge://share?url=${encodeURIComponent(blobUrl)}`);+ const sharedUrl = 'https://github.com/inkeep/playbooks/blob/main/marketing.md';+ const result = parseShareUrl(`openknowledge://share?url=${encodeURIComponent(sharedUrl)}`);expect(result).toEqual({kind: 'ok',source: 'custom-scheme',@@ -326,26 +335,26 @@ describe('parseShareUrl — custom-scheme happy path', () => {owner: 'inkeep',repo: 'playbooks',branch: 'main',- path: 'marketing.md',- blobUrl,+ sharedUrl,+ target: { kind: 'doc', docPath: 'marketing.md' },},});});test('parses custom-scheme with percent-encoded slash in branch', () => {- const blobUrl = 'https://github.com/o/r/blob/feat%2Ffoo/docs/page.md';- const result = parseShareUrl(`openknowledge://share?url=${encodeURIComponent(blobUrl)}`);+ const sharedUrl = 'https://github.com/o/r/blob/feat%2Ffoo/docs/page.md';+ const result = parseShareUrl(`openknowledge://share?url=${encodeURIComponent(sharedUrl)}`);expect(result).toMatchObject({kind: 'ok',source: 'custom-scheme',- payload: { branch: 'feat/foo', path: 'docs/page.md' },+ payload: { branch: 'feat/foo', target: { kind: 'doc', docPath: 'docs/page.md' } },});});test('tolerates additional query params on custom-scheme path', () => {- const blobUrl = 'https://github.com/o/r/blob/main/x.md';+ const sharedUrl = 'https://github.com/o/r/blob/main/x.md';const result = parseShareUrl(- `openknowledge://share?url=${encodeURIComponent(blobUrl)}&ref=campaign`,+ `openknowledge://share?url=${encodeURIComponent(sharedUrl)}&ref=campaign`,);expect(result?.kind).toBe('ok');expect(result?.source).toBe('custom-scheme');@@ -364,16 +373,46 @@ describe('parseShareUrl — custom-scheme error states', () => {});test('reports invalid for non-github URL', () => {- const blobUrl = 'https://gitlab.com/o/r/-/blob/main/x.md';- const result = parseShareUrl(`openknowledge://share?url=${encodeURIComponent(blobUrl)}`);+ const sharedUrl = 'https://gitlab.com/o/r/-/blob/main/x.md';+ const result = parseShareUrl(`openknowledge://share?url=${encodeURIComponent(sharedUrl)}`);expect(result).toEqual({ kind: 'invalid', source: 'custom-scheme' });});- test('reports invalid for github non-/blob/ URL', () => {- const blobUrl = 'https://github.com/o/r/tree/main/docs';- const result = parseShareUrl(`openknowledge://share?url=${encodeURIComponent(blobUrl)}`);+ test('reports invalid for github URL that is neither a blob nor a tree URL', () => {+ const sharedUrl = 'https://github.com/o/r/pull/123';+ const result = parseShareUrl(`openknowledge://share?url=${encodeURIComponent(sharedUrl)}`);expect(result).toEqual({ kind: 'invalid', source: 'custom-scheme' });});++ test('parses a github /tree/ URL as a folder target (custom-scheme)', () => {+ const sharedUrl = 'https://github.com/o/r/tree/main/docs';+ const result = parseShareUrl(`openknowledge://share?url=${encodeURIComponent(sharedUrl)}`);+ expect(result).toMatchObject({+ kind: 'ok',+ source: 'custom-scheme',+ payload: {+ owner: 'o',+ repo: 'r',+ branch: 'main',+ target: { kind: 'folder', folderPath: 'docs' },+ },+ });+ });++ test('parses a github /tree/ root URL as a folder target with empty folderPath', () => {+ const sharedUrl = 'https://github.com/o/r/tree/main';+ const result = parseShareUrl(`openknowledge://share?url=${encodeURIComponent(sharedUrl)}`);+ expect(result).toMatchObject({+ kind: 'ok',+ source: 'custom-scheme',+ payload: {+ owner: 'o',+ repo: 'r',+ branch: 'main',+ target: { kind: 'folder', folderPath: '' },+ },+ });+ });});describe('parseShareUrl — not-a-share-url (returns null, caller falls through)', () => {diff --git a/packages/desktop/src/main/url-scheme.ts b/packages/desktop/src/main/url-scheme.tsindex 03197aaf4..473264da3 100644--- a/packages/desktop/src/main/url-scheme.ts+++ b/packages/desktop/src/main/url-scheme.ts@@ -1,12 +1,21 @@import { isAbsolute, resolve } from 'node:path';-import { parseGitHubBlobUrl } from '@inkeep/open-knowledge';+import { parseGitHubShareUrl } from '@inkeep/open-knowledge';import {type CandidateSelection,decodeShareUrl,InvalidShareUrlError,UnsupportedShareVersionError,} from '@inkeep/open-knowledge-core';-import type { OkSharePayloadFields, OkShareReceivedPayload } from '../shared/bridge-contract.ts';+import type {+ OkSharePayloadFields,+ OkShareReceivedPayload,+ ShareTarget,+} from '../shared/bridge-contract.ts';+import type { CheckTargetExistsResult } from './check-target-exists.ts';++function shareTargetPath(target: ShareTarget): string {+ return target.kind === 'doc' ? target.docPath : target.folderPath;+}interface ParsedOpenKnowledgeUrl {readonly host: 'open';@@ -25,9 +34,9 @@ function readWebpageURL(source: unknown): string | null {}/** Successful share-URL parse — the routing payload the receive dialog renders- * against. Aliases the canonical `OkSharePayloadFields` (same fields) so the- * parse output and the IPC payload can't drift, matching the `ShareDeepLinkFields`- * alias. */+ * against. Aliases the canonical kind-aware `OkSharePayloadFields` (carries+ * `target: ShareTarget` + `sharedUrl`) so the parse output and the IPC payload+ * can't drift, matching the `ShareDeepLinkFields` alias. */export type ShareUrlPayload = OkSharePayloadFields;export type ShareUrlSource = 'universal-link' | 'custom-scheme';@@ -93,7 +102,7 @@ function parseShareUniversalLink(url: URL): ShareParseResult {if (encoded === undefined || encoded.length === 0) {return { kind: 'invalid', source: 'universal-link' };}- let decoded: { blobUrl: string };+ let decoded: { sharedUrl: string };try {decoded = decodeShareUrl(encoded);} catch (err) {@@ -109,33 +118,37 @@ function parseShareUniversalLink(url: URL): ShareParseResult {}return { kind: 'invalid', source: 'universal-link' };}- return finalizeShareResult(decoded.blobUrl, 'universal-link');+ return finalizeShareResult(decoded.sharedUrl, 'universal-link');}function parseShareCustomScheme(url: URL): ShareParseResult {- const rawBlobUrl = url.searchParams.get('url');- if (!rawBlobUrl) {+ const rawSharedUrl = url.searchParams.get('url');+ if (!rawSharedUrl) {return { kind: 'invalid', source: 'custom-scheme' };}- return finalizeShareResult(rawBlobUrl, 'custom-scheme');+ return finalizeShareResult(rawSharedUrl, 'custom-scheme');}-const MAX_BLOB_URL_LENGTH = 4096;+const MAX_SHARED_URL_LENGTH = 4096;-function finalizeShareResult(blobUrl: string, source: ShareUrlSource): ShareParseResult {- if (typeof blobUrl !== 'string' || blobUrl.length === 0) {+function finalizeShareResult(sharedUrl: string, source: ShareUrlSource): ShareParseResult {+ if (typeof sharedUrl !== 'string' || sharedUrl.length === 0) {return { kind: 'invalid', source };}- if (blobUrl.length > MAX_BLOB_URL_LENGTH) {+ if (sharedUrl.length > MAX_SHARED_URL_LENGTH) {return { kind: 'invalid', source };}- if (blobUrl.includes('\x00')) {+ if (sharedUrl.includes('\x00')) {return { kind: 'invalid', source };}- const parsed = parseGitHubBlobUrl(blobUrl);+ const parsed = parseGitHubShareUrl(sharedUrl);if (parsed === null) {return { kind: 'invalid', source };}+ const target: ShareTarget =+ parsed.kind === 'doc'+ ? { kind: 'doc', docPath: parsed.path }+ : { kind: 'folder', folderPath: parsed.path };return {kind: 'ok',source,@@ -143,8 +156,8 @@ function finalizeShareResult(blobUrl: string, source: ShareUrlSource): ShareParsowner: parsed.owner,repo: parsed.repo,branch: parsed.branch,- path: parsed.path,- blobUrl,+ sharedUrl,+ target,},};}@@ -255,18 +268,30 @@ interface ProtocolHandlerDeps {openProject(projectPath: string,opts?: {- pendingDeepLinkDoc?: string;+ pendingDeepLinkTarget?: { kind: 'doc' | 'folder'; path: string };pendingBranch?: string | null;pendingMultiCandidate?: boolean;+ pendingTargetMissing?: boolean;pendingShareBranchSwitch?: ShareDeepLinkBranchSwitchPayload;},): Promise<BrowserWindowHandle | null>;sendDeepLink(win: BrowserWindowHandle,- payload: { doc: string; branch?: string | null; multiCandidate?: boolean },+ payload: {+ doc: string;+ kind: 'doc' | 'folder';+ branch?: string | null;+ multiCandidate?: boolean;+ targetMissing?: boolean;+ },): void;sendShareDeepLink?(win: BrowserWindowHandle, payload: ShareDeepLinkPayload): void;resolveShareTarget?(share: ShareUrlPayload): Promise<CandidateSelection>;+ checkShareTargetExists?(+ projectPath: string,+ kind: 'doc' | 'folder',+ path: string,+ ): CheckTargetExistsResult;routeShareToNavigator?(payload: ShareNavigatorPayload): void;openScreen?(win: BrowserWindowHandle, screen: ScreenTarget): void;getFocusedWindow?(): BrowserWindowHandle | null;@@ -354,20 +379,35 @@ export function registerProtocolHandler(deps: ProtocolHandlerDeps): void {};switch (selection.kind) {case 'branch-match-ok': {+ const targetPath = shareTargetPath(share.target);+ const isContentRoot = share.target.kind === 'folder' && targetPath === '';+ const targetMissing =+ !isContentRoot &&+ deps.checkShareTargetExists?.(selection.candidate.path, share.target.kind, targetPath) ===+ 'missing';+ if (targetMissing) {+ deps.log?.warn(+ { url, project: selection.candidate.path },+ '[receive] target_check=missing — share target not on checked-out branch; dispatching with in-context toast',+ );+ }const existing = deps.focusWindowForProject(selection.candidate.path);if (existing) {deps.sendDeepLink(existing, {- doc: share.path,+ doc: targetPath,+ kind: share.target.kind,branch: share.branch,multiCandidate: selection.multiCandidate,+ ...(targetMissing ? { targetMissing: true } : {}),});return;}void deps.openProject(selection.candidate.path, {- pendingDeepLinkDoc: share.path,+ pendingDeepLinkTarget: { kind: share.target.kind, path: targetPath },pendingBranch: share.branch,pendingMultiCandidate: selection.multiCandidate,+ ...(targetMissing ? { pendingTargetMissing: true } : {}),}).then((win) => {if (win === null) {@@ -530,15 +570,17 @@ export function registerProtocolHandler(deps: ProtocolHandlerDeps): void {}const existing = deps.focusWindowForProject(parsed.project);if (existing) {- deps.sendDeepLink(existing, { doc: parsed.doc });+ deps.sendDeepLink(existing, { doc: parsed.doc, kind: 'doc' });return;}- void deps.openProject(parsed.project, { pendingDeepLinkDoc: parsed.doc }).catch((err) => {- deps.log?.warn(- { err: (err as Error).message, project: parsed.project },- '[url-scheme] openProject failed',- );- });+ void deps+ .openProject(parsed.project, { pendingDeepLinkTarget: { kind: 'doc', path: parsed.doc } })+ .catch((err) => {+ deps.log?.warn(+ { err: (err as Error).message, project: parsed.project },+ '[url-scheme] openProject failed',+ );+ });};const enqueueOrRoute = (url: string): void => {diff --git a/packages/desktop/src/main/window-manager.ts b/packages/desktop/src/main/window-manager.tsindex dcb28b88a..580cf0fa7 100644--- a/packages/desktop/src/main/window-manager.ts+++ b/packages/desktop/src/main/window-manager.ts@@ -88,9 +88,10 @@ interface ProjectContext {interface CreateProjectWindowOpts {projectPath: string;- pendingDeepLinkDoc?: string;+ pendingDeepLinkTarget?: { kind: 'doc' | 'folder'; path: string };pendingBranch?: string | null;pendingMultiCandidate?: boolean;+ pendingTargetMissing?: boolean;pendingShareBranchSwitch?: ShareDeepLinkBranchSwitchPayload;didEnsureGit?: boolean;consentVersion?: number;@@ -431,9 +432,10 @@ export class WindowManager {canonicalKey,projectName,lock: attached,- pendingDeepLinkDoc: opts.pendingDeepLinkDoc,+ pendingDeepLinkTarget: opts.pendingDeepLinkTarget,pendingBranch: opts.pendingBranch,pendingMultiCandidate: opts.pendingMultiCandidate,+ pendingTargetMissing: opts.pendingTargetMissing,pendingShareBranchSwitch: opts.pendingShareBranchSwitch,pendingServerRestartedToast: opts.pendingServerRestartedToast,});@@ -507,9 +509,10 @@ export class WindowManager {canonicalKey,projectName,lock,- pendingDeepLinkDoc: opts.pendingDeepLinkDoc,+ pendingDeepLinkTarget: opts.pendingDeepLinkTarget,pendingBranch: opts.pendingBranch,pendingMultiCandidate: opts.pendingMultiCandidate,+ pendingTargetMissing: opts.pendingTargetMissing,pendingShareBranchSwitch: opts.pendingShareBranchSwitch,pendingServerRestartedToast: opts.pendingServerRestartedToast,});@@ -624,11 +627,18 @@ export class WindowManager {title: formatEditorTitle(projectName),});- if (opts.pendingDeepLinkDoc) {- const doc = opts.pendingDeepLinkDoc;+ if (opts.pendingDeepLinkTarget) {+ const doc = opts.pendingDeepLinkTarget.path;+ const kind = opts.pendingDeepLinkTarget.kind;const branch = opts.pendingBranch ?? null;const multiCandidate = opts.pendingMultiCandidate === true;- registerPendingDelivery(window.webContents, 'ok:deep-link', { doc, branch, multiCandidate });+ registerPendingDelivery(window.webContents, 'ok:deep-link', {+ doc,+ kind,+ branch,+ multiCandidate,+ ...(opts.pendingTargetMissing === true ? { targetMissing: true } : {}),+ });}if (opts.pendingShareBranchSwitch) {@@ -772,9 +782,10 @@ export class WindowManager {canonicalKey: string;projectName: string;lock: ServerLockMetadataLike;- pendingDeepLinkDoc?: string;+ pendingDeepLinkTarget?: { kind: 'doc' | 'folder'; path: string };pendingBranch?: string | null;pendingMultiCandidate?: boolean;+ pendingTargetMissing?: boolean;pendingShareBranchSwitch?: ShareDeepLinkBranchSwitchPayload;pendingServerRestartedToast?: boolean;}): Promise<ProjectContext> {@@ -783,9 +794,10 @@ export class WindowManager {canonicalKey,projectName,lock,- pendingDeepLinkDoc,+ pendingDeepLinkTarget,pendingBranch,pendingMultiCandidate,+ pendingTargetMissing,pendingShareBranchSwitch,pendingServerRestartedToast,} = args;@@ -809,11 +821,18 @@ export class WindowManager {title: formatEditorTitle(projectName),});- if (pendingDeepLinkDoc) {- const doc = pendingDeepLinkDoc;+ if (pendingDeepLinkTarget) {+ const doc = pendingDeepLinkTarget.path;+ const kind = pendingDeepLinkTarget.kind;const branch = pendingBranch ?? null;const multiCandidate = pendingMultiCandidate === true;- registerPendingDelivery(window.webContents, 'ok:deep-link', { doc, branch, multiCandidate });+ registerPendingDelivery(window.webContents, 'ok:deep-link', {+ doc,+ kind,+ branch,+ multiCandidate,+ ...(pendingTargetMissing === true ? { targetMissing: true } : {}),+ });}if (pendingShareBranchSwitch) {diff --git a/packages/desktop/src/preload/index.ts b/packages/desktop/src/preload/index.tsindex c04ad26be..7f0c43351 100644--- a/packages/desktop/src/preload/index.ts+++ b/packages/desktop/src/preload/index.ts@@ -197,9 +197,23 @@ const bridge: OkDesktopBridge = {return () => ipcRenderer.removeListener('ok:update:stuck-hint', listener);},- onDeepLink(cb: (evt: { doc: string; branch?: string | null }) => void) {- const listener = (_event: IpcRendererEvent, evt: { doc: string; branch?: string | null }) =>- cb(evt);+ onDeepLink(+ cb: (evt: {+ doc: string;+ kind: 'doc' | 'folder';+ branch?: string | null;+ multiCandidate?: boolean;+ }) => void,+ ) {+ const listener = (+ _event: IpcRendererEvent,+ evt: {+ doc: string;+ kind: 'doc' | 'folder';+ branch?: string | null;+ multiCandidate?: boolean;+ },+ ) => cb(evt);// biome-ignore lint/plugin/no-loosely-typed-webcontents-ipc: preload-side subscription wrapper (precedent #14)ipcRenderer.on('ok:deep-link', listener);return () => ipcRenderer.removeListener('ok:deep-link', listener);@@ -278,7 +292,7 @@ const bridge: OkDesktopBridge = {createNew: (args) => invoke('ok:project:create-new', args),recordCreateNewBannerShown: (banner) =>invoke('ok:project:record-create-new-banner-shown', banner),- checkDocExists: (request) => invoke('ok:project:check-doc-exists', request),+ checkTargetExists: (request) => invoke('ok:project:check-target-exists', request),readHeadBranch: (projectPath: string) => invoke('ok:project:read-head-branch', projectPath),fetchBranchInfo: (request) => invoke('ok:project:fetch-branch-info', request),runCheckout: (request) => invoke('ok:project:run-checkout', request),diff --git a/packages/desktop/src/shared/bridge-contract.ts b/packages/desktop/src/shared/bridge-contract.tsindex 40004f932..98b788fc9 100644--- a/packages/desktop/src/shared/bridge-contract.ts+++ b/packages/desktop/src/shared/bridge-contract.ts@@ -136,7 +136,7 @@ export type ResolvedGitDirKind =| 'malformed-pointer'| 'inaccessible';-export type CheckDocExistsResult = 'exists' | 'missing' | 'unreadable';+export type CheckTargetExistsResult = 'exists' | 'missing' | 'unreadable';export interface OkUpdateDownloadedInfo {readonly version: string;@@ -320,8 +320,8 @@ export interface OkSharePayloadFields {readonly owner: string;readonly repo: string;readonly branch: string;- readonly path: string;- readonly blobUrl: string;+ readonly sharedUrl: string;+ readonly target: ShareTarget;}export type OkShareReceivedPayload =@@ -344,6 +344,10 @@ export type OkShareReceivedPayload =readonly share: OkSharePayloadFields;};+export type ShareTarget =+ | { readonly kind: 'doc'; readonly docPath: string }+ | { readonly kind: 'folder'; readonly folderPath: string };+export type ShareFolderValidationResult =| { readonly kind: 'ok'; readonly gitRemoteUrl: string }| { readonly kind: 'not-git' }@@ -395,7 +399,13 @@ export interface OkDesktopBridge {onWhatsNew(cb: (info: OkWhatsNewInfo) => void): OkUnsubscribe;onUpdateStuckHint(cb: (info: OkUpdateStuckHintInfo) => void): OkUnsubscribe;onDeepLink(- cb: (evt: { doc: string; branch?: string | null; multiCandidate?: boolean }) => void,+ cb: (evt: {+ doc: string;+ kind: 'doc' | 'folder';+ branch?: string | null;+ multiCandidate?: boolean;+ targetMissing?: boolean;+ }) => void,): OkUnsubscribe;onShareReceived(cb: (payload: OkShareReceivedPayload) => void): OkUnsubscribe;@@ -481,7 +491,7 @@ export interface OkDesktopBridge {path: string;target: 'new-window';entryPoint: EntryPoint;- pendingDeepLinkDoc?: string;+ pendingDeepLinkTarget?: { kind: 'doc' | 'folder'; path: string };pendingBranch?: string | null;}): Promise<void>;createNew(args: {@@ -491,15 +501,17 @@ export interface OkDesktopBridge {sharing?: 'shared' | 'local-only';}): Promise<void>;recordCreateNewBannerShown(banner: CreateNewBannerKind): Promise<void>;- checkDocExists(request: {+ checkTargetExists(request: {projectPath: string;- docPath: string;- }): Promise<CheckDocExistsResult>;+ kind: 'doc' | 'folder';+ path: string;+ }): Promise<CheckTargetExistsResult>;readHeadBranch(projectPath: string): Promise<HeadBranchInfo>;fetchBranchInfo(request: {projectPath: string;branch: string;- docPath: string;+ kind: 'doc' | 'folder';+ path: string;}): Promise<BranchInfoResponse | null>;runCheckout(request: { projectPath: string; branch: string }): Promise<CheckoutResponse | null>;awaitBranchSwitched(request: {diff --git a/packages/desktop/src/shared/ipc-channels.ts b/packages/desktop/src/shared/ipc-channels.tsindex c9696bb24..b17b2a5a3 100644--- a/packages/desktop/src/shared/ipc-channels.ts+++ b/packages/desktop/src/shared/ipc-channels.ts@@ -15,7 +15,7 @@ import type { BuildAndOpenResult } from '../main/ipc/install-skill.ts';import type { SeedApplyResult, SeedListPacksResult, SeedPlanResult } from '../main/ipc/seed.ts';import type { KeyringSmokeResult } from '../utility/keyring-smoke.ts';import type {- CheckDocExistsResult,+ CheckTargetExistsResult,HeadBranchInfo,OkDesktopConfig,OkLocalOpAuthReposResponse,@@ -65,7 +65,7 @@ interface ProjectOpenRequest {path: string;target: 'new-window';entryPoint: EntryPoint;- pendingDeepLinkDoc?: string;+ pendingDeepLinkTarget?: { kind: 'doc' | 'folder'; path: string };pendingBranch?: string | null;pendingMultiCandidate?: boolean;}@@ -306,16 +306,16 @@ export interface RequestChannels {'ok:project:get-session-state': { args: []; result: ProjectSessionState };'ok:project:set-session-state': { args: [state: ProjectSessionState]; result: undefined };'ok:project:open': { args: [request: ProjectOpenRequest]; result: undefined };- 'ok:project:check-doc-exists': {- args: [request: { projectPath: string; docPath: string }];- result: CheckDocExistsResult;+ 'ok:project:check-target-exists': {+ args: [request: { projectPath: string; kind: 'doc' | 'folder'; path: string }];+ result: CheckTargetExistsResult;};'ok:project:read-head-branch': {args: [projectPath: string];result: HeadBranchInfo;};'ok:project:fetch-branch-info': {- args: [request: { projectPath: string; branch: string; docPath: string }];+ args: [request: { projectPath: string; branch: string; kind: 'doc' | 'folder'; path: string }];result: BranchInfoResponse | null;};'ok:project:run-checkout': {diff --git a/packages/desktop/src/shared/ipc-events.ts b/packages/desktop/src/shared/ipc-events.tsindex 3a0a8cf8e..e84516dc6 100644--- a/packages/desktop/src/shared/ipc-events.ts+++ b/packages/desktop/src/shared/ipc-events.ts@@ -18,7 +18,13 @@ export interface EventChannels {'ok:update:whats-new': { payload: { version: string; releaseUrl: string } };'ok:update:stuck-hint': { payload: { downloadUrl: string } };'ok:deep-link': {- payload: { doc: string; branch?: string | null; multiCandidate?: boolean };+ payload: {+ doc: string;+ kind: 'doc' | 'folder';+ branch?: string | null;+ multiCandidate?: boolean;+ targetMissing?: boolean;+ };};'ok:share:received': { payload: OkShareReceivedPayload };'ok:mcp-wiring:show': {diff --git a/packages/desktop/tests/main/url-scheme-handler.test.ts b/packages/desktop/tests/main/url-scheme-handler.test.tsindex 3fd998ca0..b653e3a7b 100644--- a/packages/desktop/tests/main/url-scheme-handler.test.ts+++ b/packages/desktop/tests/main/url-scheme-handler.test.ts@@ -294,7 +294,9 @@ describe('registerProtocolHandler — queue-then-flush', () => {await flushPromises();await flushPromises();- expect(env.openProject).toHaveBeenCalledWith('/tmp/p', { pendingDeepLinkDoc: 'a.md' });+ expect(env.openProject).toHaveBeenCalledWith('/tmp/p', {+ pendingDeepLinkTarget: { kind: 'doc', path: 'a.md' },+ });expect(env.sendDeepLink).not.toHaveBeenCalled();});@@ -319,10 +321,10 @@ describe('registerProtocolHandler — queue-then-flush', () => {expect(env.openProject).toHaveBeenCalledTimes(2);expect(env.openProject).toHaveBeenNthCalledWith(1, '/tmp/p1', {- pendingDeepLinkDoc: 'a.md',+ pendingDeepLinkTarget: { kind: 'doc', path: 'a.md' },});expect(env.openProject).toHaveBeenNthCalledWith(2, '/tmp/p2', {- pendingDeepLinkDoc: 'b.md',+ pendingDeepLinkTarget: { kind: 'doc', path: 'b.md' },});expect(env.sendDeepLink).not.toHaveBeenCalled();});@@ -354,7 +356,9 @@ describe('registerProtocolHandler — queue-then-flush', () => {expect(env.openProject).not.toHaveBeenCalled();tickTimer(env);await flushPromises();- expect(env.openProject).toHaveBeenCalledWith('/tmp/p', { pendingDeepLinkDoc: 'a.md' });+ expect(env.openProject).toHaveBeenCalledWith('/tmp/p', {+ pendingDeepLinkTarget: { kind: 'doc', path: 'a.md' },+ });expect(env.timers.length).toBe(0);expect(env.openProject).toHaveBeenCalledTimes(1);});@@ -404,7 +408,7 @@ describe('registerProtocolHandler — queue-then-flush', () => {expect(env.focusWindowForProject).toHaveBeenCalledWith('/tmp/p');expect(env.openProject).not.toHaveBeenCalled();- expect(env.sendDeepLink).toHaveBeenCalledWith(existingWin, { doc: 'b.md' });+ expect(env.sendDeepLink).toHaveBeenCalledWith(existingWin, { doc: 'b.md', kind: 'doc' });});test('spawns new window when project is not yet open (warm different-project)', async () => {@@ -426,7 +430,9 @@ describe('registerProtocolHandler — queue-then-flush', () => {await flushPromises();await flushPromises();- expect(env.openProject).toHaveBeenCalledWith('/tmp/B', { pendingDeepLinkDoc: 'x.md' });+ expect(env.openProject).toHaveBeenCalledWith('/tmp/B', {+ pendingDeepLinkTarget: { kind: 'doc', path: 'x.md' },+ });expect(env.sendDeepLink).not.toHaveBeenCalled();});@@ -455,7 +461,7 @@ describe('registerProtocolHandler — queue-then-flush', () => {await flushPromises();expect(openProjectStub).toHaveBeenCalledWith('/tmp/broken', {- pendingDeepLinkDoc: 'x.md',+ pendingDeepLinkTarget: { kind: 'doc', path: 'x.md' },});expect(env.sendDeepLink).not.toHaveBeenCalled();});@@ -483,7 +489,9 @@ describe('registerProtocolHandler — second-instance argv parsing', () => {await flushPromises();await flushPromises();- expect(env.openProject).toHaveBeenCalledWith('/tmp/si', { pendingDeepLinkDoc: 'readme.md' });+ expect(env.openProject).toHaveBeenCalledWith('/tmp/si', {+ pendingDeepLinkTarget: { kind: 'doc', path: 'readme.md' },+ });});test('ignores argv entries that are not openknowledge:// URLs', async () => {@@ -528,7 +536,9 @@ describe('registerProtocolHandler — cold-start process.argv scan', () => {await flushPromises();await flushPromises();- expect(env.openProject).toHaveBeenCalledWith('/tmp/cs', { pendingDeepLinkDoc: 'a.md' });+ expect(env.openProject).toHaveBeenCalledWith('/tmp/cs', {+ pendingDeepLinkTarget: { kind: 'doc', path: 'a.md' },+ });});test('no-op when no openknowledge:// URLs in initial argv', async () => {@@ -595,8 +605,8 @@ describe('registerProtocolHandler — share-flow routing', () => {owner: 'inkeep',repo: 'playbooks',branch: 'main',- path: 'x.md',- blobUrl,+ sharedUrl: blobUrl,+ target: { kind: 'doc', docPath: 'x.md' },});expect(env.sendDeepLink).not.toHaveBeenCalled();});@@ -728,7 +738,7 @@ describe('registerProtocolHandler — share-flow routing', () => {env.app.fireOpenUrl('openknowledge://open?project=/tmp/p&doc=a.md');await flushPromises();- expect(env.sendDeepLink).toHaveBeenCalledWith(focusedWin, { doc: 'a.md' });+ expect(env.sendDeepLink).toHaveBeenCalledWith(focusedWin, { doc: 'a.md', kind: 'doc' });expect(sendShareDeepLink).not.toHaveBeenCalled();});});@@ -743,8 +753,8 @@ describe('registerProtocolHandler — resolved share routing (US-003)', () => {owner: 'inkeep',repo: 'playbooks',branch: 'main',- path: 'docs/getting-started.md',- blobUrl: 'https://github.com/inkeep/playbooks/blob/main/docs/getting-started.md',+ sharedUrl: 'https://github.com/inkeep/playbooks/blob/main/docs/getting-started.md',+ target: { kind: 'doc', docPath: 'docs/getting-started.md' },};}@@ -801,7 +811,7 @@ describe('registerProtocolHandler — resolved share routing (US-003)', () => {expect(resolveShareTarget).toHaveBeenCalledTimes(1);expect(resolveShareTarget).toHaveBeenCalledWith(expectedSharePayload());expect(env.openProject).toHaveBeenCalledWith('/Users/me/playbooks', {- pendingDeepLinkDoc: 'docs/getting-started.md',+ pendingDeepLinkTarget: { kind: 'doc', path: 'docs/getting-started.md' },pendingBranch: 'main',pendingMultiCandidate: true,});@@ -837,7 +847,7 @@ describe('registerProtocolHandler — resolved share routing (US-003)', () => {await flushPromises();expect(env.openProject).toHaveBeenCalledWith('/Users/me/solo-clone', {- pendingDeepLinkDoc: 'docs/getting-started.md',+ pendingDeepLinkTarget: { kind: 'doc', path: 'docs/getting-started.md' },pendingBranch: 'main',pendingMultiCandidate: false,});@@ -876,6 +886,7 @@ describe('registerProtocolHandler — resolved share routing (US-003)', () => {expect(env.focusWindowForProject).toHaveBeenCalledWith('/Users/me/playbooks');expect(env.sendDeepLink).toHaveBeenCalledWith(editorWin, {doc: 'docs/getting-started.md',+ kind: 'doc',branch: 'main',multiCandidate: true,});@@ -1450,11 +1461,11 @@ describe('registerProtocolHandler — resolved share routing (US-003)', () => {expect(env.openProject).toHaveBeenCalledWith('/p/repo-b',- expect.objectContaining({ pendingDeepLinkDoc: 'b.md' }),+ expect.objectContaining({ pendingDeepLinkTarget: { kind: 'doc', path: 'b.md' } }),);expect(env.openProject).toHaveBeenCalledWith('/p/repo-a',- expect.objectContaining({ pendingDeepLinkDoc: 'a.md' }),+ expect.objectContaining({ pendingDeepLinkTarget: { kind: 'doc', path: 'a.md' } }),);});});@@ -1628,8 +1639,8 @@ describe('registerProtocolHandler — continue-activity Handoff path', () => {owner: 'inkeep',repo: 'playbooks',branch: 'main',- path: 'x.md',- blobUrl: 'https://github.com/inkeep/playbooks/blob/main/x.md',+ sharedUrl: 'https://github.com/inkeep/playbooks/blob/main/x.md',+ target: { kind: 'doc', docPath: 'x.md' },});});@@ -1895,7 +1906,7 @@ describe('registerProtocolHandler — continue-activity Handoff path', () => {env.app.fireOpenUrl('openknowledge://open?project=/tmp/p&doc=a.md');await flushPromises();- expect(env.sendDeepLink).toHaveBeenCalledWith(focusedWin, { doc: 'a.md' });+ expect(env.sendDeepLink).toHaveBeenCalledWith(focusedWin, { doc: 'a.md', kind: 'doc' });const blobUrl = 'https://github.com/o/r/blob/main/x.md';env.app.fireOpenUrl(`openknowledge://share?url=${encodeURIComponent(blobUrl)}`);diff --git a/packages/desktop/tests/main/window-manager.test.ts b/packages/desktop/tests/main/window-manager.test.tsindex efb0abc11..c42d740ac 100644--- a/packages/desktop/tests/main/window-manager.test.ts+++ b/packages/desktop/tests/main/window-manager.test.ts@@ -1462,14 +1462,14 @@ describe('WindowManager.focusWindowForProject (M4 URL-scheme warm-start)', () =>});});-describe('WindowManager — pendingDeepLinkDoc dom-ready gate (M4 US-007 / Finding 2)', () => {+describe('WindowManager — pendingDeepLinkTarget dom-ready gate (M4 US-007 / Finding 2)', () => {let env: TestEnv;beforeEach(() => {env = buildEnv();});- test('spawn path: pendingDeepLinkDoc registers dom-ready listener BEFORE loadURL resolves', async () => {+ test('spawn path: pendingDeepLinkTarget registers dom-ready listener BEFORE loadURL resolves', async () => {let onceCalledBeforeLoadResolved = false;let domReadyRegistrations = 0;env.deps.createWindow = () => {@@ -1492,7 +1492,7 @@ describe('WindowManager — pendingDeepLinkDoc dom-ready gate (M4 US-007 / Findiconst wm = new WindowManager(env.deps);const pending = wm.createProjectWindow({projectPath: '/tmp/deep-link-proj',- pendingDeepLinkDoc: 'notes/meeting',+ pendingDeepLinkTarget: { kind: 'doc', path: 'notes/meeting' },});env.utilities[0]?.fire({ type: 'ready', port: 51220, apiOrigin: 'http://localhost:51220' });await pending;@@ -1508,12 +1508,13 @@ describe('WindowManager — pendingDeepLinkDoc dom-ready gate (M4 US-007 / Findiexpect(deepLinkCall).toBeDefined();expect(deepLinkCall?.[1]).toEqual({doc: 'notes/meeting',+ kind: 'doc',branch: null,multiCandidate: false,});});- test('spawn path: no pendingDeepLinkDoc → no ok:deep-link event fires on dom-ready', async () => {+ test('spawn path: no pendingDeepLinkTarget → no ok:deep-link event fires on dom-ready', async () => {const wm = new WindowManager(env.deps);const pending = wm.createProjectWindow({ projectPath: '/tmp/no-deep-link' });env.utilities[0]?.fire({ type: 'ready', port: 51221, apiOrigin: 'http://localhost:51221' });@@ -1526,7 +1527,7 @@ describe('WindowManager — pendingDeepLinkDoc dom-ready gate (M4 US-007 / Findiexpect(sendCalls.find((c) => c[0] === 'ok:deep-link')).toBeUndefined();});- test('attach path: pendingDeepLinkDoc also fires on dom-ready', async () => {+ test('attach path: pendingDeepLinkTarget also fires on dom-ready', async () => {const liveLock: ServerLockMetadataLike = {pid: 65793,hostname: 'my-host',@@ -1544,7 +1545,7 @@ describe('WindowManager — pendingDeepLinkDoc dom-ready gate (M4 US-007 / Findiconst wm = new WindowManager(env.deps);const ctx = await wm.createProjectWindow({projectPath: '/tmp/attach-deep-link',- pendingDeepLinkDoc: 'attached/note',+ pendingDeepLinkTarget: { kind: 'doc', path: 'attached/note' },});expect(ctx.ownsServer).toBe(false);@@ -1556,6 +1557,7 @@ describe('WindowManager — pendingDeepLinkDoc dom-ready gate (M4 US-007 / Findiexpect(deepLinkCall).toBeDefined();expect(deepLinkCall?.[1]).toEqual({doc: 'attached/note',+ kind: 'doc',branch: null,multiCandidate: false,});@@ -1565,7 +1567,7 @@ describe('WindowManager — pendingDeepLinkDoc dom-ready gate (M4 US-007 / Findiconst wm = new WindowManager(env.deps);const pending = wm.createProjectWindow({projectPath: '/tmp/branch-aware-spawn',- pendingDeepLinkDoc: 'docs/page.md',+ pendingDeepLinkTarget: { kind: 'doc', path: 'docs/page.md' },pendingBranch: 'feat/foo',});env.utilities[0]?.fire({ type: 'ready', port: 51222, apiOrigin: 'http://localhost:51222' });@@ -1578,6 +1580,7 @@ describe('WindowManager — pendingDeepLinkDoc dom-ready gate (M4 US-007 / Findiconst deepLinkCall = sendCalls.find((c) => c[0] === 'ok:deep-link');expect(deepLinkCall?.[1]).toEqual({doc: 'docs/page.md',+ kind: 'doc',branch: 'feat/foo',multiCandidate: false,});@@ -1601,7 +1604,7 @@ describe('WindowManager — pendingDeepLinkDoc dom-ready gate (M4 US-007 / Findiconst wm = new WindowManager(env.deps);await wm.createProjectWindow({projectPath: '/tmp/attach-branch',- pendingDeepLinkDoc: 'attached/note',+ pendingDeepLinkTarget: { kind: 'doc', path: 'attached/note' },pendingBranch: 'release/v2',});@@ -1612,10 +1615,33 @@ describe('WindowManager — pendingDeepLinkDoc dom-ready gate (M4 US-007 / Findiconst deepLinkCall = sendCalls.find((c) => c[0] === 'ok:deep-link');expect(deepLinkCall?.[1]).toEqual({doc: 'attached/note',+ kind: 'doc',branch: 'release/v2',multiCandidate: false,});});++ test('spawn path: pendingDeepLinkTarget threads the folder kind into the deep-link payload', async () => {+ const wm = new WindowManager(env.deps);+ const pending = wm.createProjectWindow({+ projectPath: '/tmp/folder-share-spawn',+ pendingDeepLinkTarget: { kind: 'folder', path: 'docs' },+ });+ env.utilities[0]?.fire({ type: 'ready', port: 51223, apiOrigin: 'http://localhost:51223' });+ await pending;++ const window = env.windows[0];+ if (!window) throw new Error('expected window to be created');+ window.fireDomReady();+ const sendCalls = (window.webContents.send as ReturnType<typeof mock>).mock.calls;+ const deepLinkCall = sendCalls.find((c) => c[0] === 'ok:deep-link');+ expect(deepLinkCall?.[1]).toEqual({+ doc: 'docs',+ kind: 'folder',+ branch: null,+ multiCandidate: false,+ });+ });});describe('WindowManager — pendingShareBranchSwitch dom-ready gate (US-004)', () => {diff --git a/packages/desktop/tests/smoke/share-receive-multi-worktree.e2e.ts b/packages/desktop/tests/smoke/share-receive-multi-worktree.e2e.tsindex eaca3eca4..4f88209da 100644--- a/packages/desktop/tests/smoke/share-receive-multi-worktree.e2e.ts+++ b/packages/desktop/tests/smoke/share-receive-multi-worktree.e2e.ts@@ -118,10 +118,8 @@ test.describe('share-receive multi-worktree smoke (US-014 / J1 silent dispatch)'const firstWindow = await app.firstWindow({ timeout: 15_000 });expect(firstWindow).toBeDefined();- const shareUrl =- 'openknowledge://share?' +- `owner=inkeep&repo=open-knowledge&branch=feat-bar&path=docs%2Fx.md&` +- `blobUrl=${encodeURIComponent('https://github.com/inkeep/open-knowledge/blob/feat-bar/docs/x.md')}`;+ const githubBlobUrl = 'https://github.com/inkeep/open-knowledge/blob/feat-bar/docs/x.md';+ const shareUrl = `openknowledge://share?url=${encodeURIComponent(githubBlobUrl)}`;execSync(`open -g "${shareUrl}"`, { stdio: 'pipe' });await expect(async () => {diff --git a/packages/server/assets/skills/project/SKILL.md b/packages/server/assets/skills/project/SKILL.mdindex 9a610a218..d265f1afe 100644--- a/packages/server/assets/skills/project/SKILL.md+++ b/packages/server/assets/skills/project/SKILL.md@@ -28,7 +28,7 @@ Everything below is depth. Read on demand.The full MCP surface, grouped by risk-level. Every tool's `kind` / `action` set is single-risk-level (never a read and a write behind one discriminator).-- **Reads** — `exec` (primary; shell-style `cat`/`ls`/`grep`/`find` with frontmatter + backlink + history enrichment), `search` (ranked, BM25 + recency), `get_history` (versions for a doc), `links` (`kind: 'backlinks'|'forward'|'dead'|'orphans'|'hubs'|'suggest'`), `get_config` (resolved config), `get_components` (canonical component JSX schemas), `get_authoring_palette` (markdown-native authoring forms + themed `html preview` embed starters + theme tokens), `get_preview_url` (browser-reachable preview URL on demand), `share_link` (GitHub-substrate share URL for a doc; read-only against `.git/`, no commits/pushes — returns a clear error when the project has no GitHub remote, since agents do not publish projects).+- **Reads** — `exec` (primary; shell-style `cat`/`ls`/`grep`/`find` with frontmatter + backlink + history enrichment), `search` (ranked, BM25 + recency), `get_history` (versions for a doc), `links` (`kind: 'backlinks'|'forward'|'dead'|'orphans'|'hubs'|'suggest'`), `get_config` (resolved config), `get_components` (canonical component JSX schemas), `get_authoring_palette` (markdown-native authoring forms + themed `html preview` embed starters + theme tokens), `get_preview_url` (browser-reachable preview URL on demand), `share_link` (GitHub-substrate share URL for a doc or folder; read-only against `.git/`, no commits/pushes — returns a clear error when the project has no GitHub remote, since agents do not publish projects).- **Writes** — `write_document` (new or full-replace; supports `template:` instantiation), `edit_document` (body-only find/replace), `edit_frontmatter` (1-2 keys via RFC 7396 JSON Merge Patch — preferred), `delete_document`, `rename` (probes file vs folder; rewrites referrers), `version` (`action: 'save'|'rollback'`), `folder_config` (`action: 'set-rule'|'write-template'|'delete-template'`). `set-rule` writes a folder's own frontmatter (open-shape, like a doc's); `write-template`/`delete-template` manage the folder's templates (what new docs start with).- **GitHub-sync conflicts** — `list_conflicts` (enumerate), `get_conflict_content` (base/ours/theirs stages + lifecycle), `resolve_conflict` (write a chosen resolution + commit; destructive). Mutating writes against a doc in conflict return RFC 9457 `urn:ok:error:doc-in-conflict` (409); `exec("cat …")` returns `lifecycle: {status, reason} | null` so you can detect the state proactively. See *Conflict-aware writes*.- **Workflow** — `ingest`, `research`, `consolidate`, `discover` (return procedural guides, not data).diff --git a/packages/server/src/api-extension.branch-info.test.ts b/packages/server/src/api-extension.branch-info.test.tsindex 56ac02ee9..4e9b30d3e 100644--- a/packages/server/src/api-extension.branch-info.test.ts+++ b/packages/server/src/api-extension.branch-info.test.ts@@ -89,13 +89,19 @@ async function bootRig(};}-function buildUrl(port: number, branch: string, path: string): string {+function buildUrl(port: number, branch: string, path: string, kind?: 'doc' | 'folder'): string {const params = new URLSearchParams({ branch, path });+ if (kind) params.set('kind', kind);return `http://localhost:${port}/api/git/branch-info?${params.toString()}`;}-async function getBranchInfo(port: number, branch: string, path: string): Promise<Response> {- return fetch(buildUrl(port, branch, path));+async function getBranchInfo(+ port: number,+ branch: string,+ path: string,+ kind?: 'doc' | 'folder',+): Promise<Response> {+ return fetch(buildUrl(port, branch, path, kind));}let rig: TestRig | null = null;@@ -122,13 +128,13 @@ describe('GET /api/git/branch-info', () => {currentBranch: 'main',currentHeadSha: null,detached: false,- shareFileExists: true,+ shareTargetExists: true,dirtyConflicts: { conflicts: false, files: [] },branchIsLocal: true,});});- test('branch mismatch + file exists on current branch reports shareFileExists=true', async () => {+ test('branch mismatch + file exists on current branch reports shareTargetExists=true', async () => {rig = await bootRig((projectDir) => {initRepo(projectDir);write(projectDir, 'docs/guide.md', '# main\n');@@ -143,13 +149,13 @@ describe('GET /api/git/branch-info', () => {expect(res.status).toBe(200);const json = (await res.json()) as Record<string, unknown>;expect(json.currentBranch).toBe('main');- expect(json.shareFileExists).toBe(true);+ expect(json.shareTargetExists).toBe(true);expect(json.branchIsLocal).toBe(true);expect(json.dirtyConflicts).toEqual({ conflicts: false, files: [] });expect(json.detached).toBe(false);});- test('branch mismatch + file missing on current branch reports shareFileExists=false', async () => {+ test('branch mismatch + file missing on current branch reports shareTargetExists=false', async () => {rig = await bootRig((projectDir) => {initRepo(projectDir);write(projectDir, 'README.md', 'r\n');@@ -164,7 +170,7 @@ describe('GET /api/git/branch-info', () => {expect(res.status).toBe(200);const json = (await res.json()) as Record<string, unknown>;expect(json.currentBranch).toBe('main');- expect(json.shareFileExists).toBe(false);+ expect(json.shareTargetExists).toBe(false);expect(json.branchIsLocal).toBe(true);});@@ -208,7 +214,7 @@ describe('GET /api/git/branch-info', () => {expect(json.detached).toBe(true);expect(typeof json.currentHeadSha).toBe('string');expect((json.currentHeadSha as string).length).toBe(7);- expect(json.shareFileExists).toBe(true);+ expect(json.shareTargetExists).toBe(true);});test('branch absent locally reports branchIsLocal=false', async () => {@@ -242,11 +248,11 @@ describe('GET /api/git/branch-info', () => {const json = (await res.json()) as Record<string, unknown>;expect(json.currentBranch).toBe('main');expect(json.branchIsLocal).toBe(true);- expect(json.shareFileExists).toBe(true);+ expect(json.shareTargetExists).toBe(true);expect(json.dirtyConflicts).toEqual({ conflicts: false, files: [] });});- test('nested doc path resolves shareFileExists correctly', async () => {+ test('nested doc path resolves shareTargetExists correctly', async () => {rig = await bootRig((projectDir) => {initRepo(projectDir);write(projectDir, 'a/b/c/deep.md', '# deep\n');@@ -256,7 +262,7 @@ describe('GET /api/git/branch-info', () => {const res = await getBranchInfo(rig.port, 'main', 'a/b/c/deep.md');expect(res.status).toBe(200);const json = (await res.json()) as Record<string, unknown>;- expect(json.shareFileExists).toBe(true);+ expect(json.shareTargetExists).toBe(true);});test('missing path query param returns 400', async () => {@@ -346,4 +352,69 @@ describe('GET /api/git/branch-info', () => {const res = await fetch(buildUrl(rig.port, 'main', 'a.md'), { method: 'POST' });expect(res.status).toBe(405);});++ test('kind=folder on an extant folder reports shareTargetExists=true', async () => {+ rig = await bootRig((projectDir) => {+ initRepo(projectDir);+ write(projectDir, 'docs/guides/intro.md', '# intro\n');+ commitAll(projectDir, 'init');+ });++ const res = await getBranchInfo(rig.port, 'main', 'docs/guides', 'folder');+ expect(res.status).toBe(200);+ const json = (await res.json()) as Record<string, unknown>;+ expect(json.shareTargetExists).toBe(true);+ });++ test('kind=folder on a missing folder reports shareTargetExists=false', async () => {+ rig = await bootRig((projectDir) => {+ initRepo(projectDir);+ write(projectDir, 'docs/guide.md', '# guide\n');+ commitAll(projectDir, 'init');+ });++ const res = await getBranchInfo(rig.port, 'main', 'does/not/exist', 'folder');+ expect(res.status).toBe(200);+ const json = (await res.json()) as Record<string, unknown>;+ expect(json.shareTargetExists).toBe(false);+ });++ test('kind=folder with empty path (content root) reports shareTargetExists=true (probe skipped)', async () => {+ rig = await bootRig((projectDir) => {+ initRepo(projectDir);+ write(projectDir, 'docs/guide.md', '# guide\n');+ commitAll(projectDir, 'init');+ });++ const res = await fetch(+ `http://localhost:${rig.port}/api/git/branch-info?branch=main&path=&kind=folder`,+ );+ expect(res.status).toBe(200);+ const json = (await res.json()) as Record<string, unknown>;+ expect(json.shareTargetExists).toBe(true);+ });++ test('empty path with kind=doc (default) returns 400', async () => {+ rig = await bootRig((projectDir) => {+ initRepo(projectDir);+ write(projectDir, 'a.md', 'a\n');+ commitAll(projectDir, 'init');+ });++ const res = await fetch(`http://localhost:${rig.port}/api/git/branch-info?branch=main&path=`);+ expect(res.status).toBe(400);+ });++ test('kind absent defaults to doc: behavior unchanged for a doc path', async () => {+ rig = await bootRig((projectDir) => {+ initRepo(projectDir);+ write(projectDir, 'docs/guide.md', '# guide\n');+ commitAll(projectDir, 'init');+ });++ const res = await getBranchInfo(rig.port, 'main', 'docs/guide.md');+ expect(res.status).toBe(200);+ const json = (await res.json()) as Record<string, unknown>;+ expect(json.shareTargetExists).toBe(true);+ });});diff --git a/packages/server/src/api-extension.ts b/packages/server/src/api-extension.tsindex ce09e875f..7864b5127 100644--- a/packages/server/src/api-extension.ts+++ b/packages/server/src/api-extension.ts@@ -238,8 +238,9 @@ import type { RecentlyRemovedDocs } from './recently-removed-docs.ts';import { readServerLock } from './server-lock.ts';import {buildGitHubBlobUrl,+ buildGitHubTreeUrl,emitShareConstructUrlLog,- isValidShareDocPath,+ isValidSharePath,SHARE_BASE_URL,SHARE_CONSTRUCT_URL_HANDLER_TAG,} from './share/construct-url.ts';@@ -346,7 +347,7 @@ import {import {BRANCH_INFO_HANDLER_TAG,computeBranchInfo,- isValidBranchInfoDocPath,+ isValidBranchInfoPath,isValidBranchName,} from './git-branch-info.ts';import { CHECKOUT_HANDLER_TAG, runCheckoutFlow } from './git-checkout.ts';@@ -10113,7 +10114,7 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {async (_req, res, body) => {try {if (!projectDir) {- emitShareConstructUrlLog('no-remote');+ emitShareConstructUrlLog('no-remote', { kind: body.kind });successResponse(res,200,@@ -10123,8 +10124,9 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {);return;}- if (!isValidShareDocPath(body.docPath)) {- emitShareConstructUrlLog('invalid-path');+ const sharePath = body.kind === 'doc' ? body.docPath : body.folderPath;+ if (!isValidSharePath(sharePath, body.kind)) {+ emitShareConstructUrlLog('invalid-path', { kind: body.kind });successResponse(res,200,@@ -10138,7 +10140,7 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {if (branch === null) {const originPeek = readOriginGitHubRepo(projectDir);if (originPeek.kind === 'no-remote') {- emitShareConstructUrlLog('no-remote');+ emitShareConstructUrlLog('no-remote', { kind: body.kind });successResponse(res,200,@@ -10148,7 +10150,7 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {);return;}- emitShareConstructUrlLog('detached-head');+ emitShareConstructUrlLog('detached-head', { kind: body.kind });successResponse(res,200,@@ -10160,7 +10162,7 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {}const origin = readOriginGitHubRepo(projectDir);if (origin.kind === 'no-remote') {- emitShareConstructUrlLog('no-remote');+ emitShareConstructUrlLog('no-remote', { kind: body.kind });successResponse(res,200,@@ -10171,7 +10173,7 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {return;}if (origin.kind === 'non-github') {- emitShareConstructUrlLog('non-github-remote');+ emitShareConstructUrlLog('non-github-remote', { kind: body.kind });successResponse(res,200,@@ -10183,7 +10185,10 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {}const branchExists = branchExistsOnOrigin(projectDir, branch);if (!branchExists) {- emitShareConstructUrlLog('branch-not-on-origin', false);+ emitShareConstructUrlLog('branch-not-on-origin', {+ branchExists: false,+ kind: body.kind,+ });successResponse(res,200,@@ -10193,14 +10198,32 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {);return;}- const blobUrl = buildGitHubBlobUrl(origin.owner, origin.repo, branch, body.docPath);- const shareUrl = `${SHARE_BASE_URL}${encodeShareUrl(blobUrl)}`;- emitShareConstructUrlLog('ok', true);+ const contentRel = toGitRelativePath(projectDir, contentDir);+ if (contentRel === null) {+ throw new Error('content dir is not contained within the project dir');+ }+ const sharingNonRootTarget =+ body.kind === 'doc' ? body.docPath !== '' : body.folderPath !== '';+ if (contentRel !== '' && sharingNonRootTarget) {+ getLogger('share').warn(+ { action: 'construct-url', kind: body.kind },+ '[share] content.dir != "." — non-root share URL omits the content.dir prefix; the github.com link may point at the wrong subtree. In-app receive navigation is content-relative and lands correctly.',+ );+ }+ let sharedUrl: string;+ if (body.kind === 'doc') {+ sharedUrl = buildGitHubBlobUrl(origin.owner, origin.repo, branch, body.docPath);+ } else {+ const treePath = body.folderPath === '' ? contentRel : body.folderPath;+ sharedUrl = buildGitHubTreeUrl(origin.owner, origin.repo, branch, treePath);+ }+ const shareUrl = `${SHARE_BASE_URL}${encodeShareUrl(sharedUrl)}`;+ emitShareConstructUrlLog('ok', { branchExists: true, kind: body.kind });successResponse(res,200,ShareConstructUrlResponseSchema,- { ok: true, shareUrl, blobUrl, branch },+ { ok: true, shareUrl, sharedUrl, branch },{ handler: SHARE_CONSTRUCT_URL_HANDLER_TAG },);} catch (err) {@@ -10234,7 +10257,9 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {}const url = new URL(req.url ?? '', 'http://localhost');const branch = url.searchParams.get('branch');- const docPath = url.searchParams.get('path');+ const path = url.searchParams.get('path');+ const kindParam = url.searchParams.get('kind');+ const kind: 'doc' | 'folder' = kindParam === 'folder' ? 'folder' : 'doc';if (!isValidBranchName(branch)) {errorResponse(res,@@ -10245,7 +10270,7 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {);return;}- if (!isValidBranchInfoDocPath(docPath)) {+ if (!isValidBranchInfoPath(path, kind)) {errorResponse(res,400,@@ -10255,7 +10280,7 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {);return;}- const info = await computeBranchInfo(projectDir, branch, docPath);+ const info = await computeBranchInfo(projectDir, branch, path, kind);successResponse(res, 200, BranchInfoResponseSchema, info, {handler: BRANCH_INFO_HANDLER_TAG,});diff --git a/packages/server/src/git-branch-info.test.ts b/packages/server/src/git-branch-info.test.tsindex 4b803c468..8e04253f2 100644--- a/packages/server/src/git-branch-info.test.ts+++ b/packages/server/src/git-branch-info.test.ts@@ -2,7 +2,7 @@ import { describe, expect, test } from 'bun:test';import {isBranchResolutionError,- isValidBranchInfoDocPath,+ isValidBranchInfoPath,isValidBranchName,} from './git-branch-info.ts';@@ -53,53 +53,61 @@ describe('isValidBranchName', () => {});});-describe('isValidBranchInfoDocPath', () => {+describe('isValidBranchInfoPath', () => {test('accepts a single-segment doc path', () => {- expect(isValidBranchInfoDocPath('README.md')).toBe(true);+ expect(isValidBranchInfoPath('README.md', 'doc')).toBe(true);});test('accepts a nested forward-slash doc path', () => {- expect(isValidBranchInfoDocPath('docs/sub/page.md')).toBe(true);+ expect(isValidBranchInfoPath('docs/sub/page.md', 'doc')).toBe(true);});test('rejects a leading forward-slash (absolute path)', () => {- expect(isValidBranchInfoDocPath('/etc/passwd')).toBe(false);+ expect(isValidBranchInfoPath('/etc/passwd', 'doc')).toBe(false);+ expect(isValidBranchInfoPath('/etc/passwd', 'folder')).toBe(false);});test('rejects any backslash — wire contract is forward-slash only', () => {- expect(isValidBranchInfoDocPath('docs\\page.md')).toBe(false);- expect(isValidBranchInfoDocPath('\\etc\\passwd')).toBe(false);- expect(isValidBranchInfoDocPath('foo/bar\\baz.md')).toBe(false);+ expect(isValidBranchInfoPath('docs\\page.md', 'doc')).toBe(false);+ expect(isValidBranchInfoPath('\\etc\\passwd', 'doc')).toBe(false);+ expect(isValidBranchInfoPath('foo/bar\\baz.md', 'folder')).toBe(false);});test('rejects `..` traversal segment', () => {- expect(isValidBranchInfoDocPath('docs/../etc/passwd')).toBe(false);+ expect(isValidBranchInfoPath('docs/../etc/passwd', 'doc')).toBe(false);+ expect(isValidBranchInfoPath('docs/../etc/passwd', 'folder')).toBe(false);});test('rejects `.git` segment (exact match, not `.gitignore`)', () => {- expect(isValidBranchInfoDocPath('.git/HEAD')).toBe(false);- expect(isValidBranchInfoDocPath('foo/.git/config')).toBe(false);- expect(isValidBranchInfoDocPath('.gitignore')).toBe(true);- expect(isValidBranchInfoDocPath('.github/foo.md')).toBe(true);+ expect(isValidBranchInfoPath('.git/HEAD', 'doc')).toBe(false);+ expect(isValidBranchInfoPath('foo/.git/config', 'doc')).toBe(false);+ expect(isValidBranchInfoPath('.gitignore', 'doc')).toBe(true);+ expect(isValidBranchInfoPath('.github/foo.md', 'doc')).toBe(true);});test('rejects consecutive slashes (empty segment)', () => {- expect(isValidBranchInfoDocPath('docs//page.md')).toBe(false);+ expect(isValidBranchInfoPath('docs//page.md', 'doc')).toBe(false);});test('rejects control characters', () => {- expect(isValidBranchInfoDocPath('docs/\npage.md')).toBe(false);- expect(isValidBranchInfoDocPath('docs/\x00.md')).toBe(false);+ expect(isValidBranchInfoPath('docs/\npage.md', 'doc')).toBe(false);+ expect(isValidBranchInfoPath('docs/\x00.md', 'doc')).toBe(false);});test('rejects non-string inputs', () => {- expect(isValidBranchInfoDocPath(null)).toBe(false);- expect(isValidBranchInfoDocPath(undefined)).toBe(false);- expect(isValidBranchInfoDocPath(123)).toBe(false);+ expect(isValidBranchInfoPath(null, 'doc')).toBe(false);+ expect(isValidBranchInfoPath(undefined, 'doc')).toBe(false);+ expect(isValidBranchInfoPath(123, 'doc')).toBe(false);});- test('rejects empty string', () => {- expect(isValidBranchInfoDocPath('')).toBe(false);+ test('empty string is the folder-root sentinel: valid for folder, invalid for doc', () => {+ expect(isValidBranchInfoPath('', 'folder')).toBe(true);+ expect(isValidBranchInfoPath('', 'doc')).toBe(false);+ });++ test('non-empty folder path passes the same segment gate as doc', () => {+ expect(isValidBranchInfoPath('docs/guides', 'folder')).toBe(true);+ expect(isValidBranchInfoPath('docs', 'folder')).toBe(true);});});diff --git a/packages/server/src/git-branch-info.ts b/packages/server/src/git-branch-info.tsindex 7ca93fd55..3dcfa1829 100644--- a/packages/server/src/git-branch-info.ts+++ b/packages/server/src/git-branch-info.ts@@ -9,7 +9,7 @@ export type BranchInfo =detached: false;currentBranch: string | null;currentHeadSha: null;- shareFileExists: boolean;+ shareTargetExists: boolean;dirtyConflicts: DirtyOverlapResult;branchIsLocal: boolean;}@@ -17,19 +17,19 @@ export type BranchInfo =detached: true;currentBranch: null;currentHeadSha: string;- shareFileExists: boolean;+ shareTargetExists: boolean;dirtyConflicts: DirtyOverlapResult;branchIsLocal: boolean;};-export function isValidBranchInfoDocPath(docPath: unknown): docPath is string {- if (typeof docPath !== 'string') return false;- if (docPath.length === 0) return false;- if (docPath.startsWith('/')) return false;- if (docPath.includes('\\')) return false;+export function isValidBranchInfoPath(path: unknown, kind: 'doc' | 'folder'): path is string {+ if (typeof path !== 'string') return false;+ if (path.length === 0) return kind === 'folder';+ if (path.startsWith('/')) return false;+ if (path.includes('\\')) return false;// biome-ignore lint/suspicious/noControlCharactersInRegex: control chars are exactly what we want to reject- if (/[\x00-\x1F\x7F]/.test(docPath)) return false;- for (const segment of docPath.split('/')) {+ if (/[\x00-\x1F\x7F]/.test(path)) return false;+ for (const segment of path.split('/')) {if (segment.length === 0) return false;if (segment === '..' || segment === '.git') return false;}@@ -39,7 +39,8 @@ export function isValidBranchInfoDocPath(docPath: unknown): docPath is string {export async function computeBranchInfo(projectDir: string,targetBranch: string,- docPath: string,+ path: string,+ kind: 'doc' | 'folder',): Promise<BranchInfo> {const { git } = createGitInstance(projectDir);@@ -63,11 +64,12 @@ export async function computeBranchInfo(}})();- const shareFilePromise = headStatePromise.then(async (head) => {+ const shareTargetPromise = headStatePromise.then(async (head) => {+ if (kind === 'folder' && path === '') return true;const ref = head.detached ? 'HEAD' : head.currentBranch;if (!ref) return false;try {- await git.raw(['cat-file', '-e', `${ref}:${docPath}`]);+ await git.raw(['cat-file', '-e', `${ref}:${path}`]);return true;} catch {return false;@@ -91,9 +93,9 @@ export async function computeBranchInfo(},);- const [headState, shareFileExists, branchIsLocal, dirtyConflicts] = await Promise.all([+ const [headState, shareTargetExists, branchIsLocal, dirtyConflicts] = await Promise.all([headStatePromise,- shareFilePromise,+ shareTargetPromise,branchIsLocalPromise,dirtyPromise,]);@@ -103,7 +105,7 @@ export async function computeBranchInfo(detached: true,currentBranch: null,currentHeadSha: headState.currentHeadSha,- shareFileExists,+ shareTargetExists,dirtyConflicts,branchIsLocal,};@@ -112,7 +114,7 @@ export async function computeBranchInfo(detached: false,currentBranch: headState.currentBranch,currentHeadSha: null,- shareFileExists,+ shareTargetExists,dirtyConflicts,branchIsLocal,};diff --git a/packages/server/src/mcp/tools/share-link.test.ts b/packages/server/src/mcp/tools/share-link.test.tsindex 574ee6cc4..82244597f 100644--- a/packages/server/src/mcp/tools/share-link.test.ts+++ b/packages/server/src/mcp/tools/share-link.test.ts@@ -1,6 +1,6 @@import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, test } from 'bun:test';import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises';-import { tmpdir } from 'node:os';+import { hostname, tmpdir } from 'node:os';import { resolve } from 'node:path';import { type Config, ConfigSchema } from '../../config/schema.ts';import { register, type ShareLinkDeps } from './share-link.ts';@@ -18,14 +18,24 @@ interface ToolResult {interface RegisteredTool {name: string;description: string;- handler: (args: { docName: string; cwd?: string }) => Promise<ToolResult>;+ inputSchema?: Record<string, unknown>;+ handler: (args: { path: string; kind?: 'doc' | 'folder'; cwd?: string }) => Promise<ToolResult>;}function createFakeServer() {let registered: RegisteredTool | undefined;const server = {- registerTool(name: string, cfg: { description?: string }, handler: RegisteredTool['handler']) {- registered = { name, description: cfg.description ?? '', handler };+ registerTool(+ name: string,+ cfg: { description?: string; inputSchema?: Record<string, unknown> },+ handler: RegisteredTool['handler'],+ ) {+ registered = {+ name,+ description: cfg.description ?? '',+ inputSchema: cfg.inputSchema,+ handler,+ };},} as unknown as ServerInstance;return {@@ -37,6 +47,15 @@ function createFakeServer() {};}+function successBody() {+ return {+ ok: true,+ shareUrl: 'https://openknowledge.ai/d/encoded',+ sharedUrl: 'https://github.com/o/r/blob/main/notes.md',+ branch: 'main',+ };+}+let testServer: ReturnType<typeof Bun.serve>;let baseUrl: string;let tmpDir: string;@@ -91,6 +110,23 @@ function makeDeps(serverUrl: string | undefined): ShareLinkDeps {};}+async function writeUiLock(): Promise<void> {+ const lockDir = resolve(tmpDir, '.ok', 'local');+ await mkdir(lockDir, { recursive: true });+ await writeFile(+ resolve(lockDir, 'ui.lock'),+ JSON.stringify({+ pid: process.pid,+ hostname: hostname(),+ port: 5173,+ startedAt: new Date().toISOString(),+ worktreeRoot: tmpDir,+ protocolVersion: 1,+ runtimeVersion: '0.0.0-test',+ }),+ );+}+describe('share_link — registration + preconditions', () => {test('registers a single tool named `share_link`', () => {const { server, getTool } = createFakeServer();@@ -104,116 +140,317 @@ describe('share_link — registration + preconditions', () => {expect(getTool().description).toContain('Publishing is a user act');});+ test('description documents path/kind/cwd and that kind is required for empty path', () => {+ const { server, getTool } = createFakeServer();+ register(server, makeDeps(baseUrl));+ const desc = getTool().description;+ expect(desc).toContain('`path`');+ expect(desc).toContain('`kind`');+ expect(desc).toContain('`cwd`');+ expect(desc).toContain('auto-probe');+ expect(desc).toContain('REQUIRED when `path` is empty');+ });++ test('input schema is exactly {path, kind?, cwd?}', () => {+ const { server, getTool } = createFakeServer();+ register(server, makeDeps(baseUrl));+ const schema = getTool().inputSchema;+ expect(schema).toBeDefined();+ expect(Object.keys(schema as Record<string, unknown>).sort()).toEqual(['cwd', 'kind', 'path']);+ });+test('errors when Hocuspocus URL is unset', async () => {const { server, getTool } = createFakeServer();register(server, makeDeps(undefined));await writeFile(resolve(tmpDir, 'notes.md'), '# notes');- const result = await getTool().handler({ docName: 'notes' });+ const result = await getTool().handler({ path: 'notes' });expect(result.isError).toBe(true);expect(result.content[0]?.text).toBe(HOCUSPOCUS_NOT_RUNNING_ERROR);});});-describe('share_link — doc resolution', () => {- test('returns doc-not-found when neither `.md` nor `.mdx` exists', async () => {+describe('share_link — target resolution (FR9 matrix)', () => {+ test('(a) {path:notes} with notes.mdx on disk → success, resolvedKind doc', async () => {+ await writeFile(resolve(tmpDir, 'notes.mdx'), '# notes');+ mockResponse = { status: 200, body: successBody() };+ const { server, getTool } = createFakeServer();+ register(server, makeDeps(baseUrl));+ const result = await getTool().handler({ path: 'notes' });+ expect(result.isError).toBeUndefined();+ expect(result.structuredContent).toMatchObject({ ok: true, resolvedKind: 'doc' });+ expect(seenRequests[0]?.body).toEqual({ kind: 'doc', docPath: 'notes.mdx' });+ });++ test('(b) {path:guides} with guides/ directory → success, resolvedKind folder', async () => {+ await mkdir(resolve(tmpDir, 'guides'), { recursive: true });+ mockResponse = { status: 200, body: successBody() };+ const { server, getTool } = createFakeServer();+ register(server, makeDeps(baseUrl));+ const result = await getTool().handler({ path: 'guides' });+ expect(result.isError).toBeUndefined();+ expect(result.structuredContent).toMatchObject({ ok: true, resolvedKind: 'folder' });+ expect(seenRequests[0]?.body).toEqual({ kind: 'folder', folderPath: 'guides' });+ });++ test('(c) {path:guides, kind:doc} where guides is a directory → kind-mismatch', async () => {+ await mkdir(resolve(tmpDir, 'guides'), { recursive: true });+ const { server, getTool } = createFakeServer();+ register(server, makeDeps(baseUrl));+ const result = await getTool().handler({ path: 'guides', kind: 'doc' });+ expect(result.isError).toBe(true);+ expect(result.structuredContent).toMatchObject({ ok: false, error: 'kind-mismatch' });+ expect(seenRequests).toHaveLength(0);+ });++ test('(d) {path:"", kind:folder} → root share success, folderPath ""', async () => {+ mockResponse = {+ status: 200,+ body: {+ ok: true,+ shareUrl: 'https://openknowledge.ai/d/root',+ sharedUrl: 'https://github.com/o/r/tree/main',+ branch: 'main',+ },+ };+ const { server, getTool } = createFakeServer();+ register(server, makeDeps(baseUrl));+ const result = await getTool().handler({ path: '', kind: 'folder' });+ expect(result.isError).toBeUndefined();+ expect(result.structuredContent).toMatchObject({ ok: true, resolvedKind: 'folder' });+ expect(seenRequests[0]?.body).toEqual({ kind: 'folder', folderPath: '' });+ });++ test('(e1) {path:""} with no kind → invalid-path', async () => {const { server, getTool } = createFakeServer();register(server, makeDeps(baseUrl));- const result = await getTool().handler({ docName: 'missing' });+ const result = await getTool().handler({ path: '' });expect(result.isError).toBe(true);- expect(result.structuredContent).toMatchObject({ ok: false, error: 'doc-not-found' });+ expect(result.structuredContent).toMatchObject({ ok: false, error: 'invalid-path' });+ expect(seenRequests).toHaveLength(0);+ });++ test('(e2) {path:"", kind:doc} → invalid-path', async () => {+ const { server, getTool } = createFakeServer();+ register(server, makeDeps(baseUrl));+ const result = await getTool().handler({ path: '', kind: 'doc' });+ expect(result.isError).toBe(true);+ expect(result.structuredContent).toMatchObject({ ok: false, error: 'invalid-path' });+ expect(seenRequests).toHaveLength(0);+ });++ test('(f) {path:nope} nonexistent → target-not-found', async () => {+ const { server, getTool } = createFakeServer();+ register(server, makeDeps(baseUrl));+ const result = await getTool().handler({ path: 'nope' });+ expect(result.isError).toBe(true);+ expect(result.structuredContent).toMatchObject({ ok: false, error: 'target-not-found' });expect(result.content[0]?.text).toContain('does not exist');expect(seenRequests).toHaveLength(0);});- test('strips trailing `.md` from docName before probing', async () => {+ test('symmetric: {path:notes, kind:folder} where notes.mdx is a file → kind-mismatch', async () => {+ await writeFile(resolve(tmpDir, 'notes.mdx'), '# notes');+ const { server, getTool } = createFakeServer();+ register(server, makeDeps(baseUrl));+ const result = await getTool().handler({ path: 'notes', kind: 'folder' });+ expect(result.isError).toBe(true);+ expect(result.structuredContent).toMatchObject({ ok: false, error: 'kind-mismatch' });+ expect(seenRequests).toHaveLength(0);+ });++ test('strips trailing `.md` from a doc path before probing', async () => {await writeFile(resolve(tmpDir, 'notes.md'), '# notes');+ mockResponse = { status: 200, body: successBody() };+ const { server, getTool } = createFakeServer();+ register(server, makeDeps(baseUrl));+ const result = await getTool().handler({ path: 'notes.md' });+ expect(result.isError).toBeUndefined();+ expect(seenRequests[0]?.body).toEqual({ kind: 'doc', docPath: 'notes.md' });+ });++ test('auto-probe: `.mdx` wins over `.md` when both exist', async () => {+ await writeFile(resolve(tmpDir, 'collide.md'), '# md');+ await writeFile(resolve(tmpDir, 'collide.mdx'), '# mdx');+ mockResponse = { status: 200, body: successBody() };+ const { server, getTool } = createFakeServer();+ register(server, makeDeps(baseUrl));+ const result = await getTool().handler({ path: 'collide' });+ expect(result.isError).toBeUndefined();+ expect(seenRequests[0]?.body).toEqual({ kind: 'doc', docPath: 'collide.mdx' });+ });++ test('kind:doc resolves a `.md` doc when `.mdx` absent', async () => {+ await writeFile(resolve(tmpDir, 'guide.md'), '# guide');+ mockResponse = { status: 200, body: successBody() };+ const { server, getTool } = createFakeServer();+ register(server, makeDeps(baseUrl));+ const result = await getTool().handler({ path: 'guide', kind: 'doc' });+ expect(result.isError).toBeUndefined();+ expect(result.structuredContent).toMatchObject({ ok: true, resolvedKind: 'doc' });+ expect(seenRequests[0]?.body).toEqual({ kind: 'doc', docPath: 'guide.md' });+ });++ test('rejects paths escaping the content root as target-not-found', async () => {+ const { server, getTool } = createFakeServer();+ register(server, makeDeps(baseUrl));+ const result = await getTool().handler({ path: '../escaped' });+ expect(result.isError).toBe(true);+ expect(result.structuredContent).toMatchObject({ ok: false, error: 'target-not-found' });+ expect(seenRequests).toHaveLength(0);+ });+});++describe('share_link — happy path', () => {+ test('returns shareUrl + branch + sharedUrl + resolvedKind on doc success', async () => {+ await writeFile(resolve(tmpDir, 'meeting.md'), '# meeting');mockResponse = {status: 200,body: {ok: true,- shareUrl: 'https://openknowledge.ai/d/abc',- blobUrl: 'https://github.com/o/r/blob/main/notes.md',+ shareUrl: 'https://openknowledge.ai/d/encoded',+ sharedUrl: 'https://github.com/inkeep/wiki/blob/main/meeting.md',branch: 'main',},};const { server, getTool } = createFakeServer();register(server, makeDeps(baseUrl));- const result = await getTool().handler({ docName: 'notes.md' });+ const result = await getTool().handler({ path: 'meeting' });expect(result.isError).toBeUndefined();- expect(seenRequests[0]?.body).toEqual({ docPath: 'notes.md' });+ expect(result.structuredContent).toMatchObject({+ ok: true,+ shareUrl: 'https://openknowledge.ai/d/encoded',+ sharedUrl: 'https://github.com/inkeep/wiki/blob/main/meeting.md',+ branch: 'main',+ resolvedKind: 'doc',+ });+ expect(result.content[0]?.text).toContain('https://openknowledge.ai/d/encoded');+ expect(result.content[0]?.text).toContain('main');+ expect(result.content[0]?.text).toContain('doc');+ expect(result.content[0]?.text).toContain('meeting');});- test('probes `.mdx` when `.md` is absent', async () => {- await writeFile(resolve(tmpDir, 'guide.mdx'), '# guide');+ test('folder success text names the resolved folder + branch', async () => {+ await mkdir(resolve(tmpDir, 'guides'), { recursive: true });mockResponse = {status: 200,body: {ok: true,- shareUrl: 'https://openknowledge.ai/d/xyz',- blobUrl: 'https://github.com/o/r/blob/main/guide.mdx',+ shareUrl: 'https://openknowledge.ai/d/folder',+ sharedUrl: 'https://github.com/o/r/tree/main/guides',branch: 'main',},};const { server, getTool } = createFakeServer();register(server, makeDeps(baseUrl));- const result = await getTool().handler({ docName: 'guide' });+ const result = await getTool().handler({ path: 'guides', kind: 'folder' });expect(result.isError).toBeUndefined();- expect(seenRequests[0]?.body).toEqual({ docPath: 'guide.mdx' });+ expect(result.content[0]?.text).toContain('folder');+ expect(result.content[0]?.text).toContain('guides');});- test('`.mdx` wins over `.md` when both exist (matches SUPPORTED_DOC_EXTENSIONS precedence)', async () => {- await writeFile(resolve(tmpDir, 'collide.md'), '# md');- await writeFile(resolve(tmpDir, 'collide.mdx'), '# mdx');+ test('doc success previewUrl is the doc route `/#/<doc>` when a UI is running', async () => {+ await writeFile(resolve(tmpDir, 'meeting.md'), '# meeting');+ await writeUiLock();+ mockResponse = { status: 200, body: successBody() };+ const { server, getTool } = createFakeServer();+ register(server, makeDeps(baseUrl));+ const result = await getTool().handler({ path: 'meeting' });+ expect(result.isError).toBeUndefined();+ expect(result.structuredContent).toMatchObject({+ ok: true,+ resolvedKind: 'doc',+ previewUrl: '/#/meeting',+ });+ });++ test('folder success previewUrl is the trailing-slash folder route when a UI is running', async () => {+ await mkdir(resolve(tmpDir, 'guides'), { recursive: true });+ await writeUiLock();mockResponse = {status: 200,body: {ok: true,- shareUrl: 'https://openknowledge.ai/d/collide',- blobUrl: 'https://github.com/o/r/blob/main/collide.mdx',+ shareUrl: 'https://openknowledge.ai/d/folder',+ sharedUrl: 'https://github.com/o/r/tree/main/guides',branch: 'main',},};const { server, getTool } = createFakeServer();register(server, makeDeps(baseUrl));- const result = await getTool().handler({ docName: 'collide' });+ const result = await getTool().handler({ path: 'guides', kind: 'folder' });expect(result.isError).toBeUndefined();- expect(seenRequests[0]?.body).toEqual({ docPath: 'collide.mdx' });+ expect(result.structuredContent).toMatchObject({+ ok: true,+ resolvedKind: 'folder',+ previewUrl: '/#/guides/',+ });});- test('rejects paths escaping the content root', async () => {+ test('content-root folder success previewUrl is the root route `/#/`', async () => {+ await writeUiLock();+ mockResponse = {+ status: 200,+ body: {+ ok: true,+ shareUrl: 'https://openknowledge.ai/d/root',+ sharedUrl: 'https://github.com/o/r/tree/main',+ branch: 'main',+ },+ };const { server, getTool } = createFakeServer();register(server, makeDeps(baseUrl));- const result = await getTool().handler({ docName: '../escaped' });- expect(result.isError).toBe(true);- expect(result.content[0]?.text).toContain('invalid');- expect(seenRequests).toHaveLength(0);+ const result = await getTool().handler({ path: '', kind: 'folder' });+ expect(result.isError).toBeUndefined();+ expect(result.structuredContent).toMatchObject({+ ok: true,+ resolvedKind: 'folder',+ previewUrl: '/#/',+ });});-});-describe('share_link — happy path', () => {- test('returns shareUrl + branch + blobUrl on success', async () => {- await writeFile(resolve(tmpDir, 'meeting.md'), '# meeting');+ test('nested folder previewUrl encodes per segment with trailing slash', async () => {+ await mkdir(resolve(tmpDir, 'docs', 'api guide'), { recursive: true });+ await writeUiLock();mockResponse = {status: 200,body: {ok: true,- shareUrl: 'https://openknowledge.ai/d/encoded',- blobUrl: 'https://github.com/inkeep/wiki/blob/main/meeting.md',+ shareUrl: 'https://openknowledge.ai/d/nested',+ sharedUrl: 'https://github.com/o/r/tree/main/docs/api%20guide',branch: 'main',},};const { server, getTool } = createFakeServer();register(server, makeDeps(baseUrl));- const result = await getTool().handler({ docName: 'meeting' });+ const result = await getTool().handler({ path: 'docs/api guide', kind: 'folder' });expect(result.isError).toBeUndefined();expect(result.structuredContent).toMatchObject({ok: true,- shareUrl: 'https://openknowledge.ai/d/encoded',- blobUrl: 'https://github.com/inkeep/wiki/blob/main/meeting.md',- branch: 'main',+ resolvedKind: 'folder',+ previewUrl: '/#/docs/api%20guide/',+ });+ });++ test('folder previewUrl is null when no UI is running', async () => {+ await mkdir(resolve(tmpDir, 'guides'), { recursive: true });+ mockResponse = {+ status: 200,+ body: {+ ok: true,+ shareUrl: 'https://openknowledge.ai/d/folder',+ sharedUrl: 'https://github.com/o/r/tree/main/guides',+ branch: 'main',+ },+ };+ const { server, getTool } = createFakeServer();+ register(server, makeDeps(baseUrl));+ const result = await getTool().handler({ path: 'guides', kind: 'folder' });+ expect(result.isError).toBeUndefined();+ expect(result.structuredContent).toMatchObject({+ ok: true,+ resolvedKind: 'folder',+ previewUrl: null,});- expect(result.content[0]?.text).toContain('https://openknowledge.ai/d/encoded');- expect(result.content[0]?.text).toContain('main');});});@@ -223,7 +460,7 @@ describe('share_link — business-logic errors', () => {mockResponse = { status: 200, body: { ok: false, error: 'no-remote' } };const { server, getTool } = createFakeServer();register(server, makeDeps(baseUrl));- const result = await getTool().handler({ docName: 'page' });+ const result = await getTool().handler({ path: 'page' });expect(result.isError).toBe(true);expect(result.structuredContent).toMatchObject({ ok: false, error: 'no-remote' });const message = (result.structuredContent as { message: string }).message;@@ -237,7 +474,7 @@ describe('share_link — business-logic errors', () => {mockResponse = { status: 200, body: { ok: false, error: 'detached-head' } };const { server, getTool } = createFakeServer();register(server, makeDeps(baseUrl));- const result = await getTool().handler({ docName: 'page' });+ const result = await getTool().handler({ path: 'page' });expect(result.isError).toBe(true);expect(result.structuredContent).toMatchObject({ ok: false, error: 'detached-head' });expect((result.structuredContent as { message: string }).message).toContain('detached');@@ -251,7 +488,7 @@ describe('share_link — business-logic errors', () => {};const { server, getTool } = createFakeServer();register(server, makeDeps(baseUrl));- const result = await getTool().handler({ docName: 'page' });+ const result = await getTool().handler({ path: 'page' });expect(result.isError).toBe(true);expect(result.structuredContent).toMatchObject({ok: false,@@ -268,21 +505,25 @@ describe('share_link — business-logic errors', () => {mockResponse = { status: 200, body: { ok: false, error: 'non-github-remote' } };const { server, getTool } = createFakeServer();register(server, makeDeps(baseUrl));- const result = await getTool().handler({ docName: 'page' });+ const result = await getTool().handler({ path: 'page' });expect(result.isError).toBe(true);expect(result.structuredContent).toMatchObject({ ok: false, error: 'non-github-remote' });expect((result.structuredContent as { message: string }).message).toContain('GitHub');});- test('invalid-path: closed-enum coverage for the remaining business-error variant', async () => {+ test('invalid-path (server): reworded substrate-neutral (no "document")', async () => {await writeFile(resolve(tmpDir, 'page.md'), '# page');mockResponse = { status: 200, body: { ok: false, error: 'invalid-path' } };const { server, getTool } = createFakeServer();register(server, makeDeps(baseUrl));- const result = await getTool().handler({ docName: 'page' });+ const result = await getTool().handler({ path: 'page' });expect(result.isError).toBe(true);expect(result.structuredContent).toMatchObject({ ok: false, error: 'invalid-path' });- expect((result.structuredContent as { message: string }).message).toContain('not shareable');+ const message = (result.structuredContent as { message: string }).message;+ expect(message).toContain('not shareable');+ expect(message).toContain('resolved share path');+ expect(message).not.toContain('document');+ expect(message).not.toContain('Document');});test('branch-not-on-origin: message carries the stale-fetch recovery hint', async () => {@@ -293,7 +534,7 @@ describe('share_link — business-logic errors', () => {};const { server, getTool } = createFakeServer();register(server, makeDeps(baseUrl));- const result = await getTool().handler({ docName: 'page' });+ const result = await getTool().handler({ path: 'page' });expect(result.isError).toBe(true);const message = (result.structuredContent as { message: string }).message;expect(message).toContain('git fetch origin');@@ -303,12 +544,60 @@ describe('share_link — business-logic errors', () => {await writeFile(resolve(tmpDir, 'page.md'), '# page');const { server, getTool } = createFakeServer();register(server, makeDeps('http://127.0.0.1:1')); // unreachable- const result = await getTool().handler({ docName: 'page' });+ const result = await getTool().handler({ path: 'page' });expect(result.isError).toBe(true);expect((result.structuredContent as { ok: boolean }).ok).toBe(false);});});+describe('share_link — message coverage', () => {+ const SERVER_CODES = [+ 'no-remote',+ 'detached-head',+ 'branch-not-on-origin',+ 'non-github-remote',+ 'invalid-path',+ ] as const;++ for (const code of SERVER_CODES) {+ test(`server code ${code} → non-empty message`, async () => {+ await writeFile(resolve(tmpDir, 'page.md'), '# page');+ mockResponse = { status: 200, body: { ok: false, error: code } };+ const { server, getTool } = createFakeServer();+ register(server, makeDeps(baseUrl));+ const result = await getTool().handler({ path: 'page' });+ const message = (result.structuredContent as { message: string }).message;+ expect(typeof message).toBe('string');+ expect(message.length).toBeGreaterThan(0);+ });+ }++ test('target-not-found → non-empty message', async () => {+ const { server, getTool } = createFakeServer();+ register(server, makeDeps(baseUrl));+ const result = await getTool().handler({ path: 'nope' });+ const message = (result.structuredContent as { message: string }).message;+ expect(message.length).toBeGreaterThan(0);+ });++ test('kind-mismatch → non-empty message', async () => {+ await mkdir(resolve(tmpDir, 'guides'), { recursive: true });+ const { server, getTool } = createFakeServer();+ register(server, makeDeps(baseUrl));+ const result = await getTool().handler({ path: 'guides', kind: 'doc' });+ const message = (result.structuredContent as { message: string }).message;+ expect(message.length).toBeGreaterThan(0);+ });++ test('invalid-path (tool-local empty path) → non-empty message', async () => {+ const { server, getTool } = createFakeServer();+ register(server, makeDeps(baseUrl));+ const result = await getTool().handler({ path: '' });+ const message = (result.structuredContent as { message: string }).message;+ expect(message.length).toBeGreaterThan(0);+ });+});+describe('share_link — transport / protocol error paths', () => {test('non-JSON 200 body: tool-level error mentions the parse failure', async () => {await writeFile(resolve(tmpDir, 'page.md'), '# page');@@ -318,7 +607,7 @@ describe('share_link — transport / protocol error paths', () => {});const { server, getTool } = createFakeServer();register(server, makeDeps(baseUrl));- const result = await getTool().handler({ docName: 'page' });+ const result = await getTool().handler({ path: 'page' });expect(result.isError).toBe(true);expect(result.structuredContent).toMatchObject({ ok: false, error: 'unknown' });expect(result.content[0]?.text).toMatch(/non-JSON/i);@@ -337,7 +626,7 @@ describe('share_link — transport / protocol error paths', () => {);const { server, getTool } = createFakeServer();register(server, makeDeps(baseUrl));- const result = await getTool().handler({ docName: 'page' });+ const result = await getTool().handler({ path: 'page' });expect(result.isError).toBe(true);expect(result.content[0]?.text).toContain('Internal server error');expect(result.content[0]?.text).toContain('ENETUNREACH');@@ -355,7 +644,7 @@ describe('share_link — transport / protocol error paths', () => {);const { server, getTool } = createFakeServer();register(server, makeDeps(baseUrl));- const result = await getTool().handler({ docName: 'page' });+ const result = await getTool().handler({ path: 'page' });expect(result.isError).toBe(true);expect(result.content[0]?.text).toContain('Internal server error');expect(result.content[0]?.text).not.toContain('Internal server error:');@@ -374,7 +663,7 @@ describe('share_link — transport / protocol error paths', () => {);const { server, getTool } = createFakeServer();register(server, makeDeps(baseUrl));- const result = await getTool().handler({ docName: 'page' });+ const result = await getTool().handler({ path: 'page' });expect(result.isError).toBe(true);expect(result.content[0]?.text).toContain('ENETUNREACH');expect(result.content[0]?.text).not.toContain('HTTP 500');@@ -388,7 +677,7 @@ describe('share_link — transport / protocol error paths', () => {});const { server, getTool } = createFakeServer();register(server, makeDeps(baseUrl));- const result = await getTool().handler({ docName: 'page' });+ const result = await getTool().handler({ path: 'page' });expect(result.isError).toBe(true);expect(result.content[0]?.text).toContain('HTTP 503');});@@ -398,7 +687,7 @@ describe('share_link — transport / protocol error paths', () => {mockResponse = { status: 200, body: { unexpected: 'shape', no_ok_field: true } };const { server, getTool } = createFakeServer();register(server, makeDeps(baseUrl));- const result = await getTool().handler({ docName: 'page' });+ const result = await getTool().handler({ path: 'page' });expect(result.isError).toBe(true);expect(result.structuredContent).toMatchObject({ ok: false, error: 'unknown' });expect(result.content[0]?.text).toContain('unexpected share-construct-url response shape');diff --git a/packages/server/src/mcp/tools/share-link.ts b/packages/server/src/mcp/tools/share-link.tsindex 9db1fd577..dd8960db8 100644--- a/packages/server/src/mcp/tools/share-link.ts+++ b/packages/server/src/mcp/tools/share-link.ts@@ -1,4 +1,4 @@-import { existsSync } from 'node:fs';+import { existsSync, statSync } from 'node:fs';import { join } from 'node:path';import {type ShareConstructUrlErrorCode,@@ -6,11 +6,10 @@ import {} from '@inkeep/open-knowledge-core';import { z } from 'zod';import { resolveWithinRoot } from './path-safety.ts';-import { resolvePreviewUrlForTool } from './preview-url.ts';+import { encodeDocName, resolvePreviewUrlForTool } from './preview-url.ts';import type { ConfigOrResolver, ServerInstance, ServerUrlOrResolver } from './shared.ts';import {HOCUSPOCUS_NOT_RUNNING_ERROR,- normalizeDocName,outputSchemaWithText,ROUTED_CWD_DESCRIPTION,resolveProjectServerContext,@@ -18,15 +17,18 @@ import {textResult,} from './shared.ts';+type ShareKind = 'doc' | 'folder';+export const DESCRIPTION = [- "[Requires: Hocuspocus server] Build a shareable GitHub-substrate URL (`https://openknowledge.ai/d/...`) pinned to the project's current branch + the focused doc. Read-only against the working tree — no commits, no pushes, no `git fetch`.",+ "[Requires: Hocuspocus server] Build a shareable GitHub-substrate URL (`https://openknowledge.ai/d/...`) pinned to the project's current branch + the focused target (a doc or a folder). Read-only against the working tree — no commits, no pushes, no `git fetch`.",'',- 'Use this when the user asks for a share link / shareable link / URL to send to a teammate. Recipients open the link to receive the doc into their own Open Knowledge install.',+ 'Use this when the user asks for a share link / shareable link / URL to send to a teammate. Recipients open the link to receive the doc (or folder subtree) into their own Open Knowledge install.','','**Publishing is a user act.** Agents do NOT publish projects to GitHub from this tool. When the project has no GitHub remote, this tool returns an error pointing the user at the Share wizard (or `gh repo create` + `git push`) — it does not run those steps itself.','','**Parameters:**',- '- `docName` — Document name, extension-less. Trailing `.md`/`.mdx` is stripped; the on-disk file is probed automatically.',+ '- `path` — Content-dir-relative target. For a doc, extension-less (trailing `.md`/`.mdx` is stripped; the on-disk file is probed automatically). For a folder, the directory path. The empty string `""` is the content-root sentinel (folder-only).',+ "- `kind` (optional) — `'doc'` or `'folder'`. Omit to auto-probe disk (`.mdx` → `.md` → directory, first hit wins). REQUIRED when `path` is empty (`\"\"`), since auto-probe cannot disambiguate the root.",'- `cwd` (optional) — Project root (see `cwd` description below).','','**Preconditions:** project on a named branch (not detached HEAD); origin set to a `github.com` remote; the branch already pushed to origin.',@@ -41,13 +43,20 @@ export interface ShareLinkDeps {interface ShareLinkSuccess {ok: true;shareUrl: string;- blobUrl: string;+ sharedUrl: string;branch: string;+ resolvedKind: ShareKind;}+type ShareLinkErrorCode =+ | ShareConstructUrlErrorCode+ | 'target-not-found'+ | 'kind-mismatch'+ | 'unknown';+interface ShareLinkError {ok: false;- error: ShareConstructUrlErrorCode | 'doc-not-found' | 'unknown';+ error: ShareLinkErrorCode;message: string;branch?: string;}@@ -68,7 +77,7 @@ function messageForShareError(error: ShareConstructUrlErrorCode, branch?: stringcase 'non-github-remote':return 'Origin is not a `github.com` remote. Share links are GitHub-only in v1.';case 'invalid-path':- return 'The resolved document path is not shareable (escapes the project root or names the `.git` subtree). Pass a normal docName under the content directory.';+ return 'The resolved share path is not shareable (escapes the project root or names the `.git` subtree). Pass a normal target path under the content directory.';default: {const _exhaustive: never = error;return `Unknown share-construct-url error: ${String(_exhaustive)}`;@@ -76,15 +85,17 @@ function messageForShareError(error: ShareConstructUrlErrorCode, branch?: string}}-function resolveDocSharePath(- projectDir: string,- contentDir: string,- docName: string,-): string | null {- const contained = resolveWithinRoot(contentDir, docName);- if (!contained.ok) return null;+function isExistingDirectory(abs: string): boolean {+ try {+ return statSync(abs).isDirectory();+ } catch {+ return false;+ }+}++function resolveExistingDocPath(projectDir: string, absBase: string): string | null {for (const ext of ['.mdx', '.md'] as const) {- const absWithExt = `${contained.abs}${ext}`;+ const absWithExt = `${absBase}${ext}`;if (existsSync(absWithExt)) {const projectContained = resolveWithinRoot(projectDir, absWithExt);if (!projectContained.ok) return null;@@ -94,11 +105,61 @@ function resolveDocSharePath(return null;}+type ResolveShareTargetResult =+ | { ok: true; kind: ShareKind; sharePath: string }+ | { ok: false; code: 'target-not-found' | 'kind-mismatch' | 'invalid-path' };++function resolveShareTarget(+ projectDir: string,+ contentDir: string,+ path: string,+ kind?: ShareKind,+): ResolveShareTargetResult {+ if (path === '') {+ if (kind === 'folder') return { ok: true, kind: 'folder', sharePath: '' };+ return { ok: false, code: 'invalid-path' };+ }++ const contained = resolveWithinRoot(contentDir, path);+ if (!contained.ok) return { ok: false, code: 'target-not-found' };++ const docBase = contained.abs.replace(/\.(mdx|md)$/i, '');+ const docPath = resolveExistingDocPath(projectDir, docBase);+ const dirExists = isExistingDirectory(contained.abs);++ if (kind === 'doc') {+ if (docPath !== null) return { ok: true, kind: 'doc', sharePath: docPath };+ if (dirExists) return { ok: false, code: 'kind-mismatch' };+ return { ok: false, code: 'target-not-found' };+ }+ if (kind === 'folder') {+ if (dirExists) {+ const folderContained = resolveWithinRoot(projectDir, contained.abs);+ if (!folderContained.ok) return { ok: false, code: 'target-not-found' };+ return { ok: true, kind: 'folder', sharePath: folderContained.rel };+ }+ if (docPath !== null) return { ok: false, code: 'kind-mismatch' };+ return { ok: false, code: 'target-not-found' };+ }++ if (docPath !== null) return { ok: true, kind: 'doc', sharePath: docPath };+ if (dirExists) {+ const folderContained = resolveWithinRoot(projectDir, contained.abs);+ if (!folderContained.ok) return { ok: false, code: 'target-not-found' };+ return { ok: true, kind: 'folder', sharePath: folderContained.rel };+ }+ return { ok: false, code: 'target-not-found' };+}+const OutputSchema = outputSchemaWithText({ok: z.boolean().describe('Success discriminator.'),shareUrl: z.string().optional().describe('Marketing share URL (success only).'),- blobUrl: z.string().optional().describe('Unencoded GitHub blob URL (success only).'),+ sharedUrl: z.string().optional().describe('Unencoded GitHub blob/tree URL (success only).'),branch: z.string().optional().describe('Branch the share URL pins to (success only).'),+ resolvedKind: z+ .enum(['doc', 'folder'])+ .optional()+ .describe('Kind the target resolved to (success only).'),error: z.enum(['no-remote',@@ -106,7 +167,8 @@ const OutputSchema = outputSchemaWithText({'branch-not-on-origin','non-github-remote','invalid-path',- 'doc-not-found',+ 'target-not-found',+ 'kind-mismatch','unknown',]).optional()@@ -116,7 +178,9 @@ const OutputSchema = outputSchemaWithText({.string().nullable().optional()- .describe('Route-only preview URL `/#/<doc>` (no host:port). `null` when no UI is running.'),+ .describe(+ 'Route-only preview URL (no host:port): `/#/<doc>` for a doc, `/#/<folder>/` for a folder, `/#/` for the content root. `null` when no UI is running.',+ ),previewUrlSource: z.string().optional().describe('Internal: preview-URL provenance.'),});@@ -126,9 +190,17 @@ export function register(server: ServerInstance, deps: ShareLinkDeps): void {{description: DESCRIPTION,inputSchema: {- docName: z+ path: z.string()- .describe('Document to share, extension-less. Trailing `.md`/`.mdx` is stripped.'),+ .describe(+ 'Content-dir-relative target. Doc paths are extension-less (`.md`/`.mdx` stripped). Folder paths name a directory. `""` is the content-root sentinel (folder-only).',+ ),+ kind: z+ .enum(['doc', 'folder'])+ .optional()+ .describe(+ 'Target kind. Omit to auto-probe disk (`.mdx` → `.md` → directory). REQUIRED when `path` is empty.',+ ),cwd: z.string().optional().describe(ROUTED_CWD_DESCRIPTION),},outputSchema: OutputSchema,@@ -137,7 +209,7 @@ export function register(server: ServerInstance, deps: ShareLinkDeps): void {idempotentHint: true,},},- async (args: { docName: string; cwd?: string }) => {+ async (args: { path: string; kind?: ShareKind; cwd?: string }) => {const context = await resolveProjectServerContext(deps.resolveCwd,deps.config,@@ -148,26 +220,34 @@ export function register(server: ServerInstance, deps: ShareLinkDeps): void {const { cwd, config, url } = context;if (!url) return textResult(HOCUSPOCUS_NOT_RUNNING_ERROR, true);- const normalized = normalizeDocName(args.docName);- if (!normalized.ok) return textResult(normalized.error, true);-const contentDir = join(cwd, config.content.dir);- const docPath = resolveDocSharePath(cwd, contentDir, normalized.docName);- if (docPath === null) {- const structured: ShareLinkError = {- ok: false,- error: 'doc-not-found',- message: `Document \`${normalized.docName}\` does not exist under the content directory (looked for \`.md\` and \`.mdx\`).`,- };- return textPlusStructured(`Error: ${structured.message}`, structured, true);+ const resolved = resolveShareTarget(cwd, contentDir, args.path, args.kind);+ if (!resolved.ok) {+ let message: string;+ if (resolved.code === 'kind-mismatch') {+ const requestedKind: ShareKind = args.kind === 'folder' ? 'folder' : 'doc';+ message = `\`${args.path}\` exists, but not as a ${requestedKind}. Pass \`kind: '${requestedKind === 'doc' ? 'folder' : 'doc'}'\` to share it as the other kind.`;+ } else if (resolved.code === 'invalid-path') {+ message =+ 'Cannot share the content root from an empty path without `kind: "folder"`. Pass a non-empty path, or `kind: "folder"` to share the root.';+ } else {+ message = `Target \`${args.path}\` does not exist under the content directory (looked for \`.md\`, \`.mdx\`, and a directory).`;+ }+ const structured: ShareLinkError = { ok: false, error: resolved.code, message };+ return textPlusStructured(`Error: ${message}`, structured, true);}+ const requestBody =+ resolved.kind === 'doc'+ ? { kind: 'doc' as const, docPath: resolved.sharePath }+ : { kind: 'folder' as const, folderPath: resolved.sharePath };+let res: Response;try {res = await fetch(`${url}/api/share/construct-url`, {method: 'POST',headers: { 'Content-Type': 'application/json' },- body: JSON.stringify({ docPath }),+ body: JSON.stringify(requestBody),signal: AbortSignal.timeout(30_000),});} catch (err) {@@ -237,15 +317,28 @@ export function register(server: ServerInstance, deps: ShareLinkDeps): void {return textPlusStructured(`Error: ${message}`, structured, true);}- const { shareUrl, blobUrl, branch } = body;- const structured: ShareLinkSuccess = { ok: true, shareUrl, blobUrl, branch };- const preview = await resolvePreviewUrlForTool(- normalized.docName,- { config: deps.config, resolveCwd: deps.resolveCwd },+ const { shareUrl, sharedUrl, branch } = body;+ const structured: ShareLinkSuccess = {+ ok: true,+ shareUrl,+ sharedUrl,+ branch,+ resolvedKind: resolved.kind,+ };+ const previewDeps = { config: deps.config, resolveCwd: deps.resolveCwd };+ let preview = await resolvePreviewUrlForTool(+ resolved.sharePath.replace(/\.(mdx|md)$/i, ''),+ previewDeps,cwd,);+ if (preview && resolved.kind === 'folder') {+ const normalized = resolved.sharePath.replace(/^\/+|\/+$/g, '');+ const folderRoute = normalized === '' ? '/#/' : `/#/${encodeDocName(normalized)}/`;+ preview = { ...preview, url: folderRoute };+ }+ const displayPath = args.path === '' ? '(content root)' : args.path;return textPlusStructured(- `Share link for \`${normalized.docName}\` on branch \`${branch}\`:\n${shareUrl}`,+ `Share link for ${resolved.kind} \`${displayPath}\` on branch \`${branch}\`:\n${shareUrl}`,{...structured,previewUrl: preview?.url ?? null,diff --git a/packages/server/src/share/construct-url.test.ts b/packages/server/src/share/construct-url.test.tsindex 2bfe308ff..f923ad226 100644--- a/packages/server/src/share/construct-url.test.ts+++ b/packages/server/src/share/construct-url.test.ts@@ -5,7 +5,13 @@ import type { Server } from 'node:http';import { tmpdir } from 'node:os';import { join } from 'node:path';import { decodeShareUrl } from '@inkeep/open-knowledge-core';-import { buildGitHubBlobUrl } from './construct-url.ts';+import { loggerFactory, PinoLogger } from '../logger.ts';+import {+ buildGitHubBlobUrl,+ buildGitHubTreeUrl,+ emitShareConstructUrlLog,+ isValidSharePath,+} from './construct-url.ts';interface TestRig {port: number;@@ -14,10 +20,17 @@ interface TestRig {cleanup: () => Promise<void>;}-async function bootRig(initProject?: (projectDir: string) => void): Promise<TestRig> {+async function bootRig(+ initProject?: (projectDir: string) => void,+ opts?: { contentDirIsRoot?: boolean; contentDirEscapes?: boolean },+): Promise<TestRig> {const tmpRoot = await mkdtemp(join(tmpdir(), 'share-construct-url-'));const projectDir = join(tmpRoot, 'project');- const contentDir = join(projectDir, 'content');+ const contentDir = opts?.contentDirEscapes+ ? join(tmpRoot, 'escaped-content')+ : opts?.contentDirIsRoot+ ? projectDir+ : join(projectDir, 'content');mkdirSync(contentDir, { recursive: true });initProject?.(projectDir);@@ -110,18 +123,18 @@ describe('POST /api/share/construct-url', () => {branchesOnOrigin: ['main'],});});- const res = await postConstructUrl(rig.port, { docPath: 'docs/guide.md' });+ const res = await postConstructUrl(rig.port, { kind: 'doc', docPath: 'docs/guide.md' });expect(res.status).toBe(200);const json = (await res.json()) as Record<string, unknown>;expect(json.ok).toBe(true);expect(json.branch).toBe('main');- expect(json.blobUrl).toBe('https://github.com/inkeep/open-knowledge/blob/main/docs/guide.md');+ expect(json.sharedUrl).toBe('https://github.com/inkeep/open-knowledge/blob/main/docs/guide.md');expect(typeof json.shareUrl).toBe('string');expect(json.shareUrl).toMatch(/^https:\/\/openknowledge\.ai\/d\/[A-Za-z0-9_-]+$/);const encoded = (json.shareUrl as string).replace('https://openknowledge.ai/d/', '');const decoded = decodeShareUrl(encoded);expect(decoded.version).toBe(1);- expect(decoded.blobUrl).toBe(+ expect(decoded.sharedUrl).toBe('https://github.com/inkeep/open-knowledge/blob/main/docs/guide.md',);});@@ -133,7 +146,7 @@ describe('POST /api/share/construct-url', () => {writeFileSync(join(gitDir, 'HEAD'), 'ref: refs/heads/main\n');writeFileSync(join(gitDir, 'config'), '[core]\n\trepositoryformatversion = 0\n');});- const res = await postConstructUrl(rig.port, { docPath: 'a.md' });+ const res = await postConstructUrl(rig.port, { kind: 'doc', docPath: 'a.md' });expect(res.status).toBe(200);const json = await res.json();expect(json).toEqual({ ok: false, error: 'no-remote' });@@ -147,7 +160,7 @@ describe('POST /api/share/construct-url', () => {branchesOnOrigin: ['main'],});});- const res = await postConstructUrl(rig.port, { docPath: 'a.md' });+ const res = await postConstructUrl(rig.port, { kind: 'doc', docPath: 'a.md' });expect(res.status).toBe(200);const json = await res.json();expect(json).toEqual({ ok: false, error: 'detached-head' });@@ -161,7 +174,7 @@ describe('POST /api/share/construct-url', () => {branchesOnOrigin: ['main'],});});- const res = await postConstructUrl(rig.port, { docPath: 'a.md' });+ const res = await postConstructUrl(rig.port, { kind: 'doc', docPath: 'a.md' });expect(res.status).toBe(200);const json = await res.json();expect(json).toEqual({@@ -179,7 +192,7 @@ describe('POST /api/share/construct-url', () => {branchesOnOrigin: ['main'],});});- const res = await postConstructUrl(rig.port, { docPath: 'a.md' });+ const res = await postConstructUrl(rig.port, { kind: 'doc', docPath: 'a.md' });expect(res.status).toBe(200);const json = await res.json();expect(json).toEqual({ ok: false, error: 'non-github-remote' });@@ -193,7 +206,7 @@ describe('POST /api/share/construct-url', () => {branchesOnOrigin: ['main'],});});- const res = await postConstructUrl(rig.port, { docPath: 'docs/../etc/passwd' });+ const res = await postConstructUrl(rig.port, { kind: 'doc', docPath: 'docs/../etc/passwd' });expect(res.status).toBe(200);const json = await res.json();expect(json).toEqual({ ok: false, error: 'invalid-path' });@@ -207,7 +220,7 @@ describe('POST /api/share/construct-url', () => {branchesOnOrigin: ['main'],});});- const res = await postConstructUrl(rig.port, { docPath: '.git/HEAD' });+ const res = await postConstructUrl(rig.port, { kind: 'doc', docPath: '.git/HEAD' });expect(res.status).toBe(200);const json = await res.json();expect(json).toEqual({ ok: false, error: 'invalid-path' });@@ -221,7 +234,7 @@ describe('POST /api/share/construct-url', () => {branchesOnOrigin: ['main'],});});- const res = await postConstructUrl(rig.port, { docPath: '/etc/passwd' });+ const res = await postConstructUrl(rig.port, { kind: 'doc', docPath: '/etc/passwd' });expect(res.status).toBe(200);const json = await res.json();expect(json).toEqual({ ok: false, error: 'invalid-path' });@@ -236,16 +249,16 @@ describe('POST /api/share/construct-url', () => {});});const docPath = 'docs/Q4 OKRs — Marketing.md';- const res = await postConstructUrl(rig.port, { docPath });+ const res = await postConstructUrl(rig.port, { kind: 'doc', docPath });expect(res.status).toBe(200);const json = (await res.json()) as Record<string, unknown>;expect(json.ok).toBe(true);- expect(json.blobUrl).toBe(+ expect(json.sharedUrl).toBe(`https://github.com/inkeep/open-knowledge/blob/main/${encodeURIComponent('Q4 OKRs — Marketing.md').replace(/^/, 'docs/')}`,);const encoded = (json.shareUrl as string).replace('https://openknowledge.ai/d/', '');const decoded = decodeShareUrl(encoded);- const decodedUrl = new URL(decoded.blobUrl);+ const decodedUrl = new URL(decoded.sharedUrl);const segments = decodedUrl.pathname.split('/');expect(segments.slice(0, 5)).toEqual(['', 'inkeep', 'open-knowledge', 'blob', 'main']);const decodedDocPath = segments@@ -263,16 +276,16 @@ describe('POST /api/share/construct-url', () => {branchesOnOrigin: ['feat/sharing-virality-flow'],});});- const res = await postConstructUrl(rig.port, { docPath: 'docs/guide.md' });+ const res = await postConstructUrl(rig.port, { kind: 'doc', docPath: 'docs/guide.md' });expect(res.status).toBe(200);const json = (await res.json()) as Record<string, unknown>;expect(json.ok).toBe(true);expect(json.branch).toBe('feat/sharing-virality-flow');- expect(json.blobUrl).toBe(+ expect(json.sharedUrl).toBe('https://github.com/inkeep/open-knowledge/blob/feat%2Fsharing-virality-flow/docs/guide.md',);- const blobUrl = new URL(json.blobUrl as string);- const segments = blobUrl.pathname.split('/').filter(Boolean);+ const sharedUrl = new URL(json.sharedUrl as string);+ const segments = sharedUrl.pathname.split('/').filter(Boolean);expect(segments[2]).toBe('blob');expect(decodeURIComponent(segments[3])).toBe('feat/sharing-virality-flow');});@@ -289,7 +302,7 @@ describe('POST /api/share/construct-url', () => {expect(res.status).toBe(405);});- test('rejects body without docPath with 400', async () => {+ test('rejects body without kind with 400 (discriminated union)', async () => {rig = await bootRig((projectDir) => {seedRemoteAndHead(projectDir, {head: 'ref: refs/heads/main\n',@@ -300,6 +313,99 @@ describe('POST /api/share/construct-url', () => {const res = await postConstructUrl(rig.port, {});expect(res.status).toBe(400);});++ test('rejects bare {docPath} (no kind discriminator) with 400', async () => {+ rig = await bootRig((projectDir) => {+ seedRemoteAndHead(projectDir, {+ head: 'ref: refs/heads/main\n',+ originUrl: 'https://github.com/inkeep/open-knowledge.git',+ branchesOnOrigin: ['main'],+ });+ });+ const res = await postConstructUrl(rig.port, { docPath: 'a.md' });+ expect(res.status).toBe(400);+ });++ test('rejects kind-incompatible shape (doc without docPath) with 400', async () => {+ rig = await bootRig((projectDir) => {+ seedRemoteAndHead(projectDir, {+ head: 'ref: refs/heads/main\n',+ originUrl: 'https://github.com/inkeep/open-knowledge.git',+ branchesOnOrigin: ['main'],+ });+ });+ const res = await postConstructUrl(rig.port, { kind: 'doc', folderPath: 'docs' });+ expect(res.status).toBe(400);+ });++ test('folder kind with a path: returns encoded tree URL', async () => {+ rig = await bootRig((projectDir) => {+ seedRemoteAndHead(projectDir, {+ head: 'ref: refs/heads/main\n',+ originUrl: 'https://github.com/inkeep/open-knowledge.git',+ branchesOnOrigin: ['main'],+ });+ });+ const res = await postConstructUrl(rig.port, { kind: 'folder', folderPath: 'docs/guides' });+ expect(res.status).toBe(200);+ const json = (await res.json()) as Record<string, unknown>;+ expect(json.ok).toBe(true);+ expect(json.branch).toBe('main');+ expect(json.sharedUrl).toBe('https://github.com/inkeep/open-knowledge/tree/main/docs/guides');+ const encoded = (json.shareUrl as string).replace('https://openknowledge.ai/d/', '');+ const decoded = decodeShareUrl(encoded);+ expect(decoded.sharedUrl).toBe(+ 'https://github.com/inkeep/open-knowledge/tree/main/docs/guides',+ );+ });++ test('folder ROOT (folderPath: "") with content.dir === "." degenerates to tree/<branch>', async () => {+ rig = await bootRig(+ (projectDir) => {+ seedRemoteAndHead(projectDir, {+ head: 'ref: refs/heads/main\n',+ originUrl: 'https://github.com/inkeep/open-knowledge.git',+ branchesOnOrigin: ['main'],+ });+ },+ { contentDirIsRoot: true },+ );+ const res = await postConstructUrl(rig.port, { kind: 'folder', folderPath: '' });+ expect(res.status).toBe(200);+ const json = (await res.json()) as Record<string, unknown>;+ expect(json.ok).toBe(true);+ expect(json.sharedUrl).toBe('https://github.com/inkeep/open-knowledge/tree/main');+ });++ test('folder ROOT (folderPath: "") with content.dir subdir maps to tree/<branch>/<content.dir>', async () => {+ rig = await bootRig((projectDir) => {+ seedRemoteAndHead(projectDir, {+ head: 'ref: refs/heads/main\n',+ originUrl: 'https://github.com/inkeep/open-knowledge.git',+ branchesOnOrigin: ['main'],+ });+ });+ const res = await postConstructUrl(rig.port, { kind: 'folder', folderPath: '' });+ expect(res.status).toBe(200);+ const json = (await res.json()) as Record<string, unknown>;+ expect(json.ok).toBe(true);+ expect(json.sharedUrl).toBe('https://github.com/inkeep/open-knowledge/tree/main/content');+ });++ test('folder ROOT (folderPath: "") with contentDir escaping projectDir fails loud (500), not a repo-root link', async () => {+ rig = await bootRig(+ (projectDir) => {+ seedRemoteAndHead(projectDir, {+ head: 'ref: refs/heads/main\n',+ originUrl: 'https://github.com/inkeep/open-knowledge.git',+ branchesOnOrigin: ['main'],+ });+ },+ { contentDirEscapes: true },+ );+ const res = await postConstructUrl(rig.port, { kind: 'folder', folderPath: '' });+ expect(res.status).toBe(500);+ });});describe('buildGitHubBlobUrl branch encoding', () => {@@ -357,3 +463,129 @@ describe('buildGitHubBlobUrl branch encoding', () => {);});});++describe('buildGitHubTreeUrl', () => {+ function extractBranchSegment(url: string): string {+ const segments = new URL(url).pathname.split('/').filter(Boolean);+ return segments[3];+ }++ test('folder path: segments encoded individually, no trailing slash', () => {+ const url = buildGitHubTreeUrl('owner', 'repo', 'main', 'docs/sub folder');+ expect(url).toBe('https://github.com/owner/repo/tree/main/docs/sub%20folder');+ expect(url.endsWith('/')).toBe(false);+ });++ test('slashed branch encodes slash as %2F (single URL segment)', () => {+ const url = buildGitHubTreeUrl('owner', 'repo', 'feat/foo', 'docs');+ expect(url).toBe('https://github.com/owner/repo/tree/feat%2Ffoo/docs');+ expect(extractBranchSegment(url)).toBe('feat%2Ffoo');+ expect(decodeURIComponent(extractBranchSegment(url))).toBe('feat/foo');+ });++ test('empty folderPath (root) -> tree/<branch> with no trailing slash', () => {+ const url = buildGitHubTreeUrl('owner', 'repo', 'main', '');+ expect(url).toBe('https://github.com/owner/repo/tree/main');+ expect(url.endsWith('/')).toBe(false);+ });++ test('empty folderPath with slashed branch encodes branch, no trailing slash', () => {+ const url = buildGitHubTreeUrl('owner', 'repo', 'feat/foo', '');+ expect(url).toBe('https://github.com/owner/repo/tree/feat%2Ffoo');+ });+});++describe('isValidSharePath (kind-aware)', () => {+ test('empty path: valid for folder (root), invalid for doc', () => {+ expect(isValidSharePath('', 'folder')).toBe(true);+ expect(isValidSharePath('', 'doc')).toBe(false);+ });++ test('nested path: valid for both kinds', () => {+ expect(isValidSharePath('a/b', 'folder')).toBe(true);+ expect(isValidSharePath('a/b', 'doc')).toBe(true);+ });++ test('leading slash rejected for both kinds', () => {+ expect(isValidSharePath('/a/b', 'doc')).toBe(false);+ expect(isValidSharePath('/a/b', 'folder')).toBe(false);+ });++ test('leading backslash rejected', () => {+ expect(isValidSharePath('\\a', 'doc')).toBe(false);+ });++ test('.. segment rejected', () => {+ expect(isValidSharePath('docs/../etc', 'doc')).toBe(false);+ expect(isValidSharePath('docs/../etc', 'folder')).toBe(false);+ });++ test('.git segment rejected', () => {+ expect(isValidSharePath('.git/HEAD', 'doc')).toBe(false);+ expect(isValidSharePath('a/.git/b', 'folder')).toBe(false);+ });++ test('.ok and .github dot-folders allowed (gate is .git-only per D21)', () => {+ expect(isValidSharePath('.ok/config.yml', 'doc')).toBe(true);+ expect(isValidSharePath('.github/workflows', 'folder')).toBe(true);+ expect(isValidSharePath('.ok', 'folder')).toBe(true);+ });++ test('empty intermediate segment (a//b) rejected', () => {+ expect(isValidSharePath('a//b', 'doc')).toBe(false);+ expect(isValidSharePath('a//b', 'folder')).toBe(false);+ });++ test('control chars rejected for both kinds (symmetry with isValidBranchInfoPath)', () => {+ expect(isValidSharePath('a\x00b', 'doc')).toBe(false);+ expect(isValidSharePath('a\x00b', 'folder')).toBe(false);+ expect(isValidSharePath('a\tb', 'doc')).toBe(false);+ expect(isValidSharePath('a\tb', 'folder')).toBe(false);+ expect(isValidSharePath('a\x7Fb', 'doc')).toBe(false);+ });+});++describe('emitShareConstructUrlLog telemetry', () => {+ function captureLog(emit: () => void): Array<Record<string, unknown>> {+ const records: Array<Record<string, unknown>> = [];+ loggerFactory.configure({+ loggerFactory: (name: string) => {+ const logger = new PinoLogger(name, { options: { level: 'silent' } });+ logger.info = (data: unknown) => {+ records.push(data as Record<string, unknown>);+ };+ return logger;+ },+ });+ try {+ emit();+ } finally {+ loggerFactory.reset();+ }+ return records;+ }++ test('carries bounded kind attribute on success', () => {+ const records = captureLog(() =>+ emitShareConstructUrlLog('ok', { branchExists: true, kind: 'folder' }),+ );+ expect(records).toHaveLength(1);+ expect(records[0]).toMatchObject({+ action: 'construct-url',+ result: 'ok',+ branchExists: true,+ kind: 'folder',+ });+ });++ test('carries kind on a business-logic failure', () => {+ const records = captureLog(() => emitShareConstructUrlLog('invalid-path', { kind: 'doc' }));+ expect(records[0]).toMatchObject({ result: 'invalid-path', kind: 'doc' });+ });++ test('omits kind + branchExists when opts absent', () => {+ const records = captureLog(() => emitShareConstructUrlLog('no-remote'));+ expect(records[0]).not.toHaveProperty('kind');+ expect(records[0]).not.toHaveProperty('branchExists');+ });+});diff --git a/packages/server/src/share/construct-url.ts b/packages/server/src/share/construct-url.tsindex f9423bd37..e24ebea62 100644--- a/packages/server/src/share/construct-url.ts+++ b/packages/server/src/share/construct-url.ts@@ -5,10 +5,13 @@ export const SHARE_BASE_URL = 'https://openknowledge.ai/d/';export const SHARE_CONSTRUCT_URL_HANDLER_TAG = 'share-construct-url';-export function isValidShareDocPath(docPath: string): boolean {- if (docPath.length === 0) return false;- if (docPath.startsWith('/') || docPath.startsWith('\\')) return false;- for (const segment of docPath.split(/[/\\]/)) {+export function isValidSharePath(path: string, kind: 'doc' | 'folder'): boolean {+ if (path === '') return kind === 'folder';+ if (path.startsWith('/')) return false;+ if (path.includes('\\')) return false;+ // biome-ignore lint/suspicious/noControlCharactersInRegex: control chars are exactly what we want to reject+ if (/[\x00-\x1F\x7F]/.test(path)) return false;+ for (const segment of path.split('/')) {if (segment === '..' || segment === '.git') return false;if (segment.length === 0) return false;}@@ -26,12 +29,32 @@ export function buildGitHubBlobUrl(return `https://github.com/${owner}/${repo}/blob/${encodedBranch}/${encodedSegments}`;}+export function buildGitHubTreeUrl(+ owner: string,+ repo: string,+ branch: string,+ folderPath: string,+): string {+ const encodedBranch = encodeURIComponent(branch);+ const base = `https://github.com/${owner}/${repo}/tree/${encodedBranch}`;+ if (folderPath === '') return base;+ const encodedSegments = folderPath.split('/').map(encodeURIComponent).join('/');+ return `${base}/${encodedSegments}`;+}+export function emitShareConstructUrlLog(result: 'ok' | ShareConstructUrlErrorCode,- branchExists?: boolean,+ opts?: { branchExists?: boolean; kind?: 'doc' | 'folder' },): void {+ const branchExists = opts?.branchExists;+ const kind = opts?.kind;getLogger('share').info(- { action: 'construct-url', result, ...(branchExists === undefined ? {} : { branchExists }) },+ {+ action: 'construct-url',+ result,+ ...(branchExists === undefined ? {} : { branchExists }),+ ...(kind === undefined ? {} : { kind }),+ },'share action',);}