@x-tech-laboratories/x-app 0.114.1 → 0.116.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. `synced_theme` keeps the light, dark or system theme as a synced setting, `theme`, so every device shows the one picked last. |
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`) `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. |
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. |
19
- | `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. |
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, 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 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. |
20
+ | `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. |
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. |
@@ -52,7 +54,8 @@ an app moves over by changing the package name in its imports and its `x-libs-*`
52
54
  | `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. |
53
55
  | `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. 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. |
54
56
  | `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>`. |
55
- | `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` (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. |
57
+ | `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. |
58
+ | `app_android_key` | `x-app-android-key [app folder]`: the app's Android release key, made once with keytool in `~/.local/share/<name>/signing` 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. Run it in the app's Android shell. |
56
59
  | `app_icons` | `x-app-icons [app folder]`: every icon an app ships generated from its `resources/icon.svg`, as the Design Guidelines ask: `resources/icon.png` for the desktop, the Android launcher icons at each density with an adaptive icon on white when there is an `android/` project, and `icon.svg`, `icon-192.png` and `icon-512.png` in `src/web/public` when there is one. Drawn with `@resvg/resvg-js`, an optional peer the app installs as a dev dependency. |
57
60
  | `change_checks`, `change_checks_git`, `change_checks_cli` | Checks on a change that any repository's CI runs, as `x-app-check` (see [Change checks](#change-checks)): `commits` (Conventional Commits, the `Assisted-by` trailer in the organisation's repositories and nowhere else, no AI mention outside it), `secrets` (keys and tokens in added lines, commit messages and added `.env` files, naming only the kind and place, never the value), `leftovers` (console logging, `debugger`, code commented out, a TODO without an issue), `comments` (a comment longer than one line, but for a file's overview), `coverage` (a floor lowered or code newly left out), `x-libs` (an import of a library X-App wraps) and `dependencies` (each new one named with its licence, failing a licence not allowed, read as SPDX by `spdx-satisfies`); each a pure function on a described `Change` giving `{ gate, outcome, findings }` with file:line, reading only the code around strings and regular expressions; `create_check_registry` for an app's own checks, `x_tech_options` the defaults, and `read_change` reading a change from git, its `base` resolved to a commit; `run_check_command` runs the command for an app with its own checks, defaults and name. |
58
61
  | `certificates`, `certificate_protocol`, `electron/certificates` | Servers whose https certificate the device refuses, such as a home server's self-signed one: `check_certificate` reads the certificate and what is wrong with it (self-signed, unknown authority, wrong name, expired, not yet valid), `create_certificate_trust` keeps the ones the user trusts in a JSON file, each for its own host and exact fingerprint, re-checked before it is saved, and its `methods` are the page's calls; `trust_in_session` makes Chromium accept them in a session, the window's from the next start, and `trusting_fetch` sends the main process's requests, such as the sync client's, through a Chromium session made fresh each time the list changes, so a new choice holds at once; `use_in_node` also hands them to Node's own https, which then accepts a self-signed server whose name matches. |
@@ -238,15 +241,23 @@ The rest of an app's files are short calls into X-App too:
238
241
  taking the app's package set and its `nix/app.nix` (name, display name, variables' prefix, port, database file and
239
242
  words); the app's `nix/flake.nix` takes `github:x-tech-laboratories/X-App` as an input and calls them.
240
243
  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
242
- `<PREFIX>_LAUNCHER` so the login entry runs the installed command.
244
+ copy in, and `link_scheme`, such as `"codex"`, makes the desktop entry open its links; `desktop_path`, such as
245
+ `pkgs: [ pkgs.libnotify ]`, puts programs the desktop app runs on its PATH, and `state_name` keeps an older service's
246
+ data folder `/var/lib/<state_name>`; the desktop wrapper sets
247
+ `<PREFIX>_LAUNCHER` so the login entry runs the installed command. `android_emulator_shell nixpkgs system app` adds an
248
+ Android 36 emulator to the Android shell, with `<name>-emulator` to start it and `<name>-emulator-install` to build
249
+ and open the app on it, never on a connected phone.
243
250
  - **Android**: `npm run build:android` builds the phone's page and runs `x-app-android`, which makes or updates the
244
251
  Capacitor project in `android/`, so the app keeps only `capacitor.config.json` and leaves `android/` out of git.
252
+ `x-app-android-key` makes the release key once and stores it as the repository's secrets.
245
253
  - **CI**: the app's `ci` job runs `x-tech-laboratories/X-App/.github/actions/app-ci@main`, its `nix` job
246
- `app-nix@main` with the targets to build, an Android app's `android` job `app-android@main` with the release key's
247
- secrets (the APK as the run's artifact, and a GitHub release from a `v*` tag), and its Dependabot workflow
248
- `app-dependabot-auto-merge@main`. They are composite actions, so the jobs keep the names `ci` and `nix` the ruleset
249
- requires.
254
+ `app-nix@main` with the targets to build, and its Dependabot workflow `app-dependabot-auto-merge@main`. Every push to
255
+ `main` is a release: an Android app's `android` job runs `app-android@main` with `release: push` and the release key's
256
+ secrets, a desktop app's `linux` job runs `app-linux@main` for the AppImage and Flatpak bundle from
257
+ `config/electron-builder.mjs`, and a `release` job after them runs `app-release@main`, which publishes them as the
258
+ latest GitHub release `v<version>.<run>`, so Obtainium sees each one as newer. A published APK must be signed: without
259
+ the key the `android` job fails, and nothing is released. They are composite actions, so the jobs keep the names `ci`
260
+ and `nix` the ruleset requires.
250
261
 
251
262
  `npx x-app-new X-Notes` writes all of it for a new app.
252
263
 
@@ -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>>;
@@ -66,11 +67,13 @@ export interface AppOptions<Features extends readonly Feature[]> {
66
67
  local_mcp?: {
67
68
  default_port: number;
68
69
  };
70
+ synced_theme?: boolean;
69
71
  }
70
72
  export declare const base_setting_defaults: {
71
73
  history_days: number;
72
74
  };
73
75
  export declare const backup_schedule_key = "backup_schedule";
76
+ export declare const theme_key = "theme";
74
77
  export declare function is_backup_schedule(value: unknown): value is BackupSchedule;
75
78
  export interface Restorable extends Backups {
76
79
  restore: (name: string) => Promise<void>;
@@ -118,6 +121,7 @@ export declare function define_app<const Features extends readonly Feature[]>(op
118
121
  run: (database: SqlDatabase) => void;
119
122
  };
120
123
  page_only_refusal?: string;
124
+ tools?: Feature;
121
125
  token_prefix?: string;
122
126
  history_days?: number;
123
127
  desktop_settings?: Readonly<Record<string, DesktopSettingSpec>>;
@@ -125,6 +129,7 @@ export declare function define_app<const Features extends readonly Feature[]>(op
125
129
  local_mcp?: {
126
130
  default_port: number;
127
131
  };
132
+ synced_theme?: boolean;
128
133
  features: readonly Feature<Record<string, StoreMethod>>[];
129
134
  settings_store: SettingsStore;
130
135
  setting_defaults: Readonly<import("../settings.ts").Settings>;
@@ -154,6 +159,11 @@ export declare function define_app<const Features extends readonly Feature[]>(op
154
159
  is_read_only: typeof is_read_only;
155
160
  page_only: PageOnlyCalls;
156
161
  bind_methods: (database: () => SqlDatabase, on_change: () => void, caller?: Caller) => Bound<SettingsMethods & UnionToIntersection<Features[number]["methods"]>>;
162
+ mcp: {
163
+ api: ApiSpec<Record<string, StoreMethod>>;
164
+ page_only: PageOnlyCalls;
165
+ call: (database: () => SqlDatabase, on_change: () => void, method: string, args: unknown[]) => unknown;
166
+ };
157
167
  backup_naming: BackupNaming;
158
168
  read_backup_schedule: (database: SqlDatabase) => BackupSchedule;
159
169
  adopt_backup_schedule: (database: SqlDatabase, saved: unknown) => void;
@@ -30,6 +30,8 @@ export const base_setting_defaults = {
30
30
  history_days: 365,
31
31
  };
32
32
  export const backup_schedule_key = "backup_schedule";
33
+ // The synced setting an app with synced_theme keeps its theme in.
34
+ export const theme_key = "theme";
33
35
  const base_settings = {
34
36
  ...settings_of(base_setting_defaults),
35
37
  // How this device backs up is its own, never synced.
@@ -41,7 +43,10 @@ export function is_backup_schedule(value) {
41
43
  }
42
44
  export function define_app(options) {
43
45
  // ── Settings ─────────────────────────────────────────────────────────
44
- const own_base_settings = options.history_days === undefined ? base_settings : { ...base_settings, history_days: { ...base_settings.history_days, default: options.history_days } };
46
+ const own_base_settings = {
47
+ ...(options.history_days === undefined ? base_settings : { ...base_settings, history_days: { ...base_settings.history_days, default: options.history_days } }),
48
+ ...(options.synced_theme ? { [theme_key]: { default: "system" } } : {}),
49
+ };
45
50
  const settings_store = create_settings_store([own_base_settings, options.settings ?? {}, ...options.features.map((feature) => feature.settings ?? {})], {
46
51
  app: { id: options.id, name: options.name },
47
52
  ...(options.settings_descriptions ? { descriptions: options.settings_descriptions } : {}),
@@ -75,6 +80,10 @@ export function define_app(options) {
75
80
  database.exec("PRAGMA foreign_keys = ON");
76
81
  if (options.upgrade_layout?.needed(database))
77
82
  options.upgrade_layout.run(database);
83
+ // Sync's and history's triggers name columns, so they come off while a step reshapes a table; install puts them back.
84
+ sync_engine.drop_triggers(database);
85
+ for (const history of histories)
86
+ history.drop_triggers?.(database);
78
87
  // Each feature keeps its own schema version, so features grow apart without renumbering each other's steps.
79
88
  for (const feature of features)
80
89
  migrate(database, feature.migrations, { owner: feature.id });
@@ -119,8 +128,13 @@ export function define_app(options) {
119
128
  // The calls run on the database given as the caller given, telling on_change after each write so the other pages
120
129
  // and devices hear of it.
121
130
  function bind_methods(database, on_change, caller = "page") {
122
- const bound = method_names.map((name) => {
123
- const method = all_methods[name];
131
+ return bind_table(all_methods, database, on_change, caller);
132
+ }
133
+ // Any table of calls run on the database as the caller, each write followed by the features' catch-up, its versions
134
+ // recorded and on_change told.
135
+ function bind_table(table, database, on_change, caller) {
136
+ const bound = Object.keys(table).map((name) => {
137
+ const method = table[name];
124
138
  const call = (...args) => {
125
139
  const result = as_caller(caller, () => method(database(), ...args));
126
140
  if (is_read_only(name))
@@ -140,6 +154,19 @@ export function define_app(options) {
140
154
  });
141
155
  return Object.fromEntries(bound);
142
156
  }
157
+ // What MCP offers: the app's own tools when it has them, otherwise the page's calls.
158
+ const tools = options.tools;
159
+ const mcp = {
160
+ api: (tools ? tools.api : api_spec),
161
+ page_only: tools ? page_only_calls(tools.api, options.page_only_refusal ? { refusal: options.page_only_refusal } : {}) : page_only,
162
+ // Runs one tool by name as the program caller, refusing a name it does not offer.
163
+ call: (database, on_change, method, args) => {
164
+ const table = (tools ? tools.methods : all_methods);
165
+ if (!Object.hasOwn(table, method))
166
+ throw new Error(`${options.name} has no tool ${method}`);
167
+ return bind_table({ [method]: table[method] }, database, on_change, "program")[method](...args);
168
+ },
169
+ };
143
170
  // ── Backups ──────────────────────────────────────────────────────────
144
171
  // Names such as budget-2026-06-10T09-30-00Z-auto.db.
145
172
  const naming = backup_naming(options.backup_prefix, ".db");
@@ -204,6 +231,7 @@ export function define_app(options) {
204
231
  is_read_only,
205
232
  page_only,
206
233
  bind_methods,
234
+ mcp,
207
235
  backup_naming: naming,
208
236
  read_backup_schedule,
209
237
  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,9 +29,18 @@ 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
- nativeTheme: NativeThemeLike;
41
+ nativeTheme: NativeThemeLike & {
42
+ themeSource?: "system" | "light" | "dark";
43
+ };
35
44
  screen: ScreenLike & {
36
45
  getPrimaryDisplay(): {
37
46
  workAreaSize: {
@@ -40,7 +49,10 @@ export interface ElectronLike {
40
49
  };
41
50
  };
42
51
  };
43
- shell: ShellLike;
52
+ shell: ShellLike & {
53
+ showItemInFolder?(path: string): void;
54
+ openPath?(path: string): Promise<string>;
55
+ };
44
56
  Tray?: new (image: never) => TrayLike;
45
57
  Menu?: TrayElectronLike<unknown>["Menu"];
46
58
  nativeImage?: {
@@ -52,6 +64,14 @@ export interface ElectronLike {
52
64
  };
53
65
  };
54
66
  }
67
+ export interface SaveDialogOptionsLike {
68
+ defaultPath: string;
69
+ filters: {
70
+ name: string;
71
+ extensions: string[];
72
+ }[];
73
+ }
74
+ export declare function save_dialog_options(file_name: string, downloads: string): SaveDialogOptionsLike;
55
75
  export interface TrayTools {
56
76
  call: (method: string, args?: unknown[]) => Promise<unknown>;
57
77
  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,19 @@ 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,
231
+ set_window_theme: (theme) => {
232
+ if (theme === "system" || theme === "light" || theme === "dark")
233
+ electron.nativeTheme.themeSource = theme;
234
+ },
235
+ get_data_paths: () => ({ database: database_path, backups: join(profile, "backups") }),
236
+ show_data_path: async (which) => {
237
+ if (which === "database")
238
+ electron.shell.showItemInFolder?.(database_path);
239
+ else
240
+ await electron.shell.openPath?.(join(profile, "backups"));
241
+ },
208
242
  };
209
243
  bridges.desktop.handle(ipcMain, desktop, handle_options);
210
244
  }
@@ -212,7 +246,7 @@ export function run_desktop(app, electron, options) {
212
246
  function start_app() {
213
247
  void electron.app.whenReady().then(async () => {
214
248
  try {
215
- await ensure_daemon();
249
+ await ensure_daemon(true);
216
250
  }
217
251
  catch (error) {
218
252
  dialog.showErrorBox(`${app.name} could not start`, `${error instanceof Error ? error.message : String(error)}\n\nSee ${log_file}.`);
@@ -240,7 +274,7 @@ export function run_desktop(app, electron, options) {
240
274
  // `<app>-desktop --daemon`, as the login entry runs it, starts only the daemon.
241
275
  async function start_daemon_alone() {
242
276
  try {
243
- await ensure_daemon();
277
+ await ensure_daemon(true);
244
278
  electron.app.exit(0);
245
279
  }
246
280
  catch (error) {
@@ -21,8 +21,17 @@ 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;
26
+ set_window_theme: (theme: "system" | "light" | "dark") => void;
27
+ get_data_paths: () => DataPaths;
28
+ show_data_path: (which: keyof DataPaths) => void;
24
29
  }
25
- export declare const desktop_method_names: readonly ["get_desktop_settings", "set_desktop_setting", "quit_completely"];
30
+ export interface DataPaths {
31
+ database: string;
32
+ backups: string;
33
+ }
34
+ 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"];
26
35
  export interface DaemonMethods {
27
36
  get_desktop_settings: () => DesktopSettings;
28
37
  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", "set_window_theme", "get_data_paths", "show_data_path"];
@@ -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();
@@ -3,6 +3,11 @@ import "@x-tech-laboratories/halon/halon.css";
3
3
  import type { App } from "../define.ts";
4
4
  import { type AppPages } from "./settings_page.tsx";
5
5
  export type { AppPage, AppPages, AppSubpage, PageSettingsProps } from "./settings_page.tsx";
6
+ export declare const default_sidebar_width: {
7
+ default_width: number;
8
+ min: number;
9
+ max: number;
10
+ };
6
11
  export declare function AppView({ pages }: {
7
12
  pages: AppPages;
8
13
  }): import("react").JSX.Element;
@@ -4,7 +4,7 @@ import { Fragment as _Fragment, jsx as _jsx, jsxs as _jsxs } from "react/jsx-run
4
4
  // ── Imports ──────────────────────────────────────────────────────────────────
5
5
  import "@x-tech-laboratories/halon/halon-tokens.css";
6
6
  import "@x-tech-laboratories/halon/halon.css";
7
- import { Fragment, useEffect } from "react";
7
+ import { Fragment, useEffect, useMemo, useRef } from "react";
8
8
  import { createRoot } from "react-dom/client";
9
9
  import { create_accounts_client } from "../../web/accounts.js";
10
10
  import { AccountView, UsersView } from "../../web/react/accounts.js";
@@ -13,9 +13,9 @@ import { PageHeading } from "../../web/react/layout.js";
13
13
  import { Shell, use_route } from "../../web/react/shell.js";
14
14
  import { SignInForm, use_account } from "../../web/react/sign_in.js";
15
15
  import { SyncButton } from "../../web/react/sync_settings.js";
16
- import { theme_choice } from "../../web/theme.js";
16
+ import { local_theme_storage, theme_choice } from "../../web/theme.js";
17
17
  import { desktop_api, is_android, is_desktop, web_api } from "./hosts.js";
18
- import { data_watch, page, set_page_api } from "./page.js";
18
+ import { calls, data_watch, page, set_page_api, use_settings } from "./page.js";
19
19
  import { SettingsView } from "./settings_page.js";
20
20
  // ── Pages ────────────────────────────────────────────────────────────────────
21
21
  // Relative, so a server behind a proxy under a folder keeps it.
@@ -32,6 +32,46 @@ function SidebarFoot() {
32
32
  const { device } = page();
33
33
  return device ? _jsx(SyncButton, { device: device, subscribe: (listener) => data_watch.subscribe(listener), on_open_settings: () => (window.location.hash = "/settings") }) : null;
34
34
  }
35
+ // The sidebar's first width and the range it is dragged within, remembered on this device unless the app holds it.
36
+ export const default_sidebar_width = { default_width: 248, min: 180, max: 480 };
37
+ function is_theme(value) {
38
+ return value === "system" || value === "light" || value === "dark";
39
+ }
40
+ // The theme kept in this browser, or for an app with synced_theme in its synced setting, which a change on another
41
+ // device applies here too; this browser's copy shows it before the settings arrive.
42
+ function use_theme(app) {
43
+ const settings = use_settings();
44
+ const synced = app.synced_theme === true;
45
+ const stored = synced ? settings.data?.theme : undefined;
46
+ const latest = useRef(undefined);
47
+ latest.current = stored;
48
+ const theme = useMemo(() => {
49
+ const local = local_theme_storage(`${app.id}-theme`);
50
+ if (!synced)
51
+ return theme_choice(local);
52
+ return theme_choice({
53
+ read: () => (is_theme(latest.current) ? latest.current : local.read()),
54
+ write: (chosen) => {
55
+ latest.current = chosen;
56
+ local.write(chosen);
57
+ void calls().set_setting("theme", chosen).catch(() => undefined);
58
+ },
59
+ });
60
+ }, [app.id, synced]);
61
+ // The desktop window's own parts, such as menus, follow the page's theme.
62
+ useEffect(() => {
63
+ const tell = (chosen) => void page().desktop?.set_window_theme(chosen).catch(() => undefined);
64
+ tell(theme.get());
65
+ return theme.on_change(tell);
66
+ }, [theme]);
67
+ useEffect(() => {
68
+ if (!is_theme(stored))
69
+ return;
70
+ local_theme_storage(`${app.id}-theme`).write(stored);
71
+ theme.apply(stored);
72
+ }, [stored, theme]);
73
+ return theme;
74
+ }
35
75
  function Pages({ pages, account }) {
36
76
  const { app } = pages;
37
77
  const route = use_route();
@@ -44,6 +84,7 @@ function Pages({ pages, account }) {
44
84
  const label = shown ? (subpage ? `${subpage.label} · ${shown.label}` : shown.label) : is_account ? "Your account" : "Settings";
45
85
  const view_key = route.parts.join("/");
46
86
  const chrome = pages.use_chrome?.(route.parts) ?? {};
87
+ const theme = use_theme(app);
47
88
  useEffect(() => {
48
89
  document.title = `${label} · ${app.name}`;
49
90
  }, [label, app.name]);
@@ -60,7 +101,10 @@ function Pages({ pages, account }) {
60
101
  }));
61
102
  const views = listed.map((each, index) => ({ id: each.id, label: row_label(index), href: `#/${each.id}`, ...(each.icon ? { icon: each.icon } : {}) }));
62
103
  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) }));
104
+ const framed = _jsx(Fragment, { children: view }, view_key);
105
+ if (chrome.bare)
106
+ return _jsx(_Fragment, { children: chrome.around ? chrome.around(framed) : framed });
107
+ 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, sidebar_width: chrome.sidebar_width ?? { ...default_sidebar_width, storage_key: `${app.id}-sidebar-width` }, 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
108
  }
65
109
  // ── App ──────────────────────────────────────────────────────────────────────
66
110
  // 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.
@@ -1,6 +1,6 @@
1
1
  import type { IconGlyph } from "../../web/react/icons.tsx";
2
2
  import { type SettingsCategory, type SettingsSection } from "../../web/react/layout.tsx";
3
- import type { ShellSidePane } from "../../web/react/shell.tsx";
3
+ import type { ShellSidePane, SidebarWidth } from "../../web/react/shell.tsx";
4
4
  import type { App } from "../define.ts";
5
5
  import type { StartPhoneServices } from "./android.ts";
6
6
  export interface PageSettingsProps {
@@ -26,9 +26,14 @@ 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;
33
+ sidebar_width?: SidebarWidth;
29
34
  }
30
35
  export interface AppPages {
31
- app: Pick<App, "id" | "name" | "data_name" | "server_example" | "bridges"> & Partial<Pick<App, "desktop_settings">>;
36
+ app: Pick<App, "id" | "name" | "data_name" | "server_example" | "bridges"> & Partial<Pick<App, "desktop_settings" | "synced_theme">>;
32
37
  pages: readonly AppPage[];
33
38
  general_settings?: (props: PageSettingsProps) => SettingsSection[];
34
39
  settings_categories?: (props: PageSettingsProps) => SettingsCategory[];
@@ -35,6 +35,14 @@ function Desktop({ app_name, own }) {
35
35
  };
36
36
  return (_jsxs(_Fragment, { children: [_jsx(SettingRow, { label: "Show the tray icon", hint: `Keeps ${app_name} in the tray, where closing the window leaves it.`, as_label: true, children: _jsx(Switch, { label: "Show the tray icon", checked: settings.show_tray_icon, on_change: (on) => change("show_tray_icon", on) }) }), _jsx(SettingRow, { label: "Keep running in the background", hint: "Sync and backups carry on with the window closed. Turned off, they stop shortly after the last window closes.", as_label: true, children: _jsx(Switch, { label: "Keep running in the background", checked: settings.keep_running_in_background, on_change: (on) => change("keep_running_in_background", on) }) }), _jsx(SettingRow, { label: "Start at login", hint: `Starts ${app_name} in the background when you log in, without opening its window.`, as_label: true, children: _jsx(Switch, { label: "Start at login", checked: settings.start_at_login, disabled: !settings.keep_running_in_background, on_change: (on) => change("start_at_login", on) }) }), Object.entries(own).map(([key, spec]) => (_jsx(SettingRow, { label: spec.label, ...(spec.hint ? { hint: spec.hint } : {}), as_label: true, children: _jsx(Switch, { label: spec.label, checked: settings[key] ?? spec.default, on_change: (on) => change(key, on) }) }, key))), _jsx(SettingRow, { label: "Quit completely", hint: `Closes the window and stops ${app_name} in the background too, until you open it again.`, children: _jsx("button", { type: "button", onClick: () => attempt(desktop.quit_completely()), children: "Quit completely" }) })] }));
37
37
  }
38
+ // Where this computer keeps the data, with a button that shows it in the file manager.
39
+ function DataFolder({ desktop }) {
40
+ const [paths, set_paths] = useState(null);
41
+ useEffect(() => void desktop.get_data_paths().then(set_paths, () => undefined), [desktop]);
42
+ if (!paths)
43
+ return null;
44
+ return (_jsx(SettingRow, { label: "Database", hint: _jsx("span", { className: "path", children: paths.database }), children: _jsx("button", { type: "button", onClick: () => attempt(desktop.show_data_path("database")), children: "Show in folder" }) }));
45
+ }
38
46
  // A desktop window on a server's daemon works on the server's data, as a browser does.
39
47
  function storage_category(app, is_admin) {
40
48
  const { backups, backup_folder, certificates, connections, desktop, device, host, local_mcp, peer_listening } = page();
@@ -52,9 +60,13 @@ function storage_category(app, is_admin) {
52
60
  const hint = on_server ? `Keep the server's ${data_name} alike with the devices paired with it.` : `Keep this device's ${data_name} alike with your other devices and your ${name} server.`;
53
61
  sections.push({ id: "sync", heading: "Sync", hint, content: _jsx(SyncSettings, { device: device, subscribe: (listener) => data_watch.subscribe(listener), data_name: data_name, extra: peer_listening && _jsx(PeerListeningSettings, { listening: peer_listening }) }) });
54
62
  }
63
+ if (desktop && !on_server)
64
+ sections.push({ id: "storage", heading: "Storage", hint: `Where this computer keeps its ${data_name}.`, content: _jsx(DataFolder, { desktop: desktop }) });
55
65
  if (backups && (!on_server || is_admin)) {
56
66
  const hint = backup_folder ? `This device's ${data_name}, kept in a folder of the phone's storage.` : on_server ? `The server's ${data_name}, kept in its data folder.` : `This device's ${data_name}, kept beside its database.`;
57
- const content = backup_folder ? _jsx(FolderBackups, { backups: backups, folder: backup_folder, data_name: data_name }) : _jsx(BackupSettings, { device: backups, data_name: data_name, on_restored: () => location.reload() });
67
+ // This computer's backups folder opens in the file manager.
68
+ const show_folder = !on_server && desktop && (_jsx(SettingRow, { label: "Backup folder", children: _jsx("button", { type: "button", onClick: () => attempt(desktop.show_data_path("backups")), children: "Show folder" }) }));
69
+ const content = backup_folder ? _jsx(FolderBackups, { backups: backups, folder: backup_folder, data_name: data_name }) : _jsx(BackupSettings, { device: backups, data_name: data_name, on_restored: () => location.reload(), ...(show_folder ? { folder_row: show_folder } : {}) });
58
70
  sections.push({ id: "backups", heading: "Backups", hint, content });
59
71
  }
60
72
  return sections.length === 0 ? [] : [{ heading: host === "web" ? "Server" : "This device", sections }];
@@ -1,5 +1,7 @@
1
1
  #!/usr/bin/env node
2
2
  export declare const release_line = "apply from: \"../../node_modules/@x-tech-laboratories/x-app/config/android/release.gradle\"";
3
3
  export declare function apply_release_settings(app_folder: string): boolean;
4
+ export declare const network_security_config = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<!-- Servers need https; plain http is allowed only to this phone itself, which a computer reaches through `adb reverse` while testing. -->\n<network-security-config>\n <base-config cleartextTrafficPermitted=\"false\" />\n <domain-config cleartextTrafficPermitted=\"true\">\n <domain includeSubdomains=\"false\">localhost</domain>\n <domain includeSubdomains=\"false\">127.0.0.1</domain>\n </domain-config>\n</network-security-config>\n";
5
+ export declare function apply_network_security(app_folder: string): boolean;
4
6
  export type RunCapacitor = (app_folder: string, args: string[]) => void;
5
7
  export declare function prepare_android(app_folder: string, run?: RunCapacitor): string[];
@@ -6,8 +6,8 @@
6
6
  // Android page is built, since Capacitor copies that page in.
7
7
  // ── Imports ──────────────────────────────────────────────────────────────────
8
8
  import { spawnSync } from "node:child_process";
9
- import { existsSync, readFileSync, writeFileSync } from "node:fs";
10
- import { join, resolve } from "node:path";
9
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
10
+ import { dirname, join, resolve } from "node:path";
11
11
  import { write_app_icons } from "./app_icons.js";
12
12
  // ── Release settings ─────────────────────────────────────────────────────────
13
13
  // The line that applies X-App's release settings, from the app's own node_modules so it follows X-App's version.
@@ -21,6 +21,38 @@ export function apply_release_settings(app_folder) {
21
21
  writeFileSync(build_file, `${build.trimEnd()}\n\n// X-App's release settings: the build's version and, when the key is present, its signature.\n${release_line}\n`);
22
22
  return true;
23
23
  }
24
+ // ── Network security ─────────────────────────────────────────────────────────
25
+ // Servers need https; plain http goes only to the phone itself, which a computer reaches through `adb reverse` while
26
+ // testing. An app with a file of its own keeps it.
27
+ export const network_security_config = `<?xml version="1.0" encoding="utf-8"?>
28
+ <!-- Servers need https; plain http is allowed only to this phone itself, which a computer reaches through \`adb reverse\` while testing. -->
29
+ <network-security-config>
30
+ <base-config cleartextTrafficPermitted="false" />
31
+ <domain-config cleartextTrafficPermitted="true">
32
+ <domain includeSubdomains="false">localhost</domain>
33
+ <domain includeSubdomains="false">127.0.0.1</domain>
34
+ </domain-config>
35
+ </network-security-config>
36
+ `;
37
+ const security_attribute = 'android:networkSecurityConfig="@xml/network_security_config"';
38
+ // Writes the rule where the app has none and points the manifest's application at it, and says whether it changed either.
39
+ export function apply_network_security(app_folder) {
40
+ const main = join(app_folder, "android", "app", "src", "main");
41
+ const config_file = join(main, "res", "xml", "network_security_config.xml");
42
+ let changed = false;
43
+ if (!existsSync(config_file)) {
44
+ mkdirSync(dirname(config_file), { recursive: true });
45
+ writeFileSync(config_file, network_security_config);
46
+ changed = true;
47
+ }
48
+ const manifest_file = join(main, "AndroidManifest.xml");
49
+ const manifest = readFileSync(manifest_file, "utf8");
50
+ if (!manifest.includes("android:networkSecurityConfig=")) {
51
+ writeFileSync(manifest_file, manifest.replace(/<application\b/, `<application\n ${security_attribute}`));
52
+ changed = true;
53
+ }
54
+ return changed;
55
+ }
24
56
  const run_capacitor = (app_folder, args) => {
25
57
  const result = spawnSync("npx", ["cap", ...args], { cwd: app_folder, stdio: "inherit" });
26
58
  if (result.status !== 0)
@@ -37,6 +69,8 @@ export function prepare_android(app_folder, run = run_capacitor) {
37
69
  }
38
70
  if (apply_release_settings(app_folder))
39
71
  done.push("Applied X-App's release settings");
72
+ if (apply_network_security(app_folder))
73
+ done.push("Allowed plain http only to the phone itself");
40
74
  done.push(`Drew ${write_app_icons(app_folder).length} icons`);
41
75
  run(app_folder, ["sync", "android"]);
42
76
  done.push("Synced the page and plugins into the Android project");
@@ -0,0 +1,10 @@
1
+ #!/usr/bin/env node
2
+ export type RunProgram = (program: string, args: string[], input?: Buffer | string) => void;
3
+ export interface KeyPlan {
4
+ folder: string;
5
+ keystore: string;
6
+ password_file: string;
7
+ alias: string;
8
+ }
9
+ export declare function key_plan(app_folder: string, folder?: string, home?: string): KeyPlan;
10
+ export declare function make_release_key(plan: KeyPlan, run?: RunProgram): void;
@@ -0,0 +1,53 @@
1
+ #!/usr/bin/env node
2
+ // The `x-app-android-key [app folder]` command: an app's Android release key, made once and stored as the repository's
3
+ // secrets that X-App's `app-android` action signs with, without ever printing it. The key lives in
4
+ // ~/.local/share/<app>/signing, named after the app's package, and is never replaced, since Android installs an update
5
+ // only when it carries the same key. Run it inside the app's Android shell, which has keytool, with gh signed in.
6
+ // ── Imports ──────────────────────────────────────────────────────────────────
7
+ import { spawnSync } from "node:child_process";
8
+ import { randomBytes } from "node:crypto";
9
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
10
+ import { homedir } from "node:os";
11
+ import { join, resolve } from "node:path";
12
+ const run_program = (program, args, input) => {
13
+ const result = spawnSync(program, args, { input, stdio: [input === undefined ? "inherit" : "pipe", "inherit", "inherit"] });
14
+ if (result.error)
15
+ throw new Error(`${program} could not run: ${result.error.message}`);
16
+ if (result.status !== 0)
17
+ throw new Error(`${program} ${args[0] ?? ""} failed`);
18
+ };
19
+ // Where the app's key goes: its package's name in the user's data folder, unless a folder is given.
20
+ export function key_plan(app_folder, folder, home = homedir()) {
21
+ const { name } = JSON.parse(readFileSync(join(app_folder, "package.json"), "utf8"));
22
+ const signing = folder ?? join(home, ".local", "share", name, "signing");
23
+ return { folder: signing, keystore: join(signing, `${name}-release.p12`), password_file: join(signing, "keystore-password.txt"), alias: name };
24
+ }
25
+ // Makes the key with one random password for the keystore and the key, then sets the three secrets with gh; refuses a
26
+ // key already there, which is the app's for good.
27
+ export function make_release_key(plan, run = run_program) {
28
+ if (existsSync(plan.keystore))
29
+ throw new Error(`${plan.keystore} already exists; it is the app's permanent key, so it is never replaced`);
30
+ mkdirSync(plan.folder, { recursive: true, mode: 0o700 });
31
+ writeFileSync(plan.password_file, randomBytes(32).toString("base64"), { mode: 0o600 });
32
+ run("keytool", [
33
+ "-genkeypair", "-keystore", plan.keystore, "-storetype", "PKCS12", "-alias", plan.alias,
34
+ "-keyalg", "RSA", "-keysize", "4096", "-validity", "36500",
35
+ "-dname", "CN=X-Tech Laboratories, O=X-Tech Laboratories",
36
+ "-storepass:file", plan.password_file, "-keypass:file", plan.password_file,
37
+ ]);
38
+ run("gh", ["secret", "set", "ANDROID_KEYSTORE_BASE64"], readFileSync(plan.keystore).toString("base64"));
39
+ run("gh", ["secret", "set", "ANDROID_KEYSTORE_PASSWORD"], readFileSync(plan.password_file));
40
+ run("gh", ["secret", "set", "ANDROID_KEY_ALIAS"], plan.alias);
41
+ }
42
+ if (import.meta.main) {
43
+ try {
44
+ const plan = key_plan(resolve(process.argv[2] ?? "."), process.argv[3]);
45
+ make_release_key(plan);
46
+ console.info(`Saved the key in ${plan.folder} and uploaded it to GitHub.`);
47
+ console.info("Back up both files in that folder; losing them means no later build can install over this app.");
48
+ }
49
+ catch (error) {
50
+ console.error(error instanceof Error ? error.message : String(error));
51
+ process.exit(1);
52
+ }
53
+ }
package/dist/app_new.js CHANGED
@@ -74,7 +74,7 @@ function package_json(names, options) {
74
74
  "@types/react-dom",
75
75
  "@vitejs/plugin-react",
76
76
  "@vitest/coverage-v8",
77
- ...(options.desktop ? ["electron", "electron-vite"] : []),
77
+ ...(options.desktop ? ["electron", "electron-builder", "electron-vite"] : []),
78
78
  "jsdom",
79
79
  "oxlint",
80
80
  "typescript",
@@ -338,6 +338,12 @@ import { defineConfig } from "electron-vite";
338
338
  import { desktop_vite_config } from "@x-tech-laboratories/x-app/config/electron_vite";
339
339
 
340
340
  export default defineConfig(desktop_vite_config());
341
+ `,
342
+ "config/electron-builder.mjs": `// The desktop app's AppImage and Flatpak bundle, from X-App's preset.
343
+
344
+ import { electron_builder_config } from "@x-tech-laboratories/x-app/config/electron_builder";
345
+
346
+ export default electron_builder_config({ id: "${names.slug}", name: "${names.name}", app_id: "${names.app_id}", comment: "${names.name}" });
341
347
  `,
342
348
  }
343
349
  : {}),
@@ -394,7 +400,7 @@ function nix_files(names, options) {
394
400
  in
395
401
  {
396
402
  packages.default = x-app.lib.package pkgs app;${options.desktop ? "\n packages.desktop = x-app.lib.desktop_package pkgs app;" : ""}
397
- devShells.default = x-app.lib.shell pkgs app;${options.android ? "\n devShells.android = x-app.lib.android_shell nixpkgs system;" : ""}
403
+ devShells.default = x-app.lib.shell pkgs app;${options.android ? "\n devShells.android = x-app.lib.android_shell nixpkgs system;\n devShells.android-emulator = x-app.lib.android_emulator_shell nixpkgs system app;" : ""}
398
404
  }
399
405
  ) // {
400
406
  nixosModules.default = x-app.lib.module self app;
@@ -412,29 +418,49 @@ in
412
418
  `,
413
419
  };
414
420
  }
415
- // Every push to main builds the Android package once the tests pass, signed when the repository holds the release key,
416
- // and a version tag publishes it as a release.
421
+ // Every push to main builds the Android package once the tests pass, signed with the key x-app-android-key made.
417
422
  const android_job = `
418
423
  android:
419
424
  needs: ci
420
- if: github.event_name != 'pull_request'
425
+ if: github.event_name == 'push'
421
426
  runs-on: ubuntu-latest
422
- permissions:
423
- contents: write
424
427
  steps:
425
428
  - uses: x-tech-laboratories/X-App/.github/actions/app-android@main
426
429
  with:
430
+ release: push
427
431
  keystore-base64: \${{ secrets.ANDROID_KEYSTORE_BASE64 }}
428
432
  keystore-password: \${{ secrets.ANDROID_KEYSTORE_PASSWORD }}
429
433
  key-alias: \${{ secrets.ANDROID_KEY_ALIAS }}
430
434
  `;
435
+ // Every push to main builds the desktop app's AppImage and Flatpak bundle once the tests pass.
436
+ const linux_job = `
437
+ linux:
438
+ needs: ci
439
+ if: github.event_name == 'push'
440
+ runs-on: ubuntu-latest
441
+ steps:
442
+ - uses: x-tech-laboratories/X-App/.github/actions/app-linux@main
443
+ `;
444
+ // Each push to main is published as the latest release, v<version>.<run>, with every package the jobs above built.
445
+ function release_job(options) {
446
+ const needs = [...(options.android ? ["android"] : []), ...(options.desktop ? ["linux"] : [])];
447
+ return `
448
+ release:
449
+ needs: [${needs.join(", ")}]
450
+ runs-on: ubuntu-latest
451
+ permissions:
452
+ contents: write
453
+ steps:
454
+ - uses: x-tech-laboratories/X-App/.github/actions/app-release@main
455
+ `;
456
+ }
431
457
  function github_files(options) {
432
458
  return {
433
459
  ".github/workflows/ci.yml": `name: CI
434
460
 
435
461
  on:
436
462
  push:
437
- branches: [main]${options.android ? '\n tags: ["v*"]' : ""}
463
+ branches: [main]
438
464
  pull_request:
439
465
  branches: [main]
440
466
  workflow_dispatch:
@@ -452,7 +478,7 @@ jobs:
452
478
  - uses: x-tech-laboratories/X-App/.github/actions/app-nix@main
453
479
  with:
454
480
  targets: ./nix#default${options.desktop ? " ./nix#desktop" : ""}
455
- ${options.android ? android_job : ""}`,
481
+ ${options.android ? android_job : ""}${options.desktop ? linux_job : ""}${options.android || options.desktop ? release_job(options) : ""}`,
456
482
  ".github/workflows/dependabot-auto-merge.yml": `name: Dependabot auto-merge
457
483
 
458
484
  on: pull_request
@@ -0,0 +1,10 @@
1
+ export interface ElectronBuilderOptions {
2
+ id: string;
3
+ name: string;
4
+ app_id: string;
5
+ comment: string;
6
+ categories?: readonly string[];
7
+ link_scheme?: string;
8
+ copyright?: string;
9
+ }
10
+ export declare function electron_builder_config(options: ElectronBuilderOptions): Record<string, unknown>;
@@ -0,0 +1,43 @@
1
+ // The base app's electron-builder config: a desktop app's AppImage and Flatpak bundle for Linux outside Nix, built from
2
+ // electron-vite's out/ and the app's resources/. The Flatpak keeps its data in ~/.config/<id>, as the other builds do,
3
+ // so moving between them keeps the data, and may write the login entry that starts the app in the background.
4
+ // ── Config ───────────────────────────────────────────────────────────────────
5
+ export function electron_builder_config(options) {
6
+ const categories = options.categories ?? ["Utility"];
7
+ return {
8
+ appId: options.app_id,
9
+ productName: options.name,
10
+ executableName: options.id,
11
+ copyright: options.copyright ?? "X-Tech Laboratories",
12
+ directories: { output: "dist" },
13
+ files: ["out/main/**", "out/preload/**", "out/renderer/**", "resources/**", "package.json"],
14
+ ...(options.link_scheme ? { protocols: [{ name: `${options.name} link`, schemes: [options.link_scheme] }] } : {}),
15
+ linux: {
16
+ target: ["AppImage", "flatpak"],
17
+ category: categories[0],
18
+ icon: "resources/icon.png",
19
+ synopsis: options.comment,
20
+ desktop: { entry: { Name: options.name, Comment: options.comment, Categories: `${categories.join(";")};` } },
21
+ },
22
+ appImage: { artifactName: `${options.id}-\${arch}.AppImage` },
23
+ flatpak: {
24
+ artifactName: `${options.id}-\${arch}.flatpak`,
25
+ runtimeVersion: "25.08",
26
+ baseVersion: "25.08",
27
+ finishArgs: [
28
+ "--share=ipc",
29
+ "--share=network",
30
+ "--socket=x11",
31
+ "--socket=wayland",
32
+ "--device=dri",
33
+ "--talk-name=org.freedesktop.Notifications",
34
+ // VSCode's terminal exports this, which makes Electron run as bare node.
35
+ "--unset-env=ELECTRON_RUN_AS_NODE",
36
+ // The same data folder the other builds use, so switching between them keeps the data.
37
+ `--filesystem=xdg-config/${options.id}:create`,
38
+ // The login entry that starts the app in the background.
39
+ "--filesystem=xdg-config/autostart:create",
40
+ ],
41
+ },
42
+ };
43
+ }
@@ -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
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@x-tech-laboratories/x-app",
3
- "version": "0.114.1",
3
+ "version": "0.116.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": {
@@ -19,6 +19,7 @@
19
19
  ],
20
20
  "bin": {
21
21
  "x-app-android": "dist/app_android.js",
22
+ "x-app-android-key": "dist/app_android_key.js",
22
23
  "x-app-bundle-migrations": "dist/drizzle_migrations.js",
23
24
  "x-app-check": "dist/change_checks_cli.js",
24
25
  "x-app-icons": "dist/app_icons.js",
@@ -57,6 +58,7 @@
57
58
  "@sqlite.org/sqlite-wasm": "3.53.4-build2",
58
59
  "@vitejs/plugin-react": "^6.2.1",
59
60
  "@x-tech-laboratories/halon": "^0.31.0 || ^0.32.0 || ^0.33.0 || ^0.34.0 || ^0.35.0",
61
+ "electron-builder": "^26.18.0",
60
62
  "electron-vite": "^6.0.0",
61
63
  "fastify": "^5.12.7",
62
64
  "mermaid": "^11.0.0",
@@ -127,6 +129,9 @@
127
129
  "@x-tech-laboratories/halon": {
128
130
  "optional": true
129
131
  },
132
+ "electron-builder": {
133
+ "optional": true
134
+ },
130
135
  "electron-vite": {
131
136
  "optional": true
132
137
  },