Beautiful, AI-native markdown IDE and LLM wiki
TypeScript 2nd-brainagent-skillsclaudecodexcompany-braindocsknowledge-knowledge-baseknowledge-managementllmllm-wikillm-wiki-karpathymarkdownmarkdown-editormdmdxnotespkmsecond-brainskills
Fix Show All truncation starvation and lazy-load the file tree (#1838)
Andrew Mikofalvye48bd6f113af
diff --git a/.changeset/showall-truncation-ux.md b/.changeset/showall-truncation-ux.mdnew file mode 100644index 000000000..214f2c6ce--- /dev/null+++ b/.changeset/showall-truncation-ux.md@@ -0,0 +1,5 @@+---+"@inkeep/open-knowledge": patch+---++Show All Files sidebar overhaul. The recursive listing walk now emits in level order, so hitting the entry cap drops the deepest entries first instead of arbitrarily starving top-level items behind one huge subtree. The sidebar no longer walks the whole tree up front in Show All mode: it seeds the root level lazily, fetches each folder's children on expand, and revalidates only the root plus currently-expanded folders when files change externally. The truncation and listing-error notices now render as contained, localized alert rows, and the truncation copy is truthful: it shows a locale-formatted count and explains that deeply nested files are hidden (the previous copy claimed search could find them, which it cannot — show-all-only files are not in the search index).diff --git a/packages/app/package.json b/packages/app/package.jsonindex 7a3ee6656..47ea0c851 100644--- a/packages/app/package.json+++ b/packages/app/package.json@@ -25,7 +25,7 @@"measure:fuzz": "bash scripts/measure-fuzz.sh","measure:stress": "bash scripts/measure-stress.sh","perf:compare": "bash scripts/perf-compare.sh",- "test:e2e": "playwright test tests/stress/ux-interactions.e2e.ts tests/stress/file-tree-create.e2e.ts tests/stress/create-then-rename-editable.e2e.ts tests/stress/find-replace.e2e.ts tests/stress/editor-tabs.e2e.ts tests/stress/crdt-stress.e2e.ts tests/stress/slash-command.e2e.ts tests/stress/paste-fidelity.e2e.ts tests/stress/fr-7a-disconnect-source-mode.e2e.ts tests/stress/docs-open.e2e.ts tests/stress/frozen-table-headers.e2e.ts tests/stress/asset-embed.e2e.ts tests/stress/asset-embed-advanced.e2e.ts tests/stress/asset-click-dispatch.e2e.ts tests/stress/handoff.e2e.ts tests/stress/multi-agent-presence.e2e.ts tests/stress/editor-mode-persistence.e2e.ts tests/stress/sidebar-search-pill.e2e.ts tests/stress/command-palette-semantic.e2e.ts tests/stress/agent-activity-panel.e2e.ts tests/stress/drop-pipeline-auto-open.e2e.ts tests/stress/command-palette-flicker.e2e.ts tests/stress/cm6-list-hanging-indent.e2e.ts tests/stress/ng7-rapid-nav-coherence.e2e.ts tests/stress/init-load-byte-stable.e2e.ts tests/stress/single-file-ephemeral.e2e.ts tests/stress/reveal-on-activate.e2e.ts tests/stress/selection-indicator.e2e.ts tests/stress/new-file-cross-doc-bleed.e2e.ts tests/stress/editor-mode-flip-cross-doc-bleed.e2e.ts tests/stress/editor-area-viewport-resize.e2e.ts tests/stress/qa-sidebar-responsive.e2e.ts tests/stress/prd-6955-reassertion-repro.e2e.ts tests/stress/prd-6955-reassertion-wedge.e2e.ts tests/stress/prd-6914-repro.e2e.ts",+ "test:e2e": "playwright test tests/stress/ux-interactions.e2e.ts tests/stress/file-tree-create.e2e.ts tests/stress/create-then-rename-editable.e2e.ts tests/stress/find-replace.e2e.ts tests/stress/editor-tabs.e2e.ts tests/stress/crdt-stress.e2e.ts tests/stress/slash-command.e2e.ts tests/stress/paste-fidelity.e2e.ts tests/stress/fr-7a-disconnect-source-mode.e2e.ts tests/stress/docs-open.e2e.ts tests/stress/frozen-table-headers.e2e.ts tests/stress/asset-embed.e2e.ts tests/stress/asset-embed-advanced.e2e.ts tests/stress/asset-click-dispatch.e2e.ts tests/stress/handoff.e2e.ts tests/stress/multi-agent-presence.e2e.ts tests/stress/editor-mode-persistence.e2e.ts tests/stress/sidebar-search-pill.e2e.ts tests/stress/command-palette-semantic.e2e.ts tests/stress/agent-activity-panel.e2e.ts tests/stress/drop-pipeline-auto-open.e2e.ts tests/stress/command-palette-flicker.e2e.ts tests/stress/cm6-list-hanging-indent.e2e.ts tests/stress/ng7-rapid-nav-coherence.e2e.ts tests/stress/init-load-byte-stable.e2e.ts tests/stress/single-file-ephemeral.e2e.ts tests/stress/reveal-on-activate.e2e.ts tests/stress/selection-indicator.e2e.ts tests/stress/new-file-cross-doc-bleed.e2e.ts tests/stress/editor-mode-flip-cross-doc-bleed.e2e.ts tests/stress/editor-area-viewport-resize.e2e.ts tests/stress/qa-sidebar-responsive.e2e.ts tests/stress/prd-6955-reassertion-repro.e2e.ts tests/stress/prd-6955-reassertion-wedge.e2e.ts tests/stress/prd-6914-repro.e2e.ts tests/stress/showall-lazy-tree.e2e.ts","test:e2e:install-browsers": "playwright install chromium webkit firefox","test:visual": "playwright test --config playwright.visual.config.ts","test:visual:update": "playwright test --config playwright.visual.config.ts --update-snapshots",diff --git a/packages/app/src/components/FileTree.showall-lazy.dom.test.tsx b/packages/app/src/components/FileTree.showall-lazy.dom.test.tsxnew file mode 100644index 000000000..250b185d4--- /dev/null+++ b/packages/app/src/components/FileTree.showall-lazy.dom.test.tsx@@ -0,0 +1,771 @@+import { afterEach, beforeEach, describe, expect, mock, spyOn, test } from 'bun:test';+import { i18n } from '@lingui/core';+import { cleanup, render, screen, waitFor } from '@testing-library/react';+import type { ReactNode } from 'react';+import { emitDocumentsChanged } from '@/lib/documents-events';++i18n.load('en', {});+i18n.activate('en');++function PassThrough({ children }: { children?: ReactNode }) {+ return <>{children}</>;+}++const SHOW_ALL_DEPTH1_URL = '/api/documents?showAll=true&dir=&depth=1';++let mergedConfig: unknown = { appearance: { sidebar: { showAllFiles: true } } };+let showAllResponseFactory: () => Response = () => jsonResponse({ documents: [] });+let responseByUrl = new Map<string, (init?: RequestInit) => Response | Promise<Response>>();+const fetchUrls: string[] = [];++function lazyDirUrl(dir: string): string {+ return `/api/documents?showAll=true&dir=${encodeURIComponent(dir)}&depth=1`;+}++function jsonResponse(body: unknown, status = 200): Response {+ return new Response(JSON.stringify(body), {+ status,+ headers: { 'content-type': 'application/json' },+ });+}++function docEntry(docName: string) {+ return {+ kind: 'document',+ docName,+ docExt: '.md',+ size: 1,+ modified: '2026-06-12T00:00:00.000Z',+ };+}++function folderEntry(path: string, hasChildren: boolean) {+ return {+ kind: 'folder',+ path,+ size: 0,+ modified: '2026-06-12T00:00:00.000Z',+ hasChildren,+ };+}++function makeFetchMock() {+ return mock(async (input: RequestInfo | URL, init?: RequestInit) => {+ const url = typeof input === 'string' ? input : input instanceof URL ? input.href : input.url;+ fetchUrls.push(url);+ const override = responseByUrl.get(url);+ if (override) return override(init);+ if (url === SHOW_ALL_DEPTH1_URL) return showAllResponseFactory();+ if (url.startsWith('/api/documents')) return jsonResponse({ documents: [docEntry('notes/a')] });+ if (url === '/api/workspace') {+ return jsonResponse({ contentDir: '/tmp/ok', pathSeparator: '/', symlinkResolved: true });+ }+ return jsonResponse({ ok: true });+ });+}++class StubItem {+ expanded = false;+ selected = false;+ constructor(+ readonly path: string,+ private readonly directory: boolean,+ private readonly onChange: () => void = () => {},+ ) {}+ getPath() {+ return this.path;+ }+ isDirectory() {+ return this.directory;+ }+ isExpanded() {+ return this.expanded;+ }+ expand() {+ this.expanded = true;+ this.onChange();+ }+ collapse() {+ this.expanded = false;+ this.onChange();+ }+ isSelected() {+ return this.selected;+ }+ select() {+ this.selected = true;+ }+ deselect() {+ this.selected = false;+ }+ focus() {}+}++class StubModel {+ focusedPath: string | null = null;+ selectedPaths: string[] = [];+ items = new Map<string, StubItem>();+ listeners = new Set<() => void>();+ startRenaming = mock(() => {});+ notify() {+ for (const listener of this.listeners) listener();+ }+ getFocusedPath() {+ return this.focusedPath;+ }+ getFocusedIndex() {+ return -1;+ }+ getItemHeight() {+ return 24;+ }+ getSelectedPaths() {+ return this.selectedPaths;+ }+ getItem(path: string) {+ return this.items.get(path) ?? null;+ }+ resetPaths(paths: string[], opts?: { initialExpandedPaths?: readonly string[] }) {+ this.items.clear();+ for (const path of paths) {+ this.items.set(path, new StubItem(path, path.endsWith('/'), () => this.notify()));+ }+ for (const path of opts?.initialExpandedPaths ?? []) {+ const item = this.items.get(path);+ if (item) item.expanded = true;+ }+ this.notify();+ }+ subscribe(listener: () => void) {+ this.listeners.add(listener);+ return () => {+ this.listeners.delete(listener);+ };+ }+ onMutation() {+ return () => {};+ }+ isSearchOpen() {+ return false;+ }+ add(path: string) {+ this.items.set(path, new StubItem(path, path.endsWith('/'), () => this.notify()));+ }+ move() {}+ remove() {}+}++const model = new StubModel();++mock.module('sonner', () => ({ toast: { success: mock(() => {}), error: mock(() => {}) } }));+mock.module('next-themes', () => ({ useTheme: () => ({ resolvedTheme: 'light' }) }));+mock.module('@/editor/DocumentContext', () => ({+ useDocumentContext: () => ({+ activeDocName: null,+ activeTarget: null,+ closeTabs: mock(() => {}),+ closeDocument: mock(() => {}),+ closeAndClearDocument: mock(async () => {}),+ closeAndClearForDelete: mock(async () => {}),+ closeAndClearForRename: mock(async () => {}),+ getPoolActiveDocName: () => null,+ poolHas: () => false,+ isNewTabActive: false,+ openTarget: mock(() => {}),+ prewarm: () => {},+ remapTabsForRename: mock(() => {}),+ }),+}));+mock.module('@/components/PageListContext', () => ({+ usePageList: () => ({ addPage: mock(() => {}) }),+}));+mock.module('./ui/sidebar', () => ({+ useSidebar: () => ({ notifySidebarFileSelected: mock(() => {}) }),+}));+mock.module('@/lib/config-provider', () => ({+ useConfigContext: () => ({+ okignoreBinding: null,+ projectLocalBinding: null,+ merged: mergedConfig,+ }),+}));+mock.module('./handoff/useInstalledAgents', () => ({ useInstalledAgents: () => ({ states: {} }) }));+mock.module('./handoff/useHandoffDispatch', () => ({+ buildFolderHandoffInput: () => null,+ buildHandoffInput: () => null,+ useHandoffDispatch: () => ({ dispatch: mock(async () => ({ ok: true as const })) }),+}));+mock.module('./handoff/OpenInAgentContextSubmenu', () => ({+ OpenInAgentContextSubmenu: () => null,+}));+mock.module('./sidebar-hover-prewarm', () => ({+ cancelHoverPrewarm: () => {},+ scheduleHoverPrewarm: () => {},+}));+mock.module('@/components/ui/button', () => ({+ Button: ({ children, ...props }: { children?: ReactNode; [k: string]: unknown }) => (+ <button type="button" {...props}>+ {children}+ </button>+ ),+}));+mock.module('@/components/ui/dialog', () => ({ Dialog: PassThrough }));+mock.module('@/components/ui/dropdown-menu', () => ({+ DropdownMenu: PassThrough,+ DropdownMenuCheckboxItem: PassThrough,+ DropdownMenuContent: PassThrough,+ DropdownMenuItem: PassThrough,+ DropdownMenuSeparator: () => <hr />,+ DropdownMenuSub: PassThrough,+ DropdownMenuSubContent: PassThrough,+ DropdownMenuSubTrigger: PassThrough,+ DropdownMenuTrigger: PassThrough,+}));+mock.module('@/components/ui/skeleton', () => ({+ Skeleton: ({ className }: { className?: string }) => <span className={className} />,+}));+mock.module('@/components/DeleteConfirmationDialog', () => ({+ DeleteConfirmationDialog: () => null,+}));+mock.module('@/components/NewItemDialog', () => ({ NewItemDialog: () => null }));+mock.module('@/components/TrashFailureModal', () => ({+ TrashFailureModal: () => null,+ coerceTrashFailureReason: (reason: string) => reason,+}));+mock.module('@/components/use-selection-mirror', () => ({+ asDirectoryHandle: (item: StubItem | null) => (item?.isDirectory() ? item : null),+ useSelectionMirror: () => {},+}));+mock.module('@pierre/trees', () => ({+ FILE_TREE_TAG_NAME: 'ok-file-tree',+ themeToTreeStyles: () => ({}),+}));+mock.module('@pierre/trees/react', () => ({+ useFileTree: () => ({ model }),+ FileTree: ({ header }: { header?: ReactNode }) => (+ <div data-testid="fake-pierre-tree" role="tree">+ {header}+ </div>+ ),+}));++const { FileTree } = await import('./FileTree');++describe('FileTree showAll lazy root seed', () => {+ let consoleWarnSpy: ReturnType<typeof spyOn>;++ beforeEach(() => {+ mergedConfig = { appearance: { sidebar: { showAllFiles: true } } };+ showAllResponseFactory = () => jsonResponse({ documents: [] });+ responseByUrl = new Map();+ fetchUrls.length = 0;+ model.items.clear();+ model.listeners.clear();+ model.focusedPath = null;+ model.selectedPaths = [];+ globalThis.fetch = makeFetchMock() as unknown as typeof fetch;+ consoleWarnSpy = spyOn(console, 'warn').mockImplementation(() => {});+ });++ afterEach(() => {+ cleanup();+ consoleWarnSpy.mockRestore();+ });++ test('Show All ON seeds the tree from one depth-1 root fetch, never the recursive walk (QA-001)', async () => {+ showAllResponseFactory = () =>+ jsonResponse({+ documents: [folderEntry('team', true), folderEntry('empty', false), docEntry('README')],+ truncated: false,+ });+ render(<FileTree />);++ await screen.findByTestId('fake-pierre-tree');+ await waitFor(() => expect(fetchUrls).toContain(SHOW_ALL_DEPTH1_URL));+ await waitFor(() =>+ expect([...model.items.keys()].sort()).toEqual(['README.md', 'empty/', 'team/']),+ );+ expect(fetchUrls.filter((u) => u.includes('showAll=true') && !u.includes('depth=1'))).toEqual(+ [],+ );+ });++ test('seeded folders are directory items for both hasChildren values; documents are files', async () => {+ showAllResponseFactory = () =>+ jsonResponse({+ documents: [folderEntry('team', true), folderEntry('empty', false), docEntry('README')],+ truncated: false,+ });+ render(<FileTree />);++ await screen.findByTestId('fake-pierre-tree');+ await waitFor(() => expect(model.items.size).toBe(3));+ expect(model.getItem('team/')?.isDirectory()).toBe(true);+ expect(model.getItem('empty/')?.isDirectory()).toBe(true);+ expect(model.getItem('README.md')?.isDirectory()).toBe(false);+ });++ test('a truncated depth-1 level still drives the truncation notice (QA-002 wiring)', async () => {+ showAllResponseFactory = () =>+ jsonResponse({+ documents: [docEntry('a'), docEntry('b'), docEntry('c')],+ truncated: true,+ });+ render(<FileTree />);++ await waitFor(() => {+ expect(screen.getByRole('status').textContent ?? '').toContain('Showing the first 3 items');+ });+ });++ test('seeds from a streamed NDJSON depth-1 response (entries + complete line)', async () => {+ const lines = [+ JSON.stringify(folderEntry('team', true)),+ JSON.stringify(docEntry('README')),+ JSON.stringify({ type: 'complete', truncated: true, count: 2 }),+ ].join('\n');+ showAllResponseFactory = () =>+ new Response(`${lines}\n`, {+ status: 200,+ headers: { 'content-type': 'application/x-ndjson' },+ });+ render(<FileTree />);++ await waitFor(() => expect(model.items.size).toBe(2));+ expect([...model.items.keys()].sort()).toEqual(['README.md', 'team/']);+ await waitFor(() => {+ expect(screen.getByRole('status').textContent ?? '').toContain('Showing the first 2 items');+ });+ });++ test('a server-emitted NDJSON error line surfaces its problem title, not the connectivity copy', async () => {+ const lines = [+ JSON.stringify(folderEntry('team', true)),+ JSON.stringify({ type: 'error', problem: { title: 'Folder walk failed mid-stream' } }),+ ].join('\n');+ showAllResponseFactory = () =>+ new Response(`${lines}\n`, {+ status: 200,+ headers: { 'content-type': 'application/x-ndjson' },+ });+ render(<FileTree />);++ await screen.findByText('Folder walk failed mid-stream');+ expect(screen.queryByText('Could not reach server')).toBeNull();+ });++ test('Show All OFF keeps the index-backed fetch byte-for-byte unchanged', async () => {+ mergedConfig = null; // showAllFiles → false+ render(<FileTree />);++ await screen.findByTestId('fake-pierre-tree');+ expect(fetchUrls).toContain('/api/documents');+ expect(fetchUrls.some((u) => u.includes('showAll') || u.includes('depth='))).toBe(false);+ expect([...model.items.keys()]).toEqual(['notes/a.md']);+ });+});++describe('FileTree showAll lazy folder expansion', () => {+ let consoleWarnSpy: ReturnType<typeof spyOn>;++ beforeEach(() => {+ mergedConfig = { appearance: { sidebar: { showAllFiles: true } } };+ showAllResponseFactory = () =>+ jsonResponse({+ documents: [folderEntry('team', true), folderEntry('empty', false), docEntry('README')],+ truncated: false,+ });+ responseByUrl = new Map();+ fetchUrls.length = 0;+ model.items.clear();+ model.listeners.clear();+ model.focusedPath = null;+ model.selectedPaths = [];+ globalThis.fetch = makeFetchMock() as unknown as typeof fetch;+ consoleWarnSpy = spyOn(console, 'warn').mockImplementation(() => {});+ });++ afterEach(() => {+ cleanup();+ consoleWarnSpy.mockRestore();+ });++ async function renderSeededTree() {+ render(<FileTree />);+ await waitFor(() => expect(model.items.size).toBe(3));+ }++ test('expanding an unloaded folder fetches one level and splices the children in (QA-004)', async () => {+ responseByUrl.set(lazyDirUrl('team'), () =>+ jsonResponse({+ documents: [folderEntry('team/sub', true), docEntry('team/notes')],+ truncated: false,+ }),+ );+ await renderSeededTree();++ model.getItem('team/')?.expand();++ await waitFor(() =>+ expect([...model.items.keys()].sort()).toEqual([+ 'README.md',+ 'empty/',+ 'team/',+ 'team/notes.md',+ 'team/sub/',+ ]),+ );+ expect(fetchUrls.filter((url) => url === lazyDirUrl('team'))).toHaveLength(1);+ expect(model.getItem('team/')?.isExpanded()).toBe(true);+ });++ test('collapse and re-expand serves the already-loaded children without refetching (QA-005)', async () => {+ responseByUrl.set(lazyDirUrl('team'), () =>+ jsonResponse({ documents: [docEntry('team/notes')], truncated: false }),+ );+ await renderSeededTree();++ model.getItem('team/')?.expand();+ await waitFor(() => expect(model.items.has('team/notes.md')).toBe(true));++ model.getItem('team/')?.collapse();+ model.getItem('team/')?.expand();+ await new Promise((resolve) => setTimeout(resolve, 0));++ expect(fetchUrls.filter((url) => url === lazyDirUrl('team'))).toHaveLength(1);+ expect(model.items.has('team/notes.md')).toBe(true);+ });++ test('re-expanding a folder while its fetch is still in flight does not start a duplicate', async () => {+ let releaseChildren: () => void = () => {};+ responseByUrl.set(+ lazyDirUrl('team'),+ () =>+ new Promise<Response>((resolve) => {+ releaseChildren = () =>+ resolve(jsonResponse({ documents: [docEntry('team/notes')], truncated: false }));+ }),+ );+ await renderSeededTree();++ model.getItem('team/')?.expand();+ model.getItem('team/')?.collapse();+ model.getItem('team/')?.expand();+ await new Promise((resolve) => setTimeout(resolve, 0));+ expect(fetchUrls.filter((url) => url === lazyDirUrl('team'))).toHaveLength(1);++ releaseChildren();+ await waitFor(() => expect(model.items.has('team/notes.md')).toBe(true));+ expect([...model.items.keys()].filter((path) => path === 'team/notes.md')).toHaveLength(1);+ });++ test('nested expansion lazily loads three levels, one fetch per folder', async () => {+ responseByUrl.set(lazyDirUrl('team'), () =>+ jsonResponse({ documents: [folderEntry('team/sub', true)], truncated: false }),+ );+ responseByUrl.set(lazyDirUrl('team/sub'), () =>+ jsonResponse({ documents: [docEntry('team/sub/deep')], truncated: false }),+ );+ await renderSeededTree();++ model.getItem('team/')?.expand();+ await waitFor(() => expect(model.items.has('team/sub/')).toBe(true));+ expect(model.getItem('team/sub/')?.isDirectory()).toBe(true);++ model.getItem('team/sub/')?.expand();+ await waitFor(() => expect(model.items.has('team/sub/deep.md')).toBe(true));++ expect(fetchUrls.filter((url) => url === lazyDirUrl('team'))).toHaveLength(1);+ expect(fetchUrls.filter((url) => url === lazyDirUrl('team/sub'))).toHaveLength(1);+ expect(model.getItem('team/')?.isExpanded()).toBe(true);+ expect(model.getItem('team/sub/')?.isExpanded()).toBe(true);+ });++ test('a child response that loses to a refresh cycle is discarded while revalidation repopulates the folder', async () => {+ let releaseStaleChildren: () => void = () => {};+ let teamRequestCount = 0;+ responseByUrl.set(lazyDirUrl('team'), () => {+ teamRequestCount += 1;+ if (teamRequestCount === 1) {+ return new Promise<Response>((resolve) => {+ releaseStaleChildren = () =>+ resolve(jsonResponse({ documents: [docEntry('team/stale')], truncated: false }));+ });+ }+ return jsonResponse({ documents: [docEntry('team/fresh')], truncated: false });+ });+ await renderSeededTree();++ model.getItem('team/')?.expand();+ await waitFor(() => expect(teamRequestCount).toBe(1));++ emitDocumentsChanged(['files']);+ await waitFor(() => expect(model.items.has('team/fresh.md')).toBe(true));+ expect(teamRequestCount).toBe(2);+ expect(model.getItem('team/')?.isExpanded()).toBe(true);++ releaseStaleChildren();+ await new Promise((resolve) => setTimeout(resolve, 0));+ expect(model.items.has('team/stale.md')).toBe(false);+ expect([...model.items.keys()].sort()).toEqual([+ 'README.md',+ 'empty/',+ 'team/',+ 'team/fresh.md',+ ]);+ });++ test('expanding a folder the server marked childless fetches nothing', async () => {+ await renderSeededTree();+ const requestCountBefore = fetchUrls.length;++ model.getItem('empty/')?.expand();+ await new Promise((resolve) => setTimeout(resolve, 0));++ expect(fetchUrls.slice(requestCountBefore)).toEqual([]);+ expect(model.getItem('empty/')?.isExpanded()).toBe(true);+ });++ test('a failed child fetch surfaces the error alert and the folder stays re-expandable (QA-008)', async () => {+ let teamRequestCount = 0;+ responseByUrl.set(lazyDirUrl('team'), () => {+ teamRequestCount += 1;+ if (teamRequestCount === 1) return jsonResponse({ title: 'Folder walk failed' }, 500);+ return jsonResponse({ documents: [docEntry('team/notes')], truncated: false });+ });+ await renderSeededTree();++ model.getItem('team/')?.expand();++ await waitFor(() => {+ expect(screen.getByRole('alert').textContent ?? '').toContain('Folder walk failed');+ });+ expect([...model.items.keys()].sort()).toEqual(['README.md', 'empty/', 'team/']);++ model.getItem('team/')?.collapse();+ model.getItem('team/')?.expand();+ await waitFor(() => expect(model.items.has('team/notes.md')).toBe(true));+ expect(teamRequestCount).toBe(2);+ expect(screen.queryByRole('alert')).toBeNull();+ });++ test('a network-level child fetch failure surfaces the unreachable-server alert and recovers (QA-008)', async () => {+ let teamRequestCount = 0;+ responseByUrl.set(lazyDirUrl('team'), () => {+ teamRequestCount += 1;+ if (teamRequestCount === 1) throw new TypeError('Failed to fetch');+ return jsonResponse({ documents: [docEntry('team/notes')], truncated: false });+ });+ await renderSeededTree();++ model.getItem('team/')?.expand();++ await waitFor(() => {+ expect(screen.getByRole('alert').textContent ?? '').toContain('Could not reach server');+ });+ expect([...model.items.keys()].sort()).toEqual(['README.md', 'empty/', 'team/']);++ model.getItem('team/')?.collapse();+ model.getItem('team/')?.expand();+ await waitFor(() => expect(model.items.has('team/notes.md')).toBe(true));+ expect(teamRequestCount).toBe(2);+ expect(screen.queryByRole('alert')).toBeNull();+ });+});++describe('FileTree showAll scoped refresh', () => {+ let consoleWarnSpy: ReturnType<typeof spyOn>;++ beforeEach(() => {+ mergedConfig = { appearance: { sidebar: { showAllFiles: true } } };+ showAllResponseFactory = () =>+ jsonResponse({+ documents: [folderEntry('team', true), folderEntry('empty', false), docEntry('README')],+ truncated: false,+ });+ responseByUrl = new Map();+ fetchUrls.length = 0;+ model.items.clear();+ model.listeners.clear();+ model.focusedPath = null;+ model.selectedPaths = [];+ globalThis.fetch = makeFetchMock() as unknown as typeof fetch;+ consoleWarnSpy = spyOn(console, 'warn').mockImplementation(() => {});+ });++ afterEach(() => {+ cleanup();+ consoleWarnSpy.mockRestore();+ });++ async function renderTreeWithTeamLoaded() {+ responseByUrl.set(lazyDirUrl('team'), () =>+ jsonResponse({ documents: [docEntry('team/notes')], truncated: false }),+ );+ const view = render(<FileTree />);+ await waitFor(() => expect(model.items.size).toBe(3));+ model.getItem('team/')?.expand();+ await waitFor(() => expect(model.items.has('team/notes.md')).toBe(true));+ return view;+ }++ test('a files signal revalidates the root level plus expanded folders only (QA-006 scope)', async () => {+ showAllResponseFactory = () =>+ new Response(+ `${[+ JSON.stringify(folderEntry('team', true)),+ JSON.stringify(folderEntry('empty', false)),+ JSON.stringify(docEntry('README')),+ JSON.stringify({ type: 'complete', truncated: false, count: 3 }),+ ].join('\n')}\n`,+ { status: 200, headers: { 'content-type': 'application/x-ndjson' } },+ );+ await renderTreeWithTeamLoaded();+ const before = fetchUrls.length;++ emitDocumentsChanged(['files']);++ await waitFor(() => expect(fetchUrls.slice(before)).toContain(lazyDirUrl('team')));+ await new Promise((resolve) => setTimeout(resolve, 0));+ const documentFetches = fetchUrls+ .slice(before)+ .filter((url) => url.startsWith('/api/documents'));+ expect(documentFetches.sort()).toEqual([SHOW_ALL_DEPTH1_URL, lazyDirUrl('team')].sort());+ expect(model.items.has('team/notes.md')).toBe(true);+ expect(model.getItem('team/')?.isExpanded()).toBe(true);+ });++ test('external create and delete inside an expanded folder land after the next files signal', async () => {+ responseByUrl.set(lazyDirUrl('team'), () =>+ jsonResponse({+ documents: [docEntry('team/notes'), folderEntry('team/sub', true)],+ truncated: false,+ }),+ );+ responseByUrl.set(lazyDirUrl('team/sub'), () =>+ jsonResponse({ documents: [docEntry('team/sub/deep')], truncated: false }),+ );+ render(<FileTree />);+ await waitFor(() => expect(model.items.size).toBe(3));+ model.getItem('team/')?.expand();+ await waitFor(() => expect(model.items.has('team/sub/')).toBe(true));+ model.getItem('team/sub/')?.expand();+ await waitFor(() => expect(model.items.has('team/sub/deep.md')).toBe(true));++ responseByUrl.set(lazyDirUrl('team'), () =>+ jsonResponse({+ documents: [docEntry('team/notes'), docEntry('team/created')],+ truncated: false,+ }),+ );+ responseByUrl.set(lazyDirUrl('team/sub'), () =>+ jsonResponse({ documents: [], truncated: false }),+ );++ emitDocumentsChanged(['files']);++ await waitFor(() => expect(model.items.has('team/created.md')).toBe(true));+ expect(model.items.has('team/sub/')).toBe(false);+ expect(model.items.has('team/sub/deep.md')).toBe(false);+ expect(model.items.has('team/notes.md')).toBe(true);+ expect(model.getItem('team/')?.isExpanded()).toBe(true);+ });++ test('toggling Show All OFF returns to the index listing; back ON re-seeds the lazy root (QA-007)', async () => {+ const view = await renderTreeWithTeamLoaded();++ mergedConfig = null; // appearance.sidebar.showAllFiles → false+ const beforeOff = fetchUrls.length;+ view.rerender(<FileTree />);++ await waitFor(() => expect([...model.items.keys()]).toEqual(['notes/a.md']));+ expect(fetchUrls.slice(beforeOff).filter((url) => url.startsWith('/api/documents'))).toEqual([+ '/api/documents',+ ]);++ mergedConfig = { appearance: { sidebar: { showAllFiles: true } } };+ const beforeOn = fetchUrls.length;+ view.rerender(<FileTree />);++ await waitFor(() => expect(model.items.has('team/')).toBe(true));+ expect([...model.items.keys()].sort()).toEqual(['README.md', 'empty/', 'team/']);+ expect(fetchUrls.slice(beforeOn).filter((url) => url.startsWith('/api/documents'))).toEqual([+ SHOW_ALL_DEPTH1_URL,+ ]);+ });++ test('a burst of files signals coalesces into one trailing revalidation pass', async () => {+ await renderTreeWithTeamLoaded();+ responseByUrl.set(+ SHOW_ALL_DEPTH1_URL,+ (init) =>+ new Promise<Response>((resolve, reject) => {+ const abort = () => reject(new DOMException('aborted', 'AbortError'));+ if (init?.signal?.aborted) {+ abort();+ return;+ }+ init?.signal?.addEventListener('abort', abort);+ setTimeout(() => resolve(showAllResponseFactory()), 0);+ }),+ );+ const before = fetchUrls.length;++ emitDocumentsChanged(['files']);+ emitDocumentsChanged(['files']);+ emitDocumentsChanged(['files']);++ await waitFor(() =>+ expect(fetchUrls.slice(before).filter((url) => url === lazyDirUrl('team'))).toHaveLength(1),+ );+ await new Promise((resolve) => setTimeout(resolve, 0));+ expect(fetchUrls.slice(before).filter((url) => url === SHOW_ALL_DEPTH1_URL)).toHaveLength(2);+ expect(fetchUrls.slice(before).filter((url) => url === lazyDirUrl('team'))).toHaveLength(1);+ expect(model.items.has('team/notes.md')).toBe(true);+ });++ test('a collapsed folder is not revalidated by the signal and refetches on its next expand', async () => {+ await renderTreeWithTeamLoaded();+ model.getItem('team/')?.collapse();+ responseByUrl.set(lazyDirUrl('team'), () =>+ jsonResponse({ documents: [docEntry('team/renamed')], truncated: false }),+ );+ const before = fetchUrls.length;++ emitDocumentsChanged(['files']);++ await waitFor(() => expect(fetchUrls.slice(before)).toContain(SHOW_ALL_DEPTH1_URL));+ await new Promise((resolve) => setTimeout(resolve, 0));+ expect(fetchUrls.slice(before).filter((url) => url === lazyDirUrl('team'))).toHaveLength(0);++ model.getItem('team/')?.expand();+ await waitFor(() => expect(model.items.has('team/renamed.md')).toBe(true));+ expect(model.items.has('team/notes.md')).toBe(false);+ });++ test('expanded children stay visible while their revalidation is still in flight', async () => {+ await renderTreeWithTeamLoaded();+ let releaseChildren: () => void = () => {};+ responseByUrl.set(+ lazyDirUrl('team'),+ () =>+ new Promise<Response>((resolve) => {+ releaseChildren = () =>+ resolve(jsonResponse({ documents: [docEntry('team/renamed')], truncated: false }));+ }),+ );+ const before = fetchUrls.length;++ emitDocumentsChanged(['files']);++ await waitFor(() =>+ expect(fetchUrls.slice(before).filter((url) => url === lazyDirUrl('team'))).toHaveLength(1),+ );+ expect(model.items.has('team/notes.md')).toBe(true);+ expect(model.getItem('team/')?.isExpanded()).toBe(true);++ releaseChildren();+ await waitFor(() => expect(model.items.has('team/renamed.md')).toBe(true));+ expect(model.items.has('team/notes.md')).toBe(false);+ });+});diff --git a/packages/app/src/components/FileTree.showall-lifecycle.dom.test.tsx b/packages/app/src/components/FileTree.showall-lifecycle.dom.test.tsxnew file mode 100644index 000000000..236fed1d6--- /dev/null+++ b/packages/app/src/components/FileTree.showall-lifecycle.dom.test.tsx@@ -0,0 +1,511 @@+import { afterEach, beforeEach, describe, expect, mock, spyOn, test } from 'bun:test';+import { i18n } from '@lingui/core';+import { cleanup, render, screen, waitFor } from '@testing-library/react';+import type { ReactNode } from 'react';+import { emitDocumentsChanged } from '@/lib/documents-events';++i18n.load('en', {});+i18n.activate('en');++function PassThrough({ children }: { children?: ReactNode }) {+ return <>{children}</>;+}++const SHOW_ALL_DEPTH1_URL = '/api/documents?showAll=true&dir=&depth=1';++let mergedConfig: unknown = { appearance: { sidebar: { showAllFiles: true } } };+let showAllResponseFactory: () => Response = () => jsonResponse({ documents: [] });+let responseByUrl = new Map<string, (init?: RequestInit) => Response | Promise<Response>>();+const fetchUrls: string[] = [];+let activeDocNameForTest: string | null = null;++function lazyDirUrl(dir: string): string {+ return `/api/documents?showAll=true&dir=${encodeURIComponent(dir)}&depth=1`;+}++function jsonResponse(body: unknown, status = 200): Response {+ return new Response(JSON.stringify(body), {+ status,+ headers: { 'content-type': 'application/json' },+ });+}++function docEntry(docName: string) {+ return {+ kind: 'document',+ docName,+ docExt: '.md',+ size: 1,+ modified: '2026-06-12T00:00:00.000Z',+ };+}++function folderEntry(path: string, hasChildren: boolean) {+ return {+ kind: 'folder',+ path,+ size: 0,+ modified: '2026-06-12T00:00:00.000Z',+ hasChildren,+ };+}++function makeFetchMock() {+ return mock(async (input: RequestInfo | URL, init?: RequestInit) => {+ const url = typeof input === 'string' ? input : input instanceof URL ? input.href : input.url;+ fetchUrls.push(url);+ const override = responseByUrl.get(url);+ if (override) return override(init);+ if (url === SHOW_ALL_DEPTH1_URL) return showAllResponseFactory();+ if (url.startsWith('/api/documents')) return jsonResponse({ documents: [docEntry('notes/a')] });+ if (url === '/api/workspace') {+ return jsonResponse({ contentDir: '/tmp/ok', pathSeparator: '/', symlinkResolved: true });+ }+ return jsonResponse({ ok: true });+ });+}++class StubItem {+ expanded = false;+ selected = false;+ constructor(+ readonly path: string,+ private readonly directory: boolean,+ private readonly onChange: () => void = () => {},+ ) {}+ getPath() {+ return this.path;+ }+ isDirectory() {+ return this.directory;+ }+ isExpanded() {+ return this.expanded;+ }+ expand() {+ this.expanded = true;+ this.onChange();+ }+ collapse() {+ this.expanded = false;+ this.onChange();+ }+ isSelected() {+ return this.selected;+ }+ select() {+ this.selected = true;+ }+ deselect() {+ this.selected = false;+ }+ focus() {}+}++class StubModel {+ focusedPath: string | null = null;+ selectedPaths: string[] = [];+ items = new Map<string, StubItem>();+ listeners = new Set<() => void>();+ startRenaming = mock(() => {});+ notify() {+ for (const listener of this.listeners) listener();+ }+ getFocusedPath() {+ return this.focusedPath;+ }+ getFocusedIndex() {+ return -1;+ }+ getItemHeight() {+ return 24;+ }+ getSelectedPaths() {+ return this.selectedPaths;+ }+ getItem(path: string) {+ return this.items.get(path) ?? null;+ }+ resetPaths(paths: string[], opts?: { initialExpandedPaths?: readonly string[] }) {+ this.items.clear();+ for (const path of paths) {+ this.items.set(path, new StubItem(path, path.endsWith('/'), () => this.notify()));+ }+ for (const path of opts?.initialExpandedPaths ?? []) {+ const item = this.items.get(path);+ if (item) item.expanded = true;+ }+ this.notify();+ }+ subscribe(listener: () => void) {+ this.listeners.add(listener);+ return () => {+ this.listeners.delete(listener);+ };+ }+ onMutation() {+ return () => {};+ }+ isSearchOpen() {+ return false;+ }+ add(path: string) {+ this.items.set(path, new StubItem(path, path.endsWith('/'), () => this.notify()));+ }+ move() {}+ remove() {}+}++const model = new StubModel();++mock.module('sonner', () => ({ toast: { success: mock(() => {}), error: mock(() => {}) } }));+mock.module('next-themes', () => ({ useTheme: () => ({ resolvedTheme: 'light' }) }));+mock.module('@/editor/DocumentContext', () => ({+ useDocumentContext: () => ({+ activeDocName: activeDocNameForTest,+ activeTarget: null,+ closeTabs: mock(() => {}),+ closeDocument: mock(() => {}),+ closeAndClearDocument: mock(async () => {}),+ closeAndClearForDelete: mock(async () => {}),+ closeAndClearForRename: mock(async () => {}),+ getPoolActiveDocName: () => null,+ poolHas: () => false,+ isNewTabActive: false,+ openTarget: mock(() => {}),+ prewarm: () => {},+ remapTabsForRename: mock(() => {}),+ }),+}));+mock.module('@/components/PageListContext', () => ({+ usePageList: () => ({ addPage: mock(() => {}) }),+}));+mock.module('./ui/sidebar', () => ({+ useSidebar: () => ({ notifySidebarFileSelected: mock(() => {}) }),+}));+mock.module('@/lib/config-provider', () => ({+ useConfigContext: () => ({+ okignoreBinding: null,+ projectLocalBinding: null,+ merged: mergedConfig,+ }),+}));+mock.module('./handoff/useInstalledAgents', () => ({ useInstalledAgents: () => ({ states: {} }) }));+mock.module('./handoff/useHandoffDispatch', () => ({+ buildFolderHandoffInput: () => null,+ buildHandoffInput: () => null,+ useHandoffDispatch: () => ({ dispatch: mock(async () => ({ ok: true as const })) }),+}));+mock.module('./handoff/OpenInAgentContextSubmenu', () => ({+ OpenInAgentContextSubmenu: () => null,+}));+mock.module('./sidebar-hover-prewarm', () => ({+ cancelHoverPrewarm: () => {},+ scheduleHoverPrewarm: () => {},+}));+mock.module('@/components/ui/button', () => ({+ Button: ({ children, ...props }: { children?: ReactNode; [k: string]: unknown }) => (+ <button type="button" {...props}>+ {children}+ </button>+ ),+}));+mock.module('@/components/ui/dialog', () => ({ Dialog: PassThrough }));+mock.module('@/components/ui/dropdown-menu', () => ({+ DropdownMenu: PassThrough,+ DropdownMenuCheckboxItem: PassThrough,+ DropdownMenuContent: PassThrough,+ DropdownMenuItem: PassThrough,+ DropdownMenuSeparator: () => <hr />,+ DropdownMenuSub: PassThrough,+ DropdownMenuSubContent: PassThrough,+ DropdownMenuSubTrigger: PassThrough,+ DropdownMenuTrigger: PassThrough,+}));+mock.module('@/components/ui/skeleton', () => ({+ Skeleton: ({ className }: { className?: string }) => <span className={className} />,+}));+mock.module('@/components/DeleteConfirmationDialog', () => ({+ DeleteConfirmationDialog: () => null,+}));+mock.module('@/components/NewItemDialog', () => ({ NewItemDialog: () => null }));+mock.module('@/components/TrashFailureModal', () => ({+ TrashFailureModal: () => null,+ coerceTrashFailureReason: (reason: string) => reason,+}));+mock.module('@/components/use-selection-mirror', () => ({+ asDirectoryHandle: (item: StubItem | null) => (item?.isDirectory() ? item : null),+ useSelectionMirror: () => {},+}));+mock.module('@pierre/trees', () => ({+ FILE_TREE_TAG_NAME: 'ok-file-tree',+ themeToTreeStyles: () => ({}),+}));+mock.module('@pierre/trees/react', () => ({+ useFileTree: () => ({ model }),+ FileTree: ({ header }: { header?: ReactNode }) => (+ <div data-testid="fake-pierre-tree" role="tree">+ {header}+ </div>+ ),+}));++const { FileTree } = await import('./FileTree');++describe('FileTree showAll notice lifecycle', () => {+ let consoleWarnSpy: ReturnType<typeof spyOn>;++ beforeEach(() => {+ mergedConfig = { appearance: { sidebar: { showAllFiles: true } } };+ showAllResponseFactory = () =>+ jsonResponse({+ documents: [folderEntry('capped', true), folderEntry('uncapped', true), docEntry('README')],+ truncated: false,+ });+ responseByUrl = new Map();+ fetchUrls.length = 0;+ activeDocNameForTest = null;+ model.items.clear();+ model.listeners.clear();+ model.focusedPath = null;+ model.selectedPaths = [];+ globalThis.fetch = makeFetchMock() as unknown as typeof fetch;+ consoleWarnSpy = spyOn(console, 'warn').mockImplementation(() => {});+ });++ afterEach(() => {+ cleanup();+ consoleWarnSpy.mockRestore();+ });++ async function renderSeededTree() {+ render(<FileTree />);+ await waitFor(() => expect(model.items.size).toBe(3));+ }++ async function expandCappedFolderToTruncation() {+ responseByUrl.set(lazyDirUrl('capped'), () =>+ jsonResponse({+ documents: [docEntry('capped/one'), docEntry('capped/two')],+ truncated: true,+ }),+ );+ model.getItem('capped/')?.expand();+ await waitFor(() => {+ expect(screen.getByRole('status').textContent ?? '').toContain('Showing the first 2 items');+ });+ }++ test('a child-fetch error while a truncation banner is up renders BOTH rows coherently (QA-003)', async () => {+ await renderSeededTree();+ await expandCappedFolderToTruncation();++ responseByUrl.set(lazyDirUrl('uncapped'), () =>+ jsonResponse({ title: 'Folder walk failed' }, 500),+ );+ model.getItem('uncapped/')?.expand();++ await waitFor(() => {+ expect(screen.getByRole('alert').textContent ?? '').toContain('Folder walk failed');+ });+ const alert = screen.getByRole('alert');+ const status = screen.getByRole('status');+ expect(status.textContent ?? '').toContain('Showing the first 2 items');+ expect(alert.compareDocumentPosition(status) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy();+ expect(alert.className).toContain('rounded-md');+ expect(status.className).toContain('rounded-md');+ expect(model.items.has('capped/one.md')).toBe(true);++ const scopedWarn = consoleWarnSpy.mock.calls.find(+ (call) =>+ typeof call[0] === 'string' &&+ call[0].includes('lazy folder children http error') &&+ call[1] === 'uncapped/',+ );+ expect(scopedWarn).toBeDefined();+ });++ test('an untruncated child load does NOT clear another level’s banner (QA-023 per-cycle semantics)', async () => {+ await renderSeededTree();+ await expandCappedFolderToTruncation();++ responseByUrl.set(lazyDirUrl('uncapped'), () =>+ jsonResponse({ documents: [docEntry('uncapped/fine')], truncated: false }),+ );+ model.getItem('uncapped/')?.expand();+ await waitFor(() => expect(model.items.has('uncapped/fine.md')).toBe(true));++ expect(screen.getByRole('status').textContent ?? '').toContain('Showing the first 2 items');+ });++ test('the next root refresh resets the banner from the root response (QA-023 lifecycle)', async () => {+ await renderSeededTree();+ await expandCappedFolderToTruncation();++ model.getItem('capped/')?.collapse();+ emitDocumentsChanged(['files']);++ await waitFor(() => expect(screen.queryByRole('status')).toBeNull());+ expect(model.items.has('capped/')).toBe(true);+ });++ test('a network-rejected child fetch logs the folder-scoped diagnostic (QA-022)', async () => {+ await renderSeededTree();+ responseByUrl.set(lazyDirUrl('uncapped'), () => {+ throw new TypeError('Failed to fetch');+ });+ model.getItem('uncapped/')?.expand();++ await waitFor(() => {+ expect(screen.getByRole('alert').textContent ?? '').toContain('Could not reach server');+ });+ const networkWarn = consoleWarnSpy.mock.calls.find(+ (call) =>+ typeof call[0] === 'string' && call[0].includes('lazy folder children fetch failed'),+ );+ expect(networkWarn).toBeDefined();+ });+});++describe('FileTree showAll interrupted NDJSON seed', () => {+ let consoleWarnSpy: ReturnType<typeof spyOn>;++ beforeEach(() => {+ mergedConfig = { appearance: { sidebar: { showAllFiles: true } } };+ showAllResponseFactory = () => jsonResponse({ documents: [] });+ responseByUrl = new Map();+ fetchUrls.length = 0;+ activeDocNameForTest = null;+ model.items.clear();+ model.listeners.clear();+ model.focusedPath = null;+ model.selectedPaths = [];+ globalThis.fetch = makeFetchMock() as unknown as typeof fetch;+ consoleWarnSpy = spyOn(console, 'warn').mockImplementation(() => {});+ });++ afterEach(() => {+ cleanup();+ consoleWarnSpy.mockRestore();+ });++ function dyingSeedResponse(): Response {+ const encoder = new TextEncoder();+ const stream = new ReadableStream<Uint8Array>({+ start(controller) {+ controller.enqueue(encoder.encode(`${JSON.stringify(folderEntry('ghost', true))}\n`));+ controller.error(new TypeError('connection reset'));+ },+ });+ return new Response(stream, {+ status: 200,+ headers: { 'content-type': 'application/x-ndjson' },+ });+ }++ test('a FIRST seed stream dying mid-listing shows an honest error state, then recovers (QA-025)', async () => {+ let seedRequests = 0;+ showAllResponseFactory = () => {+ seedRequests += 1;+ if (seedRequests === 1) return dyingSeedResponse();+ return jsonResponse({+ documents: [folderEntry('team', true), docEntry('README')],+ truncated: false,+ });+ };+ render(<FileTree />);++ await screen.findByText('Could not reach server');+ expect(model.items.has('ghost/')).toBe(false);+ expect(screen.queryByTestId('fake-pierre-tree')).toBeNull();+ expect(screen.queryByRole('status')).toBeNull();++ window.dispatchEvent(new Event('focus'));+ await waitFor(() => expect(model.items.has('team/')).toBe(true));+ expect(model.items.has('README.md')).toBe(true);+ expect(model.items.has('ghost/')).toBe(false);+ expect(screen.queryByRole('alert')).toBeNull();+ expect(screen.queryByText('Could not reach server')).toBeNull();+ });++ test('a REFRESH stream dying mid-listing raises the header alert over the intact tree, then recovers (QA-025)', async () => {+ let seedRequests = 0;+ showAllResponseFactory = () => {+ seedRequests += 1;+ if (seedRequests === 2) return dyingSeedResponse();+ return jsonResponse({+ documents: [folderEntry('team', true), docEntry('README')],+ truncated: false,+ });+ };+ render(<FileTree />);+ await waitFor(() => expect(model.items.has('team/')).toBe(true));++ window.dispatchEvent(new Event('focus'));+ const alert = await screen.findByRole('alert');+ expect(alert.textContent ?? '').toContain('Could not reach server');+ expect(model.items.has('team/')).toBe(true);+ expect(model.items.has('README.md')).toBe(true);+ expect(model.items.has('ghost/')).toBe(false);++ window.dispatchEvent(new Event('focus'));+ await waitFor(() => expect(screen.queryByRole('alert')).toBeNull());+ expect(model.items.has('team/')).toBe(true);+ expect(model.items.has('ghost/')).toBe(false);+ });+});++describe('FileTree showAll deep-link progressive drill-down', () => {+ let consoleWarnSpy: ReturnType<typeof spyOn>;++ beforeEach(() => {+ mergedConfig = { appearance: { sidebar: { showAllFiles: true } } };+ showAllResponseFactory = () =>+ jsonResponse({ documents: [folderEntry('a', true)], truncated: false });+ responseByUrl = new Map();+ fetchUrls.length = 0;+ activeDocNameForTest = null;+ model.items.clear();+ model.listeners.clear();+ model.focusedPath = null;+ model.selectedPaths = [];+ globalThis.fetch = makeFetchMock() as unknown as typeof fetch;+ consoleWarnSpy = spyOn(console, 'warn').mockImplementation(() => {});+ });++ afterEach(() => {+ cleanup();+ consoleWarnSpy.mockRestore();+ });++ test('opening a doc 3 levels deep auto-expands and lazily loads each ancestor level exactly once (QA-026)', async () => {+ activeDocNameForTest = 'a/b/c/doc';+ responseByUrl.set(lazyDirUrl('a'), () =>+ jsonResponse({ documents: [folderEntry('a/b', true)], truncated: false }),+ );+ responseByUrl.set(lazyDirUrl('a/b'), () =>+ jsonResponse({ documents: [folderEntry('a/b/c', true)], truncated: false }),+ );+ responseByUrl.set(lazyDirUrl('a/b/c'), () =>+ jsonResponse({ documents: [docEntry('a/b/c/doc')], truncated: false }),+ );+ render(<FileTree />);++ await waitFor(() => expect(model.items.has('a/b/c/doc.md')).toBe(true));+ expect(model.getItem('a/')?.isExpanded()).toBe(true);+ expect(model.getItem('a/b/')?.isExpanded()).toBe(true);+ expect(model.getItem('a/b/c/')?.isExpanded()).toBe(true);++ await new Promise((resolve) => setTimeout(resolve, 0));+ expect(fetchUrls.filter((url) => url === lazyDirUrl('a'))).toHaveLength(1);+ expect(fetchUrls.filter((url) => url === lazyDirUrl('a/b'))).toHaveLength(1);+ expect(fetchUrls.filter((url) => url === lazyDirUrl('a/b/c'))).toHaveLength(1);+ expect(fetchUrls.filter((u) => u.includes('showAll=true') && !u.includes('depth=1'))).toEqual(+ [],+ );++ const settledCount = fetchUrls.filter((url) => url.startsWith('/api/documents')).length;+ await new Promise((resolve) => setTimeout(resolve, 10));+ expect(fetchUrls.filter((url) => url.startsWith('/api/documents')).length).toBe(settledCount);+ });+});diff --git a/packages/app/src/components/FileTree.showall-truncation.dom.test.tsx b/packages/app/src/components/FileTree.showall-truncation.dom.test.tsxindex 4a4b5de0a..a0e256ee7 100644--- a/packages/app/src/components/FileTree.showall-truncation.dom.test.tsx+++ b/packages/app/src/components/FileTree.showall-truncation.dom.test.tsx@@ -1,11 +1,17 @@import { afterEach, beforeEach, describe, expect, mock, spyOn, test } from 'bun:test';+import { i18n } from '@lingui/core';import { cleanup, render, screen, waitFor, within } from '@testing-library/react';import type { ReactNode } from 'react';+i18n.load('en', {});+i18n.activate('en');+function PassThrough({ children }: { children?: ReactNode }) {return <>{children}</>;}+const SHOW_ALL_DEPTH1_URL = '/api/documents?showAll=true&dir=&depth=1';+let mergedConfig: unknown = { appearance: { sidebar: { showAllFiles: true } } };let showAllBody: unknown = { documents: [], truncated: true };let showAllStatus = 200;@@ -32,7 +38,7 @@ function makeFetchMock() {return mock(async (input: RequestInfo | URL) => {const url = typeof input === 'string' ? input : input instanceof URL ? input.href : input.url;fetchUrls.push(url);- if (url === '/api/documents?showAll=true') return jsonResponse(showAllBody, showAllStatus);+ if (url === SHOW_ALL_DEPTH1_URL) return jsonResponse(showAllBody, showAllStatus);if (url.startsWith('/api/documents')) return jsonResponse({ documents: [docEntry('notes/a')] });if (url === '/api/workspace') {return jsonResponse({ contentDir: '/tmp/ok', pathSeparator: '/', symlinkResolved: true });@@ -228,28 +234,46 @@ describe('FileTree showAll truncation notice', () => {consoleWarnSpy.mockRestore();});- test('renders the role=status notice with the cap-bounded count + actionable copy when truncated (QA-001/QA-002)', async () => {+ test('renders the truncation notice as a contained, iconed status row with truthful copy (QA-001/QA-002)', async () => {showAllBody = {documents: [docEntry('a'), docEntry('b'), docEntry('c')],truncated: true,};render(<FileTree />);- await waitFor(() => expect(fetchUrls).toContain('/api/documents?showAll=true'));+ await waitFor(() => expect(fetchUrls).toContain(SHOW_ALL_DEPTH1_URL));const status = await screen.findByRole('status');const text = status.textContent ?? '';- expect(text).toContain('Showing first');- expect(text).toContain('3');- expect(text).toContain('use search to find others');+ expect(text).toContain('Showing the first 3 items in one folder');+ expect(text).toContain('the rest of that folder is hidden');+ expect(text.toLowerCase()).not.toContain('search');+ expect(status.className).toContain('rounded-md');+ expect(status.className).toContain('bg-muted/50');+ const icon = status.querySelector('svg');+ expect(icon).not.toBeNull();+ expect(icon?.getAttribute('aria-hidden')).toBe('true');expect(screen.queryByRole('alert')).toBeNull();});+ test('locale-formats the truncation count (1,200 — not a raw 1200)', async () => {+ showAllBody = {+ documents: Array.from({ length: 1200 }, (_, i) => docEntry(`dir/file-${i}`)),+ truncated: true,+ };+ render(<FileTree />);++ await waitFor(() => {+ expect(screen.getByRole('status').textContent ?? '').toContain('1,200');+ });+ expect(screen.getByRole('status').textContent ?? '').not.toContain('1200');+ });+test('does NOT render the notice when the showAll response is not truncated (QA-002 negative)', async () => {showAllBody = { documents: [docEntry('a'), docEntry('b')], truncated: false };render(<FileTree />);await screen.findByTestId('fake-pierre-tree');- expect(fetchUrls).toContain('/api/documents?showAll=true');+ expect(fetchUrls).toContain(SHOW_ALL_DEPTH1_URL);expect(screen.queryByRole('status')).toBeNull();});@@ -258,7 +282,7 @@ describe('FileTree showAll truncation notice', () => {render(<FileTree />);await screen.findByTestId('fake-pierre-tree');- expect(fetchUrls).toContain('/api/documents?showAll=true');+ expect(fetchUrls).toContain(SHOW_ALL_DEPTH1_URL);expect(screen.queryByRole('status')).toBeNull();});@@ -269,7 +293,7 @@ describe('FileTree showAll truncation notice', () => {await screen.findByTestId('fake-pierre-tree');expect(fetchUrls).toContain('/api/documents');- expect(fetchUrls).not.toContain('/api/documents?showAll=true');+ expect(fetchUrls.some((u) => u.includes('showAll=true'))).toBe(false);expect(screen.queryByRole('status')).toBeNull();});@@ -289,7 +313,7 @@ describe('FileTree showAll truncation notice', () => {showAllBody = { documents: [docEntry('a'), docEntry('b'), docEntry('c')], truncated: true };render(<FileTree />);await waitFor(() =>- expect(screen.getByRole('status').textContent ?? '').toContain('Showing first'),+ expect(screen.getByRole('status').textContent ?? '').toContain('Showing the first'),);showAllBody = { title: 'Internal server error' };@@ -297,6 +321,13 @@ describe('FileTree showAll truncation notice', () => {window.dispatchEvent(new Event('focus'));await waitFor(() => expect(screen.queryByRole('status')).toBeNull());- expect(screen.getByRole('alert').textContent ?? '').toContain('Internal server error');+ const alert = screen.getByRole('alert');+ expect(alert.textContent ?? '').toContain('Internal server error');+ expect(alert.className).toContain('rounded-md');+ expect(alert.className).toContain('bg-muted/50');+ expect(alert.className).toContain('text-destructive');+ const alertIcon = alert.querySelector('svg');+ expect(alertIcon).not.toBeNull();+ expect(alertIcon?.getAttribute('aria-hidden')).toBe('true');});});diff --git a/packages/app/src/components/FileTree.tsx b/packages/app/src/components/FileTree.tsxindex 415b7b6bb..fff5b5081 100644--- a/packages/app/src/components/FileTree.tsx+++ b/packages/app/src/components/FileTree.tsx@@ -36,10 +36,12 @@ import {FolderOpen,FolderPlus,FoldVertical,+ Info,Pencil,SquarePen,Terminal,Trash2,+ TriangleAlert,UnfoldVertical,} from 'lucide-react';import { __iconNode as botIcon } from 'lucide-react/dist/esm/icons/bot';@@ -48,6 +50,7 @@ import { useTheme } from 'next-themes';import {type CSSProperties,type MouseEvent as ReactMouseEvent,+ type ReactNode,type Ref,startTransition,useEffect,@@ -113,6 +116,7 @@ import {isAssetEntry,isDocumentEntry,isFolderEntry,+ toFileEntries,} from '@/components/file-tree-utils';import { NewItemDialog } from '@/components/NewItemDialog';import {@@ -172,10 +176,11 @@ import {consumeShowAllStream,isNdjsonResponse,SHOW_ALL_NDJSON_ACCEPT,+ ShowAllStreamError,} from '@/lib/show-all-stream';import { OK_SIDEBAR_DRAG_MIME, serializeSidebarDragPayload } from '@/lib/sidebar-drag';import { joinWorkspacePath } from '@/lib/workspace-paths';-import { mergeAndPruneRecentLocalAdds } from './file-tree-merge';+import { mergeAndPruneRecentLocalAdds, spliceLazyFolderChildren } from './file-tree-merge';import { OpenInAgentContextSubmenu } from './handoff/OpenInAgentContextSubmenu';import {buildFolderHandoffInput,@@ -972,8 +977,49 @@ export interface FileTreeHandle {subscribe(listener: () => void): () => void;}+type ShowAllDepth1ListingResult =+ | { kind: 'entries'; entries: FileEntry[]; truncated: boolean }+ | { kind: 'http-error'; title: string }+ | { kind: 'network-error'; cause: unknown };++async function fetchShowAllDepth1Listing(+ dir: string,+ signal: AbortSignal,+ fallbackErrorTitle: string,+ schemaMismatchTitle: string,+): Promise<ShowAllDepth1ListingResult> {+ try {+ const res = await fetch(`/api/documents?showAll=true&dir=${encodeURIComponent(dir)}&depth=1`, {+ signal,+ headers: SHOW_ALL_NDJSON_ACCEPT,+ });+ if (isNdjsonResponse(res)) {+ const consumed = await consumeShowAllStream(res);+ return {+ kind: 'entries',+ entries: toFileEntries(consumed.entries),+ truncated: consumed.truncated,+ };+ }+ const parsed = await parseServerResponse(res, fallbackErrorTitle);+ if (!parsed.ok) return { kind: 'http-error', title: parsed.title };+ const success = DocumentListSuccessSchema.safeParse(parsed.body);+ if (!success.success) return { kind: 'http-error', title: schemaMismatchTitle };+ return {+ kind: 'entries',+ entries: toFileEntries(success.data.documents),+ truncated: success.data.truncated === true,+ };+ } catch (cause) {+ if (cause instanceof ShowAllStreamError) {+ return { kind: 'http-error', title: cause.message };+ }+ return { kind: 'network-error', cause };+ }+}+export function FileTree({ ref }: { ref?: Ref<FileTreeHandle | null> }) {- const { t } = useLingui();+ const { t, i18n } = useLingui();const {activeDocName,activeTarget,@@ -1095,6 +1141,12 @@ export function FileTree({ ref }: { ref?: Ref<FileTreeHandle | null> }) {const sidebarDragClearTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);const busyPathRef = useRef<string | null>(null);const recentLocalAddsRef = useRef<Map<string, number>>(new Map());+ const lazyLoadedDirTreePathsRef = useRef<Set<string>>(new Set());+ const lazyChildFetchControllersRef = useRef<Map<string, AbortController>>(new Map());+ const lazyChildFetchGenerationRef = useRef(0);+ const prevExpandedFolderTreePathsRef = useRef<ReadonlySet<string>>(new Set());+ const detectLazyFolderExpansionsRef = useRef<() => void>(() => {});+ const revalidateExpandedLazyDirsRef = useRef<() => void>(() => {});const showHiddenFilesRef = useRef<boolean>(false);const showAllFilesRef = useRef<boolean>(false);const refreshDocsScheduleRef = useRef<(() => void) | null>(null);@@ -1299,6 +1351,67 @@ export function FileTree({ ref }: { ref?: Ref<FileTreeHandle | null> }) {});};+ async function fetchLazyFolderChildren(folderTreePath: string) {+ const generation = lazyChildFetchGenerationRef.current;+ const controller = new AbortController();+ lazyChildFetchControllersRef.current.set(folderTreePath, controller);+ const result = await fetchShowAllDepth1Listing(+ treeDirectoryPathToFolderPath(folderTreePath),+ controller.signal,+ t`Failed to load documents`,+ t`Documents response did not match expected shape.`,+ );+ if (lazyChildFetchControllersRef.current.get(folderTreePath) === controller) {+ lazyChildFetchControllersRef.current.delete(folderTreePath);+ }+ if (controller.signal.aborted || generation !== lazyChildFetchGenerationRef.current) return;+ if (result.kind === 'network-error') {+ setError(t`Could not reach server`);+ console.warn('[FileTree] lazy folder children fetch failed:', folderTreePath, result.cause);+ return;+ }+ if (result.kind === 'http-error') {+ console.warn('[FileTree] lazy folder children http error:', folderTreePath, result.title);+ setError(result.title);+ return;+ }+ const bypassClientDotDrop = showHiddenFilesRef.current || showAllFilesRef.current;+ const children = filterVisibleEntries(result.entries, bypassClientDotDrop);+ lazyLoadedDirTreePathsRef.current.add(folderTreePath);+ setDocuments((prev) =>+ spliceLazyFolderChildren(prev, folderTreePath, children, recentLocalAddsRef.current),+ );+ setError(null);+ if (result.truncated) setTruncatedShownCount(result.entries.length);+ }++ const detectLazyFolderExpansions = () => {+ const expanded = collectExpandedFolderTreePaths();+ const previous = prevExpandedFolderTreePathsRef.current;+ prevExpandedFolderTreePathsRef.current = expanded;+ if (!showAllFilesRef.current) return;+ for (const folderTreePath of expanded) {+ if (previous.has(folderTreePath)) continue;+ if (lazyLoadedDirTreePathsRef.current.has(folderTreePath)) continue;+ if (lazyChildFetchControllersRef.current.has(folderTreePath)) continue;+ const folderPath = treeDirectoryPathToFolderPath(folderTreePath);+ const entry = documentsRef.current.find(+ (candidate): candidate is Extract<FileEntry, { kind: 'folder' }> =>+ isFolderEntry(candidate) && candidate.path === folderPath,+ );+ if (entry?.hasChildren === false) continue;+ void fetchLazyFolderChildren(folderTreePath);+ }+ };++ const revalidateExpandedLazyDirs = () => {+ for (const folderTreePath of collectExpandedFolderTreePaths()) {+ if (lazyLoadedDirTreePathsRef.current.has(folderTreePath)) continue;+ if (lazyChildFetchControllersRef.current.has(folderTreePath)) continue;+ void fetchLazyFolderChildren(folderTreePath);+ }+ };+const reconcileModelAfterChipRename = (current: readonly FileEntry[],next: readonly FileEntry[],@@ -1551,9 +1664,15 @@ export function FileTree({ ref }: { ref?: Ref<FileTreeHandle | null> }) {refreshController?.abort();const controller = new AbortController();refreshController = controller;+ lazyChildFetchGenerationRef.current += 1;+ for (const childController of lazyChildFetchControllersRef.current.values()) {+ childController.abort();+ }+ lazyChildFetchControllersRef.current.clear();+ lazyLoadedDirTreePathsRef.current.clear();try {const showAll = showAllFilesRef.current;- const url = showAll ? '/api/documents?showAll=true' : '/api/documents';+ const url = showAll ? '/api/documents?showAll=true&dir=&depth=1' : '/api/documents';const res = await fetch(url, {signal: controller.signal,headers: showAll ? SHOW_ALL_NDJSON_ACCEPT : undefined,@@ -1562,18 +1681,13 @@ export function FileTree({ ref }: { ref?: Ref<FileTreeHandle | null> }) {const { entries, truncated } = await consumeShowAllStream(res);if (!active) return;const bypassClientDotDrop = showHiddenFilesRef.current || showAll;- const serverEntries = filterVisibleEntries(- entries as unknown as FileEntry[],- bypassClientDotDrop,+ const serverEntries = filterVisibleEntries(toFileEntries(entries), bypassClientDotDrop);+ setDocuments((prev) =>+ spliceLazyFolderChildren(prev, '', serverEntries, recentLocalAddsRef.current),);- const merged = mergeAndPruneRecentLocalAdds(- serverEntries,- documentsRef.current,- recentLocalAddsRef.current,- );- setDocuments(merged);setError(null);setTruncatedShownCount(truncated ? entries.length : null);+ revalidateExpandedLazyDirsRef.current();} else {const parsed = await parseServerResponse(res, t`Failed to load documents`);if (!active) return;@@ -1588,25 +1702,34 @@ export function FileTree({ ref }: { ref?: Ref<FileTreeHandle | null> }) {} else {const bypassClientDotDrop = showHiddenFilesRef.current || showAll;const serverEntries = filterVisibleEntries(- success.data.documents as unknown as FileEntry[],+ toFileEntries(success.data.documents),bypassClientDotDrop,);- const merged = mergeAndPruneRecentLocalAdds(- serverEntries,- documentsRef.current,- recentLocalAddsRef.current,- );- setDocuments(merged);+ if (showAll) {+ setDocuments((prev) =>+ spliceLazyFolderChildren(prev, '', serverEntries, recentLocalAddsRef.current),+ );+ } else {+ const merged = mergeAndPruneRecentLocalAdds(+ serverEntries,+ documentsRef.current,+ recentLocalAddsRef.current,+ );+ setDocuments(merged);+ }setError(null);setTruncatedShownCount(showAll && success.data.truncated === true ? success.data.documents.length : null,);+ if (showAll) revalidateExpandedLazyDirsRef.current();}}}} catch (err) {if (controller.signal.aborted) return;- if (active) setError(t`Could not reach server`);+ if (active) {+ setError(err instanceof ShowAllStreamError ? err.message : t`Could not reach server`);+ }console.warn('[FileTree] fetch failed:', err);}if (active) setLoading(false);@@ -1631,6 +1754,10 @@ export function FileTree({ ref }: { ref?: Ref<FileTreeHandle | null> }) {active = false;refreshDocsScheduleRef.current = null;scheduler.dispose();+ for (const childController of lazyChildFetchControllersRef.current.values()) {+ childController.abort();+ }+ lazyChildFetchControllersRef.current.clear();window.removeEventListener('focus', handleResume);window.removeEventListener('visibilitychange', handleResume);unsubscribe();@@ -1716,6 +1843,10 @@ export function FileTree({ ref }: { ref?: Ref<FileTreeHandle | null> }) {});}, [model]);+ useEffect(() => {+ return model.subscribe(() => detectLazyFolderExpansionsRef.current());+ }, [model]);+useEffect(() => {return model.onMutation('remove', (event) => {const pending = pendingCreateRef.current;@@ -2193,6 +2324,8 @@ export function FileTree({ ref }: { ref?: Ref<FileTreeHandle | null> }) {treePathsRef.current = treePaths;folderTreePathsRef.current = folderTreePaths;activeAncestorTreePathsRef.current = activeAncestorTreePaths;+ detectLazyFolderExpansionsRef.current = detectLazyFolderExpansions;+ revalidateExpandedLazyDirsRef.current = revalidateExpandedLazyDirs;cleanupPendingCreateRef.current = cleanupPendingCreate;handleSelectionChangeRef.current = (selectedPaths) => {if (suppressSelectionRef.current || sidebarDragInProgressRef.current) return;@@ -2866,24 +2999,24 @@ export function FileTree({ ref }: { ref?: Ref<FileTreeHandle | null> }) {const anyActionBusy = busyPath !== null;const primaryDeleteTarget = deleteRequest?.targets[0] ?? null;+ let truncationNotice: string | null = null;+ if (truncatedShownCount !== null) {+ const formattedCount = new Intl.NumberFormat(i18n.locale).format(truncatedShownCount);+ truncationNotice = plural(truncatedShownCount, {+ one: 'Showing the first item in one folder — the rest of that folder is hidden. Turn off Show all files for the filtered view.',+ other: `Showing the first ${formattedCount} items in one folder — the rest of that folder is hidden. Turn off Show all files for the filtered view.`,+ });+ }return (<><div ref={fileTreeHostRef} className="flex min-h-0 flex-1 flex-col"><PierreFileTreeheader={- (error || truncatedShownCount !== null) && (+ (error || truncationNotice !== null) && (<>- {error && (- <span role="alert" className="px-3 pb-1 text-destructive text-xs">- {error}- </span>- )}- {truncatedShownCount !== null && (- <span role="status" className="px-3 pb-1 text-muted-foreground text-xs">- <Trans>- Showing first {truncatedShownCount} items — use search to find others- </Trans>- </span>+ {error && <FileTreeHeaderNotice kind="error">{error}</FileTreeHeaderNotice>}+ {truncationNotice !== null && (+ <FileTreeHeaderNotice kind="info">{truncationNotice}</FileTreeHeaderNotice>)}</>)@@ -3040,3 +3173,18 @@ function FileTreeSkeleton() {</div>);}++function FileTreeHeaderNotice({ kind, children }: { kind: 'error' | 'info'; children: ReactNode }) {+ const Icon = kind === 'error' ? TriangleAlert : Info;+ return (+ <span+ role={kind === 'error' ? 'alert' : 'status'}+ className={`mx-2 mb-1 flex items-start gap-1.5 rounded-md bg-muted/50 px-2 py-1.5 text-xs leading-snug ${+ kind === 'error' ? 'text-destructive' : 'text-muted-foreground'+ }`}+ >+ <Icon aria-hidden="true" className="mt-0.5 size-3.5 shrink-0" />+ <span className="min-w-0">{children}</span>+ </span>+ );+}diff --git a/packages/app/src/components/file-tree-merge.test.ts b/packages/app/src/components/file-tree-merge.test.tsindex daec94c9a..ed02ad725 100644--- a/packages/app/src/components/file-tree-merge.test.ts+++ b/packages/app/src/components/file-tree-merge.test.ts@@ -22,7 +22,11 @@*/import { describe, expect, test } from 'bun:test';-import { mergeAndPruneRecentLocalAdds, STALE_REFRESH_PRESERVE_WINDOW_MS } from './file-tree-merge';+import {+ mergeAndPruneRecentLocalAdds,+ STALE_REFRESH_PRESERVE_WINDOW_MS,+ spliceLazyFolderChildren,+} from './file-tree-merge';import type { FileEntry } from './file-tree-utils';function doc(basename: string, modified = '2026-05-21T00:00:00.000Z'): FileEntry {@@ -145,3 +149,102 @@ describe('mergeAndPruneRecentLocalAdds', () => {expect(recentAdds.has('edge.md')).toBe(true);});});++describe('spliceLazyFolderChildren', () => {+ test('a splice for a target folder absent from the entry set is a no-op', () => {+ const current = [folder('team'), doc('README')];+ const result = spliceLazyFolderChildren(current, 'gone/', [doc('gone/x')], new Map());+ expect(result).toEqual(current);+ });++ test('replaces the folder level with the server children; entries outside it pass through', () => {+ const current = [folder('team'), folder('other'), doc('README')];+ const children = [doc('team/notes'), folder('team/sub')];+ const recentAdds = new Map<string, number>();++ const result = spliceLazyFolderChildren(current, 'team/', children, recentAdds);++ expect(result).toEqual([+ folder('team'),+ folder('other'),+ doc('README'),+ doc('team/notes'),+ folder('team/sub'),+ ]);+ });++ test('a parent-level resplice leaves already-loaded grandchildren untouched', () => {+ const current = [folder('team'), folder('team/sub'), doc('team/sub/deep'), doc('team/notes')];+ const children = [folder('team/sub')]; // team/notes gone server-side+ const recentAdds = new Map<string, number>();++ const result = spliceLazyFolderChildren(current, 'team/', children, recentAdds);++ expect(result).toEqual([folder('team'), doc('team/sub/deep'), folder('team/sub')]);+ });++ test('sibling folders sharing the name prefix are not treated as children', () => {+ const current = [folder('team'), folder('teammates'), doc('teammates/roster')];+ const children = [doc('team/notes')];+ const recentAdds = new Map<string, number>();++ const result = spliceLazyFolderChildren(current, 'team/', children, recentAdds);++ expect(result).toEqual([+ folder('team'),+ folder('teammates'),+ doc('teammates/roster'),+ doc('team/notes'),+ ]);+ });++ test('optimistic local adds inside the folder ride the same preserve window as a full refresh', () => {+ const NOW = 1_700_000_000_000;+ const current = [folder('team'), doc('team/just-created')];+ const children = [doc('team/notes')]; // server response races the create+ const recentAdds = new Map<string, number>([['team/just-created.md', NOW]]);++ const result = spliceLazyFolderChildren(current, 'team/', children, recentAdds, NOW);++ expect(result).toEqual([folder('team'), doc('team/notes'), doc('team/just-created')]);+ expect(recentAdds.has('team/just-created.md')).toBe(true);+ });++ test('descendants of a child folder the server no longer returns are pruned with it', () => {+ const current = [folder('team'), folder('team/sub'), doc('team/sub/deep'), doc('team/notes')];+ const children = [doc('team/notes')]; // team/sub gone server-side+ const recentAdds = new Map<string, number>();++ const result = spliceLazyFolderChildren(current, 'team/', children, recentAdds);++ expect(result).toEqual([folder('team'), doc('team/notes')]);+ });++ test("root splice ('') replaces the top level and keeps loaded descendants of surviving folders", () => {+ const current = [+ folder('team'),+ doc('team/notes'),+ folder('gone'),+ doc('gone/stale'),+ doc('README'),+ ];+ const children = [folder('team'), doc('README'), doc('NEW')];+ const recentAdds = new Map<string, number>();++ const result = spliceLazyFolderChildren(current, '', children, recentAdds);++ expect(result).toEqual([doc('team/notes'), folder('team'), doc('README'), doc('NEW')]);+ });++ test('root splice preserves in-window optimistic adds at the root level', () => {+ const NOW = 1_700_000_000_000;+ const current = [folder('team'), doc('just-created')];+ const children = [folder('team')]; // server index races the create+ const recentAdds = new Map<string, number>([['just-created.md', NOW]]);++ const result = spliceLazyFolderChildren(current, '', children, recentAdds, NOW);++ expect(result).toEqual([folder('team'), doc('just-created')]);+ expect(recentAdds.has('just-created.md')).toBe(true);+ });+});diff --git a/packages/app/src/components/file-tree-merge.ts b/packages/app/src/components/file-tree-merge.tsindex e24b9af25..1af5dce30 100644--- a/packages/app/src/components/file-tree-merge.ts+++ b/packages/app/src/components/file-tree-merge.ts@@ -29,3 +29,53 @@ export function mergeAndPruneRecentLocalAdds(if (preservedLocal.length === 0) return [...serverEntries];return [...serverEntries, ...preservedLocal];}++export function spliceLazyFolderChildren(+ currentEntries: readonly FileEntry[],+ folderTreePath: string,+ serverChildren: readonly FileEntry[],+ recentAdds: Map<string, number>,+ now: number = Date.now(),+): FileEntry[] {+ if (+ folderTreePath !== '' &&+ !currentEntries.some((entry) => fileEntryToTreePath(entry) === folderTreePath)+ ) {+ return [...currentEntries];+ }+ const currentChildren: FileEntry[] = [];+ const passthrough: FileEntry[] = [];+ for (const entry of currentEntries) {+ if (isDirectChildTreePath(folderTreePath, fileEntryToTreePath(entry))) {+ currentChildren.push(entry);+ } else {+ passthrough.push(entry);+ }+ }+ const mergedChildren = mergeAndPruneRecentLocalAdds(+ serverChildren,+ currentChildren,+ recentAdds,+ now,+ );+ const survivingChildFolders = new Set(+ mergedChildren.map((entry) => fileEntryToTreePath(entry)).filter((p) => p.endsWith('/')),+ );+ const kept = passthrough.filter((entry) => {+ const treePath = fileEntryToTreePath(entry);+ if (!treePath.startsWith(folderTreePath)) return true; // outside the spliced subtree+ const rest = treePath.slice(folderTreePath.length);+ const firstSlash = rest.indexOf('/');+ if (firstSlash === -1) return true; // the spliced folder's own entry+ return survivingChildFolders.has(folderTreePath + rest.slice(0, firstSlash + 1));+ });+ return [...kept, ...mergedChildren];+}++function isDirectChildTreePath(parentDirTreePath: string, treePath: string): boolean {+ if (!treePath.startsWith(parentDirTreePath)) return false;+ const rest = treePath.slice(parentDirTreePath.length);+ if (rest === '') return false;+ const stem = rest.endsWith('/') ? rest.slice(0, -1) : rest;+ return stem !== '' && !stem.includes('/');+}diff --git a/packages/app/src/components/file-tree-utils.test.ts b/packages/app/src/components/file-tree-utils.test.tsindex 9448e8de8..780ea6a1d 100644--- a/packages/app/src/components/file-tree-utils.test.ts+++ b/packages/app/src/components/file-tree-utils.test.ts@@ -1,5 +1,11 @@import { describe, expect, test } from 'bun:test';-import { computeAncestors, defaultInitialDir, filterVisibleEntries } from './file-tree-utils';+import { type DocumentListEntry, DocumentListEntrySchema } from '@inkeep/open-knowledge-core';+import {+ computeAncestors,+ defaultInitialDir,+ filterVisibleEntries,+ toFileEntries,+} from './file-tree-utils';describe('computeAncestors', () => {test('returns empty array for null', () => {@@ -185,3 +191,113 @@ describe('filterVisibleEntries', () => {expect(reduced).toEqual([{ kind: 'document', docName: 'README' }]);});});++describe('toFileEntries', () => {+ const modified = '2026-06-12T00:00:00.000Z';++ test('maps schema-parsed wire entries to per-kind FileEntry shapes', () => {+ const wire = [+ {+ kind: 'document',+ docName: 'brain/note',+ docExt: '.mdx',+ size: 7,+ modified,+ isSymlink: true,+ canonicalDocName: 'brain/canonical',+ targetPath: 'brain/canonical.mdx',+ },+ {+ kind: 'asset',+ path: 'images/logo.png',+ assetExt: '.png',+ referencedBy: ['brain/note'],+ size: 9,+ modified,+ },+ { kind: 'folder', path: 'team', size: 0, modified, hasChildren: true },+ ].map((entry) => DocumentListEntrySchema.parse(entry));++ expect(toFileEntries(wire)).toEqual([+ {+ kind: 'document',+ docName: 'brain/note',+ docExt: '.mdx',+ size: 7,+ modified,+ isSymlink: true,+ canonicalDocName: 'brain/canonical',+ targetPath: 'brain/canonical.mdx',+ },+ {+ kind: 'asset',+ path: 'images/logo.png',+ assetExt: '.png',+ mediaKind: null,+ size: 9,+ modified,+ referencedBy: ['brain/note'],+ },+ { kind: 'folder', path: 'team', size: 0, modified, hasChildren: true },+ ]);+ });++ test('carries a populated asset mediaKind through unchanged', () => {+ const wire = [+ DocumentListEntrySchema.parse({+ kind: 'asset',+ path: 'images/demo.mp4',+ assetExt: '.mp4',+ mediaKind: 'video',+ referencedBy: [],+ size: 3,+ modified,+ }),+ ];+ expect(toFileEntries(wire)).toEqual([+ {+ kind: 'asset',+ path: 'images/demo.mp4',+ assetExt: '.mp4',+ mediaKind: 'video',+ size: 3,+ modified,+ referencedBy: [],+ },+ ]);+ });++ test('skips entries the static type admits but the wire refine forbids', () => {+ const malformed: DocumentListEntry[] = [+ {+ kind: 'document',+ docExt: '.md',+ size: 1,+ modified,+ isSymlink: false,+ canonicalDocName: null,+ targetPath: null,+ },+ {+ kind: 'asset',+ path: 'images/orphan.png',+ docExt: '.md',+ size: 1,+ modified,+ isSymlink: false,+ canonicalDocName: null,+ targetPath: null,+ },+ {+ kind: 'folder',+ docExt: '.md',+ size: 0,+ modified,+ isSymlink: false,+ canonicalDocName: null,+ targetPath: null,+ },+ ];+ expect(toFileEntries(malformed)).toEqual([]);+ });+});diff --git a/packages/app/src/components/file-tree-utils.ts b/packages/app/src/components/file-tree-utils.tsindex 648788276..f6783ead2 100644--- a/packages/app/src/components/file-tree-utils.ts+++ b/packages/app/src/components/file-tree-utils.ts@@ -1,4 +1,4 @@-import type { InlineAssetMediaKind } from '@inkeep/open-knowledge-core';+import type { DocumentListEntry, InlineAssetMediaKind } from '@inkeep/open-knowledge-core';export interface DocumentEntry {kind: 'document';@@ -26,6 +26,7 @@ interface FolderEntry {path: string;size: number;modified: string;+ hasChildren?: boolean;}export type FileEntry = DocumentEntry | AssetEntry | FolderEntry;@@ -43,6 +44,69 @@ export function isFolderEntry(entry: FileEntry): entry is FolderEntry {return entry.kind === 'folder';}+export function toFileEntries(entries: readonly DocumentListEntry[]): FileEntry[] {+ const mapped: FileEntry[] = [];+ let dropped = 0;+ for (const entry of entries) {+ switch (entry.kind) {+ case 'document':+ if (entry.docName === undefined) {+ dropped += 1;+ break;+ }+ mapped.push({+ kind: 'document',+ docName: entry.docName,+ docExt: entry.docExt,+ size: entry.size,+ modified: entry.modified,+ isSymlink: entry.isSymlink,+ canonicalDocName: entry.canonicalDocName,+ targetPath: entry.targetPath,+ });+ break;+ case 'asset':+ if (entry.path === undefined || entry.assetExt === undefined) {+ dropped += 1;+ break;+ }+ mapped.push({+ kind: 'asset',+ path: entry.path,+ assetExt: entry.assetExt,+ mediaKind: entry.mediaKind ?? null,+ size: entry.size,+ modified: entry.modified,+ referencedBy: entry.referencedBy,+ });+ break;+ case 'folder':+ if (entry.path === undefined) {+ dropped += 1;+ break;+ }+ mapped.push({+ kind: 'folder',+ path: entry.path,+ size: entry.size,+ modified: entry.modified,+ hasChildren: entry.hasChildren,+ });+ break;+ default: {+ const _exhaustive: never = entry.kind;+ break;+ }+ }+ }+ if (dropped > 0) {+ console.warn(+ `[file-tree-utils] dropped ${dropped} listing entries missing variant identity fields`,+ );+ }+ return mapped;+}+export function computeAncestors(docName: string | null): string[] {if (!docName) return [];const segments = docName.split('/').filter(Boolean);diff --git a/packages/app/src/lib/show-all-stream.test.ts b/packages/app/src/lib/show-all-stream.test.tsindex 4687b1901..996e82e32 100644--- a/packages/app/src/lib/show-all-stream.test.ts+++ b/packages/app/src/lib/show-all-stream.test.ts@@ -103,6 +103,32 @@ describe('consumeShowAllStream', () => {expect(entries.map((e) => e.docName)).toEqual(['alpha', 'beta']);});+ test('a stream that closes without a complete line returns the parsed prefix, untruncated', async () => {+ const encoder = new TextEncoder();+ const stream = new ReadableStream<Uint8Array>({+ start(controller) {+ controller.enqueue(encoder.encode(docLine('alpha') + docLine('beta')));+ controller.close();+ },+ });+ const res = new Response(stream, { headers: { 'content-type': 'application/x-ndjson' } });+ const { entries, truncated } = await consumeShowAllStream(res);+ expect(entries.map((e) => e.docName)).toEqual(['alpha', 'beta']);+ expect(truncated).toBe(false);+ });++ test('a transport error mid-stream rejects so the caller can surface unreachable-server', async () => {+ const encoder = new TextEncoder();+ const stream = new ReadableStream<Uint8Array>({+ start(controller) {+ controller.enqueue(encoder.encode(docLine('alpha')));+ controller.error(new TypeError('connection reset'));+ },+ });+ const res = new Response(stream, { headers: { 'content-type': 'application/x-ndjson' } });+ await expect(consumeShowAllStream(res)).rejects.toThrow('connection reset');+ });+test('drops a schema-divergent entry line', async () => {const bad = `${JSON.stringify({ kind: 'document', docName: 'x', assetExt: 'png' })}\n`;const body = bad + docLine('beta') + completeLine(false, 1);diff --git a/packages/app/src/lib/show-all-stream.ts b/packages/app/src/lib/show-all-stream.tsindex 78bc55590..58f672f31 100644--- a/packages/app/src/lib/show-all-stream.ts+++ b/packages/app/src/lib/show-all-stream.ts@@ -40,7 +40,7 @@ export async function consumeShowAllStream(res: Response): Promise<ShowAllStreamtry {parsed = JSON.parse(line);} catch {- console.warn('[show-all-stream] dropping unparseable NDJSON line');+ console.warn('[show-all-stream] dropping unparseable NDJSON line:', line.slice(0, 200));return false;}if (isControlEvent(parsed)) {diff --git a/packages/app/src/locales/en/messages.json b/packages/app/src/locales/en/messages.jsonindex f192ffdb0..043584dd6 100644--- a/packages/app/src/locales/en/messages.json+++ b/packages/app/src/locales/en/messages.json@@ -1085,7 +1085,6 @@["1"],"."],- "_HekAK": ["Showing first ", ["truncatedShownCount"], " items — use search to find others"],"_K2CvV": ["Template"],"_N2eSU": ["org"],"_PACVa": ["Release notes"],@@ -1456,6 +1455,22 @@],"mNY1G6": ["Undo all edits"],"mSJ3Rn": ["Computing scaffold plan"],+ "mSpqzP": [+ [+ "truncatedShownCount",+ "plural",+ {+ "one": [+ "Showing the first item in one folder — the rest of that folder is hidden. Turn off Show all files for the filtered view."+ ],+ "other": [+ "Showing the first ",+ ["formattedCount"],+ " items in one folder — the rest of that folder is hidden. Turn off Show all files for the filtered view."+ ]+ }+ ]+ ],"mU3j1b": ["Remove item ", ["0"]],"mWVJRX": ["Collapsible section with a clickable summary."],"mYGY3B": ["Date"],diff --git a/packages/app/src/locales/en/messages.po b/packages/app/src/locales/en/messages.poindex c6f57fd41..9bdb38141 100644--- a/packages/app/src/locales/en/messages.po+++ b/packages/app/src/locales/en/messages.po@@ -345,6 +345,10 @@ msgstr "{settingsDescriptorLabel} properties"msgid "{tokens, plural, one {token} other {tokens}}"msgstr "{tokens, plural, one {token} other {tokens}}"+#: src/components/FileTree.tsx+msgid "{truncatedShownCount, plural, one {Showing the first item in one folder — the rest of that folder is hidden. Turn off Show all files for the filtered view.} other {Showing the first {formattedCount} items in one folder — the rest of that folder is hidden. Turn off Show all files for the filtered view.}}"+msgstr "{truncatedShownCount, plural, one {Showing the first item in one folder — the rest of that folder is hidden. Turn off Show all files for the filtered view.} other {Showing the first {formattedCount} items in one folder — the rest of that folder is hidden. Turn off Show all files for the filtered view.}}"+#: src/presence/PresenceBar.tsxmsgid "{userName} · {tabCount, plural, one {# tab} other {# tabs}}"msgstr "{userName} · {tabCount, plural, one {# tab} other {# tabs}}"@@ -5074,10 +5078,6 @@ msgstr "Show replace"msgid "Show thumbnails"msgstr "Show thumbnails"-#: src/components/FileTree.tsx-msgid "Showing first {truncatedShownCount} items — use search to find others"-msgstr "Showing first {truncatedShownCount} items — use search to find others"-#: src/components/CommandPalette.tsxmsgid "Showing results for \"{semanticResultsLabel}\""msgstr "Showing results for \"{semanticResultsLabel}\""diff --git a/packages/app/src/locales/pseudo/messages.json b/packages/app/src/locales/pseudo/messages.jsonindex 1ff1ccabd..454da61b3 100644--- a/packages/app/src/locales/pseudo/messages.json+++ b/packages/app/src/locales/pseudo/messages.json@@ -1085,7 +1085,6 @@["1"],"."],- "_HekAK": ["Śĥōŵĩńĝ ƒĩŕśţ ", ["truncatedShownCount"], " ĩţēḿś — ũśē śēàŕćĥ ţō ƒĩńď ōţĥēŕś"],"_K2CvV": ["Ţēḿƥĺàţē"],"_N2eSU": ["ōŕĝ"],"_PACVa": ["Ŕēĺēàśē ńōţēś"],@@ -1456,6 +1455,22 @@],"mNY1G6": ["Ũńďō àĺĺ ēďĩţś"],"mSJ3Rn": ["Ćōḿƥũţĩńĝ śćàƒƒōĺď ƥĺàń"],+ "mSpqzP": [+ [+ "truncatedShownCount",+ "plural",+ {+ "one": [+ "Śĥōŵĩńĝ ţĥē ƒĩŕśţ ĩţēḿ ĩń ōńē ƒōĺďēŕ — ţĥē ŕēśţ ōƒ ţĥàţ ƒōĺďēŕ ĩś ĥĩďďēń. Ţũŕń ōƒƒ Śĥōŵ àĺĺ ƒĩĺēś ƒōŕ ţĥē ƒĩĺţēŕēď vĩēŵ."+ ],+ "other": [+ "Śĥōŵĩńĝ ţĥē ƒĩŕśţ ",+ ["formattedCount"],+ " ĩţēḿś ĩń ōńē ƒōĺďēŕ — ţĥē ŕēśţ ōƒ ţĥàţ ƒōĺďēŕ ĩś ĥĩďďēń. Ţũŕń ōƒƒ Śĥōŵ àĺĺ ƒĩĺēś ƒōŕ ţĥē ƒĩĺţēŕēď vĩēŵ."+ ]+ }+ ]+ ],"mU3j1b": ["Ŕēḿōvē ĩţēḿ ", ["0"]],"mWVJRX": ["Ćōĺĺàƥśĩƀĺē śēćţĩōń ŵĩţĥ à ćĺĩćķàƀĺē śũḿḿàŕŷ."],"mYGY3B": ["Ďàţē"],diff --git a/packages/app/src/locales/pseudo/messages.po b/packages/app/src/locales/pseudo/messages.poindex 5c0b899ae..e0a0670c0 100644--- a/packages/app/src/locales/pseudo/messages.po+++ b/packages/app/src/locales/pseudo/messages.po@@ -345,6 +345,10 @@ msgstr ""msgid "{tokens, plural, one {token} other {tokens}}"msgstr ""+#: src/components/FileTree.tsx+msgid "{truncatedShownCount, plural, one {Showing the first item in one folder — the rest of that folder is hidden. Turn off Show all files for the filtered view.} other {Showing the first {formattedCount} items in one folder — the rest of that folder is hidden. Turn off Show all files for the filtered view.}}"+msgstr ""+#: src/presence/PresenceBar.tsxmsgid "{userName} · {tabCount, plural, one {# tab} other {# tabs}}"msgstr ""@@ -5069,10 +5073,6 @@ msgstr ""msgid "Show thumbnails"msgstr ""-#: src/components/FileTree.tsx-msgid "Showing first {truncatedShownCount} items — use search to find others"-msgstr ""-#: src/components/CommandPalette.tsxmsgid "Showing results for \"{semanticResultsLabel}\""msgstr ""diff --git a/packages/app/tests/stress/_helpers/fixtures.ts b/packages/app/tests/stress/_helpers/fixtures.tsindex d304de174..5630f1182 100644--- a/packages/app/tests/stress/_helpers/fixtures.ts+++ b/packages/app/tests/stress/_helpers/fixtures.ts@@ -38,6 +38,7 @@ export interface ApiHelpers {type WorkerFixtures = {workerServer: WorkerServer;+ workerServerEnv: Record<string, string>;};type TestFixtures = {@@ -88,9 +89,9 @@ function seedRequiredFixtureFiles(contentDir: string): void {}export const test = base.extend<TestFixtures, WorkerFixtures>({+ workerServerEnv: [{}, { scope: 'worker', option: true }],workerServer: [- // biome-ignore lint/correctness/noEmptyPattern: Playwright requires an object-destructuring pattern for the fixtures arg; this fixture has no dependencies so the destructure is empty by design.- async ({}, use, workerInfo) => {+ async ({ workerServerEnv }, use, workerInfo) => {const port = await getFreePort();const contentDir = mkdtempSync(join(tmpdir(), `ok-w${workerInfo.workerIndex}-`));const viteCacheDir = prepareViteCacheDir(`w${workerInfo.workerIndex}`);@@ -103,6 +104,7 @@ export const test = base.extend<TestFixtures, WorkerFixtures>({cwd: APP_PACKAGE_ROOT,env: {...process.env,+ ...workerServerEnv,VITE_PORT: String(port),OK_TEST_CONTENT_DIR: contentDir,OK_TEST_VITE_CACHE_DIR: viteCacheDir,diff --git a/packages/app/tests/stress/showall-lazy-tree.e2e.ts b/packages/app/tests/stress/showall-lazy-tree.e2e.tsnew file mode 100644index 000000000..b8c33c3da--- /dev/null+++ b/packages/app/tests/stress/showall-lazy-tree.e2e.ts@@ -0,0 +1,187 @@+import { mkdirSync, writeFileSync } from 'node:fs';+import { join } from 'node:path';+import type { Page } from '@playwright/test';+import { expect, test } from './_helpers';++const SHOW_ALL_CAP = 25;+const OVERFLOW_CHILD_COUNT = SHOW_ALL_CAP + 5;++test.use({ workerServerEnv: { OK_SHOWALL_MAX_ENTRIES: String(SHOW_ALL_CAP) } });++function escapeRegExp(value: string): string {+ return value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');+}++function uniqueStamp(): string {+ return `${Date.now().toString(36)}${Math.floor(Math.random() * 1e8).toString(36)}`;+}++function fileRow(page: Page, filename: string) {+ return page+ .locator('[data-slot="sidebar-container"]')+ .getByRole('treeitem', { name: filename, exact: true });+}++function folderRow(page: Page, folderName: string) {+ return page+ .locator('[data-slot="sidebar-container"]')+ .getByRole('treeitem', { name: new RegExp(`^${escapeRegExp(folderName)}/?$`) });+}++async function expandFolder(page: Page, folderName: string): Promise<void> {+ const row = folderRow(page, folderName);+ await expect(row).toHaveAttribute('aria-expanded', 'false');+ await row.focus();+ await row.press('ArrowRight');+ await expect(row).toHaveAttribute('aria-expanded', 'true');+}++async function collapseFolder(page: Page, folderName: string): Promise<void> {+ const row = folderRow(page, folderName);+ await expect(row).toHaveAttribute('aria-expanded', 'true');+ await row.focus();+ await row.press('ArrowLeft');+ await expect(row).toHaveAttribute('aria-expanded', 'false');+}++async function setShowAllFiles(page: Page, enabled: boolean): Promise<void> {+ const anchor = folderRow(page, 'sidebar-folder');+ await expect(anchor).toBeVisible({ timeout: 15_000 });+ await anchor.click({ button: 'right' });+ const toggle = page.getByTestId('file-tree-menu-show-all-files');+ await expect(toggle).toBeVisible({ timeout: 5_000 });+ await expect(toggle).not.toHaveAttribute('aria-disabled', 'true', { timeout: 10_000 });+ const alreadyEnabled = (await toggle.getAttribute('aria-checked')) === 'true';+ if (alreadyEnabled === enabled) {+ await page.keyboard.press('Escape');+ await expect(toggle).toBeHidden();+ return;+ }+ await toggle.click();+ await expect(toggle).toBeHidden();+}++test('Show All seeds the root lazily and loads folder children on expand', async ({+ page,+ api,+ workerServer,+}) => {+ const stamp = uniqueStamp();+ const rootDoc = `showall-root-${stamp}`;+ const folder = `showall-dir-${stamp}`;+ const nested = `nested-${stamp}`;+ const hiddenDir = `.showall-ghost-${stamp}`;++ await api.seedDocs([+ { name: rootDoc, markdown: '# root\n' },+ { name: `${folder}/child-a`, markdown: '# a\n' },+ { name: `${folder}/child-b`, markdown: '# b\n' },+ ]);+ mkdirSync(join(workerServer.contentDir, folder, nested), { recursive: true });+ writeFileSync(join(workerServer.contentDir, folder, nested, 'deep-doc.md'), '# deep\n', 'utf-8');+ mkdirSync(join(workerServer.contentDir, hiddenDir), { recursive: true });+ writeFileSync(join(workerServer.contentDir, hiddenDir, 'ghost.md'), '# ghost\n', 'utf-8');++ const showAllListingUrls: string[] = [];+ page.on('request', (request) => {+ const url = request.url();+ if (url.includes('/api/documents') && url.includes('showAll=true')) {+ showAllListingUrls.push(url);+ }+ });++ await page.goto('/');+ await page.waitForLoadState('domcontentloaded');++ await setShowAllFiles(page, false);+ await expect(fileRow(page, `${rootDoc}.md`)).toBeVisible({ timeout: 15_000 });+ await expect(folderRow(page, folder)).toBeVisible();+ await expect(folderRow(page, hiddenDir)).toBeHidden();++ await setShowAllFiles(page, true);++ await expect(folderRow(page, hiddenDir)).toBeVisible({ timeout: 15_000 });+ await expect(fileRow(page, `${rootDoc}.md`)).toBeVisible();+ await expect(fileRow(page, 'child-a.md')).toBeHidden();+ expect(showAllListingUrls.some((url) => url.includes(`dir=${encodeURIComponent(folder)}`))).toBe(+ false,+ );++ const childLevelFetch = page.waitForRequest(+ (request) => {+ const url = request.url();+ return (+ url.includes('/api/documents') &&+ url.includes('showAll=true') &&+ url.includes(`dir=${encodeURIComponent(folder)}`) &&+ url.includes('depth=1')+ );+ },+ { timeout: 15_000 },+ );+ await expandFolder(page, folder);+ await childLevelFetch;+ await expect(fileRow(page, 'child-a.md')).toBeVisible({ timeout: 15_000 });+ await expect(fileRow(page, 'child-b.md')).toBeVisible();++ await expect(folderRow(page, nested)).toBeVisible();+ await expect(fileRow(page, 'deep-doc.md')).toBeHidden();+ await expandFolder(page, nested);+ await expect(fileRow(page, 'deep-doc.md')).toBeVisible({ timeout: 15_000 });++ expect(showAllListingUrls.length).toBeGreaterThan(0);+ for (const url of showAllListingUrls) {+ expect(url).toContain('depth=1');+ }+});++test('truncation banner appears for an overflowing level while every root entry stays visible', async ({+ page,+ api,+ workerServer,+}) => {+ const stamp = uniqueStamp();+ const rootDocA = `trunc-root-a-${stamp}`;+ const rootDocB = `trunc-root-b-${stamp}`;+ const bigFolder = `trunc-big-${stamp}`;++ await api.seedDocs([+ { name: rootDocA, markdown: '# a\n' },+ { name: rootDocB, markdown: '# b\n' },+ ]);+ mkdirSync(join(workerServer.contentDir, bigFolder), { recursive: true });+ for (let i = 0; i < OVERFLOW_CHILD_COUNT; i++) {+ writeFileSync(+ join(workerServer.contentDir, bigFolder, `entry-${String(i).padStart(2, '0')}.md`),+ `# entry ${i}\n`,+ 'utf-8',+ );+ }++ await page.goto('/');+ await page.waitForLoadState('domcontentloaded');+ await setShowAllFiles(page, true);++ const banner = page.getByRole('status').filter({ hasText: 'Showing the first' });++ await expect(folderRow(page, bigFolder)).toBeVisible({ timeout: 15_000 });+ await expect(banner).toBeHidden();++ await expandFolder(page, bigFolder);+ await expect(banner).toBeVisible({ timeout: 15_000 });+ await expect(banner).toContainText(`Showing the first ${SHOW_ALL_CAP} items`);+ await expect(banner).not.toContainText(/search/i);+ await expect(+ page+ .locator('[data-slot="sidebar-container"]')+ .getByRole('treeitem', { name: /entry-\d+\.md/ })+ .first(),+ ).toBeVisible();++ await collapseFolder(page, bigFolder);+ await expect(fileRow(page, `${rootDocA}.md`)).toBeVisible();+ await expect(fileRow(page, `${rootDocB}.md`)).toBeVisible();+ await expect(fileRow(page, 'test-doc.md')).toBeVisible();+ await expect(folderRow(page, 'sidebar-folder')).toBeVisible();+ await expect(folderRow(page, bigFolder)).toBeVisible();+});diff --git a/packages/server/src/api-extension.ts b/packages/server/src/api-extension.tsindex a67885763..d60dae15a 100644--- a/packages/server/src/api-extension.ts+++ b/packages/server/src/api-extension.ts@@ -931,7 +931,11 @@ export async function* streamShowAllEntries(try {const childCanonical = await realpath(`${absDir}/${entry.name}`);if (!isInsideContentDir(childCanonical)) continue;- } catch {+ } catch (err) {+ console.warn(+ `[document-list][showAll] probe realpath failed for ${absDir}/${entry.name}:`,+ err,+ );continue;}return true;@@ -944,122 +948,134 @@ export async function* streamShowAllEntries(}async function* walk(- absDir: string,- relDir: string,- depth: number,+ startAbsDir: string,+ startRelDir: string,+ startDepth: number,): AsyncGenerator<DocumentListEntry> {- let entries: import('node:fs').Dirent[];- try {- entries = await readdir(absDir, { withFileTypes: true });- } catch (err) {- console.warn(`[document-list][showAll] readdir failed for ${absDir}:`, err);- return;- }-- for (const entry of entries) {+ const queue: Array<{ absDir: string; relDir: string; depth: number }> = [+ { absDir: startAbsDir, relDir: startRelDir, depth: startDepth },+ ];+ for (let head = 0; head < queue.length; head++) {if (signal?.aborted) {aborted = true;return;}- if (emitted >= maxEntries) {- truncated = true;- return;+ const { absDir, relDir, depth } = queue[head];+ let entries: import('node:fs').Dirent[];+ try {+ entries = await readdir(absDir, { withFileTypes: true });+ } catch (err) {+ console.warn(`[document-list][showAll] readdir failed for ${absDir}:`, err);+ continue;}- const relPath = relDir ? `${relDir}/${entry.name}` : entry.name;- if (entry.isDirectory()) {- if (contentFilter.isDirExcluded(relPath, { bypassFilters: true })) continue;-- const dirAbsRaw = `${absDir}/${entry.name}`;- let dirCanonical: string;- try {- dirCanonical = await realpath(dirAbsRaw);- } catch (err) {- console.warn(`[document-list][showAll] realpath failed for ${dirAbsRaw}:`, err);- continue;+ for (const entry of entries) {+ if (signal?.aborted) {+ aborted = true;+ return;}- if (!isInsideContentDir(dirCanonical)) {- console.warn(- `[document-list][showAll] refusing symlink-escape ${dirAbsRaw} -> ${dirCanonical}`,- );- continue;+ if (emitted >= maxEntries) {+ truncated = true;+ return;}+ const relPath = relDir ? `${relDir}/${entry.name}` : entry.name;- if (passesDirFilter(relPath)) {- let folderStat: import('node:fs').Stats | null = null;+ if (entry.isDirectory()) {+ if (contentFilter.isDirExcluded(relPath, { bypassFilters: true })) continue;++ const dirAbsRaw = `${absDir}/${entry.name}`;+ let dirCanonical: string;try {- folderStat = await stat(dirAbsRaw);+ dirCanonical = await realpath(dirAbsRaw);} catch (err) {- console.warn(`[document-list][showAll] stat failed for ${dirAbsRaw}:`, err);+ console.warn(`[document-list][showAll] realpath failed for ${dirAbsRaw}:`, err);+ continue;+ }+ if (!isInsideContentDir(dirCanonical)) {+ console.warn(+ `[document-list][showAll] refusing symlink-escape ${dirAbsRaw} -> ${dirCanonical}`,+ );+ continue;}++ if (passesDirFilter(relPath)) {+ let folderStat: import('node:fs').Stats | null = null;+ try {+ folderStat = await stat(dirAbsRaw);+ } catch (err) {+ console.warn(`[document-list][showAll] stat failed for ${dirAbsRaw}:`, err);+ }+ emitted += 1;+ const atLeafDepth = depth >= maxDepth;+ const hasChildren = atLeafDepth+ ? await probeHasChildren(dirAbsRaw, relPath)+ : undefined;+ yield {+ kind: 'folder',+ path: relPath,+ size: 0,+ modified: folderStat ? folderStat.mtime.toISOString() : '',+ docExt: '.md',+ isSymlink: false,+ canonicalDocName: null,+ targetPath: null,+ ...(hasChildren === undefined ? {} : { hasChildren }),+ };+ }++ if (depth < maxDepth) {+ queue.push({ absDir: dirAbsRaw, relDir: relPath, depth: depth + 1 });+ }+ continue;+ }++ if (!entry.isFile()) continue;+ if (contentFilter.isExcluded(relPath, { bypassFilters: true })) continue;+ if (!passesDirFilter(relPath)) continue;++ let fileStat: import('node:fs').Stats | null = null;+ try {+ fileStat = await stat(`${absDir}/${entry.name}`);+ } catch (err) {+ console.warn(`[document-list][showAll] stat failed for ${absDir}/${entry.name}:`, err);+ continue;+ }++ if (isSupportedDocFile(entry.name)) {+ const docName = relPath.replace(/\.(md|mdx)$/i, '');+ const docExt = getDocExtension(docName);emitted += 1;- const atLeafDepth = depth >= maxDepth;- const hasChildren = atLeafDepth ? await probeHasChildren(dirAbsRaw, relPath) : undefined;yield {- kind: 'folder',- path: relPath,- size: 0,- modified: folderStat ? folderStat.mtime.toISOString() : '',- docExt: '.md',+ kind: 'document',+ docName,+ docExt,+ size: fileStat.size,+ modified: fileStat.mtime.toISOString(),isSymlink: false,canonicalDocName: null,targetPath: null,- ...(hasChildren === undefined ? {} : { hasChildren }),};+ continue;}- if (depth < maxDepth) {- yield* walk(dirAbsRaw, relPath, depth + 1);- }- continue;- }-- if (!entry.isFile()) continue;- if (contentFilter.isExcluded(relPath, { bypassFilters: true })) continue;- if (!passesDirFilter(relPath)) continue;-- let fileStat: import('node:fs').Stats | null = null;- try {- fileStat = await stat(`${absDir}/${entry.name}`);- } catch (err) {- console.warn(`[document-list][showAll] stat failed for ${absDir}/${entry.name}:`, err);- continue;- }-- if (isSupportedDocFile(entry.name)) {- const docName = relPath.replace(/\.(md|mdx)$/i, '');- const docExt = getDocExtension(docName);+ const assetExt = synthesizeShowAllAssetExt(entry.name);+ const mediaKind: InlineAssetMediaKind | null = mediaKindForSidebarAssetExtension(assetExt);emitted += 1;yield {- kind: 'document',- docName,- docExt,+ kind: 'asset',+ docName: relPath,+ docExt: assetExt,+ path: relPath,+ assetExt,+ mediaKind,+ referencedBy: [],size: fileStat.size,modified: fileStat.mtime.toISOString(),isSymlink: false,canonicalDocName: null,targetPath: null,};- continue;}-- const assetExt = synthesizeShowAllAssetExt(entry.name);- const mediaKind: InlineAssetMediaKind | null = mediaKindForSidebarAssetExtension(assetExt);- emitted += 1;- yield {- kind: 'asset',- docName: relPath,- docExt: assetExt,- path: relPath,- assetExt,- mediaKind,- referencedBy: [],- size: fileStat.size,- modified: fileStat.mtime.toISOString(),- isSymlink: false,- canonicalDocName: null,- targetPath: null,- };}}diff --git a/packages/server/src/showall-stream.test.ts b/packages/server/src/showall-stream.test.tsindex b9b684982..ff62f4dba 100644--- a/packages/server/src/showall-stream.test.ts+++ b/packages/server/src/showall-stream.test.ts@@ -1,5 +1,5 @@-import { afterEach, describe, expect, test } from 'bun:test';-import { mkdirSync, mkdtempSync, realpathSync, writeFileSync } from 'node:fs';+import { afterEach, describe, expect, spyOn, test } from 'bun:test';+import { chmodSync, mkdirSync, mkdtempSync, realpathSync, writeFileSync } from 'node:fs';import { tmpdir } from 'node:os';import { join } from 'node:path';import { ASSET_EXTENSIONS, type DocumentListEntry } from '@inkeep/open-knowledge-core';@@ -124,6 +124,187 @@ describe('streamShowAllEntries — abort + laziness', () => {const ret = await gen.return({ truncated: false });expect(ret.done).toBe(true);});++ test('abort between queued directories is honored when the remaining dirs are empty', async () => {+ const dir = realpathSync(mkdtempSync(join(tmpdir(), 'ok-showall-stream-abort-')));+ for (const sub of ['a', 'b', 'c']) {+ mkdirSync(join(dir, sub));+ }+ __resetShowAllWalkStatsForTesting();+ const controller = new AbortController();+ const gen = streamShowAllEntries({+ ...streamOptsFor(dir, 50_000),+ signal: controller.signal,+ });+ await gen.next();+ await gen.next();+ const third = await gen.next();+ expect(third.done).toBe(false);+ controller.abort();+ const final = await gen.next();+ expect(final.done).toBe(true);+ expect(__getShowAllWalkStatsForTesting().aborts).toBe(1);+ });+});++function entryPath(e: DocumentListEntry): string {+ return e.kind === 'document' ? e.docName : e.path;+}++describe('streamShowAllEntries — level-order emission (PRD-6858)', () => {+ function makeStarvationFixture(): { dir: string; rootFolders: string[]; rootDocs: string[] } {+ const dir = realpathSync(mkdtempSync(join(tmpdir(), 'ok-showall-bfs-')));+ const rootFolders: string[] = [];+ const rootDocs: string[] = [];+ for (let d = 0; d < 5; d++) {+ const sub = `dir-${d}`;+ mkdirSync(join(dir, sub));+ rootFolders.push(sub);+ for (let f = 0; f < 20; f++) {+ writeFileSync(join(dir, sub, `leaf-${String(f).padStart(2, '0')}.md`), `# leaf ${f}\n`);+ }+ }+ for (let f = 0; f < 5; f++) {+ const name = `root-file-${f}`;+ writeFileSync(join(dir, `${name}.md`), `# ${name}\n`);+ rootDocs.push(name);+ }+ return { dir, rootFolders, rootDocs };+ }++ test('cap hit inside a deep subtree never starves root-level entries', async () => {+ const { dir, rootFolders, rootDocs } = makeStarvationFixture();+ const CAP = 15;+ const { entries, truncated } = await drain(streamShowAllEntries(streamOptsFor(dir, CAP)));++ expect(truncated).toBe(true);+ expect(entries.length).toBe(CAP);++ const paths = entries.map(entryPath);+ for (const folder of rootFolders) expect(paths).toContain(folder);+ for (const doc of rootDocs) expect(paths).toContain(doc);+ });++ test('every depth-N entry emits before the first depth-N+1 entry, parents before children', async () => {+ const dir = realpathSync(mkdtempSync(join(tmpdir(), 'ok-showall-levelorder-')));+ writeFileSync(join(dir, 'root.md'), '# root\n');+ mkdirSync(join(dir, 'a', 'sub'), { recursive: true });+ mkdirSync(join(dir, 'b'));+ writeFileSync(join(dir, 'a', 'one.md'), '# one\n');+ writeFileSync(join(dir, 'a', 'note.txt'), 'asset\n');+ writeFileSync(join(dir, 'b', 'two.md'), '# two\n');+ writeFileSync(join(dir, 'a', 'sub', 'deep.md'), '# deep\n');++ const { entries, truncated } = await drain(streamShowAllEntries(streamOptsFor(dir, 50_000)));+ expect(truncated).toBe(false);++ const depths = entries.map((e) => entryPath(e).split('/').length);+ expect(depths).toEqual([1, 1, 1, 2, 2, 2, 2, 3]);++ const paths = entries.map(entryPath);+ for (const path of paths) {+ const segments = path.split('/');+ if (segments.length < 2) continue;+ const parent = segments.slice(0, -1).join('/');+ const parentIdx = entries.findIndex((e) => e.kind === 'folder' && e.path === parent);+ expect(parentIdx).toBeGreaterThanOrEqual(0);+ expect(parentIdx).toBeLessThan(paths.indexOf(path));+ }+ });++ test('maxDepth=1 yields a single level with hasChildren stamped, never recursing', async () => {+ const dir = realpathSync(mkdtempSync(join(tmpdir(), 'ok-showall-depth1-')));+ writeFileSync(join(dir, 'top.md'), '# top\n');+ mkdirSync(join(dir, 'full', 'grandchild'), { recursive: true });+ writeFileSync(join(dir, 'full', 'child.md'), '# child\n');+ mkdirSync(join(dir, 'hollow'));++ const { entries, truncated } = await drain(+ streamShowAllEntries({ ...streamOptsFor(dir, 50_000), maxDepth: 1 }),+ );+ expect(truncated).toBe(false);++ const paths = entries.map(entryPath);+ expect(paths.toSorted()).toEqual(['full', 'hollow', 'top']);++ const full = entries.find((e) => e.kind === 'folder' && e.path === 'full');+ const hollow = entries.find((e) => e.kind === 'folder' && e.path === 'hollow');+ expect(full?.kind === 'folder' && full.hasChildren).toBe(true);+ expect(hollow?.kind === 'folder' && hollow.hasChildren).toBe(false);+ });+});++describe('streamShowAllEntries — cap accounting boundary quirks', () => {+ test('an excludable entry past the cap still reports truncated (cap checked before exclusion)', async () => {+ const dir = realpathSync(mkdtempSync(join(tmpdir(), 'ok-showall-quirk-')));+ const CAP = 4;+ mkdirSync(join(dir, 'sub'));+ for (let i = 0; i < CAP - 1; i++) {+ writeFileSync(join(dir, `f-${i}.md`), `# f ${i}\n`);+ }+ mkdirSync(join(dir, 'sub', 'node_modules'));++ const { entries, truncated } = await drain(streamShowAllEntries(streamOptsFor(dir, CAP)));+ expect(entries.length).toBe(CAP);+ expect(entries.map(entryPath).toSorted()).toEqual(['f-0', 'f-1', 'f-2', 'sub']);+ expect(truncated).toBe(true);+ });++ test('the same tree under a roomier cap drains untruncated — the exclusion gate still prunes', async () => {+ const dir = realpathSync(mkdtempSync(join(tmpdir(), 'ok-showall-quirk-roomy-')));+ mkdirSync(join(dir, 'sub'));+ for (let i = 0; i < 3; i++) {+ writeFileSync(join(dir, `f-${i}.md`), `# f ${i}\n`);+ }+ mkdirSync(join(dir, 'sub', 'node_modules'));++ const { entries, truncated } = await drain(streamShowAllEntries(streamOptsFor(dir, 5)));+ expect(entries.length).toBe(4);+ expect(entries.map(entryPath)).not.toContain('sub/node_modules');+ expect(truncated).toBe(false);+ });+});++describe('streamShowAllEntries — unreadable directory mid-queue', () => {+ const runningAsRoot = typeof process.getuid === 'function' && process.getuid() === 0;++ test.skipIf(runningAsRoot)(+ 'a permission-denied directory skips with a warn while every other entry still emits',+ async () => {+ const dir = realpathSync(mkdtempSync(join(tmpdir(), 'ok-showall-eacces-')));+ writeFileSync(join(dir, 'root.md'), '# root\n');+ mkdirSync(join(dir, 'locked'));+ writeFileSync(join(dir, 'locked', 'hidden.md'), '# hidden\n');+ mkdirSync(join(dir, 'open'));+ writeFileSync(join(dir, 'open', 'visible.md'), '# visible\n');+ chmodSync(join(dir, 'locked'), 0o000);++ const warnSpy = spyOn(console, 'warn').mockImplementation(() => {});+ try {+ const { entries, truncated } = await drain(+ streamShowAllEntries(streamOptsFor(dir, 50_000)),+ );++ const paths = entries.map(entryPath);+ expect(paths).not.toContain('locked/hidden');+ expect(paths).toContain('root');+ expect(paths).toContain('open');+ expect(paths).toContain('open/visible');+ expect(truncated).toBe(false);++ const lockedWarn = warnSpy.mock.calls.find(+ (call) =>+ typeof call[0] === 'string' &&+ call[0].includes('failed for') &&+ call[0].includes('locked'),+ );+ expect(lockedWarn).toBeDefined();+ } finally {+ warnSpy.mockRestore();+ chmodSync(join(dir, 'locked'), 0o755);+ }+ },+ );});describe('streamShowAllEntries — .base/.canvas mediaKind', () => {