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
Merge remote-tracking branch 'origin/main' into standalone
Elian Doran5fce7283f169
diff --cc CLAUDE.mdindex 9778f0de7b,a818b18929..5eb93b3a5c--- a/CLAUDE.md+++ b/CLAUDE.md@@@ -8,193 -8,162 +8,220 @@@ Trilium Notes is a hierarchical note-ta## Development Commands-### Setup-- `pnpm install` - Install all dependencies-- `corepack enable` - Enable pnpm if not available--### Running Applications-- `pnpm run server:start` - Start development server (http://localhost:8080)-- `pnpm run server:start-prod` - Run server in production mode--### Building-- `pnpm run client:build` - Build client application-- `pnpm run server:build` - Build server application-- `pnpm run electron:build` - Build desktop application--### Testing-- `pnpm test:all` - Run all tests (parallel + sequential)-- `pnpm test:parallel` - Run tests that can run in parallel-- `pnpm test:sequential` - Run tests that must run sequentially (server, ckeditor5-mermaid, ckeditor5-math)-- `pnpm coverage` - Generate coverage reports--## Architecture Overview--### Monorepo Structure-- **apps/**: Runnable applications- - `client/` - Frontend application (shared by server and desktop)- - `server/` - Node.js server with web interface- - `desktop/` - Electron desktop application- - `web-clipper/` - Browser extension for saving web content- - Additional tools: `db-compare`, `dump-db`, `edit-docs`--- **packages/**: Shared libraries- - `commons/` - Shared interfaces and utilities- - `ckeditor5/` - Custom rich text editor with Trilium-specific plugins- - `codemirror/` - Code editor customizations- - `highlightjs/` - Syntax highlighting- - Custom CKEditor plugins: `ckeditor5-admonition`, `ckeditor5-footnotes`, `ckeditor5-math`, `ckeditor5-mermaid`--### Core Architecture Patterns--#### Three-Layer Cache System-- **Becca** (Backend Cache): Server-side entity cache (`apps/server/src/becca/`)-- **Froca** (Frontend Cache): Client-side mirror of backend data (`apps/client/src/services/froca.ts`)-- **Shaca** (Share Cache): Optimized cache for shared/published notes (`apps/server/src/share/`)--#### Entity System-Core entities are defined in `apps/server/src/becca/entities/`:-- `BNote` - Notes with content and metadata-- `BBranch` - Hierarchical relationships between notes (allows multiple parents)-- `BAttribute` - Key-value metadata attached to notes-- `BRevision` - Note version history-- `BOption` - Application configuration--#### Widget-Based UI-Frontend uses a widget system (`apps/client/src/widgets/`):-- `BasicWidget` - Base class for all UI components-- `NoteContextAwareWidget` - Widgets that respond to note changes-- `RightPanelWidget` - Widgets displayed in the right panel+```bash+# Setup+corepack enable && pnpm install++# Run+pnpm server:start # Dev server at http://localhost:8080+pnpm desktop:start # Electron dev app+pnpm standalone:start # Standalone client dev++# Build+pnpm client:build # Frontend+pnpm server:build # Backend+pnpm desktop:build # Electron++# Test+pnpm test:all # All tests (parallel + sequential)+pnpm test:parallel # Client + most package tests+pnpm test:sequential # Server, ckeditor5-mermaid, ckeditor5-math (shared DB)+pnpm --filter server test # Single package tests+pnpm coverage # Coverage reports++# Lint & Format+pnpm dev:linter-check # ESLint check+pnpm dev:linter-fix # ESLint fix+pnpm dev:format-check # Format check (stricter stylistic rules)+pnpm dev:format-fix # Format fix+pnpm typecheck # TypeScript type check across all projects+```++**Running a single test file**: `pnpm --filter server test spec/etapi/search.spec.ts`++## Main Applications++The four main apps share `packages/trilium-core/` for business logic but differ in runtime:++- **client** (`apps/client/`): Preact frontend with jQuery widget system. Shared UI layer used by both server and desktop.+- **server** (`apps/server/`): Node.js backend (Express, better-sqlite3). Serves the client and provides REST/WebSocket APIs.+- **desktop** (`apps/desktop/`): Electron wrapper around server + client, running both in a single process.+- **standalone** (`apps/client-standalone/` + `apps/standalone-desktop/`): Runs the entire stack in the browser — server logic compiled to WASM via sql.js, executed in a service worker. No Node.js dependency at runtime.++## Monorepo Structure++```+apps/+ client/ # Preact frontend (shared by server, desktop, standalone)+ server/ # Node.js backend (Express, better-sqlite3)+ desktop/ # Electron (bundles server + client)+ client-standalone/ # Standalone client (WASM + service workers, no Node.js)+ standalone-desktop/ # Standalone desktop variant+ server-e2e/ # Playwright E2E tests for server+ web-clipper/ # Browser extension+ website/ # Project website+ db-compare/, dump-db/, edit-docs/, build-docs/, icon-pack-builder/++packages/+ trilium-core/ # Core business logic: entities, services, SQL, sync+ commons/ # Shared interfaces and utilities+ ckeditor5/ # Custom rich text editor bundle+ codemirror/ # Code editor integration+ highlightjs/ # Syntax highlighting+ share-theme/ # Theme for shared/published notes+ ckeditor5-admonition/, ckeditor5-footnotes/, ckeditor5-math/, ckeditor5-mermaid/+ ckeditor5-keyboard-marker/, express-partial-content/, pdfjs-viewer/, splitjs/+ turndown-plugin-gfm/+```++Use `pnpm --filter <package-name> <command>` to run commands in specific packages.++## Core Architecture++### Three-Layer Cache System++All data access goes through cache layers — never bypass with direct DB queries:++- **Becca** (`packages/trilium-core/src/becca/`): Server-side entity cache. Access via `becca.notes[noteId]`.+- **Froca** (`apps/client/src/services/froca.ts`): Client-side mirror synced via WebSocket. Access via `froca.getNote()`.+- **Shaca** (`apps/server/src/share/`): Optimized cache for shared/published notes.++**Critical**: Always use cache methods, not direct DB writes. Cache methods create `EntityChange` records needed for synchronization.++### Entity System++Core entities live in `packages/trilium-core/src/becca/entities/` (not `apps/server/`):++- `BNote` — Notes with content and metadata+- `BBranch` — Multi-parent tree relationships (cloning supported)+- `BAttribute` — Key-value metadata (labels and relations)+- `BRevision` — Version history+- `BOption` — Application configuration+- `BBlob` — Binary content storage++Entities extend `AbstractBeccaEntity<T>` with built-in change tracking, hash generation, and date management.++### Entity Change & Sync Protocol++Every entity modification creates an `EntityChange` record driving sync:+1. Login with HMAC authentication (document secret + timestamp)+2. Push changes → Pull changes → Push again (conflict resolution)+3. Content hash verification with retry loop++Sync services: `packages/trilium-core/src/services/sync.ts`, `syncMutexService`, `syncUpdateService`.++### Widget-Based UI++Frontend widgets in `apps/client/src/widgets/`:+- `BasicWidget` / `TypedBasicWidget` — Base classes (jQuery `this.$widget` for DOM)+- `NoteContextAwareWidget` — Responds to note changes+- `RightPanelWidget` — Sidebar widgets with position ordering- Type-specific widgets in `type_widgets/` directory-#### API Architecture-- **Internal API**: REST endpoints in `apps/server/src/routes/api/`-- **ETAPI**: External API for third-party integrations (`apps/server/src/etapi/`)-- **WebSocket**: Real-time synchronization (`apps/server/src/services/ws.ts`)+**Widget lifecycle**: `doRenderBody()` for initial render, `refreshWithNote()` for note changes, `entitiesReloadedEvent({loadResults})` for entity updates. Uses jQuery — don't mix React patterns.-### Key Files for Understanding Architecture+Fluent builder pattern: `.child()`, `.class()`, `.css()` chaining with position-based ordering.-1. **Application Entry Points**:- - `apps/server/src/main.ts` - Server startup- - `apps/client/src/desktop.ts` - Client initialization+### API Architecture-2. **Core Services**:- - `apps/server/src/becca/becca.ts` - Backend data management- - `apps/client/src/services/froca.ts` - Frontend data synchronization- - `apps/server/src/services/backend_script_api.ts` - Scripting API+- **Internal API** (`apps/server/src/routes/api/`): REST endpoints, trusts frontend+- **ETAPI** (`apps/server/src/etapi/`): External API with basic auth tokens — maintain backwards compatibility+- **WebSocket** (`apps/server/src/services/ws.ts`): Real-time sync-3. **Database Schema**:- - `apps/server/src/assets/db/schema.sql` - Core database structure+### Platform Abstraction-4. **Configuration**:- - `package.json` - Project dependencies and scripts+`packages/trilium-core/src/services/platform.ts` defines `PlatformProvider` interface with implementations in `apps/desktop/`, `apps/server/`, and `apps/client-standalone/`. Singleton via `initPlatform()`/`getPlatform()`.-## Note Types and Features+**PlatformProvider** provides:+- `crash(message)` — Platform-specific fatal error handling+- `getEnv(key)` — Environment variable access (server/desktop use `process.env`, standalone maps URL query params like `?safeMode` → `TRILIUM_SAFE_MODE`)+- `isElectron`, `isMac`, `isWindows` — Platform detection flags-Trilium supports multiple note types, each with specialized widgets:-- **Text**: Rich text with CKEditor5 (markdown import/export)-- **Code**: Syntax-highlighted code editing with CodeMirror-- **File**: Binary file attachments-- **Image**: Image display with editing capabilities-- **Canvas**: Drawing/diagramming with Excalidraw-- **Mermaid**: Diagram generation-- **Relation Map**: Visual note relationship mapping-- **Web View**: Embedded web pages-- **Doc/Book**: Hierarchical documentation structure+**Critical rules for `trilium-core`**:+- **No `process.env` in core** — use `getPlatform().getEnv()` instead (not available in standalone/browser)+- **No `import path from "path"` in core** — Node's `path` module is externalized in browser builds. Use `packages/trilium-core/src/services/utils/path.ts` for `extname()`/`basename()` equivalents+- **No Node.js built-in modules in core** — core runs in both Node.js and the browser (standalone). Use platform-agnostic alternatives or platform providers+- **Platform detection via functions** — `isElectron()`, `isMac()`, `isWindows()` from `utils/index.ts` are functions (not constants) that call `getPlatform()`. They can only be called after `initializeCore()`, not at module top-level. If used in static definitions, wrap in a closure: `value: () => isWindows() ? "0.9" : "1.0"`+- **Barrel import caution** — `import { x } from "@triliumnext/core"` loads ALL core exports. Early-loading modules like `config.ts` should import specific subpaths (e.g. `@triliumnext/core/src/services/utils/index`) to avoid circular dependencies or initialization ordering issues+- **Electron IPC** — In desktop mode, client API calls use Electron IPC (not HTTP). The IPC handler in `apps/server/src/routes/electron.ts` must be registered via `utils.isElectron` from the **server's** utils (which correctly checks `process.versions["electron"]`), not from core's utils-## Development Guidelines+### Database-### Testing Strategy-- Server tests run sequentially due to shared database-- Client tests can run in parallel-- E2E tests use Playwright for both server and desktop apps-- Build validation tests check artifact integrity+SQLite via `better-sqlite3`. SQL abstraction in `packages/trilium-core/src/services/sql/` with `DatabaseProvider` interface, prepared statement caching, and transaction support.-### Scripting System-Trilium provides powerful user scripting capabilities:-- Frontend scripts run in browser context-- Backend scripts run in Node.js context with full API access-- Script API documentation available in `docs/Script API/`+- Schema: `apps/server/src/assets/db/schema.sql`+- Migrations: `apps/server/src/migrations/YYMMDD_HHMM__description.sql`- ### Attribute Inheritance+ ### Internationalization+ - Translation files in `apps/client/src/translations/`+ - Supported languages: English, German, Spanish, French, Romanian, Chinese+ - **Only add new translation keys to `en/translation.json`** — translations for other languages are managed via Weblate and will be contributed by the community+ - Third-party components (e.g., mind-map context menu) should use i18next `t()` for their labels, with the English strings added to `en/translation.json` under a dedicated namespace (e.g., `"mind-map"`)-### Security Considerations-- Per-note encryption with granular protected sessions-- CSRF protection for API endpoints-- OpenID and TOTP authentication support-- Sanitization of user-generated content+Three inheritance mechanisms:+1. **Standard**: `note.getInheritableAttributes()` walks parent tree+2. **Child prefix**: `child:label` on parent copies to children+3. **Template relation**: `#template=noteNoteId` includes template's inheritable attributes++### Attribute Inheritance+++Use `note.getOwnedAttribute()` for direct, `note.getAttribute()` for inherited.+ ### Client-Side API Restrictions+ - **Do not use `crypto.randomUUID()`** or other Web Crypto APIs that require secure contexts - Trilium can run over HTTP, not just HTTPS+ - Use `randomString()` from `apps/client/src/services/utils.ts` for generating IDs instead++ ### Shared Types Policy+ - Types shared between client and server belong in `@triliumnext/commons` (`packages/commons/src/lib/`)+ - Import shared types directly from `@triliumnext/commons` - do not re-export them from app-specific modules+ - Keep app-specific types (e.g., `LlmProvider` for server, `StreamCallbacks` for client) in their respective apps-## Common Development Tasks+## Important Patterns++- **Protected notes**: Check `note.isContentAvailable()` before accessing content; use `note.getTitleOrProtected()` for safe title access+- **Long operations**: Use `TaskContext` for progress reporting via WebSocket+- **Event system** (`packages/trilium-core/src/services/events.ts`): Events emitted in order (notes → branches → attributes) during load for referential integrity+- **Search**: Expression-based, scoring happens in-memory — cannot add SQL-level LIMIT/OFFSET without losing scoring+- **Widget cleanup**: Unsubscribe from events in `cleanup()`/`doDestroy()` to prevent memory leaks++## Code Style++- 4-space indentation, semicolons always required+- Double quotes (enforced by format config)+- Max line length: 100 characters+- Unix line endings+- Import sorting via `eslint-plugin-simple-import-sort`++## Testing++- **Server tests** (`apps/server/spec/`): Vitest, must run sequentially (shared DB), forks pool, max 6 workers+- **Client tests** (`apps/client/src/`): Vitest with happy-dom environment, can run in parallel+- **E2E tests** (`apps/server-e2e/`): Playwright, Chromium, server started automatically on port 8082+- **ETAPI tests** (`apps/server/spec/etapi/`): External API contract tests-### Adding New Note Types-1. Create widget in `apps/client/src/widgets/type_widgets/`-2. Register in `apps/client/src/services/note_types.ts`-3. Add backend handling in `apps/server/src/services/notes.ts`+## Documentation-### Extending Search-- Search expressions handled in `apps/server/src/services/search/`-- Add new search operators in search context files+- `docs/Script API/` — Auto-generated, never edit directly+- `docs/User Guide/` — Edit via `pnpm edit-docs:edit-docs`, not manually+- `docs/Developer Guide/` and `docs/Release Notes/` — Safe for direct Markdown editing-### Custom CKEditor Plugins-- Create new package in `packages/` following existing plugin structure-- Register in `packages/ckeditor5/src/plugins.ts`+## Key Entry Points-### Database Migrations-- Add migration scripts in `apps/server/src/migrations/`-- Update schema in `apps/server/src/assets/db/schema.sql`+- `apps/server/src/main.ts` — Server startup+- `apps/client/src/desktop.ts` — Client initialization+- `packages/trilium-core/src/becca/becca.ts` — Backend data management+- `apps/client/src/services/froca.ts` — Frontend cache+- `apps/server/src/routes/routes.ts` — API route registration+- `packages/trilium-core/src/services/sql/sql.ts` — Database abstraction++ ### Server-Side Static Assets+ - Static assets (templates, SQL, translations, etc.) go in `apps/server/src/assets/`+ - Access them at runtime via `RESOURCE_DIR` from `apps/server/src/services/resource_dir.ts` (e.g. `path.join(RESOURCE_DIR, "llm", "skills", "file.md")`)+ - **Do not use `import.meta.url`/`fileURLToPath`** to resolve file paths — the server is bundled into CJS for production, so `import.meta.url` will not point to the source directory+ - **Do not use `__dirname` with relative paths** from source files — after bundling, `__dirname` points to the bundle output, not the original source tree++ ## Build System Notes+ - Uses pnpm for monorepo management+ - Vite for fast development builds+ - ESBuild for production optimization+ - pnpm workspaces for dependency management-- Docker support with multi-stage builds++- Docker support with multi-stage buildsdiff --cc apps/build-docs/package.jsonindex cb1569b23f,98a346e05f..8b0996e20d--- a/apps/build-docs/package.json+++ b/apps/build-docs/package.json@@@ -15,12 -15,8 +15,12 @@@"author": "Elian Doran <[email protected]>","license": "AGPL-3.0-only","packageManager": "[email protected]",+ "dependencies": {+ "@triliumnext/core": "workspace:*",+ "@triliumnext/server": "workspace:*"+ },"devDependencies": {- "@redocly/cli": "2.25.2",+ "@redocly/cli": "2.25.3","archiver": "7.0.1","fs-extra": "11.3.4","js-yaml": "4.1.1",diff --cc apps/client/src/translations/en/translation.jsonindex 6afd867eae,0ee627e9da..047f022a26--- a/apps/client/src/translations/en/translation.json+++ b/apps/client/src/translations/en/translation.json@@@ -2231,55 -2277,34 +2277,85 @@@"sample_venn": "Venn","sample_ishikawa": "Ishikawa"},+ "setup": {+ "heading": "Get started with Trilium",+ "new-document": "New knowledge base",+ "new-document-description": "Start with a clean knowledge base and begin right away.",+ "sync-from-desktop": "Connect a desktop app",+ "sync-from-desktop-description": "You only have a Trilium desktop app running on another device. This device will sync its data from that desktop app.",+ "sync-from-server": "Connect to an existing server",+ "sync-from-server-description": "You have a Trilium server running elsewhere (either self-hosted or in the cloud). This device will sync its data from that server.",+ "next": "Next",+ "init-in-progress": "Document initialization in progress",+ "redirecting": "You will be shortly redirected to the application.",+ "title": "Setup",+ "sync-from-server-page-description": "Enter your server details below to connect your existing workspace.",+ "sync-in-progress-title": "Sync in progress",+ "sync-in-progress-description": "Your device is now connected and items are being synchronized.",+ "button-back": "Back",+ "button-finish-setup": "Finish setup",+ "sync-step-connecting": "Connecting to server",+ "sync-step-syncing": "Syncing data",+ "sync-step-finalizing": "Setting up options",+ "create-new-document-options-title": "How would you like to start?",+ "create-new-document-options-with-demo": "With demo content",+ "create-new-document-options-with-demo-description": "Explore Trilium with example content.",+ "create-new-document-options-empty": "Empty",+ "create-new-document-options-empty-description": "Start with a blank knowledge base. You can import demo notes later.",+ "create-new-document-title": "Preparing your knowledge base",+ "create-new-document-description": "This will only take a moment.",+ "sync-illustration-this-device": "This device",+ "sync-illustration-desktop-app": "Your desktop app",+ "sync-illustration-server": "Your server",+ "sync-from-desktop-step1": "Open your desktop instance of Trilium Notes.",+ "sync-from-desktop-step2": "From the Trilium Menu, click Options.",+ "sync-from-desktop-step3": "Click on Sync category in the note tree.",+ "sync-from-desktop-step4": "Change server instance address to point to one of the addresses on the right and click Save.",+ "sync-from-desktop-step5": "Click the \"Test sync\" button to verify connection is successful.",+ "sync-from-desktop-warning": "Make sure both devices are on the same network.",+ "sync-from-desktop-waiting": "Waiting for connection...",+ "advanced-options": "Advanced options",+ "sync-failed": "Failed to sync: {{message}}",+ "server-host": "Trilium server address",+ "server-host-placeholder": "https://<hostname>:<port>",+ "server-password": "Password",+ "proxy-server": "Proxy server (optional)",+ "proxy-server-placeholder": "https://<hostname>:<port>",+ "proxy-instruction": "If you leave proxy setting blank, system proxy will be used.",+ "dismiss-error": "Dismiss error",+ "wrong-password": "Incorrect password. Please try again.",+ "language": "Language",+ "continue": "Continue",+ "your-ip-addresses": "Addresses for this device"++ },+ "mind-map": {+ "addChild": "Add child",+ "addParent": "Add parent",+ "addSibling": "Add sibling",+ "removeNode": "Remove node",+ "focus": "Focus Mode",+ "cancelFocus": "Cancel Focus Mode",+ "moveUp": "Move up",+ "moveDown": "Move down",+ "link": "Link",+ "linkBidirectional": "Bidirectional Link",+ "clickTips": "Please click the target node",+ "summary": "Summary"+ },+ "llm": {+ "settings_title": "AI / LLM",+ "settings_description": "Configure AI and Large Language Model integrations.",+ "add_provider": "Add Provider",+ "add_provider_title": "Add AI Provider",+ "configured_providers": "Configured Providers",+ "no_providers_configured": "No providers configured yet.",+ "provider_name": "Name",+ "provider_type": "Provider",+ "actions": "Actions",+ "delete_provider": "Delete",+ "delete_provider_confirmation": "Are you sure you want to delete the provider \"{{name}}\"?",+ "api_key": "API Key",+ "api_key_placeholder": "Enter your API key",+ "cancel": "Cancel"}}diff --cc apps/server/package.jsonindex e8ee775eb2,cb7f728fd7..ee2c2d1269--- a/apps/server/package.json+++ b/apps/server/package.json@@@ -30,8 -30,14 +30,12 @@@"proxy-nginx-subdir": "docker run --name trilium-nginx-subdir --rm --network=host -v ./docker/nginx.conf:/etc/nginx/conf.d/default.conf:ro nginx:latest"},"dependencies": {+ "@ai-sdk/anthropic": "3.0.64",+ "@ai-sdk/google": "3.0.54",+ "@ai-sdk/openai": "3.0.49",+ "ai": "6.0.142","better-sqlite3": "12.8.0",- "html-to-text": "9.0.5",- "node-html-parser": "7.1.0",- "sucrase": "3.35.1"+ "html-to-text": "9.0.5"},"devDependencies": {"@braintree/sanitize-url": "7.1.2",diff --cc apps/server/src/routes/api/llm_special_notes.tsindex 0000000000,0000000000..9f60871024new file mode 100644--- /dev/null+++ b/apps/server/src/routes/api/llm_special_notes.ts@@@ -1,0 -1,0 +1,34 @@@++import { Request } from "express";++++import specialNotesService from "../../services/special_notes";++++function createLlmChat() {++ return specialNotesService.createLlmChat();++}++++function getMostRecentLlmChat() {++ const chat = specialNotesService.getMostRecentLlmChat();++ // Return null explicitly if no chat found (not undefined)++ return chat || null;++}++++function getOrCreateLlmChat() {++ return specialNotesService.getOrCreateLlmChat();++}++++function getRecentLlmChats(req: Request) {++ const limit = parseInt(req.query.limit as string) || 10;++ return specialNotesService.getRecentLlmChats(limit);++}++++function saveLlmChat(req: Request<{ llmChatNoteId: string }>) {++ return specialNotesService.saveLlmChat(req.body?.llmChatNoteId);++}++++export default {++ createLlmChat,++ getMostRecentLlmChat,++ getOrCreateLlmChat,++ getRecentLlmChats,++ saveLlmChat,++};diff --cc apps/server/src/routes/routes.tsindex b33dde72f0,eb78d500e9..43f748b70c--- a/apps/server/src/routes/routes.ts+++ b/apps/server/src/routes/routes.ts@@@ -18,17 -17,45 +18,19 @@@ import auth from "../services/auth.js"import openID from '../services/open_id.js';import { isElectron } from "../services/utils.js";import shareRoutes from "../share/routes.js";-import appInfoRoute from "./api/app_info.js";-import attachmentsApiRoute from "./api/attachments.js";-import attributesRoute from "./api/attributes.js";-import autocompleteApiRoute from "./api/autocomplete.js";import backendLogRoute from "./api/backend_log.js";-import branchesApiRoute from "./api/branches.js";-import bulkActionRoute from "./api/bulk_action.js";import clipperRoute from "./api/clipper.js";-import cloningApiRoute from "./api/cloning.js";import databaseRoute from "./api/database.js";import etapiTokensApiRoutes from "./api/etapi_tokens.js";-import exportRoute from "./api/export.js";import filesRoute from "./api/files.js";import fontsRoute from "./api/fonts.js";-import imageRoute from "./api/image.js";-import importRoute from "./api/import.js";-import keysRoute from "./api/keys.js";+ import llmChatRoute from "./api/llm_chat.js";++import llmSpecialNotesRoute from "./api/llm_special_notes.js";import loginApiRoute from "./api/login.js";import metricsRoute from "./api/metrics.js";-import noteMapRoute from "./api/note_map.js";-import notesApiRoute from "./api/notes.js";-import optionsApiRoute from "./api/options.js";-import otherRoute from "./api/other.js";import passwordApiRoute from "./api/password.js";-import recentChangesApiRoute from "./api/recent_changes.js";-import recentNotesRoute from "./api/recent_notes.js";import recoveryCodes from './api/recovery_codes.js';-import relationMapApiRoute from "./api/relation-map.js";-import revisionsApiRoute from "./api/revisions.js";-import scriptRoute from "./api/script.js";-import searchRoute from "./api/search.js";import senderRoute from "./api/sender.js";-import setupApiRoute from "./api/setup.js";-import similarNotesRoute from "./api/similar_notes.js";-import specialNotesRoute from "./api/special_notes.js";-import sqlRoute from "./api/sql.js";-import statsRoute from "./api/stats.js";-import syncApiRoute from "./api/sync.js";import systemInfoRoute from "./api/system_info.js";import totp from './api/totp.js';// API routes@@@ -158,6 -280,29 +160,11 @@@ function register(app: express.Applicatroute(PST, "/api/clipper/open/:noteId", clipperMiddleware, clipperRoute.openNote, apiResultHandler);asyncRoute(GET, "/api/clipper/notes-by-url/:noteUrl", clipperMiddleware, clipperRoute.findNotesByUrl, apiResultHandler);- asyncApiRoute(GET, "/api/special-notes/inbox/:date", specialNotesRoute.getInboxNote);- asyncApiRoute(GET, "/api/special-notes/days/:date", specialNotesRoute.getDayNote);- asyncApiRoute(GET, "/api/special-notes/week-first-day/:date", specialNotesRoute.getWeekFirstDayNote);- asyncApiRoute(GET, "/api/special-notes/weeks/:week", specialNotesRoute.getWeekNote);- asyncApiRoute(GET, "/api/special-notes/months/:month", specialNotesRoute.getMonthNote);- asyncApiRoute(GET, "/api/special-notes/quarters/:quarter", specialNotesRoute.getQuarterNote);- apiRoute(GET, "/api/special-notes/years/:year", specialNotesRoute.getYearNote);- apiRoute(GET, "/api/special-notes/notes-for-month/:month", specialNotesRoute.getDayNotesForMonth);- apiRoute(PST, "/api/special-notes/sql-console", specialNotesRoute.createSqlConsole);- asyncApiRoute(PST, "/api/special-notes/save-sql-console", specialNotesRoute.saveSqlConsole);- apiRoute(PST, "/api/special-notes/search-note", specialNotesRoute.createSearchNote);- apiRoute(PST, "/api/special-notes/save-search-note", specialNotesRoute.saveSearchNote);- apiRoute(PST, "/api/special-notes/llm-chat", specialNotesRoute.createLlmChat);- apiRoute(GET, "/api/special-notes/most-recent-llm-chat", specialNotesRoute.getMostRecentLlmChat);- apiRoute(GET, "/api/special-notes/get-or-create-llm-chat", specialNotesRoute.getOrCreateLlmChat);- apiRoute(GET, "/api/special-notes/recent-llm-chats", specialNotesRoute.getRecentLlmChats);- apiRoute(PST, "/api/special-notes/save-llm-chat", specialNotesRoute.saveLlmChat);- apiRoute(PST, "/api/special-notes/launchers/:noteId/reset", specialNotesRoute.resetLauncher);- apiRoute(PST, "/api/special-notes/launchers/:parentNoteId/:launcherType", specialNotesRoute.createLauncher);- apiRoute(PUT, "/api/special-notes/api-script-launcher", specialNotesRoute.createOrUpdateScriptLauncherFromApi);-- apiRoute(GET, "/api/sql/schema", sqlRoute.getSchema);- apiRoute(PST, "/api/sql/execute/:noteId", sqlRoute.execute);++ apiRoute(PST, "/api/special-notes/llm-chat", llmSpecialNotesRoute.createLlmChat);++ apiRoute(GET, "/api/special-notes/most-recent-llm-chat", llmSpecialNotesRoute.getMostRecentLlmChat);++ apiRoute(GET, "/api/special-notes/get-or-create-llm-chat", llmSpecialNotesRoute.getOrCreateLlmChat);++ apiRoute(GET, "/api/special-notes/recent-llm-chats", llmSpecialNotesRoute.getRecentLlmChats);++ apiRoute(PST, "/api/special-notes/save-llm-chat", llmSpecialNotesRoute.saveLlmChat);asyncRoute(PST, "/api/database/anonymize/:type", [auth.checkApiAuthOrElectron, csrfMiddleware], databaseRoute.anonymize, apiResultHandler);apiRoute(GET, "/api/database/anonymized-databases", databaseRoute.getExistingAnonymizedDatabases);@@@ -176,6 -321,18 +183,10 @@@apiRoute(GET, "/api/database/check-integrity", databaseRoute.checkIntegrity);- asyncRoute(PST, "/api/script/exec", [auth.checkApiAuth, csrfMiddleware], scriptRoute.exec, apiResultHandler);-- apiRoute(PST, "/api/script/run/:noteId", scriptRoute.run);- apiRoute(GET, "/api/script/startup", scriptRoute.getStartupBundles);- apiRoute(GET, "/api/script/widgets", scriptRoute.getWidgetBundles);- apiRoute(PST, "/api/script/bundle/:noteId", scriptRoute.getBundle);- apiRoute(GET, "/api/script/relation/:noteId/:relationName", scriptRoute.getRelationBundles);-+ // LLM chat endpoints+ asyncRoute(PST, "/api/llm-chat/stream", [auth.checkApiAuthOrElectron, csrfMiddleware], llmChatRoute.streamChat, null);+ apiRoute(GET, "/api/llm-chat/models", llmChatRoute.getModels);+// no CSRF since this is called from android approute(PST, "/api/sender/login", [loginRateLimiter], loginApiRoute.token, apiResultHandler);asyncRoute(PST, "/api/sender/image", [auth.checkEtapiToken, uploadMiddlewareWithErrorHandling], senderRoute.uploadImage, apiResultHandler);diff --cc apps/server/src/services/special_notes.tsindex 58070ff0c5,23f2c95493..4232a4ef65--- a/apps/server/src/services/special_notes.ts+++ b/apps/server/src/services/special_notes.ts@@@ -1,2 -1,401 +1,147 @@@- import { special_notes } from "@triliumnext/core";- export default special_notes;-import attributeService from "./attributes.js";-import dateNoteService from "./date_notes.js";++import { SaveLlmChatResponse } from "@triliumnext/commons";++import { t } from "i18next";+++ import becca from "../becca/becca.js";-import noteService from "./notes.js";++import dateNoteService from "./date_notes.js";+ import dateUtils from "./date_utils.js";-import log from "./log.js";+ import hoistedNoteService from "./hoisted_note.js";-import searchService from "./search/services/search.js";++import noteService from "./notes.js";+ import SearchContext from "./search/search_context.js";-import { LBTPL_NOTE_LAUNCHER, LBTPL_CUSTOM_WIDGET, LBTPL_SPACER, LBTPL_SCRIPT } from "./hidden_subtree.js";-import { t } from "i18next";-import BNote from '../becca/entities/bnote.js';-import { SaveSearchNoteResponse, SaveSqlConsoleResponse, SaveLlmChatResponse } from "@triliumnext/commons";--function getInboxNote(date: string) {- const workspaceNote = hoistedNoteService.getWorkspaceNote();- if (!workspaceNote) {- throw new Error("Unable to find workspace note");- }-- let inbox: BNote;-- if (!workspaceNote.isRoot()) {- inbox = workspaceNote.searchNoteInSubtree("#workspaceInbox");-- if (!inbox) {- inbox = workspaceNote.searchNoteInSubtree("#inbox");- }-- if (!inbox) {- inbox = workspaceNote;- }- } else {- inbox = attributeService.getNoteWithLabel("inbox") || dateNoteService.getDayNote(date);- }-- return inbox;-}--function createSqlConsole() {- const { note } = noteService.createNewNote({- parentNoteId: getMonthlyParentNoteId("_sqlConsole", "sqlConsole"),- title: "SQL Console - " + dateUtils.localNowDate(),- content: "SELECT title, isDeleted, isProtected FROM notes WHERE noteId = ''\n\n\n\n",- type: "code",- mime: "text/x-sqlite;schema=trilium"- });-- note.setLabel("iconClass", "bx bx-data");- note.setLabel("keepCurrentHoisting");-- return note;-}--async function saveSqlConsole(sqlConsoleNoteId: string) {- const sqlConsoleNote = becca.getNote(sqlConsoleNoteId);- if (!sqlConsoleNote) throw new Error(`Unable to find SQL console note ID: ${sqlConsoleNoteId}`);- const today = dateUtils.localNowDate();-- const sqlConsoleHome = attributeService.getNoteWithLabel("sqlConsoleHome") || await dateNoteService.getDayNote(today);-- const result = sqlConsoleNote.cloneTo(sqlConsoleHome.noteId);-- for (const parentBranch of sqlConsoleNote.getParentBranches()) {- if (parentBranch.parentNote?.hasAncestor("_hidden")) {- parentBranch.markAsDeleted();- }- }-- return result satisfies SaveSqlConsoleResponse;-}--function createSearchNote(searchString: string, ancestorNoteId: string) {- const { note } = noteService.createNewNote({- parentNoteId: getMonthlyParentNoteId("_search", "search"),- title: `${t("special_notes.search_prefix")} ${searchString}`,- content: "",- type: "search",- mime: "application/json"- });-- note.setLabel("searchString", searchString);- note.setLabel("keepCurrentHoisting");-- if (ancestorNoteId) {- note.setRelation("ancestor", ancestorNoteId);- }-- return note;-}--function getSearchHome() {- const workspaceNote = hoistedNoteService.getWorkspaceNote();- if (!workspaceNote) {- throw new Error("Unable to find workspace note");- }-- if (!workspaceNote.isRoot()) {- return workspaceNote.searchNoteInSubtree("#workspaceSearchHome") || workspaceNote.searchNoteInSubtree("#searchHome") || workspaceNote;- } else {- const today = dateUtils.localNowDate();-- return workspaceNote.searchNoteInSubtree("#searchHome") || dateNoteService.getDayNote(today);- }-}--function saveSearchNote(searchNoteId: string) {- const searchNote = becca.getNote(searchNoteId);- if (!searchNote) {- throw new Error("Unable to find search note");- }-- const searchHome = getSearchHome();-- const result = searchNote.cloneTo(searchHome.noteId);-- for (const parentBranch of searchNote.getParentBranches()) {- if (parentBranch.parentNote?.hasAncestor("_hidden")) {- parentBranch.markAsDeleted();- }- }-- return result satisfies SaveSearchNoteResponse;-}++import searchService from "./search/services/search.js";++ function createLlmChat() {+ const { note } = noteService.createNewNote({+ parentNoteId: getMonthlyParentNoteId("_llmChat", "llmChat"),+ title: `${t("special_notes.llm_chat_prefix")} ${dateUtils.localNowDateTime()}`,+ content: JSON.stringify({+ version: 1,+ messages: []+ }),+ type: "llmChat",+ mime: "application/json"+ });++ note.setLabel("iconClass", "bx bx-message-square-dots");+ note.setLabel("keepCurrentHoisting");++ return note;+ }++ /**+ * Gets the most recently modified LLM chat note.+ * Used by sidebar chat to persist conversation across page refreshes.+ * Returns null if no chat exists.+ */+ function getMostRecentLlmChat() {+ // Search for all llmChat notes and return the most recently modified+ const results = searchService.searchNotes(+ "note.type = llmChat",+ new SearchContext({+ ancestorNoteId: "_llmChat",+ limit: 1,+ orderBy: "utcDateModified",+ orderDirection: "desc"+ })+ );++ return results.length > 0 ? results[0] : null;+ }++ /**+ * Gets the most recent LLM chat or creates a new one if none exists.+ * Used by sidebar chat for persistent conversations.+ */+ function getOrCreateLlmChat() {+ const existingChat = getMostRecentLlmChat();++ if (existingChat) {+ return existingChat;+ }++ return createLlmChat();+ }++ /**+ * Gets a list of recent LLM chat notes.+ * Used by sidebar chat history popup.+ */+ function getRecentLlmChats(limit: number = 10) {+ const results = searchService.searchNotes(+ "note.type = llmChat",+ new SearchContext({+ ancestorNoteId: "_llmChat",+ limit,+ orderBy: "utcDateModified",+ orderDirection: "desc"+ })+ );++ return results.map(note => ({+ noteId: note.noteId,+ title: note.title,+ dateModified: note.utcDateModified+ }));+ }++ function getLlmChatHome() {+ const workspaceNote = hoistedNoteService.getWorkspaceNote();+ if (!workspaceNote) {+ throw new Error("Unable to find workspace note");+ }++ if (!workspaceNote.isRoot()) {+ return workspaceNote.searchNoteInSubtree("#workspaceLlmChatHome") || workspaceNote.searchNoteInSubtree("#llmChatHome") || workspaceNote;- } else {- const today = dateUtils.localNowDate();-- return workspaceNote.searchNoteInSubtree("#llmChatHome") || dateNoteService.getDayNote(today);+ }++ const today = dateUtils.localNowDate();++++ return workspaceNote.searchNoteInSubtree("#llmChatHome") || dateNoteService.getDayNote(today);+++ }+-function saveLlmChat(llmChatNoteId: string) {++function saveLlmChat(llmChatNoteId: string | null) {+ const llmChatNote = becca.getNote(llmChatNoteId);+ if (!llmChatNote) {+ throw new Error(`Unable to find LLM chat note ID: ${llmChatNoteId}`);+ }++ const llmChatHome = getLlmChatHome();++ const result = llmChatNote.cloneTo(llmChatHome.noteId);++ for (const parentBranch of llmChatNote.getParentBranches()) {+ if (parentBranch.parentNote?.hasAncestor("_hidden")) {+ parentBranch.markAsDeleted();+ }+ }++ return result satisfies SaveLlmChatResponse;+ }++ function getMonthlyParentNoteId(rootNoteId: string, prefix: string) {+ const month = dateUtils.localNowDate().substring(0, 7);+ const labelName = `${prefix}MonthNote`;++ let monthNote = searchService.findFirstNoteWithQuery(`#${labelName}="${month}"`, new SearchContext({ ancestorNoteId: rootNoteId }));++ if (!monthNote) {+ monthNote = noteService.createNewNote({+ parentNoteId: rootNoteId,+ title: month,+ content: "",+ isProtected: false,+ type: "book"+ }).note;++ monthNote.addLabel(labelName, month);+ }++ return monthNote.noteId;+ }+-function createScriptLauncher(parentNoteId: string, forceNoteId?: string) {- const note = noteService.createNewNote({- noteId: forceNoteId,- title: "Script Launcher",- type: "launcher",- content: "",- parentNoteId: parentNoteId- }).note;-- note.addRelation("template", LBTPL_SCRIPT);- return note;-}--export type LauncherType = "launcher" | "note" | "script" | "customWidget" | "spacer";--interface LauncherConfig {- parentNoteId: string;- launcherType: LauncherType;- noteId?: string;-}--function createLauncher({ parentNoteId, launcherType, noteId }: LauncherConfig) {- let note;-- if (launcherType === "note") {- note = noteService.createNewNote({- noteId: noteId,- title: "Note Launcher",- type: "launcher",- content: "",- parentNoteId: parentNoteId- }).note;-- note.addRelation("template", LBTPL_NOTE_LAUNCHER);- } else if (launcherType === "script") {- note = createScriptLauncher(parentNoteId, noteId);- } else if (launcherType === "customWidget") {- note = noteService.createNewNote({- noteId: noteId,- title: "Widget Launcher",- type: "launcher",- content: "",- parentNoteId: parentNoteId- }).note;-- note.addRelation("template", LBTPL_CUSTOM_WIDGET);- } else if (launcherType === "spacer") {- note = noteService.createNewNote({- noteId: noteId,- branchId: noteId,- title: "Spacer",- type: "launcher",- content: "",- parentNoteId: parentNoteId- }).note;-- note.addRelation("template", LBTPL_SPACER);- } else {- throw new Error(`Unrecognized launcher type '${launcherType}'`);- }-- return {- success: true,- note- };-}--function resetLauncher(noteId: string) {- const note = becca.getNote(noteId);-- if (note?.isLaunchBarConfig()) {- if (note) {- if (noteId === "_lbRoot" || noteId === "_lbMobileRoot") {- // deleting hoisted notes are not allowed, so we just reset the children- for (const childNote of note.getChildNotes()) {- childNote.deleteNote();- }- } else {- note.deleteNote();- }- } else {- log.info(`Note ${noteId} has not been found and cannot be reset.`);- }- } else {- log.info(`Note ${noteId} is not a resettable launcher note.`);- }-- // the re-building deleted launchers will be done in handlers-}--/**- * This exists to ease transition into the new launchbar, but it's not meant to be a permanent functionality.- * Previously, the launchbar was fixed and the only way to add buttons was through this API, so a lot of buttons have been- * created just to fill this user hole.- *- * Another use case was for script-packages (e.g. demo Task manager) which could this way register automatically/easily- * into the launchbar - for this it's recommended to use backend API's createOrUpdateLauncher()- */-function createOrUpdateScriptLauncherFromApi(opts: { id: string; title: string; action: string; icon?: string; shortcut?: string }) {- if (opts.id && !/^[a-z0-9]+$/i.test(opts.id)) {- throw new Error(`Launcher ID can be alphanumeric only, '${opts.id}' given`);- }-- const launcherId = opts.id || `tb_${opts.title.toLowerCase().replace(/[^[a-z0-9]/gi, "")}`;-- if (!opts.title) {- throw new Error("Title is mandatory property to create or update a launcher.");- }-- const launcherNote = becca.getNote(launcherId) || createScriptLauncher("_lbVisibleLaunchers", launcherId);-- launcherNote.title = opts.title;- launcherNote.setContent(`(${opts.action})()`);- launcherNote.setLabel("scriptInLauncherContent"); // there's no target note, the script is in the launcher's content- launcherNote.mime = "application/javascript;env=frontend";- launcherNote.save();-- if (opts.shortcut) {- launcherNote.setLabel("keyboardShortcut", opts.shortcut);- } else {- launcherNote.removeLabel("keyboardShortcut");- }-- if (opts.icon) {- launcherNote.setLabel("iconClass", `bx bx-${opts.icon}`);- } else {- launcherNote.removeLabel("iconClass");- }-- return launcherNote;-}-+ export default {- getInboxNote,- createSqlConsole,- saveSqlConsole,- createSearchNote,- saveSearchNote,+ createLlmChat,+ getMostRecentLlmChat,+ getOrCreateLlmChat,+ getRecentLlmChats,+ saveLlmChat,- createLauncher,- resetLauncher,- createOrUpdateScriptLauncherFromApi+ };diff --cc package.jsonindex 151c60f094,b3bb706df8..f9d0f83464--- a/package.json+++ b/package.json@@@ -18,7 -18,7 +18,8 @@@"desktop:start": "pnpm run --filter desktop dev","desktop:build": "pnpm run --filter desktop build","desktop:start-prod": "pnpm run --filter desktop start-prod",+ "standalone:start": "pnpm run --filter client-standalone dev",+ "desktop:start-prod-no-dir": "pnpm run --filter desktop start-prod-no-dir","edit-docs:edit-docs": "pnpm run --filter edit-docs edit-docs","edit-docs:build": "pnpm run --filter edit-docs build","website:start": "pnpm run --filter website dev",diff --cc packages/trilium-core/src/services/app_info.tsindex 178b68c382,0000000000..5a8b19e178mode 100644,000000..100644--- a/packages/trilium-core/src/services/app_info.ts+++ b/packages/trilium-core/src/services/app_info.ts@@@ -1,19 -1,0 +1,19 @@@+import build from "./build.js";+import packageJson from "../../package.json" with { type: "json" };+import { AppInfo } from "@triliumnext/commons";+- const APP_DB_VERSION = 234;++const APP_DB_VERSION = 235;+const SYNC_VERSION = 37;+const CLIPPER_PROTOCOL_VERSION = "1.0";++const appInfo: AppInfo = {+ appVersion: packageJson.version,+ dbVersion: APP_DB_VERSION,+ syncVersion: SYNC_VERSION,+ buildDate: build.buildDate,+ buildRevision: build.buildRevision,+ clipperProtocolVersion: CLIPPER_PROTOCOL_VERSION,+ utcDateTime: new Date().toISOString()+}++export default appInfo;diff --cc packages/trilium-core/src/services/hidden_subtree.tsindex 0f3dbc4082,0000000000..feaeb42a49mode 100644,000000..100644--- a/packages/trilium-core/src/services/hidden_subtree.ts+++ b/packages/trilium-core/src/services/hidden_subtree.ts@@@ -1,512 -1,0 +1,517 @@@+import type { HiddenSubtreeItem } from "@triliumnext/commons";+import { t } from "i18next";++import becca from "../becca/becca.js";+import BAttribute from "../becca/entities/battribute.js";+import BBranch from "../becca/entities/bbranch.js";+import BNote from "../becca/entities/bnote.js";+import buildLaunchBarConfig from "./hidden_subtree_launcherbar.js";+import buildHiddenSubtreeTemplates from "./hidden_subtree_templates.js";+import { cleanUpHelp, getHelpHiddenSubtreeData } from "./in_app_help.js";+import migrationService from "./migration.js";+import noteService from "./notes.js";- import { getLog } from "./log.js";- import { getSql } from "./sql/index.js";++export const LBTPL_ROOT = "_lbTplRoot";+export const LBTPL_BASE = "_lbTplBase";+export const LBTPL_HEADER = "_lbTplHeader";+export const LBTPL_NOTE_LAUNCHER = "_lbTplLauncherNote";+export const LBTPL_WIDGET = "_lbTplLauncherWidget";+export const LBTPL_COMMAND = "_lbTplLauncherCommand";+export const LBTPL_SCRIPT = "_lbTplLauncherScript";+export const LBTPL_SPACER = "_lbTplSpacer";+export const LBTPL_CUSTOM_WIDGET = "_lbTplCustomWidget";++/*+ * Hidden subtree is generated as a "predictable structure" which means that it avoids generating random IDs to always+ * produce the same structure. This is needed because it is run on multiple instances in the sync cluster which might produce+ * duplicate subtrees. This way, all instances will generate the same structure with the same IDs.+ */++let hiddenSubtreeDefinition: HiddenSubtreeItem;++function buildHiddenSubtreeDefinition(helpSubtree: HiddenSubtreeItem[]): HiddenSubtreeItem {+ const launchbarConfig = buildLaunchBarConfig();++ return {+ id: "_hidden",+ title: t("hidden-subtree.root-title"),+ type: "doc",+ icon: "bx bx-hide",+ // we want to keep the hidden subtree always last, otherwise there will be problems with e.g., keyboard navigation+ // over tree when it's in the middle+ notePosition: 999_999_999,+ enforceAttributes: true,+ attributes: [+ { type: "label", name: "docName", value: "hidden" }+ ],+ children: [+ {+ id: "_search",+ title: t("hidden-subtree.search-history-title"),+ type: "doc"+ },+ {+ id: "_globalNoteMap",+ title: t("hidden-subtree.note-map-title"),+ type: "noteMap",+ attributes: [+ { type: "label", name: "mapRootNoteId", value: "hoisted" },+ { type: "label", name: "keepCurrentHoisting" }+ ]+ },+ {+ id: "_sqlConsole",+ title: t("hidden-subtree.sql-console-history-title"),+ type: "doc",+ icon: "bx-data"+ },++ {++ id: "_llmChat",++ title: t("hidden-subtree.llm-chat-history-title"),++ type: "doc",++ icon: "bx-message-square-dots"++ },+ {+ id: "_share",+ title: t("hidden-subtree.shared-notes-title"),+ type: "doc",+ attributes: [{ type: "label", name: "docName", value: "share" }]+ },+ {+ id: "_bulkAction",+ title: t("hidden-subtree.bulk-action-title"),+ type: "doc"+ },+ {+ id: "_backendLog",+ title: t("hidden-subtree.backend-log-title"),+ type: "contentWidget",+ icon: "bx-terminal",+ attributes: [+ { type: "label", name: "keepCurrentHoisting" },+ { type: "label", name: "fullContentWidth" }+ ]+ },+ {+ // place for user scripts hidden stuff (scripts should not create notes directly under hidden root)+ id: "_userHidden",+ title: t("hidden-subtree.user-hidden-title"),+ type: "doc",+ attributes: [{ type: "label", name: "docName", value: "user_hidden" }]+ },+ {+ id: LBTPL_ROOT,+ title: t("hidden-subtree.launch-bar-templates-title"),+ type: "doc",+ children: [+ {+ id: LBTPL_BASE,+ title: t("hidden-subtree.base-abstract-launcher-title"),+ type: "doc"+ },+ {+ id: LBTPL_COMMAND,+ title: t("hidden-subtree.command-launcher-title"),+ type: "doc",+ attributes: [+ { type: "relation", name: "template", value: LBTPL_BASE },+ { type: "label", name: "launcherType", value: "command" },+ { type: "label", name: "docName", value: "launchbar_command_launcher" }+ ]+ },+ {+ id: LBTPL_NOTE_LAUNCHER,+ title: t("hidden-subtree.note-launcher-title"),+ type: "doc",+ attributes: [+ { type: "relation", name: "template", value: LBTPL_BASE },+ { type: "label", name: "launcherType", value: "note" },+ { type: "label", name: "relation:target", value: "promoted" },+ { type: "label", name: "relation:hoistedNote", value: "promoted" },+ { type: "label", name: "label:keyboardShortcut", value: "promoted,text" },+ { type: "label", name: "docName", value: "launchbar_note_launcher" }+ ]+ },+ {+ id: LBTPL_SCRIPT,+ title: t("hidden-subtree.script-launcher-title"),+ type: "doc",+ attributes: [+ { type: "relation", name: "template", value: LBTPL_BASE },+ { type: "label", name: "launcherType", value: "script" },+ { type: "label", name: "relation:script", value: "promoted" },+ { type: "label", name: "label:keyboardShortcut", value: "promoted,text" },+ { type: "label", name: "docName", value: "launchbar_script_launcher" }+ ]+ },+ {+ id: LBTPL_WIDGET,+ title: t("hidden-subtree.built-in-widget-title"),+ type: "doc",+ attributes: [+ { type: "relation", name: "template", value: LBTPL_BASE },+ { type: "label", name: "launcherType", value: "builtinWidget" }+ ]+ },+ {+ id: LBTPL_SPACER,+ title: t("hidden-subtree.spacer-title"),+ type: "doc",+ icon: "bx-move-vertical",+ attributes: [+ { type: "relation", name: "template", value: LBTPL_WIDGET },+ { type: "label", name: "builtinWidget", value: "spacer" },+ { type: "label", name: "label:baseSize", value: "promoted,number" },+ { type: "label", name: "label:growthFactor", value: "promoted,number" },+ { type: "label", name: "docName", value: "launchbar_spacer" }+ ]+ },+ {+ id: LBTPL_CUSTOM_WIDGET,+ title: t("hidden-subtree.custom-widget-title"),+ type: "doc",+ attributes: [+ { type: "relation", name: "template", value: LBTPL_BASE },+ { type: "label", name: "launcherType", value: "customWidget" },+ { type: "label", name: "relation:widget", value: "promoted" },+ { type: "label", name: "docName", value: "launchbar_widget_launcher" }+ ]+ }+ ]+ },+ {+ id: "_lbRoot",+ title: t("hidden-subtree.launch-bar-title"),+ type: "doc",+ icon: "bx-sidebar",+ isExpanded: true,+ attributes: [{ type: "label", name: "docName", value: "launchbar_intro" }],+ children: [+ {+ id: "_lbAvailableLaunchers",+ title: t("hidden-subtree.available-launchers-title"),+ type: "doc",+ icon: "bx-hide",+ isExpanded: true,+ attributes: [{ type: "label", name: "docName", value: "launchbar_intro" }],+ children: launchbarConfig.desktopAvailableLaunchers+ },+ {+ id: "_lbVisibleLaunchers",+ title: t("hidden-subtree.visible-launchers-title"),+ type: "doc",+ icon: "bx-show",+ isExpanded: true,+ attributes: [{ type: "label", name: "docName", value: "launchbar_intro" }],+ children: launchbarConfig.desktopVisibleLaunchers+ }+ ]+ },+ {+ id: "_lbMobileRoot",+ title: "Mobile Launch Bar",+ type: "doc",+ icon: "bx-mobile",+ isExpanded: true,+ attributes: [{ type: "label", name: "docName", value: "launchbar_intro" }],+ children: [+ {+ id: "_lbMobileAvailableLaunchers",+ title: t("hidden-subtree.available-launchers-title"),+ type: "doc",+ icon: "bx-hide",+ isExpanded: true,+ attributes: [{ type: "label", name: "docName", value: "launchbar_intro" }],+ children: launchbarConfig.mobileAvailableLaunchers+ },+ {+ id: "_lbMobileVisibleLaunchers",+ title: t("hidden-subtree.visible-launchers-title"),+ type: "doc",+ icon: "bx-show",+ isExpanded: true,+ attributes: [{ type: "label", name: "docName", value: "launchbar_intro" }],+ children: launchbarConfig.mobileVisibleLaunchers+ }+ ]+ },+ {+ id: "_options",+ title: t("hidden-subtree.options-title"),+ type: "book",+ icon: "bx-cog",+ children: [+ { id: "_optionsAppearance", title: t("hidden-subtree.appearance-title"), type: "contentWidget", icon: "bx-layout" },+ { id: "_optionsShortcuts", title: t("hidden-subtree.shortcuts-title"), type: "contentWidget", icon: "bxs-keyboard" },+ { id: "_optionsTextNotes", title: t("hidden-subtree.text-notes"), type: "contentWidget", icon: "bx-text" },+ { id: "_optionsCodeNotes", title: t("hidden-subtree.code-notes-title"), type: "contentWidget", icon: "bx-code" },+ { id: "_optionsImages", title: t("hidden-subtree.images-title"), type: "contentWidget", icon: "bx-image" },+ { id: "_optionsSpellcheck", title: t("hidden-subtree.spellcheck-title"), type: "contentWidget", icon: "bx-check-double" },+ { id: "_optionsPassword", title: t("hidden-subtree.password-title"), type: "contentWidget", icon: "bx-lock" },+ { id: '_optionsMFA', title: t('hidden-subtree.multi-factor-authentication-title'), type: 'contentWidget', icon: 'bx-lock ' },+ { id: "_optionsEtapi", title: t("hidden-subtree.etapi-title"), type: "contentWidget", icon: "bx-extension" },+ { id: "_optionsBackup", title: t("hidden-subtree.backup-title"), type: "contentWidget", icon: "bx-data" },+ { id: "_optionsSync", title: t("hidden-subtree.sync-title"), type: "contentWidget", icon: "bx-wifi" },++ { id: "_optionsLlm", title: t("hidden-subtree.llm-title"), type: "contentWidget", icon: "bx-bot" },+ { id: "_optionsAi", title: "AI Chat", type: "contentWidget", enforceDeleted: true },+ { id: "_optionsOther", title: t("hidden-subtree.other"), type: "contentWidget", icon: "bx-dots-horizontal" },+ { id: "_optionsLocalization", title: t("hidden-subtree.localization"), type: "contentWidget", icon: "bx-world" },+ { id: "_optionsAdvanced", title: t("hidden-subtree.advanced-title"), type: "contentWidget" }+ ]+ },+ {+ id: "_help",+ title: t("hidden-subtree.user-guide"),+ type: "book",+ icon: "bx-help-circle",+ children: helpSubtree,+ isExpanded: true+ },+ buildHiddenSubtreeTemplates()+ ]+ };+}++interface CheckHiddenExtraOpts {+ restoreNames?: boolean;+}++function checkHiddenSubtree(force = false, extraOpts: CheckHiddenExtraOpts = {}) {+ if (!force && !migrationService.isDbUpToDate()) {+ // on-delete hook might get triggered during some future migration and cause havoc+ getLog().info("Will not check hidden subtree until migration is finished.");+ return;+ }++ const helpSubtree = getHelpHiddenSubtreeData();+ if (!hiddenSubtreeDefinition || force) {+ hiddenSubtreeDefinition = buildHiddenSubtreeDefinition(helpSubtree);+ }++ getSql().transactional(() => {+ checkHiddenSubtreeRecursively("root", hiddenSubtreeDefinition, extraOpts);+ });++ try {+ cleanUpHelp(helpSubtree);+ } catch (e) {+ // Non-critical operation should something go wrong.+ console.error(e);+ }+}++/**+ * Get all expected parent IDs for a given note ID from the hidden subtree definition+ */+function getExpectedParentIds(noteId: string, subtree: HiddenSubtreeItem): string[] {+ const expectedParents: string[] = [];++ function traverse(item: HiddenSubtreeItem, parentId: string) {+ if (item.id === noteId) {+ expectedParents.push(parentId);+ }++ if (item.children) {+ for (const child of item.children) {+ traverse(child, item.id);+ }+ }+ }++ // Start traversal from root+ if (subtree.id === noteId) {+ expectedParents.push("root");+ }++ if (subtree.children) {+ for (const child of subtree.children) {+ traverse(child, subtree.id);+ }+ }++ return expectedParents;+}++/**+ * Check if a note ID is within the hidden subtree structure+ */+function isWithinHiddenSubtree(noteId: string): boolean {+ // Consider a note to be within hidden subtree if it starts with underscore+ // This is the convention used for hidden subtree notes+ return noteId.startsWith("_") || noteId === "root";+}++function checkHiddenSubtreeRecursively(parentNoteId: string, item: HiddenSubtreeItem, extraOpts: CheckHiddenExtraOpts = {}) {+ if (!item.id || !item.type || !item.title) {+ throw new Error(`Item does not contain mandatory properties: ${JSON.stringify(item)}`);+ }++ if (item.id.charAt(0) !== "_") {+ throw new Error(`ID has to start with underscore, given '${item.id}'`);+ }++ let note = becca.notes[item.id] as BNote | undefined;+ let branch: BBranch | undefined;+ const log = getLog();++ if (item.enforceDeleted) {+ note?.deleteNote();+ return;+ }++ if (!note) {+ // Missing item, add it.+ ({ note, branch } = noteService.createNewNote({+ noteId: item.id,+ title: item.title,+ type: item.type,+ parentNoteId,+ content: item.content ?? "",+ ignoreForbiddenParents: true+ }));+ } else {+ // Existing item, check if it's in the right state.+ branch = note.getParentBranches().find((branch) => branch.parentNoteId === parentNoteId);++ if (item.content && note.getContent() !== item.content) {+ log.info(`Updating content of ${item.id}.`);+ note.setContent(item.content);+ }++ if (item.enforceBranches || item.id.startsWith("_help")) {+ // Clean up any branches that shouldn't exist according to the meta definition+ // For hidden subtree notes, we want to ensure they only exist in their designated locations++ // If the note exists but doesn't have a branch in the expected parent,+ // create the missing branch to ensure it's in the correct location+ if (!branch) {+ log.info(`Creating missing branch for note ${item.id} under parent ${parentNoteId}.`);+ branch = new BBranch({+ noteId: item.id,+ parentNoteId,+ notePosition: item.notePosition !== undefined ? item.notePosition : undefined,+ isExpanded: item.isExpanded !== undefined ? item.isExpanded : false+ }).save();+ }++ // Remove any branches that are not in the expected parent.+ const expectedParents = getExpectedParentIds(item.id, hiddenSubtreeDefinition);+ const currentBranches = note.getParentBranches();++ for (const currentBranch of currentBranches) {+ // Only delete branches that are not in the expected locations+ // and are within the hidden subtree structure (avoid touching user-created clones)+ if (!expectedParents.includes(currentBranch.parentNoteId) &&+ isWithinHiddenSubtree(currentBranch.parentNoteId)) {+ log.info(`Removing unexpected branch for note '${item.id}' from parent '${currentBranch.parentNoteId}'`);+ currentBranch.markAsDeleted();+ }+ }+ }+ }++ const attrs = [...(item.attributes || [])];++ if (item.icon) {+ attrs.push({ type: "label", name: "iconClass", value: `bx ${item.icon}` });+ }++ if (item.type === "launcher") {+ if (item.command) {+ attrs.push({ type: "relation", name: "template", value: LBTPL_COMMAND });+ attrs.push({ type: "label", name: "command", value: item.command });+ } else if (item.builtinWidget) {+ if (item.builtinWidget === "spacer") {+ attrs.push({ type: "relation", name: "template", value: LBTPL_SPACER });+ attrs.push({ type: "label", name: "baseSize", value: item.baseSize });+ attrs.push({ type: "label", name: "growthFactor", value: item.growthFactor });+ } else {+ attrs.push({ type: "relation", name: "template", value: LBTPL_WIDGET });+ }++ attrs.push({ type: "label", name: "builtinWidget", value: item.builtinWidget });+ } else if (item.targetNoteId) {+ attrs.push({ type: "relation", name: "template", value: LBTPL_NOTE_LAUNCHER });+ attrs.push({ type: "relation", name: "target", value: item.targetNoteId });+ } else if (!item.enforceDeleted) {+ throw new Error(`No action defined for launcher ${JSON.stringify(item)}`);+ }+ }++ const shouldRestoreNames = extraOpts.restoreNames || note.noteId.startsWith("_help") || item.id.startsWith("_lb") || item.id.startsWith("_template");+ if (shouldRestoreNames && note.title !== item.title) {+ note.title = item.title;+ note.save();+ }++ if (note.type !== item.type) {+ // enforce a correct note type+ note.type = item.type;+ note.save();+ }++ if (branch) {+ // in case of launchers the branch ID is not preserved and should not be relied upon - launchers which move between+ // visible and available will change branch since the branch's parent-child relationship is immutable+ if (item.notePosition !== undefined && branch.notePosition !== item.notePosition) {+ branch.notePosition = item.notePosition;+ branch.save();+ }++ if (item.isExpanded !== undefined && branch.isExpanded !== item.isExpanded) {+ branch.isExpanded = item.isExpanded;+ branch.save();+ }+ }++ // Enforce attribute structure if needed.+ if (item.enforceAttributes) {+ for (const attribute of note.getAttributes()) {+ // Remove unwanted attributes.+ const attrDef = attrs.find(a => a.name === attribute.name);+ if (!attrDef) {+ console.log(`Removing unwanted attribute ${attribute.name} where expected attrs are ${attrs.map(a => a.name).join(", ")}`);+ attribute.markAsDeleted();+ continue;+ }++ // Ensure value is consistent.+ if (attribute.value !== attrDef.value || attribute.type !== attrDef.type) {+ attribute.type = attrDef.type;+ attribute.value = attrDef.value ?? "";+ attribute.save();+ }+ }+ }++ for (const attr of attrs) {+ const attrId = `${note.noteId}_${attr.type.charAt(0)}${attr.name}`;++ const existingAttribute = note.getAttributes().find((attr) => attr.attributeId === attrId);++ if (!existingAttribute) {+ new BAttribute({+ attributeId: attrId,+ noteId: note.noteId,+ type: attr.type,+ name: attr.name,+ value: attr.value,+ isInheritable: attr.isInheritable+ }).save();+ } else if (attr.name === "docName" || (existingAttribute.noteId.startsWith("_help") && attr.name === "iconClass")) {+ if (existingAttribute.value !== attr.value) {+ log.info(`Updating attribute ${attrId} from "${existingAttribute.value}" to "${attr.value}"`);+ existingAttribute.value = attr.value ?? "";+ existingAttribute.save();+ }+ }+ }++ for (const child of item.children || []) {+ checkHiddenSubtreeRecursively(item.id, child, extraOpts);+ }+}++export default {+ checkHiddenSubtree+};diff --cc packages/trilium-core/src/services/note_types.tsindex bc0574dc83,0000000000..1038bb7ef1mode 100644,000000..100644--- a/packages/trilium-core/src/services/note_types.ts+++ b/packages/trilium-core/src/services/note_types.ts@@@ -1,34 -1,0 +1,35 @@@+const noteTypes = [+ { type: "text", defaultMime: "text/html" },+ { type: "code", defaultMime: "text/plain" },+ { type: "render", defaultMime: "" },+ { type: "file", defaultMime: "application/octet-stream" },+ { type: "image", defaultMime: "" },+ { type: "search", defaultMime: "" },+ { type: "relationMap", defaultMime: "application/json" },+ { type: "book", defaultMime: "" },+ { type: "noteMap", defaultMime: "" },+ { type: "mermaid", defaultMime: "text/vnd.mermaid" },+ { type: "canvas", defaultMime: "application/json" },+ { type: "webView", defaultMime: "" },+ { type: "launcher", defaultMime: "" },+ { type: "doc", defaultMime: "" },+ { type: "contentWidget", defaultMime: "" },+ { type: "mindMap", defaultMime: "application/json" },- { type: "spreadsheet", defaultMime: "application/json" }++ { type: "spreadsheet", defaultMime: "application/json" },++ { type: "llmChat", defaultMime: "application/json" }+];++function getDefaultMimeForNoteType(typeName: string) {+ const typeRec = noteTypes.find((nt) => nt.type === typeName);++ if (!typeRec) {+ throw new Error(`Cannot find note type '${typeName}'`);+ }++ return typeRec.defaultMime;+}++export default {+ getNoteTypeNames: () => noteTypes.map((nt) => nt.type),+ getDefaultMimeForNoteType+};diff --cc packages/trilium-core/src/services/options_init.tsindex 730b9791a7,0000000000..0219a4d33bmode 100644,000000..100644--- a/packages/trilium-core/src/services/options_init.ts+++ b/packages/trilium-core/src/services/options_init.ts@@@ -1,261 -1,0 +1,264 @@@+import { type KeyboardShortcutWithRequiredActionName, type OptionMap, type OptionNames, SANITIZER_DEFAULT_ALLOWED_TAGS } from "@triliumnext/commons";++import appInfo from "./app_info.js";+import { getPlatform } from "./platform.js";+import dateUtils from "./utils/date.js";+import keyboardActions from "./keyboard_actions.js";+import { getLog } from "./log.js";+import optionService from "./options.js";+import { isWindows, randomSecureToken } from "./utils/index.js";++export function initDocumentOptions() {+ optionService.createOption("documentId", randomSecureToken(16), false);+ optionService.createOption("documentSecret", randomSecureToken(16), false);+}++/**+ * Contains additional options to be initialized for a new database, containing the information entered by the user.+ */+interface NotSyncedOpts {+ syncServerHost?: string;+ syncProxy?: string;+}++/**+ * Represents a correspondence between an option and its default value, to be initialized when the database is missing that particular option (after a migration from an older version, or when creating a new database).+ */+interface DefaultOption {+ name: OptionNames;+ /**+ * The value to initialize the option with, if the option is not already present in the database.+ *+ * If a function is passed Gin instead, the function is called if the option does not exist (with access to the current options) and the return value is used instead. Useful to migrate a new option with a value depending on some other option that might be initialized.+ */+ value: string | ((options: OptionMap) => string);+ isSynced: boolean;+}++/**+ * Initializes the default options for new databases only.+ *+ * @param initialized `true` if the database has been fully initialized (i.e. a new database was created), or `false` if the database is created for sync.+ * @param opts additional options to be initialized, for example the sync configuration.+ */+export async function initNotSyncedOptions(initialized: boolean, opts: NotSyncedOpts = {}) {+ optionService.createOption(+ "openNoteContexts",+ JSON.stringify([+ {+ notePath: "root",+ active: true+ }+ ]),+ false+ );++ optionService.createOption("lastDailyBackupDate", dateUtils.utcNowDateTime(), false);+ optionService.createOption("lastWeeklyBackupDate", dateUtils.utcNowDateTime(), false);+ optionService.createOption("lastMonthlyBackupDate", dateUtils.utcNowDateTime(), false);+ optionService.createOption("dbVersion", appInfo.dbVersion.toString(), false);++ optionService.createOption("initialized", initialized ? "true" : "false", false);++ optionService.createOption("lastSyncedPull", "0", false);+ optionService.createOption("lastSyncedPush", "0", false);++ optionService.createOption("theme", "next", false);+ optionService.createOption("textNoteEditorType", "ckeditor-classic", true);++ optionService.createOption("syncServerHost", opts.syncServerHost || "", false);+ optionService.createOption("syncServerTimeout", "120000", false);+ optionService.createOption("syncProxy", opts.syncProxy || "", false);+}++/**+ * Contains all the default options that must be initialized on new and existing databases (at startup). The value can also be determined based on other options, provided they have already been initialized.+ */+const defaultOptions: DefaultOption[] = [+ { name: "revisionSnapshotTimeInterval", value: "600", isSynced: true },+ { name: "revisionSnapshotTimeIntervalTimeScale", value: "60", isSynced: true }, // default to Minutes+ { name: "revisionSnapshotNumberLimit", value: "-1", isSynced: true },+ { name: "protectedSessionTimeout", value: "600", isSynced: true },+ { name: "protectedSessionTimeoutTimeScale", value: "60", isSynced: true },+ { name: "zoomFactor", value: () => isWindows() ? "0.9" : "1.0", isSynced: false },+ { name: "overrideThemeFonts", value: "false", isSynced: false },+ { name: "mainFontFamily", value: "theme", isSynced: false },+ { name: "mainFontSize", value: "100", isSynced: false },+ { name: "treeFontFamily", value: "theme", isSynced: false },+ { name: "treeFontSize", value: "100", isSynced: false },+ { name: "detailFontFamily", value: "theme", isSynced: false },+ { name: "detailFontSize", value: "110", isSynced: false },+ { name: "monospaceFontFamily", value: "theme", isSynced: false },+ { name: "monospaceFontSize", value: "110", isSynced: false },+ { name: "spellCheckEnabled", value: "true", isSynced: false },+ { name: "spellCheckLanguageCode", value: "en-US", isSynced: false },+ { name: "imageMaxWidthHeight", value: "2000", isSynced: true },+ { name: "imageJpegQuality", value: "75", isSynced: true },+ { name: "autoFixConsistencyIssues", value: "true", isSynced: false },+ { name: "vimKeymapEnabled", value: "false", isSynced: false },+ { name: "codeLineWrapEnabled", value: "true", isSynced: false },+ {+ name: "codeNotesMimeTypes",+ value: '["text/x-csrc","text/x-c++src","text/x-csharp","text/css","text/x-elixir","text/x-go","text/x-groovy","text/x-haskell","text/html","message/http","text/x-java","application/javascript;env=frontend","application/javascript;env=backend","application/json","text/x-kotlin","text/x-markdown","text/x-perl","text/x-php","text/x-python","text/x-ruby",null,"text/x-sql","text/x-sqlite;schema=trilium","text/x-swift","text/xml","text/x-yaml","text/x-sh","application/typescript"]',+ isSynced: true+ },+ { name: "leftPaneWidth", value: "25", isSynced: false },+ { name: "leftPaneVisible", value: "true", isSynced: false },+ { name: "rightPaneWidth", value: "25", isSynced: false },+ { name: "rightPaneVisible", value: "true", isSynced: false },+ { name: "rightPaneCollapsedItems", value: "[]", isSynced: false },+ { name: "nativeTitleBarVisible", value: "false", isSynced: false },+ { name: "eraseEntitiesAfterTimeInSeconds", value: "604800", isSynced: true }, // default is 7 days+ { name: "eraseEntitiesAfterTimeScale", value: "86400", isSynced: true }, // default 86400 seconds = Day+ { name: "hideArchivedNotes_main", value: "false", isSynced: false },+ { name: "debugModeEnabled", value: "false", isSynced: false },+ { name: "headingStyle", value: "underline", isSynced: true },+ { name: "autoCollapseNoteTree", value: "true", isSynced: true },+ { name: "autoReadonlySizeText", value: "32000", isSynced: false },+ { name: "autoReadonlySizeCode", value: "64000", isSynced: false },+ { name: "dailyBackupEnabled", value: "true", isSynced: false },+ { name: "weeklyBackupEnabled", value: "true", isSynced: false },+ { name: "monthlyBackupEnabled", value: "true", isSynced: false },+ { name: "maxContentWidth", value: "1200", isSynced: false },+ { name: "centerContent", value: "false", isSynced: false },+ { name: "compressImages", value: "true", isSynced: true },+ { name: "downloadImagesAutomatically", value: "true", isSynced: true },+ { name: "minTocHeadings", value: "5", isSynced: true },+ { name: "highlightsList", value: '["underline","color","bgColor"]', isSynced: true },+ { name: "checkForUpdates", value: "true", isSynced: true },+ { name: "disableTray", value: "false", isSynced: false },+ { name: "eraseUnusedAttachmentsAfterSeconds", value: "2592000", isSynced: true }, // default 30 days+ { name: "eraseUnusedAttachmentsAfterTimeScale", value: "86400", isSynced: true }, // default 86400 seconds = Day+ { name: "logRetentionDays", value: "90", isSynced: false }, // default 90 days+ { name: "customSearchEngineName", value: "DuckDuckGo", isSynced: true },+ { name: "customSearchEngineUrl", value: "https://duckduckgo.com/?q={keyword}", isSynced: true },+ { name: "editedNotesOpenInRibbon", value: "true", isSynced: true },+ { name: "mfaEnabled", value: "false", isSynced: false },+ { name: "mfaMethod", value: "totp", isSynced: false },+ { name: "encryptedRecoveryCodes", value: "false", isSynced: false },+ { name: "userSubjectIdentifierSaved", value: "false", isSynced: false },++ // Appearance+ { name: "splitEditorOrientation", value: "horizontal", isSynced: true },+ {+ name: "codeNoteTheme",+ value: (optionsMap) => {+ switch (optionsMap.theme) {+ case "light":+ case "next-light":+ return "default:vs-code-light";+ case "dark":+ case "next-dark":+ default:+ return "default:vs-code-dark";+ }+ },+ isSynced: false+ },+ { name: "motionEnabled", value: "true", isSynced: false },+ { name: "shadowsEnabled", value: "true", isSynced: false },+ { name: "backdropEffectsEnabled", value: "true", isSynced: false },+ { name: "smoothScrollEnabled", value: "true", isSynced: false },+ { name: "newLayout", value: "true", isSynced: true },++ // Internationalization+ { name: "locale", value: "en", isSynced: true },+ { name: "formattingLocale", value: "", isSynced: true }, // no value means auto-detect+ { name: "firstDayOfWeek", value: "1", isSynced: true },+ { name: "firstWeekOfYear", value: "0", isSynced: true },+ { name: "minDaysInFirstWeek", value: "4", isSynced: true },+ { name: "languages", value: "[]", isSynced: true },++ // Code block configuration+ {+ name: "codeBlockTheme",+ value: (optionsMap) => {+ if (optionsMap.theme === "light") {+ return "default:stackoverflow-light";+ }+ return "default:stackoverflow-dark";++ },+ isSynced: false+ },+ { name: "codeBlockWordWrap", value: "false", isSynced: true },++ // Text note configuration+ { name: "textNoteEditorType", value: "ckeditor-balloon", isSynced: true },+ { name: "textNoteEditorMultilineToolbar", value: "false", isSynced: true },+ { name: "textNoteEmojiCompletionEnabled", value: "true", isSynced: true },+ { name: "textNoteCompletionEnabled", value: "true", isSynced: true },+ { name: "textNoteSlashCommandsEnabled", value: "true", isSynced: true },++ // HTML import configuration+ { name: "layoutOrientation", value: "vertical", isSynced: false },+ { name: "backgroundEffects", value: "true", isSynced: false },+ {+ name: "allowedHtmlTags",+ value: JSON.stringify(SANITIZER_DEFAULT_ALLOWED_TAGS),+ isSynced: true+ },++ // Share settings+ { name: "redirectBareDomain", value: "false", isSynced: true },+ { name: "showLoginInShareTheme", value: "false", isSynced: true },++ {+ name: "seenCallToActions",+ value: JSON.stringify([+ "new_layout", "background_effects", "next_theme"+ ]),+ isSynced: true+ },- { name: "experimentalFeatures", value: "[]", isSynced: true }++ { name: "experimentalFeatures", value: "[]", isSynced: true },++++ // AI / LLM++ { name: "llmProviders", value: "[]", isSynced: false }+];++/**+ * Initializes the options, by checking which options from {@link #allDefaultOptions()} are missing and registering them. It will also check some environment variables such as safe mode, to make any necessary adjustments.+ *+ * This method is called regardless of whether a new database is created, or an existing database is used.+ */+export function initStartupOptions() {+ const optionsMap = optionService.getOptionMap();++ const allDefaultOptions = defaultOptions.concat(getKeyboardDefaultOptions());++ const log = getLog();+ for (const { name, value, isSynced } of allDefaultOptions) {+ if (!(name in optionsMap)) {+ let resolvedValue;+ if (typeof value === "function") {+ resolvedValue = value(optionsMap);+ } else {+ resolvedValue = value;+ }++ optionService.createOption(name, resolvedValue, isSynced);+ log.info(`Created option "${name}" with default value "${resolvedValue}"`);+ }+ }++ if (getPlatform().getEnv("TRILIUM_START_NOTE_ID") || getPlatform().getEnv("TRILIUM_SAFE_MODE")) {+ optionService.setOption(+ "openNoteContexts",+ JSON.stringify([+ {+ notePath: getPlatform().getEnv("TRILIUM_START_NOTE_ID") || "root",+ active: true+ }+ ])+ );+ }+}++function getKeyboardDefaultOptions() {+ return (keyboardActions.getDefaultKeyboardActions().filter((ka) => "actionName" in ka) as KeyboardShortcutWithRequiredActionName[]).map((ka) => ({+ name: `keyboardShortcuts${ka.actionName.charAt(0).toUpperCase()}${ka.actionName.slice(1)}`,+ value: JSON.stringify(ka.defaultShortcuts),+ isSynced: false+ })) as DefaultOption[];+}+diff --cc pnpm-lock.yamlindex 368cdcee48,b74a7161ed..ae6d0368f7--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@@ -157,17 -158,10 +158,17 @@@ importersversion: 4.1.2(@opentelemetry/[email protected])(@types/[email protected])(@vitest/[email protected])(@vitest/[email protected])([email protected]([email protected])([email protected]))([email protected]([email protected])([email protected]))([email protected](@types/[email protected])([email protected]))([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))apps/build-docs:+ dependencies:+ '@triliumnext/core':+ specifier: workspace:*+ version: link:../../packages/trilium-core+ '@triliumnext/server':+ specifier: workspace:*+ version: link:../serverdevDependencies:'@redocly/cli':- specifier: 2.25.2- version: 2.25.2(@opentelemetry/[email protected])([email protected])([email protected])([email protected])([email protected])+ specifier: 2.25.3+ version: 2.25.3(@opentelemetry/[email protected])([email protected])([email protected])([email protected])([email protected])archiver:specifier: 7.0.1version: 7.0.1