Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.
Desktop notifications over Workbench SSE
Status
Frozen implementation contract for gap G4. Companion to
desktop-product-gaps.md (G4) and desktop-start-receipt.md (ownership of
the Runtime is already settled; this contract does not reopen it).
Owner: Avibe core
Date: 2026-09-10
Baseline: desktop branch after #1975 / #1977 (tray + start-receipt).
Account/category extension: 2026-11-02, consuming #3127's merged preferences
and Inbox badge contract (workbench-refinements.md).
Product outcome
When the Avibe window is unfocused or closed (tray still alive), the user gets a native OS notification for the two classes of event that actually need them to look:
- A Vault request that is waiting on them (
approval.requested). - A background agent run that has reached a terminal state
(
run.terminal), only if the run was clearly backgrounded or ran longer than ~30 seconds.
Default on. The tray has a checkable "Notifications" item that persists
this device's preference. Account-wide enabled, bots, and sessions
preferences provide a separate gate, described below. System Focus / Do
Not Disturb is left to the OS; Avibe does not reimplement it.
Notification activation follows the OS-default behavior described in
Click below. Deep-link navigation into a specific session
(avibe://session/<id>) is G5 and is not in this slice.
Why SSE, not polling
The shell already probes GET /ready every two seconds after navigation;
that loop is the liveness signal ("is the Runtime still there?").
Attention ("something needs you") is a different job. Polling it off
/ready would:
- bound notification latency to the probe period (bad for blocking Vault approvals);
- tax a tray-resident Agent OS with permanent empty-cycle HTTP;
- fork the product's event model: Workbench already consumes SSE, desktop notifications would pull.
v1 therefore reuses the existing event source (GET /api/events)
and leaves /ready as liveness-only.
Frozen transport
Endpoint
GET {origin}/api/events on the adopted Runtime origin (the same
loopback origin the shell already validated and navigated to).
No new HTTP route. The Workbench EventSource client at
ui/src/context/ApiContext.tsx already opens this path with no extra
auth on loopback; the shell does the same. Adding a cookie or token
requirement to /api/events is a breaking change for both clients and
is out of scope.
SSE framing already in production (vibe/ui_server.py::workbench_events):
- handshake:
: stream connectedcomment, thenevent: connected; - 15-second keep-alive comment (
: ping) so proxies do not idle-kill; - each application event:
event: <type>+data: <json>where the JSON is{"type": <type>, "data": <payload>}(seesse_broker.py).
The shell parses this framing; it does not invent a second protocol.
Connection ownership
The shell owns the SSE connection, not the WebView.
- Opened once the Runtime is adopted/started and
/readyhas succeeded. - Survives window close (the tray is the user's handle on a living Runtime; notifications must still arrive).
- Torn down when the shell gives up on the Runtime: three consecutive
/readyfailures (existing bootstrap recovery), explicit Stop of an owned Runtime, Uninstall, or Quit-and-stop. Adopted Runtimes that outlive the shell keep running; the SSE dies with the shell, which is the same visibility the user already accepted by quitting. - Reconnect with bounded backoff on stream drop, independently of the
/readyprobe. A reconnect does not replay history (the broker has no replay); the shell must tolerate missed events. Vault pending state is recoverable on click by opening the Workbench.
/ready probing and the SSE are two loops with one shared origin.
Neither substitutes for the other: a live SSE with a failing /ready
still triggers bootstrap recovery; a live /ready with a down SSE
retries the stream and does not take the window back to bootstrap.
Filtering, not a second bus
The broker is a global fan-out. The shell subscribes to the existing
stream and filters. It does not ask Python for a dedicated attention
channel in v1. Adding GET /api/desktop/attention would be a contract
v2 if the filter ever becomes a product-logic burden the shell should
not carry.
v1 filter (exact event type strings, already published):
SSE event |
Payload fields used | Notification class | When it fires |
|---|---|---|---|
vaults.updated |
request_id, request_status |
approval.requested |
request_status == "pending" and request_id present |
runs.updated |
run_id, status, session_id, run_type |
run.terminal |
status in {succeeded, failed, canceled} AND the run is "background" (see below) |
Every other event (message.new, session.activity, queue.updated,
inbox.unread.changed, show.event, keep-alives, unknown types) is
ignored by the notification path. notifications.preferences.updated
is a refetch hint, never an OS notification or an authoritative preference
snapshot. The filter is an allow-list: a new event type never becomes a
notification by accident.
"Background" for run.terminal
A terminal runs.updated notifies iff at least one of the two
properties below holds. This is not an allow-list of product verbs
and is not extended in v1 (a new always-background kind is a contract
revision). run_type=agent_run — including default async
vibe agent run — is not a special case: it follows the duration
rule only. v1 does not add visibility to the SSE payload.
A terminal runs.updated notifies if either:
- Duration ≥ 30s, measured as
completed_at − started_at(both durable, ISO-8601 on the terminal event).completed_atis the event'scompleted_atif present, otherwise the terminalupdated_at. Never "receipt time minus started_at" — a two-second run delivered a minute later (sleep, stall, reconnect) must not cross the threshold. If the terminal event omitsstarted_ator the completion timestamp, the shell refetchesGET /api/harness/runs/<run_id>once. Still missing either stamp → fail closed (no notify). or run_type∈{scheduled, watch}even under 30s (stored values fromcore/scheduled_tasks.py/core/watches.py;taskis a definition kind, not a run_type).
Python adds started_at and completed_at (or always-populated
terminal updated_at) on terminal runs.updated. No "please
notify" flag, no visibility field in v1.
Dedup
approval.requested: key =request_id. Same pending request is never notified twice while the key is retained. Non-pending transitions drop the key when observed. Because the broker has no replay, a reconnect can miss that transition — so this set is bounded the same way as run keys (LRU or TTL; default 512 or 24h). Do not rely on seeing a later status to bound memory. A dropped key may notify again if the same request is still pending; that is acceptable (at-least-once), not a leak.run.terminal: key =run_id. Terminal is once per key while the key is retained. Retention is bounded (LRU or TTL, frozen default: 512 entries or 24 hours, whichever hits first). The bound only needs to cover repeated terminal publications of the same run (SSE bursts / reconnect duplicates), not process lifetime. A tray-resident shell must not grow this set without bound.
A notification is suppressed (not queued) when:
- the Avibe window is focused and visible; or
- the tray "Notifications" item is unchecked; or
- the account-wide
enabledpreference is false; or - for
run.terminalonly, its account category is quiet.
System DND / Focus is the OS's problem.
Account preferences and run categories
The shell reads GET /api/notifications/preferences on every successful
SSE connection and on notifications.preferences.updated. Both use the
adopted loopback origin, with no redirects or new credentials. Only an
ok: true response containing all three boolean fields under preferences
is accepted; unknown fields are ignored. The event payload is never trusted.
Failed, malformed, or old-server reads keep the last valid snapshot; before
any valid snapshot the defaults are all on. Each read is bounded to five
seconds and 256 KiB. Refresh finishes before the next frame is processed;
in-flight run deliveries wait for that snapshot too. Badge reads continue
independently during a preference read.
enabled=falsesuppresses all OS notification classes, including Vault.bots=falsesuppresses Botrun.terminalbanners only.sessions=falsesuppresses ordinary Sessionrun.terminalbanners only.- Vault approvals ignore both category switches, while still honoring master, device, and focus/visibility gates.
GET /api/harness/runs/<id> provides notification_category: "bot" | "session"
from the same current Bot registry expression as Inbox. Scope, Project
membership, and run kind never imply a category. A run without a concrete
Bot permanent Session is session. The shell uses this detail field, not
an event-supplied category. A run must be loud both at receipt and at
delivery: re-enabling a category does not replay quiet events, and muting
while a detail read is pending suppresses its eventual delivery.
An unavailable detail, missing/unknown category on an older Runtime, or an overloaded lookup backlog is allowed to use generic copy only when both categories are loud. Otherwise it is dropped, so failure cannot bypass quiet-category intent. Existing background-duration rules still apply; preferences never turn a short foreground run into a banner.
Frozen presentation
Copy lives in the shell, keyed by class + locale
Existing SSE payloads are refetch hints (run_id / request_id), not
finished user copy. The shell therefore owns the notification outcome
text (and, for run banners, sanitizes the source label described below),
using the same locale catalog pattern as the tray (sys-locale →
desktopBootstrap keys in ui/src/i18n/{en,zh}.json, verified by
npm run test:i18n).
v1 keys (names frozen; wording is i18n content, not contract):
desktopBootstrap.notifications.approvalRequested.titledesktopBootstrap.notifications.approvalRequested.bodydesktopBootstrap.notifications.runSucceeded.titledesktopBootstrap.notifications.runSucceeded.bodydesktopBootstrap.notifications.runFailed.titledesktopBootstrap.notifications.runFailed.bodydesktopBootstrap.notifications.runCanceled.titledesktopBootstrap.notifications.runCanceled.bodydesktopBootstrap.notifications.toggle(tray menu label)
Run notifications name their source
A run banner says where the work happened, the way a mail notification
names the sender: the title is the source and the body is the
outcome (the catalog's run title, e.g. "Run completed"). The source
comes from the run detail the shell already reads
(GET /api/harness/runs/<id>), in precedence order:
session_project_name · session_label— a Workbench session in a Project (session_project_nameis the Project display name, projected by the same session summary that producessession_label);session_labelalone — an IM session reads as its channel name;definition_name— the task or watch, when no session resolved.
A terminal run that qualifies as background work is read back once for its label and category; an unreadable or label-less detail keeps the generic catalog title and body if both categories are loud (a known loud category also permits a missing label). Approval banners keep generic copy. Detail reads run beside the SSE reader, never inside it: each is bounded by the request timeout, at most 16 are in flight, and at most 64 are pending (later runs queue for a slot, since a run without stamps is only qualified by its read). Past that backlog the shell is overloaded: runs the event already qualifies notify at once with generic copy only when both categories are loud; otherwise they are dropped. A run only its read could qualify fails closed. Stopping the loop cancels them, so a slow Runtime never delays the next event.
These labels are Runtime strings on their way to a privileged OS
surface, so they leave only through one sanitizer
(RunDetail::source): control characters and invisible bidi /
zero-width formatting removed (the same set as core/citations.py;
ZWJ, ZWNJ and variation selectors kept), whitespace collapsed, each
part bounded to 48 characters. The SSE payload itself
is still never interpolated.
Plugin and permission
tauri-plugin-notification on the shell. Permission prompts are the
OS's (macOS notification permission on first fire). The plugin is
invoked from Rust, never from the WebView.
No new IPC command, no capability widening. Notifications are
shell-privileged the same way the tray is: the Workbench page cannot
trigger them. shell_boundaries.rs gains an assertion that the
notification path does not grant any remote capability.
Click
v1 ships OS-default activation, not a shell click callback: on macOS,
clicking a banner activates the sending app by default (approximately
show + focus); on Windows, unpackaged-toast click behavior is OS/backend
dependent and may only dismiss. The notification plugin's desktop API
does not expose an action callback. Explicit cross-platform click =
show + unminimize + set_focus is v2 with native activation adapter
(macOS UNUserNotificationCenter delegate + Windows toast activation).
No Workbench navigation or simulated click wiring is included in v1.
Frozen architecture split
Python Runtime Shell (Rust)
────────────── ────────────
SSEBroker ──GET /api/events──► attention filter
vaults.updated (allow-list)
runs.updated + 30s / run_type rule
(everything else ignored) + dedup
+ focus/pref gate
└── tauri-plugin-notification
/ready probe (existing, 2s) liveness only, never attention
Python changes in v1: include started_at and completed_at (or
guarantee terminal updated_at) on terminal runs.updated payloads
(run_updated_payload / publish_run_updated). Additive fields on
the existing payload, not a new route. Workbench refetch consumers
ignore unknown fields.
Rust changes live in desktop/runtime-host (filter, dedup, reconnect
— Tauri-free, testable) and a thin src-tauri adapter that fires the
plugin and reads window-focus / tray-pref state.
Tests (invariants, not enumerations)
- Filter allow-list: given a stream that mixes ignored types with one
vaults.updated {request_status: pending, request_id}and one terminalruns.updated, only those two classes produce a notification intent. A newly invented event type in the same fixture must not. - Dedup: two identical
request_idpendings → one intent; a non-pending transition then a new pending with the same id → a second intent. - Duration property:
completed_at − started_at(or terminalupdated_at − started_at) ≥ 30s → intent for a non-scheduled run; a 2s run whose event arrives 60s later does not. Missing either stamp after one refetch → no intent.run_type=scheduled/watch→ intent even under 30s. A new run_type in the fixture must not notify unless it is those two or the duration property hits. - Dedup bound: both approval and run key sets stay within 512 entries / 24h; inserting past the bound drops the oldest, and a later duplicate of a dropped key may notify again.
- Account preferences: master gates both classes, category switches gate only their run categories, never Vault; receipt and delivery both honor quiet categories. Preference hints refetch, failed reads preserve the last valid value, reconnect refreshes, and suppression never replays.
- Old-server/overload fallback: unknown run category can notify only if
both categories are loud. Badge reads prefer
badge_total, including zero, and fall back only when it is absent. - Focus gate: window focused + visible → no intent even on a matching event.
- Reconnect: stream drop then restore does not panic, does not replay, does not take bootstrap recovery by itself.
- Boundary:
shell_boundariesstill forbids remote capabilities; notification code is not reachable from a navigated Workbench page. - i18n: the new keys exist in both catalogs with matching
placeholders (
npm run test:i18n).
Drive the filter with a fake SSE collaborator under tokio's virtual
clock (same pattern as runtime-host/tests/bootstrap.rs) so the 30s
threshold is exercised in microseconds.
Unread badge (follow-up)
The app icon badge is the second consumer of the shell-owned connection,
not a second connection. Each connect and each decoded frame, of any
type, schedules a read of GET /api/inbox?platform=avibe&limit=1 and
paints its badge_total (unread in loud categories). Only when that field
is absent on an older Runtime does the shell fall back to unread_total;
an explicit zero or malformed field never falls through to the raw count.
A trailing-edge coalescer allows at most one
read per second. Triggering on every frame instead of an allowlist means
the badge never depends on knowing which events change unread state, and
the 15s heartbeat bounds staleness after a failed read. The badge is
state, so the device Notifications toggle and the focus gate do not apply.
Account preferences affect the server's badge_total, not whether the
shell stays connected or refreshes the count.
stop clears it on the main thread, behind any paint the voided
generation queued. The WebView cannot own the badge: WebKit suspends
page timers while the window is backgrounded, and WKWebView does not
implement navigator.setAppBadge. Windows lacks a Tauri badge count; an
overlay icon is follow-up work.
Explicit non-goals (v1)
- A new HTTP route or a Python "please notify" flag. (The run detail
gained additive projected fields
session_project_nameandnotification_categoryon its existing route; preferences reuse #3127's account endpoint.) - Deep-link click targets (G5).
- Notifying on every chat message, every
session.activity, or foreground turns that finish quickly. - Replaying missed events after reconnect.
- Changing
/api/eventsauth. - Windows-vs-macOS copy differences beyond the shared catalog.
Sequencing
Depends on the tray (#1975, merged): the Notifications toggle lives on the same menu as "Start at Login", and window-hidden-to-tray is the state in which notifications matter.
Does not depend on G1 signing or G2 auto-update.
Does not block G5. A notification-specific deep-link target follows the native activation adapter rather than assuming a v1 click callback exists.