Skip to content

Desktop Integration

Wijanarko Putra Rajeb edited this page Nov 20, 2026 · 20 revisions

Desktop integration

Tray Icon and Start at Login (serve --tray / --startup)

  • The tray is a CHILD OF THE SERVER, and the process tree is the whole registration. serve --tray passes --tray into the server's argv (lifecycle/argv-flags.ts), and src/server/lib/tray/runtime.server.ts ensureTray spawns the platform host as a plain Bun.spawn child. There is no pid file, no status/stop for the icon and nothing to keep in sync: the host exits when the server exits, and the menu's Quit signals the server. This replaced a kabmo tray command that spawned the host detached and had to record a pid, answer tray status/tray stop and keep a record consistent — all of which the process tree now does for free.

  • The host watches its own parent, because a server can die without saying goodbye. getppid is polled on a timer (watchParent: in host/darwin.js, process.ppid in host/linux.js, the parent process in host/win32.ps1); when the server exits the host is reparented to launchd/init, the change is seen, and the icon goes away. Verified end to end: a fake server spawned the shipped host, exited, and the host terminated itself. That is what makes a SIGKILLed or crashed server leave no orphan icon.

  • Quit signals the SERVER, so the icon and the console end together. kill(getppid(), SIGTERM) on macOS (via ObjC.bindFunction), process.kill(process.ppid, 'SIGTERM') on Linux, taskkill /PID <parent> /T on Windows. Verified against a fake server: the Quit row produced a SIGTERM at the parent. A tray that outlived its server would be an icon for a port nobody serves.

  • Every host is a dumb renderer, and the SERVER is the brain. Each host draws its own menu (the rows are data: Open Console, Open Logs, Start/Disable Start at Login, Quit) and every path it needs comes from the config document the server wrote. Nothing in a host probes liveness or reads a record: there is no liveness question left to ask once the host IS the server's child.

  • The login entry runs serve --foreground, and that is the second load-bearing rule. launchd reaps a job's whole process tree when the job's program exits, so an entry that ran a detached serve (which returns as soon as the health check passes) produced no server at all — verified: launchctl print showed state = not running while the log recorded a successful start. In the foreground the CLI is the long-lived job, the server is its child, and the tray is the server's child: one tree, nothing exiting early. buildLoginEntryArgv (tray/entry.ts) also pins --prod (a login entry has no shell to export NODE_ENV) and carries --tray only when the registering invocation asked for it, so --startup alone is a supported shape.

  • --no-startup is a REGISTRATION change and returns before the port guard. Asking to stop starting at login must work whether or not something already serves the port. Measured with the handler below the guard: serve --no-startup on a busy port failed with "already served" and left the entry in place.

  • The host script is COPIED into the data directory before it runs (hosts.ts installHostScript → <data>/tray/host/, refreshed on every start). A login entry outlives the install that wrote it — an kabmo update replaces the package tree, a checkout moves — so the path baked into the plist, the .desktop file or the Run key has to be one only the data directory owns.

  • packageDir(), never import.meta.dir, resolves the shipped host. The production bundle flattens every server module into dist/client/index.js, so import.meta.dir is dist/client and the host sources are not beside it. Measured: the bundled server logged icon shown and then osascript: …/darwin.js: No such file or directory. The same rule is why entry.ts canonicalizes the CLI path with realpathSync — the CLI resolves its own root as <dir>/../.., and its path helper does not collapse a .., so a generated plist carried <pkg>/src/cli/../../src/cli/kabmo.js.

  • --no-startup lives in NEGATED_LONG, not BOOLEAN_LONG, and that is the whole reason it works. BOOLEAN_LONG stores a flag under its own spelling (options['no-startup']), while the command reads options.startup — so the flag parsed and the command never saw it. src/cli/lib/args.test.js pins the mapping, so a new hyphenated flag has to choose a side. startup is tri-state (null unmentioned, true install, false remove), because "install" and "remove" must be told apart from "not mentioned".

  • Linux is the one platform that can lack a tray client, and the server says so and keeps serving. yad and zenity are absent from a default install on many distributions, and no icon can be drawn without one — so ensureTray returns {started:false, reason} and the entry logs tray: not shown — … with the package to install. macOS and Windows always have a tray API. ensureTray never throws: a tray is a convenience over the console, never a prerequisite for it.

  • ensureTray is idempotent through a globalThis slot, for the reason the database handle is anchored there: bun --hot re-runs the server entry, and without the slot the reload would spawn a second icon beside the one the first generation still holds.

  • host/linux.js runs main() only when it IS the program (Bun.argv[1]?.endsWith('linux.js')). Without the guard, importing the module to assert its payload builders started a tray from the importing process's argv — which is exactly how the first test run failed.

  • buildTrayConfig resolves every path a host needs, per PORT (<data>/tray/<port>.config.json, mode 0600, rewritten on each start): the bun binary, the CLI entry, the icon, the log file, the URL and its scheme, and whether a login entry exists (so the menu can label its row without a subprocess). The scheme comes from the listener rather than the flag alone — a --tls server answers nothing on HTTP, so a wrong scheme would make "Open Console" open a URL that cannot connect.

  • The tray icon has TWO styles, and the choice is a separate setting from the in-app icon style (trayIconStyle in shared/lib/theme/tray-icon-style.ts, Settings → Appearance → Shell → Tray icon). color is the shipped app icon, plate and all, and is the default so an upgrade changes nothing. monochrome is a GREYSCALE conversion of the app icon, not a black-and-white silhouette: the green plate becomes dark on a light theme and light on a dark one, the cream K strokes become light on a light theme and dark on a dark one, and the orange arm becomes the middle grey in both (public/tray-monochrome-light.png / -dark.png, generated by scripts/tray-icon.mjs). Two files are shipped because the plate and the strokes swap luminance with the theme; the orange arm does not. The greys are drawn AS-IS on every platform, including macOS: a template image would be repainted in the menu bar's own ink (black or white), which is not the conversion the setting promises. The setting is separate from iconStyle because the tray is a SYSTEM surface: a monochrome menu-bar glyph beside full-colour console marks is the macOS convention.

  • The tray host reads its config ONCE, so a settings edit is pushed to it (refreshTrayIcon in tray/runtime.server.ts, called from routes/settings/root.ts when the patch names trayIconStyle or theme). The old child is stopped and a new one started with the same listener facts; when nothing moved the call is a no-op, which is what makes it safe after every settings write. The theme is included because it picks which greyscale plate (light or dark) the host draws.

  • The Windows host loads the PNG through a Bitmap, not System.Drawing.Icon (host/win32.ps1). Icon only reads .ico files, and constructing it from the shipped PNG throws; Bitmap.FromFile(...).GetHicon() is the documented way to turn a PNG into a NotifyIcon icon. The macOS host and the server half are verified; the Windows host's API surface is the documented one and was not exercised on this machine.

  • State lives in <data>/tray/: <port>.config.json (what the host reads) and host/ (the extracted scripts). MOCK is irrelevant here — a tray watches a server, not a dataset.

Starting a Local Server From the Shell

  • The child gets the SAME PATH the lookup used, because the CLI is a #!/usr/bin/env bun script (and a Windows shim on Windows). which("kabmo") probes ~/.bun/bin explicitly (a Finder/Start-menu/.desktop launch inherits a minimal PATH), but the spawn inherited the app's minimal PATH, so the kernel's /usr/bin/env bun answered env: bun: No such file or directory in desktop-<port>.log — measured on macOS: three clicks, three identical lines, and the panel reported "The local server exited during startup". Each shell now widens the child's PATH with the one list its lookup also reads: spawnEnvironment()/searchDirectories() (System.swift), child_path()/search_directories() (system.rs), LaunchPlan.ChildPath()/SearchDirectories() (LaunchPlan.cs). Verified on macOS by spawning /bin/sh -c 'printf %s "$PATH"' under env -i PATH=/usr/bin:/bin and reading ~/.bun/bin back from the child; the Windows and Linux rules suites assert the same widening.
  • A shell owns ONE local server, and the STORE enforces it. ServerStore.start refuses while a recorded pid (spawned) still answers — runningOwned() (Swift), running_owned() (Rust), RunningOwnedAsync() (C#) — with the sentence "A local server is already running (…). Stop it before starting another." A second server shares the same data directory: one database, one plugin set, one tray slot, and another omp child. Measured before the rule: two sequential Supervisor.start calls on free ports returned local:64400 and local:64401, both alive. The panel renders the fact instead of the button ({label} is running — stop it to start another.), and a recorded pid whose server DIED does not block — that Start is the restart. The three rules suites assert both halves (refused while one answers, allowed when the recorded one is dead).
  • A dead row still offers Remove. Stop requires owned && running; Remove used to require !owned, so a server this shell started that had died had NO action and could not be cleared without reloading the page. The rule is now !owned || !running, in server-control/Row.tsx (split out of Panel.tsx for the 350-line ceiling).

The macOS Menu Bar

  • The menu bar is a LIBRARY TABLE, and that is the fix for the Edit menu shipping missing. packages/macos/Sources/KabmoDesktop/MenuBar.swift builds App/File/Edit/View/Window/Help; App.swift only installs it (NSApp.mainMenu, servicesMenu, helpMenu, windowsMenu). Tests/MenuBarTests.swift asserts the same table the app installs, so a row that disappears fails a test instead of shipping. The Edit menu's rows stay in EditMenu.swift because a WKWebView receives no ⌘C/⌘V/⌘X/⌘Z/⌘A without a menu item declaring the chord.
  • A row that runs a PAGE command declares NO key equivalent. AppKit handles key equivalents before the first responder, so a native row declaring ⌘B consumes the chord and the page's dispatcher (client/lib/commands/dispatcher.ts) never sees it — the same mechanism the Edit menu documents from the other side. The catalog is the single source for a chord, including the user's overrides, so a second copy in the menu would drift and would keep firing a chord the user rebound. The row calls window.__kabmoRunCommand(id) instead (client/lib/native/run-command.ts), and the id rides representedObject.
  • ⌘= does not match a "+" key equivalent, and a hidden alternate is the fix. Measured with NSMenu.performKeyEquivalent on macOS 27: an item declaring "+" with .command answers false for ⌘=, and a hidden item declaring "=" answers true. The View menu therefore carries a visible Zoom In (⌘+) and a hidden Zoom In (⌘=); the hidden row participates in matching and is never drawn.
  • AppKit appends the window list to windowsMenu but NOT "Bring All to Front". Measured: after windowsMenu.update() with one window, the menu held ["Minimize", "", "Probe Window"] — the window entry appeared, the Bring All row did not. So that row is stated in the table rather than assumed.
  • servicesMenu and helpMenu are set, and each buys something specific. Without NSApp.servicesMenu the Services submenu is absent, which removes every system service from selected text; NSApp.helpMenu is what makes AppKit add the Help search field. The Help rows are Kabmo Help (the wiki), Keyboard Shortcuts (a page command) and Report an Issue….
  • The Web Inspector is gated by the BUILD, not by a toggle that reloads. isInspectable is set once at web-view creation from #if DEBUG / KABMO_DEVTOOLS=1; the old row toggled it and called reload() to make the change take effect, which discarded the live document. The row is a checkmark ("Allow Web Inspector", ⌥⌘I) and only exists in a build that enabled it.
  • Page zoom is remembered per HOST, because pageZoom is reset by every navigation. ZoomStore (pure, tested) owns the clamp (0.5–3), the 10% step and the zoom.<host:port> key; didFinish re-applies it. Without this a reload — ⌘R, the shell's own recovery, a server restart — put the page back at 100% for a user who had zoomed in to read the timeline.
  • The full-screen row names the transition it will perform. validateMenuItem rewrites "Enter Full Screen" to "Exit Full Screen" while the window is full screen, and draws Keep on Top's checkmark from window.level. A static "Toggle Full Screen" is not what HIG asks for.

Documents Opened From the OS (Finder / Explorer / Linux desktop)

  • Kabmo is a document HANDLER on all three desktop shells: a .pdf, .docx, .xlsx, .md, .csv, .svg, an image or a .log can be double-clicked, dropped on the Dock/taskbar icon, or picked from "Open With" — and it opens a tab in the console. Three declarations make that true, and they are RENDERED FROM ONE TABLE (release/document-types.mjs) by scripts/shell-document-types.mjs, because each lives in a file a person could edit and each drifts SILENTLY: the app still installs, it simply stops appearing in "Open With" for a format added later. bun run shell:docs writes them; bun run shell:docs:check is the CI gate (gates.yml) and release/document-types.test.js asserts every artifact against the table.

    • macOS — CFBundleDocumentTypes in Info.plist, injected by packages/macos/scripts/build-app.sh from --plist. Every row is CFBundleTypeRole: Viewer + LSHandlerRank: Alternate, which is what makes Kabmo an OPTION and never the app that takes every PDF on the machine; the build then plutil -lints the assembled plist, because a malformed one makes macOS refuse to LAUNCH with no message. Verified: after lsregister -f, NSWorkspace.URLsForApplicationsToOpenURL for a .pdf lists …/build/Kabmo.app beside Preview and Chrome.
    • Linux — the .desktop entry's MimeType= (from --mime) and Exec=@EXEC@ %F. %F is the half that makes it a document handler: without it the launcher starts the app and drops the file. build-app.sh writes the list to mime-types.txt in the tarball and install.sh + all three packagers (deb, rpm, AppImage) fill the token, so a published install needs no scripts/ directory to render it.
    • Windows — packages/windows/installer/document-types.iss (GENERATED, #included by kabmo.iss) registers Software\Classes\Applications\Kabmo.exe — the entry "Open with" lists — plus one <ext>\OpenWithProgids value per extension. OpenWithProgids and never Progid: the latter TAKES THE EXTENSION OVER. ChangesAssociations=yes is what makes Windows rebuild the cached menu; without it the entries land in the registry and Explorer keeps serving the old list until the next logon.
  • The shell collects the paths and the PAGE opens the tabs, because no browser API can see a launch. WKWebView gets no File for an openFiles: callback and WebKitGTK has no launchQueue; the page-level PWA path (client/lib/launch/file-handlers.ts) only exists in Chromium and only for an installed PWA. So each shell owns a queue and one delivery rule:

    • macOS — applicationWillFinishLaunching queues launchPaths(from: ProcessInfo.processInfo.arguments) (which is how open -a Kabmo x.pdf arrives) and application(_:openFiles:) queues a double-click; both land in OpenPathQueue and are flushed on didFinish, the first moment a page can answer. The answer is always .success — a file the editor refuses belongs on the console, where the sentence can be read, not in Finder's own error dialog.
    • Linux — Gio.ApplicationFlags::HANDLES_OPEN is what makes the app a handler at all; with it a launch that carried files emits open INSTEAD of activate, so ensure_shell builds the shell for whichever signal arrives first and the argv batch is queued only when the shell is actually built — otherwise a later activation from the dock re-queued the file the app started with.
    • Windows — Environment.GetCommandLineArgs() in the constructor, flushed on NavigationCompleted. The rules (LaunchPaths.From, OpenPathQueue, OpenPathsScript.For) live in the LIBRARY, not in ShellHost, so the suite can drive them with no window.
  • Delivery is window.__kabmoOpenPaths(paths) — a plain function, not a bridge command. evaluateJavaScript/run_javascript/ExecuteScriptAsync all reach it, the page needs no reply, and the console reports its own refusals. The script is built by the JSON encoder in every shell (openPathsScript, openPathsScript, OpenPathsScript.For): a filename may contain a quote, a backslash or a newline, and hand-built interpolation is how one of them turns a value into source. Verified against a real WKWebView: a batch with quote"and\back.md arrives as that exact string.

  • The queue TAKES, and it de-duplicates. A taken batch is gone, so a reload cannot reopen the file the user closed; a duplicate (a second activation, open -a delivering the same path on argv AND through openFiles) opens one tab. The macOS/Windows suites assert both; the Linux rules suite drives the same table.

  • A file the OS hands over is usually OUTSIDE every workspace, so the gesture itself is the permission. POST /api/fs/grant (routes/fs/grant.ts) registers the file's own DIRECTORY in lib/fs/external-roots.ts and then answers the same scope payload /api/fs/scope would have. Five bounds, each a security property rather than a convenience: a grant names a directory (not a subtree), the filesystem root is refused outright, only an ABSOLUTE path can grant, the set is bounded (MAX_EXTERNAL_ROOTS 8, oldest evicted, re-granting moves a root to the newest position), and it lives on globalThis so bun --hot cannot drop the root an open tab's file sits in. The route is a POST with a JSON body and a same-origin check (isSameOriginRequest), because a cross-origin page can fire a no-cors request at localhost without reading the answer and a grant is a lasting change.

  • resolveOpenableFile (client/lib/fs/resolve-open.ts) is the ONE place an absolute reference becomes a tab, shared by the OS-launch path and the editor's drop target. It asks /api/fs/scope first and retries through /api/fs/grant ONLY for code: 'outside_workspace' — a file inside a workspace must not be granted, because the list is bounded and every ordinary open would evict a real one. A binary or oversized file is refused with the server's own sentence instead of opening a tab whose whole content is that sentence.

  • scope.ts exports describeFileReference so the grant route answers with the SAME classification — a second copy is how a granted file and a workspace file end up opening with different kinds.

  • Verified end to end, on an isolated MOCK server: the built Kabmo.app launched with a file on argv connected to the console, the page opened a tab, and session_ui_state recorded {"name":"probe.md","path":"probe.md","root":"/tmp/kabmo-shell-probe"} — the grant, the relative path and the tab, all three. The same page also opened a file handed over through window.__kabmoOpenPaths in a browser, which is the half that has no shell at all.

  • The PHONE shells open documents too, and the bytes travel through the PAGE because the console is not on the phone. Both are declared from the same release/document-types.mjs table (--android → the intent-filter region of AndroidManifest.xml; --ios → the CFBundleDocumentTypes region of packages/ios/Resources/Info.plist), so a format added for the desktop trio cannot be missing on a phone. Android gets TWO filters (VIEW for a file manager, SEND for the share sheet), BROWSABLE on VIEW only, and no android:priority — a priority makes Kabmo the PREFERRED handler, the same overreach as CFBundleTypeRole: Owner. iOS adds LSSupportsOpeningDocumentsInPlace, so "Open in Kabmo" hands over the original URL instead of copying a 20 MiB workbook into the app's Inbox.

  • device-files.ts is the receiving half on the phone, and the tab it opens is READ-ONLY. Neither shell can hand over a path the server could read — the file is on the device, the console is elsewhere — so the shell reads the bytes and pushes them in, announced first and streamed as base64 in chunks (__kabmoOpenFiles([{id,name,mimeType,size}]) then __kabmoOpenChunk(id, base64, last)), because one evaluateJavascript/evaluateJavaScript of 27–43 MiB is a multi-second main-thread stall. The page accumulates and only DECODES on the final chunk, so a transfer that dies halfway can never open as a truncated document, and the chunk boundary is a multiple of four so each piece decodes on its own — a boundary that is only correct because the other side happens to join first is a rule waiting to be broken.

  • A device-backed tab carries handleId (the in-page byte registry) and its own deviceFile flag, and the three states say three different things. handleMissing ("the permission ended — reopen from the OS"), deviceMissing ("the bytes did not survive the reload — open it again from the app that shared it") and the live case ("opened from this device, read-only; copy it into a workspace"). The Save button is disabled in all three, each with its own sentence — measured in the browser: before the flag existed a device tab said "Nothing to save — this file could not be read" over a document that was on screen. saveEditorFile refuses a handleId whose registration is gone, so nothing is ever posted to /api/fs/action under a display name (pinned by save-file.test.ts).

  • What is NOT covered by a test: the Windows and Linux shells are reviewed and syntax-checked here but not compiled (no dotnet, no GTK on this machine); their suites run in publish-windows.yml and publish-linux.yml. The macOS delegate's three lines are the only unexercised part of that shell — the queue, the script and the delivery into a real webview are all pinned.

Downloads (the pairing QR, and every file the console offers)

  • A download in a shell must be an HTTP URL the host fetches itself. The page cannot hand a Blob to the operating system: Android's DownloadListener explicitly ignores blob: and data: URLs, WKWebView treats a blob: navigation as a document, and WebKitGTK cancels a transfer with no destination. So the pairing QR is served by GET /api/connect/pair/qr.png?pairingId=… (routes/connect/pair-qr.ts) and the dialog's Download control is a plain <a href download>. The PNG is drawn once at mint time (lib/connect/qr-png.server.ts, a hand-written 1-bit greyscale PNG) and held with the pending pairing for its five-minute life — the download request cannot re-render, because it never runs the page. Measured: a 29-module code is 370x370 px at 10 px per module, sips reads it, and jsQR decodes the produced bytes back to the payload.
  • canShowMIMEType is NOT the download test; Content-Disposition is. Measured in a real WKWebView: a response carrying attachment; filename="kabmo-pairing-qr.png" still reports canShowMIMEType == true for image/png. A policy that only asked "can the web view show this?" therefore displayed the image and saved nothing — the "the button does nothing in the shell" report. Both Apple shells now treat an attachment disposition (the TYPE, not the word inside a filename) as a download (DownloadPolicy in iOS, DownloadFile.isAttachment on macOS).
  • macOS had no download handling at all, and a download attribute is an ACTION decision there. WKNavigationAction.shouldPerformDownload must be answered with .download, and WKNavigationResponsePolicy.download needs a WKDownloadDelegate or the transfer fails with no destination. ShellDownloads writes to ~/Downloads, never overwrites (qr.png → qr 2.png) and reveals the finished file in Finder. Verified with a real WKWebView against an attachment response: the click produced shouldPerformDownload, the delegate wrote the file, and the bytes were identical to the served PNG.
  • Linux needs an explicit download-started destination (main.rs, connect_download_started → WebKitDownload::set_destination). Without it WebKitGTK cancels the transfer silently. The naming rules live in src/downloads.rs and the rules suite pins them.
  • Android writes through DownloadManager with the WebView's cookie (KabmoDownloads) and needs WRITE_EXTERNAL_STORAGE capped at API 28 for setDestinationInExternalPublicDir; from API 29 scoped storage needs nothing. Windows needs no code: WebView2's default download handling saves the attachment and shows its own UI.

System Notifications (finished / waiting / failed)

  • All three preferences ship FALSE, and permission is asked only when one is switched on. notifyOnFinish, notifyOnAsk and notifyOnError (settings → Notifications) default to false, and isNotificationEnabled accepts only the literal true — a truthy string from a hand-edited blob must not opt a user into OS banners. Turning one on calls notification_request; the Android shell asks for POST_NOTIFICATIONS there (API 33+, a runtime permission a WebView cannot request), and iOS/macOS call requestAuthorization. A fresh install is therefore never prompted for a banner it did not choose. Opening the settings page with a preference already on asks again, which covers "enabled in another tab/device".
  • The Notifications page has two DELIVERY sections — Desktop and Mobile — plus the three event triggers. notifyDesktopEnabled / notifyMobileEnabled ship true and only the literal false silences a platform (isNotificationPlatformEnabled): the master keys postdate the feature, so an install that already opted into an event must keep receiving it, while the events stay the opt-in (false until chosen). notificationPlatformForClient() picks the section from the DEVICE — a phone/tablet user agent, or a coarse primary pointer, or touch points plus hover: none — never from window width: a narrow desktop window reflows the shell but still answers to Desktop. A banner is sent only when its event is on AND its platform's master is on.
  • A banner is sent in EVERY window state. There is no focus gate: the event switch and the platform master are the only conditions, so a focused Kabmo still gets the banner the user asked for. visibilityState / hasFocus no longer decide anything, and the shells make the platform agree (see willPresent below).
  • The SERVER decides an event, and two transports deliver it. A run settling and an agent parking a dialog are written to notification_events (server/lib/notifications/feed.server.ts), gated there by the event switches, then fanned out twice: the realtime notifications topic for an open page, and GET /api/notifications/stream for the Android shell. The decision used to live in the page, which diffed consecutive sidebar:status snapshots — and that is what broke on a phone: a backgrounded WebView is FROZEN, so it sees no transition, and the one snapshot it finally receives on resume carries the whole backlog, which fires every banner in a burst (the reported "no notification while the app is closed, then all of them at once"). A page that never had to infer the event cannot replay one. The topic's snapshot is deliberately EMPTY, for the same reason: a reconnect must not re-announce.
  • A banner names the EVENT's moment and the run's length. The event carries at (epoch ms) and durationMs; Android sets setWhen(at) with setShowWhen(true), so a banner delivered after the app is reopened names when the run ended instead of claiming it just happened, and renders the duration in setSubText (48s / 3m 12s / 1h 04m, truncated). The duration comes from session_stream_state.started_at, written only on the transition INTO stream — a run writes stream several times (prompt dispatch, agent_start, a model change), and restarting the clock on each would report the last frame's age. An ask has no duration and shows no subtext rather than "0s". The browser path uses Notification.timestamp; shells without a duration slot omit it.
  • A banner's text is stripped of glyphs the shade cannot draw. A session title is arbitrary text — Nerd Font icons and Powerline separators are pasted into names because a terminal-wide font draws them — and the Android shade uses the system font, which has no Private Use Area coverage, so each icon arrived as a tofu box. notificationText removes the three PUAs, variation selectors and zero-width controls and collapses whitespace, BEFORE the length clip so the budget counts drawable characters; emoji, CJK and punctuation survive, and an icon-only title falls back to Kabmo.
  • The Android shell keeps its own stream while the app is away. A specialUse foreground service (NotificationWatchService — not dataSync, which Android 15 caps at six hours a day) holds GET /api/notifications/stream?platform=mobile&after=<id>, started by notification_watch (pushed by the console on boot and on every switch change) only while the shell's OWN Notify while closed switch is on (AndroidWatch.backgroundWanted, default off) — while the page is still visible, because Android 12+ refuses a foreground-service start from the background — and stopped when the switches, or that switch, go off. The cursor is a persisted per-server id: after=<last id> resumes, and NO cursor is answered with a cursor frame carrying the newest id rather than the outbox, so a fresh install never announces history. The disabled frame means the mobile master is off — the stream stays open with heartbeats because the setting can be flipped from another device.
  • The watcher is gated four ways, and each gate is a cost that was being paid for nothing. WatchPolicy.shouldRun(armed, background, canPost, hasServer) (JVM-tested) decides: the console's switches, the shell's own opt-in to the ongoing row (background, default off — Android forces a foreground service to show a notification, so running by default put a permanent "Agent notifications are on" row on every install with any switch on), the OS POST_NOTIFICATIONS grant (API 33+ — denied means every show is a no-op, so the socket and the ongoing row are pure cost), and a saved address. MainActivity.onResume re-arms, so a grant given after the switches were turned on starts it, and the watch loop re-reads the grant every pass, so a revocation stops it. The stream's heartbeat is 60 s (it was 25 s, which woke the radio more than twice as often for the same liveness proof), and the shell reads with a 150 s timeout: 0 left a socket that died without a FIN blocked forever, so no banner arrived again until the app was reopened. While the console is in front (ShellVisibility, set from onStart/onStop) the PAGE posts and the watcher only advances its cursor — both posting was a second notify for the same tag and id. Doze is best-effort by design: no wake lock, because one would cost more than the banner it saves.
  • Finish and error are read from the SHARED session list, not the open timeline. The transition is detected SERVER-side (markStreamStatus reads the row it is about to replace, so a repaired terminal write is not news) and announced through the notification feed; useNotificationEvents in the page only posts what it is handed. An abort is silent (the user stopped it, or a heal pass settled a process that was already gone), and an ask is noteAwaitingInput, fired where the dialog is parked (RPC trackUiDialog, ACP answerPermissionRequest).
  • A failed run is the SAME transition with runFailure set. session_stream_state.failure is written by the RPC terminal settle (endedFailure) and by ACP's settleAcpTurn (its failed/failure verdict), and by the MOCK stream's catch and the child-exit path. markStreamStatus writes it only on finish and CLEARS it on every new stream, so a normal second run is not announced as the first run's error. The reason is the notification body, clipped in the client.
  • Four shell commands, one shape across five shells. notification_request answers {granted} in the state AFTER the prompt; notification_show takes {title, body, kind, tag, sessionId} — kind (finish / error / ask) selects the chime, see the next bullet. Android posts through NotificationManager on a kabmo-agent-v2 channel, or kabmo-attention-v2 for an ask (NotificationCommands is the pure, JVM-tested wire; AndroidNotifier owns the platform objects); iOS and macOS use UNUserNotificationCenter with the tag as the request identifier; Linux spawns notify-send --wait --action=default=Open --app-name=Kabmo --icon=kabmo --hint=string:sound-file:<path> -- before the text, so a title beginning with - cannot become a flag; Windows posts a Shell_NotifyIcon balloon (NIIF_NOSOUND plus the embedded chime), which Windows 10+ presents as an Action Center toast (an unpackaged WPF app has no toast registration, and the tray icon is released with the window). The tag replaces an earlier banner for the same event; Windows' balloon API has no tag and replaces its own last balloon.
  • A DENIED grant is a fact the page must know, and it is read WITHOUT prompting. notification_state answers {status, canOpenSettings} — granted / denied / notDetermined / unknown — from UNUserNotificationCenter.getNotificationSettings on macOS and iOS, and from NotificationManager.areNotificationsEnabled() plus the runtime permission on Android (which is why Android's isGranted is no longer just POST_NOTIFICATIONS: a granted permission with the per-app toggle off drops every notify() silently). Windows and Linux do not answer it — neither exposes a queryable per-app grant, and Linux has no portable settings screen for it either — so the page keeps unknown rather than guess. The page reads it at boot (main.tsx) and again whenever the Notifications page mounts or regains focus, because the fix happens in the system settings. notification_settings_open opens that screen (macOS: the Notifications pane; iOS: the app's Settings page) and a refusal is a sentence, not a silent no-op. Measured on macOS 26: the shell posted every banner, willPresent answered [.banner, .list, .sound], and usernoted logged authorizationStatus: Denied plus Presenting … as none — the switches read "on" while nothing arrived. The page now states the refusal inline on the Notifications page AND in a modal mounted once at the app root (NotificationPermissionDialog), shown on boot whenever notifications are ACTIVE (an event preference plus this device's master) and the grant is denied or notDetermined — the failure was invisible precisely because it only lived on a page the user never opened. notDetermined offers the prompt (from the click, which a browser requires); dismissal is per page load. nativeBannerPlaysSound returns false on a denied grant, so the Web Audio cue plays instead of being handed to a banner the platform drops.
  • The banner carries the Kabmo chime, and the page goes silent inside a shell. A shell's notification plays the same two cues the console synthesizes — a climbing two-tone sine for finish/error and a falling triangle for ask — from packages/notification-sound/kabmo_notification.wav and kabmo_attention.wav, rendered by generate.mjs from the numbers in client/hooks/ui/notification-sound.ts. The raw Web Audio envelopes peak at -17 and -14 dBFS (measured on the render), which is right for a cue mixed against nothing and inaudible under the OS's notification volume, so each file is normalized once to -2.5 dBFS by a single linear factor. Nothing copies them into a source tree: the Android Gradle build copies them into a GENERATED res/raw (a committed second copy would drift the first time one is regenerated — NotificationSound is the JVM-tested URI/channel rule), build-ipa.sh puts them in the bundle root, build-app.sh in Contents/Resources — both under a VERSIONED name (kabmo_notification-<version>.wav), because UNNotificationSound(named:) caches a failed lookup by name: a name that was ever missing stays missing after the file is added, and the platform plays its own tone instead. The runtime builds the same string from CFBundleShortVersionString, so every release is a fresh lookup and the two sides cannot drift. Measured on macOS 26: the daemon resolves the sound against the app record usernoted keeps, and a record built from a DIFFERENT bundle with the same CFBundleIdentifier (a mounted DMG, the dev build app) makes every lookup fail with ToneLibrary's toneWithIdentifierIsValid: NO and fall back to built-in action 22 (mDataSize 252462); ejecting the stale copies, lsregister -u the dev build, and restarting NotificationCenter/usernoted made the bundle's kabmo_notification-0.12.5.wav play (mDataSize 44100). The shell now heals this itself: NotificationRegistration re-registers the installed bundle and restarts usernoted/NotificationCenter once per version — after ShellUpdater swaps the bundle, and from applicationDidFinishLaunching for a manual install — so an update repairs a stale record without a reboot. The Linux binary carries them via include_bytes! and writes the one the daemon is pointed at into XDG_RUNTIME_DIR, rewriting it when the bytes differ. Measured 2026: GNOME Shell honors sound-file (js/ui/notificationDaemon.js reads the hint into MessageTray.Sound), KDE Plasma honors it from 6.4 (bug 472037, fixed by commit 1b25adde; Plasma ≤6.3 ignores every sound hint), and dunst/mako have their own sound settings rather than the hint. When GetCapabilities does not advertise sound, the shell plays the chime itself (paplay/pw-play/aplay/ffplay) and passes suppress-sound, so a daemon with no sound support still gets the cue; when the capability cannot be read, the sound-file hint stays. No update heal is needed there: the new binary rewrites the same path, and the daemon reads the file when it plays. Android needs TWO channels because a channel's sound is frozen at creation and setSound on the builder is ignored on API 26+ — the ids carry -v2 and the pre-chime kabmo-agent is deleted, or an upgraded install would keep the default tone. nativeBannerPlaysSound is the other half: a shell with the event switch and the platform master on owns the sound, so triggerChatCompletionSound / triggerInputRequiredSound return without touching Web Audio. Without that gate both fire for one event within a few hundred milliseconds — the double chime this exists to remove. A browser, or a shell whose banners are off, keeps the Web Audio cue (nothing else would make a sound). Windows plays the same chime: a balloon has no "play this file" slot, so the shell suppresses the platform tone with NIIF_NOSOUND and plays the embedded WAV with PlaySound; kind selects the cue. The WAVs are embedded in the assembly and written to %TEMP% once, rewritten when the bytes differ, so an update never keeps the previous cue.
  • Outside a shell the browser's Notification API is the fallback, and it is used only when permission is already granted — the client never prompts from a background event. Android Chrome's new Notification() is refused (notifications there require a service worker), which is reported once and does not affect the shells.
  • A click lands on the session, not merely on the app. Every shell carries the session id as part of the notification (userInfo on Apple, an Intent extra on Android, the last-posted id on Windows, the default action on Linux) and runs window.__kabmoOpenSession(id) — the same ?sessionId= write a sidebar click makes (client/lib/router/open-session.ts). The id is JSON-encoded in every shell, because an interpolated quote would become source. A cold-start click is QUEUED until the first finished load (Android's pendingScripts, iOS/macOS's pendingNotificationSession, Linux's page-readiness flag), and the Android Intent extra is removed once read so a rotation cannot replay it.
  • macOS and iOS install a willPresent presentation returning [.banner, .list, .sound], and the sound is the named Kabmo chime (UNNotificationSound(named:), the file the bundle scripts copy) rather than the platform default. Without it UNUserNotificationCenter's default suppresses a notification for the frontmost app, which — now that the client sends regardless of focus — would swallow every banner while Kabmo is the window the user is reading. The delegate still handles didReceive for the click, and both shells queue its session until the first finished load. The macOS app must be the bundled, signed .app for UNUserNotificationCenter to register; swift run is not a supported place to test notifications.

The Launch Splash When the Console Cannot Be Reached

  • The failure splash offers TWO actions, and the second one is the way out. Retry reloads the address on screen; Server settings opens a native form — an address field prefilled with the address the window was trying, the servers this shell already remembers, and Connect. The console's own server control is a PAGE, so the one moment a user needs to change the address is the one moment there is no page to open it from. Android's SettingsActivity was already that way; the three desktop shells had only Retry, which left a wrong port fixable only by editing servers.json.
  • The button plates come from the palette, not the platform's control style. The shipped Retry was NSButton(bezelStyle: .rounded) on macOS, WPF's default Button template on Windows and a bare GtkButton under Adwaita on Linux — each a system-grey control on the console's paper ground, unreachable from ShellPalette. They now use the same filled/outlined pair the Android and iOS overlays draw: the primary filled with ink and labelled in canvas, the secondary on paper with the ink label and a hairline border, at 13pt with an 8pt corner, 16 x 6 padding and 30pt minimum height. On Windows that needs a ControlTemplate (Aero2 ignores CornerRadius); on Linux it needs background-image: none (Adwaita paints a gradient over the background colour).
  • The rules are a value type, and the dialog only draws it. ServerSettingsForm (Swift, C#, Rust) holds the prefill, the picker's rows and the address validation (normaliseUrl/ServerAddress.Normalise), so every rule that fails silently — a field prefilled with an address nobody typed, an address accepted that the store would refuse — is asserted in each shell's rules suite without a window.
  • Connect is connectRemote, and a remembered address is not a duplicate. ServerStore.connectRemote normalises, reuses the row when the address is already in the list (activate would otherwise be preceded by an addRemote that throws "already in the list"), selects it and probes. A remote that does not answer is refused with its own sentence, and the sheet is re-presented with what the user typed — the alert/dialog has already closed when Connect is pressed, so that is the only place the refusal can be read.

Clone this wiki locally