Files
Netcatty/components/notes/NotesManager.test.tsx
T
cc5ad3be16 perf: isolate Terminal hot props, cut memory/jank, and repay architecture debt (#2790)
* refactor: migrate architecture-debt hooks into application/state

Move SFTP Wave A stores/hooks and related vault/AI/terminal/systemManager
hooks out of components into application/state, update importers, and keep
thin deprecated re-exports at the old paths.

Co-authored-by: 陈大猫 <binaricat@users.noreply.github.com>

* refactor(sftp): align local bookmarks store API with global bookmarks

Export subscribe/get/set/rehydrate helpers from localSftpBookmarks to match
the globalSftpBookmarks external-store pattern.

Co-authored-by: 陈大猫 <binaricat@users.noreply.github.com>

* fix(electron): reduce baseline memory via spellcheck/GPU/prewarm guards

Disable spellcheck on BrowserWindows and the default session, drop spare
renderers, gate aggressive GPU switches behind NETCATTY_COMPAT_GPU, and make
settings prewarm opt-in via NETCATTY_PREWARM_SETTINGS.

Co-authored-by: 陈大猫 <binaricat@users.noreply.github.com>

* Isolate notes and customAccent from TerminalLayer hot props

Route vault notes through notesStore (shellHistoryStore pattern) and
app accent through appearanceChromeStore so note edits and accent-drag
ticks no longer rebuild TerminalLayer. Notes/AI slots and Terminal leaves
subscribe locally; VaultView and open-note callbacks stay unchanged.

Co-authored-by: 陈大猫 <binaricat@users.noreply.github.com>

* fix(ui): cut unnecessary AppView/VaultView/settings re-renders

Stabilize TopTabs close handler, memo AppHostTreeLayer, exclude accent from
settingsVersion, ignore connectionLogs off the logs section, share lastConnected
host refs, and keep rename dialog drafts local so chrome domain stays stable.

Co-authored-by: 陈大猫 <binaricat@users.noreply.github.com>

* chore: package size, dead code, and consolidation cleanup

Remove unused direct deps, exclude Vite-bundled renderer packages from
electron-builder, delete high-confidence dead code/no-op transfer warm
wiring, consolidate cloud provider IDs and KnownHost/SFTP helpers, and
land UI/AGENTS quick wins (rAF text batching, notes draft debounce,
streaming plain text, tempDirBridge, diagnostics adapter, External MCP
setters).

Co-authored-by: 陈大猫 <binaricat@users.noreply.github.com>

* fix: stabilize rAF text batching and diagnostics tests

Polyfill requestAnimationFrame for Node, flush pending text before
steer buffering, bypass rAF while steer is in flight, and stub
global localStorage for AI panel diagnostics adapter tests.

Co-authored-by: 陈大猫 <binaricat@users.noreply.github.com>

* fix: correct import paths after application/state hook migrations

Migrated vault/AI/system hooks still used components/-relative imports;
point them at repo-root domain/components/types/lib instead.

Co-authored-by: 陈大猫 <binaricat@users.noreply.github.com>

* fix: address Bugbot/Codex regressions from perf cleanup

- Keep blank Enter from closing RenameDraftDialog; only reset rename state after a non-empty submit
- Flush note drafts before vault mutations so pending title/body edits are not overwritten
- Re-apply appearanceChromeStore accent on appearanceTheme in Terminal, and keep layer themes unaccented

Co-authored-by: 陈大猫 <binaricat@users.noreply.github.com>

* fix(notes): flush draft before markdown export paths

Co-authored-by: 陈大猫 <binaricat@users.noreply.github.com>

* fix: keep editor-close hotkey ref fresh during render

Assign handleRequestCloseEditorTabRef in render instead of useEffect so
Cmd/Ctrl+W never hits the App stub before the effect runs.

Co-authored-by: 陈大猫 <binaricat@users.noreply.github.com>

* fix: keep accent in chrome themes without TerminalLayer thrash

Restore accent in globalAppearance for chrome/injection consumers.
Keep resolveFocusedAppearance identity stable across accent drag via
accent ref, while Terminal leaf still re-applies appearanceChromeStore.

Co-authored-by: 陈大猫 <binaricat@users.noreply.github.com>

* fix: keep compose chrome accent live and merge note renames

Subscribe theme-panel focusedAppearance to appearanceChromeStore so
compose-bar chrome updates during color-picker drag even when
resolveFocusedAppearance identity stays stable. Tree renames now merge
title into the post-flush note instead of replacing from a stale row.

Co-authored-by: 陈大猫 <binaricat@users.noreply.github.com>

* fix: clear terminal accent when switching back to theme mode

Re-resolve appearanceTheme by catalog id before applyCustomAccent so a
stale baked custom cursor/selection cannot stick after accentMode returns
to theme while TerminalLayer memo ignores accent props.

Co-authored-by: 陈大猫 <binaricat@users.noreply.github.com>

* fix: register unsaved prompt singleton during render

AppView close handlers call promptUnsavedChanges outside the old
render-prop. Assign the singleton during render so Cmd/Ctrl+W and tab
close never hit the pre-effect null window that auto-cancels.

Co-authored-by: 陈大猫 <binaricat@users.noreply.github.com>

* fix: keep vault import hooks UI-free and flush notes on teardown

Move ImportOptions into application/state and inject a notifier so
useVaultImportHandlers no longer imports components. Notes drafts also
flush on pagehide/beforeunload when Electron tears down without React
unmount.

Co-authored-by: 陈大猫 <binaricat@users.noreply.github.com>

* fix: move AI terminal session context builders into domain

buildAITerminalSessionInfo and AIPanelContext now live under domain/ so
application hooks no longer import TerminalLayerSupport and create a
UI → application → UI cycle.

Co-authored-by: 陈大猫 <binaricat@users.noreply.github.com>

* fix: drop duplicate AIPanelContext type from TerminalLayerSupport

The type is re-exported from domain; the local definition conflicted.

Co-authored-by: 陈大猫 <binaricat@users.noreply.github.com>

* fix: keep migrated state hooks free of UI-layer imports

Move aiChatStreamingSupport into infrastructure/ai and poll list helpers
into domain/systemManager so useAIChatStreaming / useSystemManager no
longer import from components. Leave thin re-exports at the old paths.

Co-authored-by: 陈大猫 <binaricat@users.noreply.github.com>

* fix: move remaining migrated-hook deps out of components

Host-key verification types/helpers now live in domain/, and SFTP column
layout types live in application/state/sftp/columnLayout. Application
hooks no longer import those definitions from the UI layer.

Co-authored-by: 陈大猫 <binaricat@users.noreply.github.com>

* fix: clear lint blockers and flush notes when panels hide

Move AI panel diagnostics persistence into application/state so
components stop importing localStorageAdapter. Flush note drafts when
retained NotesManager mounts become inactive, and silence related lint
warnings in theme/host-key helpers.

Co-authored-by: 陈大猫 <binaricat@users.noreply.github.com>

* fix(notes): publish notesStore sync on vault note updates

updateNotes/updateNoteGroups now publishNotesSnapshot immediately so
AI/notes consumers do not briefly read a stale catalog after a hide
flush. Flush inactive drafts in useLayoutEffect before paint.

Co-authored-by: 陈大猫 <binaricat@users.noreply.github.com>

---------

Co-authored-by: Cursor Agent <cursoragent@cursor.com>
Co-authored-by: 陈大猫 <binaricat@users.noreply.github.com>
2026-08-07 14:40:38 +08:00

312 lines
11 KiB
TypeScript

import test from "node:test";
import assert from "node:assert/strict";
import { readFileSync } from "node:fs";
import React from "react";
import { renderToStaticMarkup } from "react-dom/server";
import { I18nProvider } from "../../application/i18n/I18nProvider.tsx";
import type { VaultNote } from "../../types.ts";
import { TooltipProvider } from "../ui/tooltip.tsx";
import {
getFallbackNoteSelectionState,
getNoteActionTargetGroup,
getNoteGroupSelectionState,
getNotesGroupDropAction,
getNoteSelectionState,
getValidatedNoteSelectionState,
getSelectedVaultNote,
isNoteFolderTreeSelected,
NotesManager,
} from "./NotesManager.tsx";
const note = (overrides: Partial<VaultNote> = {}): VaultNote => ({
id: "note-1",
title: "Postgres failover checklist",
content: "# Steps\n\nPromote replica",
group: "Ops",
createdAt: 1,
updatedAt: 1,
order: 1000,
...overrides,
});
const renderNotes = (
notes: VaultNote[] = [note()],
displayMode: React.ComponentProps<typeof NotesManager>["displayMode"] = "full",
noteGroups: string[] = ["Ops"],
openNoteId: string | null = null,
) => renderToStaticMarkup(
<I18nProvider locale="en">
<TooltipProvider>
<NotesManager
notes={notes}
noteGroups={noteGroups}
hosts={[]}
onUpdateNotes={() => undefined}
onUpdateNoteGroups={() => undefined}
displayMode={displayMode}
openNoteId={openNoteId}
/>
</TooltipProvider>
</I18nProvider>,
);
test("NotesManager renders notes tree and selected markdown editor", () => {
const markup = renderNotes();
assert.match(markup, /Ops/);
assert.match(markup, /Postgres failover checklist/);
assert.match(markup, /data-notes-editor-loading="true"/);
});
test("NotesManager marks selected notebook rows with shared tree state", () => {
const markup = renderNotes();
assert.match(markup, /data-vault-tree-row="group"/);
assert.match(markup, /data-vault-tree-row="item"/);
assert.equal(markup.match(/data-selected="true"/g)?.length, 1);
assert.match(markup, /data-vault-tree-row="group"[^>]*data-selected="false"/);
assert.match(markup, /data-vault-tree-row="item"[^>]*data-selected="true"/);
});
test("NotesManager balances folder and note tree icon sizes", () => {
const markup = renderNotes();
assert.match(markup, /width="16" height="16"[^>]*class="lucide lucide-folder/);
assert.match(markup, /width="16" height="16"[^>]*class="lucide lucide-file-text/);
});
test("NotesManager selection helpers keep note and folder selection exclusive", () => {
const notes = [note(), note({ id: "note-2", title: "Deploy", group: "Deploy" })];
const noteSelection = getNoteSelectionState(notes[0], false);
const sidebarNoteSelection = getNoteSelectionState(notes[0], true);
const groupSelection = getNoteGroupSelectionState("Ops");
assert.equal(getSelectedVaultNote(notes, "note-1")?.title, "Postgres failover checklist");
assert.equal(getSelectedVaultNote(notes, null), null);
assert.deepEqual(noteSelection, {
selectedNoteId: "note-1",
selectedGroup: null,
overlayNoteId: null,
});
assert.deepEqual(sidebarNoteSelection, {
selectedNoteId: "note-1",
selectedGroup: null,
overlayNoteId: "note-1",
});
assert.deepEqual(groupSelection, {
selectedNoteId: null,
selectedGroup: "Ops",
overlayNoteId: null,
});
assert.equal(isNoteFolderTreeSelected("Ops", "note-1", "Ops"), false);
assert.equal(isNoteFolderTreeSelected("Ops", null, "Ops"), true);
assert.equal(getNoteActionTargetGroup(notes[0], "Deploy"), "Ops");
assert.equal(getNoteActionTargetGroup(null, "Deploy"), "Deploy");
});
test("NotesManager note creation, duplicate, and delete fallback selections stay exclusive", () => {
const notes = [
note(),
note({ id: "note-2", title: "Deploy", group: "Deploy", order: 2000 }),
];
const createdOrDuplicated = note({ id: "new-note", group: "Ops" });
assert.deepEqual(getNoteSelectionState(createdOrDuplicated, false), {
selectedNoteId: "new-note",
selectedGroup: null,
overlayNoteId: null,
});
assert.deepEqual(getNoteSelectionState(createdOrDuplicated, true), {
selectedNoteId: "new-note",
selectedGroup: null,
overlayNoteId: "new-note",
});
assert.deepEqual(getFallbackNoteSelectionState(notes.slice(1), false), {
selectedNoteId: "note-2",
selectedGroup: null,
overlayNoteId: null,
});
assert.deepEqual(getFallbackNoteSelectionState(notes.slice(1), true), {
selectedNoteId: null,
selectedGroup: null,
overlayNoteId: null,
});
});
test("NotesManager selects the first loaded note when full mode has no selection", () => {
const notes = [
note({ id: "note-2", title: "Loaded note", group: "Ops", order: 2000 }),
];
assert.deepEqual(getValidatedNoteSelectionState(notes, null, null, false), {
selectedNoteId: "note-2",
selectedGroup: null,
overlayNoteId: null,
});
assert.equal(getValidatedNoteSelectionState(notes, null, "Ops", false), null);
assert.equal(getValidatedNoteSelectionState(notes, null, null, true), null);
});
test("NotesManager group drop helper separates reorder, inside, and ignored drops", () => {
assert.equal(getNotesGroupDropAction("Ops", "Deploy", "before"), "reorder");
assert.equal(getNotesGroupDropAction("Ops", "Deploy", "after"), "reorder");
assert.equal(getNotesGroupDropAction("Ops", "Deploy", "inside"), "inside");
assert.equal(getNotesGroupDropAction("Ops", "Ops", "before"), "ignore");
assert.equal(getNotesGroupDropAction("Ops", "Ops/DB", "inside"), "ignore");
assert.equal(getNotesGroupDropAction(null, "Deploy", "before"), "ignore");
});
test("NotesManager exposes shared tree drag targets and context menus", () => {
const markup = renderNotes();
assert.match(markup, /data-notes-drop-zone="root"/);
assert.match(markup, /data-notes-drag-kind="group"/);
assert.match(markup, /data-notes-drag-kind="note"/);
assert.match(markup, /data-notes-context-menu="group"/);
assert.match(markup, /data-notes-context-menu="note"/);
assert.match(markup, /draggable="true"/);
assert.match(markup, /data-open="false"/);
assert.match(markup, /role="separator"/);
});
test("NotesManager restores and persists the note editor mode without resetting on note switch", () => {
const source = readFileSync(new URL("./NotesManager.tsx", import.meta.url), "utf8");
assert.match(source, /STORAGE_KEY_VAULT_NOTES_EDITOR_MODE/);
assert.match(source, /useStoredString<NoteEditorMode>\(\s*STORAGE_KEY_VAULT_NOTES_EDITOR_MODE,\s*"edit",\s*isNoteEditorMode/s);
assert.doesNotMatch(source, /localStorageAdapter/);
assert.doesNotMatch(source, /setNoteEditorMode\("edit"\)/);
});
test("NotesManager renders nested notebook folders", () => {
const markup = renderNotes([
note({
group: "Ops/DB/Failover",
title: "Replica promotion",
content: "Promote replica",
}),
]);
assert.match(markup, /Ops/);
assert.match(markup, /DB/);
assert.match(markup, /Failover/);
assert.match(markup, /Replica promotion/);
});
test("NotesManager keeps saved notebook folder order", () => {
const markup = renderNotes(
[
note({ id: "alpha-note", title: "Alpha note", group: "Alpha" }),
note({ id: "beta-note", title: "Beta note", group: "Beta" }),
],
"full",
["Beta", "Alpha"],
);
assert.ok(markup.indexOf("Beta") < markup.indexOf("Alpha"));
});
test("NotesManager renders empty state", () => {
const markup = renderNotes([]);
assert.match(markup, /No notes yet/);
assert.match(markup, /New Note/);
assert.match(markup, /Import Markdown/);
assert.doesNotMatch(markup, /data-notes-drop-zone="root"/);
});
test("NotesManager exposes markdown import controls", () => {
const source = readFileSync(new URL("./NotesManager.tsx", import.meta.url), "utf8");
assert.match(source, /notes\.action\.importMarkdown/);
assert.match(source, /importMarkdownPayloadsToVaultNotes/);
assert.match(source, /accept="\.md,\.markdown,\.txt"/);
assert.match(source, /importTargetGroupRef/);
assert.match(source, /openImportMarkdownPicker/);
assert.match(source, /notes\.action\.importMarkdown[\s\S]*openImportMarkdownPicker\(groupPath\)/);
assert.match(source, /multiple/);
});
test("NotesManager exposes markdown export controls", () => {
const source = readFileSync(new URL("./NotesManager.tsx", import.meta.url), "utf8");
assert.match(source, /notes\.action\.exportNote/);
assert.match(source, /notes\.action\.exportGroup/);
assert.match(source, /notes\.action\.exportAll/);
assert.match(source, /buildVaultNoteMarkdownExportFiles/);
assert.match(source, /buildTextFilesZipBlob/);
assert.match(source, /downloadNotesBlob/);
assert.match(source, /text\/markdown;charset=utf-8/);
});
test("NotesManager shows placeholder label for notes without titles", () => {
const markup = renderNotes([note({ title: "" })]);
assert.match(markup, /Note title/);
});
test("NotesManager flushes drafts on pagehide/beforeunload", () => {
const source = readFileSync(new URL("./NotesManager.tsx", import.meta.url), "utf8");
assert.match(source, /addEventListener\("pagehide"/);
assert.match(source, /addEventListener\("beforeunload"/);
assert.match(source, /flushNoteDraft/);
});
test("NotesManager flushes drafts when retained mounts become inactive", () => {
const source = readFileSync(new URL("./NotesManager.tsx", import.meta.url), "utf8");
assert.match(source, /isActive\?: boolean/);
assert.match(source, /if \(isActive\) return;/);
assert.match(source, /useLayoutEffect\(\(\) => \{\s*if \(isActive\) return;/);
assert.match(source, /visibilitychange/);
});
test("NotesManager tree rename allows clearing note titles", () => {
const source = readFileSync(new URL("./NotesManager.tsx", import.meta.url), "utf8");
const renameBlock = source.match(/onRenameCommit=\{\(name\) => \{[\s\S]*?\}\}/)?.[0] ?? "";
assert.match(renameBlock, /renameNoteFromTree\(note\.id, name\)/);
assert.doesNotMatch(renameBlock, /if \(!title\) return/);
assert.match(source, /note\.id === noteId \? \{ \.\.\.note, title: nextTitle, updatedAt \}/);
});
test("NotesManager sidebar mode renders list without editor by default", () => {
const markup = renderNotes([note()], "sidebar");
assert.match(markup, /Ops/);
assert.match(markup, /Postgres failover checklist/);
assert.doesNotMatch(markup, /editable markdown/);
assert.doesNotMatch(markup, /data-notes-editor-loading="true"/);
});
test("NotesManager sidebar mode opens the requested note without selecting its folder", () => {
const markup = renderNotes(
[
note(),
note({
id: "note-2",
title: "Deploy overlay",
content: "Deploy overlay content",
group: "Ops",
order: 2000,
}),
],
"sidebar",
["Ops"],
"note-2",
);
assert.match(markup, /Deploy overlay/);
assert.match(markup, /data-notes-editor-loading="true"/);
assert.equal(markup.match(/data-selected="true"/g)?.length, 1);
assert.match(markup, /data-vault-tree-row="group"[^>]*data-selected="false"/);
assert.match(markup, /data-vault-tree-row="item"[^>]*data-selected="true"[^>]*data-note-id="note-2"/);
});
test("NotesManager can re-open the same sidebar note when the request id changes", () => {
const source = readFileSync(new URL("./NotesManager.tsx", import.meta.url), "utf8");
assert.match(source, /openNoteRequestId\?: number \| null/);
assert.match(source, /\[isSidebarMode, onOpenNoteIdHandled, openNoteId, openNoteRequestId, sortedNotes\]/);
});