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
chore(skills): add measure-startup-requests skill
Elian Doranb5323e49a23d
diff --git a/.claude/skills/measure-startup-requests/SKILL.md b/.claude/skills/measure-startup-requests/SKILL.mdnew file mode 100644index 0000000000..b8ebefaa9d--- /dev/null+++ b/.claude/skills/measure-startup-requests/SKILL.md@@ -0,0 +1,65 @@+---+name: measure-startup-requests+description: Use when measuring what the Trilium client loads at startup — "what loads at boot?", "did this change reduce the startup bundle?", "is <dependency> lazy?", or any before/after comparison for lazy-loading / code-splitting work. Drives a headless browser through login against the running dev server, records every request, and analyzes captures (summary, heavy-dependency probe, before/after diff). Don't write a new throwaway Playwright script or inline node analyzers — both already live here.+---++# Measuring Trilium startup requests++Two scripts in this folder do everything; don't reinvent them:++```bash+# 1. Capture a full startup (login → network quiet) into a JSON file:+TRILIUM_PASSWORD=<password> node .claude/skills/measure-startup-requests/capture-requests.mjs <out.json> [baseUrl]++# 2. Analyze captures:+node .claude/skills/measure-startup-requests/analyze-requests.mjs summary <capture.json> [--top N]+node .claude/skills/measure-startup-requests/analyze-requests.mjs probe <capture.json> [name ...]+node .claude/skills/measure-startup-requests/analyze-requests.mjs diff <before.json> <after.json> [--filter <regex>]+```++## Prerequisites++- The dev server must already be running (`pnpm server:start`, http://localhost:8080 by default).+ Note which checkout it serves: the capture reflects the tree the *server* runs from, not your cwd+ (verify with `curl` on a file that only exists in one tree if unsure).+- `TRILIUM_PASSWORD` env var if the instance has a password.+- Playwright is resolved from `packages/trilium-e2e`; the script prefers system Edge/Chrome, so no+ `playwright install` is needed.++## Workflow for lazy-loading work++1. Capture a **baseline** before changing anything: `capture-requests.mjs baseline.json`.+2. Make the change (Vite dev picks it up automatically; a fresh headless session has no HMR state).+3. Capture again and compare: `analyze-requests.mjs diff baseline.json after.json`.+4. `probe` confirms specific heavy deps stayed off the boot path.++## Interpreting results++- **Dev-mode numbers, not production.** The dev server serves unbundled ES modules (~500+ script+ requests is normal), so sizes are uncompressed and per-module. The *module sets* and import+ chains are what matter; production chunk sizes differ.+- **Request order ≈ import discovery order.** To find what triggers a heavy load, look at the+ `seq` of the first module of that package and at the `/src/...` modules requested just before it,+ then confirm the chain by grepping for static importers.+- **Sessions are stateful.** Open tabs / the active note change what loads (e.g. a text note pulls+ CKEditor legitimately). Totals between two captures are only comparable for the same session+ state; prefer the `diff` of targeted module sets, and treat full-MB totals as indicative.+- **Never filter raw URLs.** Dev URLs embed the absolute checkout path via `/@fs/...`, so a+ worktree named e.g. `lazy-ribbon` makes every request match `/ribbon/`. The analyzer normalizes+ paths (strips host, `?v=`/`?t=` params, `/assets/vX.Y.Z`, and the `/@fs/<checkout>` prefix) —+ rely on that.+- Vite's hash-named shared chunks (`dist-XXXX.js`) are identified by their `.js.map` in+ `.cache/vite/deps/`: `grep -o '"[^"]*node_modules/[^"]*"' <chunk>.js.map | ...` and count by+ package. (The 800 KB `es-toolkit`+`mdast`/`hast` chunk is CKEditor's internals, for example.)++## Reference++The default `probe` list is the set of heavy deps that were deliberately made lazy (CKEditor,+highlight.js, KaTeX, codemirror-vim, snapdom, force-graph, the LLM chat graph, ...) — if one of+them reports `LOADED` on a plain board/empty note startup, a regression sneaked in. After the+2026-06 lazy-loading work the new-layout baseline was ~557 requests / 3.75 MB / 500 scripts+(down from 810 / 8.02 MB / 745).++Known remaining eager-load offenders (candidates for future work): `applyModals` in+`layout_commons.tsx` statically mounts ~30 dialogs and their graphs at boot; the Inter font ships+as a 433 KB TTF instead of woff2.diff --git a/.claude/skills/measure-startup-requests/analyze-requests.mjs b/.claude/skills/measure-startup-requests/analyze-requests.mjsnew file mode 100644index 0000000000..40c8f0beef--- /dev/null+++ b/.claude/skills/measure-startup-requests/analyze-requests.mjs@@ -0,0 +1,138 @@+#!/usr/bin/env node+/**+ * Analyzes request captures produced by capture-requests.mjs.+ *+ * Usage:+ * node analyze-requests.mjs summary <capture.json> [--top N]+ * node analyze-requests.mjs probe <capture.json> [name ...]+ * node analyze-requests.mjs diff <before.json> <after.json> [--filter <regex>]+ *+ * summary totals by resource type plus the N largest requests (default 25)+ * probe checks whether known heavy dependencies were loaded (or the given names)+ * diff modules that disappeared/appeared between two captures, by normalized path+ */+import fs from "fs";++// Heavy dependencies worth keeping off the startup path. Extend as new ones appear.+const DEFAULT_PROBES = [+ "deps/ckeditor5.js",+ "ckeditor5-premium-features",+ "highlight__js",+ "deps/katex.js",+ "snapdom",+ "codemirror-vim",+ "force-graph",+ "mermaid",+ "excalidraw",+ "emoji_definitions",+ "llm_chat/",+ "fancytree",+ "numfmt"+];++/**+ * Makes URLs comparable across hosts, Vite cache-busting params, asset version+ * prefixes and checkout locations (the @fs absolute path differs per worktree —+ * never filter on raw URLs, a worktree name like "lazy-ribbon" can match your filter).+ */+function normalize(url) {+ return url+ .replace(/^https?:\/\/[^/]+/, "")+ .replace(/[?&](v|t)=[a-z0-9]+/gi, "")+ .replace(/\/assets\/v[^/]+\//, "/")+ .replace(/\/@fs\/.*?\/(packages|apps|node_modules|\.cache)\//, "/$1/");+}++function load(file) {+ return JSON.parse(fs.readFileSync(file, "utf8"));+}++function kb(bytes) {+ return `${(bytes / 1024).toFixed(1)}K`;+}++function totals(requests) {+ const bytes = requests.reduce((sum, r) => sum + (r.bodySize || 0), 0);+ const scripts = requests.filter((r) => r.resourceType === "script").length;+ return `${requests.length} requests / ${(bytes / 1024 / 1024).toFixed(2)} MB / ${scripts} scripts`;+}++function summary(file, topN) {+ const requests = load(file);+ const byType = {};+ for (const r of requests) {+ const type = r.resourceType || "other";+ byType[type] = byType[type] || { count: 0, size: 0 };+ byType[type].count++;+ byType[type].size += r.bodySize || 0;+ }++ console.log(`Total: ${totals(requests)}\n`);+ console.log("--- By resource type ---");+ for (const [type, v] of Object.entries(byType).sort((a, b) => b[1].size - a[1].size)) {+ console.log(type.padEnd(12), String(v.count).padStart(4), kb(v.size).padStart(10));+ }++ console.log(`\n--- Top ${topN} largest ---`);+ for (const r of [...requests].sort((a, b) => (b.bodySize || 0) - (a.bodySize || 0)).slice(0, topN)) {+ console.log(kb(r.bodySize || 0).padStart(9), (r.resourceType || "").padEnd(11), normalize(r.url));+ }+}++function probe(file, names) {+ const requests = load(file);+ for (const name of names.length ? names : DEFAULT_PROBES) {+ const hit = requests.find((r) => normalize(r.url).includes(name));+ console.log(+ name.padEnd(28),+ hit ? `LOADED seq ${String(hit.seq).padStart(4)} ${kb(hit.bodySize || 0)}` : "not loaded"+ );+ }+}++function diff(beforeFile, afterFile, filterRegex) {+ const filter = filterRegex ? new RegExp(filterRegex) : null;+ const collect = (file) => {+ const map = new Map();+ for (const r of load(file)) {+ const url = normalize(r.url);+ if (!filter || filter.test(url)) map.set(url, r.bodySize || 0);+ }+ return map;+ };+ const before = collect(beforeFile);+ const after = collect(afterFile);++ const print = (title, entries) => {+ const total = entries.reduce((sum, [, size]) => sum + size, 0);+ console.log(`\n--- ${title} (${entries.length} requests, ${kb(total)}) ---`);+ for (const [url, size] of entries.sort((a, b) => b[1] - a[1])) {+ console.log(kb(size).padStart(9), url);+ }+ };++ print("Gone (in before, not in after)", [...before].filter(([url]) => !after.has(url)));+ print("Added (in after, not in before)", [...after].filter(([url]) => !before.has(url)));+ console.log(`\nBefore: ${totals(load(beforeFile))}`);+ console.log(`After: ${totals(load(afterFile))}`);+}++const [command, ...args] = process.argv.slice(2);+switch (command) {+ case "summary": {+ const topIndex = args.indexOf("--top");+ summary(args[0], topIndex >= 0 ? parseInt(args[topIndex + 1], 10) : 25);+ break;+ }+ case "probe":+ probe(args[0], args.slice(1));+ break;+ case "diff": {+ const filterIndex = args.indexOf("--filter");+ diff(args[0], args[1], filterIndex >= 0 ? args[filterIndex + 1] : null);+ break;+ }+ default:+ console.error("Usage: analyze-requests.mjs <summary|probe|diff> ... (see file header)");+ process.exit(1);+}diff --git a/.claude/skills/measure-startup-requests/capture-requests.mjs b/.claude/skills/measure-startup-requests/capture-requests.mjsnew file mode 100644index 0000000000..f269afb9a4--- /dev/null+++ b/.claude/skills/measure-startup-requests/capture-requests.mjs@@ -0,0 +1,107 @@+#!/usr/bin/env node+/**+ * Captures every network request made by the Trilium client during a full startup+ * (login → app fully loaded) against a running dev server, and writes them to a+ * JSON file for analysis with analyze-requests.mjs.+ *+ * Usage:+ * node .claude/skills/measure-startup-requests/capture-requests.mjs [output.json] [baseUrl]+ *+ * Environment:+ * TRILIUM_PASSWORD password of the dev instance (required if a login page appears)+ * TRILIUM_URL base URL (default http://localhost:8080), overridden by the second argument+ */+import fs from "fs";+import { createRequire } from "module";+import path from "path";+import { fileURLToPath } from "url";++// Playwright is not installed at the repo root; resolve it from the e2e package.+const repoRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..", "..", "..");+const e2eRequire = createRequire(path.join(repoRoot, "packages", "trilium-e2e", "package.json"));+const { chromium } = e2eRequire("playwright");++const outputPath = process.argv[2] ?? "requests.json";+const baseUrl = process.argv[3] ?? process.env.TRILIUM_URL ?? "http://localhost:8080";++// The pinned Playwright browser build is usually not downloaded in dev setups,+// so prefer system browsers before falling back to the bundled one.+async function launchBrowser() {+ let lastError;+ for (const channel of ["msedge", "chrome", undefined]) {+ try {+ return await chromium.launch(channel ? { channel } : {});+ } catch (e) {+ lastError = e;+ }+ }+ throw lastError;+}++const requests = [];+let seq = 0;++const browser = await launchBrowser();+const context = await browser.newContext();+const page = await context.newPage();++page.on("response", async (response) => {+ const req = response.request();+ let bodySize = 0;+ try {+ const sizes = await req.sizes();+ bodySize = sizes.responseBodySize;+ } catch {+ // request may be from a worker or already closed+ }+ requests.push({+ seq: seq++,+ method: req.method(),+ url: req.url(),+ resourceType: req.resourceType(),+ status: response.status(),+ fromServiceWorker: response.fromServiceWorker(),+ bodySize+ });+});++page.on("websocket", (ws) => {+ requests.push({+ seq: seq++,+ method: "WS",+ url: ws.url(),+ resourceType: "websocket",+ status: null,+ bodySize: 0+ });+});++console.log(`Navigating to ${baseUrl}...`);+await page.goto(baseUrl, { waitUntil: "networkidle" });++if (page.url().includes("login")) {+ const password = process.env.TRILIUM_PASSWORD;+ if (!password) {+ console.error("The instance requires a login; set the TRILIUM_PASSWORD environment variable.");+ await browser.close();+ process.exit(1);+ }+ console.log("Logging in...");+ await page.fill("#password", password);+ await page.click("form button.btn-success");+ await page.waitForURL((url) => !url.pathname.includes("login"), { timeout: 30000 });+}++console.log("Waiting for the app to fully load...");+try {+ await page.waitForLoadState("networkidle", { timeout: 30000 });+} catch {}+// Extra settle time for deferred/idle loading, then require a quiet network again.+await page.waitForTimeout(8000);+try {+ await page.waitForLoadState("networkidle", { timeout: 10000 });+} catch {}++fs.writeFileSync(outputPath, JSON.stringify(requests, null, 2));+console.log(`Captured ${requests.length} requests -> ${outputPath}`);+await browser.close();