@x-tech-laboratories/x-app 0.122.0 → 0.123.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
@@ -14,11 +14,11 @@ an app moves over by changing the package name in its imports and its `x-libs-*`
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. On the server it also gets `config_file`, the path of the config it read, for an app that reads its own keys again when the file changes (with `config_watch`), `declared_tokens()` and `reread_declared_tokens(config)` after such a reload. `before_restore` and `after_restore` may return a promise, which the restore waits for, such as a writer flushing first. |
15
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`. A table's `needs(method)` names the role a call needs from the network or MCP beyond the table's reach, such as an operator's for the calls that change something, refused with 403; every call runs with its request's viewer, which `current_viewer()` of `server/viewer_scope` reads, so the services can name who asked. |
16
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. |
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
+ | `app/desktop`, `app/preload` | `run_desktop(app, electron, { main_dir })`: Electron's main process as a portal onto this computer's daemon or a server, with the window (`default_size` fixed or from the screen's free area, the daemon told while one is in front for its services' `window_in_front`), the tray (`show_tray_icon`, the app's own `tray` rows above Show, Quit and Quit completely, worked out with `call(method)` or a host table's `call("<table>/<call>")`, a write a row makes reaching every window at once, closing the last window leaving the app in it, `--hidden` starting there), the app's `link_scheme` links opening the window on their page (`route_of_link` to map them its own way; the page follows the `open` event), the login entry, a second launch and `--daemon`; the app's own `desktop_settings` switches sit in Settings → Desktop app beside the base's; `run_preload(app, electron)` puts every bridge on the page. The page's `desktop` calls also give the computer's idle seconds (`get_idle_seconds`, from Electron's `powerMonitor`) `set_window_theme`, which the page calls so the window's own parts follow its theme, `get_data_paths` and `show_data_path`, which show this computer's database and backups folder in the file manager from Settings, and `save_text_file`, which asks where through the Save dialog, starting in Downloads (`save_dialog_options`); opening the window replaces a daemon another build left running, and a Flatpak keeps its profile in `~/.config/<id>` as the other builds do. Electron is handed in, so neither imports it. An app with `local_mcp: { default_port }` serves its calls as MCP on 127.0.0.1 from the desktop daemon (`electron/mcp`, page-only calls left out, calls run as `program`), turned on under Settings → MCP server. |
18
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`. |
19
19
  | `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`. |
20
- | `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. In a browser, Settings ends with Users and Tokens (`users_settings`) for an admin of the server, with the app's `role_text`; an app's own `use_chrome` sidebar, such as a tree, sits under the pages' rows. |
21
- | `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
+ | `app/web/app_page`, `app/web/page` | `render_app({ app, pages, general_settings })`: the page on the web, the desktop or Android in the `Shell`, with sign-in in a browser, the theme kept in this browser or, for an app with `synced_theme`, in its synced setting, the sidebar's dragged width remembered on this device (`default_sidebar_width`) unless the chrome's `sidebar_width` holds it, Your account, Settings (the app's general sections, each page's own, Connections, Desktop app, Sync, Backups and Import and export, the settings as a file) and `SyncButton`; `page_hooks<Methods>()` gives the app's typed `calls`, `use_data` and `use_settings`. The phone's host (`app/web/android`) loads only on Android. The page API's `on_event(name, listener)` hears the named events the app's services `emit`, on the web and the desktop. A page may have an `icon` (the sidebar then shows icon rows), a `use_badge` hook ("Inbox · 3"), `in_sidebar: false` with `active_as` for a page reached only by its route; `default_page` names the page an empty route opens, and the `use_chrome(parts)` hook gives the `sidebar` content under the rows, header `tools`, a `side_pane`, a `contained` window where only the page scrolls with a `main_class` for its box, `around`, which wraps the page, such as in the app's own context or with dialogs over any page, and `bare` for the page alone with no sidebar or header, such as a strip embedded in another program. `settings_categories(props)` adds the app's own Settings categories after General, for settings no one page owns. A page's `children` fold open under its row in the sidebar (`#/diet/foods`, the title "Foods · Diet", the first shown when none is named, a single child leaving the page one row); its `use_items` hook gives rows worked out as the page runs, such as each paired device, folding open under it onto `#/devices/<id>` with the title "Pixel · Devices"; and `phone_services` loads the app's own work on the phone only there, such as reminders handed to Android, told of every write, every change from another device and each return to the app; an older version's backup schedule in the page's storage moves into the setting. In a browser, Settings ends with Users and Tokens (`users_settings`) for an admin of the server, with the app's `role_text`; an app's own `use_chrome` sidebar, such as a tree, sits under the pages' rows. |
21
+ | `config/vite`, `config/electron_vite`, `config/vitest`, `config/electron_builder`, `config/tsconfig/*.json` | An X-app's configs as presets: `web_vite_config({ port })` and `android_vite_config()` for the page, `desktop_vite_config()` for electron-vite's window, daemon, preload and page, `vitest_config()` for tests in `tests/` in UTC with coverage of `src/` to the terminal, merged with the app's own floor so `autoUpdate` still raises it, and `base`, `node`, `web` and `tests` tsconfigs to extend. The page presets stand in for Capacitor where the app has none installed (`config/capacitor`'s `capacitor_stand_in`), so a web and desktop app needs no phone packages, and the dev server proxies `/api/`, leaving the page's own `api.ts` to Vite. `electron_builder_config({ id, name, app_id, comment, categories, link_scheme })` is the desktop app's AppImage and Flatpak bundle for electron-builder, the Flatpak keeping its data in `~/.config/<id>` as the other builds do, and reaching what else `flatpak_permissions` names, such as `--system-talk-name=org.bluez`. |
22
22
  | `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`. |
23
23
  | `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. |
24
24
  | `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. |
@@ -91,7 +91,7 @@ an app moves over by changing the package name in its imports and its `x-libs-*`
91
91
  | `electron/mcp`, `local_mcp_protocol`, `web/react/local_mcp_settings` | A desktop app's own MCP endpoint, for AI clients on the same computer: `create_local_mcp` serves an `api_spec`'s calls as tools through `server/mcp` on 127.0.0.1 only, leaving out page-only calls and refusing the uses its `page_only` rule names, since the window reaches those over the daemon's socket, refusing any request whose Host or Origin is not a local name, turned on and given a port by `LocalMcpMethods` and kept in a settings file; with `require_token` on it also refuses any request without its token as `Authorization: Bearer`, the token made by the daemon and kept in `token_file` (`mcp-token` beside the settings unless set, mode 0600), kept across restarts and forgotten when the setting is turned off, and the status then carries `token` and `token_file`; `local_mcp_client_config` gives the `mcpServers` entry with its `headers`, and `local_mcp_add_command` the `claude mcp add` line reading the token from its file; `LocalMcpSettings` is the Settings rows to turn it on, pick the port, require a token, copy the `claude mcp add` command and show or copy the client config. |
92
92
  | `agent/commands` | `run_command` and `stream_command`: one shell command, in its own process group. |
93
93
  | `agent/programs` | `run_program`: one program with its arguments and no shell, each stream shown to a sink, kept, both or dropped, stopped by an abort signal and, in a process group of its own, with all it started; 127 when it is not installed; `start_line_program`, a program talked to in lines both ways while it runs, each whole line it prints handed on as it arrives (a character split across chunks kept whole), lines written to it until `end_input`, its group stopped by the signal; `BoundedBuffer`, `signal_group` and `on_path`; `whole_lines(sink)` passes on only whole lines, decoding characters split across chunks, with `flush()` for the rest, so programs printing side by side into one output never split each other's lines. |
94
- | `agent/ssh_config` | `ssh_host_options(text, host, { home, local_user })`: what an OpenSSH client config such as `~/.ssh/config` says of one host (`host_name`, `user`, `port`, `identity_files` with `~`, `%h`, `%u` filled in), the first value of each keyword winning and Host patterns taking `*`, `?` and `!`, so a program reaching hosts over SSH honours its user's aliases as `ssh` and asyncssh do; `host_line_matches`. Match blocks and Include are not followed. |
94
+ | `agent/ssh_config` | `ssh_host_options(text, host, { home, local_user })`: what an OpenSSH client config such as `~/.ssh/config` says of one host (`host_name`, `user`, `port`, `identity_files` with `~`, `%h`, `%u` filled in), the first value of each keyword winning and Host patterns taking `*`, `?` and `!`, so a program reaching hosts over SSH honours its user's aliases as `ssh` and asyncssh do; `host_line_matches`. Match blocks and Include are not followed.; `on_host: true` runs the computer's own program from inside a Flatpak through `flatpak-spawn --host` (`host_argv`, `in_flatpak`), which the Flatpak needs `--talk-name=org.freedesktop.Flatpak` for. |
95
95
  | `agent/firefox_bookmarks` | Firefox's bookmarks on this computer: `firefox_profile(set_folder)` (the folder set, with `~`, or the default profile from `profiles.ini`, read by `default_profile_of`), `read_firefox_bookmarks(profile)` from a copy of `places.sqlite` with its write-ahead log, since Firefox keeps it locked, read again only once either changes, tags left out; `bookmark_folders` by path, `bookmark_folder_path`, `bookmarks_in_folder` with every folder inside, `search_bookmarks` by every word of the title or address, `bookmarks_by_guid` and `is_page_bookmark`. |
96
96
  | `agent/claude_stream` | `start_claude_stream`: a Claude Code session driven over its stream-json protocol (`claude -p --input-format stream-json --output-format stream-json`) on `start_line_program`: `send_user` writes a message with the id the session echoes once it has read it, `control` sends a control request such as an interrupt or a change of permission mode and settles with the answer, a refusal or a timeout, the session's own requests such as `can_use_tool` go to `on_request` and are answered with `respond` (`allow_tool`, `deny_tool`), any not taken refused, and every other line is handed on with its JSON; `user_message_line`. |
97
97
  | `agent/git` | Git through `run_program`, never a shell: `git` throws git's own last words on an exit code not allowed; `default_branch` from origin's HEAD; `add_worktree` makes a worktree once at a path on its own branch, from the freshly fetched default branch or a `base`, or takes the branch when it exists; `list_worktrees`, the main checkout first with each head and branch; `reset_worktree` back to a commit, new files cleaned; `remove_worktree`, forced or not, with its branch; `read_raw_changes` and `read_numstat` for `git diff --raw -z` and `--numstat -z` (renames by their new path, binary files as null), `sum_numstat` and `untracked_files`. |
@@ -254,9 +254,14 @@ An app whose work needs a computer, such as one that runs programs on checkouts,
254
254
  - **Host tables**: `host_tables: { stages: { hosts: ["server", "desktop"], api: stages_api } }` names calls the hosts
255
255
  answer themselves; the services return `tables: { stages: { methods, elsewhere } }`. The page reaches them with
256
256
  `host_table("stages")`, null where the host it works on does not answer them or does not let its viewer.
257
- - **Notices**: `context.notify({ kind, title, body, key, url })` from the services; the desktop daemon shows it where
258
- `notify_<kind>` in `desktop_settings` is on, and every window and phone working on that host from elsewhere shows it
259
- by its own switch.
257
+ - **Notices**: `context.notify({ kind, title, body, key, url, urgency })` from the services; the desktop daemon shows it
258
+ where `notify_<kind>` in `desktop_settings` is on, and every window and phone working on that host from elsewhere
259
+ shows it by its own switch. The server sends it through the channels its config's `notify_channels` lists (ntfy,
260
+ webhook, mail or Apprise). `context.withdraw(key)` takes it back wherever it shows, such as a call that stopped ringing.
261
+ - **Following changes**: the services' `after_change(change)` runs after every change the pages hear of, whoever made
262
+ it, with the synced tables written when known, such as to follow a setting; `after_remote_change` runs only for sync's.
263
+ - **Plugins**: the services load `context.plugins_folder`; on the server the page loads the plugins' web sides from
264
+ `/api/plugins/index.json`.
260
265
  - **Other devices**: `remote_access: true` lets the daemon serve its calls and host tables on the network, and
261
266
  `phone: "portal"` makes the phone a window onto a host chosen under Connections, keeping no data, its notices shown
262
267
  through `phone_notifications` (Capacitor's `LocalNotifications`).
@@ -277,7 +282,10 @@ The rest of an app's files are short calls into X-App too:
277
282
  An app with git dependencies names each lock entry's https URL in `git_dependencies`, which the packages fetch and
278
283
  copy in, and `link_scheme`, such as `"codex"`, makes the desktop entry open its links; `desktop_path`, such as
279
284
  `pkgs: [ pkgs.libnotify ]`, puts programs the desktop app runs on its PATH, and `state_name` keeps an older service's
280
- 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; `sources`, such as `[ "src/core" "src/monitors" ]`, are more folders the server package runs from, and `programs`, such as `{ x-monitor-agent = "src/agent/main.ts"; }`, more commands it installs; the module's `settings` option adds keys of the machine's own to that file, winning over the module's; the desktop wrapper sets
285
+ 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; `sources`, such as `[ "src/core" "src/monitors" ]`, are more folders the server package runs from, and `programs`, such as `{ x-monitor-agent = "src/agent/main.ts"; }`, more commands it installs; `native_modules`, such as `[ "usocket" ]`, are built for Node in the server package and for Electron in the desktop one;
286
+ the module's `notifyChannels` and `settings` options add to that file, `settings` with keys of the machine's own,
287
+ winning over the module's, so an app's own module can set its keys from options of its own, its credentials and
288
+ firewall ports merging as in any module; the desktop wrapper sets
281
289
  `<PREFIX>_LAUNCHER` so the login entry runs the installed command. `android_emulator_shell nixpkgs system app` adds an
282
290
  Android 36 emulator to the Android shell, with `<name>-emulator` to start it and `<name>-emulator-install` to build
283
291
  and open the app on it, never on a connected phone.
@@ -12,6 +12,7 @@ export interface ProgramOptions {
12
12
  cwd?: string;
13
13
  signal?: AbortSignal;
14
14
  own_group?: boolean;
15
+ on_host?: boolean;
15
16
  }
16
17
  export interface ProgramResult {
17
18
  exit_code: number;
@@ -36,11 +37,14 @@ export declare function on_path(name: string): Promise<string | null>;
36
37
  export declare function whole_lines(sink: Sink): Sink & {
37
38
  flush(): void;
38
39
  };
40
+ export declare function in_flatpak(variables?: NodeJS.ProcessEnv): boolean;
41
+ export declare function host_argv(argv: readonly string[], cwd?: string, variables?: NodeJS.ProcessEnv): string[];
39
42
  export declare function run_program(argv: readonly string[], options?: ProgramOptions): Promise<ProgramResult>;
40
43
  export interface LineProgramOptions {
41
44
  cwd?: string;
42
45
  env?: NodeJS.ProcessEnv;
43
46
  signal?: AbortSignal;
47
+ on_host?: boolean;
44
48
  on_line: (line: string) => void;
45
49
  }
46
50
  export interface LineProgramExit {
@@ -90,6 +90,24 @@ export function whole_lines(sink) {
90
90
  },
91
91
  };
92
92
  }
93
+ // ── The computer's programs ──────────────────────────────────────────────────
94
+ // Whether this process runs in a Flatpak's sandbox, which has its own programs rather than the computer's.
95
+ export function in_flatpak(variables = process.env) {
96
+ return Boolean(variables.FLATPAK_ID);
97
+ }
98
+ // The command that runs a program on the computer itself: through flatpak-spawn --host from inside a Flatpak, in the
99
+ // folder given, which the Flatpak needs --talk-name=org.freedesktop.Flatpak for; the program as given otherwise.
100
+ export function host_argv(argv, cwd, variables = process.env) {
101
+ if (!in_flatpak(variables))
102
+ return [...argv];
103
+ return ["flatpak-spawn", "--host", "--watch-bus", ...(cwd ? [`--directory=${cwd}`] : []), ...argv];
104
+ }
105
+ // What to start, and where: the program as asked, or flatpak-spawn starting it on the computer, which takes the folder itself.
106
+ function spawned(argv, on_host, cwd) {
107
+ if (!on_host || !in_flatpak())
108
+ return { command: [...argv], cwd };
109
+ return { command: host_argv(argv, cwd), cwd: undefined };
110
+ }
93
111
  // ── Running ──────────────────────────────────────────────────────────────────
94
112
  // Runs the program to its end and never rejects: a program that cannot start answers 127 or -1 with why.
95
113
  export function run_program(argv, options = {}) {
@@ -100,11 +118,12 @@ export function run_program(argv, options = {}) {
100
118
  resolve({ exit_code: -1, stdout: "", stderr: "Stopped before it started" });
101
119
  return;
102
120
  }
103
- const child = spawn(argv[0], argv.slice(1), {
121
+ const start = spawned(argv, options.on_host, options.cwd);
122
+ const child = spawn(start.command[0], start.command.slice(1), {
104
123
  detached: options.own_group ?? false,
105
124
  stdio: [options.stdin == null ? "ignore" : "pipe", "pipe", "pipe"],
106
125
  env: options.env,
107
- cwd: options.cwd,
126
+ cwd: start.cwd,
108
127
  });
109
128
  if (options.stdin != null) {
110
129
  child.stdin.on("error", () => { });
@@ -142,7 +161,7 @@ export function run_program(argv, options = {}) {
142
161
  };
143
162
  child.on("error", (error) => {
144
163
  const missing = error.code === "ENOENT";
145
- const message = missing ? `${argv[0]} is not installed on this host` : `Could not start ${argv[0]}: ${error.message}`;
164
+ const message = missing ? `${start.command[0]} is not installed on this host` : `Could not start ${start.command[0]}: ${error.message}`;
146
165
  if (shows(stderr_use))
147
166
  options.err?.write(`${message}\n`);
148
167
  settle({ exit_code: missing ? not_installed_exit_code : -1, stdout: "", stderr: message });
@@ -158,7 +177,8 @@ export function run_program(argv, options = {}) {
158
177
  export function start_line_program(argv, options) {
159
178
  if (options.signal?.aborted)
160
179
  return { write_line: () => undefined, end_input: () => undefined, is_open: () => false, finished: Promise.resolve({ exit_code: -1, stderr: "Stopped before it started" }) };
161
- const child = spawn(argv[0], argv.slice(1), { detached: true, stdio: ["pipe", "pipe", "pipe"], env: options.env, cwd: options.cwd });
180
+ const start = spawned(argv, options.on_host, options.cwd);
181
+ const child = spawn(start.command[0], start.command.slice(1), { detached: true, stdio: ["pipe", "pipe", "pipe"], env: options.env, cwd: start.cwd });
162
182
  let open = true;
163
183
  child.stdin.on("error", () => (open = false));
164
184
  const stderr = new BoundedBuffer(stderr_limit_in_bytes);
@@ -14,6 +14,7 @@ export interface DaemonOptions {
14
14
  routes?: AppRoutes;
15
15
  web_folder?: string;
16
16
  show_notice?: (notice: AppNotice) => void;
17
+ withdraw_notice?: (key: string) => void;
17
18
  }
18
19
  export interface Daemon {
19
20
  shut_down: () => Promise<void>;
@@ -20,7 +20,7 @@ import { file_sync_storage } from "../sync_file_storage.js";
20
20
  import { create_sync_peer, sync_device_methods } from "../sync_peer.js";
21
21
  import { keep_listening_for_peers } from "../sync_peer_listening.js";
22
22
  import { mcp_tools, register_host_tables } from "./host_tables.js";
23
- import { notice_event, notice_is_on, read_desktop_settings } from "./protocol.js";
23
+ import { notice_event, notice_withdrawn_event, notice_is_on, read_desktop_settings } from "./protocol.js";
24
24
  import { create_remote_access } from "./remote_access.js";
25
25
  import { declared_file_of, no_services, side_databases } from "./services.js";
26
26
  import { build_server, call_body_limit, data_change_text, open_app_database, register_app_calls, watch_outside_changes } from "./server.js";
@@ -33,10 +33,10 @@ export async function start_daemon(app, options) {
33
33
  const unused_check_ms = options.unused_check_ms ?? 5000;
34
34
  // Backed up before an upgrade, before another copy replaces it, and daily, beside the database.
35
35
  const opened = open_app_database(app, database_path, join(profile, "backups"));
36
- // Every window's event stream, told when the data changed or sync's status moved.
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.
36
+ // The app's services once started, which answer its host tables and hear of every change.
39
37
  let services = no_services;
38
+ // Every window's event stream, told when the data changed or sync's status moved.
39
+ const changes = new EventStream({ change_data: data_change_text(app, opened.database, (change) => services.after_change?.(change)) });
40
40
  // Server certificates the user trusted, such as a home server's self-signed one, handed to Node's own fetch.
41
41
  const certificates = create_certificate_trust({ file: join(profile, "trusted-certificates.json"), use_in_node: true });
42
42
  // Off until "Let other devices connect" is turned on; then other devices reach this computer's sync on its port.
@@ -89,7 +89,8 @@ export async function start_daemon(app, options) {
89
89
  : null;
90
90
  // ── Notices ────────────────────────────────────────────────────────
91
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" }));
92
+ const show_notice = options.show_notice ?? ((notice) => void notifier.show({ title: notice.title, body: notice.body, key: notice.key, urgency: notice.urgency ?? "normal", ...(notice.url ? { url: notice.url } : {}), icon: "app" }));
93
+ const withdraw_notice = options.withdraw_notice ?? ((key) => void notifier.dismiss({ key }));
93
94
  // Shown here where this computer's switch for its kind is on, and sent to every window, for those working on this
94
95
  // daemon from another computer to show there.
95
96
  function notify(notice) {
@@ -97,6 +98,11 @@ export async function start_daemon(app, options) {
97
98
  show_notice(notice);
98
99
  changes.send(JSON.stringify(notice), { event: notice_event });
99
100
  }
101
+ // Taken back here and in every window that showed it.
102
+ function withdraw(key) {
103
+ withdraw_notice(key);
104
+ changes.send(JSON.stringify(key), { event: notice_withdrawn_event });
105
+ }
100
106
  // ── Other devices ──────────────────────────────────────────────────
101
107
  // Accounts that sign other devices in are a file of their own beside the data, as on the server.
102
108
  const accounts_database = app.remote_access ? new DatabaseSync(join(profile, "accounts.db")) : null;
@@ -209,6 +215,7 @@ export async function start_daemon(app, options) {
209
215
  window_in_front: () => window_in_front,
210
216
  icon_path: options.icon_path ?? null,
211
217
  notify,
218
+ withdraw,
212
219
  });
213
220
  }
214
221
  // Devices signed in from elsewhere follow the restored data too.
@@ -117,6 +117,7 @@ export interface DesktopOptions {
117
117
  is_own_profile: boolean;
118
118
  }) => Record<string, string>;
119
119
  show_notice?: (notice: AppNotice) => void;
120
+ withdraw_notice?: (key: string) => void;
120
121
  }
121
122
  export declare function run_desktop(app: App, electron: ElectronLike, options: DesktopOptions): void;
122
123
  export {};
@@ -23,7 +23,7 @@ import { call_daemon, daemon_log_path, daemon_socket_path, start_daemon } from "
23
23
  import { peer_listening_method_names, sync_device_method_names } from "../sync_protocol.js";
24
24
  import { route_of_link } from "./links.js";
25
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";
26
+ import { host_ability_method_names, notice_event, notice_is_on, notice_withdrawn_event } from "./protocol.js";
27
27
  // The Save dialog's options for a file name: Downloads with that name, offering files of its kind.
28
28
  export function save_dialog_options(file_name, downloads) {
29
29
  const extension = extname(file_name).slice(1);
@@ -86,7 +86,8 @@ export function run_desktop(app, electron, options) {
86
86
  // A daemon elsewhere tells of its notices as events; this computer shows them by its own switches, as its own
87
87
  // daemon shows its own.
88
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" }));
89
+ const show_notice = options.show_notice ?? ((notice) => void notifier.show({ title: notice.title, body: notice.body, key: notice.key, urgency: notice.urgency ?? "normal", ...(notice.url ? { url: notice.url } : {}), icon: "app" }));
90
+ const withdraw_notice = options.withdraw_notice ?? ((key) => void notifier.dismiss({ key }));
90
91
  async function notice_from_elsewhere(data) {
91
92
  if (router.is_here())
92
93
  return;
@@ -114,6 +115,8 @@ export function run_desktop(app, electron, options) {
114
115
  on_event: (event, data) => {
115
116
  if (event === notice_event)
116
117
  void notice_from_elsewhere(data).catch(() => undefined);
118
+ if (event === notice_withdrawn_event && !router.is_here())
119
+ withdraw_notice(JSON.parse(data));
117
120
  app.bridges.events.emit(windows(), "app_event", { event, data: data === "" ? null : JSON.parse(data) });
118
121
  },
119
122
  on_switch: () => {
@@ -188,8 +191,8 @@ export function run_desktop(app, electron, options) {
188
191
  // ── Tray ───────────────────────────────────────────────────────────
189
192
  // A write from a tray row reaches every window and the tray at once, as the daemon tells this process of no change it made.
190
193
  async function tray_call(method, args = []) {
191
- const result = await call(`call/${method}`, args);
192
- if (!app.is_read_only(method)) {
194
+ const result = await call(method.includes("/") ? method : `call/${method}`, args);
195
+ if (!app.is_read_only(method.slice(method.lastIndexOf("/") + 1))) {
193
196
  app.bridges.events.emit(windows(), "changed", null);
194
197
  void tray?.refresh();
195
198
  }
@@ -57,8 +57,10 @@ export interface AppNotice {
57
57
  body: string;
58
58
  key: string;
59
59
  url: string;
60
+ urgency?: "low" | "normal" | "critical";
60
61
  }
61
62
  export declare const notice_event = "notice";
63
+ export declare const notice_withdrawn_event = "notice_withdrawn";
62
64
  export declare function notice_is_on(kind: string, switches: Readonly<Record<string, boolean>>): boolean;
63
65
  export type Host = "web" | "desktop" | "android";
64
66
  export interface BackupFolder {
@@ -16,6 +16,8 @@ export const desktop_method_names = ["get_desktop_settings", "set_desktop_settin
16
16
  export const host_ability_method_names = ["get_host_abilities"];
17
17
  // The named event a host sends its pages with each notice.
18
18
  export const notice_event = "notice";
19
+ // The named event a host sends its pages when a notice is taken back, its data the notice's key.
20
+ export const notice_withdrawn_event = "notice_withdrawn";
19
21
  // Whether this device shows a notice of the kind given: its switch, where the app has one, or always.
20
22
  export function notice_is_on(kind, switches) {
21
23
  return switches[`notify_${kind}`] ?? true;
@@ -3,11 +3,14 @@ import { type FastifyInstance } from "fastify";
3
3
  import { type BackupMethods } from "../backups.ts";
4
4
  import { OidcClient } from "../server/oidc.ts";
5
5
  import { AccountStore } from "../server/account_store.ts";
6
+ import { type Channel } from "../server/notify/channels.ts";
6
7
  import { EventStream } from "../server/events.ts";
7
8
  import { type SqlDatabase } from "../sql.ts";
8
9
  import { type ServerTheme } from "../web/theme.ts";
9
10
  import { type SyncPeer } from "../sync_peer.ts";
11
+ import { type DataChange } from "../sync_protocol.ts";
10
12
  import type { App, HostKind } from "./define.ts";
13
+ import { type AppNotice } from "./protocol.ts";
11
14
  import { type AppRoutes, type HostServices, type StartServices } from "./services.ts";
12
15
  export interface AppDatabase {
13
16
  database: () => DatabaseSync;
@@ -20,7 +23,7 @@ export interface AppDatabase {
20
23
  close: () => void;
21
24
  }
22
25
  export declare function open_app_database(app: App, path: string, backups_folder: string): AppDatabase;
23
- export declare function data_change_text(app: Pick<App, "take_data_change">, database: () => SqlDatabase): () => string;
26
+ export declare function data_change_text(app: Pick<App, "take_data_change">, database: () => SqlDatabase, after?: (change: DataChange | null) => void): () => string;
24
27
  export declare function watch_outside_changes(database: () => SqlDatabase, on_change: () => void, every_ms?: number): () => void;
25
28
  export declare const call_body_limit: number;
26
29
  export declare function call_args(app: App, method: string, body: unknown): unknown[];
@@ -47,6 +50,7 @@ export interface ServerOptions {
47
50
  }
48
51
  export declare const user_only_backup_calls: ReadonlySet<string>;
49
52
  export declare function build_server(app: App, options: ServerOptions): Promise<FastifyInstance>;
53
+ export declare function notify_through(channels: readonly Channel[], notice: AppNotice): void;
50
54
  export interface RunServerOptions {
51
55
  web_folder: URL;
52
56
  argv?: string[];
@@ -20,6 +20,7 @@ import { AccountStore, holds_accounts, move_accounts } from "../server/account_s
20
20
  import { register_call_table } from "../server/call_table.js";
21
21
  import { register_open_cors } from "../server/cors.js";
22
22
  import { read_server_config } from "../server/config.js";
23
+ import { read_channels } from "../server/notify/channels.js";
23
24
  import { EventStream } from "../server/events.js";
24
25
  import { register_mcp_route } from "../server/mcp.js";
25
26
  import { register_plugin_files } from "../server/plugin_files.js";
@@ -32,8 +33,9 @@ import { tidy_database, tidy_every_ms } from "../sql.js";
32
33
  import { file_sync_storage } from "../sync_file_storage.js";
33
34
  import { read_server_theme } from "../web/theme.js";
34
35
  import { create_sync_peer, sync_device_methods } from "../sync_peer.js";
36
+ import { data_change_of } from "../sync_protocol.js";
35
37
  import { call_path_of, mcp_tools, register_host_tables } from "./host_tables.js";
36
- import { notice_event } from "./protocol.js";
38
+ import { notice_event, notice_withdrawn_event } from "./protocol.js";
37
39
  import { declared_file_of, no_services, side_databases } from "./services.js";
38
40
  // The server and the daemon run on Node, so a call's caller holds across its awaits.
39
41
  use_caller_scope(node_caller_scope());
@@ -110,15 +112,24 @@ function adopt_schedule_file(app, database, file) {
110
112
  app.adopt_backup_schedule(database, saved);
111
113
  rmSync(file, { force: true });
112
114
  }
113
- // What a change event carries: the tables written since the last one, or nothing when that cannot be told, as mid-restore.
114
- export function data_change_text(app, database) {
115
+ // What a change event carries: the tables written since the last one, or nothing when that cannot be told, as
116
+ // mid-restore. after hears of each change as it is announced, such as the app's services following a setting.
117
+ export function data_change_text(app, database, after) {
115
118
  return () => {
119
+ let text = "";
116
120
  try {
117
- return JSON.stringify(app.take_data_change(database()));
121
+ text = JSON.stringify(app.take_data_change(database()));
118
122
  }
119
123
  catch {
120
- return "";
124
+ text = "";
121
125
  }
126
+ try {
127
+ after?.(data_change_of(text));
128
+ }
129
+ catch (error) {
130
+ console.error(`after a change: ${error instanceof Error ? error.message : String(error)}`);
131
+ }
132
+ return text;
122
133
  };
123
134
  }
124
135
  // Another program, such as an older build of the app, may write the database file; SQLite moves data_version only
@@ -276,6 +287,12 @@ export async function build_server(app, options) {
276
287
  await register_web_folder(server, { folder: options.web_folder });
277
288
  return server;
278
289
  }
290
+ // A notice the server passes on through each of its channels; a channel that fails is only logged.
291
+ export function notify_through(channels, notice) {
292
+ const level = notice.urgency === "critical" ? "warning" : "info";
293
+ for (const channel of channels)
294
+ void channel({ title: notice.title, body: notice.body, level }).catch((error) => console.warn(`notify: ${error instanceof Error ? error.message : String(error)}`));
295
+ }
279
296
  // Starts the app's web server on the database its config names, and stops it on SIGINT and SIGTERM.
280
297
  export async function run_server(app, options) {
281
298
  const prefix = app.env_prefix;
@@ -322,9 +339,11 @@ export async function run_server(app, options) {
322
339
  });
323
340
  const oidc_settings = oidc_from_environment(prefix, options.env ?? process.env);
324
341
  // Every page hears of a change, whether a page or another device made it, and which tables it touched.
325
- const changes = new EventStream({ change_data: data_change_text(app, opened.database) });
326
342
  // Answers the host tables and the app's routes once started; before then they say the server is still starting.
327
343
  let services = no_services;
344
+ const changes = new EventStream({ change_data: data_change_text(app, opened.database, (change) => services.after_change?.(change)) });
345
+ // A mistake in a channel, or a secret file that cannot be read, stops the server starting.
346
+ const channels = read_channels(config.notify_channels, { name: "notify_channels" });
328
347
  // The server is one sync peer among the devices, kept beside the data so a restore leaves its pairings be; an app
329
348
  // whose server is the only copy keeps none.
330
349
  const sync = app.sync === false ? null : create_sync_peer({
@@ -378,8 +397,13 @@ export async function run_server(app, options) {
378
397
  back_up: opened.back_up,
379
398
  window_in_front: () => false,
380
399
  icon_path: null,
381
- // The server shows no notice itself; the pages and phones working on it show them.
382
- notify: (notice) => changes.send(JSON.stringify(notice), { event: notice_event }),
400
+ // The server shows no notice itself: it goes out through the config's channels, and the pages and phones
401
+ // working on the server show it.
402
+ notify: (notice) => {
403
+ notify_through(channels, notice);
404
+ changes.send(JSON.stringify(notice), { event: notice_event });
405
+ },
406
+ withdraw: (key) => changes.send(JSON.stringify(key), { event: notice_withdrawn_event }),
383
407
  })
384
408
  : no_services;
385
409
  opened.on_restore({ before: () => services.before_restore?.(), after: () => services.after_restore?.() });
@@ -2,6 +2,7 @@ import { DatabaseSync } from "node:sqlite";
2
2
  import type { FastifyInstance } from "fastify";
3
3
  import type { Need } from "../server/account_sign_in.ts";
4
4
  import type { DeclaredToken } from "../server/declared_tokens.ts";
5
+ import type { DataChange } from "../sync_protocol.ts";
5
6
  import type { App } from "./define.ts";
6
7
  import type { AppNotice } from "./protocol.ts";
7
8
  export interface HostContext {
@@ -23,6 +24,7 @@ export interface HostContext {
23
24
  window_in_front: () => boolean;
24
25
  icon_path: string | null;
25
26
  notify: (notice: AppNotice) => void;
27
+ withdraw: (key: string) => void;
26
28
  }
27
29
  export interface ServedTable {
28
30
  methods: object;
@@ -35,6 +37,7 @@ export interface HostServices {
35
37
  tables?: Readonly<Record<string, ServedTable>>;
36
38
  own?: unknown;
37
39
  after_remote_change?: () => void;
40
+ after_change?: (change: DataChange | null) => void;
38
41
  }
39
42
  export type StartServices = (context: HostContext) => HostServices | Promise<HostServices>;
40
43
  export interface AppRoutes {
@@ -96,7 +96,13 @@ function Pages({ pages, account }) {
96
96
  // A page with pages of its own shows the one the route names, or its first; with only one it is the page itself.
97
97
  const children = shown?.children && shown.children.length > 1 ? shown.children : [];
98
98
  const subpage = children.find((child) => child.id === rest[0]) ?? children[0];
99
- const label = shown ? (subpage ? `${subpage.label} · ${shown.label}` : shown.label) : is_account ? "Your account" : "Settings";
99
+ // Each listed page's items, such as paired devices, from its hook, called in the same order every time.
100
+ const listed = pages.pages.filter((each) => each.in_sidebar !== false);
101
+ const items = listed.map((each) => each.use_items?.() ?? null);
102
+ const shown_items = shown ? (items[listed.indexOf(shown)] ?? []) : [];
103
+ const item = subpage ? undefined : shown_items.find((each) => each.id === rest[0]);
104
+ const named = subpage ?? item;
105
+ const label = shown ? (named ? `${named.label} · ${shown.label}` : shown.label) : is_account ? "Your account" : "Settings";
100
106
  const view_key = shown?.view_key ? [section, shown.view_key(rest)].join("/") : route.parts.join("/");
101
107
  const chrome = pages.use_chrome?.(route.parts) ?? {};
102
108
  const theme = use_theme(app);
@@ -104,24 +110,22 @@ function Pages({ pages, account }) {
104
110
  document.title = `${label} · ${app.name}`;
105
111
  }, [label, app.name]);
106
112
  // Each listed page's badge, such as how many things wait, from its hook, called in the same order every time.
107
- const listed = pages.pages.filter((each) => each.in_sidebar !== false);
108
113
  const badges = listed.map((each) => each.use_badge?.() ?? null);
109
114
  const row_label = (index) => (badges[index] ? `${listed[index].label} · ${badges[index]}` : listed[index].label);
110
115
  const with_icons = listed.some((each) => each.icon);
111
116
  // An app's own sidebar content, such as a tree, takes the place of plain sections, so the pages show as rows above it.
112
- const folding = listed.some((each) => each.children && each.children.length > 1);
113
- const sections = listed.map((each, index) => ({
114
- id: each.id,
115
- label: row_label(index),
116
- href: `#/${each.id}`,
117
- ...(each.children && each.children.length > 1 ? { children: each.children.map((child) => ({ id: child.id, label: child.label, href: `#/${each.id}/${child.id}` })) } : {}),
118
- }));
117
+ const rows_under = (each, index) => (each.children && each.children.length > 1 ? each.children : (items[index] ?? []));
118
+ const folding = listed.some((each, index) => rows_under(each, index).length > 0);
119
+ const sections = listed.map((each, index) => {
120
+ const under = rows_under(each, index);
121
+ return { id: each.id, label: row_label(index), href: `#/${each.id}`, ...(under.length ? { children: under.map((child) => ({ id: child.id, label: child.label, href: `#/${each.id}/${child.id}` })) } : {}) };
122
+ });
119
123
  const views = listed.map((each, index) => ({ id: each.id, label: row_label(index), href: `#/${each.id}`, ...(each.icon ? { icon: each.icon } : {}) }));
120
124
  const view = shown ? shown.view(rest) : is_account ? _jsx(AccountPage, { account: account }) : _jsx(SettingsView, { pages: pages, is_admin: account === null || is_admin(account.me), viewer: account ? { client: accounts, me: account.me } : null });
121
125
  const framed = _jsx(Fragment, { children: view }, view_key);
122
126
  if (chrome.bare)
123
127
  return _jsx(_Fragment, { children: chrome.around ? chrome.around(framed) : framed });
124
- return (_jsx(Shell, { brand: app.name, brand_icon: pages.brand_icon ?? "icon.svg", ...(with_icons || (chrome.sidebar && !folding) ? { 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 }));
128
+ return (_jsx(Shell, { brand: app.name, brand_icon: pages.brand_icon ?? "icon.svg", ...(with_icons || (chrome.sidebar && !folding) ? { views } : { sections }), active: shown?.active_as ?? section, active_item: named?.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 }));
125
129
  }
126
130
  // ── App ──────────────────────────────────────────────────────────────────────
127
131
  // 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.
@@ -4,6 +4,7 @@ import { type AppNotice, type PageApi } from "../protocol.ts";
4
4
  import type { PhoneLifecycle } from "./android.ts";
5
5
  export declare function read_notice_switches(app: Pick<App, "desktop_settings">, saved: string | null): Record<string, boolean>;
6
6
  export declare function phone_notice_shower(plugin: LocalNotificationsLike, open_link: (url: string) => void): (notice: AppNotice) => void;
7
+ export declare function phone_notice_withdrawer(plugin: LocalNotificationsLike): (key: string) => void;
7
8
  export interface PortalOptions {
8
9
  lifecycle: PhoneLifecycle;
9
10
  notifications?: LocalNotificationsLike;
@@ -9,7 +9,7 @@ import { phone_certificates } from "../../phone_certificates.js";
9
9
  import { local_connection_storage } from "../../web/connection_storage.js";
10
10
  import { call_remote, follow_remote } from "../../web/remote_daemon.js";
11
11
  import { route_of_link } from "../links.js";
12
- import { data_change_of, notice_event, notice_is_on } from "../protocol.js";
12
+ import { data_change_of, notice_event, notice_is_on, notice_withdrawn_event } from "../protocol.js";
13
13
  import { host_tables_of, read_host_abilities } from "./hosts.js";
14
14
  // ── Switches ─────────────────────────────────────────────────────────────────
15
15
  // The notice switches this phone keeps, each of the app's `notify_` desktop switches at its default where unset.
@@ -36,6 +36,14 @@ export function phone_notice_shower(plugin, open_link) {
36
36
  void plugin.checkPermissions().then(({ display }) => (display === "granted" || display === "denied" ? undefined : plugin.requestPermissions()));
37
37
  return (notice) => void plugin.schedule({ notifications: [{ id: notice_id(notice.key), title: notice.title, body: notice.body, extra: { url: notice.url }, isExactNotification: false }] }).catch((error) => console.error("could not show a notice", error));
38
38
  }
39
+ // Takes a notice the host withdrew off the screen, and out of those still to show.
40
+ export function phone_notice_withdrawer(plugin) {
41
+ return (key) => {
42
+ const notifications = [{ id: notice_id(key), title: "", body: "" }];
43
+ void plugin.cancel({ notifications }).catch(() => undefined);
44
+ void plugin.removeDeliveredNotifications?.({ notifications }).catch(() => undefined);
45
+ };
46
+ }
39
47
  export async function portal_api(app, options) {
40
48
  const storage = options.storage ?? localStorage;
41
49
  const switches_key = `${app.id}-notice-kinds`;
@@ -67,6 +75,7 @@ export async function portal_api(app, options) {
67
75
  location.hash = route;
68
76
  };
69
77
  const show = options.notifications ? phone_notice_shower(options.notifications, open_link) : null;
78
+ const withdraw = options.notifications ? phone_notice_withdrawer(options.notifications) : null;
70
79
  if (link.daemon()) {
71
80
  follow_remote(link, (event, data) => {
72
81
  if (event === "hello")
@@ -77,6 +86,8 @@ export async function portal_api(app, options) {
77
86
  const parsed = data === "" ? null : JSON.parse(data);
78
87
  if (event === notice_event && show && notice_is_on(parsed.kind, switches()))
79
88
  show(parsed);
89
+ if (event === notice_withdrawn_event && withdraw && typeof parsed === "string")
90
+ withdraw(parsed);
80
91
  for (const listener of named.get(event) ?? [])
81
92
  listener(parsed);
82
93
  }
@@ -20,6 +20,7 @@ export interface AppPage {
20
20
  active_as?: string;
21
21
  view_key?: (parts: string[]) => string;
22
22
  children?: readonly AppSubpage[];
23
+ use_items?: () => readonly AppSubpage[] | null;
23
24
  }
24
25
  export interface AppSubpage {
25
26
  id: string;
@@ -13,7 +13,8 @@ import { PageHeading, SettingRow, SettingsPage } from "../../web/react/layout.js
13
13
  import { Loaded } from "../../web/react/states.js";
14
14
  import { RemoteAccessSettings } from "../../web/react/remote_access_settings.js";
15
15
  import { PeerListeningSettings, SyncSettings } from "../../web/react/sync_settings.js";
16
- import { attempt } from "../../web/react/toasts.js";
16
+ import { read_picked, save_text } from "../../web/files.js";
17
+ import { attempt, attempt_value, toast } from "../../web/react/toasts.js";
17
18
  import { calls, data_watch, page, use_settings } from "./page.js";
18
19
  // ── Sections ─────────────────────────────────────────────────────────────────
19
20
  // A phone's backups go in a folder picked once in its storage, where file managers and sync apps reach them.
@@ -57,6 +58,23 @@ function NoticeSwitches({ app, switches }) {
57
58
  attempt(switches.set(key, on));
58
59
  } }) }, key))) }));
59
60
  }
61
+ // Every setting but this device's own, as a file to take to another device or install, and read back.
62
+ function SettingsFile({ app_id }) {
63
+ const settings_calls = calls();
64
+ const export_file = async () => {
65
+ const file = await attempt_value(() => settings_calls.export_settings());
66
+ if (file)
67
+ save_text(`${app_id}-settings-${new Date().toISOString().slice(0, 10)}.json`, JSON.stringify(file, null, 2));
68
+ };
69
+ const import_file = async (text) => {
70
+ if (text === null)
71
+ return;
72
+ const result = await attempt_value(() => settings_calls.import_settings(text));
73
+ if (result)
74
+ toast(result.changed === 1 ? "1 setting set." : `${result.changed} settings set.`, { tone: "good" });
75
+ };
76
+ return (_jsx(SettingRow, { label: "Settings file", hint: "Every setting but this device's own, such as its notifications; keys for other services stay out.", children: _jsxs("div", { className: "button-list", children: [_jsx("button", { type: "button", onClick: () => void export_file(), children: "Export" }), _jsxs("label", { className: "button", children: ["Import", _jsx("input", { type: "file", accept: ".json,application/json", className: "visually-hidden", "aria-label": "Import settings", onChange: (event) => void read_picked(event).then(import_file) })] })] }) }));
77
+ }
60
78
  // A desktop window on a server's daemon, or a phone that keeps no data, works on the host's data, as a browser does.
61
79
  function storage_category(pages, is_admin) {
62
80
  const { app } = pages;
@@ -82,6 +100,7 @@ function storage_category(pages, is_admin) {
82
100
  }
83
101
  if (desktop && !on_server)
84
102
  sections.push({ id: "storage", heading: "Storage", hint: `Where this computer keeps its ${data_name}.`, content: _jsx(DataFolder, { desktop: desktop }) });
103
+ sections.push({ id: "settings-file", heading: "Import and export", hint: `Take ${name}'s settings to another device, or bring them back.`, content: _jsx(SettingsFile, { app_id: app.id }) });
85
104
  if (backups && (!on_server || is_admin)) {
86
105
  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.`;
87
106
  // This computer's backups folder opens in the file manager.
@@ -6,5 +6,6 @@ export interface ElectronBuilderOptions {
6
6
  categories?: readonly string[];
7
7
  link_scheme?: string;
8
8
  copyright?: string;
9
+ flatpak_permissions?: readonly string[];
9
10
  }
10
11
  export declare function electron_builder_config(options: ElectronBuilderOptions): Record<string, unknown>;
@@ -37,6 +37,7 @@ export function electron_builder_config(options) {
37
37
  `--filesystem=xdg-config/${options.id}:create`,
38
38
  // The login entry that starts the app in the background.
39
39
  "--filesystem=xdg-config/autostart:create",
40
+ ...(options.flatpak_permissions ?? []),
40
41
  ],
41
42
  },
42
43
  };
@@ -33,6 +33,13 @@ export interface LocalNotificationsLike {
33
33
  extra?: unknown;
34
34
  };
35
35
  }) => void): Promise<unknown>;
36
+ removeDeliveredNotifications?(options: {
37
+ notifications: {
38
+ id: number;
39
+ title: string;
40
+ body: string;
41
+ }[];
42
+ }): Promise<void>;
36
43
  }
37
44
  export interface PhoneNotice {
38
45
  key: string;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@x-tech-laboratories/x-app",
3
- "version": "0.122.0",
3
+ "version": "0.123.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": {