@x-tech-laboratories/x-app 0.119.0 → 0.121.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.
Files changed (42) hide show
  1. package/README.md +21 -2
  2. package/dist/app/daemon.d.ts +7 -1
  3. package/dist/app/daemon.js +76 -8
  4. package/dist/app/define.d.ts +22 -1
  5. package/dist/app/define.js +34 -1
  6. package/dist/app/desktop.d.ts +13 -0
  7. package/dist/app/desktop.js +35 -3
  8. package/dist/app/host_tables.d.ts +20 -0
  9. package/dist/app/host_tables.js +91 -0
  10. package/dist/app/preload.js +5 -0
  11. package/dist/app/protocol.d.ts +29 -1
  12. package/dist/app/protocol.js +8 -1
  13. package/dist/app/remote_access.d.ts +17 -0
  14. package/dist/app/remote_access.js +85 -0
  15. package/dist/app/server.d.ts +12 -4
  16. package/dist/app/server.js +63 -14
  17. package/dist/app/services.d.ts +15 -0
  18. package/dist/app/web/android.d.ts +1 -1
  19. package/dist/app/web/android.js +9 -0
  20. package/dist/app/web/app_page.js +43 -6
  21. package/dist/app/web/hosts.d.ts +4 -2
  22. package/dist/app/web/hosts.js +33 -0
  23. package/dist/app/web/page.d.ts +3 -0
  24. package/dist/app/web/page.js +24 -4
  25. package/dist/app/web/portal.d.ts +14 -0
  26. package/dist/app/web/portal.js +115 -0
  27. package/dist/app/web/settings_page.d.ts +5 -1
  28. package/dist/app/web/settings_page.js +25 -6
  29. package/dist/change_checks.js +1 -1
  30. package/dist/github_targets.d.ts +12 -0
  31. package/dist/github_targets.js +90 -0
  32. package/dist/remote_access_protocol.d.ts +26 -0
  33. package/dist/remote_access_protocol.js +33 -0
  34. package/dist/server/github_webhook.d.ts +2 -12
  35. package/dist/server/github_webhook.js +2 -87
  36. package/dist/sql.d.ts +5 -0
  37. package/dist/sql.js +21 -0
  38. package/dist/web/react/remote_access_settings.d.ts +5 -0
  39. package/dist/web/react/remote_access_settings.js +55 -0
  40. package/dist/web/remote_daemon.d.ts +26 -0
  41. package/dist/web/remote_daemon.js +105 -0
  42. package/package.json +1 -1
package/README.md CHANGED
@@ -12,6 +12,7 @@ an app moves over by changing the package name in its imports and its `x-libs-*`
12
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. `take_data_change(database)` names the synced tables written since the last call for that connection (null on its first call and after a restore); the server and daemon send it with each change, so a page's `on_change(listener)` hears `{ tables }` and fetches only what it shows from them, or everything on null. `synced_theme` keeps the light, dark or system theme as a synced setting, `theme`, so every device shows the one picked last. |
13
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
+ | `app/host_tables`, `app/remote_access`, `remote_access_protocol` | What an app's hosts answer themselves beside its data calls, such as files a computer keeps or programs it runs: `define_app({ host_tables })` names each table with its `api`, the `hosts` that answer it (`"server"`, `"desktop"`) and who reaches it from the network or MCP (`network`: `"admin"` unless set, `"any"`, or `"none"` for this computer's own window alone); the services hand in each table's `methods`, and `elsewhere`, the same calls refusing what only this computer's user may do, for the network and MCP. Every host serves them under `/api/<table>/<call>` (503 until the services started), `/api/host/get_host_abilities` says what the viewer reaches (`admin`, `tables`), MCP and OpenAPI offer them beside the data calls, and the desktop bridges them, a `"none"` table staying on this computer's daemon. `remote_access: true` is the daemon's "Let other devices connect" for its own calls (`create_remote_access`: `remote.json` and the admins in `remote-admins`, mode 0600, https from a certificate and key, listening only while on, changed only over the socket), on `build_server` with the accounts in `accounts.db`, moved there once from the data's own file; `read_remote_access`, `remote_access_problem`. |
15
16
  | `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
17
  | `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
18
  | `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`. |
@@ -45,7 +46,7 @@ an app moves over by changing the package name in its imports and its `x-libs-*`
45
46
  | `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. |
46
47
  | `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. |
47
48
  | `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. |
48
- | `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`. |
49
+ | `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`; `tidy_database` refreshes the query planner's statistics and, once a tenth of the file (or the `free_share` given) is empty pages, vacuums it smaller and empties the write-ahead log, leaving a rewrite another connection's write holds up for next time. The base app tidies its database on opening, after a restore and every `tidy_every_ms` (a day) on the server and the desktop daemon, and on opening and on coming back after a day on a phone. |
49
50
  | `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. |
50
51
  | `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. |
51
52
  | `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. |
@@ -68,6 +69,7 @@ an app moves over by changing the package name in its imports and its `x-libs-*`
68
69
  | `phone_certificates` | `phone_certificates()`: the page's certificate calls on a phone, answered by X-App's Android plugin `XLibsCertificates`, which `cap sync` adds by itself: it reads a server's certificate and what is wrong with it, keeps the ones the user trusts for their own host and fingerprint, and installs a WebView client that lets the page's requests through to them, so `SyncSettings`, `SyncCertificatePrompt` and `TrustedCertificates` work on a phone as on the desktop. Forgetting one holds from the app's next start, since the WebView keeps a connection it already opened. An app that sets its own WebView client replaces that one. |
69
70
  | `phone_backups` | `phone_backups`: a phone app's `backups` in a folder the user picks once in its storage, where file managers and sync apps reach them, through X-App's Android plugin `XLibsBackupFolder`, which `cap sync` adds by itself; `restore` backs up first, swaps the phone database's bytes and saves, `folder_name` and `choose_folder` for the settings row, and daily backups wait quietly until a folder is picked. |
70
71
  | `phone_notices` | `keep_phone_notices`: notices handed to a phone ahead of time through Capacitor's local notifications, the app passing its own `LocalNotifications`, since a phone has no daemon; `refresh` takes back every pending notice and sets the soonest 64 of the next 14 days again, `ask_permission` asks once, `show` puts a notice up at once with no alarm (`isExactNotification: false`), so a notice for now never needs Android's exact-alarm leave or opens its settings screen, `exact: false` lets the notices set ahead ring inexactly too, and a tap hands the notice's `extra` back, such as a link to open. `notice_id` names a key as Android's number. |
72
+ | `web/remote_daemon` | A page's calls to a daemon or server on another computer with this device's token, as a phone that keeps no data makes them: `call_remote` (a refusal in the host's words, a 401 as `LoginNeeded`, no host chosen or out of reach in plain words), `remote_table` for every call under a path, and `follow_remote` reading the event stream over `fetch`, since EventSource sends no token, reconnecting until stopped (`parse_remote_event`). |
71
73
  | `phone_service` | `phone_service`: work a phone app keeps doing while it is closed, such as staying reachable, in an Android foreground service run by X-App's plugin `XLibsForegroundService`, which `cap sync` adds by itself: the service loads the app's own worker page (such as `worker.html` from its page files) in a WebView it owns, so the work outlives the app's window, a killed process (Android starts it again) and, with `start_at_boot`, a reboot; `start`, `stop`, `is_running`, `post` and `on_message` for the page, and `worker_host` for the worker's side, the messages crossing as JSON. The app declares the service and the boot receiver in its own manifest, with the `connectedDevice` foreground service permissions, as the module's opening comment shows, so no other app gets them. |
72
74
  | `phone_sockets` | `phone_sockets()`: UDP and TCP sockets for a `phone_service` worker, answered by X-App's Android side: `udp_open` (with `broadcast`, holding Android's multicast lock), `tcp_listen`, `tcp_connect` and `list_interfaces`; a TCP socket reads nothing until `read_line` takes one line or `start_reading` everything after, so `start_tls` can follow plain text in either TLS role, as KDE Connect's identity line does, with the app's PEM certificate and key, letting any peer through and handing back its certificate for the worker to pin; `pause` and `resume` for a slow reader, and `write` settling once sent. Events that arrive before a listener are kept for it. Needs `CHANGE_WIFI_MULTICAST_STATE` and `WAKE_LOCK` in the app's manifest; each event keeps the phone awake a few seconds so the worker can answer. |
73
75
  | `app/item_history`, `app/web/item_history` | A history for each kind of item made of rows across tables, such as a workout with its exercises and sets: `item_history_feature(kinds)` keeps each kind's versions (an `ItemLevel` list read by `read_snapshot` and put back by `apply_snapshot`, a deleted item coming back whole) and adds `list_item_history`, `list_recent_changes` and `restore_item_version` with their specs; on the page, `HistoryView` lists the latest changes, `HistoryButton` and `open_item_history` open one item's versions, each restorable after a confirm. |
@@ -129,6 +131,7 @@ an app moves over by changing the package name in its imports and its `x-libs-*`
129
131
  | `server/forge_webhook` | A forge's pushes: `is_signed` for GitHub's HMAC, Gitea's and Forgejo's signatures, a bearer token or GitLab's token; `event_of`, `parse_payload` and `read_push`, which names the branch and the repository URLs through the app's own normaliser; `AddressLockout` for an address that keeps failing to sign; `SeenDeliveries`, whose `is_replay` notices a signed body sent again within a day; `Debouncer` so a burst of pushes starts one run; `register_webhook_route`, which keeps the raw body the signature covers. |
130
132
  | `server/poller`, `server/runs` | `CyclePoller`: each watched item's cycle on its own timer, every `interval` or every `job_poll` while busy, with `refresh` and `soon`; `follow_run`: a long run's new output copied to a sink and the run finished once it has ended, with `describe` and `translate` hooks, an unreachable agent, a malformed or stuck poll reply, or a failing sink leaving it as `unreachable` to be followed again and only an agent that no longer knows the run ending it early, each follow taking at most `most_polls_per_follow` polls and about `most_output_per_follow_in_bytes`, and a `translate` that throws keeping the raw output. |
131
133
  | `server/github_webhook` | GitHub's webhooks on `forge_webhook`: `create_github_receiver` is a `register_webhook_route` receive that counts a delivery only when signed with X-Hub-Signature-256 under the app's secret (never a bearer token or another forge's header), turns away an address that keeps failing, answers a replayed delivery id without passing it on again, answers a ping and passes on only the repository and the pull requests, branches and issues an event names (`targets_of`, for `github_target_events`), each checked for shape and a fork's branch left out; `read_targets` for stored ones, `delivery_id_of`, `repository_of`, `is_repository_name`, `read_public_url` and `payload_url_of`. |
134
+ | `github_targets` | GitHub's webhook payloads as any part of an app reads them, in a page, a phone or Node: `targets_of(event, payload)` (the repository and the pull requests, branches and issues it names, each list at most 50, or null), `read_targets` for targets as stored, `repository_of`, `delivery_id_of`, `is_repository_name` and `github_target_events`; `server/github_webhook` passes them on. |
132
135
  | `server/events` | `EventStream`: server-sent events with a client id per page, a heartbeat, `announce_change(except_client_id)` so the page that made a change is not told, nameless or named events to all or chosen clients, headers set before the stream opens (such as `register_open_cors`'s) sent with it, and every stream ended with the app; `leading_cooldown` sends the first change at once and a burst's rest once per cooldown. |
133
136
  | `server/call_table` | `register_call_table`: a table of calls served as POST `<path>/<method>` with the arguments as a JSON list, as a desktop app's daemon and a web server both answer them, and by name as a JSON object for the calls whose argument names `params` gives, such as the app's `api_spec` (`api_spec`'s `NamedParams` is all it needs); a name the table lacks (its prototype's included) is refused, every answer goes as JSON so a string stays a string, a read is sent uncached, and `on_change` runs after any call `is_read_only` does not pass, with the caller's client id. |
134
137
  | `server/leases` | `Leases`: what a page holds open while it shows something costly, such as fast polling of a running job while its log is open, each lease ending when closed or once it goes unrenewed for a while. |
@@ -162,6 +165,7 @@ an app moves over by changing the package name in its imports and its `x-libs-*`
162
165
  | `web/react/layout`, `badges`, `states` | `PageHeading` with a subtitle, icon, banner, actions and a `level` for inside dialogs and panels; panels (`Section`, with a `level` for one inside a dialog or under another heading), `GroupSections`, a panel per group from `group_items` headed by its name and count, facts, tiles, cards, tabs, `Crumbs` with chevrons between steps that link, run a function or mark where the reader is, `PathText` for a path shown with the same chevrons, steppers, `FormRow` for a form's labelled fields, `FormGroup` folding part of a form under a summary line such as "More options", `SettingsPage` with an `Outline` beside its sections, settings rows, `RowActions` and `moved` for ordered lists, `SelectionBar` for picked rows, their count with its thousands separated; badges, `StateBadge` naming each state's text and tone and `ToneBadge` showing the state's own name in its tone, chips in an item's own colour, dashed or removable, `ColorDot` and `StatusPill`, a state dot with text and an action; `use_resource` with its `status` (idle until `enabled`, loading, loaded, failed), a `watch` that reloads it quietly (bumps during a load fold into one load after it), and its loading states, `Loaded` going by the status so a null result shows its `empty` slot or the children. |
163
166
  | `web/react/sync_settings`, `backup_settings` | The settings rows every device shows: `SyncSettings`, the sync status, this device with its id and where others reach it, a pairing code to show when they can, each paired device with how it was last reached and Remove after a confirm, and a field to enter another device's code; `SyncButton`, the same status as a sidebar row with the changes waiting, syncing on a click or opening the settings when sync failed or no device is paired, and shown even then; `BackupSettings`, back up now, the daily schedule, and each backup to restore or delete after a confirm. |
164
167
  | `web/react/connections` | `ConnectionSettings`: the Connections section of Settings, every daemon the app can talk to with the one in use marked Connected, Connect to switch, Rename and Remove (after a confirm) for daemons on other hosts, and a form to add one by address, name and password, asking for the code when the daemon does and offering to trust a certificate the device refuses given `certificates`. |
168
+ | `web/react/remote_access_settings` | `RemoteAccessSettings`: "Let other devices connect" for a desktop daemon, with its state (listening where, or why not), address, port, https certificate and key files, Save, and the admins other devices sign in as, added with a password of 10 characters or more and removed after asking; `reach` words what they can do once in. The base app shows it under Settings → Other devices. |
165
169
  | `web/react/certificates` | `CertificateDialog`: what is wrong with a server's certificate in plain words, the certificate itself with its fingerprint, and Trust or Don't connect; `offer_certificate_trust` and `ask_to_trust_certificate` open it from anywhere, `with_certificate_prompt` wraps a fetch to ask and retry once, `SyncCertificatePrompt` asks whenever syncing with a paired device's https address fails over its certificate, and `TrustedCertificates` lists them to forget. |
166
170
  | `web/react/time` | `Age`: a time as how long ago, with the full stamp on hover; `use_now`, the time read again each minute; `use_countdown`, a countdown on a wall-clock deadline, so a page that slept shows the time really left, with start, stop, pause, resume and extend and a callback once at zero. |
167
171
  | `web/accounts` | `create_accounts_client`: the page's calls to `server/account_sign_in`, from the page itself or, given the server's address as `base`, from a desktop or phone app, which signs in with `sign_in_device` and keeps the token; `SignInRefused` says when only the code is missing; `pref(key)` and `set_pref(key, value, { keepalive })` read and write the signed-in user's own preferences (`AccountPref`). |
@@ -243,6 +247,21 @@ void render_app({ app, pages: [{ id: "plan", label: "Plan", view: () => <PlanVie
243
247
 
244
248
  A change an app needs in the base goes into the base, so no app keeps a copy of a base file.
245
249
 
250
+ An app whose work needs a computer, such as one that runs programs on checkouts, adds to that:
251
+
252
+ - **Host tables**: `host_tables: { stages: { hosts: ["server", "desktop"], api: stages_api } }` names calls the hosts
253
+ answer themselves; the services return `tables: { stages: { methods, elsewhere } }`. The page reaches them with
254
+ `host_table("stages")`, null where the host it works on does not answer them or does not let its viewer.
255
+ - **Notices**: `context.notify({ kind, title, body, key, url })` from the services; the desktop daemon shows it where
256
+ `notify_<kind>` in `desktop_settings` is on, and every window and phone working on that host from elsewhere shows it
257
+ by its own switch.
258
+ - **Other devices**: `remote_access: true` lets the daemon serve its calls and host tables on the network, and
259
+ `phone: "portal"` makes the phone a window onto a host chosen under Connections, keeping no data, its notices shown
260
+ through `phone_notifications` (Capacitor's `LocalNotifications`).
261
+ - **Routes**: `run_server(app, { routes })` and `run_daemon(app, env, { routes })` take routes of the app's own, such as
262
+ a webhook's, with their `open_paths`; `services().own` holds what they need. `run_desktop`'s `daemon_env` adds to the
263
+ daemon's environment, and the desktop bridge's `pick_folder` asks for a folder.
264
+
246
265
  The rest of an app's files are short calls into X-App too:
247
266
 
248
267
  - **Configs** sit in the app's `config/` folder: `tsconfig.<target>.json` extends `tsconfig.base.json` and
@@ -256,7 +275,7 @@ The rest of an app's files are short calls into X-App too:
256
275
  An app with git dependencies names each lock entry's https URL in `git_dependencies`, which the packages fetch and
257
276
  copy in, and `link_scheme`, such as `"codex"`, makes the desktop entry open its links; `desktop_path`, such as
258
277
  `pkgs: [ pkgs.libnotify ]`, puts programs the desktop app runs on its PATH, and `state_name` keeps an older service's
259
- data folder `/var/lib/<state_name>`; the desktop wrapper sets
278
+ data folder `/var/lib/<state_name>`, and `server_config`, such as `dir: { stages_folder = "${dir}/stages"; }`, adds the app's own keys to the server's config file; the desktop wrapper sets
260
279
  `<PREFIX>_LAUNCHER` so the login entry runs the installed command. `android_emulator_shell nixpkgs system app` adds an
261
280
  Android 36 emulator to the Android shell, with `<name>-emulator` to start it and `<name>-emulator-install` to build
262
281
  and open the app on it, never on a connected phone.
@@ -1,5 +1,6 @@
1
1
  import type { App } from "./define.ts";
2
- import { type StartServices } from "./services.ts";
2
+ import { type AppNotice } from "./protocol.ts";
3
+ import { type AppRoutes, type StartServices } from "./services.ts";
3
4
  export interface DaemonOptions {
4
5
  database_path: string;
5
6
  socket_path: string;
@@ -10,6 +11,9 @@ export interface DaemonOptions {
10
11
  services?: StartServices;
11
12
  declared_file?: string;
12
13
  icon_path?: string | null;
14
+ routes?: AppRoutes;
15
+ web_folder?: string;
16
+ show_notice?: (notice: AppNotice) => void;
13
17
  }
14
18
  export interface Daemon {
15
19
  shut_down: () => Promise<void>;
@@ -17,4 +21,6 @@ export interface Daemon {
17
21
  export declare function start_daemon(app: App, options: DaemonOptions): Promise<Daemon | null>;
18
22
  export declare function run_daemon(app: App, env?: NodeJS.ProcessEnv, extra?: {
19
23
  services?: StartServices;
24
+ routes?: AppRoutes;
25
+ web_folder?: URL;
20
26
  }): Promise<void>;
@@ -5,7 +5,11 @@
5
5
  import { existsSync, readFileSync, writeFileSync } from "node:fs";
6
6
  import { hostname } from "node:os";
7
7
  import { dirname, join } from "node:path";
8
+ import { DatabaseSync } from "node:sqlite";
9
+ import { fileURLToPath } from "node:url";
8
10
  import fastify from "fastify";
11
+ import { Notifier } from "../agent/desktop_notify.js";
12
+ import { AccountStore, holds_accounts, move_accounts } from "../server/account_store.js";
9
13
  import { create_certificate_trust } from "../certificates.js";
10
14
  import { create_local_mcp } from "../electron/mcp.js";
11
15
  import { DaemonRunningError, daemon_socket_path, listen_on_socket } from "../local_daemon.js";
@@ -15,9 +19,11 @@ import { register_error_replies, register_lenient_json_body } from "../server/re
15
19
  import { file_sync_storage } from "../sync_file_storage.js";
16
20
  import { create_sync_peer, sync_device_methods } from "../sync_peer.js";
17
21
  import { keep_listening_for_peers } from "../sync_peer_listening.js";
22
+ import { mcp_tools, register_host_tables } from "./host_tables.js";
23
+ import { notice_event, notice_is_on, read_desktop_settings } from "./protocol.js";
24
+ import { create_remote_access } from "./remote_access.js";
18
25
  import { declared_file_of, no_services, side_databases } from "./services.js";
19
- import { read_desktop_settings } from "./protocol.js";
20
- import { call_body_limit, data_change_text, open_app_database, register_app_calls, watch_outside_changes } from "./server.js";
26
+ import { build_server, call_body_limit, data_change_text, open_app_database, register_app_calls, watch_outside_changes } from "./server.js";
21
27
  // ── Daemon ───────────────────────────────────────────────────────────────────
22
28
  // Answers on the socket and starts sync; null when another daemon on the same database already answers.
23
29
  export async function start_daemon(app, options) {
@@ -29,6 +35,8 @@ export async function start_daemon(app, options) {
29
35
  const opened = open_app_database(app, database_path, join(profile, "backups"));
30
36
  // Every window's event stream, told when the data changed or sync's status moved.
31
37
  const changes = new EventStream({ change_data: data_change_text(app, opened.database) });
38
+ // The app's services once started, which answer its host tables and hear of sync's changes.
39
+ let services = no_services;
32
40
  // Server certificates the user trusted, such as a home server's self-signed one, handed to Node's own fetch.
33
41
  const certificates = create_certificate_trust({ file: join(profile, "trusted-certificates.json"), use_in_node: true });
34
42
  // Off until "Let other devices connect" is turned on; then other devices reach this computer's sync on its port.
@@ -41,7 +49,10 @@ export async function start_daemon(app, options) {
41
49
  storage: file_sync_storage({ file: join(profile, "sync-peers.json"), back_up_before_replace: opened.back_up }),
42
50
  device_name: `${app.name} on ${hostname()}`,
43
51
  addresses: () => listening.addresses(),
44
- on_remote_change: () => changes.announce_change(),
52
+ on_remote_change: () => {
53
+ changes.announce_change();
54
+ services.after_remote_change?.();
55
+ },
45
56
  on_status: (status) => changes.send(JSON.stringify(status), { event: "sync_status" }),
46
57
  });
47
58
  // ── Desktop settings ───────────────────────────────────────────────
@@ -58,18 +69,61 @@ export async function start_daemon(app, options) {
58
69
  stop_daemon: () => void setTimeout(() => void shut_down(), 0),
59
70
  set_window_in_front: (in_front) => void (window_in_front = in_front === true),
60
71
  };
72
+ const services_now = () => services;
73
+ // This computer's own AI clients reach the host tables too, as callers from elsewhere do, so what only this
74
+ // computer's user may change stays refused.
75
+ const local_tools = mcp_tools(app, { kind: "desktop", from_network: true, is_admin: () => true }, services_now, opened.database, () => changes.announce_change());
61
76
  // Off until turned on in Settings; a change made through it reaches the open windows and syncs like any other.
62
77
  const local_mcp = app.local_mcp
63
78
  ? create_local_mcp({
64
79
  name: app.id,
65
80
  version: app.version,
66
81
  instructions: app.instructions,
67
- api: app.mcp.api,
82
+ api: local_tools.api,
68
83
  is_read_only: app.is_read_only,
69
84
  page_only: app.mcp.page_only,
70
85
  settings_file: join(profile, "mcp.json"),
71
86
  default_port: app.local_mcp.default_port,
72
- call: (method, args) => app.mcp.call(opened.database, () => changes.announce_change(), method, args),
87
+ call: (method, args) => local_tools.call(method, args),
88
+ })
89
+ : null;
90
+ // ── Notices ────────────────────────────────────────────────────────
91
+ const notifier = new Notifier({ app_name: app.name, icons: options.icon_path ? { app: options.icon_path } : {}, on_error: (message) => console.error(`${app.id} notifications: ${message}`) });
92
+ const show_notice = options.show_notice ?? ((notice) => void notifier.show({ title: notice.title, body: notice.body, key: notice.key, ...(notice.url ? { url: notice.url } : {}), icon: "app" }));
93
+ // Shown here where this computer's switch for its kind is on, and sent to every window, for those working on this
94
+ // daemon from another computer to show there.
95
+ function notify(notice) {
96
+ if (notice_is_on(notice.kind, read_desktop()))
97
+ show_notice(notice);
98
+ changes.send(JSON.stringify(notice), { event: notice_event });
99
+ }
100
+ // ── Other devices ──────────────────────────────────────────────────
101
+ // Accounts that sign other devices in are a file of their own beside the data, as on the server.
102
+ const accounts_database = app.remote_access ? new DatabaseSync(join(profile, "accounts.db")) : null;
103
+ // An older version kept them in the data's own file; they move out once, after a backup of the file as it was.
104
+ if (accounts_database && holds_accounts(opened.database()) && !holds_accounts(accounts_database)) {
105
+ await opened.back_up();
106
+ move_accounts(opened.database(), accounts_database);
107
+ }
108
+ // The daemon runs as out/main/daemon.js, beside the desktop app's built page.
109
+ const web_folder = options.web_folder ?? join(dirname(process.argv[1] ?? "."), "../renderer");
110
+ // Off until turned on; then other devices sign in as an admin this computer added and reach the same calls and the
111
+ // host tables but those kept to this computer.
112
+ const remote = accounts_database
113
+ ? create_remote_access({
114
+ profile,
115
+ default_port: app.ports.server,
116
+ build: (admins, https) => build_server(app, {
117
+ database: opened.database,
118
+ accounts: new AccountStore({ database: accounts_database, app_name: app.name, declared: admins, ...(app.token_prefix ? { token_prefix: app.token_prefix } : {}) }),
119
+ web_folder,
120
+ changes,
121
+ backup_methods: opened.backup_methods,
122
+ kind: "desktop",
123
+ services: services_now,
124
+ ...(options.routes ? { routes: options.routes } : {}),
125
+ ...(https ? { https } : {}),
126
+ }),
73
127
  })
74
128
  : null;
75
129
  // ── Calls ──────────────────────────────────────────────────────────
@@ -89,16 +143,21 @@ export async function start_daemon(app, options) {
89
143
  if (local_mcp)
90
144
  register_call_table(api, "/local_mcp", local_mcp.methods, { is_read_only });
91
145
  register_call_table(api, "/daemon", daemon_methods, { is_read_only, on_change: tell_others });
146
+ if (remote)
147
+ register_call_table(api, "/remote", remote.methods, { is_read_only });
148
+ // This computer's own window reaches every host table, those kept to it included.
149
+ const reach = { kind: "desktop", from_network: false, is_admin: () => true };
150
+ register_host_tables(api, app, reach, services_now, changes);
92
151
  }, { prefix: "/api" });
93
152
  // ── Lifecycle ──────────────────────────────────────────────────────
94
153
  let stopping = null;
95
154
  let unused_timer;
96
155
  const sides = side_databases(database_path);
97
- let services = no_services;
98
156
  function shut_down() {
99
157
  stopping ??= (async () => {
100
158
  clearInterval(unused_timer);
101
159
  stop_watching();
160
+ await remote?.stop();
102
161
  await services.stop();
103
162
  sync.stop();
104
163
  await local_mcp?.stop();
@@ -106,6 +165,7 @@ export async function start_daemon(app, options) {
106
165
  await listening.stop();
107
166
  sides.close_all();
108
167
  opened.close();
168
+ accounts_database?.close();
109
169
  options.on_stopped();
110
170
  })();
111
171
  return stopping;
@@ -116,6 +176,7 @@ export async function start_daemon(app, options) {
116
176
  catch (error) {
117
177
  await daemon.close();
118
178
  opened.close();
179
+ accounts_database?.close();
119
180
  // Another daemon on this database got there first, which is all that was asked for.
120
181
  if (error instanceof DaemonRunningError)
121
182
  return null;
@@ -135,14 +196,21 @@ export async function start_daemon(app, options) {
135
196
  plugins_folder: join(profile, "plugins"),
136
197
  declared_file: options.declared_file ?? `/etc/${app.id}/declared.json`,
137
198
  announce: (client_id) => changes.announce_change(client_id),
199
+ wrote: () => {
200
+ app.record_writes(opened.database());
201
+ changes.announce_change();
202
+ },
138
203
  emit: (event, data) => changes.send(JSON.stringify(data), { event }),
139
204
  side_database: sides.open,
140
205
  back_up: opened.back_up,
141
206
  window_in_front: () => window_in_front,
142
207
  icon_path: options.icon_path ?? null,
208
+ notify,
143
209
  });
144
- opened.on_restore({ before: () => services.before_restore?.(), after: () => services.after_restore?.() });
145
210
  }
211
+ // Devices signed in from elsewhere follow the restored data too.
212
+ opened.on_restore({ before: () => services.before_restore?.(), after: () => (services.after_restore?.(), void remote?.restart()) });
213
+ await remote?.restart();
146
214
  // Without "Keep running in the background", the daemon stops a while after its last window has gone.
147
215
  let unused_since = Date.now();
148
216
  unused_timer = setInterval(() => {
@@ -165,7 +233,7 @@ export async function run_daemon(app, env = process.env, extra = {}) {
165
233
  // A run on another database has a socket of its own.
166
234
  const socket_path = env[`${app.env_prefix}_SOCKET`] || daemon_socket_path({ app: app.id, data_file: database_path });
167
235
  try {
168
- const daemon = await start_daemon(app, { database_path, socket_path, on_stopped: () => process.exit(0), declared_file: declared_file_of(app, env), icon_path: env[`${app.env_prefix}_ICON`] ?? null, ...extra });
236
+ const daemon = await start_daemon(app, { database_path, socket_path, on_stopped: () => process.exit(0), declared_file: declared_file_of(app, env), icon_path: env[`${app.env_prefix}_ICON`] ?? null, ...(extra.services ? { services: extra.services } : {}), ...(extra.routes ? { routes: extra.routes } : {}), ...(extra.web_folder ? { web_folder: fileURLToPath(extra.web_folder) } : {}) });
169
237
  // Another daemon on this database got there first, which is all that was asked for.
170
238
  if (!daemon)
171
239
  process.exit(0);
@@ -12,7 +12,8 @@ import { type SettingSpec, type SettingsMethods, type SettingsStore, type Settin
12
12
  import { type MigrationStep, type SqlDatabase } from "../sql.ts";
13
13
  import { type SyncedTable } from "../sync_engine.ts";
14
14
  import { type PeerListeningMethods, type SyncDeviceMethods, type SyncStatus } from "../sync_protocol.ts";
15
- import { type DataChange, type DesktopMethods, type DesktopSettingSpec } from "./protocol.ts";
15
+ import { type RemoteAccessMethods } from "../remote_access_protocol.ts";
16
+ import { type DataChange, type DesktopMethods, type DesktopSettingSpec, type HostAbilityMethods } from "./protocol.ts";
16
17
  export type StoreMethod = (database: SqlDatabase, ...args: never[]) => unknown;
17
18
  export type KeptHistory = Pick<History<unknown>, "synced_table" | "install" | "forget_touched" | "record" | "prune"> & Partial<Pick<History<unknown>, "drop_triggers">>;
18
19
  export interface Feature<Methods extends Record<string, StoreMethod> = Record<string, StoreMethod>> {
@@ -28,6 +29,13 @@ export interface Feature<Methods extends Record<string, StoreMethod> = Record<st
28
29
  }
29
30
  export declare function define_feature<Methods extends Record<string, StoreMethod>>(feature: Feature<Methods>): Feature<Methods>;
30
31
  export declare function is_read_only(method: string): boolean;
32
+ export type HostKind = "server" | "desktop";
33
+ export interface HostTable<Methods = Record<string, (...args: never[]) => unknown>> {
34
+ api: ApiSpec<Methods>;
35
+ hosts: readonly HostKind[];
36
+ network?: "admin" | "any" | "none";
37
+ }
38
+ declare const host_table_route: (name: string) => string;
31
39
  type UnionToIntersection<Union> = (Union extends unknown ? (value: Union) => void : never) extends (value: infer Both) => void ? Both : never;
32
40
  type Bound<Methods> = {
33
41
  [Name in keyof Methods]: Methods[Name] extends (database: SqlDatabase, ...args: infer Args) => infer Result ? (...args: Args) => Result : never;
@@ -68,6 +76,9 @@ export interface AppOptions<Features extends readonly Feature[]> {
68
76
  default_port: number;
69
77
  };
70
78
  synced_theme?: boolean;
79
+ host_tables?: Readonly<Record<string, HostTable>>;
80
+ remote_access?: boolean;
81
+ phone?: "device" | "portal";
71
82
  }
72
83
  export declare const base_setting_defaults: {
73
84
  history_days: number;
@@ -96,6 +107,9 @@ export interface AppBridges<Methods extends Record<keyof Methods, (...args: neve
96
107
  connections: Bridge<ConnectionMethods>;
97
108
  local_mcp: Bridge<LocalMcpMethods>;
98
109
  events: EventsBridge<AppEvents>;
110
+ host: Bridge<HostAbilityMethods>;
111
+ remote_access: Bridge<RemoteAccessMethods>;
112
+ host_tables: Readonly<Record<string, Bridge<Record<string, (...args: never[]) => unknown>>>>;
99
113
  }
100
114
  export declare function define_app<const Features extends readonly Feature[]>(options: AppOptions<Features>): {
101
115
  id: string;
@@ -130,6 +144,8 @@ export declare function define_app<const Features extends readonly Feature[]>(op
130
144
  default_port: number;
131
145
  };
132
146
  synced_theme?: boolean;
147
+ remote_access?: boolean;
148
+ phone?: "device" | "portal";
133
149
  features: readonly Feature<Record<string, StoreMethod>>[];
134
150
  settings_store: SettingsStore;
135
151
  setting_defaults: Readonly<import("../settings.ts").Settings>;
@@ -164,6 +180,7 @@ export declare function define_app<const Features extends readonly Feature[]>(op
164
180
  is_read_only: typeof is_read_only;
165
181
  page_only: PageOnlyCalls;
166
182
  bind_methods: (database: () => SqlDatabase, on_change: () => void, caller?: Caller) => Bound<SettingsMethods & UnionToIntersection<Features[number]["methods"]>>;
183
+ record_writes: (database: SqlDatabase) => void;
167
184
  mcp: {
168
185
  api: ApiSpec<Record<string, StoreMethod>>;
169
186
  page_only: PageOnlyCalls;
@@ -174,6 +191,10 @@ export declare function define_app<const Features extends readonly Feature[]>(op
174
191
  adopt_backup_schedule: (database: SqlDatabase, saved: unknown) => void;
175
192
  backup_methods: (kept: Restorable, database: () => SqlDatabase, check_schedule: () => void) => BackupMethods;
176
193
  bridges: AppBridges<Bound<SettingsMethods & UnionToIntersection<Features[number]["methods"]>>>;
194
+ host_tables: Readonly<Record<string, HostTable<Record<string, (...args: never[]) => unknown>>>>;
195
+ tables_on: (kind: HostKind, from_network: boolean) => string[];
196
+ table_of_call: (method: string, kind: HostKind) => string | null;
197
+ host_table_path: typeof host_table_route;
177
198
  };
178
199
  type ErasedCalls = any;
179
200
  export type App = Omit<ReturnType<typeof define_app<readonly Feature[]>>, "bridges" | "bind_methods" | "api_spec" | "method_names"> & {
@@ -16,7 +16,8 @@ import { migrate } from "../sql.js";
16
16
  import { create_sync_engine } from "../sync_engine.js";
17
17
  import { backup_method_names } from "../backups.js";
18
18
  import { peer_listening_method_names, sync_device_method_names } from "../sync_protocol.js";
19
- import { desktop_method_names } from "./protocol.js";
19
+ import { remote_access_method_names } from "../remote_access_protocol.js";
20
+ import { desktop_method_names, host_ability_method_names } from "./protocol.js";
20
21
  export function define_feature(feature) {
21
22
  return feature;
22
23
  }
@@ -24,6 +25,8 @@ export function define_feature(feature) {
24
25
  export function is_read_only(method) {
25
26
  return /^(list|get|search|lookup|export)_/.test(method);
26
27
  }
28
+ // The path a host table's calls are posted under, such as /api/stages/.
29
+ const host_table_route = (name) => `/api/${name}/`;
27
30
  // The settings every app keeps: how long its history reaches back, and this device's backup schedule.
28
31
  export const base_setting_defaults = {
29
32
  // How many days of changes the history keeps, each item keeping its newest version; 0 keeps them all.
@@ -166,6 +169,15 @@ export function define_app(options) {
166
169
  });
167
170
  return Object.fromEntries(bound);
168
171
  }
172
+ // After the app's own work wrote to the database outside a call, such as a job's progress: the features catch up and
173
+ // the versions are recorded, as after a call that writes.
174
+ function record_writes(database) {
175
+ for (const feature of features)
176
+ feature.after_write?.(database);
177
+ for (const history of histories)
178
+ history.record(database);
179
+ prune_daily(database);
180
+ }
169
181
  // What MCP offers: the app's own tools when it has them, otherwise the page's calls.
170
182
  const tools = options.tools;
171
183
  const mcp = {
@@ -229,7 +241,23 @@ export function define_app(options) {
229
241
  // The desktop app's own MCP endpoint, for AI clients on the same computer.
230
242
  local_mcp: define_bridge(`${prefix}_local_mcp`, local_mcp_method_names),
231
243
  events: define_events(`${prefix}_events`),
244
+ host: define_bridge(`${prefix}_host`, host_ability_method_names),
245
+ // Letting other devices reach this computer's daemon, answered over its socket alone.
246
+ remote_access: define_bridge(`${prefix}_remote`, remote_access_method_names),
247
+ host_tables: Object.fromEntries(Object.entries(options.host_tables ?? {}).map(([name, table]) => [name, define_bridge(`${prefix}_${name}`, Object.keys(table.api))])),
232
248
  };
249
+ // ── Host tables ──────────────────────────────────────────────────────
250
+ const host_tables = options.host_tables ?? {};
251
+ // The tables a kind of host answers, and of those, the ones the network and MCP reach.
252
+ function tables_on(kind, from_network) {
253
+ return Object.entries(host_tables)
254
+ .filter(([, table]) => table.hosts.includes(kind) && !(from_network && table.network === "none"))
255
+ .map(([name]) => name);
256
+ }
257
+ // The table one of the host tables' calls belongs to, or null for any other call.
258
+ function table_of_call(method, kind) {
259
+ return tables_on(kind, true).find((name) => Object.hasOwn(host_tables[name].api, method)) ?? null;
260
+ }
233
261
  return {
234
262
  ...options,
235
263
  features,
@@ -244,11 +272,16 @@ export function define_app(options) {
244
272
  is_read_only,
245
273
  page_only,
246
274
  bind_methods,
275
+ record_writes,
247
276
  mcp,
248
277
  backup_naming: naming,
249
278
  read_backup_schedule,
250
279
  adopt_backup_schedule,
251
280
  backup_methods,
252
281
  bridges,
282
+ host_tables,
283
+ tables_on,
284
+ table_of_call,
285
+ host_table_path: host_table_route,
253
286
  };
254
287
  }
@@ -6,6 +6,7 @@ import { type TrayElectronLike, type TrayLike, type TrayRow } from "../electron/
6
6
  import { type BrowserWindowLike, type BrowserWindowOptionsLike, type NativeThemeLike, type ScreenLike, type ShellLike } from "../electron/window.ts";
7
7
  import { call_daemon, start_daemon } from "../local_daemon.ts";
8
8
  import type { App } from "./define.ts";
9
+ import { type AppNotice } from "./protocol.ts";
9
10
  type DesktopWindow = BrowserWindowLike & FocusableWindowLike & WindowLike & {
10
11
  webContents: {
11
12
  reload(): void;
@@ -33,6 +34,13 @@ export interface ElectronLike {
33
34
  canceled: boolean;
34
35
  filePath?: string;
35
36
  }>;
37
+ showOpenDialog?(options: {
38
+ properties: "openDirectory"[];
39
+ defaultPath?: string;
40
+ }): Promise<{
41
+ canceled: boolean;
42
+ filePaths: string[];
43
+ }>;
36
44
  };
37
45
  powerMonitor?: {
38
46
  getSystemIdleTime(): number;
@@ -104,6 +112,11 @@ export interface DesktopOptions {
104
112
  set_autostart?: (options: AutostartOptions, on: boolean) => void;
105
113
  tray?: AppTrayRows;
106
114
  route_of_link?: (link: string) => string | null;
115
+ daemon_env?: (profile: {
116
+ path: string;
117
+ is_own_profile: boolean;
118
+ }) => Record<string, string>;
119
+ show_notice?: (notice: AppNotice) => void;
107
120
  }
108
121
  export declare function run_desktop(app: App, electron: ElectronLike, options: DesktopOptions): void;
109
122
  export {};
@@ -6,6 +6,7 @@ import { unwatchFile, watchFile } from "node:fs";
6
6
  import { homedir, hostname } from "node:os";
7
7
  import { writeFile } from "node:fs/promises";
8
8
  import { extname, join, resolve } from "node:path";
9
+ import { Notifier } from "../agent/desktop_notify.js";
9
10
  import { launch_command, set_autostart } from "../autostart.js";
10
11
  import { backup_method_names } from "../backups.js";
11
12
  import { certificate_method_names } from "../certificate_protocol.js";
@@ -21,6 +22,8 @@ import { create_window, is_app_page } from "../electron/window.js";
21
22
  import { call_daemon, daemon_log_path, daemon_socket_path, start_daemon } from "../local_daemon.js";
22
23
  import { peer_listening_method_names, sync_device_method_names } from "../sync_protocol.js";
23
24
  import { route_of_link } from "./links.js";
25
+ import { remote_access_method_names } from "../remote_access_protocol.js";
26
+ import { host_ability_method_names, notice_event, notice_is_on } from "./protocol.js";
24
27
  // The Save dialog's options for a file name: Downloads with that name, offering files of its kind.
25
28
  export function save_dialog_options(file_name, downloads) {
26
29
  const extension = extname(file_name).slice(1);
@@ -57,7 +60,8 @@ export function run_desktop(app, electron, options) {
57
60
  function ensure_daemon(replace_other_build = false) {
58
61
  // Only the user's own daemon reads what this computer's configuration declares, unless a run names a file itself.
59
62
  const declared = is_own_profile ? {} : { [`${prefix}_DECLARED_FILE`]: env[`${prefix}_DECLARED_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 });
63
+ const own_env = options.daemon_env?.({ path: profile, is_own_profile }) ?? {};
64
+ 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, ...own_env }, log_file, replace_other_build });
61
65
  }
62
66
  // Saves the text where the user picks, starting in Downloads; false when the dialog was cancelled.
63
67
  async function save_text_file(file_name, text) {
@@ -79,13 +83,26 @@ export function run_desktop(app, electron, options) {
79
83
  const connections = create_connections({ storage: connection_file_storage(join(profile, "connections.json")), offers_local: true, device_name: `${app.name} on ${hostname()}` });
80
84
  const link = create_daemon_link({ connections, socket_path });
81
85
  const windows = () => BrowserWindow.getAllWindows();
86
+ // A daemon elsewhere tells of its notices as events; this computer shows them by its own switches, as its own
87
+ // daemon shows its own.
88
+ const notifier = new Notifier({ app_name: app.name, icons: { app: icon_path }, on_error: (message) => console.error(`${app.id} notifications: ${message}`) });
89
+ const show_notice = options.show_notice ?? ((notice) => void notifier.show({ title: notice.title, body: notice.body, key: notice.key, ...(notice.url ? { url: notice.url } : {}), icon: "app" }));
90
+ async function notice_from_elsewhere(data) {
91
+ if (router.is_here())
92
+ return;
93
+ const notice = JSON.parse(data);
94
+ if (notice_is_on(notice.kind, await get_desktop_settings()))
95
+ show_notice(notice);
96
+ }
97
+ // Host tables kept to this computer stay with its own daemon, as does who may connect to it.
98
+ const own_tables = Object.entries(app.host_tables).filter(([, table]) => table.network === "none").map(([name]) => name);
82
99
  // Calls and change events go to the chosen daemon; another daemon chosen reloads every window.
83
100
  const router = create_daemon_router({
84
101
  connections,
85
102
  link,
86
103
  call_local: (path, args, headers) => call_socket(socket_path, path, args, headers),
87
104
  restart_local: () => ensure_daemon(),
88
- local_tables: [...default_local_tables, "peer_listening"],
105
+ local_tables: [...default_local_tables, "peer_listening", "remote", ...own_tables],
89
106
  is_read_only: app.is_read_only,
90
107
  on_change: (change) => {
91
108
  app.bridges.events.emit(windows(), "changed", change);
@@ -94,7 +111,11 @@ export function run_desktop(app, electron, options) {
94
111
  },
95
112
  on_sync_status: (status) => app.bridges.events.emit(windows(), "sync_status", status),
96
113
  // The app's own events, such as a reply as it is written, go to every window by name.
97
- on_event: (event, data) => app.bridges.events.emit(windows(), "app_event", { event, data: data === "" ? null : JSON.parse(data) }),
114
+ on_event: (event, data) => {
115
+ if (event === notice_event)
116
+ void notice_from_elsewhere(data).catch(() => undefined);
117
+ app.bridges.events.emit(windows(), "app_event", { event, data: data === "" ? null : JSON.parse(data) });
118
+ },
98
119
  on_switch: () => {
99
120
  for (const window of windows())
100
121
  window.webContents.reload();
@@ -219,6 +240,11 @@ export function run_desktop(app, electron, options) {
219
240
  bridges.connections.handle(ipcMain, connections.methods, handle_options);
220
241
  if (app.local_mcp)
221
242
  bridges.local_mcp.handle(ipcMain, forwarded(local_mcp_method_names, "local_mcp"), handle_options);
243
+ if (app.remote_access)
244
+ bridges.remote_access.handle(ipcMain, forwarded(remote_access_method_names, "remote"), handle_options);
245
+ bridges.host.handle(ipcMain, forwarded(host_ability_method_names, "host"), handle_options);
246
+ for (const [name, bridge] of Object.entries(bridges.host_tables))
247
+ bridge.handle(ipcMain, forwarded(Object.keys(app.host_tables[name].api), name), handle_options);
222
248
  const desktop = {
223
249
  get_desktop_settings,
224
250
  set_desktop_setting: async (key, value) => {
@@ -233,6 +259,12 @@ export function run_desktop(app, electron, options) {
233
259
  electron.nativeTheme.themeSource = theme;
234
260
  },
235
261
  get_data_paths: () => ({ database: database_path, backups: join(profile, "backups") }),
262
+ pick_folder: async (current) => {
263
+ if (!dialog.showOpenDialog)
264
+ throw new Error("This desktop app cannot show a folder dialog.");
265
+ const picked = await dialog.showOpenDialog({ properties: ["openDirectory"], ...(current ? { defaultPath: current } : {}) });
266
+ return picked.canceled ? null : (picked.filePaths[0] ?? null);
267
+ },
236
268
  show_data_path: async (which) => {
237
269
  if (which === "database")
238
270
  electron.shell.showItemInFolder?.(database_path);
@@ -0,0 +1,20 @@
1
+ import type { FastifyInstance, FastifyRequest } from "fastify";
2
+ import { type ApiSpec } from "../api_spec.ts";
3
+ import type { EventStream } from "../server/events.ts";
4
+ import type { SqlDatabase } from "../sql.ts";
5
+ import type { App, HostKind } from "./define.ts";
6
+ import type { HostAbilities } from "./protocol.ts";
7
+ import type { HostServices } from "./services.ts";
8
+ export interface HostReach {
9
+ kind: HostKind;
10
+ from_network: boolean;
11
+ is_admin: (request: FastifyRequest) => boolean;
12
+ }
13
+ export declare function host_abilities(app: App, reach: HostReach, request: FastifyRequest): HostAbilities;
14
+ export declare function register_host_tables(api: FastifyInstance, app: App, reach: HostReach, services: () => HostServices, changes: EventStream): void;
15
+ export interface McpTools {
16
+ api: ApiSpec<Record<string, (...args: never[]) => unknown>>;
17
+ call: (method: string, args: unknown[], request?: FastifyRequest) => Promise<unknown>;
18
+ }
19
+ export declare function mcp_tools(app: App, reach: HostReach, services: () => HostServices, database: () => SqlDatabase, announce: () => void): McpTools;
20
+ export declare function call_path_of(app: App, kind: HostKind): (method: string) => string;