Beautiful, AI-native markdown IDE and LLM wiki
TypeScript 2nd-brainagent-skillsclaudecodexcompany-braindocsknowledge-knowledge-baseknowledge-managementllmllm-wikillm-wiki-karpathymarkdownmarkdown-editormdmdxnotespkmsecond-brainskills
fix(ok): keep folders out of the wikilink picker (PRD-7932) (#3431)
Abraham80325a7bdf24
diff --git a/.changeset/wikilink-picker-no-folders.md b/.changeset/wikilink-picker-no-folders.mdnew file mode 100644index 000000000..44bd62ae3--- /dev/null+++ b/.changeset/wikilink-picker-no-folders.md@@ -0,0 +1,5 @@+---+'@inkeep/open-knowledge': patch+---++Folders no longer appear in the `[[` wiki-link picker. The shared suggestion corpus gained folder entries for the composer's `@` attach picker, and the wiki-link pickers were dressing them up as pages — selecting one inserted a link that opened the folder path as a document. Folders are now opt-in on the corpus fetch (only the composer asks for them) and the wiki-link item builder refuses folder rows outright. Proper folder links are tracked separately (PRD-7956).diff --git a/packages/app/src/editor/composer-mention/composer-mention.test.ts b/packages/app/src/editor/composer-mention/composer-mention.test.tsindex 0d56f356c..53d7c7561 100644--- a/packages/app/src/editor/composer-mention/composer-mention.test.ts+++ b/packages/app/src/editor/composer-mention/composer-mention.test.ts@@ -1,4 +1,5 @@-import { describe, expect, test } from 'vitest';+import { afterEach, describe, expect, test, vi } from 'vitest';+import { __resetDocumentListInflightForTests } from '@/lib/documents-fetch';import type { PageItem } from '../extensions/wiki-link-suggestion';import { createMentionCorpus, pageItemToPath } from './composer-mention';@@ -29,6 +30,49 @@ describe('pageItemToPath', () => {});});+describe('createMentionCorpus — default corpus', () => {+ const realFetch = globalThis.fetch;++ afterEach(() => {+ globalThis.fetch = realFetch;+ __resetDocumentListInflightForTests();+ });++ test('the default fetch opts into folders — the composer is the one folder consumer', async () => {+ // Pins createMentionCorpus's default argument, not an injected stub:+ // fetchPages excludes folders unless asked, and the composer must keep+ // asking so folders stay attachable as chips.+ globalThis.fetch = vi.fn(async (input: RequestInfo | URL) => {+ const url = typeof input === 'string' ? input : input.toString();+ const body = url.startsWith('/api/pages')+ ? {+ pages: [+ {+ docName: 'notes',+ title: 'Notes',+ docExt: '.md',+ size: 1,+ modified: '2026-06-24T00:00:00.000Z',+ },+ ],+ }+ : {+ documents: [+ { kind: 'folder', path: 'specs/foo', size: 0, modified: '2026-06-24T00:00:00.000Z' },+ ],+ };+ return new Response(JSON.stringify(body), {+ status: 200,+ headers: { 'content-type': 'application/json' },+ });+ }) as typeof globalThis.fetch;++ const corpus = createMentionCorpus();+ const items = await corpus.getItems('');+ expect(items.map((item) => item.path)).toEqual(['notes.md', 'specs/foo']);+ });+});+describe('createMentionCorpus — fetch retry contract', () => {const PAGE: PageItem = { kind: 'page', docName: 'notes', title: 'Notes' };diff --git a/packages/app/src/editor/composer-mention/composer-mention.ts b/packages/app/src/editor/composer-mention/composer-mention.tsindex 117ba397f..aa77fa746 100644--- a/packages/app/src/editor/composer-mention/composer-mention.ts+++ b/packages/app/src/editor/composer-mention/composer-mention.ts@@ -309,7 +309,12 @@ export interface MentionCorpusSnapshot {* rather than locking the corpus empty for the whole session. `reset()` (called* on menu exit) clears everything so a freshly-created doc shows up next time.*/-export function createMentionCorpus(fetch: () => Promise<PageItem[]> = fetchPages) {+export function createMentionCorpus(+ // Folders are opt-in on fetchPages (the wiki-link pickers must never see+ // them); the composer is the one consumer that wants them, as attachable+ // chips.+ fetch: () => Promise<PageItem[]> = () => fetchPages({ includeFolders: true }),+) {let cachedPages: PageItem[] = [];let pagesLoaded = false;let pagesPromise: Promise<PageItem[]> | null = null;diff --git a/packages/app/src/editor/extensions/wiki-link-suggestion.test.ts b/packages/app/src/editor/extensions/wiki-link-suggestion.test.tsindex c8813fdfe..3e7a26e9e 100644--- a/packages/app/src/editor/extensions/wiki-link-suggestion.test.ts+++ b/packages/app/src/editor/extensions/wiki-link-suggestion.test.ts@@ -84,6 +84,23 @@ describe('buildSuggestionItems', () => {]);});+ test('never emits a folder row, typed or empty query', () => {+ // Belt against a folder-bearing corpus (fetchPages excludes folders by+ // default, but composer-shared callers can hand them in): the non-asset+ // mapping arm would dress a folder as a page and the inserted wiki link+ // would open the folder path as a document.+ const withFolders: PageItem[] = [+ ...pages,+ { kind: 'folder', docName: '.claude', title: '.claude' },+ { kind: 'folder', docName: 'specs/foo', title: 'foo' },+ ];+ expect(buildSuggestionItems(withFolders, '')).toEqual(buildSuggestionItems(pages, ''));+ // A query that matches ONLY folders falls through to the create-new row+ // rather than surfacing the folder.+ const folderOnly = buildSuggestionItems(withFolders, 'specs/foo');+ expect(folderOnly.every((item) => item.kind === 'create')).toBe(true);+ });+test('matches by docName when title differs', () => {expect(buildSuggestionItems(pages, 'qa-source')).toEqual([{@@ -341,18 +358,34 @@ describe('fetchPages', () => {},);- const result = await fetchPages();+ const result = await fetchPages({ includeFolders: true });const folder = result.find((item) => item.kind === 'folder');expect(folder).toEqual({ kind: 'folder', docName: 'specs/foo', title: 'foo' });});+ test('folders are excluded by default — the wiki-link pickers must never see them', async () => {+ stubFetch(+ { pages: [pageEntry('notes', 'Notes')] },+ {+ documents: [+ { kind: 'folder', path: 'specs/foo', size: 0, modified: '2026-06-24T00:00:00.000Z' },+ { kind: 'folder', path: '.claude', size: 0, modified: '2026-06-24T00:00:00.000Z' },+ ],+ },+ );++ const result = await fetchPages();+ expect(result.some((item) => item.kind === 'folder')).toBe(false);+ expect(result.map((item) => item.docName)).toEqual(['notes']);+ });+test('a top-level folder titles from its bare path', async () => {stubFetch({ pages: [] },{ documents: [{ kind: 'folder', path: 'specs', modified: '2026-06-24T00:00:00.000Z' }] },);- const result = await fetchPages();+ const result = await fetchPages({ includeFolders: true });expect(result).toContainEqual({ kind: 'folder', docName: 'specs', title: 'specs' });});@@ -368,7 +401,7 @@ describe('fetchPages', () => {},);- const result = await fetchPages();+ const result = await fetchPages({ includeFolders: true });// Assert docName order, not kind: referenced assets and unreferenced files// both project to `kind:'asset'`, so a kind-only check wouldn't catch a// spread-order swap between them. Order is pages, assets, files, folders.diff --git a/packages/app/src/editor/extensions/wiki-link-suggestion.ts b/packages/app/src/editor/extensions/wiki-link-suggestion.tsindex d12ec0c81..33feb8085 100644--- a/packages/app/src/editor/extensions/wiki-link-suggestion.ts+++ b/packages/app/src/editor/extensions/wiki-link-suggestion.ts@@ -143,7 +143,15 @@ interface SuggestionSearchCorpus<T> {corpus: WorkspaceSearchCorpus;}-let cachedPageSearchCorpus: SuggestionSearchCorpus<PageItem> | null = null;+/**+ * Fingerprint-keyed corpus cache with room for TWO corpora: the pickers'+ * folder-free corpus (WYSIWYG `[[` + source mode share one fingerprint) and+ * the composer's folder-bearing corpus. A single slot made every `@` ⇄ `[[`+ * switch rebuild the search index on the first non-empty keystroke; two slots+ * keep both warm. Insertion-ordered Map, oldest entry evicted beyond the cap.+ */+const PAGE_SEARCH_CORPUS_CACHE_SLOTS = 2;+const cachedPageSearchCorpora = new Map<string, SuggestionSearchCorpus<PageItem>>();let cachedHeadingSearchCorpus: SuggestionSearchCorpus<HeadingEntry> | null = null;/** Split `query` on the first `#` with a non-empty left side. */@@ -220,8 +228,14 @@ function getCachedPageSearchCorpus(pages: readonly PageItem[]): SuggestionSearchconst fingerprint = pages.map((page) => `${page.kind ?? 'page'}\u0000${page.docName}\u0000${page.title}`).join('\u0001');- if (cachedPageSearchCorpus?.fingerprint === fingerprint) return cachedPageSearchCorpus;- cachedPageSearchCorpus = {+ const cached = cachedPageSearchCorpora.get(fingerprint);+ if (cached) {+ // Refresh recency so the evicted entry is the least recently used one.+ cachedPageSearchCorpora.delete(fingerprint);+ cachedPageSearchCorpora.set(fingerprint, cached);+ return cached;+ }+ const built: SuggestionSearchCorpus<PageItem> = {fingerprint,byId: new Map(pages.map((page) => [`${pageSearchKind(page)}:${page.docName}`, page])),corpus: createWorkspaceSearchCorpus(@@ -234,7 +248,13 @@ function getCachedPageSearchCorpus(pages: readonly PageItem[]): SuggestionSearch),),};- return cachedPageSearchCorpus;+ cachedPageSearchCorpora.set(fingerprint, built);+ while (cachedPageSearchCorpora.size > PAGE_SEARCH_CORPUS_CACHE_SLOTS) {+ const oldest = cachedPageSearchCorpora.keys().next().value;+ if (oldest === undefined) break;+ cachedPageSearchCorpora.delete(oldest);+ }+ return built;}function getCachedHeadingSearchCorpus(@@ -276,7 +296,13 @@ export function buildSuggestionItems(query: string,context: WikiLinkContext = EMPTY_WIKI_LINK_CONTEXT,): WikiLinkSuggestionItem[] {- const filtered = filterPages(pages, query, context);+ // Hard guard, independent of the fetch-side default: a folder PageItem must+ // never surface as a wiki-link row — the non-asset arm below would dress it+ // as a page and the inserted link would open the folder path as a document.+ // Filtering after ranking can undershoot MAX_ITEMS, which is+ // fine for a belt that only engages when a caller hands in a folder-bearing+ // corpus.+ const filtered = filterPages(pages, query, context).filter((item) => item.kind !== 'folder');if (filtered.length > 0) {return filtered.map((item) =>item.kind === 'asset'@@ -358,7 +384,20 @@ export function wikiLinkMatcher(config: {};}-export async function fetchPages(): Promise<PageItem[]> {+export interface FetchPagesOptions {+ /**+ * Append `kind:'folder'` entries to the returned corpus. Folder targets are+ * only meaningful to the ACP composer's `@` picker, where selecting one+ * attaches the folder as a chip (serialized to its bare path). The `[[`+ * wiki-link pickers must never see them: a wiki link serializes to a doc+ * target, so a picked folder inserts a link that opens the folder path as a+ * document. First-class folder links are a separate planned feature;+ * until that lands, folders stay out of every default consumer.+ */+ includeFolders?: boolean;+}++export async function fetchPages(options: FetchPagesOptions = {}): Promise<PageItem[]> {const r = await fetch('/api/pages');let body: unknown;try {@@ -434,8 +473,11 @@ export async function fetchPages(): Promise<PageItem[]> {return { kind: 'asset', docName: `/${file.path}`, title };});+ if (!options.includeFolders) return [...pages, ...assets, ...files];+// Folders (`kind:'folder'`) carry no `.md` suffix — their `path` is the- // workspace-relative folder path the chip serializes to verbatim.+ // workspace-relative folder path the chip serializes to verbatim. Opt-in+ // (see FetchPagesOptions): only the composer's `@` picker wants them.const folders = docData.documents.filter((entry): entry is { kind: 'folder'; path: string } => {return entry.kind === 'folder' && typeof entry.path === 'string' && entry.path.length > 0;diff --git a/packages/app/src/editor/plugins/wiki-link-source.test.ts b/packages/app/src/editor/plugins/wiki-link-source.test.tsindex b3d718a46..524bbead8 100644--- a/packages/app/src/editor/plugins/wiki-link-source.test.ts+++ b/packages/app/src/editor/plugins/wiki-link-source.test.ts@@ -174,6 +174,20 @@ describe('end-to-end target matching', () => {expect(targetSet.has(extractWikilinkTarget('reports/q1'))).toBe(true);});+ test('folder rows keep seeding the known-target set: full path AND basename', () => {+ // The plugin fetches its page list WITH folders solely for this set (the+ // completion source strips them): a folder holding no markdown children+ // arrives only as a kind:'folder' row, and a bare-basename wikilink to a+ // folder resolves only through the row's title. Losing either form+ // redlines links in source mode that the WYSIWYG chip resolves.+ const targetSet = buildKnownWikilinkTargetSet([+ { kind: 'folder', docName: 'specs/foo', title: 'foo' },+ ]);++ expect(targetSet.has(extractWikilinkTarget('specs/foo'))).toBe(true);+ expect(targetSet.has(extractWikilinkTarget('foo'))).toBe(true);+ });+test('empty target (bare #anchor in wikilink) matches nothing', () => {// The plugin's check `target && !pageSet.has(target)` treats empty target// as a no-op (never emits broken-mark); verified here by the truthy check.diff --git a/packages/app/src/editor/plugins/wiki-link-source.ts b/packages/app/src/editor/plugins/wiki-link-source.tsindex e8b12a24f..9b27828e2 100644--- a/packages/app/src/editor/plugins/wiki-link-source.ts+++ b/packages/app/src/editor/plugins/wiki-link-source.ts@@ -87,7 +87,12 @@ async function getWikiLinkContext(docName: string | null): Promise<WikiLinkConteasync function getPages(): Promise<PageItem[]> {const now = Date.now();if (pagesCache && now - pagesCacheTime < PAGES_CACHE_TTL_MS) return pagesCache;- pagesCache = await fetchPages();+ // Folders are requested here even though the completion source strips them:+ // `buildKnownWikilinkTargetSet` seeds the broken-link decoration with each+ // folder's path AND basename (via `buildPageNameSet`), so an existing+ // `[[some/folder]]` must not redline in source mode while the WYSIWYG chip+ // resolves it. `buildSourceWikiLinkLookup` skips folder rows itself.+ pagesCache = await fetchPages({ includeFolders: true });pagesCacheTime = now;knownTargetSet = buildKnownWikilinkTargetSet(pagesCache);wikiLinkLookup = buildSourceWikiLinkLookup(pagesCache);@@ -418,7 +423,16 @@ async function wikiLinkCompletionSource(}),getWikiLinkContext(currentDocName),]);- const filtered = filterPages(pages, query, linkContext);+ // Folders stay out of the picker (they are decoration/click inputs only,+ // fetched above): strip BEFORE ranking so they never occupy top-N slots,+ // and so this corpus fingerprints identically to the WYSIWYG picker's+ // folder-free corpus — one shared search-index cache entry, no rebuild+ // when switching surfaces.+ const filtered = filterPages(+ pages.filter((p) => p.kind !== 'folder'),+ query,+ linkContext,+ );return {from: triggerPos,