From 7587b987d3c7118619d0d663f5a3c634760d2b0c Mon Sep 17 00:00:00 2001 From: Adib Hanna Date: Thu, 5 Nov 2026 10:13:06 -0600 Subject: [PATCH 01/27] Fix(tests): three editor suites finish the parse before they read the result These suites assert on the syntax tree's work right after a dispatch or a mount, and a state only gets 20 ms of parsing. On a loaded runner the budget is gone before the definition, list or fence is in the tree: `cm-markdown-links` read no `.tok-link`, `cm-tight-list-enter` got a plain newline from Enter, and `custom-code-languages` read no `.tok-keyword`. Each failed once on a slow machine and passed on the rerun. They now finish the parse first, with `forceParsing` as gates-and-cut.md says. Each suite gains a case that mounts under a stalled clock and proves the parse really was cut, so it fails without the helper and fails loudly if CodeMirror's timing moves. With every clock read jumping 25 ms the link and list suites pass whole. Two things this does not cover. `custom-code-languages` has a second source of load-dependent results: the TextMate tokenizer's own 20 ms line limit, which the engine retries once on the first line. And Enter on a cut tree is a real product behavior, not only a test artifact: the Markdown keymap reads the state's tree, so Enter pressed while the parse has not reached the caret is a plain newline. Neither is changed here. --- .../src/lib/cm-markdown-links.test.ts | 49 +++++++++++++++++-- .../src/lib/cm-tight-list-enter.test.ts | 21 +++++++- .../src/lib/custom-code-languages.test.ts | 41 +++++++++++++++- 3 files changed, 106 insertions(+), 5 deletions(-) diff --git a/packages/app-core/src/lib/cm-markdown-links.test.ts b/packages/app-core/src/lib/cm-markdown-links.test.ts index 15e69652..3de679bc 100644 --- a/packages/app-core/src/lib/cm-markdown-links.test.ts +++ b/packages/app-core/src/lib/cm-markdown-links.test.ts @@ -1,12 +1,17 @@ // @vitest-environment jsdom import { markdown, markdownLanguage } from '@codemirror/lang-markdown' -import { defaultHighlightStyle, syntaxHighlighting } from '@codemirror/language' +import { + defaultHighlightStyle, + forceParsing, + syntaxHighlighting, + syntaxTreeAvailable +} from '@codemirror/language' import { EditorState } from '@codemirror/state' import { EditorView } from '@codemirror/view' -import { describe, expect, it } from 'vitest' +import { describe, expect, it, vi } from 'vitest' import { markdownLinkExtension } from './cm-markdown-links' -function mount(doc: string): EditorView { +function create(doc: string): EditorView { return new EditorView({ state: EditorState.create({ doc, @@ -19,6 +24,30 @@ function mount(doc: string): EditorView { }) } +/** A state gets 20 ms of parsing and a slow runner can spend them before the + * definition at the end of a note, so a test finishes the parse before it reads + * a decoration. In the app the idle worker does this moments later. */ +function finishParse(view: EditorView): void { + forceParsing(view, view.state.doc.length, 5000) +} + +function mount(doc: string): EditorView { + const view = create(doc) + finishParse(view) + return view +} + +/** Every read of the clock jumps past the budget: one parser step per slice. */ +function withStalledClock(work: () => T): T { + let now = Date.now() + const clock = vi.spyOn(Date, 'now').mockImplementation(() => (now += 25)) + try { + return work() + } finally { + clock.mockRestore() + } +} + describe('Markdown link highlighting', () => { it('keeps wikilink labels highlighted in source mode', () => { const view = mount('See [[My Note|label]] and [EE].') @@ -82,9 +111,23 @@ describe('Markdown link highlighting', () => { view.dispatch({ changes: { from: at, insert: '\n\n[some label]: https://example.com' } }) + finishParse(view) expect(view.dom.querySelector('.tok-link')?.textContent).toBe('[Some Label]') view.dispatch({ changes: { from: at, to: view.state.doc.length } }) + finishParse(view) + expect(view.dom.querySelector('.tok-link')).toBeNull() + } finally { + view.destroy() + } + }) + + it('highlights a defined reference once a parse cut before its definition finishes', () => { + const view = withStalledClock(() => create('[EE]\n\nEnd.\n\n[EE]: https://example.com')) + try { + expect(syntaxTreeAvailable(view.state)).toBe(false) expect(view.dom.querySelector('.tok-link')).toBeNull() + finishParse(view) + expect(view.dom.querySelector('.tok-link')?.textContent).toBe('[EE]') } finally { view.destroy() } diff --git a/packages/app-core/src/lib/cm-tight-list-enter.test.ts b/packages/app-core/src/lib/cm-tight-list-enter.test.ts index 4dfb7280..11dae9e8 100644 --- a/packages/app-core/src/lib/cm-tight-list-enter.test.ts +++ b/packages/app-core/src/lib/cm-tight-list-enter.test.ts @@ -3,7 +3,8 @@ // Enter pressed for real in an editor mounted like EditorPane's (note grammar, // the Vim-aware markdown keymap, ordered-list renumbering): a list never grows // blank lines of its own, even once one sits between its first two items. -import { afterEach, describe, expect, it } from 'vitest' +import { afterEach, describe, expect, it, vi } from 'vitest' +import { forceParsing, syntaxTreeAvailable } from '@codemirror/language' import { EditorState } from '@codemirror/state' import { EditorView, keymap } from '@codemirror/view' import { noteMarkdown } from './cm-markdown-language' @@ -35,7 +36,11 @@ function mount(marked: string): EditorView { return view } +/** Enter reads the list from the syntax tree, and a state only gets 20 ms of + * parsing: on a slow runner the list is not in the tree yet and Enter is a plain + * newline. These tests are about what Enter does to a parsed list. */ function pressEnter(view: EditorView, shiftKey = false): void { + forceParsing(view, view.state.doc.length, 5000) view.contentDOM.dispatchEvent( new KeyboardEvent('keydown', { key: 'Enter', keyCode: 13, shiftKey, bubbles: true, cancelable: true }) ) @@ -54,6 +59,20 @@ function type(view: EditorView, text: string): void { } describe('Enter in a list keeps it tight', () => { + it('finishes a parse cut by a slow runner before it presses Enter', () => { + let now = Date.now() + const clock = vi.spyOn(Date, 'now').mockImplementation(() => (now += 25)) + let view: EditorView + try { + view = mount('# Title\n\nProse.\n\n- one\n- two|') + } finally { + clock.mockRestore() + } + expect(syntaxTreeAvailable(view.state)).toBe(false) + pressEnter(view) + expect(marked(view)).toBe('# Title\n\nProse.\n\n- one\n- two\n- |') + }) + it('opens the next bullet right below once a blank line sits between the first two', () => { const view = mount('- one\n\n- two|') pressEnter(view) diff --git a/packages/app-core/src/lib/custom-code-languages.test.ts b/packages/app-core/src/lib/custom-code-languages.test.ts index 32a4cbcf..802668d2 100644 --- a/packages/app-core/src/lib/custom-code-languages.test.ts +++ b/packages/app-core/src/lib/custom-code-languages.test.ts @@ -1,7 +1,8 @@ // @vitest-environment jsdom -import { afterEach, describe, expect, it } from "vitest"; +import { afterEach, describe, expect, it, vi } from "vitest"; import { markdown as markdownLanguage } from "@codemirror/lang-markdown"; +import { forceParsing, syntaxTreeAvailable } from "@codemirror/language"; import { EditorState } from "@codemirror/state"; import { EditorView } from "@codemirror/view"; import type { CustomCodeLanguage } from "@shared/custom-code-languages"; @@ -44,6 +45,12 @@ const jsonnet: CustomCodeLanguage = { grammar: gleam.grammar.replaceAll("gleam", "jsonnet"), }; +// The fence's decorations come from the syntax tree, and a state only gets 20 ms +// of parsing: a slow runner reads the DOM before the fence is in the tree. +function finishParse(view: EditorView): void { + forceParsing(view, view.state.doc.length, 5000); +} + afterEach(async () => { await customCodeLanguageRegistry.replace([]); }); @@ -105,6 +112,7 @@ describe("custom code language runtime", () => { ], }), }); + finishParse(view); expect(host.querySelector(".tok-keyword")?.textContent).toBe("fn"); expect(host.querySelector(".tok-number")?.textContent).toBe("42"); view.destroy(); @@ -132,6 +140,7 @@ describe("custom code language runtime", () => { ], }), }); + finishParse(view); expect(host.querySelector(".tok-keyword")).toBeNull(); view.destroy(); host.remove(); @@ -154,6 +163,36 @@ describe("custom code language runtime", () => { ], }), }); + finishParse(view); + expect(host.querySelector(".tok-keyword")?.textContent).toBe("let"); + view.destroy(); + host.remove(); + }); + + it("decorates a fence once a parse cut before it finishes", async () => { + await customCodeLanguageRegistry.replace([gleam]); + const host = document.createElement("div"); + document.body.append(host); + let now = Date.now(); + const clock = vi.spyOn(Date, "now").mockImplementation(() => (now += 25)); + let view: EditorView; + try { + view = new EditorView({ + parent: host, + state: EditorState.create({ + doc: "# Title\n\nProse.\n\n```gleam\nlet answer = 42\n```", + extensions: [ + markdownLanguage({ codeLanguages: resolveCodeLanguage }), + customCodeFenceHighlightExtension, + ], + }), + }); + } finally { + clock.mockRestore(); + } + expect(syntaxTreeAvailable(view.state)).toBe(false); + expect(host.querySelector(".tok-keyword")).toBeNull(); + finishParse(view); expect(host.querySelector(".tok-keyword")?.textContent).toBe("let"); view.destroy(); host.remove(); From 7db768004442cc1d91cb57e64f65657c59f0806c Mon Sep 17 00:00:00 2001 From: Adib Hanna Date: Thu, 5 Nov 2026 10:16:57 -0600 Subject: [PATCH 02/27] Fix(mcp): five scope and name answers from the review are right MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A review of the scope changes in 2.83.0 found five wrong answers. Each is covered in scope-system-folders.test.ts, and the shared fixture did not have to change. `create_note` with `subpath: "dir\ud83d"` wrote the note and `move_note` with that `targetSubpath` moved it, then both answered `URI malformed`, because the `link` in the answer goes through encodeURIComponent. A client that retried made a second note. Arguments are now made well-formed where the request arrives, with U+FFFD, which is what a file name turned half a surrogate pair into on disk anyway. With deny `Pub/secret.md`, `create_note` and `move_note` could land on `archive/Pub/secret.md`, which the client then could not see. The destination check only looked at the folder. The final path is now checked too, walking taken names as the write will, so a numbered name onto a hidden path is refused as well, and a move to the folder a note is already in stays the no-op it was. `duplicate_note` of a copy could make a 213-byte name that `write_note` refused: a 200-byte title gained " copy" twice. A title at the limit now gives way to the word, on whole characters, and the scoped check uses the same name. With `Cafe/` and NFC `Café/` side by side, an NFD allow entry shared nothing: `spell` found two accent-folded matches and gave up before `accentsAgree` could choose. It now prefers the path equal after case and Unicode form, and only then folds accents. Deny `Journal` also hid `Ärchive/Journal/x.md`, because a path's system folder was found after folding accents. A real path now goes by case and Unicode form. A deny entry still folds accents, since a near miss in an entry must over-hide. The Go `zn mcp` in ZenNotes/tui mirrors these scope rules and was not changed here. --- .../src/mcp/scope-system-folders.test.ts | 150 ++++++++++++++++++ apps/desktop/src/mcp/scoped-backend.ts | 94 ++++++++--- apps/desktop/src/mcp/server.ts | 5 +- apps/desktop/src/mcp/tool-support.ts | 20 +++ apps/desktop/src/mcp/vault-ops.ts | 11 +- 5 files changed, 250 insertions(+), 30 deletions(-) diff --git a/apps/desktop/src/mcp/scope-system-folders.test.ts b/apps/desktop/src/mcp/scope-system-folders.test.ts index 73da3051..6b6864cf 100644 --- a/apps/desktop/src/mcp/scope-system-folders.test.ts +++ b/apps/desktop/src/mcp/scope-system-folders.test.ts @@ -383,3 +383,153 @@ describe('a note title', () => { expect(looks).toBeLessThanOrEqual(10000) }, 30000) }) + +describe('what the review of the scope changes found', () => { + it('answers create_note and move_note with a lone surrogate in a subpath', async () => { + await seed({ '.zennotes/vault.json': ROOT_LAYOUT, 'Note.md': 'x' }) + const client = await connect() + const created = await call(client, 'create_note', { + folder: 'inbox', + title: 'Made', + subpath: 'dir\ud83d' + }) + expect(created.isError, created.text).toBe(false) + expect(JSON.parse(created.text).path).toBe('dir�/Made.md') + const moved = await call(client, 'move_note', { + path: 'Note.md', + targetFolder: 'inbox', + targetSubpath: 'other\ud83d' + }) + expect(moved.isError, moved.text).toBe(false) + expect(JSON.parse(moved.text).path).toBe('other�/Note.md') + expect(await exists('other�/Note.md')).toBe(true) + }) + + it('refuses a create or a move whose final path a deny entry hides', async () => { + await seed({ + '.zennotes/vault.json': ROOT_LAYOUT, + 'Pub/secret.md': 'hidden', + 'Pub/open.md': 'x', + 'archive/Pub/other.md': 'x', + 'Drafts/secret.md': 'to move' + }) + const client = await connect({ deny: ['Pub/secret.md'] }) + const created = await call(client, 'create_note', { + folder: 'archive', + title: 'secret', + subpath: 'Pub' + }) + expect(created.isError).toBe(true) + expect(await exists('archive/Pub/secret.md')).toBe(false) + const moved = await call(client, 'move_note', { + path: 'Drafts/secret.md', + targetFolder: 'archive', + targetSubpath: 'Pub' + }) + expect(moved.isError).toBe(true) + expect(await exists('archive/Pub/secret.md')).toBe(false) + expect(await exists('Drafts/secret.md')).toBe(true) + // Any other name there is fine, and a taken hidden name moves on to a free one. + const free = await call(client, 'create_note', { folder: 'archive', title: 'open', subpath: 'Pub' }) + expect(JSON.parse(free.text).path).toBe('archive/Pub/open.md') + const numbered = await call(client, 'create_note', { folder: 'inbox', title: 'secret', subpath: 'Pub' }) + expect(JSON.parse(numbered.text).path).toBe('Pub/secret 2.md') + }) + + it('refuses a create whose numbered name a deny entry hides', async () => { + await seed({ + '.zennotes/vault.json': ROOT_LAYOUT, + 'Pub/draft.md': 'x', + 'archive/Pub/draft.md': 'x', + 'Pub/draft 2.md': 'hidden' + }) + const client = await connect({ deny: ['Pub/draft 2.md'] }) + const created = await call(client, 'create_note', { folder: 'archive', title: 'draft', subpath: 'Pub' }) + expect(created.isError).toBe(true) + expect(await exists('archive/Pub/draft 2.md')).toBe(false) + }) + + it('keeps a move within its own folder a no-op, whatever a deny entry says of its copies', async () => { + await seed({ '.zennotes/vault.json': ROOT_LAYOUT, 'Pub/draft.md': 'x', 'Pub/draft 2.md': 'hidden' }) + const client = await connect({ deny: ['Pub/draft 2.md'] }) + const moved = await call(client, 'move_note', { + path: 'Pub/draft.md', + targetFolder: 'inbox', + targetSubpath: 'Pub' + }) + expect(moved.isError, moved.text).toBe(false) + expect(JSON.parse(moved.text).path).toBe('Pub/draft.md') + }) + + it('keeps a copy of a copy of a long title writable', async () => { + const title = 'x'.repeat(200) + await seed({ '.zennotes/vault.json': ROOT_LAYOUT, [`${title}.md`]: 'body' }) + const client = await connect() + const first = JSON.parse((await call(client, 'duplicate_note', { path: `${title}.md` })).text) + const second = JSON.parse((await call(client, 'duplicate_note', { path: first.path })).text) + for (const copy of [first, second]) { + expect(Buffer.byteLength(copy.path)).toBeLessThanOrEqual(209) + const written = await call(client, 'write_note', { path: copy.path, body: 'edited' }) + expect(written.isError, written.text).toBe(false) + } + expect(first.path).toBe(`${'x'.repeat(195)} copy.md`) + expect(second.path).toBe(`${'x'.repeat(195)} copy 2.md`) + }) + + it('cuts a long title for a copy on whole characters', async () => { + const title = 'é'.repeat(100) + await seed({ '.zennotes/vault.json': ROOT_LAYOUT, [`${title}.md`]: 'body' }) + const client = await connect() + const copy = JSON.parse((await call(client, 'duplicate_note', { path: `${title}.md` })).text) + expect(copy.path).toBe(`${'é'.repeat(97)} copy.md`) + }) + + it('lets a scoped client copy only when the cut name is one it can see', async () => { + const title = 'x'.repeat(200) + await seed({ '.zennotes/vault.json': ROOT_LAYOUT, [`${title}.md`]: 'body' }) + const client = await connect({ allow: [`${title}.md`] }) + const copy = await call(client, 'duplicate_note', { path: `${title}.md` }) + expect(copy.isError).toBe(true) + expect(await exists(`${'x'.repeat(195)} copy.md`)).toBe(false) + }) + + it('finds the accented folder for an allow entry in another Unicode form', async () => { + const nfc = 'Café' + const nfd = 'Café' + await seed({ '.zennotes/vault.json': ROOT_LAYOUT, 'Cafe/plain.md': 'x', [`${nfc}/accent.md`]: 'y' }) + const client = await connect({ allow: [nfd] }) + const notes = JSON.parse((await call(client, 'list_notes', {})).text) as { path: string }[] + expect(notes.map((note) => note.path.normalize('NFC'))).toEqual([`${nfc}/accent.md`]) + }) + + it('finds the accented folder for an allow entry in another case and form', async () => { + const nfc = 'Café' + await seed({ '.zennotes/vault.json': ROOT_LAYOUT, 'Cafe/plain.md': 'x', [`${nfc}/accent.md`]: 'y' }) + const client = await connect({ allow: ['café'] }) + const notes = JSON.parse((await call(client, 'list_notes', {})).text) as { path: string }[] + expect(notes.map((note) => note.path.normalize('NFC'))).toEqual([`${nfc}/accent.md`]) + }) + + it('does not take an accented folder for the system folder it folds to', async () => { + await seed({ + '.zennotes/vault.json': ROOT_LAYOUT, + 'Journal/a.md': 'hidden', + 'archive/Journal/b.md': 'hidden', + 'Ärchive/Journal/c.md': 'shared' + }) + const client = await connect({ deny: ['Journal'] }) + const notes = JSON.parse((await call(client, 'list_notes', {})).text) as { path: string }[] + expect(notes.map((note) => note.path.normalize('NFC'))).toEqual(['Ärchive/Journal/c.md']) + }) + + it('still follows a differently cased system folder', async () => { + await seed({ + '.zennotes/vault.json': ROOT_LAYOUT, + 'Journal/a.md': 'hidden', + 'ARCHIVE/Journal/b.md': 'hidden' + }) + const client = await connect({ deny: ['Journal'] }) + const notes = JSON.parse((await call(client, 'list_notes', {})).text) as { path: string }[] + expect(notes.map((note) => note.path)).toEqual([]) + }) +}) diff --git a/apps/desktop/src/mcp/scoped-backend.ts b/apps/desktop/src/mcp/scoped-backend.ts index 37d51465..c32bd50b 100644 --- a/apps/desktop/src/mcp/scoped-backend.ts +++ b/apps/desktop/src/mcp/scoped-backend.ts @@ -46,6 +46,7 @@ import { RemoteRequestError } from '../main/remote/connection.js' import { AssetDestinationRefused, ATTACHMENTS_DIRS, + copyTitle, foldersAsListed, goesThroughLink, sanitizeTitle, @@ -90,6 +91,9 @@ const ASSETS_DIR = 'assets' const NO_COPY_NAME = 'This assistant cannot give the note that name.' +/** How many taken names the check of a new note's path goes through. */ +const MAX_LANDING_STEPS = 10000 + const notFound = (rel: string): Error => new Error(`Note not found: ${rel}`) export const assetNotFound = (rel: string): Error => new Error(`Asset not found: ${rel}`) export const deletedAssetNotFound = (token: string): Error => @@ -117,12 +121,15 @@ function hintLinkedFolder(kind: string, dir: string): void { * someone who wrote the accent meant that folder, and this is a different one. * Mirrors accentsAgree in ZenNotes/tui. */ function accentsAgree(entry: string, canonical: string): boolean { - const lower = (value: string): string => { - let out = '' - for (const ch of value.normalize('NFC')) out += ch.toLowerCase() - return out - } - return lower(entry) === lower(canonical) || lower(entry) === foldMcpScopePath(entry) + return foldCase(entry) === foldCase(canonical) || foldCase(entry) === foldMcpScopePath(entry) +} + +/** Case and Unicode form only, which a volume can ignore. Accents stay: `Café` and + * `Cafe` are two folders, side by side on any volume. */ +function foldCase(value: string): string { + let out = '' + for (const ch of value.normalize('NFC')) out += ch.toLowerCase() + return out } function joinRel(dir: string, sub: string): string { @@ -131,21 +138,23 @@ function joinRel(dir: string, sub: string): string { return `${dir}/${sub}` } -/** The vault's spelling of `p` among known paths: exact, else the one path - * equal to it after case and accent folding. */ +/** The vault's spelling of `p` among known paths: exact, else the one path equal + * to it after case and Unicode form, else the one equal after accent folding too. + * The order matters beside a look-alike: NFD `Café` means `Café/` and is not left + * undecided by `Cafe/` next to it. */ function spell(p: string, known: readonly string[]): string | null { + const cased = foldCase(p) const folded = foldMcpScopePath(p) - let match: string | null = null - let count = 0 + // The lists can name one path twice, which is still one path. + const near = new Set() + const loose = new Set() for (const k of known) { if (k === p) return k - // The lists can name one path twice, which is still one path. - if (foldMcpScopePath(k) === folded && k !== match) { - match = k - count += 1 - } + if (foldCase(k) === cased) near.add(k) + if (foldMcpScopePath(k) === folded) loose.add(k) } - return count === 1 ? match : null + const [only] = near.size > 0 ? near : loose + return (near.size > 0 ? near.size : loose.size) === 1 ? only : null } /** A client's path in vault-relative POSIX form, or null: `.` and `..` @@ -319,12 +328,14 @@ class ScopeView { } /** A path without the system folder it sits in, the same path when it sits in - * none and '' when it names one. In any case, since entries match that way. */ - private withoutSystemFolder(p: string): string { - const folded = foldMcpScopePath(p) + * none and '' when it names one. A real path goes by case and Unicode form, so + * `Ärchive/` next to `archive/` stays the plain folder it is. A deny entry is + * only words and folds accents too, since a near miss there must over-hide. */ + private withoutSystemFolder(p: string, fold: (value: string) => string = foldCase): string { + const folded = fold(p) for (const folder of FOLDERS) { const dir = this.bucketDir(folder) - if (dir && isInsideMcpScopeEntry(folded, foldMcpScopePath(dir))) { + if (dir && isInsideMcpScopeEntry(folded, fold(dir))) { return p.split('/').slice(dir.split('/').length).join('/') } } @@ -337,7 +348,7 @@ class ScopeView { const inSystemFolder = this.withoutSystemFolder(p) return this.deny.some((entry) => { if (isInsideMcpScopeEntryFolded(p, entry)) return true - const within = this.withoutSystemFolder(entry) + const within = this.withoutSystemFolder(entry, foldMcpScopePath) return ( within !== '' && inSystemFolder !== p && @@ -356,7 +367,7 @@ class ScopeView { return ( inSystemFolder !== '' && inSystemFolder !== p && - isInsideMcpScopeEntryFolded(this.withoutSystemFolder(entry), inSystemFolder) + isInsideMcpScopeEntryFolded(this.withoutSystemFolder(entry, foldMcpScopePath), inSystemFolder) ) }) } @@ -427,6 +438,23 @@ class ScopeView { return spelled.slice(bucket.length).replace(/^\//, '') } + /** Refuses a name that lands on a path a deny entry hides. A folder can be fine + * and one file in it not: `archive/Pub` with a deny entry on `Pub/secret.md`. The + * search for a free name walks what is really there, as the write will, so it + * can step past a taken name and onto a hidden one. */ + async refuseHiddenLanding(dir: string, title: string, ext = '.md'): Promise { + if (this.deny.length === 0) return + let candidate = title + for (let n = 2; n <= MAX_LANDING_STEPS; n += 1) { + const rel = joinRel(dir, `${candidate}${ext}`) + if (!(await this.occupied(rel))) { + if (this.visible(rel)) return + throw this.createRefusal() + } + candidate = `${title} ${n}` + } + } + /** Whether a system folder is one of those, however it is spelled. */ isLinkedFolder(dir: string): boolean { return this.linkedFolders.some((entry) => isInsideMcpScopeEntryFolded(dir, entry)) @@ -874,7 +902,12 @@ export class ScopedBackend implements VaultBackend { ): Promise => { this.need('write') const v = await this.load() - return await this.inner.createNote(folder, title, await v.destination(folder, subpath), body) + const destination = await v.destination(folder, subpath) + await v.refuseHiddenLanding( + joinRel(v.bucketDir(folder), destination), + sanitizeTitle(title ?? 'Untitled') + ) + return await this.inner.createNote(folder, title, destination, body) } appendToNote = async (rel: string, text: string): Promise => @@ -904,7 +937,15 @@ export class ScopedBackend implements VaultBackend { moveNote = async (rel: string, folder: NoteFolder, subpath: string): Promise => { const meta = await this.noteFor(rel, 'write') const v = await this.load() - return await this.inner.moveNote(meta.path, folder, await v.destination(folder, subpath)) + const destination = await v.destination(folder, subpath) + const dir = joinRel(v.bucketDir(folder), destination) + const from = path.posix.dirname(meta.path) + // A note moved to where it already is stays put, under its own name. + if (dir !== (from === '.' ? '' : from)) { + const ext = path.posix.extname(meta.path) + await v.refuseHiddenLanding(dir, path.posix.basename(meta.path, ext), ext) + } + return await this.inner.moveNote(meta.path, folder, destination) } // Archiving and trashing are lifecycle exits: the note may leave what the @@ -975,8 +1016,9 @@ export class ScopedBackend implements VaultBackend { const meta = await this.noteFor(rel, 'write') const v = await this.load() const ext = path.posix.extname(meta.path) - const stem = ext ? meta.path.slice(0, -ext.length) : meta.path - if (!v.visible(`${stem} copy${ext}`)) throw new Error(NO_COPY_NAME) + const dir = path.posix.dirname(meta.path) + const name = `${copyTitle(path.posix.basename(meta.path, ext))}${ext}` + if (!v.visible(joinRel(dir === '.' ? '' : dir, name))) throw new Error(NO_COPY_NAME) const copy = await this.inner.duplicateNote(meta.path) // A numbered name can land where the first name would not. if (!v.visible(copy.path)) { diff --git a/apps/desktop/src/mcp/server.ts b/apps/desktop/src/mcp/server.ts index dd3a2a97..5cb3ebb0 100644 --- a/apps/desktop/src/mcp/server.ts +++ b/apps/desktop/src/mcp/server.ts @@ -50,7 +50,8 @@ import { RawToolResult, requireFolder, requireString, - type ToolDef + type ToolDef, + wellFormedArguments } from './tool-support.js' /* ---------- Comment authorship ---------------------------------------- */ @@ -1275,7 +1276,7 @@ export async function runMcpServer(options: McpServerOptions = {}): Promise + const toolArgs = wellFormedArguments((args ?? {}) as Record) const seen = backend // An edit to a note is recorded so the user can review it in the app. const result = await runRecordingAgentEdit(name, toolArgs, seen, defaultCommentAuthor(), () => diff --git a/apps/desktop/src/mcp/tool-support.ts b/apps/desktop/src/mcp/tool-support.ts index 373ff308..f694e766 100644 --- a/apps/desktop/src/mcp/tool-support.ts +++ b/apps/desktop/src/mcp/tool-support.ts @@ -31,6 +31,26 @@ export class RawToolResult { constructor(readonly content: ToolContent[]) {} } +/** + * Arguments as they will be stored. JSON can carry half a surrogate pair, which a + * file name turns into U+FFFD on the way to disk, while `encodeURIComponent` refuses + * it outright: the note was written and the answer, which links to it, was + * `URI malformed`. A client that retried then made a second note. + */ +export function wellFormedArguments(value: T): T { + if (typeof value === 'string') return value.replace(/\p{Cs}/gu, '\ufffd') as T + if (Array.isArray(value)) return value.map(wellFormedArguments) as T + if (value && typeof value === 'object') { + return Object.fromEntries( + Object.entries(value).map(([key, item]) => [ + wellFormedArguments(key), + wellFormedArguments(item) + ]) + ) as T + } + return value +} + export function requireString(args: Record, key: string): string { const value = args[key] if (typeof value !== 'string' || !value.trim()) { diff --git a/apps/desktop/src/mcp/vault-ops.ts b/apps/desktop/src/mcp/vault-ops.ts index 695f7f4c..e02c7a33 100644 --- a/apps/desktop/src/mcp/vault-ops.ts +++ b/apps/desktop/src/mcp/vault-ops.ts @@ -1794,6 +1794,13 @@ function cutToBytes(text: string, limit: number): string { return out } +/** A note's copy: a title at the limit gives way to the word, so a copy of a + * copy stays a name every other tool can write. */ +export function copyTitle(title: string): string { + const word = ' copy' + return `${cutToBytes(title, MAX_TITLE_BYTES - word.length).trimEnd()}${word}` +} + export function sanitizeTitle(raw: string): string { // Filenames must be safe on all 3 OSes. Strip path separators, null, // and common reserved characters. @@ -1937,8 +1944,8 @@ export async function duplicateNote(root: string, rel: string): Promise Date: Thu, 5 Nov 2026 10:24:45 -0600 Subject: [PATCH 03/27] Fix(vault): copying folders into a new vault no longer leaves a stray `inbox` folder Open an empty folder and the app seeds `inbox/Welcome.md` without writing the layout to vault.json. Copy folders in, and the layout, still inferred, turns to root mode: the system Inbox row became a plain lowercase `inbox` folder holding a Welcome note nobody asked for. Root mode is the right answer there, since it shows what was copied, so that part stays. What goes is the leftover. When a vault that has not stated its layout reads as root mode, an `inbox/` holding only an untouched Welcome, or nothing, is removed. That runs on open, which heals a vault that already turned, and after a root-level change while the app is running. Switching a stated vault to root mode does the same. "Untouched" means the bytes hash to a text this app seeded. Every one from the git history is listed, as the phones already do for their own seed, and the first test fails if the current text is not among them. A note you edited stays where it is, and so does anything else in that folder. Such a vault shows `inbox` as an ordinary folder with nothing hidden. It deliberately does not state inbox mode at the seed, which would hide everything copied in behind the banner. It does not infer inbox mode from a non-empty `inbox/` as the phones do either, which would turn a flat Obsidian vault with a folder of that name upside down. A remapped inbox and a capitalized `Inbox/` are the owner's by name and are left alone. --- apps/desktop/src/main/index.ts | 18 ++++ apps/desktop/src/main/vault.test.ts | 126 ++++++++++++++++++++++++++++ apps/desktop/src/main/vault.ts | 81 +++++++++++++++++- packages/app-core/src/lib/help.ts | 2 +- 4 files changed, 225 insertions(+), 2 deletions(-) diff --git a/apps/desktop/src/main/index.ts b/apps/desktop/src/main/index.ts index 5f6e0ff2..7533c703 100644 --- a/apps/desktop/src/main/index.ts +++ b/apps/desktop/src/main/index.ts @@ -116,6 +116,7 @@ import { writeFileAtomic, setVaultSettings, rootContentHiddenByInboxMode, + settleSeededInbox, type PersistedRemoteWorkspaceConfig, type PersistedRemoteWorkspaceProfile, type PersistedWindowState, @@ -445,6 +446,7 @@ const windowVaults = new WindowVaultRegistry({ if (vaultChangeAffectsSettings(ev)) { invalidateVaultSettingsCache(root); scheduleShareVaultsRefresh(); + scheduleSeededInboxSettle(root); } }, sendVaultChange: (windowId, ev) => { @@ -453,6 +455,22 @@ const windowVaults = new WindowVaultRegistry({ win.webContents.send(IPC.VAULT_ON_CHANGE, ev); }, }); +// A copy arrives as a burst of root-level events; one look after it is enough. +const SEEDED_INBOX_SETTLE_DELAY_MS = 400; +const seededInboxSettles = new Map(); +function scheduleSeededInboxSettle(root: string): void { + clearTimeout(seededInboxSettles.get(root)); + seededInboxSettles.set( + root, + setTimeout(() => { + seededInboxSettles.delete(root); + void settleSeededInbox(root).catch((err) => + console.error("settling a seeded inbox failed", err), + ); + }, SEEDED_INBOX_SETTLE_DELAY_MS), + ); +} + const DEFAULT_WINDOW_WIDTH = 1280; const DEFAULT_WINDOW_HEIGHT = 820; const MIN_WINDOW_WIDTH = 900; diff --git a/apps/desktop/src/main/vault.test.ts b/apps/desktop/src/main/vault.test.ts index 924e81ad..15ea9ed4 100644 --- a/apps/desktop/src/main/vault.test.ts +++ b/apps/desktop/src/main/vault.test.ts @@ -44,6 +44,7 @@ import { restoreDeletedAsset, restoreFromTrash, rootContentHiddenByInboxMode, + settleSeededInbox, searchVaultText, searchVaultTextCapabilities, setVaultSettings, @@ -98,6 +99,131 @@ describe('rootContentHiddenByInboxMode (#195)', () => { }) }) +describe('a folder opened empty, then filled', () => { + const exists = (p: string): Promise => + stat(p).then( + () => true, + () => false + ) + + async function seededVault(): Promise { + const root = await makeTempDir('zennotes-vault-seeded-') + await ensureVaultLayout(root) + expect(await exists(path.join(root, 'inbox', 'Welcome.md'))).toBe(true) + expect((await getVaultSettings(root)).primaryNotesLocation).toBe('inbox') + return root + } + + async function copyFolderIn(root: string): Promise { + await mkdir(path.join(root, 'Projects'), { recursive: true }) + await writeFile(path.join(root, 'Projects', 'Plan.md'), '# Plan\n') + invalidateVaultSettingsCache(root) + } + + it('takes away the system inbox holding only an untouched Welcome', async () => { + const root = await seededVault() + await copyFolderIn(root) + expect(await settleSeededInbox(root)).toBe(true) + expect(await exists(path.join(root, 'inbox'))).toBe(false) + expect((await getVaultSettings(root)).primaryNotesLocation).toBe('root') + expect(await readFile(path.join(root, 'Projects', 'Plan.md'), 'utf8')).toBe('# Plan\n') + }) + + it('heals a vault that already turned, the next time it opens', async () => { + const root = await seededVault() + await copyFolderIn(root) + await ensureVaultLayout(root) + expect(await exists(path.join(root, 'inbox'))).toBe(false) + }) + + it('takes away an empty inbox and what Finder left in it', async () => { + const root = await seededVault() + await rm(path.join(root, 'inbox', 'Welcome.md')) + await writeFile(path.join(root, 'inbox', '.DS_Store'), 'x') + await copyFolderIn(root) + expect(await settleSeededInbox(root)).toBe(true) + expect(await exists(path.join(root, 'inbox'))).toBe(false) + }) + + it.each([ + ['an edited Welcome', 'Welcome.md', '# Mine now\n'], + ['a note of the same bytes under another name', 'Copy.md', null] + ])('never touches %s', async (_label, name, body) => { + const root = await seededVault() + const seeded = await readFile(path.join(root, 'inbox', 'Welcome.md'), 'utf8') + await writeFile(path.join(root, 'inbox', name), body ?? seeded) + if (name !== 'Welcome.md') await rm(path.join(root, 'inbox', 'Welcome.md')) + await copyFolderIn(root) + expect(await settleSeededInbox(root)).toBe(false) + expect(await readFile(path.join(root, 'inbox', name), 'utf8')).toBe(body ?? seeded) + }) + + it('never touches an untouched Welcome beside another note', async () => { + const root = await seededVault() + await writeFile(path.join(root, 'inbox', 'Mine.md'), 'mine') + await copyFolderIn(root) + expect(await settleSeededInbox(root)).toBe(false) + expect(await exists(path.join(root, 'inbox', 'Welcome.md'))).toBe(true) + expect(await exists(path.join(root, 'inbox', 'Mine.md'))).toBe(true) + }) + + it('does nothing while the layout still reads as inbox mode', async () => { + const root = await seededVault() + expect(await settleSeededInbox(root)).toBe(false) + expect(await exists(path.join(root, 'inbox', 'Welcome.md'))).toBe(true) + }) + + it('does nothing in a vault that states its layout', async () => { + const root = await seededVault() + const base = await getVaultSettings(root) + await setVaultSettings(root, { ...base, primaryNotesLocation: 'inbox' }) + await copyFolderIn(root) + expect(await settleSeededInbox(root)).toBe(false) + expect(await exists(path.join(root, 'inbox', 'Welcome.md'))).toBe(true) + expect(await rootContentHiddenByInboxMode(root)).toBe(true) + }) + + it('leaves a folder the inbox was remapped to', async () => { + const root = await makeTempDir('zennotes-vault-remapped-') + await mkdir(path.join(root, '.zennotes'), { recursive: true }) + await writeFile( + path.join(root, '.zennotes', 'vault.json'), + JSON.stringify({ systemFolderPaths: { inbox: 'inbox-of-mine' } }) + ) + await mkdir(path.join(root, 'inbox'), { recursive: true }) + await mkdir(path.join(root, 'Projects'), { recursive: true }) + expect(await settleSeededInbox(root)).toBe(false) + expect(await exists(path.join(root, 'inbox'))).toBe(true) + }) + + it('leaves a capitalized Inbox, which is a folder of the owner', async () => { + const root = await makeTempDir('zennotes-vault-capital-') + await mkdir(path.join(root, 'Inbox'), { recursive: true }) + await mkdir(path.join(root, 'Projects'), { recursive: true }) + expect(await settleSeededInbox(root)).toBe(false) + expect(await exists(path.join(root, 'Inbox'))).toBe(true) + }) + + it('switching a stated vault to root mode takes the seed-only inbox with it', async () => { + const root = await seededVault() + const base = await getVaultSettings(root) + const stated = await setVaultSettings(root, { ...base, primaryNotesLocation: 'inbox' }) + await copyFolderIn(root) + await setVaultSettings(root, { ...stated, primaryNotesLocation: 'root' }) + expect(await exists(path.join(root, 'inbox'))).toBe(false) + expect(await rootContentHiddenByInboxMode(root)).toBe(false) + }) + + it('switching to root mode keeps an inbox with an edited Welcome', async () => { + const root = await seededVault() + const base = await getVaultSettings(root) + const stated = await setVaultSettings(root, { ...base, primaryNotesLocation: 'inbox' }) + await writeFile(path.join(root, 'inbox', 'Welcome.md'), '# Mine now\n') + await setVaultSettings(root, { ...stated, primaryNotesLocation: 'root' }) + expect(await readFile(path.join(root, 'inbox', 'Welcome.md'), 'utf8')).toBe('# Mine now\n') + }) +}) + describe('daily-notes task settings round-trip (#288)', () => { it('persists the Harper dictionary and ignored suggestions through set/get', async () => { const root = await makeTempDir('zennotes-vault-harper-') diff --git a/apps/desktop/src/main/vault.ts b/apps/desktop/src/main/vault.ts index f388bba1..a00a6c9d 100644 --- a/apps/desktop/src/main/vault.ts +++ b/apps/desktop/src/main/vault.ts @@ -8,7 +8,7 @@ import { import { agentEditFolderPath, removeAgentEditRecord } from './agent-edit-files' import { promises as fs, type Dirent } from 'node:fs' import { execFile, spawn } from 'node:child_process' -import { randomUUID } from 'node:crypto' +import { createHash, randomUUID } from 'node:crypto' import path from 'node:path' import { promisify } from 'node:util' import { app, shell } from 'electron' @@ -1534,6 +1534,7 @@ export async function setVaultSettings( root: string, next: VaultSettings ): Promise { + const previousPrimary = (await getVaultSettings(root)).primaryNotesLocation const fallbackPrimary = statesPrimaryNotesLocation(next) ? DEFAULT_VAULT_SETTINGS.primaryNotesLocation : await inferredPrimaryNotesLocation(root, statedSystemFolderPaths(next)) @@ -1565,6 +1566,8 @@ export async function setVaultSettings( ) // A new root-level directory is exactly what the inference reads. inferredPrimaryCache.delete(root) + } else if (previousPrimary === 'inbox') { + await removeSeedOnlyInbox(root, normalized.systemFolderPaths) } return cloneVaultSettings(normalized) } @@ -1650,6 +1653,81 @@ export function folderForRelativePath( return 'inbox' } +/** + * SHA-256 of every Welcome note this app has seeded, the current text included + * (a test holds it to that). None ever leaves: these bytes are the proof that a + * vault's Welcome is still ours and that nobody wrote in it. + */ +const WELCOME_SEED_SHA256 = new Set([ + '50c264c87b2790dbb685cd9a699118e1d62e84eb5532701e96d5b1ab55373fac', + 'a5d1b711723c817947c48b844ddc789b9889ce13645a060f33e6e6c4362cf1af', + 'f1d62f8864688c0c51d627c1156c8a00b0c3925eddf0678dfe3da84dd5e6a9e8', + '04fabc332abe4b892d548782ecfcec27b77cf157ec59c7f0663b5774fae01aa9' +]) + +/** + * Takes away `inbox/` when it only holds what this app put there, so it does not + * sit among the notes as a plain folder in a vault that keeps them at its root. + * Anything else in it stays where it is, a note you edited included: such a vault + * shows `inbox` as an ordinary folder, and nothing in it is hidden. A folder the + * inbox was remapped to is theirs by name, and so is `Inbox/`, which a + * case-insensitive volume would otherwise answer for. + */ +async function removeSeedOnlyInbox( + root: string, + systemFolderPaths?: SystemFolderPaths | null +): Promise { + if (resolveFolderPath('inbox', systemFolderPaths) !== 'inbox') return false + const inbox = path.join(root, 'inbox') + try { + const top = await fs.readdir(root, { withFileTypes: true }) + if (!top.some((entry) => entry.name === 'inbox' && entry.isDirectory())) return false + const entries = await fs.readdir(inbox, { withFileTypes: true }) + // Finder writes this into any folder it shows; it says nothing about the folder. + const inside = entries.filter((entry) => entry.name !== '.DS_Store') + if (inside.length > 1) return false + const [only] = inside + if (only) { + if (only.name !== 'Welcome.md' || !only.isFile()) return false + const welcome = path.join(inbox, only.name) + const hash = createHash('sha256').update(await fs.readFile(welcome)).digest('hex') + if (!WELCOME_SEED_SHA256.has(hash)) return false + await fs.rm(welcome) + } + await fs.rm(path.join(inbox, '.DS_Store'), { force: true }) + // Not recursive: a file landing after the look stays, and so does the folder. + await fs.rmdir(inbox) + return true + } catch { + return false + } +} + +/** + * A folder opened empty is seeded in inbox mode without saying so in vault.json, + * so the layout is still inferred when folders are copied in, and it turns to root + * mode. That is right, it shows what was copied. What it must not leave behind is + * the system Inbox as a lowercase `inbox` folder holding a Welcome nobody asked for. + * Stating inbox mode at the seed instead would hide everything copied in behind a + * banner, and inferring inbox mode from a non-empty `inbox/` would turn a flat + * Obsidian vault with a folder of that name upside down. + */ +export async function settleSeededInbox(root: string): Promise { + if (isEphemeralRoot(root)) return false + let parsed: unknown = null + try { + parsed = JSON.parse(await fs.readFile(vaultSettingsPath(root), 'utf8')) + } catch (err) { + // A vault.json that does not parse states nothing we can read, and leaves + // its owner a problem that is not this function's to act on. + if ((err as NodeJS.ErrnoException).code !== 'ENOENT') return false + } + if (statesPrimaryNotesLocation(parsed)) return false + const paths = statedSystemFolderPaths(parsed) + if ((await inferPrimaryNotesLocation(root, paths)) !== 'root') return false + return await removeSeedOnlyInbox(root, paths) +} + /** * Ensure the expected vault folder layout exists and seed a welcome note * the very first time a vault is opened. @@ -1674,6 +1752,7 @@ export async function ensureVaultLayout(root: string): Promise { } } if (!wasEmpty) { + await settleSeededInbox(root) try { await migrateLegacyDatabases(root) } catch (err) { diff --git a/packages/app-core/src/lib/help.ts b/packages/app-core/src/lib/help.ts index 9b90766d..f969293e 100644 --- a/packages/app-core/src/lib/help.ts +++ b/packages/app-core/src/lib/help.ts @@ -322,7 +322,7 @@ export const HELP_CORE_CONCEPTS: HelpCard[] = [ { title: 'Primary notes can live at the vault root', body: - 'Settings → Vault lets you choose between the original Inbox model and a Vault root model. Vault root mode surfaces top-level notes, folders, and loose files directly, which is better for imported Obsidian-style vaults and flat Markdown folders.' + 'Settings → Vault lets you choose between the original Inbox model and a Vault root model. Vault root mode surfaces top-level notes, folders, and loose files directly, which is better for imported Obsidian-style vaults and flat Markdown folders. A vault that has not chosen follows what is in it: copy folders into a new one and it turns to Vault root mode. The Welcome note goes with the Inbox if nobody wrote in it; a note you edited stays, as a folder named `inbox`.' }, { title: 'Tabs and splits are first-class', From b33d101412dcc07847eb7f2dab516769f367aa69 Mon Sep 17 00:00:00 2001 From: Adib Hanna Date: Thu, 5 Nov 2026 10:28:58 -0600 Subject: [PATCH 04/27] Fix(tables): an embed in an editor table cell draws what read mode draws `| ![[Note]] | x |` drew a broken image in the table widget, because a cell goes through `renderMarkdown` on its own and that pipeline makes every `![[...]]` an ``. Read mode shows a link there: `expandEmbeds` turns a note's embed on a table row into a link, and the asset pass turns the rest into pictures or links. The widget had neither step. It was worse than the report. A real `![[pic.png]]` was broken in a cell too: the `` kept the source's `pic.png`, which loads nothing from a vault. Nothing ever resolved it. A cell now takes both steps. A note's embed becomes a link, by the same rule as `expandEmbeds` and through a helper that sits beside it, so a code span stays text. A name with no file extension becomes a link too, drawn as a broken link until the note exists. A picture loads through `resolveLocalAssetUrl`, and any other file (`.tldraw`, `.pdf`) is a plain link. The picture stays inside its cell. An idle cell holding an embed redraws when the lists it depends on change, since the asset list can arrive after the first paint. The cell's source is untouched. An `.excalidraw` embed in a cell still draws nothing in the editor, as before. --- packages/app-core/src/lib/cm-table.test.ts | 107 +++++++++++++++++++++ packages/app-core/src/lib/cm-table.ts | 75 ++++++++++++++- packages/app-core/src/lib/transclusion.ts | 14 +++ packages/app-core/src/styles/index.css | 4 + 4 files changed, 195 insertions(+), 5 deletions(-) diff --git a/packages/app-core/src/lib/cm-table.test.ts b/packages/app-core/src/lib/cm-table.test.ts index 3e443f35..c81c904f 100644 --- a/packages/app-core/src/lib/cm-table.test.ts +++ b/packages/app-core/src/lib/cm-table.test.ts @@ -984,6 +984,113 @@ describe('unresolved wikilinks in table cells', () => { }) }) +describe('embeds in table cells', () => { + const saved = { + notes: useStore.getState().notes, + vault: useStore.getState().vault, + selectedPath: useStore.getState().selectedPath, + assetFiles: useStore.getState().assetFiles, + assetFilesListed: useStore.getState().assetFilesListed + } + afterEach(() => { + useStore.setState(saved) + vi.restoreAllMocks() + }) + const embeds = { + isNote: (target: string) => target.split('#')[0] === 'Note', + assetUrl: (href: string) => `zen-asset://local/${href}` + } + const html = (raw: string): string => renderInlineCell(raw, undefined, embeds) + + it.each([ + ['![[Note]]', 'Note', 'Note'], + ['![[Note|label]]', 'Note', 'label'], + ['![[Note#Part]]', 'Note#Part', 'Note > Part'] + ])('draws %s as a link to the note, not a broken image', (raw, target, label) => { + const out = document.createElement('div') + out.innerHTML = html(raw) + expect(out.querySelector('img')).toBeNull() + const link = out.querySelector('a.wikilink') + expect(link?.dataset.wikilink).toBe(target) + expect(link?.textContent).toBe(label) + }) + + it('loads a real image from the vault, keeping its size hint', () => { + const out = document.createElement('div') + out.innerHTML = html('![[pic.png|300]]') + const img = out.querySelector('img') + expect(img?.getAttribute('src')).toBe('zen-asset://local/pic.png') + expect(img?.getAttribute('width')).toBe('300') + out.innerHTML = html('![alt](pic.png)') + expect(out.querySelector('img')?.getAttribute('src')).toBe('zen-asset://local/pic.png') + }) + + it('draws a file that is not a picture as a link', () => { + const out = document.createElement('div') + out.innerHTML = html('![[board.tldraw]]') + expect(out.querySelector('img')).toBeNull() + expect(out.querySelector('a')?.getAttribute('href')).toBe('board.tldraw') + expect(out.querySelector('a')?.textContent).toBe('board.tldraw') + }) + + it('leaves an embed in a code span as text', () => { + expect(html('`![[Note]]`')).toBe('![[Note]]') + }) + + it('leaves the source alone: the cell still commits what was written', () => { + useStore.setState({ notes: [{ path: 'Note.md', title: 'Note', folder: 'inbox' }] } as never) + const view = mount('| A |\n| --- |\n| ![[Note]] |') + const cell = [...view.dom.querySelectorAll('.cm-table-cell')].find( + (c) => c.dataset.row === '0' + )! + expect(cell.dataset.raw).toBe('![[Note]]') + expect(cell.querySelector('img')).toBeNull() + expect(cell.querySelector('a.wikilink')?.classList.contains('broken')).toBe(false) + expect(view.state.doc.toString()).toContain('| ![[Note]] |') + view.destroy() + }) + + it('shows an embed of a note that does not exist as a broken link, until it does', () => { + useStore.setState({ notes: [] } as never) + const view = mount('| A |\n| --- |\n| ![[Later]] |') + const cell = () => + [...view.dom.querySelectorAll('.cm-table-cell')].find( + (c) => c.dataset.row === '0' + )! + expect(cell().querySelector('img')).toBeNull() + expect(cell().querySelector('a.wikilink')?.classList.contains('broken')).toBe(true) + useStore.setState({ notes: [{ path: 'Later.md', title: 'Later', folder: 'inbox' }] } as never) + expect(cell().querySelector('a.wikilink')?.classList.contains('broken')).toBe(false) + view.destroy() + }) + + it('draws the picture once the asset list arrives', () => { + Object.defineProperty(window, 'zen', { + configurable: true, + value: { + resolveVaultAssetUrl: (_root: string, path: string) => `zen-asset://local/${path}`, + resolveLocalAssetUrl: () => null + } + }) + useStore.setState({ + notes: [], + vault: { root: '/vault', name: 'vault' }, + selectedPath: 'Doc.md', + assetFiles: [], + assetFilesListed: false + } as never) + const view = mount('| A |\n| --- |\n| ![[pic.png]] |') + const img = () => view.dom.querySelector('.cm-table-cell img') + expect(img()?.getAttribute('src')).toBe('pic.png') + useStore.setState({ + assetFiles: [{ path: 'assets/pic.png', name: 'pic.png' }], + assetFilesListed: true + } as never) + expect(img()?.getAttribute('src')).toBe('zen-asset://local/assets/pic.png') + view.destroy() + }) +}) + describe('tableBlockAt — the fallback when the parse has not caught up (#485)', () => { const doc = (text: string) => Text.of(text.split('\n')) diff --git a/packages/app-core/src/lib/cm-table.ts b/packages/app-core/src/lib/cm-table.ts index 0c538ed8..9c8e384c 100644 --- a/packages/app-core/src/lib/cm-table.ts +++ b/packages/app-core/src/lib/cm-table.ts @@ -45,6 +45,10 @@ const MIN_COL_WIDTH = 48 import { openTableContextMenu } from './cm-table-menu' import { convertTableToDatabase } from './table-to-database' import { renderMarkdown } from './markdown' +import { classifyLocalAssetHref, localAssetLabel, resolveLocalAssetUrl } from './local-assets' +import { isExcalidrawPath, isObsidianExcalidrawPath } from '@shared/excalidraw' +import { linkNoteEmbedsInCell } from './transclusion' +import { resolveWikilinkTarget } from './wikilinks' import { getCM, Vim } from '@replit/codemirror-vim' import { undo, redo } from '@codemirror/commands' import { useStore } from '../store' @@ -151,22 +155,29 @@ const INSERT_ESCAPE_TIMEOUT_MS = 1000 * * `linkResolves`, when given, decides each `[[wikilink]]` the way the editor * does: a link that reaches nothing gets the reading view's `broken` class. + * + * `embeds`, when given, gives the cell what the reading view does with `![[…]]`: + * a note becomes a link, a picture loads from the vault, and any other file is a + * link rather than a broken picture. */ export function renderInlineCell( text: string, - linkResolves?: (target: string) => boolean + linkResolves?: (target: string) => boolean, + embeds?: CellEmbeds ): string { const trimmed = text.trim() if (!trimmed) return '' // A newline would close the synthetic row; cells are single-line by // construction, but contenteditable can hand one back after a paste. - const source = escapeCell(trimmed.replace(/\s*\n\s*/g, ' ')) + const flat = trimmed.replace(/\s*\n\s*/g, ' ') + const source = escapeCell(embeds ? linkNoteEmbedsInCell(flat, embeds.isNote) : flat) const parsed = document.createElement('template') parsed.innerHTML = renderMarkdown(`| ${source} |\n| --- |`) const cell = parsed.content.querySelector('th, td') // Never swallow the text: if the pipeline returns something unexpected (its // error fallback, say), show the source rather than an empty cell. if (cell) { + if (embeds) resolveCellImages(cell, embeds) if (linkResolves) markUnresolvedCellLinks(cell, linkResolves) return cell.innerHTML } @@ -175,6 +186,32 @@ export function renderInlineCell( return plain.innerHTML } +export interface CellEmbeds { + /** Whether a `![[target]]` names a note. */ + isNote: (target: string) => boolean + /** Where a picture's href loads from, or null when that is not known yet. */ + assetUrl: (href: string) => string | null +} + +/** A rendered `` only says what the source said, which loads nothing from a + * vault. A file that is not a picture was never going to draw. */ +function resolveCellImages(root: ParentNode, embeds: CellEmbeds): void { + root.querySelectorAll('img[src]').forEach((img) => { + const href = img.getAttribute('src') ?? '' + const kind = classifyLocalAssetHref(href) + if (!kind) return + if (kind === 'image') { + const url = embeds.assetUrl(href) + if (url) img.setAttribute('src', url) + return + } + const link = img.ownerDocument.createElement('a') + link.setAttribute('href', href) + link.textContent = img.getAttribute('alt') || localAssetLabel(href, 'Attachment') + img.replaceWith(link) + }) +} + /** Give every rendered `[[wikilink]]` under `root` the `broken` class when its * target reaches nothing (a click would create the note), and take it off * when it does. The editor draws those links muted with a dashed underline @@ -191,9 +228,27 @@ function markUnresolvedCellLinks( }) } -/** A cell's idle HTML, with its wikilinks decided against the vault. */ +/** Whether a cell's `![[target]]` is a note's: the reading view's test, plus a + * name with no file extension, which can only be a note that is not there yet. */ +function cellEmbedIsNote(target: string): boolean { + const notes = useStore.getState().notes + const note = Array.isArray(notes) ? resolveWikilinkTarget(notes, target) : null + if (note) return !isExcalidrawPath(note.path) && !isObsidianExcalidrawPath(note.path) + const name = target.split(/[#^]/, 1)[0] ?? '' + return !/\.[^./\s]+$/.test(name) || /\.md$/i.test(name) +} + +const VAULT_CELL_EMBEDS: CellEmbeds = { + isNote: cellEmbedIsNote, + assetUrl: (href) => { + const { vault, selectedPath } = useStore.getState() + return resolveLocalAssetUrl(vault?.root, selectedPath, href) + } +} + +/** A cell's idle HTML, with its links and embeds decided against the vault. */ function renderCellHtml(text: string): string { - return renderInlineCell(text, wikilinkResolves) + return renderInlineCell(text, wikilinkResolves, VAULT_CELL_EMBEDS) } /** If a `` width marker sits on the line right after the @@ -2553,7 +2608,17 @@ const tableCellLinkStates = ViewPlugin.fromClass( ) { view.contentDOM .querySelectorAll('.cm-table-widget .cm-table-cell') - .forEach((cell) => markUnresolvedCellLinks(cell, wikilinkResolves)) + .forEach((cell) => { + // What an embed draws can change with the same lists: a note that + // now exists, or the asset list arriving after the first paint. + const raw = cell.dataset.raw ?? '' + if (cell.dataset.rendered === 'true' && raw.includes('![')) { + const html = renderCellHtml(raw) + if (cell.innerHTML !== html) cell.innerHTML = html + return + } + markUnresolvedCellLinks(cell, wikilinkResolves) + }) } }) } diff --git a/packages/app-core/src/lib/transclusion.ts b/packages/app-core/src/lib/transclusion.ts index 0f69687f..b53b7d97 100644 --- a/packages/app-core/src/lib/transclusion.ts +++ b/packages/app-core/src/lib/transclusion.ts @@ -80,6 +80,20 @@ function inTableRow(md: string, index: number): boolean { return false } +/** + * What `expand` does to an embed on a table row, for the source of one cell, which + * is all a table widget in the editor has: a cell holds a link to the note, not the + * note. Anything else (an image, a file) stays an embed. + */ +export function linkNoteEmbedsInCell(cell: string, isNote: (target: string) => boolean): string { + const ranges = codeRanges(cell) + return cell.replace(EMBED_RE, (match: string, inner: string, index: number) => { + if (inCode(index, ranges)) return match + const target = (inner.split(WIKILINK_SEPARATOR, 1)[0] ?? '').trim() + return target && isNote(target) ? match.slice(1) : match + }) +} + /** Drop a leading YAML/TOML frontmatter block so it isn't embedded as text. */ function stripFrontmatter(md: string): string { return md.replace(/^?\s*---\n[\s\S]*?\n---\n?/, '').replace(/^?\s*\+\+\+\n[\s\S]*?\n\+\+\+\n?/, '') diff --git a/packages/app-core/src/styles/index.css b/packages/app-core/src/styles/index.css index 9286aa3d..2cb4df2a 100644 --- a/packages/app-core/src/styles/index.css +++ b/packages/app-core/src/styles/index.css @@ -5768,6 +5768,10 @@ html[data-completed-task-style="gray-strikethrough"] .prose-zen li.task-list-ite .cm-table-widget.is-col-resizing .cm-table-cell { user-select: none; } +.cm-table-widget .cm-table-cell img { + max-width: 100%; + height: auto; +} .cm-table-widget th, .cm-table-widget td { border: 1px solid rgb(var(--z-bg-3) / 0.9); From 761766123f656ed16c0ebae7d10641fb3b1a30aa Mon Sep 17 00:00:00 2001 From: Adib Hanna Date: Thu, 5 Nov 2026 10:35:22 -0600 Subject: [PATCH 05/27] Fix(palette): Go to Files, Quick Notes and Inbox go there "Go to Files" opened nothing. It called `setView({ kind: 'assets' })`, which only means something to the note list layout, while the sidebar's Assets row calls `openAssetsView()`. `setView` also clears the selected note, so the title and the status bar changed while the note stayed open in front of you. "Go to Quick Notes" and "Go to Inbox" made the same call, and the pinned pane's "Reveal in files" did too. Files and Quick Notes now open their pages, as Archive and Trash always have. Inbox has no page, so it opens its row in the sidebar and puts the cursor there, keeping the note open. The note list layout still gets `setView`, since that layout shows the folder. A vault that keeps its notes at the root has no Inbox row, so the command is not offered there. The reported "Assets table header after Enter on a no-match search" was not that: the page text held NAME, FOLDER and TAGS because Enter opens the New note dialog, and those are its fields. --- .../src/components/PinnedReferencePane.tsx | 2 +- packages/app-core/src/lib/commands.test.ts | 70 +++++++++++++++++++ packages/app-core/src/lib/commands.ts | 11 +-- packages/app-core/src/lib/sidebar-focus.ts | 30 ++++++++ 4 files changed, 108 insertions(+), 5 deletions(-) diff --git a/packages/app-core/src/components/PinnedReferencePane.tsx b/packages/app-core/src/components/PinnedReferencePane.tsx index 920ad58a..0af1e811 100644 --- a/packages/app-core/src/components/PinnedReferencePane.tsx +++ b/packages/app-core/src/components/PinnedReferencePane.tsx @@ -522,7 +522,7 @@ export function PinnedReferencePane(): JSX.Element | null { title={isAsset ? `Reveal ${title} in files` : `Reveal ${title} in the sidebar`} onClick={() => { if (isAsset) { - setView({ kind: 'assets' }) + void useStore.getState().openAssetsView() return } const parts = pinnedRefPath.split('/') diff --git a/packages/app-core/src/lib/commands.test.ts b/packages/app-core/src/lib/commands.test.ts index a4c864f4..c0c23b89 100644 --- a/packages/app-core/src/lib/commands.test.ts +++ b/packages/app-core/src/lib/commands.test.ts @@ -36,6 +36,76 @@ beforeEach(() => { installZen() }) +describe('the Go commands', () => { + const note = { + path: 'inbox/One.md', + title: 'One', + folder: 'inbox', + body: '# One', + siblingOrder: 0 + } + + function arrange(useStore: { + setState: (s: never) => void + getState: () => { vaultSettings: object } + }): void { + useStore.setState({ + vault: { root: '/v', name: 'v' }, + selectedPath: note.path, + activeNote: note, + sidebarOpen: true, + unifiedSidebar: true, + noteListOpen: false, + collapsedFolders: ['inbox:', 'Other:'], + vaultSettings: { ...useStore.getState().vaultSettings, primaryNotesLocation: 'inbox' } + } as never) + } + + it.each([ + ['nav.assets', 'openAssetsView'], + ['nav.folder.quick', 'openQuickNotesView'], + ['nav.folder.archive', 'openArchiveView'], + ['nav.folder.trash', 'openTrashView'] + ])('%s opens its page and leaves the open note alone until it does', async (id, opener) => { + const { buildCommands, useStore } = await loadCommands() + arrange(useStore) + const open = vi.fn(async () => {}) + useStore.setState({ [opener]: open } as never) + await buildCommands().find((c) => c.id === id)!.run() + expect(open).toHaveBeenCalledTimes(1) + expect(useStore.getState().activeNote?.path).toBe(note.path) + expect(useStore.getState().selectedPath).toBe(note.path) + }) + + it('nav.folder.inbox opens the row in the sidebar and keeps the open note', async () => { + const { buildCommands, useStore } = await loadCommands() + arrange(useStore) + await buildCommands().find((c) => c.id === 'nav.folder.inbox')!.run() + const state = useStore.getState() + expect(state.activeNote?.path).toBe(note.path) + expect(state.selectedPath).toBe(note.path) + expect(state.collapsedFolders).toEqual(['Other:']) + expect(state.focusedPanel).toBe('sidebar') + }) + + it('nav.folder.inbox still shows the folder in the note list layout', async () => { + const { buildCommands, useStore } = await loadCommands() + arrange(useStore) + useStore.setState({ unifiedSidebar: false, noteListOpen: true } as never) + await buildCommands().find((c) => c.id === 'nav.folder.inbox')!.run() + expect(useStore.getState().view).toEqual({ kind: 'folder', folder: 'inbox', subpath: '' }) + }) + + it('nav.folder.inbox is not offered in a vault that keeps its notes at the root', async () => { + const { buildCommands, useStore } = await loadCommands() + arrange(useStore) + useStore.setState({ + vaultSettings: { ...useStore.getState().vaultSettings, primaryNotesLocation: 'root' } + } as never) + expect(buildCommands().some((c) => c.id === 'nav.folder.inbox')).toBe(false) + }) +}) + describe('vault commands', () => { it('exposes one switch-vault picker command', async () => { const { buildCommands, useStore } = await loadCommands() diff --git a/packages/app-core/src/lib/commands.ts b/packages/app-core/src/lib/commands.ts index ea21a182..01c750bf 100644 --- a/packages/app-core/src/lib/commands.ts +++ b/packages/app-core/src/lib/commands.ts @@ -24,7 +24,7 @@ import { promptApp } from './prompt-requests' import { captureNavigationContext } from './navigation-context' import { buildMoveNotePrompt, moveNoteVocabulary, parseMoveNoteTarget } from './move-note' import { focusPaneInDirection } from './pane-nav' -import { focusSidebarPanel } from './sidebar-focus' +import { focusSidebarPanel, revealSystemFolderInSidebar } from './sidebar-focus' import { runSidebarNotePlan, sidebarCommandPlan } from './sidebar-note-actions' import { openContextGallery } from './folder-gallery-open' import { newContextKanban } from './kanban-create' @@ -75,6 +75,7 @@ import { getKeymapDisplay, getLeaderChordDisplay, type KeymapId } from './keymap import { commandBindingHint } from './command-keymaps' import { dispatchKeyboardContextMenu, findTabContextMenuTarget } from './keyboard-context-menu' import { resolveSystemFolderLabels } from './system-folder-labels' +import { isPrimaryNotesAtRoot } from './vault-layout' import { findDailyNoteForDate, findMonthlyNoteForDate, @@ -1649,13 +1650,15 @@ export function buildCommands(options?: { includeUnavailable?: boolean }): Comma title: `Go to ${labels().quick}`, category: 'Go', keywords: 'quick scratch', - run: () => getState().setView({ kind: 'folder', folder: 'quick', subpath: '' }) + run: () => getState().openQuickNotesView() }, { id: 'nav.folder.inbox', title: `Go to ${labels().inbox}`, category: 'Go', - run: () => getState().setView({ kind: 'folder', folder: 'inbox', subpath: '' }) + // A vault that keeps its notes at the root has no Inbox row to go to. + when: () => !isPrimaryNotesAtRoot(getState().vaultSettings), + run: () => revealSystemFolderInSidebar('inbox') }, { id: 'nav.folder.archive', @@ -1676,7 +1679,7 @@ export function buildCommands(options?: { includeUnavailable?: boolean }): Comma title: 'Go to Files', category: 'Go', keywords: 'assets files images', - run: () => getState().setView({ kind: 'assets' }) + run: () => getState().openAssetsView() }, { id: 'nav.focus.sidebar', diff --git a/packages/app-core/src/lib/sidebar-focus.ts b/packages/app-core/src/lib/sidebar-focus.ts index 5e416681..84c80bc7 100644 --- a/packages/app-core/src/lib/sidebar-focus.ts +++ b/packages/app-core/src/lib/sidebar-focus.ts @@ -1,3 +1,4 @@ +import type { NoteFolder } from '@shared/ipc' import { useStore } from '../store' /** @@ -35,3 +36,32 @@ export function focusSidebarPanel( requestAnimationFrame(() => run(attempts)) } + +/** + * Goes to a system folder that has no page of its own: its row, opened and under + * the cursor. The note list shows a folder when that layout is on; without it, + * `setView` changed nothing on screen except the title and the status bar, which + * went blank while the note stayed open. + */ +export function revealSystemFolderInSidebar(folder: NoteFolder): void { + const state = useStore.getState() + if (!state.unifiedSidebar && state.noteListOpen) { + state.setView({ kind: 'folder', folder, subpath: '' }) + return + } + if (!state.sidebarOpen) state.toggleSidebar() + const key = `${folder}:` + if (state.collapsedFolders.includes(key)) { + state.setCollapsedFolders(state.collapsedFolders.filter((other) => other !== key)) + } + focusSidebarPanel() + // After the render the focus causes, whose reveal puts the cursor on the open note. + requestAnimationFrame(() => { + const row = document.querySelector( + `[data-sidebar-type="folder"][data-sidebar-key="${key}"]` + ) + const idx = Number(row?.dataset.sidebarIdx) + if (Number.isFinite(idx)) useStore.getState().setSidebarCursorIndex(idx) + row?.scrollIntoView({ block: 'nearest' }) + }) +} From 7c3e5d9c958b36b14ee1a9daac5b2874a6f4a2c4 Mon Sep 17 00:00:00 2001 From: Adib Hanna Date: Thu, 5 Nov 2026 10:35:22 -0600 Subject: [PATCH 06/27] Fix(help): the manual on a tablet stops describing what is not there The iPad and Android tablet Help explained Import, opening a vault in the file manager, Quick Look, the floating capture window, Raycast, updates and the whole CLI, none of which exist there. The web client had most of the same problem. An entry can now say where it applies, `only: 'desktop' | 'computer' | 'workflows'`, and HelpView reads the manual through `helpForHost`. An entry with no tag shows everywhere. The desktop app gets every entry in the same order, which a test holds it to. The web client keeps what a terminal can do against a server and drops what only the desktop app installs, and shows workflows when its server runs them. Two passing mentions stay on phones, inside entries that otherwise apply: the cover card says Quick Look draws covers, and the tabs card lists Reveal in Finder. --- packages/app-core/src/components/HelpView.tsx | 43 +++--- packages/app-core/src/lib/help-hosts.test.ts | 133 ++++++++++++++++++ packages/app-core/src/lib/help.ts | 117 +++++++++++++-- 3 files changed, 265 insertions(+), 28 deletions(-) create mode 100644 packages/app-core/src/lib/help-hosts.test.ts diff --git a/packages/app-core/src/components/HelpView.tsx b/packages/app-core/src/components/HelpView.tsx index 6733a349..f6a135ae 100644 --- a/packages/app-core/src/components/HelpView.tsx +++ b/packages/app-core/src/components/HelpView.tsx @@ -8,13 +8,9 @@ import { type KeymapOverrides } from '../lib/keymaps' import { - HELP_CLI, - HELP_CORE_CONCEPTS, - HELP_HOW_TO_GUIDES, - HELP_QUICK_START, + helpForHost, HELP_SETTINGS, - HELP_SHORTCUT_SECTIONS, - HELP_VIM_COMMANDS + HELP_SHORTCUT_SECTIONS } from '../lib/help' import { parseHelpKeys } from '../lib/help-keys' import { helpSearchText, renderHelpRichText } from '../lib/help-rich-text' @@ -276,33 +272,40 @@ export function HelpView(): JSX.Element { const allCommands = buildCommands({ includeUnavailable: true }) + const appInfo = window.zen.getAppInfo() + const supportsWorkflows = window.zen.getCapabilities().supportsWorkflows + const manual = useMemo( + () => helpForHost({ runtime: appInfo.runtime, hostKind: appInfo.hostKind, supportsWorkflows }), + [appInfo.runtime, appInfo.hostKind, supportsWorkflows] + ) + const quickStart = useMemo( () => - HELP_QUICK_START.filter((card) => + manual.quickStart.filter((card) => matchesQuery(deferredQuery, card.title, card.body) ), - [deferredQuery] + [deferredQuery, manual] ) const coreConcepts = useMemo( () => - HELP_CORE_CONCEPTS.filter((card) => + manual.concepts.filter((card) => matchesQuery(deferredQuery, card.title, card.body) ), - [deferredQuery] + [deferredQuery, manual] ) const howToGuides = useMemo( () => - HELP_HOW_TO_GUIDES.filter((card) => + manual.howTo.filter((card) => matchesQuery(deferredQuery, card.title, card.body) ), - [deferredQuery] + [deferredQuery, manual] ) const shortcutSections = useMemo( () => - HELP_SHORTCUT_SECTIONS.map((section) => { + manual.shortcuts.map((section) => { const items = section.items.filter((item) => matchesQuery( deferredQuery, @@ -327,12 +330,12 @@ export function HelpView(): JSX.Element { } return null }).filter((section): section is (typeof HELP_SHORTCUT_SECTIONS)[number] => !!section), - [deferredQuery, keymapOverrides] + [deferredQuery, keymapOverrides, manual] ) const vimCommands = useMemo( () => - HELP_VIM_COMMANDS.filter((command) => + manual.vim.filter((command) => matchesQuery( deferredQuery, resolveVimCommandLabel(command.command, keymapOverrides), @@ -343,12 +346,12 @@ export function HelpView(): JSX.Element { ...command, command: resolveVimCommandLabel(command.command, keymapOverrides) })), - [deferredQuery, keymapOverrides] + [deferredQuery, keymapOverrides, manual] ) const settingsSections = useMemo( () => - HELP_SETTINGS.map((section) => { + manual.settings.map((section) => { const items = section.items.filter((item) => matchesQuery(deferredQuery, section.title, item.label, item.detail) ) @@ -357,13 +360,13 @@ export function HelpView(): JSX.Element { } return null }).filter((section): section is (typeof HELP_SETTINGS)[number] => !!section), - [deferredQuery] + [deferredQuery, manual] ) const cliCards = useMemo( () => - HELP_CLI.filter((card) => matchesQuery(deferredQuery, card.title, card.body)), - [deferredQuery] + manual.cli.filter((card) => matchesQuery(deferredQuery, card.title, card.body)), + [deferredQuery, manual] ) const commandGroups = useMemo(() => { diff --git a/packages/app-core/src/lib/help-hosts.test.ts b/packages/app-core/src/lib/help-hosts.test.ts new file mode 100644 index 00000000..14c45ad8 --- /dev/null +++ b/packages/app-core/src/lib/help-hosts.test.ts @@ -0,0 +1,133 @@ +// @vitest-environment jsdom +import { act, createElement } from 'react' +import { createRoot } from 'react-dom/client' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { + HELP_CLI, + HELP_CORE_CONCEPTS, + HELP_HOW_TO_GUIDES, + HELP_QUICK_START, + HELP_SETTINGS, + HELP_SHORTCUT_SECTIONS, + HELP_VIM_COMMANDS, + helpForHost, + type HelpHost +} from './help' + +const DESKTOP: HelpHost = { runtime: 'desktop', hostKind: 'desktop' } +const WEB: HelpHost = { runtime: 'web', hostKind: 'browser', supportsWorkflows: false } +const IPAD: HelpHost = { runtime: 'web', hostKind: 'ios' } +const ANDROID: HelpHost = { runtime: 'web', hostKind: 'android' } + +const text = (host: HelpHost): string => JSON.stringify(helpForHost(host)) +const titles = (host: HelpHost): string[] => { + const manual = helpForHost(host) + return [...manual.quickStart, ...manual.howTo, ...manual.concepts, ...manual.cli].map( + (card) => card.title + ) +} + +describe('the manual on each host', () => { + it('is the whole manual on the desktop app, in the same order', () => { + const manual = helpForHost(DESKTOP) + expect(manual.quickStart).toEqual(HELP_QUICK_START) + expect(manual.howTo).toEqual(HELP_HOW_TO_GUIDES) + expect(manual.concepts).toEqual(HELP_CORE_CONCEPTS) + expect(manual.shortcuts).toEqual(HELP_SHORTCUT_SECTIONS) + expect(manual.vim).toEqual(HELP_VIM_COMMANDS) + expect(manual.settings).toEqual(HELP_SETTINGS) + expect(manual.cli).toEqual(HELP_CLI) + }) + + it('names a legacy desktop host without a host kind the same way', () => { + expect(helpForHost({ runtime: 'desktop' })).toEqual(helpForHost(DESKTOP)) + }) + + it.each([ + ['iPad', IPAD], + ['Android', ANDROID] + ])('leaves out what does not exist on %s', (_name, host) => { + const shown = titles(host) + for (const gone of [ + 'Bring your Notion workspace over', + 'Bring your Obsidian vault over', + 'Open a vault in your file manager', + 'Preview a note in Finder with Quick Look', + 'Search from Raycast on macOS', + 'Capture from anywhere with the floating window', + 'Check for updates and install them', + 'What the CLI is for', + 'Automate repetitive edits with Workflows' + ]) { + expect(shown).not.toContain(gone) + } + const manual = helpForHost(host) + expect(manual.cli).toEqual([]) + expect(manual.shortcuts.map((s) => s.title)).not.toContain('Quick capture window') + expect(manual.shortcuts.flatMap((s) => s.items).map((i) => i.action)).not.toContain('Import notes') + expect(manual.shortcuts.flatMap((s) => s.items).map((i) => i.action)).not.toContain('Open vault folder') + expect(manual.vim.map((c) => c.summary)).not.toContain('Leader open vault folder') + expect(manual.settings.map((s) => s.title)).not.toContain('CLI') + for (const word of ['Raycast', 'Import Notes', 'File Explorer']) { + expect(text(host)).not.toContain(word) + } + // What works there stays. + expect(shown).toContain('Pick a vault you control') + expect(shown).toContain('Tabs and splits are first-class') + }) + + it('keeps the terminal on the web client, without what only the desktop app installs', () => { + const shown = titles(WEB) + expect(shown).toContain('Point it at a self-hosted server') + expect(shown).toContain('The CLI is the bridge to launchers') + expect(shown).not.toContain('Install it once from Settings') + expect(shown).not.toContain('Bring your Notion workspace over') + expect(shown).not.toContain('Preview a note in Finder with Quick Look') + }) + + it('shows workflows on a web client whose server runs them', () => { + expect(titles(WEB)).not.toContain('Automate repetitive edits with Workflows') + expect(titles({ ...WEB, supportsWorkflows: true })).toContain( + 'Automate repetitive edits with Workflows' + ) + expect(helpForHost({ ...WEB, supportsWorkflows: true }).settings.map((s) => s.title)).toContain( + 'Workflows' + ) + }) +}) + +describe('HelpView on a tablet', () => { + let host: HTMLElement + let root: ReturnType + beforeEach(() => { + Object.defineProperty(window, 'zen', { + configurable: true, + value: { + platformSync: () => 'darwin', + getAppInfo: () => ({ runtime: 'web', hostKind: 'ios' }), + getCapabilities: () => ({ supportsWorkflows: false }) + } + }) + ;(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true + host = document.createElement('div') + document.body.append(host) + root = createRoot(host) + vi.stubGlobal('ResizeObserver', class { observe() {} disconnect() {} unobserve() {} }) + }) + afterEach(() => { + act(() => root.unmount()) + host.remove() + vi.unstubAllGlobals() + }) + + it('renders without the desktop topics, and keeps no link to an empty section', async () => { + const { HelpView } = await import('../components/HelpView') + await act(async () => root.render(createElement(HelpView))) + const rendered = host.textContent ?? '' + expect(rendered).toContain('Pick a vault you control') + expect(rendered).not.toContain('Bring your Notion workspace over') + expect(rendered).not.toContain('Preview a note in Finder') + expect(rendered).not.toContain('What the CLI is for') + expect(host.querySelector('#help-cli')).toBeNull() + }) +}) diff --git a/packages/app-core/src/lib/help.ts b/packages/app-core/src/lib/help.ts index f969293e..ff94eb53 100644 --- a/packages/app-core/src/lib/help.ts +++ b/packages/app-core/src/lib/help.ts @@ -1,10 +1,21 @@ +/** + * Where an entry applies, when that is not everywhere the manual is read. Without + * it, an entry shows on every host. `desktop`: the desktop app only. `computer`: + * also the web client, which sits at a keyboard with a terminal nearby, but not a + * phone or tablet. `workflows`: wherever the host runs workflows, which on the web + * depends on its server. + */ +export type HelpAvailability = 'desktop' | 'computer' | 'workflows' + export interface HelpCard { title: string + only?: HelpAvailability body: string } export interface HelpShortcut { keys: string + only?: HelpAvailability action: string detail: string } @@ -12,19 +23,37 @@ export interface HelpShortcut { export interface HelpShortcutSection { id: string title: string + only?: HelpAvailability description: string items: HelpShortcut[] } export interface HelpExCommand { command: string + only?: HelpAvailability summary: string detail: string } export interface HelpSettingsSection { title: string - items: Array<{ label: string; detail: string }> + only?: HelpAvailability + items: Array<{ label: string; only?: HelpAvailability; detail: string }> +} + +/** What the manual needs to know about the app it is being read in. */ +export interface HelpHost { + runtime: 'desktop' | 'web' + hostKind?: 'desktop' | 'browser' | 'ios' | 'android' + supportsWorkflows?: boolean +} + +/** Whether an entry applies here. On the desktop app every entry does. */ +export function helpAppliesTo(only: HelpAvailability | undefined, host: HelpHost): boolean { + if (!only || host.runtime === 'desktop') return true + if (only === 'workflows') return host.supportsWorkflows === true + if (only === 'computer') return host.hostKind !== 'ios' && host.hostKind !== 'android' + return false } export const HELP_QUICK_START: HelpCard[] = [ @@ -93,11 +122,13 @@ export const HELP_HOW_TO_GUIDES: HelpCard[] = [ }, { title: 'Capture from anywhere with the floating window', + only: 'desktop', body: 'Press the quick capture hotkey (CommandOrControl+Shift+Space by default, configurable under Settings → Editor) to drop a small always-on-top window over whatever app you are using. You type in one place: the first line becomes the note title and the rest is the body. Mod+Enter saves the note into Quick Notes and hides the window; Mod+N saves and immediately opens a fresh blank capture so you can jot several in a row; Mod+P loads an existing note to edit instead. Editing the first line of a Quick note renames that note in place rather than creating a duplicate, and you can drag the window by its top bar to reposition it.' }, { title: 'Save a page or text from Safari and other apps (Share → ZenNotes)', + only: 'desktop', body: 'On macOS, choose Share → ZenNotes in Safari or any app with a Share menu to save the page you are on, the text you selected, or both, as a note: in Quick Notes unless you choose another place. The sheet shows what you are saving and, in its heading, where it will go, a line for an optional note, and, when you use more than one vault, the vault it goes to: your local and Cloud vaults and the servers you have connected to. Return saves and Escape cancels; ⌘1 to ⌘9 pick a vault in the order the menu lists them, and the sheet remembers the vault you picked last. A page becomes a note named after the page, with your selection quoted, your note under it and a link back to the page; text on its own becomes a note named from its first line, the way the quick capture window names one. Settings → Vault → Notes → **Default shares location** decides where shares land, per vault: Quick Notes (the default), your primary notes location, or a specific folder inside it such as `Clippings`; a Quick Notes or Inbox folder you remapped is honored, and a vault on a self-hosted server offers the setting once that server runs 2.79 or later (an older server keeps Quick Notes). With ZenNotes running the note appears right away; when it is not running, the share waits and is filed the next time you open ZenNotes, and a share for a server is filed once ZenNotes is connected to that server. The extension comes with the app and registers once you have opened ZenNotes; macOS may list it switched off at first, so if ZenNotes is missing from a Share menu, choose Edit Extensions… at the bottom of that menu and turn ZenNotes on, or turn it on in System Settings → General → Login Items & Extensions → Sharing.' }, @@ -128,16 +159,19 @@ export const HELP_HOW_TO_GUIDES: HelpCard[] = [ }, { title: 'Automate repetitive edits with Workflows', + only: 'workflows', body: 'Workflows turn a vault ritual (find the notes tagged `#book`, keep the ones rated 4 or higher, write them as a table into the reading log, tag the rest `#someday`) into a file you run with one key. The feature is off by default: turn it on once under Settings → Workflows and the view appears in the sidebar (also `Space a` in Vim mode, or "Open Workflows" in the command palette). Start from the recipe gallery ("New workflow"): each recipe is an ordinary `.md` file that copies into `.zennotes/workflows/` and opens in the same editor as anything you write yourself, as a canvas and as text, whichever you prefer. Press `R` (or the Run button) and nothing happens blind: a dry-run confirmation lists every change first, grouped and counted, and after you apply, Undo restores every file the run wrote, byte for byte. That promise survives the worst case: a run the app never finished (a crash mid-apply) is found on the next launch and offered back as an undo, and undoing a run names any file you edited after it ran instead of reverting your work silently. You can also run any active workflow without opening the view at all: every one is a command-palette entry, and "Run Workflow…" opens a picker; the receipt arrives as a toast carrying the Undo button. New workflows start as inert drafts until you activate them, and importing a workflow someone shared is a review, never an install. New to all of this? Settings → Workflows → Start tutorial walks the whole loop hands-on, on a practice folder it seeds and then removes.' }, { title: 'Bring your Notion workspace over', + only: 'desktop', body: 'Run “Import Notes…” from the command palette (`Space I` in Vim mode), or set it up during onboarding, and choose Notion. Then choose Sign in with Notion. Your browser asks you to approve, and that’s all the setup: nothing has to be shared page by page. ZenNotes then shows your workspace as a tree with everything ticked. Open a page to see what’s under it and untick whatever should stay behind, which leaves out everything beneath it too; arrows or `j`/`k`/`h`/`l` in Vim mode move, Space ticks. Choose Import and it reads what you picked, then adds one `Notion Import` folder to your notes in one step, so nothing already in your vault changes and deleting that folder undoes it. Pages become notes (a page with subpages is `Title.md` beside a `Title/` folder), and links between them become `[[wikilinks]]`. Images, PDFs, audio, video and other files go in the folder’s `assets/`, including ones hosted outside Notion; one that can’t be fetched stays a link, and YouTube and Vimeo stay embeds. Databases become real ZenNotes databases: fields keep their types, relations become note links, and table and board views keep their columns, sorts and the filters ZenNotes can express. A large workspace can take hours at Notion’s rate limit. It runs in the background, and if you stop it or quit, the next run picks up where it was. Formula and rollup columns keep the values they had and stop calculating; calendar, timeline, gallery and other views become tables; comments, page history and permissions do not come over. `Import Report` in the folder lists what was left out or changed. Imported to-dos stay out of Tasks unless you tick “Show imported to-dos in Tasks”. Not available on a vault hosted on a server: import into a local vault, then sync it. Use a token instead if you’d rather share page by page with a Notion integration.' }, { title: 'Bring your Obsidian vault over', + only: 'desktop', body: 'Run “Import Notes…” from the command palette (`Space I` in Vim mode), or set it up during onboarding, choose Obsidian, and pick the folder that holds your vault. There are two ways to go from there. Open as its own vault points ZenNotes at the folder directly, so both apps share the same files and nothing is copied. Copy in brings it into the vault you have open: you get a tree of its folders and notes with everything ticked, and unticking a folder leaves it out, though images a kept note uses still come along. It adds one `Obsidian Import` folder in one step, with the same folders inside, so your original vault and what’s already here don’t change, and deleting that folder undoes it. Callouts, `[[wikilinks]]`, embeds, block references, tags and frontmatter work as they are, so most notes stay byte for byte what they were. A link only changes where its name is now shared: a title two folders use, or one that’s already in this vault, gets pinned to the note Obsidian would have opened. `.obsidian` and `.trash` stay behind, and plugins don’t come over, so Dataview queries stay code blocks and canvases and Obsidian Bases stay files that ZenNotes doesn’t open. `Import Report` in the folder lists these, and where your daily notes and templates went so you can point Settings at them. To-dos show in Tasks unless you untick “Show imported to-dos in Tasks”.' }, @@ -183,6 +217,7 @@ export const HELP_HOW_TO_GUIDES: HelpCard[] = [ }, { title: 'Open a vault in your file manager', + only: 'desktop', body: 'Every local vault can open its folder in Finder, File Explorer or your file manager, whether or not it is the vault you are in. Click the vault name at the top of the sidebar: each vault in the list shows a folder button when you point at it, and `Shift+Enter` does the same for the row under the cursor. In the vault switcher (`Space v`), `Shift+Enter` opens the highlighted vault’s folder instead of switching to it. For the vault you are in, use “Open in Finder” in that same sidebar menu, “Open Vault in File Manager” in the command palette, `Space F` in Vim mode, or the button in Settings → Vault → Location. A remote workspace has no folder on this machine, so it does not offer this, and neither does the web app. A vault whose folder has moved says so instead of opening.' }, @@ -238,16 +273,19 @@ export const HELP_HOW_TO_GUIDES: HelpCard[] = [ }, { title: 'Search from Raycast on macOS', + only: 'desktop', body: 'Install the `zn` CLI from Settings → CLI, then use the Raycast Extension section on the same page to install ZenNotes for Raycast locally. Raycast can search notes, filter by folder or tag, open a note in the app, open it in a floating window, archive or unarchive, move to Trash, reveal in Finder, copy the note path, and copy a wikilink.' }, { title: 'Preview a note in Finder with Quick Look', + only: 'desktop', body: 'On macOS, select a Markdown file in Finder and press Space: Quick Look shows it the way ZenNotes renders it, in your theme and fonts, with callouts, tasks, tables, code, math, Mermaid diagrams and the images the note embeds. Press Open in ZenNotes to open it in the app: a note inside a vault you use opens there, any other file in its own window. Once you click into the preview, Enter does the same, and with Vim mode on `o` opens it too while `j` / `k`, Ctrl+D / Ctrl+U, `gg` and `G` move through the note. The preview is read-only and never goes online: links to websites open in your browser, wikilinks and tags stay plain text, and pictures on the web are not loaded. The preview comes with the app and turns on after you open ZenNotes once; to use another app\'s preview, turn ZenNotes off in System Settings → General → Login Items & Extensions → Quick Look.' }, { title: 'Check for updates and install them', + only: 'desktop', body: 'Use Check for Updates from the app menu, the command palette, or Settings → About. ZenNotes also checks on its own shortly after launch. If that check finds no network (Settings → About then says "Waiting for network"), nothing needs doing: it checks again by itself once the connection is back, and keeps trying at growing intervals if GitHub stays out of reach. A check that runs while a new release is still being published says so (for example "ZenNotes 2.79.0 is still being published"): try again in a few minutes. Any other failed check or download is one sentence in Settings → About, with the technical text under Details, where Copy details and Report an Issue help with a bug report. When a release is available, ZenNotes can download it in the background and then prompt you to install and relaunch. A copy installed by a package manager (the AUR package, or a tarball unpacked by hand) is only told that a newer version exists; install it the way you installed ZenNotes, since the package manager owns those files. On Arch, a `.pacman` build installs through a graphical polkit prompt; dismissing it keeps the download ready to retry, and if no graphical agent can run, Details in Settings → About shows the manual install command.' }, @@ -263,6 +301,7 @@ export const HELP_HOW_TO_GUIDES: HelpCard[] = [ }, { title: 'Connect the desktop app to a self-hosted server', + only: 'desktop', body: 'Settings → Vault → Remote workspace takes the server URL and its token. **On macOS**, a server on your own network also needs the system Local Network permission: macOS asks the first time ZenNotes reaches a local address, and if you dismiss that prompt the connection fails with no packets sent and no further warning: it looks exactly like a server that is down. Turn it back on under System Settings → Privacy & Security → Local Network. A server reached over the public internet is unaffected. Live updates travel over a WebSocket at /api/watch. If a reverse proxy in front of the server does not pass WebSocket upgrades, the app refreshes on its own every 30 seconds instead, so a note renamed or trashed on another device can show its old name for up to half a minute; passing the upgrade through gives instant updates.' }, @@ -278,11 +317,13 @@ export const HELP_HOW_TO_GUIDES: HelpCard[] = [ }, { title: 'Customize the look: themes vs. overrides', + only: 'desktop', body: 'ZenNotes has two CSS-based ways to change how it looks. A **theme** is a complete palette you select under Settings → Appearance → Custom. An **override** is a small CSS file that layers on top of whichever theme is active, toggled on or off under Settings → Appearance → Overrides. Reach for a theme to design a whole look; reach for an override to change one or two things (a different accent, a darker background) without forking a theme. Both apply live, no restart.' }, { title: 'Build a custom theme', + only: 'desktop', body: 'Settings → Appearance → Custom → New theme scaffolds a folder at `~/.config/zennotes/themes//` with a `manifest.json` and a `theme.css`, reveals it, and adds a card you click to apply. Edits to `theme.css` apply live. Only the active theme CSS is loaded, so write `:root { … }` for the light/shared values and `:root[data-theme-mode="dark"] { … }` for dark. You never put the theme name in a selector. Colors are the `--z-*` tokens, written as space-separated RGB (`--z-accent: 255 59 48;`): backgrounds `--z-bg` / `--z-bg-softer` / `--z-bg-1`…`--z-bg-4`, text `--z-fg-1` / `--z-fg-2` / `--z-grey-0`…`--z-grey-2`, accent `--z-accent` / `--z-accent-soft` / `--z-accent-muted`, and the syntax hues `--z-red` / `--z-green` / `--z-yellow` / `--z-blue` / `--z-purple` / `--z-aqua`. `manifest.json` carries name, author, version, description, `modes` (light | dark | both), and an optional preview swatch.' }, @@ -293,16 +334,19 @@ export const HELP_HOW_TO_GUIDES: HelpCard[] = [ }, { title: 'Add syntax highlighting for another language', + only: 'desktop', body: 'In the desktop app, open Settings → Editor → Languages and select a self-contained `.tmLanguage.json` TextMate grammar. Choose its fenced-code tag and aliases, then edit the sample to verify the live preview before installing it. Enabled languages highlight the same fences in Edit, Split, and Preview without changing your Markdown files. Built-in language and diagram tags stay reserved. ZenNotes stores installed packs machine-wide under `~/.config/zennotes/languages/`; this first version adds highlighting only, not completion, formatting, indentation, or language-server features.' }, { title: 'Override one thing on any theme', + only: 'desktop', body: 'An override is a `.css` file in `~/.config/zennotes/overrides/`, toggled under Settings → Appearance → Overrides. Enabled overrides inject on top of the active theme in filename order, so they win the cascade. Target `:root[data-theme] { … }` so the rule beats both built-in and custom themes. Because they sit on top, one override re-themes everything: `:root[data-theme] { --z-accent: 255 59 48; }` turns the accent hot pink on every theme. Overrides stack, so keep several small ones and flip each independently. The seeded `example.css` is a commented cookbook with the full token list and ready-to-uncomment recipes. To find what controls an element, use the **Developer tools** button in that same Overrides section and inspect it.' }, { title: 'Bundle fonts and images in a theme', + only: 'desktop', body: 'Ship an asset with a theme by dropping the file in the theme folder and referencing it with the `zen-theme://` scheme, where the host is the folder name: `@font-face { font-family: "Display"; src: url(zen-theme://my-theme/display.woff2); }`. Remote http/https URLs are never loaded, so themes stay self-contained and work offline; small images can also be inlined as `data:` URIs. Font family and text size are not theme tokens. Set those under Settings → Typography.' } @@ -561,6 +605,7 @@ export const HELP_CORE_CONCEPTS: HelpCard[] = [ }, { title: 'Open links in other applications', + only: 'desktop', body: 'On desktop, enable application prefixes such as zotero, obsidian, or vscode under Settings → Editor → Links → External application links. Separate prefixes with commas; they are saved in config.toml. Use ordinary Markdown, for example [Paper](zotero://open-pdf/library/items/W78FUE98). Editor clicks, Cmd/Ctrl-click, preview links, and Vim gd open enabled links in the installed application. A disabled application link offers Open settings, never note creation. If the application cannot open the link, ZenNotes shows an error.' }, @@ -591,6 +636,7 @@ export const HELP_CORE_CONCEPTS: HelpCard[] = [ }, { title: 'The CLI is the bridge to launchers', + only: 'computer', body: 'The `zn` command-line tool can list, read, search, capture, edit, archive, trash, inspect tasks, work with databases (`zn base list / rows / get / add / set / create / pages`: add rows with record pages (a row added while the database opens on a view of picked rows joins that view\'s picks, as + Row does in the grid), give every record its page with `zn base pages`, set fields with the grid’s exact semantics, locally or against a self-hosted server; renaming a record page with `zn rename` keeps its row pointing at it), and start the MCP server without the app running. With no `--vault` or `--server` flag, `zn` works on the vault the app has open, a connected server included (it sends the token `zn connect` saved for that server, or `ZENNOTES_REMOTE_TOKEN` / `--token`). Raycast uses it for search, then uses `zennotes://open` and `zennotes://open-window` links to bring the selected note back into ZenNotes. On macOS, Settings → CLI can install the bundled Raycast extension locally so users do not need to wait for the Raycast Store version.' }, @@ -621,21 +667,25 @@ export const HELP_CORE_CONCEPTS: HelpCard[] = [ }, { title: 'Updates are release-driven', + only: 'desktop', body: 'In-app updates read the published GitHub release feed. That means update checks, download prompts, and release notes are all driven by the same public releases you can open manually from the app menu or command palette.' }, { title: 'Workflows plan first and write second', + only: 'workflows', body: 'A workflow is a plain `.md` file under `.zennotes/workflows/`: frontmatter plus one pipeline per line, like `good = books | where rating >= 4`. Wires carry sets of notes, so every wire on the canvas shows the live count flowing through it, and the canvas and the text are lossless projections of the same file (layout is computed, so no coordinates ever land in your vault). The engine can only propose changes: running shows the full dry-run diff before anything is applied, applying journals every file\'s pre-run bytes so Undo restores them exactly, and a run that fails midway rolls the whole thing back on its own. There are no code steps, no shell, and no network, which is why a workflow you did not write is safe to read and run. A workflow runs when you run it, and since 2.55 also on its own when its `trigger:` names an event: `on note-created`, `on note-saved`, `on note-moved` or `on tag-added` fires for the note you change in this app, a moment after it settles, with no confirmation and a receipt toast that carries Undo (see the Event triggers card); a `schedule` trigger parses but does not fire yet. Local desktop vaults, self-hosted web servers, and desktop remote workspaces can all author and run workflows; a remote workspace needs a server on 2.29 or newer, and against an older server workflows stay read-only. The feature is off by default; enable it under Settings → Workflows.' }, { title: 'The workflow grammar in one card', + only: 'workflows', body: 'Six sources open a set: `all`, `folder inbox`, `tag #book`, `search reading list`, `current`, `selection` (the Trash and Archive stay out unless you name them, like `folder trash`; the four system names `inbox`, `quick`, `archive`, `trash` mean those folders wherever the vault keeps them, so on a vault whose notes live at the root `folder inbox` is the vault root). Thirteen steps filter and shape it: `where rating >= 4`, `tagged` / `not-tagged #x`, `no-tags`, `in inbox/projects`, `matching inbox/**/*.md`, `contains TODO`, `since 7d`, `sort finished desc`, `limit 25`, `dedupe`, and `union` / `subtract ` to combine named wires. `tag`, `tagged` and `not-tagged` also take a comma-separated list and match any tag in it, so `all | not-tagged #someday, #reference` keeps the notes carrying neither, and `all | no-tags` keeps the notes with no tag at all. Mutating steps change every note on the wire, always behind the dry-run confirmation: `set status done`, `add-tag` / `remove-tag`, `move`, `rename {{date}}-{{title}}`, `append` / `prepend`, `apply-template`, `archive`, `trash`. Outputs turn the wire into text: `render table title, rating` feeds `write "Log.md"`, `write-section "Log.md" "Finished"`, `create-each "inbox/{{title}}.md"`, `notify`, or `clipboard`, and `call ` folds another workflow into the same run. `{{title}}`, `{{date}}`, `{{count}}` and any frontmatter field expand per note. Press `?` in the Workflows view for the live reference, with a one-line description and a real example for every step.' }, { title: 'Event triggers', + only: 'workflows', body: 'Set `trigger: on note-saved` (or `on note-created`, `on note-moved`, `on tag-added`) on an active workflow and it runs by itself when you make that change in this app, about a second and a half after the note settles: a burst of autosaves while you type is one run, and a note you are still typing in waits for its next save. `note-moved` fires with the note\'s new path for a rename, a move, Archive, Trash and Restore; `tag-added` fires for a save that gave the note a tag it did not have. The run sees only the note that changed: every source (`all`, `folder`, `tag`, `search`, `current`) resolves over that one note, so `all | contains type: topic | move Topics` means "file this note under Topics when it says so", and nothing is read across the vault on every save. Add a condition to fire only when the note matches: `trigger: on note-saved where folder = inbox` takes the same `field op value` a `where` step takes. There is no confirmation; the receipt toast carries Undo, a run that changed nothing says nothing, and a note the run would write that has unsaved edits is left alone and named. Only edits made in this app fire: a change that arrives by sync or from another device does not, what a run itself writes never fires again, a folder rename does not fire for the notes inside it, and the phone apps do not fire at all. `status: draft` or `trigger: manual` silences one workflow; Settings → Workflows → Event triggers (`workflow_event_triggers` under `[view]` in config.toml) silences them all on this device. A `schedule` trigger still parses without firing.' } @@ -694,6 +744,7 @@ export const HELP_SHORTCUT_SECTIONS: HelpShortcutSection[] = [ { id: 'quick-capture-window', title: 'Quick capture window', + only: 'desktop', description: 'These apply inside the floating capture window, opened with the quick capture hotkey.', items: [ { keys: 'Mod+Enter', action: 'Save and hide', detail: 'Save the note into Quick Notes and hide the window. A fresh capture clears for next time; an opened note is left as you left it.' }, @@ -726,13 +777,13 @@ export const HELP_SHORTCUT_SECTIONS: HelpShortcutSection[] = [ { keys: 'Space G', action: 'Folder gallery', detail: 'Open the Gallery of the folder under the sidebar cursor (while the sidebar has focus) or of the open note’s folder: its notes as cards led by their covers. h / j / k / l move, Enter opens, / filters by title. A capital G, since `Space g` is the Atlas.' }, { keys: 'Space k', action: 'New Kanban', detail: 'Create a Kanban board (To do, Doing, Done) in the folder under the sidebar cursor while the sidebar has focus, otherwise where new databases go, and open it. Also New Kanban in the palette and `:kanban`.' }, { keys: 'Space v', action: 'Switch vault', detail: 'Open the command palette directly to the local vault switcher.' }, - { keys: 'Space I', action: 'Import notes', detail: 'Open the Import window, for Notion and Obsidian.' }, - { keys: 'Space F', action: 'Open vault folder', detail: 'Open the current vault’s folder in Finder, File Explorer or your file manager. Desktop, local vaults only.' }, + { only: 'desktop', keys: 'Space I', action: 'Import notes', detail: 'Open the Import window, for Notion and Obsidian.' }, + { only: 'desktop', keys: 'Space F', action: 'Open vault folder', detail: 'Open the current vault’s folder in Finder, File Explorer or your file manager. Desktop, local vaults only.' }, { keys: 'Space a', action: 'Open workflows', detail: 'Open the Workflows view, where saved pipelines over your notes are built and run. Workflows are off by default; turn them on under Settings → Workflows first.' }, { keys: 'Space r', action: 'Review Cloud conflicts', detail: 'Open whatever Cloud sync is waiting on: the queue of files two devices changed at once, one decision at a time, or the vault settings question, which lists each setting that differs with this device’s value beside the cloud’s and lets you pick a side per setting. When the open note is one of the waiting files, the queue starts on it. A waiting note also says so across its top, in Edit and Preview alike: sync is paused for it until you choose what to keep, and its Review button opens the queue on it. Choosing the other device’s version puts the file where that device left it; when this device already has a different file there, that file moves beside it under the next free name, such as Untitled 2.md. A notification with Review appears once when a new conflict arrives. When the Cloud vault this vault syncs with is deleted, on this device, another device or the website, the status bar says Cloud vault deleted and the binding opens Settings → Cloud instead, where This vault says what happened until you choose a cloud vault, start a new one, or dismiss the notice. If another device moved it into an end-to-end encrypted vault, the status bar says Cloud vault now encrypted instead, and This vault asks you to unlock this device if needed, then choose the encrypted vault. The binding and the command palette entry appear only while something is waiting, and open the same place as Review in the status bar.' }, { keys: 'Space g', action: 'Open atlas', detail: 'Open the Atlas view: the whole vault drawn as a map of notes and links.' }, { keys: 'Space q', action: 'Quick capture window', detail: 'Open the floating, always-on-top capture window, same as the global hotkey.' }, - { keys: 'Space b', action: 'Hide to tray', detail: 'With Settings → Appearance → Keep running in the tray on, hide this window. ZenNotes keeps running, Cloud sync and the Quick capture hotkey keep working, and the tray icon brings the window back. Hide Window to Tray in the command palette does the same.' }, + { only: 'desktop', keys: 'Space b', action: 'Hide to tray', detail: 'With Settings → Appearance → Keep running in the tray on, hide this window. ZenNotes keeps running, Cloud sync and the Quick capture hotkey keep working, and the tray icon brings the window back. Hide Window to Tray in the command palette does the same.' }, { keys: 'Space i', action: 'Insert template into note', detail: 'Pick a template and insert it at the cursor of the active note, instead of creating a new note from it. Without Vim mode, give “Insert template into current note” a key under Settings → Keymap.' }, { keys: 'Space c', action: 'Toggle calendar', detail: 'Show or hide the calendar panel for the active pane.' }, { keys: 'Space n', action: 'Toggle timeline', detail: 'Show or hide the Timeline panel for the active pane, and move the keyboard into it: j / k move, gg / G jump to the ends, x ticks the task, Enter opens it at its line, m opens the task menu, / focuses the filter, and Esc goes back to the note. Mod+7 toggles it in any mode.' }, @@ -905,6 +956,7 @@ export const HELP_SHORTCUT_SECTIONS: HelpShortcutSection[] = [ { id: 'workflows-view', title: 'Workflows view', + only: 'workflows', description: 'Off by default; enable under Settings → Workflows. The single-letter keys below are Vim-mode only, like every list in the app; arrows, Enter, and Esc always work, and Shift+F10 (or the ContextMenu key) opens the row menu in either mode.', items: [ @@ -1281,6 +1333,7 @@ export const HELP_VIM_COMMANDS: HelpExCommand[] = [ }, { command: ' F', + only: 'desktop', summary: 'Leader open vault folder', detail: 'Open the current vault’s folder in the system file manager.' }, @@ -1388,7 +1441,7 @@ export const HELP_SETTINGS: HelpSettingsSection[] = [ { label: 'Theme, mode, and variant', detail: 'Pick a theme family: Apple, Gruvbox, Catppuccin, GitHub, Solarized, One, Nord, Tokyo Night, Kanagawa (Wave / Dragon / Paper Ink (Custom) / Lotus), Rosé Pine (Rosé Pine / Moon / Dawn), or the monochrome, true-black (OLED-friendly) Black Metal, plus light or dark mode and the active flavor or contrast where the theme supports it.' }, { label: 'Window title bar', detail: 'Under Settings → Appearance → Chrome, turn off Window title bar to remove the main window title and controls on macOS, Windows, and Linux, including tiling desktops such as Hyprland. The sidebar and editor stay visible, and the change applies to open vault windows without a restart. Drag blank space in the tab strip, the sidebar header or the note list header to move the window, or use your window manager shortcuts. Press Cmd/Ctrl+, to restore the setting. The preference is saved as [appearance].show_window_title_bar in config.toml. In the browser app the same switch is called Title bar: it hides the bar with the open note’s title, in that browser.' }, { label: 'Status bar', detail: 'Under Settings → Appearance → Chrome, Status bar shows or hides the bar along the bottom of the window: the ZenNotes Cloud status (Synced, Sync now, Set up) and, on desktop, the open note’s backlinks, words, characters, reading time and cursor position. It is on by default. Turned off, the bar stays hidden except while Cloud needs you: a sync that stopped or failed, files or vault settings waiting for review, a Cloud vault that went away, or a device that was signed out. Then it comes back until that is dealt with, so nothing that needs an answer goes silent. On Android the bar is the Cloud row at the bottom of the screen, and turning it off gives that row back to the note; the iPhone already shows that row only while Cloud needs you. Toggle it from the command palette (Toggle Status Bar) or, in Vim mode, with `:set nostatusbar` and `:set statusbar`. The preference is saved as [appearance].show_status_bar in config.toml.' }, - { label: 'Keep running in the tray', detail: 'Off by default. Under Settings → Appearance → Window, turn it on and closing the last window hides it instead of ending the session: a ZenNotes icon in the system tray (the menu bar on macOS) stays, Cloud sync and the Quick capture hotkey keep working, and the icon\'s tooltip and menu show the sync state while a Cloud vault is linked. Click the icon, or choose Open ZenNotes in its menu, to bring the window back; on macOS the Dock icon does too. Quit from the icon\'s menu, with Quit ZenNotes in the command palette, or with Cmd+Q on macOS. On a desktop with no tray host the icon does not appear: open ZenNotes again and the window comes back. `Space b` (Hide Window to Tray in the palette) hides the window on purpose, which a tiling window manager cannot do with minimise. The setting belongs to this computer and is not part of config.toml. While ZenNotes runs it also checks for updates every six hours, not only at launch.' }, + { only: 'desktop', label: 'Keep running in the tray', detail: 'Off by default. Under Settings → Appearance → Window, turn it on and closing the last window hides it instead of ending the session: a ZenNotes icon in the system tray (the menu bar on macOS) stays, Cloud sync and the Quick capture hotkey keep working, and the icon\'s tooltip and menu show the sync state while a Cloud vault is linked. Click the icon, or choose Open ZenNotes in its menu, to bring the window back; on macOS the Dock icon does too. Quit from the icon\'s menu, with Quit ZenNotes in the command palette, or with Cmd+Q on macOS. On a desktop with no tray host the icon does not appear: open ZenNotes again and the window comes back. `Space b` (Hide Window to Tray in the palette) hides the window on purpose, which a tiling window manager cannot do with minimise. The setting belongs to this computer and is not part of config.toml. While ZenNotes runs it also checks for updates every six hours, not only at launch.' }, { label: 'Dark sidebar', detail: 'Tint the sidebar slightly darker than the canvas so the chrome reads as a distinct surface.' }, { label: 'Sidebar arrows', detail: 'Show or hide disclosure arrows for collapsible sidebar folders and sections.' }, { label: 'Use theme for PDF export', detail: 'Under Settings → Appearance → PDF export. Off by default, so exported PDFs use a clean light print theme. Turn it on to export in your current look instead: your theme (colors and dark/light, including custom themes), plus your enabled CSS snippets and color tweaks, as a full-bleed page. This toggle is the single switch for how the PDF looks; your CSS snippets style the export only while it is on, so you customize the PDF by editing your snippets, not with a separate print stylesheet.' } @@ -1454,7 +1507,7 @@ export const HELP_SETTINGS: HelpSettingsSection[] = [ { title: 'Vault', items: [ - { label: 'Vault location', detail: 'Open the folder ZenNotes treats as the active vault in Finder, File Explorer or your file manager, or change it.' }, + { only: 'desktop', label: 'Vault location', detail: 'Open the folder ZenNotes treats as the active vault in Finder, File Explorer or your file manager, or change it.' }, { label: 'Vault name', detail: 'What the sidebar header, the vault switcher and the title bar call this vault; the folder keeps its own name on disk. Leave it empty to use the folder name. Saved in the vault’s `.zennotes/vault.json`, so it follows the folder wherever it is opened. Also “Rename Vault…” in the command palette (`:vault_rename`) and the sidebar’s vault menu. Local vaults only.' }, { label: 'Primary notes location', detail: 'Treat `inbox/` as the main notes area, or use the vault root directly for an Obsidian-style flat vault.' }, { label: 'Default Locations', detail: 'Choose where new Excalidraw drawings, databases (Kanbans included), and task files are created so they do not pile up in the vault root: the primary notes location (the default), the folder of the note you are currently viewing, or a specific folder you name (e.g. `Drawings` or `Tasks`). A specific folder lives inside the primary notes area, so `Tasks` means `inbox/Tasks/` in an Inbox vault and `Tasks/` in a root vault; the folder field lists the folders there and shows the exact destination. In a root vault, a folder under `assets/` (or another attachments folder, or a hidden one) cannot hold notes, so new files go to the vault root instead and the field says why. New task files come from `+ New task`, the `a` key in the Tasks view, `:newtask` and the command palette; `New Task in Folder…` and `:newtask ` still pick a folder per task. Search Settings for "tasks folder" or "drawings folder" to jump there. Only new files are affected; existing ones stay put.' }, @@ -1481,6 +1534,7 @@ export const HELP_SETTINGS: HelpSettingsSection[] = [ }, { title: 'CLI', + only: 'desktop', items: [ { label: 'Install Command-Line Tool', detail: 'Symlink the bundled `zn` wrapper into a usable PATH location so any terminal session can capture, search, and edit notes. ZenNotes prefers user-writable directories and only prompts for admin access when no writable PATH target is available. The app carries the tested CLI runtime, so desktop-managed updates ship together. Builds with the terminal app install a persistent copy that also works after desktop closes.' }, { label: 'Status, path, and quick reference', detail: 'Settings → CLI shows whether `zn` is installed, where the symlink lives, and a copy-able quick reference of the most useful commands. If the chosen directory is not on PATH yet, Settings shows the exact shell command to add it. An "External install" badge appears when something else owns `zn` so ZenNotes never clobbers an unmanaged binary.' }, @@ -1511,6 +1565,7 @@ export const HELP_SETTINGS: HelpSettingsSection[] = [ }, { title: 'Workflows', + only: 'workflows', items: [ { label: 'Workflows', detail: 'Off by default. Turn it on to add the Workflows view (sidebar row, palette commands, and the Space a leader binding in Vim mode): saved, repeatable pipelines over your notes, edited on a canvas and run behind a dry-run confirmation with whole-run undo. Turning it off hides all of that again and closes the view if it is open.' } ] @@ -1522,9 +1577,9 @@ export const HELP_SETTINGS: HelpSettingsSection[] = [ { label: 'Version details', detail: 'Under the version, a Version details block lists what a bug report needs: operating system and architecture, the Electron or browser engine, how this copy was installed, and the remote server version when connected to one. Copy details puts the block on the clipboard. In Vim mode, `:version` prints the same lines and `:version copy` copies them.' }, { label: 'What’s New', detail: 'The first time ZenNotes starts after an update, a window shows what the version brought, once: its highlights, any announcement, and a link to the full release notes. Escape or Close dismisses it. Open it again any time with What’s New in ZenNotes in the command palette, or `:whatsnew` in Vim mode.' }, { label: 'Count this copy anonymously', detail: 'Once when ZenNotes is installed and once per update, the desktop app sends zennotes.org the version, operating system, architecture and install type, so we know how many copies are in use. It carries no identifier and nothing about your notes, vaults or account, and only daily totals are kept. On by default; turn it off here to send nothing. Set in config.toml as `[privacy] usage_count`.' }, - { label: 'Updates and releases', detail: 'Check for updates, download a newer build, install and relaunch, or jump straight to the latest GitHub release from inside the app. AUR and tarball installs get the check and the notice only; the package manager does the install.' }, + { only: 'desktop', label: 'Updates and releases', detail: 'Check for updates, download a newer build, install and relaunch, or jump straight to the latest GitHub release from inside the app. AUR and tarball installs get the check and the notice only; the package manager does the install.' }, { label: 'Website, community, and issue links', detail: 'The app now exposes direct links to the ZenNotes website, Discord, GitHub repository, and issue tracker so support paths stay discoverable.' }, - { label: 'Configuration file', detail: 'Your preferences (theme, editor, Vim, keymaps, fonts, search backend, and more) are mirrored to a plain-text `config.toml` so you can sync them across machines with git, stow, or chezmoi. It lives at `$XDG_CONFIG_HOME/zennotes/config.toml` (`~/.config/zennotes/config.toml` on macOS and Linux, `%APPDATA%\\zennotes\\config.toml` on Windows), or wherever `$ZENNOTES_CONFIG_DIR` points. The file is self-documenting: every available setting is listed with its allowed values, and every keymap action is listed with its default binding (commented out: uncomment a line and edit it to remap, or set it to `""` to remove the key entirely), and every command palette command is listed under `[keymaps.commands]` (`"note.trash" = "Mod+Backspace"`, or `"note.archive" = "Leader x a"` for a leader sequence; a command id written straight under `[keymaps]` is read as a command key too and moved to that table on the next save), so you can discover and change anything without opening the app. That list reads the same on every OS: where macOS has its own default, the line notes it, as in `# "tabs.select1" = "Alt+1" # Go to tab 1 (macOS: "Ctrl+1")`, so a file synced between a Mac and a Linux or Windows machine changes only when you change a setting. Settings → About has Reveal and Copy-path buttons. Existing setups are written out automatically the first time you launch this version, and edits to the file, by hand or via a synced dotfile, apply live without a restart. Tables and keys only zn uses, like `[terminal]`, stay in the file when the app saves it. Machine-specific layout (window size, pane widths, collapsed folders) stays local so the file does not churn.' }, + { only: 'desktop', label: 'Configuration file', detail: 'Your preferences (theme, editor, Vim, keymaps, fonts, search backend, and more) are mirrored to a plain-text `config.toml` so you can sync them across machines with git, stow, or chezmoi. It lives at `$XDG_CONFIG_HOME/zennotes/config.toml` (`~/.config/zennotes/config.toml` on macOS and Linux, `%APPDATA%\\zennotes\\config.toml` on Windows), or wherever `$ZENNOTES_CONFIG_DIR` points. The file is self-documenting: every available setting is listed with its allowed values, and every keymap action is listed with its default binding (commented out: uncomment a line and edit it to remap, or set it to `""` to remove the key entirely), and every command palette command is listed under `[keymaps.commands]` (`"note.trash" = "Mod+Backspace"`, or `"note.archive" = "Leader x a"` for a leader sequence; a command id written straight under `[keymaps]` is read as a command key too and moved to that table on the next save), so you can discover and change anything without opening the app. That list reads the same on every OS: where macOS has its own default, the line notes it, as in `# "tabs.select1" = "Alt+1" # Go to tab 1 (macOS: "Ctrl+1")`, so a file synced between a Mac and a Linux or Windows machine changes only when you change a setting. Settings → About has Reveal and Copy-path buttons. Existing setups are written out automatically the first time you launch this version, and edits to the file, by hand or via a synced dotfile, apply live without a restart. Tables and keys only zn uses, like `[terminal]`, stay in the file when the app saves it. Machine-specific layout (window size, pane widths, collapsed folders) stays local so the file does not churn.' }, { label: 'Lumary Labs', detail: 'The About section links to Lumary Labs at lumarylabs.com so company details stay easy to find from inside the app.' } ] } @@ -1533,87 +1588,133 @@ export const HELP_SETTINGS: HelpSettingsSection[] = [ export const HELP_CLI: HelpCard[] = [ { title: 'What the CLI is for', + only: 'computer', body: '`zn` is a command-line companion that talks to your vault directly. It reads and writes the same markdown files the app does, so anything you do in a terminal (capture, search, append, archive, list tasks) shows up in the app instantly. Use it for shell pipelines, scripts, cron jobs, editor plugins (vim, emacs, helix), launcher integrations (Raycast, Alfred), or just because the keyboard is faster.' }, { title: 'Install it once from Settings', + only: 'desktop', body: 'Open Settings → CLI and click Install. ZenNotes symlinks the bundled wrapper into a usable PATH location, preferring user-writable directories and only asking for admin access when no writable PATH target is available. After that, `zn --help` works in any new terminal. You can also run the install from the command palette via "Install Command-Line Tool (zn)".' }, { title: 'The terminal app and existing installations', + only: 'desktop', body: 'Builds with the Go terminal tool include `zn tui`. An existing desktop-managed CLI keeps itself up to date (see Updates arrive without a ZenNotes update); keep using the same `zn` commands. Settings shows the installed terminal version and offers Repair if an upgrade needs attention. Desktop-installed commands keep following the desktop vault, while the TUI remembers its own selection. Explicit `--vault` and `--server` flags still win. Set `ZENNOTES_WORKSPACE_SOURCE=terminal` to use the terminal default for a command, or `ZENNOTES_CLI_ENGINE=legacy` to run the previous CLI during the transition. Homebrew and manual installations stay managed by their own installer. A shortcut left behind by a moved Mac app or an old AppImage can be repaired from Settings: review the old target, replacement and backup path before choosing Repair shortcut. Note saves preserve creation dates in small files under `.zennotes/note-metadata` without changing Markdown; keep the `.zennotes` folder with vault backups. Explicit legacy rollback needs the original app resources to remain available.' }, { title: 'CLI 0.17.0 in desktop 2.83.0', + only: 'desktop', body: 'On macOS and Linux, desktop 2.83.0 bundles CLI 0.17.0. Run `zn` in an interactive terminal or `zn tui` to open the editor. It includes editable settings, restored splits and sessions, comments, attachments, templates, bulk actions, and cross-note yank and paste. Use `:version` in the TUI for a persistent report and press `c` or `y` to copy it. `zn status`, `zn doctor`, `zn config`, and `zn completion` help with setup and scripts; `zn server` manages native local servers, also available through `:servers`. Since 0.6.1, `zn vault list` marks each entry `app` (saved by this desktop app) or `terminal` (saved by zn itself) and says which of them `zn use`, `zn disconnect` and `zn vault remove` act on; every command starts without waiting on terminals that do not answer a background-color query; and the help output lines up. 0.6.2 is the first release with a signed manifest, which is how this app keeps its managed zn current, 0.6.3 reads a line over a lone `-` as a paragraph, as the app does (#898), and 0.7.0’s `zn mcp` records an assistant’s edits for review in this app and no longer lets an assistant write into `.zennotes`. 0.7.1 leaves cancelled tasks out of the open ones in `zn task list` and in `zn mcp`’s `list_tasks` (#929), and when a server needs a token, its message points to Settings → MCP → Server token. 0.7.2 reads tasks in numbered lists and quotes the way the app does, in `zn task` and in `zn mcp`, and 0.8.0 adds `zn task watch`, which prints each task status change as it happens, and gives each task’s status in `zn task list --json` and in `list_tasks`. 0.8.1 keeps a finished task note in its Custom status column and gives `zn mcp` this app’s assistant instructions again, and 0.9.0 follows the vault’s Task folders in `zn task list`, `zn task watch` and `zn mcp`, and the TUI’s Settings saves both Tasks folder lists where every app reads them. 0.9.1 keeps a wikilink of more than one word from widening the TUI preview’s row and scrolling the whole screen. 0.9.2 lets a second `$` on a wrapped line reach the end of the line and makes three backticks a code fence, 0.10.0 adds `zn base pages`, which gives every database record its record page so each can be linked, and 0.11.0 gives a task without a due date its own No due date group and Status board column, as this app does (#990), and orders the task list by priority with `O` or `:order priority` (#989). 0.12.0 can draw display math and TikZ in the TUI preview with `[terminal] math = "latex"`, using TeX installed on your computer (zn does not include TeX; `zn doctor` prints the install commands), 0.12.1 fits pictures in the preview to the pane as it grows or shrinks, 0.12.2 says which TeX tool is missing and how to install it, and 0.13.0 lets `zn mcp` share only part of a vault (`--allow-path`, `--deny-path`, `--read-only`, `--access`; see Share part of a vault with an assistant), keeps assistants out of hidden and system folders, and puts a row `zn base add` makes into the picked rows of the view the database opens on; 0.13.1 leaves the template folder out of tasks, search and tags, as the app does; 0.14.0 adds month, week and day views to the TUI’s Tasks calendar, a bar cursor while you type, a note’s own view mode from its frontmatter (`[terminal] view_mode_field` and `[terminal.view_mode_rules]`), and opens every new note in the editor; and 0.15.0 stops undo from wiping a note, lets autosave be turned off (`[terminal] autosave = false`), and makes `gd` follow links the way the desktop does. 0.16.0 gives `zn mcp` tools for attachments, `update_task`, `daily_note` and sections. 0.17.0 draws Mermaid diagrams at any pane width, keeps a note’s control sequences out of your terminal, keeps code literal in the preview, and reads a table’s `[[Note\\|alias]]` as a link. Run `zn update --check` to see the latest CLI release; for a desktop-managed CLI, ZenNotes installs it. The full command reference is at https://zennotes.org/tui/docs.' }, { title: 'Updates arrive without a ZenNotes update', + only: 'desktop', body: 'For a zn installed from Settings → CLI, ZenNotes checks the latest zn release once a day and installs it when it is newer than the zn you have, so a CLI fix no longer waits for a ZenNotes release. Every release carries a manifest signed with the ZenNotes release key: ZenNotes checks that signature and the download\'s checksum, then runs the new zn once to confirm it answers before switching to it, so a failed or tampered download never replaces a working CLI. The zn a ZenNotes build ships is its floor: a newer release stays installed across restarts, and a ZenNotes update that ships something newer takes over. A release that needs a newer ZenNotes waits until you update ZenNotes. Turn off Update zn automatically in Settings → CLI → Updates to be told instead; Check for updates there, or Check for zn Updates… in the command palette, checks right away. A zn installed with Homebrew, Go or by hand keeps updating through its own installer (`zn update`).' }, { title: 'No app required', + only: 'computer', body: 'The CLI reads from the same vault folder the desktop app uses, so it works whether or not ZenNotes is open. When the app is open, file watchers pick up CLI changes automatically, so captures and edits show up live in the sidebar.' }, { title: 'Point it at a self-hosted server', + only: 'computer', body: 'Every command works against a vault behind a ZenNotes server, not just one on this disk. Once you have connected the desktop app to a server, that server is nameable from the terminal: `zn list --server home`, `zn capture "..." --server home`. `zn vault list` shows local vaults and servers together, and `--vault ` resolves either kind, so the short name you already type keeps working. Pass a URL directly for a server you have not saved (`zn list --server 192.168.1.10:7878`) and `--token` for its auth token. For CI or a headless box, set `ZENNOTES_SERVER` and `ZENNOTES_REMOTE_TOKEN` instead of storing anything on disk. `zn open` is the one exception: it hands file paths to the desktop app, so it needs a local vault.' }, { title: 'Capture is the gateway drug', + only: 'computer', body: 'The fastest way to add a note is `zn capture "..."`. Pipe-friendly: `pbpaste | zn capture --tag idea` lifts the clipboard into a tagged note. The first non-empty line becomes the title. Markdown works too: `zn capture "- [ ] buy milk"` keeps the leading `- [ ]` as a task in the body (so it appears in the Tasks view) while the title reads "buy milk".' }, { title: 'Read and search from the terminal', + only: 'computer', body: 'Use `zn list` to see recent notes, `zn list --tag work --limit 5` to filter, `zn read inbox/Project.md` to print a body, and `zn search "deadline"` for full-text matches with file:line previews. Quote paths with spaces, like `zn read "hellointerview/system design.md"`, or use `--path`. Add `--json` to any command to get structured output you can pipe into `jq`.' }, { title: 'Open notes, folders, and a second window', + only: 'computer', body: '`zn open inbox/Today.md` brings the ZenNotes window to the front with that note loaded, and `zn open ~/code/project/docs` opens a folder as a focused session without turning it into a vault. When a window already shows the vault or folder, `zn open` raises that window. Add `-n` (or `--new-window`) for a second window on the same notes instead, with its own tabs, leaving the first window where it was: `zn open -n ~/notes`. A markdown file outside every vault always reuses its editor window, since nothing keeps two standalone editors of one file in sync.' }, { title: 'Raycast uses the same CLI', + only: 'desktop', body: 'On macOS, install the Raycast extension locally from Settings → CLI after `zn` is installed. ZenNotes copies the bundled extension into app data, runs the local build, and imports it into Raycast, so you do not need the Raycast Store version. The Search Notes command reads from `zn list --json`, then uses `zennotes://open` to open notes in the main app or `zennotes://open-window` to open a floating window. Cmd+K actions also archive, unarchive, move to Trash, reveal in Finder, copy the path, and copy a wikilink.' }, { title: 'Raycast local install requirements', + only: 'desktop', body: 'The local Raycast installer is macOS-only. It needs Raycast, the `zn` CLI, Node.js 22.14 or newer, and npm 7 or newer available from your login shell. Settings shows each requirement, the local extension path, and whether the installed copy is current with the bundled ZenNotes version.' }, { title: 'Edit incrementally', + only: 'computer', body: 'Prefer `zn append` and `zn prepend` over `zn write` for journals and running lists: they preserve the rest of the body. Both accept `--body "literal"` or `--body -` to read stdin (so `cat ideas.txt | zn append daily.md --body -` works).' }, { title: 'Tasks and folders', + only: 'computer', body: '`zn task list` enumerates open checkboxes across the vault with stable ids; with `--json`, each task also carries its status. `zn task toggle ` flips a task without opening the note. `zn task watch` prints a line each time a task’s status changes, with the previous and the new status: a card moved on the Kanban board, a task note’s `status:` or a line’s `@status:` edited, or a box checked. With `--json` each change is one line of JSON, so a script can start an agent when a task becomes ready; zn only reports, and whatever runs is your own script. `zn folder list / create / rename / delete` keep your subfolder tree manageable from the terminal.' }, { title: 'MCP for AI agents', + only: 'computer', body: '`zn mcp` starts the ZenNotes MCP server in stdio mode, the same one Claude Code, Claude Desktop, and Codex use under the hood. The Claude desktop app\'s Code tab runs Claude Code, so it reads the **Claude Code (CLI + Desktop Code tab)** entry in Settings → MCP; **Claude Desktop (Chat)** reaches only its Chat tab. Once `zn` is installed from Settings → CLI, Settings → MCP installs configure the clients to launch `zn mcp` directly, so the install path is one stable absolute path that survives app moves; otherwise, a `zn` installed some other way included, they run the server bundled with the app. The server works on the vault the app has open: a folder on this machine, or a self-hosted ZenNotes server you connected from Settings → Vault. `vault_info` says which. Switch vaults in the app and the server follows: the assistant\'s next tool call is refused with a note naming the old and the new vault, and once `vault_info` confirms the switch it carries on in the new one, so nothing planned in one vault lands in the other. A server that requires a token needs one the MCP server can read, because the app keeps its own copy in the OS secret store. Settings → MCP → Server token → **Let assistants use it** saves it to `credentials.toml` in the config folder, the file `zn connect` writes and both servers read (`zn mcp` and the bundled one), and the assistant\'s next call uses it. Any program running as you can read that file, so it is your choice: **Stop sharing** removes the token, forgetting the server in Settings → Vault removes it too, and a new token you save for the server replaces it. From a terminal, `zn connect --no-default` saves it the same way without changing which vault `zn` follows, and `ZENNOTES_REMOTE_TOKEN` in the MCP client\'s environment works as well. To point an agent somewhere else, give the command the same flags every other `zn` command takes: `zn mcp --vault work` or `zn mcp --server home --token ` in the client\'s config, or `ZENNOTES_SERVER` / `ZENNOTES_VAULT` in its environment. Beyond reading and writing notes, the server can hold a review with you through comments: ask the assistant to read a note\'s comments and answer them, and its replies land in the Comments panel under yours, signed with its name (`list_comments`, `add_comment`, `reply_to_comment`, `resolve_comment`).\n\nIt can work with attachments too. `list_assets` lists every file in the vault that is not a note, `read_asset` returns one up to 5 MiB (an image the model can see, text as text, anything else as an embedded file), and `upload_asset` adds a file from base64, up to 16 MiB, to the `assets` folder without overwriting anything and returns the embed to paste into a note. `rename_asset` and `move_asset` update the notes that link to the file and name any that may still use the old name, `duplicate_asset` copies it, and `delete_asset` moves it to the Trash with a token `restore_asset` takes; `list_assets` with `deleted: true` shows what can come back. Permanent deletion stays in the app. Files reach `upload_asset` as base64 in the tool call, so a model that writes it out itself only manages small ones; there is deliberately no argument that reads a path on your computer, since that would let an assistant with no file access of its own pull any of your files into the vault.\n\nFour more save an assistant from guessing. `update_task` changes a task\'s due date, priority, `@waiting`, state, status or text by its id, `daily_note` finds the daily, weekly or monthly note for a date under the vault\'s own settings and says how to start it if it does not exist, `note_sections` lists a note\'s headings or reads the part under one, and `edit_section` appends to, prepends to or replaces that part.' }, { title: 'Share part of a vault with an assistant', + only: 'computer', body: 'An assistant connected through MCP sees the whole vault unless its launch flags say otherwise, and the server enforces them on every tool: listings, search, tags, tasks, backlinks, assets, comments and error messages, so a hidden note cannot be listed or read another way. One thing can still show: a new or moved file takes a number when a hidden file already has its name. `--allow-path ` shares only that folder or note and what is inside it (repeat it for more), `--deny-path ` hides one even inside an allowed folder, `--read-only` offers the reading tools only, and `--access comment` adds the comment tools to them. Paths are vault-relative, as the tools report them: `Projects` in a vault that keeps notes at its root, `inbox/Projects` in one with an Inbox folder, and a system folder you moved under its own name (`99 Archive/Projects` shares that folder\'s archived notes). A path covers the folder and everything below it, never a sibling that only starts with the same letters, and case and accents do not matter, except that an `--allow-path` with accents shares only a folder that has them. `zn mcp` and the server bundled with the app take the same flags and give the same answers; add them after the command in the client\'s config, for example `"args": ["mcp", "--allow-path", "Projects", "--read-only"]`. Settings → MCP then shows that client as **Needs update**, and updating it there removes the flags.\n\nWhat the assistant gets: a hidden note answers exactly like a missing one (`Note not found`), and so do paths through a symbolic link, case variants and the `.zennotes` folder. Its errors and `vault_info` never show where the vault lives on disk, and `vault_info` lists what was shared under `access`. Tools it cannot use are not offered, and `empty_trash` never is once paths are restricted, since it would delete trashed notes it cannot see. New notes, moves and restores land only inside allowed folders, never through a symbolic link; archiving or trashing a note it can see is allowed even when the archive or trash is not shared, and the note then leaves its view. A `--deny-path` follows a note into the other system folders, however it names the folder: `Journal` also hides `archive/Journal`. `duplicate_note` refuses a copy that would land outside what is shared. A folder is renamed or deleted as a whole only when nothing inside it is hidden. Renaming a note rewrites `[[links]]` only in notes the assistant can see with `zn mcp`, and in none with the bundled server; on a self-hosted ZenNotes server, which rewrites links in every note, an assistant that sees part of the vault cannot rename notes. Attachments follow the same paths: a file is visible when its path is, and a hidden one answers `Asset not found`, like a missing one. Name them in the flags as `list_assets` shows them (`--allow-path assets`, `--deny-path assets/private`). `upload_asset` writes only to `assets`, so it needs that folder shared. Renaming or moving a file rewrites links only in notes the assistant can see. On a self-hosted server, an assistant that sees part of the vault cannot rename, move, read or copy a file; it can list, upload, delete and restore. `daily_note` gives no template, since a template is not filed under any folder a path can name, and where a note\'s folder is not shared it says so rather than offering to create it. A `--deny-path` that names nothing in the vault (renamed outside ZenNotes, or meant for another vault) shares nothing at all until it is fixed, so a rename never quietly reveals what it hid; the MCP server\'s log, which the client keeps, names the entry.\n\nThe flags govern the ZenNotes tools only. An assistant that can also run commands or read files (Claude Code, Codex, OpenCode) can still read the vault from disk.' }, { title: 'Review an assistant’s edits', + only: 'computer', body: 'When an assistant changes a note through MCP (`write_note`, `append_to_note`, `prepend_to_note`, `insert_at_line`, `replace_in_note`, `edit_section`, `toggle_task`, `update_task`), ZenNotes keeps what the note said before, beside it in `.zennotes/agent-edits/`. The note then shows a banner, “Claude Code changed this note 4 minutes ago”, and **Review changes** opens the review in the note itself: each change inline, the removed lines above the new ones, with **Accept** and **Reject** on each and **Accept all**, **Reject all** and **Done** on top. Reject puts the old text back. The note is read-only while you review, and once every change is decided the kept copy is deleted. What you typed after the assistant is yours and is not part of the review. Keys: Ctrl+Alt+↓ and Ctrl+Alt+↑ (Cmd+Option on macOS) move between changes, Ctrl+Shift+Enter (Cmd+Shift+Enter) accepts and Ctrl+Shift+Backspace (Cmd+Shift+Backspace) rejects; in Vim mode, Vim’s diff-mode keys: `]c` and `[c` move, `dp` keeps a change and `do` puts back what it replaced. Escape or **Done** leaves the review and keeps what is undecided. The palette lists every note waiting (**Review Agent Changes**). To tell the assistant why, comment on a change before you decide it; it reads comments with `list_comments`. Turn it off in Settings → MCP → **Review agent edits**. Not kept yet: notes in a vault on a self-hosted server, new notes an assistant creates, and moves, renames and deletions (Trash keeps those).' } ] + +/** The manual as this host shows it. On the desktop app, the whole of it. */ +export function helpForHost(host: HelpHost): { + quickStart: HelpCard[] + howTo: HelpCard[] + concepts: HelpCard[] + shortcuts: HelpShortcutSection[] + vim: HelpExCommand[] + settings: HelpSettingsSection[] + cli: HelpCard[] +} { + const applies = (entry: { only?: HelpAvailability }): boolean => + helpAppliesTo(entry.only, host) + return { + quickStart: HELP_QUICK_START.filter(applies), + howTo: HELP_HOW_TO_GUIDES.filter(applies), + concepts: HELP_CORE_CONCEPTS.filter(applies), + shortcuts: HELP_SHORTCUT_SECTIONS.filter(applies).map((section) => ({ + ...section, + items: section.items.filter(applies) + })), + vim: HELP_VIM_COMMANDS.filter(applies), + settings: HELP_SETTINGS.filter(applies).map((section) => ({ + ...section, + items: section.items.filter(applies) + })), + cli: HELP_CLI.filter(applies) + } +} From 946b37a250f9b0bafd3fca9a8f1f4b53ed1fb72d Mon Sep 17 00:00:00 2001 From: Adib Hanna Date: Thu, 5 Nov 2026 10:36:55 -0600 Subject: [PATCH 07/27] Fix(search): a result names its folder by your label, and root notes name none In a vault that keeps its notes at the root, every note at the root sat in search results labeled INBOX. The row printed `n.folder`, the internal bucket name, which also ignored a custom system folder label. Search Text in Vault, Embed Existing Drawing and the Tags view printed it too, the last one in a vault with an Inbox. `noteAreaLabel` answers for all of them: the label, custom ones included, or nothing for the notes of a root-mode vault. The Quick Capture window's note picker still prints the bucket name. It runs without the store that holds the vault's settings, so it has nothing to decide with. --- .../src/components/EmbedDrawingPalette.tsx | 8 +++++++- .../src/components/SearchPalette.test.ts | 19 +++++++++++++++++-- .../app-core/src/components/SearchPalette.tsx | 13 +++++++++---- packages/app-core/src/components/TagView.tsx | 18 ++++++++++-------- .../src/components/VaultTextSearchPalette.tsx | 13 +++++++++---- .../app-core/src/lib/system-folder-labels.ts | 14 ++++++++++++++ 6 files changed, 66 insertions(+), 19 deletions(-) diff --git a/packages/app-core/src/components/EmbedDrawingPalette.tsx b/packages/app-core/src/components/EmbedDrawingPalette.tsx index 3c10d4db..2b2663ad 100644 --- a/packages/app-core/src/components/EmbedDrawingPalette.tsx +++ b/packages/app-core/src/components/EmbedDrawingPalette.tsx @@ -3,6 +3,8 @@ import { useStore } from '../store' import type { NoteMeta } from '@shared/ipc' import { isExcalidrawPath, isObsidianExcalidrawPath } from '@shared/excalidraw' import { rankItems } from '../lib/fuzzy-score' +import { noteAreaLabel } from '../lib/system-folder-labels' +import { isPrimaryNotesAtRoot } from '../lib/vault-layout' import { isPaletteNextKey, isPalettePreviousKey } from '../lib/palette-nav' import { isImeComposing } from '../lib/ime' import { focusEditorAfterPaletteClose, focusEditorNormalMode } from '../lib/editor-focus' @@ -15,6 +17,8 @@ import { Modal } from './ui/Modal' */ export function EmbedDrawingPalette(): JSX.Element { const notes = useStore((s) => s.notes) + const vaultSettings = useStore((s) => s.vaultSettings) + const systemFolderLabels = useStore((s) => s.systemFolderLabels) const setOpen = useStore((s) => s.setEmbedDrawingPaletteOpen) const insertEmbedAtCursor = useStore((s) => s.insertEmbedAtCursor) const [query, setQuery] = useState('') @@ -109,7 +113,9 @@ export function EmbedDrawingPalette(): JSX.Element { {n.title} - {n.folder} + + {noteAreaLabel(n.folder, isPrimaryNotesAtRoot(vaultSettings), systemFolderLabels)} + )) )} diff --git a/packages/app-core/src/components/SearchPalette.test.ts b/packages/app-core/src/components/SearchPalette.test.ts index b0c2de49..53166dbf 100644 --- a/packages/app-core/src/components/SearchPalette.test.ts +++ b/packages/app-core/src/components/SearchPalette.test.ts @@ -303,7 +303,7 @@ describe('SearchPalette: the create row opens a New note form', () => { type(search(), 'Alph') const rows = [...document.querySelectorAll('[data-search-idx]')] expect(rows.map((r) => r.dataset.searchIdx)).toEqual(['0', '1']) - expect(rows[0].textContent).toBe('Alphainbox') + expect(rows[0].textContent).toBe('AlphaInbox') expect(rows[1].hasAttribute('data-search-create')).toBe(true) expect(highlighted()).toBe('0') @@ -639,10 +639,25 @@ describe('SearchPalette: each row shows the note\'s folder (#982)', () => { { title: 'Overview', folder: 'Projects/Atlas/docs' }, { title: 'Overview', folder: 'Projects/Billing/docs' }, { title: 'Overview', folder: 'archive/2025/Atlas' }, - { title: 'Overview', folder: 'inbox' } + { title: 'Overview', folder: 'Inbox' } ]) }) + it('names a root note by the custom label of its folder', () => { + useStore.setState({ systemFolderLabels: { inbox: 'Desk' } } as never) + act(() => root.render(createElement(SearchPalette))) + expect(shown().at(-1)).toEqual({ title: 'Overview', folder: 'Desk' }) + }) + + it('names no folder for a note at the root of a vault that keeps notes there', () => { + useStore.setState({ + vaultSettings: { ...useStore.getState().vaultSettings, primaryNotesLocation: 'root' } + } as never) + act(() => root.render(createElement(SearchPalette))) + const row = [...document.querySelectorAll('[data-search-idx]')].at(-1)! + expect(row.textContent).toBe('Overview') + }) + it('cuts a long folder from the left and keeps a root note\'s area label', () => { act(() => root.render(createElement(SearchPalette))) const dirs = [...document.querySelectorAll('[data-search-dir]')] diff --git a/packages/app-core/src/components/SearchPalette.tsx b/packages/app-core/src/components/SearchPalette.tsx index ad6b446c..1c616666 100644 --- a/packages/app-core/src/components/SearchPalette.tsx +++ b/packages/app-core/src/components/SearchPalette.tsx @@ -20,7 +20,7 @@ import { type AreaLabels, type SearchCreateDraft } from '../lib/search-create' -import { resolveSystemFolderLabels } from '../lib/system-folder-labels' +import { noteAreaLabel, resolveSystemFolderLabels } from '../lib/system-folder-labels' import { isPrimaryNotesAtRoot, noteFolderLabel } from '../lib/vault-layout' import { isPathInTemplateFolder, resolveTemplateFolder } from '@shared/template-folder' import { useToastStore } from '../lib/toast' @@ -334,6 +334,11 @@ export function SearchPalette(): JSX.Element { } const n = row.note const dir = noteFolderLabel(n, vaultSettings) + const area = noteAreaLabel( + n.folder, + isPrimaryNotesAtRoot(vaultSettings), + systemFolderLabels + ) return ( ) }) diff --git a/packages/app-core/src/components/TagView.tsx b/packages/app-core/src/components/TagView.tsx index 58203c72..c398df9e 100644 --- a/packages/app-core/src/components/TagView.tsx +++ b/packages/app-core/src/components/TagView.tsx @@ -23,6 +23,7 @@ import { listViewSequencesLive, listViewYieldsKey } from '../lib/list-view-keys' +import { noteAreaLabel } from '../lib/system-folder-labels' import { isPrimaryNotesAtRoot, noteFolderSubpath } from '../lib/vault-layout' import { isImeComposing } from '../lib/ime' import { isAppOverlayOpen } from '../lib/overlay-open' @@ -52,12 +53,11 @@ function formatDate(ms: number): string { } function folderLabel(note: NoteMeta): string { - const vaultSettings = useStore.getState().vaultSettings + const { vaultSettings, systemFolderLabels } = useStore.getState() const subpath = noteFolderSubpath(note, vaultSettings) - if (note.folder === 'inbox' && isPrimaryNotesAtRoot(vaultSettings)) { - return subpath - } - return subpath ? `${note.folder} › ${subpath}` : note.folder + const area = noteAreaLabel(note.folder, isPrimaryNotesAtRoot(vaultSettings), systemFolderLabels) + if (!area) return subpath + return subpath ? `${area} › ${subpath}` : area } export function TagView(): JSX.Element { @@ -737,9 +737,11 @@ export function TagView(): JSX.Element {
{note.title || '(untitled)'}
-
- {folderLabel(note) || note.folder} -
+ {folderLabel(note) && ( +
+ {folderLabel(note)} +
+ )} {/* The tagged blocks listed below say more than the opening of the note, so the excerpt only shows without them. */} {note.excerpt && row.blockCount === 0 && ( diff --git a/packages/app-core/src/components/VaultTextSearchPalette.tsx b/packages/app-core/src/components/VaultTextSearchPalette.tsx index 7d805451..41421cbd 100644 --- a/packages/app-core/src/components/VaultTextSearchPalette.tsx +++ b/packages/app-core/src/components/VaultTextSearchPalette.tsx @@ -5,7 +5,8 @@ import type { VaultTextSearchMatch } from '@shared/ipc' import { useStore } from '../store' -import { resolveSystemFolderLabels } from '../lib/system-folder-labels' +import { noteAreaLabel, resolveSystemFolderLabels } from '../lib/system-folder-labels' +import { isPrimaryNotesAtRoot } from '../lib/vault-layout' import { isPathInTemplateFolder, resolveTemplateFolder } from '@shared/template-folder' import { isPaletteNextKey, isPalettePreviousKey } from '../lib/palette-nav' import { isImeComposing } from '../lib/ime' @@ -167,6 +168,8 @@ export function VaultTextSearchPalette(): JSX.Element { // leave them out themselves (desktop 2.80, server 2.80); this catches an // older server and the renderer's own fallback. const vaultSettings = useStore((s) => s.vaultSettings) + const matchArea = (folder: VaultTextSearchMatch['folder']): string | null => + noteAreaLabel(folder, isPrimaryNotesAtRoot(vaultSettings), systemFolderLabels) const templateFolderRef = useRef(null) templateFolderRef.current = resolveTemplateFolder(vaultSettings) const resultRefs = useRef>([]) @@ -459,9 +462,11 @@ export function VaultTextSearchPalette(): JSX.Element { {renderHighlightedText(match.title, query)} - - {match.folder} - + {matchArea(match.folder) && ( + + {matchArea(match.folder)} + + )} L{match.lineNumber}
diff --git a/packages/app-core/src/lib/system-folder-labels.ts b/packages/app-core/src/lib/system-folder-labels.ts index 566f308b..e1299c6b 100644 --- a/packages/app-core/src/lib/system-folder-labels.ts +++ b/packages/app-core/src/lib/system-folder-labels.ts @@ -53,3 +53,17 @@ export function resolveSystemFolderLabels( tasks: getSystemFolderLabel('tasks', overrides) } } + +/** + * What a result row calls the system folder a note sits in: its label, custom ones + * included. Nothing for the notes of a vault that keeps them at its root, which are + * in no folder worth naming, whatever the bucket is called internally. + */ +export function noteAreaLabel( + folder: LabelKey, + primaryNotesAtRoot: boolean, + overrides?: SystemFolderLabels | null +): string | null { + if (folder === 'inbox' && primaryNotesAtRoot) return null + return getSystemFolderLabel(folder, overrides) +} From 04e7e10e2859c1cb41d8daedbbe3f0690f621021 Mon Sep 17 00:00:00 2001 From: Adib Hanna Date: Thu, 5 Nov 2026 10:39:09 -0600 Subject: [PATCH 08/27] Fix(connections): touch screens no longer show a "hover" chip or a preview A Connections card wears a "hover" chip, which on an iPad or an Android tablet names something that cannot be done. It now carries `zn-hover-only`, which hides it wherever nothing can hover. A finger on a card also fired `pointerenter` and opened the preview on its way to opening the note, so the row now ignores a touch pointer. The word was also the preview's own heading, reachable with `p` from a keyboard on those same devices. It now says Preview. The `p` hint keeps "hover preview", since it only shows at a keyboard. --- .../src/components/ConnectionsPanel.test.ts | 71 +++++++++++++++++++ .../src/components/ConnectionsPanel.tsx | 9 ++- .../src/components/NoteHoverPreview.tsx | 2 +- 3 files changed, 79 insertions(+), 3 deletions(-) diff --git a/packages/app-core/src/components/ConnectionsPanel.test.ts b/packages/app-core/src/components/ConnectionsPanel.test.ts index 57d42781..0b05cc47 100644 --- a/packages/app-core/src/components/ConnectionsPanel.test.ts +++ b/packages/app-core/src/components/ConnectionsPanel.test.ts @@ -106,3 +106,74 @@ describe('ConnectionsPanel: following a connection hands the keyboard to the edi expect(focusEditorNormalMode).toHaveBeenCalledTimes(1) }) }) + +describe('ConnectionsPanel: a row where nothing can hover', () => { + let host: HTMLDivElement + let root: Root + let originalState: ReturnType + + beforeEach(async () => { + originalState = useStore.getState() + host = document.createElement('div') + document.body.append(host) + root = createRoot(host) + ;(window as unknown as { zen: unknown }).zen = { + readNote: vi.fn(async (path: string) => ({ + ...meta(path.replace(/^inbox\/|\.md$/g, '')), + body: bodies[path] ?? '' + })) + } + const alpha = { ...meta('Alpha'), wikilinks: ['Beta'] } + useStore.setState({ + notes: [alpha, meta('Beta')], + selectedPath: alpha.path, + activeNote: { ...alpha, body: bodies[alpha.path] } + } as never) + await act(async () => + root.render( + createElement(ConnectionsPanel, { + note: { ...alpha, body: bodies[alpha.path] } as NoteContent + } as never) + ) + ) + }) + + afterEach(() => { + act(() => root.unmount()) + host.remove() + useStore.setState(originalState, true) + }) + + const row = (): HTMLElement => + host.querySelector('[data-connections-type="note"]')! + + it('marks the hover chip for the rule that hides it on touch', () => { + const chip = row().querySelector('[data-connection-hover-chip]') + expect(chip?.textContent).toBe('hover') + expect(chip?.classList.contains('zn-hover-only')).toBe(true) + }) + + it('opens no preview under a finger, and still does under a pointer', async () => { + const enter = (pointerType: string): void => { + const event = new MouseEvent('pointerover', { bubbles: true }) + Object.defineProperty(event, 'pointerType', { value: pointerType }) + row().dispatchEvent(event) + } + const preview = (): Element | null => document.querySelector('.note-hover-preview') + vi.useFakeTimers() + try { + await act(async () => { + enter('touch') + vi.advanceTimersByTime(1000) + }) + expect(preview()).toBeNull() + await act(async () => { + enter('mouse') + vi.advanceTimersByTime(1000) + }) + } finally { + vi.useRealTimers() + } + await vi.waitFor(() => expect(preview()).not.toBeNull()) + }) +}) diff --git a/packages/app-core/src/components/ConnectionsPanel.tsx b/packages/app-core/src/components/ConnectionsPanel.tsx index bf507950..c98a6840 100644 --- a/packages/app-core/src/components/ConnectionsPanel.tsx +++ b/packages/app-core/src/components/ConnectionsPanel.tsx @@ -488,7 +488,10 @@ function ConnectionRow({
+ {/* Says the row previews under a pointer, which a finger is not. */} diff --git a/packages/app-core/src/components/NoteHoverPreview.tsx b/packages/app-core/src/components/NoteHoverPreview.tsx index 98391908..57f9bd4e 100644 --- a/packages/app-core/src/components/NoteHoverPreview.tsx +++ b/packages/app-core/src/components/NoteHoverPreview.tsx @@ -159,7 +159,7 @@ export function NoteHoverPreview({
- Hover Preview + Preview
{note.title}
{note.path}
From e5a1944acf5af110880fe199cc23b6385cedf973 Mon Sep 17 00:00:00 2001 From: Adib Hanna Date: Thu, 5 Nov 2026 10:40:16 -0600 Subject: [PATCH 09/27] Fix(editor): a pane toolbar button goes dark as soon as its panel closes MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit After ⌘2 closed Connections, the panel was gone at once while its toolbar button stayed lit for another 150 ms: `transition-colors` faded the background out. A button that shows state should change with that state, so the pane toolbar's buttons no longer fade. --- .../components/EditorPane-toolbar-style.test.ts | 16 ++++++++++++++++ packages/app-core/src/components/EditorPane.tsx | 2 +- 2 files changed, 17 insertions(+), 1 deletion(-) create mode 100644 packages/app-core/src/components/EditorPane-toolbar-style.test.ts diff --git a/packages/app-core/src/components/EditorPane-toolbar-style.test.ts b/packages/app-core/src/components/EditorPane-toolbar-style.test.ts new file mode 100644 index 00000000..677ff4d1 --- /dev/null +++ b/packages/app-core/src/components/EditorPane-toolbar-style.test.ts @@ -0,0 +1,16 @@ +import { readFileSync } from 'node:fs' +import { describe, expect, it } from 'vitest' + +const source = readFileSync(new URL('./EditorPane.tsx', import.meta.url), 'utf8') + +describe('the pane toolbar buttons', () => { + it('drop their highlight at once when a panel closes', () => { + // With a color transition, closing Connections with ⌘2 took the panel away at + // once and left its button lit for another 150 ms. + const start = source.indexOf('function IconBtn(') + expect(start).toBeGreaterThan(-1) + const body = source.slice(start, source.indexOf('\n}\n', start)) + expect(body).toContain("'bg-paper-200 text-ink-900'") + expect(body).not.toContain('transition-colors') + }) +}) diff --git a/packages/app-core/src/components/EditorPane.tsx b/packages/app-core/src/components/EditorPane.tsx index d39a8dc3..ddef27a2 100644 --- a/packages/app-core/src/components/EditorPane.tsx +++ b/packages/app-core/src/components/EditorPane.tsx @@ -5578,7 +5578,7 @@ function IconBtn({ aria-label={title} aria-pressed={active} className={[ - 'group relative flex h-7 w-7 items-center justify-center rounded-md transition-colors', + 'group relative flex h-7 w-7 items-center justify-center rounded-md', disabled ? 'cursor-default text-ink-500/40' : active From 4ae92f3657322c093faaa7beb5a6f447649c1b9b Mon Sep 17 00:00:00 2001 From: Adib Hanna Date: Thu, 5 Nov 2026 10:40:16 -0600 Subject: [PATCH 10/27] Fix(connections): the hover preview no longer smears the text behind it The preview asked for `bg-paper-100/98` and `backdrop-blur-md`. 98 is not on the opacity scale, so Tailwind generated no background at all, and the blur drew the note behind it through the header and the body. The preview is a solid surface now, with no blur, which is what the class was trying to say. --- .../app-core/src/components/NoteHoverPreview.test.ts | 9 +++++++++ packages/app-core/src/components/NoteHoverPreview.tsx | 2 +- 2 files changed, 10 insertions(+), 1 deletion(-) diff --git a/packages/app-core/src/components/NoteHoverPreview.test.ts b/packages/app-core/src/components/NoteHoverPreview.test.ts index b64e75cb..0a4f5b36 100644 --- a/packages/app-core/src/components/NoteHoverPreview.test.ts +++ b/packages/app-core/src/components/NoteHoverPreview.test.ts @@ -70,6 +70,15 @@ describe('NoteHoverPreview', () => { expect(card.textContent).not.toContain('Loading preview') }) + it('stays opaque, so nothing behind it smears through the blur', async () => { + readNote.mockResolvedValue({ ...note, body: PLAN }) + const preview = await render() + // `bg-paper-100/98` looks opaque, but 98 is not on the opacity scale, so + // Tailwind drew no background at all and the blur showed the text behind it. + expect(preview.classList.contains('bg-paper-100')).toBe(true) + expect(preview.className).not.toContain('backdrop-blur') + }) + it('says it is loading while the note is read', async () => { readNote.mockReturnValue(new Promise(() => {})) const card = await render() diff --git a/packages/app-core/src/components/NoteHoverPreview.tsx b/packages/app-core/src/components/NoteHoverPreview.tsx index 57f9bd4e..d877c6ef 100644 --- a/packages/app-core/src/components/NoteHoverPreview.tsx +++ b/packages/app-core/src/components/NoteHoverPreview.tsx @@ -148,7 +148,7 @@ export function NoteHoverPreview({ return createPortal(
Date: Thu, 5 Nov 2026 10:40:16 -0600 Subject: [PATCH 11/27] Fix(lists): a note's preview line stops repeating its title MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Trash rows read "Old meeting notes" and then "Old meeting notes The agenda…". The excerpt is the opening of the body with its Markdown stripped, so a note that starts with a heading carries its title in it. Archive, Quick Notes, the note list, the Tags view and Connections cards all print it under a title too. Those rows now drop the title from the line they show. The excerpt itself is unchanged, since search reads it and the server and CLI build their own. --- .../app-core/src/components/ArchiveView.tsx | 3 +- .../src/components/ConnectionsPanel.tsx | 5 +- packages/app-core/src/components/NoteList.tsx | 3 +- .../src/components/QuickNotesView.tsx | 3 +- packages/app-core/src/components/TagView.tsx | 5 +- .../app-core/src/components/TrashView.test.ts | 50 +++++++++++++++++++ .../app-core/src/components/TrashView.tsx | 3 +- .../app-core/src/lib/note-excerpt.test.ts | 21 ++++++++ packages/app-core/src/lib/note-excerpt.ts | 14 ++++++ 9 files changed, 99 insertions(+), 8 deletions(-) create mode 100644 packages/app-core/src/components/TrashView.test.ts create mode 100644 packages/app-core/src/lib/note-excerpt.test.ts create mode 100644 packages/app-core/src/lib/note-excerpt.ts diff --git a/packages/app-core/src/components/ArchiveView.tsx b/packages/app-core/src/components/ArchiveView.tsx index 5764a573..f5e5ed44 100644 --- a/packages/app-core/src/components/ArchiveView.tsx +++ b/packages/app-core/src/components/ArchiveView.tsx @@ -17,6 +17,7 @@ import { } from '../lib/list-view-keys' import { resolveSystemFolderLabels } from '../lib/system-folder-labels' import { isAppOverlayOpen } from '../lib/overlay-open' +import { excerptBesideTitle } from '../lib/note-excerpt' // Every action this view answers, so a chord bound to one reaches it. const ARCHIVE_VIEW_ACTIONS: readonly KeymapId[] = [ @@ -475,7 +476,7 @@ export function ArchiveView(): JSX.Element {
{note.path}
- {note.excerpt || 'Empty note'} + {excerptBesideTitle(note.title, note.excerpt) || 'Empty note'}
diff --git a/packages/app-core/src/components/ConnectionsPanel.tsx b/packages/app-core/src/components/ConnectionsPanel.tsx index c98a6840..dd0e1cc1 100644 --- a/packages/app-core/src/components/ConnectionsPanel.tsx +++ b/packages/app-core/src/components/ConnectionsPanel.tsx @@ -17,6 +17,7 @@ import { promptApp } from '../lib/prompt-requests' import { focusEditorNormalMode } from '../lib/editor-focus' import { usePanelResize } from '../lib/use-panel-resize' import { PanelResizeHandle } from './PanelResizeHandle' +import { excerptBesideTitle } from '../lib/note-excerpt' interface MentionItem { note: NoteMeta @@ -315,7 +316,7 @@ export function ConnectionsPanel({ openConnection(item.path)} onHover={(rect) => { cancelScheduledClose() @@ -369,7 +370,7 @@ export function ConnectionsPanel({ // rather than replacing it, since a note can link the page // plainly and point at a block in the same breath. (#601) [ - item.excerpt, + excerptBesideTitle(item.title, item.excerpt), blocks.length ? `Points at ${blocks.map((id) => `^${id}`).join(', ')}` : '' diff --git a/packages/app-core/src/components/NoteList.tsx b/packages/app-core/src/components/NoteList.tsx index 7d0c0a49..92cbfb81 100644 --- a/packages/app-core/src/components/NoteList.tsx +++ b/packages/app-core/src/components/NoteList.tsx @@ -31,6 +31,7 @@ import { import { assetTabPath } from '../lib/asset-tabs' import { getScrollTopForVirtualIndex, getVirtualRange } from '../lib/virtual-list' import { chromeCarriesWindowDrag } from '../lib/window-chrome' +import { excerptBesideTitle } from '../lib/note-excerpt' function formatDate(ms: number): string { const d = new Date(ms) @@ -978,7 +979,7 @@ function NoteRow({ {formatDate(note.updatedAt)}
- {note.excerpt || 'Empty note'} + {excerptBesideTitle(note.title, note.excerpt) || 'Empty note'} ) diff --git a/packages/app-core/src/components/QuickNotesView.tsx b/packages/app-core/src/components/QuickNotesView.tsx index 40bd09fc..9e3b3f1c 100644 --- a/packages/app-core/src/components/QuickNotesView.tsx +++ b/packages/app-core/src/components/QuickNotesView.tsx @@ -12,6 +12,7 @@ import { } from '../lib/list-view-keys' import { getSystemFolderLabel } from '../lib/system-folder-labels' import { isAppOverlayOpen } from '../lib/overlay-open' +import { excerptBesideTitle } from '../lib/note-excerpt' // Every action this view answers, so a chord bound to one reaches it. const QUICK_NOTES_VIEW_ACTIONS: readonly KeymapId[] = [ @@ -285,7 +286,7 @@ export function QuickNotesView(): JSX.Element {
{note.path}
- {note.excerpt || 'Empty note'} + {excerptBesideTitle(note.title, note.excerpt) || 'Empty note'}
diff --git a/packages/app-core/src/components/TagView.tsx b/packages/app-core/src/components/TagView.tsx index c398df9e..4661ec8c 100644 --- a/packages/app-core/src/components/TagView.tsx +++ b/packages/app-core/src/components/TagView.tsx @@ -27,6 +27,7 @@ import { noteAreaLabel } from '../lib/system-folder-labels' import { isPrimaryNotesAtRoot, noteFolderSubpath } from '../lib/vault-layout' import { isImeComposing } from '../lib/ime' import { isAppOverlayOpen } from '../lib/overlay-open' +import { excerptBesideTitle } from '../lib/note-excerpt' // Every action this view answers, so a chord bound to one reaches it. const TAG_VIEW_ACTIONS: readonly KeymapId[] = [ @@ -744,9 +745,9 @@ export function TagView(): JSX.Element { )} {/* The tagged blocks listed below say more than the opening of the note, so the excerpt only shows without them. */} - {note.excerpt && row.blockCount === 0 && ( + {excerptBesideTitle(note.title, note.excerpt) && row.blockCount === 0 && (
- {note.excerpt} + {excerptBesideTitle(note.title, note.excerpt)}
)}
diff --git a/packages/app-core/src/components/TrashView.test.ts b/packages/app-core/src/components/TrashView.test.ts new file mode 100644 index 00000000..6a743b43 --- /dev/null +++ b/packages/app-core/src/components/TrashView.test.ts @@ -0,0 +1,50 @@ +// @vitest-environment jsdom +import { act, createElement } from 'react' +import { createRoot, type Root } from 'react-dom/client' +import { afterEach, beforeEach, describe, expect, it } from 'vitest' +import type { NoteMeta } from '@shared/ipc' +import { useStore } from '../store' +import { TrashView } from './TrashView' + +;(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true + +const old: NoteMeta = { + path: 'trash/Old meeting notes.md', + title: 'Old meeting notes', + folder: 'trash', + siblingOrder: 0, + createdAt: 0, + updatedAt: 0, + size: 0, + tags: [], + wikilinks: [], + hasAttachments: false, + assetEmbeds: [], + excerpt: 'Old meeting notes The agenda covered budgets.' +} + +describe('TrashView rows', () => { + let host: HTMLDivElement + let root: Root + let originalState: ReturnType + beforeEach(() => { + originalState = useStore.getState() + host = document.createElement('div') + document.body.append(host) + root = createRoot(host) + Element.prototype.scrollIntoView = () => {} + useStore.setState({ notes: [old] } as never) + }) + afterEach(() => { + act(() => root.unmount()) + host.remove() + useStore.setState(originalState, true) + }) + + it('do not repeat the title in the preview line', () => { + act(() => root.render(createElement(TrashView))) + const text = host.textContent ?? '' + expect(text).toContain('The agenda covered budgets.') + expect(text).not.toContain('Old meeting notes The agenda') + }) +}) diff --git a/packages/app-core/src/components/TrashView.tsx b/packages/app-core/src/components/TrashView.tsx index 5031deca..5f259a3b 100644 --- a/packages/app-core/src/components/TrashView.tsx +++ b/packages/app-core/src/components/TrashView.tsx @@ -14,6 +14,7 @@ import { import { getSystemFolderLabel } from '../lib/system-folder-labels' import { confirmApp } from '../lib/confirm-requests' import { isAppOverlayOpen } from '../lib/overlay-open' +import { excerptBesideTitle } from '../lib/note-excerpt' // Every action this view answers, so a chord bound to one reaches it. const TRASH_VIEW_ACTIONS: readonly KeymapId[] = [ @@ -384,7 +385,7 @@ export function TrashView(): JSX.Element {
{note.path}
- {note.excerpt || 'Empty note'} + {excerptBesideTitle(note.title, note.excerpt) || 'Empty note'}
diff --git a/packages/app-core/src/lib/note-excerpt.test.ts b/packages/app-core/src/lib/note-excerpt.test.ts new file mode 100644 index 00000000..4aba8f95 --- /dev/null +++ b/packages/app-core/src/lib/note-excerpt.test.ts @@ -0,0 +1,21 @@ +import { describe, expect, it } from 'vitest' +import { excerptBesideTitle } from './note-excerpt' + +describe('excerptBesideTitle', () => { + it('drops the title a heading put at the start', () => { + expect(excerptBesideTitle('Old meeting notes', 'Old meeting notes The agenda…')).toBe('The agenda…') + }) + + it('leaves nothing when the note is only its heading', () => { + expect(excerptBesideTitle('Plan', 'Plan')).toBe('') + }) + + it('leaves a word the title only starts', () => { + expect(excerptBesideTitle('Plan', 'Planning the week')).toBe('Planning the week') + }) + + it('leaves an excerpt that does not open with the title', () => { + expect(excerptBesideTitle('Plan', 'Before the Plan')).toBe('Before the Plan') + expect(excerptBesideTitle('', 'Something')).toBe('Something') + }) +}) diff --git a/packages/app-core/src/lib/note-excerpt.ts b/packages/app-core/src/lib/note-excerpt.ts new file mode 100644 index 00000000..5b0c6bad --- /dev/null +++ b/packages/app-core/src/lib/note-excerpt.ts @@ -0,0 +1,14 @@ +/** + * A note's excerpt, for a row that already prints its title. The excerpt is the + * opening of the body with its Markdown stripped, so a note that starts with a + * heading repeats the title in it: "Old meeting notes The agenda covered". Search + * keeps the whole excerpt; only what is read beside the title drops it. + */ +export function excerptBesideTitle(title: string, excerpt: string): string { + const name = title.trim() + const text = excerpt.trimStart() + if (!name || !text.startsWith(name)) return excerpt + const rest = text.slice(name.length) + // `Plan` must not eat the start of `Planning the week`. + return rest === '' || /^\s/.test(rest) ? rest.trimStart() : excerpt +} From 217b76e2dd28f0b436ef67afaa0bf5cd9f0f8352 Mon Sep 17 00:00:00 2001 From: Adib Hanna Date: Thu, 5 Nov 2026 10:44:17 -0600 Subject: [PATCH 12/27] Fix(tasks): the Tasks header fits a tablet, and its filter hint follows Vim mode MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit On an iPad the Tasks filter's placeholder was clipped to "/ to fc", and when "scanning…" appeared it pushed Refresh and Close off the edge: the header was one row that could only shrink the input. It now wraps, so the buttons move to a second row when they do not fit. The placeholder named `/` with Vim off, where that key does nothing. It now says just "Filter…" there, and the Tags view's does the same. --- packages/app-core/src/components/TagView.tsx | 2 +- .../src/components/TasksView-header.test.ts | 63 +++++++++++++++++++ .../app-core/src/components/TasksView.tsx | 13 ++-- 3 files changed, 73 insertions(+), 5 deletions(-) create mode 100644 packages/app-core/src/components/TasksView-header.test.ts diff --git a/packages/app-core/src/components/TagView.tsx b/packages/app-core/src/components/TagView.tsx index 4661ec8c..8988d3e0 100644 --- a/packages/app-core/src/components/TagView.tsx +++ b/packages/app-core/src/components/TagView.tsx @@ -510,7 +510,7 @@ export function TagView(): JSX.Element { setFilter(e.target.value)} onKeyDown={(e) => { diff --git a/packages/app-core/src/components/TasksView-header.test.ts b/packages/app-core/src/components/TasksView-header.test.ts new file mode 100644 index 00000000..c4659c53 --- /dev/null +++ b/packages/app-core/src/components/TasksView-header.test.ts @@ -0,0 +1,63 @@ +// @vitest-environment jsdom + +import { act, createElement } from 'react' +import { createRoot, type Root } from 'react-dom/client' +import { afterEach, describe, expect, it, vi } from 'vitest' +import { TASKS_TAB_PATH } from '@shared/tasks' +import { makeLeaf } from '../lib/pane-layout' +import { useStore } from '../store' +import { TasksView } from './TasksView' + +;(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true + +let host: HTMLDivElement +let root: Root +let originalState: ReturnType + +function mount(vimMode: boolean, tasksLoading = false): void { + originalState = useStore.getState() + Object.defineProperty(Element.prototype, 'scrollIntoView', { configurable: true, value: vi.fn() }) + const leaf = makeLeaf([TASKS_TAB_PATH], TASKS_TAB_PATH) + useStore.setState({ + vimMode, + paneLayout: leaf, + activePaneId: leaf.id, + vaultTasks: [], + tasksLoading, + tasksFilter: '', + refreshTasks: vi.fn(async () => {}) + }) + host = document.createElement('div') + document.body.append(host) + root = createRoot(host) + act(() => root.render(createElement(TasksView))) +} + +afterEach(() => { + act(() => root.unmount()) + host.remove() + useStore.setState(originalState, true) +}) + +const filter = (): HTMLInputElement => + host.querySelector('[data-tasks-header] input')! + +describe('the Tasks header', () => { + it('names the / key only in Vim mode, which is the only place it works', () => { + mount(false) + expect(filter().placeholder).toBe('Filter…') + act(() => root.unmount()) + host.remove() + useStore.setState(originalState, true) + mount(true) + expect(filter().placeholder).toBe('Filter… / to focus') + }) + + it('wraps rather than pushing its buttons off a narrow pane', () => { + mount(false, true) + const header = host.querySelector('[data-tasks-header]')! + expect(header.classList.contains('flex-wrap')).toBe(true) + expect(header.textContent).toContain('scanning') + expect(header.textContent).toContain('Refresh') + }) +}) diff --git a/packages/app-core/src/components/TasksView.tsx b/packages/app-core/src/components/TasksView.tsx index 356c489c..a0740dbf 100644 --- a/packages/app-core/src/components/TasksView.tsx +++ b/packages/app-core/src/components/TasksView.tsx @@ -1010,7 +1010,12 @@ export function TasksView(): JSX.Element { > {/* Nothing here wraps inside itself: on a narrow pane the filter box gives up its width first. */} -
+ {/* Wraps instead of squeezing: on a tablet the filter was clipped to "/ to fo", + and "scanning…" appearing pushed Refresh and Close off the edge. */} +

Tasks

@@ -1018,7 +1023,7 @@ export function TasksView(): JSX.Element { ? `${filteredTasks.length} of ${shownTasks.length}` : `${shownTasks.length} total`} - {loading && scanning…} + {loading && scanning…}
{VIEW_BUTTONS.map(({ id, label, shortcut, Icon }) => { @@ -1043,14 +1048,14 @@ export function TasksView(): JSX.Element { })}
-
+
{/* Mounted in every sub-view: the same query narrows the list, the calendar, and the Kanban board, so switching views keeps the focus you typed. (#583) */} setFilter(e.target.value)} onKeyDown={(e) => { From b71a80b5c03fdaafbb41ccaeee443b5a345372ea Mon Sep 17 00:00:00 2001 From: Adib Hanna Date: Thu, 5 Nov 2026 10:44:17 -0600 Subject: [PATCH 13/27] Fix(cloud): the footer can cancel a sign-in waiting on the browser MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit While Cloud was connecting, the footer showed "Connecting to Cloud…" with no action: `showAction` left that phase out, so the only Cancel was in Settings → Cloud. On a phone, where that row is the way into Cloud, a browser that never came back left nothing to press. The action now reads Cancel during a sign-in and does what Settings does, through `logoutCloudAccount`, and the footer goes back to Connect. It keeps `data-cloud-sync-action`, so the shells' 44 px rule applies, and desktop gets it too. The iPhone's footer only draws in the attention and error phases, so that shell has to add `connecting` for this to show there. --- .../app-core/src/components/StatusBar.test.ts | 50 +++++++++++++++++++ .../app-core/src/components/StatusBar.tsx | 19 +++++-- packages/app-core/src/lib/cloud-auto-sync.ts | 14 ++++++ 3 files changed, 78 insertions(+), 5 deletions(-) diff --git a/packages/app-core/src/components/StatusBar.test.ts b/packages/app-core/src/components/StatusBar.test.ts index fd9131cf..f49aab83 100644 --- a/packages/app-core/src/components/StatusBar.test.ts +++ b/packages/app-core/src/components/StatusBar.test.ts @@ -20,6 +20,7 @@ const bridgeMocks = vi.hoisted(() => ({ saveCloudConflictDraft: vi.fn(), resolveCloudConflict: vi.fn(), syncCloudVault: vi.fn(), + logoutCloudAccount: vi.fn(async () => ({ state: "disconnected" })), })); vi.mock("@zennotes/bridge-contract/bridge", () => ({ @@ -102,6 +103,55 @@ describe("cloud sync status time", () => { host.remove(); }); + it("offers a way out of a sign-in waiting on the browser", async () => { + useCloudSyncStatusStore.setState({ + phase: "connecting", + vaultName: null, + lastSyncedAt: null, + error: null, + }); + bridgeMocks.logoutCloudAccount.mockClear(); + const host = document.createElement("div"); + document.body.append(host); + const root = createRoot(host); + + act(() => root.render(createElement(StatusBar, { note: null }))); + + const button = host.querySelector("[data-cloud-sync-action]"); + expect(button?.textContent).toBe("Cancel"); + expect(button?.getAttribute("aria-label")).toBe("Cancel sign-in"); + expect(host.textContent).toContain("Connecting to Cloud"); + await act(async () => button?.click()); + expect(bridgeMocks.logoutCloudAccount).toHaveBeenCalledTimes(1); + expect(useCloudSyncStatusStore.getState().phase).toBe("disconnected"); + expect(useCloudSyncStatusStore.getState().error).toBeNull(); + expect( + host.querySelector("[data-cloud-sync-action]")?.textContent, + ).toBe("Connect"); + + act(() => root.unmount()); + host.remove(); + }); + + it("still offers nothing while a sync runs", () => { + useCloudSyncStatusStore.setState({ + phase: "syncing", + vaultName: "Notes", + lastSyncedAt: null, + error: null, + }); + const host = document.createElement("div"); + document.body.append(host); + const root = createRoot(host); + + act(() => root.render(createElement(StatusBar, { note: null }))); + + expect(host.querySelector("[data-cloud-sync-action]")).toBeNull(); + + act(() => root.unmount()); + host.remove(); + }); + it("names a file-size stop on the status row, where a phone cannot hover for the reason", () => { useCloudSyncStatusStore.setState({ phase: "attention", diff --git a/packages/app-core/src/components/StatusBar.tsx b/packages/app-core/src/components/StatusBar.tsx index 2506b24c..16dc2f23 100644 --- a/packages/app-core/src/components/StatusBar.tsx +++ b/packages/app-core/src/components/StatusBar.tsx @@ -10,6 +10,7 @@ import { cloudSyncShownPhase, cloudVaultRemovalLabel, cloudVaultRemovalMessage, + cancelCloudSignInFromStatusBar, connectCloudAccountFromStatusBar, formatRelativeSyncTime, openCloudConflictReview, @@ -212,8 +213,12 @@ function CloudSyncStatus({ // Files waiting on a decision outrank every other action: the queue stays // one click away even while the next run is in flight, because those runs // cannot finish the waiting file anyway. + // The browser may never come back, and a phone has no other way out from here. + const cancelsSignIn = phase === "connecting" && !hasResolvableConflict; const actionLabel = - phase === "disconnected" + cancelsSignIn + ? "Cancel" + : phase === "disconnected" ? error && errorKind !== "signed-out" ? "Retry" : "Connect" @@ -228,8 +233,8 @@ function CloudSyncStatus({ : phase === "error" ? "Retry" : "Sync now"; - const showAction = - hasResolvableConflict || (phase !== "syncing" && phase !== "connecting"); + const showAction = hasResolvableConflict || phase !== "syncing"; + const actionTitle = cancelsSignIn ? "Cancel sign-in" : title; const openCloudSettings = (): void => { requestSettingsTarget("cloud"); @@ -237,6 +242,10 @@ function CloudSyncStatus({ }; const runCloudAction = (): void => { + if (cancelsSignIn) { + void cancelCloudSignInFromStatusBar().catch(() => undefined); + return; + } if (phase === "disconnected") { void connectCloudAccountFromStatusBar().catch(() => undefined); return; @@ -299,8 +308,8 @@ function CloudSyncStatus({
- } text="Recent" /> + {recent.length > 0 && ( + } text="Recent" /> + )} {recent.length > 0 ? (
    {recent.map((note) => ( From c362271993e38992997f1487bcd7f45c6deb1323 Mon Sep 17 00:00:00 2001 From: Adib Hanna Date: Thu, 5 Nov 2026 10:47:22 -0600 Subject: [PATCH 15/27] Fix(sidebar): only the selected row is lit on a tablet, and after Duplicate anywhere Two extra highlights, both on rows nobody had picked. On a touch device the sidebar drew the keyboard's cursor. Nothing moves that cursor without a keyboard, so it stayed where a tap or a render left it: the Inbox wore its ring after launch, and after a vault filled, Archive stayed tinted until another row was tapped, holding `data-sidebar-idx=3`. Lists, boards and grids already leave the cursor undrawn on such a device through `useKeyboardCursor`, and the sidebar now does the same. Only the drawing changes: the index and its anchoring stay, and a focused sidebar no longer strips the active row's tint there, since nothing else is marking it. Opening a menu on a row selects that row, which stayed selected after the menu closed. After Duplicate, from a long press or a right-click, the source stayed lit beside the copy it opened. A selection made only for the menu now ends with the menu. One the person made with Shift or Cmd stays. --- .../Sidebar.touch-highlight.test.ts | 142 ++++++++++++++++++ packages/app-core/src/components/Sidebar.tsx | 72 ++++++--- 2 files changed, 192 insertions(+), 22 deletions(-) create mode 100644 packages/app-core/src/components/Sidebar.touch-highlight.test.ts diff --git a/packages/app-core/src/components/Sidebar.touch-highlight.test.ts b/packages/app-core/src/components/Sidebar.touch-highlight.test.ts new file mode 100644 index 00000000..f069e312 --- /dev/null +++ b/packages/app-core/src/components/Sidebar.touch-highlight.test.ts @@ -0,0 +1,142 @@ +// @vitest-environment jsdom + +import { act, createElement } from 'react' +import { createRoot, type Root } from 'react-dom/client' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import type { NoteMeta } from '@shared/ipc' +import { useStore } from '../store' +import { Sidebar } from './Sidebar' + +;(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true + +function note(title: string): NoteMeta { + return { + path: `inbox/${title}.md`, + title, + folder: 'inbox', + siblingOrder: 0, + createdAt: 0, + updatedAt: 0, + size: 0, + tags: [], + wikilinks: [], + hasAttachments: false, + assetEmbeds: [], + excerpt: '' + } +} + +let coarse = false +let host: HTMLDivElement +let root: Root +let originalState: ReturnType + +beforeEach(() => { + originalState = useStore.getState() + Object.defineProperty(window, 'matchMedia', { + configurable: true, + value: (query: string) => ({ + matches: coarse && query === '(pointer: coarse)', + media: query, + addEventListener: () => {}, + removeEventListener: () => {}, + addListener: () => {}, + removeListener: () => {} + }) + }) + Object.defineProperty(Element.prototype, 'scrollIntoView', { configurable: true, value: vi.fn() }) + vi.stubGlobal('ResizeObserver', class { observe() {} disconnect() {} unobserve() {} }) + const known: Record = { + platformSync: () => 'darwin', + getAppInfo: () => ({ runtime: 'web', hostKind: 'ios' }), + getCapabilities: () => ({}), + duplicateNote: vi.fn(async () => note('One copy')) + } + ;(window as unknown as { zen: unknown }).zen = new Proxy(known, { + get: (target, name: string) => + target[name] ?? + (name.startsWith('on') ? () => () => {} : async () => null) + }) + useStore.setState({ + vault: { root: '/v', name: 'v' }, + notes: [note('One'), note('Two')], + collapsedFolders: [], + sidebarOpen: true, + selectedPath: null, + focusedPanel: 'sidebar', + sidebarCursorIndex: 3, + refreshNotes: vi.fn(async () => {}), + selectNote: vi.fn(async () => {}) + } as never) + host = document.createElement('div') + document.body.append(host) + root = createRoot(host) +}) + +afterEach(() => { + act(() => root.unmount()) + host.remove() + document.body.innerHTML = '' + useStore.setState(originalState, true) + vi.unstubAllGlobals() + coarse = false +}) + +const cursorRows = (): Element[] => [ + ...host.querySelectorAll('.vim-cursor, .vim-cursor-on-active, .vim-cursor-on-selected') +] + +const noteRow = (title: string): HTMLElement => + host.querySelector(`[data-sidebar-path="inbox/${title}.md"]`)! + +async function openMenuOn(row: HTMLElement): Promise { + await act(async () => { + row.dispatchEvent( + new MouseEvent('contextmenu', { bubbles: true, cancelable: true, clientX: 10, clientY: 10 }) + ) + }) +} + +const menuItem = (label: string): HTMLButtonElement => + [...document.querySelectorAll('[data-ctx-menu] button')].find((button) => + button.textContent?.trim().startsWith(label) + )! + +describe('Sidebar highlights', () => { + it('draws the keyboard cursor where a pointer is fine', async () => { + await act(async () => root.render(createElement(Sidebar))) + expect(cursorRows()).toHaveLength(1) + }) + + it('draws no keyboard cursor on a touch device, whatever the index says', async () => { + coarse = true + await act(async () => root.render(createElement(Sidebar))) + expect(cursorRows()).toHaveLength(0) + }) + + it('takes the highlight off a row when its menu closes', async () => { + await act(async () => root.render(createElement(Sidebar))) + const row = noteRow('Two') + await openMenuOn(row) + const selected = row.getAttribute('class') + expect(selected).toContain('bg-accent/[0.09]') + await act(async () => menuItem('Duplicate').click()) + expect(noteRow('Two').getAttribute('class')).not.toContain('bg-accent/[0.09]') + }) + + it('keeps a selection the person made when a menu closes', async () => { + await act(async () => root.render(createElement(Sidebar))) + const click = (row: HTMLElement, init: MouseEventInit): Promise => + act(async () => { + row.dispatchEvent(new MouseEvent('click', { bubbles: true, cancelable: true, ...init })) + }) + await click(noteRow('One'), { metaKey: true }) + await click(noteRow('Two'), { metaKey: true }) + await openMenuOn(noteRow('Two')) + await act(async () => { + document.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape', bubbles: true })) + }) + expect(noteRow('One').getAttribute('class')).toContain('bg-accent/[0.09]') + expect(noteRow('Two').getAttribute('class')).toContain('bg-accent/[0.09]') + }) +}) diff --git a/packages/app-core/src/components/Sidebar.tsx b/packages/app-core/src/components/Sidebar.tsx index 9a0fda31..8b8435b6 100644 --- a/packages/app-core/src/components/Sidebar.tsx +++ b/packages/app-core/src/components/Sidebar.tsx @@ -145,6 +145,7 @@ import { } from "../lib/sidebar-cursor"; import { buildVaultSwitcherEntries } from "../lib/vault-switcher"; import { canOpenVaultFolders, fileManagerName, openVaultFolder } from "../lib/vault-folder"; +import { useKeyboardCursor } from "../lib/keyboard-cursor"; import { formatKeyToken } from "../lib/keymaps"; import { registerSidebarActionHost, @@ -729,6 +730,7 @@ export function Sidebar(): JSX.Element { selectedSidebarItems.filter((item) => item.kind === "folder").length; const selectionAnchorKeyRef = useRef(selectionAnchorKey); const selectedSidebarKeysRef = useRef(selectedSidebarKeys); + const menuOnlySelectionRef = useRef(null); const selectedSidebarItemsRef = useRef(selectedSidebarItems); const selectedSidebarCountRef = useRef(selectedSidebarCount); const sidebarScrollRef = useRef(null); @@ -914,6 +916,9 @@ export function Sidebar(): JSX.Element { const prepareContextSelection = useCallback( (item: SidebarSelectionItem): void => { const key = selectionKeyForItem(item); + const inSelection = + selectedSidebarKeysRef.current.has(key) && selectedSidebarKeysRef.current.size > 1; + menuOnlySelectionRef.current = inSelection ? null : key; setSelectedSidebarKeys((prev) => { if (prev.has(key) && prev.size > 1) return prev; return new Set([key]); @@ -923,6 +928,18 @@ export function Sidebar(): JSX.Element { [], ); + // A row a menu was opened on is highlighted while that menu is up, and the menu + // was the only reason. Left on, Duplicate showed two lit rows: the source, and the + // copy it opened. A selection the person made stays, whatever a menu did. + const endMenuOnlySelection = useCallback((): void => { + const key = menuOnlySelectionRef.current; + menuOnlySelectionRef.current = null; + if (!key) return; + setSelectedSidebarKeys((prev) => + prev.size === 1 && prev.has(key) ? new Set() : prev, + ); + }, []); + const dragPayloadForItem = useCallback( (item: SidebarSelectionItem): DragPayload => { const key = selectionKeyForItem(item); @@ -2923,7 +2940,12 @@ export function Sidebar(): JSX.Element { // New on every render, so the tree components below can tell "Sidebar // rendered me" from "I re-rendered alone" (see useStableSidebarIdxBase). const idxPass: SidebarIdxPass = {}; - const vimCursor = isSidebarFocused ? sidebarCursorIndex : -1; + // Whether the keyboard's cursor is drawn at all. Where there is no keyboard to + // move it, a tap or a filling vault left it on a row as a second highlight: the + // Inbox wore its ring after launch, and Archive stayed tinted after a sync. + const keyboardCursor = useKeyboardCursor(); + const cursorDrawn = isSidebarFocused && keyboardCursor; + const vimCursor = cursorDrawn ? sidebarCursorIndex : -1; const vaultHeaderIdx = canSwitchVaults ? idxCounter.current.value++ : -1; const vaultHeaderVimHighlight = vimCursor === vaultHeaderIdx; // VimNav clamps cursor position via Math.min/Math.max on each @@ -3449,7 +3471,7 @@ export function Sidebar(): JSX.Element { }} sidebarIdx={idx} vimHighlight={vimHighlight} - sidebarFocused={isSidebarFocused} + sidebarFocused={cursorDrawn} dataAttrs={{ "data-sidebar-type": "note", "data-sidebar-path": item.path, @@ -3489,7 +3511,7 @@ export function Sidebar(): JSX.Element { } sidebarIdx={idx} vimHighlight={vimHighlight} - sidebarFocused={isSidebarFocused} + sidebarFocused={cursorDrawn} dataAttrs={{ "data-sidebar-type": "folder", "data-sidebar-folder": item.folder, @@ -3509,7 +3531,7 @@ export function Sidebar(): JSX.Element { label={folderLabels.tasks} sidebarIdx={idxCounter.current.value++} vimHighlight={vimCursor === idxCounter.current.value - 1} - sidebarFocused={isSidebarFocused} + sidebarFocused={cursorDrawn} /> {/* Hidden when the feature is off. Because the row is skipped before @@ -3524,7 +3546,7 @@ export function Sidebar(): JSX.Element { sidebarType="workflows" sidebarIdx={idxCounter.current.value++} vimHighlight={vimCursor === idxCounter.current.value - 1} - sidebarFocused={isSidebarFocused} + sidebarFocused={cursorDrawn} /> )} @@ -3538,7 +3560,7 @@ export function Sidebar(): JSX.Element { sidebarType="workflows" sidebarIdx={idxCounter.current.value++} vimHighlight={vimCursor === idxCounter.current.value - 1} - sidebarFocused={isSidebarFocused} + sidebarFocused={cursorDrawn} /> )} @@ -3570,7 +3592,7 @@ export function Sidebar(): JSX.Element { idxCounter={idxCounter.current} idxPass={idxPass} vimCursor={vimCursor} - sidebarFocused={isSidebarFocused} + sidebarFocused={cursorDrawn} groupByKind={groupByKind} showSidebarChevrons={showSidebarChevrons} headerAction={ @@ -3604,7 +3626,7 @@ export function Sidebar(): JSX.Element { isFolderActive={isFolderActive} selectedPath={selectedPath} selectedKeys={selectedSidebarKeys} - sidebarFocused={isSidebarFocused} + sidebarFocused={cursorDrawn} showSidebarChevrons={showSidebarChevrons} onSelectNote={handleSelectNote} onSelectItem={handleSidebarItemSelect} @@ -3653,7 +3675,7 @@ export function Sidebar(): JSX.Element { idxCounter={idxCounter.current} idxPass={idxPass} vimCursor={vimCursor} - sidebarFocused={isSidebarFocused} + sidebarFocused={cursorDrawn} groupByKind={groupByKind} showSidebarChevrons={showSidebarChevrons} /> @@ -3687,7 +3709,7 @@ export function Sidebar(): JSX.Element { idxCounter={idxCounter.current} idxPass={idxPass} vimCursor={vimCursor} - sidebarFocused={isSidebarFocused} + sidebarFocused={cursorDrawn} groupByKind={groupByKind} showSidebarChevrons={showSidebarChevrons} /> @@ -3794,7 +3816,7 @@ export function Sidebar(): JSX.Element { active ? isVimHighlight ? "vim-cursor-on-active bg-paper-300/70 text-ink-900 font-medium" - : isSidebarFocused + : cursorDrawn ? "bg-accent/15 text-accent font-medium" : "bg-paper-300/70 text-ink-900 font-medium" : isVimHighlight @@ -3811,7 +3833,7 @@ export function Sidebar(): JSX.Element { openFolderMenu(e, "archive", "")} sidebarIdx={idxCounter.current.value++} vimHighlight={vimCursor === idxCounter.current.value - 1} - sidebarFocused={isSidebarFocused} + sidebarFocused={cursorDrawn} sidebarType="archive" /> openFolderMenu(e, "trash", "")} sidebarIdx={idxCounter.current.value++} vimHighlight={vimCursor === idxCounter.current.value - 1} - sidebarFocused={isSidebarFocused} + sidebarFocused={cursorDrawn} sidebarType="trash" />
@@ -3951,7 +3973,7 @@ export function Sidebar(): JSX.Element { onClick={() => void revealAssetsDir()} sidebarIdx={idxCounter.current.value++} vimHighlight={vimCursor === idxCounter.current.value - 1} - sidebarFocused={isSidebarFocused} + sidebarFocused={cursorDrawn} sidebarData={{ type: "files" }} /> )} @@ -3964,7 +3986,7 @@ export function Sidebar(): JSX.Element { onClick={() => void openHelpView()} sidebarIdx={idxCounter.current.value++} vimHighlight={vimCursor === idxCounter.current.value - 1} - sidebarFocused={isSidebarFocused} + sidebarFocused={cursorDrawn} sidebarData={{ type: "help" }} /> setSettingsOpen(true)} sidebarIdx={idxCounter.current.value++} vimHighlight={vimCursor === idxCounter.current.value - 1} - sidebarFocused={isSidebarFocused} + sidebarFocused={cursorDrawn} sidebarData={{ type: "settings" }} />
@@ -3998,7 +4020,10 @@ export function Sidebar(): JSX.Element { x={folderMenu.x} y={folderMenu.y} items={folderMenuItems} - onClose={() => setFolderMenu(null)} + onClose={() => { + setFolderMenu(null); + endMenuOnlySelection(); + }} /> )} {assetsRowMenu && ( @@ -4051,7 +4076,10 @@ export function Sidebar(): JSX.Element { x={noteMenu.x} y={noteMenu.y} items={noteMenuItems} - onClose={() => setNoteMenu(null)} + onClose={() => { + setNoteMenu(null); + endMenuOnlySelection(); + }} /> )} {assetMenu && ( From 936bc37888da67c17ded766e0abc1ea259b3761d Mon Sep 17 00:00:00 2001 From: Adib Hanna Date: Thu, 5 Nov 2026 10:51:36 -0600 Subject: [PATCH 16/27] Fix(tablet): the title row clears the status bar, and tooltips name the right keys MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit On an Android tablet the title row sat under the status bar, since the shell only insets the page on a phone. The app shell now keeps below `safe-area-inset-top` wherever the page draws under a bar. That is 0 on desktop, and a phone shell's own padding already says the same thing. The tooltips said ⌘1 and ⇧⌘E on Android, because they were written out by hand, and so did the same tooltips on Windows and Linux. They now read the keymap, so a phone or PC reads Ctrl+1, a Mac and an iPad read ⌘1, a rebound action names its new key, and an unbound one names none. The same goes for the other keys spelled out in the sidebar's Search and Quick Notes, Home, the empty pane, the comment box and the onboarding tips. The rest of the app's written-out keys are in the manual, which translates them. --- .../app-core/src/components/CommentsPanel.tsx | 16 ++++--- .../app-core/src/components/EditorPane.tsx | 44 +++++++++++++++---- packages/app-core/src/components/HomeView.tsx | 7 ++- .../src/components/OnboardingWizard.tsx | 11 ++--- packages/app-core/src/components/Sidebar.tsx | 27 +++++++++--- .../app-core/src/lib/app-shell-inset.test.ts | 14 ++++++ .../src/lib/shortcut-labels-source.test.ts | 19 ++++++++ .../app-core/src/lib/shortcut-labels.test.ts | 37 ++++++++++++++++ .../app-core/src/lib/sidebar-restore.test.ts | 2 +- packages/app-core/src/styles/index.css | 3 ++ 10 files changed, 152 insertions(+), 28 deletions(-) create mode 100644 packages/app-core/src/lib/app-shell-inset.test.ts create mode 100644 packages/app-core/src/lib/shortcut-labels-source.test.ts create mode 100644 packages/app-core/src/lib/shortcut-labels.test.ts diff --git a/packages/app-core/src/components/CommentsPanel.tsx b/packages/app-core/src/components/CommentsPanel.tsx index 8ea90033..7b807368 100644 --- a/packages/app-core/src/components/CommentsPanel.tsx +++ b/packages/app-core/src/components/CommentsPanel.tsx @@ -10,6 +10,7 @@ import { import type { NoteComment, NoteContent } from '@shared/ipc' import { useStore } from '../store' import { commentQuote } from '../lib/comments' +import { formatKeyToken } from '../lib/keymaps' import { threadNoteComments, type NoteCommentThread } from '@shared/note-comments' import { renderMarkdown } from '../lib/markdown' import { usePanelResize } from '../lib/use-panel-resize' @@ -49,6 +50,9 @@ const dateFormatter = new Intl.DateTimeFormat(undefined, { }) const EMPTY_COMMENTS: NoteComment[] = [] +/** The comment box's submit key, which its keydown reads as Cmd or Ctrl. */ +const SUBMIT_KEY = (): string => formatKeyToken('Mod+Enter') + function cssEscape(value: string): string { if (typeof CSS !== 'undefined' && typeof CSS.escape === 'function') return CSS.escape(value) return value.replace(/["\\]/g, '\\$&') @@ -322,11 +326,11 @@ export function CommentsPanel({ disabled={!body.trim()} onClick={() => void submit()} aria-keyshortcuts="Meta+Enter Control+Enter" - title="Comment (⌘↵)" + title={`Comment (${SUBMIT_KEY()})`} className="flex items-center gap-1.5 rounded-md bg-accent px-3 py-1.5 text-xs font-medium text-white transition-colors hover:bg-accent/90 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent/45 disabled:cursor-default disabled:bg-paper-300 disabled:text-ink-500" > Comment - ⌘↵ + {SUBMIT_KEY()}
@@ -595,11 +599,11 @@ function CommentCard({ onSave() }} aria-keyshortcuts="Meta+Enter Control+Enter" - title="Save (⌘↵)" + title={`Save (${SUBMIT_KEY()})`} className="flex items-center gap-1.5 rounded-md bg-accent px-3 py-1.5 text-xs font-medium text-white transition-colors hover:bg-accent/90 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent/45 disabled:cursor-default disabled:bg-paper-300 disabled:text-ink-500" > Save - ⌘↵ + {SUBMIT_KEY()} @@ -672,11 +676,11 @@ function CommentCard({ event.stopPropagation() onSubmitReply() }} - title="Reply (⌘↵)" + title={`Reply (${SUBMIT_KEY()})`} className="flex items-center gap-1.5 rounded-md bg-accent px-3 py-1.5 text-xs font-medium text-white transition-colors hover:bg-accent/90 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent/45 disabled:cursor-default disabled:bg-paper-300 disabled:text-ink-500" > Reply - ⌘↵ + {SUBMIT_KEY()} diff --git a/packages/app-core/src/components/EditorPane.tsx b/packages/app-core/src/components/EditorPane.tsx index ddef27a2..4042aa65 100644 --- a/packages/app-core/src/components/EditorPane.tsx +++ b/packages/app-core/src/components/EditorPane.tsx @@ -4294,7 +4294,13 @@ export function EditorPane({ pane }: { pane: PaneLeaf }): JSX.Element { > - void exportActiveNotePdf()}> + void exportActiveNotePdf()} + > @@ -4728,7 +4734,10 @@ export function EditorPane({ pane }: { pane: PaneLeaf }): JSX.Element {
{!sidebarOpen && ( @@ -4789,7 +4798,14 @@ export function EditorPane({ pane }: { pane: PaneLeaf }): JSX.Element { {sidebarSlot === 'pane-strip' && (
- +
@@ -4808,7 +4824,14 @@ export function EditorPane({ pane }: { pane: PaneLeaf }): JSX.Element {
{sidebarSlot === 'note-header' && (
- +
@@ -5462,6 +5485,9 @@ function EmptyPaneState({ zenMode: boolean onShowSidebar: () => void }): JSX.Element { + const overrides = useStore((s) => s.keymapOverrides) + const zenKey = getKeymapDisplay(overrides, 'global.toggleZenMode') + const sidebarKey = getKeymapDisplay(overrides, 'global.toggleSidebar') return (
@@ -5473,7 +5499,7 @@ function EmptyPaneState({

{zenMode - ? 'Leave Zen mode with ⌘. to bring the rest of the app chrome back.' + ? `Leave Zen mode${zenKey ? ` with ${zenKey}` : ''} to bring the rest of the app chrome back.` : sidebarOpen ? 'Select a note from the sidebar, or create a new one to start writing.' : 'Bring the sidebar back to browse your notes, folders, and shortcuts.'} @@ -5487,9 +5513,11 @@ function EmptyPaneState({ > Show sidebar - - ⌘1 - + {sidebarKey && ( + + {sidebarKey} + + )}

)} diff --git a/packages/app-core/src/components/HomeView.tsx b/packages/app-core/src/components/HomeView.tsx index 613a2b5a..3bd2de32 100644 --- a/packages/app-core/src/components/HomeView.tsx +++ b/packages/app-core/src/components/HomeView.tsx @@ -1,3 +1,4 @@ +import { getKeymapDisplay } from '../lib/keymaps' import { useCallback, useEffect, useMemo, useRef } from 'react' import type { NoteMeta } from '@shared/ipc' import { filterTasksForDisplay, inferDailyTaskDueDates, type VaultTask } from '@shared/tasks' @@ -74,6 +75,10 @@ export function HomeView({ }): JSX.Element { const notes = useStore((s) => s.notes) const folders = useStore((s) => s.folders) + const sidebarKey = getKeymapDisplay( + useStore((s) => s.keymapOverrides), + 'global.toggleSidebar' + ) const vaultTasks = useStore((s) => s.vaultTasks) const showArchivedTasks = useStore((s) => s.showArchivedTasks) const hideEmptyTasks = useStore((s) => s.hideEmptyTasks) @@ -301,7 +306,7 @@ export function HomeView({ > Sidebar - ⌘1 + {sidebarKey && {sidebarKey}} )} diff --git a/packages/app-core/src/components/OnboardingWizard.tsx b/packages/app-core/src/components/OnboardingWizard.tsx index 8e2c7157..828180a0 100644 --- a/packages/app-core/src/components/OnboardingWizard.tsx +++ b/packages/app-core/src/components/OnboardingWizard.tsx @@ -1,3 +1,4 @@ +import { formatKeyToken } from '../lib/keymaps' import { useEffect, useMemo, useRef, useState } from 'react' import { useStore } from '../store' import { resolveAuto, THEMES, type ThemeFamily, type ThemeMode } from '../lib/themes' @@ -1042,11 +1043,11 @@ function DoneStep({ }): JSX.Element { const tips = useMemo( () => [ - { keys: '⌘P', label: 'Find a note' }, - { keys: '⇧⌘P', label: 'Command palette' }, - { keys: '⇧⌘N', label: 'New quick note' }, - { keys: '⌘.', label: 'Toggle zen mode' }, - { keys: '⌘,', label: 'Settings' } + { keys: formatKeyToken('Mod+P'), label: 'Find a note' }, + { keys: formatKeyToken('Shift+Mod+P'), label: 'Command palette' }, + { keys: formatKeyToken('Shift+Mod+N'), label: 'New quick note' }, + { keys: formatKeyToken('Mod+.'), label: 'Toggle zen mode' }, + { keys: formatKeyToken('Mod+,'), label: 'Settings' } ], [] ) diff --git a/packages/app-core/src/components/Sidebar.tsx b/packages/app-core/src/components/Sidebar.tsx index 8b8435b6..63a01d00 100644 --- a/packages/app-core/src/components/Sidebar.tsx +++ b/packages/app-core/src/components/Sidebar.tsx @@ -146,7 +146,7 @@ import { import { buildVaultSwitcherEntries } from "../lib/vault-switcher"; import { canOpenVaultFolders, fileManagerName, openVaultFolder } from "../lib/vault-folder"; import { useKeyboardCursor } from "../lib/keyboard-cursor"; -import { formatKeyToken } from "../lib/keymaps"; +import { formatKeyToken, getKeymapDisplay, labelWithShortcut } from "../lib/keymaps"; import { registerSidebarActionHost, type SidebarSelectionSnapshot, @@ -482,6 +482,8 @@ export function Sidebar(): JSX.Element { const hasAssetsDir = useStore((s) => s.hasAssetsDir); const focusedPanel = useStore((s) => s.focusedPanel); const vimMode = useStore((s) => s.vimMode); + const keymapOverrides = useStore((s) => s.keymapOverrides); + const searchKey = getKeymapDisplay(keymapOverrides, "global.searchNotes"); const sidebarCursorIndex = useStore((s) => s.sidebarCursorIndex); const activeNote = useStore((s) => s.activeNote); const activeDirty = useStore((s) => s.activeDirty); @@ -3269,7 +3271,13 @@ export function Sidebar(): JSX.Element { > - +
@@ -3282,13 +3290,15 @@ export function Sidebar(): JSX.Element {
{ e.stopPropagation(); diff --git a/packages/app-core/src/lib/app-shell-inset.test.ts b/packages/app-core/src/lib/app-shell-inset.test.ts new file mode 100644 index 00000000..cd222c22 --- /dev/null +++ b/packages/app-core/src/lib/app-shell-inset.test.ts @@ -0,0 +1,14 @@ +import { readFileSync } from 'node:fs' +import { describe, expect, it } from 'vitest' + +const styles = readFileSync(new URL('../styles/index.css', import.meta.url), 'utf8').replace( + /\/\*[\s\S]*?\*\//g, + '' +) + +describe('the app shell', () => { + it('stays below a status bar the page draws under, and is unmoved where there is none', () => { + const rule = /\.zn-app-shell \{([^}]*)\}/.exec(styles)?.[1] ?? '' + expect(rule).toContain('padding-top: env(safe-area-inset-top, 0px)') + }) +}) diff --git a/packages/app-core/src/lib/shortcut-labels-source.test.ts b/packages/app-core/src/lib/shortcut-labels-source.test.ts new file mode 100644 index 00000000..a3b1c645 --- /dev/null +++ b/packages/app-core/src/lib/shortcut-labels-source.test.ts @@ -0,0 +1,19 @@ +import { readFileSync } from 'node:fs' +import { describe, expect, it } from 'vitest' + +const read = (name: string): string => + readFileSync(new URL(`../components/${name}.tsx`, import.meta.url), 'utf8') + +describe('what a component shows', () => { + it.each(['EditorPane', 'Sidebar', 'HomeView', 'CommentsPanel', 'OnboardingWizard'])( + '%s names no Mac key of its own', + (name) => { + const shown = read(name) + .split('\n') + .filter((line) => !/^\s*(\/\/|\*|\/\*)/.test(line)) + .map((line) => line.replace(/\s\/\/ .*$/, '')) + .join('\n') + expect(shown).not.toMatch(/⌘/) + } + ) +}) diff --git a/packages/app-core/src/lib/shortcut-labels.test.ts b/packages/app-core/src/lib/shortcut-labels.test.ts new file mode 100644 index 00000000..33accf72 --- /dev/null +++ b/packages/app-core/src/lib/shortcut-labels.test.ts @@ -0,0 +1,37 @@ +// @vitest-environment jsdom +import { describe, expect, it } from 'vitest' +import { formatKeymapBinding, getKeymapDisplay, labelWithShortcut } from './keymaps' + +function onPlatform(platform: string, run: () => T): T { + const zen = (window as unknown as { zen?: unknown }).zen + ;(window as unknown as { zen: unknown }).zen = { platformSync: () => platform } + try { + return run() + } finally { + ;(window as unknown as { zen?: unknown }).zen = zen + } +} + +describe('shortcuts named in a tooltip', () => { + it('reads Ctrl on Android, Windows and Linux, and the Mac keys on a Mac or an iPad', () => { + for (const platform of ['android', 'win32', 'linux']) { + onPlatform(platform, () => { + expect(getKeymapDisplay(null, 'global.toggleSidebar')).toBe('Ctrl+1') + expect(getKeymapDisplay(null, 'global.exportNotePdf')).toBe('Shift+Ctrl+E') + }) + } + onPlatform('darwin', () => { + expect(getKeymapDisplay(null, 'global.toggleSidebar')).toBe('⌘1') + expect(getKeymapDisplay(null, 'global.exportNotePdf')).toBe('⇧⌘E') + }) + }) + + it('reads the submit key of the comment box for the platform', () => { + onPlatform('android', () => expect(formatKeymapBinding('Mod+Enter', 'shortcut')).toBe('Ctrl+Enter')) + onPlatform('darwin', () => expect(formatKeymapBinding('Mod+Enter', 'shortcut')).toBe('⌘↵')) + }) + + it('leaves the key out of a tooltip when the action is unbound', () => { + expect(labelWithShortcut('Show sidebar', '')).toBe('Show sidebar') + }) +}) diff --git a/packages/app-core/src/lib/sidebar-restore.test.ts b/packages/app-core/src/lib/sidebar-restore.test.ts index a5b758cf..2cd7e269 100644 --- a/packages/app-core/src/lib/sidebar-restore.test.ts +++ b/packages/app-core/src/lib/sidebar-restore.test.ts @@ -45,7 +45,7 @@ describe('EditorPane', () => { it('draws a control for both slots the tab strip does not cover', () => { expect(editorPaneSource).toMatch(/sidebarSlot === 'pane-strip' && \(/) expect(editorPaneSource).toMatch(/sidebarSlot === 'note-header' && \(/) - expect(editorPaneSource.match(/title="Show sidebar \(⌘1\)"/g)).toHaveLength(3) + expect(editorPaneSource.match(/'Show sidebar',\n\s+getKeymapDisplay/g)).toHaveLength(3) }) it('marks them so a phone layout, which has no sidebar, can leave them out', () => { diff --git a/packages/app-core/src/styles/index.css b/packages/app-core/src/styles/index.css index 2cb4df2a..22b24301 100644 --- a/packages/app-core/src/styles/index.css +++ b/packages/app-core/src/styles/index.css @@ -46,6 +46,9 @@ .zn-app-shell { height: 100vh; height: 100dvh; + /* Under a status bar the page draws beneath (a tablet's, where the title row stays; + * a phone shell sets its own padding here). 0 on desktop. */ + padding-top: env(safe-area-inset-top, 0px); } /* Keep the sidebar footer's controls above the iOS home indicator once From ccea16d848cd338d6a43272c41aaf1c689002da6 Mon Sep 17 00:00:00 2001 From: Adib Hanna Date: Thu, 5 Nov 2026 10:51:36 -0600 Subject: [PATCH 17/27] Fix(title bar): the Assets page is named in the title bar Every other page names itself in the title bar. Assets fell through to the vault's name, which read as though Go to Files had gone nowhere. --- .../app-core/src/components/TitleBar.test.ts | 115 ++++-------------- packages/app-core/src/components/TitleBar.tsx | 3 + 2 files changed, 29 insertions(+), 89 deletions(-) diff --git a/packages/app-core/src/components/TitleBar.test.ts b/packages/app-core/src/components/TitleBar.test.ts index f8640452..8d16dc45 100644 --- a/packages/app-core/src/components/TitleBar.test.ts +++ b/packages/app-core/src/components/TitleBar.test.ts @@ -1,97 +1,34 @@ // @vitest-environment jsdom import { act, createElement } from 'react' -import { createRoot, type Root } from 'react-dom/client' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { createRoot } from 'react-dom/client' +import { afterEach, describe, expect, it } from 'vitest' +import { ASSETS_VIEW_TAB_PATH } from '@shared/assets-view' +import { useStore } from '../store' import { TitleBar } from './TitleBar' -const state = vi.hoisted(() => ({ - showWindowTitleBar: true as boolean | undefined, - vault: { name: 'Demo vault' }, - activeNote: null, - selectedPath: null, - systemFolderLabels: {}, - workspaceMode: 'local' -})) - -vi.mock('../store', () => ({ - useStore: (select: (value: typeof state) => unknown) => select(state) -})) - -describe('window title bar', () => { - let root: Root - let host: HTMLDivElement - let runtime: 'desktop' | 'web' - let platform: NodeJS.Platform - const close = vi.fn() - - beforeEach(() => { - runtime = 'desktop' - platform = 'linux' - state.showWindowTitleBar = true - close.mockClear() - ;(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true - Object.defineProperty(window, 'zen', { - configurable: true, - value: { - getAppInfo: () => ({ runtime }), - platformSync: () => platform, - windowClose: close - } - }) - host = document.createElement('div') - document.body.append(host) - root = createRoot(host) - }) - - afterEach(() => { +;(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true + +describe('TitleBar', () => { + const originalState = useStore.getState() + afterEach(() => useStore.setState(originalState, true)) + + it('names the Assets page instead of falling back to the vault', () => { + ;(window as unknown as { zen: unknown }).zen = { + platformSync: () => 'darwin', + getAppInfo: () => ({ runtime: 'desktop' }) + } + useStore.setState({ + showWindowTitleBar: true, + vault: { root: '/v', name: 'my vault' }, + activeNote: null, + selectedPath: ASSETS_VIEW_TAB_PATH + } as never) + const host = document.createElement('div') + const root = createRoot(host) + act(() => root.render(createElement(TitleBar))) + expect(host.textContent).toContain('Assets') + expect(host.textContent).not.toContain('my vault') act(() => root.unmount()) - host.remove() - }) - - it.each(['darwin', 'linux', 'win32'])('reclaims the whole title row on %s', (os) => { - platform = os - act(() => root.render(createElement(TitleBar))) - expect(host.textContent).toContain('Demo vault') - state.showWindowTitleBar = false - act(() => root.render(createElement(TitleBar))) - expect(host.childElementCount).toBe(0) - state.showWindowTitleBar = true - act(() => root.render(createElement(TitleBar))) - expect(host.textContent).toContain('Demo vault') - }) - - it('restores working Linux window controls when shown again', () => { - state.showWindowTitleBar = false - act(() => root.render(createElement(TitleBar))) - expect(host.querySelector('button')).toBeNull() - state.showWindowTitleBar = true - act(() => root.render(createElement(TitleBar))) - act(() => host.querySelector('button[aria-label="✕"]')!.click()) - expect(close).toHaveBeenCalledOnce() - }) - - it('hides in the browser too, and old preferences keep it', () => { - runtime = 'web' - state.showWindowTitleBar = false - act(() => root.render(createElement(TitleBar))) - expect(host.childElementCount).toBe(0) - state.showWindowTitleBar = undefined - act(() => root.render(createElement(TitleBar))) - expect(host.textContent).toContain('Demo vault') - runtime = 'desktop' - act(() => root.render(createElement(TitleBar))) - expect(host.textContent).toContain('Demo vault') - }) - - it('leaves onboarding a strip to move the desktop window by', () => { - state.showWindowTitleBar = false - act(() => root.render(createElement(TitleBar, { standalone: true }))) - const strip = host.firstElementChild - expect(strip?.classList.contains('drag-region')).toBe(true) - expect(host.textContent).toBe('') - runtime = 'web' - act(() => root.render(createElement(TitleBar, { standalone: true }))) - expect(host.childElementCount).toBe(0) }) }) diff --git a/packages/app-core/src/components/TitleBar.tsx b/packages/app-core/src/components/TitleBar.tsx index 1c2836c0..95c318ea 100644 --- a/packages/app-core/src/components/TitleBar.tsx +++ b/packages/app-core/src/components/TitleBar.tsx @@ -3,6 +3,7 @@ import { isTasksTabPath } from '@shared/tasks' import { isWorkflowsTabPath } from '@shared/workflows-view' import { isAtlasTabPath } from '@shared/atlas-view' import { isTagsTabPath } from '@shared/tags' +import { isAssetsViewTabPath } from '@shared/assets-view' import { isHelpTabPath } from '@shared/help' import { isArchiveTabPath } from '@shared/archive' import { isTrashTabPath } from '@shared/trash' @@ -41,6 +42,8 @@ export function TitleBar({ standalone = false }: { standalone?: boolean }): JSX. ? 'Tags' : isHelpTabPath(selectedPath) ? 'Help' + : isAssetsViewTabPath(selectedPath) + ? 'Assets' : isArchiveTabPath(selectedPath) ? labels.archive : isTrashTabPath(selectedPath) From cacbbfc468db49f3e46d1df16cdc66a30211390a Mon Sep 17 00:00:00 2001 From: Adib Hanna Date: Thu, 5 Nov 2026 10:53:09 -0600 Subject: [PATCH 18/27] Fix(mcp): a local vault's record pages are notes, and a deny entry can name one On a local vault the bundled server left the pages in a `.base` database out of `list_notes` and `list_tasks`, though `read_note` and `search_text` could reach them. Under a path scope they did not exist at all. A deny entry on a page or a database counted as naming nothing, so the fail-closed rule shut the client out of everything, with a message saying the entry was renamed or deleted when it was not. A server has listed these pages since #527, so the answers depended on where the vault was. The server now opens a local vault with record pages on, so they are in the listings, tasks, tags and backlinks, and a scope judges them by path like any other note. A deny entry hides just that page or database, an allow entry on either shares it, and an entry that really names nothing still stops the client. A database with no pages yet can be named too. This matches zn's 86ed8ff. It stays strict. A database's `data.csv` and `schema.json` are not listed and stay out of reach, nothing can be created or moved into a `.base` folder under a scope, a folder holding a hidden page cannot go as a whole, and a scoped client cannot delete a database folder as a folder. The CLI's listings are unchanged, since they draw a database as one thing, and so is the shared fixture. `spell` already goes exact, then lower-cased NFC, then folded, each pass counting one path once, as zn's a00ca1f does. It gains direct tests here. --- apps/desktop/src/cli/backend.ts | 5 + apps/desktop/src/mcp/record-pages.test.ts | 171 ++++++++++++++++++++++ apps/desktop/src/mcp/scoped-backend.ts | 7 +- apps/desktop/src/mcp/server.ts | 14 +- apps/desktop/src/mcp/vault-ops.ts | 22 ++- packages/app-core/src/lib/help.ts | 2 +- 6 files changed, 212 insertions(+), 9 deletions(-) create mode 100644 apps/desktop/src/mcp/record-pages.test.ts diff --git a/apps/desktop/src/cli/backend.ts b/apps/desktop/src/cli/backend.ts index 0319ae4e..28b4dc97 100644 --- a/apps/desktop/src/cli/backend.ts +++ b/apps/desktop/src/cli/backend.ts @@ -154,6 +154,9 @@ export interface VaultBackend { * the tag tools and commands leave its notes out, as the app does. */ templateFolder(): Promise listNotes(): Promise + /** Where a folder listing leaves database folders out, names them: a path scope + * can name one even with no record page yet. */ + listDatabaseDirs?(): Promise<{ folder: NoteFolder; subpath: string }[]> listAssets(): Promise /** An attachment's bytes. */ readAsset(rel: string): Promise @@ -321,6 +324,8 @@ class LocalBackend implements VaultBackend { } templateFolder = (): Promise => readTemplateFolder(this.root) listNotes = (): Promise => listNotes(this.root) + listDatabaseDirs = (): Promise<{ folder: NoteFolder; subpath: string }[]> => + listDatabaseDirs(this.root) marksLinks = async (): Promise => true linkedSystemFolders = async (): Promise => { const { primaryNotesLocation, systemFolderPaths } = await this.vaultLayout() diff --git a/apps/desktop/src/mcp/record-pages.test.ts b/apps/desktop/src/mcp/record-pages.test.ts new file mode 100644 index 00000000..aa5c5c4d --- /dev/null +++ b/apps/desktop/src/mcp/record-pages.test.ts @@ -0,0 +1,171 @@ +import { promises as fsp } from 'node:fs' +import os from 'node:os' +import path from 'node:path' +import { Client } from '@modelcontextprotocol/sdk/client/index.js' +import { InMemoryTransport } from '@modelcontextprotocol/sdk/inMemory.js' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { newMcpScope, type McpScopeFlags } from '@shared/mcp-scope' +import { spell } from './scoped-backend' +import { runMcpServer } from './server' + +// A database's record pages are notes to an assistant on this machine, as they are +// on a server and in zn. Mirrors internal/mcp/record_pages_test.go in ZenNotes/tui. + +const RECORD_PAGE = 'memory/Books.base/Alpha.md' + +let root: string +const clients: Client[] = [] + +async function seed(): Promise { + const files: Record = { + '.zennotes/vault.json': '{"primaryNotesLocation":"root"}', + 'memory/note.md': '# Note\n\nneedle in the note\n\n[[Alpha]]\n', + 'memory/Books.base/data.csv': 'title\nAlpha\n', + 'memory/Books.base/schema.json': '{}\n', + [RECORD_PAGE]: '# Alpha\n\nneedle on the page\n\n- [ ] page task\n', + 'memory/Empty.base/data.csv': 'title\n', + 'memory/Empty.base/schema.json': '{}\n' + } + for (const [rel, body] of Object.entries(files)) { + const abs = path.join(root, ...rel.split('/')) + await fsp.mkdir(path.dirname(abs), { recursive: true }) + await fsp.writeFile(abs, body) + } +} + +const exists = (rel: string): Promise => + fsp.lstat(path.join(root, ...rel.split('/'))).then( + () => true, + () => false + ) + +async function connect(flags?: McpScopeFlags): Promise { + const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair() + await runMcpServer({ + resolveTarget: async () => ({ kind: 'local', root }), + scope: flags ? newMcpScope(flags) : null, + transport: serverTransport + }) + const client = new Client({ name: 'claude-code', version: '0' }) + await client.connect(clientTransport) + clients.push(client) + return client +} + +async function call( + client: Client, + name: string, + args: Record = {} +): Promise<{ text: string; isError: boolean }> { + const result = await client.callTool({ name, arguments: args }) + const parts = result.content as { text?: string }[] + return { text: parts[0]?.text ?? '', isError: !!result.isError } +} + +/** Every listing asked whether the page is there. They must agree. */ +async function seesRecordPage(client: Client): Promise { + const notes = (await call(client, 'list_notes')).text.includes(RECORD_PAGE) + const search = (await call(client, 'search_text', { query: 'needle' })).text.includes(RECORD_PAGE) + const tasks = (await call(client, 'list_tasks')).text.includes('page task') + const read = await call(client, 'read_note', { path: RECORD_PAGE }) + const opened = !read.isError && read.text.includes('needle on the page') + expect({ search, tasks, opened }).toEqual({ search: notes, tasks: notes, opened: notes }) + return notes +} + +beforeEach(async () => { + root = await fsp.realpath(await fsp.mkdtemp(path.join(os.tmpdir(), 'zen-record-pages-'))) + vi.stubEnv('ZENNOTES_CONFIG_DIR', path.join(root, '.config-for-test')) + await seed() +}) + +afterEach(async () => { + vi.restoreAllMocks() + vi.unstubAllEnvs() + await Promise.all(clients.splice(0).map((client) => client.close())) + await fsp.rm(root, { recursive: true, force: true }) +}) + +describe('a record page and a path scope', () => { + it.each<[string, McpScopeFlags | undefined, boolean, boolean]>([ + ['no paths', undefined, true, true], + ['allow the folder holding it', { allow: ['memory'] }, true, true], + ['allow the database', { allow: ['memory/Books.base'] }, true, false], + ['allow the page', { allow: [RECORD_PAGE] }, true, false], + ['allow another database', { allow: ['memory/Empty.base'] }, false, false], + ['deny the page', { deny: [RECORD_PAGE] }, false, true], + ['deny the page in another case', { deny: ['MEMORY/books.BASE/ALPHA.md'] }, false, true], + ['deny the database', { deny: ['memory/Books.base'] }, false, true], + ['deny the database with no pages', { deny: ['memory/Empty.base'] }, true, true], + ['deny its folder', { deny: ['memory'] }, false, false] + ])('%s', async (_name, flags, page, note) => { + const client = await connect(flags) + expect(await seesRecordPage(client)).toBe(page) + const listed = (await call(client, 'list_notes')).text + expect(listed.includes('memory/note.md')).toBe(note) + expect(listed).not.toContain('data.csv') + expect(listed).not.toContain('schema.json') + }) + + it.each(['memory/Gone.base', 'memory/Books.base/Gone.md'])( + 'still stops the client for an entry that names nothing: %s', + async (deny) => { + const client = await connect({ deny: [deny] }) + const listed = await call(client, 'list_notes') + expect(listed.isError).toBe(true) + expect(listed.text).toContain('does not exist in this vault') + } + ) +}) + +describe('what holds around a record page', () => { + it('keeps the folder whole and the database closed', async () => { + const client = await connect({ deny: [RECORD_PAGE] }) + expect((await call(client, 'delete_folder', { folder: 'inbox', subpath: 'memory' })).isError).toBe(true) + expect( + (await call(client, 'rename_folder', { folder: 'inbox', subpath: 'memory', newSubpath: 'moved' })) + .isError + ).toBe(true) + expect((await call(client, 'read_asset', { path: 'memory/Books.base/data.csv' })).isError).toBe(true) + expect( + (await call(client, 'create_note', { folder: 'inbox', subpath: 'memory/Books.base', title: 'Nope' })) + .isError + ).toBe(true) + expect(await exists(RECORD_PAGE)).toBe(true) + expect(await exists('memory/Books.base/Nope.md')).toBe(false) + }) + + it('does not let a client that sees a database delete it as a folder', async () => { + const client = await connect({ allow: ['memory/Books.base'] }) + const deleted = await call(client, 'delete_folder', { folder: 'inbox', subpath: 'memory/Books.base' }) + expect(deleted.isError).toBe(true) + expect(await exists(RECORD_PAGE)).toBe(true) + }) + + it('keeps the database out of the folder listing', async () => { + const client = await connect() + expect((await call(client, 'list_folders')).text).not.toContain('Books.base') + }) +}) + +describe('spell', () => { + const nfc = 'Caf\u00e9' + const nfd = 'Cafe\u0301' + + it('prefers exact, then case and composition, then folded accents', () => { + expect(spell(nfc, [nfc, nfd])).toBe(nfc) + expect(spell(nfd, ['Cafe', nfc])).toBe(nfc) + expect(spell('caf\u00c9', ['Cafe', nfc])).toBe(nfc) + expect(spell('cafe', [nfc])).toBe(nfc) + }) + + it('matches nothing for two paths equal after case and composition', () => { + expect(spell(nfd, [nfc, 'CAF\u00c9'])).toBeNull() + expect(spell('cafe', ['Cafe', 'CAFE'])).toBeNull() + }) + + it('counts a path a list names twice once, in each pass', () => { + expect(spell(nfd, [nfc, nfc, 'Cafe'])).toBe(nfc) + expect(spell('cafe', [nfc, nfc])).toBe(nfc) + }) +}) diff --git a/apps/desktop/src/mcp/scoped-backend.ts b/apps/desktop/src/mcp/scoped-backend.ts index c32bd50b..3bee337e 100644 --- a/apps/desktop/src/mcp/scoped-backend.ts +++ b/apps/desktop/src/mcp/scoped-backend.ts @@ -142,7 +142,7 @@ function joinRel(dir: string, sub: string): string { * to it after case and Unicode form, else the one equal after accent folding too. * The order matters beside a look-alike: NFD `Café` means `Café/` and is not left * undecided by `Cafe/` next to it. */ -function spell(p: string, known: readonly string[]): string | null { +export function spell(p: string, known: readonly string[]): string | null { const cased = foldCase(p) const folded = foldMcpScopePath(p) // The lists can name one path twice, which is still one path. @@ -573,6 +573,11 @@ export class ScopedBackend implements VaultBackend { known.push(note.path) } known.push(...v.dirs) + // A database folder is there to name, where a folder listing leaves it out, even + // with no record page yet. It stays out of v.dirs: it takes no notes and no moves. + for (const entry of (await this.inner.listDatabaseDirs?.()) ?? []) { + known.push(v.folderRel(entry)) + } // An entry can name an attachment folder or an asset, which the listings // above do not show, so those are read only for an entry they did not find. diff --git a/apps/desktop/src/mcp/server.ts b/apps/desktop/src/mcp/server.ts index 5cb3ebb0..3e00eb73 100644 --- a/apps/desktop/src/mcp/server.ts +++ b/apps/desktop/src/mcp/server.ts @@ -27,7 +27,7 @@ import { type VaultTarget } from '../cli/vault-target.js' import { RemoteRequestError } from '../main/remote/connection.js' -import type { NoteFolder } from './vault-ops.js' +import { treatRecordPagesAsNotes, type NoteFolder } from './vault-ops.js' import { addComment, listCommentThreads, replyToComment, resolveComment } from './comment-ops.js' import { isMcpScopeActive, @@ -54,6 +54,14 @@ import { wellFormedArguments } from './tool-support.js' +/** A vault as an assistant sees it: on this machine, a database's record pages are + * notes, as they are on a server. */ +function openVaultForAssistant(target: VaultTarget): VaultBackend { + const backend = createBackend(target) + if (backend.kind === 'local') treatRecordPagesAsNotes(backend.root) + return backend +} + /* ---------- Comment authorship ---------------------------------------- */ // The MCP client's name from the initialize handshake ("claude-code", @@ -1108,7 +1116,7 @@ export class VaultSession { constructor( private readonly resolve: () => Promise, - private readonly open: (target: VaultTarget) => VaultBackend = createBackend, + private readonly open: (target: VaultTarget) => VaultBackend = openVaultForAssistant, /** Keeps absolute paths out of what a switch reports. */ private readonly scoped = false, private readonly served: (target: VaultTarget) => Promise = servedTarget @@ -1220,7 +1228,7 @@ export async function runMcpServer(options: McpServerOptions = {}): Promise name.toLowerCase().endsWith('.base') + +const recordPageVaults = new Set() + +/** + * Has the walks treat this vault's database record pages as notes, as a server's + * listings do, so a client gets one answer wherever its vault is and a path scope + * can name what it can see. The MCP server calls it for each vault it opens. Mirrors + * `RecordPages` on the Vault in ZenNotes/tui. + */ +export function treatRecordPagesAsNotes(root: string): void { + recordPageVaults.add(root) +} const ASSETS_DIR = 'assets' const PRIMARY_ATTACHMENTS_DIR = 'attachements' const LEGACY_ATTACHMENTS_DIRS = [PRIMARY_ATTACHMENTS_DIR, '_assets'] @@ -908,7 +921,8 @@ export async function listNotes(root: string): Promise { const full = path.join(dirAbs, entry.name) if (entry.isDirectory()) { if (entry.name.startsWith('.')) continue - if (isFormDirName(entry.name)) continue // database folder — not loose notes + // A database folder, whose pages are notes only where that was asked for. + if (isFormDirName(entry.name) && !recordPageVaults.has(root)) continue // When walking the vault root in primary='root' mode, system // subdirectories (quick/, archive/, trash/, attachments) are // not part of inbox — they're walked separately as their own diff --git a/packages/app-core/src/lib/help.ts b/packages/app-core/src/lib/help.ts index ff94eb53..3518eba5 100644 --- a/packages/app-core/src/lib/help.ts +++ b/packages/app-core/src/lib/help.ts @@ -1680,7 +1680,7 @@ export const HELP_CLI: HelpCard[] = [ title: 'Share part of a vault with an assistant', only: 'computer', body: - 'An assistant connected through MCP sees the whole vault unless its launch flags say otherwise, and the server enforces them on every tool: listings, search, tags, tasks, backlinks, assets, comments and error messages, so a hidden note cannot be listed or read another way. One thing can still show: a new or moved file takes a number when a hidden file already has its name. `--allow-path ` shares only that folder or note and what is inside it (repeat it for more), `--deny-path ` hides one even inside an allowed folder, `--read-only` offers the reading tools only, and `--access comment` adds the comment tools to them. Paths are vault-relative, as the tools report them: `Projects` in a vault that keeps notes at its root, `inbox/Projects` in one with an Inbox folder, and a system folder you moved under its own name (`99 Archive/Projects` shares that folder\'s archived notes). A path covers the folder and everything below it, never a sibling that only starts with the same letters, and case and accents do not matter, except that an `--allow-path` with accents shares only a folder that has them. `zn mcp` and the server bundled with the app take the same flags and give the same answers; add them after the command in the client\'s config, for example `"args": ["mcp", "--allow-path", "Projects", "--read-only"]`. Settings → MCP then shows that client as **Needs update**, and updating it there removes the flags.\n\nWhat the assistant gets: a hidden note answers exactly like a missing one (`Note not found`), and so do paths through a symbolic link, case variants and the `.zennotes` folder. Its errors and `vault_info` never show where the vault lives on disk, and `vault_info` lists what was shared under `access`. Tools it cannot use are not offered, and `empty_trash` never is once paths are restricted, since it would delete trashed notes it cannot see. New notes, moves and restores land only inside allowed folders, never through a symbolic link; archiving or trashing a note it can see is allowed even when the archive or trash is not shared, and the note then leaves its view. A `--deny-path` follows a note into the other system folders, however it names the folder: `Journal` also hides `archive/Journal`. `duplicate_note` refuses a copy that would land outside what is shared. A folder is renamed or deleted as a whole only when nothing inside it is hidden. Renaming a note rewrites `[[links]]` only in notes the assistant can see with `zn mcp`, and in none with the bundled server; on a self-hosted ZenNotes server, which rewrites links in every note, an assistant that sees part of the vault cannot rename notes. Attachments follow the same paths: a file is visible when its path is, and a hidden one answers `Asset not found`, like a missing one. Name them in the flags as `list_assets` shows them (`--allow-path assets`, `--deny-path assets/private`). `upload_asset` writes only to `assets`, so it needs that folder shared. Renaming or moving a file rewrites links only in notes the assistant can see. On a self-hosted server, an assistant that sees part of the vault cannot rename, move, read or copy a file; it can list, upload, delete and restore. `daily_note` gives no template, since a template is not filed under any folder a path can name, and where a note\'s folder is not shared it says so rather than offering to create it. A `--deny-path` that names nothing in the vault (renamed outside ZenNotes, or meant for another vault) shares nothing at all until it is fixed, so a rename never quietly reveals what it hid; the MCP server\'s log, which the client keeps, names the entry.\n\nThe flags govern the ZenNotes tools only. An assistant that can also run commands or read files (Claude Code, Codex, OpenCode) can still read the vault from disk.' + 'An assistant connected through MCP sees the whole vault unless its launch flags say otherwise, and the server enforces them on every tool: listings, search, tags, tasks, backlinks, assets, comments and error messages, so a hidden note cannot be listed or read another way. One thing can still show: a new or moved file takes a number when a hidden file already has its name. `--allow-path ` shares only that folder or note and what is inside it (repeat it for more), `--deny-path ` hides one even inside an allowed folder, `--read-only` offers the reading tools only, and `--access comment` adds the comment tools to them. Paths are vault-relative, as the tools report them: `Projects` in a vault that keeps notes at its root, `inbox/Projects` in one with an Inbox folder, and a system folder you moved under its own name (`99 Archive/Projects` shares that folder\'s archived notes). A path covers the folder and everything below it, never a sibling that only starts with the same letters, and case and accents do not matter, except that an `--allow-path` with accents shares only a folder that has them. A database\'s record pages are notes to an assistant, wherever the vault is, so a path can name one page or the whole `.base` folder; its `data.csv` and `schema.json` stay out of reach. `zn mcp` and the server bundled with the app take the same flags and give the same answers; add them after the command in the client\'s config, for example `"args": ["mcp", "--allow-path", "Projects", "--read-only"]`. Settings → MCP then shows that client as **Needs update**, and updating it there removes the flags.\n\nWhat the assistant gets: a hidden note answers exactly like a missing one (`Note not found`), and so do paths through a symbolic link, case variants and the `.zennotes` folder. Its errors and `vault_info` never show where the vault lives on disk, and `vault_info` lists what was shared under `access`. Tools it cannot use are not offered, and `empty_trash` never is once paths are restricted, since it would delete trashed notes it cannot see. New notes, moves and restores land only inside allowed folders, never through a symbolic link; archiving or trashing a note it can see is allowed even when the archive or trash is not shared, and the note then leaves its view. A `--deny-path` follows a note into the other system folders, however it names the folder: `Journal` also hides `archive/Journal`. `duplicate_note` refuses a copy that would land outside what is shared. A folder is renamed or deleted as a whole only when nothing inside it is hidden. Renaming a note rewrites `[[links]]` only in notes the assistant can see with `zn mcp`, and in none with the bundled server; on a self-hosted ZenNotes server, which rewrites links in every note, an assistant that sees part of the vault cannot rename notes. Attachments follow the same paths: a file is visible when its path is, and a hidden one answers `Asset not found`, like a missing one. Name them in the flags as `list_assets` shows them (`--allow-path assets`, `--deny-path assets/private`). `upload_asset` writes only to `assets`, so it needs that folder shared. Renaming or moving a file rewrites links only in notes the assistant can see. On a self-hosted server, an assistant that sees part of the vault cannot rename, move, read or copy a file; it can list, upload, delete and restore. `daily_note` gives no template, since a template is not filed under any folder a path can name, and where a note\'s folder is not shared it says so rather than offering to create it. A `--deny-path` that names nothing in the vault (renamed outside ZenNotes, or meant for another vault) shares nothing at all until it is fixed, so a rename never quietly reveals what it hid; the MCP server\'s log, which the client keeps, names the entry.\n\nThe flags govern the ZenNotes tools only. An assistant that can also run commands or read files (Claude Code, Codex, OpenCode) can still read the vault from disk.' }, { title: 'Review an assistant’s edits', From ad059c56622bdab7348eade39831d055f94ca92f Mon Sep 17 00:00:00 2001 From: Adib Hanna Date: Thu, 5 Nov 2026 11:08:46 -0600 Subject: [PATCH 19/27] Fix(reference): the pinned pane's reveal finds the note in any vault layout The pinned pane's title reveals its note in the sidebar, and it took the path's first segment for a system folder. In a vault that keeps notes at the root, `Projects/x.md` asked for a folder called `Projects`, and in one with a moved system folder it asked for the directory's own name. It also went through `setView`, which blanked the title and the status bar while the open note stayed. It now resolves the path through `sidebarRevealTarget`, opens the folders above the note, and puts the cursor on its row, or on the folder when a windowed list has not drawn the row. The note list layout still gets `setView`, with the right folder. --- .../components/PinnedReferencePane.test.ts | 91 +++++++++++++++++++ .../src/components/PinnedReferencePane.tsx | 7 +- packages/app-core/src/lib/sidebar-focus.ts | 36 ++++++++ 3 files changed, 129 insertions(+), 5 deletions(-) diff --git a/packages/app-core/src/components/PinnedReferencePane.test.ts b/packages/app-core/src/components/PinnedReferencePane.test.ts index d71cbc5a..0d2357c6 100644 --- a/packages/app-core/src/components/PinnedReferencePane.test.ts +++ b/packages/app-core/src/components/PinnedReferencePane.test.ts @@ -122,3 +122,94 @@ describe('PinnedReferencePane search bindings (#860)', () => { expect(searchPanelOpen(view.state)).toBe(false) }) }) + +describe('PinnedReferencePane reveal in the sidebar', () => { + let host: HTMLDivElement + let root: Root + let originalState: ReturnType + + beforeEach(() => { + originalState = useStore.getState() + Object.defineProperty(Range.prototype, 'getClientRects', { + configurable: true, + value: () => [] + }) + Object.defineProperty(Range.prototype, 'getBoundingClientRect', { + configurable: true, + value: () => new DOMRect() + }) + host = document.createElement('div') + document.body.append(host) + root = createRoot(host) + }) + + afterEach(() => { + act(() => root.unmount()) + host.remove() + useStore.setState(originalState, true) + }) + + async function reveal( + path: string, + settings: Record, + layout: { unifiedSidebar: boolean; noteListOpen: boolean } = { + unifiedSidebar: true, + noteListOpen: false + } + ): Promise { + const pinned = { ...note, path } + useStore.setState({ + vault: { root: '/vault', name: 'Vault' }, + selectedPath: 'inbox/Open.md', + pinnedRefPath: path, + pinnedRefKind: 'note', + pinnedRefVisible: true, + pinnedRefMode: 'edit', + noteRefs: {}, + noteContents: { [path]: pinned }, + noteDirty: {}, + vimMode: false, + livePreview: false, + keymapOverrides: {}, + searchOpen: false, + updateNoteBody: vi.fn(), + sidebarOpen: true, + vaultSettings: { ...originalState.vaultSettings, ...settings }, + collapsedFolders: ['inbox:', 'inbox:Projects', 'inbox:Projects/Deep', 'archive:Sub', 'other:'], + ...layout + } as never) + await act(async () => root.render(createElement(PinnedReferencePane))) + const button = host.querySelector('button[title^="Reveal "]')! + await act(async () => button.click()) + } + + it('finds the folders of a note in a vault that keeps notes at its root', async () => { + await reveal('Projects/Deep/Reference.md', { primaryNotesLocation: 'root' }) + const state = useStore.getState() + expect(state.collapsedFolders).toEqual(['archive:Sub', 'other:']) + expect(state.focusedPanel).toBe('sidebar') + expect(state.selectedPath).toBe('inbox/Open.md') + }) + + it('finds the folders of a note under a moved system folder', async () => { + await reveal('99 Old/Sub/Reference.md', { + primaryNotesLocation: 'inbox', + systemFolderPaths: { archive: '99 Old' } + }) + expect(useStore.getState().collapsedFolders).not.toContain('archive:Sub') + expect(useStore.getState().collapsedFolders).toContain('inbox:') + }) + + it('shows the right folder in the note list layout', async () => { + await reveal( + 'Projects/Deep/Reference.md', + { primaryNotesLocation: 'root' }, + { unifiedSidebar: false, noteListOpen: true } + ) + expect(useStore.getState().view).toEqual({ + kind: 'folder', + folder: 'inbox', + subpath: 'Projects/Deep' + }) + }) +}) diff --git a/packages/app-core/src/components/PinnedReferencePane.tsx b/packages/app-core/src/components/PinnedReferencePane.tsx index 0af1e811..f1800e5a 100644 --- a/packages/app-core/src/components/PinnedReferencePane.tsx +++ b/packages/app-core/src/components/PinnedReferencePane.tsx @@ -46,6 +46,7 @@ import { syntaxHighlighting, HighlightStyle, defaultHighlightStyle } from '@code import { tags as t } from '@lezer/highlight' import { autocompletion } from '@codemirror/autocomplete' import { useStore } from '../store' +import { revealNoteInSidebar } from '../lib/sidebar-focus' import type { LineNumberMode } from '../store' import { livePreviewPlugin } from '../lib/cm-live-preview' import { sourceRevealExtension, sourceRevealForNewNote } from '../lib/cm-source-reveal' @@ -199,7 +200,6 @@ export function PinnedReferencePane(): JSX.Element | null { const editorFontSize = useStore((s) => s.editorFontSize) const editorLineHeight = useStore((s) => s.editorLineHeight) const textFont = useStore((s) => s.textFont) - const setView = useStore((s) => s.setView) const viewRef = useRef(null) const viewPathRef = useRef(null) @@ -525,10 +525,7 @@ export function PinnedReferencePane(): JSX.Element | null { void useStore.getState().openAssetsView() return } - const parts = pinnedRefPath.split('/') - const top = parts[0] as 'inbox' | 'quick' | 'archive' | 'trash' - const subpath = parts.slice(1, -1).join('/') - setView({ kind: 'folder', folder: top, subpath }) + revealNoteInSidebar(pinnedRefPath) }} className="flex min-w-0 flex-1 items-center gap-2 truncate text-left text-sm font-semibold text-ink-900 hover:text-ink-700" > diff --git a/packages/app-core/src/lib/sidebar-focus.ts b/packages/app-core/src/lib/sidebar-focus.ts index 84c80bc7..c1ea95a8 100644 --- a/packages/app-core/src/lib/sidebar-focus.ts +++ b/packages/app-core/src/lib/sidebar-focus.ts @@ -1,5 +1,6 @@ import type { NoteFolder } from '@shared/ipc' import { useStore } from '../store' +import { sidebarRevealTarget } from './vault-layout' /** * Hand the keyboard to the sidebar for real: set the focused panel AND move @@ -65,3 +66,38 @@ export function revealSystemFolderInSidebar(folder: NoteFolder): void { row?.scrollIntoView({ block: 'nearest' }) }) } + +/** + * Goes to a note's row: its folders opened and the cursor on it, or on the nearest + * folder when the row is not drawn (a long folder's list is windowed). The folder + * comes from the vault's layout, never from the path's first segment, which names + * nothing in a vault that keeps its notes at the root or has moved a system folder. + */ +export function revealNoteInSidebar(path: string): void { + const state = useStore.getState() + const target = sidebarRevealTarget(path, state.vaultSettings) + if (!target) return + const subpath = target.parts.slice(0, -1).join('/') + if (!state.unifiedSidebar && state.noteListOpen) { + state.setView({ kind: 'folder', folder: target.folder, subpath }) + return + } + if (!state.sidebarOpen) state.toggleSidebar() + const closed = new Set(target.ancestors) + const expanded = state.collapsedFolders.filter((key) => !closed.has(key)) + if (expanded.length !== state.collapsedFolders.length) state.setCollapsedFolders(expanded) + focusSidebarPanel() + requestAnimationFrame(() => { + const rows = [...document.querySelectorAll('[data-sidebar-idx]')] + const row = + rows.find((el) => el.dataset.sidebarType === 'note' && el.dataset.sidebarPath === path) ?? + rows.find( + (el) => + el.dataset.sidebarType === 'folder' && + el.dataset.sidebarKey === `${target.folder}:${subpath}` + ) + const idx = Number(row?.dataset.sidebarIdx) + if (Number.isFinite(idx)) useStore.getState().setSidebarCursorIndex(idx) + row?.scrollIntoView({ block: 'nearest' }) + }) +} From 14f80315d9b2cfd63326d7f3e309edb0b2717512 Mon Sep 17 00:00:00 2001 From: Adib Hanna Date: Thu, 5 Nov 2026 11:08:46 -0600 Subject: [PATCH 20/27] Fix(diagrams): the TikZ error stops naming a Mac key MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit "Quit (⌘Q) and relaunch" named a Mac key on every platform. The sentence says what to do without it, so the key is gone rather than gated. The source check that keeps written-out Mac keys out of the components now covers this file too. --- packages/app-core/src/lib/diagram-renderers.ts | 2 +- packages/app-core/src/lib/shortcut-labels-source.test.ts | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/packages/app-core/src/lib/diagram-renderers.ts b/packages/app-core/src/lib/diagram-renderers.ts index 8cd5ae6c..4396cb88 100644 --- a/packages/app-core/src/lib/diagram-renderers.ts +++ b/packages/app-core/src/lib/diagram-renderers.ts @@ -306,7 +306,7 @@ async function renderTikzBlock(el: HTMLElement): Promise { surface.innerHTML = '
Rendering TikZ…
'; if (typeof window.zen?.renderTikz !== "function") { - surface.innerHTML = `
TikZ renderer not loaded. Quit (⌘Q) and relaunch the app: the preload script is only attached when a window is first created, so a plain reload isn't enough.
`; + surface.innerHTML = `
TikZ renderer not loaded. Quit and relaunch the app: the preload script is only attached when a window is first created, so a plain reload isn't enough.
`; return; } try { diff --git a/packages/app-core/src/lib/shortcut-labels-source.test.ts b/packages/app-core/src/lib/shortcut-labels-source.test.ts index a3b1c645..7971dd4e 100644 --- a/packages/app-core/src/lib/shortcut-labels-source.test.ts +++ b/packages/app-core/src/lib/shortcut-labels-source.test.ts @@ -2,10 +2,10 @@ import { readFileSync } from 'node:fs' import { describe, expect, it } from 'vitest' const read = (name: string): string => - readFileSync(new URL(`../components/${name}.tsx`, import.meta.url), 'utf8') + readFileSync(new URL(name.endsWith('.ts') ? `./${name}` : `../components/${name}.tsx`, import.meta.url), 'utf8') describe('what a component shows', () => { - it.each(['EditorPane', 'Sidebar', 'HomeView', 'CommentsPanel', 'OnboardingWizard'])( + it.each(['EditorPane', 'Sidebar', 'HomeView', 'CommentsPanel', 'OnboardingWizard', 'diagram-renderers.ts'])( '%s names no Mac key of its own', (name) => { const shown = read(name) From 9189b42566913bb7357958b53a2b79d1db2646f4 Mon Sep 17 00:00:00 2001 From: Adib Hanna Date: Thu, 5 Nov 2026 11:08:46 -0600 Subject: [PATCH 21/27] Fix(capture): the Quick Capture picker names folders as search does The picker and the note chip printed the internal bucket name, so a root note in a vault that keeps notes at its root read "inbox", and a custom label was ignored. The window has no store, but it does not need one: its prefs already come from the same storage, which holds the labels, and `getVaultSettings` is on the bridge. It now uses `noteAreaLabel` like the other result rows, and the row's path comes from `noteFolderSubpath`, so a moved system folder is not repeated in it. If the settings cannot be read, the rows read as they would in a vault with an Inbox. --- .../src/components/QuickCaptureApp.test.ts | 38 ++++++++++- .../src/components/QuickCaptureApp.tsx | 65 +++++++++++++------ 2 files changed, 81 insertions(+), 22 deletions(-) diff --git a/packages/app-core/src/components/QuickCaptureApp.test.ts b/packages/app-core/src/components/QuickCaptureApp.test.ts index 42e3c78b..e48445c5 100644 --- a/packages/app-core/src/components/QuickCaptureApp.test.ts +++ b/packages/app-core/src/components/QuickCaptureApp.test.ts @@ -404,6 +404,42 @@ describe('Quick Capture close shortcut (#893)', () => { expect(overlayInput()?.placeholder).toContain('Run a command') }) + describe('how the picker names a folder', () => { + function seedLayout(primaryNotesLocation: 'inbox' | 'root'): void { + const zen = (window as unknown as { zen: Record }).zen + Object.defineProperty(window, 'zen', { + configurable: true, + value: { ...zen, getVaultSettings: vi.fn(async () => ({ primaryNotesLocation })) } + }) + } + const areas = (): string[] => + [...document.querySelectorAll('[data-picker-area]')].map((row) => row.textContent ?? '') + + afterEach(() => localStorage.removeItem('zen:prefs:v2')) + + it('names none for a note of a vault that keeps notes at its root', async () => { + seedNotes([ + { path: 'Plan.md', title: 'Plan', folder: 'inbox' }, + { path: 'archive/Old.md', title: 'Old', folder: 'archive' } + ]) + seedLayout('root') + const view = await mount() + await toNormalMode(view) + await onWindow(modP) + expect(areas()).toEqual(['Archive']) + }) + + it('uses a custom label in a vault with an Inbox', async () => { + localStorage.setItem('zen:prefs:v2', JSON.stringify({ systemFolderLabels: { inbox: 'Desk' } })) + seedNotes([{ path: 'inbox/Plan.md', title: 'Plan', folder: 'inbox' }]) + seedLayout('inbox') + const view = await mount() + await toNormalMode(view) + await onWindow(modP) + expect(areas()).toEqual(['Desk']) + }) + }) + it('moves down rather than toggling once the picker has focus', async () => { seedNotes([ { path: 'inbox/Alpha.md', title: 'Alpha', folder: 'inbox' }, @@ -557,7 +593,7 @@ describe('Quick Capture close shortcut (#893)', () => { expect(cells).toContain('Calendar Panel Tasks Placement') expect(cells).toContain('ZenNotes/Enhancements') // Neither the folder nor the filename is repeated in the path column. - expect(cells.filter((c) => c === 'inbox')).toHaveLength(1) + expect(cells.filter((c) => c === 'Inbox')).toHaveLength(1) expect(cells.some((c) => c.endsWith('.md'))).toBe(false) // The column is right to left so its ellipsis lands on the left, and the // path inside it is embedded left to right, as in Open Buffers: without diff --git a/packages/app-core/src/components/QuickCaptureApp.tsx b/packages/app-core/src/components/QuickCaptureApp.tsx index e2d24b46..0417161e 100644 --- a/packages/app-core/src/components/QuickCaptureApp.tsx +++ b/packages/app-core/src/components/QuickCaptureApp.tsx @@ -69,7 +69,7 @@ import { import { completionKeymapExtension, completionNavKeymap } from '../lib/cm-completion-nav' import { slashCommandRender, templateSlashCommandSource } from '../lib/cm-slash-commands' import { calloutTypeSource } from '../lib/cm-callouts' -import type { NoteMeta } from '@shared/ipc' +import type { NoteMeta, VaultSettings } from '@shared/ipc' import type { VimWrappedLineMotionMode } from '@shared/app-config' import { DEFAULT_THEME_ID, @@ -84,6 +84,12 @@ import { } from '../lib/note-search' import { deriveTitleFromBody, planQuickCaptureSave } from '../lib/quick-capture-save' import { applyVimInsertEscape } from '../lib/vim-insert-escape' +import { + noteAreaLabel, + normalizeSystemFolderLabels, + type SystemFolderLabels +} from '../lib/system-folder-labels' +import { isPrimaryNotesAtRoot, noteFolderSubpath } from '../lib/vault-layout' import { isPaletteNextKey, isPalettePreviousKey } from '../lib/palette-nav' import { isImeComposing } from '../lib/ime' import { PinIcon } from './icons' @@ -110,6 +116,7 @@ interface QuickCapturePrefs { interfaceFont: string | null textFont: string | null monoFont: string | null + systemFolderLabels: SystemFolderLabels } function loadPrefs(): QuickCapturePrefs { @@ -128,7 +135,8 @@ function loadPrefs(): QuickCapturePrefs { cursorBlink: true, interfaceFont: null, textFont: null, - monoFont: null + monoFont: null, + systemFolderLabels: {} } try { const raw = localStorage.getItem(PREFS_KEY) @@ -143,7 +151,8 @@ function loadPrefs(): QuickCapturePrefs { cursorBlink: parsed.cursorBlink !== false, themeFamily: (parsed.themeFamily as ThemeFamily) ?? fallback.themeFamily, themeMode: (parsed.themeMode as ThemeMode) ?? fallback.themeMode, - editorTabSize: normalizeEditorTabSize(parsed.editorTabSize) + editorTabSize: normalizeEditorTabSize(parsed.editorTabSize), + systemFolderLabels: normalizeSystemFolderLabels(parsed.systemFolderLabels) } } catch { return fallback @@ -278,6 +287,7 @@ export function QuickCaptureApp(): JSX.Element { const [submitting, setSubmitting] = useState(false) const [error, setError] = useState(null) const [notes, setNotes] = useState([]) + const [vaultSettings, setVaultSettings] = useState(null) const [overlay, setOverlay] = useState<'none' | 'search' | 'command'>('none') const editorRef = useRef(null) @@ -307,6 +317,13 @@ export function QuickCaptureApp(): JSX.Element { if (!alive) return setNotes(all.filter((n) => n.folder !== 'trash')) }) + // Only names folders on the rows. Without it they read as an Inbox vault. + void Promise.resolve() + .then(() => window.zen.getVaultSettings()) + .then((settings) => { + if (alive) setVaultSettings(settings) + }) + .catch(() => undefined) } refresh() const off = window.zen.onVaultChange(() => refresh()) @@ -664,6 +681,8 @@ export function QuickCaptureApp(): JSX.Element { } }, []) const modKey = isMacPlatform ? '⌘' : 'Ctrl' + const areaLabel = (folder: NoteMeta['folder']): string | null => + noteAreaLabel(folder, isPrimaryNotesAtRoot(vaultSettings), prefs.systemFolderLabels) // Pin state — when on, the window stays on top of all windows and no longer // auto-hides on blur, so it behaves like a floating sticky note. @@ -720,12 +739,12 @@ export function QuickCaptureApp(): JSX.Element { > {headerTitle || 'New note'} - {mode.kind === 'existing' && ( + {mode.kind === 'existing' && areaLabel(mode.note.folder) && ( - {mode.note.folder} + {areaLabel(mode.note.folder)} )} ) From 63b4a4f0dad2b0db386a80aea5b6bec29471a794 Mon Sep 17 00:00:00 2001 From: Adib Hanna Date: Thu, 5 Nov 2026 11:36:00 -0600 Subject: [PATCH 22/27] Fix(vault): only a verified Welcome leaves on its own, and only when safe Review of the seeded inbox change found four ways it took too much. An empty `inbox/` was removed on open and from the watcher, with no message, though nothing shows this app made it: someone who keeps one, or a capture tool writing to it, lost the folder. An empty folder now goes only on an explicit switch to root mode, and the automatic paths act only when a verified Welcome is there. An edit landing between the hash and the delete was lost. The Welcome is now renamed aside, hashed again where nothing can save to it, and then deleted or put back. A file saved after the rename keeps the folder. Comments on an untouched Welcome ended up orphaned, so a Welcome with a comments sidecar now stays. The note's creation record goes with it when it does leave. Choosing Vault root in onboarding removed the Welcome, and switching back to Inbox did not restore it, so the vault opened blank. The Welcome now goes only when there is something else at the root to look at. A vault that says root keeps being looked at, so the Welcome leaves once the folders arrive. --- apps/desktop/src/main/vault.test.ts | 81 ++++++++++++++++++++++++++++- apps/desktop/src/main/vault.ts | 59 ++++++++++++++++++--- 2 files changed, 131 insertions(+), 9 deletions(-) diff --git a/apps/desktop/src/main/vault.test.ts b/apps/desktop/src/main/vault.test.ts index 15ea9ed4..656ac0da 100644 --- a/apps/desktop/src/main/vault.test.ts +++ b/apps/desktop/src/main/vault.test.ts @@ -136,11 +136,90 @@ describe('a folder opened empty, then filled', () => { expect(await exists(path.join(root, 'inbox'))).toBe(false) }) - it('takes away an empty inbox and what Finder left in it', async () => { + it('leaves an empty inbox on its own: it may be a capture tool\'s', async () => { const root = await seededVault() await rm(path.join(root, 'inbox', 'Welcome.md')) await writeFile(path.join(root, 'inbox', '.DS_Store'), 'x') await copyFolderIn(root) + expect(await settleSeededInbox(root)).toBe(false) + await ensureVaultLayout(root) + expect(await exists(path.join(root, 'inbox'))).toBe(true) + }) + + it('takes away an empty inbox and what Finder left in it on a switch to root mode', async () => { + const root = await seededVault() + await rm(path.join(root, 'inbox', 'Welcome.md')) + await writeFile(path.join(root, 'inbox', '.DS_Store'), 'x') + const base = await getVaultSettings(root) + const stated = await setVaultSettings(root, { ...base, primaryNotesLocation: 'inbox' }) + await setVaultSettings(root, { ...stated, primaryNotesLocation: 'root' }) + expect(await exists(path.join(root, 'inbox'))).toBe(false) + }) + + it('keeps an edit that lands while the Welcome is being looked at', async () => { + const root = await seededVault() + await copyFolderIn(root) + const welcome = path.join(root, 'inbox', 'Welcome.md') + const realRename = fsPromises.rename + const rename = vi.spyOn(fsPromises, 'rename').mockImplementationOnce(async (from, to) => { + // The first hash has passed. The edit lands before the file moves. + await writeFile(welcome, '# Mine now\n') + await realRename(from, to) + }) + expect(await settleSeededInbox(root)).toBe(false) + rename.mockRestore() + expect(await readFile(welcome, 'utf8')).toBe('# Mine now\n') + expect((await fsPromises.readdir(path.join(root, 'inbox'))).sort()).toEqual(['Welcome.md']) + }) + + it('keeps a file saved while the Welcome is out of the way, and the folder with it', async () => { + const root = await seededVault() + await copyFolderIn(root) + const welcome = path.join(root, 'inbox', 'Welcome.md') + const realRename = fsPromises.rename + const rename = vi.spyOn(fsPromises, 'rename').mockImplementationOnce(async (from, to) => { + await realRename(from, to) + await writeFile(welcome, '# Saved after the move\n') + }) + await settleSeededInbox(root) + rename.mockRestore() + expect(await readFile(welcome, 'utf8')).toBe('# Saved after the move\n') + expect(await fsPromises.readdir(path.join(root, 'inbox'))).toEqual(['Welcome.md']) + }) + + it('keeps a Welcome with comments on it', async () => { + const root = await seededVault() + await writeNoteComments(root, 'inbox/Welcome.md', [ + { + id: 'c1', + body: 'mine', + anchorStart: 0, + anchorEnd: 1, + anchorText: '#', + createdAt: 1, + updatedAt: 1 + } as never + ]) + await copyFolderIn(root) + expect(await settleSeededInbox(root)).toBe(false) + expect(await exists(path.join(root, 'inbox', 'Welcome.md'))).toBe(true) + }) + + it('keeps the Welcome when root mode is chosen with nothing else in the vault', async () => { + const root = await seededVault() + const base = await getVaultSettings(root) + const asRoot = await setVaultSettings(root, { ...base, primaryNotesLocation: 'root' }) + expect(await exists(path.join(root, 'inbox', 'Welcome.md'))).toBe(true) + // Switching back in the same breath finds the vault as it was. + await setVaultSettings(root, { ...asRoot, primaryNotesLocation: 'inbox' }) + expect(await exists(path.join(root, 'inbox', 'Welcome.md'))).toBe(true) + }) + + it('lets the Welcome go once a vault that chose root mode gets something else', async () => { + const root = await seededVault() + const base = await getVaultSettings(root) + await setVaultSettings(root, { ...base, primaryNotesLocation: 'root' }) + await copyFolderIn(root) expect(await settleSeededInbox(root)).toBe(true) expect(await exists(path.join(root, 'inbox'))).toBe(false) }) diff --git a/apps/desktop/src/main/vault.ts b/apps/desktop/src/main/vault.ts index a00a6c9d..dccf956e 100644 --- a/apps/desktop/src/main/vault.ts +++ b/apps/desktop/src/main/vault.ts @@ -1421,6 +1421,10 @@ function statesPrimaryNotesLocation(parsed: unknown): boolean { return (parsed as { primaryNotesLocation?: unknown }).primaryNotesLocation != null } +function statesRootMode(parsed: unknown): boolean { + return (parsed as { primaryNotesLocation?: unknown } | null)?.primaryNotesLocation === 'root' +} + /** The remap stated by a parsed (or caller-supplied) settings object, for the * inference (a remapped system dir is not loose root content). */ function statedSystemFolderPaths(parsed: unknown): SystemFolderPaths { @@ -1567,7 +1571,7 @@ export async function setVaultSettings( // A new root-level directory is exactly what the inference reads. inferredPrimaryCache.delete(root) } else if (previousPrimary === 'inbox') { - await removeSeedOnlyInbox(root, normalized.systemFolderPaths) + await removeSeedOnlyInbox(root, normalized.systemFolderPaths, { explicit: true }) } return cloneVaultSettings(normalized) } @@ -1672,10 +1676,17 @@ const WELCOME_SEED_SHA256 = new Set([ * shows `inbox` as an ordinary folder, and nothing in it is hidden. A folder the * inbox was remapped to is theirs by name, and so is `Inbox/`, which a * case-insensitive volume would otherwise answer for. + * + * An empty folder goes only when someone asked, by switching to root mode: without + * a Welcome there is no sign this app made it, and it can be a capture tool's. The + * Welcome goes only beside something else to look at, since a vault switched to root + * before anything is in it (onboarding) would otherwise open on nothing, and + * switching back could not bring it back. A later look removes it once there is more. */ async function removeSeedOnlyInbox( root: string, - systemFolderPaths?: SystemFolderPaths | null + systemFolderPaths: SystemFolderPaths | null | undefined, + { explicit }: { explicit: boolean } ): Promise { if (resolveFolderPath('inbox', systemFolderPaths) !== 'inbox') return false const inbox = path.join(root, 'inbox') @@ -1687,12 +1698,13 @@ async function removeSeedOnlyInbox( const inside = entries.filter((entry) => entry.name !== '.DS_Store') if (inside.length > 1) return false const [only] = inside + if (!only && !explicit) return false if (only) { if (only.name !== 'Welcome.md' || !only.isFile()) return false - const welcome = path.join(inbox, only.name) - const hash = createHash('sha256').update(await fs.readFile(welcome)).digest('hex') - if (!WELCOME_SEED_SHA256.has(hash)) return false - await fs.rm(welcome) + if ((await inferPrimaryNotesLocation(root, systemFolderPaths)) !== 'root') return false + if (await pathExists(noteCommentsPath(root, 'inbox/Welcome.md'))) return false + if (!(await takeAwayUntouchedWelcome(inbox, only.name))) return false + await removeNoteCreation(root, 'inbox/Welcome.md') } await fs.rm(path.join(inbox, '.DS_Store'), { force: true }) // Not recursive: a file landing after the look stays, and so does the folder. @@ -1703,6 +1715,35 @@ async function removeSeedOnlyInbox( } } +const pathExists = (target: string): Promise => + fs.lstat(target).then( + () => true, + () => false + ) + +const sha256 = async (file: string): Promise => + createHash('sha256').update(await fs.readFile(file)).digest('hex') + +/** + * Deletes the Welcome if it is still a seed. It is hashed where nothing can save to + * it any more: an edit landing between a hash and a delete would be lost. A save + * after the rename makes a new file, which keeps the folder. An edit the rename + * carried with it goes back, beside any newer file rather than over it. + */ +async function takeAwayUntouchedWelcome(inbox: string, name: string): Promise { + const welcome = path.join(inbox, name) + if (!WELCOME_SEED_SHA256.has(await sha256(welcome))) return false + const aside = path.join(inbox, `.Welcome.settling-${randomUUID()}`) + await fs.rename(welcome, aside) + if (WELCOME_SEED_SHA256.has(await sha256(aside))) { + await fs.rm(aside) + return true + } + const taken = await pathExists(welcome) + await fs.rename(aside, taken ? path.join(inbox, `Welcome ${randomUUID()}.md`) : welcome) + return false +} + /** * A folder opened empty is seeded in inbox mode without saying so in vault.json, * so the layout is still inferred when folders are copied in, and it turns to root @@ -1722,10 +1763,12 @@ export async function settleSeededInbox(root: string): Promise { // its owner a problem that is not this function's to act on. if ((err as NodeJS.ErrnoException).code !== 'ENOENT') return false } - if (statesPrimaryNotesLocation(parsed)) return false + // A vault that says root has no Inbox to keep. One that says inbox keeps it, however + // much is at its root: that is what the banner is for. + if (statesPrimaryNotesLocation(parsed) && !statesRootMode(parsed)) return false const paths = statedSystemFolderPaths(parsed) if ((await inferPrimaryNotesLocation(root, paths)) !== 'root') return false - return await removeSeedOnlyInbox(root, paths) + return await removeSeedOnlyInbox(root, paths, { explicit: false }) } /** From 30fb79f9fca8e7d295c1d59801930b9dd05cca1e Mon Sep 17 00:00:00 2001 From: Adib Hanna Date: Thu, 5 Nov 2026 11:36:00 -0600 Subject: [PATCH 23/27] Fix(cloud): Cancel in the footer cannot sign out an account that just connected The footer can be behind the account: the browser may finish between the last look and the click, and Cancel then signed the new account out. It now reads the account status first. A connected account is left alone and a sync is requested, and only a sign-in still in progress is cancelled. --- .../app-core/src/components/StatusBar.test.ts | 24 +++++++++++++++++++ packages/app-core/src/lib/cloud-auto-sync.ts | 11 +++++++-- 2 files changed, 33 insertions(+), 2 deletions(-) diff --git a/packages/app-core/src/components/StatusBar.test.ts b/packages/app-core/src/components/StatusBar.test.ts index f49aab83..d04c3e76 100644 --- a/packages/app-core/src/components/StatusBar.test.ts +++ b/packages/app-core/src/components/StatusBar.test.ts @@ -21,6 +21,7 @@ const bridgeMocks = vi.hoisted(() => ({ resolveCloudConflict: vi.fn(), syncCloudVault: vi.fn(), logoutCloudAccount: vi.fn(async () => ({ state: "disconnected" })), + getCloudAccountStatus: vi.fn(async () => ({ state: "connecting" })), })); vi.mock("@zennotes/bridge-contract/bridge", () => ({ @@ -133,6 +134,29 @@ describe("cloud sync status time", () => { host.remove(); }); + it("does not sign out an account that connected while Cancel was on its way", async () => { + useCloudSyncStatusStore.setState({ + phase: "connecting", + vaultName: null, + lastSyncedAt: null, + error: null, + }); + bridgeMocks.logoutCloudAccount.mockClear(); + bridgeMocks.getCloudAccountStatus.mockResolvedValueOnce({ state: "connected" }); + const host = document.createElement("div"); + document.body.append(host); + const root = createRoot(host); + + act(() => root.render(createElement(StatusBar, { note: null }))); + await act(async () => + host.querySelector("[data-cloud-sync-action]")?.click(), + ); + expect(bridgeMocks.logoutCloudAccount).not.toHaveBeenCalled(); + + act(() => root.unmount()); + host.remove(); + }); + it("still offers nothing while a sync runs", () => { useCloudSyncStatusStore.setState({ phase: "syncing", diff --git a/packages/app-core/src/lib/cloud-auto-sync.ts b/packages/app-core/src/lib/cloud-auto-sync.ts index 46cf328e..0f498ba5 100644 --- a/packages/app-core/src/lib/cloud-auto-sync.ts +++ b/packages/app-core/src/lib/cloud-auto-sync.ts @@ -358,10 +358,17 @@ export async function connectCloudAccountFromStatusBar( /** The footer's way out of a sign-in that is waiting on the browser, which is the * same thing Settings → Cloud's Cancel sign-in does. */ export async function cancelCloudSignInFromStatusBar( - bridge: Pick = getZenBridge(), + bridge: Pick = getZenBridge(), ): Promise { try { - await bridge.logoutCloudAccount(); + // The footer can be behind: the browser may have finished between the last look + // and this click, and Cancel must not sign out an account that just connected. + const status = await bridge.getCloudAccountStatus(); + if (status.state === "connected") { + requestCloudAutoSync("account-change"); + return; + } + if (status.state === "connecting") await bridge.logoutCloudAccount(); markCloudSyncDisconnected(); } catch (error) { markCloudSyncDisconnected(failureText(cloudSyncErrorCopy(error))); From 69e42732606ded22db588a118bcedb2ab0671c9f Mon Sep 17 00:00:00 2001 From: Adib Hanna Date: Thu, 5 Nov 2026 11:36:00 -0600 Subject: [PATCH 24/27] Fix(sidebar): a tablet with a keyboard gets its cursor, and a Cmd selection stays A tablet in a keyboard case with no trackpad likely still reports a coarse pointer, so its keys moved a cursor nobody could see. `useKeyboardCursor` now draws the cursor once a key is pressed outside a text field, and stops when a finger touches the screen. A text field does not count, since that is where an on-screen keyboard types, so touch alone stays cursorless. This reaches every list that uses the hook. Its test file is rewritten and keeps both earlier cases. One row selected with Cmd lost its selection when a menu on it closed, because only a selection of two or more counted as the person's. Any selection the row was already in now stays. --- .../Sidebar.touch-highlight.test.ts | 25 ++++ packages/app-core/src/components/Sidebar.tsx | 4 +- .../app-core/src/lib/keyboard-cursor.test.ts | 109 +++++++++++++----- packages/app-core/src/lib/keyboard-cursor.ts | 55 ++++++++- 4 files changed, 156 insertions(+), 37 deletions(-) diff --git a/packages/app-core/src/components/Sidebar.touch-highlight.test.ts b/packages/app-core/src/components/Sidebar.touch-highlight.test.ts index f069e312..a687f49b 100644 --- a/packages/app-core/src/components/Sidebar.touch-highlight.test.ts +++ b/packages/app-core/src/components/Sidebar.touch-highlight.test.ts @@ -114,6 +114,31 @@ describe('Sidebar highlights', () => { expect(cursorRows()).toHaveLength(0) }) + it('draws the cursor on a touch device once a key is pressed', async () => { + coarse = true + await act(async () => root.render(createElement(Sidebar))) + expect(cursorRows()).toHaveLength(0) + await act(async () => { + document.body.dispatchEvent(new KeyboardEvent('keydown', { key: 'j', bubbles: true })) + }) + expect(cursorRows()).toHaveLength(1) + }) + + it('keeps one row selected with Cmd when a menu on it closes', async () => { + await act(async () => root.render(createElement(Sidebar))) + await act(async () => { + noteRow('Two').dispatchEvent( + new MouseEvent('click', { bubbles: true, cancelable: true, metaKey: true }) + ) + }) + expect(noteRow('Two').getAttribute('class')).toContain('bg-accent/[0.09]') + await openMenuOn(noteRow('Two')) + await act(async () => { + document.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape', bubbles: true })) + }) + expect(noteRow('Two').getAttribute('class')).toContain('bg-accent/[0.09]') + }) + it('takes the highlight off a row when its menu closes', async () => { await act(async () => root.render(createElement(Sidebar))) const row = noteRow('Two') diff --git a/packages/app-core/src/components/Sidebar.tsx b/packages/app-core/src/components/Sidebar.tsx index 63a01d00..9d2c4e39 100644 --- a/packages/app-core/src/components/Sidebar.tsx +++ b/packages/app-core/src/components/Sidebar.tsx @@ -918,9 +918,7 @@ export function Sidebar(): JSX.Element { const prepareContextSelection = useCallback( (item: SidebarSelectionItem): void => { const key = selectionKeyForItem(item); - const inSelection = - selectedSidebarKeysRef.current.has(key) && selectedSidebarKeysRef.current.size > 1; - menuOnlySelectionRef.current = inSelection ? null : key; + menuOnlySelectionRef.current = selectedSidebarKeysRef.current.has(key) ? null : key; setSelectedSidebarKeys((prev) => { if (prev.has(key) && prev.size > 1) return prev; return new Set([key]); diff --git a/packages/app-core/src/lib/keyboard-cursor.test.ts b/packages/app-core/src/lib/keyboard-cursor.test.ts index e5ee84d5..7be1e269 100644 --- a/packages/app-core/src/lib/keyboard-cursor.test.ts +++ b/packages/app-core/src/lib/keyboard-cursor.test.ts @@ -1,46 +1,99 @@ // @vitest-environment jsdom - import { act, createElement } from 'react' -import { createRoot } from 'react-dom/client' -import { afterEach, describe, expect, it } from 'vitest' +import { createRoot, type Root } from 'react-dom/client' +import { afterEach, beforeEach, describe, expect, it } from 'vitest' import { useKeyboardCursor } from './keyboard-cursor' -const original = Object.getOwnPropertyDescriptor(window, 'matchMedia') +;(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true + +function Probe(): JSX.Element { + return createElement('output', null, useKeyboardCursor() ? 'drawn' : 'hidden') +} + +let coarse = true +let host: HTMLDivElement +let root: Root + +const shown = (): string | null => host.textContent + +function press(key: string, target: EventTarget = document.body): void { + act(() => { + target.dispatchEvent(new KeyboardEvent('keydown', { key, bubbles: true })) + }) +} + +function touch(pointerType: string): void { + act(() => { + const event = new MouseEvent('pointerdown', { bubbles: true }) + Object.defineProperty(event, 'pointerType', { value: pointerType }) + document.body.dispatchEvent(event) + }) +} -function pointer(coarse: boolean): void { +beforeEach(() => { + coarse = true Object.defineProperty(window, 'matchMedia', { configurable: true, - value: (query: string) => ({ matches: coarse && query === '(pointer: coarse)' }) + value: (query: string) => ({ matches: coarse && query === '(pointer: coarse)', media: query }) }) -} + host = document.createElement('div') + document.body.append(host) + root = createRoot(host) + act(() => root.render(createElement(Probe))) +}) -async function read(): Promise { - ;(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true - let seen: boolean | undefined - function Probe(): null { - seen = useKeyboardCursor() - return null - } - const host = document.createElement('div') - const root = createRoot(host) - await act(async () => root.render(createElement(Probe))) +afterEach(() => { act(() => root.unmount()) - return seen! -} + host.remove() +}) describe('useKeyboardCursor', () => { - afterEach(() => { - if (original) Object.defineProperty(window, 'matchMedia', original) - else delete (window as { matchMedia?: unknown }).matchMedia + it('draws where the pointer is fine, whatever happens', () => { + act(() => root.unmount()) + coarse = false + root = createRoot(host) + act(() => root.render(createElement(Probe))) + expect(shown()).toBe('drawn') + touch('touch') + expect(shown()).toBe('drawn') + }) + + it('stays hidden on touch alone', () => { + expect(shown()).toBe('hidden') + touch('touch') + expect(shown()).toBe('hidden') + }) + + it('draws once a key is pressed on a tablet with a keyboard, until a finger comes back', () => { + press('j') + expect(shown()).toBe('drawn') + touch('mouse') + expect(shown()).toBe('drawn') + touch('touch') + expect(shown()).toBe('hidden') + }) + + it.each(['Shift', 'Meta', 'Unidentified'])('takes no notice of %s', (key) => { + press(key) + expect(shown()).toBe('hidden') }) - it('draws the cursor where there is a keyboard', async () => { - pointer(false) - expect(await read()).toBe(true) + it.each(['input', 'textarea'])('takes no notice of typing in a %s', (tag) => { + const field = document.createElement(tag) + document.body.append(field) + press('a', field) + field.remove() + expect(shown()).toBe('hidden') }) - it('draws none on a touch-first device, a phone', async () => { - pointer(true) - expect(await read()).toBe(false) + it('takes no notice of typing in the editor', () => { + const editor = document.createElement('div') + editor.setAttribute('contenteditable', 'true') + const line = document.createElement('div') + editor.append(line) + document.body.append(editor) + press('a', line) + editor.remove() + expect(shown()).toBe('hidden') }) }) diff --git a/packages/app-core/src/lib/keyboard-cursor.ts b/packages/app-core/src/lib/keyboard-cursor.ts index 6b954b43..676650b5 100644 --- a/packages/app-core/src/lib/keyboard-cursor.ts +++ b/packages/app-core/src/lib/keyboard-cursor.ts @@ -1,13 +1,56 @@ -import { useMemo } from 'react' +import { useSyncExternalStore } from 'react' import { isTouchPrimaryDevice } from './cm-vim-ime-guard' +// A tablet in a keyboard case with no trackpad still reports a coarse pointer, and +// its keys move the cursor. So a key outside a text field says a keyboard is there, +// and a finger on the screen says we are back to touch. A text field does not count: +// that is where an on-screen keyboard types. +let keysInUse = false +const listeners = new Set<() => void>() + +function setKeysInUse(next: boolean): void { + if (next === keysInUse) return + keysInUse = next + listeners.forEach((listener) => listener()) +} + +function isTextEntry(target: EventTarget | null): boolean { + if (!(target instanceof HTMLElement)) return false + return !!target.closest('input, textarea, select, [contenteditable="true"]') +} + +function onKeyDown(event: KeyboardEvent): void { + if (['Shift', 'Control', 'Alt', 'Meta', 'CapsLock', 'Unidentified', 'Dead'].includes(event.key)) return + if (!isTextEntry(event.target)) setKeysInUse(true) +} + +function onPointerDown(event: PointerEvent): void { + if (event.pointerType === 'touch') setKeysInUse(false) +} + +function subscribe(listener: () => void): () => void { + if (listeners.size === 0) { + window.addEventListener('keydown', onKeyDown, true) + window.addEventListener('pointerdown', onPointerDown, true) + } + listeners.add(listener) + return () => { + listeners.delete(listener) + if (listeners.size === 0) { + window.removeEventListener('keydown', onKeyDown, true) + window.removeEventListener('pointerdown', onPointerDown, true) + keysInUse = false + } + } +} + /** * Whether to draw the keyboard's cursor: the tint, ring or key hints on the - * row, card or cell the keys act on. A touch-first device (a phone) has no - * keyboard to move it, so lists, boards and grids there draw none. Only the - * drawing depends on this; the cursor itself, its refs and the scroll that - * follows it stay as they are. Read once per mount. + * row, card or cell the keys act on. A touch-first device has no keyboard to move + * it until one shows up, so lists, boards and grids there draw none until a key + * is pressed. Only the drawing depends on this; the cursor itself, its refs and the + * scroll that follows it stay as they are. */ export function useKeyboardCursor(): boolean { - return useMemo(() => !isTouchPrimaryDevice(), []) + return useSyncExternalStore(subscribe, () => keysInUse || !isTouchPrimaryDevice()) } From b5adb71e5a3a53978cd5376d8e69b9355c3348a1 Mon Sep 17 00:00:00 2001 From: Adib Hanna Date: Thu, 5 Nov 2026 11:36:00 -0600 Subject: [PATCH 25/27] Fix(mcp): a client with a path scope leaves a record page where it is MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `duplicate_note` on a record page under a scope wrote `Alpha copy.md` into the `.base` folder, where nothing is meant to be created. A rename, move, archive or trash took a page out of step with its database, whose schema names its pages and whose row titles follow them, and a scoped client may not even see that database. All five now refuse, as zn's 3333194 does. Reading and writing a page still work, a hidden page still answers as a missing one, an archived page cannot be restored through a scope since a destination never reaches a `.base` folder, and at full access a page stays an ordinary note. The Help says what a path scope can do with one. The check of a new note's final path stopped silently after 10,000 taken names and let the write go ahead. It now refuses. And a note's path now goes through `spell`, as zn's 265723f does, so an NFD `Café/x.md` beside `Cafe/x.md` is found. The shared fixture is unchanged. --- apps/desktop/src/mcp/record-pages.test.ts | 65 +++++++++++++++++++ .../src/mcp/scope-system-folders.test.ts | 35 ++++++++++ apps/desktop/src/mcp/scoped-backend.ts | 34 ++++++---- packages/app-core/src/lib/help.ts | 2 +- 4 files changed, 123 insertions(+), 13 deletions(-) diff --git a/apps/desktop/src/mcp/record-pages.test.ts b/apps/desktop/src/mcp/record-pages.test.ts index aa5c5c4d..5c4d9dfc 100644 --- a/apps/desktop/src/mcp/record-pages.test.ts +++ b/apps/desktop/src/mcp/record-pages.test.ts @@ -148,6 +148,71 @@ describe('what holds around a record page', () => { }) }) +describe('a record page stays where it is under a path scope', () => { + const SCHEMA = '{"pages":{"row-1":"Alpha.md"}}' + const scopes: [string, McpScopeFlags][] = [ + ['allow', { allow: ['memory', 'archive', 'trash', 'elsewhere'] }], + ['deny', { deny: ['memory/note.md'] }] + ] + const tools: [string, Record][] = [ + ['rename_note', { path: RECORD_PAGE, newTitle: 'Beta' }], + ['move_note', { path: RECORD_PAGE, targetFolder: 'inbox', targetSubpath: 'memory' }], + ['archive_note', { path: RECORD_PAGE }], + ['move_to_trash', { path: RECORD_PAGE }], + ['duplicate_note', { path: RECORD_PAGE }] + ] + + describe.each(scopes)('with %s', (_name, flags) => { + it.each(tools)('%s refuses', async (tool, args) => { + await fsp.mkdir(path.join(root, 'elsewhere'), { recursive: true }) + await fsp.mkdir(path.join(root, 'archive'), { recursive: true }) + await fsp.mkdir(path.join(root, 'trash'), { recursive: true }) + await fsp.writeFile(path.join(root, 'elsewhere', 'x.md'), 'x') + await fsp.writeFile(path.join(root, 'memory/Books.base/schema.json'), SCHEMA) + const client = await connect(flags) + const answer = await call(client, tool, args) + expect(answer.isError, answer.text).toBe(true) + expect(answer.text).toContain('record page') + expect(await exists(RECORD_PAGE)).toBe(true) + expect(await exists('memory/Books.base/Alpha copy.md')).toBe(false) + expect(await exists('memory/Books.base/Beta.md')).toBe(false) + expect(await exists('memory/Alpha.md')).toBe(false) + expect(await fsp.readFile(path.join(root, 'memory/Books.base/schema.json'), 'utf8')).toBe(SCHEMA) + const written = await call(client, 'write_note', { path: RECORD_PAGE, body: 'edited\n' }) + expect(written.isError, written.text).toBe(false) + }) + }) + + it('answers a hidden page as a missing one, before what it is', async () => { + const client = await connect({ deny: [RECORD_PAGE] }) + const answer = await call(client, 'duplicate_note', { path: RECORD_PAGE }) + expect(answer.text).toContain('Note not found') + }) + + it('refuses to bring an archived page back through a scope', async () => { + const archived = 'archive/memory/Books.base/Beta.md' + await fsp.mkdir(path.join(root, 'archive/memory/Books.base'), { recursive: true }) + await fsp.writeFile(path.join(root, archived), '# Beta\n') + const client = await connect({ deny: ['memory/note.md'] }) + const answer = await call(client, 'unarchive_note', { path: archived }) + expect(answer.isError, answer.text).toBe(true) + expect(await exists(archived)).toBe(true) + }) + + it('stays an ordinary note at full access', async () => { + const client = await connect() + const copied = await call(client, 'duplicate_note', { path: RECORD_PAGE }) + expect(copied.isError, copied.text).toBe(false) + expect(await exists('memory/Books.base/Alpha copy.md')).toBe(true) + }) + + it('stays an ordinary note to a scope that only limits access', async () => { + const client = await connect({ access: 'write' }) + const copied = await call(client, 'duplicate_note', { path: RECORD_PAGE }) + expect(copied.isError, copied.text).toBe(false) + }) +}) + describe('spell', () => { const nfc = 'Caf\u00e9' const nfd = 'Cafe\u0301' diff --git a/apps/desktop/src/mcp/scope-system-folders.test.ts b/apps/desktop/src/mcp/scope-system-folders.test.ts index 6b6864cf..3413524e 100644 --- a/apps/desktop/src/mcp/scope-system-folders.test.ts +++ b/apps/desktop/src/mcp/scope-system-folders.test.ts @@ -493,6 +493,41 @@ describe('what the review of the scope changes found', () => { expect(await exists(`${'x'.repeat(195)} copy.md`)).toBe(false) }) + it('refuses a create when it runs out of names to check against a deny entry', async () => { + await seed({ + '.zennotes/vault.json': ROOT_LAYOUT, + 'Pub/secret.md': 'hidden', + 'archive/Pub/draft.md': 'x' + }) + const client = await connect({ deny: ['Pub/secret.md'] }) + const lstat = fsp.lstat.bind(fsp) + vi.spyOn(fsp, 'lstat').mockImplementation((async (p: string, options: never) => { + if (String(p).includes(`${path.sep}draft`)) { + return { isSymbolicLink: () => false, isDirectory: () => false } + } + return await lstat(p, options) + }) as never) + const created = await call(client, 'create_note', { + folder: 'archive', + title: 'draft', + subpath: 'Pub' + }) + expect(created.isError, created.text).toBe(true) + expect(created.text).toContain('cannot put notes there') + }, 30000) + + it('reads a note by another Unicode form beside a folder one accent away', async () => { + await seed({ + '.zennotes/vault.json': ROOT_LAYOUT, + 'Cafe/x.md': 'plain', + 'Caf\u00e9/x.md': 'accent' + }) + const client = await connect({ allow: ['Caf\u00e9'] }) + const read = await call(client, 'read_note', { path: 'Cafe\u0301/x.md' }) + expect(read.isError, read.text).toBe(false) + expect(read.text).toContain('accent') + }) + it('finds the accented folder for an allow entry in another Unicode form', async () => { const nfc = 'Café' const nfd = 'Café' diff --git a/apps/desktop/src/mcp/scoped-backend.ts b/apps/desktop/src/mcp/scoped-backend.ts index 3bee337e..268dc6db 100644 --- a/apps/desktop/src/mcp/scoped-backend.ts +++ b/apps/desktop/src/mcp/scoped-backend.ts @@ -41,6 +41,7 @@ import { type SystemFolderPaths } from '@shared/system-folder-paths' import type { DatabaseOps } from '@shared/database-ops' +import { formDirContaining } from '@shared/databases' import type { VaultAssetMeta, VaultBackend, VaultDescription, VaultLayout } from '../cli/backend.js' import { RemoteRequestError } from '../main/remote/connection.js' import { @@ -91,6 +92,9 @@ const ASSETS_DIR = 'assets' const NO_COPY_NAME = 'This assistant cannot give the note that name.' +const RECORD_PAGE_STAYS_PUT = + "This assistant cannot rename, move, copy, archive or trash a database's record page." + /** How many taken names the check of a new note's path goes through. */ const MAX_LANDING_STEPS = 10000 @@ -376,18 +380,8 @@ class ScopeView { note(raw: string): NoteMeta | null { const clean = cleanRequest(raw) if (!clean) return null - let meta = this.byPath.get(clean) ?? null - if (!meta) { - const folded = foldMcpScopePath(clean) - let count = 0 - for (const [p, m] of this.byPath) { - if (foldMcpScopePath(p) === folded) { - meta = m - count += 1 - } - } - if (count !== 1) return null - } + const spelled = this.byPath.has(clean) ? clean : spell(clean, [...this.byPath.keys()]) + const meta = spelled == null ? null : (this.byPath.get(spelled) ?? null) return meta && this.visible(meta.path) ? meta : null } @@ -453,6 +447,8 @@ class ScopeView { } candidate = `${title} ${n}` } + // No name was checked, so none can be vouched for. + throw this.createRefusal() } /** Whether a system folder is one of those, however it is spelled. */ @@ -660,6 +656,15 @@ export class ScopedBackend implements VaultBackend { if (!mcpAccessAtLeast(this.scope.access, access)) throw new Error(mcpAccessRefusal(this.scope)) } + /** A client with a path scope may not see the database a page belongs to, whose + * schema names its pages and whose row titles follow them, so it reads and edits a + * page and leaves it where it is. Mirrors keepsRecordPage in ZenNotes/tui. */ + private keepRecordPage(meta: NoteMeta): void { + if (isMcpScopeRestricted(this.scope) && formDirContaining(meta.path)) { + throw new Error(RECORD_PAGE_STAYS_PUT) + } + } + /** Loads the view and resolves a note: the first step of every per-note * operation. */ private async noteFor(rel: string, access: McpAccess): Promise { @@ -930,6 +935,7 @@ export class ScopedBackend implements VaultBackend { */ renameNote = async (rel: string, nextTitle: string): Promise => { const meta = await this.noteFor(rel, 'write') + this.keepRecordPage(meta) const v = await this.load() const next = path.posix.join(path.posix.dirname(meta.path), `${sanitizeTitle(nextTitle)}.md`) if (!v.visible(next)) throw new Error('This assistant cannot give the note that name.') @@ -941,6 +947,7 @@ export class ScopedBackend implements VaultBackend { moveNote = async (rel: string, folder: NoteFolder, subpath: string): Promise => { const meta = await this.noteFor(rel, 'write') + this.keepRecordPage(meta) const v = await this.load() const destination = await v.destination(folder, subpath) const dir = joinRel(v.bucketDir(folder), destination) @@ -983,12 +990,14 @@ export class ScopedBackend implements VaultBackend { archiveNote = async (rel: string): Promise => { const meta = await this.noteFor(rel, 'write') + this.keepRecordPage(meta) await this.refuseLinkedExit(meta, 'archive') return await this.answerRefusal(() => this.inner.archiveNote(meta.path)) } moveToTrash = async (rel: string): Promise => { const meta = await this.noteFor(rel, 'write') + this.keepRecordPage(meta) await this.refuseLinkedExit(meta, 'trash') return await this.answerRefusal(() => this.inner.moveToTrash(meta.path)) } @@ -1019,6 +1028,7 @@ export class ScopedBackend implements VaultBackend { /** An allow entry can name one note, and its copy would land outside it. */ duplicateNote = async (rel: string): Promise => { const meta = await this.noteFor(rel, 'write') + this.keepRecordPage(meta) const v = await this.load() const ext = path.posix.extname(meta.path) const dir = path.posix.dirname(meta.path) diff --git a/packages/app-core/src/lib/help.ts b/packages/app-core/src/lib/help.ts index 3518eba5..a0c76935 100644 --- a/packages/app-core/src/lib/help.ts +++ b/packages/app-core/src/lib/help.ts @@ -1680,7 +1680,7 @@ export const HELP_CLI: HelpCard[] = [ title: 'Share part of a vault with an assistant', only: 'computer', body: - 'An assistant connected through MCP sees the whole vault unless its launch flags say otherwise, and the server enforces them on every tool: listings, search, tags, tasks, backlinks, assets, comments and error messages, so a hidden note cannot be listed or read another way. One thing can still show: a new or moved file takes a number when a hidden file already has its name. `--allow-path ` shares only that folder or note and what is inside it (repeat it for more), `--deny-path ` hides one even inside an allowed folder, `--read-only` offers the reading tools only, and `--access comment` adds the comment tools to them. Paths are vault-relative, as the tools report them: `Projects` in a vault that keeps notes at its root, `inbox/Projects` in one with an Inbox folder, and a system folder you moved under its own name (`99 Archive/Projects` shares that folder\'s archived notes). A path covers the folder and everything below it, never a sibling that only starts with the same letters, and case and accents do not matter, except that an `--allow-path` with accents shares only a folder that has them. A database\'s record pages are notes to an assistant, wherever the vault is, so a path can name one page or the whole `.base` folder; its `data.csv` and `schema.json` stay out of reach. `zn mcp` and the server bundled with the app take the same flags and give the same answers; add them after the command in the client\'s config, for example `"args": ["mcp", "--allow-path", "Projects", "--read-only"]`. Settings → MCP then shows that client as **Needs update**, and updating it there removes the flags.\n\nWhat the assistant gets: a hidden note answers exactly like a missing one (`Note not found`), and so do paths through a symbolic link, case variants and the `.zennotes` folder. Its errors and `vault_info` never show where the vault lives on disk, and `vault_info` lists what was shared under `access`. Tools it cannot use are not offered, and `empty_trash` never is once paths are restricted, since it would delete trashed notes it cannot see. New notes, moves and restores land only inside allowed folders, never through a symbolic link; archiving or trashing a note it can see is allowed even when the archive or trash is not shared, and the note then leaves its view. A `--deny-path` follows a note into the other system folders, however it names the folder: `Journal` also hides `archive/Journal`. `duplicate_note` refuses a copy that would land outside what is shared. A folder is renamed or deleted as a whole only when nothing inside it is hidden. Renaming a note rewrites `[[links]]` only in notes the assistant can see with `zn mcp`, and in none with the bundled server; on a self-hosted ZenNotes server, which rewrites links in every note, an assistant that sees part of the vault cannot rename notes. Attachments follow the same paths: a file is visible when its path is, and a hidden one answers `Asset not found`, like a missing one. Name them in the flags as `list_assets` shows them (`--allow-path assets`, `--deny-path assets/private`). `upload_asset` writes only to `assets`, so it needs that folder shared. Renaming or moving a file rewrites links only in notes the assistant can see. On a self-hosted server, an assistant that sees part of the vault cannot rename, move, read or copy a file; it can list, upload, delete and restore. `daily_note` gives no template, since a template is not filed under any folder a path can name, and where a note\'s folder is not shared it says so rather than offering to create it. A `--deny-path` that names nothing in the vault (renamed outside ZenNotes, or meant for another vault) shares nothing at all until it is fixed, so a rename never quietly reveals what it hid; the MCP server\'s log, which the client keeps, names the entry.\n\nThe flags govern the ZenNotes tools only. An assistant that can also run commands or read files (Claude Code, Codex, OpenCode) can still read the vault from disk.' + 'An assistant connected through MCP sees the whole vault unless its launch flags say otherwise, and the server enforces them on every tool: listings, search, tags, tasks, backlinks, assets, comments and error messages, so a hidden note cannot be listed or read another way. One thing can still show: a new or moved file takes a number when a hidden file already has its name. `--allow-path ` shares only that folder or note and what is inside it (repeat it for more), `--deny-path ` hides one even inside an allowed folder, `--read-only` offers the reading tools only, and `--access comment` adds the comment tools to them. Paths are vault-relative, as the tools report them: `Projects` in a vault that keeps notes at its root, `inbox/Projects` in one with an Inbox folder, and a system folder you moved under its own name (`99 Archive/Projects` shares that folder\'s archived notes). A path covers the folder and everything below it, never a sibling that only starts with the same letters, and case and accents do not matter, except that an `--allow-path` with accents shares only a folder that has them. A database\'s record pages are notes to an assistant, wherever the vault is, so a path can name one page or the whole `.base` folder; its `data.csv` and `schema.json` stay out of reach. With a path scope, on a local vault too, it sees and can write the record pages inside what it allows, but cannot rename, move, copy, archive or trash one. `zn mcp` and the server bundled with the app take the same flags and give the same answers; add them after the command in the client\'s config, for example `"args": ["mcp", "--allow-path", "Projects", "--read-only"]`. Settings → MCP then shows that client as **Needs update**, and updating it there removes the flags.\n\nWhat the assistant gets: a hidden note answers exactly like a missing one (`Note not found`), and so do paths through a symbolic link, case variants and the `.zennotes` folder. Its errors and `vault_info` never show where the vault lives on disk, and `vault_info` lists what was shared under `access`. Tools it cannot use are not offered, and `empty_trash` never is once paths are restricted, since it would delete trashed notes it cannot see. New notes, moves and restores land only inside allowed folders, never through a symbolic link; archiving or trashing a note it can see is allowed even when the archive or trash is not shared, and the note then leaves its view. A `--deny-path` follows a note into the other system folders, however it names the folder: `Journal` also hides `archive/Journal`. `duplicate_note` refuses a copy that would land outside what is shared. A folder is renamed or deleted as a whole only when nothing inside it is hidden. Renaming a note rewrites `[[links]]` only in notes the assistant can see with `zn mcp`, and in none with the bundled server; on a self-hosted ZenNotes server, which rewrites links in every note, an assistant that sees part of the vault cannot rename notes. Attachments follow the same paths: a file is visible when its path is, and a hidden one answers `Asset not found`, like a missing one. Name them in the flags as `list_assets` shows them (`--allow-path assets`, `--deny-path assets/private`). `upload_asset` writes only to `assets`, so it needs that folder shared. Renaming or moving a file rewrites links only in notes the assistant can see. On a self-hosted server, an assistant that sees part of the vault cannot rename, move, read or copy a file; it can list, upload, delete and restore. `daily_note` gives no template, since a template is not filed under any folder a path can name, and where a note\'s folder is not shared it says so rather than offering to create it. A `--deny-path` that names nothing in the vault (renamed outside ZenNotes, or meant for another vault) shares nothing at all until it is fixed, so a rename never quietly reveals what it hid; the MCP server\'s log, which the client keeps, names the entry.\n\nThe flags govern the ZenNotes tools only. An assistant that can also run commands or read files (Claude Code, Codex, OpenCode) can still read the vault from disk.' }, { title: 'Review an assistant’s edits', From 327367eade965c6f4d554d20eefbd951ef32bf9e Mon Sep 17 00:00:00 2001 From: Adib Hanna Date: Thu, 5 Nov 2026 11:50:33 -0600 Subject: [PATCH 26/27] Fix(tests): this branch's new source checks and reveal tests pass on Windows CI on Windows failed on three things this branch added, none of them product code. Two checks read `EditorPane.tsx` and looked for a newline, which a Windows checkout writes as CRLF. The third was an unhandled error: revealing a row focuses the sidebar with retries, those tests have no sidebar to settle on, and a retry fired after the test's window was torn down. The tests now wait those retries out. With EditorPane.tsx converted to CRLF, the source checks pass here too. --- .../src/components/EditorPane-toolbar-style.test.ts | 3 ++- .../app-core/src/components/PinnedReferencePane.test.ts | 7 ++++++- packages/app-core/src/lib/commands.test.ts | 8 +++++++- packages/app-core/src/lib/sidebar-restore.test.ts | 2 +- 4 files changed, 16 insertions(+), 4 deletions(-) diff --git a/packages/app-core/src/components/EditorPane-toolbar-style.test.ts b/packages/app-core/src/components/EditorPane-toolbar-style.test.ts index 677ff4d1..61206cf2 100644 --- a/packages/app-core/src/components/EditorPane-toolbar-style.test.ts +++ b/packages/app-core/src/components/EditorPane-toolbar-style.test.ts @@ -1,7 +1,8 @@ import { readFileSync } from 'node:fs' import { describe, expect, it } from 'vitest' -const source = readFileSync(new URL('./EditorPane.tsx', import.meta.url), 'utf8') +// Windows checks the source out with CRLF. +const source = readFileSync(new URL('./EditorPane.tsx', import.meta.url), 'utf8').replace(/\r\n/g, '\n') describe('the pane toolbar buttons', () => { it('drop their highlight at once when a panel closes', () => { diff --git a/packages/app-core/src/components/PinnedReferencePane.test.ts b/packages/app-core/src/components/PinnedReferencePane.test.ts index 0d2357c6..c70134cd 100644 --- a/packages/app-core/src/components/PinnedReferencePane.test.ts +++ b/packages/app-core/src/components/PinnedReferencePane.test.ts @@ -128,6 +128,10 @@ describe('PinnedReferencePane reveal in the sidebar', () => { let root: Root let originalState: ReturnType + // Revealing focuses the sidebar with retries, on timers that must not outlive the + // test's window: there is no sidebar here for them to settle on. + const focusRetriesDone = (): Promise => new Promise((resolve) => setTimeout(resolve, 250)) + beforeEach(() => { originalState = useStore.getState() Object.defineProperty(Range.prototype, 'getClientRects', { @@ -143,7 +147,8 @@ describe('PinnedReferencePane reveal in the sidebar', () => { root = createRoot(host) }) - afterEach(() => { + afterEach(async () => { + await focusRetriesDone() act(() => root.unmount()) host.remove() useStore.setState(originalState, true) diff --git a/packages/app-core/src/lib/commands.test.ts b/packages/app-core/src/lib/commands.test.ts index c0c23b89..6209294b 100644 --- a/packages/app-core/src/lib/commands.test.ts +++ b/packages/app-core/src/lib/commands.test.ts @@ -1,6 +1,6 @@ // @vitest-environment jsdom -import { beforeEach, describe, expect, it, vi } from 'vitest' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' function installZen(): void { Object.defineProperty(window, 'zen', { @@ -37,6 +37,12 @@ beforeEach(() => { }) describe('the Go commands', () => { + // Revealing focuses the sidebar with retries, on timers that must not outlive the + // test's window: there is no sidebar here for them to settle on. + const focusRetriesDone = (): Promise => new Promise((resolve) => setTimeout(resolve, 250)) + + afterEach(focusRetriesDone) + const note = { path: 'inbox/One.md', title: 'One', diff --git a/packages/app-core/src/lib/sidebar-restore.test.ts b/packages/app-core/src/lib/sidebar-restore.test.ts index 2cd7e269..eb33fa45 100644 --- a/packages/app-core/src/lib/sidebar-restore.test.ts +++ b/packages/app-core/src/lib/sidebar-restore.test.ts @@ -45,7 +45,7 @@ describe('EditorPane', () => { it('draws a control for both slots the tab strip does not cover', () => { expect(editorPaneSource).toMatch(/sidebarSlot === 'pane-strip' && \(/) expect(editorPaneSource).toMatch(/sidebarSlot === 'note-header' && \(/) - expect(editorPaneSource.match(/'Show sidebar',\n\s+getKeymapDisplay/g)).toHaveLength(3) + expect(editorPaneSource.match(/'Show sidebar',\r?\n\s+getKeymapDisplay/g)).toHaveLength(3) }) it('marks them so a phone layout, which has no sidebar, can leave them out', () => { From 8f20e8a9df254ed6c18338baa28f735fb278ba19 Mon Sep 17 00:00:00 2001 From: Adib Hanna Date: Thu, 5 Nov 2026 12:11:01 -0600 Subject: [PATCH 27/27] Fix(mcp): a scoped client cannot delete a record page or treat a database as a folder `delete_note` on a record page leaves the same stale `pages` entry in the database's `schema.json` as the other five, so under a path scope it now gets the same refusal, as zn's a702472 does. A full-access delete is unchanged. A local vault's folder listing already leaves `.base` folders out, so a scoped client there could not list, rename or delete one. A server's listing does include them, and through this server a scoped client on a remote vault could. Under a path scope they now drop out of the view on both, as zn's 3442647 does, while a path can still name one in an entry. At full access, or with a scope that only limits access, nothing changes. Two tests from the earlier record page commit passed for the wrong reason: they left out `confirm`, or spelled `oldSubpath` wrong, so the tool refused before any scope check. They now send real arguments and assert the scope's answer. The shared fixture is unchanged, and the Help says what a path scope can do. --- apps/desktop/src/mcp/record-pages.test.ts | 119 ++++++++++++++++++++-- apps/desktop/src/mcp/scoped-backend.ts | 26 +++-- packages/app-core/src/lib/help.ts | 2 +- 3 files changed, 130 insertions(+), 17 deletions(-) diff --git a/apps/desktop/src/mcp/record-pages.test.ts b/apps/desktop/src/mcp/record-pages.test.ts index 5c4d9dfc..9859812a 100644 --- a/apps/desktop/src/mcp/record-pages.test.ts +++ b/apps/desktop/src/mcp/record-pages.test.ts @@ -5,7 +5,8 @@ import { Client } from '@modelcontextprotocol/sdk/client/index.js' import { InMemoryTransport } from '@modelcontextprotocol/sdk/inMemory.js' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { newMcpScope, type McpScopeFlags } from '@shared/mcp-scope' -import { spell } from './scoped-backend' +import type { VaultBackend } from '../cli/backend' +import { ScopedBackend, spell } from './scoped-backend' import { runMcpServer } from './server' // A database's record pages are notes to an assistant on this machine, as they are @@ -121,11 +122,14 @@ describe('a record page and a path scope', () => { describe('what holds around a record page', () => { it('keeps the folder whole and the database closed', async () => { const client = await connect({ deny: [RECORD_PAGE] }) - expect((await call(client, 'delete_folder', { folder: 'inbox', subpath: 'memory' })).isError).toBe(true) - expect( - (await call(client, 'rename_folder', { folder: 'inbox', subpath: 'memory', newSubpath: 'moved' })) - .isError - ).toBe(true) + const deleted = await call(client, 'delete_folder', { folder: 'inbox', subpath: 'memory', confirm: true }) + expect(deleted.text).toContain('cannot delete that folder') + const renamed = await call(client, 'rename_folder', { + folder: 'inbox', + oldSubpath: 'memory', + newSubpath: 'moved' + }) + expect(renamed.text).toContain('cannot rename that folder') expect((await call(client, 'read_asset', { path: 'memory/Books.base/data.csv' })).isError).toBe(true) expect( (await call(client, 'create_note', { folder: 'inbox', subpath: 'memory/Books.base', title: 'Nope' })) @@ -137,8 +141,12 @@ describe('what holds around a record page', () => { it('does not let a client that sees a database delete it as a folder', async () => { const client = await connect({ allow: ['memory/Books.base'] }) - const deleted = await call(client, 'delete_folder', { folder: 'inbox', subpath: 'memory/Books.base' }) - expect(deleted.isError).toBe(true) + const deleted = await call(client, 'delete_folder', { + folder: 'inbox', + subpath: 'memory/Books.base', + confirm: true + }) + expect(deleted.text).toContain('Folder not found') expect(await exists(RECORD_PAGE)).toBe(true) }) @@ -159,7 +167,8 @@ describe('a record page stays where it is under a path scope', () => { ['move_note', { path: RECORD_PAGE, targetFolder: 'inbox', targetSubpath: 'memory' }], ['archive_note', { path: RECORD_PAGE }], ['move_to_trash', { path: RECORD_PAGE }], - ['duplicate_note', { path: RECORD_PAGE }] + ['duplicate_note', { path: RECORD_PAGE }], + ['delete_note', { path: RECORD_PAGE, confirm: true }] ] describe.each(scopes)('with %s', (_name, flags) => { @@ -204,6 +213,9 @@ describe('a record page stays where it is under a path scope', () => { const copied = await call(client, 'duplicate_note', { path: RECORD_PAGE }) expect(copied.isError, copied.text).toBe(false) expect(await exists('memory/Books.base/Alpha copy.md')).toBe(true) + const deleted = await call(client, 'delete_note', { path: RECORD_PAGE, confirm: true }) + expect(deleted.isError, deleted.text).toBe(false) + expect(await exists(RECORD_PAGE)).toBe(false) }) it('stays an ordinary note to a scope that only limits access', async () => { @@ -213,6 +225,95 @@ describe('a record page stays where it is under a path scope', () => { }) }) +describe('a database is not a folder to a client with a path scope', () => { + const scopes: [string, McpScopeFlags][] = [ + ['allow its folder', { allow: ['memory'] }], + ['allow it', { allow: ['memory/Books.base'] }], + ['deny another note', { deny: ['memory/note.md'] }], + ['deny another database', { deny: ['memory/Empty.base'] }] + ] + const tools: [string, Record][] = [ + ['delete_folder', { folder: 'inbox', subpath: 'memory/Books.base', confirm: true }], + ['rename_folder', { folder: 'inbox', oldSubpath: 'memory/Books.base', newSubpath: 'Plain' }], + ['rename_folder', { folder: 'inbox', oldSubpath: 'memory/Books.base', newSubpath: 'memory/Moved.base' }] + ] + + describe.each(scopes)('on a local vault, with %s', (_name, flags) => { + it('lists none, and neither renames nor deletes one', async () => { + const client = await connect(flags) + expect((await call(client, 'list_folders')).text).not.toContain('.base') + for (const [tool, args] of tools) { + const answer = await call(client, tool, args) + expect(answer.isError, `${tool}: ${answer.text}`).toBe(true) + expect(answer.text).toContain('Folder not found') + } + expect(await exists(RECORD_PAGE)).toBe(true) + expect(await exists('memory/Books.base/data.csv')).toBe(true) + expect(await exists('Plain')).toBe(false) + expect(await exists('memory/Moved.base')).toBe(false) + }) + }) + + // A server's listing does show them, so this is where the filter does the work. + function serverVault(): { + backend: VaultBackend + renameFolder: ReturnType + deleteFolder: ReturnType + } { + const renameFolder = vi.fn(async () => 'moved') + const deleteFolder = vi.fn(async () => {}) + const backend = { + kind: 'remote', + root: '', + label: 'server', + vaultLayout: async () => ({ primaryNotesLocation: 'root', systemFolderPaths: {} }), + marksLinks: async () => true, + linkedSystemFolders: async () => [], + listNotes: async () => [ + { path: RECORD_PAGE, title: 'Alpha', folder: 'inbox' }, + { path: 'memory/note.md', title: 'note', folder: 'inbox' } + ], + listFolders: async () => [ + { folder: 'inbox', subpath: 'memory' }, + { folder: 'inbox', subpath: 'memory/Books.base' }, + { folder: 'inbox', subpath: 'memory/Empty.base' } + ], + listAssets: async () => [], + renameFolder, + deleteFolder + } as unknown as VaultBackend + return { backend, renameFolder, deleteFolder } + } + + describe.each(scopes)('on a server, with %s', (_name, flags) => { + it('lists none, and neither renames nor deletes one', async () => { + const { backend, renameFolder, deleteFolder } = serverVault() + const scoped = new ScopedBackend(backend, newMcpScope(flags)) + expect(JSON.stringify(await scoped.listFolders())).not.toContain('.base') + await expect(scoped.deleteFolder('inbox', 'memory/Books.base')).rejects.toThrow('Folder not found') + await expect(scoped.renameFolder('inbox', 'memory/Books.base', 'Plain')).rejects.toThrow( + 'Folder not found' + ) + expect(deleteFolder).not.toHaveBeenCalled() + expect(renameFolder).not.toHaveBeenCalled() + }) + }) + + it('leaves a server listing whole for a scope that only limits access', async () => { + const { backend, deleteFolder } = serverVault() + const scoped = new ScopedBackend(backend, newMcpScope({ access: 'write' })) + expect(JSON.stringify(await scoped.listFolders())).toContain('Books.base') + await scoped.deleteFolder('inbox', 'memory/Books.base') + expect(deleteFolder).toHaveBeenCalledOnce() + }) + + it('can still name a server database in a deny entry', async () => { + const { backend } = serverVault() + const scoped = new ScopedBackend(backend, newMcpScope({ deny: ['memory/Empty.base'] })) + expect((await scoped.listNotes()).map((note) => note.path)).toContain(RECORD_PAGE) + }) +}) + describe('spell', () => { const nfc = 'Caf\u00e9' const nfd = 'Cafe\u0301' diff --git a/apps/desktop/src/mcp/scoped-backend.ts b/apps/desktop/src/mcp/scoped-backend.ts index 268dc6db..94cd670f 100644 --- a/apps/desktop/src/mcp/scoped-backend.ts +++ b/apps/desktop/src/mcp/scoped-backend.ts @@ -93,7 +93,7 @@ const ASSETS_DIR = 'assets' const NO_COPY_NAME = 'This assistant cannot give the note that name.' const RECORD_PAGE_STAYS_PUT = - "This assistant cannot rename, move, copy, archive or trash a database's record page." + "This assistant cannot rename, move, copy, archive, trash or delete a database's record page." /** How many taken names the check of a new note's path goes through. */ const MAX_LANDING_STEPS = 10000 @@ -546,7 +546,14 @@ export class ScopedBackend implements VaultBackend { if (!linkedFolders) throw new Error(UNMARKED_LINKS) const listed = await this.inner.listNotes() const notes = restricted ? listed.filter((note) => !note.symlink) : listed - const folders = await this.inner.listFolders() + // A server lists a database folder as a folder, for its renderer. To a client with + // a path scope it is not one: it could delete the database, or rename it into a + // plain folder, with no sight of what else uses it. As on a local vault, a path + // can still name it. Mirrors build in ZenNotes/tui. + const allFolders = await this.inner.listFolders() + const folders = restricted + ? allFolders.filter((entry) => !formDirContaining(entry.subpath)) + : allFolders const v = new ScopeView( layout.systemFolderPaths, layout.primaryNotesLocation === 'root', @@ -571,9 +578,11 @@ export class ScopedBackend implements VaultBackend { known.push(...v.dirs) // A database folder is there to name, where a folder listing leaves it out, even // with no record page yet. It stays out of v.dirs: it takes no notes and no moves. - for (const entry of (await this.inner.listDatabaseDirs?.()) ?? []) { - known.push(v.folderRel(entry)) - } + const databaseDirs = [ + ...allFolders.filter((entry) => !folders.includes(entry)), + ...((await this.inner.listDatabaseDirs?.()) ?? []) + ] + for (const entry of databaseDirs) known.push(v.folderRel(entry)) // An entry can name an attachment folder or an asset, which the listings // above do not show, so those are read only for an entry they did not find. @@ -1043,8 +1052,11 @@ export class ScopedBackend implements VaultBackend { return copy } - deleteNote = async (rel: string): Promise => - await this.inner.deleteNote((await this.noteFor(rel, 'write')).path) + deleteNote = async (rel: string): Promise => { + const meta = await this.noteFor(rel, 'write') + this.keepRecordPage(meta) + await this.inner.deleteNote(meta.path) + } emptyTrash = async (): Promise => { this.need('write') diff --git a/packages/app-core/src/lib/help.ts b/packages/app-core/src/lib/help.ts index a0c76935..a17ddd2e 100644 --- a/packages/app-core/src/lib/help.ts +++ b/packages/app-core/src/lib/help.ts @@ -1680,7 +1680,7 @@ export const HELP_CLI: HelpCard[] = [ title: 'Share part of a vault with an assistant', only: 'computer', body: - 'An assistant connected through MCP sees the whole vault unless its launch flags say otherwise, and the server enforces them on every tool: listings, search, tags, tasks, backlinks, assets, comments and error messages, so a hidden note cannot be listed or read another way. One thing can still show: a new or moved file takes a number when a hidden file already has its name. `--allow-path ` shares only that folder or note and what is inside it (repeat it for more), `--deny-path ` hides one even inside an allowed folder, `--read-only` offers the reading tools only, and `--access comment` adds the comment tools to them. Paths are vault-relative, as the tools report them: `Projects` in a vault that keeps notes at its root, `inbox/Projects` in one with an Inbox folder, and a system folder you moved under its own name (`99 Archive/Projects` shares that folder\'s archived notes). A path covers the folder and everything below it, never a sibling that only starts with the same letters, and case and accents do not matter, except that an `--allow-path` with accents shares only a folder that has them. A database\'s record pages are notes to an assistant, wherever the vault is, so a path can name one page or the whole `.base` folder; its `data.csv` and `schema.json` stay out of reach. With a path scope, on a local vault too, it sees and can write the record pages inside what it allows, but cannot rename, move, copy, archive or trash one. `zn mcp` and the server bundled with the app take the same flags and give the same answers; add them after the command in the client\'s config, for example `"args": ["mcp", "--allow-path", "Projects", "--read-only"]`. Settings → MCP then shows that client as **Needs update**, and updating it there removes the flags.\n\nWhat the assistant gets: a hidden note answers exactly like a missing one (`Note not found`), and so do paths through a symbolic link, case variants and the `.zennotes` folder. Its errors and `vault_info` never show where the vault lives on disk, and `vault_info` lists what was shared under `access`. Tools it cannot use are not offered, and `empty_trash` never is once paths are restricted, since it would delete trashed notes it cannot see. New notes, moves and restores land only inside allowed folders, never through a symbolic link; archiving or trashing a note it can see is allowed even when the archive or trash is not shared, and the note then leaves its view. A `--deny-path` follows a note into the other system folders, however it names the folder: `Journal` also hides `archive/Journal`. `duplicate_note` refuses a copy that would land outside what is shared. A folder is renamed or deleted as a whole only when nothing inside it is hidden. Renaming a note rewrites `[[links]]` only in notes the assistant can see with `zn mcp`, and in none with the bundled server; on a self-hosted ZenNotes server, which rewrites links in every note, an assistant that sees part of the vault cannot rename notes. Attachments follow the same paths: a file is visible when its path is, and a hidden one answers `Asset not found`, like a missing one. Name them in the flags as `list_assets` shows them (`--allow-path assets`, `--deny-path assets/private`). `upload_asset` writes only to `assets`, so it needs that folder shared. Renaming or moving a file rewrites links only in notes the assistant can see. On a self-hosted server, an assistant that sees part of the vault cannot rename, move, read or copy a file; it can list, upload, delete and restore. `daily_note` gives no template, since a template is not filed under any folder a path can name, and where a note\'s folder is not shared it says so rather than offering to create it. A `--deny-path` that names nothing in the vault (renamed outside ZenNotes, or meant for another vault) shares nothing at all until it is fixed, so a rename never quietly reveals what it hid; the MCP server\'s log, which the client keeps, names the entry.\n\nThe flags govern the ZenNotes tools only. An assistant that can also run commands or read files (Claude Code, Codex, OpenCode) can still read the vault from disk.' + 'An assistant connected through MCP sees the whole vault unless its launch flags say otherwise, and the server enforces them on every tool: listings, search, tags, tasks, backlinks, assets, comments and error messages, so a hidden note cannot be listed or read another way. One thing can still show: a new or moved file takes a number when a hidden file already has its name. `--allow-path ` shares only that folder or note and what is inside it (repeat it for more), `--deny-path ` hides one even inside an allowed folder, `--read-only` offers the reading tools only, and `--access comment` adds the comment tools to them. Paths are vault-relative, as the tools report them: `Projects` in a vault that keeps notes at its root, `inbox/Projects` in one with an Inbox folder, and a system folder you moved under its own name (`99 Archive/Projects` shares that folder\'s archived notes). A path covers the folder and everything below it, never a sibling that only starts with the same letters, and case and accents do not matter, except that an `--allow-path` with accents shares only a folder that has them. A database\'s record pages are notes to an assistant, wherever the vault is, so a path can name one page or the whole `.base` folder; its `data.csv` and `schema.json` stay out of reach. With a path scope, on a local vault too, it sees and can write the record pages inside what it allows, but cannot rename, move, copy, archive, trash or delete one, or treat a `.base` folder as a folder. `zn mcp` and the server bundled with the app take the same flags and give the same answers; add them after the command in the client\'s config, for example `"args": ["mcp", "--allow-path", "Projects", "--read-only"]`. Settings → MCP then shows that client as **Needs update**, and updating it there removes the flags.\n\nWhat the assistant gets: a hidden note answers exactly like a missing one (`Note not found`), and so do paths through a symbolic link, case variants and the `.zennotes` folder. Its errors and `vault_info` never show where the vault lives on disk, and `vault_info` lists what was shared under `access`. Tools it cannot use are not offered, and `empty_trash` never is once paths are restricted, since it would delete trashed notes it cannot see. New notes, moves and restores land only inside allowed folders, never through a symbolic link; archiving or trashing a note it can see is allowed even when the archive or trash is not shared, and the note then leaves its view. A `--deny-path` follows a note into the other system folders, however it names the folder: `Journal` also hides `archive/Journal`. `duplicate_note` refuses a copy that would land outside what is shared. A folder is renamed or deleted as a whole only when nothing inside it is hidden. Renaming a note rewrites `[[links]]` only in notes the assistant can see with `zn mcp`, and in none with the bundled server; on a self-hosted ZenNotes server, which rewrites links in every note, an assistant that sees part of the vault cannot rename notes. Attachments follow the same paths: a file is visible when its path is, and a hidden one answers `Asset not found`, like a missing one. Name them in the flags as `list_assets` shows them (`--allow-path assets`, `--deny-path assets/private`). `upload_asset` writes only to `assets`, so it needs that folder shared. Renaming or moving a file rewrites links only in notes the assistant can see. On a self-hosted server, an assistant that sees part of the vault cannot rename, move, read or copy a file; it can list, upload, delete and restore. `daily_note` gives no template, since a template is not filed under any folder a path can name, and where a note\'s folder is not shared it says so rather than offering to create it. A `--deny-path` that names nothing in the vault (renamed outside ZenNotes, or meant for another vault) shares nothing at all until it is fixed, so a rename never quietly reveals what it hid; the MCP server\'s log, which the client keeps, names the entry.\n\nThe flags govern the ZenNotes tools only. An assistant that can also run commands or read files (Claude Code, Codex, OpenCode) can still read the vault from disk.' }, { title: 'Review an assistant’s edits',