@x-tech-laboratories/x-app 0.134.0 → 0.136.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -19,15 +19,15 @@ from a folder with its own `package.json` that depends on the agent package alon
19
19
  | Import | What it holds |
20
20
  | ---------------------------------------- | ----------------------------------------------------------------------------- |
21
21
  | `app/define` | The base app: `define_app` puts an X-app's name, ports, files, its own settings and its `define_feature` features (tables, migrations, calls, `api_spec`, settings, histories) together into one store every device keeps (`open_store` calling each feature's `on_open`, `needs_upgrade`, `bind_methods(database, on_change, caller)` running each call as its `caller`, calling each feature's `after_write`, recording versions and announcing writes, `is_read_only`), `page_only` (the specs' `page_only` calls and the writes of `user_only` settings, refused with `page_only_refusal`), its sync engine, its backups' names and schedule, and its bridges named after the app; `AppMethodsOf<typeof app>` types the app's calls. `history_days` sets how far an app's history reaches back until the user chooses (365 unless set); what opening changed is recorded as this device's version, and old versions are pruned on opening and after a write once a day. `settings_knows(key)` lets an import take keys without a spec of their own, such as `diet.target_protein`; `upgrade_layout: { needed, run }` brings a database an older version laid out its own way, such as a versions table keyed another way, in line before any migration, backed up first; `adopt_backup_schedule(database, saved)` moves a schedule an older version kept elsewhere into the setting once. `tools`, a feature of the app's own, is what MCP offers in place of the page's calls, such as tools that take names rather than ids, each run as the `program` caller (`app.mcp`). Sync's and history's triggers come off while migrations run, so a step may drop a column they name. `take_data_change(database)` names the synced tables written since the last call for that connection (null on its first call and after a restore); the server and daemon send it with each change, so a page's `on_change(listener)` hears `{ tables }` and fetches only what it shows from them, or everything on null. `synced_theme` keeps the light, dark or system theme as a synced setting, `theme`, so every device shows the one picked last. `roles` gives the accounts' roles from least to most able (`["user", "admin"]` unless set); `sync: false` is an app whose server is the only copy of its data, such as one watching other machines, so the server keeps no sync peer and Settings shows no Sync section; `declared_tokens: { key, scopes }` reads tokens from that key of the server's config through `server/declared_tokens`. |
22
- | `app/server`, `app/daemon` | `run_server(app, { web_folder })`: the web server from `<PREFIX>_CONFIG` with accounts in `accounts.db` (moved there once from the data's own file, tokens starting with the app's `token_prefix`), the calls, OpenAPI, MCP, the server's backups and its sync peer, a token or MCP client refused the app's `page_only` calls and the `user_only_backup_calls` (restore, remove, schedule) and its calls run as the `program` caller; `run_daemon(app)`: the desktop daemon from `<PREFIX>_DB` with sync, letting devices connect, backups, certificates and the desktop settings; Both take the app's `services` (see `app/services`), `run_daemon(app, env, { services })`. A `backup-schedule.json` an older version kept beside the database moves into this device's setting on opening. Both tell every page when another program, such as an older build, writes the database file (`watch_outside_changes`, on SQLite's `data_version`). `build_server`, `start_daemon`, `open_app_database` (with `on_restore` hooks) and `register_app_calls` for tests and apps that add their own. The server also signs in through OpenID Connect from `<PREFIX>_OIDC_*` (`oidc_from_environment`), bounds sessions by the config's `session_seconds` and `remembered_seconds`, and serves the config's `theme` (`{ scheme, colors }`, read by `read_server_theme`) at the open `GET /api/theme`, which the browser's page applies before it draws: a pinned scheme leaves the Shell's theme row out, and each colour sets a Halon token over both schemes. With the config's `plugins_folder` it serves each plugin's page side under `/api/plugins` (`server/plugin_files`). The app's `routes` may name `open_prefixes`, such as `/api/push/`, `guarded_paths` outside the API, such as `/metrics`, and `needed(method, path, route)`, what a route of its own needs of the one asking, such as an operator's role, null for a path it does not own. The config's `second_factor_from` names the role that must set up a second factor before it changes anything and `token_days` the longest a token lasts. Every server refuses a path spelled two ways (`server/canonical_paths`) and a body that is not JSON and trusts a reverse proxy on this machine for the visitor's address; an app with `security_headers` (true, or `server/security_headers`' options) sends them on every answer. MCP offers an admin `list_backups`, `create_backup` and `get_backup_schedule` (`backup_tools`). |
22
+ | `app/server`, `app/daemon` | `run_server(app, { web_folder })`: the web server from `<PREFIX>_CONFIG` with accounts in `accounts.db` (moved there once from the data's own file, tokens starting with the app's `token_prefix`), the calls, OpenAPI, MCP, the server's backups and its sync peer, a token or MCP client refused the app's `page_only` calls and the `user_only_backup_calls` (restore, remove, schedule) and its calls run as the `program` caller; `run_daemon(app)`: the desktop daemon from `<PREFIX>_DB` with sync, letting devices connect, backups, certificates and the desktop settings; Both take the app's `services` (see `app/services`), `run_daemon(app, env, { services })`. A `backup-schedule.json` an older version kept beside the database moves into this device's setting on opening. Both tell every page when another program, such as an older build, writes the database file (`watch_outside_changes`, on SQLite's `data_version`). `build_server`, `start_daemon`, `open_app_database` (with `on_restore` hooks) and `register_app_calls` for tests and apps that add their own. The server also signs in through OpenID Connect from `<PREFIX>_OIDC_*` (`oidc_from_environment`), bounds sessions by the config's `session_seconds` and `remembered_seconds`, and serves the config's `theme` (`{ scheme, colors }`, read by `read_server_theme`) at the open `GET /api/theme`, which the browser's page applies before it draws: a pinned scheme leaves the Shell's theme row out, and each colour sets a Halon token over both schemes. With the config's `plugins_folder` it serves each plugin's page side under `/api/plugins` (`server/plugin_files`). The app's `routes` may name `open_prefixes`, such as `/api/push/`, `guarded_paths` outside the API, such as `/metrics`, and `needed(method, path, route)`, what a route of its own needs of the one asking, such as an operator's role, null for a path it does not own, and `media_prefixes`, the media its routes stream, such as `/api/stream/`, which an `<audio>` element plays through `page().media_src(path)`: the path itself in a browser, a link the server signs on a portal (`server/media_links`). The config's `second_factor_from` names the role that must set up a second factor before it changes anything and `token_days` the longest a token lasts. Every server refuses a path spelled two ways (`server/canonical_paths`) and a body that is not JSON and trusts a reverse proxy on this machine for the visitor's address; an app with `security_headers` (true, or `server/security_headers`' options) sends them on every answer. MCP offers an admin `list_backups`, `create_backup` and `get_backup_schedule` (`backup_tools`). |
23
23
  | `app/services` | An app's own work beside its calls, run by both hosts: `StartServices` gets a `HostContext` (`kind`, `database()`, `profile`, `device_name`, the server's raw `config`, `plugins_folder`, `declared_file` from `<PREFIX>_DECLARED_FILE` or `/etc/<id>/declared.json`, `announce`, `emit(event, data)` for the page's `on_event`, `side_database(name)` for a never-backed-up file such as `<base>-index.db`, `back_up`) and returns `HostServices` (`before_restore`, `after_restore`, `stop`), stopped before sync and the database. On the server it also gets `config_file`, the path of the config it read, for an app that reads its own keys again when the file changes (with `config_watch`), `declared_tokens()` and `reread_declared_tokens(config)` after such a reload. `before_restore` and `after_restore` may return a promise, which the restore waits for, such as a writer flushing first. |
24
24
  | `app/host_tables`, `app/remote_access`, `remote_access_protocol` | What an app's hosts answer themselves beside its data calls, such as files a computer keeps or programs it runs: `define_app({ host_tables })` names each table with its `api`, the `hosts` that answer it (`"server"`, `"desktop"`) and who reaches it from the network or MCP (`network`: `"admin"` unless set, `"any"`, or `"none"` for this computer's own window alone); the services hand in each table's `methods`, and `elsewhere`, the same calls refusing what only this computer's user may do, for the network and MCP. Every host serves them under `/api/<table>/<call>` (503 until the services started), `/api/host/get_host_abilities` says what the viewer reaches (`admin`, `tables`), MCP and OpenAPI offer them beside the data calls, and the desktop bridges them, a `"none"` table staying on this computer's daemon. `remote_access: true` is the daemon's "Let other devices connect" for its own calls (`create_remote_access`: `remote.json` and the admins in `remote-admins`, mode 0600, https from a certificate and key, listening only while on, changed only over the socket), on `build_server` with the accounts in `accounts.db`, moved there once from the data's own file; `read_remote_access`, `remote_access_problem`. A table's `needs(method)` names the role a call needs from the network or MCP beyond the table's reach, such as an operator's for the calls that change something, refused with 403; every call runs with its request's viewer, which `current_viewer()` of `server/viewer_scope` reads, so the services can name who asked. |
25
25
  | `app/links` | `app_link(scheme, route)` and `route_of_link(scheme, link)`: an app's links such as `x-notes://note/<id>` and the page route they open. |
26
- | `app/desktop`, `app/preload` | `run_desktop(app, electron, { main_dir })`: Electron's main process as a portal onto this computer's daemon or a server, with the window (`default_size` fixed or from the screen's free area, the daemon told while one is in front for its services' `window_in_front`), the tray (`show_tray_icon`, the app's own `tray` rows above Show, Quit and Quit completely, worked out with `call(method)` or a host table's `call("<table>/<call>")`, a write a row makes reaching every window at once, closing the last window leaving the app in it, `--hidden` starting there), the app's `link_scheme` links opening the window on their page (`route_of_link` to map them its own way; the page follows the `open` event), the login entry, a second launch and `--daemon`; the app's own `desktop_settings` switches sit in Settings → Desktop app beside the base's; `run_preload(app, electron)` puts every bridge on the page. The page's `desktop` calls also give the computer's idle seconds (`get_idle_seconds`, from Electron's `powerMonitor`) `set_window_theme`, which the page calls so the window's own parts follow its theme, `get_data_paths` and `show_data_path`, which show this computer's database and backups folder in the file manager from Settings, and `save_text_file`, which asks where through the Save dialog, starting in Downloads (`save_dialog_options`); opening the window replaces a daemon another build left running, and a Flatpak keeps its profile in `~/.config/<id>` as the other builds do. Electron is handed in, so neither imports it. An app with `local_mcp: { default_port }` serves its calls as MCP on 127.0.0.1 from the desktop daemon (`electron/mcp`, page-only calls left out, calls run as `program`), turned on under Settings → MCP server. |
26
+ | `app/desktop`, `app/preload` | `run_desktop(app, electron, { main_dir })`: Electron's main process as a portal onto this computer's daemon or a server, with the window (`default_size` fixed or from the screen's free area, the daemon told while one is in front for its services' `window_in_front`), the tray (`show_tray_icon`, the app's own `tray` rows above Show, Quit and Quit completely, worked out with `call(method)` or a host table's `call("<table>/<call>")`, a write a row makes reaching every window at once, closing the last window leaving the app in it, `--hidden` starting there), the app's `link_scheme` links opening the window on their page (`route_of_link` to map them its own way; the page follows the `open` event), the login entry, a second launch and `--daemon`; the app's own `desktop_settings` switches sit in Settings → Desktop app beside the base's; `run_preload(app, electron)` puts every bridge on the page. The page's `desktop` calls also give the computer's idle seconds (`get_idle_seconds`, from Electron's `powerMonitor`) `set_window_theme`, which the page calls so the window's own parts follow its theme, `get_data_paths` and `show_data_path`, which show this computer's database and backups folder in the file manager from Settings, `pick_folder` and `pick_file` (a title, a starting place and the kinds of file offered), `pick_save_path`, where the daemon then writes a file such as an exported playlist, starting in the folder named, `show_in_folder`, which picks a file out in the file manager, and `save_text_file`, which asks where through the Save dialog, starting in Downloads (`save_dialog_options`); opening the window replaces a daemon another build left running, and a Flatpak keeps its profile in `~/.config/<id>` as the other builds do. Electron is handed in, so neither imports it. An app with `local_mcp: { default_port }` serves its calls as MCP on 127.0.0.1 from the desktop daemon (`electron/mcp`, page-only calls left out, calls run as `program`), turned on under Settings → MCP server. |
27
27
  | `app/window_size` | `fit_window_size(work_area)`: a first window of most of the screen's free area, between 960×640 and 1800×1200 and never past the screen; hand it to `run_desktop` as `default_size`. |
28
28
  | `app/seed` | A development database of an app's example data, made by its own calls: `seed_app_database(app, { file, reset, seed })` opens a fresh file with the app's schema and hands `seed` the app's calls, refusing a file already there without `reset` (which takes its `-wal` and `-shm` too) and the desktop app's real database in `~/.config/<id>` (`real_database_path`) whatever path leads there; `run_seed(app, seed)` is the seed script's whole command line, `<file> [--reset]`, read by `seed_target`. |
29
- | `app/web/app_page`, `app/web/page` | `render_app({ app, pages, general_settings })`: the page on the web, the desktop or Android in the `Shell`, with sign-in in a browser, the theme kept in this browser or, for an app with `synced_theme`, in its synced setting, the sidebar's dragged width remembered on this device (`default_sidebar_width`) unless the chrome's `sidebar_width` holds it, Your account, Settings (the app's general sections, each page's own, Connections, Desktop app, Sync, Backups and Import and export, the settings as a file) and `SyncButton`; `page_hooks<Methods>()` gives the app's typed `calls`, `use_data` and `use_settings`. The phone's host (`app/web/android`) loads only on Android. The page API's `on_event(name, listener)` hears the named events the app's services `emit`, on the web and the desktop. A page may have an `icon` (the sidebar then shows icon rows), a `use_badge` hook ("Inbox · 3"), `in_sidebar: false` with `active_as` for a page reached only by its route; `default_page` names the page an empty route opens, and the `use_chrome(parts)` hook gives the `sidebar` content under the rows, header `tools`, a `side_pane`, a `contained` window where only the page scrolls with a `main_class` for its box, `around`, which wraps the page, such as in the app's own context or with dialogs over any page, and `bare` for the page alone with no sidebar or header, such as a strip embedded in another program. `settings_categories(props)` adds the app's own Settings categories after General, for settings no one page owns. A page's `children` fold open under its row in the sidebar (`#/diet/foods`, the title "Foods · Diet", the first shown when none is named, a single child leaving the page one row); its `use_items` hook gives rows worked out as the page runs, such as each paired device, folding open under it onto `#/devices/<id>` with the title "Pixel · Devices", and its `title(parts)` names the window for its route, such as "Job 12"; and `phone_services` loads the app's own work on the phone only there, such as reminders handed to Android, told of every write, every change from another device and each return to the app; an older version's backup schedule in the page's storage moves into the setting. In a browser, Settings ends with Users and Tokens (`users_settings`) for an admin of the server, with the app's `role_text`; an app's own `use_chrome` sidebar, such as a tree, sits under the pages' rows. |
30
- | `app/web/page_dashboards` | A page's own dashboards: a page declares `dashboard: { data_sources, ready_cards, initial, place }` and the base app draws `Dashboards` on its main route, above its view or in its place, each person's kept per page under the account preference `dashboards`, which every app's server allows and cleans with `clean_page_dashboards`, or on the device where no one signs in; the tabs' menu adds, renames, duplicates, resets and deletes them. |
29
+ | `app/web/app_page`, `app/web/page` | `render_app({ app, pages, general_settings })`: the page on the web, the desktop or Android in the `Shell`, with sign-in in a browser, the theme kept in this browser or, for an app with `synced_theme`, in its synced setting, the sidebar's dragged width remembered on this device (`default_sidebar_width`) unless the chrome's `sidebar_width` holds it, Your account, Settings (Appearance with this device's Halon density, compact, normal or comfortable, set as the root's `data-density` before the page draws (`app/web/density`), the app's general sections, each page's own, Connections, Desktop app, Sync, Backups and Import and export, the settings as a file) and `SyncButton`; `page_hooks<Methods>()` gives the app's typed `calls`, `use_data` and `use_settings`. The phone's host (`app/web/android`) loads only on Android. The page API's `on_event(name, listener)` hears the named events the app's services `emit`, on the web and the desktop. A page may have an `icon` (the sidebar then shows icon rows), a `use_badge` hook ("Inbox · 3"), `in_sidebar: false` with `active_as` for a page reached only by its route; `default_page` names the page an empty route opens, and the `use_chrome(parts)` hook gives the `sidebar` content under the rows, header `tools`, a `side_pane`, a `contained` window where only the page scrolls with a `main_class` for its box, `around`, which wraps the page, such as in the app's own context or with dialogs over any page, and `bare` for the page alone with no sidebar or header, such as a strip embedded in another program. `settings_categories(props)` adds the app's own Settings categories after General, for settings no one page owns. A page's `children` fold open under its row in the sidebar (`#/diet/foods`, the title "Foods · Diet", the first shown when none is named, a single child leaving the page one row); its `use_items` hook gives rows worked out as the page runs, such as each paired device, folding open under it onto `#/devices/<id>` with the title "Pixel · Devices", and its `title(parts)` names the window for its route, such as "Job 12"; and `phone_services` loads the app's own work on the phone only there, such as reminders handed to Android, told of every write, every change from another device and each return to the app; an older version's backup schedule in the page's storage moves into the setting. In a browser, Settings ends with Users and Tokens (`users_settings`) for an admin of the server, with the app's `role_text`; an app's own `use_chrome` sidebar, such as a tree, sits under the pages' rows. |
30
+ | `app/web/page_dashboards` | A page's own dashboards: a page declares `dashboard: { data_sources, ready_cards, initial, place }` and the base app draws `Dashboards` on its main route, above its view, below it (`place: "below"`), where the view draws `PageDashboardsHere` (`"inline"`, such as under its heading) or in its place (`"only"`), each person's kept per page under the account preference `dashboards`, which every app's server allows and cleans with `clean_page_dashboards`, or on the device where no one signs in; the tabs' menu adds, renames, duplicates, resets and deletes them. |
31
31
  | `config/vite`, `config/electron_vite`, `config/vitest`, `config/electron_builder`, `config/tsconfig/*.json` | An X-app's configs as presets: `web_vite_config({ port })` and `android_vite_config()` for the page, `desktop_vite_config()` for electron-vite's window, daemon, preload and page, `vitest_config()` for tests in `tests/` in UTC with coverage of `src/` to the terminal, merged with the app's own floor so `autoUpdate` still raises it, and `base`, `node`, `web` and `tests` tsconfigs to extend. The page presets stand in for Capacitor where the app has none installed (`config/capacitor`'s `capacitor_stand_in`), so a web and desktop app needs no phone packages, and the dev server proxies `/api/`, leaving the page's own `api.ts` to Vite. `electron_builder_config({ id, name, app_id, comment, categories, link_scheme })` is the desktop app's AppImage and Flatpak bundle for electron-builder, the Flatpak keeping its data in `~/.config/<id>` as the other builds do, and reaching what else `flatpak_permissions` names, such as `--system-talk-name=org.bluez`. |
32
32
  | `app_new` | The `x-app-new <X-Name>` command: a new X-app's files written once, laid out as the Application Standard asks, on the base app, the presets, X-App's Nix lib and its CI actions, with an example notes feature; `--port`, `--folder`, `--no-desktop` and `--no-android`. |
33
33
  | `idle_watch` | `step_idle_watch`: time away from the computer while something runs, such as a timer: each look at the idle seconds (the desktop's `get_idle_seconds`) moves the watch on, and once someone comes back it hands back the stretch away (`AwaySpan`) when it passed the threshold, a long gap between looks, as when the computer slept, counting as time away from the last look; `fresh_idle_watch` to start. |
@@ -67,6 +67,7 @@ from a folder with its own `package.json` that depends on the agent package alon
67
67
  | `snippets` | `shorten(text, length = 200)`: text put on one line and cut with an ellipsis, for an excerpt under a title. |
68
68
  | `drizzle`, `drizzle_migrations` | Typed SQLite on Drizzle ORM 1.0.0-rc.5, chosen over Kysely and hand-written SQL because it types rows from one schema in TypeScript, writes the migration SQL from it with drizzle-kit and runs synchronously: `open_drizzle` over any `SqlDatabase`, and `drizzle_of`, which the stores call, making it once per connection, so the same queries run on node:sqlite and in a phone's page, `synced_tables` reading the sync list from the schema's primary keys, `migrate_drizzle` per owner, the schema builders and query operators so an app never imports Drizzle, with `AnySQLiteColumn` for a table whose rows point at its own, and `x-app-bundle-migrations <folder>`, which turns drizzle-kit's migration folders into an `index.ts` a server running .ts files can import. |
69
69
  | `sync_engine`, `sync_peer`, `sync_protocol`, `sync_seal`, `server/sync_peer_routes`, `sync_peer_discovery`, `sync_peer_listening` | SQLite kept alike on every device with no server: `create_sync_engine` stamps each value of the tables it is given through triggers, so the app's own writes need no change, and the newest write of each value wins, each key of a table's `map_columns` (JSON objects such as ids from many sources) counting as a value of its own so two devices adding different keys keep both; a table marked `rows_never_change`, such as saved versions, keeps one version per row instead of one per column, its older per-column versions folded into it on opening. `changed_tables_since(database, cursor)` names the synced tables written after a point. Every copy is a peer: `create_sync_peer` pairs with another device through a one-time code (`create_pairing_code`, `pair_device`), the two copies merging with nothing asked, then sends each paired device its changes within seconds, takes theirs in the same round trip, holds a waiting call open to hear of theirs at once, and passes on what it took from the others, so devices that never reach each other still end up alike; the group's list of devices travels too, so a new device is introduced to the rest and a removed one (`remove_device`) is refused by all. Each call is sealed with both devices' keys on tweetnacl's box (`sync_seal`), chosen over TLS with pinned certificates because it runs alike on Node and in a phone's page; calls still travel over https only. After a restore (`forget_history`) each peer is made to match the restored copy once, keeping a copy of its own first. `register_sync_peer_routes` answers other devices at `sync/peer` under a daemon's prefix, `listen_for_peers` opens a desktop daemon's own port for them, `discover_peers` finds paired devices on the local network by mDNS, on bonjour-service, and `keep_listening_for_peers` (`sync_peer_listening`) is a desktop daemon's "Let other devices connect" setting, kept in a file beside the database, which answers over https with a self-signed certificate made once (`peer_certificate`, on selfsigned, chosen because it makes one with Node's own crypto) and whose `PeerListeningMethods`, its fingerprint included, the page shows with `PeerListeningSettings`; `SyncSettings` given `certificates` asks to review and trust that certificate when pairing fails over it, and pairs again. |
70
+ | `derived_ids` | `derived_id(kind, ...parts)`: an id every device works out alike from what a row is, for rows two devices may make at once, such as a genre a scan meets on a laptop and on the server before they sync, so sync merges them into one row instead of two that clash on the natural key; the first 128 bits of the SHA-512 (tweetnacl) of the kind and the length-prefixed parts, as a version 8 UUID that sits beside `crypto.randomUUID()` ones. No `node:` or DOM imports. |
70
71
  | `sync_files`, `node_file_store`, `electron/file_protocol` | Files that sync beside the rows that name them, such as covers or photos, so a large picture never travels with every change: each is named by the sha256 of its bytes (`hash_bytes`, `put_file`, `is_file_name`) and kept in a `SyncFileStore`, a folder on Node (`folder_file_store`, written through a rename) or IndexedDB on a phone (`indexed_db_files`); given `files: { store, referenced }`, the sync peer sends each paired device the named files it lacks and fetches those this device lacks after each exchange, a few at a time, trying a file neither has yet again next round, and keeps the ones it is sent, refusing bytes that do not match their name; `register_file_scheme` and `serve_files` show them in a desktop page as `<scheme>://<name>`. |
71
72
  | `app_android` | `x-app-android [app folder]`: the app's Capacitor project in `android/`, made from Capacitor's template when it is missing, given X-App's `config/android/release.gradle` and, where it has none of its own, a network rule allowing plain http only to the phone itself (`network_security_config`), for `adb reverse` while testing, (the version CI hands each build, and signing when the release key is in the environment), its launcher icons from `x-app-icons`, then `cap sync android`. Run after the Android page is built; the app keeps `android/` out of git. |
72
73
  | `app_android_key` | `x-app-android-key [app folder] [key folder]` or `x-app-android-key --org <org> [key folder]`: an Android release key, made once with keytool in `~/.local/share/<name>/signing` (or the given folder) and never replaced, and stored with gh as the `ANDROID_KEYSTORE_BASE64`, `ANDROID_KEYSTORE_PASSWORD` and `ANDROID_KEY_ALIAS` secrets `app-android` signs with, handed over on stdin so nothing prints it. `--org` makes one key for every app, kept as organization secrets every repository reads; a repository's own secrets of those names win. Run it in the app's Android shell. |
@@ -80,6 +81,7 @@ from a folder with its own `package.json` that depends on the agent package alon
80
81
  | `phone_backups` | `phone_backups`: a phone app's `backups` in a folder the user picks once in its storage, where file managers and sync apps reach them, through X-App's Android plugin `XLibsBackupFolder`, which `cap sync` adds by itself; `restore` backs up first, swaps the phone database's bytes and saves, `folder_name` and `choose_folder` for the settings row, and daily backups wait quietly until a folder is picked. |
81
82
  | `phone_notices` | `keep_phone_notices`: notices handed to a phone ahead of time through Capacitor's local notifications, the app passing its own `LocalNotifications`, since a phone has no daemon; `refresh` takes back every pending notice and sets the soonest 64 of the next 14 days again, `ask_permission` asks once, `show` puts a notice up at once with no alarm (`isExactNotification: false`), so a notice for now never needs Android's exact-alarm leave or opens its settings screen, `exact: false` lets the notices set ahead ring inexactly too, and a tap hands the notice's `extra` back, such as a link to open. `notice_id` names a key as Android's number. |
82
83
  | `web/remote_daemon` | A page's calls to a daemon or server on another computer with this device's token, as a phone that keeps no data makes them: `call_remote` (a refusal in the host's words, a 401 as `LoginNeeded`, no host chosen or out of reach in plain words), `remote_table` for every call under a path, and `follow_remote` reading the event stream over `fetch`, since EventSource sends no token, reconnecting until stopped (`parse_remote_event`). |
84
+ | `web/audio_engine` | `AudioEngine`: a `PlaybackEngine` on the page's own `<audio>` element, for a page that plays what its server streams, as on a phone or in a browser where there is no mpv: `resolve` turns a file's address into one the element fetches (such as `page().media_src`), a part of a file plays from its start to its end with positions counted from that start, a gain becomes a lower volume, never louder than the file, the element's failures are said in words, and `preload` fetches the next file on a second element that takes over when it is loaded. `make_audio` hands in a stand-in for tests. |
83
85
  | `phone_service` | `phone_service`: work a phone app keeps doing while it is closed, such as staying reachable, in an Android foreground service run by X-App's plugin `XLibsForegroundService`, which `cap sync` adds by itself: the service loads the app's own worker page (such as `worker.html` from its page files) in a WebView it owns, so the work outlives the app's window, a killed process (Android starts it again) and, with `start_at_boot`, a reboot; `start`, `stop`, `is_running`, `post` and `on_message` for the page, and `worker_host` for the worker's side, the messages crossing as JSON. The app declares the service and the boot receiver in its own manifest, with the `connectedDevice` foreground service permissions, as the module's opening comment shows, so no other app gets them. |
84
86
  | `phone_sockets` | `phone_sockets()`: UDP and TCP sockets for a `phone_service` worker, answered by X-App's Android side: `udp_open` (with `broadcast`, holding Android's multicast lock), `tcp_listen`, `tcp_connect` and `list_interfaces`; a TCP socket reads nothing until `read_line` takes one line or `start_reading` everything after, so `start_tls` can follow plain text in either TLS role, as KDE Connect's identity line does, with the app's PEM certificate and key, letting any peer through and handing back its certificate for the worker to pin; `pause` and `resume` for a slow reader, and `write` settling once sent. Events that arrive before a listener are kept for it. Needs `CHANGE_WIFI_MULTICAST_STATE` and `WAKE_LOCK` in the app's manifest; each event keeps the phone awake a few seconds so the worker can answer. |
85
87
  | `app/item_history`, `app/web/item_history` | A history for each kind of item made of rows across tables, such as a workout with its exercises and sets: `item_history_feature(kinds)` keeps each kind's versions (an `ItemLevel` list read by `read_snapshot` and put back by `apply_snapshot`, a deleted item coming back whole) and adds `list_item_history`, `list_recent_changes` and `restore_item_version` with their specs; on the page, `HistoryView` lists the latest changes, `HistoryButton` and `open_item_history` open one item's versions, each restorable after a confirm. |
@@ -108,7 +110,10 @@ from a folder with its own `package.json` that depends on the agent package alon
108
110
  | `agent/worktree_files` | A worktree's files for a page to browse read-only: `list_worktree_files`, what git tracks or would track, ignored files and skipped folders (`.git`, `node_modules`) left out, cut at a count; `read_worktree_file`, one file's text, or none for a binary or too large one, saying whether it came through a symlink; `confined_path` refuses an empty, absolute or `..` path, a skipped folder, and a symlink that leads out of the worktree or into a skipped folder. |
109
111
  | `agent/github` | `github_cli`: GitHub through the `gh` program the user is signed into, so the app holds no token: `account`, `start_sign_in` with the device code and `sign_out`; `find_or_open_issue`, the open issue whose title is close enough (`best_title_match`, `title_likeness`) or a new one; `view_issue`, `ensure_labels` making only the missing ones, `edit_issue`, `post_comment`, `update_comment` (false once the comment is gone) and `close_issue`; `find_pull_request` for a branch, `view_pull_request` and `read_checks` by bucket, while checks still run too; `register_hook` adding or updating a repository's webhook. Bodies and the hook's secret go on gh's standard input, never its command line. |
110
112
  | `agent_transcript` | An agent session's transcript, the same in a daemon, a page and a phone: `fold_stream_message` folds each stream-json line into steps (thinking, text, tool calls with their input and result, notices for an interrupt or a failed turn, the model and permission mode), partial blocks merged as they end; `add_user_message` is pending until the stream echoes it (`pending_messages`); `add_permission` and `waiting_permissions` for tool calls waiting on the user, denied by `close_open_blocks` when the session ends first; `stored_transcript` keeps it within a size, dropping the earliest steps but the starting input, and `read_transcript` reads it back; `tool_summary`, `edit_of` for the change an editing tool makes, and `permission_rule`, `rule_covers` and `rule_words` for allowing a tool, or a command's program, for the rest of the session. |
111
- | `mpv` | Media played through mpv, run as a program of its own and driven over its JSON IPC socket: `MpvEngine` plays one file at a time behind `PlaybackEngine` (load with a start, an end, a gain in decibels and mpv's own per-file options, the next file appended for a gapless join, play, pause, stop, seek, volume, and `state`, `position` and `ended` events), sound only unless `video`; `MpvProcess` is mpv itself, found by `find_mpv` (each override in turn, then the PATH, through `on_path`) and started on the first command, its socket moved to /tmp when the temporary folder's path is too long for one, a start that fails or times out refused with why and mpv's last log line, started again by the next command after a failure or an exit, with `observe` for properties kept across restarts, `on_event`, `on_stop` and `close`, which waits until mpv has gone; `NullEngine` for testing an app's player without mpv. |
113
+ | `mpv` | Media played through mpv, run as a program of its own and driven over its JSON IPC socket: `MpvEngine` plays one file at a time behind `PlaybackEngine` (from `playback`; load with a start, an end, a gain in decibels and mpv's own per-file options, the next file appended for a gapless join, play, pause, stop, seek, volume, and `state`, `position` and `ended` events), sound only unless `video`; `MpvProcess` is mpv itself, found by `find_mpv` (each override in turn, then the PATH, through `on_path`) and started on the first command, its socket moved to /tmp when the temporary folder's path is too long for one, a start that fails or times out refused with why and mpv's last log line, started again by the next command after a failure or an exit, with `observe` for properties kept across restarts, `on_event`, `on_stop` and `close`, which waits until mpv has gone; `NullEngine` is re-exported from `playback`. |
114
+ | `playback` | What an app's player drives, with no Node or DOM: `PlaybackEngine` (one file at a time: load with a start, an end and a gain in decibels, play, pause, stop, seek, volume 0 to 100, `preload` naming the next file for a gapless join, and `state`, `position` and `ended` events), played by `MpvEngine` (`mpv`) on a computer and `AudioEngine` (`web/audio_engine`) in a page; `NullEngine` plays nothing and remembers what it was asked, with `tick`, `finish` and `fail`, for testing a player. |
115
+ | `play_queue` | `PlayQueue`: what plays and what plays next, for a music or podcast player, the same in a daemon on mpv and in a page on an `<audio>` element: a standing list (`set_context`) played after the queue (`enqueue` at the end or next, `dequeue`, `move_in_queue`, `clear_queue`), repeat off, one or all, shuffle in a seeded order (`shuffle_order`) that a new pass changes and `peek_next` leaves alone, previous restarting a track past three seconds, a listen counted as a play at half the track or four minutes (`counts_as_play`) and as a skip when left past three seconds, never both, and the next file preloaded. The app's `PlayQueueSource` says what a track is, which file plays it (`QueueMedia`: uri, part and gain), why one cannot play, and keeps each play and skip; its calls may answer later, as a page's calls to its server do, and a play that fails to be kept goes to `on_error` while the music plays on. `status()` and `subscribe` give `status` and `position` events. |
116
+ | `playlist_files` | Playlist files as paths: `read_playlist_file(text, path)` reads M3U and M3U8 (with `#PLAYLIST`), PLS (in `File<n>` order) and XSPF (on fast-xml-parser) by the path's extension, `resolve_entry` joining a relative entry to the playlist's folder and decoding `file://` URLs; `write_playlist_file(format, name, entries)` writes them back with each entry's artist, title and length where the format can; `playlist_format`, `name_from_path`. No `node:` or DOM imports. |
112
117
  | `agent/wake` | `magic_packet` and `send_magic_packet`: Wake-on-LAN, a few copies of the packet broadcast to a port, sent by a server or by an agent on the sleeping machine's network; `parse_mac` takes colons, dashes, dots or none, a SecureOn `password` follows the packet (`parse_password`), `send_wake_packet` sends a ready packet, and `remote_send_command` is the shell line that sends it from another host with python3 or socat. |
113
118
  | `agent/desktop_notify` | `Notifier`: desktop notifications through notify-send in the agent's own session, with a Dismiss button, a link opened by xdg-open on a click, a timeout the agent enforces even for critical ones, and keys, so a newer notification for a key replaces the old and dismissing the key closes it; the app names itself and maps its own icon names to files. |
114
119
  | `agent/scheduled_notices` | `keep_giving_scheduled_notices`: notices that fall due at set moments, such as reminders, shown through a `Notifier` by a daemon with or without a window; each check shows what fell due since the last, and the moment reached is kept so one missed while stopped still shows, up to half a day late. |
@@ -133,6 +138,8 @@ from a folder with its own `package.json` that depends on the agent package alon
133
138
  | `server/sqlite_backups` | `sqlite_backups`: the `backups` of an SQLite database as `VACUUM INTO` copies in a folder, and `restore`, which backs up the current data first and swaps the file under a closed connection; a server whose connection others hold leaves out `close` and `open`, so the restore is staged beside the database and `take_staged_restore` puts it in place on the next start, before the database opens. |
134
139
  | `server/backup_routes`, `web/backups` | A server's backups for the page's `BackupSettings`: `register_backup_routes` serves the list, backing up now, the daily schedule, restoring and deleting, with the schedule in a JSON file through `json_backup_schedule`; `backup_client` is the page's side. |
135
140
  | `server/sign_in`, `server/login_page` | `register_token_sign_in`: a server with one secret signs browsers in on its own login page, keeps them in by an HMAC-derived cookie, takes the secret as a bearer header, waits after a wrong try, answers 429 with Retry-After once an address has `address_tries_allowed` (20) wrong tries in `address_try_window_seconds` (300), on the login page or as a bearer header on a guarded path, the right ones not counted and a request without one never, and turns the rest away (401 in text or JSON under the API prefix, 303 to the login page elsewhere, with open paths); `register_sign_in_guard` is the turning-away alone, for an app with its own sessions, and given `address_tries` it counts a bearer header that does not sign in against that `AttemptLimit`. Both judge the path as the router reads it, count any route matched under the API prefix as the API, and answer 400 to a path that reads two ways (see `server/request_path`). |
141
+ | `server/media_links` | Links to a server's media that carry their own sign-in, for an `<audio>` or `<video>` element, which cannot send a token: `create_media_links({ prefixes })` signs one path for one user (an HMAC over the path, the user and when it ends, twelve hours unless `lifetime_seconds`, keyed by a secret made as the server starts) and checks it; given to `register_accounts` as `media_links`, anyone signed in, a read-only token included, makes one at `POST <api>/media_link` with the path, and a GET of that path alone with `?link=` comes in as that user, read-only. An app names its media with `AppRoutes.media_prefixes`, and the page plays one through `page().media_src(path)`. |
142
+ | `server/file_ranges` | A file on the server's disk sent with HTTP ranges, so an `<audio>` or `<video>` element starts anywhere and seeks without fetching it whole: `send_file_ranges(request, reply, path)` answers one range with 206 and `content-range`, the whole file with 200, HEAD with the size alone, a range past the end with 416 and a missing file with 404, the type named by `media_type(path)` from the extension (audio and video kinds) unless given; `requested_range(header, size)` reads one range, an open end or the last bytes, and gives the whole file for several. The route decides which file a request may have. |
136
143
  | `server/request_path` | `path_of`: a request's path as Fastify's router reads it (escapes decoded as it decodes them, its semicolon, trailing-slash, duplicate-slash and case options followed); `route_of`: the matched route's pattern; `is_plain_path`: false for a path that reads two ways (an escaped letter, digit or `-._~`, a `#`, a target not starting with `/`, an empty, `.` or `..` segment, or a path not beginning as its route does), which the sign-in guards refuse. Escapes such as `%20` and `%2F` stay allowed. |
137
144
  | `server/account_store` | `AccountStore`: users with the app's ordered roles and its own access rules, checked by `check_access`, the accounts file's users declared at the highest role, second factor with recovery codes, sessions and tokens, all in the app's SQLite database under `account_*` tables. `move_accounts(from, to)` moves them, as they are, out of an app's own database into their own once, and `holds_accounts` says whether a database keeps them. Request handlers call `authenticate_async`, `change_password_async`, `create_user_async` and `update_user_async`, which hash in `password_hashes` (`shared_password_hashes` unless set); the synchronous ones stay for scripts and tests. A user gets `secret_tries_allowed` (5) wrong second-factor or recovery codes, signing in or turning the second factor off, in `secret_try_window_seconds` (300), and as many wrong current passwords apart from those, before waiting: `authenticate` then answers `retry_after_seconds` and the others throw a 429 `AccountError` carrying it. `token_scopes` names the narrower tokens the app offers beside full and read-only ones, such as `{ add_items: { label: "Add items", hint, calls: ["add_item"] } }`: a token made with `create_token(owner, { name, read_only, scope })` reads as a read-only one does and may also make its scope's calls. A token lasts `days` when given; `longest_token_days` caps that and is how long a token lasts without it, and an ended token no longer signs in. Each token has a `kind`: `device` when the device sign-in made it (`create_token(..., { kind: "device" })`, always a full token), `program` for one made on the account page; a full, unscoped token made before kinds were kept counts as a device, so no device is cut off, and the token lists show a device chip so a program's token from then can be revoked. |
138
145
  | `server/account_sign_in` | `register_accounts`: the standard sign-in. A name and password (then the code when the user has a second factor), single sign-on or a trusted proxy opens a session kept in the database; "Keep me signed in" unticked ends it with the browser, ticked keeps it until revoked, both bounded by `session_seconds` and `remembered_seconds`. One name from one address gets `tries_allowed` (5) tries in `try_window` ("5 minutes"), and one address gets `address_tries_allowed` (20) failing or running sign-ins in `address_try_window_seconds` (300) whatever names it gives, a right password not counted, with each wrong bearer token on a guarded path counted in the same limit and a right one refused too once it is used up; either answers 429 `{ error }` with Retry-After, the same for a name that exists and one that does not, and a code refused by the store's own limit adds `code_needed` (see [Accounts](#accounts)). `second_factor_from` names the lowest role that must use a second factor: until such a user sets one up, their session only reads, signs out and sets up the second factor or password, and cannot make tokens or sign in devices; `/api/me` says so with `second_factor_needed`. A device signs in with `device` and gets a token of kind `device` instead; a request's `viewer.token_kind` says which kind of token it came with (a declared token's is `program`), and `is_user_or_device(viewer)` whether it is the user at the page or on one of their devices rather than a program. It also serves the account routes (password, second factor, sessions, tokens), the admin's users and tokens, and checks each app route, and any `guarded_paths` outside the API such as `/metrics`, against `needed(method, path, route)`, which gets the path as the router reads it and the matched route's pattern (such as `/api/builds/:id`, or null); `open_prefixes` leaves routes that check their own credentials, such as a push URL, open; a read-only token only reads, except on `read_only_paths` such as `/api/mcp` that keep it to reading themselves. Given `call_of` (such as `calls_under("/api/call")` for a call table) and `is_read_only`, a read-only token may also POST the calls that only read, and a scoped token its scope's calls, on the API as over MCP; `GET <api>/account/token_scopes` lists the scopes for the token form. Given `call_of` and `page_only` (from `api_spec`'s `page_only_calls`), every token, a device's included, is refused the calls only the user at the page may make, by their marks before the body is read and by the app's rule once it is; a session or the trusted proxy makes them. |
@@ -20,7 +20,7 @@ export interface ElectronLike {
20
20
  app: AppLike & {
21
21
  isPackaged: boolean;
22
22
  getAppPath(): string;
23
- getPath(name: "userData" | "downloads"): string;
23
+ getPath(name: "userData" | "downloads" | "documents" | "music" | "videos" | "pictures" | "home"): string;
24
24
  setPath(name: "userData", path: string): void;
25
25
  whenReady(): Promise<unknown>;
26
26
  on(event: "will-quit" | "window-all-closed", listener: () => void): unknown;
@@ -36,8 +36,13 @@ export interface ElectronLike {
36
36
  filePath?: string;
37
37
  }>;
38
38
  showOpenDialog?(options: {
39
- properties: "openDirectory"[];
39
+ properties: ("openDirectory" | "openFile")[];
40
40
  defaultPath?: string;
41
+ title?: string;
42
+ filters?: {
43
+ name: string;
44
+ extensions: string[];
45
+ }[];
41
46
  }): Promise<{
42
47
  canceled: boolean;
43
48
  filePaths: string[];
@@ -80,6 +85,7 @@ export interface SaveDialogOptionsLike {
80
85
  name: string;
81
86
  extensions: string[];
82
87
  }[];
88
+ title?: string;
83
89
  }
84
90
  export declare function save_dialog_options(file_name: string, downloads: string): SaveDialogOptionsLike;
85
91
  export interface TrayTools {
@@ -345,6 +345,31 @@ export function run_desktop(app, electron, options) {
345
345
  const picked = await dialog.showOpenDialog({ properties: ["openDirectory"], ...(current ? { defaultPath: current } : {}) });
346
346
  return picked.canceled ? null : (picked.filePaths[0] ?? null);
347
347
  },
348
+ pick_file: async (options) => {
349
+ if (!dialog.showOpenDialog)
350
+ throw new Error("This desktop app cannot show a file dialog.");
351
+ const picked = await dialog.showOpenDialog({
352
+ properties: ["openFile"],
353
+ ...(options?.title ? { title: options.title } : {}),
354
+ ...(options?.current ? { defaultPath: options.current } : {}),
355
+ ...(options?.kinds ? { filters: options.kinds } : {}),
356
+ });
357
+ return picked.canceled ? null : (picked.filePaths[0] ?? null);
358
+ },
359
+ pick_save_path: async (file_name, options) => {
360
+ if (!dialog.showSaveDialog)
361
+ throw new Error("This desktop app cannot show a Save dialog.");
362
+ const { canceled, filePath } = await dialog.showSaveDialog({
363
+ ...save_dialog_options(file_name, electron.app.getPath(options?.folder ?? "downloads")),
364
+ ...(options?.title ? { title: options.title } : {}),
365
+ ...(options?.kinds ? { filters: options.kinds } : {}),
366
+ });
367
+ return canceled || !filePath ? null : filePath;
368
+ },
369
+ show_in_folder: (path) => {
370
+ if (typeof path === "string" && path !== "")
371
+ electron.shell.showItemInFolder?.(path);
372
+ },
348
373
  read_plugin_file: read_plugin_web_file,
349
374
  show_data_path: async (which) => {
350
375
  if (which === "database")
@@ -31,13 +31,30 @@ export interface DesktopMethods {
31
31
  get_data_paths: () => DataPaths;
32
32
  show_data_path: (which: keyof DataPaths) => void;
33
33
  pick_folder: (current: string) => string | null;
34
+ pick_file: (options: PickFileOptions) => string | null;
35
+ pick_save_path: (file_name: string, options?: PickSaveOptions) => string | null;
36
+ show_in_folder: (path: string) => void;
34
37
  read_plugin_file: (path: string) => string;
35
38
  }
39
+ export interface FileKind {
40
+ name: string;
41
+ extensions: string[];
42
+ }
43
+ export interface PickFileOptions {
44
+ title?: string;
45
+ current?: string;
46
+ kinds?: FileKind[];
47
+ }
48
+ export interface PickSaveOptions {
49
+ title?: string;
50
+ folder?: "downloads" | "documents" | "music" | "videos" | "pictures" | "home";
51
+ kinds?: FileKind[];
52
+ }
36
53
  export interface DataPaths {
37
54
  database: string;
38
55
  backups: string;
39
56
  }
40
- export declare const desktop_method_names: readonly ["get_desktop_settings", "set_desktop_setting", "quit_completely", "get_idle_seconds", "save_text_file", "set_window_theme", "get_data_paths", "show_data_path", "pick_folder", "read_plugin_file"];
57
+ export declare const desktop_method_names: readonly ["get_desktop_settings", "set_desktop_setting", "quit_completely", "get_idle_seconds", "save_text_file", "set_window_theme", "get_data_paths", "show_data_path", "pick_folder", "pick_file", "pick_save_path", "show_in_folder", "read_plugin_file"];
41
58
  export declare function file_scheme_of(app_id: string): string;
42
59
  export declare const desktop_plugin_base = "x-app-plugins://local/";
43
60
  export interface DaemonMethods {
@@ -94,6 +111,7 @@ export interface PageApi<Methods extends Record<keyof Methods, (...args: never[]
94
111
  fetch?: typeof fetch;
95
112
  outside_fetch?: (input: string | URL | Request, init?: RequestInit) => Promise<Response>;
96
113
  file_src?: (name: string) => Promise<string>;
114
+ media_src?: (path: string) => Promise<string>;
97
115
  plugin_base?: string;
98
116
  read_plugin_file?: (path: string) => Promise<string>;
99
117
  on_change: (listener: (change: DataChange | null) => void) => () => void;
@@ -12,7 +12,7 @@ export function read_desktop_settings(saved, specs = {}) {
12
12
  const defaults = { ...desktop_setting_defaults, ...Object.fromEntries(Object.entries(specs).map(([key, spec]) => [key, spec.default])) };
13
13
  return Object.fromEntries(Object.entries(defaults).map(([key, fallback]) => [key, typeof settings[key] === "boolean" ? settings[key] : fallback]));
14
14
  }
15
- export const desktop_method_names = ["get_desktop_settings", "set_desktop_setting", "quit_completely", "get_idle_seconds", "save_text_file", "set_window_theme", "get_data_paths", "show_data_path", "pick_folder", "read_plugin_file"];
15
+ export const desktop_method_names = ["get_desktop_settings", "set_desktop_setting", "quit_completely", "get_idle_seconds", "save_text_file", "set_window_theme", "get_data_paths", "show_data_path", "pick_folder", "pick_file", "pick_save_path", "show_in_folder", "read_plugin_file"];
16
16
  // The desktop page's scheme for the app's synced files, as <scheme>://<name>, such as x-notes-file://<name>.
17
17
  export function file_scheme_of(app_id) {
18
18
  return `${app_id}-file`;
@@ -25,7 +25,9 @@ import { register_canonical_paths } from "../server/canonical_paths.js";
25
25
  import { read_channels } from "../server/notify/channels.js";
26
26
  import { register_security_headers } from "../server/security_headers.js";
27
27
  import { EventStream } from "../server/events.js";
28
+ import { regexp_matches } from "../filter_sql.js";
28
29
  import { register_mcp_route } from "../server/mcp.js";
30
+ import { create_media_links } from "../server/media_links.js";
29
31
  import { register_plugin_files } from "../server/plugin_files.js";
30
32
  import { register_synced_files } from "../server/synced_file_route.js";
31
33
  import { register_outside_route } from "./outside_route.js";
@@ -74,6 +76,8 @@ export function open_app_database(app, path, backups_folder) {
74
76
  // An upgrade is backed up first, since it cannot be undone any other way.
75
77
  function start(connection) {
76
78
  connection.exec("PRAGMA journal_mode = WAL");
79
+ // The REGEXP that filter_sql's regex test compiles to, which SQLite leaves to the host.
80
+ connection.function("REGEXP", { deterministic: true }, regexp_matches);
77
81
  if (existed && app.needs_upgrade(connection))
78
82
  connection.prepare("VACUUM INTO ?").run(join(backups_folder, app.backup_naming.name_for(new Date(), false)));
79
83
  app.open_store(connection);
@@ -254,6 +258,7 @@ export async function build_server(app, options) {
254
258
  ...(options.second_factor_from ? { second_factor_from: options.second_factor_from } : {}),
255
259
  // A read-only token may still list and read through MCP, which posts every request.
256
260
  read_only_paths: ["/api/mcp"],
261
+ media_links: options.routes?.media_prefixes?.length ? create_media_links({ prefixes: options.routes.media_prefixes }) : null,
257
262
  needed: (method, path, route) => {
258
263
  if ([...admin_paths, ...admin_tables].some((admin_path) => path.startsWith(admin_path)))
259
264
  return { role: options.accounts.top_role };
@@ -47,6 +47,7 @@ export interface AppRoutes {
47
47
  open_prefixes?: readonly string[];
48
48
  guarded_paths?: readonly string[];
49
49
  needed?: (method: string, path: string, route: string | null) => Need | null;
50
+ media_prefixes?: readonly string[];
50
51
  register: (server: FastifyInstance, services: () => HostServices) => void | Promise<void>;
51
52
  }
52
53
  export declare function declared_file_of(app: Pick<App, "id" | "env_prefix">, env: NodeJS.ProcessEnv): string;
@@ -1,14 +1,17 @@
1
1
  import "@x-tech-laboratories/halon/halon-tokens.css";
2
2
  import "@x-tech-laboratories/halon/halon.css";
3
3
  import type { App } from "../define.ts";
4
- import { type AppPages } from "./settings_page.tsx";
4
+ import type { AccountPrefsClient } from "../../web/react/account_prefs.ts";
5
+ import { type AppPage, type AppPages } from "./settings_page.tsx";
5
6
  export type { AppChrome, AppPage, AppPages, AppSubpage, PageSettingsProps } from "./settings_page.tsx";
6
7
  export type { PageDashboard } from "./page_dashboards.tsx";
8
+ export { PageDashboardsHere } from "./page_dashboards.tsx";
7
9
  export declare const default_sidebar_width: {
8
10
  default_width: number;
9
11
  min: number;
10
12
  max: number;
11
13
  };
14
+ export declare function with_dashboards(shown: AppPage, rest: string[], app_id: string, client: AccountPrefsClient | null): React.ReactNode;
12
15
  export declare function AppView({ pages }: {
13
16
  pages: AppPages;
14
17
  }): import("react").JSX.Element;
@@ -17,9 +17,11 @@ import { SyncButton } from "../../web/react/sync_settings.js";
17
17
  import { apply_theme_colors, local_theme_storage, pinned_theme_choice, read_server_theme, theme_choice } from "../../web/theme.js";
18
18
  import { phone_outside_fetch } from "../outside_fetch.js";
19
19
  import { desktop_api, is_android, is_desktop, web_api } from "./hosts.js";
20
+ import { apply_density, read_density } from "./density.js";
20
21
  import { calls, data_watch, page, set_page_api, set_page_reach, use_data, use_settings } from "./page.js";
21
- import { PageDashboardsView } from "./page_dashboards.js";
22
+ import { PageDashboardsProvider, PageDashboardsView } from "./page_dashboards.js";
22
23
  import { SettingsView } from "./settings_page.js";
24
+ export { PageDashboardsHere } from "./page_dashboards.js";
23
25
  // ── Pages ────────────────────────────────────────────────────────────────────
24
26
  // Relative, so a server behind a proxy under a folder keeps it.
25
27
  const accounts = create_accounts_client({ base: "api" });
@@ -100,14 +102,19 @@ function use_default_page(pages) {
100
102
  return null;
101
103
  return pages.pages.some((each) => each.id === chosen.data) ? String(chosen.data) : fallback;
102
104
  }
105
+ // A page's view with its dashboards above it, below it, where it puts them or in its place, on its main route.
103
106
  // A page's view with its dashboards above it, or in its place, on its main route.
104
- function with_dashboards(shown, rest, app_id, client) {
107
+ export function with_dashboards(shown, rest, app_id, client) {
105
108
  if (!shown.dashboard || rest.length > 0)
106
109
  return shown.view(rest);
107
- const dashboards = _jsx(PageDashboardsView, { app_id: app_id, page_id: shown.id, dashboard: shown.dashboard, client: client });
110
+ const dashboards = _jsx("div", { className: "page", children: _jsx(PageDashboardsView, { app_id: app_id, page_id: shown.id, dashboard: shown.dashboard, client: client }) });
111
+ if (shown.dashboard.place === "inline")
112
+ return _jsx(PageDashboardsProvider, { dashboards: _jsx(PageDashboardsView, { app_id: app_id, page_id: shown.id, dashboard: shown.dashboard, client: client }), children: shown.view(rest) });
108
113
  if (shown.dashboard.place === "only")
109
- return _jsx("div", { className: "page", children: dashboards });
110
- return _jsxs(_Fragment, { children: [_jsx("div", { className: "page", children: dashboards }), shown.view(rest)] });
114
+ return dashboards;
115
+ if (shown.dashboard.place === "below")
116
+ return _jsxs(_Fragment, { children: [shown.view(rest), dashboards] });
117
+ return _jsxs(_Fragment, { children: [dashboards, shown.view(rest)] });
111
118
  }
112
119
  function Pages({ pages, account }) {
113
120
  const default_page = use_default_page(pages);
@@ -233,6 +240,8 @@ async function phone_outside(app) {
233
240
  }
234
241
  // Starts the page on whichever host it runs: the desktop app, the phone app or a browser.
235
242
  export async function render_app(pages, root = document.getElementById("app")) {
243
+ // The rows' height this device keeps, set before anything draws.
244
+ apply_density(read_density(pages.app.id));
236
245
  const api = await host_api(pages.app, pages);
237
246
  // A browser takes the look its server pins before anything draws, the sign-in page included.
238
247
  if (api.host === "web") {
@@ -0,0 +1,6 @@
1
+ export type Density = "compact" | "normal" | "comfortable";
2
+ export declare function read_density(app_id: string, storage?: Pick<Storage, "getItem"> | null): Density;
3
+ export declare function apply_density(density: Density, root?: HTMLElement): void;
4
+ export declare function DensityRow({ app_id }: {
5
+ app_id: string;
6
+ }): import("react").JSX.Element;
@@ -0,0 +1,40 @@
1
+ import { jsx as _jsx } from "react/jsx-runtime";
2
+ // How tall the rows of lists and tables are: Halon's compact, normal or comfortable density, chosen under Settings →
3
+ // General → Appearance and kept on this device, since a phone and a large screen want different ones. The page sets it
4
+ // as the root's data-density before it draws.
5
+ // ── Imports ──────────────────────────────────────────────────────────────────
6
+ import { useState } from "react";
7
+ import { Segmented } from "../../web/react/controls.js";
8
+ import { SettingRow } from "../../web/react/layout.js";
9
+ const densities = ["compact", "normal", "comfortable"];
10
+ const density_key = (app_id) => `${app_id}-density`;
11
+ // The density this device keeps, normal when none is kept or the page's storage cannot be read.
12
+ export function read_density(app_id, storage = safe_storage()) {
13
+ const kept = storage?.getItem(density_key(app_id));
14
+ return densities.includes(kept) ? kept : "normal";
15
+ }
16
+ export function apply_density(density, root = document.documentElement) {
17
+ root.setAttribute("data-density", density);
18
+ }
19
+ function safe_storage() {
20
+ try {
21
+ return localStorage;
22
+ }
23
+ catch {
24
+ return null;
25
+ }
26
+ }
27
+ // ── Row ──────────────────────────────────────────────────────────────────────
28
+ export function DensityRow({ app_id }) {
29
+ const [density, set_density] = useState(() => read_density(app_id));
30
+ const choose = (next) => {
31
+ set_density(next);
32
+ apply_density(next);
33
+ safe_storage()?.setItem(density_key(app_id), next);
34
+ };
35
+ return (_jsx(SettingRow, { label: "Density", hint: "How tall the rows of lists and tables are on this device.", children: _jsx(Segmented, { label: "Density", choices: [
36
+ { value: "compact", label: "Compact" },
37
+ { value: "normal", label: "Normal" },
38
+ { value: "comfortable", label: "Comfortable" },
39
+ ], value: density, on_change: choose }) }));
40
+ }
@@ -108,6 +108,8 @@ export function web_api(app) {
108
108
  device: app.sync === false ? null : bridges.device.web_rpc((method, args) => post_call(device_path, method, args)),
109
109
  backups: bridges.backups.web_rpc((method, args) => post_call(backups_path, method, args)),
110
110
  ...(app.synced_files ? { file_src: async (name) => `api/files/${encodeURIComponent(name)}` } : {}),
111
+ // The browser's own sign-in goes with the element's request, so the path plays as it is, from the page's base.
112
+ media_src: async (path) => path.replace(/^\//, ""),
111
113
  plugin_base: "api/plugins/",
112
114
  // The server's own routes, with the browser's sign-in.
113
115
  fetch: (input, init) => fetch(input, init),
@@ -1,3 +1,4 @@
1
+ import { type ReactNode } from "react";
1
2
  import { type Dashboard } from "../../dashboard.ts";
2
3
  import type { AccountPrefsClient } from "../../web/react/account_prefs.ts";
3
4
  import { type DataSource, type ReadyCardKind } from "../../web/react/dashboard.tsx";
@@ -5,10 +6,15 @@ export interface PageDashboard {
5
6
  data_sources: DataSource[];
6
7
  ready_cards?: ReadyCardKind[];
7
8
  initial?: () => Dashboard;
8
- place?: "above" | "only";
9
+ place?: "above" | "below" | "inline" | "only";
9
10
  refresh_in_milliseconds?: number;
10
11
  }
11
12
  export declare const page_dashboards_pref = "dashboards";
13
+ export declare function PageDashboardsProvider({ dashboards, children }: {
14
+ dashboards: ReactNode;
15
+ children: ReactNode;
16
+ }): import("react").JSX.Element;
17
+ export declare function PageDashboardsHere(): import("react").JSX.Element;
12
18
  interface PageDashboardsProps {
13
19
  app_id: string;
14
20
  page_id: string;
@@ -1,8 +1,9 @@
1
- import { jsx as _jsx } from "react/jsx-runtime";
1
+ import { Fragment as _Fragment, jsx as _jsx } from "react/jsx-runtime";
2
2
  // A page's own dashboards, as the base app draws them above the page: the app declares the data its cards may chart,
3
3
  // its ready-made cards and the dashboard each person starts with, and every person arranges their own, kept with their
4
4
  // account or, with no one signed in, on this device. The tabs' menu adds, renames, duplicates, resets and deletes them.
5
5
  // ── Imports ──────────────────────────────────────────────────────────────────
6
+ import { createContext, useContext } from "react";
6
7
  import { clean_page_dashboards } from "../../dashboard.js";
7
8
  import { use_account_pref } from "../../web/react/account_prefs.js";
8
9
  import { Dashboards } from "../../web/react/dashboard.js";
@@ -12,6 +13,16 @@ import { toast } from "../../web/react/toasts.js";
12
13
  import { data_watch } from "./page.js";
13
14
  // The account preference every page's dashboards are kept under, which the base app's server allows.
14
15
  export const page_dashboards_pref = "dashboards";
16
+ // ── Placing ──────────────────────────────────────────────────────────────────
17
+ const PlacedDashboards = createContext(null);
18
+ // Hands a page's dashboards to the `PageDashboardsHere` its view draws, for a page whose dashboards go "inline".
19
+ export function PageDashboardsProvider({ dashboards, children }) {
20
+ return _jsx(PlacedDashboards.Provider, { value: dashboards, children: children });
21
+ }
22
+ // Where a page that places its dashboards "inline" draws them in its view; nothing on any other page or route.
23
+ export function PageDashboardsHere() {
24
+ return _jsx(_Fragment, { children: useContext(PlacedDashboards) });
25
+ }
15
26
  // ── Keeping ──────────────────────────────────────────────────────────────────
16
27
  const no_dashboards = {};
17
28
  const is_page_dashboards = (value) => typeof value === "object" && value !== null && JSON.stringify(clean_page_dashboards(value)) === JSON.stringify(value);
@@ -101,6 +101,14 @@ export async function portal_api(app, options) {
101
101
  return {
102
102
  host: "android",
103
103
  calls: bridges.calls.web_rpc(rpc("call")),
104
+ // The element cannot send this phone's token, so it plays a link the host signs for it.
105
+ media_src: async (path) => {
106
+ const daemon = link.daemon();
107
+ if (!daemon)
108
+ throw new Error("Choose a server under Settings → Connections first.");
109
+ const { link: signed } = (await call_remote(link, "/api/media_link", [path]));
110
+ return `${daemon.address}${signed}`;
111
+ },
104
112
  // The routes of the host this phone works on, with its token.
105
113
  fetch: server_fetch(link.daemon, options.fetch ?? ((input, init) => fetch(input, init))),
106
114
  device: null,
@@ -12,6 +12,7 @@ import { RemoteAccessSettings } from "../../web/react/remote_access_settings.js"
12
12
  import { PeerListeningSettings, SyncSettings } from "../../web/react/sync_settings.js";
13
13
  import { read_picked, save_text } from "../../web/files.js";
14
14
  import { attempt, attempt_value, toast } from "../../web/react/toasts.js";
15
+ import { DensityRow } from "./density.js";
15
16
  import { calls, data_watch, page, use_settings } from "./page.js";
16
17
  // ── Sections ─────────────────────────────────────────────────────────────────
17
18
  // A phone's backups go in a folder picked once in its storage, where file managers and sync apps reach them.
@@ -126,7 +127,10 @@ export function SettingsView({ pages, is_admin = true, viewer = null }) {
126
127
  const set_setting = async (key, value) => void (await calls().set_setting(key, value));
127
128
  return (_jsxs(_Fragment, { children: [_jsx(PageHeading, { title: "Settings" }), _jsx(Loaded, { resource: settings, children: (values) => {
128
129
  const props = { settings: values, set_setting };
129
- const general = pages.general_settings?.(props) ?? [];
130
+ const general = [
131
+ { id: "appearance", heading: "Appearance", content: _jsx(DensityRow, { app_id: pages.app.id }) },
132
+ ...(pages.general_settings?.(props) ?? []),
133
+ ];
130
134
  return (_jsx(SettingsPage, { categories: [
131
135
  ...(general.length > 0 ? [{ heading: "General", sections: general }] : []),
132
136
  ...(pages.settings_categories?.(props) ?? []).filter((category) => category.sections.length > 0),
@@ -0,0 +1 @@
1
+ export declare function derived_id(kind: string, ...parts: readonly (string | number)[]): string;
@@ -0,0 +1,35 @@
1
+ // Ids every device works out alike from what a row is, for rows two devices may make at once, such as a genre a scan
2
+ // meets on a laptop and on the server before they sync: both make the same id, so sync merges the two into one row
3
+ // instead of keeping two that clash on the row's natural key. An id is the first 128 bits of the SHA-512 of the kind and
4
+ // the parts, written as a UUID (version 8, the form for ids made some other way), so it sits beside random ids made by
5
+ // crypto.randomUUID() in the same column. No `node:` or DOM imports.
6
+ // ── Imports ──────────────────────────────────────────────────────────────────
7
+ import nacl from "tweetnacl";
8
+ // ── Ids ──────────────────────────────────────────────────────────────────────
9
+ // Text as UTF-8 bytes, by hand, since a shared module sees neither TextEncoder nor Buffer.
10
+ function utf8(text) {
11
+ const bytes = [];
12
+ for (const character of text) {
13
+ const code = character.codePointAt(0);
14
+ if (code < 0x80)
15
+ bytes.push(code);
16
+ else if (code < 0x800)
17
+ bytes.push(0xc0 | (code >> 6), 0x80 | (code & 0x3f));
18
+ else if (code < 0x10000)
19
+ bytes.push(0xe0 | (code >> 12), 0x80 | ((code >> 6) & 0x3f), 0x80 | (code & 0x3f));
20
+ else
21
+ bytes.push(0xf0 | (code >> 18), 0x80 | ((code >> 12) & 0x3f), 0x80 | ((code >> 6) & 0x3f), 0x80 | (code & 0x3f));
22
+ }
23
+ return Uint8Array.from(bytes);
24
+ }
25
+ // The id of a row of a kind, such as "genre", from its natural key's parts, such as the field and the value; the same
26
+ // parts always give the same id, and different kinds never share one.
27
+ export function derived_id(kind, ...parts) {
28
+ // Each part's length goes in front of it, so ("ab", "c") and ("a", "bc") differ.
29
+ const text = [kind, ...parts.map(String)].map((part) => `${part.length}:${part}`).join("");
30
+ const bytes = nacl.hash(utf8(text)).slice(0, 16);
31
+ bytes[6] = (bytes[6] & 0x0f) | 0x80;
32
+ bytes[8] = (bytes[8] & 0x3f) | 0x80;
33
+ const hex = Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0")).join("");
34
+ return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
35
+ }