@x-tech-laboratories/x-app 0.114.0 → 0.115.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
@@ -9,15 +9,17 @@ an app moves over by changing the package name in its imports and its `x-libs-*`
9
9
 
10
10
  | Import | What it holds |
11
11
  | ---------------------------------------- | ----------------------------------------------------------------------------- |
12
- | `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. |
13
- | `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. `build_server`, `start_daemon`, `open_app_database` (with `on_restore` hooks) and `register_app_calls` for tests and apps that add their own. |
12
+ | `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. |
13
+ | `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. |
14
14
  | `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. |
15
15
  | `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. |
16
- | `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, 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. 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. |
16
+ | `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, 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`) 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. |
17
17
  | `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`. |
18
- | `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, Your account, Settings (the app's general sections, each page's own, Connections, Desktop app, Sync and Backups) 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` and a `side_pane`. `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), 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. |
18
+ | `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`. |
19
+ | `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, Your account, Settings (the app's general sections, each page's own, Connections, Desktop app, Sync and Backups) 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), 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. |
19
20
  | `config/vite`, `config/electron_vite`, `config/vitest`, `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. |
20
21
  | `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`. |
22
+ | `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. |
21
23
  | `durations` | `parse_duration` for settings such as `"2h30m"`, `format_duration` in months down to seconds and "less than a second" below one, `format_age`, and `format_clock` for a playing time such as `"3:07"`, with `{ hours: "always" }` writing `"0:03:07"` so a column of times lines up and `empty` for no time. |
22
24
  | `log` | Loggers by scope and level from a setting such as `"warn,play:debug"`; a malformed setting falls back instead of silencing logging, and a setting read through a function applies to loggers made before it arrived; a dotted scope such as `app.core.db` without its own level takes its nearest parent's. |
23
25
  | `cron` | `CronSchedule.parse`: five-field cron lines read in local time, with `@daily`-style aliases, month and weekday names, steps, ranges and lists, 7 as Sunday, a restricted day of month and weekday matching either as cron does, and a line that never matches a real date refused; `next_after` gives the first run strictly after a moment. On it, the schedules a user picks for recurring work (`RunSchedule`): every so many minutes, hours or days after the last run, or at a time on chosen weekdays; `checked_schedule(given, { min_minutes })` with a plain reason for a bad one, `describe_schedule` ("at 07:30 on Monday and Friday", "every 2 hours"), `schedule_cron` for an "at" schedule, and `is_due` and `next_due` given the last run, due once however many times it was missed. |
@@ -40,7 +42,7 @@ an app moves over by changing the package name in its imports and its `x-libs-*`
40
42
  | `grouping` | `group_items`: items sorted into groups by a key each has, such as a status, a year or the collections they are in, an item with several keys in each of their groups, the app's `order` of keys first and the rest by name, numbers by value, `descending` when asked, each group keeping the items' order and those with no key last; for `GroupSections`, `GroupedMediaGrid` or a table under headings. |
41
43
  | `money` | `format_money` in a currency and locale to a set number of places, falling back to the number and code on a currency Intl refuses; `round_money` rounding halves away from zero, `money_step`, `sum_money`, `is_currency_code` and `currency_options` naming each currency for a select. |
42
44
  | `i18n` | Words in the reader's language: `create_translator` looks each key up in catalogs in turn, so a missing translation falls back to the next, with `{name}` placeholders filled; `merge_messages`; `best_locale`, the available locale that best fits the reader's preferred ones, an exact tag before the same language; `text_direction` for the `dir` attribute. |
43
- | `sql` | `SqlDatabase`, the part of a synchronous SQLite connection the apps use, met by node:sqlite and by `web/sqlite_wasm`; `in_transaction`, and `migrate`, each step once in its own transaction, through `user_version` or, with an `owner` such as a feature or plugin, its own row in `schema_versions`. |
45
+ | `sql` | `SqlDatabase`, the part of a synchronous SQLite connection the apps use, met by node:sqlite and by `web/sqlite_wasm`; `in_transaction`, and `migrate`, each step (a script, its statements, or code given the database) once in its own transaction, through `user_version` or, with an `owner` such as a feature or plugin, its own row in `schema_versions`. |
44
46
  | `settings` | An app's settings feature: one synced `settings (key, value)` table of JSON values, the same table and first step (`settings_migration` under the owner `"settings"`) every app already ran. Each feature declares a `SettingSpec` per key (`default`, `user_only`, `local` for this device alone, `secret` for another service's key, or its own `hide` and `keep`), `settings_of` giving every key of a defaults table the same spec; `create_settings_store(tables, { app })` merges them, refusing a key declared twice, and gives the migration, the synced table entry with its `local_keys`, `defaults`, the `user_only` set, `is_user_only_call` for `page_only_calls` (a user-only write, an import holding one, an export with secrets), `is_device_only` for `register_sync_routes`, `value_of`, and `get_settings`, `set_setting`, `export_settings` and `import_settings` with their api specs. Secrets read as `hidden_secret` and are kept when it comes back; the settings file is the standard's `{ app, kind: "settings", version, exported_at, settings }`, an import ignoring unknown keys and those of one device. `read_setting`, `write_setting` and `read_stored_settings` reach rows directly. No `node:` or DOM imports. |
45
47
  | `caller`, `node_caller_scope` | Who is making the call in hand: `as_caller("page" \| "program" \| "engine", work)` around a call, `current_caller()` read by a store, and `caller_of(request)` (a token is a program). With a `CallerScope` in use (`use_caller_scope`), the caller holds across the call's awaits; the base app's server and daemon use `node_caller_scope()`, Node's `AsyncLocalStorage`, and without one, as on a phone, it holds for the call's synchronous part. |
46
48
  | `api_spec` | An app's calls described once for other programs: `ApiSpec` gives each method its words and a JSON Schema per argument, so a method without one fails to compile; `input_schema` takes the arguments as one object, `positional_args` puts named arguments back in the method's order from a spec or any `NamedParams`, `openapi_document` writes an OpenAPI 3.1 document with one POST per call, and `route_openapi_document` one for REST routes such as `server/mcp`'s `route_tools` serves, each under its own path and verb with its path, query and body arguments; `check_known_ids` refuses a call naming an id that does not exist, such as "no such track a1", before it acts, `unknown_ids` lists them, and `keep_known_ids` cuts a remembered list, such as picked columns, down to the ids that still exist. A spec marked `page_only: true` is a call only the user may make at the app's own page (a signed-in browser, or a desktop window through its daemon's socket), such as approving what an assistant proposed: `page_only_calls(api, { rule?, refusal? })` gives the `PageOnlyCalls` the other modules take (`is_page_only(method)` for the marks, `is_page_only_call(method, args)` adding the app's `rule(method, args)` such as a write to some settings, `is_page_only_request(method, body)` for arguments as a list or by name, unchecked so a call with wrong names is left to refuse them itself, and the `refusal` text, `default_page_only_refusal` unless set), and both OpenAPI documents mark such a call with `x-page-only: true` and a 403. |
@@ -147,7 +149,7 @@ an app moves over by changing the package name in its imports and its `x-libs-*`
147
149
  | `web/prefs`, `web/react/prefs` | Remembered view settings that read as their default when stored corrupt, stale or of the wrong shape; `use_pref` keeps one as component state. |
148
150
  | `web/selection`, `web/virtual`, `web/drag` | Picking rows with plain, Ctrl and Shift clicks from a fixed anchor, or as lists of ids with the anchor kept by id, the row an arrow or page key moves to; which rows of a long list a viewport needs; a badge such as "3 tasks" as the drag image. |
149
151
  | `web/react/shell` | `Shell`: top bar with the brand and its icon and the app's `tools`; section links, or, once a section has `children`, a `SectionTree` of section rows folding open onto their items on `Tree`, the folded ones kept in the `sections_pref` pref and a folded section lit up in place of its hidden `active_item`; or the app's `views` as rows with their icons (from `web/react/icons`) in the sidebar's navigation, the one `active` names raised and marked as the current page, above the app's own sidebar in a `.sidebar-content` box, the sidebar then an aside so the views are its only navigation landmark, or that sidebar alone, scrolling above a foot pinned to the sidebar's bottom that holds the app's `sidebar_foot` rows, then the theme, the signed-in `user` linked to `user_href` with Sign out, and `settings` last; resizable; a `side_pane` docked on the right beside main ([A pane on the right](#a-pane-on-the-right)), its open state kept by `use_side_pane` in a pref; `brand_logo` for a full logo that already holds the name, drawn alone in its place; a `status_bar` at the foot of the window, toasts, dialogs and menus, with or without logins (no account row without a `user`, `logged_out` hiding the sidebar and tools), its phone menu held by the Shell or the app, and for app-like pages a `contained` window where only main scrolls and the brand heading the sidebar; `labels` for its own words in another language; `ThemeRow`, the theme as a sidebar row, `ThemeButton`, as an icon button, both drawing the system theme on a server and until the page is picked up, and `use_route`. |
150
- | `web/react/layout`, `badges`, `states` | `PageHeading` with a subtitle, icon, banner, actions and a `level` for inside dialogs and panels; panels (`Section`, with a `level` for one inside a dialog or under another heading), `GroupSections`, a panel per group from `group_items` headed by its name and count, facts, tiles, cards, tabs, `Crumbs` with chevrons between steps that link, run a function or mark where the reader is, `PathText` for a path shown with the same chevrons, steppers, `FormRow` for a form's labelled fields, `FormGroup` folding part of a form under a summary line such as "More options", `SettingsPage` with an `Outline` beside its sections, settings rows, `RowActions` and `moved` for ordered lists, `SelectionBar` for picked rows, their count with its thousands separated; badges, `StateBadge` naming each state's text and tone and `ToneBadge` showing the state's own name in its tone, chips in an item's own colour, dashed or removable, `ColorDot` and `StatusPill`, a state dot with text and an action; `use_resource` with its `status` (idle until `enabled`, loading, loaded, failed), a `watch` that reloads it quietly, and its loading states, `Loaded` going by the status so a null result shows its `empty` slot or the children. |
152
+ | `web/react/layout`, `badges`, `states` | `PageHeading` with a subtitle, icon, banner, actions and a `level` for inside dialogs and panels; panels (`Section`, with a `level` for one inside a dialog or under another heading), `GroupSections`, a panel per group from `group_items` headed by its name and count, facts, tiles, cards, tabs, `Crumbs` with chevrons between steps that link, run a function or mark where the reader is, `PathText` for a path shown with the same chevrons, steppers, `FormRow` for a form's labelled fields, `FormGroup` folding part of a form under a summary line such as "More options", `SettingsPage` with an `Outline` beside its sections, settings rows, `RowActions` and `moved` for ordered lists, `SelectionBar` for picked rows, their count with its thousands separated; badges, `StateBadge` naming each state's text and tone and `ToneBadge` showing the state's own name in its tone, chips in an item's own colour, dashed or removable, `ColorDot` and `StatusPill`, a state dot with text and an action; `use_resource` with its `status` (idle until `enabled`, loading, loaded, failed), a `watch` that reloads it quietly (bumps during a load fold into one load after it), and its loading states, `Loaded` going by the status so a null result shows its `empty` slot or the children. |
151
153
  | `web/react/sync_settings`, `backup_settings` | The settings rows every device shows: `SyncSettings`, the sync status, this device with its id and where others reach it, a pairing code to show when they can, each paired device with how it was last reached and Remove after a confirm, and a field to enter another device's code; `SyncButton`, the same status as a sidebar row with the changes waiting, syncing on a click or opening the settings when sync failed or no device is paired, and shown even then; `BackupSettings`, back up now, the daily schedule, and each backup to restore or delete after a confirm. |
152
154
  | `web/react/connections` | `ConnectionSettings`: the Connections section of Settings, every daemon the app can talk to with the one in use marked Connected, Connect to switch, Rename and Remove (after a confirm) for daemons on other hosts, and a form to add one by address, name and password, asking for the code when the daemon does and offering to trust a certificate the device refuses given `certificates`. |
153
155
  | `web/react/certificates` | `CertificateDialog`: what is wrong with a server's certificate in plain words, the certificate itself with its fingerprint, and Trust or Don't connect; `offer_certificate_trust` and `ask_to_trust_certificate` open it from anywhere, `with_certificate_prompt` wraps a fetch to ask and retry once, `SyncCertificatePrompt` asks whenever syncing with a paired device's https address fails over its certificate, and `TrustedCertificates` lists them to forget. |
@@ -238,7 +240,9 @@ The rest of an app's files are short calls into X-App too:
238
240
  taking the app's package set and its `nix/app.nix` (name, display name, variables' prefix, port, database file and
239
241
  words); the app's `nix/flake.nix` takes `github:x-tech-laboratories/X-App` as an input and calls them.
240
242
  An app with git dependencies names each lock entry's https URL in `git_dependencies`, which the packages fetch and
241
- copy in, and `link_scheme`, such as `"codex"`, makes the desktop entry open its links; the desktop wrapper sets
243
+ copy in, and `link_scheme`, such as `"codex"`, makes the desktop entry open its links; `desktop_path`, such as
244
+ `pkgs: [ pkgs.libnotify ]`, puts programs the desktop app runs on its PATH, and `state_name` keeps an older service's
245
+ data folder `/var/lib/<state_name>`; the desktop wrapper sets
242
246
  `<PREFIX>_LAUNCHER` so the login entry runs the installed command.
243
247
  - **Android**: `npm run build:android` builds the phone's page and runs `x-app-android`, which makes or updates the
244
248
  Capacitor project in `android/`, so the app keeps only `capacitor.config.json` and leaves `android/` out of git.
@@ -17,7 +17,7 @@ import { create_sync_peer, sync_device_methods } from "../sync_peer.js";
17
17
  import { keep_listening_for_peers } from "../sync_peer_listening.js";
18
18
  import { declared_file_of, no_services, side_databases } from "./services.js";
19
19
  import { read_desktop_settings } from "./protocol.js";
20
- import { call_body_limit, open_app_database, register_app_calls } from "./server.js";
20
+ import { call_body_limit, open_app_database, register_app_calls, watch_outside_changes } from "./server.js";
21
21
  // ── Daemon ───────────────────────────────────────────────────────────────────
22
22
  // Answers on the socket and starts sync; null when another daemon on the same database already answers.
23
23
  export async function start_daemon(app, options) {
@@ -64,12 +64,12 @@ export async function start_daemon(app, options) {
64
64
  name: app.id,
65
65
  version: app.version,
66
66
  instructions: app.instructions,
67
- api: app.api_spec,
67
+ api: app.mcp.api,
68
68
  is_read_only: app.is_read_only,
69
- page_only: app.page_only,
69
+ page_only: app.mcp.page_only,
70
70
  settings_file: join(profile, "mcp.json"),
71
71
  default_port: app.local_mcp.default_port,
72
- call: (method, args) => app.bridges.calls.dispatch(app.bind_methods(opened.database, () => changes.announce_change(), "program"), method, args),
72
+ call: (method, args) => app.mcp.call(opened.database, () => changes.announce_change(), method, args),
73
73
  })
74
74
  : null;
75
75
  // ── Calls ──────────────────────────────────────────────────────────
@@ -98,6 +98,7 @@ export async function start_daemon(app, options) {
98
98
  function shut_down() {
99
99
  stopping ??= (async () => {
100
100
  clearInterval(unused_timer);
101
+ stop_watching();
101
102
  await services.stop();
102
103
  sync.stop();
103
104
  await local_mcp?.stop();
@@ -123,6 +124,7 @@ export async function start_daemon(app, options) {
123
124
  await listening.start();
124
125
  sync.start();
125
126
  await local_mcp?.start();
127
+ const stop_watching = watch_outside_changes(opened.database, () => changes.announce_change());
126
128
  if (options.services) {
127
129
  services = await options.services({
128
130
  kind: "desktop",
@@ -14,7 +14,7 @@ import { type SyncedTable } from "../sync_engine.ts";
14
14
  import { type PeerListeningMethods, type SyncDeviceMethods, type SyncStatus } from "../sync_protocol.ts";
15
15
  import { type DesktopMethods, type DesktopSettingSpec } from "./protocol.ts";
16
16
  export type StoreMethod = (database: SqlDatabase, ...args: never[]) => unknown;
17
- export type KeptHistory = Pick<History<unknown>, "synced_table" | "install" | "forget_touched" | "record" | "prune">;
17
+ export type KeptHistory = Pick<History<unknown>, "synced_table" | "install" | "forget_touched" | "record" | "prune"> & Partial<Pick<History<unknown>, "drop_triggers">>;
18
18
  export interface Feature<Methods extends Record<string, StoreMethod> = Record<string, StoreMethod>> {
19
19
  id: string;
20
20
  migrations: readonly MigrationStep[];
@@ -59,6 +59,7 @@ export interface AppOptions<Features extends readonly Feature[]> {
59
59
  run: (database: SqlDatabase) => void;
60
60
  };
61
61
  page_only_refusal?: string;
62
+ tools?: Feature;
62
63
  token_prefix?: string;
63
64
  history_days?: number;
64
65
  desktop_settings?: Readonly<Record<string, DesktopSettingSpec>>;
@@ -118,6 +119,7 @@ export declare function define_app<const Features extends readonly Feature[]>(op
118
119
  run: (database: SqlDatabase) => void;
119
120
  };
120
121
  page_only_refusal?: string;
122
+ tools?: Feature;
121
123
  token_prefix?: string;
122
124
  history_days?: number;
123
125
  desktop_settings?: Readonly<Record<string, DesktopSettingSpec>>;
@@ -154,6 +156,11 @@ export declare function define_app<const Features extends readonly Feature[]>(op
154
156
  is_read_only: typeof is_read_only;
155
157
  page_only: PageOnlyCalls;
156
158
  bind_methods: (database: () => SqlDatabase, on_change: () => void, caller?: Caller) => Bound<SettingsMethods & UnionToIntersection<Features[number]["methods"]>>;
159
+ mcp: {
160
+ api: ApiSpec<Record<string, StoreMethod>>;
161
+ page_only: PageOnlyCalls;
162
+ call: (database: () => SqlDatabase, on_change: () => void, method: string, args: unknown[]) => unknown;
163
+ };
157
164
  backup_naming: BackupNaming;
158
165
  read_backup_schedule: (database: SqlDatabase) => BackupSchedule;
159
166
  adopt_backup_schedule: (database: SqlDatabase, saved: unknown) => void;
@@ -75,6 +75,10 @@ export function define_app(options) {
75
75
  database.exec("PRAGMA foreign_keys = ON");
76
76
  if (options.upgrade_layout?.needed(database))
77
77
  options.upgrade_layout.run(database);
78
+ // Sync's and history's triggers name columns, so they come off while a step reshapes a table; install puts them back.
79
+ sync_engine.drop_triggers(database);
80
+ for (const history of histories)
81
+ history.drop_triggers?.(database);
78
82
  // Each feature keeps its own schema version, so features grow apart without renumbering each other's steps.
79
83
  for (const feature of features)
80
84
  migrate(database, feature.migrations, { owner: feature.id });
@@ -119,8 +123,13 @@ export function define_app(options) {
119
123
  // The calls run on the database given as the caller given, telling on_change after each write so the other pages
120
124
  // and devices hear of it.
121
125
  function bind_methods(database, on_change, caller = "page") {
122
- const bound = method_names.map((name) => {
123
- const method = all_methods[name];
126
+ return bind_table(all_methods, database, on_change, caller);
127
+ }
128
+ // Any table of calls run on the database as the caller, each write followed by the features' catch-up, its versions
129
+ // recorded and on_change told.
130
+ function bind_table(table, database, on_change, caller) {
131
+ const bound = Object.keys(table).map((name) => {
132
+ const method = table[name];
124
133
  const call = (...args) => {
125
134
  const result = as_caller(caller, () => method(database(), ...args));
126
135
  if (is_read_only(name))
@@ -140,6 +149,19 @@ export function define_app(options) {
140
149
  });
141
150
  return Object.fromEntries(bound);
142
151
  }
152
+ // What MCP offers: the app's own tools when it has them, otherwise the page's calls.
153
+ const tools = options.tools;
154
+ const mcp = {
155
+ api: (tools ? tools.api : api_spec),
156
+ page_only: tools ? page_only_calls(tools.api, options.page_only_refusal ? { refusal: options.page_only_refusal } : {}) : page_only,
157
+ // Runs one tool by name as the program caller, refusing a name it does not offer.
158
+ call: (database, on_change, method, args) => {
159
+ const table = (tools ? tools.methods : all_methods);
160
+ if (!Object.hasOwn(table, method))
161
+ throw new Error(`${options.name} has no tool ${method}`);
162
+ return bind_table({ [method]: table[method] }, database, on_change, "program")[method](...args);
163
+ },
164
+ };
143
165
  // ── Backups ──────────────────────────────────────────────────────────
144
166
  // Names such as budget-2026-06-10T09-30-00Z-auto.db.
145
167
  const naming = backup_naming(options.backup_prefix, ".db");
@@ -204,6 +226,7 @@ export function define_app(options) {
204
226
  is_read_only,
205
227
  page_only,
206
228
  bind_methods,
229
+ mcp,
207
230
  backup_naming: naming,
208
231
  read_backup_schedule,
209
232
  adopt_backup_schedule,
@@ -18,7 +18,7 @@ export interface ElectronLike {
18
18
  app: AppLike & {
19
19
  isPackaged: boolean;
20
20
  getAppPath(): string;
21
- getPath(name: "userData"): string;
21
+ getPath(name: "userData" | "downloads"): string;
22
22
  setPath(name: "userData", path: string): void;
23
23
  whenReady(): Promise<unknown>;
24
24
  on(event: "will-quit" | "window-all-closed", listener: () => void): unknown;
@@ -29,6 +29,13 @@ export interface ElectronLike {
29
29
  };
30
30
  dialog: {
31
31
  showErrorBox(title: string, content: string): void;
32
+ showSaveDialog?(options: SaveDialogOptionsLike): Promise<{
33
+ canceled: boolean;
34
+ filePath?: string;
35
+ }>;
36
+ };
37
+ powerMonitor?: {
38
+ getSystemIdleTime(): number;
32
39
  };
33
40
  ipcMain: IpcMainLike;
34
41
  nativeTheme: NativeThemeLike;
@@ -52,6 +59,14 @@ export interface ElectronLike {
52
59
  };
53
60
  };
54
61
  }
62
+ export interface SaveDialogOptionsLike {
63
+ defaultPath: string;
64
+ filters: {
65
+ name: string;
66
+ extensions: string[];
67
+ }[];
68
+ }
69
+ export declare function save_dialog_options(file_name: string, downloads: string): SaveDialogOptionsLike;
55
70
  export interface TrayTools {
56
71
  call: (method: string, args?: unknown[]) => Promise<unknown>;
57
72
  open: (route: string) => void;
@@ -3,8 +3,9 @@
3
3
  // module builds without it.
4
4
  // ── Imports ──────────────────────────────────────────────────────────────────
5
5
  import { unwatchFile, watchFile } from "node:fs";
6
- import { hostname } from "node:os";
7
- import { join, resolve } from "node:path";
6
+ import { homedir, hostname } from "node:os";
7
+ import { writeFile } from "node:fs/promises";
8
+ import { extname, join, resolve } from "node:path";
8
9
  import { launch_command, set_autostart } from "../autostart.js";
9
10
  import { backup_method_names } from "../backups.js";
10
11
  import { certificate_method_names } from "../certificate_protocol.js";
@@ -20,6 +21,11 @@ import { create_window, is_app_page } from "../electron/window.js";
20
21
  import { call_daemon, daemon_log_path, daemon_socket_path, start_daemon } from "../local_daemon.js";
21
22
  import { peer_listening_method_names, sync_device_method_names } from "../sync_protocol.js";
22
23
  import { route_of_link } from "./links.js";
24
+ // The Save dialog's options for a file name: Downloads with that name, offering files of its kind.
25
+ export function save_dialog_options(file_name, downloads) {
26
+ const extension = extname(file_name).slice(1);
27
+ return { defaultPath: join(downloads, file_name), filters: extension ? [{ name: extension.toUpperCase(), extensions: [extension] }] : [] };
28
+ }
23
29
  // ── Desktop ──────────────────────────────────────────────────────────────────
24
30
  export function run_desktop(app, electron, options) {
25
31
  const { BrowserWindow, dialog, ipcMain } = electron;
@@ -35,6 +41,9 @@ export function run_desktop(app, electron, options) {
35
41
  const is_own_profile = own_profile === undefined;
36
42
  if (!is_own_profile)
37
43
  electron.app.setPath("userData", resolve(options.cwd ?? process.cwd(), own_profile));
44
+ // Flatpak moves the config folder into its sandbox; the Flatpak may write ~/.config/<id>, so it keeps the profile the other builds use.
45
+ else if (env.FLATPAK_ID)
46
+ electron.app.setPath("userData", join(homedir(), ".config", app.id));
38
47
  const profile = electron.app.getPath("userData");
39
48
  const database_path = join(profile, app.database_file);
40
49
  // Any other profile gets a daemon, socket and log of its own, so a dev or test run never reaches the user's daemon.
@@ -43,10 +52,22 @@ export function run_desktop(app, electron, options) {
43
52
  const icon_path = join(options.main_dir, "../../resources/icon.png");
44
53
  // The command that starts this app again, which the login entry runs.
45
54
  const own_command = (args) => launch_command({ launcher: env[`${prefix}_LAUNCHER`] ?? null, is_packaged: electron.app.isPackaged, app_path: electron.app.getAppPath(), args });
46
- function ensure_daemon() {
55
+ // Opening the app replaces a daemon another build left running, such as one from before an upgrade. Only opening does:
56
+ // two windows of different builds that both replaced on reconnecting would stop each other's daemon in turn.
57
+ function ensure_daemon(replace_other_build = false) {
47
58
  // Only the user's own daemon reads what this computer's configuration declares, unless a run names a file itself.
48
59
  const declared = is_own_profile ? {} : { [`${prefix}_DECLARED_FILE`]: env[`${prefix}_DECLARED_FILE`] ?? "" };
49
- return start({ socket_path, script: join(options.main_dir, "daemon.js"), env: { [`${prefix}_DB`]: database_path, [`${prefix}_SOCKET`]: socket_path, [`${prefix}_ICON`]: icon_path, ...declared }, log_file });
60
+ return start({ socket_path, script: join(options.main_dir, "daemon.js"), env: { [`${prefix}_DB`]: database_path, [`${prefix}_SOCKET`]: socket_path, [`${prefix}_ICON`]: icon_path, ...declared }, log_file, replace_other_build });
61
+ }
62
+ // Saves the text where the user picks, starting in Downloads; false when the dialog was cancelled.
63
+ async function save_text_file(file_name, text) {
64
+ if (!dialog.showSaveDialog)
65
+ throw new Error("This desktop app cannot show a Save dialog.");
66
+ const { canceled, filePath } = await dialog.showSaveDialog(save_dialog_options(file_name, electron.app.getPath("downloads")));
67
+ if (canceled || !filePath)
68
+ return false;
69
+ await writeFile(filePath, text);
70
+ return true;
50
71
  }
51
72
  // ── Connections ──────────────────────────────────────────────────────
52
73
  // Certificates the user trusted, read again whenever the daemon saves the list, so calls to a server honour them.
@@ -63,7 +84,7 @@ export function run_desktop(app, electron, options) {
63
84
  connections,
64
85
  link,
65
86
  call_local: (path, args, headers) => call_socket(socket_path, path, args, headers),
66
- restart_local: ensure_daemon,
87
+ restart_local: () => ensure_daemon(),
67
88
  local_tables: [...default_local_tables, "peer_listening"],
68
89
  is_read_only: app.is_read_only,
69
90
  on_change: () => {
@@ -205,6 +226,8 @@ export function run_desktop(app, electron, options) {
205
226
  await apply_window_settings();
206
227
  },
207
228
  quit_completely,
229
+ get_idle_seconds: () => electron.powerMonitor?.getSystemIdleTime() ?? 0,
230
+ save_text_file,
208
231
  };
209
232
  bridges.desktop.handle(ipcMain, desktop, handle_options);
210
233
  }
@@ -212,7 +235,7 @@ export function run_desktop(app, electron, options) {
212
235
  function start_app() {
213
236
  void electron.app.whenReady().then(async () => {
214
237
  try {
215
- await ensure_daemon();
238
+ await ensure_daemon(true);
216
239
  }
217
240
  catch (error) {
218
241
  dialog.showErrorBox(`${app.name} could not start`, `${error instanceof Error ? error.message : String(error)}\n\nSee ${log_file}.`);
@@ -240,7 +263,7 @@ export function run_desktop(app, electron, options) {
240
263
  // `<app>-desktop --daemon`, as the login entry runs it, starts only the daemon.
241
264
  async function start_daemon_alone() {
242
265
  try {
243
- await ensure_daemon();
266
+ await ensure_daemon(true);
244
267
  electron.app.exit(0);
245
268
  }
246
269
  catch (error) {
@@ -21,8 +21,10 @@ export interface DesktopMethods {
21
21
  get_desktop_settings: () => DesktopSettings;
22
22
  set_desktop_setting: <Key extends keyof DesktopSettings>(key: Key, value: DesktopSettings[Key]) => void;
23
23
  quit_completely: () => void;
24
+ get_idle_seconds: () => number;
25
+ save_text_file: (file_name: string, text: string) => boolean;
24
26
  }
25
- export declare const desktop_method_names: readonly ["get_desktop_settings", "set_desktop_setting", "quit_completely"];
27
+ export declare const desktop_method_names: readonly ["get_desktop_settings", "set_desktop_setting", "quit_completely", "get_idle_seconds", "save_text_file"];
26
28
  export interface DaemonMethods {
27
29
  get_desktop_settings: () => DesktopSettings;
28
30
  set_desktop_setting: (key: keyof DesktopSettings, value: boolean) => void;
@@ -11,4 +11,4 @@ export function read_desktop_settings(saved, specs = {}) {
11
11
  const defaults = { ...desktop_setting_defaults, ...Object.fromEntries(Object.entries(specs).map(([key, spec]) => [key, spec.default])) };
12
12
  return Object.fromEntries(Object.entries(defaults).map(([key, fallback]) => [key, typeof settings[key] === "boolean" ? settings[key] : fallback]));
13
13
  }
14
- export const desktop_method_names = ["get_desktop_settings", "set_desktop_setting", "quit_completely"];
14
+ export const desktop_method_names = ["get_desktop_settings", "set_desktop_setting", "quit_completely", "get_idle_seconds", "save_text_file"];
@@ -0,0 +1,20 @@
1
+ import { DatabaseSync } from "node:sqlite";
2
+ import type { App } from "./define.ts";
3
+ export declare function real_database_path(app: Pick<App, "id" | "database_file">, home?: string): string;
4
+ export interface SeedOptions<Methods> {
5
+ file: string;
6
+ reset?: boolean;
7
+ seed: (calls: Methods, database: DatabaseSync) => void;
8
+ home?: string;
9
+ }
10
+ export declare function seed_app_database<Methods>(app: App & {
11
+ bind_methods: (database: () => DatabaseSync, on_change: () => void) => Methods;
12
+ }, options: SeedOptions<Methods>): void;
13
+ export declare function seed_target(argv: string[], app_name: string): {
14
+ file: string;
15
+ reset: boolean;
16
+ } | {
17
+ usage: string;
18
+ code: number;
19
+ };
20
+ export declare function run_seed<Methods>(app: Parameters<typeof seed_app_database<Methods>>[0], seed: SeedOptions<Methods>["seed"], argv?: string[]): void;
@@ -0,0 +1,64 @@
1
+ // A development database filled with an app's example data, made by the app's own calls so it is laid out as the app
2
+ // keeps it, and never the user's real data: the desktop app's database in ~/.config/<id> is refused, whatever path leads
3
+ // there. An app's seed script is one call, run as `<script> <file> [--reset]`.
4
+ // ── Imports ──────────────────────────────────────────────────────────────────
5
+ import { existsSync, mkdirSync, realpathSync, rmSync } from "node:fs";
6
+ import { homedir } from "node:os";
7
+ import { dirname, join, resolve } from "node:path";
8
+ import { DatabaseSync } from "node:sqlite";
9
+ import { parseArgs } from "node:util";
10
+ // ── Files ────────────────────────────────────────────────────────────────────
11
+ // Where the desktop app keeps the user's own data, which is never seeded.
12
+ export function real_database_path(app, home = homedir()) {
13
+ return join(home, ".config", app.id, app.database_file);
14
+ }
15
+ function same_file(first, second) {
16
+ const real_path = (path) => (existsSync(path) ? realpathSync(path) : resolve(path));
17
+ return real_path(first) === real_path(second);
18
+ }
19
+ // The database goes together with its write-ahead log and shared memory.
20
+ function remove_database(path) {
21
+ for (const suffix of ["", "-wal", "-shm"])
22
+ rmSync(path + suffix, { force: true });
23
+ }
24
+ // Makes the file afresh with the app's schema and example data; refuses the real database and, without reset, any file there.
25
+ export function seed_app_database(app, options) {
26
+ const path = resolve(options.file);
27
+ if (same_file(path, real_database_path(app, options.home)))
28
+ throw new Error(`refusing to seed the real database at ${path}`);
29
+ if (existsSync(path)) {
30
+ if (!options.reset)
31
+ throw new Error(`${path} already exists; pass --reset to replace it`);
32
+ remove_database(path);
33
+ }
34
+ mkdirSync(dirname(path), { recursive: true });
35
+ const database = new DatabaseSync(path);
36
+ try {
37
+ database.exec("PRAGMA journal_mode = WAL");
38
+ app.open_store(database);
39
+ options.seed(app.bind_methods(() => database, () => undefined), database);
40
+ }
41
+ finally {
42
+ database.close();
43
+ }
44
+ }
45
+ // ── Command ──────────────────────────────────────────────────────────────────
46
+ // The seed script's command line: the file and --reset, or the usage on --help or a missing file.
47
+ export function seed_target(argv, app_name) {
48
+ const usage = `Usage: seed-database <file> [--reset]\n\nMakes a development ${app_name} database filled with example data, dated around today.\n --reset replace the file if it already exists`;
49
+ const { values, positionals } = parseArgs({ args: argv, allowPositionals: true, options: { reset: { type: "boolean" }, help: { type: "boolean" } } });
50
+ if (values.help || positionals.length !== 1)
51
+ return { usage, code: values.help ? 0 : 1 };
52
+ return { file: positionals[0], reset: values.reset === true };
53
+ }
54
+ // Runs a seed script from the command line, printing what it made or why it would not.
55
+ export function run_seed(app, seed, argv = process.argv.slice(2)) {
56
+ const target = seed_target(argv, app.name);
57
+ if ("usage" in target) {
58
+ console.log(target.usage);
59
+ process.exitCode = target.code;
60
+ return;
61
+ }
62
+ seed_app_database(app, { file: target.file, reset: target.reset, seed });
63
+ console.log(`Seeded ${resolve(target.file)}`);
64
+ }
@@ -18,6 +18,7 @@ export interface AppDatabase {
18
18
  close: () => void;
19
19
  }
20
20
  export declare function open_app_database(app: App, path: string, backups_folder: string): AppDatabase;
21
+ export declare function watch_outside_changes(database: () => SqlDatabase, on_change: () => void, every_ms?: number): () => void;
21
22
  export declare const call_body_limit: number;
22
23
  export declare function call_args(app: App, method: string, body: unknown): unknown[];
23
24
  export declare function register_app_calls(api: FastifyInstance, app: App, database: () => SqlDatabase, changes: EventStream): void;
@@ -89,6 +89,34 @@ function adopt_schedule_file(app, database, file) {
89
89
  app.adopt_backup_schedule(database, saved);
90
90
  rmSync(file, { force: true });
91
91
  }
92
+ // Another program, such as an older build of the app, may write the database file; SQLite moves data_version only
93
+ // for another connection's commits, so this one's own writes never count. Checked every second; returns how to stop.
94
+ export function watch_outside_changes(database, on_change, every_ms = 1000) {
95
+ const version_of = () => {
96
+ try {
97
+ return database().prepare("PRAGMA data_version").get().data_version;
98
+ }
99
+ catch {
100
+ // Closed for a restore, which announces its own change.
101
+ return null;
102
+ }
103
+ };
104
+ let connection = database();
105
+ let last = version_of();
106
+ const timer = setInterval(() => {
107
+ const now = version_of();
108
+ // A restore opens a new connection, whose count starts afresh.
109
+ if (database() !== connection) {
110
+ connection = database();
111
+ last = now;
112
+ return;
113
+ }
114
+ if (now !== null && last !== null && now !== last)
115
+ on_change();
116
+ last = now;
117
+ }, every_ms);
118
+ return () => clearInterval(timer);
119
+ }
92
120
  // ── Calls ────────────────────────────────────────────────────────────────────
93
121
  // An import arrives as one call's argument.
94
122
  export const call_body_limit = 32 * 1024 * 1024;
@@ -156,10 +184,10 @@ export async function build_server(app, options) {
156
184
  name: app.id,
157
185
  version: app.version,
158
186
  instructions: app.instructions,
159
- api: app.api_spec,
187
+ api: app.mcp.api,
160
188
  is_read_only: app.is_read_only,
161
- page_only: app.page_only,
162
- call: (method, args) => app.bridges.calls.dispatch(app.bind_methods(database, () => changes.announce_change(), "program"), method, args),
189
+ page_only: app.mcp.page_only,
190
+ call: (method, args) => app.mcp.call(database, () => changes.announce_change(), method, args),
163
191
  });
164
192
  // The server's backups, as the page's Settings reach them.
165
193
  api.post("/backups/:method", async (request, reply) => {
@@ -229,6 +257,7 @@ export async function run_server(app, options) {
229
257
  on_remote_change: () => changes.announce_change(),
230
258
  });
231
259
  const server = await build_server(app, { database: opened.database, accounts, web_folder: server_config.web_folder, sync, changes, backup_methods: opened.backup_methods });
260
+ const stop_watching = watch_outside_changes(opened.database, () => changes.announce_change());
232
261
  const address = await server.listen({ host: server_config.host, port: server_config.port });
233
262
  sync.start();
234
263
  const sides = side_databases(database_path);
@@ -254,6 +283,7 @@ export async function run_server(app, options) {
254
283
  let stopping = null;
255
284
  const stop = () => (stopping ??= server.close().then(async () => {
256
285
  await services.stop();
286
+ stop_watching();
257
287
  sync.stop();
258
288
  sides.close_all();
259
289
  opened.close();
@@ -60,7 +60,10 @@ function Pages({ pages, account }) {
60
60
  }));
61
61
  const views = listed.map((each, index) => ({ id: each.id, label: row_label(index), href: `#/${each.id}`, ...(each.icon ? { icon: each.icon } : {}) }));
62
62
  const view = shown ? shown.view(rest) : is_account ? _jsx(AccountPage, { account: account }) : _jsx(SettingsView, { pages: pages, is_admin: account === null || is_admin(account.me) });
63
- return (_jsx(Shell, { brand: app.name, brand_icon: pages.brand_icon ?? "icon.svg", ...(with_icons ? { views } : { sections }), active: shown?.active_as ?? section, active_item: subpage?.id ?? null, sections_pref: `${app.id}-sidebar-collapsed`, ...(chrome.sidebar ? { sidebar: chrome.sidebar } : {}), ...(chrome.tools ? { tools: chrome.tools } : {}), ...(chrome.side_pane ? { side_pane: chrome.side_pane } : {}), theme: theme_choice(`${app.id}-theme`), view_key: view_key, user: account ? account.me.name : undefined, user_href: account ? "#/account" : undefined, on_logout: account ? () => void account.sign_out() : undefined, sidebar_foot: _jsx(SidebarFoot, {}), settings: { href: "#/settings" }, children: _jsx(Fragment, { children: view }, view_key) }));
63
+ const framed = _jsx(Fragment, { children: view }, view_key);
64
+ if (chrome.bare)
65
+ return _jsx(_Fragment, { children: chrome.around ? chrome.around(framed) : framed });
66
+ return (_jsx(Shell, { brand: app.name, brand_icon: pages.brand_icon ?? "icon.svg", ...(with_icons ? { views } : { sections }), active: shown?.active_as ?? section, active_item: subpage?.id ?? null, sections_pref: `${app.id}-sidebar-collapsed`, ...(chrome.sidebar ? { sidebar: chrome.sidebar } : {}), ...(chrome.tools ? { tools: chrome.tools } : {}), ...(chrome.side_pane ? { side_pane: chrome.side_pane } : {}), ...(chrome.contained ? { contained: true } : {}), ...(chrome.main_class ? { main_class: chrome.main_class } : {}), theme: theme_choice(`${app.id}-theme`), view_key: view_key, user: account ? account.me.name : undefined, user_href: account ? "#/account" : undefined, on_logout: account ? () => void account.sign_out() : undefined, sidebar_foot: _jsx(SidebarFoot, {}), settings: { href: "#/settings" }, children: chrome.around ? chrome.around(framed) : framed }));
64
67
  }
65
68
  // ── App ──────────────────────────────────────────────────────────────────────
66
69
  // A browser reaches the server's data, so it signs in; the desktop and phone apps keep their own and sign in only to sync.
@@ -26,6 +26,10 @@ export interface AppChrome {
26
26
  sidebar?: React.ReactNode;
27
27
  tools?: React.ReactNode;
28
28
  side_pane?: ShellSidePane;
29
+ contained?: boolean;
30
+ main_class?: string;
31
+ around?: (view: React.ReactNode) => React.ReactNode;
32
+ bare?: boolean;
29
33
  }
30
34
  export interface AppPages {
31
35
  app: Pick<App, "id" | "name" | "data_name" | "server_example" | "bridges"> & Partial<Pick<App, "desktop_settings">>;
@@ -0,0 +1,13 @@
1
+ export interface IdleWatch {
2
+ last_sample_at: number | null;
3
+ away_since: number | null;
4
+ }
5
+ export declare const fresh_idle_watch: IdleWatch;
6
+ export interface AwaySpan {
7
+ from: number;
8
+ to: number;
9
+ }
10
+ export declare function step_idle_watch(watch: IdleWatch, now: number, idle_seconds: number, threshold_seconds: number, poll_milliseconds: number): {
11
+ watch: IdleWatch;
12
+ away: AwaySpan | null;
13
+ };
@@ -0,0 +1,22 @@
1
+ // Time away from the computer while something runs, such as a timer on a task: a watch that looks now and then at how
2
+ // long the computer has gone without input (the desktop's get_idle_seconds) and hands back the stretch away once
3
+ // someone comes back, so the app can ask whether to keep that time.
4
+ export const fresh_idle_watch = { last_sample_at: null, away_since: null };
5
+ // Takes one look at how long the computer has gone without input, and hands back the time away once someone comes back.
6
+ // A long gap between looks, as when the computer slept, counts as time away from the last look.
7
+ export function step_idle_watch(watch, now, idle_seconds, threshold_seconds, poll_milliseconds) {
8
+ const threshold_milliseconds = threshold_seconds * 1000;
9
+ const idle_since = now - idle_seconds * 1000;
10
+ let away_since = watch.away_since;
11
+ const missed_looks = watch.last_sample_at !== null && now - watch.last_sample_at >= Math.max(threshold_milliseconds, 2 * poll_milliseconds);
12
+ if (missed_looks)
13
+ away_since = Math.min(away_since ?? Infinity, watch.last_sample_at);
14
+ if (idle_seconds >= threshold_seconds)
15
+ away_since = Math.min(away_since ?? Infinity, idle_since);
16
+ const is_back = idle_seconds < threshold_seconds;
17
+ if (is_back && away_since !== null) {
18
+ const span = { from: away_since, to: Math.max(away_since, idle_since) };
19
+ return { watch: { last_sample_at: now, away_since: null }, away: span.to - span.from >= threshold_milliseconds ? span : null };
20
+ }
21
+ return { watch: { last_sample_at: now, away_since }, away: null };
22
+ }
package/dist/sql.d.ts CHANGED
@@ -15,7 +15,7 @@ export interface SqlDatabase {
15
15
  close: () => void;
16
16
  }
17
17
  export declare function in_transaction<Result>(database: SqlDatabase, work: () => Result): Result;
18
- export type MigrationStep = string | readonly string[];
18
+ export type MigrationStep = string | readonly string[] | ((database: SqlDatabase) => void);
19
19
  export interface MigrateOptions {
20
20
  owner?: string;
21
21
  }
package/dist/sql.js CHANGED
@@ -15,6 +15,8 @@ export function in_transaction(database, work) {
15
15
  }
16
16
  }
17
17
  function run_step(database, step) {
18
+ if (typeof step === "function")
19
+ return step(database);
18
20
  for (const statement of typeof step === "string" ? [step] : step)
19
21
  database.exec(statement);
20
22
  }
@@ -20,24 +20,53 @@ export function use_resource(work, dependencies, options = {}) {
20
20
  const latest_work = useRef(work);
21
21
  latest_work.current = work;
22
22
  const generation = useRef(0);
23
- const reload = useCallback((quiet = false) => {
23
+ // The load under way, and whether a quiet reload asked for while it ran is still owed.
24
+ const running = useRef(null);
25
+ const owed = useRef(false);
26
+ const load = useCallback((quiet) => {
24
27
  const mine = ++generation.current;
25
28
  if (!quiet)
26
29
  set_state({ data: null, error: null, status: "loading" });
27
- return latest_work.current().then((data) => { if (mine === generation.current)
30
+ const settled = latest_work.current().then((data) => { if (mine === generation.current)
28
31
  set_state({ data, error: null, status: "loaded" }); }, (error) => {
29
32
  if (pass_login_needed(error) || mine !== generation.current)
30
33
  return;
31
34
  set_state((before) => quiet && before.data !== null ? before : { data: null, error, status: "failed" });
35
+ }).finally(() => {
36
+ if (running.current !== settled)
37
+ return;
38
+ running.current = null;
39
+ if (owed.current && mine === generation.current) {
40
+ owed.current = false;
41
+ void load(true);
42
+ }
32
43
  });
44
+ running.current = settled;
45
+ return settled;
33
46
  }, []);
47
+ // Quiet reloads asked for while a load runs become one more load once it settles, so a burst of changes on a slow server
48
+ // never stacks requests up behind each other.
49
+ const reload = useCallback((quiet = false) => {
50
+ if (quiet && running.current) {
51
+ owed.current = true;
52
+ return running.current;
53
+ }
54
+ owed.current = false;
55
+ return load(quiet);
56
+ }, [load]);
34
57
  useEffect(() => {
35
58
  if (enabled)
36
59
  return void reload();
37
60
  // Turning off drops the load under way and what it showed.
38
61
  generation.current += 1;
62
+ owed.current = false;
39
63
  set_state((before) => before.status === "idle" ? before : { data: null, error: null, status: "idle" });
40
64
  }, [enabled, ...dependencies]);
65
+ // A page that has gone loads nothing more.
66
+ useEffect(() => () => {
67
+ generation.current += 1;
68
+ owed.current = false;
69
+ }, []);
41
70
  useEffect(() => {
42
71
  if (!options.refresh_in_milliseconds || !enabled)
43
72
  return;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@x-tech-laboratories/x-app",
3
- "version": "0.114.0",
3
+ "version": "0.115.0",
4
4
  "description": "Code the X-apps share: agents and their long runs, passwords and sign-in, the Fastify server pieces, durations, and the web page's helpers and widgets",
5
5
  "license": "GPL-3.0-or-later",
6
6
  "repository": {