Skip to content

Beautiful, AI-native markdown IDE and LLM wiki

feat(open-knowledge): file-tree Show visibility toggles menu (#2510)

Nick Gomez31ad83c74098
diff --git a/.changeset/tree-show-visibility-options.md b/.changeset/tree-show-visibility-options.md
new file mode 100644
index 000000000..ef843f614
--- /dev/null
+++ b/.changeset/tree-show-visibility-options.md
@@ -0,0 +1,24 @@
+---
+"@inkeep/open-knowledge": minor
+---
+
+The file tree gains a "Show" visibility menu. The tree-options button in the
+sidebar toolbar (now always visible) opens a two-section popover: the existing
+Expand all / Collapse all commands, and a new Show group with four checkboxes:
+Hidden files, .ok folders, Only markdown files, and Skills. The same toggles
+appear in the sidebar right-click menu and the macOS View menu, and every
+surface stays in sync. Preferences persist per project per machine.
+
+- "Only markdown files" strips the tree to just your .md/.mdx documents and
+ folders, for a focused notes view.
+- ".ok folders" reveals OpenKnowledge's own project state (skills, templates,
+ config) in place, read-only: clicks route to the Skills editor, the template
+ editor, or a read-only viewer, and internal `worktrees/` and `local/`
+ directories are never listed. Search is unaffected by the reveal.
+- "Skills" hides or shows the sidebar Skills section.
+- Opening a doc the tree currently hides (via a link, search, or URL) now
+ leaves the tree quiet: no stale row stays highlighted and the tree no longer
+ scrolls to the wrong row (two pre-existing defects fixed). A subtle editor
+ indicator names which toggles hide the current doc, with one-click flips.
+- When active filters hide everything, the tree explains itself and offers a
+ one-click "Reset view filters".
diff --git a/packages/app/package.json b/packages/app/package.json
index f2acbb7a9..9cc35f889 100644
--- a/packages/app/package.json
+++ b/packages/app/package.json
@@ -26,7 +26,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/file-tree-drag-to-root.e2e.ts tests/stress/file-tree-deselect-to-root.e2e.ts tests/stress/file-tree-compact-folders.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/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 tests/stress/tabs-component-strip.e2e.ts tests/stress/source-find-scroll.e2e.ts tests/stress/harness-app-warmth.e2e.ts tests/stress/qa-canary-authoring-both-modes.e2e.ts tests/stress/qa-canary-live-typing.e2e.ts tests/stress/keystroke-cadence-danger-space.e2e.ts tests/stress/jsx-unregistered-backspace-delete.e2e.ts tests/stress/jsx-unregistered-ime-concurrent.e2e.ts tests/stress/jsx-backspace-delete.e2e.ts tests/stress/link-authoring-bytes.e2e.ts tests/stress/link-authoring-apex.e2e.ts",
+ "test:e2e": "playwright test tests/stress/ux-interactions.e2e.ts tests/stress/file-tree-create.e2e.ts tests/stress/file-tree-drag-to-root.e2e.ts tests/stress/file-tree-deselect-to-root.e2e.ts tests/stress/file-tree-compact-folders.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/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 tests/stress/tabs-component-strip.e2e.ts tests/stress/source-find-scroll.e2e.ts tests/stress/harness-app-warmth.e2e.ts tests/stress/qa-canary-authoring-both-modes.e2e.ts tests/stress/qa-canary-live-typing.e2e.ts tests/stress/keystroke-cadence-danger-space.e2e.ts tests/stress/jsx-unregistered-backspace-delete.e2e.ts tests/stress/jsx-unregistered-ime-concurrent.e2e.ts tests/stress/jsx-backspace-delete.e2e.ts tests/stress/link-authoring-bytes.e2e.ts tests/stress/link-authoring-apex.e2e.ts tests/stress/quiet-tree-hidden-doc.e2e.ts tests/stress/show-ok-folders.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",
@@ -44,7 +44,7 @@
{
"name": "main app bundle (gzipped)",
"path": "dist/assets/index-*.js",
- "limit": "462 kB",
+ "limit": "466 kB",
"gzip": true,
"running": false
},
diff --git a/packages/app/src/components/AssetPreview.dom.test.tsx b/packages/app/src/components/AssetPreview.dom.test.tsx
index 0f6e7e5ec..720851962 100644
--- a/packages/app/src/components/AssetPreview.dom.test.tsx
+++ b/packages/app/src/components/AssetPreview.dom.test.tsx
@@ -18,11 +18,29 @@
*/
import { afterEach, beforeEach, describe, expect, mock, spyOn, test } from 'bun:test';
import { cleanup, fireEvent, render, screen } from '@testing-library/react';
+import type { ReactNode } from 'react';
+import { renderLinguiTemplate } from '@/test-utils/lingui-mock';
import {
expectVisualClassTokens,
expectVisualClassTokensAbsent,
} from '@/test-utils/visual-contract';
+mock.module('@lingui/react/macro', () => ({
+ Trans: ({ children }: { children: ReactNode }) => <>{children}</>,
+ useLingui: () => ({ t: renderLinguiTemplate }),
+}));
+
+// The asset view hosts the NotInSidebarIndicator, whose config hook throws
+// without a provider — stub the app-default view. `mergedConfig` is a knob so
+// the indicator tests below can flip the only-markdown axis.
+let mergedConfig: { appearance?: { sidebar?: { showOnlyMarkdownFiles?: boolean } } } | null = null;
+mock.module('@/lib/config-provider', () => ({
+ useConfigContext: () => ({
+ merged: mergedConfig,
+ projectLocalBinding: null,
+ }),
+}));
+
// `<Pdf>` lazy-loads pdfjs-dist via `await import()` inside an effect and
// uses `ResizeObserver` synchronously during render to compute fit-width /
// fit-height base scale. jsdom provides neither, and booting pdfjs in a
@@ -166,3 +184,32 @@ describe('AssetPreview — image loading-state placeholder (PRD-6638)', () => {
expectVisualClassTokens(slot?.className, ['aspect-[16/9]']);
});
});
+
+describe('AssetPreview — not-in-sidebar indicator', () => {
+ beforeEach(() => {
+ mergedConfig = null;
+ });
+
+ afterEach(() => cleanup());
+
+ test('a visible asset renders no indicator', () => {
+ render(<AssetPreview assetPath="assets/data.csv" mediaKind={null} />);
+ expect(screen.queryByTestId('not-in-sidebar-indicator')).toBeNull();
+ });
+
+ test('a dot-path asset names the hidden-files toggle above the preview', () => {
+ render(<AssetPreview assetPath=".scratch/data.csv" mediaKind={null} />);
+ expect(screen.queryByTestId('not-in-sidebar-indicator')).not.toBeNull();
+ expect(screen.queryByTestId('not-in-sidebar-flip-hidden-files')).not.toBeNull();
+ expect(screen.queryByTestId('not-in-sidebar-flip-only-markdown')).toBeNull();
+ });
+
+ test('only-markdown mode names its toggle for a visible non-markdown asset', () => {
+ mergedConfig = { appearance: { sidebar: { showOnlyMarkdownFiles: true } } };
+ render(<AssetPreview assetPath="assets/data.csv" mediaKind={null} />);
+ expect(screen.queryByTestId('not-in-sidebar-flip-only-markdown')).not.toBeNull();
+ expect(screen.queryByTestId('not-in-sidebar-flip-hidden-files')).toBeNull();
+ // The preview body itself stays fully functional below the indicator.
+ expect(screen.queryByTestId('asset-preview-open-as-text')).not.toBeNull();
+ });
+});
diff --git a/packages/app/src/components/AssetPreview.text-dispatch.dom.test.tsx b/packages/app/src/components/AssetPreview.text-dispatch.dom.test.tsx
index 7310b2a60..13715e71a 100644
--- a/packages/app/src/components/AssetPreview.text-dispatch.dom.test.tsx
+++ b/packages/app/src/components/AssetPreview.text-dispatch.dom.test.tsx
@@ -33,6 +33,16 @@ mock.module('@/editor/asset-dispatch', () => ({
dispatchAssetClick: dispatchAssetClickStub,
}));
+// The asset view hosts the NotInSidebarIndicator, whose config hook throws
+// without a provider — stub the app-default view (all fixtures here use
+// visible paths, so the indicator stays unmounted).
+mock.module('@/lib/config-provider', () => ({
+ useConfigContext: () => ({
+ merged: null,
+ projectLocalBinding: null,
+ }),
+}));
+
const { AssetPreview } = await import('./AssetPreview.tsx');
describe('AssetPreview — text-viewer dispatch', () => {
diff --git a/packages/app/src/components/AssetPreview.tsx b/packages/app/src/components/AssetPreview.tsx
index fe4c97f54..7542940bc 100644
--- a/packages/app/src/components/AssetPreview.tsx
+++ b/packages/app/src/components/AssetPreview.tsx
@@ -2,6 +2,7 @@ import { type InlineAssetMediaKind, toDesktopAssetHref } from '@inkeep/open-know
import { Trans } from '@lingui/react/macro';
import { useState } from 'react';
import { MermaidFileViewer } from '@/components/MermaidFileViewer';
+import { NotInSidebarIndicator } from '@/components/NotInSidebarIndicator';
import { TextViewer } from '@/components/TextViewer';
import { Button } from '@/components/ui/button';
import { LoadingImage } from '@/components/ui/loading-image';
@@ -36,12 +37,30 @@ function assetTextUrl(assetPath: string): string {
}
export function AssetPreview({ assetPath, mediaKind }: AssetPreviewProps) {
+ return (
+ <div className="flex h-full min-h-0 flex-col">
+ {/* Self-gating chrome above whichever preview body renders: names the
+ visibility toggle(s) hiding this file's tree row. Lives here rather
+ than per-branch so every asset surface (pdf / text / fallback)
+ carries the same contract. */}
+ <NotInSidebarIndicator
+ entry={{ kind: 'asset', path: assetPath }}
+ className="shrink-0 border-b bg-background px-3 py-1.5"
+ />
+ <div className="min-h-0 flex-1">
+ <AssetPreviewBody assetPath={assetPath} mediaKind={mediaKind} />
+ </div>
+ </div>
+ );
+}
+
+function AssetPreviewBody({ assetPath, mediaKind }: AssetPreviewProps) {
// Local override toggle: when the user clicks "View as text" from
// the fallback pane, mount the `TextViewer` for the
// same asset path without re-navigating. Reset is handled at the
// call site — `EditorArea` passes `key={activeTarget.assetPath}`, so
- // navigating to a different asset remounts this component and
- // re-initializes `forceText` to `false`. A child `key` (e.g. the
+ // navigating to a different asset remounts this component (body included)
+ // and re-initializes `forceText` to `false`. A child `key` (e.g. the
// `key={assetPath}` on `<TextViewer>` below) does NOT reset parent
// state — that would silently bleed `forceText=true` from a previous
// file onto an image / video / pdf, garbling them through CodeMirror.
diff --git a/packages/app/src/components/EditorToolbar.dom.test.tsx b/packages/app/src/components/EditorToolbar.dom.test.tsx
index f494ca25c..e55b034ba 100644
--- a/packages/app/src/components/EditorToolbar.dom.test.tsx
+++ b/packages/app/src/components/EditorToolbar.dom.test.tsx
@@ -16,16 +16,26 @@ mock.module('./EditorBreadcrumb', () => ({
),
}));
+// The breadcrumb cell's NotInSidebarIndicator reads merged config through the
+// context hook, which throws without a provider — stub the app-default view
+// (no toggles set, binding absent) so the toolbar mounts standalone.
+mock.module('@/lib/config-provider', () => ({
+ useConfigContext: () => ({
+ merged: null,
+ projectLocalBinding: null,
+ }),
+}));
+
describe('EditorToolbar runtime layout', () => {
afterEach(() => cleanup());
- async function renderToolbar() {
+ async function renderToolbar(activeDocName = 'docs/Page.md') {
const { EditorToolbar } = await import('./EditorToolbar');
render(
<TooltipProvider>
<EditorToolbar
- activeDocName="docs/Page.md"
+ activeDocName={activeDocName}
isSourceMode={false}
sourceDisabled={false}
onModeChange={() => {}}
@@ -66,4 +76,21 @@ describe('EditorToolbar runtime layout', () => {
const middleCell = sourceButton.closest('.pointer-events-auto.flex.justify-center');
expect(middleCell).toBeTruthy();
});
+
+ test('a tree-hidden doc gets the not-in-sidebar indicator beside the breadcrumb', async () => {
+ await renderToolbar('.scratch/hidden-note');
+
+ const indicator = screen.getByTestId('not-in-sidebar-indicator');
+ // Same interactive cell as the breadcrumb — the toolbar grid is
+ // pointer-events-none, so anything outside an auto cell is unclickable.
+ const breadcrumbCell = screen.getByTestId('editor-breadcrumb-probe').parentElement;
+ expect(breadcrumbCell?.contains(indicator)).toBe(true);
+ expectVisualClassTokens(breadcrumbCell?.className, ['pointer-events-auto']);
+ });
+
+ test('a doc with a visible tree row renders no indicator', async () => {
+ await renderToolbar();
+
+ expect(screen.queryByTestId('not-in-sidebar-indicator')).toBeNull();
+ });
});
diff --git a/packages/app/src/components/EditorToolbar.tsx b/packages/app/src/components/EditorToolbar.tsx
index e7dff4905..962bc3beb 100644
--- a/packages/app/src/components/EditorToolbar.tsx
+++ b/packages/app/src/components/EditorToolbar.tsx
@@ -10,6 +10,7 @@ import { parseProjectSkillContentDocName } from '@/lib/managed-artifact-doc-name
import { cn } from '@/lib/utils';
import { EditorBreadcrumb } from './EditorBreadcrumb';
import { EditorModeToggle } from './EditorModeToggle';
+import { NotInSidebarIndicator } from './NotInSidebarIndicator';
// Lazy-loaded: skill install/history chrome (+ the shared useSkillActions
// dialogs) only mounts when the active doc is a skill, so it stays out of the
@@ -80,11 +81,20 @@ export function EditorToolbar({
so the breadcrumb's per-segment `title` tooltips actually surface.
Future siblings dropped into this cell must follow the same rule.
*/}
- <div className="pointer-events-auto flex min-w-0 items-center">
+ <div className="pointer-events-auto flex min-w-0 items-center gap-2">
{/* Skills show their identity (name/scope) in the panel, so the
`.ok/skills/<name>` path breadcrumb is noise — suppress it for
both scopes to match the global-skill editor. */}
{activeSkill ? null : <EditorBreadcrumb docName={activeDocName} />}
+ {/* Self-gating: renders only when a visibility toggle hides this
+ doc's tree row, and never for skills/templates (their names
+ attribute no axis). */}
+ {activeDocName === null ? null : (
+ <NotInSidebarIndicator
+ entry={{ kind: 'document', docName: activeDocName }}
+ className="shrink-0"
+ />
+ )}
</div>
<div className="pointer-events-auto flex justify-center">
<EditorModeToggle
diff --git a/packages/app/src/components/EmptyEditorState.test.ts b/packages/app/src/components/EmptyEditorState.test.ts
index f27bec78e..1e44a83be 100644
--- a/packages/app/src/components/EmptyEditorState.test.ts
+++ b/packages/app/src/components/EmptyEditorState.test.ts
@@ -74,4 +74,18 @@ describe('countEntries() — onboarding gate', () => {
]),
).toBe(0);
});
+
+ test('sidebar view toggles cannot alter the gate — the counter has no axis input', () => {
+ // Entries a view toggle could reveal (dot-path via show-hidden, .ok via
+ // show-ok) must not move the onboarding gate: the count always uses
+ // default visibility.
+ expect(
+ countEntries([
+ { kind: 'document', docName: 'INDEX' },
+ { kind: 'folder', path: 'brain' },
+ { kind: 'document', docName: '.scratch/wip' },
+ { kind: 'document', docName: '.ok/skills/research/SKILL' },
+ ]),
+ ).toBe(2);
+ });
});
diff --git a/packages/app/src/components/FileSidebar.dom.test.tsx b/packages/app/src/components/FileSidebar.dom.test.tsx
index a690f3782..03d547043 100644
--- a/packages/app/src/components/FileSidebar.dom.test.tsx
+++ b/packages/app/src/components/FileSidebar.dom.test.tsx
@@ -1,5 +1,5 @@
import { afterEach, beforeEach, describe, expect, mock, test } from 'bun:test';
-import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';
+import { act, cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react';
import { type ReactNode, useEffect } from 'react';
import { renderLinguiTemplate } from '@/test-utils/lingui-mock';
import {
@@ -71,10 +71,17 @@ let activeTarget: { kind: 'folder'; folderPath: string } | null = {
let folderState: FolderState = { folderCount: 2, expandedCount: 1 };
let hasTemplates = true;
let mergedConfig: {
- appearance?: { sidebar?: { showHiddenFiles?: boolean } };
+ appearance?: {
+ sidebar?: {
+ showHiddenFiles?: boolean;
+ showOnlyMarkdownFiles?: boolean;
+ showSkillsSection?: boolean;
+ };
+ };
} | null = {
appearance: { sidebar: { showHiddenFiles: false } },
};
+let projectLocalBindingNull = false;
let sidebarSearchThrows = false;
let projectPatchResult: { ok: true } | { ok: false; error: unknown } = { ok: true };
let openInAgentSubmenuProps: Array<{
@@ -270,11 +277,46 @@ mock.module('@/components/ui/context-menu', () => ({
mock.module('@/components/ui/dropdown-menu', () => ({
DropdownMenu: PassThrough,
- DropdownMenuContent: ({ children }: { children?: ReactNode }) => (
- <div data-testid="tree-options-menu">{children}</div>
+ DropdownMenuCheckboxItem: ({
+ checked,
+ children,
+ disabled,
+ onCheckedChange,
+ ...props
+ }: {
+ checked?: boolean;
+ children?: ReactNode;
+ disabled?: boolean;
+ onCheckedChange?: (checked: boolean) => void;
+ [key: string]: unknown;
+ }) => (
+ <button
+ type="button"
+ role="menuitemcheckbox"
+ aria-checked={checked ? 'true' : 'false'}
+ disabled={disabled}
+ onClick={() => {
+ if (!disabled) onCheckedChange?.(!checked);
+ }}
+ {...props}
+ >
+ {children}
+ </button>
+ ),
+ DropdownMenuContent: ({
+ children,
+ ...props
+ }: {
+ children?: ReactNode;
+ [key: string]: unknown;
+ }) => <div {...props}>{children}</div>,
+ DropdownMenuGroup: ({ children, ...props }: { children?: ReactNode; [key: string]: unknown }) => (
+ // fieldset carries the implicit `group` role Radix's Group renders with.
+ <fieldset {...props}>{children}</fieldset>
),
DropdownMenuItem: Button,
- DropdownMenuSeparator: () => null,
+ DropdownMenuLabel: ({ children }: { children?: ReactNode }) => <div>{children}</div>,
+ DropdownMenuSeparator: () => <hr data-testid="dropdown-menu-separator" />,
DropdownMenuTrigger: PassThrough,
}));
@@ -359,9 +401,11 @@ mock.module('@/hooks/use-folder-config', () => ({
mock.module('@/lib/config-provider', () => ({
useConfigContext: () => ({
merged: mergedConfig,
- projectLocalBinding: {
- patch: projectLocalPatch,
- },
+ projectLocalBinding: projectLocalBindingNull
+ ? null
+ : {
+ patch: projectLocalPatch,
+ },
}),
}));
@@ -391,6 +435,7 @@ describe('FileSidebar runtime behavior', () => {
folderState = { folderCount: 2, expandedCount: 1 };
hasTemplates = true;
mergedConfig = { appearance: { sidebar: { showHiddenFiles: false } } };
+ projectLocalBindingNull = false;
sidebarSearchThrows = false;
projectPatchResult = { ok: true };
openInAgentSubmenuProps = [];
@@ -530,6 +575,159 @@ describe('FileSidebar runtime behavior', () => {
expect(screen.queryByRole('button', { name: 'Collapse all' })).toBeNull();
});
+ test('toolbar create actions fall back to the workspace root for a revealed .ok folder', async () => {
+ activeTarget = { kind: 'folder', folderPath: 'notes/.ok/templates' };
+ await renderSidebar();
+ await waitFor(() => expect(treeListeners.size).toBe(1));
+
+ fireEvent.click(screen.getAllByRole('button', { name: 'New file' })[0]);
+ fireEvent.click(screen.getAllByRole('button', { name: 'New from template' })[0]);
+ // Root-scoped template row — the cascade re-resolves against the root
+ // fallback dir, not the active `.ok` folder.
+ fireEvent.click(screen.getByRole('button', { name: 'Root daily' }));
+ fireEvent.click(screen.getAllByRole('button', { name: 'New folder' })[0]);
+
+ expect(treeCalls.startCreating).toHaveBeenCalledWith('file', '');
+ expect(treeCalls.createFromTemplate).toHaveBeenCalledWith('', 'root-daily');
+ expect(treeCalls.startCreating).toHaveBeenCalledWith('folder', '');
+ });
+
+ test('toolbar create actions keep a nested non-.ok dotfolder as the create dir', async () => {
+ activeTarget = { kind: 'folder', folderPath: 'notes/.obsidian' };
+ await renderSidebar();
+ await waitFor(() => expect(treeListeners.size).toBe(1));
+
+ fireEvent.click(screen.getAllByRole('button', { name: 'New file' })[0]);
+
+ expect(treeCalls.startCreating).toHaveBeenCalledWith('file', 'notes/.obsidian');
+ });
+
+ test('tree-options popover renders the command pair, then a separator, then the labeled Show group of visibility checkboxes', async () => {
+ await renderSidebar();
+ await waitFor(() => expect(treeListeners.size).toBe(1));
+
+ const menu = screen.getByTestId('tree-options-menu');
+ // Mixed expansion state from beforeEach keeps both command items visible.
+ expect(within(menu).getByRole('button', { name: 'Expand all' })).toBeTruthy();
+ const collapseAll = within(menu).getByRole('button', { name: 'Collapse all' });
+ expect(within(menu).getByTestId('dropdown-menu-separator')).toBeTruthy();
+
+ const group = within(menu).getByRole('group', { name: 'Show' });
+ const checkboxes = within(group).getAllByRole('menuitemcheckbox');
+ expect(checkboxes.map((el) => el.textContent)).toEqual([
+ 'Hidden files',
+ '.ok folders',
+ 'Only markdown files',
+ 'Skills',
+ ]);
+ // Commands lead; the Show group follows.
+ expect(
+ collapseAll.compareDocumentPosition(group) & Node.DOCUMENT_POSITION_FOLLOWING,
+ ).toBeTruthy();
+ });
+
+ test('tree-options trigger stays visible with zero folders and the popover collapses to just the Show group', async () => {
+ folderState = { folderCount: 0, expandedCount: 0 };
+ await renderSidebar();
+ await waitFor(() => expect(treeListeners.size).toBe(1));
+
+ expect(screen.getByRole('button', { name: 'Tree view options' })).toBeTruthy();
+ const menu = screen.getByTestId('tree-options-menu');
+ // Both commands would no-op without folders, so they and their trailing
+ // separator smart-hide; the Show group is state-independent and remains.
+ expect(within(menu).queryByRole('button', { name: 'Expand all' })).toBeNull();
+ expect(within(menu).queryByRole('button', { name: 'Collapse all' })).toBeNull();
+ expect(within(menu).queryByTestId('dropdown-menu-separator')).toBeNull();
+ expect(within(menu).getAllByRole('menuitemcheckbox')).toHaveLength(4);
+ });
+
+ test('each Show checkbox reflects its config leaf and writes it through the project-local binding', async () => {
+ mergedConfig = {
+ appearance: { sidebar: { showHiddenFiles: true, showOnlyMarkdownFiles: false } },
+ };
+ await renderSidebar();
+ const menu = screen.getByTestId('tree-options-menu');
+
+ // Checked state mirrors merged config — hidden files on, .ok folders +
+ // only-markdown off (keys absent / false), skills defaulting on while its
+ // key is absent.
+ expect(
+ within(menu).getByTestId('tree-options-show-hidden-files').getAttribute('aria-checked'),
+ ).toBe('true');
+ expect(
+ within(menu).getByTestId('tree-options-show-ok-folders').getAttribute('aria-checked'),
+ ).toBe('false');
+ expect(
+ within(menu)
+ .getByTestId('tree-options-show-only-markdown-files')
+ .getAttribute('aria-checked'),
+ ).toBe('false');
+ expect(within(menu).getByTestId('tree-options-show-skills').getAttribute('aria-checked')).toBe(
+ 'true',
+ );
+
+ fireEvent.click(within(menu).getByTestId('tree-options-show-hidden-files'));
+ expect(projectLocalPatch).toHaveBeenCalledWith({
+ appearance: { sidebar: { showHiddenFiles: false } },
+ });
+ fireEvent.click(within(menu).getByTestId('tree-options-show-ok-folders'));
+ expect(projectLocalPatch).toHaveBeenCalledWith({
+ appearance: { sidebar: { showOkFolders: true } },
+ });
+ fireEvent.click(within(menu).getByTestId('tree-options-show-only-markdown-files'));
+ expect(projectLocalPatch).toHaveBeenCalledWith({
+ appearance: { sidebar: { showOnlyMarkdownFiles: true } },
+ });
+ fireEvent.click(within(menu).getByTestId('tree-options-show-skills'));
+ expect(projectLocalPatch).toHaveBeenCalledWith({
+ appearance: { sidebar: { showSkillsSection: false } },
+ });
+ });
+
+ test('Show checkboxes disable while the project-local binding is unavailable', async () => {
+ projectLocalBindingNull = true;
+ await renderSidebar();
+ const menu = screen.getByTestId('tree-options-menu');
+
+ for (const id of [
+ 'tree-options-show-hidden-files',
+ 'tree-options-show-ok-folders',
+ 'tree-options-show-only-markdown-files',
+ 'tree-options-show-skills',
+ ]) {
+ const checkbox = within(menu).getByTestId(id) as HTMLButtonElement;
+ expect(checkbox.disabled).toBe(true);
+ fireEvent.click(checkbox);
+ }
+ for (const id of [
+ 'empty-space-menu-show-hidden-files',
+ 'empty-space-menu-show-ok-folders',
+ 'empty-space-menu-show-only-markdown-files',
+ 'empty-space-menu-show-skills-section',
+ ]) {
+ const checkbox = screen.getByTestId(id) as HTMLButtonElement;
+ expect(checkbox.disabled).toBe(true);
+ fireEvent.click(checkbox);
+ }
+ expect(projectLocalPatch).not.toHaveBeenCalled();
+ });
+
+ test('a rejected visibility patch surfaces the settings toast', async () => {
+ projectPatchResult = {
+ ok: false,
+ error: { code: 'TEST_REJECTED', message: 'scope violation' },
+ };
+ await renderSidebar();
+
+ fireEvent.click(
+ within(screen.getByTestId('tree-options-menu')).getByTestId(
+ 'tree-options-show-only-markdown-files',
+ ),
+ );
+ expect(toastErrors[0]?.[0]).toBe('Could not update sidebar settings');
+ expect(toastErrors[0]?.[1]).toEqual({ description: 'scope violation' });
+ });
+
test('empty-space menu renders ordered project-root actions and routes each runtime effect', async () => {
installBridge();
await renderSidebar();
@@ -543,6 +741,9 @@ describe('FileSidebar runtime behavior', () => {
'open-in-agent-empty-space-submenu',
'empty-space-menu-copy-full-path',
'empty-space-menu-show-hidden-files',
+ 'empty-space-menu-show-ok-folders',
+ 'empty-space-menu-show-only-markdown-files',
+ 'empty-space-menu-show-skills-section',
'empty-space-menu-expand-all',
'empty-space-menu-collapse-all',
];
@@ -581,6 +782,44 @@ describe('FileSidebar runtime behavior', () => {
});
});
+ test('empty-space visibility toggles carry full-form labels and patch their own leaves', async () => {
+ mergedConfig = { appearance: { sidebar: { showOnlyMarkdownFiles: true } } };
+ await renderSidebar();
+
+ const hidden = screen.getByTestId('empty-space-menu-show-hidden-files');
+ const okFolders = screen.getByTestId('empty-space-menu-show-ok-folders');
+ const onlyMarkdown = screen.getByTestId('empty-space-menu-show-only-markdown-files');
+ const skills = screen.getByTestId('empty-space-menu-show-skills-section');
+ expect(hidden.textContent).toBe('Show hidden files');
+ expect(okFolders.textContent).toBe('Show .ok folders');
+ expect(onlyMarkdown.textContent).toBe('Show only markdown files');
+ expect(skills.textContent).toBe('Show skills section');
+
+ // Skills expects checked with its key absent from the fixture: the
+ // section toggle is the one default-on leaf.
+ expect(hidden.getAttribute('aria-checked')).toBe('false');
+ expect(okFolders.getAttribute('aria-checked')).toBe('false');
+ expect(onlyMarkdown.getAttribute('aria-checked')).toBe('true');
+ expect(skills.getAttribute('aria-checked')).toBe('true');
+
+ fireEvent.click(hidden);
+ expect(projectLocalPatch).toHaveBeenCalledWith({
+ appearance: { sidebar: { showHiddenFiles: true } },
+ });
+ fireEvent.click(okFolders);
+ expect(projectLocalPatch).toHaveBeenCalledWith({
+ appearance: { sidebar: { showOkFolders: true } },
+ });
+ fireEvent.click(onlyMarkdown);
+ expect(projectLocalPatch).toHaveBeenCalledWith({
+ appearance: { sidebar: { showOnlyMarkdownFiles: false } },
+ });
+ fireEvent.click(skills);
+ expect(projectLocalPatch).toHaveBeenCalledWith({
+ appearance: { sidebar: { showSkillsSection: false } },
+ });
+ });
+
test('toolbar and empty-space menu hide "New from template" when no templates exist', async () => {
// Both template-create surfaces drop the entry entirely when the resolved
// cascade is empty — the toolbar button and the empty-space submenu, not
@@ -608,6 +847,7 @@ describe('FileSidebar runtime behavior', () => {
canCollapseAll: true,
canExpandAll: true,
showHiddenFiles: false,
+ showOkFolders: false,
}),
),
);
@@ -621,11 +861,46 @@ describe('FileSidebar runtime behavior', () => {
canCollapseAll: true,
canExpandAll: false,
showHiddenFiles: false,
+ showOkFolders: false,
}),
),
);
});
+ test('showSkillsSection false removes the Skills section from the sidebar', async () => {
+ mergedConfig = { appearance: { sidebar: { showSkillsSection: false } } };
+ await renderSidebar();
+
+ expect(screen.queryByTestId('skills-sidebar-section')).toBeNull();
+ // The rest of the sidebar is unaffected by the section gate.
+ expect(screen.getByTestId('file-tree-stub')).toBeTruthy();
+ });
+
+ test('Skills section renders when showSkillsSection is unset and when config is absent', async () => {
+ // beforeEach config carries no showSkillsSection key — the default is ON.
+ const rendered = await renderSidebar();
+ expect(screen.getByTestId('skills-sidebar-section')).toBeTruthy();
+
+ // No merged config at all (early load) must also leave the section on.
+ mergedConfig = null;
+ const { FileSidebar } = await import('./FileSidebar');
+ rendered.rerender(<FileSidebar onOpenSearch={onOpenSearch} />);
+ expect(screen.getByTestId('skills-sidebar-section')).toBeTruthy();
+ });
+
+ test('hidden Skills section stays hidden while a skill doc is the active doc', async () => {
+ // The gate reads only the config axis: an open skill doc must not pull the
+ // section back (no auto-reveal), and the sidebar stays fully functional.
+ mergedConfig = { appearance: { sidebar: { showSkillsSection: false } } };
+ activeDocName = '.ok/skills/test-skill/SKILL';
+ activeTarget = null;
+ await renderSidebar();
+
+ expect(screen.queryByTestId('skills-sidebar-section')).toBeNull();
+ expect(screen.getByTestId('file-tree-stub')).toBeTruthy();
+ expect(screen.getAllByRole('button', { name: 'New file' }).length).toBeGreaterThan(0);
+ });
+
test('search pill render failures are contained to the pill row and reset when sidebar state changes', async () => {
const originalConsoleError = console.error;
console.error = mock(() => {}) as never;
diff --git a/packages/app/src/components/FileSidebar.menu-action.dom.test.tsx b/packages/app/src/components/FileSidebar.menu-action.dom.test.tsx
index 6561bad59..8b11ccc47 100644
--- a/packages/app/src/components/FileSidebar.menu-action.dom.test.tsx
+++ b/packages/app/src/components/FileSidebar.menu-action.dom.test.tsx
@@ -53,6 +53,7 @@ const ACTIVE_TARGET = {
target: 'notes/source',
docName: 'notes/source',
} satisfies ResolvedNavigationTarget;
+let activeTarget: ResolvedNavigationTarget | null = ACTIVE_TARGET;
const notifyViewMenuStateChangedMock = mock(() => {});
const toggleSidebarMock = mock(() => {});
@@ -67,6 +68,16 @@ const treeCalls = {
startCreatingFromTemplate: mock((_parentDir: string) => {}),
};
const projectLocalPatch = mock((_patch: unknown) => ({ ok: true as const }));
+// Production `projectLocalBinding` keeps its identity across config-value
+// changes (the provider swaps only `config` on binding updates), so the
+// menu-action effect re-binds on a visibility flip ONLY when the flipped
+// value itself is in its dependency array. The harness must mirror that:
+// a stable binding object plus a merged config swapped between renders —
+// a fresh binding per render would re-subscribe every render and mask
+// stale-closure regressions in the effect's deps.
+const projectLocalBindingStub = { patch: projectLocalPatch };
+const DEFAULT_MERGED_CONFIG = { appearance: { sidebar: { showHiddenFiles: false } } };
+let mergedConfig: { appearance?: { sidebar?: Record<string, boolean> } } = DEFAULT_MERGED_CONFIG;
let menuActionCallback: ((action: MenuAction) => void) | null = null;
mock.module('@/lib/perf', () => ({
@@ -136,8 +147,30 @@ mock.module('@/components/ui/context-menu', () => ({
mock.module('@/components/ui/dropdown-menu', () => ({
DropdownMenu: PassThrough,
+ DropdownMenuCheckboxItem: ({
+ checked,
+ children,
+ onCheckedChange: _onCheckedChange,
+ ...props
+ }: {
+ checked?: boolean;
+ children?: ReactNode;
+ onCheckedChange?: (checked: boolean) => void;
+ [key: string]: unknown;
+ }) => (
+ <button
+ type="button"
+ role="menuitemcheckbox"
+ aria-checked={checked ? 'true' : 'false'}
+ {...props}
+ >
+ {children}
+ </button>
+ ),
DropdownMenuContent: ElementPassThrough,
+ DropdownMenuGroup: ElementPassThrough,
DropdownMenuItem: Button,
+ DropdownMenuLabel: ElementPassThrough,
DropdownMenuSeparator: () => null,
DropdownMenuTrigger: PassThrough,
}));
@@ -167,8 +200,12 @@ mock.module('@/components/handoff/useHandoffDispatch', () => ({
useHandoffDispatch: () => ({ dispatch: handoffDispatchMock }),
}));
+// Stable across renders like production (`states` is useState state there) —
+// a fresh object per render would churn the menu-action effect's
+// `handoffInstallStates` dep and re-subscribe on every render.
+const installedAgentStates = { codex: { installed: true } };
mock.module('@/components/handoff/useInstalledAgents', () => ({
- useInstalledAgents: () => ({ states: { codex: { installed: true } } }),
+ useInstalledAgents: () => ({ states: installedAgentStates }),
}));
mock.module('@/components/ProjectSwitcher', () => ({
@@ -187,7 +224,7 @@ mock.module('@/components/UpdateNotices', () => ({
mock.module('@/editor/DocumentContext', () => ({
useDocumentContext: () => ({
activeDocName: 'notes/source',
- activeTarget: ACTIVE_TARGET,
+ activeTarget,
}),
}));
@@ -202,16 +239,19 @@ mock.module('@/hooks/use-folder-config', () => ({
mock.module('@/lib/config-provider', () => ({
useConfigContext: () => ({
- projectLocalBinding: { patch: projectLocalPatch },
- merged: { appearance: { sidebar: { showHiddenFiles: false } } },
+ projectLocalBinding: projectLocalBindingStub,
+ merged: mergedConfig,
}),
}));
+// Stable for the same reason as `installedAgentStates` — `workspace` is a
+// dep of the menu-action effect.
+const workspaceStub = {
+ contentDir: '/tmp/open-knowledge',
+ pathSeparator: '/',
+};
mock.module('@/lib/use-workspace', () => ({
- useWorkspace: () => ({
- contentDir: '/tmp/open-knowledge',
- pathSeparator: '/',
- }),
+ useWorkspace: () => workspaceStub,
}));
mock.module('sonner', () => ({
@@ -231,6 +271,8 @@ const {
describe('FileSidebar menu-action runtime routing', () => {
beforeEach(() => {
menuActionCallback = null;
+ activeTarget = ACTIVE_TARGET;
+ mergedConfig = DEFAULT_MERGED_CONFIG;
for (const fn of [
notifyViewMenuStateChangedMock,
toggleSidebarMock,
@@ -343,6 +385,90 @@ describe('FileSidebar menu-action runtime routing', () => {
}
});
+ test('mutating menu actions quietly no-op on a revealed .ok folder while create falls back to root', async () => {
+ activeTarget = {
+ kind: 'folder',
+ target: 'notes/.ok/templates',
+ folderPath: 'notes/.ok/templates',
+ };
+ const renamed: ResolvedNavigationTarget[] = [];
+ const duplicated: ResolvedNavigationTarget[] = [];
+ const deleted: ResolvedNavigationTarget[] = [];
+ const unsubscribeRename = subscribeToFileTreeMenuActionRename((target) => renamed.push(target));
+ const unsubscribeDuplicate = subscribeToFileTreeMenuActionDuplicate((target) =>
+ duplicated.push(target),
+ );
+ const unsubscribeDelete = subscribeToFileTreeMenuActionDelete((target) => deleted.push(target));
+
+ try {
+ render(<FileSidebar onOpenSearch={() => {}} />);
+ await waitFor(() => expect(menuActionCallback).not.toBeNull());
+
+ menuActionCallback?.('rename' as MenuAction);
+ menuActionCallback?.('duplicate' as MenuAction);
+ menuActionCallback?.('move-to-trash' as MenuAction);
+
+ expect(renamed).toEqual([]);
+ expect(duplicated).toEqual([]);
+ expect(deleted).toEqual([]);
+
+ // Create stays live but re-targets the workspace root; read-only routes
+ // keep serving the `.ok` path.
+ menuActionCallback?.('new-doc' as MenuAction);
+ expect(treeCalls.startCreating).toHaveBeenCalledWith('file', '');
+
+ menuActionCallback?.('copy-relative-path' as MenuAction);
+ await waitFor(() =>
+ expect(navigator.clipboard.writeText).toHaveBeenCalledWith('notes/.ok/templates'),
+ );
+ } finally {
+ unsubscribeRename();
+ unsubscribeDuplicate();
+ unsubscribeDelete();
+ }
+ });
+
+ test('mutating menu actions no-op on an opened .ok asset but stay live for other assets', async () => {
+ activeTarget = {
+ kind: 'asset',
+ target: '.ok/raw-probe.md',
+ assetPath: '.ok/raw-probe.md',
+ mediaKind: null,
+ };
+ const renamed: ResolvedNavigationTarget[] = [];
+ const deleted: ResolvedNavigationTarget[] = [];
+ const unsubscribeRename = subscribeToFileTreeMenuActionRename((target) => renamed.push(target));
+ const unsubscribeDelete = subscribeToFileTreeMenuActionDelete((target) => deleted.push(target));
+
+ try {
+ const rendered = render(<FileSidebar onOpenSearch={() => {}} />);
+ await waitFor(() => expect(menuActionCallback).not.toBeNull());
+
+ menuActionCallback?.('rename' as MenuAction);
+ menuActionCallback?.('move-to-trash' as MenuAction);
+
+ expect(renamed).toEqual([]);
+ expect(deleted).toEqual([]);
+
+ const imageTarget = {
+ kind: 'asset',
+ target: 'images/logo.png',
+ assetPath: 'images/logo.png',
+ mediaKind: 'image',
+ } satisfies ResolvedNavigationTarget;
+ activeTarget = imageTarget;
+ rendered.rerender(<FileSidebar onOpenSearch={() => {}} />);
+ await waitFor(() => expect(menuActionCallback).not.toBeNull());
+
+ menuActionCallback?.('rename' as MenuAction);
+
+ expect(renamed).toEqual([imageTarget]);
+ } finally {
+ unsubscribeRename();
+ unsubscribeDelete();
+ }
+ });
+
test('shell, clipboard, handoff, and visibility-toggle actions use runtime dependencies', async () => {
render(<FileSidebar onOpenSearch={() => {}} />);
await waitFor(() => expect(menuActionCallback).not.toBeNull());
@@ -372,6 +498,66 @@ describe('FileSidebar menu-action runtime routing', () => {
expect(projectLocalPatch).toHaveBeenCalledWith({
appearance: { sidebar: { showHiddenFiles: true } },
});
+
+ // The sibling visibility toggles invert their merged-config reads
+ // (.ok folders + only-markdown resolve false, skills resolves true in
+ // this harness).
+ menuActionCallback?.('toggle-show-ok-folders' as MenuAction);
+ expect(projectLocalPatch).toHaveBeenCalledWith({
+ appearance: { sidebar: { showOkFolders: true } },
+ });
+
+ menuActionCallback?.('toggle-show-only-markdown-files' as MenuAction);
+ expect(projectLocalPatch).toHaveBeenCalledWith({
+ appearance: { sidebar: { showOnlyMarkdownFiles: true } },
+ });
+
+ menuActionCallback?.('toggle-show-skills-section' as MenuAction);
+ expect(projectLocalPatch).toHaveBeenCalledWith({
+ appearance: { sidebar: { showSkillsSection: false } },
+ });
+ });
+
+ test('visibility toggles read the latest merged config across a flip round-trip', async () => {
+ // A native View-menu toggle fires twice in a row: first click patches the
+ // inverted default, the CRDT converges the merged config, second click
+ // must invert the CONVERGED value — a handler closure that misses the
+ // flipped state in its effect deps writes the stale inversion (a no-op)
+ // and the menu item sticks in one state.
+ const toggleRoundTrips = [
+ { action: 'toggle-show-hidden-files', key: 'showHiddenFiles', defaultValue: false },
+ { action: 'toggle-show-ok-folders', key: 'showOkFolders', defaultValue: false },
+ {
+ action: 'toggle-show-only-markdown-files',
+ key: 'showOnlyMarkdownFiles',
+ defaultValue: false,
+ },
+ { action: 'toggle-show-skills-section', key: 'showSkillsSection', defaultValue: true },
+ ] as const;
+
+ const { rerender } = render(<FileSidebar onOpenSearch={() => {}} />);
+ await waitFor(() => expect(menuActionCallback).not.toBeNull());
+
+ for (const { action, key, defaultValue } of toggleRoundTrips) {
+ mergedConfig = { appearance: { sidebar: {} } };
+ rerender(<FileSidebar onOpenSearch={() => {}} />);
+
+ projectLocalPatch.mockClear();
+ menuActionCallback?.(action as MenuAction);
+ expect(projectLocalPatch).toHaveBeenCalledWith({
+ appearance: { sidebar: { [key]: !defaultValue } },
+ });
+
+ // Converge: the merged config now reflects the patched value.
+ mergedConfig = { appearance: { sidebar: { [key]: !defaultValue } } };
+ rerender(<FileSidebar onOpenSearch={() => {}} />);
+
+ projectLocalPatch.mockClear();
+ menuActionCallback?.(action as MenuAction);
+ expect(projectLocalPatch).toHaveBeenCalledWith({
+ appearance: { sidebar: { [key]: defaultValue } },
+ });
+ }
});
test('pushes View menu state to the desktop bridge with merged visibility and tree gates', async () => {
@@ -383,6 +569,8 @@ describe('FileSidebar menu-action runtime routing', () => {
canCollapseAll: true,
canExpandAll: true,
showHiddenFiles: false,
+ showOnlyMarkdownFiles: false,
+ showSkillsSection: true,
sidebarVisible: true,
}),
),
diff --git a/packages/app/src/components/FileSidebar.share.dom.test.tsx b/packages/app/src/components/FileSidebar.share.dom.test.tsx
index 985270743..51608bf4b 100644
--- a/packages/app/src/components/FileSidebar.share.dom.test.tsx
+++ b/packages/app/src/components/FileSidebar.share.dom.test.tsx
@@ -129,8 +129,30 @@ mock.module('@/components/ui/context-menu', () => ({
mock.module('@/components/ui/dropdown-menu', () => ({
DropdownMenu: PassThrough,
+ DropdownMenuCheckboxItem: ({
+ checked,
+ children,
+ onCheckedChange: _onCheckedChange,
+ ...props
+ }: {
+ checked?: boolean;
+ children?: ReactNode;
+ onCheckedChange?: (checked: boolean) => void;
+ [key: string]: unknown;
+ }) => (
+ <button
+ type="button"
+ role="menuitemcheckbox"
+ aria-checked={checked ? 'true' : 'false'}
+ {...props}
+ >
+ {children}
+ </button>
+ ),
DropdownMenuContent: ElementPassThrough,
+ DropdownMenuGroup: ElementPassThrough,
DropdownMenuItem: Button,
+ DropdownMenuLabel: ElementPassThrough,
DropdownMenuSeparator: () => null,
DropdownMenuTrigger: PassThrough,
}));
diff --git a/packages/app/src/components/FileSidebar.tsx b/packages/app/src/components/FileSidebar.tsx
index 35b2e1447..01d6eb257 100644
--- a/packages/app/src/components/FileSidebar.tsx
+++ b/packages/app/src/components/FileSidebar.tsx
@@ -17,7 +17,7 @@ import { ErrorBoundary } from 'react-error-boundary';
import { toast } from 'sonner';
import { ConflictsSection } from '@/components/ConflictsSection';
import { FileTree, type FileTreeHandle } from '@/components/FileTree';
-import { defaultInitialDir } from '@/components/file-tree-utils';
+import { defaultInitialDir, hasOkPathSegment } from '@/components/file-tree-utils';
import { OpenInAgentEmptySpaceSubmenu } from '@/components/handoff/OpenInAgentEmptySpaceSubmenu';
import {
buildProjectScopedHandoffInput,
@@ -45,8 +45,12 @@ import {
} from '@/components/ui/context-menu';
import {
DropdownMenu,
+ DropdownMenuCheckboxItem,
DropdownMenuContent,
+ DropdownMenuGroup,
DropdownMenuItem,
+ DropdownMenuLabel,
+ DropdownMenuSeparator,
DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';
import {
@@ -194,10 +198,15 @@ function FileSidebarInner({ onOpenSearch }: FileSidebarProps) {
// showing the open doc. Every `initialCreateDir` consumer is creation-scoped
// (toolbar, template cascade, File-menu new-*), so overriding here covers all
// of them; active-item actions (Duplicate / Rename / …) read `activeTarget`.
- const baseCreateDir =
+ const activeCreateDir =
activeTarget?.kind === 'folder' || activeTarget?.kind === 'folder-index'
? activeTarget.folderPath
: defaultInitialDir(activeDocName);
+ // Revealed `.ok` rows are read-only OK-managed state — never a create
+ // target. Fall back to the workspace root (the same dir an empty-space
+ // deselect resolves to); the server's reserved-path rejection stays the
+ // authoritative backstop.
+ const baseCreateDir = hasOkPathSegment(activeCreateDir) ? '' : activeCreateDir;
const [treeCreationCleared, setTreeCreationCleared] = useState(false);
const initialCreateDir = treeCreationCleared ? '' : baseCreateDir;
@@ -227,9 +236,10 @@ function FileSidebarInner({ onOpenSearch }: FileSidebarProps) {
// start time when both sides read the same expression.
const shouldFadeChrome = isElectronHost && isCollapsed;
- // Reactive subscription to FileTree's folder state. Drives the
- // smart-hide of the Tree view options dropdown:
- // - dropdown trigger hidden when there are no folders
+ // Reactive subscription to FileTree's folder state. Drives the smart-hide
+ // of the Expand/Collapse-all commands across the tree-options popover, the
+ // empty-space menu, and the native View menu:
+ // - both hidden when there are no folders (each would be a no-op)
// - "Expand all" hidden when every folder is already expanded
// - "Collapse all" hidden when every folder is already collapsed
//
@@ -242,8 +252,8 @@ function FileSidebarInner({ onOpenSearch }: FileSidebarProps) {
// return` — same race shape: effect runs once on mount with empty deps, the
// handle is non-null in commit phase, but the effect's closure captured the
// ref read AT EFFECT TIME and bailed; no re-subscribe ever happens. Visible
- // symptom both times: dropdown trigger hidden on cold launch even when
- // folders existed.
+ // symptom both times (under the trigger's then-standing hasFolders gate):
+ // dropdown trigger hidden on cold launch even when folders existed.
//
// The fix below uses `useState` + a ref-callback (`setTree`). React invokes
// the ref-callback synchronously during commit when the child's
@@ -315,8 +325,9 @@ function FileSidebarInner({ onOpenSearch }: FileSidebarProps) {
// Empty-space menu wiring. Workspace drives the disabled-with-hint state
// for the act-on-project items; install states + dispatch drive the Send
- // to AI submenu; project-local binding drives the Show . / Show all check
- // states. The bridge is required for the Electron-only items (Reveal in
+ // to AI submenu; the project-local binding drives the visibility
+ // checkboxes (checked from the merged config; null binding disables). The
+ // bridge is required for the Electron-only items (Reveal in
// Finder) — those rows return null in web mode via the
// `if (!bridge) return null` cross-cutting pattern. Copy full path is
// visible in both modes (`navigator.clipboard.writeText` is Baseline
@@ -338,14 +349,17 @@ function FileSidebarInner({ onOpenSearch }: FileSidebarProps) {
const emptySpaceHandoffInput = buildProjectScopedHandoffInput({ workspace });
const { projectLocalBinding, merged } = useConfigContext();
const showHiddenFiles = merged?.appearance?.sidebar?.showHiddenFiles ?? false;
- // Smart-hide gates for the Expand/Collapse-all tree-state items — tree-
- // scoped. Mirrors the toolbar dropdown's behavior: hide when the action
- // would be a no-op (no folders at all; every folder already in the target
- // state). The empty-space menu does NOT carry a separator before the
- // section when both items hide.
- const showEmptySpaceExpandAll = hasFolders && !allExpanded;
- const showEmptySpaceCollapseAll = hasFolders && !noneExpanded;
- const showEmptySpaceTreeStateSection = showEmptySpaceExpandAll || showEmptySpaceCollapseAll;
+ const showOkFolders = merged?.appearance?.sidebar?.showOkFolders ?? false;
+ const showOnlyMarkdownFiles = merged?.appearance?.sidebar?.showOnlyMarkdownFiles ?? false;
+ const showSkillsSection = merged?.appearance?.sidebar?.showSkillsSection ?? true;
+ // Smart-hide gates for the Expand/Collapse-all tree-state items, shared by
+ // the toolbar popover, the empty-space menu, and the native View menu (via
+ // the IPC push below): hide when the action would be a no-op (no folders at
+ // all; every folder already in the target state). Neither in-renderer menu
+ // carries a separator around the section when both items hide.
+ const showExpandAll = hasFolders && !allExpanded;
+ const showCollapseAll = hasFolders && !noneExpanded;
+ const showTreeStateSection = showExpandAll || showCollapseAll;
// Sidebar-wide context-menu surface. Right-click anywhere inside the
// sidebar except interactive controls (toolbar buttons, search-pill button,
@@ -412,13 +426,19 @@ function FileSidebarInner({ onOpenSearch }: FileSidebarProps) {
},
);
};
- const handleEmptySpaceShowHiddenFilesToggle = (checked: boolean) => {
+ // Single write path for the sidebar visibility checkboxes (toolbar popover,
+ // empty-space menu, native View menu action): every toggle patches the same
+ // project-local config shape and surfaces rejections with the same toast.
+ const patchSidebarVisibility = (sidebar: {
+ showHiddenFiles?: boolean;
+ showOkFolders?: boolean;
+ showOnlyMarkdownFiles?: boolean;
+ showSkillsSection?: boolean;
+ }) => {
if (projectLocalBinding === null) return;
- const result = projectLocalBinding.patch({
- appearance: { sidebar: { showHiddenFiles: checked } },
- });
+ const result = projectLocalBinding.patch({ appearance: { sidebar } });
if (!result.ok) {
- console.warn('[FileSidebar] showHiddenFiles toggle rejected:', humanFormat(result.error));
+ console.warn('[FileSidebar] sidebar visibility toggle rejected:', humanFormat(result.error));
toast.error(t`Could not update sidebar settings`, {
description: humanFormat(result.error),
});
@@ -438,18 +458,30 @@ function FileSidebarInner({ onOpenSearch }: FileSidebarProps) {
// changes (CRDT-pushed) AND tree-state transitions (Pierre model emits
// via the tree.subscribe path that already updates `folderState`). The
// bridge gate keeps web mode a no-op. `canExpandAll` / `canCollapseAll`
- // mirror the empty-space menu's `showEmptySpace*` gates exactly — both
- // surfaces should agree on what counts as a no-op action.
+ // are the same shared smart-hide gates the in-renderer menus render from,
+ // so every surface agrees on what counts as a no-op action.
// `sidebarVisible` flips the View → Show/Hide Sidebar label main-side.
useEffect(() => {
if (!bridge) return;
bridge.editor.notifyViewMenuStateChanged({
showHiddenFiles,
- canExpandAll: showEmptySpaceExpandAll,
- canCollapseAll: showEmptySpaceCollapseAll,
+ showOkFolders,
+ showOnlyMarkdownFiles,
+ showSkillsSection,
+ canExpandAll: showExpandAll,
+ canCollapseAll: showCollapseAll,
sidebarVisible: sidebarState === 'expanded',
});
- }, [bridge, showHiddenFiles, showEmptySpaceExpandAll, showEmptySpaceCollapseAll, sidebarState]);
+ }, [
+ bridge,
+ showHiddenFiles,
+ showOkFolders,
+ showOnlyMarkdownFiles,
+ showSkillsSection,
+ showExpandAll,
+ showCollapseAll,
+ sidebarState,
+ ]);
// macOS menu-action subscriber. Main fires `ok:menu-action` for every
// user click on a state-aware File menu item or a View menu toggle /
@@ -481,9 +513,17 @@ function FileSidebarInner({ onOpenSearch }: FileSidebarProps) {
// whenever any input the routing depends on changes, so the handler
// closure always sees the latest `activeTarget`, `workspace`, etc.
// without stale-closure bugs.
+ // biome-ignore lint/correctness/useExhaustiveDependencies: patchSidebarVisibility is behaviorally stable — it reads only projectLocalBinding + t, both already deps; listing the helper itself would re-create the subscription every render (sibling pattern: CommandPalette's refreshSemanticStatus).
useEffect(() => {
if (!bridge) return;
return bridge.onMenuAction((action) => {
+ // Revealed `.ok` targets are read-only: the mutating picks below
+ // (rename / duplicate / move-to-trash) quietly no-op on them, mirroring
+ // the row menu's suppressed affordances. The server's reserved-path
+ // rejection stays the authoritative backstop; read-only routes (reveal,
+ // copy path, send-to-ai) keep working.
+ const isOkManagedTarget =
+ activeTarget !== null && hasOkPathSegment(resolveActiveTargetRelativePath(activeTarget));
switch (action) {
case 'new-doc': {
if (!workspace || !tree) return;
@@ -501,12 +541,12 @@ function FileSidebarInner({ onOpenSearch }: FileSidebarProps) {
return;
}
case 'rename': {
- if (!activeTarget) return;
+ if (!activeTarget || isOkManagedTarget) return;
emitFileTreeMenuActionRename(activeTarget);
return;
}
case 'duplicate': {
- if (!activeTarget) return;
+ if (!activeTarget || isOkManagedTarget) return;
emitFileTreeMenuActionDuplicate(activeTarget);
return;
}
@@ -514,7 +554,7 @@ function FileSidebarInner({ onOpenSearch }: FileSidebarProps) {
// FileTree owns the 2-step delete spine; surface the
// request via the documents-events bus the row context menu also
// feeds. Same payload shape as the sidebar's right-click Delete.
- if (!activeTarget) return;
+ if (!activeTarget || isOkManagedTarget) return;
emitFileTreeMenuActionDelete(activeTarget);
return;
}
@@ -590,20 +630,20 @@ function FileSidebarInner({ onOpenSearch }: FileSidebarProps) {
});
return;
}
+ case 'toggle-show-ok-folders': {
+ patchSidebarVisibility({ showOkFolders: !showOkFolders });
+ return;
+ }
case 'toggle-show-hidden-files': {
- if (projectLocalBinding === null) return;
- const result = projectLocalBinding.patch({
- appearance: { sidebar: { showHiddenFiles: !showHiddenFiles } },
- });
- if (!result.ok) {
- console.warn(
- '[FileSidebar] toggle-show-hidden-files rejected:',
- humanFormat(result.error),
- );
- toast.error(t`Could not update sidebar settings`, {
- description: humanFormat(result.error),
- });
- }
+ patchSidebarVisibility({ showHiddenFiles: !showHiddenFiles });
+ return;
+ }
+ case 'toggle-show-only-markdown-files': {
+ patchSidebarVisibility({ showOnlyMarkdownFiles: !showOnlyMarkdownFiles });
+ return;
+ }
+ case 'toggle-show-skills-section': {
+ patchSidebarVisibility({ showSkillsSection: !showSkillsSection });
return;
}
case 'expand-all-tree': {
@@ -643,6 +683,9 @@ function FileSidebarInner({ onOpenSearch }: FileSidebarProps) {
initialCreateDir,
projectLocalBinding,
showHiddenFiles,
+ showOkFolders,
+ showOnlyMarkdownFiles,
+ showSkillsSection,
handoffInstallStates,
dispatchHandoff,
toggleSidebar,
@@ -789,7 +832,7 @@ function FileSidebarInner({ onOpenSearch }: FileSidebarProps) {
)}
>
{/*
- * Expand/Collapse-All uses DropdownMenu (click-to-open). The
+ * Tree view options uses DropdownMenu (click-to-open). The
* earlier hover-to-open HoverCard shape was unreachable from
* keyboard and touch: Radix HoverCard's content root forcibly
* sets `tabindex="-1"` on every tabbable descendant
@@ -799,32 +842,84 @@ function FileSidebarInner({ onOpenSearch }: FileSidebarProps) {
* focus between items, and is the shadcn-standard pattern
* for toolbar menus.
*
- * Smart-hide: trigger only renders when the tree has folders
- * (no folders → both menu items would be no-ops, so the entire
- * trigger is wasted screen real estate). Individual items hide
- * when their action would no-op: "Expand all" hides when every
- * folder is already expanded; "Collapse all" hides when none
- * are expanded. Mixed states show both items.
+ * The trigger is always visible: the Show group is state-
+ * independent, so the menu always has content. The Expand/
+ * Collapse-all commands smart-hide individually when their
+ * action would no-op (no folders; every folder already
+ * expanded / collapsed), taking their separator with them.
*/}
- {hasFolders ? (
- <DropdownMenu>
- <ToolbarDropdownTrigger icon={ListCollapse} label={t`Tree view options`} />
- <DropdownMenuContent align="end" className="min-w-52">
- {!allExpanded ? (
- <DropdownMenuItem onSelect={() => tree?.expandAll()}>
- <UnfoldVertical aria-hidden="true" />
- <Trans>Expand all</Trans>
- </DropdownMenuItem>
- ) : null}
- {!noneExpanded ? (
- <DropdownMenuItem onSelect={() => tree?.collapseAll()}>
- <FoldVertical aria-hidden="true" />
- <Trans>Collapse all</Trans>
- </DropdownMenuItem>
- ) : null}
- </DropdownMenuContent>
- </DropdownMenu>
- ) : null}
+ <DropdownMenu>
+ <ToolbarDropdownTrigger icon={ListCollapse} label={t`Tree view options`} />
+ <DropdownMenuContent
+ align="end"
+ className="min-w-52"
+ data-testid="tree-options-menu"
+ >
+ {showExpandAll ? (
+ <DropdownMenuItem onSelect={() => tree?.expandAll()}>
+ <UnfoldVertical aria-hidden="true" />
+ <Trans>Expand all</Trans>
+ </DropdownMenuItem>
+ ) : null}
+ {showCollapseAll ? (
+ <DropdownMenuItem onSelect={() => tree?.collapseAll()}>
+ <FoldVertical aria-hidden="true" />
+ <Trans>Collapse all</Trans>
+ </DropdownMenuItem>
+ ) : null}
+ {showTreeStateSection ? <DropdownMenuSeparator /> : null}
+ {/* Labeled `role="group"` so assistive tech announces the
+ section; the visual DropdownMenuLabel alone is skipped
+ by arrow-key menu navigation. Items read group-relative
+ ("Hidden files") because the label carries the "Show";
+ the unsectioned menu surfaces use the full-form labels. */}
+ <DropdownMenuGroup aria-label={t`Show`}>
+ <DropdownMenuLabel>
+ <Trans>Show</Trans>
+ </DropdownMenuLabel>
+ <DropdownMenuCheckboxItem
+ checked={showHiddenFiles}
+ onCheckedChange={(checked) =>
+ patchSidebarVisibility({ showHiddenFiles: checked })
+ }
+ disabled={projectLocalBinding === null}
+ data-testid="tree-options-show-hidden-files"
+ >
+ <Trans>Hidden files</Trans>
+ </DropdownMenuCheckboxItem>
+ <DropdownMenuCheckboxItem
+ checked={showOkFolders}
+ onCheckedChange={(checked) =>
+ patchSidebarVisibility({ showOkFolders: checked })
+ }
+ disabled={projectLocalBinding === null}
+ data-testid="tree-options-show-ok-folders"
+ >
+ <Trans>.ok folders</Trans>
+ </DropdownMenuCheckboxItem>
+ <DropdownMenuCheckboxItem
+ checked={showOnlyMarkdownFiles}
+ onCheckedChange={(checked) =>
+ patchSidebarVisibility({ showOnlyMarkdownFiles: checked })
+ }
+ disabled={projectLocalBinding === null}
+ data-testid="tree-options-show-only-markdown-files"
+ >
+ <Trans>Only markdown files</Trans>
+ </DropdownMenuCheckboxItem>
+ <DropdownMenuCheckboxItem
+ checked={showSkillsSection}
+ onCheckedChange={(checked) =>
+ patchSidebarVisibility({ showSkillsSection: checked })
+ }
+ disabled={projectLocalBinding === null}
+ data-testid="tree-options-show-skills"
+ >
+ <Trans>Skills</Trans>
+ </DropdownMenuCheckboxItem>
+ </DropdownMenuGroup>
+ </DropdownMenuContent>
+ </DropdownMenu>
<ToolbarButton
icon={SquarePen}
label={t`New file`}
@@ -978,7 +1073,10 @@ function FileSidebarInner({ onOpenSearch }: FileSidebarProps) {
</CollapsibleContent>
</SidebarGroup>
</Collapsible>
- <SkillsSidebarSection />
+ {/* View-preference gate on the section render only: with the
+ section hidden, skill docs stay reachable (links, search,
+ direct routes) and open with full editor chrome. */}
+ {showSkillsSection ? <SkillsSidebarSection /> : null}
{/* Deselect-to-root hit target. With the tree sized flush to its
rows there's no empty space inside it to click, so the leftover
sidebar space below the sections takes over: clicking it clears
@@ -1034,7 +1132,7 @@ function FileSidebarInner({ onOpenSearch }: FileSidebarProps) {
</ContextMenuTrigger>
<ContextMenuContent className="min-w-52">
{/*
- * Empty-space menu — 11 items, 4 sections.
+ * Empty-space menu — 4 sections.
*
* Section 1: Creation (always visible). New file / from
* template / folder dispatch the project-root creation flow
@@ -1046,10 +1144,13 @@ function FileSidebarInner({ onOpenSearch }: FileSidebarProps) {
* is cross-host (filtered via useInstalledAgents); Copy full path
* is cross-host.
*
- * Section 3: Toggle. Two ContextMenuCheckboxItems mirror the View
- * menu. Read state from the merged config; write through the
- * project-local CRDT binding so the View menu and any other surface
- * stay in sync via the existing subscribe path.
+ * Section 3: Visibility toggles. The same checkboxes as the
+ * toolbar popover's Show group, in the same order, but with
+ * full-form labels ("Show hidden files") because this flat menu has
+ * no group label to carry the "Show". Read state from the merged
+ * config; write through the project-local CRDT binding so the
+ * popover, the View menu, and any other surface stay in sync via
+ * the existing subscribe path.
*
* Section 4: Tree state. Expand/Collapse all tree-scoped with
* smart-hide — both items hide when there are no folders, and each
@@ -1140,14 +1241,40 @@ function FileSidebarInner({ onOpenSearch }: FileSidebarProps) {
<ContextMenuSeparator />
<ContextMenuCheckboxItem
checked={showHiddenFiles}
- onCheckedChange={handleEmptySpaceShowHiddenFilesToggle}
+ onCheckedChange={(checked) => patchSidebarVisibility({ showHiddenFiles: checked })}
disabled={projectLocalBinding === null}
data-testid="empty-space-menu-show-hidden-files"
>
<Trans>Show hidden files</Trans>
</ContextMenuCheckboxItem>
- {showEmptySpaceTreeStateSection ? <ContextMenuSeparator /> : null}
- {showEmptySpaceExpandAll ? (
+ <ContextMenuCheckboxItem
+ checked={showOkFolders}
+ onCheckedChange={(checked) => patchSidebarVisibility({ showOkFolders: checked })}
+ disabled={projectLocalBinding === null}
+ data-testid="empty-space-menu-show-ok-folders"
+ >
+ <Trans>Show .ok folders</Trans>
+ </ContextMenuCheckboxItem>
+ <ContextMenuCheckboxItem
+ checked={showOnlyMarkdownFiles}
+ onCheckedChange={(checked) =>
+ patchSidebarVisibility({ showOnlyMarkdownFiles: checked })
+ }
+ disabled={projectLocalBinding === null}
+ data-testid="empty-space-menu-show-only-markdown-files"
+ >
+ <Trans>Show only markdown files</Trans>
+ </ContextMenuCheckboxItem>
+ <ContextMenuCheckboxItem
+ checked={showSkillsSection}
+ onCheckedChange={(checked) => patchSidebarVisibility({ showSkillsSection: checked })}
+ disabled={projectLocalBinding === null}
+ data-testid="empty-space-menu-show-skills-section"
+ >
+ <Trans>Show skills section</Trans>
+ </ContextMenuCheckboxItem>
+ {showTreeStateSection ? <ContextMenuSeparator /> : null}
+ {showExpandAll ? (
<ContextMenuItem
onSelect={handleEmptySpaceExpandAll}
data-testid="empty-space-menu-expand-all"
@@ -1156,7 +1283,7 @@ function FileSidebarInner({ onOpenSearch }: FileSidebarProps) {
<Trans>Expand all</Trans>
</ContextMenuItem>
) : null}
- {showEmptySpaceCollapseAll ? (
+ {showCollapseAll ? (
<ContextMenuItem
onSelect={handleEmptySpaceCollapseAll}
data-testid="empty-space-menu-collapse-all"
diff --git a/packages/app/src/components/FileTree.duplicate.dom.test.tsx b/packages/app/src/components/FileTree.duplicate.dom.test.tsx
index b9a8296ed..442c92e0b 100644
--- a/packages/app/src/components/FileTree.duplicate.dom.test.tsx
+++ b/packages/app/src/components/FileTree.duplicate.dom.test.tsx
@@ -239,6 +239,10 @@ function duplicateCalls() {
return fetchCalls.filter((call) => call.url === '/api/duplicate-path');
}
+function deletePathCalls() {
+ return fetchCalls.filter((call) => call.url === '/api/delete-path');
+}
+
function expectMenuOrder(labels: readonly RegExp[]) {
const items = Array.from(
document.querySelectorAll<HTMLElement>('[role="menuitem"], [role="menuitemcheckbox"]'),
@@ -266,6 +270,9 @@ function makeFetchMock() {
symlinkResolved: true,
});
}
+ if (url === '/api/delete-path') {
+ return jsonResponse({ deletedDocNames: [] });
+ }
if (url === '/api/duplicate-path') {
if (duplicateGate) await duplicateGate;
if (duplicateFetchError) throw duplicateFetchError;
@@ -442,7 +449,9 @@ mock.module('@pierre/trees/react', () => ({
}));
const { FileTree } = await import('./FileTree');
-const { emitFileTreeMenuActionDuplicate } = await import('@/lib/file-tree-menu-action-events');
+const { emitFileTreeMenuActionDelete, emitFileTreeMenuActionDuplicate } = await import(
+ '@/lib/file-tree-menu-action-events'
+);
function renderFileTree() {
return render(<FileTree />);
@@ -593,16 +602,12 @@ describe('FileTree duplicate action runtime behavior', () => {
expect(closeMenuMock).toHaveBeenCalled();
});
- test('folder context menu exposes runtime order, subtree actions, visibility toggle, and folder hide', async () => {
+ test('folder context menu exposes runtime order, subtree actions, and folder hide', async () => {
menuItem = { kind: 'directory', path: 'notes/' };
okignoreBindingMock = {
current: () => '',
patch: mock(() => ({ ok: true })),
};
- projectLocalBindingMock = { patch: mock(() => ({ ok: true })) };
- mergedConfigMock = {
- appearance: { sidebar: { showHiddenFiles: true } },
- };
const user = userEvent.setup();
renderFileTree();
@@ -613,7 +618,6 @@ describe('FileTree duplicate action runtime behavior', () => {
/New folder/,
/Open with AI/,
/Copy path/,
- /Show hidden files/,
/Expand all/,
/Duplicate/,
/Rename/,
@@ -621,13 +625,10 @@ describe('FileTree duplicate action runtime behavior', () => {
/Delete/,
]);
- const showHidden = screen.getByTestId('file-tree-menu-show-hidden-files');
- expect(showHidden.getAttribute('aria-checked')).toBe('true');
-
- await user.click(showHidden);
- expect(projectLocalBindingMock.patch).toHaveBeenCalledWith({
- appearance: { sidebar: { showHiddenFiles: false } },
- });
+ // Global visibility toggles live on the sidebar surfaces (toolbar
+ // popover, empty-space menu, native View menu) — the per-row menu
+ // carries none.
+ expect(screen.queryByTestId('file-tree-menu-show-hidden-files')).toBeNull();
await user.click(screen.getByRole('menuitem', { name: /expand all/i }));
expect(model.getItem('notes/')?.isExpanded()).toBe(true);
@@ -655,6 +656,49 @@ describe('FileTree duplicate action runtime behavior', () => {
expect(screen.getByRole('menuitem', { name: /copy path/i })).toBeTruthy();
});
+ test('.ok file row menu keeps read-only actions and drops every mutate action', async () => {
+ menuItem = { kind: 'file', path: '.ok/templates/greeting.md' };
+ okignoreBindingMock = {
+ current: () => '',
+ patch: mock(() => ({ ok: true })),
+ };
+ renderFileTree();
+
+ await waitFor(() => {
+ expect(screen.getByRole('menuitem', { name: /copy path/i })).toBeTruthy();
+ });
+ // Read-only posture: OK-managed rows expose no rename/delete/duplicate/
+ // hide — the canonical editors own template/skill mutation, and raw `.ok`
+ // state is inspect-only.
+ expect(screen.queryByRole('menuitem', { name: /duplicate/i })).toBeNull();
+ expect(screen.queryByRole('menuitem', { name: /rename/i })).toBeNull();
+ expect(screen.queryByRole('menuitem', { name: /^delete/i })).toBeNull();
+ expect(screen.queryByTestId('file-tree-menu-hide')).toBeNull();
+ });
+
+ test('.ok folder row menu drops create and mutate sections, keeps path/tree actions', async () => {
+ menuItem = { kind: 'directory', path: '.ok/' };
+ okignoreBindingMock = {
+ current: () => '',
+ patch: mock(() => ({ ok: true })),
+ };
+ renderFileTree();
+
+ await waitFor(() => {
+ expect(screen.getByRole('menuitem', { name: /copy path/i })).toBeTruthy();
+ });
+ // Creating inside `.ok` is server-refused — offering New file/folder here
+ // would be a broken affordance, so the create section hides with the
+ // mutate section.
+ expect(screen.queryByRole('menuitem', { name: /new file/i })).toBeNull();
+ expect(screen.queryByRole('menuitem', { name: /new folder/i })).toBeNull();
+ expect(screen.queryByRole('menuitem', { name: /new from template/i })).toBeNull();
+ expect(screen.queryByRole('menuitem', { name: /duplicate/i })).toBeNull();
+ expect(screen.queryByRole('menuitem', { name: /rename/i })).toBeNull();
+ expect(screen.queryByRole('menuitem', { name: /^delete/i })).toBeNull();
+ expect(screen.queryByTestId('file-tree-menu-hide')).toBeNull();
+ });
+
test('duplicate response is schema-validated before UI reconciliation', async () => {
duplicateResponse = {
kind: 'file',
@@ -896,6 +940,45 @@ describe('FileTree duplicate action runtime behavior', () => {
expect(duplicateCalls()).toHaveLength(0);
});
+ test('Cmd/Ctrl+D ignores revealed .ok rows', async () => {
+ renderFileTree();
+ await screen.findByRole('menuitem', { name: /duplicate/i });
+ fetchCalls = [];
+
+ model.focusedPath = '.ok/templates/greeting.md';
+ model.selectedPaths = ['.ok/templates/greeting.md'];
+ screen.getByTestId('tree-focus-target').focus();
+ fireEvent.keyDown(document, { key: 'd', ctrlKey: true });
+
+ await new Promise((resolve) => setTimeout(resolve, 0));
+ expect(duplicateCalls()).toHaveLength(0);
+ });
+
+ test('Cmd/Ctrl+C on a revealed .ok row keeps native copy and enqueues no paste target', async () => {
+ renderFileTree();
+ await screen.findByRole('menuitem', { name: /duplicate/i });
+ fetchCalls = [];
+
+ model.focusedPath = 'notes/.ok/';
+ model.selectedPaths = ['notes/.ok/'];
+ screen.getByTestId('tree-focus-target').focus();
+ const copyEvent = new KeyboardEvent('keydown', {
+ key: 'c',
+ ctrlKey: true,
+ bubbles: true,
+ cancelable: true,
+ });
+ document.dispatchEvent(copyEvent);
+
+ model.focusedPath = null;
+ model.selectedPaths = ['notes/source.mdx'];
+ fireEvent.keyDown(document, { key: 'v', ctrlKey: true });
+
+ await new Promise((resolve) => setTimeout(resolve, 0));
+ expect(copyEvent.defaultPrevented).toBe(false);
+ expect(duplicateCalls()).toHaveLength(0);
+ });
+
test('Cmd+Backspace opens delete confirmation for the selected tree item', async () => {
renderFileTree();
await screen.findByRole('menuitem', { name: /duplicate/i });
@@ -954,6 +1037,34 @@ describe('FileTree duplicate action runtime behavior', () => {
);
});
+ test('Delete on a revealed .ok row opens no delete confirmation', async () => {
+ renderFileTree();
+ await screen.findByRole('menuitem', { name: /duplicate/i });
+
+ model.focusedPath = '.ok/';
+ model.selectedPaths = [];
+ screen.getByTestId('tree-focus-target').focus();
+ fireEvent.keyDown(document, { key: 'Delete' });
+
+ await new Promise((resolve) => setTimeout(resolve, 0));
+ expect(screen.queryByTestId('delete-confirmation-dialog')).toBeNull();
+ expect(deleteConfirmationProps).toBeNull();
+ });
+
+ test('Delete on a mixed selection confirms only the non-.ok targets', async () => {
+ renderFileTree();
+ await screen.findByRole('menuitem', { name: /duplicate/i });
+
+ model.focusedPath = null;
+ model.selectedPaths = ['notes/source.mdx', 'notes/.ok/'];
+ screen.getByTestId('tree-focus-target').focus();
+ fireEvent.keyDown(document, { key: 'Delete' });
+
+ await screen.findByTestId('delete-confirmation-dialog');
+ expect(deleteConfirmationProps?.itemName).toBe('source.mdx');
+ expect(deleteConfirmationProps?.customTitle).toBeUndefined();
+ });
+
test('Delete opens one confirmation for multi-selected targets with nested paths deduped', async () => {
renderFileTree();
await screen.findByRole('menuitem', { name: /duplicate/i });
@@ -1027,4 +1138,37 @@ describe('FileTree duplicate action runtime behavior', () => {
}),
);
});
+
+ test('delete event bus drops .ok targets before any delete side effect', async () => {
+ renderFileTree();
+ await screen.findByRole('menuitem', { name: /duplicate/i });
+ fetchCalls = [];
+
+ act(() => {
+ emitFileTreeMenuActionDelete({
+ kind: 'folder',
+ target: '.ok',
+ folderPath: '.ok',
+ } satisfies ResolvedNavigationTarget);
+ });
+
+ await new Promise((resolve) => setTimeout(resolve, 0));
+ expect(deletePathCalls()).toHaveLength(0);
+
+ // Same spine stays live for deletable targets — proves the drop above is
+ // the .ok gate, not a dead subscription.
+ act(() => {
+ emitFileTreeMenuActionDelete({
+ kind: 'folder',
+ target: 'notes',
+ folderPath: 'notes',
+ } satisfies ResolvedNavigationTarget);
+ });
+
+ await waitFor(() => expect(deletePathCalls()).toHaveLength(1));
+ expect(JSON.parse(String(deletePathCalls()[0]?.init?.body))).toEqual({
+ kind: 'folder',
+ path: 'notes',
+ });
+ });
});
diff --git a/packages/app/src/components/FileTree.selection-mirror.dom.test.tsx b/packages/app/src/components/FileTree.selection-mirror.dom.test.tsx
index cd940d5f4..f5bd0b2be 100644
--- a/packages/app/src/components/FileTree.selection-mirror.dom.test.tsx
+++ b/packages/app/src/components/FileTree.selection-mirror.dom.test.tsx
@@ -93,6 +93,13 @@ function Harness({ initialPath, model }: { initialPath: string | null; model: St
<button type="button" data-testid="set-null" onClick={() => setActiveTreePath(null)}>
none
</button>
+ <button
+ type="button"
+ data-testid="set-absent"
+ onClick={() => setActiveTreePath('.hidden/absent.md')}
+ >
+ absent
+ </button>
<span data-testid="selected">{model.getSelectedPaths().join(',')}</span>
</>
);
@@ -141,6 +148,91 @@ describe('FileTree selection-mirror (Tier-3 mount)', () => {
expect(model.getSelectedPaths()).toEqual([]);
});
+ test('navigating to a doc with no visible tree row deselects the previous row', async () => {
+ // Quiet-tree contract: when the active doc's row is absent from the model
+ // (filtered out, or not fetched yet), the previously active row must not
+ // keep a stale highlight while the editor shows a different doc.
+ const model = makeStubModel(['A.md', 'B.md', 'C.md']);
+ render(<Harness initialPath="A.md" model={model} />);
+
+ expect(model.getSelectedPaths()).toEqual(['A.md']);
+
+ const user = userEvent.setup();
+ await user.click(screen.getByTestId('set-absent'));
+
+ expect(model.getSelectedPaths()).toEqual([]);
+ });
+
+ test('absent active row still expands visible ancestors while clearing stale selection', () => {
+ // A partially-hidden path: `parent/` has a visible row, the active child
+ // does not. The mirror must expand the visible ancestor (ancestor
+ // priority) AND clear the stale selection left on another row — the
+ // quiet-tree deselect must not short-circuit the expansion loop.
+ let parentExpanded = false;
+ let parentExpandCallCount = 0;
+ let otherSelected = true;
+ const items = new Map<string, StubItem>([
+ [
+ 'parent/',
+ {
+ getPath: () => 'parent/',
+ isSelected: () => false,
+ select: () => {},
+ deselect: () => {},
+ isExpanded: () => parentExpanded,
+ expand: () => {
+ parentExpanded = true;
+ parentExpandCallCount += 1;
+ },
+ focus: () => {},
+ isDirectory: () => true,
+ getFocusCount: () => 0,
+ },
+ ],
+ [
+ 'other.md',
+ {
+ getPath: () => 'other.md',
+ isSelected: () => otherSelected,
+ select: () => {
+ otherSelected = true;
+ },
+ deselect: () => {
+ otherSelected = false;
+ },
+ isExpanded: () => false,
+ expand: () => {},
+ focus: () => {},
+ isDirectory: () => false,
+ getFocusCount: () => 0,
+ },
+ ],
+ ]);
+ const model: StubModel = {
+ getItem: (path: string) => items.get(path) ?? null,
+ getSelectedPaths: () =>
+ Array.from(items.entries())
+ .filter(([, it]) => it.isSelected())
+ .map(([p]) => p),
+ };
+ function PartiallyHiddenHarness() {
+ const suppressSelectionRef = useRef(false);
+ useSelectionMirror(
+ // biome-ignore lint/suspicious/noExplicitAny: Tier-3 stub for the test budget; production callers always pass real Pierre models.
+ model as any,
+ 'parent/.hidden-child.md',
+ 'parent/',
+ suppressSelectionRef,
+ );
+ return null;
+ }
+ render(<PartiallyHiddenHarness />);
+
+ expect(parentExpandCallCount).toBe(1);
+ expect(parentExpanded).toBe(true);
+ expect(model.getSelectedPaths()).toEqual([]);
+ });
+
test('non-empty activeAncestorTreePathsSignature expands every collapsed ancestor', () => {
// Builds a stub model whose `parent/` ancestor reports expanded=false +
// a working expand() — without this test the ancestor-expansion loop
diff --git a/packages/app/src/components/FileTree.showall-lazy.dom.test.tsx b/packages/app/src/components/FileTree.showall-lazy.dom.test.tsx
index 7771fdbb3..467f9f33b 100644
--- a/packages/app/src/components/FileTree.showall-lazy.dom.test.tsx
+++ b/packages/app/src/components/FileTree.showall-lazy.dom.test.tsx
@@ -37,7 +37,8 @@ const SHOW_ALL_DEPTH1_URL = '/api/documents?showAll=true&dir=&depth=1';
// --- mutable per-test state ---
// The sidebar always issues the lazy depth-1 disk-walk listing; these tests
-// exercise that default path. Config only carries `showHiddenFiles` now.
+// exercise that default path. Config carries the sidebar visibility toggles
+// (`showHiddenFiles`, `showOnlyMarkdownFiles`).
let mergedConfig: unknown = { appearance: { sidebar: {} } };
// Factory for the depth-1 response so the NDJSON test can stream instead of
// returning buffered JSON.
@@ -70,6 +71,9 @@ function docEntry(docName: string) {
};
}
+// Non-markdown leaf as the showAll disk walk ships it: every non-md file is
+// `kind:'asset'` with an empty `referencedBy` (the walk never computes real
+// references).
function assetEntry(path: string) {
return {
kind: 'asset',
@@ -227,7 +231,7 @@ mock.module('@/editor/DocumentContext', () => ({
}),
}));
mock.module('@/components/PageListContext', () => ({
- usePageList: () => ({ addPage: mock(() => {}) }),
+ usePageList: () => ({ addPage: mock(() => {}), pages: new Set<string>() }),
}));
mock.module('./ui/sidebar', () => ({
useSidebar: () => ({ notifySidebarFileSelected: mock(() => {}) }),
@@ -398,11 +402,11 @@ describe('FileTree showAll lazy root seed', () => {
});
test('Show hidden files alone gates dot-segment entries in the disk-walk listing', async () => {
- // bypassClientDotDrop is now keyed solely on showHiddenFiles (the Show all
- // files toggle is gone), so this toggle alone decides whether dot-segment
- // entries the disk walk ships are shown. OFF: a root-level dotfile is
- // dropped client-side while its non-dot sibling stays; flipping ON
- // re-fetches and reveals it.
+ // The client dot-segment drop is keyed solely on showHiddenFiles (the
+ // Show all files toggle is gone), so this toggle alone decides whether
+ // dot-segment entries the disk walk ships are shown. OFF: a root-level
+ // dotfile is dropped client-side while its non-dot sibling stays;
+ // flipping ON re-fetches and reveals it.
mergedConfig = { appearance: { sidebar: { showHiddenFiles: false } } };
showAllResponseFactory = () =>
jsonResponse({
@@ -1245,3 +1249,417 @@ describe('FileTree relaunch-aware reconnect (desktop auto-update)', () => {
expect(screen.queryByRole('alert')).toBeNull();
});
});
+
+describe('FileTree only-markdown visibility', () => {
+ let consoleWarnSpy: ReturnType<typeof spyOn>;
+
+ beforeEach(() => {
+ mergedConfig = { appearance: { sidebar: {} } };
+ 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('non-markdown leaves render with the toggle off — the default stays byte-identical', async () => {
+ showAllResponseFactory = () =>
+ jsonResponse({
+ documents: [docEntry('README'), assetEntry('data.csv'), folderEntry('team', true)],
+ truncated: false,
+ });
+ render(<FileTree />);
+
+ await waitFor(() => expect(model.items.has('data.csv')).toBe(true));
+ expect(model.items.has('README.md')).toBe(true);
+ expect(model.items.has('team/')).toBe(true);
+ });
+
+ test('only-markdown ON hides non-markdown leaves; documents and folders (even markdown-empty ones) stay', async () => {
+ mergedConfig = { appearance: { sidebar: { showOnlyMarkdownFiles: true } } };
+ showAllResponseFactory = () =>
+ jsonResponse({
+ documents: [
+ docEntry('README'),
+ assetEntry('data.csv'),
+ folderEntry('team', true),
+ folderEntry('assets-only', true),
+ ],
+ truncated: false,
+ });
+ render(<FileTree />);
+
+ await waitFor(() => expect(model.items.has('README.md')).toBe(true));
+ // Folders are exempt from the filter — a folder with no markdown anywhere
+ // still renders (it expands to empty rather than disappearing).
+ expect(model.items.has('team/')).toBe(true);
+ expect(model.items.has('assets-only/')).toBe(true);
+ expect(model.items.has('data.csv')).toBe(false);
+ });
+
+ test('flipping only-markdown refetches through the scheduler and preserves folder expansion', async () => {
+ showAllResponseFactory = () =>
+ jsonResponse({
+ documents: [docEntry('README'), assetEntry('data.csv'), folderEntry('team', true)],
+ truncated: false,
+ });
+ responseByUrl.set(lazyDirUrl('team'), () =>
+ jsonResponse({
+ documents: [docEntry('team/notes'), assetEntry('team/data.json')],
+ truncated: false,
+ }),
+ );
+ const view = render(<FileTree />);
+ await waitFor(() => expect(model.items.has('data.csv')).toBe(true));
+ model.getItem('team/')?.expand();
+ await waitFor(() => expect(model.items.has('team/data.json')).toBe(true));
+ const rootFetchesBefore = fetchUrls.filter((url) => url === SHOW_ALL_DEPTH1_URL).length;
+
+ mergedConfig = { appearance: { sidebar: { showOnlyMarkdownFiles: true } } };
+ view.rerender(<FileTree />);
+
+ // The flip re-fetches (root splice + expanded-folder revalidation) and the
+ // re-applied filter drops every non-markdown leaf, including ones in the
+ // already-loaded child level.
+ await waitFor(() => expect(model.items.has('data.csv')).toBe(false));
+ await waitFor(() => expect(model.items.has('team/data.json')).toBe(false));
+ expect(model.items.has('README.md')).toBe(true);
+ expect(model.items.has('team/notes.md')).toBe(true);
+ // Expansion state carries across the flip — no reset-to-collapsed.
+ expect(model.getItem('team/')?.isExpanded()).toBe(true);
+ expect(fetchUrls.filter((url) => url === SHOW_ALL_DEPTH1_URL)).toHaveLength(
+ rootFetchesBefore + 1,
+ );
+
+ // Flipping back off restores the default rendering — the toggle is pure
+ // view state, nothing was lost.
+ mergedConfig = { appearance: { sidebar: { showOnlyMarkdownFiles: false } } };
+ view.rerender(<FileTree />);
+ await waitFor(() => expect(model.items.has('data.csv')).toBe(true));
+ await waitFor(() => expect(model.items.has('team/data.json')).toBe(true));
+ expect(model.getItem('team/')?.isExpanded()).toBe(true);
+ });
+
+ test('only-markdown filters the streamed NDJSON seed — batches and the completion splice alike', async () => {
+ mergedConfig = { appearance: { sidebar: { showOnlyMarkdownFiles: true } } };
+ const lines = [
+ JSON.stringify(assetEntry('data.csv')),
+ JSON.stringify(docEntry('README')),
+ JSON.stringify(folderEntry('team', true)),
+ JSON.stringify({ type: 'complete', truncated: false, count: 3 }),
+ ].join('\n');
+ showAllResponseFactory = () =>
+ new Response(`${lines}\n`, {
+ status: 200,
+ headers: { 'content-type': 'application/x-ndjson' },
+ });
+ render(<FileTree />);
+
+ await waitFor(() => expect([...model.items.keys()].sort()).toEqual(['README.md', 'team/']));
+ });
+
+ test('only-markdown filters lazy folder children; a markdown-empty folder expands to empty and stays open', async () => {
+ mergedConfig = { appearance: { sidebar: { showOnlyMarkdownFiles: true } } };
+ showAllResponseFactory = () =>
+ jsonResponse({
+ documents: [folderEntry('team', true), folderEntry('assets-only', true)],
+ truncated: false,
+ });
+ responseByUrl.set(lazyDirUrl('team'), () =>
+ jsonResponse({
+ documents: [docEntry('team/notes'), assetEntry('team/data.json')],
+ truncated: false,
+ }),
+ );
+ responseByUrl.set(lazyDirUrl('assets-only'), () =>
+ jsonResponse({ documents: [assetEntry('assets-only/pic.png')], truncated: false }),
+ );
+ render(<FileTree />);
+ await waitFor(() => expect(model.items.size).toBe(2));
+
+ model.getItem('team/')?.expand();
+ await waitFor(() => expect(model.items.has('team/notes.md')).toBe(true));
+ expect(model.items.has('team/data.json')).toBe(false);
+
+ model.getItem('assets-only/')?.expand();
+ await waitFor(() => expect(fetchUrls).toContain(lazyDirUrl('assets-only')));
+ await new Promise((resolve) => setTimeout(resolve, 0));
+ // The level was fetched and filtered to zero: the folder renders no
+ // children but keeps its expanded state — it is not dropped or collapsed.
+ expect(model.items.has('assets-only/pic.png')).toBe(false);
+ expect(model.getItem('assets-only/')?.isExpanded()).toBe(true);
+ });
+
+ test('hidden-files and only-markdown compose per axis: a dot-path doc needs H on and passes M', async () => {
+ mergedConfig = {
+ appearance: { sidebar: { showHiddenFiles: false, showOnlyMarkdownFiles: true } },
+ };
+ showAllResponseFactory = () =>
+ jsonResponse({
+ documents: [docEntry('.hidden-note'), assetEntry('.hidden-data.csv'), docEntry('README')],
+ truncated: false,
+ });
+ const view = render(<FileTree />);
+
+ // Hidden files off: both dot-path entries drop regardless of kind.
+ await waitFor(() => expect(model.items.has('README.md')).toBe(true));
+ expect(model.items.has('.hidden-note.md')).toBe(false);
+ expect(model.items.has('.hidden-data.csv')).toBe(false);
+
+ mergedConfig = {
+ appearance: { sidebar: { showHiddenFiles: true, showOnlyMarkdownFiles: true } },
+ };
+ view.rerender(<FileTree />);
+
+ // Both on: the dot-path markdown doc passes both axes; the dot-path csv
+ // clears the hidden axis but still fails only-markdown (AND composition).
+ await waitFor(() => expect(model.items.has('.hidden-note.md')).toBe(true));
+ expect(model.items.has('README.md')).toBe(true);
+ expect(model.items.has('.hidden-data.csv')).toBe(false);
+ });
+});
+
+describe('FileTree filtered-to-zero empty state', () => {
+ let consoleWarnSpy: ReturnType<typeof spyOn>;
+
+ beforeEach(() => {
+ mergedConfig = { appearance: { sidebar: {} } };
+ 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('only-markdown hiding every row of a non-empty project shows the reset explainer', async () => {
+ mergedConfig = { appearance: { sidebar: { showOnlyMarkdownFiles: true } } };
+ showAllResponseFactory = () =>
+ jsonResponse({
+ documents: [assetEntry('data.csv'), assetEntry('logo.png')],
+ truncated: false,
+ });
+ render(<FileTree />);
+
+ await waitFor(() => expect(screen.queryByTestId('file-tree-filtered-to-zero')).toBeTruthy());
+ expect(screen.queryByTestId('reset-view-filters')).toBeTruthy();
+ expect(screen.queryByText('No files yet.')).toBeNull();
+ });
+
+ test('a truly empty project keeps the existing empty state even while only-markdown is on', async () => {
+ mergedConfig = { appearance: { sidebar: { showOnlyMarkdownFiles: true } } };
+ showAllResponseFactory = () => jsonResponse({ documents: [], truncated: false });
+ render(<FileTree />);
+
+ await waitFor(() => expect(screen.queryByText('No files yet.')).toBeTruthy());
+ expect(screen.queryByTestId('file-tree-filtered-to-zero')).toBeNull();
+ });
+
+ test('a dot-only project at defaults keeps the pre-feature empty state', async () => {
+ showAllResponseFactory = () =>
+ jsonResponse({
+ documents: [folderEntry('.scratch', true), docEntry('.draft')],
+ truncated: false,
+ });
+ render(<FileTree />);
+
+ await waitFor(() => expect(screen.queryByText('No files yet.')).toBeTruthy());
+ expect(screen.queryByTestId('file-tree-filtered-to-zero')).toBeNull();
+ });
+
+ test('the streamed NDJSON listing classifies filtered-to-zero at completion', async () => {
+ mergedConfig = { appearance: { sidebar: { showOnlyMarkdownFiles: true } } };
+ const lines = [
+ JSON.stringify(assetEntry('data.csv')),
+ JSON.stringify(assetEntry('logo.png')),
+ JSON.stringify({ type: 'complete', truncated: false, count: 2 }),
+ ].join('\n');
+ showAllResponseFactory = () =>
+ new Response(`${lines}\n`, {
+ status: 200,
+ headers: { 'content-type': 'application/x-ndjson' },
+ });
+ render(<FileTree />);
+
+ await waitFor(() => expect(screen.queryByTestId('file-tree-filtered-to-zero')).toBeTruthy());
+ expect(screen.queryByText('No files yet.')).toBeNull();
+ });
+});
+
+describe('FileTree show-ok-folders visibility', () => {
+ let consoleWarnSpy: ReturnType<typeof spyOn>;
+
+ const SHOW_OK_DEPTH1_URL = '/api/documents?showAll=true&showOk=true&dir=&depth=1';
+ const lazyOkDirUrl = (dir: string) =>
+ `/api/documents?showAll=true&showOk=true&dir=${encodeURIComponent(dir)}&depth=1`;
+
+ beforeEach(() => {
+ mergedConfig = { appearance: { sidebar: {} } };
+ 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-ok ON requests the listing with showOk=true and renders .ok rows', async () => {
+ mergedConfig = { appearance: { sidebar: { showOkFolders: true } } };
+ responseByUrl.set(SHOW_OK_DEPTH1_URL, () =>
+ jsonResponse({
+ documents: [docEntry('README'), folderEntry('.ok', true)],
+ truncated: false,
+ }),
+ );
+ render(<FileTree />);
+
+ await waitFor(() => expect(model.items.has('.ok/')).toBe(true));
+ expect(model.items.has('README.md')).toBe(true);
+ // The reveal is request-scoped: the plain showAll listing is never issued
+ // while the axis is on.
+ expect(fetchUrls).toContain(SHOW_OK_DEPTH1_URL);
+ expect(fetchUrls).not.toContain(SHOW_ALL_DEPTH1_URL);
+ });
+
+ test('the default listing never passes showOk — off stays byte-identical to today', async () => {
+ showAllResponseFactory = () =>
+ jsonResponse({
+ documents: [docEntry('README'), folderEntry('team', true)],
+ truncated: false,
+ });
+ render(<FileTree />);
+
+ await waitFor(() => expect(model.items.has('README.md')).toBe(true));
+ expect(fetchUrls.some((url) => url.includes('showOk'))).toBe(false);
+ });
+
+ test('hidden-files on does not reveal .ok rows and does not request showOk', async () => {
+ mergedConfig = { appearance: { sidebar: { showHiddenFiles: true } } };
+ // The default listing already ships the bare `.ok` folder row (skills
+ // carve-out); with only the H axis on the client must keep dropping it.
+ showAllResponseFactory = () =>
+ jsonResponse({
+ documents: [docEntry('README'), folderEntry('.scratch', true), folderEntry('.ok', true)],
+ truncated: false,
+ });
+ render(<FileTree />);
+
+ await waitFor(() => expect(model.items.has('.scratch/')).toBe(true));
+ expect(model.items.has('.ok/')).toBe(false);
+ expect(fetchUrls.some((url) => url.includes('showOk'))).toBe(false);
+ });
+
+ test('expanding a revealed .ok folder lazy-fetches its children with showOk=true', async () => {
+ mergedConfig = { appearance: { sidebar: { showOkFolders: true } } };
+ responseByUrl.set(SHOW_OK_DEPTH1_URL, () =>
+ jsonResponse({
+ documents: [docEntry('README'), folderEntry('.ok', true)],
+ truncated: false,
+ }),
+ );
+ responseByUrl.set(lazyOkDirUrl('.ok'), () =>
+ jsonResponse({
+ documents: [folderEntry('.ok/templates', true), assetEntry('.ok/config.yml')],
+ truncated: false,
+ }),
+ );
+ render(<FileTree />);
+ await waitFor(() => expect(model.items.has('.ok/')).toBe(true));
+
+ model.getItem('.ok/')?.expand();
+
+ await waitFor(() => expect(model.items.has('.ok/templates/')).toBe(true));
+ expect(model.items.has('.ok/config.yml')).toBe(true);
+ expect(fetchUrls).toContain(lazyOkDirUrl('.ok'));
+ });
+
+ test('flipping show-ok refetches through the scheduler and preserves expansion state', async () => {
+ showAllResponseFactory = () =>
+ jsonResponse({
+ documents: [docEntry('README'), folderEntry('team', true)],
+ truncated: false,
+ });
+ responseByUrl.set(lazyDirUrl('team'), () =>
+ jsonResponse({ documents: [docEntry('team/notes')], truncated: false }),
+ );
+ responseByUrl.set(SHOW_OK_DEPTH1_URL, () =>
+ jsonResponse({
+ documents: [docEntry('README'), folderEntry('team', true), folderEntry('.ok', true)],
+ truncated: false,
+ }),
+ );
+ responseByUrl.set(lazyOkDirUrl('team'), () =>
+ jsonResponse({ documents: [docEntry('team/notes')], truncated: false }),
+ );
+ const view = render(<FileTree />);
+ await waitFor(() => expect(model.items.has('team/')).toBe(true));
+ model.getItem('team/')?.expand();
+ await waitFor(() => expect(model.items.has('team/notes.md')).toBe(true));
+
+ mergedConfig = { appearance: { sidebar: { showOkFolders: true } } };
+ view.rerender(<FileTree />);
+
+ await waitFor(() => expect(model.items.has('.ok/')).toBe(true));
+ // Expansion state carries across the flip — no reset-to-collapsed.
+ expect(model.getItem('team/')?.isExpanded()).toBe(true);
+
+ // Flipping back off refetches the plain listing; the root splice prunes
+ // the `.ok` row and the default view is restored.
+ mergedConfig = { appearance: { sidebar: { showOkFolders: false } } };
+ view.rerender(<FileTree />);
+ await waitFor(() => expect(model.items.has('.ok/')).toBe(false));
+ expect(model.items.has('README.md')).toBe(true);
+ expect(model.getItem('team/')?.isExpanded()).toBe(true);
+ });
+
+ test('an expanded .ok folder stays expanded across a refresh cycle', async () => {
+ mergedConfig = { appearance: { sidebar: { showOkFolders: true } } };
+ responseByUrl.set(SHOW_OK_DEPTH1_URL, () =>
+ jsonResponse({
+ documents: [docEntry('README'), folderEntry('.ok', true)],
+ truncated: false,
+ }),
+ );
+ responseByUrl.set(lazyOkDirUrl('.ok'), () =>
+ jsonResponse({ documents: [folderEntry('.ok/templates', true)], truncated: false }),
+ );
+ render(<FileTree />);
+ await waitFor(() => expect(model.items.has('.ok/')).toBe(true));
+ model.getItem('.ok/')?.expand();
+ await waitFor(() => expect(model.items.has('.ok/templates/')).toBe(true));
+
+ // External change signal → root revalidation → model reset. The expanded
+ // `.ok/` folder must survive the reset's expansion-preservation pass.
+ emitDocumentsChanged();
+ await waitFor(() =>
+ expect(fetchUrls.filter((url) => url === SHOW_OK_DEPTH1_URL).length).toBeGreaterThan(1),
+ );
+ await waitFor(() => expect(model.getItem('.ok/')?.isExpanded()).toBe(true));
+ expect(model.items.has('.ok/templates/')).toBe(true);
+ });
+});
diff --git a/packages/app/src/components/FileTree.tsx b/packages/app/src/components/FileTree.tsx
index 0c0a03fbc..2c6f62a57 100644
--- a/packages/app/src/components/FileTree.tsx
+++ b/packages/app/src/components/FileTree.tsx
@@ -1,6 +1,4 @@
import {
- type Config,
- type ConfigBinding,
CreateFolderSuccessSchema,
CreatePageSuccessSchema,
DeletePathSuccessSchema,
@@ -8,7 +6,6 @@ import {
DuplicatePathSuccessSchema,
type HandoffOutcome,
type HandoffTarget,
- humanFormat,
type InstallState,
isDocumentOverOpenByteLimit,
type OkignoreBinding,
@@ -62,6 +59,7 @@ import {
} from 'react';
import { toast } from 'sonner';
import { DeleteConfirmationDialog } from '@/components/DeleteConfirmationDialog';
+import { FileTreeFilteredToZeroNotice } from '@/components/FileTreeFilteredToZeroNotice';
import {
MARKDOWN_FILE_ICON_PATH_D,
MARKDOWN_FILE_ICON_VIEWBOX,
@@ -133,10 +131,12 @@ import {
} from '@/components/file-tree-selection';
import { selectTrashConfirmCopy, trashTargetDisplayName } from '@/components/file-tree-trash-copy';
import {
+ classifyEmptyTree,
type DocumentEntry,
type FileEntry,
type FolderEntry,
filterVisibleEntries,
+ hasOkPathSegment,
isAssetEntry,
isDocumentEntry,
isFolderEntry,
@@ -145,6 +145,7 @@ import {
import { NewItemDialog } from '@/components/NewItemDialog';
import {
largeFileNavigationTarget,
+ okContentNavigationTarget,
type ResolvedNavigationTarget,
} from '@/components/navigation-targets';
import { usePageList } from '@/components/PageListContext';
@@ -164,7 +165,6 @@ import { Button } from '@/components/ui/button';
import { Dialog } from '@/components/ui/dialog';
import {
DropdownMenu,
- DropdownMenuCheckboxItem,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuSeparator,
@@ -566,13 +566,6 @@ interface FileTreeMenuProps {
};
model: PierreFileTreeModel;
okignoreBinding: OkignoreBinding | null;
- /** Project-local config binding for the `Show hidden files` folder-menu
- * toggle. Patched directly here (mirrors the okignore Hide flow); `null`
- * during cold-start disables the toggle item. */
- projectLocalBinding: ConfigBinding | null;
- /** Layered config view, source for the toggle check-state
- * (`appearance.sidebar.showHiddenFiles`). */
- mergedConfig: Config | null;
onStartCreating: (kind: 'file' | 'folder', parentDir: string) => void;
/** Inline create-from-template for the given parent dir + template name —
* same inline-rename fast path as `onStartCreating`, seeded from a template.
@@ -632,7 +625,12 @@ function selectedTreePathsToDeleteTargets(
selectedTreePaths: readonly string[],
documents: readonly FileEntry[],
): FileTreeTarget[] {
- const uniqueDeletablePaths = [...new Set(selectedTreePaths)];
+ // Revealed `.ok` rows are read-only OK-managed state — they never become
+ // delete targets, even when swept into a multi-selection beside deletable
+ // rows (this also keeps the confirm dialog's item count honest).
+ const uniqueDeletablePaths = [...new Set(selectedTreePaths)].filter(
+ (treePath) => !hasOkPathSegment(treePath),
+ );
const selectedFolderPaths = uniqueDeletablePaths.filter((treePath) => treePath.endsWith('/'));
return uniqueDeletablePaths
.filter(
@@ -661,7 +659,11 @@ function resolveDuplicableKeyboardTarget(
assetTreePaths: ReadonlySet<string>,
): FileTreeTarget | null {
const selectedPath = focusedOrFirstSelectedTreePath(model);
- if (!selectedPath || assetTreePaths.has(selectedPath)) return null;
+ // Revealed `.ok` rows are read-only OK-managed state — no keyboard
+ // copy/paste/duplicate, matching their menu's suppressed affordances.
+ if (!selectedPath || assetTreePaths.has(selectedPath) || hasOkPathSegment(selectedPath)) {
+ return null;
+ }
return treePathToTarget(selectedPath, documents);
}
@@ -750,8 +752,6 @@ function FileTreeMenu({
handoff,
model,
okignoreBinding,
- projectLocalBinding,
- mergedConfig,
onStartCreating,
onCreateFromTemplate,
onDuplicate,
@@ -765,11 +765,14 @@ function FileTreeMenu({
const { t } = useLingui();
const target = treeItemToTarget(item, documents);
const isFolder = item.kind === 'directory';
+ // Revealed `.ok` rows are inspect-only: no create/rename/delete/duplicate/
+ // hide affordances (creates into `.ok` are server-refused; mutation of
+ // OK-managed state belongs to its canonical editors). Path/tree actions
+ // (Reveal, Copy path, Expand/Collapse) stay.
+ const isOkRow = hasOkPathSegment(item.path);
const okignoreTarget = target.kind === 'asset' ? null : target;
const canHide = okignoreTarget !== null && okignoreBinding !== null;
const hideLabel = isFolder ? t`Hide folder` : t`Hide this file`;
- const showHiddenFiles = mergedConfig?.appearance?.sidebar?.showHiddenFiles ?? false;
- const canToggleVisibility = projectLocalBinding !== null;
// Drives the smart-hide of the folder menu's "New from template" submenu.
// Only folder rows can fetch (null → idle, no request) and the menu mounts
// on-demand per right-click, so this fetch fires once when the menu opens —
@@ -858,26 +861,6 @@ function FileTreeMenu({
</DropdownMenuItem>
) : null;
- // Project-local visibility toggle for the folder menu's filter section.
- // Mirrors the empty-space surface's binding patch (FileSidebar). The filter
- // EFFECT (client dot-segment bypass) is a separate seam; this only flips the
- // persisted config the filter pipeline reads.
- //
- // Validation failures (e.g. doc YAML parse-error in the project-local
- // config) reject the patch; without surfacing the rejection the checkbox
- // appears to toggle but silently reverts at the next CRDT push.
- const handleShowHiddenFilesToggle = (checked: boolean) => {
- if (projectLocalBinding === null) return;
- const result = projectLocalBinding.patch({
- appearance: { sidebar: { showHiddenFiles: checked } },
- });
- if (!result.ok) {
- console.warn('[FileTree] showHiddenFiles toggle rejected:', humanFormat(result.error));
- toast.error(t`Could not update sidebar settings`, {
- description: humanFormat(result.error),
- });
- }
- };
// Smart-hide for the subtree Expand/Collapse-All items — counts folders
// under the right-clicked folder (root + descendants) using the same
// `folderPath === root || folderPath.startsWith(root)` predicate that
@@ -924,45 +907,52 @@ function FileTreeMenu({
>
{isFolder ? (
<>
- <DropdownMenuItem
- disabled={anyActionBusy}
- onSelect={() => {
- closeForInlineSurface();
- onStartCreating('file', treeDirectoryPathToFolderPath(item.path));
- }}
- >
- <SquarePen aria-hidden="true" />
- <Trans>New file</Trans>
- </DropdownMenuItem>
- {folderHasTemplates ? (
- <DropdownMenuSub>
- <DropdownMenuSubTrigger disabled={anyActionBusy}>
- <FilePlus aria-hidden="true" />
- <Trans>New from template</Trans>
- </DropdownMenuSubTrigger>
- <DropdownMenuSubContent>
- <TemplateMenuRows
- parentDir={treeDirectoryPathToFolderPath(item.path)}
- onSelectTemplate={(templateName) => {
- closeForInlineSurface();
- onCreateFromTemplate(treeDirectoryPathToFolderPath(item.path), templateName);
- }}
- ItemComponent={DropdownMenuItem}
- />
- </DropdownMenuSubContent>
- </DropdownMenuSub>
+ {!isOkRow ? (
+ <>
+ <DropdownMenuItem
+ disabled={anyActionBusy}
+ onSelect={() => {
+ closeForInlineSurface();
+ onStartCreating('file', treeDirectoryPathToFolderPath(item.path));
+ }}
+ >
+ <SquarePen aria-hidden="true" />
+ <Trans>New file</Trans>
+ </DropdownMenuItem>
+ {folderHasTemplates ? (
+ <DropdownMenuSub>
+ <DropdownMenuSubTrigger disabled={anyActionBusy}>
+ <FilePlus aria-hidden="true" />
+ <Trans>New from template</Trans>
+ </DropdownMenuSubTrigger>
+ <DropdownMenuSubContent>
+ <TemplateMenuRows
+ parentDir={treeDirectoryPathToFolderPath(item.path)}
+ onSelectTemplate={(templateName) => {
+ closeForInlineSurface();
+ onCreateFromTemplate(
+ treeDirectoryPathToFolderPath(item.path),
+ templateName,
+ );
+ }}
+ ItemComponent={DropdownMenuItem}
+ />
+ </DropdownMenuSubContent>
+ </DropdownMenuSub>
+ ) : null}
+ <DropdownMenuItem
+ disabled={anyActionBusy}
+ onSelect={() => {
+ closeForInlineSurface();
+ onStartCreating('folder', treeDirectoryPathToFolderPath(item.path));
+ }}
+ >
+ <FolderPlus aria-hidden="true" />
+ <Trans>New folder</Trans>
+ </DropdownMenuItem>
+ <DropdownMenuSeparator />
+ </>
) : null}
- <DropdownMenuItem
- disabled={anyActionBusy}
- onSelect={() => {
- closeForInlineSurface();
- onStartCreating('folder', treeDirectoryPathToFolderPath(item.path));
- }}
- >
- <FolderPlus aria-hidden="true" />
- <Trans>New folder</Trans>
- </DropdownMenuItem>
- <DropdownMenuSeparator />
<RevealInFileManagerMenuItem item={item} workspace={workspace} onClose={close} />
<OpenInAgentContextSubmenu
input={handoffInput}
@@ -1002,17 +992,6 @@ function FileTreeMenu({
</DropdownMenuItem>
</DropdownMenuSubContent>
</DropdownMenuSub>
- <DropdownMenuSeparator />
- {/* Flips the persisted `showHiddenFiles` config; the client-side
- dot-segment filter reads it from a separate seam. */}
- <DropdownMenuCheckboxItem
- checked={showHiddenFiles}
- onCheckedChange={handleShowHiddenFilesToggle}
- disabled={!canToggleVisibility}
- data-testid="file-tree-menu-show-hidden-files"
- >
- <Trans>Show hidden files</Trans>
- </DropdownMenuCheckboxItem>
{/* Subtree-scoped Expand/Collapse, smart-hidden. The divider only
renders when the section is non-empty so a fully-expanded or
fully-collapsed subtree collapses to a single divider before
@@ -1040,67 +1019,72 @@ function FileTreeMenu({
<Trans>Collapse all</Trans>
</DropdownMenuItem>
) : null}
- {/* Destructive section. Rename sits with Hide/Delete here (not at
- the top with creation) so the menu's read order is
- create → act → filter → tree → mutate-or-remove. */}
- <DropdownMenuSeparator />
- <DropdownMenuItem
- disabled={anyActionBusy}
- onSelect={() => {
- if (target.kind === 'asset') return;
- close();
- onDuplicate(target);
- }}
- >
- <CopyPlus aria-hidden="true" />
- <Trans>Duplicate</Trans>
- </DropdownMenuItem>
- <DropdownMenuItem
- disabled={anyActionBusy}
- onSelect={() => {
- closeForInlineSurface();
- model.startRenaming(item.path);
- }}
- >
- <Pencil aria-hidden="true" />
- <Trans>Rename</Trans>
- </DropdownMenuItem>
- <DropdownMenuItem
- data-testid="file-tree-menu-hide"
- disabled={!canHide}
- onSelect={() => {
- if (!okignoreBinding || !okignoreTarget) return;
- close();
- const pattern = buildOkignorePatternFromTarget(okignoreTarget);
- const current = okignoreBinding.current();
- const doc = parseOkignoreDoc(current);
- // appendPattern returns the same doc reference for whitespace-only
- // input AND for duplicates; skip the patch on both no-ops so we
- // don't churn the Y.Text with identical bytes.
- const updated = appendPattern(doc, pattern);
- if (updated === doc) return;
- okignoreBinding.patch(serializeOkignoreDoc(updated));
- const basename = okignoreTarget.path.split('/').pop() || okignoreTarget.path;
- toast.success(t`Hidden folder “${basename}”`, {
- description: t`Manage hidden files in Settings → Ignore patterns.`,
- duration: 5000,
- });
- }}
- >
- <EyeOff aria-hidden="true" />
- {hideLabel}
- </DropdownMenuItem>
- <DropdownMenuItem
- variant="destructive"
- disabled={anyActionBusy}
- onSelect={() => {
- close();
- onDelete(deleteTargets);
- }}
- >
- <Trash2 aria-hidden="true" />
- {deleteLabel}
- </DropdownMenuItem>
+ {/* Destructive section (hidden for inspect-only .ok rows). Rename
+ sits with Hide/Delete here (not at the top with creation) so
+ the menu's read order is create → act → tree →
+ mutate-or-remove. */}
+ {!isOkRow ? (
+ <>
+ <DropdownMenuSeparator />
+ <DropdownMenuItem
+ disabled={anyActionBusy}
+ onSelect={() => {
+ if (target.kind === 'asset') return;
+ close();
+ onDuplicate(target);
+ }}
+ >
+ <CopyPlus aria-hidden="true" />
+ <Trans>Duplicate</Trans>
+ </DropdownMenuItem>
+ <DropdownMenuItem
+ disabled={anyActionBusy}
+ onSelect={() => {
+ closeForInlineSurface();
+ model.startRenaming(item.path);
+ }}
+ >
+ <Pencil aria-hidden="true" />
+ <Trans>Rename</Trans>
+ </DropdownMenuItem>
+ <DropdownMenuItem
+ data-testid="file-tree-menu-hide"
+ disabled={!canHide}
+ onSelect={() => {
+ if (!okignoreBinding || !okignoreTarget) return;
+ close();
+ const pattern = buildOkignorePatternFromTarget(okignoreTarget);
+ const current = okignoreBinding.current();
+ const doc = parseOkignoreDoc(current);
+ // appendPattern returns the same doc reference for whitespace-only
+ // input AND for duplicates; skip the patch on both no-ops so we
+ // don't churn the Y.Text with identical bytes.
+ const updated = appendPattern(doc, pattern);
+ if (updated === doc) return;
+ okignoreBinding.patch(serializeOkignoreDoc(updated));
+ const basename = okignoreTarget.path.split('/').pop() || okignoreTarget.path;
+ toast.success(t`Hidden folder “${basename}”`, {
+ description: t`Manage hidden files in Settings → Ignore patterns.`,
+ duration: 5000,
+ });
+ }}
+ >
+ <EyeOff aria-hidden="true" />
+ {hideLabel}
+ </DropdownMenuItem>
+ <DropdownMenuItem
+ variant="destructive"
+ disabled={anyActionBusy}
+ onSelect={() => {
+ close();
+ onDelete(deleteTargets);
+ }}
+ >
+ <Trash2 aria-hidden="true" />
+ {deleteLabel}
+ </DropdownMenuItem>
+ </>
+ ) : null}
</>
) : (
<>
@@ -1145,67 +1129,72 @@ function FileTreeMenu({
</DropdownMenuItem>
</DropdownMenuSubContent>
</DropdownMenuSub>
- <DropdownMenuSeparator />
- {!isAsset ? (
- <DropdownMenuItem
- disabled={anyActionBusy}
- onSelect={() => {
- close();
- onDuplicate(target);
- }}
- >
- <CopyPlus aria-hidden="true" />
- <Trans>Duplicate</Trans>
- </DropdownMenuItem>
- ) : null}
- <DropdownMenuItem
- disabled={anyActionBusy}
- onSelect={() => {
- closeForInlineSurface();
- model.startRenaming(item.path);
- }}
- >
- <Pencil aria-hidden="true" />
- <Trans>Rename</Trans>
- </DropdownMenuItem>
- {okignoreTarget ? (
- <DropdownMenuItem
- data-testid="file-tree-menu-hide"
- disabled={!canHide}
- onSelect={() => {
- if (!okignoreBinding) return;
- close();
- const pattern = buildOkignorePatternFromTarget(okignoreTarget);
- const current = okignoreBinding.current();
- const doc = parseOkignoreDoc(current);
- // appendPattern returns the same doc reference for whitespace-only
- // input AND for duplicates; skip the patch on both no-ops so we
- // don't churn the Y.Text with identical bytes.
- const updated = appendPattern(doc, pattern);
- if (updated === doc) return;
- okignoreBinding.patch(serializeOkignoreDoc(updated));
- const basename = okignoreTarget.path.split('/').pop() || okignoreTarget.path;
- toast.success(t`Hidden “${basename}”`, {
- description: t`Manage hidden files in Settings → Ignore patterns.`,
- duration: 5000,
- });
- }}
- >
- <EyeOff aria-hidden="true" />
- {hideLabel}
- </DropdownMenuItem>
+ {/* Mutate section (hidden for inspect-only .ok rows). */}
+ {!isOkRow ? (
+ <>
+ <DropdownMenuSeparator />
+ {!isAsset ? (
+ <DropdownMenuItem
+ disabled={anyActionBusy}
+ onSelect={() => {
+ close();
+ onDuplicate(target);
+ }}
+ >
+ <CopyPlus aria-hidden="true" />
+ <Trans>Duplicate</Trans>
+ </DropdownMenuItem>
+ ) : null}
+ <DropdownMenuItem
+ disabled={anyActionBusy}
+ onSelect={() => {
+ closeForInlineSurface();
+ model.startRenaming(item.path);
+ }}
+ >
+ <Pencil aria-hidden="true" />
+ <Trans>Rename</Trans>
+ </DropdownMenuItem>
+ {okignoreTarget ? (
+ <DropdownMenuItem
+ data-testid="file-tree-menu-hide"
+ disabled={!canHide}
+ onSelect={() => {
+ if (!okignoreBinding) return;
+ close();
+ const pattern = buildOkignorePatternFromTarget(okignoreTarget);
+ const current = okignoreBinding.current();
+ const doc = parseOkignoreDoc(current);
+ // appendPattern returns the same doc reference for whitespace-only
+ // input AND for duplicates; skip the patch on both no-ops so we
+ // don't churn the Y.Text with identical bytes.
+ const updated = appendPattern(doc, pattern);
+ if (updated === doc) return;
+ okignoreBinding.patch(serializeOkignoreDoc(updated));
+ const basename = okignoreTarget.path.split('/').pop() || okignoreTarget.path;
+ toast.success(t`Hidden “${basename}”`, {
+ description: t`Manage hidden files in Settings → Ignore patterns.`,
+ duration: 5000,
+ });
+ }}
+ >
+ <EyeOff aria-hidden="true" />
+ {hideLabel}
+ </DropdownMenuItem>
+ ) : null}
+ <DropdownMenuItem
+ variant="destructive"
+ disabled={anyActionBusy}
+ onSelect={() => {
+ close();
+ onDelete(deleteTargets);
+ }}
+ >
+ <Trash2 aria-hidden="true" />
+ {deleteLabel}
+ </DropdownMenuItem>
+ </>
) : null}
- <DropdownMenuItem
- variant="destructive"
- disabled={anyActionBusy}
- onSelect={() => {
- close();
- onDelete(deleteTargets);
- }}
- >
- <Trash2 aria-hidden="true" />
- {deleteLabel}
- </DropdownMenuItem>
</>
)}
</DropdownMenuContent>
@@ -1229,10 +1218,9 @@ export interface FileTreeHandle {
* Snapshot of the tree's folder state, cheap to call on every render.
* Reads `folderTreePathsRef.current` for `folderCount` and iterates
* `model.getItem(path)?.isExpanded()` for `expandedCount`. FileSidebar
- * uses this via `useSyncExternalStore` to drive the conditional render
- * of the Tree view options dropdown — hiding the trigger when there
- * are no folders, and individual Expand/Collapse-All items when their
- * action would be a no-op.
+ * subscribes (`subscribe` + this getter) to smart-hide the Expand/
+ * Collapse-all commands across its menu surfaces when their action
+ * would be a no-op.
*/
getFolderState(): { folderCount: number; expandedCount: number };
/**
@@ -1264,6 +1252,16 @@ type ShowAllDepth1ListingResult =
| { kind: 'http-error'; title: string }
| { kind: 'network-error'; cause: unknown };
+/**
+ * The depth-1 disk-walk listing URL. `showOk` is the request-scoped reveal
+ * of `.ok` rows (Show .ok folders axis) — the server admits `.ok` entries on
+ * this walk only, so the flag rides the listing URL rather than any global
+ * mode.
+ */
+function showAllDepth1Url(dir: string, showOk: boolean): string {
+ return `/api/documents?showAll=true${showOk ? '&showOk=true' : ''}&dir=${encodeURIComponent(dir)}&depth=1`;
+}
+
/**
* One level of the Show All listing for `dir` (`''` = content root), via the
* same NDJSON-or-buffered branching as the root refresh. Failures come back
@@ -1273,12 +1271,13 @@ type ShowAllDepth1ListingResult =
*/
async function fetchShowAllDepth1Listing(
dir: string,
+ showOk: boolean,
signal: AbortSignal,
fallbackErrorTitle: string,
schemaMismatchTitle: string,
): Promise<ShowAllDepth1ListingResult> {
try {
- const res = await fetch(`/api/documents?showAll=true&dir=${encodeURIComponent(dir)}&depth=1`, {
+ const res = await fetch(showAllDepth1Url(dir, showOk), {
signal,
headers: SHOW_ALL_NDJSON_ACCEPT,
});
@@ -1342,7 +1341,7 @@ export function FileTree({
} = useDocumentContext();
const { notifySidebarFileSelected } = useSidebar();
const { resolvedTheme } = useTheme();
- const { addPage, pageMeta } = usePageList();
+ const { addPage, pageMeta, pages } = usePageList();
function navigationTargetForDocument(
docName: string,
size: number | null | undefined,
@@ -1391,6 +1390,11 @@ export function FileTree({
// Count of entries the server returned when the showAll walk hit its entry
// cap (so the list is a partial prefix); null when the list is complete.
const [truncatedShownCount, setTruncatedShownCount] = useState<number | null>(null);
+ // Pre-filter size of the most recent depth-1 root listing, captured where
+ // the listing lands. The filtered `documents` state can't distinguish an
+ // empty project from filters hiding everything (raw listings aren't
+ // retained), so the empty slot's classifier reads this signal instead.
+ const [unfilteredRootEntryCount, setUnfilteredRootEntryCount] = useState(0);
const [busyPath, setBusyPath] = useState<string | null>(null);
const [deleteRequest, setDeleteRequest] = useState<FileTreeDeleteRequest | null>(null);
/**
@@ -1460,6 +1464,25 @@ export function FileTree({
const docEntry = entries.find(
(item): item is DocumentEntry => isDocumentEntry(item) && item.docName === action.path,
);
+ // Revealed `.ok` document rows never open the raw editable editor: the
+ // shared routing sends template files to the template editor, keeps
+ // indexed skill docs on the normal doc flow (null), and lands everything
+ // else on the read-only text viewer — same rule the hash resolver's
+ // doc-open guard applies.
+ const okTarget = okContentNavigationTarget(action.path, {
+ pages,
+ docExt: docEntry?.docExt,
+ });
+ if (okTarget?.kind === 'asset') {
+ openTarget(okTarget, { tabBehavior: 'replace-active' });
+ replaceHashWithoutNavigation(hashFromAssetPath(okTarget.assetPath));
+ notifySidebarFileSelected();
+ return;
+ }
+ if (okTarget?.kind === 'doc') {
+ navigateToWithPulse(okTarget.docName);
+ return;
+ }
navigateToWithPulse(action.path, docEntry?.size, {
registerPage: hasSupportedDocumentExtension(action.path),
});
@@ -1532,12 +1555,20 @@ export function FileTree({
const prevExpandedFolderTreePathsRef = useRef<ReadonlySet<string>>(new Set());
const detectLazyFolderExpansionsRef = useRef<() => void>(() => {});
const revalidateExpandedLazyDirsRef = useRef<() => void>(() => {});
- // The async fetch closure in the docs refresh effect is created once at
- // mount; reading `showHiddenFiles` directly would capture the mount-time
- // value. The ref lets the closure read the latest toggle state when the
- // response actually lands. Initialized to `false` (matches the cold-start
- // default before config loads); synced in the bulk useLayoutEffect below.
+ // The async fetch closures in the docs refresh effect are created once at
+ // mount; reading the visibility toggles directly would capture their
+ // mount-time values. The refs let a closure read the latest toggle state
+ // when the response actually lands. Initialized to `false` (matches the
+ // cold-start defaults before config loads); synced in the bulk
+ // useLayoutEffect below.
const showHiddenFilesRef = useRef<boolean>(false);
+ const showOnlyMarkdownFilesRef = useRef<boolean>(false);
+ const showOkFoldersRef = useRef<boolean>(false);
+ const treeVisibilityFromRefs = () => ({
+ showHiddenFiles: showHiddenFilesRef.current,
+ showOnlyMarkdownFiles: showOnlyMarkdownFilesRef.current,
+ showOkFolders: showOkFoldersRef.current,
+ });
// Hoists the docs scheduler's `request()` out of its effect closure so
// the showHiddenFiles-flip effect can re-fetch without re-mounting the
// listener / scheduler. Set to a callable in the docs effect; cleared on
@@ -1599,7 +1630,7 @@ export function FileTree({
// aborting → a successful fetch self-heals the panel without waiting for the
// next focus / CC1 refresh. Skips the initial render.
const isFirstRelaunchEffectRunRef = useRef(true);
- // biome-ignore lint/correctness/useExhaustiveDependencies: relaunchInFlight is a transition trigger, not a read — the body calls the hoisted scheduler ref only. Sibling pattern at the showHiddenFiles flip effect below.
+ // biome-ignore lint/correctness/useExhaustiveDependencies: relaunchInFlight is a transition trigger, not a read — the body calls the hoisted scheduler ref only. Sibling pattern at the visibility-toggle flip effect below.
useEffect(() => {
if (isFirstRelaunchEffectRunRef.current) {
isFirstRelaunchEffectRunRef.current = false;
@@ -1744,8 +1775,10 @@ export function FileTree({
isElectronHost: typeof window !== 'undefined' && window.okDesktop != null,
dispatch: dispatchHandoff,
};
- const { okignoreBinding, projectLocalBinding, merged } = useConfigContext();
+ const { okignoreBinding, merged } = useConfigContext();
const showHiddenFiles = merged?.appearance?.sidebar?.showHiddenFiles ?? false;
+ const showOnlyMarkdownFiles = merged?.appearance?.sidebar?.showOnlyMarkdownFiles ?? false;
+ const showOkFolders = merged?.appearance?.sidebar?.showOkFolders ?? false;
const isAvailable = () => busyPathRef.current === null;
@@ -1837,7 +1870,9 @@ export function FileTree({
const treePaths = documentsToTreePaths(documents);
const treePathsSignature = treePathSignature(treePaths);
const treePathsRef = useRef(treePaths);
- const folderTreePaths = collectTreeFolderPathsFromDocuments(documents);
+ const folderTreePaths = collectTreeFolderPathsFromDocuments(documents, {
+ includeOkFolders: showOkFolders,
+ });
const folderTreePathsRef = useRef(folderTreePaths);
// Keep parents visible without forcing the selected folder itself open.
@@ -1859,7 +1894,9 @@ export function FileTree({
const expandedPathsForReset = (nextDocuments?: readonly FileEntry[]) => {
const nextFolderPaths = new Set(
- collectTreeFolderPathsFromDocuments(nextDocuments ?? documentsRef.current),
+ collectTreeFolderPathsFromDocuments(nextDocuments ?? documentsRef.current, {
+ includeOkFolders: showOkFoldersRef.current,
+ }),
);
const expanded = collectExpandedFolderTreePaths();
for (const ancestor of activeAncestorTreePathsRef.current) {
@@ -1886,6 +1923,7 @@ export function FileTree({
lazyChildFetchControllersRef.current.set(folderTreePath, controller);
const result = await fetchShowAllDepth1Listing(
treeDirectoryPathToFolderPath(folderTreePath),
+ showOkFoldersRef.current,
controller.signal,
t`Failed to load documents`,
t`Documents response did not match expected shape.`,
@@ -1912,8 +1950,7 @@ export function FileTree({
reportServerReachableError(result.title);
return;
}
- const bypassClientDotDrop = showHiddenFilesRef.current;
- const children = filterVisibleEntries(result.entries, bypassClientDotDrop);
+ const children = filterVisibleEntries(result.entries, treeVisibilityFromRefs());
lazyLoadedDirTreePathsRef.current.add(folderTreePath);
// Functional update: concurrent child fetches resolve in the same
// microtask batch, and `documentsRef` only syncs on commit — reading it
@@ -2273,7 +2310,7 @@ export function FileTree({
// each folder stamped `hasChildren` so it can offer expansion without
// the server walking its subtree. The full recursive walk (no `depth`)
// remains served for non-sidebar callers.
- const res = await fetch('/api/documents?showAll=true&dir=&depth=1', {
+ const res = await fetch(showAllDepth1Url('', showOkFoldersRef.current), {
signal: controller.signal,
// Opt into the NDJSON stream so the server walks disk without
// buffering the whole listing; the buffered JSON path stays the
@@ -2288,12 +2325,15 @@ export function FileTree({
// batch — NOT a root splice, which prunes folders not yet streamed.
// The authoritative prune + optimistic-merge reconcile is the single
// splice once the stream completes, matching the buffered branch.
- const bypassClientDotDrop = showHiddenFilesRef.current;
+ // One snapshot for the whole stream so batches and the completion
+ // splice filter identically; a mid-stream toggle flip refetches
+ // (flip effect below) rather than half-filtering this run.
+ const visibility = treeVisibilityFromRefs();
let paintedFirstBatch = false;
const { entries, truncated } = await consumeShowAllStream(res, {
onBatch: (batch) => {
if (!active || controller.signal.aborted) return;
- const batchEntries = filterVisibleEntries(toFileEntries(batch), bypassClientDotDrop);
+ const batchEntries = filterVisibleEntries(toFileEntries(batch), visibility);
// Only act on a batch that yields a VISIBLE row. The server walk
// emits hidden entries (dot-dirs/files) in arbitrary readdir order;
// the client filters them. Clearing `loading` on an all-hidden
@@ -2311,7 +2351,8 @@ export function FileTree({
},
});
if (!active) return;
- const serverEntries = filterVisibleEntries(toFileEntries(entries), bypassClientDotDrop);
+ const rootEntries = toFileEntries(entries);
+ const serverEntries = filterVisibleEntries(rootEntries, visibility);
// The depth-1 root level replaces in place rather than replacing the
// whole document set: children already loaded for folders the server
// still returns keep rendering (no flash-empty on every CC1 push),
@@ -2325,6 +2366,7 @@ export function FileTree({
setError(null);
noteConnectivityRecovered();
setTruncatedShownCount(truncated ? entries.length : null);
+ setUnfilteredRootEntryCount(rootEntries.length);
revalidateExpandedLazyDirsRef.current();
} else {
const parsed = await parseServerResponse(res, t`Failed to load documents`);
@@ -2339,13 +2381,10 @@ export function FileTree({
setTruncatedShownCount(null);
} else {
// Non-streaming fallback for the same depth-1 listing. The disk
- // walk ships dot-segment paths; the client-side dot-drop hides
- // them unless Show hidden files is on.
- const bypassClientDotDrop = showHiddenFilesRef.current;
- const serverEntries = filterVisibleEntries(
- toFileEntries(success.data.documents),
- bypassClientDotDrop,
- );
+ // walk ships everything the server admits; the client-side
+ // visibility filter applies the sidebar toggles.
+ const rootEntries = toFileEntries(success.data.documents);
+ const serverEntries = filterVisibleEntries(rootEntries, treeVisibilityFromRefs());
// Same in-place root splice + expanded-dir revalidation as the
// NDJSON branch above — the buffered JSON shape is the
// non-streaming fallback for the identical depth-1 listing.
@@ -2357,6 +2396,7 @@ export function FileTree({
setTruncatedShownCount(
success.data.truncated === true ? success.data.documents.length : null,
);
+ setUnfilteredRootEntryCount(rootEntries.length);
revalidateExpandedLazyDirsRef.current();
}
}
@@ -2420,20 +2460,22 @@ export function FileTree({
};
}, [t]);
- // Re-fetch + re-filter when the user flips Show hidden files. The server response
- // doesn't depend on the toggle (server filters are unaffected), but the
- // client-side filter does — refreshing keeps the request/response shape
- // unchanged and reuses the scheduler's in-flight coalescing. Skips on first
- // render to avoid double-fetching on mount.
- const isFirstShowHiddenFilesEffectRunRef = useRef(true);
- // biome-ignore lint/correctness/useExhaustiveDependencies: showHiddenFiles is a flip-detection trigger, not a read — the effect body reads refs only. Sibling pattern at the treePathsSignature reset effect above.
+ // Re-fetch + re-filter when the user flips a sidebar visibility toggle.
+ // Hidden files and only-markdown are pure client-side filters (the server
+ // response doesn't depend on them); Show .ok folders parameterizes the
+ // request itself (the listing URL carries `showOk`). Either way the flip
+ // reuses the scheduler's in-flight coalescing, and the fetch closures read
+ // the flipped values through the refs. Skips on first render to avoid
+ // double-fetching on mount.
+ const isFirstVisibilityFlipEffectRunRef = useRef(true);
+ // biome-ignore lint/correctness/useExhaustiveDependencies: the visibility toggles are flip-detection triggers, not reads — the effect body reads refs only. Sibling pattern at the treePathsSignature reset effect above.
useEffect(() => {
- if (isFirstShowHiddenFilesEffectRunRef.current) {
- isFirstShowHiddenFilesEffectRunRef.current = false;
+ if (isFirstVisibilityFlipEffectRunRef.current) {
+ isFirstVisibilityFlipEffectRunRef.current = false;
return;
}
refreshDocsScheduleRef.current?.();
- }, [showHiddenFiles]);
+ }, [showHiddenFiles, showOnlyMarkdownFiles, showOkFolders]);
useEffect(() => {
let active = true;
@@ -2571,7 +2613,7 @@ export function FileTree({
// biome-ignore lint/correctness/useExhaustiveDependencies: activeAncestorTreePathsSignature + treePathsSignature are re-run triggers — the row's visible index shifts when ancestors expand or the tree repopulates.
useEffect(() => {
if (loading || !activeTreePath) return;
- revealActiveRow(model);
+ revealActiveRow(model, activeTreePath);
}, [activeTreePath, activeAncestorTreePathsSignature, treePathsSignature, loading, model]);
useEffect(() => {
@@ -3278,6 +3320,8 @@ export function FileTree({
assetTreePathsRef.current = assetTreePaths;
busyPathRef.current = busyPath;
showHiddenFilesRef.current = showHiddenFiles;
+ showOnlyMarkdownFilesRef.current = showOnlyMarkdownFiles;
+ showOkFoldersRef.current = showOkFolders;
treePathsRef.current = treePaths;
folderTreePathsRef.current = folderTreePaths;
activeAncestorTreePathsRef.current = activeAncestorTreePaths;
@@ -3848,9 +3892,13 @@ export function FileTree({
}
async function handleDeleteTargets(targets: FileTreeTarget[]) {
- const deleteTargets = targets.map((target) =>
- canonicalizeAssetTargetForDelete(target, documentsRef.current),
- );
+ // Last chokepoint before side effects: on Electron, `shell.trashItem`
+ // moves files to the OS Trash BEFORE the server's reserved-path guard can
+ // refuse, so read-only `.ok` targets are dropped here regardless of which
+ // entry surface produced them.
+ const deleteTargets = targets
+ .filter((target) => !hasOkPathSegment(target.path))
+ .map((target) => canonicalizeAssetTargetForDelete(target, documentsRef.current));
const firstTarget = deleteTargets[0];
if (!firstTarget) return;
@@ -4308,6 +4356,15 @@ export function FileTree({
</div>
);
}
+ if (
+ classifyEmptyTree({
+ visibility: { showHiddenFiles, showOnlyMarkdownFiles },
+ unfilteredRootEntryCount,
+ knownPageCount: pages.size,
+ }) === 'filtered-to-zero'
+ ) {
+ return <FileTreeFilteredToZeroNotice />;
+ }
return (
<section
aria-label={t`File drop zone`}
@@ -4384,8 +4441,6 @@ export function FileTree({
handoff={handoff}
model={model}
okignoreBinding={okignoreBinding}
- projectLocalBinding={projectLocalBinding}
- mergedConfig={merged}
onStartCreating={startCreating}
onCreateFromTemplate={(parentDir, templateName) =>
startCreating('file', parentDir, { template: templateName })
diff --git a/packages/app/src/components/FileTreeFilteredToZeroNotice.dom.test.tsx b/packages/app/src/components/FileTreeFilteredToZeroNotice.dom.test.tsx
new file mode 100644
index 000000000..263374c83
--- /dev/null
+++ b/packages/app/src/components/FileTreeFilteredToZeroNotice.dom.test.tsx
@@ -0,0 +1,102 @@
+/**
+ * Behavioral tests for the filtered-to-zero tree notice: the reset action's
+ * config payload (tree-content toggles to defaults, Skills section untouched),
+ * the disabled state while the project-local binding is unavailable, and the
+ * rejection toast — the same write-path contract as every other sidebar
+ * visibility surface.
+ *
+ * Runs under `bun run test:dom` (jsdom substrate per precedent #43).
+ */
+import { afterEach, beforeEach, describe, expect, mock, test } from 'bun:test';
+import { cleanup, fireEvent, render, screen } from '@testing-library/react';
+import { renderLinguiTemplate } from '@/test-utils/lingui-mock';
+
+mock.module('@lingui/react/macro', () => ({
+ useLingui: () => ({ t: renderLinguiTemplate }),
+}));
+
+let projectLocalBindingNull = false;
+let patchResultOk = true;
+const patchCalls: unknown[] = [];
+const toastErrors: unknown[][] = [];
+
+mock.module('@/lib/config-provider', () => ({
+ useConfigContext: () => ({
+ merged: null,
+ projectLocalBinding: projectLocalBindingNull
+ ? null
+ : {
+ patch: (value: unknown) => {
+ patchCalls.push(value);
+ return patchResultOk
+ ? { ok: true, appliedPaths: [], effective: {} }
+ : { ok: false, error: { issues: [] } };
+ },
+ },
+ }),
+}));
+
+mock.module('sonner', () => ({
+ toast: {
+ error: (...args: unknown[]) => toastErrors.push(args),
+ success: () => {},
+ },
+}));
+
+const { FileTreeFilteredToZeroNotice } = await import('./FileTreeFilteredToZeroNotice');
+
+const resetButton = () => screen.queryByTestId('reset-view-filters');
+
+describe('FileTreeFilteredToZeroNotice', () => {
+ beforeEach(() => {
+ projectLocalBindingNull = false;
+ patchResultOk = true;
+ patchCalls.length = 0;
+ toastErrors.length = 0;
+ });
+
+ afterEach(() => cleanup());
+
+ test('explains the state and offers the reset action', () => {
+ render(<FileTreeFilteredToZeroNotice />);
+
+ expect(screen.queryByTestId('file-tree-filtered-to-zero')).toBeTruthy();
+ expect(screen.queryByText('All files are hidden by view filters.')).toBeTruthy();
+ expect(resetButton()).toBeTruthy();
+ });
+
+ test('reset restores the tree-content toggles to defaults and leaves the Skills section alone', () => {
+ render(<FileTreeFilteredToZeroNotice />);
+
+ fireEvent.click(resetButton() as HTMLElement);
+ expect(patchCalls).toEqual([
+ {
+ appearance: {
+ sidebar: {
+ showHiddenFiles: false,
+ showOnlyMarkdownFiles: false,
+ showOkFolders: false,
+ },
+ },
+ },
+ ]);
+ });
+
+ test('reset is disabled while the project-local binding is unavailable', () => {
+ projectLocalBindingNull = true;
+ render(<FileTreeFilteredToZeroNotice />);
+
+ expect((resetButton() as HTMLButtonElement).disabled).toBe(true);
+ fireEvent.click(resetButton() as HTMLElement);
+ expect(patchCalls).toEqual([]);
+ });
+
+ test('a rejected patch surfaces the shared settings toast', () => {
+ patchResultOk = false;
+ render(<FileTreeFilteredToZeroNotice />);
+
+ fireEvent.click(resetButton() as HTMLElement);
+ expect(toastErrors.length).toBe(1);
+ expect(toastErrors[0]?.[0]).toBe('Could not update sidebar settings');
+ });
+});
diff --git a/packages/app/src/components/FileTreeFilteredToZeroNotice.tsx b/packages/app/src/components/FileTreeFilteredToZeroNotice.tsx
new file mode 100644
index 000000000..43405af7e
--- /dev/null
+++ b/packages/app/src/components/FileTreeFilteredToZeroNotice.tsx
@@ -0,0 +1,67 @@
+import { humanFormat } from '@inkeep/open-knowledge-core';
+import { useLingui } from '@lingui/react/macro';
+import { toast } from 'sonner';
+import { Button } from '@/components/ui/button';
+import { useConfigContext } from '@/lib/config-provider';
+
+/**
+ * Empty-slot notice for a tree whose active view filters hide every row of a
+ * non-empty project — rendered in place of the `No files yet` state so a
+ * filtered view is never mistaken for an empty one. The caller (FileTree's
+ * empty slot) owns that classification; this component owns the explanation
+ * and the one-click recovery.
+ *
+ * Reset restores the tree-content toggles to their defaults. The Skills
+ * section toggle is deliberately untouched: it gates a sidebar section, not
+ * tree rows, so it can never contribute to this state.
+ */
+export function FileTreeFilteredToZeroNotice() {
+ const { t } = useLingui();
+ const { projectLocalBinding } = useConfigContext();
+
+ // Same write path + rejection surface as the sidebar's visibility
+ // checkboxes (FileSidebar's patchSidebarVisibility): one config shape, one
+ // toast, so every flip surface behaves identically.
+ const handleReset = () => {
+ if (projectLocalBinding === null) return;
+ const result = projectLocalBinding.patch({
+ appearance: {
+ sidebar: {
+ showHiddenFiles: false,
+ showOnlyMarkdownFiles: false,
+ showOkFolders: false,
+ },
+ },
+ });
+ if (!result.ok) {
+ console.warn(
+ '[FileTreeFilteredToZeroNotice] view-filter reset rejected:',
+ humanFormat(result.error),
+ );
+ toast.error(t`Could not update sidebar settings`, {
+ description: humanFormat(result.error),
+ });
+ }
+ };
+
+ return (
+ <div
+ data-testid="file-tree-filtered-to-zero"
+ className="flex flex-1 flex-col items-center justify-center gap-3 py-8"
+ >
+ <span className="select-none text-sidebar-foreground/30 text-sm">
+ {t`All files are hidden by view filters.`}
+ </span>
+ <Button
+ variant="link"
+ size="sm"
+ className="font-mono uppercase"
+ disabled={projectLocalBinding === null}
+ onClick={handleReset}
+ data-testid="reset-view-filters"
+ >
+ {t`Reset view filters`}
+ </Button>
+ </div>
+ );
+}
diff --git a/packages/app/src/components/NotInSidebarIndicator.dom.test.tsx b/packages/app/src/components/NotInSidebarIndicator.dom.test.tsx
new file mode 100644
index 000000000..0c8bac6c0
--- /dev/null
+++ b/packages/app/src/components/NotInSidebarIndicator.dom.test.tsx
@@ -0,0 +1,143 @@
+/**
+ * Behavioral tests for the not-in-sidebar indicator: per-axis attribution
+ * rendering, per-axis flip patches, recompute after a flip that leaves the
+ * doc hidden by the other axis, and the silent cases (visible docs, skills /
+ * templates / `.ok` docs, which never have a row the toggles govern).
+ *
+ * Runs under `bun run test:dom` (jsdom substrate per precedent #43).
+ */
+import { afterEach, beforeEach, describe, expect, mock, test } from 'bun:test';
+import type { Config } from '@inkeep/open-knowledge-core';
+import { cleanup, fireEvent, render, screen } from '@testing-library/react';
+import { renderLinguiTemplate } from '@/test-utils/lingui-mock';
+
+mock.module('@lingui/react/macro', () => ({
+ useLingui: () => ({ t: renderLinguiTemplate }),
+}));
+
+type SidebarVisibilityConfig = {
+ appearance?: {
+ sidebar?: {
+ showHiddenFiles?: boolean;
+ showOnlyMarkdownFiles?: boolean;
+ };
+ };
+};
+
+let mergedConfig: SidebarVisibilityConfig | null = null;
+let projectLocalBindingNull = false;
+let patchResultOk = true;
+const patchCalls: unknown[] = [];
+const toastErrors: unknown[][] = [];
+
+mock.module('@/lib/config-provider', () => ({
+ useConfigContext: () => ({
+ merged: mergedConfig as Config | null,
+ projectLocalBinding: projectLocalBindingNull
+ ? null
+ : {
+ patch: (value: unknown) => {
+ patchCalls.push(value);
+ return patchResultOk
+ ? { ok: true, appliedPaths: [], effective: {} }
+ : { ok: false, error: { issues: [] } };
+ },
+ },
+ }),
+}));
+
+mock.module('sonner', () => ({
+ toast: {
+ error: (...args: unknown[]) => toastErrors.push(args),
+ success: () => {},
+ },
+}));
+
+const { NotInSidebarIndicator } = await import('./NotInSidebarIndicator');
+
+const indicator = () => screen.queryByTestId('not-in-sidebar-indicator');
+const hiddenFilesFlip = () => screen.queryByTestId('not-in-sidebar-flip-hidden-files');
+const onlyMarkdownFlip = () => screen.queryByTestId('not-in-sidebar-flip-only-markdown');
+
+describe('NotInSidebarIndicator', () => {
+ beforeEach(() => {
+ mergedConfig = null;
+ projectLocalBindingNull = false;
+ patchResultOk = true;
+ patchCalls.length = 0;
+ toastErrors.length = 0;
+ });
+
+ afterEach(() => cleanup());
+
+ test('dot-path doc at defaults names the hidden-files axis only', () => {
+ render(<NotInSidebarIndicator entry={{ kind: 'document', docName: '.scratch/note' }} />);
+
+ expect(indicator()).toBeTruthy();
+ expect(hiddenFilesFlip()).toBeTruthy();
+ expect(onlyMarkdownFlip()).toBeNull();
+ });
+
+ test('flip action patches the axis config leaf through the project-local binding', () => {
+ render(<NotInSidebarIndicator entry={{ kind: 'document', docName: '.scratch/note' }} />);
+
+ fireEvent.click(hiddenFilesFlip() as HTMLElement);
+ expect(patchCalls).toEqual([{ appearance: { sidebar: { showHiddenFiles: true } } }]);
+ });
+
+ test('both-axes file lists both toggles; flipping one leaves the other (recompute)', () => {
+ mergedConfig = { appearance: { sidebar: { showOnlyMarkdownFiles: true } } };
+ const rendered = render(
+ <NotInSidebarIndicator entry={{ kind: 'asset', path: '.scratch/data.csv' }} />,
+ );
+ expect(hiddenFilesFlip()).toBeTruthy();
+ expect(onlyMarkdownFlip()).toBeTruthy();
+
+ fireEvent.click(onlyMarkdownFlip() as HTMLElement);
+ expect(patchCalls).toEqual([{ appearance: { sidebar: { showOnlyMarkdownFiles: false } } }]);
+
+ // The patch lands in merged config via the CRDT round-trip; mirror that
+ // by re-rendering with the updated merged view.
+ mergedConfig = { appearance: { sidebar: { showOnlyMarkdownFiles: false } } };
+ rendered.rerender(
+ <NotInSidebarIndicator entry={{ kind: 'asset', path: '.scratch/data.csv' }} />,
+ );
+ expect(indicator()).toBeTruthy();
+ expect(hiddenFilesFlip()).toBeTruthy();
+ expect(onlyMarkdownFlip()).toBeNull();
+ });
+
+ test('renders nothing when the doc has a visible row', () => {
+ render(<NotInSidebarIndicator entry={{ kind: 'document', docName: 'notes/todo' }} />);
+ expect(indicator()).toBeNull();
+ });
+
+ test('renders nothing for docs structurally outside the tree (skills, templates, .ok)', () => {
+ mergedConfig = { appearance: { sidebar: { showOnlyMarkdownFiles: true } } };
+ for (const docName of [
+ '.ok/skills/writer/SKILL',
+ '__skill__/global/writer',
+ '__template__/.private/meeting-notes',
+ ]) {
+ const rendered = render(<NotInSidebarIndicator entry={{ kind: 'document', docName }} />);
+ expect(indicator()).toBeNull();
+ rendered.unmount();
+ }
+ });
+
+ test('flip actions disable while the project-local binding is unavailable', () => {
+ projectLocalBindingNull = true;
+ render(<NotInSidebarIndicator entry={{ kind: 'document', docName: '.scratch/note' }} />);
+
+ expect(indicator()).toBeTruthy();
+ expect((hiddenFilesFlip() as HTMLButtonElement).disabled).toBe(true);
+ });
+
+ test('a rejected patch surfaces the shared settings-update toast', () => {
+ patchResultOk = false;
+ render(<NotInSidebarIndicator entry={{ kind: 'document', docName: '.scratch/note' }} />);
+
+ fireEvent.click(hiddenFilesFlip() as HTMLElement);
+ expect(toastErrors.length).toBe(1);
+ });
+});
diff --git a/packages/app/src/components/NotInSidebarIndicator.tsx b/packages/app/src/components/NotInSidebarIndicator.tsx
new file mode 100644
index 000000000..6f7963704
--- /dev/null
+++ b/packages/app/src/components/NotInSidebarIndicator.tsx
@@ -0,0 +1,101 @@
+import { humanFormat } from '@inkeep/open-knowledge-core';
+import { useLingui } from '@lingui/react/macro';
+import { EyeOff } from 'lucide-react';
+import { toast } from 'sonner';
+import { Button } from '@/components/ui/button';
+import { useConfigContext } from '@/lib/config-provider';
+import { cn } from '@/lib/utils';
+import { attributeTreeHiddenAxes } from './file-tree-utils';
+
+interface NotInSidebarIndicatorProps {
+ /**
+ * The active doc as the sidebar tree would model it: markdown docs carry
+ * their docName, every other file its project-relative path. The kind is
+ * what the only-markdown axis judges, so the mounting surface (markdown
+ * editor vs asset view) supplies it rather than re-deriving it from the
+ * ref's extension.
+ */
+ entry: { kind: 'document'; docName: string } | { kind: 'asset'; path: string };
+ className?: string;
+}
+
+/**
+ * Passive "not shown in sidebar" chrome: when the active doc has no visible
+ * tree row because a visibility toggle hides it, names each hiding toggle as
+ * a one-click flip. Renders nothing whenever no user-flippable axis hides the
+ * doc — visible docs, and docs structurally outside the tree (skills,
+ * templates, `.ok` paths), stay indicator-free via the shared attribution
+ * predicate. Never a toast: the state is routine (any link/search hit can
+ * open a hidden doc), so it lives quietly in the surface's own chrome.
+ */
+export function NotInSidebarIndicator({ entry, className }: NotInSidebarIndicatorProps) {
+ const { t } = useLingui();
+ const { projectLocalBinding, merged } = useConfigContext();
+ const sidebar = merged?.appearance?.sidebar;
+ const axes = attributeTreeHiddenAxes(entry, {
+ showHiddenFiles: sidebar?.showHiddenFiles ?? false,
+ showOnlyMarkdownFiles: sidebar?.showOnlyMarkdownFiles ?? false,
+ });
+ if (!axes.hiddenFiles && !axes.onlyMarkdownFiles) return null;
+
+ // Same write path + rejection surface as the sidebar's visibility
+ // checkboxes (FileSidebar's patchSidebarVisibility): one config shape, one
+ // toast, so every flip surface behaves identically.
+ const patchSidebarVisibility = (patch: {
+ showHiddenFiles?: boolean;
+ showOnlyMarkdownFiles?: boolean;
+ }) => {
+ if (projectLocalBinding === null) return;
+ const result = projectLocalBinding.patch({ appearance: { sidebar: patch } });
+ if (!result.ok) {
+ console.warn(
+ '[NotInSidebarIndicator] sidebar visibility flip rejected:',
+ humanFormat(result.error),
+ );
+ toast.error(t`Could not update sidebar settings`, {
+ description: humanFormat(result.error),
+ });
+ }
+ };
+
+ const flipChipClass =
+ 'h-5 rounded-sm px-1.5 font-normal text-2xs text-muted-foreground hover:text-foreground';
+
+ return (
+ <div
+ data-testid="not-in-sidebar-indicator"
+ className={cn('flex items-center gap-1.5 text-muted-foreground/70 text-xs', className)}
+ >
+ <EyeOff aria-hidden="true" className="size-3.5 shrink-0" />
+ <span className="whitespace-nowrap">{t`Not in sidebar`}</span>
+ {axes.hiddenFiles ? (
+ <Button
+ variant="outline"
+ size="sm"
+ className={flipChipClass}
+ disabled={projectLocalBinding === null}
+ onClick={() => patchSidebarVisibility({ showHiddenFiles: true })}
+ aria-label={t`Show hidden files`}
+ title={t`Show hidden files`}
+ data-testid="not-in-sidebar-flip-hidden-files"
+ >
+ {t`Hidden files`}
+ </Button>
+ ) : null}
+ {axes.onlyMarkdownFiles ? (
+ <Button
+ variant="outline"
+ size="sm"
+ className={flipChipClass}
+ disabled={projectLocalBinding === null}
+ onClick={() => patchSidebarVisibility({ showOnlyMarkdownFiles: false })}
+ aria-label={t`Turn off Only markdown files`}
+ title={t`Turn off Only markdown files`}
+ data-testid="not-in-sidebar-flip-only-markdown"
+ >
+ {t`Only markdown files`}
+ </Button>
+ ) : null}
+ </div>
+ );
+}
diff --git a/packages/app/src/components/file-tree-adapter.test.ts b/packages/app/src/components/file-tree-adapter.test.ts
index d66664588..4591f137c 100644
--- a/packages/app/src/components/file-tree-adapter.test.ts
+++ b/packages/app/src/components/file-tree-adapter.test.ts
@@ -95,6 +95,30 @@ describe('file-tree-adapter', () => {
).toEqual(['docs/']);
});
+ test('includeOkFolders admits .ok folder paths for the revealed tree', () => {
+ // With the Show .ok folders axis on, `.ok` rows render — so their folder
+ // paths must collect like any other folder (expansion preservation across
+ // model resets filters through this set; a missing `.ok/` entry would
+ // collapse the revealed folder on every refresh cycle).
+ const entries = [
+ doc('docs/guide'),
+ doc('.ok/skills/my-skill/SKILL'),
+ { kind: 'folder' as const, path: '.ok/skills/my-skill', size: 0, modified: '' },
+ doc('notes/.ok/templates/daily'),
+ ];
+ expect(collectTreeFolderPathsFromDocuments(entries, { includeOkFolders: true })).toEqual([
+ '.ok/',
+ '.ok/skills/',
+ '.ok/skills/my-skill/',
+ 'docs/',
+ 'notes/',
+ 'notes/.ok/',
+ 'notes/.ok/templates/',
+ ]);
+ // The option defaults off — zero-argument callers keep the exclusion.
+ expect(collectTreeFolderPathsFromDocuments(entries)).toEqual(['docs/']);
+ });
+
test('computes active ancestor paths using Trees directory slash convention', () => {
expect(computeTreeAncestorPaths('README.md')).toEqual([]);
expect(computeTreeAncestorPaths('docs/guide.md')).toEqual(['docs/']);
diff --git a/packages/app/src/components/file-tree-adapter.ts b/packages/app/src/components/file-tree-adapter.ts
index 6d632337a..933cbc758 100644
--- a/packages/app/src/components/file-tree-adapter.ts
+++ b/packages/app/src/components/file-tree-adapter.ts
@@ -103,7 +103,10 @@ export function documentsTreePathSignature(documents: readonly FileEntry[]): str
return treePathSignature(documentsToTreePaths(documents));
}
-export function collectTreeFolderPathsFromDocuments(documents: readonly FileEntry[]): string[] {
+export function collectTreeFolderPathsFromDocuments(
+ documents: readonly FileEntry[],
+ options: { includeOkFolders?: boolean } = {},
+): string[] {
const folderPaths = new Set<string>();
for (const entry of documents) {
const path = isFolderEntry(entry)
@@ -114,11 +117,13 @@ export function collectTreeFolderPathsFromDocuments(documents: readonly FileEntr
const segments = path.split('/').filter(Boolean);
// `.ok/` is an internal directory. Skills-as-content makes
// `.ok/skills/<name>/SKILL` real content docs and `.ok` itself
- // index-descendable, so they now reach the document list — but `.ok` is
- // never a user-visible tree folder (skills live in the Skills section).
- // Excluding it keeps the folder count (and the hasFolders-gated "Tree view
- // options" toolbar) about VISIBLE folders only.
- if (segments.includes('.ok')) continue;
+ // index-descendable, so they now reach the document list — but by default
+ // `.ok` is never a user-visible tree folder (skills live in the Skills
+ // section), and excluding it keeps the folder set (expand/collapse-all
+ // iteration, expansion preservation across model resets) about VISIBLE
+ // folders only. When the Show .ok folders axis reveals `.ok` rows, the
+ // caller opts their folder paths in so they behave like any other folder.
+ if (!options.includeOkFolders && segments.includes('.ok')) continue;
if (isFolderEntry(entry)) {
const folderPath = folderPathToTreeDirectoryPath(entry.path);
if (folderPath) folderPaths.add(folderPath);
diff --git a/packages/app/src/components/file-tree-reveal.test.ts b/packages/app/src/components/file-tree-reveal.test.ts
index 9131c05bf..65c49b4a3 100644
--- a/packages/app/src/components/file-tree-reveal.test.ts
+++ b/packages/app/src/components/file-tree-reveal.test.ts
@@ -5,7 +5,7 @@ import { revealActiveRow } from './file-tree-reveal';
type RevealModel = Pick<FileTree, 'getFocusedPath' | 'scrollToPath'>;
// `revealActiveRow` delegates to Pierre's imperative `scrollToPath` (beta.4+),
-// so the contract is "scroll the focused path into view without stealing focus."
+// so the contract is "scroll the active row into view without stealing focus."
// A spy on the model is the behavior surface — no DOM/shadow-root walking left.
function makeModel(focusedPath: string | null) {
const scrollToPath = mock(() => {});
@@ -17,9 +17,9 @@ function makeModel(focusedPath: string | null) {
}
describe('revealActiveRow', () => {
- test('scrolls the focused path into view without stealing DOM focus', () => {
+ test('scrolls the active row into view without stealing DOM focus', () => {
const { model, scrollToPath } = makeModel('docs/quickstart');
- revealActiveRow(model);
+ revealActiveRow(model, 'docs/quickstart');
expect(scrollToPath).toHaveBeenCalledTimes(1);
expect(scrollToPath).toHaveBeenCalledWith('docs/quickstart', {
offset: 'nearest',
@@ -29,7 +29,13 @@ describe('revealActiveRow', () => {
test('no-ops when there is no focused row', () => {
const { model, scrollToPath } = makeModel(null);
- revealActiveRow(model);
+ revealActiveRow(model, 'docs/quickstart');
+ expect(scrollToPath).not.toHaveBeenCalled();
+ });
+
+ test('no-ops when the focused row is not the active row (stale focus after the active doc lost its tree row)', () => {
+ const { model, scrollToPath } = makeModel('docs/previously-active');
+ revealActiveRow(model, '.scratch/hidden-note.md');
expect(scrollToPath).not.toHaveBeenCalled();
});
});
diff --git a/packages/app/src/components/file-tree-reveal.ts b/packages/app/src/components/file-tree-reveal.ts
index 73c569d50..9fa179712 100644
--- a/packages/app/src/components/file-tree-reveal.ts
+++ b/packages/app/src/components/file-tree-reveal.ts
@@ -5,17 +5,22 @@ import type { FileTree as PierreFileTreeModel } from '@pierre/trees';
type RevealModel = Pick<PierreFileTreeModel, 'getFocusedPath' | 'scrollToPath'>;
/**
- * Scroll @pierre/trees' virtualized list so the just-activated (focused) row is
- * in view. `useSelectionMirror` sets the focused path on a programmatic open,
- * but Pierre only auto-scrolls a focused row when the tree owns DOM focus —
- * which a programmatic open never gives it — so the row can stay below the fold.
- * `scrollToPath` is Pierre's own imperative scroll (sticky-folder aware), called
- * with `focus: false` so the row is revealed without stealing DOM focus and
- * `offset: 'nearest'` so it scrolls the minimum distance. No-ops when there is
- * no focused row.
+ * Scroll @pierre/trees' virtualized list so the just-activated row is in view.
+ * `useSelectionMirror` sets the focused path on a programmatic open, but
+ * Pierre only auto-scrolls a focused row when the tree owns DOM focus — which
+ * a programmatic open never gives it — so the row can stay below the fold.
+ * `scrollToPath` is Pierre's own imperative scroll (sticky-folder aware),
+ * called with `focus: false` so the row is revealed without stealing DOM focus
+ * and `offset: 'nearest'` so it scrolls the minimum distance.
+ *
+ * Scrolls only when the focused row IS the active row. When the active doc has
+ * no visible row (e.g. hidden by a view filter), the mirror cannot move focus
+ * off the previously active row — Pierre has no unfocus API — so the focused
+ * path is a stale leftover, and scrolling to it would yank the tree to a row
+ * that is not the open document. No-ops in that case (and when nothing is
+ * focused).
*/
-export function revealActiveRow(model: RevealModel): void {
- const focusedPath = model.getFocusedPath();
- if (!focusedPath) return;
- model.scrollToPath(focusedPath, { offset: 'nearest', focus: false });
+export function revealActiveRow(model: RevealModel, activeTreePath: string): void {
+ if (model.getFocusedPath() !== activeTreePath) return;
+ model.scrollToPath(activeTreePath, { offset: 'nearest', focus: false });
}
diff --git a/packages/app/src/components/file-tree-utils.test.ts b/packages/app/src/components/file-tree-utils.test.ts
index 720ec5da5..5c4dc930c 100644
--- a/packages/app/src/components/file-tree-utils.test.ts
+++ b/packages/app/src/components/file-tree-utils.test.ts
@@ -1,12 +1,34 @@
import { describe, expect, test } from 'bun:test';
import { type DocumentListEntry, DocumentListEntrySchema } from '@inkeep/open-knowledge-core';
import {
+ attributeTreeHiddenAxes,
+ classifyEmptyTree,
computeAncestors,
defaultInitialDir,
filterVisibleEntries,
+ hasOkPathSegment,
toFileEntries,
} from './file-tree-utils';
+describe('hasOkPathSegment', () => {
+ test('matches a .ok segment at root and nested depth', () => {
+ expect(hasOkPathSegment('.ok')).toBe(true);
+ expect(hasOkPathSegment('.ok/config.yml')).toBe(true);
+ expect(hasOkPathSegment('notes/.ok/templates/starter')).toBe(true);
+ });
+
+ test('matches case variants, mirroring the server reserved-path guard', () => {
+ expect(hasOkPathSegment('.OK')).toBe(true);
+ expect(hasOkPathSegment('notes/.Ok/templates')).toBe(true);
+ });
+
+ test('does not match lookalike segments or substrings', () => {
+ expect(hasOkPathSegment('notes/.okay/file')).toBe(false);
+ expect(hasOkPathSegment('book/chapter')).toBe(false);
+ expect(hasOkPathSegment('ok/file')).toBe(false);
+ });
+});
+
describe('computeAncestors', () => {
test('returns empty array for null', () => {
expect(computeAncestors(null)).toEqual([]);
@@ -120,7 +142,7 @@ describe('filterVisibleEntries', () => {
{ kind: 'document' as const, docName: 'README' },
{ kind: 'asset' as const, path: 'opencode.json' },
];
- expect(filterVisibleEntries(entries, true)).toEqual(entries);
+ expect(filterVisibleEntries(entries, { showHiddenFiles: true })).toEqual(entries);
});
test('returns empty array when every entry is hidden', () => {
@@ -150,7 +172,7 @@ describe('filterVisibleEntries', () => {
{ kind: 'document' as const, docName: 'README' },
{ kind: 'folder' as const, path: '.claude' },
],
- false,
+ { showHiddenFiles: false },
),
).toEqual([{ kind: 'document', docName: 'README' }]);
});
@@ -161,7 +183,7 @@ describe('filterVisibleEntries', () => {
{ kind: 'folder' as const, path: '.claude' },
{ kind: 'document' as const, docName: '.config' },
];
- expect(filterVisibleEntries(entries, true)).toEqual(entries);
+ expect(filterVisibleEntries(entries, { showHiddenFiles: true })).toEqual(entries);
});
test('showHiddenFiles=true recovers entries nested under a dot-prefixed ancestor', () => {
@@ -171,7 +193,7 @@ describe('filterVisibleEntries', () => {
{ kind: 'document' as const, docName: 'brain/visible' },
{ kind: 'folder' as const, path: 'brain/.archived' },
];
- expect(filterVisibleEntries(entries, true)).toEqual(entries);
+ expect(filterVisibleEntries(entries, { showHiddenFiles: true })).toEqual(entries);
});
test('showHiddenFiles=true recovers asset entries with dot-prefixed ancestor', () => {
@@ -180,7 +202,7 @@ describe('filterVisibleEntries', () => {
{ kind: 'asset' as const, path: '.attachments/secret.png' },
{ kind: 'asset' as const, path: 'brain/.private/diagram.svg' },
];
- expect(filterVisibleEntries(entries, true)).toEqual(entries);
+ expect(filterVisibleEntries(entries, { showHiddenFiles: true })).toEqual(entries);
});
test('showHiddenFiles=true still rejects empty-ref entries', () => {
@@ -191,7 +213,7 @@ describe('filterVisibleEntries', () => {
{ kind: 'folder' as const, path: '' },
{ kind: 'document' as const, docName: 'README' },
],
- true,
+ { showHiddenFiles: true },
),
).toEqual([{ kind: 'document', docName: 'README' }]);
});
@@ -202,10 +224,10 @@ describe('filterVisibleEntries', () => {
{ kind: 'folder' as const, path: '.claude' },
{ kind: 'document' as const, docName: 'brain/.archived/note' },
];
- const onceTrue = filterVisibleEntries(entries, true);
- expect(filterVisibleEntries(onceTrue, true)).toEqual(onceTrue);
- const onceFalse = filterVisibleEntries(entries, false);
- expect(filterVisibleEntries(onceFalse, false)).toEqual(onceFalse);
+ const onceTrue = filterVisibleEntries(entries, { showHiddenFiles: true });
+ expect(filterVisibleEntries(onceTrue, { showHiddenFiles: true })).toEqual(onceTrue);
+ const onceFalse = filterVisibleEntries(entries, { showHiddenFiles: false });
+ expect(filterVisibleEntries(onceFalse, { showHiddenFiles: false })).toEqual(onceFalse);
});
test('showHiddenFiles=true → false transition produces today behavior (no leak)', () => {
@@ -213,13 +235,265 @@ describe('filterVisibleEntries', () => {
{ kind: 'document' as const, docName: 'README' },
{ kind: 'folder' as const, path: '.claude' },
];
- const expanded = filterVisibleEntries(entries, true);
+ const expanded = filterVisibleEntries(entries, { showHiddenFiles: true });
expect(expanded).toEqual(entries);
- const reduced = filterVisibleEntries(expanded, false);
+ const reduced = filterVisibleEntries(expanded, { showHiddenFiles: false });
expect(reduced).toEqual([{ kind: 'document', docName: 'README' }]);
});
});
+/**
+ * Axis composition for the sidebar visibility model: one orthogonal axis per
+ * toggle, composed by AND, all-off defaults reproduce the long-standing
+ * hidden-only filter. Each test walks one object class through the
+ * hidden-files × only-markdown grid so a regression in a single cell names
+ * the exact class that broke.
+ */
+describe('filterVisibleEntries — axis composition', () => {
+ type Axes = NonNullable<Parameters<typeof filterVisibleEntries>[1]>;
+ const shows = (
+ entry: { kind?: unknown; docName?: string; path?: string },
+ axes?: Axes,
+ ): boolean => filterVisibleEntries([entry], axes).length === 1;
+
+ const visibleDoc = { kind: 'document' as const, docName: 'notes/todo' };
+ const visibleAsset = { kind: 'asset' as const, path: 'src/main.rs' };
+ const visibleWireFile = { kind: 'file' as const, path: 'LICENSE' };
+ const dotDoc = { kind: 'document' as const, docName: '.scratch/note' };
+ const dotAsset = { kind: 'asset' as const, path: '.scratch/data.csv' };
+ const visibleFolder = { kind: 'folder' as const, path: 'guides' };
+ const dotFolder = { kind: 'folder' as const, path: '.scratch' };
+
+ test('visible markdown doc passes every hidden-files × only-markdown cell', () => {
+ expect(shows(visibleDoc, {})).toBe(true);
+ expect(shows(visibleDoc, { showHiddenFiles: true })).toBe(true);
+ expect(shows(visibleDoc, { showOnlyMarkdownFiles: true })).toBe(true);
+ expect(shows(visibleDoc, { showHiddenFiles: true, showOnlyMarkdownFiles: true })).toBe(true);
+ });
+
+ test('visible non-markdown leaf hides under only-markdown regardless of hidden-files', () => {
+ for (const leaf of [visibleAsset, visibleWireFile]) {
+ expect(shows(leaf, {})).toBe(true);
+ expect(shows(leaf, { showHiddenFiles: true })).toBe(true);
+ expect(shows(leaf, { showOnlyMarkdownFiles: true })).toBe(false);
+ expect(shows(leaf, { showHiddenFiles: true, showOnlyMarkdownFiles: true })).toBe(false);
+ }
+ });
+
+ test('dot-path markdown doc follows hidden-files; only-markdown keeps it', () => {
+ expect(shows(dotDoc, {})).toBe(false);
+ expect(shows(dotDoc, { showHiddenFiles: true })).toBe(true);
+ expect(shows(dotDoc, { showOnlyMarkdownFiles: true })).toBe(false);
+ expect(shows(dotDoc, { showHiddenFiles: true, showOnlyMarkdownFiles: true })).toBe(true);
+ });
+
+ test('dot-path non-markdown leaf shows only when hidden-files is on and only-markdown off', () => {
+ expect(shows(dotAsset, {})).toBe(false);
+ expect(shows(dotAsset, { showHiddenFiles: true })).toBe(true);
+ expect(shows(dotAsset, { showOnlyMarkdownFiles: true })).toBe(false);
+ expect(shows(dotAsset, { showHiddenFiles: true, showOnlyMarkdownFiles: true })).toBe(false);
+ });
+
+ test('folders pass the only-markdown axis unconditionally', () => {
+ expect(shows(visibleFolder, {})).toBe(true);
+ expect(shows(visibleFolder, { showHiddenFiles: true })).toBe(true);
+ expect(shows(visibleFolder, { showOnlyMarkdownFiles: true })).toBe(true);
+ expect(shows(visibleFolder, { showHiddenFiles: true, showOnlyMarkdownFiles: true })).toBe(true);
+ });
+
+ test('dot-folder follows hidden-files; its children are judged per their own axes', () => {
+ expect(shows(dotFolder, {})).toBe(false);
+ expect(shows(dotFolder, { showOnlyMarkdownFiles: true })).toBe(false);
+ expect(shows(dotFolder, { showHiddenFiles: true })).toBe(true);
+ const both = { showHiddenFiles: true, showOnlyMarkdownFiles: true };
+ expect(shows(dotFolder, both)).toBe(true);
+ expect(shows(dotDoc, both)).toBe(true);
+ expect(shows(dotAsset, both)).toBe(false);
+ });
+
+ const okRootFolder = { kind: 'folder' as const, path: '.ok' };
+ const okTemplateDoc = { kind: 'document' as const, docName: '.ok/templates/meeting-notes' };
+ const okConfigAsset = { kind: 'asset' as const, path: '.ok/config.yml' };
+ const nestedOkDoc = { kind: 'document' as const, docName: 'docs/.ok/templates/spec' };
+ const dotAncestorOkDoc = { kind: 'document' as const, docName: '.scratch/.ok/wip' };
+
+ test('hidden-files on never reveals .ok entries — show-ok alone governs them', () => {
+ for (const entry of [okRootFolder, okTemplateDoc, okConfigAsset, nestedOkDoc]) {
+ expect(shows(entry, { showHiddenFiles: true })).toBe(false);
+ }
+ });
+
+ test('show-ok reveals root and per-folder .ok entries without hidden-files', () => {
+ const okOn = { showOkFolders: true };
+ expect(shows(okRootFolder, okOn)).toBe(true);
+ expect(shows(okTemplateDoc, okOn)).toBe(true);
+ expect(shows(okConfigAsset, okOn)).toBe(true);
+ expect(shows(nestedOkDoc, okOn)).toBe(true);
+ expect(shows(dotDoc, okOn)).toBe(false);
+ });
+
+ test('only-markdown composes inside a revealed .ok', () => {
+ const okMd = { showOkFolders: true, showOnlyMarkdownFiles: true };
+ expect(shows(okTemplateDoc, okMd)).toBe(true);
+ expect(shows(okConfigAsset, okMd)).toBe(false);
+ expect(shows(okRootFolder, okMd)).toBe(true);
+ });
+
+ test('a dot-segment ancestor above the .ok segment still follows hidden-files', () => {
+ expect(shows(dotAncestorOkDoc, { showOkFolders: true })).toBe(false);
+ expect(shows(dotAncestorOkDoc, { showOkFolders: true, showHiddenFiles: true })).toBe(true);
+ });
+
+ test('.ok entries never appear under default axes', () => {
+ expect(filterVisibleEntries([okRootFolder, okTemplateDoc, nestedOkDoc])).toEqual([]);
+ });
+
+ test('empty refs stay rejected with every axis on', () => {
+ expect(
+ filterVisibleEntries([{ kind: 'document' as const, docName: '' }], {
+ showHiddenFiles: true,
+ showOnlyMarkdownFiles: true,
+ showOkFolders: true,
+ }),
+ ).toEqual([]);
+ });
+
+ test('default axes reproduce the pre-axis filter output exactly', () => {
+ const entries = [
+ visibleDoc,
+ visibleAsset,
+ visibleWireFile,
+ visibleFolder,
+ dotDoc,
+ dotFolder,
+ { kind: 'asset' as const, path: 'opencode.json' },
+ okTemplateDoc,
+ { kind: 'document' as const, docName: '' },
+ ];
+ expect(filterVisibleEntries(entries)).toEqual([
+ visibleDoc,
+ visibleAsset,
+ visibleWireFile,
+ visibleFolder,
+ ]);
+ });
+});
+
+/**
+ * attributeTreeHiddenAxes — per-axis attribution for the editor's
+ * not-in-sidebar indicator. The contract mirrors filterVisibleEntries clause
+ * by clause: an axis is attributed exactly when its filter clause is what
+ * drops the entry, and refs outside the tree's domain (managed-artifact
+ * names, `.ok` paths) attribute nothing — blaming a toggle that cannot
+ * reveal them would be a lie.
+ */
+describe('attributeTreeHiddenAxes', () => {
+ const none = { hiddenFiles: false, onlyMarkdownFiles: false };
+
+ test('dot-path markdown doc attributes hidden-files at defaults', () => {
+ expect(attributeTreeHiddenAxes({ kind: 'document', docName: '.scratch/note' })).toEqual({
+ hiddenFiles: true,
+ onlyMarkdownFiles: false,
+ });
+ });
+
+ test('dot-path markdown doc attributes nothing once hidden-files is on', () => {
+ expect(
+ attributeTreeHiddenAxes(
+ { kind: 'document', docName: '.scratch/note' },
+ { showHiddenFiles: true },
+ ),
+ ).toEqual(none);
+ });
+
+ test('non-markdown file attributes only-markdown when the toggle is on', () => {
+ expect(
+ attributeTreeHiddenAxes({ kind: 'asset', path: 'data.csv' }, { showOnlyMarkdownFiles: true }),
+ ).toEqual({ hiddenFiles: false, onlyMarkdownFiles: true });
+ });
+
+ test('non-markdown file attributes nothing at defaults', () => {
+ expect(attributeTreeHiddenAxes({ kind: 'asset', path: 'data.csv' })).toEqual(none);
+ });
+
+ test('dot-path non-markdown file attributes both axes; flipping one leaves the other', () => {
+ const entry = { kind: 'asset' as const, path: '.scratch/data.csv' };
+ expect(attributeTreeHiddenAxes(entry, { showOnlyMarkdownFiles: true })).toEqual({
+ hiddenFiles: true,
+ onlyMarkdownFiles: true,
+ });
+ expect(
+ attributeTreeHiddenAxes(entry, { showHiddenFiles: true, showOnlyMarkdownFiles: true }),
+ ).toEqual({ hiddenFiles: false, onlyMarkdownFiles: true });
+ expect(attributeTreeHiddenAxes(entry, { showHiddenFiles: true })).toEqual(none);
+ });
+
+ test('visible markdown doc attributes nothing in every axis cell', () => {
+ const entry = { kind: 'document' as const, docName: 'notes/todo' };
+ for (const showHiddenFiles of [false, true]) {
+ for (const showOnlyMarkdownFiles of [false, true]) {
+ expect(attributeTreeHiddenAxes(entry, { showHiddenFiles, showOnlyMarkdownFiles })).toEqual(
+ none,
+ );
+ }
+ }
+ });
+
+ test('.ok paths attribute nothing — the O axis alone governs them', () => {
+ for (const ref of ['.ok/skills/writer/SKILL', '.ok/templates/meeting', 'docs/.ok/config.yml']) {
+ expect(attributeTreeHiddenAxes({ kind: 'document', docName: ref })).toEqual(none);
+ expect(
+ attributeTreeHiddenAxes(
+ { kind: 'asset', path: ref },
+ { showHiddenFiles: false, showOnlyMarkdownFiles: true },
+ ),
+ ).toEqual(none);
+ }
+ });
+
+ test('managed-artifact doc names attribute nothing, even with dot segments inside', () => {
+ // The template form embeds its owning folder, which can itself be a dot
+ // path — without the managed-name guard that would misattribute
+ // hidden-files to a doc that never has a tree row.
+ for (const ref of ['__skill__/global/writer', '__template__/.private/meeting-notes']) {
+ expect(attributeTreeHiddenAxes({ kind: 'document', docName: ref })).toEqual(none);
+ expect(
+ attributeTreeHiddenAxes(
+ { kind: 'document', docName: ref },
+ { showOnlyMarkdownFiles: true },
+ ),
+ ).toEqual(none);
+ }
+ });
+
+ test('empty refs attribute nothing', () => {
+ expect(attributeTreeHiddenAxes({ kind: 'document', docName: '' })).toEqual(none);
+ });
+
+ test('agrees with filterVisibleEntries: axes attributed ⇔ the filter drops the entry', () => {
+ const entries = [
+ { kind: 'document' as const, docName: 'notes/todo' },
+ { kind: 'document' as const, docName: '.scratch/note' },
+ { kind: 'asset' as const, path: 'data.csv' },
+ { kind: 'asset' as const, path: '.scratch/data.csv' },
+ { kind: 'file' as const, path: 'LICENSE' },
+ { kind: 'folder' as const, path: 'guides' },
+ { kind: 'folder' as const, path: '.scratch' },
+ { kind: 'asset' as const, path: 'opencode.json' },
+ ];
+ for (const entry of entries) {
+ for (const showHiddenFiles of [false, true]) {
+ for (const showOnlyMarkdownFiles of [false, true]) {
+ const axes = { showHiddenFiles, showOnlyMarkdownFiles };
+ const attributed = attributeTreeHiddenAxes(entry, axes);
+ const dropped = filterVisibleEntries([entry], axes).length === 0;
+ expect(attributed.hiddenFiles || attributed.onlyMarkdownFiles).toBe(dropped);
+ }
+ }
+ }
+ });
+});
+
/**
* toFileEntries — the wire→sidebar boundary. Fixtures go through the real
* schema parse so the test exercises exactly the handoff the FileTree fetch
@@ -372,3 +646,70 @@ describe('toFileEntries', () => {
expect(toFileEntries(malformed)).toEqual([]);
});
});
+
+/**
+ * classifyEmptyTree — the filtered-vs-truly-empty split behind the tree's
+ * empty slot. Callers invoke it only once the rendered (filtered) tree is
+ * empty; the classifier decides which empty state that is from the two
+ * unfiltered-nonempty signals (pre-filter root listing count, indexed page
+ * set) plus the active axes.
+ */
+describe('classifyEmptyTree', () => {
+ test('only-markdown hiding a non-empty root listing classifies filtered-to-zero', () => {
+ expect(
+ classifyEmptyTree({
+ visibility: { showOnlyMarkdownFiles: true },
+ unfilteredRootEntryCount: 3,
+ knownPageCount: 0,
+ }),
+ ).toBe('filtered-to-zero');
+ });
+
+ test('the indexed page set alone marks the project non-empty', () => {
+ expect(
+ classifyEmptyTree({
+ visibility: { showOnlyMarkdownFiles: true },
+ unfilteredRootEntryCount: 0,
+ knownPageCount: 2,
+ }),
+ ).toBe('filtered-to-zero');
+ });
+
+ test('no entries from either signal is true-empty regardless of toggles', () => {
+ expect(
+ classifyEmptyTree({
+ visibility: { showHiddenFiles: true, showOnlyMarkdownFiles: true },
+ unfilteredRootEntryCount: 0,
+ knownPageCount: 0,
+ }),
+ ).toBe('true-empty');
+ });
+
+ test('defaults keep the pre-feature empty state: a dot-only project is true-empty', () => {
+ // With every axis at its default, an empty render means every listing
+ // entry is default-hidden (dot paths) — the long-standing "No files yet"
+ // state. Resetting toggles to defaults could not change it, so the reset
+ // affordance must not be offered.
+ expect(classifyEmptyTree({ unfilteredRootEntryCount: 4, knownPageCount: 4 })).toBe(
+ 'true-empty',
+ );
+ });
+
+ test('reveal-only axes never classify filtered-to-zero', () => {
+ for (const visibility of [{ showHiddenFiles: true }, { showOkFolders: true }]) {
+ expect(
+ classifyEmptyTree({ visibility, unfilteredRootEntryCount: 2, knownPageCount: 0 }),
+ ).toBe('true-empty');
+ }
+ });
+
+ test('hidden-files on does not neutralize the only-markdown classification', () => {
+ expect(
+ classifyEmptyTree({
+ visibility: { showHiddenFiles: true, showOnlyMarkdownFiles: true },
+ unfilteredRootEntryCount: 1,
+ knownPageCount: 0,
+ }),
+ ).toBe('filtered-to-zero');
+ });
+});
diff --git a/packages/app/src/components/file-tree-utils.ts b/packages/app/src/components/file-tree-utils.ts
index a7d04cc04..afa28a79b 100644
--- a/packages/app/src/components/file-tree-utils.ts
+++ b/packages/app/src/components/file-tree-utils.ts
@@ -4,6 +4,7 @@ import {
type DocumentListEntry,
type InlineAssetMediaKind,
isHiddenDocName,
+ isManagedArtifactDocName,
} from '@inkeep/open-knowledge-core';
export interface DocumentEntry {
@@ -214,29 +215,167 @@ export function defaultInitialDir(activeDocName: string | null): string {
}
/**
- * Sidebar render-set filter. By default drops any entry the shared
- * `isHiddenDocName` predicate classifies as hidden — a dot-segment at any depth
- * (parallel to EmptyEditorState.countEntries()'s onboarding gate), or a
- * well-known non-dotted agent config (`HIDDEN_CONFIG_BASENAMES`, e.g.
- * `opencode.json`). Delegating to the core predicate keeps the sidebar in
- * lockstep with search ranking + agent egress, which classify hidden the same
- * way. When `showHiddenFiles` is true the hidden branch is bypassed — server
- * filters (`.gitignore` / `.okignore` / `BUILTIN_SKIP_DIRS`) still apply, so
- * `.git/`, `.ok/`, `node_modules/` stay hidden. The toggle recovers
- * user-authored hidden entries that the server ships (e.g.
- * `brain/.archived/note.md`) but the client today hides.
+ * Sidebar visibility toggles — one orthogonal axis per field, composed by
+ * AND. Every axis defaults to off, and the all-off output is exactly the
+ * long-standing hidden-only filter, so zero-config callers keep today's
+ * behavior.
+ */
+interface TreeVisibility {
+ /**
+ * Reveal entries the shared `isHiddenDocName` predicate classifies as
+ * hidden (dot-segment paths, well-known agent configs). Never reveals
+ * `.ok` — that is `showOkFolders`' axis alone.
+ */
+ showHiddenFiles?: boolean;
+ /**
+ * Keep only markdown docs and folders; every other leaf drops. In this
+ * data model client `kind:'document'` holds exactly the on-disk
+ * `.md`/`.mdx` files, so the kind check is the extension filter.
+ */
+ showOnlyMarkdownFiles?: boolean;
+ /**
+ * Reveal entries under a `.ok` path segment (OK-managed state: skills,
+ * templates, folder metadata). The only axis that governs them.
+ */
+ showOkFolders?: boolean;
+}
+
+/**
+ * Sidebar render-set filter. With every axis off (the default) it drops
+ * exactly the entries the shared `isHiddenDocName` predicate classifies as
+ * hidden — a dot-segment at any depth (parallel to
+ * EmptyEditorState.countEntries()'s onboarding gate), or a well-known
+ * non-dotted agent config (`HIDDEN_CONFIG_BASENAMES`, e.g. `opencode.json`).
+ * Delegating to the core predicate keeps the sidebar in lockstep with search
+ * ranking + agent egress, which classify hidden the same way.
+ *
+ * `showHiddenFiles` bypasses that hidden branch — server filters
+ * (`.gitignore` / `.okignore` / `BUILTIN_SKIP_DIRS`) still apply, so `.git/`
+ * and `node_modules/` stay out regardless. It recovers user-authored hidden
+ * entries the server ships (e.g. `brain/.archived/note.md`) but the client
+ * hides by default.
+ *
+ * `.ok`-segment entries are carved out of that bypass: they are OK-managed
+ * state, not user-authored dotfiles, and listings can carry them (the index
+ * admits `.ok/skills/**` docs). Only `showOkFolders` admits them — with the
+ * one composition seam that a dot-segment ancestor ABOVE the `.ok` segment
+ * still follows `showHiddenFiles`, so revealing `.ok` never drags a hidden
+ * parent folder into view.
*
* Empty-string `ref` is always rejected — surfaces a stray entry shipped
* without a docName/path.
*/
+/**
+ * Whether a docName / path sits under the OK-managed `.ok` directory (a
+ * `.ok` segment at any depth). One predicate for every consumer — the
+ * render-set filter, the indicator attribution, click routing, and the
+ * doc-open guard must all agree on what counts as OK-managed.
+ *
+ * Case-insensitive to mirror the server's reserved-path guard: on the
+ * case-insensitive filesystems OK primarily runs on, `.OK/x` addresses the
+ * same directory as `.ok/x`, so the client gates must treat the variants
+ * identically or the two layers disagree about what is read-only.
+ */
+export function hasOkPathSegment(ref: string): boolean {
+ return ref.split('/').some((segment) => segment.toLowerCase() === '.ok');
+}
+
+/**
+ * Only-markdown axis clause: drops every leaf that is not a markdown doc or a
+ * folder. Shared verbatim by the render-set filter and the indicator's
+ * attribution so the two can never judge the axis differently.
+ */
+function failsOnlyMarkdownAxis(kind: unknown, showOnlyMarkdownFiles: boolean): boolean {
+ return showOnlyMarkdownFiles && kind !== 'document' && kind !== 'folder';
+}
+
+/** Hidden-files axis clause for refs outside a `.ok` subtree. */
+function failsHiddenFilesAxis(ref: string, showHiddenFiles: boolean): boolean {
+ return !showHiddenFiles && isHiddenDocName(ref);
+}
+
export function filterVisibleEntries<T extends { kind?: unknown; docName?: string; path?: string }>(
entries: ReadonlyArray<T>,
- showHiddenFiles = false,
+ visibility: TreeVisibility = {},
): T[] {
+ const {
+ showHiddenFiles = false,
+ showOnlyMarkdownFiles = false,
+ showOkFolders = false,
+ } = visibility;
return entries.filter((entry) => {
const ref = entry.docName ?? entry.path ?? '';
if (ref === '') return false;
- if (showHiddenFiles) return true;
- return !isHiddenDocName(ref);
+ if (failsOnlyMarkdownAxis(entry.kind, showOnlyMarkdownFiles)) {
+ return false;
+ }
+ const segments = ref.split('/');
+ const okIndex = segments.indexOf('.ok');
+ if (okIndex !== -1) {
+ if (!showOkFolders) return false;
+ const ancestorPath = segments.slice(0, okIndex).join('/');
+ return showHiddenFiles || ancestorPath === '' || !isHiddenDocName(ancestorPath);
+ }
+ return !failsHiddenFilesAxis(ref, showHiddenFiles);
});
}
+
+/**
+ * Which visibility axes currently keep `entry` out of the sidebar tree —
+ * the attribution behind the editor's not-in-sidebar indicator, one field
+ * per user-flippable toggle. Judged clause-for-clause against
+ * `filterVisibleEntries`: an axis is attributed exactly when its clause is
+ * what drops the entry, so "some axis attributed" ⇔ "the filter drops it"
+ * for every ref the axes govern (test-pinned).
+ *
+ * Refs outside those axes' domain attribute nothing: managed-artifact names
+ * (skills/templates, which never have a tree row) and `.ok` paths (governed
+ * by `showOkFolders` alone) — an indicator naming Hidden files / Only
+ * markdown files for them would point at toggles that cannot reveal them.
+ */
+export function attributeTreeHiddenAxes(
+ entry: { kind?: unknown; docName?: string; path?: string },
+ visibility: TreeVisibility = {},
+): { hiddenFiles: boolean; onlyMarkdownFiles: boolean } {
+ const { showHiddenFiles = false, showOnlyMarkdownFiles = false } = visibility;
+ const ref = entry.docName ?? entry.path ?? '';
+ if (ref === '' || isManagedArtifactDocName(ref) || hasOkPathSegment(ref)) {
+ return { hiddenFiles: false, onlyMarkdownFiles: false };
+ }
+ return {
+ hiddenFiles: failsHiddenFilesAxis(ref, showHiddenFiles),
+ onlyMarkdownFiles: failsOnlyMarkdownAxis(entry.kind, showOnlyMarkdownFiles),
+ };
+}
+
+/**
+ * Which empty state a rendered-empty tree is in. Call only once the filtered
+ * render set is empty — the classifier then splits "the project has nothing
+ * to show" (the long-standing `No files yet` state) from "the active view
+ * filters hide everything" (an explainer with a reset-to-defaults action).
+ *
+ * The filtered `documents` state cannot make this call by itself (raw
+ * listings are not retained), so the split reads the two unfiltered-nonempty
+ * signals that do flow client-side: the pre-filter count of the depth-1 root
+ * listing, and the indexed markdown page set.
+ *
+ * `showHiddenFiles` and `showOkFolders` are reveal-only — each merely
+ * bypasses a default-hidden branch of `filterVisibleEntries` — so
+ * `showOnlyMarkdownFiles` is the single axis that can hide entries the
+ * defaults would show. Without it, an empty render is what the defaults
+ * produce (dot-only projects render empty by long-standing design), and a
+ * reset to defaults could not change it: that state stays true-empty.
+ */
+export function classifyEmptyTree(input: {
+ visibility?: TreeVisibility;
+ /** Pre-filter entry count of the most recent depth-1 root listing. */
+ unfilteredRootEntryCount: number;
+ /** Size of the indexed markdown page set (PageListContext `pages`). */
+ knownPageCount: number;
+}): 'true-empty' | 'filtered-to-zero' {
+ const { visibility = {}, unfilteredRootEntryCount, knownPageCount } = input;
+ const projectHasEntries = unfilteredRootEntryCount > 0 || knownPageCount > 0;
+ return projectHasEntries && (visibility.showOnlyMarkdownFiles ?? false)
+ ? 'filtered-to-zero'
+ : 'true-empty';
+}
diff --git a/packages/app/src/components/navigation-targets.test.ts b/packages/app/src/components/navigation-targets.test.ts
index 451e77281..fd42aff56 100644
--- a/packages/app/src/components/navigation-targets.test.ts
+++ b/packages/app/src/components/navigation-targets.test.ts
@@ -5,6 +5,7 @@ import {
docNameForNavigationTarget,
downgradeFolderIndexForHashNav,
largeFileNavigationTarget,
+ okContentNavigationTarget,
resolveNavigationTarget,
withLargeFileOpenGuard,
} from './navigation-targets';
@@ -344,6 +345,138 @@ describe('resolveNavigationTarget', () => {
});
});
+describe('okContentNavigationTarget (read-only .ok routing)', () => {
+ const pages = new Set(['notes/real', '.ok/skills/writer/SKILL']);
+
+ test('targets without a .ok path segment are not governed', () => {
+ expect(okContentNavigationTarget('notes/real', { pages })).toBeNull();
+ expect(okContentNavigationTarget('brand-new/idea', { pages })).toBeNull();
+ // A plain `ok` segment is a user folder, not the managed directory.
+ expect(okContentNavigationTarget('docs/ok/guide', { pages })).toBeNull();
+ });
+
+ test('template file paths rewrite to the managed-artifact template editor', () => {
+ expect(okContentNavigationTarget('.ok/templates/meeting', { pages })).toEqual({
+ kind: 'doc',
+ target: '__template__/meeting',
+ docName: '__template__/meeting',
+ });
+ expect(okContentNavigationTarget('team/.ok/templates/spec', { pages })).toEqual({
+ kind: 'doc',
+ target: '__template__/team/spec',
+ docName: '__template__/team/spec',
+ });
+ });
+
+ test('page-list members stay normal content docs (skills carve-out)', () => {
+ expect(okContentNavigationTarget('.ok/skills/writer/SKILL', { pages })).toBeNull();
+ });
+
+ test('doc-shaped .ok targets resolve to the read-only text viewer on their .md path', () => {
+ expect(okContentNavigationTarget('.ok/raw-probe', { pages })).toEqual({
+ kind: 'asset',
+ target: '.ok/raw-probe.md',
+ assetPath: '.ok/raw-probe.md',
+ mediaKind: 'text',
+ });
+ expect(okContentNavigationTarget('notes/.ok/frontmatter', { pages })).toEqual({
+ kind: 'asset',
+ target: 'notes/.ok/frontmatter.md',
+ assetPath: 'notes/.ok/frontmatter.md',
+ mediaKind: 'text',
+ });
+ });
+
+ test('a known on-disk extension overrides the .md default', () => {
+ expect(okContentNavigationTarget('.ok/templates/a/b', { pages, docExt: '.mdx' })).toEqual({
+ kind: 'asset',
+ target: '.ok/templates/a/b.mdx',
+ assetPath: '.ok/templates/a/b.mdx',
+ mediaKind: 'text',
+ });
+ });
+
+ test('nested template paths are not template files — they land on the viewer', () => {
+ // The template rewrite only matches single-segment leaves; a nested path
+ // must not fall through to an editable resolution.
+ expect(okContentNavigationTarget('.ok/templates/a/b', { pages })).toMatchObject({
+ kind: 'asset',
+ assetPath: '.ok/templates/a/b.md',
+ });
+ });
+
+ test('extension-carrying .ok leaves resolve as their own asset path', () => {
+ expect(okContentNavigationTarget('.ok/config.yml', { pages })).toEqual({
+ kind: 'asset',
+ target: '.ok/config.yml',
+ assetPath: '.ok/config.yml',
+ mediaKind: 'text',
+ });
+ expect(okContentNavigationTarget('.ok/assets/logo.png', { pages })).toMatchObject({
+ kind: 'asset',
+ assetPath: '.ok/assets/logo.png',
+ mediaKind: 'image',
+ });
+ });
+
+ test('worktrees and local paths land read-only even though listings exclude them', () => {
+ for (const target of ['.ok/worktrees/checkout/README', '.ok/local/config.yml']) {
+ expect(okContentNavigationTarget(target, { pages })?.kind).toBe('asset');
+ }
+ });
+});
+
+describe('resolveNavigationTarget .ok guard', () => {
+ const options = { pages: new Set(['notes/real', '.ok/skills/writer/SKILL']) };
+
+ test('.ok targets never resolve to missing — the viewer replaces create-mode', () => {
+ // Existing file and nonexistent name are unknowable at resolve time; both
+ // shapes must land on the read-only viewer (its error pane is the
+ // non-create missing surface), never on the create-mode editor.
+ expect(resolveNavigationTarget('.ok/raw-probe', options)).toEqual({
+ kind: 'asset',
+ target: '.ok/raw-probe.md',
+ assetPath: '.ok/raw-probe.md',
+ mediaKind: 'text',
+ });
+ expect(resolveNavigationTarget('notes/.ok/frontmatter', options)).toMatchObject({
+ kind: 'asset',
+ assetPath: 'notes/.ok/frontmatter.md',
+ });
+ expect(resolveNavigationTarget('.ok/worktrees/checkout/README', options)).toMatchObject({
+ kind: 'asset',
+ });
+ });
+
+ test('sanctioned .ok resolutions are unchanged: skills stay docs, templates rewrite', () => {
+ expect(resolveNavigationTarget('.ok/skills/writer/SKILL', options)).toEqual({
+ kind: 'doc',
+ target: '.ok/skills/writer/SKILL',
+ docName: '.ok/skills/writer/SKILL',
+ });
+ expect(resolveNavigationTarget('.ok/templates/meeting', options)).toEqual({
+ kind: 'doc',
+ target: '__template__/meeting',
+ docName: '__template__/meeting',
+ });
+ });
+
+ test('.ok folder targets keep resolving to the folder overview', () => {
+ expect(resolveNavigationTarget('.ok', options)).toEqual({
+ kind: 'folder',
+ target: '.ok',
+ folderPath: '.ok',
+ });
+ });
+
+ test('non-.ok misses keep the create-mode missing resolution', () => {
+ expect(resolveNavigationTarget('brand-new/idea', options)).toEqual({
+ kind: 'missing',
+ target: 'brand-new/idea',
+ });
+ });
+});
+
describe('docNameForNavigationTarget', () => {
test('returns null for folder targets so folder navigation stays doc-free', () => {
expect(
diff --git a/packages/app/src/components/navigation-targets.ts b/packages/app/src/components/navigation-targets.ts
index 7f5ff82ad..3ae9d708e 100644
--- a/packages/app/src/components/navigation-targets.ts
+++ b/packages/app/src/components/navigation-targets.ts
@@ -5,6 +5,7 @@ import {
isManagedArtifactDocName,
isMermaidDocFile,
managedArtifactDocNameFromContentTarget,
+ mediaKindForSidebarAssetExtension,
parseGlobalSkillBundleDoc,
parseManagedArtifactName,
projectSkillContentDocName,
@@ -12,7 +13,7 @@ import {
toWikiLinkSlug,
} from '@inkeep/open-knowledge-core';
import { normalizeDocNameInput } from '@/lib/doc-paths';
-import { computeAncestors } from './file-tree-utils';
+import { computeAncestors, hasOkPathSegment } from './file-tree-utils';
export type ResolvedNavigationTarget =
| {
@@ -134,6 +135,66 @@ function basenameResolve(
return pagesByBasename.get(slug);
}
+/**
+ * The on-disk file a doc-shaped `.ok` target addresses. A leaf that already
+ * carries an extension (`config.yml`) is the file itself; an extension-less
+ * leaf maps to its markdown file — the same `.md` the create-mode editor
+ * would have lazily written, so the viewer shows exactly the bytes the old
+ * write path would have touched. A leading dot alone (`.env`) is not an
+ * extension.
+ */
+function okReadOnlyAssetPath(docName: string, docExt?: string): string {
+ if (docExt) return `${docName}${docExt}`;
+ const leaf = docName.split('/').pop() ?? '';
+ return leaf.lastIndexOf('.') > 0 ? docName : `${docName}.md`;
+}
+
+/**
+ * Read-only routing for content targets under a `.ok` path segment — the
+ * doc-open guard that keeps OK-managed state out of editable and create-mode
+ * editors. Raw `.ok/**` docNames are loadable as editable CRDT docs by
+ * construction (persistence has no content-filter gate), so every doc-shaped
+ * resolution of a `.ok` target must land on a sanctioned surface:
+ *
+ * - Template FILE paths (`[<folder>/].ok/templates/<name>`, single-segment
+ * leaf) rewrite to their managed-artifact doc — the validating template
+ * editor. Same rule the wiki-link resolver already applies.
+ * - Page-list members (the `.ok/skills/**` carve-out) return null: they are
+ * sanctioned content docs and keep the normal doc flow (the skill editor
+ * chrome keys off the docName).
+ * - Everything else resolves to the read-only text viewer on the file's
+ * on-disk path; for a nonexistent file the viewer's error pane is the
+ * non-create "missing" surface.
+ *
+ * Returns null for targets outside `.ok`. Pure docName-shape rule plus
+ * page-list membership — consumes NO visibility state, so navigation stays
+ * visibility-blind.
+ */
+export function okContentNavigationTarget(
+ docName: string,
+ options: { pages: ReadonlySet<string>; docExt?: string },
+): ResolvedNavigationTarget | null {
+ if (!hasOkPathSegment(docName)) return null;
+ const artifactDocName = managedArtifactDocNameFromContentTarget(docName);
+ if (artifactDocName) {
+ return { kind: 'doc', target: artifactDocName, docName: artifactDocName };
+ }
+ if (options.pages.has(docName)) return null;
+ const assetPath = okReadOnlyAssetPath(docName, options.docExt);
+ // Serve asymmetry behind this target: text-shaped `.ok` files render fully
+ // (the text viewer fetches `/api/asset-text`, which has no content-filter
+ // gate), but binary/media kinds (image, pdf, video) fetch `/api/asset`,
+ // whose `isPathIgnored` gate keeps the `.ok` floor — their preview 404s by
+ // design. The `.ok` reveal is enumeration-only and never widens asset
+ // serving.
+ return {
+ kind: 'asset',
+ target: assetPath,
+ assetPath,
+ mediaKind: mediaKindForSidebarAssetExtension(assetPath.slice(assetPath.lastIndexOf('.') + 1)),
+ };
+}
+
export function resolveNavigationTarget(
target: string,
options: {
@@ -276,10 +337,14 @@ export function resolveNavigationTarget(
};
}
- return {
- kind: 'missing',
- target: extensionlessTarget || normalizedTarget,
- };
+ // A missing `.ok` target must not fall through to the create-mode editor —
+ // route it to the read-only viewer instead (see okContentNavigationTarget).
+ return (
+ okContentNavigationTarget(normalizedTarget, options) ?? {
+ kind: 'missing',
+ target: extensionlessTarget || normalizedTarget,
+ }
+ );
}
/**
diff --git a/packages/app/src/components/use-selection-mirror.ts b/packages/app/src/components/use-selection-mirror.ts
index 3e1da6d4c..f662812b1 100644
--- a/packages/app/src/components/use-selection-mirror.ts
+++ b/packages/app/src/components/use-selection-mirror.ts
@@ -22,6 +22,12 @@ function selectOnlyTreeItem(
}
}
+function deselectAllTreeItems(model: PierreFileTreeModel): void {
+ for (const selectedPath of model.getSelectedPaths()) {
+ model.getItem(selectedPath)?.deselect();
+ }
+}
+
export function useSelectionMirror(
model: PierreFileTreeModel,
activeTreePath: string | null,
@@ -50,9 +56,7 @@ export function useSelectionMirror(
};
suppressSelectionRef.current = true;
if (!activeTreePath) {
- for (const selectedPath of model.getSelectedPaths()) {
- model.getItem(selectedPath)?.deselect();
- }
+ deselectAllTreeItems(model);
releaseSelectionSuppression();
return;
}
@@ -67,6 +71,13 @@ export function useSelectionMirror(
}
const item = model.getItem(activeTreePath);
if (!item) {
+ // The active doc has no visible row (filtered out, or not fetched yet).
+ // Keep the tree quiet: clear any stale selection left on the previously
+ // active row instead of letting its highlight linger next to an editor
+ // showing a different doc. Focus cannot be cleared the same way — Pierre
+ // has no unfocus API — so the stale focused path is neutralized by the
+ // active-row guard in `revealActiveRow` rather than here.
+ deselectAllTreeItems(model);
releaseSelectionSuppression();
return;
}
diff --git a/packages/app/src/lib/desktop-bridge-types.ts b/packages/app/src/lib/desktop-bridge-types.ts
index 1f74a432c..09a11c87d 100644
--- a/packages/app/src/lib/desktop-bridge-types.ts
+++ b/packages/app/src/lib/desktop-bridge-types.ts
@@ -213,6 +213,9 @@ type OkMenuAction =
| 'copy-relative-path'
// View menu items — visibility toggles + tree-scoped expand/collapse.
| 'toggle-show-hidden-files'
+ | 'toggle-show-ok-folders'
+ | 'toggle-show-only-markdown-files'
+ | 'toggle-show-skills-section'
| 'expand-all-tree'
| 'collapse-all-tree'
| 'toggle-doc-panel'
@@ -697,6 +700,9 @@ type OkEditorActiveTargetSnapshot =
*/
interface OkEditorViewMenuStateSnapshot {
readonly showHiddenFiles: boolean;
+ readonly showOkFolders: boolean;
+ readonly showOnlyMarkdownFiles: boolean;
+ readonly showSkillsSection: boolean;
readonly canExpandAll: boolean;
readonly canCollapseAll: boolean;
readonly sidebarVisible: boolean;
diff --git a/packages/app/src/lib/onboarding-document-count.test.ts b/packages/app/src/lib/onboarding-document-count.test.ts
index d3863b3e8..9ab4e77bf 100644
--- a/packages/app/src/lib/onboarding-document-count.test.ts
+++ b/packages/app/src/lib/onboarding-document-count.test.ts
@@ -49,4 +49,20 @@ describe('countVisibleEntries', () => {
test('excludes entries that ship without a docName or path', () => {
expect(countVisibleEntries([doc(''), folder('')])).toBe(0);
});
+
+ test('sidebar view toggles cannot alter the count — the counter has no axis input', () => {
+ // Entries a view toggle could reveal (dot-path via show-hidden, .ok via
+ // show-ok) or drop (non-markdown via only-markdown) must not move the
+ // onboarding gate: the count always uses default visibility.
+ expect(
+ countVisibleEntries([
+ doc('welcome'),
+ folder('guides'),
+ doc('.scratch/wip'),
+ doc('.ok/skills/research/SKILL'),
+ asset('logo.png'),
+ file('data.csv'),
+ ]),
+ ).toBe(2);
+ });
});
diff --git a/packages/app/src/locales/en/messages.json b/packages/app/src/locales/en/messages.json
index 534a0b214..bb07546d8 100644
--- a/packages/app/src/locales/en/messages.json
+++ b/packages/app/src/locales/en/messages.json
@@ -78,6 +78,7 @@
"0wswKc": ["Horizontal rule that divides sections."],
"0xnmlQ": ["Repository name"],
"0yL--g": ["Review conflicts"],
+ "10g8I_": ["Turn off Only markdown files"],
"12F9WL": ["(no id)"],
"16D5Zj": ["Are you sure you want to delete ", ["itemName"], "? This action cannot be undone."],
"1AumWo": ["Push failed — check the server logs for details."],
@@ -221,6 +222,7 @@
],
"4zGlN_": ["Paste image URL or click upload"],
"5-FeN2": ["Share URL"],
+ "5-o4kO": ["Only markdown files"],
"54Y6Fg": ["Could not load templates. Try again later."],
"56WWtu": ["Couldn't load starter packs: ", ["error"]],
"56xUL1": ["Property name"],
@@ -285,6 +287,7 @@
"6Aih4U": ["Offline"],
"6EKG_c": ["What agents match on to decide when to use the skill."],
"6HCOwA": ["Failed to open."],
+ "6KCH4m": ["Hidden files"],
"6LbUG7": ["The repository is private and your GitHub account doesn't have access to it."],
"6MnZEC": ["Terminal failed to load"],
"6O626z": ["No headings match \"", ["trimmedAnchorQuery"], "\""],
@@ -391,6 +394,7 @@
"8uAWix": [
"This template lives in a parent folder — deleting it affects every folder beneath it that doesn't define its own version."
],
+ "8vETh9": ["Show"],
"92rbk2": ["Mirror loading <0>", ["mirrorRef"], "</0>"],
"96G6Re": ["New folder"],
"96w9hU": ["Something went wrong opening this file (HTTP ", ["status"], ")."],
@@ -601,6 +605,7 @@
"EEYbdt": ["Publish"],
"EHu0x2": ["Syncing"],
"EJuO7B": ["Connect a GitHub account to browse and sync your repositories."],
+ "ELYtNJ": [".ok folders"],
"EL_YRd": ["Mirror of <0>api-spec</0>"],
"EOjU5V": ["Inline Math Properties"],
"ETyvvg": ["No language match."],
@@ -700,6 +705,7 @@
"Give the AI tools you use access to read and update your projects. Pick what to set up below, and change it anytime."
],
"GGsM4y": ["Selected in graph"],
+ "GHsJb8": ["Show .ok folders"],
"GJH-AT": [
["docName"],
" is ",
@@ -963,6 +969,7 @@
"Choose whether this project's OpenKnowledge setup, including its AI-tool connections, is saved with the project so teammates get it too, or kept only on your computer."
],
"NEzPEh": ["Create a new branch, or check out an existing one, in its own window."],
+ "NF_Wcg": ["Show skills section"],
"NIWAux": ["No docs registered under #", ["tagDocsName"], "."],
"NJyQi_": ["Branch ", ["shareBranch"], " no longer exists on the remote."],
"NKkZXl": ["Initialize and open"],
@@ -1283,6 +1290,7 @@
],
"W8vpBM": ["starter pack"],
"W9_Bub": ["Local changes overlap with incoming sync"],
+ "WHPvOb": ["All files are hidden by view filters."],
"WL6puM": ["Path resolves outside project"],
"WMIKXK": [
"Are you sure you want to delete ",
@@ -1307,6 +1315,7 @@
"Wgmlsw": ["Fetching"],
"Wh0im4": ["editing [[", ["realCurrentDoc"], "]]"],
"WhOsNE": ["Strikethrough"],
+ "WkTLN7": ["Show only markdown files"],
"WmPbvm": ["Get product updates in your inbox."],
"Wq6Wcm": ["Please enter a valid email address."],
"WqLq6M": ["Open with AI ", ["displayName"]],
@@ -1821,8 +1830,10 @@
"iuTKci": ["No edits yet."],
"iycx_A": ["Pushing"],
"j9Vqvc": ["inherited"],
+ "j9tqwO": ["Not in sidebar"],
"jAMpHn": ["What is a starter pack?"],
"jBVUXo": ["Couldn't open the terminal — please try again."],
+ "jC8LSZ": ["Reset view filters"],
"jEZ6Lf": ["provisional"],
"jEdF24": ["Missing page: ", ["linkTitle"], ". Click to create."],
"jKd3AP": ["Could not enable the terminal: ", ["0"]],
diff --git a/packages/app/src/locales/en/messages.po b/packages/app/src/locales/en/messages.po
index b7a5dfc63..3a36351c7 100644
--- a/packages/app/src/locales/en/messages.po
+++ b/packages/app/src/locales/en/messages.po
@@ -25,6 +25,10 @@ msgstr " Your selection could not be restored."
msgid " Your selection has been restored."
msgstr " Your selection has been restored."
+#: src/components/FileSidebar.tsx
+msgid ".ok folders"
+msgstr ".ok folders"
+
#. placeholder {0}: skill.name
#. placeholder {1}: label(result.hosts)
#: src/components/skill-actions.tsx
@@ -794,6 +798,10 @@ msgstr "AI tools & CLI"
msgid "All files"
msgstr "All files"
+#: src/components/FileTreeFilteredToZeroNotice.tsx
+msgid "All files are hidden by view filters."
+msgstr "All files are hidden by view filters."
+
#: src/components/DiffView.tsx
msgid "All hunks resolved"
msgstr "All hunks resolved"
@@ -1874,7 +1882,8 @@ msgid "Could not turn off the terminal: {0}"
msgstr "Could not turn off the terminal: {0}"
#: src/components/FileSidebar.tsx
-#: src/components/FileTree.tsx
+#: src/components/FileTreeFilteredToZeroNotice.tsx
+#: src/components/NotInSidebarIndicator.tsx
msgid "Could not update sidebar settings"
msgstr "Could not update sidebar settings"
@@ -3457,6 +3466,11 @@ msgstr "Helps your coding agent recognize OpenKnowledge projects and route reads
msgid "Hidden “{basename}”"
msgstr "Hidden “{basename}”"
+#: src/components/FileSidebar.tsx
+#: src/components/NotInSidebarIndicator.tsx
+msgid "Hidden files"
+msgstr "Hidden files"
+
#: src/components/FileTree.tsx
msgid "Hidden folder “{basename}”"
msgstr "Hidden folder “{basename}”"
@@ -4735,6 +4749,10 @@ msgstr "Not connected"
msgid "Not connected to GitHub."
msgstr "Not connected to GitHub."
+#: src/components/NotInSidebarIndicator.tsx
+msgid "Not in sidebar"
+msgstr "Not in sidebar"
+
#: src/components/CommandPalette.tsx
#: src/components/handoff/OpenInAgentMenuItem.tsx
msgid "Not installed"
@@ -4824,6 +4842,11 @@ msgstr "One pattern per line — appended to <0>.okignore</0>."
msgid "Only collaborators"
msgstr "Only collaborators"
+#: src/components/FileSidebar.tsx
+#: src/components/NotInSidebarIndicator.tsx
+msgid "Only markdown files"
+msgstr "Only markdown files"
+
#: src/editor/components/TagDialog.tsx
msgid "Only the current document uses <0>#{tag}</0>."
msgstr "Only the current document uses <0>#{tag}</0>."
@@ -5842,6 +5865,10 @@ msgstr "Reset to default"
msgid "Reset view"
msgstr "Reset view"
+#: src/components/FileTreeFilteredToZeroNotice.tsx
+msgid "Reset view filters"
+msgstr "Reset view filters"
+
#: src/editor/components/ResizeHandles.tsx
msgid "Resize {handleKey}"
msgstr "Resize {handleKey}"
@@ -6353,6 +6380,14 @@ msgstr "Shared via git with everyone working on this project."
msgid "Sharing a doc needs a GitHub repository. Create one for this project."
msgstr "Sharing a doc needs a GitHub repository. Create one for this project."
+#: src/components/FileSidebar.tsx
+msgid "Show"
+msgstr "Show"
+
+#: src/components/FileSidebar.tsx
+msgid "Show .ok folders"
+msgstr "Show .ok folders"
+
#. placeholder {0}: hiddenPacks.length
#: src/components/PackCardGrid.tsx
msgid "Show {0} more"
@@ -6392,7 +6427,7 @@ msgid "Show Files ({sidebarShortcutLabel})"
msgstr "Show Files ({sidebarShortcutLabel})"
#: src/components/FileSidebar.tsx
-#: src/components/FileTree.tsx
+#: src/components/NotInSidebarIndicator.tsx
msgid "Show hidden files"
msgstr "Show hidden files"
@@ -6404,6 +6439,10 @@ msgstr "Show HTML preview"
msgid "Show less"
msgstr "Show less"
+#: src/components/FileSidebar.tsx
+msgid "Show only markdown files"
+msgstr "Show only markdown files"
+
#: src/lib/keyboard-shortcuts.ts
msgid "Show or hide document panel"
msgstr "Show or hide document panel"
@@ -6432,6 +6471,10 @@ msgstr "Show replace"
msgid "Show selection preview"
msgstr "Show selection preview"
+#: src/components/FileSidebar.tsx
+msgid "Show skills section"
+msgstr "Show skills section"
+
#: src/components/MermaidFileViewer.tsx
msgid "Show source"
msgstr "Show source"
@@ -6505,6 +6548,7 @@ msgstr "Skill level"
msgid "Skill renamed"
msgstr "Skill renamed"
+#: src/components/FileSidebar.tsx
#: src/components/settings/SettingsDialogShell.tsx
#: src/components/settings/SkillsManagerSection.tsx
#: src/components/SkillsSidebarSection.tsx
@@ -7380,6 +7424,10 @@ msgstr "Try a prompt"
msgid "Try again"
msgstr "Try again"
+#: src/components/NotInSidebarIndicator.tsx
+msgid "Turn off Only markdown files"
+msgstr "Turn off Only markdown files"
+
#: src/components/settings/SearchSection.tsx
msgid "Turn on"
msgstr "Turn on"
diff --git a/packages/app/src/locales/pseudo/messages.json b/packages/app/src/locales/pseudo/messages.json
index 8ec8e9933..db73d0583 100644
--- a/packages/app/src/locales/pseudo/messages.json
+++ b/packages/app/src/locales/pseudo/messages.json
@@ -78,6 +78,7 @@
"0wswKc": ["Ĥōŕĩźōńţàĺ ŕũĺē ţĥàţ ďĩvĩďēś śēćţĩōńś."],
"0xnmlQ": ["Ŕēƥōśĩţōŕŷ ńàḿē"],
"0yL--g": ["Ŕēvĩēŵ ćōńƒĺĩćţś"],
+ "10g8I_": ["Ţũŕń ōƒƒ Ōńĺŷ ḿàŕķďōŵń ƒĩĺēś"],
"12F9WL": ["(ńō ĩď)"],
"16D5Zj": ["Àŕē ŷōũ śũŕē ŷōũ ŵàńţ ţō ďēĺēţē ", ["itemName"], "? Ţĥĩś àćţĩōń ćàńńōţ ƀē ũńďōńē."],
"1AumWo": ["Ƥũśĥ ƒàĩĺēď — ćĥēćķ ţĥē śēŕvēŕ ĺōĝś ƒōŕ ďēţàĩĺś."],
@@ -221,6 +222,7 @@
],
"4zGlN_": ["Ƥàśţē ĩḿàĝē ŨŔĹ ōŕ ćĺĩćķ ũƥĺōàď"],
"5-FeN2": ["Śĥàŕē ŨŔĹ"],
+ "5-o4kO": ["Ōńĺŷ ḿàŕķďōŵń ƒĩĺēś"],
"54Y6Fg": ["Ćōũĺď ńōţ ĺōàď ţēḿƥĺàţēś. Ţŕŷ àĝàĩń ĺàţēŕ."],
"56WWtu": ["Ćōũĺďń'ţ ĺōàď śţàŕţēŕ ƥàćķś: ", ["error"]],
"56xUL1": ["Ƥŕōƥēŕţŷ ńàḿē"],
@@ -285,6 +287,7 @@
"6Aih4U": ["Ōƒƒĺĩńē"],
"6EKG_c": ["Ŵĥàţ àĝēńţś ḿàţćĥ ōń ţō ďēćĩďē ŵĥēń ţō ũśē ţĥē śķĩĺĺ."],
"6HCOwA": ["Ƒàĩĺēď ţō ōƥēń."],
+ "6KCH4m": ["Ĥĩďďēń ƒĩĺēś"],
"6LbUG7": ["Ţĥē ŕēƥōśĩţōŕŷ ĩś ƥŕĩvàţē àńď ŷōũŕ ĜĩţĤũƀ àććōũńţ ďōēśń'ţ ĥàvē àććēśś ţō ĩţ."],
"6MnZEC": ["Ţēŕḿĩńàĺ ƒàĩĺēď ţō ĺōàď"],
"6O626z": ["Ńō ĥēàďĩńĝś ḿàţćĥ \"", ["trimmedAnchorQuery"], "\""],
@@ -391,6 +394,7 @@
"8uAWix": [
"Ţĥĩś ţēḿƥĺàţē ĺĩvēś ĩń à ƥàŕēńţ ƒōĺďēŕ — ďēĺēţĩńĝ ĩţ àƒƒēćţś ēvēŕŷ ƒōĺďēŕ ƀēńēàţĥ ĩţ ţĥàţ ďōēśń'ţ ďēƒĩńē ĩţś ōŵń vēŕśĩōń."
],
+ "8vETh9": ["Śĥōŵ"],
"92rbk2": ["Ḿĩŕŕōŕ ĺōàďĩńĝ <0>", ["mirrorRef"], "</0>"],
"96G6Re": ["Ńēŵ ƒōĺďēŕ"],
"96w9hU": ["Śōḿēţĥĩńĝ ŵēńţ ŵŕōńĝ ōƥēńĩńĝ ţĥĩś ƒĩĺē (ĤŢŢƤ ", ["status"], ")."],
@@ -601,6 +605,7 @@
"EEYbdt": ["Ƥũƀĺĩśĥ"],
"EHu0x2": ["Śŷńćĩńĝ"],
"EJuO7B": ["Ćōńńēćţ à ĜĩţĤũƀ àććōũńţ ţō ƀŕōŵśē àńď śŷńć ŷōũŕ ŕēƥōśĩţōŕĩēś."],
+ "ELYtNJ": [".ōķ ƒōĺďēŕś"],
"EL_YRd": ["Ḿĩŕŕōŕ ōƒ <0>àƥĩ-śƥēć</0>"],
"EOjU5V": ["Ĩńĺĩńē Ḿàţĥ Ƥŕōƥēŕţĩēś"],
"ETyvvg": ["Ńō ĺàńĝũàĝē ḿàţćĥ."],
@@ -700,6 +705,7 @@
"Ĝĩvē ţĥē ÀĨ ţōōĺś ŷōũ ũśē àććēśś ţō ŕēàď àńď ũƥďàţē ŷōũŕ ƥŕōĴēćţś. Ƥĩćķ ŵĥàţ ţō śēţ ũƥ ƀēĺōŵ, àńď ćĥàńĝē ĩţ àńŷţĩḿē."
],
"GGsM4y": ["Śēĺēćţēď ĩń ĝŕàƥĥ"],
+ "GHsJb8": ["Śĥōŵ .ōķ ƒōĺďēŕś"],
"GJH-AT": [
["docName"],
" ĩś ",
@@ -963,6 +969,7 @@
"Ćĥōōśē ŵĥēţĥēŕ ţĥĩś ƥŕōĴēćţ'ś ŌƥēńĶńōŵĺēďĝē śēţũƥ, ĩńćĺũďĩńĝ ĩţś ÀĨ-ţōōĺ ćōńńēćţĩōńś, ĩś śàvēď ŵĩţĥ ţĥē ƥŕōĴēćţ śō ţēàḿḿàţēś ĝēţ ĩţ ţōō, ōŕ ķēƥţ ōńĺŷ ōń ŷōũŕ ćōḿƥũţēŕ."
],
"NEzPEh": ["Ćŕēàţē à ńēŵ ƀŕàńćĥ, ōŕ ćĥēćķ ōũţ àń ēxĩśţĩńĝ ōńē, ĩń ĩţś ōŵń ŵĩńďōŵ."],
+ "NF_Wcg": ["Śĥōŵ śķĩĺĺś śēćţĩōń"],
"NIWAux": ["Ńō ďōćś ŕēĝĩśţēŕēď ũńďēŕ #", ["tagDocsName"], "."],
"NJyQi_": ["ßŕàńćĥ ", ["shareBranch"], " ńō ĺōńĝēŕ ēxĩśţś ōń ţĥē ŕēḿōţē."],
"NKkZXl": ["Ĩńĩţĩàĺĩźē àńď ōƥēń"],
@@ -1283,6 +1290,7 @@
],
"W8vpBM": ["śţàŕţēŕ ƥàćķ"],
"W9_Bub": ["Ĺōćàĺ ćĥàńĝēś ōvēŕĺàƥ ŵĩţĥ ĩńćōḿĩńĝ śŷńć"],
+ "WHPvOb": ["Àĺĺ ƒĩĺēś àŕē ĥĩďďēń ƀŷ vĩēŵ ƒĩĺţēŕś."],
"WL6puM": ["Ƥàţĥ ŕēśōĺvēś ōũţśĩďē ƥŕōĴēćţ"],
"WMIKXK": [
"Àŕē ŷōũ śũŕē ŷōũ ŵàńţ ţō ďēĺēţē ",
@@ -1307,6 +1315,7 @@
"Wgmlsw": ["Ƒēţćĥĩńĝ"],
"Wh0im4": ["ēďĩţĩńĝ [[", ["realCurrentDoc"], "]]"],
"WhOsNE": ["Śţŕĩķēţĥŕōũĝĥ"],
+ "WkTLN7": ["Śĥōŵ ōńĺŷ ḿàŕķďōŵń ƒĩĺēś"],
"WmPbvm": ["Ĝēţ ƥŕōďũćţ ũƥďàţēś ĩń ŷōũŕ ĩńƀōx."],
"Wq6Wcm": ["Ƥĺēàśē ēńţēŕ à vàĺĩď ēḿàĩĺ àďďŕēśś."],
"WqLq6M": ["Ōƥēń ŵĩţĥ ÀĨ ", ["displayName"]],
@@ -1821,8 +1830,10 @@
"iuTKci": ["Ńō ēďĩţś ŷēţ."],
"iycx_A": ["Ƥũśĥĩńĝ"],
"j9Vqvc": ["ĩńĥēŕĩţēď"],
+ "j9tqwO": ["Ńōţ ĩń śĩďēƀàŕ"],
"jAMpHn": ["Ŵĥàţ ĩś à śţàŕţēŕ ƥàćķ?"],
"jBVUXo": ["Ćōũĺďń'ţ ōƥēń ţĥē ţēŕḿĩńàĺ — ƥĺēàśē ţŕŷ àĝàĩń."],
+ "jC8LSZ": ["Ŕēśēţ vĩēŵ ƒĩĺţēŕś"],
"jEZ6Lf": ["ƥŕōvĩśĩōńàĺ"],
"jEdF24": ["Ḿĩśśĩńĝ ƥàĝē: ", ["linkTitle"], ". Ćĺĩćķ ţō ćŕēàţē."],
"jKd3AP": ["Ćōũĺď ńōţ ēńàƀĺē ţĥē ţēŕḿĩńàĺ: ", ["0"]],
diff --git a/packages/app/src/locales/pseudo/messages.po b/packages/app/src/locales/pseudo/messages.po
index 7c2f12975..5282cb474 100644
--- a/packages/app/src/locales/pseudo/messages.po
+++ b/packages/app/src/locales/pseudo/messages.po
@@ -25,6 +25,10 @@ msgstr ""
msgid " Your selection has been restored."
msgstr ""
+#: src/components/FileSidebar.tsx
+msgid ".ok folders"
+msgstr ""
+
#. placeholder {0}: skill.name
#. placeholder {1}: label(result.hosts)
#: src/components/skill-actions.tsx
@@ -789,6 +793,10 @@ msgstr ""
msgid "All files"
msgstr ""
+#: src/components/FileTreeFilteredToZeroNotice.tsx
+msgid "All files are hidden by view filters."
+msgstr ""
+
#: src/components/DiffView.tsx
msgid "All hunks resolved"
msgstr ""
@@ -1869,7 +1877,8 @@ msgid "Could not turn off the terminal: {0}"
msgstr ""
#: src/components/FileSidebar.tsx
-#: src/components/FileTree.tsx
+#: src/components/FileTreeFilteredToZeroNotice.tsx
+#: src/components/NotInSidebarIndicator.tsx
msgid "Could not update sidebar settings"
msgstr ""
@@ -3452,6 +3461,11 @@ msgstr ""
msgid "Hidden “{basename}”"
msgstr ""
+#: src/components/FileSidebar.tsx
+#: src/components/NotInSidebarIndicator.tsx
+msgid "Hidden files"
+msgstr ""
+
#: src/components/FileTree.tsx
msgid "Hidden folder “{basename}”"
msgstr ""
@@ -4730,6 +4744,10 @@ msgstr ""
msgid "Not connected to GitHub."
msgstr ""
+#: src/components/NotInSidebarIndicator.tsx
+msgid "Not in sidebar"
+msgstr ""
+
#: src/components/CommandPalette.tsx
#: src/components/handoff/OpenInAgentMenuItem.tsx
msgid "Not installed"
@@ -4819,6 +4837,11 @@ msgstr ""
msgid "Only collaborators"
msgstr ""
+#: src/components/FileSidebar.tsx
+#: src/components/NotInSidebarIndicator.tsx
+msgid "Only markdown files"
+msgstr ""
+
#: src/editor/components/TagDialog.tsx
msgid "Only the current document uses <0>#{tag}</0>."
msgstr ""
@@ -5837,6 +5860,10 @@ msgstr ""
msgid "Reset view"
msgstr ""
+#: src/components/FileTreeFilteredToZeroNotice.tsx
+msgid "Reset view filters"
+msgstr ""
+
#: src/editor/components/ResizeHandles.tsx
msgid "Resize {handleKey}"
msgstr ""
@@ -6348,6 +6375,14 @@ msgstr ""
msgid "Sharing a doc needs a GitHub repository. Create one for this project."
msgstr ""
+#: src/components/FileSidebar.tsx
+msgid "Show"
+msgstr ""
+
+#: src/components/FileSidebar.tsx
+msgid "Show .ok folders"
+msgstr ""
+
#. placeholder {0}: hiddenPacks.length
#: src/components/PackCardGrid.tsx
msgid "Show {0} more"
@@ -6387,7 +6422,7 @@ msgid "Show Files ({sidebarShortcutLabel})"
msgstr ""
#: src/components/FileSidebar.tsx
-#: src/components/FileTree.tsx
+#: src/components/NotInSidebarIndicator.tsx
msgid "Show hidden files"
msgstr ""
@@ -6399,6 +6434,10 @@ msgstr ""
msgid "Show less"
msgstr ""
+#: src/components/FileSidebar.tsx
+msgid "Show only markdown files"
+msgstr ""
+
#: src/lib/keyboard-shortcuts.ts
msgid "Show or hide document panel"
msgstr ""
@@ -6427,6 +6466,10 @@ msgstr ""
msgid "Show selection preview"
msgstr ""
+#: src/components/FileSidebar.tsx
+msgid "Show skills section"
+msgstr ""
+
#: src/components/MermaidFileViewer.tsx
msgid "Show source"
msgstr ""
@@ -6500,6 +6543,7 @@ msgstr ""
msgid "Skill renamed"
msgstr ""
+#: src/components/FileSidebar.tsx
#: src/components/settings/SettingsDialogShell.tsx
#: src/components/settings/SkillsManagerSection.tsx
#: src/components/SkillsSidebarSection.tsx
@@ -7375,6 +7419,10 @@ msgstr ""
msgid "Try again"
msgstr ""
+#: src/components/NotInSidebarIndicator.tsx
+msgid "Turn off Only markdown files"
+msgstr ""
+
#: src/components/settings/SearchSection.tsx
msgid "Turn on"
msgstr ""
diff --git a/packages/app/tests/integration/showall-single-flight.test.ts b/packages/app/tests/integration/showall-single-flight.test.ts
index 781d456fa..83870d79e 100644
--- a/packages/app/tests/integration/showall-single-flight.test.ts
+++ b/packages/app/tests/integration/showall-single-flight.test.ts
@@ -56,6 +56,10 @@ beforeAll(async () => {
mkdirSync(join(contentDir, sub));
writeFileSync(join(contentDir, sub, 'note.md'), `# ${sub}\n`);
}
+ // Non-skill `.ok` content for the showOk key-isolation test below. Default
+ // showAll walks never admit `.ok`, so the sibling tests are unaffected.
+ mkdirSync(join(contentDir, '.ok', 'templates'), { recursive: true });
+ writeFileSync(join(contentDir, '.ok', 'templates', 'daily.md'), '# Daily\n');
server = await createTestServer({ contentDir, keepContentDir: false });
}, 60_000);
@@ -137,6 +141,32 @@ describe('single-flight dedupe (AC1, AC2)', () => {
}, 30_000);
});
+describe('showOk single-flight isolation', () => {
+ test('concurrent showAll and showAll+showOk requests never coalesce', async () => {
+ // The in-flight key must incorporate the showOk flag: coalescing across
+ // modes would hand one caller the other mode's listing — either a plain
+ // caller receiving `.ok` rows or a reveal caller silently missing them.
+ __resetShowAllWalkStatsForTesting();
+ const [plainRes, revealRes] = await Promise.all([
+ fetch(showAllUrl()),
+ fetch(`${showAllUrl()}&showOk=true`),
+ ]);
+ expect(plainRes.ok).toBe(true);
+ expect(revealRes.ok).toBe(true);
+ const plain = DocumentListSuccessSchema.parse(await plainRes.json());
+ const reveal = DocumentListSuccessSchema.parse(await revealRes.json());
+
+ // Distinct cache keys → two independent walks...
+ expect(__getShowAllWalkStatsForTesting().invocations).toBe(2);
+
+ // ...and each caller received its own mode's listing.
+ const pathOf = (e: { kind: string; docName?: string; path?: string }) =>
+ e.kind === 'folder' ? (e.path ?? '') : (e.docName ?? e.path ?? '');
+ expect(plain.documents.map(pathOf).some((p) => p.split('/').includes('.ok'))).toBe(false);
+ expect(reveal.documents.map(pathOf)).toContain('.ok/templates/daily');
+ }, 30_000);
+});
+
describe('abort-on-disconnect (AC4)', () => {
test.skip('a disconnect with no other waiter aborts the shared walk', async () => {
__resetShowAllWalkStatsForTesting();
diff --git a/packages/app/tests/integration/showok-reveal.test.ts b/packages/app/tests/integration/showok-reveal.test.ts
new file mode 100644
index 000000000..0be493122
--- /dev/null
+++ b/packages/app/tests/integration/showok-reveal.test.ts
@@ -0,0 +1,150 @@
+/**
+ * `?showOk=true` tree-listing reveal over the real HTTP API. The flag admits
+ * `.ok` rows — minus `.ok/worktrees` and `.ok/local` — into the showAll walk
+ * on both the buffered and NDJSON paths, and ONLY there: with the flag in
+ * active use, the watcher-index-backed default listing and the search corpus
+ * must stay `.ok`-free (reveal is a per-request view, never an index rescope),
+ * and a plain showAll request keeps today's `.ok`-less listing.
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { mkdirSync, mkdtempSync, realpathSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { DocumentListSuccessSchema, SearchSuccessSchema } from '@inkeep/open-knowledge-core';
+import { createTestServer, type TestServer } from './test-harness';
+
+// Unique body/name tokens so the search-corpus assertions can't false-pass on
+// unrelated fixture content: the control token lives in an indexed doc (the
+// positive control proving search works), the ok token ONLY under `.ok`.
+const VISIBLE_TOKEN = 'zzcontroltoken';
+const OK_TOKEN = 'zzoktemplatetoken';
+let server: TestServer;
+
+function documentsUrl(params: string): string {
+ return `http://127.0.0.1:${server.port}/api/documents${params}`;
+}
+
+type ListedEntry = { kind: string; docName?: string; path?: string };
+
+function entryPath(e: ListedEntry): string {
+ return e.kind === 'folder' ? (e.path ?? '') : (e.docName ?? e.path ?? '');
+}
+
+function hasOkSegment(p: string): boolean {
+ return p.split('/').includes('.ok');
+}
+
+beforeAll(async () => {
+ const contentDir = realpathSync(mkdtempSync(join(tmpdir(), 'ok-showok-reveal-')));
+ writeFileSync(join(contentDir, `${VISIBLE_TOKEN}.md`), `# Control\n\n${VISIBLE_TOKEN} body\n`);
+ mkdirSync(join(contentDir, '.ok', 'templates'), { recursive: true });
+ writeFileSync(join(contentDir, '.ok', 'config.yml'), 'content:\n dir: .\n');
+ writeFileSync(
+ join(contentDir, '.ok', 'templates', `${OK_TOKEN}.md`),
+ `# Template\n\n${OK_TOKEN} body\n`,
+ );
+ mkdirSync(join(contentDir, '.ok', 'worktrees', 'checkout'), { recursive: true });
+ writeFileSync(join(contentDir, '.ok', 'worktrees', 'checkout', 'README.md'), '# checkout\n');
+ // `.ok/local` is not seeded — the booted server creates its own runtime
+ // state there (server.lock), which is exactly what must never be listed.
+ server = await createTestServer({ contentDir, keepContentDir: false });
+}, 60_000);
+
+afterAll(async () => {
+ await server.cleanup();
+});
+
+describe('showOk reveal on GET /api/documents', () => {
+ test('showAll+showOk buffered listing reveals .ok rows minus worktrees/local', async () => {
+ const res = await fetch(documentsUrl('?showAll=true&showOk=true'));
+ expect(res.ok).toBe(true);
+ const body = DocumentListSuccessSchema.parse(await res.json());
+ const paths = body.documents.map(entryPath);
+ expect(paths).toContain('.ok');
+ expect(paths).toContain('.ok/config.yml');
+ expect(paths).toContain('.ok/templates');
+ expect(paths).toContain(`.ok/templates/${OK_TOKEN}`);
+ expect(paths.some((p) => p.startsWith('.ok/worktrees'))).toBe(false);
+ expect(paths.some((p) => p.startsWith('.ok/local'))).toBe(false);
+ }, 30_000);
+
+ test('showAll without showOk stays .ok-free (default listing unchanged)', async () => {
+ const res = await fetch(documentsUrl('?showAll=true'));
+ expect(res.ok).toBe(true);
+ const body = DocumentListSuccessSchema.parse(await res.json());
+ const paths = body.documents.map(entryPath);
+ expect(paths.some(hasOkSegment)).toBe(false);
+ expect(paths).toContain(VISIBLE_TOKEN);
+ }, 30_000);
+
+ test('the NDJSON streaming path honors showOk', async () => {
+ const res = await fetch(documentsUrl('?showAll=true&showOk=true'), {
+ headers: { Accept: 'application/x-ndjson' },
+ });
+ expect(res.ok).toBe(true);
+ expect(res.headers.get('content-type')).toContain('application/x-ndjson');
+ const rows = (await res.text())
+ .split('\n')
+ .filter((line) => line.length > 0)
+ .map((line) => JSON.parse(line) as ListedEntry & { type?: string });
+ const entries = rows.filter((row) => row.type === undefined);
+ const paths = entries.map(entryPath);
+ expect(paths).toContain(`.ok/templates/${OK_TOKEN}`);
+ expect(paths.some((p) => p.startsWith('.ok/worktrees'))).toBe(false);
+ expect(paths.some((p) => p.startsWith('.ok/local'))).toBe(false);
+ }, 30_000);
+
+ test('lazy .ok expansion composes showOk with dir + depth', async () => {
+ const res = await fetch(
+ documentsUrl(`?showAll=true&showOk=true&dir=${encodeURIComponent('.ok')}&depth=1`),
+ );
+ expect(res.ok).toBe(true);
+ const body = DocumentListSuccessSchema.parse(await res.json());
+ const paths = body.documents.map(entryPath);
+ expect(paths).toContain('.ok/config.yml');
+ expect(paths).toContain('.ok/templates');
+ expect(paths.some((p) => p.startsWith('.ok/worktrees'))).toBe(false);
+ expect(paths.some((p) => p.startsWith('.ok/local'))).toBe(false);
+ const templates = body.documents.find((d) => d.kind === 'folder' && d.path === '.ok/templates');
+ expect(templates?.kind === 'folder' && templates.hasChildren).toBe(true);
+ }, 30_000);
+});
+
+describe('showOk never leaks past the tree listing', () => {
+ test('with showOk in use, the watcher index keeps non-skill .ok content out', async () => {
+ // Exercise the reveal first so the flag is genuinely in use before the
+ // index-backed read.
+ await (await fetch(documentsUrl('?showAll=true&showOk=true'))).json();
+ const res = await fetch(documentsUrl(''));
+ expect(res.ok).toBe(true);
+ const body = DocumentListSuccessSchema.parse(await res.json());
+ const paths = body.documents.map(entryPath);
+ // The bare `.ok` folder row and `.ok/skills/**` are the pre-existing
+ // skills-as-content carve-out surface of the default listing (the client
+ // adapter drops them from the tree); everything else under `.ok` must
+ // stay out of the index regardless of showOk traffic.
+ const nonSkillOkPaths = paths.filter(
+ (p) => hasOkSegment(p) && p !== '.ok' && !p.startsWith('.ok/skills/'),
+ );
+ expect(nonSkillOkPaths).toEqual([]);
+ // Positive control: the index itself is populated and serving.
+ expect(paths).toContain(VISIBLE_TOKEN);
+ }, 30_000);
+
+ test('with showOk in use, the search corpus never sees .ok content', async () => {
+ await (await fetch(documentsUrl('?showAll=true&showOk=true'))).json();
+ // Positive control first: an indexed doc's token IS searchable, so the
+ // `.ok` negative below can't pass vacuously on a broken corpus.
+ const controlRes = await fetch(
+ `http://127.0.0.1:${server.port}/api/search?query=${VISIBLE_TOKEN}`,
+ );
+ expect(controlRes.ok).toBe(true);
+ const control = SearchSuccessSchema.parse(await controlRes.json());
+ expect(control.results.length).toBeGreaterThan(0);
+
+ const okRes = await fetch(`http://127.0.0.1:${server.port}/api/search?query=${OK_TOKEN}`);
+ expect(okRes.ok).toBe(true);
+ const okBody = SearchSuccessSchema.parse(await okRes.json());
+ expect(okBody.results).toEqual([]);
+ }, 30_000);
+});
diff --git a/packages/app/tests/meta/showok-caller-coverage.test.ts b/packages/app/tests/meta/showok-caller-coverage.test.ts
new file mode 100644
index 000000000..659da2b70
--- /dev/null
+++ b/packages/app/tests/meta/showok-caller-coverage.test.ts
@@ -0,0 +1,115 @@
+/**
+ * `showOk` caller meta-test — static analysis gate.
+ *
+ * The `showOk` read-opt lifts ContentFilter's `.ok` always-skip floor for the
+ * tree-listing reveal (`GET /api/documents?showAll=true&showOk=true`). Every
+ * other filter consumer — watcher seed + event admission, search corpus,
+ * embeddings, MCP, asset serving, persistence — must keep the absolute floor:
+ * a caller that passes `showOk` rescopes what its surface can enumerate, so
+ * the set of production sources that may even NAME the flag is pinned here.
+ *
+ * Modeled on `getfileindex-allfiles-coverage.test.ts` — same shape: scan
+ * production sources for the capability, require explicit authorization.
+ * Authorization here is by source REGION (the walk-opts contract plus the
+ * documents-list handler) rather than enclosing-function name, because the
+ * flag legitimately appears in nested helpers and local consts whose names
+ * are incidental.
+ */
+import { describe, expect, test } from 'bun:test';
+import { readdirSync, readFileSync, statSync } from 'node:fs';
+import { join } from 'node:path';
+
+const SERVER_SRC_ROOT = join(import.meta.dirname, '../../../server/src');
+const CLI_SRC_ROOT = join(import.meta.dirname, '../../../cli/src');
+// Defines the `ContentFilterReadOpts.showOk` opt and consumes it in the
+// always-skip floor of `isExcluded` / `isDirExcluded`.
+const CONTENT_FILTER_PATH = join(SERVER_SRC_ROOT, 'content-filter.ts');
+// The one sanctioned data path: `handleDocumentList` parses `?showOk=true`
+// and threads it through `streamShowAllEntries` / `walkContentDirForShowAll`.
+const API_EXT_PATH = join(SERVER_SRC_ROOT, 'api-extension.ts');
+
+/** Recursively enumerate `.ts` files under `dir`, skipping test files. */
+function listProductionTsFiles(dir: string): string[] {
+ const out: string[] = [];
+ for (const entry of readdirSync(dir)) {
+ const full = join(dir, entry);
+ const st = statSync(full);
+ if (st.isDirectory()) {
+ out.push(...listProductionTsFiles(full));
+ } else if (st.isFile() && entry.endsWith('.ts') && !entry.endsWith('.test.ts')) {
+ out.push(full);
+ }
+ }
+ return out;
+}
+
+/**
+ * Character range `[start, end)` of the authorized region beginning at
+ * `startAnchor` and ending at the first `endAnchor` match after it. Both
+ * anchors are asserted present so a rename/refactor fails loudly instead of
+ * silently authorizing the rest of the file.
+ */
+function sliceRegion(source: string, startAnchor: string, endAnchor: RegExp): [number, number] {
+ const start = source.indexOf(startAnchor);
+ expect(start).toBeGreaterThanOrEqual(0);
+ const rest = source.slice(start + startAnchor.length);
+ const endMatch = endAnchor.exec(rest);
+ expect(endMatch).not.toBeNull();
+ const end = start + startAnchor.length + (endMatch?.index ?? 0);
+ return [start, end];
+}
+
+describe('showOk caller coverage', () => {
+ test('no server/cli production file outside the two sanctioned ones names showOk', () => {
+ const allowedFiles = new Set([CONTENT_FILTER_PATH, API_EXT_PATH]);
+ const offenders: string[] = [];
+ for (const root of [SERVER_SRC_ROOT, CLI_SRC_ROOT]) {
+ for (const file of listProductionTsFiles(root)) {
+ if (allowedFiles.has(file)) continue;
+ if (/\bshowOk\b/.test(readFileSync(file, 'utf8'))) offenders.push(file);
+ }
+ }
+ expect(offenders).toEqual([]);
+ });
+
+ test('every showOk occurrence in api-extension.ts sits in an authorized region', () => {
+ const source = readFileSync(API_EXT_PATH, 'utf8');
+ // Region A: the walk-opts contract + the walk itself (interface field,
+ // destructure, the shared filter-opts object, gate comments).
+ const [walkStart, walkEnd] = sliceRegion(
+ source,
+ 'export interface StreamShowAllOpts',
+ /export async function walkContentDirForShowAll/,
+ );
+ // Region B: the documents-list handler (query parse, both walk
+ // invocations, the single-flight key).
+ const [handlerStart, handlerEnd] = sliceRegion(
+ source,
+ 'const handleDocumentList = withValidation(',
+ /\bconst handle[A-Z][A-Za-z]*\s*=/,
+ );
+
+ const outside: string[] = [];
+ for (const match of source.matchAll(/\bshowOk\b/g)) {
+ const offset = match.index ?? 0;
+ const inWalk = offset >= walkStart && offset < walkEnd;
+ const inHandler = offset >= handlerStart && offset < handlerEnd;
+ if (!inWalk && !inHandler) {
+ const line = source.slice(0, offset).split('\n').length;
+ outside.push(
+ `api-extension.ts:${line} — showOk outside the walk-opts and document-list regions. ` +
+ 'Only the tree-listing path may pass the flag; a new consumer needs a deliberate ' +
+ 'spec decision, not a new call site.',
+ );
+ }
+ }
+ expect(outside).toEqual([]);
+ });
+
+ test('the sanctioned surfaces still exist (allowlist-rot guard)', () => {
+ // If the flag is renamed or removed, this test forces the allowlist and
+ // regions above to be revisited rather than rotting into dead authority.
+ expect(readFileSync(CONTENT_FILTER_PATH, 'utf8')).toContain('showOk?: boolean');
+ expect(readFileSync(API_EXT_PATH, 'utf8')).toContain("searchParams.get('showOk')");
+ });
+});
diff --git a/packages/app/tests/stress/quiet-tree-hidden-doc.e2e.ts b/packages/app/tests/stress/quiet-tree-hidden-doc.e2e.ts
new file mode 100644
index 000000000..262b6142c
--- /dev/null
+++ b/packages/app/tests/stress/quiet-tree-hidden-doc.e2e.ts
@@ -0,0 +1,231 @@
+// Quiet-tree contract for docs the sidebar tree does not display. Opening a
+// tree-hidden doc (dot-path, with hidden files off — the default) must open
+// the editor normally while the tree stays quiet: the previously active row
+// deselects, the tree does not scroll to the stale row, and visible ancestors
+// of a partially-hidden path stay expanded. The editor's not-in-sidebar
+// indicator completes the contract: it names the hiding toggle beside the
+// breadcrumb and flips it in place.
+import { mkdirSync, writeFileSync } from 'node:fs';
+import { join } from 'node:path';
+import type { Page } from '@playwright/test';
+import { expect, test } from './_helpers';
+
+function uniqueStamp(): string {
+ return `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`;
+}
+
+const sidebar = (page: Page) => page.locator('[data-slot="sidebar-container"]');
+const fileRow = (page: Page, fileName: string) =>
+ sidebar(page).getByRole('treeitem', { name: fileName, exact: true });
+const folderRow = (page: Page, folderName: string) =>
+ sidebar(page).getByRole('treeitem', { name: folderName, exact: true });
+const selectedRow = (page: Page) => sidebar(page).locator('[aria-selected="true"]');
+// Pierre's internal scroll element inside the file-tree-container shadow root
+// (Playwright CSS pierces open shadow roots).
+const treeScroller = (page: Page) => sidebar(page).locator('[data-file-tree-virtualized-scroll]');
+
+const editorHeading = (page: Page, text: string) =>
+ page.locator('.ProseMirror:not(.composer-prosemirror) h1', { hasText: text });
+
+/** Yield a few animation frames so any pending commit/effect would have landed. */
+async function settleFrames(page: Page, frames = 5): Promise<void> {
+ await page.evaluate(
+ (count) =>
+ new Promise<void>((resolve) => {
+ let remaining = count;
+ const tick = () => {
+ if (--remaining <= 0) resolve();
+ else requestAnimationFrame(tick);
+ };
+ requestAnimationFrame(tick);
+ }),
+ frames,
+ );
+}
+
+/**
+ * Wait until the server's page list includes every given docName. Dot-path
+ * docs cannot be seeded through the agent-write API (dot segments are
+ * rejected), so they are written straight to the worker's content dir — the
+ * app must not navigate until the server actually lists them.
+ */
+async function waitForPagesToInclude(baseURL: string, docNames: string[]): Promise<void> {
+ await expect
+ .poll(
+ async () => {
+ const response = await fetch(`${baseURL}/api/pages`).catch(() => null);
+ if (!response?.ok) return ['__pages-fetch-failed__'];
+ const data = (await response.json()) as { pages?: Array<{ docName: string }> };
+ const known = new Set((data.pages ?? []).map((entry) => entry.docName));
+ return docNames.filter((name) => !known.has(name));
+ },
+ { timeout: 15_000 },
+ )
+ .toEqual([]);
+}
+
+async function createFolder(baseURL: string, path: string): Promise<void> {
+ const response = await fetch(`${baseURL}/api/create-folder`, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ path }),
+ });
+ if (!response.ok && response.status !== 409) {
+ throw new Error(`create-folder failed for ${path}: ${response.status}`);
+ }
+}
+
+test('opening a tree-hidden doc keeps the tree quiet: previous row deselects, no auto-scroll', async ({
+ page,
+ api,
+ workerServer,
+}) => {
+ const stamp = uniqueStamp();
+ const hiddenDir = `.quiet-scratch-${stamp}`;
+ const hiddenDocName = `${hiddenDir}/hidden-note`;
+ const targetDoc = `zz-quiet-target-${stamp}`;
+
+ // Enough rows above the zz-sorted target that revealing it must scroll the
+ // virtualized tree — the no-scroll assertion below is vacuous otherwise.
+ const fillerNames = Array.from(
+ { length: 40 },
+ (_, i) => `quiet-filler-${stamp}-${String(i).padStart(2, '0')}`,
+ );
+ for (const name of fillerNames) {
+ await api.createPage(`${name}.md`);
+ }
+ await api.createPage(`${targetDoc}.md`);
+
+ mkdirSync(join(workerServer.contentDir, hiddenDir), { recursive: true });
+ writeFileSync(
+ join(workerServer.contentDir, hiddenDir, 'hidden-note.md'),
+ '# Quiet hidden note\n',
+ 'utf-8',
+ );
+ await waitForPagesToInclude(workerServer.baseURL, [hiddenDocName, targetDoc]);
+
+ await page.goto(`/#/${targetDoc}`);
+ await fileRow(page, `${targetDoc}.md`).waitFor({ state: 'visible', timeout: 15_000 });
+ await expect(selectedRow(page)).toHaveCount(1);
+ await expect(selectedRow(page)).toHaveAttribute('aria-label', `${targetDoc}.md`);
+
+ // Revealing the bottom-sorted target scrolled the tree; park it back at the
+ // top so a stale reveal-scroll after the hidden-doc hop is observable.
+ expect(await treeScroller(page).evaluate((el) => el.scrollTop)).toBeGreaterThan(0);
+ await treeScroller(page).evaluate((el) => {
+ el.scrollTop = 0;
+ });
+ expect(await treeScroller(page).evaluate((el) => el.scrollTop)).toBe(0);
+
+ await page.evaluate((docName) => {
+ window.location.hash = `#/${docName}`;
+ }, hiddenDocName);
+
+ // The editor opens the hidden doc fully...
+ await expect(editorHeading(page, 'Quiet hidden note')).toBeVisible({ timeout: 15_000 });
+
+ // ...while the tree stays quiet: nothing selected, no scroll to the stale row.
+ await settleFrames(page);
+ await expect(selectedRow(page)).toHaveCount(0);
+ expect(await treeScroller(page).evaluate((el) => el.scrollTop)).toBe(0);
+
+ // The previous row is genuinely deselected — not merely virtualized out of
+ // the viewport: bring it back into view and re-check.
+ await treeScroller(page).evaluate((el) => {
+ el.scrollTop = el.scrollHeight;
+ });
+ await fileRow(page, `${targetDoc}.md`).waitFor({ state: 'visible', timeout: 15_000 });
+ await expect(selectedRow(page)).toHaveCount(0);
+});
+
+test('visible ancestors of a partially-hidden path stay expanded while the tree stays quiet', async ({
+ page,
+ api,
+ workerServer,
+}) => {
+ const stamp = uniqueStamp();
+ const startDoc = `quiet-start-${stamp}`;
+ const parentFolder = `quiet-parent-${stamp}`;
+ const hiddenChildDocName = `${parentFolder}/.hidden-child`;
+
+ await createFolder(workerServer.baseURL, parentFolder);
+ await api.createPage(`${startDoc}.md`);
+ await api.createPage(`${parentFolder}/sibling-note.md`);
+ writeFileSync(
+ join(workerServer.contentDir, parentFolder, '.hidden-child.md'),
+ '# Quiet hidden child\n',
+ 'utf-8',
+ );
+ await waitForPagesToInclude(workerServer.baseURL, [hiddenChildDocName, startDoc]);
+
+ await page.goto(`/#/${startDoc}`);
+ await fileRow(page, `${startDoc}.md`).waitFor({ state: 'visible', timeout: 15_000 });
+ await expect(selectedRow(page)).toHaveCount(1);
+ await expect(selectedRow(page)).toHaveAttribute('aria-label', `${startDoc}.md`);
+
+ // Folders sort first — park the tree at the top so the parent folder row is
+ // rendered (it may be virtualized out when this worker's tree is long).
+ await treeScroller(page).evaluate((el) => {
+ el.scrollTop = 0;
+ });
+ await folderRow(page, parentFolder).waitFor({ state: 'visible', timeout: 15_000 });
+ await expect(folderRow(page, parentFolder)).toHaveAttribute('aria-expanded', 'false');
+
+ await page.evaluate((docName) => {
+ window.location.hash = `#/${docName}`;
+ }, hiddenChildDocName);
+
+ await expect(editorHeading(page, 'Quiet hidden child')).toBeVisible({ timeout: 15_000 });
+
+ // The hidden child has no row, so nothing is selected — but its visible
+ // ancestor folder is expanded and pinned (ancestor priority unchanged).
+ await expect(folderRow(page, parentFolder)).toHaveAttribute('aria-expanded', 'true');
+ await settleFrames(page);
+ await expect(folderRow(page, parentFolder)).toHaveAttribute('aria-expanded', 'true');
+ await expect(selectedRow(page)).toHaveCount(0);
+ expect(await treeScroller(page).evaluate((el) => el.scrollTop)).toBe(0);
+});
+
+test('the not-in-sidebar indicator names the hiding toggle and its flip reveals the row', async ({
+ page,
+ workerServer,
+}) => {
+ const stamp = uniqueStamp();
+ const hiddenDir = `.indicator-scratch-${stamp}`;
+ const hiddenDocName = `${hiddenDir}/indicator-note`;
+
+ mkdirSync(join(workerServer.contentDir, hiddenDir), { recursive: true });
+ writeFileSync(
+ join(workerServer.contentDir, hiddenDir, 'indicator-note.md'),
+ '# Indicator note\n',
+ 'utf-8',
+ );
+ await waitForPagesToInclude(workerServer.baseURL, [hiddenDocName]);
+
+ await page.goto(`/#/${hiddenDocName}`);
+ await expect(editorHeading(page, 'Indicator note')).toBeVisible({ timeout: 15_000 });
+
+ // The doc is hidden solely by the hidden-files axis: the indicator names
+ // exactly that toggle (no only-markdown chip) while the tree stays quiet.
+ const indicator = page.getByTestId('not-in-sidebar-indicator');
+ await expect(indicator).toBeVisible();
+ await expect(page.getByTestId('not-in-sidebar-flip-hidden-files')).toBeVisible();
+ await expect(page.getByTestId('not-in-sidebar-flip-only-markdown')).toHaveCount(0);
+ await expect(selectedRow(page)).toHaveCount(0);
+
+ // Flip from the indicator: the tree refetches, the row appears, the
+ // selection mirror re-selects it, and the indicator retires.
+ await page.getByTestId('not-in-sidebar-flip-hidden-files').click();
+ await fileRow(page, 'indicator-note.md').waitFor({ state: 'visible', timeout: 15_000 });
+ await expect(indicator).toHaveCount(0);
+ await expect(selectedRow(page)).toHaveAttribute('aria-label', 'indicator-note.md');
+
+ // Flip back from the tree-options popover (this worker's server is shared
+ // by the file's other tests — restore the default) and the indicator
+ // recomputes back into view for the still-open doc.
+ await page.getByRole('button', { name: 'Tree view options' }).click();
+ await page.getByTestId('tree-options-show-hidden-files').click();
+ await expect(fileRow(page, 'indicator-note.md')).toHaveCount(0, { timeout: 15_000 });
+ await expect(page.getByTestId('not-in-sidebar-indicator')).toBeVisible();
+ await expect(selectedRow(page)).toHaveCount(0);
+});
diff --git a/packages/app/tests/stress/show-ok-folders.e2e.ts b/packages/app/tests/stress/show-ok-folders.e2e.ts
new file mode 100644
index 000000000..c0b93ce97
--- /dev/null
+++ b/packages/app/tests/stress/show-ok-folders.e2e.ts
@@ -0,0 +1,246 @@
+// Show .ok folders — the request-scoped `.ok` reveal with read-only posture.
+// Flipping the toggle fetches the listing with `showOk=true` and renders the
+// `.ok` rows (minus `worktrees/` and `local/`, which the server excludes at
+// every depth); clicks land on sanctioned surfaces only — template files on
+// the template editor, everything else on the read-only text viewer — and no
+// `.ok` row exposes a mutate context action. The doc-open guard is
+// visibility-independent: a direct hash to a raw `.ok` docName lands on the
+// read-only viewer (never the editable / create-mode editor), whether or not
+// the reveal is on. Mutation affordances stay dead even when a `.ok` row is
+// the activated target: toolbar create falls back to the workspace root and
+// keyboard delete opens no dialog.
+import { existsSync, mkdirSync, writeFileSync } from 'node:fs';
+import { join } from 'node:path';
+import type { Page } from '@playwright/test';
+import { expect, test } from './_helpers';
+
+function uniqueStamp(): string {
+ return `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`;
+}
+
+const sidebar = (page: Page) => page.locator('[data-slot="sidebar-container"]');
+const fileRow = (page: Page, fileName: string) =>
+ sidebar(page).getByRole('treeitem', { name: fileName, exact: true });
+const folderRow = (page: Page, folderName: string) =>
+ sidebar(page).getByRole('treeitem', { name: folderName, exact: true });
+const treeScroller = (page: Page) => sidebar(page).locator('[data-file-tree-virtualized-scroll]');
+const textViewer = (page: Page) => page.locator('[data-text-viewer]');
+
+async function toggleShowOkFolders(page: Page): Promise<void> {
+ await page.getByRole('button', { name: 'Tree view options' }).click();
+ await page.getByTestId('tree-options-show-ok-folders').click();
+}
+
+test('toggle reveals .ok rows, routes clicks to sanctioned surfaces, and keeps rows mutate-free', async ({
+ page,
+ api,
+ workerServer,
+}) => {
+ const stamp = uniqueStamp();
+ const controlDoc = `ok-reveal-control-${stamp}`;
+ const templateName = `greeting-${stamp}`;
+ const rawDocBase = `notes-probe-${stamp}`;
+
+ await api.createPage(`${controlDoc}.md`);
+ const okDir = join(workerServer.contentDir, '.ok');
+ mkdirSync(join(okDir, 'templates'), { recursive: true });
+ mkdirSync(join(okDir, 'worktrees', 'checkout'), { recursive: true });
+ mkdirSync(join(okDir, 'local'), { recursive: true });
+ writeFileSync(join(okDir, 'templates', `${templateName}.md`), '# Greeting template\n', 'utf-8');
+ writeFileSync(join(okDir, `${rawDocBase}.md`), `# Raw probe ${stamp}\n`, 'utf-8');
+ writeFileSync(join(okDir, 'worktrees', 'checkout', 'README.md'), '# checkout\n', 'utf-8');
+
+ await page.goto(`/#/${controlDoc}`);
+ await fileRow(page, `${controlDoc}.md`).waitFor({ state: 'visible', timeout: 15_000 });
+
+ // Default state: the reveal is off and no `.ok` row exists.
+ await expect(folderRow(page, '.ok')).toHaveCount(0);
+
+ await toggleShowOkFolders(page);
+ await treeScroller(page).evaluate((el) => {
+ el.scrollTop = 0;
+ });
+ await folderRow(page, '.ok').waitFor({ state: 'visible', timeout: 15_000 });
+
+ // Expand `.ok`: templates + the raw doc appear; the server never lists
+ // `worktrees/` or `local/` (excluded at every depth even while revealed).
+ await folderRow(page, '.ok').click();
+ await folderRow(page, 'templates').waitFor({ state: 'visible', timeout: 15_000 });
+ await fileRow(page, `${rawDocBase}.md`).waitFor({ state: 'visible', timeout: 15_000 });
+ await expect(folderRow(page, 'worktrees')).toHaveCount(0);
+ await expect(folderRow(page, 'local')).toHaveCount(0);
+
+ // No mutate context actions on .ok rows — folder first…
+ await folderRow(page, 'templates').click({ button: 'right' });
+ await expect(page.getByRole('menuitem', { name: /copy path/i })).toBeVisible({
+ timeout: 5_000,
+ });
+ await expect(page.getByRole('menuitem', { name: /new file/i })).toHaveCount(0);
+ await expect(page.getByRole('menuitem', { name: /rename/i })).toHaveCount(0);
+ await expect(page.getByRole('menuitem', { name: /duplicate/i })).toHaveCount(0);
+ await expect(page.getByRole('menuitem', { name: /^delete/i })).toHaveCount(0);
+ await expect(page.getByRole('menuitem', { name: /hide/i })).toHaveCount(0);
+ await page.keyboard.press('Escape');
+
+ // …then a file row.
+ await fileRow(page, `${rawDocBase}.md`).click({ button: 'right' });
+ await expect(page.getByRole('menuitem', { name: /copy path/i })).toBeVisible({
+ timeout: 5_000,
+ });
+ await expect(page.getByRole('menuitem', { name: /rename/i })).toHaveCount(0);
+ await expect(page.getByRole('menuitem', { name: /duplicate/i })).toHaveCount(0);
+ await expect(page.getByRole('menuitem', { name: /^delete/i })).toHaveCount(0);
+ await expect(page.getByRole('menuitem', { name: /hide/i })).toHaveCount(0);
+ await page.keyboard.press('Escape');
+
+ // A raw `.ok` doc row opens the read-only text viewer, not an editor.
+ // Read-only is enforced at the CodeMirror dispatch level (the DOM stays
+ // contenteditable for selection/copy UX), so the honest check is
+ // behavioral: typing changes nothing.
+ await fileRow(page, `${rawDocBase}.md`).click();
+ await expect(textViewer(page)).toBeVisible({ timeout: 15_000 });
+ await expect(page.getByText(`Raw probe ${stamp}`)).toBeVisible({ timeout: 15_000 });
+ await page.locator('[data-text-viewer] .cm-content').click();
+ await page.keyboard.type('MUTATION-ATTEMPT');
+ await expect(page.getByText('MUTATION-ATTEMPT')).toHaveCount(0);
+ await expect(page.getByText(`Raw probe ${stamp}`)).toBeVisible();
+
+ // A template file row routes to the managed-artifact template editor.
+ await folderRow(page, 'templates').click();
+ await fileRow(page, `${templateName}.md`).waitFor({ state: 'visible', timeout: 15_000 });
+ await fileRow(page, `${templateName}.md`).click();
+ await expect
+ .poll(async () => decodeURIComponent(await page.evaluate(() => window.location.hash)), {
+ timeout: 15_000,
+ })
+ .toBe(`#/__template__/${templateName}`);
+
+ // Restore the worker-shared default from the same popover; the `.ok` rows
+ // retire with the flip.
+ await toggleShowOkFolders(page);
+ await expect(folderRow(page, '.ok')).toHaveCount(0, { timeout: 15_000 });
+});
+
+test('a direct hash to a raw .ok docName lands read-only — existing shows bytes, missing never offers create', async ({
+ page,
+ api,
+ workerServer,
+}) => {
+ const stamp = uniqueStamp();
+ const anchorDoc = `ok-guard-anchor-${stamp}`;
+ const rawDocBase = `guard-probe-${stamp}`;
+
+ await api.createPage(`${anchorDoc}.md`);
+ mkdirSync(join(workerServer.contentDir, '.ok'), { recursive: true });
+ writeFileSync(
+ join(workerServer.contentDir, '.ok', `${rawDocBase}.md`),
+ `# Guard probe ${stamp}\n`,
+ 'utf-8',
+ );
+
+ await page.goto(`/#/${anchorDoc}`);
+ await fileRow(page, `${anchorDoc}.md`).waitFor({ state: 'visible', timeout: 15_000 });
+
+ // Existing raw `.ok` file, reveal OFF (the guard is visibility-blind): the
+ // bytes open in the read-only viewer, never an editable editor.
+ await page.evaluate((docName) => {
+ window.location.hash = `#/${docName}`;
+ }, `.ok/${rawDocBase}`);
+ await expect(textViewer(page)).toBeVisible({ timeout: 15_000 });
+ await expect(page.getByText(`Guard probe ${stamp}`)).toBeVisible({ timeout: 15_000 });
+ // Behavioral read-only pin: CodeMirror rejects the write at dispatch level.
+ await page.locator('[data-text-viewer] .cm-content').click();
+ await page.keyboard.type('MUTATION-ATTEMPT');
+ await expect(page.getByText('MUTATION-ATTEMPT')).toHaveCount(0);
+ await expect(page.getByText(`Guard probe ${stamp}`)).toBeVisible();
+
+ // Nonexistent `.ok` docName: the viewer's error pane is the non-create
+ // missing surface — typing-to-create is never offered.
+ await page.evaluate((docName) => {
+ window.location.hash = `#/${docName}`;
+ }, `.ok/ghost-${stamp}`);
+ await expect(textViewer(page)).toBeVisible({ timeout: 15_000 });
+ await expect(page.getByPlaceholder('Start writing to create this page')).toHaveCount(0);
+ await expect(page.getByText('Start writing to create this page')).toHaveCount(0);
+});
+
+test('an activated .ok folder row never becomes a mutation target — create falls back to root, keyboard delete no-ops', async ({
+ page,
+ api,
+ workerServer,
+}) => {
+ const stamp = uniqueStamp();
+ const anchorDoc = `ok-mutation-anchor-${stamp}`;
+ const controlFolder = `ok-delete-control-${stamp}`;
+ const createdDoc = `ok-create-fallback-${stamp}`;
+ const probeDocBase = `activation-probe-${stamp}`;
+
+ await api.createPage(`${anchorDoc}.md`);
+ await api.createPage(`${controlFolder}/inside.md`);
+ const okDir = join(workerServer.contentDir, '.ok');
+ mkdirSync(okDir, { recursive: true });
+ writeFileSync(join(okDir, `${probeDocBase}.md`), `# Activation probe ${stamp}\n`, 'utf-8');
+
+ await page.goto(`/#/${anchorDoc}`);
+ await fileRow(page, `${anchorDoc}.md`).waitFor({ state: 'visible', timeout: 15_000 });
+
+ await toggleShowOkFolders(page);
+ await treeScroller(page).evaluate((el) => {
+ el.scrollTop = 0;
+ });
+ await folderRow(page, '.ok').waitFor({ state: 'visible', timeout: 15_000 });
+
+ // Activate the revealed `.ok` folder row; the expansion (probe file
+ // appearing) proves the click landed and `.ok` is the active folder.
+ await folderRow(page, '.ok').click();
+ await fileRow(page, `${probeDocBase}.md`).waitFor({ state: 'visible', timeout: 15_000 });
+
+ // Toolbar New file with `.ok` active: the create target falls back to the
+ // workspace root. The inline rename input opens against the auto-
+ // incrementing default (`Untitled.md` if not taken, else `Untitled 2.md`).
+ await page.getByRole('button', { name: 'New file', exact: true }).click();
+ const renameInput = page.getByRole('textbox', { name: /rename Untitled/i });
+ await expect(renameInput).toBeVisible({ timeout: 10_000 });
+ await renameInput.fill(createdDoc);
+ await renameInput.press('Enter');
+ await fileRow(page, `${createdDoc}.md`).waitFor({ state: 'visible', timeout: 15_000 });
+
+ // Disk is the authority: the doc landed at the root, never inside `.ok`.
+ await expect
+ .poll(() => existsSync(join(workerServer.contentDir, `${createdDoc}.md`)), {
+ timeout: 15_000,
+ })
+ .toBe(true);
+ expect(existsSync(join(okDir, `${createdDoc}.md`))).toBe(false);
+
+ // Keyboard delete, positive control first: the same Delete key on a normal
+ // folder row opens the confirm dialog — proving key routing and tree focus
+ // work in this harness, so the `.ok` absence assertion below cannot pass
+ // vacuously. The tree's keydown handler requires focus inside the tree
+ // host, and a click alone doesn't guarantee it — focus the row explicitly
+ // (same pattern as file-tree-create's select-all helper). Escape cancels
+ // without deleting.
+ const controlRow = folderRow(page, controlFolder);
+ await controlRow.click();
+ await controlRow.focus();
+ await expect(controlRow).toBeFocused();
+ await page.keyboard.press('Delete');
+ await expect(page.getByRole('dialog')).toBeVisible({ timeout: 10_000 });
+ await page.keyboard.press('Escape');
+ await expect(page.getByRole('dialog')).toHaveCount(0);
+
+ // The same key on the selected-and-focused `.ok` row: no dialog opens, and
+ // the folder (with its probe file) stays on disk.
+ const okRow = folderRow(page, '.ok');
+ await okRow.click();
+ await okRow.focus();
+ await expect(okRow).toBeFocused();
+ await page.keyboard.press('Delete');
+ await expect(page.getByRole('dialog')).toHaveCount(0);
+ await expect(okRow).toBeVisible();
+ expect(existsSync(join(okDir, `${probeDocBase}.md`))).toBe(true);
+
+ // Restore the worker-shared default from the same popover.
+ await toggleShowOkFolders(page);
+ await expect(folderRow(page, '.ok')).toHaveCount(0, { timeout: 15_000 });
+});
diff --git a/packages/app/tests/stress/sidebar-search-pill.e2e.ts b/packages/app/tests/stress/sidebar-search-pill.e2e.ts
index b4ecbd925..c7b58992e 100644
--- a/packages/app/tests/stress/sidebar-search-pill.e2e.ts
+++ b/packages/app/tests/stress/sidebar-search-pill.e2e.ts
@@ -29,8 +29,9 @@
* suppressed by the pill overrides
* - the pill follows the sidebar offcanvas during collapse
* - web-mode 'Files' label still renders alongside the pill
- * - empty-workspace path (hasFolders === false → Tree view options
- * dropdown hidden) renders the pill alongside the 3-button toolbar
+ * - empty-workspace path (hasFolders === false) renders the pill
+ * alongside the 4-button toolbar — the Tree view options trigger is
+ * state-independent (its Show group always has content)
* - the multi-scope search backend still yields results when the pill
* opens the palette (no regression in palette functionality)
* - the locked `data-telemetry-event="ok.sidebar.search_pill.click"`
@@ -843,7 +844,7 @@ test.describe('sidebar-search-pill — Electron host & sidebar-state', () => {
.toBe('expanded');
});
- test('empty workspace — pill renders alongside the 3-button toolbar (Tree view options hidden by hasFolders gate)', async ({
+ test('empty workspace — pill renders alongside the 4-button toolbar (Tree view options trigger is state-independent)', async ({
page,
api,
workerServer,
@@ -878,7 +879,7 @@ test.describe('sidebar-search-pill — Electron host & sidebar-state', () => {
await page.setViewportSize(DESKTOP_VIEWPORT);
await page.goto('/');
- // Three core toolbar buttons present. ASCII-only substring match for
+ // Four core toolbar buttons present. ASCII-only substring match for
// `New from template` — see the comment in the "legacy Search
// ToolbarButton is gone from SidebarHeader" test above for the
// cross-platform accessible-name rationale.
@@ -890,17 +891,12 @@ test.describe('sidebar-search-pill — Electron host & sidebar-state', () => {
).toBeVisible();
await expect(sidebarHeader(page).getByRole('button', { name: 'New folder' })).toBeVisible();
- // Tree view options trigger is HIDDEN (hasFolders gate evaluates to
- // false because the content directory has no folders). Poll because
- // the file watcher + folder-state subscription propagation may take a
- // moment to reflect the rm.
- await expect
- .poll(
- async () =>
- await sidebarHeader(page).getByRole('button', { name: 'Tree view options' }).count(),
- { timeout: 10_000 },
- )
- .toBe(0);
+ // Tree view options trigger stays VISIBLE with zero folders — its Show
+ // group is folder-state-independent, so the trigger no longer smart-
+ // hides with the Expand/Collapse-all commands.
+ await expect(
+ sidebarHeader(page).getByRole('button', { name: 'Tree view options' }),
+ ).toBeVisible();
// Pill renders normally.
await expect(pill(page)).toBeVisible();
diff --git a/packages/core/src/config/bind-config-doc.test.ts b/packages/core/src/config/bind-config-doc.test.ts
index 16206e36a..7627d1a2d 100644
--- a/packages/core/src/config/bind-config-doc.test.ts
+++ b/packages/core/src/config/bind-config-doc.test.ts
@@ -124,6 +124,31 @@ describe('bindConfigDoc — patch()', () => {
binding.dispose();
});
+ test('writes the sidebar view toggles via a project-local binding + returns effective config', () => {
+ const binding = bindConfigDoc(provider, 'project-local');
+ const result = binding.patch({
+ appearance: {
+ sidebar: {
+ showOnlyMarkdownFiles: true,
+ showSkillsSection: false,
+ showOkFolders: true,
+ },
+ },
+ });
+
+ expect(result.ok).toBe(true);
+ if (!result.ok) throw new Error('expected ok');
+ expect(result.appliedPaths).toEqual([
+ 'appearance.sidebar.showOnlyMarkdownFiles',
+ 'appearance.sidebar.showSkillsSection',
+ 'appearance.sidebar.showOkFolders',
+ ]);
+ expect(result.effective.appearance?.sidebar?.showOnlyMarkdownFiles).toBe(true);
+ expect(result.effective.appearance?.sidebar?.showSkillsSection).toBe(false);
+ expect(result.effective.appearance?.sidebar?.showOkFolders).toBe(true);
+ binding.dispose();
+ });
+
test('updates existing field + preserves comments via yaml@2 Document', () => {
const initial = '# Project config\ncontent:\n dir: old # original\n';
doc.getText('source').insert(0, initial);
diff --git a/packages/core/src/config/field-registry.test.ts b/packages/core/src/config/field-registry.test.ts
index ca4b32e73..996a18d9c 100644
--- a/packages/core/src/config/field-registry.test.ts
+++ b/packages/core/src/config/field-registry.test.ts
@@ -201,7 +201,7 @@ describe('ConfigSchema coverage (NR3 — every leaf has fieldRegistry metadata)'
// `<projectDir>/.ok/local/config.yml` is gitignored and never mirrored
// to the public repo. `autoSync.enabled` controls per-machine sync;
// the `appearance.sidebar.*` toggles are per-machine view preferences
- // for hidden / ignored files in the file tree; `search.semantic.*` is the
+ // for what the file tree and sidebar show; `search.semantic.*` is the
// per-machine opt-in for embeddings search — enabling it sends content to
// a third-party provider (egress) and needs a local API key, so the choice
// (and its non-secret provider knobs) is inherently per-machine.
@@ -215,6 +215,9 @@ describe('ConfigSchema coverage (NR3 — every leaf has fieldRegistry metadata)'
.sort();
expect(projectLocalStrict).toEqual([
'appearance.sidebar.showHiddenFiles',
+ 'appearance.sidebar.showOkFolders',
+ 'appearance.sidebar.showOnlyMarkdownFiles',
+ 'appearance.sidebar.showSkillsSection',
'autoSync.enabled',
'search.semantic.baseUrl',
'search.semantic.dimensions',
@@ -224,4 +227,19 @@ describe('ConfigSchema coverage (NR3 — every leaf has fieldRegistry metadata)'
'terminal.enabled',
]);
});
+
+ test('showOnlyMarkdownFiles description documents the .md/.mdx extension contract', () => {
+ // "Markdown" canonically includes .mdx here; the registered description
+ // is the single documented home for that contract (it is the source
+ // injected into the published JSON schema).
+ const leaves: { path: string[]; schema: unknown }[] = [];
+ walkLeaves(ConfigSchema, [], leaves);
+ const leaf = leaves.find(
+ (l) => l.path.join('.') === 'appearance.sidebar.showOnlyMarkdownFiles',
+ );
+ expect(leaf).toBeDefined();
+ const description = getFieldMeta(leaf?.schema)?.description ?? '';
+ expect(description).toContain('.md');
+ expect(description).toContain('.mdx');
+ });
});
diff --git a/packages/core/src/config/removed-keys.test.ts b/packages/core/src/config/removed-keys.test.ts
index 0710f630a..afff29f36 100644
--- a/packages/core/src/config/removed-keys.test.ts
+++ b/packages/core/src/config/removed-keys.test.ts
@@ -35,6 +35,11 @@ describe('REMOVED_KEYS registry', () => {
const dotted = REMOVED_KEYS.map((k) => k.path.join('.'));
expect(new Set(dotted).size).toBe(dotted.length);
});
+
+ test('showAllFiles redirect names the only-markdown view preference as its successor', () => {
+ const entry = REMOVED_KEYS.find((k) => k.path.join('.') === 'appearance.sidebar.showAllFiles');
+ expect(entry?.redirect).toContain('appearance.sidebar.showOnlyMarkdownFiles');
+ });
});
describe('detectRemovedKeys', () => {
diff --git a/packages/core/src/config/removed-keys.ts b/packages/core/src/config/removed-keys.ts
index dec0221a2..3d8a4c2f1 100644
--- a/packages/core/src/config/removed-keys.ts
+++ b/packages/core/src/config/removed-keys.ts
@@ -146,14 +146,14 @@ export const REMOVED_KEYS: readonly RemovedKey[] = [
].join(' '),
},
{
- // The "Show all files" sidebar toggle was removed; the tree now always
- // lists every file on disk. Top-level config is loose, so a residual
+ // The "Show all files" sidebar toggle was removed; the tree lists every
+ // file on disk by default. Top-level config is loose, so a residual
// `appearance.sidebar.showAllFiles: false` would otherwise be a silent
// no-op for users who had scoped their tree to indexed/linked content.
path: ['appearance', 'sidebar', 'showAllFiles'],
redirect: [
'appearance.sidebar.showAllFiles has been removed.',
- 'The sidebar now always lists every file on disk; dot-prefixed entries are still gated by appearance.sidebar.showHiddenFiles. There is no longer a way to scope the tree to indexed/linked content.',
+ 'The sidebar lists every file on disk by default; dot-prefixed entries are gated by appearance.sidebar.showHiddenFiles, and appearance.sidebar.showOnlyMarkdownFiles scopes the tree down to markdown documents as a per-machine view preference.',
MIGRATE_HINT,
].join(' '),
},
diff --git a/packages/core/src/config/schema.test.ts b/packages/core/src/config/schema.test.ts
index 15f2ec389..bc3d1d5bd 100644
--- a/packages/core/src/config/schema.test.ts
+++ b/packages/core/src/config/schema.test.ts
@@ -108,6 +108,37 @@ describe('content.attachmentFolderPath', () => {
});
});
+describe('appearance.sidebar view toggles', () => {
+ test('sidebar defaults: hidden files off, only-markdown off, Skills section on, .ok folders off', () => {
+ const sidebar = ConfigSchema.parse({ appearance: { sidebar: {} } }).appearance.sidebar;
+ expect(sidebar).toEqual({
+ showHiddenFiles: false,
+ showOnlyMarkdownFiles: false,
+ showSkillsSection: true,
+ showOkFolders: false,
+ });
+ });
+
+ test('explicit values override every toggle default', () => {
+ const sidebar = ConfigSchema.parse({
+ appearance: {
+ sidebar: {
+ showHiddenFiles: true,
+ showOnlyMarkdownFiles: true,
+ showSkillsSection: false,
+ showOkFolders: true,
+ },
+ },
+ }).appearance.sidebar;
+ expect(sidebar).toEqual({
+ showHiddenFiles: true,
+ showOnlyMarkdownFiles: true,
+ showSkillsSection: false,
+ showOkFolders: true,
+ });
+ });
+});
+
describe('legacy upload.* keys remain non-authoritative', () => {
test('upload.* keys pass through looseObject without schema error', () => {
const result = ConfigSchema.safeParse({
diff --git a/packages/core/src/config/schema.ts b/packages/core/src/config/schema.ts
index 6ceb87e55..485810ddb 100644
--- a/packages/core/src/config/schema.ts
+++ b/packages/core/src/config/schema.ts
@@ -128,13 +128,13 @@ export const ConfigSchema = z.looseObject({
// pattern and not what users expect from the chrome toggle.
// SchemaStore validation flags it in project YAML; chrome toggle
// always writes via `userBinding.patch()`.
- // `appearance.sidebar.showHiddenFiles` is a per-machine, per-project
- // visibility toggle. Project scope would
- // bleed one teammate's "show hidden files" choice across collaborators via
- // git; user scope would force a single global setting for every OK
- // project. `project-local` (gitignored `<projectDir>/.ok/local/config.yml`)
- // is the only correct home — each teammate chooses independently for
- // their machine.
+ // The `appearance.sidebar.*` leaves are per-machine, per-project view
+ // toggles (hidden files, only-markdown filter, Skills section, .ok
+ // reveal). Project scope would bleed one teammate's view choice across
+ // collaborators via git; user scope would force a single global setting
+ // for every OK project. `project-local` (gitignored
+ // `<projectDir>/.ok/local/config.yml`) is the only correct home — each
+ // teammate chooses independently for their machine.
//
// `appearance.preview.autoOpen` is USER-scope: whether the agent
// auto-opens or refreshes the OK preview UI on edits is a personal
@@ -184,6 +184,36 @@ export const ConfigSchema = z.looseObject({
'Show dot-prefixed entries (e.g. .ok/, .okignore) in the file tree. Per-machine (project-local) — not shared with collaborators.',
})
.default(false),
+ showOnlyMarkdownFiles: z
+ .boolean()
+ .register(fieldRegistry, {
+ scope: 'project-local',
+ agentSettable: false,
+ defaultScope: 'project-local',
+ description:
+ 'Show only markdown documents (.md/.mdx) and folders in the file tree, hiding other file types from view. View-only: hidden files stay on disk and remain reachable via links and search. Per-machine (project-local) — not shared with collaborators.',
+ })
+ .default(false),
+ showSkillsSection: z
+ .boolean()
+ .register(fieldRegistry, {
+ scope: 'project-local',
+ agentSettable: false,
+ defaultScope: 'project-local',
+ description:
+ 'Show the Skills section in the sidebar. Skill documents remain reachable via links and search while the section is hidden. Per-machine (project-local) — not shared with collaborators.',
+ })
+ .default(true),
+ showOkFolders: z
+ .boolean()
+ .register(fieldRegistry, {
+ scope: 'project-local',
+ agentSettable: false,
+ defaultScope: 'project-local',
+ description:
+ 'Show .ok folders (skills, templates, and other OpenKnowledge-managed state) in the file tree as read-only entries. .ok/worktrees and .ok/local never appear. Per-machine (project-local) — not shared with collaborators.',
+ })
+ .default(false),
})
.optional(),
})
diff --git a/packages/core/src/config/validate-patch-scopes.test.ts b/packages/core/src/config/validate-patch-scopes.test.ts
index c8ab6908e..47dd71fec 100644
--- a/packages/core/src/config/validate-patch-scopes.test.ts
+++ b/packages/core/src/config/validate-patch-scopes.test.ts
@@ -28,6 +28,34 @@ describe('validatePatchScopes', () => {
expect(violation?.actualScope).toBe('user');
});
+ test('returns null for the sidebar view toggles written by a project-local writer', () => {
+ expect(
+ validatePatchScopes(
+ {
+ appearance: {
+ sidebar: {
+ showOnlyMarkdownFiles: true,
+ showSkillsSection: false,
+ showOkFolders: true,
+ },
+ },
+ },
+ 'project-local',
+ ),
+ ).toBeNull();
+ });
+
+ test('returns SCOPE_VIOLATION for a sidebar view toggle written by a project writer', () => {
+ const violation = validatePatchScopes(
+ { appearance: { sidebar: { showOnlyMarkdownFiles: true } } },
+ 'project',
+ );
+ expect(violation?.code).toBe('SCOPE_VIOLATION');
+ expect(violation?.path).toEqual(['appearance', 'sidebar', 'showOnlyMarkdownFiles']);
+ expect(violation?.expectedScope).toBe('project-local');
+ expect(violation?.actualScope).toBe('project');
+ });
+
test('returns null for autoSync.default (project) written by a project writer', () => {
// The committed sibling of autoSync.enabled: true/false/null are all valid
// project-scope writes (null clears the committed default → "ask").
diff --git a/packages/core/src/constants/menu-labels.ts b/packages/core/src/constants/menu-labels.ts
index 026fa6cf8..d316b7080 100644
--- a/packages/core/src/constants/menu-labels.ts
+++ b/packages/core/src/constants/menu-labels.ts
@@ -33,6 +33,9 @@ export const MENU_LABELS = {
fullPath: 'Full path',
relativePath: 'Relative path',
showHiddenFiles: 'Show hidden files',
+ showOkFolders: 'Show .ok folders',
+ showOnlyMarkdownFiles: 'Show only markdown files',
+ showSkillsSection: 'Show skills section',
expandAll: 'Expand all',
collapseAll: 'Collapse all',
} as const;
diff --git a/packages/core/src/desktop-bridge.ts b/packages/core/src/desktop-bridge.ts
index 45f44f8c2..5a1809d45 100644
--- a/packages/core/src/desktop-bridge.ts
+++ b/packages/core/src/desktop-bridge.ts
@@ -81,6 +81,9 @@ type OkMenuAction =
| 'copy-relative-path'
// View menu items.
| 'toggle-show-hidden-files'
+ | 'toggle-show-ok-folders'
+ | 'toggle-show-only-markdown-files'
+ | 'toggle-show-skills-section'
| 'expand-all-tree'
| 'collapse-all-tree'
| 'toggle-doc-panel'
@@ -774,6 +777,9 @@ type OkEditorActiveTargetSnapshot =
*/
interface OkEditorViewMenuStateSnapshot {
readonly showHiddenFiles: boolean;
+ readonly showOkFolders: boolean;
+ readonly showOnlyMarkdownFiles: boolean;
+ readonly showSkillsSection: boolean;
readonly canExpandAll: boolean;
readonly canCollapseAll: boolean;
readonly sidebarVisible: boolean;
diff --git a/packages/desktop/src/main/index.ts b/packages/desktop/src/main/index.ts
index 5d4a0693c..497da3088 100644
--- a/packages/desktop/src/main/index.ts
+++ b/packages/desktop/src/main/index.ts
@@ -337,7 +337,11 @@ import {
} from './url-scheme.ts';
import { migrateLegacyUserDataDir } from './userdata-migration.ts';
import { buildUtilityForkEnv } from './utility-fork-env.ts';
-import { mergeViewMenuState } from './view-menu-state.ts';
+import {
+ buildViewMenuStateDeps,
+ createDefaultEditorViewMenuState,
+ mergeViewMenuState,
+} from './view-menu-state.ts';
import {
type BrowserWindowLike,
setWindowInstanceLabel,
@@ -814,29 +818,10 @@ let editorActiveTarget: EditorActiveTargetSnapshot = { kind: null };
* `ok:editor:view-menu-state-changed`. Drives the View menu's checkbox
* reflection for the visibility toggles and the smart-hide on Expand All /
* Collapse All. Module-scope rather than per-window for the same reason
- * `editorActiveTarget` is — the menu is a singleton. Defaults match the
- * renderer's resolved defaults so the View menu reflects the right state
- * before the first renderer push lands: Show hidden files off, and both
- * Expand/Collapse rendered (no smart-hide) so the items are reachable.
+ * `editorActiveTarget` is — the menu is a singleton. Pre-push defaults
+ * (and their rationale) live with `createDefaultEditorViewMenuState`.
*/
-let editorViewMenuState: EditorViewMenuStateSnapshot = {
- showHiddenFiles: false,
- canExpandAll: true,
- canCollapseAll: true,
- // Initial menu-label assumption before the first renderer push lands.
- // FileSidebar / EditorArea push the actual resolved state on mount (the
- // renderer computes it synchronously from the partition resolver), but
- // until then the View-menu items default to "Hide …" — matching the
- // common wide-window startup where both sidebars resolve to expanded.
- sidebarVisible: true,
- docPanelVisible: true,
- // Terminal starts hidden — the View menu reads "Show Terminal" until the
- // renderer pushes its first terminal-visibility snapshot.
- terminalVisible: false,
- // No session is mounted until the user first opens the dock, so the Terminal
- // menu's "Kill Terminal" item stays disabled until the renderer reports live.
- terminalLive: false,
-};
+let editorViewMenuState: EditorViewMenuStateSnapshot = createDefaultEditorViewMenuState();
/**
* electron-vite dev-server URL. Set by `electron-vite dev` at launch time.
@@ -2152,27 +2137,13 @@ async function runApplicationMenuRefresh(): Promise<void> {
onCopyFullPath: () => sendMenuActionToFocused('copy-full-path'),
onCopyRelativePath: () => sendMenuActionToFocused('copy-relative-path'),
// View menu items reflect the latest renderer-pushed snapshot via
- // `ok:editor:view-menu-state-changed`. Defaults at the snapshot
- // declaration site keep the menu reachable before the first push lands.
- // Toggling still fires `ok:menu-action` which the renderer routes
- // through `projectLocalBinding.patch(...)`; the resulting CRDT
- // mutation triggers a sibling push back so the checkmark snaps.
- showHiddenFilesChecked: editorViewMenuState.showHiddenFiles,
- canExpandAll: editorViewMenuState.canExpandAll,
- canCollapseAll: editorViewMenuState.canCollapseAll,
- sidebarVisible: editorViewMenuState.sidebarVisible,
- docPanelVisible: editorViewMenuState.docPanelVisible,
- terminalVisible: editorViewMenuState.terminalVisible,
- terminalLive: editorViewMenuState.terminalLive,
- onToggleShowHiddenFiles: () => sendMenuActionToFocused('toggle-show-hidden-files'),
- onToggleSidebar: () => sendMenuActionToFocused('toggle-sidebar'),
- onToggleDocPanel: () => sendMenuActionToFocused('toggle-doc-panel'),
- onToggleTerminal: () => sendMenuActionToFocused('toggle-terminal'),
- onNewTerminal: () => sendMenuActionToFocused('new-terminal'),
- onKillTerminal: () => sendMenuActionToFocused('kill-terminal'),
+ // `ok:editor:view-menu-state-changed`; `buildViewMenuStateDeps` owns the
+ // field/action mapping. Toggling fires `ok:menu-action` which the
+ // renderer routes through `projectLocalBinding.patch(...)`; the
+ // resulting CRDT mutation triggers a sibling push back so the checkmark
+ // snaps.
+ ...buildViewMenuStateDeps(editorViewMenuState, sendMenuActionToFocused),
onNewTerminalWindow: () => openTerminalWindow(),
- onExpandAll: () => sendMenuActionToFocused('expand-all-tree'),
- onCollapseAll: () => sendMenuActionToFocused('collapse-all-tree'),
// Edit -> "Check Spelling While Typing": the checkbox reflects the
// persisted app-wide flag; the click flips it through the shared toggle
// (session + persist + menu rebuild) so this and the in-editor
diff --git a/packages/desktop/src/main/menu.ts b/packages/desktop/src/main/menu.ts
index 9d45f5bc3..0468f6caa 100644
--- a/packages/desktop/src/main/menu.ts
+++ b/packages/desktop/src/main/menu.ts
@@ -210,15 +210,25 @@ export interface MenuDeps {
onCopyFullPath?(): void;
onCopyRelativePath?(): void;
/**
- * View menu visibility-toggle state. When undefined, the View-menu
- * Show … check items render unchecked. These mirror the sidebar checkbox
- * state — main reads the latest snapshot pushed from the renderer (via
- * the active-target push or a sibling notification) so both surfaces
- * (sidebar context menu, View menu) stay in sync.
+ * View menu visibility-toggle state. When undefined, each View-menu
+ * Show … check item renders at its config-schema default. These mirror
+ * the sidebar checkbox state — main reads the latest snapshot pushed
+ * from the renderer (via the active-target push or a sibling
+ * notification) so all surfaces (tree-options popover, sidebar context
+ * menu, View menu) stay in sync.
*/
showHiddenFilesChecked?: boolean;
/** View → Show hidden files click handler — flips the projectLocalBinding flag. */
onToggleShowHiddenFiles?(): void;
+ showOkFoldersChecked?: boolean;
+ /** View → Show .ok folders click handler — flips the projectLocalBinding flag. */
+ onToggleShowOkFolders?(): void;
+ showOnlyMarkdownFilesChecked?: boolean;
+ /** View → Show only markdown files click handler — flips the projectLocalBinding flag. */
+ onToggleShowOnlyMarkdownFiles?(): void;
+ showSkillsSectionChecked?: boolean;
+ /** View → Show skills section click handler — flips the projectLocalBinding flag. */
+ onToggleShowSkillsSection?(): void;
/**
* Sidebar visibility — drives the View → Show/Hide sidebar item's label
* (Apple HIG convention: single row whose label toggles based on current
@@ -629,11 +639,14 @@ export function buildMenuTemplate(deps: MenuDeps): MenuItemConstructorOptions[]
click: () => deps.onToggleTerminal?.(),
},
{ type: 'separator' },
- // File-display visibility toggle. Checkbox state mirrors the sidebar's
- // empty-space + folder menu items. Toggling here flips the
- // projectLocalBinding flag via the renderer's menu-action handler;
- // the resulting CRDT write propagates back through merged config so
- // both surfaces (sidebar + View menu) stay in sync.
+ // Sidebar visibility toggles. Checkbox state mirrors the sidebar's
+ // tree-options popover + empty-space context menu, in the same order.
+ // Toggling any of them flips the projectLocalBinding flag via the
+ // renderer's menu-action handler; the resulting CRDT write propagates
+ // back through merged config so every surface stays in sync. The
+ // unwired `checked` fallbacks match the renderer's resolved config
+ // defaults (hidden files + .ok folders + only-markdown off, skills
+ // section on).
{
label: MENU_LABELS.showHiddenFiles,
accelerator: 'CmdOrCtrl+Shift+.',
@@ -642,6 +655,27 @@ export function buildMenuTemplate(deps: MenuDeps): MenuItemConstructorOptions[]
enabled: deps.onToggleShowHiddenFiles !== undefined,
click: () => deps.onToggleShowHiddenFiles?.(),
},
+ {
+ label: MENU_LABELS.showOkFolders,
+ type: 'checkbox',
+ checked: deps.showOkFoldersChecked ?? false,
+ enabled: deps.onToggleShowOkFolders !== undefined,
+ click: () => deps.onToggleShowOkFolders?.(),
+ },
+ {
+ label: MENU_LABELS.showOnlyMarkdownFiles,
+ type: 'checkbox',
+ checked: deps.showOnlyMarkdownFilesChecked ?? false,
+ enabled: deps.onToggleShowOnlyMarkdownFiles !== undefined,
+ click: () => deps.onToggleShowOnlyMarkdownFiles?.(),
+ },
+ {
+ label: MENU_LABELS.showSkillsSection,
+ type: 'checkbox',
+ checked: deps.showSkillsSectionChecked ?? true,
+ enabled: deps.onToggleShowSkillsSection !== undefined,
+ click: () => deps.onToggleShowSkillsSection?.(),
+ },
{ type: 'separator' },
// Tree-scoped Expand/Collapse all. Smart-hide via `visible: false`
// (rather than `enabled: false`) so a fully-expanded tree doesn't
diff --git a/packages/desktop/src/main/state-store.ts b/packages/desktop/src/main/state-store.ts
index f1e3dc64f..c4c506e5d 100644
--- a/packages/desktop/src/main/state-store.ts
+++ b/packages/desktop/src/main/state-store.ts
@@ -1,6 +1,6 @@
/**
- * Pure state-store helpers for app-level persistence (recent projects, last-
- * opened, window bounds). The main entry persists this to
+ * Pure state-store helpers for app-level persistence (recent projects,
+ * last-opened, spell-check preference). The main entry persists this to
* `app.getPath('userData')/state.json`; tests exercise the pure helpers
* directly without an Electron process.
*
diff --git a/packages/desktop/src/main/view-menu-state.test.ts b/packages/desktop/src/main/view-menu-state.test.ts
index 32ab24ea3..a57da4a91 100644
--- a/packages/desktop/src/main/view-menu-state.test.ts
+++ b/packages/desktop/src/main/view-menu-state.test.ts
@@ -1,9 +1,16 @@
import { describe, expect, test } from 'bun:test';
-import { mergeViewMenuState } from './view-menu-state';
+import {
+ buildViewMenuStateDeps,
+ createDefaultEditorViewMenuState,
+ mergeViewMenuState,
+} from './view-menu-state';
describe('mergeViewMenuState — multi-publisher non-clobbering contract', () => {
const initial = {
showHiddenFiles: false,
+ showOkFolders: false,
+ showOnlyMarkdownFiles: false,
+ showSkillsSection: true,
canExpandAll: true,
canCollapseAll: true,
sidebarVisible: true,
@@ -24,6 +31,9 @@ describe('mergeViewMenuState — multi-publisher non-clobbering contract', () =>
expect(afterEditorArea).toEqual({
showHiddenFiles: true,
+ showOkFolders: false,
+ showOnlyMarkdownFiles: false,
+ showSkillsSection: true,
canExpandAll: false,
canCollapseAll: false,
sidebarVisible: false,
@@ -31,6 +41,28 @@ describe('mergeViewMenuState — multi-publisher non-clobbering contract', () =>
});
});
+ test('FileSidebar visibility push (all four toggles) preserves the terminal + doc-panel fields', () => {
+ const base = createDefaultEditorViewMenuState();
+ const afterTerminal = mergeViewMenuState(base, { terminalVisible: true, terminalLive: true });
+
+ const afterVisibilityPush = mergeViewMenuState(afterTerminal, {
+ showHiddenFiles: true,
+ showOkFolders: true,
+ showOnlyMarkdownFiles: true,
+ showSkillsSection: false,
+ });
+
+ expect(afterVisibilityPush).toEqual({
+ ...base,
+ terminalVisible: true,
+ terminalLive: true,
+ showHiddenFiles: true,
+ showOkFolders: true,
+ showOnlyMarkdownFiles: true,
+ showSkillsSection: false,
+ });
+ });
+
test('FileSidebar push (5 fields) preserves EditorArea docPanelVisible', () => {
const afterEditorArea = mergeViewMenuState(initial, {
docPanelVisible: false,
@@ -82,3 +114,86 @@ describe('mergeViewMenuState — multi-publisher non-clobbering contract', () =>
expect(afterToggleHide.terminalVisible).toBe(false);
});
});
+
+describe('createDefaultEditorViewMenuState — pre-first-push menu state', () => {
+ test("matches the renderer's resolved config defaults exactly", () => {
+ // toEqual on the full object: adding a snapshot field without deciding
+ // its pre-push default must fail here, not silently read undefined.
+ expect(createDefaultEditorViewMenuState()).toEqual({
+ showHiddenFiles: false,
+ showOkFolders: false,
+ showOnlyMarkdownFiles: false,
+ showSkillsSection: true,
+ canExpandAll: true,
+ canCollapseAll: true,
+ sidebarVisible: true,
+ docPanelVisible: true,
+ terminalVisible: false,
+ terminalLive: false,
+ });
+ });
+});
+
+describe('buildViewMenuStateDeps — snapshot → menu-deps wiring', () => {
+ // Every field deliberately differs from the pre-push default so an
+ // accidental default-instead-of-snapshot read fails the mapping assertions.
+ const snapshot = {
+ showHiddenFiles: true,
+ showOkFolders: true,
+ showOnlyMarkdownFiles: true,
+ showSkillsSection: false,
+ canExpandAll: false,
+ canCollapseAll: false,
+ sidebarVisible: false,
+ docPanelVisible: false,
+ terminalVisible: true,
+ terminalLive: true,
+ } as const;
+
+ test('maps every snapshot field onto its menu dep', () => {
+ const deps = buildViewMenuStateDeps(snapshot, () => {});
+ expect(deps.showHiddenFilesChecked).toBe(true);
+ expect(deps.showOkFoldersChecked).toBe(true);
+ expect(deps.showOnlyMarkdownFilesChecked).toBe(true);
+ expect(deps.showSkillsSectionChecked).toBe(false);
+ expect(deps.canExpandAll).toBe(false);
+ expect(deps.canCollapseAll).toBe(false);
+ expect(deps.sidebarVisible).toBe(false);
+ expect(deps.docPanelVisible).toBe(false);
+ expect(deps.terminalVisible).toBe(true);
+ expect(deps.terminalLive).toBe(true);
+ });
+
+ test('each toggle / tree / terminal handler dispatches its menu-action ID', () => {
+ const dispatched: string[] = [];
+ const deps = buildViewMenuStateDeps(createDefaultEditorViewMenuState(), (action) => {
+ dispatched.push(action);
+ });
+
+ deps.onToggleShowHiddenFiles?.();
+ deps.onToggleShowOkFolders?.();
+ deps.onToggleShowOnlyMarkdownFiles?.();
+ deps.onToggleShowSkillsSection?.();
+ deps.onToggleSidebar?.();
+ deps.onToggleDocPanel?.();
+ deps.onToggleTerminal?.();
+ deps.onNewTerminal?.();
+ deps.onKillTerminal?.();
+ deps.onExpandAll?.();
+ deps.onCollapseAll?.();
+
+ expect(dispatched).toEqual([
+ 'toggle-show-hidden-files',
+ 'toggle-show-ok-folders',
+ 'toggle-show-only-markdown-files',
+ 'toggle-show-skills-section',
+ 'toggle-sidebar',
+ 'toggle-doc-panel',
+ 'toggle-terminal',
+ 'new-terminal',
+ 'kill-terminal',
+ 'expand-all-tree',
+ 'collapse-all-tree',
+ ]);
+ });
+});
diff --git a/packages/desktop/src/main/view-menu-state.ts b/packages/desktop/src/main/view-menu-state.ts
index f4ba4065f..1d076fe24 100644
--- a/packages/desktop/src/main/view-menu-state.ts
+++ b/packages/desktop/src/main/view-menu-state.ts
@@ -1,4 +1,6 @@
+import type { OkMenuAction } from '../shared/bridge-contract';
import type { EditorViewMenuStateSnapshot } from '../shared/ipc-channels';
+import type { MenuDeps } from './menu';
export function mergeViewMenuState(
prev: EditorViewMenuStateSnapshot,
@@ -6,3 +8,95 @@ export function mergeViewMenuState(
): EditorViewMenuStateSnapshot {
return { ...prev, ...partial };
}
+
+/**
+ * The View-menu state main holds before the first renderer push lands.
+ * Defaults match the renderer's resolved config defaults so the menu
+ * reflects the right state at startup: Show hidden files + Show .ok
+ * folders + Show only markdown files off, Show skills section on, both
+ * Expand/Collapse rendered (no smart-hide), sidebar + doc panel assumed
+ * visible (the common wide-window startup), terminal hidden with no live
+ * session.
+ */
+export function createDefaultEditorViewMenuState(): EditorViewMenuStateSnapshot {
+ return {
+ showHiddenFiles: false,
+ showOkFolders: false,
+ showOnlyMarkdownFiles: false,
+ showSkillsSection: true,
+ canExpandAll: true,
+ canCollapseAll: true,
+ sidebarVisible: true,
+ docPanelVisible: true,
+ terminalVisible: false,
+ terminalLive: false,
+ };
+}
+
+/**
+ * The slice of `MenuDeps` derived from the renderer-pushed snapshot plus the
+ * menu-action dispatchers that round-trip back to the renderer. `Pick` keeps
+ * every key checked against `MenuDeps` — a spread into the menu-install call
+ * would let a misnamed field pass silently (spreads skip excess-property
+ * checks).
+ */
+type ViewMenuStateDeps = Pick<
+ MenuDeps,
+ | 'showHiddenFilesChecked'
+ | 'showOkFoldersChecked'
+ | 'showOnlyMarkdownFilesChecked'
+ | 'showSkillsSectionChecked'
+ | 'canExpandAll'
+ | 'canCollapseAll'
+ | 'sidebarVisible'
+ | 'docPanelVisible'
+ | 'terminalVisible'
+ | 'terminalLive'
+ | 'onToggleShowHiddenFiles'
+ | 'onToggleShowOkFolders'
+ | 'onToggleShowOnlyMarkdownFiles'
+ | 'onToggleShowSkillsSection'
+ | 'onToggleSidebar'
+ | 'onToggleDocPanel'
+ | 'onToggleTerminal'
+ | 'onNewTerminal'
+ | 'onKillTerminal'
+ | 'onExpandAll'
+ | 'onCollapseAll'
+>;
+
+/**
+ * Map the view-menu snapshot onto menu deps. Pure and separate from the
+ * Electron entry point so the field/action wiring stays unit-testable — the
+ * type mirrors pin the snapshot SHAPE, but nothing else checks that each
+ * field lands on the right dep or that each toggle dispatches the right
+ * menu-action ID.
+ */
+export function buildViewMenuStateDeps(
+ state: EditorViewMenuStateSnapshot,
+ sendMenuAction: (action: OkMenuAction) => void,
+): ViewMenuStateDeps {
+ return {
+ showHiddenFilesChecked: state.showHiddenFiles,
+ showOkFoldersChecked: state.showOkFolders,
+ showOnlyMarkdownFilesChecked: state.showOnlyMarkdownFiles,
+ showSkillsSectionChecked: state.showSkillsSection,
+ canExpandAll: state.canExpandAll,
+ canCollapseAll: state.canCollapseAll,
+ sidebarVisible: state.sidebarVisible,
+ docPanelVisible: state.docPanelVisible,
+ terminalVisible: state.terminalVisible,
+ terminalLive: state.terminalLive,
+ onToggleShowHiddenFiles: () => sendMenuAction('toggle-show-hidden-files'),
+ onToggleShowOkFolders: () => sendMenuAction('toggle-show-ok-folders'),
+ onToggleShowOnlyMarkdownFiles: () => sendMenuAction('toggle-show-only-markdown-files'),
+ onToggleShowSkillsSection: () => sendMenuAction('toggle-show-skills-section'),
+ onToggleSidebar: () => sendMenuAction('toggle-sidebar'),
+ onToggleDocPanel: () => sendMenuAction('toggle-doc-panel'),
+ onToggleTerminal: () => sendMenuAction('toggle-terminal'),
+ onNewTerminal: () => sendMenuAction('new-terminal'),
+ onKillTerminal: () => sendMenuAction('kill-terminal'),
+ onExpandAll: () => sendMenuAction('expand-all-tree'),
+ onCollapseAll: () => sendMenuAction('collapse-all-tree'),
+ };
+}
diff --git a/packages/desktop/src/shared/bridge-contract.ts b/packages/desktop/src/shared/bridge-contract.ts
index 49bde737f..80c8972e5 100644
--- a/packages/desktop/src/shared/bridge-contract.ts
+++ b/packages/desktop/src/shared/bridge-contract.ts
@@ -200,11 +200,14 @@ export type OkMenuAction =
| 'copy-full-path'
| 'copy-relative-path'
// View menu items. Sidebar visibility toggles
- // (mirror the sidebar's empty-space + folder menu state) + tree-scoped
- // Expand/Collapse All (sibling of subtree-scoped versions on folder
- // rows). Renderer handler reads merged config / Pierre tree state to
- // dispatch the appropriate primitive when the menu item is clicked.
+ // (mirror the sidebar's tree-options popover + empty-space menu state) +
+ // tree-scoped Expand/Collapse All (sibling of subtree-scoped versions on
+ // folder rows). Renderer handler reads merged config / Pierre tree state
+ // to dispatch the appropriate primitive when the menu item is clicked.
| 'toggle-show-hidden-files'
+ | 'toggle-show-ok-folders'
+ | 'toggle-show-only-markdown-files'
+ | 'toggle-show-skills-section'
| 'expand-all-tree'
| 'collapse-all-tree'
| 'toggle-doc-panel'
@@ -809,6 +812,9 @@ export type OkEditorActiveTargetSnapshot =
*/
export interface OkEditorViewMenuStateSnapshot {
readonly showHiddenFiles: boolean;
+ readonly showOkFolders: boolean;
+ readonly showOnlyMarkdownFiles: boolean;
+ readonly showSkillsSection: boolean;
readonly canExpandAll: boolean;
readonly canCollapseAll: boolean;
readonly sidebarVisible: boolean;
diff --git a/packages/desktop/src/shared/ipc-channels.ts b/packages/desktop/src/shared/ipc-channels.ts
index 281d84136..fb5878a46 100644
--- a/packages/desktop/src/shared/ipc-channels.ts
+++ b/packages/desktop/src/shared/ipc-channels.ts
@@ -620,6 +620,9 @@ export type EditorActiveTargetSnapshot =
*/
export interface EditorViewMenuStateSnapshot {
readonly showHiddenFiles: boolean;
+ readonly showOkFolders: boolean;
+ readonly showOnlyMarkdownFiles: boolean;
+ readonly showSkillsSection: boolean;
readonly canExpandAll: boolean;
readonly canCollapseAll: boolean;
readonly sidebarVisible: boolean;
diff --git a/packages/desktop/tests/integration/m1-smoke.test.ts b/packages/desktop/tests/integration/m1-smoke.test.ts
index e32beec65..9f4eef9fa 100644
--- a/packages/desktop/tests/integration/m1-smoke.test.ts
+++ b/packages/desktop/tests/integration/m1-smoke.test.ts
@@ -599,13 +599,18 @@ describe('M1 smoke', () => {
expect(coreMembers.size).toBeGreaterThan(0);
expect(appMembers.size).toBeGreaterThan(0);
// 26 + 2 worktree actions (`new-worktree`, `switch-worktree`) for the
- // worktree selector (worktree = window).
- expect(desktopMembers.size).toBe(28);
+ // worktree selector (worktree = window) + 3 sidebar visibility toggles
+ // (`toggle-show-ok-folders`, `toggle-show-only-markdown-files`,
+ // `toggle-show-skills-section`).
+ expect(desktopMembers.size).toBe(31);
expect(desktopMembers).toEqual(coreMembers);
expect(desktopMembers).toEqual(appMembers);
- // Pin the surviving visibility toggle explicitly: a bare count check
- // wouldn't notice a simultaneous add+remove that nets to the same size.
+ // Pin the visibility toggles explicitly: a bare count check wouldn't
+ // notice a simultaneous add+remove that nets to the same size.
expect(desktopMembers.has('toggle-show-hidden-files')).toBe(true);
+ expect(desktopMembers.has('toggle-show-ok-folders')).toBe(true);
+ expect(desktopMembers.has('toggle-show-only-markdown-files')).toBe(true);
+ expect(desktopMembers.has('toggle-show-skills-section')).toBe(true);
expect(desktopMembers.has('new-worktree')).toBe(true);
expect(desktopMembers.has('switch-worktree')).toBe(true);
});
diff --git a/packages/desktop/tests/main/menu.test.ts b/packages/desktop/tests/main/menu.test.ts
index 95142e5fc..7e0e7b5d4 100644
--- a/packages/desktop/tests/main/menu.test.ts
+++ b/packages/desktop/tests/main/menu.test.ts
@@ -821,6 +821,164 @@ describe('buildMenuTemplate — View menu visibility toggles + tree-scoped expan
});
});
+describe('buildMenuTemplate — View → Show .ok folders', () => {
+ test('renders as a checkbox, unchecked by default', () => {
+ const template = buildMenuTemplate(makeDeps({ onToggleShowOkFolders: mock(() => {}) }));
+ const item = findByLabel(template, 'Show .ok folders');
+ expect(item).toBeDefined();
+ expect(item?.type).toBe('checkbox');
+ expect(item?.checked).toBe(false);
+ expect(item?.enabled).toBe(true);
+ });
+
+ test('reflects showOkFoldersChecked', () => {
+ const template = buildMenuTemplate(
+ makeDeps({ onToggleShowOkFolders: mock(() => {}), showOkFoldersChecked: true }),
+ );
+ expect(findByLabel(template, 'Show .ok folders')?.checked).toBe(true);
+ });
+
+ test('DISABLED when the toggle handler is missing (unit-test default)', () => {
+ const template = buildMenuTemplate(makeDeps());
+ expect(findByLabel(template, 'Show .ok folders')?.enabled).toBe(false);
+ });
+
+ test('sits directly after Show hidden files (menu order across every surface)', () => {
+ const template = buildMenuTemplate(makeDeps());
+ const view = findByLabel(template, 'View');
+ const sub = view?.submenu as MenuItemConstructorOptions[] | undefined;
+ const labels = sub?.map((i) => i.label).filter(Boolean) ?? [];
+ const hiddenIdx = labels.indexOf('Show hidden files');
+ const okIdx = labels.indexOf('Show .ok folders');
+ const onlyMdIdx = labels.indexOf('Show only markdown files');
+ expect(hiddenIdx).toBeGreaterThan(-1);
+ expect(okIdx).toBe(hiddenIdx + 1);
+ expect(onlyMdIdx).toBe(okIdx + 1);
+ });
+
+ test('binds no keyboard accelerator and click dispatches the toggle dep', () => {
+ const onToggleShowOkFolders = mock(() => {});
+ const template = buildMenuTemplate(makeDeps({ onToggleShowOkFolders }));
+ const item = findByLabel(template, 'Show .ok folders');
+ expect(item?.accelerator).toBeUndefined();
+ (item?.click as (() => void) | undefined)?.();
+ expect(onToggleShowOkFolders).toHaveBeenCalledTimes(1);
+ });
+
+ test('click is a safe no-op when the dep is omitted', () => {
+ const template = buildMenuTemplate(makeDeps());
+ expect(() =>
+ (findByLabel(template, 'Show .ok folders')?.click as (() => void) | undefined)?.(),
+ ).not.toThrow();
+ });
+});
+
+describe('buildMenuTemplate — View → Show only markdown files / Show skills section', () => {
+ test('Show only markdown files renders as a checkbox, unchecked by default', () => {
+ const template = buildMenuTemplate(makeDeps({ onToggleShowOnlyMarkdownFiles: mock(() => {}) }));
+ const item = findByLabel(template, 'Show only markdown files');
+ expect(item).toBeDefined();
+ expect(item?.type).toBe('checkbox');
+ expect(item?.checked).toBe(false);
+ expect(item?.enabled).toBe(true);
+ });
+
+ test('Show only markdown files reflects showOnlyMarkdownFilesChecked', () => {
+ const template = buildMenuTemplate(
+ makeDeps({
+ onToggleShowOnlyMarkdownFiles: mock(() => {}),
+ showOnlyMarkdownFilesChecked: true,
+ }),
+ );
+ expect(findByLabel(template, 'Show only markdown files')?.checked).toBe(true);
+ });
+
+ test('Show skills section renders as a checkbox, CHECKED by default (section is default-on)', () => {
+ // The unwired-checked default must match the renderer's resolved config
+ // default (showSkillsSection ?? true) so the menu reads correctly before
+ // the first renderer push lands — the inverse of Show hidden files.
+ const template = buildMenuTemplate(makeDeps({ onToggleShowSkillsSection: mock(() => {}) }));
+ const item = findByLabel(template, 'Show skills section');
+ expect(item).toBeDefined();
+ expect(item?.type).toBe('checkbox');
+ expect(item?.checked).toBe(true);
+ expect(item?.enabled).toBe(true);
+ });
+
+ test('Show skills section reflects showSkillsSectionChecked', () => {
+ const template = buildMenuTemplate(
+ makeDeps({ onToggleShowSkillsSection: mock(() => {}), showSkillsSectionChecked: false }),
+ );
+ expect(findByLabel(template, 'Show skills section')?.checked).toBe(false);
+ });
+
+ test('both DISABLED when their toggle handler is missing (unit-test default)', () => {
+ const template = buildMenuTemplate(makeDeps());
+ expect(findByLabel(template, 'Show only markdown files')?.enabled).toBe(false);
+ expect(findByLabel(template, 'Show skills section')?.enabled).toBe(false);
+ });
+
+ test('neither binds a keyboard accelerator (only Show hidden files carries Cmd+Shift+.)', () => {
+ const template = buildMenuTemplate(
+ makeDeps({
+ onToggleShowOnlyMarkdownFiles: mock(() => {}),
+ onToggleShowSkillsSection: mock(() => {}),
+ }),
+ );
+ expect(findByLabel(template, 'Show only markdown files')?.accelerator).toBeUndefined();
+ expect(findByLabel(template, 'Show skills section')?.accelerator).toBeUndefined();
+ });
+
+ test('clicks dispatch their toggle deps', () => {
+ const onToggleShowOnlyMarkdownFiles = mock(() => {});
+ const onToggleShowSkillsSection = mock(() => {});
+ const template = buildMenuTemplate(
+ makeDeps({ onToggleShowOnlyMarkdownFiles, onToggleShowSkillsSection }),
+ );
+ (findByLabel(template, 'Show only markdown files')?.click as (() => void) | undefined)?.();
+ expect(onToggleShowOnlyMarkdownFiles).toHaveBeenCalledTimes(1);
+ (findByLabel(template, 'Show skills section')?.click as (() => void) | undefined)?.();
+ expect(onToggleShowSkillsSection).toHaveBeenCalledTimes(1);
+ });
+
+ test('clicks are safe no-ops when the deps are omitted', () => {
+ const template = buildMenuTemplate(makeDeps());
+ expect(() =>
+ (findByLabel(template, 'Show only markdown files')?.click as (() => void) | undefined)?.(),
+ ).not.toThrow();
+ expect(() =>
+ (findByLabel(template, 'Show skills section')?.click as (() => void) | undefined)?.(),
+ ).not.toThrow();
+ });
+
+ test('order: Show hidden files → Show .ok folders → Show only markdown files → Show skills section → expand/collapse', () => {
+ // Same order as the tree-options popover Show group so every surface
+ // presents the visibility toggles identically.
+ const template = buildMenuTemplate(
+ makeDeps({
+ onToggleShowHiddenFiles: mock(() => {}),
+ onToggleShowOkFolders: mock(() => {}),
+ onToggleShowOnlyMarkdownFiles: mock(() => {}),
+ onToggleShowSkillsSection: mock(() => {}),
+ onExpandAll: mock(() => {}),
+ }),
+ );
+ const view = findByLabel(template, 'View');
+ const sub = view?.submenu as MenuItemConstructorOptions[] | undefined;
+ const labels = sub?.map((i) => i.label ?? `[role:${i.role ?? 'sep'}]`) ?? [];
+ const hiddenIdx = labels.indexOf('Show hidden files');
+ const okIdx = labels.indexOf('Show .ok folders');
+ const onlyMdIdx = labels.indexOf('Show only markdown files');
+ const skillsIdx = labels.indexOf('Show skills section');
+ const expandIdx = labels.indexOf('Expand all');
+ expect(hiddenIdx).toBeGreaterThan(-1);
+ expect(okIdx).toBe(hiddenIdx + 1);
+ expect(onlyMdIdx).toBe(okIdx + 1);
+ expect(skillsIdx).toBe(onlyMdIdx + 1);
+ expect(expandIdx).toBeGreaterThan(skillsIdx);
+ });
+});
+
describe('buildMenuTemplate — View → Show/Hide sidebar', () => {
// The sidebar-toggle View-menu item follows Apple HIG convention (Finder's
// pattern): a single row whose label flips between "Show sidebar" /
diff --git a/packages/server/src/api-extension.ts b/packages/server/src/api-extension.ts
index 4bf8e0c2a..81b8bc0a2 100644
--- a/packages/server/src/api-extension.ts
+++ b/packages/server/src/api-extension.ts
@@ -1370,6 +1370,13 @@ export interface StreamShowAllOpts {
* the subtree.
*/
maxDepth?: number;
+ /**
+ * Admit `.ok` entries — minus `.ok/worktrees` and `.ok/local` — through the
+ * content filter's always-skip floor (see `ContentFilterReadOpts.showOk`).
+ * Backs `?showOk=true`; threaded into every filter consultation the walk
+ * and its `hasChildren` probe make.
+ */
+ showOk?: boolean;
}
export interface WalkShowAllOpts extends StreamShowAllOpts {
@@ -1396,8 +1403,10 @@ export interface WalkShowAllOpts extends StreamShowAllOpts {
* `build/`, `coverage/`, …) surface. The `ALWAYS_SKIP_DIRS` floor still prunes
* `.git/` / `node_modules/` / `.ok/` even under bypass (those trees are
* unbounded and never hold user markdown — pruning them is the Show All Files
- * OOM guard), and the un-bypassable STOP-rule gate keeps synthetic
- * `__system__` / `__config__` / `__user__` / `__local__` docs hidden.
+ * OOM guard); `showOk` re-admits `.ok` minus `worktrees`/`local`, the two
+ * children that can be repo-scale. The un-bypassable STOP-rule gate keeps
+ * synthetic `__system__` / `__config__` / `__user__` / `__local__` docs
+ * hidden.
*
* Yields the union DocumentListEntry shape:
* - dirs → kind: 'folder' (with `path`)
@@ -1414,8 +1423,12 @@ export interface WalkShowAllOpts extends StreamShowAllOpts {
export async function* streamShowAllEntries(
opts: StreamShowAllOpts,
): AsyncGenerator<DocumentListEntry, { truncated: boolean }, void> {
- const { contentDir, contentFilter, dirFilter, maxEntries, signal } = opts;
+ const { contentDir, contentFilter, dirFilter, maxEntries, signal, showOk } = opts;
const maxDepth = opts.maxDepth ?? Number.POSITIVE_INFINITY;
+ // One opts object for every filter consultation: the dir gates, the
+ // `hasChildren` probe, and the file backstop must agree on admission, or a
+ // revealed folder probes childless / yields rows its own dir gate pruned.
+ const filterOpts = { bypassFilters: true, showOk } as const;
showAllWalkInvocations += 1;
// Running count of yielded entries — the streaming analogue of the buffered
// `documents.length` cap probe. Shared across the whole traversal so the
@@ -1531,7 +1544,7 @@ export async function* streamShowAllEntries(
for (const entry of entries) {
const relPath = relDir ? `${relDir}/${entry.name}` : entry.name;
if (entry.isDirectory()) {
- if (contentFilter.isDirExcluded(relPath, { bypassFilters: true })) continue;
+ if (contentFilter.isDirExcluded(relPath, filterOpts)) continue;
// Symlink-escape parity with the main walk: a child that is a symlink to
// a directory outside contentDir must not count as an admitted child
// (the walk refuses to descend into it), so the probe must refuse it too.
@@ -1551,7 +1564,7 @@ export async function* streamShowAllEntries(
}
return true;
}
- if (entry.isFile() && !contentFilter.isExcluded(relPath, { bypassFilters: true })) {
+ if (entry.isFile() && !contentFilter.isExcluded(relPath, filterOpts)) {
return true;
}
}
@@ -1620,7 +1633,8 @@ export async function* streamShowAllEntries(
// bypassFilters:true admits gitignored + content-bearing skip-dirs
// (dist/, build/), but the ALWAYS_SKIP_DIRS floor still prunes
// .git/, node_modules/, .ok/ here — the Show All Files OOM guard.
- if (contentFilter.isDirExcluded(relPath, { bypassFilters: true })) continue;
+ // showOk re-admits .ok minus worktrees/local for the tree reveal.
+ if (contentFilter.isDirExcluded(relPath, filterOpts)) continue;
// Symlink-escape guard. `Dirent.isDirectory()` returns true for a
// symlink pointing at a directory; without canonical-path containment,
@@ -1724,7 +1738,7 @@ export async function* streamShowAllEntries(
}
const targetRel = toPosix(relative(contentDir, canonical));
if (canonStat.isDirectory()) {
- if (contentFilter.isDirExcluded(relPath, { bypassFilters: true })) continue;
+ if (contentFilter.isDirExcluded(relPath, filterOpts)) continue;
if (!passesDirFilter(relPath)) continue;
emitted += 1;
yield {
@@ -1741,7 +1755,7 @@ export async function* streamShowAllEntries(
continue;
}
if (!canonStat.isFile()) continue;
- if (contentFilter.isExcluded(relPath, { bypassFilters: true })) continue;
+ if (contentFilter.isExcluded(relPath, filterOpts)) continue;
if (!passesDirFilter(relPath)) continue;
emitted += 1;
if (isSupportedDocFile(entry.name)) {
@@ -1777,11 +1791,10 @@ export async function* streamShowAllEntries(
}
if (!entry.isFile()) continue;
- // `isExcluded(rel, {bypassFilters:true})` admits every file except the
- // unbypassable STOP-rule docs and the ALWAYS_SKIP_DIRS floor. Floor files
- // can't actually reach here — the dir gate above already skipped
- // .git/node_modules/.ok — so this is just the file-level backstop.
- if (contentFilter.isExcluded(relPath, { bypassFilters: true })) continue;
+ // The file-level backstop mirrors the dir gate's admission (shared
+ // filterOpts): floor files can't actually reach here — the dir gate
+ // above already skipped .git/node_modules/(non-revealed) .ok.
+ if (contentFilter.isExcluded(relPath, filterOpts)) continue;
if (!passesDirFilter(relPath)) continue;
let fileStat: import('node:fs').Stats | null = null;
@@ -1917,8 +1930,19 @@ function isValidRelativeContentPath(path: string): boolean {
return path.split('/').every((segment) => segment && segment !== '.' && segment !== '..');
}
+/**
+ * True when any `/`-separated segment of `path` is `.ok` or `.git`, at any
+ * depth — nested `<folder>/.ok/` is a first-class OK shape (folder metadata +
+ * templates), so a top-level-only check is not a boundary. Segments compare
+ * case-insensitively: on the default case-insensitive macOS filesystem an
+ * externally-addressed `.OK/x` IS `.ok/x`. Same segment walk as
+ * `pathHasAlwaysSkipSegment` in content-filter.ts.
+ */
function isReservedProjectStatePath(path: string): boolean {
- return path === '.ok' || path.startsWith('.ok/') || path === '.git' || path.startsWith('.git/');
+ return path.split('/').some((segment) => {
+ const normalized = segment.toLowerCase();
+ return normalized === OK_DIR || normalized === '.git';
+ });
}
function isReservedSyntheticFolderPath(path: string): boolean {
@@ -5818,6 +5842,10 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {
const url = new URL(req.url ?? '/', `http://${req.headers.host ?? 'localhost'}`);
const dir = url.searchParams.get('dir');
const showAll = url.searchParams.get('showAll') === 'true';
+ // Tree-listing reveal: admit `.ok` rows (minus worktrees/local) into
+ // the showAll walk. Inert without showAll — the watcher indexes
+ // backing the non-showAll path never hold non-skill `.ok` entries.
+ const showOk = url.searchParams.get('showOk') === 'true';
// Lazy per-directory contract: `?depth=1` yields only the
// scoped dir's immediate children (each folder stamped `hasChildren`),
// so the sidebar fetches one level on expand instead of the whole tree.
@@ -5896,6 +5924,7 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {
dirFilter: dir,
maxEntries,
maxDepth: showAllMaxDepth,
+ showOk,
signal: controller.signal,
});
let count = 0;
@@ -5952,9 +5981,12 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {
if (showAll && contentFilter) {
// Single-flight: coalesce concurrent identical walks into one. Key by
// the already-traversal-validated `dir` (the exact `dirFilter` the
- // walk consumes), so requests producing the same traversal share one
- // walk and one sorted result; distinct dirs run independently.
- const key = `showAll:${showAllMaxDepth === 1 ? 'd1:' : ''}${dir ?? ''}`;
+ // walk consumes) plus the depth and showOk markers, so only requests
+ // producing the same traversal share one walk and one sorted result.
+ // Coalescing across showOk modes would hand one caller the other
+ // mode's listing (`.ok` rows leaking to a plain caller, or silently
+ // missing for a reveal caller).
+ const key = `showAll:${showAllMaxDepth === 1 ? 'd1:' : ''}${showOk ? 'ok:' : ''}${dir ?? ''}`;
let entry = showAllInflight.get(key);
if (!entry) {
const controller = new AbortController();
@@ -5973,6 +6005,7 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {
documents,
maxEntries,
maxDepth: showAllMaxDepth,
+ showOk,
signal: controller.signal,
});
documents.sort((a, b) => {
@@ -9164,17 +9197,17 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {
);
return;
}
- // Reject managed-artifact + `.ok/`-rooted targets. Now that
+ // Reject managed-artifact + reserved-directory targets. Now that
// `.ok/skills/**` is indexed/served content, a raw create-page into
// `.ok/skills/<name>/SKILL.md` would write directly with ZERO skill-schema
// validation (no name/description checks, no XML-tag ban) and surface as a
// malformed phantom skill. Skills/templates must go through their own
// validating write/install spines; every other `.ok/` child is excluded
- // from the content scope anyway. The first segment test catches the raw
- // filesystem path; `isManagedArtifactDocName` catches the synthetic
- // `__skill__/` / `__template__/` doc-name forms.
- const firstSegment = filePath.split('/')[0];
- if (firstSegment === OK_DIR || isManagedArtifactDocName(candidateDocName)) {
+ // from the content scope anyway. The reserved-path test catches raw
+ // filesystem paths with a `.ok`/`.git` segment at any depth;
+ // `isManagedArtifactDocName` catches the synthetic `__skill__/` /
+ // `__template__/` doc-name forms.
+ if (isReservedProjectStatePath(filePath) || isManagedArtifactDocName(candidateDocName)) {
errorResponse(
res,
400,
@@ -9183,7 +9216,7 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {
{
handler: 'create-page',
detail:
- 'Cannot create a page under .ok/ — skills and templates are authored through their own validating flows.',
+ 'Cannot create a page inside .ok or .git — skills and templates are authored through their own validating flows.',
},
);
return;
@@ -9366,12 +9399,12 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {
);
return;
}
- if (folderPath === '.ok' || folderPath.startsWith('.ok/')) {
+ if (isReservedProjectStatePath(folderPath)) {
errorResponse(
res,
400,
'urn:ok:error:reserved-doc-name',
- "'.ok' is a reserved directory.",
+ '.ok and .git are reserved directories.',
{ handler: 'create-folder' },
);
return;
@@ -9442,8 +9475,7 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {
return;
}
if (
- requestedPath === '.ok' ||
- requestedPath.startsWith('.ok/') ||
+ isReservedProjectStatePath(requestedPath) ||
(kind === 'file' && (isSystemDoc(requestedDocName) || isConfigDoc(requestedDocName))) ||
(kind === 'folder' && isReservedSyntheticFolderPath(requestedPath))
) {
@@ -9853,23 +9885,20 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {
);
return;
}
- // Reject paths whose first segment is `.ok` — that directory holds OK
- // config (`config.yml`, `frontmatter.yml`, `templates/`) plus the
- // per-machine `local/` runtime subtree (server.lock, principal.json,
- // cache, etc.). Symmetric with the `__system__` carve-out. The
- // `AGENTS.md` file inside `.ok/` is a tracked content file by design,
- // but a rename TO or FROM this directory would clobber OK bookkeeping.
- if (
- fromPath === '.ok' ||
- fromPath.startsWith('.ok/') ||
- toPath === '.ok' ||
- toPath.startsWith('.ok/')
- ) {
+ // Reject paths with a `.ok` or `.git` segment at any depth — root
+ // `.ok/` holds OK config (`config.yml`, `frontmatter.yml`,
+ // `templates/`) plus the per-machine `local/` runtime subtree
+ // (server.lock, principal.json, cache, etc.), and nested
+ // `<folder>/.ok/` holds folder metadata + templates. Symmetric with
+ // the `__system__` carve-out. The `AGENTS.md` file inside `.ok/` is a
+ // tracked content file by design, but a rename TO or FROM these
+ // directories would clobber OK bookkeeping.
+ if (isReservedProjectStatePath(fromPath) || isReservedProjectStatePath(toPath)) {
errorResponse(
res,
400,
'urn:ok:error:reserved-doc-name',
- '.ok is a reserved directory.',
+ '.ok and .git are reserved directories.',
{
handler: 'rename-path',
},
@@ -10198,7 +10227,7 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {
if (operationKind === 'file') {
probeAndRegisterSourceFileExtension(contentDir, operationPath);
}
- if (operationKind === 'asset' && isReservedProjectStatePath(operationPath)) {
+ if (isReservedProjectStatePath(operationPath)) {
errorResponse(
res,
400,
@@ -10410,12 +10439,11 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {
// loop fires.
const isReservedFolder =
operationKind === 'folder' && isReservedSyntheticFolderPath(path);
- const isReservedAsset = operationKind === 'asset' && isReservedProjectStatePath(path);
if (
(operationKind === 'file' &&
(isSystemDoc(operationDocName) || isConfigDoc(operationDocName))) ||
isReservedFolder ||
- isReservedAsset
+ isReservedProjectStatePath(path)
) {
errorResponse(
res,
diff --git a/packages/server/src/api-file-ops.test.ts b/packages/server/src/api-file-ops.test.ts
index c679d0c29..96c4c4f8c 100644
--- a/packages/server/src/api-file-ops.test.ts
+++ b/packages/server/src/api-file-ops.test.ts
@@ -851,7 +851,7 @@ describe('file operation API routes', () => {
{
const parsed = JSON.parse(result.body) as Record<string, unknown>;
expect(parsed.type).toBe('urn:ok:error:reserved-doc-name');
- expect(parsed.title).toContain('.ok is a reserved directory');
+ expect(parsed.title).toContain('.ok and .git are reserved directories');
}
});
@@ -875,7 +875,7 @@ describe('file operation API routes', () => {
{
const parsed = JSON.parse(result.body) as Record<string, unknown>;
expect(parsed.type).toBe('urn:ok:error:reserved-doc-name');
- expect(parsed.title).toContain('.ok is a reserved directory');
+ expect(parsed.title).toContain('.ok and .git are reserved directories');
}
});
@@ -2827,7 +2827,7 @@ describe('file operation API routes', () => {
expect(existsSync(join(dir, '.ok/local/cache'))).toBe(false);
expect(JSON.parse(result.body)).toMatchObject({
type: 'urn:ok:error:reserved-doc-name',
- title: "'.ok' is a reserved directory.",
+ title: '.ok and .git are reserved directories.',
status: 400,
});
});
diff --git a/packages/server/src/api-ok-reserved-guard.test.ts b/packages/server/src/api-ok-reserved-guard.test.ts
new file mode 100644
index 000000000..60562b338
--- /dev/null
+++ b/packages/server/src/api-ok-reserved-guard.test.ts
@@ -0,0 +1,464 @@
+import { afterEach, describe, expect, test } from 'bun:test';
+import { existsSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
+import type { IncomingMessage, ServerResponse } from 'node:http';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { Readable } from 'node:stream';
+import { createApiExtension } from './api-extension.ts';
+import { BacklinkIndex } from './backlink-index.ts';
+import { _resetDocExtensionsForTests } from './doc-extensions.ts';
+
+/**
+ * Reserved project-state guard across the generic mutation handlers
+ * (create-page, create-folder, duplicate-path, rename-path, delete-path,
+ * trash-cleanup): any request naming a `.ok` or `.git` path segment at ANY
+ * depth must 400 with `urn:ok:error:reserved-doc-name` and leave disk
+ * untouched. Nested `<folder>/.ok/` is a first-class OK shape (folder
+ * metadata + templates), and on case-insensitive filesystems `.OK/x`
+ * addresses `.ok/x`, so top-level-only or case-sensitive checks are not a
+ * boundary. Skills and templates mutate only through their own validating
+ * handlers, never through these generic file ops.
+ */
+
+function makeReq(url: string, method: string, body: unknown): IncomingMessage {
+ const raw = body === undefined ? '' : JSON.stringify(body);
+ const readable = Readable.from(Buffer.from(raw)) as unknown as IncomingMessage;
+ readable.method = method;
+ readable.url = url;
+ readable.headers = { host: 'localhost' };
+ return readable;
+}
+
+interface CapturedResponse {
+ status: number;
+ headers: Record<string, string>;
+ body: string;
+}
+
+function makeRes(): { res: ServerResponse; captured: CapturedResponse } {
+ const captured: CapturedResponse = { status: 0, headers: {}, body: '' };
+ const res = {
+ writeHead(status: number, headers?: Record<string, string>) {
+ captured.status = status;
+ if (headers) Object.assign(captured.headers, headers);
+ },
+ end(body?: string) {
+ captured.body = body ?? '';
+ },
+ } as unknown as ServerResponse;
+ return { res, captured };
+}
+
+async function callApi(contentDir: string, url: string, body: unknown): Promise<CapturedResponse> {
+ const backlinkIndex = new BacklinkIndex({ projectDir: contentDir, contentDir });
+ await backlinkIndex.rebuildFromDisk();
+ const ext = createApiExtension({
+ hocuspocus: {
+ documents: new Map(),
+ closeConnections() {},
+ unloadDocument: async () => {},
+ } as unknown as Parameters<typeof createApiExtension>[0]['hocuspocus'],
+ sessionManager: {
+ closeSession: async () => {},
+ closeAllForDoc: async () => {},
+ } as unknown as Parameters<typeof createApiExtension>[0]['sessionManager'],
+ contentDir,
+ serverInstanceId: 'test-server-instance',
+ getFileIndex: () => new Map(),
+ getFolderIndex: () => new Map(),
+ backlinkIndex,
+ });
+ const req = makeReq(url, 'POST', body);
+ const { res, captured } = makeRes();
+ await (
+ ext as unknown as {
+ onRequest: (ctx: { request: IncomingMessage; response: ServerResponse }) => Promise<void>;
+ }
+ ).onRequest({ request: req, response: res });
+ return captured;
+}
+
+function expectReservedRejection(result: CapturedResponse): void {
+ expect(result.status).toBe(400);
+ expect(JSON.parse(result.body)).toMatchObject({
+ type: 'urn:ok:error:reserved-doc-name',
+ status: 400,
+ });
+}
+
+let tmpDir: string;
+
+function setupTmpDir(): string {
+ tmpDir = mkdtempSync(join(tmpdir(), 'ok-reserved-guard-'));
+ return tmpDir;
+}
+
+afterEach(() => {
+ _resetDocExtensionsForTests();
+ if (tmpDir) {
+ rmSync(tmpDir, { recursive: true, force: true });
+ }
+});
+
+describe('reserved-path guard — create-page', () => {
+ test('rejects a root .ok target and writes nothing', async () => {
+ const dir = setupTmpDir();
+
+ const result = await callApi(dir, '/api/create-page', { path: '.ok/probe.md' });
+
+ expectReservedRejection(result);
+ expect(existsSync(join(dir, '.ok/probe.md'))).toBe(false);
+ expect(existsSync(join(dir, '.ok'))).toBe(false);
+ });
+
+ test('rejects a nested .ok target at any depth and writes nothing', async () => {
+ const dir = setupTmpDir();
+ mkdirSync(join(dir, 'notes'), { recursive: true });
+
+ const result = await callApi(dir, '/api/create-page', {
+ path: 'notes/.ok/probe.md',
+ });
+
+ expectReservedRejection(result);
+ expect(existsSync(join(dir, 'notes/.ok'))).toBe(false);
+ });
+
+ test('rejects a case-variant .OK target and writes nothing', async () => {
+ const dir = setupTmpDir();
+
+ const result = await callApi(dir, '/api/create-page', { path: '.OK/probe.md' });
+
+ expectReservedRejection(result);
+ expect(existsSync(join(dir, '.OK/probe.md'))).toBe(false);
+ });
+});
+
+describe('reserved-path guard — create-folder', () => {
+ test('rejects a root .ok destination and creates nothing', async () => {
+ const dir = setupTmpDir();
+
+ const result = await callApi(dir, '/api/create-folder', { path: '.ok/cache' });
+
+ expectReservedRejection(result);
+ expect(existsSync(join(dir, '.ok/cache'))).toBe(false);
+ });
+
+ test('rejects a nested .ok destination and creates nothing', async () => {
+ const dir = setupTmpDir();
+ mkdirSync(join(dir, 'notes'), { recursive: true });
+
+ const result = await callApi(dir, '/api/create-folder', { path: 'notes/.ok/cache' });
+
+ expectReservedRejection(result);
+ expect(existsSync(join(dir, 'notes/.ok'))).toBe(false);
+ });
+
+ test('rejects a case-variant .OK destination and creates nothing', async () => {
+ const dir = setupTmpDir();
+
+ const result = await callApi(dir, '/api/create-folder', { path: '.OK/cache' });
+
+ expectReservedRejection(result);
+ expect(existsSync(join(dir, '.OK/cache'))).toBe(false);
+ });
+});
+
+describe('reserved-path guard — duplicate-path', () => {
+ test('rejects a root .ok folder source', async () => {
+ const dir = setupTmpDir();
+ mkdirSync(join(dir, '.ok/templates'), { recursive: true });
+
+ const result = await callApi(dir, '/api/duplicate-path', {
+ kind: 'folder',
+ path: '.ok/templates',
+ });
+
+ expectReservedRejection(result);
+ expect(existsSync(join(dir, '.ok/templates copy'))).toBe(false);
+ });
+
+ test('rejects a nested .ok file source and copies nothing', async () => {
+ const dir = setupTmpDir();
+ mkdirSync(join(dir, 'notes/.ok/templates'), { recursive: true });
+ writeFileSync(join(dir, 'notes/.ok/templates/starter.md'), '# Starter\n', 'utf-8');
+
+ const result = await callApi(dir, '/api/duplicate-path', {
+ kind: 'file',
+ path: 'notes/.ok/templates/starter',
+ });
+
+ expectReservedRejection(result);
+ expect(existsSync(join(dir, 'notes/.ok/templates/starter copy.md'))).toBe(false);
+ });
+
+ test('rejects a case-variant .OK folder source', async () => {
+ const dir = setupTmpDir();
+
+ const result = await callApi(dir, '/api/duplicate-path', { kind: 'folder', path: '.OK' });
+
+ expectReservedRejection(result);
+ });
+});
+
+describe('reserved-path guard — rename-path', () => {
+ test('rejects a root .ok source path', async () => {
+ const dir = setupTmpDir();
+ mkdirSync(join(dir, '.ok/templates'), { recursive: true });
+
+ const result = await callApi(dir, '/api/rename-path', {
+ kind: 'folder',
+ fromPath: '.ok/templates',
+ toPath: 'liberated-templates',
+ });
+
+ expectReservedRejection(result);
+ expect(existsSync(join(dir, '.ok/templates'))).toBe(true);
+ expect(existsSync(join(dir, 'liberated-templates'))).toBe(false);
+ });
+
+ test('rejects a nested .ok source path and moves nothing', async () => {
+ const dir = setupTmpDir();
+ mkdirSync(join(dir, 'notes/.ok/templates'), { recursive: true });
+ writeFileSync(join(dir, 'notes/.ok/templates/starter.md'), '# Starter\n', 'utf-8');
+
+ const result = await callApi(dir, '/api/rename-path', {
+ kind: 'file',
+ fromPath: 'notes/.ok/templates/starter',
+ toPath: 'liberated',
+ });
+
+ expectReservedRejection(result);
+ expect(existsSync(join(dir, 'notes/.ok/templates/starter.md'))).toBe(true);
+ expect(existsSync(join(dir, 'liberated.md'))).toBe(false);
+ });
+
+ test('rejects a nested .ok destination path and moves nothing', async () => {
+ const dir = setupTmpDir();
+ writeFileSync(join(dir, 'real.md'), '# Real\n', 'utf-8');
+ mkdirSync(join(dir, 'notes'), { recursive: true });
+
+ const result = await callApi(dir, '/api/rename-path', {
+ kind: 'file',
+ fromPath: 'real',
+ toPath: 'notes/.ok/sneak',
+ });
+
+ expectReservedRejection(result);
+ expect(existsSync(join(dir, 'real.md'))).toBe(true);
+ expect(existsSync(join(dir, 'notes/.ok'))).toBe(false);
+ });
+
+ test('rejects a case-variant .OK destination path and moves nothing', async () => {
+ const dir = setupTmpDir();
+ writeFileSync(join(dir, 'real.md'), '# Real\n', 'utf-8');
+
+ const result = await callApi(dir, '/api/rename-path', {
+ kind: 'file',
+ fromPath: 'real',
+ toPath: '.OK/sneak',
+ });
+
+ expectReservedRejection(result);
+ expect(existsSync(join(dir, 'real.md'))).toBe(true);
+ });
+});
+
+describe('reserved-path guard — delete-path', () => {
+ test('rejects a root .ok folder delete and removes nothing', async () => {
+ const dir = setupTmpDir();
+ mkdirSync(join(dir, '.ok/templates'), { recursive: true });
+ writeFileSync(join(dir, '.ok/templates/starter.md'), '# Starter\n', 'utf-8');
+
+ const result = await callApi(dir, '/api/delete-path', { kind: 'folder', path: '.ok' });
+
+ expectReservedRejection(result);
+ expect(existsSync(join(dir, '.ok/templates/starter.md'))).toBe(true);
+ });
+
+ test('rejects a nested .ok folder delete and removes nothing', async () => {
+ const dir = setupTmpDir();
+ mkdirSync(join(dir, 'notes/.ok/templates'), { recursive: true });
+ writeFileSync(join(dir, 'notes/.ok/templates/starter.md'), '# Starter\n', 'utf-8');
+
+ const result = await callApi(dir, '/api/delete-path', { kind: 'folder', path: 'notes/.ok' });
+
+ expectReservedRejection(result);
+ expect(existsSync(join(dir, 'notes/.ok/templates/starter.md'))).toBe(true);
+ });
+
+ test('rejects a root .ok file delete and removes nothing', async () => {
+ const dir = setupTmpDir();
+ mkdirSync(join(dir, '.ok/templates'), { recursive: true });
+ writeFileSync(join(dir, '.ok/templates/starter.md'), '# Starter\n', 'utf-8');
+
+ const result = await callApi(dir, '/api/delete-path', {
+ kind: 'file',
+ path: '.ok/templates/starter',
+ });
+
+ expectReservedRejection(result);
+ expect(existsSync(join(dir, '.ok/templates/starter.md'))).toBe(true);
+ });
+
+ test('rejects a nested .ok file delete and removes nothing', async () => {
+ const dir = setupTmpDir();
+ mkdirSync(join(dir, 'notes/.ok/templates'), { recursive: true });
+ writeFileSync(join(dir, 'notes/.ok/templates/starter.md'), '# Starter\n', 'utf-8');
+
+ const result = await callApi(dir, '/api/delete-path', {
+ kind: 'file',
+ path: 'notes/.ok/templates/starter',
+ });
+
+ expectReservedRejection(result);
+ expect(existsSync(join(dir, 'notes/.ok/templates/starter.md'))).toBe(true);
+ });
+
+ test('rejects a case-variant .OK file delete', async () => {
+ const dir = setupTmpDir();
+
+ const result = await callApi(dir, '/api/delete-path', {
+ kind: 'file',
+ path: '.OK/anything',
+ });
+
+ expectReservedRejection(result);
+ });
+
+ test('rejects a nested .ok asset delete and removes nothing', async () => {
+ const dir = setupTmpDir();
+ mkdirSync(join(dir, 'notes/.ok'), { recursive: true });
+ writeFileSync(join(dir, 'notes/.ok/logo.png'), 'fake image bytes', 'utf-8');
+
+ const result = await callApi(dir, '/api/delete-path', {
+ kind: 'asset',
+ path: 'notes/.ok/logo.png',
+ });
+
+ expectReservedRejection(result);
+ expect(existsSync(join(dir, 'notes/.ok/logo.png'))).toBe(true);
+ });
+});
+
+describe('reserved-path guard — trash-cleanup', () => {
+ test('rejects a nested .ok folder cleanup', async () => {
+ const dir = setupTmpDir();
+
+ const result = await callApi(dir, '/api/trash/cleanup', {
+ kind: 'folder',
+ path: 'notes/.ok',
+ });
+
+ expectReservedRejection(result);
+ });
+
+ test('rejects a root .ok file cleanup', async () => {
+ const dir = setupTmpDir();
+
+ const result = await callApi(dir, '/api/trash/cleanup', {
+ kind: 'file',
+ path: '.ok/templates/starter',
+ });
+
+ expectReservedRejection(result);
+ });
+});
+
+describe('reserved-path guard — .git segments', () => {
+ test('create-page rejects a nested .git target and writes nothing', async () => {
+ const dir = setupTmpDir();
+ mkdirSync(join(dir, 'notes'), { recursive: true });
+
+ const result = await callApi(dir, '/api/create-page', { path: 'notes/.git/scratch.md' });
+
+ expectReservedRejection(result);
+ expect(existsSync(join(dir, 'notes/.git'))).toBe(false);
+ });
+
+ test('delete-path rejects a nested .git folder delete and removes nothing', async () => {
+ const dir = setupTmpDir();
+ mkdirSync(join(dir, 'notes/.git'), { recursive: true });
+ writeFileSync(join(dir, 'notes/.git/config'), '[core]\n', 'utf-8');
+
+ const result = await callApi(dir, '/api/delete-path', { kind: 'folder', path: 'notes/.git' });
+
+ expectReservedRejection(result);
+ expect(existsSync(join(dir, 'notes/.git/config'))).toBe(true);
+ });
+
+ test('create-folder rejects a nested .git target and creates nothing', async () => {
+ const dir = setupTmpDir();
+ mkdirSync(join(dir, 'notes'), { recursive: true });
+
+ const result = await callApi(dir, '/api/create-folder', { path: 'notes/.git/hooks' });
+
+ expectReservedRejection(result);
+ expect(existsSync(join(dir, 'notes/.git'))).toBe(false);
+ });
+
+ test('duplicate-path rejects a nested .git source and copies nothing', async () => {
+ const dir = setupTmpDir();
+ mkdirSync(join(dir, 'notes/.git'), { recursive: true });
+ writeFileSync(join(dir, 'notes/.git/config'), '[core]\n', 'utf-8');
+
+ const result = await callApi(dir, '/api/duplicate-path', {
+ kind: 'folder',
+ path: 'notes/.git',
+ });
+
+ expectReservedRejection(result);
+ expect(existsSync(join(dir, 'notes/.git copy'))).toBe(false);
+ });
+
+ test('rename-path rejects a .git destination and moves nothing', async () => {
+ const dir = setupTmpDir();
+ writeFileSync(join(dir, 'real.md'), '# Real\n', 'utf-8');
+ mkdirSync(join(dir, 'notes'), { recursive: true });
+
+ const result = await callApi(dir, '/api/rename-path', {
+ kind: 'file',
+ fromPath: 'real',
+ toPath: 'notes/.git/sneak',
+ });
+
+ expectReservedRejection(result);
+ expect(existsSync(join(dir, 'real.md'))).toBe(true);
+ expect(existsSync(join(dir, 'notes/.git'))).toBe(false);
+ });
+
+ test('rename-path rejects a nested .git source and moves nothing', async () => {
+ const dir = setupTmpDir();
+ mkdirSync(join(dir, 'notes/.git'), { recursive: true });
+ writeFileSync(join(dir, 'notes/.git/config'), '[core]\n', 'utf-8');
+
+ const result = await callApi(dir, '/api/rename-path', {
+ kind: 'folder',
+ fromPath: 'notes/.git',
+ toPath: 'liberated-git',
+ });
+
+ expectReservedRejection(result);
+ expect(existsSync(join(dir, 'notes/.git/config'))).toBe(true);
+ expect(existsSync(join(dir, 'liberated-git'))).toBe(false);
+ });
+});
+
+describe('reserved-path guard — ordinary nested dotfolders stay mutable', () => {
+ test('create and delete inside notes/.obsidian succeed', async () => {
+ const dir = setupTmpDir();
+ mkdirSync(join(dir, 'notes'), { recursive: true });
+
+ const created = await callApi(dir, '/api/create-page', {
+ path: 'notes/.obsidian/scratch.md',
+ });
+ expect(created.status).toBe(200);
+ expect(existsSync(join(dir, 'notes/.obsidian/scratch.md'))).toBe(true);
+
+ const deleted = await callApi(dir, '/api/delete-path', {
+ kind: 'file',
+ path: 'notes/.obsidian/scratch',
+ });
+ expect(deleted.status).toBe(200);
+ expect(existsSync(join(dir, 'notes/.obsidian/scratch.md'))).toBe(false);
+ });
+});
diff --git a/packages/server/src/content-filter.test.ts b/packages/server/src/content-filter.test.ts
index dbc5c16c5..f56198ac1 100644
--- a/packages/server/src/content-filter.test.ts
+++ b/packages/server/src/content-filter.test.ts
@@ -802,6 +802,99 @@ describe('ContentFilter', () => {
});
});
+ describe('showOk lifts the .ok floor for the tree-listing walk only', () => {
+ // `?showAll=true&showOk=true` — the documents-endpoint walk passes both
+ // opts together. showOk admits `.ok`-segment paths through the always-skip
+ // floor in `isExcluded` / `isDirExcluded` only; `.ok/worktrees` and
+ // `.ok/local` stay pruned at every depth, every other floor member and
+ // every other floor rule is untouched, and `isPathIgnored` (the asset-serve
+ // gate) keeps the absolute floor.
+ const REVEAL = { bypassFilters: true, showOk: true } as const;
+
+ function assertShowOkReveal(filter: ContentFilter) {
+ // `.ok` and its content-bearing children become descendable, at the
+ // root and nested per-folder.
+ expect(filter.isDirExcluded('.ok', REVEAL)).toBe(false);
+ expect(filter.isDirExcluded('.ok/templates', REVEAL)).toBe(false);
+ expect(filter.isDirExcluded('.ok/skills', REVEAL)).toBe(false);
+ expect(filter.isDirExcluded('.ok/skills/demo', REVEAL)).toBe(false);
+ expect(filter.isDirExcluded('meetings/.ok', REVEAL)).toBe(false);
+ expect(filter.isDirExcluded('meetings/.ok/templates', REVEAL)).toBe(false);
+
+ // `.ok/worktrees` (repo-scale git checkouts) and `.ok/local`
+ // (per-machine runtime state) stay floored at every depth.
+ expect(filter.isDirExcluded('.ok/worktrees', REVEAL)).toBe(true);
+ expect(filter.isDirExcluded('.ok/worktrees/checkout', REVEAL)).toBe(true);
+ expect(filter.isDirExcluded('.ok/local', REVEAL)).toBe(true);
+ expect(filter.isDirExcluded('.ok/local/cache', REVEAL)).toBe(true);
+ expect(filter.isDirExcluded('meetings/.ok/worktrees', REVEAL)).toBe(true);
+ expect(filter.isDirExcluded('meetings/.ok/local', REVEAL)).toBe(true);
+
+ // Case-insensitively, like the secret floor: on the default
+ // case-insensitive macOS filesystem a `.ok/Local` created by an
+ // external tool IS `.ok/local` — the walk sees the on-disk casing, so
+ // a case-sensitive lookahead would reveal the runtime state.
+ expect(filter.isDirExcluded('.ok/Worktrees', REVEAL)).toBe(true);
+ expect(filter.isDirExcluded('.ok/Local', REVEAL)).toBe(true);
+ expect(filter.isDirExcluded('.ok/LOCAL/cache', REVEAL)).toBe(true);
+ expect(filter.isExcluded('.ok/Local/server.lock', REVEAL)).toBe(true);
+ expect(filter.isExcluded('meetings/.ok/WORKTREES/checkout/README.md', REVEAL)).toBe(true);
+
+ // Files under revealed `.ok` admit; under the excluded children they
+ // stay hidden.
+ expect(filter.isExcluded('.ok/config.yml', REVEAL)).toBe(false);
+ expect(filter.isExcluded('.ok/.gitignore', REVEAL)).toBe(false);
+ expect(filter.isExcluded('.ok/templates/daily.md', REVEAL)).toBe(false);
+ expect(filter.isExcluded('.ok/skills/demo/SKILL.md', REVEAL)).toBe(false);
+ expect(filter.isExcluded('meetings/.ok/frontmatter.yml', REVEAL)).toBe(false);
+ expect(filter.isExcluded('.ok/local/server.lock', REVEAL)).toBe(true);
+ expect(filter.isExcluded('.ok/worktrees/checkout/README.md', REVEAL)).toBe(true);
+
+ // Every other always-skip member is untouched by showOk — including
+ // when nested inside a revealed `.ok` subtree.
+ expect(filter.isDirExcluded('.git', REVEAL)).toBe(true);
+ expect(filter.isDirExcluded('node_modules', REVEAL)).toBe(true);
+ expect(filter.isDirExcluded('.open-knowledge', REVEAL)).toBe(true);
+ expect(filter.isDirExcluded('.openknowledge', REVEAL)).toBe(true);
+ expect(filter.isExcluded('.git/objects/x.md', REVEAL)).toBe(true);
+ expect(filter.isExcluded('node_modules/pkg/README.md', REVEAL)).toBe(true);
+ expect(filter.isDirExcluded('.ok/templates/node_modules', REVEAL)).toBe(true);
+ expect(filter.isExcluded('.ok/templates/node_modules/pkg/x.md', REVEAL)).toBe(true);
+
+ // Junk + secret floors still run inside revealed `.ok`.
+ expect(filter.isExcluded('.ok/.DS_Store', REVEAL)).toBe(true);
+ expect(filter.isExcluded('.ok/templates/server.pem', REVEAL)).toBe(true);
+ expect(filter.isExcluded('.ok/skills/demo/id_rsa', REVEAL)).toBe(true);
+ expect(filter.isDirExcluded('.ok/skills/demo/.ssh', REVEAL)).toBe(true);
+
+ // Reserved synthetic doc names stay hidden under every flag combination.
+ expect(filter.isExcluded('__system__.md', REVEAL)).toBe(true);
+ expect(filter.isExcluded('__config__/project.md', REVEAL)).toBe(true);
+ expect(filter.isExcluded('__local__/project.md', REVEAL)).toBe(true);
+
+ // `isPathIgnored` keeps the absolute floor — showOk widens the listing
+ // walk only, never asset serving.
+ expect(filter.isPathIgnored('.ok/config.yml', REVEAL)).toBe(true);
+ expect(filter.isPathIgnored('.ok/templates/daily.md', REVEAL)).toBe(true);
+
+ // showOk lifts only the always-skip floor: without bypassFilters the
+ // configurable BUILTIN_SKIP_DIRS rule still hides non-skill `.ok`
+ // content, so a stray showOk on a normal-mode caller reveals nothing.
+ expect(filter.isDirExcluded('.ok/templates', { showOk: true })).toBe(true);
+ expect(filter.isExcluded('.ok/config.yml', { showOk: true })).toBe(true);
+ }
+
+ test('sync factory (createContentFilter)', () => {
+ const filter = createContentFilter({ projectDir, contentDir: projectDir });
+ assertShowOkReveal(filter);
+ });
+
+ test('async factory (createContentFilterAsync) mirrors the reveal', async () => {
+ const filter = await createContentFilterAsync({ projectDir, contentDir: projectDir });
+ assertShowOkReveal(filter);
+ });
+ });
+
describe('reserved system doc names', () => {
test('excludes __system__.md', () => {
const filter = createContentFilter({ projectDir, contentDir: projectDir });
diff --git a/packages/server/src/content-filter.ts b/packages/server/src/content-filter.ts
index 2d4501a4c..1763003f6 100644
--- a/packages/server/src/content-filter.ts
+++ b/packages/server/src/content-filter.ts
@@ -24,7 +24,7 @@ import { readdir, readFile as readFileAsync } from 'node:fs/promises';
import { homedir } from 'node:os';
import { dirname, extname, join, relative, resolve } from 'node:path';
import { promisify } from 'node:util';
-import { LINKABLE_ASSET_EXTENSIONS, SKILL_CONTENT_ROOT } from '@inkeep/open-knowledge-core';
+import { LINKABLE_ASSET_EXTENSIONS, OK_DIR, SKILL_CONTENT_ROOT } from '@inkeep/open-knowledge-core';
import ignore, { type Ignore } from 'ignore';
import { isReservedForUserTree } from './cc1-broadcast.ts';
import { withHiddenWindowsConsole } from './child-process-windows-hide.ts';
@@ -139,14 +139,40 @@ const ALWAYS_SKIP_DIRS = new Set<string>([
'.pi',
]);
+/**
+ * `.ok` children that stay on the always-skip floor even under `showOk`:
+ * `worktrees/` can hold full repo-scale git checkouts (the same unbounded-
+ * traversal hazard the floor exists to prevent) and `local/` is per-machine
+ * runtime state — locks, caches, error logs carrying hostnames and absolute
+ * paths.
+ */
+const OK_ALWAYS_SKIP_CHILDREN = new Set(['worktrees', 'local']);
+
/**
* True when any segment of `relativePath` is an always-skip directory. Called
* before the `bypassFilters` early-return in every exclusion predicate so the
* floor holds regardless of caller (including the `?showAll=true` disk walk).
+ * `showOk` admits `.ok` segments — unless the next segment is an
+ * `OK_ALWAYS_SKIP_CHILDREN` member — so the tree-listing walk can reveal
+ * `.ok` content on request; every other floor member is unconditional.
+ * The child lookahead matches case-insensitively for the same reason as
+ * `isSecretBearingFile`: on the default case-insensitive macOS filesystem
+ * an externally-created `.ok/Local` IS `.ok/local`, and the walk sees the
+ * on-disk casing.
*/
-function pathHasAlwaysSkipSegment(relativePath: string): boolean {
- for (const segment of relativePath.split('/')) {
- if (ALWAYS_SKIP_DIRS.has(segment)) return true;
+function pathHasAlwaysSkipSegment(relativePath: string, showOk?: boolean): boolean {
+ const segments = relativePath.split('/');
+ for (let i = 0; i < segments.length; i++) {
+ const segment = segments[i];
+ if (!ALWAYS_SKIP_DIRS.has(segment)) continue;
+ if (
+ showOk &&
+ segment === OK_DIR &&
+ !OK_ALWAYS_SKIP_CHILDREN.has((segments[i + 1] ?? '').toLowerCase())
+ ) {
+ continue;
+ }
+ return true;
}
return false;
}
@@ -566,6 +592,17 @@ export type RebuildResult =
*/
interface ContentFilterReadOpts {
bypassFilters?: boolean;
+ /**
+ * Admit `.ok`-segment paths through the always-skip floor — `isExcluded` /
+ * `isDirExcluded` only; `isPathIgnored` (the asset-serve gate) keeps the
+ * absolute floor so serving never widens. `.ok/worktrees` and `.ok/local`
+ * stay pruned at every depth (see `OK_ALWAYS_SKIP_CHILDREN`). Lifts only
+ * the floor: without `bypassFilters` the configurable `BUILTIN_SKIP_DIRS`
+ * rule still hides non-skill `.ok` content. Per-request use only — backs
+ * the `?showOk=true` tree-listing flag on `GET /api/documents`; no other
+ * caller may pass it.
+ */
+ showOk?: boolean;
}
export interface ContentFilter {
@@ -847,7 +884,9 @@ export function createContentFilter(opts: ContentFilterOptions): ContentFilter {
// excluded even under bypass. Defense-in-depth: the showAll walk gates
// directories via `isDirExcluded`, but any caller enumerating files
// directly must not admit `.git/` / `node_modules/` / `.ok/` content.
- if (pathHasAlwaysSkipSegment(relativePath)) return true;
+ // `showOk` re-admits `.ok` minus `worktrees`/`local` for the
+ // tree-listing reveal.
+ if (pathHasAlwaysSkipSegment(relativePath, opts?.showOk)) return true;
// (0c') Junk-file floor — `.DS_Store` / `.localized` stay excluded even
// under bypass, so Show All Files never surfaces OS Finder metadata.
@@ -908,8 +947,11 @@ export function createContentFilter(opts: ContentFilterOptions): ContentFilter {
// or `.ok/`: on a repo-root content dir those trees (a multi-GB `.git`,
// thousands of `node_modules`) make the recursive walk unbounded and
// exhaust the heap. This single prune is the load-bearing OOM fix —
- // traversal, not file admission, is what blows up.
- if (pathHasAlwaysSkipSegment(relativePath)) return true;
+ // traversal, not file admission, is what blows up. `showOk` re-admits
+ // `.ok` for the tree-listing reveal while `worktrees`/`local` — the two
+ // children that can be repo-scale — stay pruned, keeping the guard
+ // honest.
+ if (pathHasAlwaysSkipSegment(relativePath, opts?.showOk)) return true;
// Single-file scope — descend only the chain of directories leading to
// the one admitted doc; prune everything else so the watcher seed +
// index walks never enumerate siblings. Before the bypass branch so the
@@ -1446,8 +1488,9 @@ export async function createContentFilterAsync(opts: ContentFilterOptions): Prom
const skillExt = extname(relativePath).slice(1).toLowerCase();
return !LINKABLE_ASSET_EXTENSIONS.has(skillExt);
}
- // Always-skip floor — survives bypass (see sync variant for rationale).
- if (pathHasAlwaysSkipSegment(relativePath)) return true;
+ // Always-skip floor — survives bypass; `showOk` re-admits `.ok` minus
+ // `worktrees`/`local` (see sync variant for rationale).
+ if (pathHasAlwaysSkipSegment(relativePath, opts?.showOk)) return true;
// Junk-file floor — `.DS_Store` / `.localized` survive bypass too.
if (isAlwaysSkipFile(relativePath)) return true;
// Single-file scope — admit ONLY the one target doc (see sync variant).
@@ -1474,8 +1517,9 @@ export async function createContentFilterAsync(opts: ContentFilterOptions): Prom
// bypass the always-skip floor below keeps `.ok` pruned.
if (!opts?.bypassFilters && isSkillContentAncestorDir(relativePath)) return false;
// Always-skip floor — survives bypass; load-bearing OOM fix for the
- // `?showAll=true` walk (see sync variant for rationale).
- if (pathHasAlwaysSkipSegment(relativePath)) return true;
+ // `?showAll=true` walk. `showOk` re-admits `.ok` minus
+ // `worktrees`/`local` (see sync variant for rationale).
+ if (pathHasAlwaysSkipSegment(relativePath, opts?.showOk)) return true;
// Single-file scope — prune every dir that isn't an ancestor of the one
// admitted doc (see sync variant).
if (singleDocRelPath !== undefined) {
diff --git a/packages/server/src/showall-stream.test.ts b/packages/server/src/showall-stream.test.ts
index 79ba8b138..9f58da864 100644
--- a/packages/server/src/showall-stream.test.ts
+++ b/packages/server/src/showall-stream.test.ts
@@ -529,3 +529,93 @@ describe('streamShowAllEntries — symlinked directories', () => {
expect(truncated).toBe(false);
});
});
+
+describe('streamShowAllEntries — showOk reveal', () => {
+ // Root `.ok` (config, templates, skills, worktrees, local), a nested
+ // per-folder `.ok`, and a floor dir that must stay pruned under every flag.
+ function makeOkFixture(): string {
+ const dir = realpathSync(mkdtempSync(join(tmpdir(), 'ok-showall-showok-')));
+ writeFileSync(join(dir, 'note.md'), '# note\n');
+ mkdirSync(join(dir, '.ok', 'templates'), { recursive: true });
+ writeFileSync(join(dir, '.ok', 'config.yml'), 'content:\n dir: .\n');
+ writeFileSync(join(dir, '.ok', 'templates', 'daily.md'), '# Daily\n');
+ mkdirSync(join(dir, '.ok', 'skills', 'demo'), { recursive: true });
+ writeFileSync(join(dir, '.ok', 'skills', 'demo', 'SKILL.md'), '# Demo skill\n');
+ mkdirSync(join(dir, '.ok', 'worktrees', 'checkout'), { recursive: true });
+ writeFileSync(join(dir, '.ok', 'worktrees', 'checkout', 'README.md'), '# checkout\n');
+ mkdirSync(join(dir, '.ok', 'local'), { recursive: true });
+ writeFileSync(join(dir, '.ok', 'local', 'server.lock'), '{}\n');
+ mkdirSync(join(dir, 'notes', '.ok'), { recursive: true });
+ writeFileSync(join(dir, 'notes', 'page.md'), '# page\n');
+ writeFileSync(join(dir, 'notes', '.ok', 'frontmatter.yml'), 'title: Notes\n');
+ mkdirSync(join(dir, 'node_modules', 'pkg'), { recursive: true });
+ writeFileSync(join(dir, 'node_modules', 'pkg', 'x.md'), '# x\n');
+ return dir;
+ }
+
+ test('showOk surfaces .ok rows in place, excluding worktrees and local at every depth', async () => {
+ const dir = makeOkFixture();
+ const { entries, truncated } = await drain(
+ streamShowAllEntries({ ...streamOptsFor(dir, 50_000), showOk: true }),
+ );
+ expect(truncated).toBe(false);
+
+ const paths = entries.map(entryPath);
+ expect(paths).toContain('note');
+ expect(paths).toContain('.ok');
+ expect(paths).toContain('.ok/config.yml');
+ expect(paths).toContain('.ok/templates');
+ expect(paths).toContain('.ok/templates/daily');
+ expect(paths).toContain('.ok/skills/demo/SKILL');
+ expect(paths).toContain('notes/.ok');
+ expect(paths).toContain('notes/.ok/frontmatter.yml');
+ expect(paths.some((p) => p.startsWith('.ok/worktrees'))).toBe(false);
+ expect(paths.some((p) => p.startsWith('.ok/local'))).toBe(false);
+ expect(paths.some((p) => p.startsWith('node_modules'))).toBe(false);
+
+ // Markdown under `.ok` classifies as document, non-markdown as asset —
+ // the same kind dispatch the rest of the walk uses.
+ const daily = entries.find((e) => e.kind === 'document' && e.docName === '.ok/templates/daily');
+ expect(daily).toBeDefined();
+ const config = entries.find((e) => e.kind === 'asset' && e.path === '.ok/config.yml');
+ expect(config).toBeDefined();
+ });
+
+ test('without showOk the same fixture yields no .ok rows (default unchanged)', async () => {
+ const dir = makeOkFixture();
+ const { entries } = await drain(streamShowAllEntries(streamOptsFor(dir, 50_000)));
+ const paths = entries.map(entryPath);
+ expect(paths.some((p) => p === '.ok' || p.includes('.ok/') || p.endsWith('/.ok'))).toBe(false);
+ expect(paths).toContain('note');
+ expect(paths).toContain('notes/page');
+ });
+
+ test('maxDepth=1 with showOk yields the .ok folder and its probe sees admitted children', async () => {
+ const dir = makeOkFixture();
+ const { entries } = await drain(
+ streamShowAllEntries({ ...streamOptsFor(dir, 50_000), showOk: true, maxDepth: 1 }),
+ );
+ expect(entries.map(entryPath).toSorted()).toEqual(['.ok', 'note', 'notes']);
+ const okFolder = entries.find((e) => e.kind === 'folder' && e.path === '.ok');
+ expect(okFolder?.kind === 'folder' && okFolder.hasChildren).toBe(true);
+ });
+
+ test('dirFilter=.ok with showOk lists the .ok children lazily, minus the excluded pair', async () => {
+ const dir = makeOkFixture();
+ const { entries } = await drain(
+ streamShowAllEntries({
+ ...streamOptsFor(dir, 50_000),
+ showOk: true,
+ dirFilter: '.ok',
+ maxDepth: 1,
+ }),
+ );
+ expect(entries.map(entryPath).toSorted()).toEqual([
+ '.ok/config.yml',
+ '.ok/skills',
+ '.ok/templates',
+ ]);
+ const templates = entries.find((e) => e.kind === 'folder' && e.path === '.ok/templates');
+ expect(templates?.kind === 'folder' && templates.hasChildren).toBe(true);
+ });
+});