Build your personal knowledge base with Trilium Notes
TypeScript electronelectron-appknowledge-baseknowledge-graphknowledge-managementknowledge-management-graphlocal-firstnote-managmentnote-takernote-takingnotebooknotesnotes-apppersonal-knowledge-basepersonal-wikiscriptableself-hostedself-hostingwiki
test(client): automated review
Elian Doran19f7bbf1dd98
diff --git a/apps/client/src/services/attribute_renderer.spec.ts b/apps/client/src/services/attribute_renderer.spec.tsindex 276dc4dcab..4cf0916017 100644--- a/apps/client/src/services/attribute_renderer.spec.ts+++ b/apps/client/src/services/attribute_renderer.spec.ts@@ -117,6 +117,29 @@ describe("renderAttributes", () => {const $empty = await attributeRenderer.renderAttributes([], false);expect($empty.text()).toBe("");});++ it("strips the per-attribute wrapping span but keeps the relation reference link", async () => {+ const target = buildNote({ title: "Target Note" });+ const $container = await attributeRenderer.renderAttributes(+ [attr({ type: "relation", name: "myrel", value: target.noteId })],+ false+ );++ expect($container.text()).toBe("~myrel=Target Note");++ // The reference link <a> survives the .html() inner-HTML extraction...+ const $link = $container.find("a.reference-link");+ expect($link.length).toBe(1);+ expect($link.attr("href")).toBe(`#root/${target.noteId}`);+ expect($link.text()).toBe("Target Note");++ // ...but the per-attribute wrapping <span> emitted by renderAttribute is stripped:+ // the only span is $container itself (rendered-note-attributes), with no nested spans.+ expect($container.is("span.rendered-note-attributes")).toBe(true);+ expect($container.find("span").length).toBe(0);+ // The reference link is a direct child of the container, not nested in a span.+ expect($container.children("a.reference-link").length).toBe(1);+ });});describe("renderNormalAttributes", () => {diff --git a/apps/client/src/services/attributes.spec.ts b/apps/client/src/services/attributes.spec.tsindex 80694427bf..6b30bcbae0 100644--- a/apps/client/src/services/attributes.spec.ts+++ b/apps/client/src/services/attributes.spec.ts@@ -329,6 +329,11 @@ describe("toggleDangerousAttribute", () => {isInheritable: false}, undefined);expect(server.remove).toHaveBeenCalledWith(`notes/${note.noteId}/attributes/${attrId}`);+ // The renamed attribute must be PUT before the original is removed, to avoid a flicker+ // where there would momentarily be no active content attribute.+ const putMock = server.put as unknown as ReturnType<typeof vi.fn>;+ const removeMock = server.remove as unknown as ReturnType<typeof vi.fn>;+ expect(putMock.mock.invocationCallOrder[0]).toBeLessThan(removeMock.mock.invocationCallOrder[0]);});it("enables a disabled relation by stripping the prefix", async () => {@@ -342,6 +347,11 @@ describe("toggleDangerousAttribute", () => {isInheritable: false});expect(server.remove).toHaveBeenCalledWith(`notes/${note.noteId}/attributes/${attrId}`);+ // The renamed attribute must be PUT before the original is removed, to avoid a flicker+ // where there would momentarily be no active content attribute.+ const putMock = server.put as unknown as ReturnType<typeof vi.fn>;+ const removeMock = server.remove as unknown as ReturnType<typeof vi.fn>;+ expect(putMock.mock.invocationCallOrder[0]).toBeLessThan(removeMock.mock.invocationCallOrder[0]);});it("skips attributes whose name already matches the desired state", async () => {diff --git a/apps/client/src/services/bulk_action.spec.ts b/apps/client/src/services/bulk_action.spec.tsindex a01d665367..125054b577 100644--- a/apps/client/src/services/bulk_action.spec.ts+++ b/apps/client/src/services/bulk_action.spec.ts@@ -6,6 +6,18 @@ import noteAttributeCache from "./note_attribute_cache.js";import { buildNote } from "../test/easy-froca";import bulkActionService, { executeBulkActions } from "./bulk_action";import AddLabelBulkAction from "../widgets/bulk_actions/label/add_label";+import UpdateLabelValueBulkAction from "../widgets/bulk_actions/label/update_label_value";+import RenameLabelBulkAction from "../widgets/bulk_actions/label/rename_label";+import DeleteLabelBulkAction from "../widgets/bulk_actions/label/delete_label";+import AddRelationBulkAction from "../widgets/bulk_actions/relation/add_relation";+import UpdateRelationTargetBulkAction from "../widgets/bulk_actions/relation/update_relation_target";+import RenameRelationBulkAction from "../widgets/bulk_actions/relation/rename_relation";+import DeleteRelationBulkAction from "../widgets/bulk_actions/relation/delete_relation";+import RenameNoteBulkAction from "../widgets/bulk_actions/note/rename_note";+import MoveNoteBulkAction from "../widgets/bulk_actions/note/move_note";+import DeleteNoteBulkAction from "../widgets/bulk_actions/note/delete_note";+import DeleteRevisionsBulkAction from "../widgets/bulk_actions/note/delete_revisions";+import ExecuteScriptBulkAction from "../widgets/bulk_actions/execute_script";import server from "./server.js";import ws from "./ws.js";import toast from "./toast.js";@@ -43,9 +55,27 @@ describe("bulk_action service", () => {expect(bulkActionService.ACTION_CLASSES).toContain(AddLabelBulkAction);// Four groups: labels, relations, notes, other.expect(bulkActionService.ACTION_GROUPS).toHaveLength(4);- expect(bulkActionService.ACTION_GROUPS[3].actions).toEqual([- bulkActionService.ACTION_GROUPS[3].actions[0]+ // Each group contains exactly its concrete action classes, in order.+ expect(bulkActionService.ACTION_GROUPS[0].actions).toEqual([+ AddLabelBulkAction,+ UpdateLabelValueBulkAction,+ RenameLabelBulkAction,+ DeleteLabelBulkAction]);+ expect(bulkActionService.ACTION_GROUPS[1].actions).toEqual([+ AddRelationBulkAction,+ UpdateRelationTargetBulkAction,+ RenameRelationBulkAction,+ DeleteRelationBulkAction+ ]);+ expect(bulkActionService.ACTION_GROUPS[2].actions).toEqual([+ RenameNoteBulkAction,+ MoveNoteBulkAction,+ DeleteNoteBulkAction,+ DeleteRevisionsBulkAction+ ]);+ // The "other" group contains exactly ExecuteScriptBulkAction.+ expect(bulkActionService.ACTION_GROUPS[3].actions).toEqual([ExecuteScriptBulkAction]);});it("addAction posts an action attribute and waits for sync", async () => {@@ -68,7 +98,7 @@ describe("bulk_action service", () => {const note = buildNote({ title: "Note with actions" });// Valid known action.- addActionLabel(note.noteId, JSON.stringify({ name: "addLabel", labelName: "foo" }));+ const validAttr = addActionLabel(note.noteId, JSON.stringify({ name: "addLabel", labelName: "foo" }));// Invalid JSON -> JSON.parse throws -> catch branch -> null.addActionLabel(note.noteId, "{not-valid-json");// Valid JSON but unknown action name -> no ActionClass -> null.@@ -80,6 +110,11 @@ describe("bulk_action service", () => {expect(actions).toHaveLength(1);expect(actions[0]).toBeInstanceOf(AddLabelBulkAction);expect(actions[0].actionDef).toEqual({ name: "addLabel", labelName: "foo" });+ // The constructor threads the producing "action" label into this.attribute,+ // which saveAction/deleteAction later use to PUT/DELETE against the server.+ expect(actions[0].attribute).toBe(validAttr);+ expect(actions[0].attribute.attributeId).toBe(validAttr.attributeId);+ expect(actions[0].attribute.value).toBe(JSON.stringify({ name: "addLabel", labelName: "foo" }));// Both failures were logged.expect(logError).toHaveBeenCalledTimes(2);expect(logError.mock.calls[0][0]).toContain("failed with error");diff --git a/apps/client/src/services/bundle.spec.ts b/apps/client/src/services/bundle.spec.tsindex f063fe639d..668e89889e 100644--- a/apps/client/src/services/bundle.spec.ts+++ b/apps/client/src/services/bundle.spec.ts@@ -1,6 +1,7 @@import { beforeAll, beforeEach, describe, expect, it, vi } from "vitest";import { buildNote } from "../test/easy-froca";+import { ReactWrappedWidget } from "../widgets/basic_widget.js";import bundleService, { Bundle, executeBundle, executeBundleWithoutErrorHandling, WidgetsByParent } from "./bundle";import server from "./server.js";import * as toast from "./toast";@@ -85,8 +86,11 @@ describe("executeStartupBundles (default export)", () => {it("requests non-mobile startup scripts and executes each bundle", async () => {const id = buildNote({ title: "Startup note" }).noteId;+ // The script runs inside the eval'd bundle body, so a write to `window` is an observable+ // side effect proving the bundle was actually executed (not merely fetched).+ delete (window as any).__startupRan;const bundles: Bundle[] = [{- script: `api.__startupRan = true;`,+ script: `window.__startupRan = true;`,html: "",noteId: id,allNoteIds: [id]@@ -98,6 +102,9 @@ describe("executeStartupBundles (default export)", () => {await bundleService.executeStartupBundles();expect(getSpy).toHaveBeenCalledWith("script/startup");+ // The for-loop that calls executeBundle(bundle) actually ran the seeded script.+ expect((window as any).__startupRan).toBe(true);+ delete (window as any).__startupRan;});it("requests mobile startup scripts when on mobile", async () => {@@ -208,7 +215,13 @@ describe("WidgetsByParent", () => {} as any);const widgets = w.get("right-pane");- expect(widgets.length).toBeGreaterThanOrEqual(1);+ expect(widgets).toHaveLength(1);+ // No position was supplied, so the `if (preactWidget.position)` branch is skipped and the+ // wrapped widget keeps the ReactWrappedWidget default `_position` (undefined) rather than+ // being overridden to a falsy value.+ const wrapped = widgets[0] as any;+ expect(wrapped).toBeInstanceOf(ReactWrappedWidget);+ expect(wrapped.position).toBeUndefined();});});diff --git a/apps/client/src/services/clipboard.spec.ts b/apps/client/src/services/clipboard.spec.tsindex 9b3c85f3b7..1363385cc6 100644--- a/apps/client/src/services/clipboard.spec.ts+++ b/apps/client/src/services/clipboard.spec.ts@@ -83,7 +83,7 @@ describe("copy", () => {});it("writes reference links to the system clipboard on Electron", async () => {- const { childBranchId } = buildParentWithChild();+ const { parent, childBranchId, childNoteId } = buildParentWithChild();(window as any).electronApi = {};const writeSpy = vi.fn(async (..._args: any[]) => {});@@ -101,12 +101,24 @@ describe("copy", () => {await clipboard.copy([childBranchId]);+ // The link key is `${branch.parentNoteId}/${branch.noteId}` with the reference-link option.expect(linkService.createLink).toHaveBeenCalledTimes(1);+ expect(linkService.createLink).toHaveBeenCalledWith(`${parent.noteId}/${childNoteId}`, { referenceLink: true });+expect(writeSpy).toHaveBeenCalledTimes(1);const items = writeSpy.mock.calls[0][0] as any[];expect(items).toHaveLength(1);- expect(items[0].data["text/html"]).toBeInstanceOf(Blob);- expect(items[0].data["text/plain"]).toBeInstanceOf(Blob);++ // The html slot carries the link's outerHTML; the plain slot carries its text.+ const htmlBlob = items[0].data["text/html"] as Blob;+ const plainBlob = items[0].data["text/plain"] as Blob;+ expect(htmlBlob).toBeInstanceOf(Blob);+ expect(plainBlob).toBeInstanceOf(Blob);+ expect(htmlBlob.type).toBe("text/html");+ expect(plainBlob.type).toBe("text/plain");+ expect(await htmlBlob.text()).toBe(link[0].outerHTML);+ expect(await plainBlob.text()).toBe("Child link");+expect(toastService.showMessage).toHaveBeenCalledTimes(1);});});diff --git a/apps/client/src/services/command_registry.spec.ts b/apps/client/src/services/command_registry.spec.tsindex 7950078561..567ca1c73b 100644--- a/apps/client/src/services/command_registry.spec.ts+++ b/apps/client/src/services/command_registry.spec.ts@@ -363,6 +363,12 @@ describe("CommandRegistry executeCommand", () => {keyboardAction: action({ scope: "text-detail" })});await registry.executeCommand("textCmd");+ // executeCommand does NOT await executeWithTextDetail (source line 248), and+ // executeWithTextDetail internally awaits getTypeWidget(). Flush the+ // microtask/macrotask queue so the fire-and-forget widgetTrigger call has+ // definitely run before we assert, rather than relying on incidental+ // microtask ordering of a single await hop.+ await new Promise((r) => setTimeout(r, 0));expect(widgetTrigger).toHaveBeenCalledWith("addLinkToText", { ntxId: "ntx-1" });});diff --git a/apps/client/src/services/content_renderer_text.spec.ts b/apps/client/src/services/content_renderer_text.spec.tsindex e5313add43..c57b935f93 100644--- a/apps/client/src/services/content_renderer_text.spec.ts+++ b/apps/client/src/services/content_renderer_text.spec.ts@@ -17,6 +17,19 @@ vi.mock("mermaid", () => ({}}));+// Spy on the KaTeX auto-render entry point so we can assert that+// `postProcessRichContent` only invokes it when a `span.math-tex` is present.+// The original module is kept intact (default export, CSS side-effects) so the+// rest of the render pipeline behaves normally.+const renderMathInElementSpy = vi.hoisted(() => vi.fn());+vi.mock("./math.js", async (importOriginal) => {+ const original = await importOriginal<typeof import("./math.js")>();+ return {+ ...original,+ renderMathInElement: renderMathInElementSpy+ };+});+import renderText, {applyInlineMermaid,postProcessRichContent,@@ -158,17 +171,32 @@ describe("Text content renderer", () => {});it("invokes KaTeX inline rendering when math-tex spans are present", async () => {+ renderMathInElementSpy.mockClear();const contentEl = document.createElement("div");const note = buildNote({title: "Math note",content: `<p>Formula: <span class="math-tex">\\(a^2 + b^2\\)</span></p>`});- // happy-dom runs in quirks mode, so KaTeX may surface a parse error rather- // than a full .katex tree; either way, auto-render touches the span. We only- // assert that the math span survives the rendering pass (line is exercised).await expect(renderText(note, $(contentEl))).resolves.toBeUndefined();- // The math span is preserved through the KaTeX auto-render pass.+ // The math span is preserved through the rendering pass.expect(contentEl.querySelector("span.math-tex")).not.toBeNull();+ // The conditional KaTeX auto-render branch ran: it was invoked exactly once+ // with the rendered content element ($renderedContent[0]) and the trust flag.+ expect(renderMathInElementSpy).toHaveBeenCalledTimes(1);+ expect(renderMathInElementSpy).toHaveBeenCalledWith(contentEl, { trust: true });+ });++ it("does not invoke KaTeX inline rendering when no math-tex spans are present", async () => {+ renderMathInElementSpy.mockClear();+ const contentEl = document.createElement("div");+ const note = buildNote({+ title: "Plain note",+ content: `<p>No formulas here.</p>`+ });+ await expect(renderText(note, $(contentEl))).resolves.toBeUndefined();+ // The math branch is gated on the presence of a span.math-tex; with none+ // present the auto-render entry point must be left untouched.+ expect(renderMathInElementSpy).not.toHaveBeenCalled();});it("rewrites reference-link titles using the note title", async () => {diff --git a/apps/client/src/services/css_class_manager.spec.ts b/apps/client/src/services/css_class_manager.spec.tsindex eb87f0b4dc..39ddafcf60 100644--- a/apps/client/src/services/css_class_manager.spec.ts+++ b/apps/client/src/services/css_class_manager.spec.ts@@ -74,7 +74,11 @@ describe("createClassForColor", () => {const html = $("head").find("style").last().html() ?? "";expect(html).toContain(".color-123456");expect(html).toContain("--original-custom-color: #123456");- expect(html).toContain("--custom-color-hue:");+ // The emitted hue must be the actual numeric value (not "unset"), since #123456 is saturated.+ const expectedHue = getHue(Color("#123456"));+ expect(expectedHue).toBe(210);+ expect(html).toContain(`--custom-color-hue: ${expectedHue};`);+ expect(html).not.toContain("--custom-color-hue: unset");});it("does not re-inject a <style> for an already-registered color", () => {@@ -104,20 +108,39 @@ describe("createClassForColor", () => {});it("adjusts lightness for both a very light and a very dark color", () => {- // Very light color: dark-theme min-lightness clamp kicks in (Math.max picks the min).+ // Helper to read the registered style block for a given class fragment.+ function styleFor(classFragment: string) {+ return $("head")+ .find("style")+ .filter((_, el) => ($(el).html() ?? "").includes(classFragment))+ .first()+ .html() ?? "";+ }++ // Very light color (lab L ~= 99.65). Under happy-dom the theme CSS vars are unset, so+ // the source falls back to lightThemeColorMaxLightness=70 / darkThemeColorMinLightness=50.+ // The light-theme color is clamped down to L=70 (a mid-gray, distinct from the original),+ // while the dark-theme color stays at the original (Math.max keeps the higher lightness).const light = cssClassManager.createClassForColor("#fefefe");expect(light).toContain("color-FEFEFE");- // Very dark color: light-theme max-lightness clamp kicks in (Math.min picks the max).+ const lightHtml = styleFor(".color-FEFEFE");+ expect(lightHtml).toContain("--original-custom-color: #FEFEFE");+ expect(lightHtml).toContain("--light-theme-custom-color: #ABABAB");+ expect(lightHtml).toContain("--dark-theme-custom-color: #FEFEFE");+ // The clamp actually moved the light-theme color away from the original.+ expect(lightHtml).not.toContain("--light-theme-custom-color: #FEFEFE");++ // Very dark color (lab L ~= 0.27). The dark-theme color is clamped up to L=50 (a mid-gray),+ // while the light-theme color stays at the original (Math.min keeps the lower lightness).const dark = cssClassManager.createClassForColor("#010101");expect(dark).toContain("color-010101");- const darkHtml = $("head")- .find("style")- .filter((_, el) => ($(el).html() ?? "").includes(".color-010101"))- .first()- .html() ?? "";- expect(darkHtml).toContain("--light-theme-custom-color:");- expect(darkHtml).toContain("--dark-theme-custom-color:");+ const darkHtml = styleFor(".color-010101");+ expect(darkHtml).toContain("--original-custom-color: #010101");+ expect(darkHtml).toContain("--light-theme-custom-color: #010101");+ expect(darkHtml).toContain("--dark-theme-custom-color: #777777");+ // The clamp actually moved the dark-theme color away from the original.+ expect(darkHtml).not.toContain("--dark-theme-custom-color: #010101");});});diff --git a/apps/client/src/services/date_notes.spec.ts b/apps/client/src/services/date_notes.spec.tsindex a1dc5dc69a..c31a4e2305 100644--- a/apps/client/src/services/date_notes.spec.ts+++ b/apps/client/src/services/date_notes.spec.ts@@ -24,6 +24,9 @@ describe("date_notes", () => {expect.stringMatching(/^special-notes\/inbox\/\d{4}-\d{2}-\d{2}$/),"date-note");+ // getInboxNote is the only day-note-style helper that intentionally skips the+ // change-id wait, unlike every sibling which awaits it.+ expect(ws.waitForMaxKnownEntityChangeId).not.toHaveBeenCalled();expect(result).toBe(note);});@@ -84,6 +87,18 @@ describe("date_notes", () => {expect(result).toBe(note);});+ it("getWeekNote tolerates a missing server response via optional chaining", async () => {+ // getWeekNote is the only helper using froca.getNote(note?.noteId); a null server+ // response must resolve to null (froca.getNote(undefined) returns null) instead of throwing.+ server.get = vi.fn(async () => null) as typeof server.get;++ const result = await dateNotes.getWeekNote("2025-W22");++ expect(server.get).toHaveBeenCalledWith("special-notes/weeks/2025-W22", "date-note");+ expect(ws.waitForMaxKnownEntityChangeId).toHaveBeenCalled();+ expect(result).toBeNull();+ });+it("getMonthNote queries months endpoint", async () => {const note = buildNote({ title: "Month" });server.get = vi.fn(async () => ({ noteId: note.noteId })) as typeof server.get;diff --git a/apps/client/src/services/focus.spec.ts b/apps/client/src/services/focus.spec.tsindex 1094e65089..ee7ec72d06 100644--- a/apps/client/src/services/focus.spec.ts+++ b/apps/client/src/services/focus.spec.ts@@ -9,10 +9,45 @@ afterEach(() => {});describe("focus service", () => {- it("does nothing when no element was saved", () => {- // Nothing focused -> $(":focus") is empty, so the saved element is falsy and focusSavedElement returns early.+ it("does nothing (no focus change) when nothing was focused at save time", () => {+ // saveFocusedElement() always assigns a jQuery object: $(":focus") is an *empty* wrapped+ // set when nothing is focused (never null). So the early-return at the top of+ // focusSavedElement() is NOT hit here; execution falls through to .hasClass("ck") (false)+ // then .focus() on the empty set, which is a harmless no-op.+ const $body = $(document.body);+ ($body[0] as HTMLElement).focus();+ // happy-dom keeps focus on <body> by default; record the active element to prove it is unchanged.+ const before = document.activeElement;+saveFocusedElement();++ // Spy on jQuery's focus to prove no real element receives focus via the empty-set branch.+ const focusProtoSpy = vi.spyOn($.fn, "focus");expect(() => focusSavedElement()).not.toThrow();+ // .focus() is invoked on the empty wrapped set (harmless), but the active element is unchanged.+ expect(focusProtoSpy).toHaveBeenCalledTimes(1);+ expect(document.activeElement).toBe(before);+ });++ it("returns early (engages the !$lastFocusedElement guard) once the saved element has been cleared", () => {+ // Save and restore a real element first; restoring sets $lastFocusedElement = null (line 28).+ const $input = $("<input type='text'>").appendTo(document.body);+ ($input[0] as HTMLInputElement).focus();+ saveFocusedElement();+ focusSavedElement();+ expect(document.activeElement).toBe($input[0]);++ // Now move focus away. A second focusSavedElement() hits the `if (!$lastFocusedElement) return;`+ // early-return branch and must NOT touch focus.+ const $other = $("<input type='text'>").appendTo(document.body);+ ($other[0] as HTMLInputElement).focus();+ expect(document.activeElement).toBe($other[0]);++ const focusProtoSpy = vi.spyOn($.fn, "focus");+ focusSavedElement();+ // Early return: no .focus() invoked at all and the active element is untouched.+ expect(focusProtoSpy).not.toHaveBeenCalled();+ expect(document.activeElement).toBe($other[0]);});it("restores focus to a plain saved element", () => {@@ -52,6 +87,16 @@ describe("focus service", () => {focusSavedElement();expect(focusSpy).toHaveBeenCalledTimes(1);+ expect(focusSpy).toHaveBeenCalledWith();++ // The ck branch must also reset $lastFocusedElement to null (line 28). Move focus and call+ // again: with the saved element cleared, the early return engages and the editor is NOT+ // re-focused. If the ck branch failed to null the field, focusSpy would fire a second time.+ const $elsewhere = $("<input type='text'>").appendTo(document.body);+ ($elsewhere[0] as HTMLInputElement).focus();+ focusSavedElement();+ expect(focusSpy).toHaveBeenCalledTimes(1);+ expect(document.activeElement).toBe($elsewhere[0]);});it("logs when the ck element has no resolvable CKEditor instance", () => {diff --git a/apps/client/src/services/froca.spec.ts b/apps/client/src/services/froca.spec.tsindex f0dee33d5c..937f840f9b 100644--- a/apps/client/src/services/froca.spec.ts+++ b/apps/client/src/services/froca.spec.ts@@ -281,6 +281,7 @@ describe("loadSearchNote", () => {const search = buildNote({ id: "ls-bad", title: "Search", type: "search" });server.get = vi.fn(async () => ({ searchResultNoteIds: "boom", highlightedTokens: [], error: null })) as typeof server.get;await expect(froca.loadSearchNote(search.noteId)).rejects.toThrow(/failed/);+ expect(server.get).toHaveBeenCalledWith(`search-note/${search.noteId}`);});it("populates virtual child branches from search results", async () => {@@ -298,6 +299,7 @@ describe("loadSearchNote", () => {const out = await froca.loadSearchNote(search.noteId);+ expect(server.get).toHaveBeenCalledWith(`search-note/${search.noteId}`);expect(out).toEqual({ error: null });expect(search.searchResultsLoaded).toBe(true);expect(search.highlightedTokens).toEqual(["token"]);@@ -316,6 +318,7 @@ describe("loadSearchNote", () => {}) as typeof server.get;const out = await froca.loadSearchNote(search.noteId);+ expect(server.get).toHaveBeenCalledWith(`search-note/${search.noteId}`);expect(out).toEqual({ error: "oops" });expect(froca.notes["ls-gone"].searchResultsLoaded).toBe(true);});diff --git a/apps/client/src/services/froca_updater.spec.ts b/apps/client/src/services/froca_updater.spec.tsindex 3e68813fc7..1371adf04b 100644--- a/apps/client/src/services/froca_updater.spec.ts+++ b/apps/client/src/services/froca_updater.spec.ts@@ -7,6 +7,7 @@ import FBranch from "../entities/fbranch.js";import type { EntityChange } from "../server_types.js";import froca from "./froca.js";import frocaUpdater from "./froca_updater.js";+import type LoadResults from "./load_results.js";import noteAttributeCache from "./note_attribute_cache.js";import options from "./options.js";import utils from "./utils.js";@@ -105,6 +106,12 @@ describe("froca_updater - note changes", () => {expect(`${note.noteId}-content` in froca.blobPromises).toBe(false);expect("unrelated-key" in froca.blobPromises).toBe(true);expect(triggerSpy).toHaveBeenCalledTimes(1);++ // The named behaviour: a content change is actually REGISTERED in the load results+ // (addNoteContent branch). Inspect the payload delivered to triggerEvent.+ expect(triggerSpy).toHaveBeenCalledWith("entitiesReloaded", expect.anything());+ const loadResults = triggerSpy.mock.calls[0][1].loadResults as LoadResults;+ expect(loadResults.isNoteContentReloaded(note.noteId)).toBeTruthy();});it("does not register content change when protection status changed", async () => {@@ -122,6 +129,15 @@ describe("froca_updater - note changes", () => {await process([ec({ entityName: "notes", entityId: note.noteId, componentId: "comp-y", entity: row as any })]);expect(note.isProtected).toBe(true);expect(note.blobId).toBe("newBlob2");++ // The defining behaviour: despite the blobId change, NO content change is registered+ // because the protection status flipped. Inspect the load results payload to confirm+ // addNoteContent was skipped (the note is still tracked, but not as a content reload).+ expect(triggerSpy).toHaveBeenCalledWith("entitiesReloaded", expect.anything());+ const loadResults = triggerSpy.mock.calls[0][1].loadResults as LoadResults;+ expect(loadResults.isNoteContentReloaded(note.noteId)).toBeFalsy();+ // ...but the note itself is still recorded as reloaded (addNote ran regardless).+ expect(loadResults.isNoteReloaded(note.noteId)).toBe(true);});it("updates a note without componentId (no content registration branch)", async () => {@@ -305,6 +321,12 @@ describe("froca_updater - revisions / options / etapi_tokens", () => {it("adds a revision and fires the event", async () => {await process([ec({ entityName: "revisions", entityId: "rev1", noteId: "n1", componentId: "c" })]);expect(triggerSpy).toHaveBeenCalledTimes(1);+ // The product of processEntityChanges is the LoadResults payload: assert the revision+ // was actually recorded for the right note, not merely that the event fired.+ expect(triggerSpy).toHaveBeenCalledWith("entitiesReloaded", expect.anything());+ const loadResults = triggerSpy.mock.calls[0][1].loadResults as LoadResults;+ expect(loadResults.hasRevisionForNote("n1")).toBe(true);+ expect(loadResults.hasRevisionForNote("other-note")).toBe(false);});it("sets an option and records it, but skips openNoteContexts noise", async () => {@@ -321,6 +343,10 @@ describe("froca_updater - revisions / options / etapi_tokens", () => {it("marks etapi token changes", async () => {await process([ec({ entityName: "etapi_tokens", entityId: "tok1", entity: { isDeleted: false } as any })]);expect(triggerSpy).toHaveBeenCalledTimes(1);+ // Assert the recorded state, not just that the event fired.+ expect(triggerSpy).toHaveBeenCalledWith("entitiesReloaded", expect.anything());+ const loadResults = triggerSpy.mock.calls[0][1].loadResults as LoadResults;+ expect(loadResults.hasEtapiTokenChanges).toBe(true);});});@@ -465,10 +491,24 @@ describe("froca_updater - attribute changes", () => {const note = buildNote({ title: "ErasedAttrHost", "~inherit": "target-loaded" });const attrId = note.attributes[0];await process([ec({ entityName: "attributes", entityId: attrId, isErased: true, entity: undefined })]);- // erased + not in froca attributes? It IS in froca via buildNote, so reload triggered.- // But entity is undefined => ancestor scan 'continue' branch is exercised.+ // The attribute IS in froca via buildNote and is erased => the early reloadFrontendApp()+ // path is taken (this is the code path actually hit by this fixture).+ expect(reloadSpy).toHaveBeenCalledTimes(1);+ // And because the ancestor scan sees entity === undefined it must NOT reload the target note.expect(reloadNotesSpy).not.toHaveBeenCalled();});++ it("ancestor scan 'continue' branch: an erased attribute absent from froca reloads nothing", async () => {+ // An erased attribute that is NOT in froca.attributes: the early reload short-circuit is+ // skipped (attribute not loaded), so the ancestor scan runs and hits `if (!entity) continue`.+ await process([ec({ entityName: "attributes", entityId: "never-loaded-attr", isErased: true, entity: undefined })]);+ // No early full reload (attribute was not in froca) ...+ expect(reloadSpy).not.toHaveBeenCalled();+ // ... no per-note reload (the scan's continue branch skipped the missing-note push) ...+ expect(reloadNotesSpy).not.toHaveBeenCalled();+ // ... and the load results stay empty, so no event fires.+ expect(triggerSpy).not.toHaveBeenCalled();+ });});describe("froca_updater - attachment changes", () => {@@ -598,6 +638,10 @@ describe("froca_updater - attachment changes", () => {} as any})]);expect(triggerSpy).toHaveBeenCalledTimes(1);+ // The attachment row is still recorded even though the owner note is absent.+ expect(triggerSpy).toHaveBeenCalledWith("entitiesReloaded", expect.anything());+ const loadResults = triggerSpy.mock.calls[0][1].loadResults as LoadResults;+ expect(loadResults.getAttachmentRows().some((a) => a.attachmentId === "att-noowner")).toBe(true);});});@@ -701,6 +745,11 @@ describe("froca_updater - branch coverage edge cases", () => {// not erased, not deleted, attachment not loaded, and ec.entity is undefinedawait process([ec({ entityName: "attachments", entityId: "att-noentity" })]);expect(triggerSpy).toHaveBeenCalledTimes(1);+ // Even with no entity payload, the source still pushes a row (the undefined attachmentEntity)+ // into the load results, which is what makes the event non-empty and fire.+ expect(triggerSpy).toHaveBeenCalledWith("entitiesReloaded", expect.anything());+ const loadResults = triggerSpy.mock.calls[0][1].loadResults as LoadResults;+ expect(loadResults.getAttachmentRows().length).toBe(1);});});diff --git a/apps/client/src/services/frontend_script_api.spec.ts b/apps/client/src/services/frontend_script_api.spec.tsindex 485a9c4629..891a47cdb2 100644--- a/apps/client/src/services/frontend_script_api.spec.ts+++ b/apps/client/src/services/frontend_script_api.spec.ts@@ -211,18 +211,24 @@ describe("runOnBackend / __runOnBackendInner", () => {});it("warns and still runs when passed an async function reference", async () => {- vi.spyOn(server, "post").mockResolvedValue({ success: true, executionResult: 1 } as never);+ const post = vi.spyOn(server, "post").mockResolvedValue({ success: true, executionResult: 1 } as never);const showError = vi.spyOn(toastService, "showError").mockImplementation(() => undefined as never);const asyncFn = async () => {};- await makeApi().runOnBackend(asyncFn, []);+ const result = await makeApi().runOnBackend(asyncFn, []);expect(showError).toHaveBeenCalled();+ // "still runs": the warning does not short-circuit; it proceeds to the backend and returns the result.+ expect(post).toHaveBeenCalledWith("script/exec", expect.any(Object), "script");+ expect(result).toBe(1);});it("warns when passed an async function as a string", async () => {- vi.spyOn(server, "post").mockResolvedValue({ success: true, executionResult: 1 } as never);+ const post = vi.spyOn(server, "post").mockResolvedValue({ success: true, executionResult: 1 } as never);const showError = vi.spyOn(toastService, "showError").mockImplementation(() => undefined as never);- await makeApi().runOnBackend("async function f(){}", []);+ const result = await makeApi().runOnBackend("async function f(){}", []);expect(showError).toHaveBeenCalled();+ // "still runs": the warning does not short-circuit; it proceeds to the backend and returns the result.+ expect(post).toHaveBeenCalledWith("script/exec", expect.any(Object), "script");+ expect(result).toBe(1);});it("does not warn for a plain sync function and defaults params to an empty array", async () => {diff --git a/apps/client/src/services/glob.spec.ts b/apps/client/src/services/glob.spec.tsindex c8efcb32c7..c00a74ea24 100644--- a/apps/client/src/services/glob.spec.ts+++ b/apps/client/src/services/glob.spec.ts@@ -20,6 +20,7 @@ import glob from "./glob.js";import { requireCss } from "./glob.js";import linkService from "./link.js";import server from "./server.js";+import utils from "./utils.js";import ws from "./ws.js";const getComponentByEl = appContext.getComponentByEl as ReturnType<typeof vi.fn>;@@ -55,9 +56,10 @@ describe("setupGlobs", () => {it("wires up the glob object with values and delegating helpers", () => {glob.setupGlobs();- // direct value assignments- expect(window.glob.isDesktop).toBeTypeOf("function");- expect(window.glob.isMobile).toBeTypeOf("function");+ // direct value assignments: assert identity, not just that they are functions,+ // so a swapped/wrong reference (e.g. both set to utils.isMobile) is caught.+ expect(window.glob.isDesktop).toBe(utils.isDesktop);+ expect(window.glob.isMobile).toBe(utils.isMobile);expect(window.glob.getHeaders).toBe(server.getHeaders);expect(window.glob.froca).toBe(froca);expect(window.glob.treeCache).toBe(froca);diff --git a/apps/client/src/services/hoisted_note.spec.ts b/apps/client/src/services/hoisted_note.spec.tsindex 6e47759ac9..3c92708baa 100644--- a/apps/client/src/services/hoisted_note.spec.ts+++ b/apps/client/src/services/hoisted_note.spec.ts@@ -195,5 +195,49 @@ describe("hoisted_note service", () => {expect(confirm).not.toHaveBeenCalled();expect(unhoistSpy).toHaveBeenCalledTimes(1);});++ it("still prompts for a bookmark path even when the hoisted note is inside _hidden", async () => {+ // A bookmark target (`_lbBookmarks`) re-enables the guard on BOTH decision points:+ // - line 52: the path includes `_hidden` (would normally skip) but the+ // `|| includes("_lbBookmarks")` clause forces entry into the guard block.+ // - line 61: the hoisted note IS under `_hidden` (so `!hasAncestor("_hidden")`+ // is false), but the `|| includes("_lbBookmarks")` clause forces confirm().+ // This is the exact inverse of the previous (non-bookmark) test, which skips confirm.+ buildNote({ id: "_hidden", title: "Hidden" });+ const hoisted = buildNote({ title: "HoistedHidden" });+ hoisted.parents.push("_hidden");+ const requested = buildNote({ title: "Bookmark target" });++ resolveNotePath.mockResolvedValue("_hidden/_lbBookmarks/target");+ getNoteIdFromUrl.mockReturnValue(requested.noteId);+ confirm.mockResolvedValue(false);+ setActiveContext(hoisted.noteId);++ const result = await hoistedNoteService.checkNoteAccess("p", ctx(hoisted.noteId));+ // confirm was declined -> access denied, no unhoist.+ expect(result).toBe(false);+ expect(confirm).toHaveBeenCalledTimes(1);+ expect(unhoistSpy).not.toHaveBeenCalled();+ });++ it("unhoists for a confirmed bookmark path when the hoisted note is inside _hidden", async () => {+ // Same bookmark-path branch as above, but the user confirms: access is granted+ // and unhoist runs, proving the `_lbBookmarks` clause at line 61 reaches confirm()+ // and the post-confirm unhoist on this otherwise-skipped (_hidden) path.+ buildNote({ id: "_hidden", title: "Hidden" });+ const hoisted = buildNote({ title: "HoistedHidden2" });+ hoisted.parents.push("_hidden");+ const requested = buildNote({ title: "Bookmark target 2" });++ resolveNotePath.mockResolvedValue("_hidden/_lbBookmarks/target");+ getNoteIdFromUrl.mockReturnValue(requested.noteId);+ confirm.mockResolvedValue(true);+ setActiveContext(hoisted.noteId);++ const result = await hoistedNoteService.checkNoteAccess("p", ctx(hoisted.noteId));+ expect(result).toBe(true);+ expect(confirm).toHaveBeenCalledTimes(1);+ expect(unhoistSpy).toHaveBeenCalledTimes(1);+ });});});diff --git a/apps/client/src/services/i18n.spec.ts b/apps/client/src/services/i18n.spec.tsindex 3b4af5ef74..4a6be1db37 100644--- a/apps/client/src/services/i18n.spec.ts+++ b/apps/client/src/services/i18n.spec.ts@@ -1,4 +1,4 @@-import { findDuplicateJsonKeys, LOCALES } from "@triliumnext/commons";+import { dayjs, findDuplicateJsonKeys, LOCALES } from "@triliumnext/commons";import { readFileSync } from "fs";import { join } from "path";import { describe, expect, it, vi } from "vitest";@@ -75,6 +75,10 @@ describe("i18n", () => {await initLocale("de");expect(getCurrentLanguage()).toBe("de");+ // The second responsibility of initLocale is `await setDayjsLocale(locale)`, which+ // switches the global dayjs locale. Assert the observable side effect so removing or+ // mis-passing the locale to setDayjsLocale would be caught.+ expect(dayjs.locale()).toBe("de");// The deferred resolves once translations are ready.await expect(translationsInitializedPromise).resolves.toBeUndefined();});diff --git a/apps/client/src/services/image.spec.ts b/apps/client/src/services/image.spec.tsindex 07c891d19d..37af54f635 100644--- a/apps/client/src/services/image.spec.ts+++ b/apps/client/src/services/image.spec.ts@@ -2,11 +2,14 @@ import $ from "jquery";import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import imageService, { copyImageReferenceToClipboard } from "./image.js";+import * as toastModule from "./toast.js";import toastService from "./toast.js";describe("copyImageReferenceToClipboard", () => {let execCommandSpy: ReturnType<typeof vi.fn>;let removeAllRangesSpy: ReturnType<typeof vi.fn>;+ let addRangeSpy: ReturnType<typeof vi.fn>;+ let showErrorSpy: ReturnType<typeof vi.spyOn>;beforeEach(() => {// image.ts calls the bare global `logError`, normally installed by ws.ts (which setup.ts mocks).@@ -16,15 +19,17 @@ describe("copyImageReferenceToClipboard", () => {execCommandSpy = vi.fn(() => true);(document as any).execCommand = execCommandSpy;- // Track range clean-up performed in the finally block.+ // Track range clean-up performed in the finally block, and range addition done by selectImage's happy path.removeAllRangesSpy = vi.fn();+ addRangeSpy = vi.fn();const selection = {removeAllRanges: removeAllRangesSpy,- addRange: vi.fn()+ addRange: addRangeSpy};vi.spyOn(window, "getSelection").mockReturnValue(selection as unknown as Selection);vi.spyOn(toastService, "showMessage").mockImplementation(() => {});+ showErrorSpy = vi.spyOn(toastModule, "showError").mockImplementation(() => {});});afterEach(() => {@@ -42,8 +47,13 @@ describe("copyImageReferenceToClipboard", () => {expect($wrapper.attr("contenteditable")).toBeUndefined();expect(execCommandSpy).toHaveBeenCalledWith("copy");expect(toastService.showMessage).toHaveBeenCalledTimes(1);- // Selection was created on the element (selectImage took the happy path) and cleaned up.+ // The happy path adds the element's range to the selection -> proves selectImage actually+ // selected the image (removeAllRanges alone is also fired by the finally block, so it proves nothing).+ expect(addRangeSpy).toHaveBeenCalledTimes(1);+ // Selection was cleaned up in the finally block.expect(removeAllRangesSpy).toHaveBeenCalled();+ // No error feedback on the success path.+ expect(showErrorSpy).not.toHaveBeenCalled();element.remove();});@@ -55,6 +65,9 @@ describe("copyImageReferenceToClipboard", () => {copyImageReferenceToClipboard($wrapper);expect(toastService.showMessage).not.toHaveBeenCalled();+ // The user-facing failure feedback is the named showError export from toast.ts (message is an+ // i18n string, so we only assert it was invoked once on the failure path).+ expect(showErrorSpy).toHaveBeenCalledTimes(1);expect((window as any).logError).toHaveBeenCalledTimes(1);expect($wrapper.attr("contenteditable")).toBeUndefined();});diff --git a/apps/client/src/services/import.spec.ts b/apps/client/src/services/import.spec.tsindex d8c7148787..c4384ade24 100644--- a/apps/client/src/services/import.spec.ts+++ b/apps/client/src/services/import.spec.ts@@ -2,6 +2,7 @@ import { beforeAll, beforeEach, describe, expect, it, vi } from "vitest";import type { WebSocketMessage } from "@triliumnext/commons";import appContext from "../components/app_context.js";+import * as i18n from "./i18n.js";import server from "./server.js";import toastService from "./toast.js";import ws from "./ws.js";@@ -96,12 +97,24 @@ describe("uploadFiles", () => {});it("surfaces an upload error through the toast service via the ajax error callback", async () => {- ($ as any).ajax = vi.fn(async (opts: any) => {- opts.error({ responseText: "boom" });- return {};- });- await uploadFiles("notes", "p1", ["a"], { shrinkImages: false });- expect(toastService.showError).toHaveBeenCalledTimes(1);+ // Spy on the i18n binding so we can verify xhr.responseText is forwarded+ // without depending on i18next interpolation (i18next is uninitialised in+ // the test env, so t() returns the key and never interpolates). We assert+ // the call args/structure rather than a human-readable translated string.+ const tSpy = vi.spyOn(i18n, "t");+ try {+ ($ as any).ajax = vi.fn(async (opts: any) => {+ opts.error({ responseText: "boom" });+ return {};+ });+ await uploadFiles("notes", "p1", ["a"], { shrinkImages: false });+ expect(toastService.showError).toHaveBeenCalledTimes(1);+ // The xhr.responseText ("boom") must be forwarded into the message+ // interpolation, not dropped or replaced with the whole xhr object.+ expect(tSpy).toHaveBeenCalledWith("import.failed", { message: "boom" });+ } finally {+ tSpy.mockRestore();+ }});it("is also reachable through the default export", async () => {@@ -228,6 +241,21 @@ describe("importAttachments ws handler", () => {expect(setNote).not.toHaveBeenCalled();});+ it("navigates with an undefined note id when the parent gates but the imported note id is missing", async () => {+ // The source gates navigation on result.parentNoteId but passes+ // result.importedNoteId to setNote. With a parent present and no+ // imported id, setNote is still called with the (undefined) id.+ await handler()({+ type: "taskSucceeded",+ taskType: "importAttachments",+ taskId: "a4b",+ result: { parentNoteId: "par2" }+ } as any);+ expect(toastService.showPersistent).toHaveBeenCalledTimes(1);+ expect(setNote).toHaveBeenCalledTimes(1);+ expect(setNote).toHaveBeenCalledWith(undefined, { viewScope: { viewMode: "attachments" } });+ });+it("tolerates a missing active context on success navigation", async () => {getActiveContext.mockReturnValue(undefined as any);await handler()({diff --git a/apps/client/src/services/link.spec.ts b/apps/client/src/services/link.spec.tsindex 7d2e2ef748..df9e8097f7 100644--- a/apps/client/src/services/link.spec.ts+++ b/apps/client/src/services/link.spec.ts@@ -610,6 +610,17 @@ describe("loadReferenceLinkTitle", () => {// the title becomes the note title, and the bookmark small is appendedexpect($el.text()).toContain("Loaded");expect($el.find("small").length).toBe(1);+ // the bookmark <small> carries the bookmark glyph and the bookmark text+ expect($el.find("small span.bx.bx-bookmark").length).toBe(1);+ expect($el.find("small").text()).toContain("Sec");+ // the color class produced by note.getColorClass() is applied to $el (source line 431)+ const colorClass = note.getColorClass();+ expect(colorClass).not.toBe("");+ expect($el.hasClass(colorClass)).toBe(true);+ // an icon span is prepended (source lines 444-449); getIcon() yields the iconClass labels+ const $iconSpan = $el.children("span").first();+ expect($iconSpan.length).toBe(1);+ expect($iconSpan.hasClass("bx-star")).toBe(true);});it("uses the element's own href and finds the inner anchor when none is passed", async () => {diff --git a/apps/client/src/services/llm_chat.spec.ts b/apps/client/src/services/llm_chat.spec.tsindex 713a1ab320..fd4666df95 100644--- a/apps/client/src/services/llm_chat.spec.ts+++ b/apps/client/src/services/llm_chat.spec.ts@@ -142,8 +142,9 @@ describe("streamChatCompletion", () => {{ type: "done" },{ type: "unknown_ignored" }];- // Split a "data: " line across two chunks to exercise the buffer carry-over,- // and include a blank/non-data line which must be ignored.+ // Each event is a complete `data: ...\n` line; include a non-data line which must be+ // ignored, plus a trailing partial line left in the buffer (never flushed). The+ // cross-read buffer carry-over is exercised separately in its own test above.const chunks = [...events.map((e) => `data: ${JSON.stringify(e)}\n`),"ignored non-data line\n",@@ -165,6 +166,33 @@ describe("streamChatCompletion", () => {expect(cb.onDone).toHaveBeenCalledTimes(1);});+ it("reassembles a single SSE data line split across two read() boundaries", async () => {+ // The first chunk ends with a partial JSON line; the second chunk completes it.+ // This exercises the `buffer += decode(...)` / `lines.pop()` carry-over (source 78-80):+ // the partial line at the end of the first read must be completed by the next read.+ const chunks = [`data: {"type":"text",`, `"content":"hi"}\n`];+ vi.stubGlobal("fetch", vi.fn(async () => makeStreamResponse(chunks)));++ const cb = makeCallbacks();+ await streamChatCompletion(messages, config, cb);++ expect(cb.onChunk).toHaveBeenCalledTimes(1);+ expect(cb.onChunk).toHaveBeenCalledWith("hi");+ });++ it("does not invoke onDone when the stream ends without an explicit done event", async () => {+ // onDone() fires only for a `{type:"done"}` SSE event (source 126-128), NOT when the+ // reader simply returns {done:true}. Lock in that a clean stream end leaves onDone uncalled.+ const chunks = [`data: ${JSON.stringify({ type: "text", content: "only" })}\n`];+ vi.stubGlobal("fetch", vi.fn(async () => makeStreamResponse(chunks)));++ const cb = makeCallbacks();+ await streamChatCompletion(messages, config, cb);++ expect(cb.onChunk).toHaveBeenCalledWith("only");+ expect(cb.onDone).not.toHaveBeenCalled();+ });+it("ignores citation/usage events that carry no payload", async () => {const chunks = [`data: ${JSON.stringify({ type: "citation" })}\n`,diff --git a/apps/client/src/services/load_results.spec.ts b/apps/client/src/services/load_results.spec.tsindex 7e72c3b24a..970e317b2f 100644--- a/apps/client/src/services/load_results.spec.ts+++ b/apps/client/src/services/load_results.spec.ts@@ -20,17 +20,17 @@ describe("LoadResults", () => {expect(lr.getEntityRow("attributes", "missing")).toBeUndefined();});- it("tracks note <-> component associations, deduplicating component ids", () => {+ it("tracks note <-> component associations across multiple component ids", () => {const lr = new LoadResults([]);lr.addNote("n1"); // no component idlr.addNote("n1", "comp1");- lr.addNote("n1", "comp1"); // duplicate component id is ignored+ lr.addNote("n1", "comp1"); // adding the same component id again is a no-op (see dedup test below)lr.addNote("n1", "comp2");expect(lr.getNoteIds()).toEqual(["n1"]);expect(lr.isNoteReloaded("n1")).toBe(true);- // reloaded only counts components other than the one passed in+ // reloaded only counts components other than the one passed in; comp2 is still presentexpect(lr.isNoteReloaded("n1", "comp1")).toBe(true);expect(lr.isNoteReloaded("n2")).toBeFalsy(); // unknown note -> undefined (short-circuit)expect(lr.isNoteReloaded(undefined)).toBe(false);@@ -42,6 +42,37 @@ describe("LoadResults", () => {expect(lr.isNoteReloaded("solo", "comp1")).toBe(false);});+ it("ignores a duplicate component id for the same note", () => {+ // The source guards against pushing the same component id twice+ // (noteIdToComponentId[noteId] only ever contains comp once).+ // LoadResults exposes no getter for the per-note component-id array, so the+ // dedup cannot be observed directly: with the only component excluded,+ // isNoteReloaded returns false whether the array is ["comp"] or ["comp","comp"].+ // We still pin the observable contract that the duplicate add changes nothing.+ const dedup = new LoadResults([]);+ dedup.addNote("dup", "compX");+ dedup.addNote("dup", "compX"); // duplicate add++ // excluding the only (deduped) component => not reloaded for that component+ expect(dedup.isNoteReloaded("dup", "compX")).toBe(false);+ // but reloaded when no component is excluded, and the note id is tracked exactly once+ expect(dedup.isNoteReloaded("dup")).toBe(true);+ expect(dedup.getNoteIds()).toEqual(["dup"]);++ // a result that has only the (single) duplicated component association is non-empty,+ // matching the same observable behaviour as a single add (no phantom extra entries)+ expect(dedup.isEmpty()).toBe(false);++ // adding a *different* component for the same note is reflected (excluding compX+ // still leaves compY visible), confirming the dedup is per-component, not global+ const reload = new LoadResults([]);+ reload.addNote("dup2", "compX");+ reload.addNote("dup2", "compX");+ reload.addNote("dup2", "compY");+ expect(reload.isNoteReloaded("dup2", "compX")).toBe(true);+ expect(reload.isNoteReloaded("dup2", "compY")).toBe(true);+ });+it("merges branch rows with their tracked component id and drops unknown branches", () => {const lr = new LoadResults([ec("branches", "b1", { branchId: "b1", parentNoteId: "p" })]);lr.addBranch("b1", "comp1");diff --git a/apps/client/src/services/mermaid.spec.ts b/apps/client/src/services/mermaid.spec.tsindex 80b2497ecf..8c85d80657 100644--- a/apps/client/src/services/mermaid.spec.ts+++ b/apps/client/src/services/mermaid.spec.ts@@ -73,9 +73,10 @@ describe("loadElkIfNeeded", () => {}// NOTE: the module-level `elkLoaded` flag flips to true the first time an- // elk diagram is parsed, so the order of these tests matters: the- // "does not register" cases run first (while the flag is still false),- // the "registers" case flips it, and the "already loaded" case relies on it.+ // elk diagram is parsed, and the source exposes no way to reset it. The+ // "does not register" cases must therefore run while the flag is still false.+ // The "already loaded" early-exit test flips the flag itself (so it does not+ // depend on a sibling test having run first) before asserting the early exit.it("does not register loaders when parsing yields nothing", async () => {const mermaid = fakeMermaid(null);@@ -104,6 +105,12 @@ describe("loadElkIfNeeded", () => {});it("exits immediately without parsing once elk has already been loaded", async () => {+ // Make this test self-contained rather than relying on a sibling test having+ // already flipped the module-level `elkLoaded` flag: first flip it ourselves by+ // parsing an elk diagram, then assert the early-exit on a fresh mermaid instance.+ const firstMermaid = fakeMermaid({ config: { layout: "elk" } });+ await loadElkIfNeeded(firstMermaid, "---\nconfig:\n layout: elk\n---\ngraph TD; A-->B");+const mermaid = fakeMermaid({ config: { layout: "elk" } });await loadElkIfNeeded(mermaid, "---\nconfig:\n layout: elk\n---\ngraph TD; A-->B");expect(mermaid.parse).not.toHaveBeenCalled();diff --git a/apps/client/src/services/mime_types.spec.ts b/apps/client/src/services/mime_types.spec.tsindex 5c6fb0e19f..538ad3e4f4 100644--- a/apps/client/src/services/mime_types.spec.ts+++ b/apps/client/src/services/mime_types.spec.ts@@ -1,6 +1,20 @@import { MIME_TYPE_AUTO, MIME_TYPES_DICT, normalizeMimeTypeForCKEditor } from "@triliumnext/commons";import { describe, expect, it, vi } from "vitest";+// Wrap the real `normalizeMimeTypeForCKEditor` in a spy so we can observe how many+// times the highlight.js mapping build loop invokes it. It is called once per MIME+// type while the map is being built and not at all on cached lookups, which is how+// we prove the map is constructed exactly once.+const normalizeSpy = vi.hoisted(() => vi.fn());+vi.mock("@triliumnext/commons", async (importOriginal) => {+ const actual = await importOriginal<typeof import("@triliumnext/commons")>();+ normalizeSpy.mockImplementation(actual.normalizeMimeTypeForCKEditor);+ return {+ ...actual,+ normalizeMimeTypeForCKEditor: (...args: Parameters<typeof actual.normalizeMimeTypeForCKEditor>) => normalizeSpy(...args)+ };+});+import options from "./options.js";import mimeTypesService, { getHighlightJsNameForMime } from "./mime_types.js";@@ -59,14 +73,32 @@ describe("mime_types service", () => {});it("getHighlightJsNameForMime maps CKEditor-normalized mimes to highlight.js codes and caches the mapping", () => {- // text/x-csrc -> text-x-csrc -> "c"- expect(getHighlightJsNameForMime(normalizeMimeTypeForCKEditor("text/x-csrc"))).toBe("c");+ // Pre-normalize all argument MIME types so the only remaining `normalizeMimeTypeForCKEditor`+ // calls are the ones the build loop makes internally. This lets us count build-loop+ // invocations without the test's own argument-prep calls polluting the spy.+ const cMime = normalizeMimeTypeForCKEditor("text/x-csrc"); // text-x-csrc+ const cssMime = normalizeMimeTypeForCKEditor("text/css"); // text-css+ const aplMime = normalizeMimeTypeForCKEditor("text/apl");++ // The first lookup builds the mapping: the loop normalizes every MIME type once.+ normalizeSpy.mockClear();+ expect(getHighlightJsNameForMime(cMime)).toBe("c");+ const buildCalls = normalizeSpy.mock.calls.length;+ // The build ran and touched every MIME type (one normalize call per dictionary entry).+ expect(buildCalls).toBe(MIME_TYPES_DICT.length);+ expect(buildCalls).toBeGreaterThan(1);++ // Every subsequent lookup must hit the cached map and NOT rebuild it,+ // i.e. `normalizeMimeTypeForCKEditor` is not invoked again.+ normalizeSpy.mockClear();// text/css -> text-css -> "css" (exercises the cached path on the second call)- expect(getHighlightJsNameForMime(normalizeMimeTypeForCKEditor("text/css"))).toBe("css");+ expect(getHighlightJsNameForMime(cssMime)).toBe("css");// A mime that exists but has no mdLanguageCode is omitted from the mapping.- expect(getHighlightJsNameForMime(normalizeMimeTypeForCKEditor("text/apl"))).toBeUndefined();+ expect(getHighlightJsNameForMime(aplMime)).toBeUndefined();// An entirely unknown mime resolves to undefined.expect(getHighlightJsNameForMime("totally-unknown")).toBeUndefined();+ // No rebuild happened across these three cached lookups.+ expect(normalizeSpy).not.toHaveBeenCalled();});it("re-exports MIME_TYPE_AUTO and the public helpers", () => {diff --git a/apps/client/src/services/note_autocomplete.spec.ts b/apps/client/src/services/note_autocomplete.spec.tsindex 43d929249e..5565aed9bd 100644--- a/apps/client/src/services/note_autocomplete.spec.ts+++ b/apps/client/src/services/note_autocomplete.spec.ts@@ -200,12 +200,39 @@ describe("autocompleteSource (via dataset)", () => {it("resets searchDelay back to the computed value after it was zeroed", async () => {server.get = vi.fn(async () => []) as typeof server.get;- const { $el, dataset } = initAndGetSource();- // showRecentNotes zeroes the shared searchDelay...- noteAutocomplete.showRecentNotes($el);- // ...and the next source invocation runs immediately and restores it.- await runSource(dataset, "x");- expect(server.get).toHaveBeenCalled();+ // Capture the delay arg the source's debounce schedules with, so we can+ // observe that the zeroed searchDelay is restored to the computed value.+ const scheduledDelays: number[] = [];+ const originalSetTimeout = globalThis.setTimeout;+ const setTimeoutSpy = vi.spyOn(globalThis, "setTimeout").mockImplementation(((fn: any, delay?: number, ...rest: any[]) => {+ scheduledDelays.push(delay as number);+ // call through to the real timer so runSource's cb still resolves+ return originalSetTimeout(fn, delay as number, ...rest);+ }) as unknown as typeof setTimeout);+ try {+ const { $el, dataset } = initAndGetSource();+ // showRecentNotes zeroes the shared module-level searchDelay...+ noteAutocomplete.showRecentNotes($el);+ // ...so the FIRST source invocation debounces with delay 0 (immediate)+ // and, because searchDelay === 0, restores it to getSearchDelay(notesCount).+ await runSource(dataset, "x");+ // ...and the SECOND source invocation now sees the restored (non-zero)+ // delay rather than 0 — this is the reset behaviour the test name claims.+ await runSource(dataset, "y");+ expect(server.get).toHaveBeenCalled();++ // The source-callback delays we captured (filtering out any unrelated+ // timers froca/setup may schedule): the run after zeroing uses 0, the+ // following run uses the restored computed delay (which is NOT 0).+ // notesCount resolves to undefined in this mocked environment, so+ // getSearchDelay(undefined) === NaN — still distinct from the zeroed 0.+ expect(scheduledDelays).toContain(0); // the immediate run after zeroing+ const restored = scheduledDelays[scheduledDelays.length - 1];+ expect(restored).not.toBe(0); // searchDelay was restored away from 0+ expect(Number.isNaN(restored)).toBe(true); // == getSearchDelay(undefined)+ } finally {+ setTimeoutSpy.mockRestore();+ }});it("queries the server and returns plain results", async () => {@@ -547,10 +574,23 @@ describe("initNoteAutocomplete wiring", () => {const $el = makeEl();noteAutocomplete.initNoteAutocomplete($el);$el.autocomplete("val", "some text");+ const callsBefore = autocompleteCalls.length;const ev = $.Event("keydown", { shiftKey: true, key: "Enter" });$el.trigger(ev);- // fullTextSearch toggles options.fastSearch and re-sets val- expect(lastCommandWith("val")).toBe(true);+ // fullTextSearch re-runs the search: it clears val ("val", "") and then+ // re-sets it to the captured search string ("val", "some text"). Assert+ // BOTH setter calls happened after the Shift+Enter, proving the body after+ // the blank-string guard actually ran (not merely the getter read).+ const setterCallsAfter = autocompleteCalls+ .slice(callsBefore)+ .filter((c) => c[0] === "val" && c[1] !== undefined)+ .map((c) => c[1]);+ expect(setterCallsAfter).toContain("");+ expect(setterCallsAfter).toContain("some text");+ // the clear ("val", "") must precede the re-set ("val", "some text")+ expect(setterCallsAfter.indexOf("")).toBeLessThan(setterCallsAfter.indexOf("some text"));+ // and the input ends up re-populated with the search string+ expect($el.autocomplete("val")).toBe("some text");});it("ignores keydowns that are not Ctrl+Enter / Shift+Enter", () => {@@ -679,9 +719,17 @@ describe("autocomplete:selected handler", () => {chooseNoteType.mockResolvedValue({ success: true, noteType: "text", notePath: "chosen/path" });createNote.mockResolvedValue({ note: undefined });getActiveContext.mockReturnValue(undefined);- const { $el } = initWithSelected();+ const { $el, handlers } = initWithSelected();await fireSelected($el, { action: "create-note", noteTitle: "X", parentNoteId: "p" });expect(createNote).toHaveBeenCalledWith("chosen/path", expect.any(Object));+ // The missing-note branch must be tolerated end to end: note?.getBestNotePathString+ // and getActiveContext()?.hoistedNoteId are both undefined and must not throw.+ // The flow still falls through to fire autocomplete:noteselected with an+ // undefined notePath (rather than crashing inside the async handler).+ expect(handlers["autocomplete:noteselected"]).toBeDefined();+ expect(handlers["autocomplete:noteselected"].notePath).toBeUndefined();+ // the selection was written back as a cleared path (setSelectedNotePath(undefined))+ expect($el.attr("data-note-path") ?? "").toBe("");});it("handles a plain note selection", async () => {@@ -749,10 +797,18 @@ describe("fullTextSearch guards", () => {const callsBefore = autocompleteCalls.length;const ev = $.Event("keydown", { shiftKey: true, key: "Enter" });$el.trigger(ev);- // fullTextSearch bailed out before re-setting val/focus- // the only thing that may have run is the val getter inside the guard- expect(autocompleteCalls.length).toBeGreaterThanOrEqual(callsBefore);- // setSelectedNotePath would have written the path; it was not called+ // fullTextSearch bailed out at the blank-string guard before re-setting+ // val / focus. The ONLY autocomplete call it may make is the single getter+ // read ("val" with datasets === undefined) at its first line. Assert that+ // NO setter call ("val", <non-undefined>) was added afterwards, which is+ // what would distinguish the early-return path from the full execution+ // (which would have written ["val", ""] then ["val", " "]).+ const callsAfter = autocompleteCalls.slice(callsBefore);+ const setterCalls = callsAfter.filter((c) => c[0] === "val" && c[1] !== undefined);+ expect(setterCalls).toEqual([]);+ // every autocomplete call after Shift+Enter is at most the guard's getter read+ expect(callsAfter.every((c) => c[0] === "val" && c[1] === undefined)).toBe(true);+ // setSelectedNotePath (which runs only on the non-early path) was not calledexpect($el.attr("data-note-path") ?? "").toBe("");});});diff --git a/apps/client/src/services/note_tooltip.spec.ts b/apps/client/src/services/note_tooltip.spec.tsindex 3fc53046f7..4f0043335f 100644--- a/apps/client/src/services/note_tooltip.spec.ts+++ b/apps/client/src/services/note_tooltip.spec.ts@@ -307,23 +307,43 @@ describe("mouseEnterHandler", () => {expect($link.attr("data-link-id")).toBe("existing");});- it("returns without showing a tooltip when rendered content is empty", async () => {+ it("assigns a fresh random link id and skips the tooltip on the not-hovering branch", async () => {vi.useFakeTimers();const $link = makeLink('<a href="#root/abc">x</a>');parseNavigationStateFromUrl.mockReturnValue({ notePath: "root/abc", noteId: "abc", viewScope: { viewMode: "default" } });+ // null note renders the deleted placeholder which isHtmlEmpty treats as non-empty,+ // so the suppression here comes from the not-hovering branch (hoverActive is false),+ // NOT the empty-content guard (which is covered separately below while hovering).froca.getNote = vi.fn(async () => null) as any;const promise = mouseEnterHandler.call($link[0], eventFor($link));await vi.advanceTimersByTimeAsync(600);await promise;- // null note renders the deleted placeholder which isHtmlEmpty treats as non-empty,- // but we are not hovering, so no tooltip is created.+ // not hovering -> no tooltip is created.expect(($.fn as any).tooltip).not.toHaveBeenCalled();// a fresh random link id was assignedexpect($link.attr("data-link-id")).toMatch(/^link-\d+$/);});+ it("returns without showing a tooltip when the rendered note content is empty while hovering", async () => {+ vi.useFakeTimers();+ const $link = makeLink('<a href="#root/abc">x</a>');+ parseNavigationStateFromUrl.mockReturnValue({ notePath: "root/abc", noteId: "abc", viewScope: { viewMode: "default" } });+ // A note with no best note path makes renderTooltip resolve to `undefined`,+ // so the empty-content guard (`!content`) fires even though we ARE hovering.+ const note = fakeNote({ noteId: "abc", bestPath: undefined });+ froca.getNote = vi.fn(async () => note) as any;+ hoverActive = true;++ const promise = mouseEnterHandler.call($link[0], eventFor($link));+ await vi.advanceTimersByTimeAsync(600);+ await promise;++ // hovering, but empty content -> early return before the tooltip is created.+ expect(($.fn as any).tooltip).not.toHaveBeenCalled();+ });+it("returns without showing a tooltip when the footnote target yields empty content", async () => {vi.useFakeTimers();// anchor with no matching target -> renderFootnoteOrAnchor returns ""@@ -404,8 +424,19 @@ describe("mouseEnterHandler", () => {await promise;expect(froca.getNote).not.toHaveBeenCalled();- // hovered -> tooltip shown (init call + "show" call)- expect(($.fn as any).tooltip).toHaveBeenCalled();+ // hovered -> tooltip was both initialised and explicitly shown.+ const tooltipMock = ($.fn as any).tooltip as ReturnType<typeof vi.fn>;+ expect(tooltipMock).toHaveBeenCalledWith("show");++ // The init call carries the rendered footnote body in its title and the+ // note-tooltip class in its template.+ const initCall = tooltipMock.mock.calls.find((c) => typeof c[0] === "object");+ expect(initCall?.[0].title).toContain("footnote body");+ expect(initCall?.[0].template).toContain("note-tooltip");+ // note is null on the footnote path, so the template carries only the random+ // tooltip-<n> class with no trailing color class.+ expect(initCall?.[0].template).toMatch(/tooltip note-tooltip tooltip-\d+"/);+ expect(initCall?.[0].template).not.toContain("color-");});it("creates, shows and tracks a tooltip while hovering, then dismisses on click and via the watchdog", async () => {diff --git a/apps/client/src/services/note_types.spec.ts b/apps/client/src/services/note_types.spec.tsindex 242a1c4de5..4810c04ede 100644--- a/apps/client/src/services/note_types.spec.ts+++ b/apps/client/src/services/note_types.spec.ts@@ -98,13 +98,24 @@ describe("getBlankNoteTypes (via getNoteTypeItems)", () => {expect(item.uiIcon.startsWith("bx ")).toBe(true);}- // isNew -> NEW badge, isBeta -> BETA badge. spreadsheet is both new+beta.+ // the per-type `mime` is mapped through verbatim (note creation depends on it)+ const text = cmdItems.find((i: any) => i.type === "text");+ expect(text.mime).toBe("text/html");const spreadsheet = cmdItems.find((i: any) => i.type === "spreadsheet");+ expect(spreadsheet.mime).toBe("application/json");++ // isNew -> NEW badge, isBeta -> BETA badge. spreadsheet is both new+beta.expect(spreadsheet.badges).toHaveLength(2);- expect(spreadsheet.badges.some((b: any) => b.className === "new-note-type-badge")).toBe(true);+ // exactly one NEW badge (has the className) ...+ const newBadges = spreadsheet.badges.filter((b: any) => b.className === "new-note-type-badge");+ expect(newBadges).toHaveLength(1);+ // ... and exactly one BETA badge (the badge with only a title, no className).+ const betaBadges = spreadsheet.badges.filter((b: any) => b.className === undefined);+ expect(betaBadges).toHaveLength(1);+ expect(typeof betaBadges[0].title).toBe("string");+ expect(betaBadges[0].title.length).toBeGreaterThan(0);// text has no badges- const text = cmdItems.find((i: any) => i.type === "text");expect(text.badges).toEqual([]);} finally {restore();@@ -116,8 +127,16 @@ describe("getBlankNoteTypes (via getNoteTypeItems)", () => {const restore = withTemplatesRoot([]);try {const items = await noteTypesService.getNoteTypeItems();- const types = items.filter((i: any) => i.type).map((i: any) => i.type);+ const cmdItems: any[] = items.filter((i: any) => i.type);+ const types = cmdItems.map((i: any) => i.type);expect(types).toContain("llmChat");++ // llmChat is isBeta only -> exactly one BETA badge (title, no className).+ const llmChat = cmdItems.find((i: any) => i.type === "llmChat");+ expect(llmChat.badges).toHaveLength(1);+ expect(llmChat.badges[0].className).toBeUndefined();+ expect(typeof llmChat.badges[0].title).toBe("string");+ expect(llmChat.badges[0].title.length).toBeGreaterThan(0);} finally {restore();}@@ -185,12 +204,27 @@ describe("getBuiltInTemplates", () => {// Collections pass (filterCollections=true, title set) pushes a header then// the collection template.- expect(items.some((i) => i.kind === "header")).toBe(true);+ const headerIdx = items.findIndex((i) => i.kind === "header");+ expect(headerIdx).toBeGreaterThanOrEqual(0);expect(items.some((i) => i.templateNoteId === "tpl-coll")).toBe(true);// The note missing the "template" label is never included.expect(items.some((i) => i.templateNoteId === "tpl-skip")).toBe(false);+ // Each template is emitted in EXACTLY ONE pass — the label filter must keep+ // tpl-plain out of the collections pass and tpl-coll out of the non-collection+ // pass. An inverted/broken filter would emit a template in both passes (a+ // duplicate), which `.some(...)` above would not catch.+ const plainIdx = items.findIndex((i) => i.templateNoteId === "tpl-plain");+ const collIdx = items.findIndex((i) => i.templateNoteId === "tpl-coll");+ expect(items.filter((i) => i.templateNoteId === "tpl-plain")).toHaveLength(1);+ expect(items.filter((i) => i.templateNoteId === "tpl-coll")).toHaveLength(1);++ // ...and the placement reflects which pass emitted them: tpl-plain (non-collection+ // pass) precedes the collections header; tpl-coll (collections pass) follows it.+ expect(plainIdx).toBeLessThan(headerIdx);+ expect(collIdx).toBeGreaterThan(headerIdx);+// built-in template items carry command/type/icon/title.const plainItem = items.find((i) => i.templateNoteId === "tpl-plain");expect(plainItem.command).toBe("cmd");diff --git a/apps/client/src/services/open.spec.ts b/apps/client/src/services/open.spec.tsindex df53d84c92..a2d5fbbbc9 100644--- a/apps/client/src/services/open.spec.ts+++ b/apps/client/src/services/open.spec.ts@@ -86,6 +86,15 @@ describe("open service", () => {downloadFileNote(note, null, undefined);expect(window.location.href).toContain(`api/notes/${note.noteId}/download?`);});++ it("downloads via URL (not customDownload) for an ordinary file even when a parent component is present", () => {+ const note = buildNote({ title: "Plain", type: "file" });+ (note as any).mime = "image/png";+ const parent = { triggerEvent: vi.fn() } as any;+ downloadFileNote(note, parent, "ntx-2");+ expect(parent.triggerEvent).not.toHaveBeenCalled();+ expect(window.location.href).toContain(`api/notes/${note.noteId}/download?`);+ });});describe("downloadAttachment", () => {@@ -180,17 +189,32 @@ describe("open service", () => {});describe("openNoteOnServer", () => {- it("logs an error when no sync server host is configured", async () => {+ // options is a process-wide singleton with no reset between spec files; capture the+ // original value and restore it so these tests do not leak into other specs.+ let originalSyncServerHost: string | undefined;++ beforeEach(async () => {await options.initializedPromise;+ originalSyncServerHost = options.get("syncServerHost");+ });++ afterEach(() => {+ if (originalSyncServerHost === undefined) {+ options.set("syncServerHost", "");+ } else {+ options.set("syncServerHost", originalSyncServerHost);+ }+ });++ it("logs an error when no sync server host is configured", async () => {options.set("syncServerHost", "");const errSpy = vi.spyOn(console, "error").mockImplementation(() => {});await open.openNoteOnServer("n5");- expect(errSpy).toHaveBeenCalled();+ expect(errSpy).toHaveBeenCalledWith("No sync server host configured");expect(window.open).not.toHaveBeenCalled();});it("opens the note URL in a new browser tab when a sync server host is set", async () => {- await options.initializedPromise;options.set("syncServerHost", "https://sync.example.com");await open.openNoteOnServer("n6");expect(window.open).toHaveBeenCalledWith(diff --git a/apps/client/src/services/options.spec.ts b/apps/client/src/services/options.spec.tsindex 232948d3e2..790f0c7f12 100644--- a/apps/client/src/services/options.spec.ts+++ b/apps/client/src/services/options.spec.ts@@ -17,6 +17,12 @@ describe("Options service", () => {// The constructor (non-share branch) issues server.get("options"); the global// mock returns {}. Awaiting the promise exercises load() and leaves arr = {}.await options.initializedPromise;++ // Establish the empty-record state explicitly via load({}) so this assertion does+ // not silently depend on this test running BEFORE the load()/set() tests that+ // mutate the shared singleton's backing record (the singleton is never reset+ // between tests). This makes the empty-names check order-independent.+ options.load({});expect(options.getNames()).toEqual([]);});@@ -129,6 +135,21 @@ describe("Options service", () => {expect(warn).toHaveBeenCalledTimes(1);expect(fresh.getFloat(k("anything"))).toBeNull();+ // Asymmetry: get/getNames/getJson/getInt/getFloat all read `this.arr?.[key]`+ // and tolerate the uninitialized (undefined) record, but the remaining+ // accessors do NOT use optional chaining and therefore THROW on a fresh+ // share-branch instance where `arr` was never assigned:+ // is() -> `this.arr[key]` (source line 64)+ // set() -> `this.arr[key] = ...` (source line 68)+ // save() -> calls set() (source line 72)+ // toggle() -> calls is() then save (source line 89)+ // Pin this real behavioral difference so a regression that added/removed the+ // optional chaining on either group would be caught.+ expect(() => fresh.is(k("anything"))).toThrow();+ expect(() => fresh.set(k("anything"), "v")).toThrow();+ await expect(fresh.save(k("anything"), "v")).rejects.toThrow();+ await expect(fresh.toggle(k("anything"))).rejects.toThrow();+vi.doUnmock("./utils.js");vi.resetModules();});diff --git a/apps/client/src/services/protected_session.spec.ts b/apps/client/src/services/protected_session.spec.tsindex 1858f5c255..5c5486016c 100644--- a/apps/client/src/services/protected_session.spec.ts+++ b/apps/client/src/services/protected_session.spec.ts@@ -19,12 +19,23 @@ vi.mock("./ws.js", () => ({}}));+// i18next is never `.init()`ed in this unit-test environment, so the real+// `t()` returns `undefined`, erasing the toast text/title. Mock `t` with a+// deterministic key-based serializer so we can assert which translation KEY+// (and the `count` interpolation) the source selected for each branch -- the+// structure/args, never a human-readable translated string.+vi.mock("./i18n.js", () => ({+ t: (key: string, opts?: Record<string, unknown>) =>+ opts && "count" in opts ? `${key}:count=${opts.count}` : key+}));+import appContext from "../components/app_context.js";import froca from "./froca.js";import options from "./options.js";import protectedSessionHolder from "./protected_session_holder.js";import server from "./server.js";import toastService from "./toast.js";+import type { ToastOptionsWithRequiredId } from "./toast.js";import utils from "./utils.js";let protectedSession: typeof import("./protected_session.js").default;@@ -52,7 +63,11 @@ describe("enterProtectedSession", () => {expect(options.is).toHaveBeenCalledWith("isPasswordSet");expect(triggerCommand).toHaveBeenCalledWith("showPasswordNotSet");- // returns the raw deferred (not the promise) in this branch+ // returns the RAW deferred (not dfd.promise()) in this branch: a jQuery+ // Deferred is externally resolvable, so it exposes `.resolve`, whereas a+ // `.promise()` object does not. `.promise` exists on both, so it cannot+ // distinguish the two branches.+ expect(typeof (result as any).resolve).toBe("function");expect(typeof (result as any).promise).toBe("function");});@@ -239,9 +254,21 @@ describe("protectNotes task ws handler", () => {data: { protect: true }});+ // Beyond id/icon, the toast must carry the interpolated progress text+ // (protecting key + the progressCount) and the protecting title. The+ // mocked `t` serializes the selected KEY and `count`, so we assert+ // structure/args, never a translated string.+ const toast = showPersistent.mock.calls[0][0] as ToastOptionsWithRequiredId;expect(showPersistent).toHaveBeenCalledWith(- expect.objectContaining({ id: "task-prot", icon: "check-shield" })+ expect.objectContaining({+ id: "task-prot",+ icon: "check-shield",+ message: "protected_session.protecting-in-progress:count=5",+ title: "protected_session.protecting-title"+ }));+ // The progressCount must be interpolated into the message.+ expect(toast.message).toContain("count=5");});it("shows a persistent progress toast while unprotecting", async () => {@@ -255,9 +282,45 @@ describe("protectNotes task ws handler", () => {data: { protect: false }});+ const toast = showPersistent.mock.calls[0][0] as ToastOptionsWithRequiredId;expect(showPersistent).toHaveBeenCalledWith(- expect.objectContaining({ id: "task-unprot", icon: "shield" })+ expect.objectContaining({+ id: "task-unprot",+ icon: "shield",+ message: "protected_session.unprotecting-in-progress-count:count=2",+ title: "protected_session.unprotecting-title"+ }));+ expect(toast.message).toContain("count=2");+ });++ it("uses distinct progress text for the protecting vs unprotecting branch", async () => {+ // Drive both branches within one test so the assertion is self-contained+ // and not dependent on sibling-test ordering. The protect/unprotect ternary+ // (source line 122) must select different text for each.+ const showPersistent = vi.spyOn(toastService, "showPersistent").mockReturnValue(undefined as any);++ await dispatch({+ type: "taskProgressCount",+ taskType: "protectNotes",+ taskId: "task-prot-text",+ progressCount: 5,+ data: { protect: true }+ });+ await dispatch({+ type: "taskProgressCount",+ taskType: "protectNotes",+ taskId: "task-unprot-text",+ progressCount: 5,+ data: { protect: false }+ });++ const protectingToast = showPersistent.mock.calls[0][0] as ToastOptionsWithRequiredId;+ const unprotectingToast = showPersistent.mock.calls[1][0] as ToastOptionsWithRequiredId;+ // Same progressCount, opposite protect flag => the message/title text must+ // diverge (different translation keys are selected per branch).+ expect(protectingToast.message).not.toBe(unprotectingToast.message);+ expect(protectingToast.title).not.toBe(unprotectingToast.title);});it("shows a timed success toast on taskSucceeded for both protecting and unprotecting", async () => {diff --git a/apps/client/src/services/render.spec.tsx b/apps/client/src/services/render.spec.tsxindex 56823c30af..9709ce9696 100644--- a/apps/client/src/services/render.spec.tsx+++ b/apps/client/src/services/render.spec.tsx@@ -13,6 +13,10 @@ vi.mock("../widgets/react/react_utils.jsx", () => ({renderReactWidgetAtElement: (...args: unknown[]) => renderAtElementMock(...args)}));+import FAttribute from "../entities/fattribute.js";+import type FNote from "../entities/fnote.js";+import noteAttributeCache from "../services/note_attribute_cache.js";+import utils from "../services/utils.js";import { buildNote } from "../test/easy-froca";import froca from "./froca.js";import renderDefault, { render, renderIfJsx } from "./render.js";@@ -20,6 +24,24 @@ import server from "./server.js";const flush = () => new Promise<void>((resolve) => setTimeout(resolve, 0));+// Adds an extra `~renderNote` relation to an already-built note (buildNote's+// object-literal API can only express one relation per key).+function addRenderNoteRelation(note: FNote, targetNoteId: string) {+ const attributeId = utils.randomString(12);+ const attribute = new FAttribute(froca, {+ noteId: note.noteId,+ attributeId,+ type: "relation",+ name: "renderNote",+ value: targetNoteId,+ position: note.attributes.length,+ isInheritable: false+ });+ froca.attributes[attributeId] = attribute;+ note.attributes.push(attributeId);+ (noteAttributeCache.attributes[note.noteId] ??= []).push(attribute);+}+describe("render", () => {beforeEach(() => {vi.clearAllMocks();@@ -78,6 +100,44 @@ describe("render", () => {expect($container.length).toBe(1);expect($container.html()).toContain("hi");expect(executeMock).toHaveBeenCalledOnce();+ // The bundle is executed with the resolved bundle object, the HOST note+ // (not the target render note), and the appended $scriptContainer element.+ const [bundleArg, noteArg, containerArg] = executeMock.mock.calls[0];+ expect(bundleArg).toEqual(+ expect.objectContaining({ html: "<p>hi</p>", noteId: "scriptNote" })+ );+ expect(noteArg).toBe(note);+ expect(noteArg).not.toBe(target);+ // Third arg is the jQuery-wrapped container that was appended to $el.+ expect((containerArg as JQuery<HTMLElement>)[0]).toBe($container[0]);+ });++ it("loops over every renderNote relation: one container + bundle fetch + execution per target", async () => {+ const target1 = buildNote({ title: "Target A" });+ const target2 = buildNote({ title: "Target B" });+ const note = buildNote({ title: "Multi host", "~renderNote": target1.noteId });+ addRenderNoteRelation(note, target2.noteId);+ const $el = $("<div>");++ const result = await render(note, $el);++ expect(result).toBe(true);+ // A separate script container is appended per render-note relation.+ expect($el.children().length).toBe(2);+ // The bundle endpoint is requested once per target id.+ expect(server.postWithSilentInternalServerError).toHaveBeenCalledTimes(2);+ expect(server.postWithSilentInternalServerError).toHaveBeenCalledWith(`script/bundle/${target1.noteId}`);+ expect(server.postWithSilentInternalServerError).toHaveBeenCalledWith(`script/bundle/${target2.noteId}`);+ // The bundle is executed once per target, each into its own container.+ expect(executeMock).toHaveBeenCalledTimes(2);+ const firstContainer = executeMock.mock.calls[0][2] as JQuery<HTMLElement>;+ const secondContainer = executeMock.mock.calls[1][2] as JQuery<HTMLElement>;+ expect(firstContainer[0]).toBe($el.children()[0]);+ expect(secondContainer[0]).toBe($el.children()[1]);+ expect(firstContainer[0]).not.toBe(secondContainer[0]);+ // Both executions are wired to the host note, not the targets.+ expect(executeMock.mock.calls[0][1]).toBe(note);+ expect(executeMock.mock.calls[1][1]).toBe(note);});it("invokes onError when the bundle could not be loaded", async () => {diff --git a/apps/client/src/services/resizer.spec.ts b/apps/client/src/services/resizer.spec.tsindex 9af6d6db90..5540e97899 100644--- a/apps/client/src/services/resizer.spec.ts+++ b/apps/client/src/services/resizer.spec.ts@@ -37,6 +37,21 @@ function setRightPaneVisible(visible: boolean) {});}+/**+ * Force `$("#launcher-pane").outerWidth()` to a chosen pixel value (happy-dom has+ * no layout, so it otherwise returns 0). Used to exercise the vertical-layout+ * reserved-width math, which is invisible when the reserved width collapses to 0.+ */+function setLauncherPaneWidth(px: number) {+ const origOuterWidth = ($ as any).fn.outerWidth;+ return vi.spyOn(($ as any).fn, "outerWidth").mockImplementation(function (this: any, ...args: any[]) {+ if (this[0]?.id === "launcher-pane") {+ return px;+ }+ return origOuterWidth.apply(this, args);+ });+}+/*** Load a fresh copy of resizer.ts (its module-level state is otherwise a* singleton that never resets) with options.get/getInt stubbed to the supplied@@ -97,11 +112,39 @@ describe("setupLeftPaneResizer", () => {});it("when left pane is hidden in vertical layout, reserves launcher-pane width", async () => {+ // Give the launcher pane a real width so the vertical reservation math+ // produces a value distinguishable from the horizontal 100% case.+ setLauncherPaneWidth(120);const { resizer } = await loadResizer({ layoutOrientation: "vertical" });resizer.setupLeftPaneResizer(false);- // launcher-pane outerWidth() is 0 in happy-dom (no layout) -> reservedWidth 0 -> 100%.+ // reservedWidth = 120 / window.innerWidth * 100; rest-pane = (100 - reservedWidth)%.+ const reservedWidth = (120 / window.innerWidth) * 100;+ expect(reservedWidth).toBeGreaterThan(0);+ expect($("#rest-pane").css("width")).toBe(`${100 - reservedWidth}%`);+ // Must be strictly less than the horizontal 100% so a broken reservation is caught.+ const restPaneWidthValue = parseFloat($("#rest-pane").css("width"));+ expect(restPaneWidthValue).toBeLessThan(100);+ });++ it("when left pane is hidden in vertical layout with no launcher width, falls back to 100%", async () => {+ // launcher-pane outerWidth() is 0 in happy-dom (no layout) -> the `|| 0`+ // fallback yields reservedWidth 0 -> rest-pane 100%.+ const { resizer } = await loadResizer({ layoutOrientation: "vertical" });++ resizer.setupLeftPaneResizer(false);++ expect($("#rest-pane").css("width")).toBe("100%");+ });++ it("when left pane is hidden in horizontal layout, does NOT reserve launcher-pane width", async () => {+ // Even with a non-zero launcher width, the horizontal branch ignores it.+ setLauncherPaneWidth(120);+ const { resizer } = await loadResizer({ layoutOrientation: "horizontal" });++ resizer.setupLeftPaneResizer(false);+expect($("#rest-pane").css("width")).toBe("100%");});@@ -125,6 +168,13 @@ describe("setupLeftPaneResizer", () => {// onDragEnd rounds and saves the new left pane width.config.onDragEnd([42.6, 57.4]);expect(options.save).toHaveBeenCalledWith("leftPaneWidth", 43);++ // onDragEnd also mutates the module-level cache: a subsequent rebuild must use+ // the NEW (dragged + rounded) width 43, not the original 30 -> sizes [43, 57].+ resizer.setupLeftPaneResizer(true);+ flushRaf();+ expect(SplitMock).toHaveBeenCalledTimes(2);+ expect(SplitMock.mock.calls[1][1].sizes).toEqual([43, 57]);});it("clamps a missing stored width (getInt -> null) up to the minimum of 5", async () => {@@ -205,6 +255,12 @@ describe("setupRightPaneResizer", () => {config.onDragEnd([60.2, 39.8]);expect(options.save).toHaveBeenCalledWith("rightPaneWidth", 40);++ // onDragEnd also mutates the module-level cache: a subsequent rebuild must use+ // the NEW (dragged + rounded) width 40, not the original 25 -> sizes [60, 40].+ resizer.setupRightPaneResizer();+ expect(SplitMock).toHaveBeenCalledTimes(2);+ expect(SplitMock.mock.calls[1][1].sizes).toEqual([60, 40]);isSpy.mockRestore();});diff --git a/apps/client/src/services/server.spec.ts b/apps/client/src/services/server.spec.tsindex c7a9b67515..1ce3e5546e 100644--- a/apps/client/src/services/server.spec.ts+++ b/apps/client/src/services/server.spec.ts@@ -210,7 +210,9 @@ describe("ajax error handling", () => {(window as any).$.ajax = (opts: AjaxOptions) => {opts.error({ status: 400, responseText: JSON.stringify({ message: "Bad input" }) });};- await expect(server.post("url", {})).rejects.toBeDefined();+ // The ValidationError thrown inside reportError is swallowed by the catch in ajax();+ // the request must still reject with the raw responseText, NOT the ValidationError instance.+ await expect(server.post("url", {})).rejects.toBe(JSON.stringify({ message: "Bad input" }));expect(toastMock.showError).toHaveBeenCalledWith("Bad input");});diff --git a/apps/client/src/services/spaced_update.spec.ts b/apps/client/src/services/spaced_update.spec.tsindex 5ee74f27f4..dd71c2d7e8 100644--- a/apps/client/src/services/spaced_update.spec.ts+++ b/apps/client/src/services/spaced_update.spec.ts@@ -151,6 +151,48 @@ describe("SpacedUpdate", () => {expect(spacedUpdate.isAllSavedAndTriggerUpdate()).toBe(true);expect(updater).not.toHaveBeenCalled();});++ it("returns the pre-flush saved state synchronously and kicks off the un-awaited flush", () => {+ const updater = vi.fn(async () => {});+ const spacedUpdate = new SpacedUpdate(updater, 50);++ spacedUpdate.scheduleUpdate(); // pending change++ // `allSaved` is computed from `changed` BEFORE the (un-awaited) updateNowIfNecessary()+ // flush runs, so the call returns false for a pending change and never throws.+ let result: boolean;+ expect(() => {+ result = spacedUpdate.isAllSavedAndTriggerUpdate();+ }).not.toThrow();+ expect(result!).toBe(false);++ // The flush was started synchronously (updater invoked) rather than awaited.+ expect(updater).toHaveBeenCalledTimes(1);+ });++ it("restores the changed flag when an update fails so a later flush retries", async () => {+ const states: string[] = [];+ let shouldFail = true;+ const updater = vi.fn(async () => {+ if (shouldFail) {+ throw new Error("flush boom");+ }+ });+ const spacedUpdate = new SpacedUpdate(updater, 50, (s) => states.push(s));++ spacedUpdate.scheduleUpdate();++ // Await the flush directly (the same code path isAllSavedAndTriggerUpdate fires+ // and forgets) so the rejection is observed here instead of floating.+ await expect(spacedUpdate.updateNowIfNecessary()).rejects.toThrow("flush boom");+ expect(states).toContain("error");++ // The catch restored `changed`, so a subsequent flush retries the updater and saves.+ shouldFail = false;+ await spacedUpdate.updateNowIfNecessary();+ expect(updater).toHaveBeenCalledTimes(2);+ expect(states).toContain("saved");+ });});describe("resetUpdateTimer / setUpdateInterval", () => {diff --git a/apps/client/src/services/sync.spec.ts b/apps/client/src/services/sync.spec.tsindex 8ff26fb067..a9ef022343 100644--- a/apps/client/src/services/sync.spec.ts+++ b/apps/client/src/services/sync.spec.ts@@ -44,6 +44,9 @@ describe("syncNow", () => {expect(server.post).toHaveBeenCalledWith("sync/now");expect(showMessage).toHaveBeenCalledTimes(1);+ // Pin the exact success key so a typo'd or swapped key (e.g. the failure key) is caught.+ expect(translate).toHaveBeenCalledWith("sync.finished-successfully");+ expect(showMessage).toHaveBeenCalledWith({ key: "sync.finished-successfully", opts: undefined });expect(showError).not.toHaveBeenCalled();});diff --git a/apps/client/src/services/syntax_highlight.spec.ts b/apps/client/src/services/syntax_highlight.spec.tsindex e3a143604c..0c0a5ec2d2 100644--- a/apps/client/src/services/syntax_highlight.spec.ts+++ b/apps/client/src/services/syntax_highlight.spec.ts@@ -45,6 +45,17 @@ vi.mock("@triliumnext/highlightjs", () => {};});+// Spy on the clipboard helpers so we can assert which copy path the click handlers take+// (copyTextWithToast in-app vs copyText in share mode). Persists across vi.resetModules().+const clip = vi.hoisted(() => ({+ copyText: vi.fn(),+ copyTextWithToast: vi.fn()+}));+vi.mock("./clipboard_ext.js", () => ({+ copyText: (t: string) => clip.copyText(t),+ copyTextWithToast: (t: string) => clip.copyTextWithToast(t)+}));+// Imports AFTER the vi.mock calls (which are hoisted above imports anyway).import type OptionsType from "./options.js";@@ -251,34 +262,49 @@ describe("syntax_highlight", () => {describe("copy buttons", () => {it("appends a copy button that copies via toast when not in share mode", async () => {+ clip.copyText.mockClear();+ clip.copyTextWithToast.mockClear();const mod = await freshModule();const $code = $codeBlock("copy me");mod.applyCopyToClipboardButton($code);const $btn = $code.parent().find("button.copy-button");expect($btn.length).toBe(1);- // exercise the click handler (non-share path)++ // Non-share path: the click copies the code block's text via the toast helper.$btn.trigger("click");+ expect(clip.copyTextWithToast).toHaveBeenCalledWith("copy me");+ expect(clip.copyText).not.toHaveBeenCalled();});it("copy button uses the plain copy path in share mode", async () => {+ clip.copyText.mockClear();+ clip.copyTextWithToast.mockClear();const mod = await freshModule();ctrl.isShare = true;const $code = $codeBlock("share copy");mod.applyCopyToClipboardButton($code);$code.parent().find("button.copy-button").trigger("click");++ // Share path: plain copyText, no toast.+ expect(clip.copyText).toHaveBeenCalledWith("share copy");+ expect(clip.copyTextWithToast).not.toHaveBeenCalled();});it("inline code copy adds class + handler for both share and non-share", async () => {+ clip.copyText.mockClear();+ clip.copyTextWithToast.mockClear();const mod = await freshModule();const $inline = $("<code>").text("inline");mod.applyInlineCodeCopy($inline);expect($inline.hasClass("copyable-inline-code")).toBe(true);$inline.trigger("click"); // non-share path+ expect(clip.copyTextWithToast).toHaveBeenCalledWith("inline");ctrl.isShare = true;const $inline2 = $("<code>").text("inline share");mod.applyInlineCodeCopy($inline2);$inline2.trigger("click"); // share path+ expect(clip.copyText).toHaveBeenCalledWith("inline share");});});