Compare commits

..
20 Commits
Author SHA1 Message Date
Mohamed Boudra afb8634dc3 chore(release): cut 0.17.6 2026-11-27 03:11:49 +01:00
Mohamed Boudra 0baecb2e0a docs: prepare v0.17.6 changelog 2026-11-27 03:01:01 +01:00
lukeandRoundRedDot 3fcb4524bb fix(antigravity): remove the account usage source
The usage source ran `agy -p /usage` in the background on behalf of the
user. Google's Antigravity FAQ says headless mode is intended for direct
scripting and CI, and that wrapping agy inside third-party applications is
not supported on consumer plans and can lead to account suspension. A
maintainer reply in google-antigravity/antigravity-cli#1493 confirms that
driving `agy -p` from a third-party harness breaches the terms, with no
exception for personal use.

Remove the Antigravity usage source so Paseo no longer runs agy in headless
mode. The provider and the generic usage-source launch plumbing, used by
other plugins, are unchanged.

Co-authored-by: RoundRedDot <roundreddot@gmail.com>
2026-11-27 03:00:25 +01:00
paseo-bot[bot] edd526561f Fix two model picker bugs that lost a click or an Enter (#10962)
* fix(app): keep a pressed model row under the pointer

Pressing a model row focuses it. The row's focus handler marked it as the
keyboard-active row, and the list then scrolled that row into view. When
the list had not yet reported which rows it shows, as on a slow machine
right after a provider opens, it centered the row. The row moved before
the button came up, and the click selected nothing.

Only keyboard focus (:focus-visible on web) now marks a row active, so a
press never scrolls the list.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(app): keep model search focused when the model list scrolls on web

React Native Web blurs the focused input on every scroll when
keyboardDismissMode is on-drag. The reveal scroll after ArrowDown, or a
wheel scroll, moved focus out of the search field, and the sheet focus
trap put it on the Back button, so Enter went back instead of selecting.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
(cherry picked from commit e6f0ad272d)
2026-11-27 02:56:07 +01:00
Mohamed Boudra 2f54a1d750 fix(markdown): set HeaderCopyButton contentDescription without overriding View getter
Fixes #10934 and #10968. Removes the HeaderCopyButton.getContentDescription() override completely so AppCompatImageButton.<init> (and Samsung One UI's View.semSetHoverPopupType) never dispatches into uninitialized subclass fields, and sets View.contentDescription directly with recursive sync on copyLabel updates.

(cherry picked from commit a3389a063d)
2026-11-27 02:25:58 +01:00
paseo-bot[bot] 12ae5f537b fix(android): let a mouse click select model picker rows (#10972)
On Android, a mouse sends a click as DOWN, BUTTON_PRESS, BUTTON_RELEASE and UP.
Gesture handler's Tap ignores DOWN and UP from a mouse and waits for the BUTTON
events. Android delivers those through dispatchGenericMotionEvent, and
RNGestureHandlerRootView forwarded only hover events from there. A mouse click
on a Gesture.Tap row, such as a provider or model row in the wide model
picker, never fired.

Backport upstream react-native-gesture-handler#4265 (2.33.0) into the 2.32.0
patch: forward BUTTON_PRESS and BUTTON_RELEASE to the orchestrator, and start
the LongPress timer on BUTTON_PRESS.

Fixes #10744

Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
(cherry picked from commit 21c2e55dd1)
2026-11-27 02:18:25 +01:00
paseo-bot[bot] b6cab288fc fix(app): keep a tab from saving a directory another tab evicted (#10942)
Each browser tab runs its own replica cache over one shared IndexedDB
database. When one tab ran over the 32 MiB budget it deleted a host's
rows, but only that tab knew. Another open tab kept writing workspace
and agent updates with its old checkpoint, so the database ended up with
a projects cursor and no project rows. A new tab trusted that cursor,
the daemon answered "no changes", and the sidebar showed no projects or
workspaces for the host.

The IndexedDB store now keeps a revision on each host's checkpoint. A
tab may write directory rows only while the stored revision matches the
one it last read or wrote, checked in the same transaction as the write.
Each write rotates the revision. A tab whose host was evicted or
rewritten by another tab has its directory writes dropped until a full
refresh replaces the baseline. Timeline writes are not affected.
Malformed-row repairs go through the same check.

Version 2 checkpoints could have been written by the cross-tab path, so
the checkpoint version moves to 3 and existing caches re-sync their
directory once.

Fixes #10206

Co-authored-by: Gtio <gtoxlili@outlook.com>
(cherry picked from commit 74c33b03d3)
2026-11-27 02:18:25 +01:00
Mohamed Boudra 5bbc180cfe Reorganize Settings by device vs. host scope and consolidate sparse sections (#10933)
* feat(app): split client and host settings and consolidate sections

Previously, client-local host configuration (connection routes, sidebar appearance, removing a host from this device) lived under Host settings alongside daemon-owned configuration, while agent prompts, tools, skills, and lifecycle toggles were split across overlapping sections and several single-row app settings had standalone sidebar pages.

Separate Settings strictly by ownership:
- 'This device' owns client-local preferences plus a new 'Hosts' page (/settings/hosts and /settings/device-hosts/[serverId]) for saved hosts, connection routes, local sidebar appearance, and removing a host from this device.
- 'Host' owns daemon-scoped settings only: 'Tools & prompts' combines system prompt, Paseo/browser tools, and Paseo skills; 'Workspaces' combines auto-archive and metadata generation while 'Projects' stays dedicated to the project list; 'Daemon' owns daemon status, updates, agent runtime lifecycle (resume after restart, release idle agents), and restart.
- Collapse sparse app sections into General (+ CLI), Chat & panes (+ sending, open location, editor, terminal, conditional files, browser data), Notifications & access (+ permissions), and About (+ diagnostics), while keeping redirects for all legacy settings routes.

* fix(app): restore offline Workspaces card, prune unused wrappers, and update docs

* docs: update Settings paths across EN and zh-CN docs

* test(e2e): update remaining app and desktop settings section selectors

* test(desktop): update Settings destination labels in memory regression check

(cherry picked from commit e4dc119df8)
2026-11-27 02:18:25 +01:00
paseo-bot[bot] 557d2e596d fix(server): keep worktree ownership inside the configured worktrees root (#10878)
When a worktree directory is gone, the marker search walks up from its
path and stops at the first Paseo worktree above it. If the daemon home
lives inside another Paseo worktree, that search found the enclosing
worktree and reported it as the owner. Legacy restore then ran
`git worktree add` on the enclosing path and failed with "already
exists", and deleting the missing worktree removed the enclosing one.

A Paseo worktree that holds the worktrees root owns none of the
worktrees beneath it, so the marker search now ignores it and the path
under the worktrees root decides ownership.

Closes #10745

Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
(cherry picked from commit 4201a4de35)
2026-11-27 02:14:58 +01:00
Mohamed Boudra f2102d0c2a Eliminate flashes and show unarchiving state when restoring archived workspaces and agents (#10928)
* fix(workspace): eliminate flashes and show unarchiving state on restore

Unarchiving a workspace previously broadcast workspace_update before its archived agents finished unarchiving, emitted spurious agent_update(remove) deltas for archived agents, and dropped the Restoring screen before tabs and chat timelines settled—causing the archived-agent callout and multiple loading spinners to flash before the chat stabilized.

Defer workspace publication with token-scoped holds until workspace-archived agents finish unarchiving and their agent_update messages flush; track positive directory membership in AgentUpdatesService and suppress intermediate close broadcasts during unarchiveSnapshot; hold the Restoring overlay in an isolated stacking context until auto-open agent tabs and visible agent timelines settle; keep already-ready archived chats mounted without reverting to boot; and display an inline Unarchiving... state during both single-agent unarchive and mid-teardown workspace undo without mislabeling pre-archived agents.

* fix(server): keep mid-teardown undo visible in directory reads and update stubs

Split deferBroadcast from isPublicationDeferred so a mid-teardown archive undo holds workspace_update emission until all agents finish unarchiving without hiding the already-active workspace from WorkspaceDirectory reads for other clients.

Update createStub<WorkspaceRegistry> test harnesses with the deferral methods and seed the tracked agent in session.workspaces.test.ts before clearing its workspaceId.

* test(server): seed matching label before asserting filtered agent removal

With positive directory membership in AgentUpdatesService, filtered agent subscriptions only emit remove when an agent that was previously included leaves the filter.

(cherry picked from commit 2be71aedcb)
2026-11-27 02:14:58 +01:00
Mohamed Boudra 186899e66f Navigate models, providers, and profiles with arrow keys in the model picker (#10929)
* feat(app): support arrow-key navigation in the model picker

ModelBrowser renders profiles, providers, and models as custom children inside Combobox (with an empty options array) and AdaptiveModalSheet, so arrow keys were swallowed by Combobox on wide layouts and ignored in the folded sheet.

Add a pure navigation model in ModelBrowser for profiles, providers, models, and search results, delegate overlay keys from Combobox and AdaptiveModalSheet, scroll active rows into view on explicit keyboard movement without clipping the pinned Profiles header on open, and stabilize DesktopComboboxBody's floating callback ref so Combobox re-renders do not re-register the overlay scope and steal focus onto the Back button.

* fix(app): unify model browser projection and skip native initial highlight

* fix(app): share FlatList scroll reveal and honor native hardware keyboards

(cherry picked from commit a27f0819c8)
2026-11-27 02:14:58 +01:00
Mohamed Boudra 7d14347282 Stop background git fetch from spawning D-Bus daemons and hammering failing auth (#10921)
* fix(server): guard headless D-Bus autolaunch and pause background fetch on auth failure

* fix(server): resolve runtime D-Bus socket and unify repo fetch state

* fix(server): handle in-flight fetch overlap, origin removal, and setup races

(cherry picked from commit 46eb98d604)
2026-11-27 02:14:58 +01:00
Mohamed Boudra 89b0f85c8c fix(linux): strip AppImage runtime environment from shells and child processes (#10920)
* fix(linux): strip AppImage runtime env from shells and child processes

The Linux AppImage wrapper exports APPIMAGE, APPDIR, ARGV0, and OWD and prepends $APPDIR paths before launching Electron. That environment leaked through Desktop's login-shell probe, the daemon launcher, and external child builders, causing zsh to override argv[0] for external commands and breaking tools like mise and systemctl aliases.

Add a shared Linux-only stripAppImageRuntimeEnv helper and apply it at the login-shell probe, daemon launch, server external process, and Desktop editor-target boundaries while leaving process.env.APPIMAGE intact in Electron main for auto-updates and CLI installation.

* fix(desktop): strip AppImage runtime env from SSH transport spawns

Electron main intentionally retains AppImage environment variables for auto-updates and CLI symlinking, so spawning ssh without an explicit env passed ARGV0 and $APPDIR paths into OpenSSH ProxyCommand/ProxyJump shell invocations.

* chore: export stripAppImageRuntimeEnv solely from @getpaseo/server/process

Drop the duplicate re-export from @getpaseo/server/daemon-control and run the platform-parameterized config-environment AppImage tests on all OSes.

(cherry picked from commit 7d3e045ff8)
2026-11-27 02:14:58 +01:00
Mohamed Boudra 3fc2ef4469 test(e2e): settle Tailscale toggles and flush slowed socket queues (#10918)
In pair-device-relay.spec.ts, slowConnectionToHost left delayed WebSocket frames in its queue after restoreSpeed() ran, and disableTailscale returned once the Tailscale listener closed before the browser received daemon.tailscale.set.response. Under CI load, enableTailscale could run while the prior change was still in flight.

Wait for the Tailscale switch to return to the enabled state in enableTailscale and disableTailscale, flush queued WebSocket frames when restoring speed, and verify slow-connection off-then-on toggling in pair-device-relay.spec.ts. (PR #10903 already disabled the Tailscale switch in app code while a toggle is pending.)

(cherry picked from commit 20b70e37e7)
2026-11-27 02:14:58 +01:00
LiebeLee bf41c28a5e fix(timeline): recover from rewind epoch changes instead of dropping rows (#8794)
A rewind mints a new timeline epoch on the daemon. A client that misses the
agent.timeline.replacement invalidation then sees every subsequent live row in
the new epoch, and the sequencing gate dropped those rows with no recovery: the
chat stayed on pre-rewind history forever while the new epoch streamed.

Treat an epoch mismatch on a live row like a sequence gap. The app asks for
catch-up from its own cursor, the daemon answers a stale-epoch request with a
reset tail, and the existing destructive replacement installs current history.
The seq 1 fast path stays as is.

(cherry picked from commit fcac35d3b9)
2026-11-27 02:14:58 +01:00
Mohamed Boudra 2428a8c232 Refresh Tailscale availability in place (#10903)
* feat(devices): add Refresh button for Tailscale availability

When Tailscale is unavailable, waiting to start, or fails its status check in Host Settings -> Devices or Setup -> Mobile, show a Refresh button so users can install or start Tailscale in place and continue without restarting Paseo or leaving the screen.

On the daemon side, live interface detection via os.networkInterfaces() already re-probes on every daemon.get_status.request without caching, but extra listeners in the waiting state waited for their 2-second retry timer before re-attempting bind. Refreshing daemon status now re-probes waiting listeners immediately before reporting status.

On the app side, enable refetchOnWindowFocus for Tailscale status, separate manual Refresh state from background polling so polling does not flicker the button, surface manual refresh failures even when a previous status is loaded, and make refresh and toggle actions mutually exclusive.

* test(e2e): verify Refresh triggers status request ahead of poll

* test(terminal): batch writes in ten-thousand-row history test

Matches #10683: Windows ConPTY timed out at 15s while writing 12,050 rows one write at a time under parallel test load. Batching in 256-row chunks produces the identical terminal output and assertions.

* ui(devices): use circular icon button for Tailscale refresh

Replace the text-labeled Refresh pill with a circular outline icon button (with desktop tooltip and localized accessibilityLabel) so the Tailscale row stays quieter and fits on one line beside the switch on 390px compact viewports.

* ui(devices): drop Relay Recommended badge and lead subtitle with No setup

* test(website): drive code review scene clock explicitly

Matches #10808: headless WebKit on CI paints slowly, so the code review scene missed its 10s wall-clock timeout under the 64ms/frame cap. Use openHomepageWithSceneClock, page.clock.runFor, and finishPanelSwap like the sibling scene tests.

(cherry picked from commit 2636c4384f)
2026-11-27 02:14:57 +01:00
paseo-bot[bot] 64b8861a9f Give the Windows untrusted worktrunk test the journey's 90 second budget (#10900)
The test starts the daemon twice, archives four times, and restores twice.
On Windows CI it took 18 to 46 seconds on green main runs and timed out at
60 seconds on main run 45734061560, where every test in the file ran about
twice as slow.

Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
(cherry picked from commit a7dbeadd5f)
2026-11-27 02:14:57 +01:00
Mohamed Boudra ccd9f0a436 fix(desktop): avoid macOS Dock progress bar freeze and harden release smoke 2026-11-26 15:29:16 +01:00
Mohamed Boudra 713b6dbbfe chore(release): cut 0.17.5 2026-11-26 07:42:07 +01:00
Mohamed Boudra 32c3805aad docs: prepare v0.17.5 changelog 2026-11-26 07:36:24 +01:00
122 changed files with 516 additions and 6691 deletions
+24
View File
@@ -1,5 +1,29 @@
# Changelog
## 0.17.6 - 2026-11-27
### Improved
- Reorganized Settings into Device and Host sections and consolidated sparse pages ([#10933](https://github.com/getpaseo/paseo/pull/10933))
- Added arrow-key navigation for models, providers, and profiles in the model picker ([#10929](https://github.com/getpaseo/paseo/pull/10929), [#10962](https://github.com/getpaseo/paseo/pull/10962))
- Added an in-place Refresh control for Tailscale availability in host settings and setup ([#10903](https://github.com/getpaseo/paseo/pull/10903))
### Changed
- Removed the Antigravity usage source that ran `agy -p /usage` in the background ([#10953](https://github.com/getpaseo/paseo/pull/10953) by [@luoph](https://github.com/luoph))
### Fixed
- Fixed Paseo Android crashing on Samsung devices when a chat shows a code block or quote ([#10964](https://github.com/getpaseo/paseo/pull/10964))
- Fixed mouse clicks not selecting model picker rows on Android ([#10972](https://github.com/getpaseo/paseo/pull/10972))
- Fixed macOS Desktop freezing during startup because of Dock progress bar updates ([#10939](https://github.com/getpaseo/paseo/pull/10939))
- Fixed Linux AppImage leaking its runtime environment into shells and child processes ([#10920](https://github.com/getpaseo/paseo/pull/10920))
- Fixed background Git fetches on Linux spawning orphan D-Bus daemons and retrying failing auth in a loop ([#10921](https://github.com/getpaseo/paseo/pull/10921))
- Fixed flashes when restoring archived workspaces and agents, and added an unarchiving state ([#10928](https://github.com/getpaseo/paseo/pull/10928))
- Fixed worktree ownership drifting outside the configured worktrees root ([#10878](https://github.com/getpaseo/paseo/pull/10878))
- Fixed new web tabs losing projects after another tab evicts the directory cache ([#10942](https://github.com/getpaseo/paseo/pull/10942))
- Fixed timelines dropping rows when a rewind epoch changes ([#8794](https://github.com/getpaseo/paseo/pull/8794) by [@LiebeLee](https://github.com/LiebeLee))
## 0.17.5 - 2026-11-26
- **Archive workspaces together:** Cmd/Ctrl+click a workspace in the sidebar to select multiple workspaces and archive them in one step. ([#10798](https://github.com/getpaseo/paseo/pull/10798), [#10821](https://github.com/getpaseo/paseo/pull/10821))
+24
View File
@@ -1,5 +1,29 @@
# Changelog
## 0.17.6 - 2026-11-27
### 改进
- 将设置重组为设备和主机两个范围,并合并了内容较少的页面 ([#10933](https://github.com/getpaseo/paseo/pull/10933))
- 为模型选择器中的模型、Provider 和配置文件新增方向键导航 ([#10929](https://github.com/getpaseo/paseo/pull/10929), [#10962](https://github.com/getpaseo/paseo/pull/10962))
- 在主机设置和初始设置中新增就地刷新 Tailscale 可用性的按钮 ([#10903](https://github.com/getpaseo/paseo/pull/10903))
### 变更
- 移除了在后台运行 `agy -p /usage` 的 Antigravity 用量数据源 ([#10953](https://github.com/getpaseo/paseo/pull/10953),贡献者:[@luoph](https://github.com/luoph))
### 修复
- 修复对话中出现代码块或引用时 Paseo Android 在三星设备上崩溃的问题 ([#10964](https://github.com/getpaseo/paseo/pull/10964))
- 修复在 Android 上使用鼠标点击无法选择模型选择器行的问题 ([#10972](https://github.com/getpaseo/paseo/pull/10972))
- 修复 macOS 桌面端因 Dock 进度条更新在启动时卡死的问题 ([#10939](https://github.com/getpaseo/paseo/pull/10939))
- 修复 Linux AppImage 将其运行时环境变量泄漏到 Shell 和子进程的问题 ([#10920](https://github.com/getpaseo/paseo/pull/10920))
- 修复 Linux 上后台 Git fetch 启动孤立 D-Bus 进程并在认证失败后循环重试的问题 ([#10921](https://github.com/getpaseo/paseo/pull/10921))
- 修复恢复已归档工作区和 Agent 时的界面闪烁问题,并新增恢复中状态提示 ([#10928](https://github.com/getpaseo/paseo/pull/10928))
- 修复 worktree 所有权超出已配置 worktrees 根目录的问题 ([#10878](https://github.com/getpaseo/paseo/pull/10878))
- 修复另一个标签页淘汰目录缓存后,新打开的网页标签页丢失 project 的问题 ([#10942](https://github.com/getpaseo/paseo/pull/10942))
- 修复 rewind epoch 变更时时间线丢失行的问题 ([#8794](https://github.com/getpaseo/paseo/pull/8794),贡献者:[@LiebeLee](https://github.com/LiebeLee))
## 0.17.5 - 2026-11-26
- **批量归档工作区**:在侧边栏按住 Cmd/Ctrl 点击工作区即可多选,一步归档。([#10798](https://github.com/getpaseo/paseo/pull/10798), [#10821](https://github.com/getpaseo/paseo/pull/10821))
+2 -12
View File
@@ -10,20 +10,10 @@ Agent payloads name a host and agent. Ignore their workspace hint when opening:
the agent can move after a notification is sent. Use `navigateToAgent`, which
uses the current store record or the agent route to resolve the workspace from
the host. Terminal payloads name their workspace and use `navigateToWorkspace`.
Plugin payloads carry `kind: "plugin"`, `serverId`, `pluginId`, `notificationId`,
and optional `open` and `data`; `openPluginNotification` in
`packages/app/src/plugins/notification-open.ts` waits up to 8 seconds for the
target host's plugin catalog to settle on cold launch, runs registered
`client.onNotificationOpen` handlers with caught error isolation, and falls back
to declarative `open` (`agent`, `workspace`, `screen`) or the host root route.
See [agent targets and deferred opens](expo-router.md#agent-targets) for route
ownership and workspace recovery. Per-device two-knob notification preferences
(`@getpaseo/protocol/notification-preferences`) sync with mobile push tokens via
`register_push_token` (gated on `server_info.features.pushNotificationPreferences`)
so the daemon filters Expo pushes per token, while desktop and web clients filter
in-app OS notifications locally before calling `sendOsNotification`. Notification
generation and presence remain daemon concerns.
ownership and workspace recovery. Notification generation, presence, and push
eligibility remain daemon concerns.
## Native delivery
+1 -21
View File
@@ -1,7 +1,7 @@
# Plugins
Local plugins contribute daemon RPCs, native app surfaces, workspace panels, Command Center items,
client slash commands, timeline items, notifications, header buttons, composer pills, app themes, composer attachment sources, and settings screens.
client slash commands, timeline items, header buttons, composer pills, app themes, composer attachment sources, and settings screens.
Paseo executes `index.server.ts` in a subprocess and `index.client.tsx` in every connected app.
> **Trust every plugin you add.** `paseo plugin add` and `paseo plugin install` mean “I trust this codebase.” Plugins are unsandboxed: server code and preparation commands run with the daemon user's access on the daemon host, and client contributions run inside Paseo. The repository's dependencies and future updates are part of that trust decision. With `--host`, preparation runs on that remote daemon host.
@@ -549,26 +549,6 @@ The same holds for a hook that runs inside an agent's lifecycle lane: an `agent.
an option, model, thinking or mode change) waits on the open, which waits on the hook. The hooks
reference tells plugin authors to start such a write without awaiting it.
## Send notifications
Server plugins call `server.notifications.send(input)` over the `notification.send` /
`notification.result` / `notification.error` IPC messages. `PluginNotificationDispatcher` in
`packages/server/src/server/plugins/notifications.ts` trims and truncates `title` (<= 160 chars)
and `body` (<= 500 chars), validates `key` (<= 128 chars), `open` (IDs <= 256 chars, serialized
<= 1,024 UTF-8 bytes), and `data` (<= 1,024 UTF-8 bytes so APNs and FCM envelopes stay within
4 KiB), drops duplicate `(pluginId, key)` pairs for 60 seconds, and enforces a per-plugin token
bucket (burst 10, refill 1 per 6 seconds). Stopping a plugin clears its deduplication and
rate-limit state.
`WebSocketServer.sendPluginNotification` stamps the runtime `pluginId`, `serverId`, and
`notificationId`, runs `computeNotificationPlan` (using `open.agentId` as the focus target when
`open.type === "agent"`), filters Expo pushes per token with `{ kind: "plugin", pluginId }`, and
publishes `plugin.notification` to sessions subscribed to that event category. Clients gate their
`"plugin.notification"` subscription on `server_info.features.pluginNotifications` (`COMPAT(pluginNotifications)`).
See [notifications.md](notifications.md) for tap routing and cold-launch catalog readiness, and the
[public notifications reference](../public-docs/plugins/reference.md#notifications) for the author
contract.
## Contribute a provider
Register a provider from `index.server.ts`. The provider connection is callback-based and owns all
@@ -0,0 +1,12 @@
Improved
- Reorganized Settings into Device and Host sections and consolidated sparse pages
- Added arrow-key navigation for models, providers, and profiles in the model picker
- Added an in-place Refresh control for Tailscale availability in host settings and setup
Changed
- Removed the Antigravity usage source that ran agy -p /usage in the background
Fixed
- Fixed Paseo Android crashing on Samsung devices when a chat shows a code block or quote
Full notes: https://paseo.sh/changelog
@@ -0,0 +1,12 @@
Improved
- Reorganized Settings into Device and Host sections and consolidated sparse pages
- Added arrow-key navigation for models, providers, and profiles in the model picker
- Added an in-place Refresh control for Tailscale availability in host settings and setup
Changed
- Removed the Antigravity usage source that ran agy -p /usage in the background
Fixed
- Fixed Paseo Android crashing on Samsung devices when a chat shows a code block or quote
Full notes: https://paseo.sh/changelog
@@ -0,0 +1,12 @@
Improved
- Reorganized Settings into Device and Host sections and consolidated sparse pages
- Added arrow-key navigation for models, providers, and profiles in the model picker
- Added an in-place Refresh control for Tailscale availability in host settings and setup
Changed
- Removed the Antigravity usage source that ran agy -p /usage in the background
Fixed
- Fixed Paseo Android crashing on Samsung devices when a chat shows a code block or quote
Full notes: https://paseo.sh/changelog
@@ -0,0 +1,12 @@
Improved
- Reorganized Settings into Device and Host sections and consolidated sparse pages
- Added arrow-key navigation for models, providers, and profiles in the model picker
- Added an in-place Refresh control for Tailscale availability in host settings and setup
Changed
- Removed the Antigravity usage source that ran agy -p /usage in the background
Fixed
- Fixed Paseo Android crashing on Samsung devices when a chat shows a code block or quote
Full notes: https://paseo.sh/changelog
+1 -1
View File
@@ -1 +1 @@
sha256-B2hX/4xDGTtFC2LBRL/0US3YERfM/cDXvu8cjztpsd8=
sha256-6XXAVBTH6rIdg5eQ9cUeUwV22ikVqTtdWo7i9DYO+/M=
+29 -29
View File
@@ -1,12 +1,12 @@
{
"name": "paseo",
"version": "0.17.5",
"version": "0.17.6",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "paseo",
"version": "0.17.5",
"version": "0.17.6",
"hasInstallScript": true,
"license": "Apache-2.0",
"workspaces": [
@@ -37541,7 +37541,7 @@
},
"packages/app": {
"name": "@getpaseo/app",
"version": "0.17.5",
"version": "0.17.6",
"dependencies": {
"@codemirror/commands": "6.10.4",
"@codemirror/language": "6.12.4",
@@ -39694,13 +39694,13 @@
},
"packages/cli": {
"name": "@getpaseo/cli",
"version": "0.17.5",
"version": "0.17.6",
"license": "Apache-2.0",
"dependencies": {
"@clack/prompts": "^1.0.0",
"@getpaseo/client": "0.17.5",
"@getpaseo/protocol": "0.17.5",
"@getpaseo/server": "0.17.5",
"@getpaseo/client": "0.17.6",
"@getpaseo/protocol": "0.17.6",
"@getpaseo/server": "0.17.6",
"chalk": "^5.3.0",
"commander": "^12.0.0",
"mime-types": "^2.1.35",
@@ -39947,11 +39947,11 @@
},
"packages/client": {
"name": "@getpaseo/client",
"version": "0.17.5",
"version": "0.17.6",
"license": "Apache-2.0",
"dependencies": {
"@getpaseo/protocol": "0.17.5",
"@getpaseo/relay": "0.17.5",
"@getpaseo/protocol": "0.17.6",
"@getpaseo/relay": "0.17.6",
"ws": "^8.20.0",
"zod": "^4.4.3"
},
@@ -39963,7 +39963,7 @@
},
"packages/desktop": {
"name": "@getpaseo/desktop",
"version": "0.17.5",
"version": "0.17.6",
"license": "Apache-2.0",
"dependencies": {
"@getpaseo/cli": "*",
@@ -40206,7 +40206,7 @@
},
"packages/expo-two-way-audio": {
"name": "@getpaseo/expo-two-way-audio",
"version": "0.17.5",
"version": "0.17.6",
"license": "MIT",
"devDependencies": {
"@types/jest": "^29.5.14",
@@ -40252,7 +40252,7 @@
},
"packages/highlight": {
"name": "@getpaseo/highlight",
"version": "0.17.5",
"version": "0.17.6",
"license": "Apache-2.0",
"dependencies": {
"@codemirror/language": "6.12.4",
@@ -40282,7 +40282,7 @@
},
"packages/plugin": {
"name": "@getpaseo/plugin",
"version": "0.17.5",
"version": "0.17.6",
"license": "Apache-2.0",
"dependencies": {
"@agentclientprotocol/sdk": "^1.4.0",
@@ -40290,8 +40290,8 @@
"use-sync-external-store": "^1.6.0"
},
"devDependencies": {
"@getpaseo/client": "0.17.5",
"@getpaseo/protocol": "0.17.5",
"@getpaseo/client": "0.17.6",
"@getpaseo/protocol": "0.17.6",
"@types/node": "^20.9.0",
"@types/react": "~19.2.0",
"react": "19.2.3",
@@ -40301,8 +40301,8 @@
"zod": "^4.4.3"
},
"peerDependencies": {
"@getpaseo/client": "0.17.5",
"@getpaseo/protocol": "0.17.5",
"@getpaseo/client": "0.17.6",
"@getpaseo/protocol": "0.17.6",
"react": ">=19.1.0 <20",
"react-native": ">=0.81.5",
"zod": "^4.4.3"
@@ -40324,7 +40324,7 @@
},
"packages/protocol": {
"name": "@getpaseo/protocol",
"version": "0.17.5",
"version": "0.17.6",
"license": "Apache-2.0",
"dependencies": {
"semver": "^7.8.5",
@@ -40351,7 +40351,7 @@
}
},
"packages/react-native-enriched-markdown": {
"version": "0.17.5",
"version": "0.17.6",
"hasInstallScript": true,
"license": "MIT",
"peerDependencies": {
@@ -40367,7 +40367,7 @@
},
"packages/relay": {
"name": "@getpaseo/relay",
"version": "0.17.5",
"version": "0.17.6",
"license": "Apache-2.0",
"dependencies": {
"@noble/ciphers": "^2.4.0",
@@ -40589,17 +40589,17 @@
},
"packages/server": {
"name": "@getpaseo/server",
"version": "0.17.5",
"version": "0.17.6",
"license": "Apache-2.0",
"dependencies": {
"@agentclientprotocol/sdk": "^0.17.1",
"@anthropic-ai/claude-agent-sdk": "0.3.326",
"@anthropic-ai/sdk": "^0.104.2",
"@getpaseo/client": "0.17.5",
"@getpaseo/highlight": "0.17.5",
"@getpaseo/plugin": "0.17.5",
"@getpaseo/protocol": "0.17.5",
"@getpaseo/relay": "0.17.5",
"@getpaseo/client": "0.17.6",
"@getpaseo/highlight": "0.17.6",
"@getpaseo/plugin": "0.17.6",
"@getpaseo/protocol": "0.17.6",
"@getpaseo/relay": "0.17.6",
"@isaacs/ttlcache": "^2.1.4",
"@modelcontextprotocol/node": "2.1.2",
"@modelcontextprotocol/sdk": "1.29.0",
@@ -41550,7 +41550,7 @@
},
"packages/website": {
"name": "@getpaseo/website",
"version": "0.17.5",
"version": "0.17.6",
"dependencies": {
"@cloudflare/vite-plugin": "^1.29.1",
"@cloudflare/workers-types": "^4.20260317.1",
@@ -43161,7 +43161,7 @@
},
"plugins": {
"name": "@getpaseo/builtin-plugins",
"version": "0.17.5",
"version": "0.17.6",
"dependencies": {
"@getpaseo/plugin": "*",
"zod": "^4.4.3"
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "paseo",
"version": "0.17.5",
"version": "0.17.6",
"private": true,
"description": "Paseo: voice-controlled development environment for local AI coding agents",
"keywords": [
@@ -1,245 +0,0 @@
import { expect, test } from "../support/fixtures";
import { gotoAppShell, openSettings } from "../support/helpers/app";
import {
clearRecordedBrowserNotifications,
clickRecordedBrowserNotification,
expectDefaultNotificationSettings,
expectNotificationSubControlsDisabled,
expectNotificationSwitchState,
expectRecordedAgentNotifications,
expectRecordedPluginNotifications,
installBrowserNotificationRecorder,
openNotificationSettings,
readRecordedBrowserNotifications,
setNotificationSwitch,
setPluginNotificationSwitch,
} from "../support/helpers/notification-settings";
import { copyPluginExample } from "../support/helpers/plugin-fixture";
import { seedWorkspace, type SeedDaemonClient } from "../support/helpers/seed-client";
const FAST_FINISHED_PROMPT =
"emit settled assistant image markdown: ![done](https://example.com/done.png)";
const PERMISSION_PROMPT = "emit a synthetic plan approval";
const ERROR_PROMPT = "emit a synthetic turn failure";
async function runMockAgentTurn(
client: SeedDaemonClient,
input: {
cwd: string;
workspaceId: string;
title: string;
prompt: string;
waitForStatus: "idle" | "error" | "running";
},
): Promise<string> {
const agent = await client.createAgent({
provider: "mock",
cwd: input.cwd,
workspaceId: input.workspaceId,
title: input.title,
modeId: "load-test",
model: "e2e-fast-stream",
initialPrompt: input.prompt,
});
await client.waitForAgentUpsert(
agent.id,
(snapshot) => snapshot.status === input.waitForStatus,
15_000,
);
return agent.id;
}
test.describe("Settings → Notifications and OS notification filtering", () => {
test("displays defaults, persists switch changes across reload, disables sub-controls when paused, and filters OS notifications", async ({
page,
}) => {
await installBrowserNotificationRecorder(page);
const seeded = await seedWorkspace({ repoPrefix: "notification-settings-" });
const pluginExample = await copyPluginExample("notifications");
let installedPlugin = false;
try {
await gotoAppShell(page);
await openSettings(page);
await openNotificationSettings(page);
await test.step("renders Settings → Notifications with expected out-of-the-box defaults", async () => {
await expectDefaultNotificationSettings(page);
await expect(
page.getByText("Installed plugins appear here so you can mute them individually", {
exact: true,
}),
).toBeVisible();
});
await test.step("default preferences suppress finished turn notifications while delivering permission and error notifications", async () => {
await clearRecordedBrowserNotifications(page);
await runMockAgentTurn(seeded.client, {
cwd: seeded.repoPath,
workspaceId: seeded.workspaceId,
title: "Default finished agent",
prompt: FAST_FINISHED_PROMPT,
waitForStatus: "idle",
});
const permissionAgentId = await runMockAgentTurn(seeded.client, {
cwd: seeded.repoPath,
workspaceId: seeded.workspaceId,
title: "Default permission agent",
prompt: PERMISSION_PROMPT,
waitForStatus: "running",
});
const errorAgentId = await runMockAgentTurn(seeded.client, {
cwd: seeded.repoPath,
workspaceId: seeded.workspaceId,
title: "Default error agent",
prompt: ERROR_PROMPT,
waitForStatus: "error",
});
await expectRecordedAgentNotifications(page, [
{ agentId: permissionAgentId, reason: "permission" },
{ agentId: errorAgentId, reason: "error" },
]);
});
await test.step("enabling Agent finished persists across page reload and allows finished notifications", async () => {
await setNotificationSwitch(page, "Agent finished", true);
await page.reload();
await expectNotificationSwitchState(page, "Agent finished", {
checked: true,
disabled: false,
});
await clearRecordedBrowserNotifications(page);
const finishedAgentId = await runMockAgentTurn(seeded.client, {
cwd: seeded.repoPath,
workspaceId: seeded.workspaceId,
title: "Enabled finished agent",
prompt: FAST_FINISHED_PROMPT,
waitForStatus: "idle",
});
await expectRecordedAgentNotifications(page, [
{ agentId: finishedAgentId, reason: "finished" },
]);
});
await test.step("toggling Enable notifications off disables sub-controls, persists across reload, and suppresses all notifications", async () => {
await setNotificationSwitch(page, "Enable notifications", false);
await expect(
page.getByText("All notifications, including plugins, are paused on this device", {
exact: true,
}),
).toBeVisible();
await expectNotificationSubControlsDisabled(page, true);
await page.reload();
await expectNotificationSwitchState(page, "Enable notifications", {
checked: false,
disabled: false,
});
await expectNotificationSubControlsDisabled(page, true);
await clearRecordedBrowserNotifications(page);
await runMockAgentTurn(seeded.client, {
cwd: seeded.repoPath,
workspaceId: seeded.workspaceId,
title: "Paused error agent",
prompt: ERROR_PROMPT,
waitForStatus: "error",
});
await runMockAgentTurn(seeded.client, {
cwd: seeded.repoPath,
workspaceId: seeded.workspaceId,
title: "Paused finished agent",
prompt: FAST_FINISHED_PROMPT,
waitForStatus: "idle",
});
// Give any in-flight event delivery a chance to settle and verify none fired.
await page.waitForTimeout(300);
expect(await readRecordedBrowserNotifications(page)).toEqual([]);
});
await test.step("delivers plugin notifications, routes OS notification taps through client.onNotificationOpen, and suppresses notifications when the plugin is muted", async () => {
await setNotificationSwitch(page, "Enable notifications", true);
await seeded.client.patchDaemonConfig({ pluginsEnabled: true });
await seeded.client.installDirectoryPlugin(pluginExample.directory);
installedPlugin = true;
const pluginToggle = page.getByRole("switch", { name: "Build alerts", exact: true });
await expect(pluginToggle).toBeVisible();
await expect(pluginToggle).toHaveAttribute("aria-checked", "true");
await clearRecordedBrowserNotifications(page);
const sent = (await seeded.client.invokePluginRpc("notifications-example", "alerts.send", {
buildId: "204",
title: "Build #204 failed",
body: "Playwright suite failed on main",
})) as { status: string; notificationId: string };
expect(sent.status).toBe("sent");
await expectRecordedPluginNotifications(page, [
{
pluginId: "notifications-example",
title: "Build #204 failed",
body: "Playwright suite failed on main",
notificationId: sent.notificationId,
},
]);
await clickRecordedBrowserNotification(page, 0);
await expect(page.getByText("Build alert #204", { exact: true })).toBeVisible();
await expect(
page.getByText("Playwright suite failed on main", { exact: true }),
).toBeVisible();
await expect(
page.getByText(`Notification ID: ${sent.notificationId}`, { exact: true }),
).toBeVisible();
await openSettings(page);
await openNotificationSettings(page);
await setPluginNotificationSwitch(page, "Build alerts", false);
await clearRecordedBrowserNotifications(page);
const mutedResult = (await seeded.client.invokePluginRpc(
"notifications-example",
"alerts.send",
{
buildId: "205",
title: "Build #205 failed",
body: "Muted build alert",
},
)) as { status: string };
expect(mutedResult.status).toBe("sent");
// Trigger an unmuted agent error notification so we prove delivery settled and only
// the unmuted notification arrived (Build #205 was suppressed).
const sentinelErrorAgentId = await runMockAgentTurn(seeded.client, {
cwd: seeded.repoPath,
workspaceId: seeded.workspaceId,
title: "Sentinel unmuted error agent",
prompt: ERROR_PROMPT,
waitForStatus: "error",
});
await expectRecordedAgentNotifications(page, [
{ agentId: sentinelErrorAgentId, reason: "error" },
]);
});
} finally {
if (installedPlugin) {
await seeded.client.removePlugin("notifications-example").catch(() => undefined);
}
await pluginExample.cleanup().catch(() => undefined);
await seeded.cleanup();
}
});
});
@@ -1,269 +0,0 @@
import { expect, type Page } from "@playwright/test";
import { openSettingsSection } from "./settings";
export interface RecordedBrowserNotification {
title: string;
body: string | null;
data: Record<string, unknown> | null;
}
type NotificationSwitchName =
| "Enable notifications"
| "Agent needs permission"
| "Agent errored"
| "Agent finished"
| "Terminal needs input"
| "Terminal finished"
| "Plugin notifications";
export async function installBrowserNotificationRecorder(page: Page): Promise<void> {
await page.addInitScript(() => {
const recorded: RecordedBrowserNotification[] = [];
const instances: Array<{ triggerClick: () => void }> = [];
const win = window as unknown as {
__paseoRecordedNotifications?: RecordedBrowserNotification[];
__paseoNotificationInstances?: Array<{ triggerClick: () => void }>;
};
win.__paseoRecordedNotifications = recorded;
win.__paseoNotificationInstances = instances;
class StubBrowserNotification {
static permission: NotificationPermission = "granted";
static async requestPermission(): Promise<NotificationPermission> {
return "granted";
}
title: string;
body: string | null;
data: Record<string, unknown> | null;
private readonly clickListeners: Array<() => void> = [];
constructor(
title: string,
options?: { body?: string; data?: Record<string, unknown>; icon?: string },
) {
this.title = title;
this.body = options?.body ?? null;
this.data = options?.data ?? null;
recorded.push({
title: this.title,
body: this.body,
data: this.data,
});
instances.push({
triggerClick: () => {
for (const listener of this.clickListeners) {
listener();
}
},
});
}
addEventListener(type: string, listener: () => void): void {
if (type === "click" && typeof listener === "function") {
this.clickListeners.push(listener);
}
}
close(): void {}
}
Object.defineProperty(window, "Notification", {
configurable: true,
writable: true,
value: StubBrowserNotification,
});
});
}
export async function readRecordedBrowserNotifications(
page: Page,
): Promise<RecordedBrowserNotification[]> {
return page.evaluate(() => {
const win = window as unknown as {
__paseoRecordedNotifications?: RecordedBrowserNotification[];
};
return [...(win.__paseoRecordedNotifications ?? [])];
});
}
export async function clearRecordedBrowserNotifications(page: Page): Promise<void> {
await page.evaluate(() => {
const win = window as unknown as {
__paseoRecordedNotifications?: RecordedBrowserNotification[];
__paseoNotificationInstances?: Array<{ triggerClick: () => void }>;
};
if (win.__paseoRecordedNotifications) {
win.__paseoRecordedNotifications.length = 0;
}
if (win.__paseoNotificationInstances) {
win.__paseoNotificationInstances.length = 0;
}
});
}
export async function clickRecordedBrowserNotification(page: Page, index = 0): Promise<void> {
await page.evaluate((targetIndex) => {
const win = window as unknown as {
__paseoNotificationInstances?: Array<{ triggerClick: () => void }>;
};
const instance = win.__paseoNotificationInstances?.[targetIndex];
if (!instance) {
throw new Error(`No recorded browser notification at index ${targetIndex}`);
}
instance.triggerClick();
}, index);
}
export async function expectRecordedPluginNotifications(
page: Page,
expected: ReadonlyArray<{
pluginId: string;
title: string;
body: string;
notificationId?: string;
}>,
): Promise<void> {
await expect
.poll(async () => (await readRecordedBrowserNotifications(page)).length)
.toBe(expected.length);
const notifications = await readRecordedBrowserNotifications(page);
const includeId = expected.some((item) => item.notificationId !== undefined);
expect(
notifications.map((entry) =>
includeId
? {
pluginId: entry.data?.pluginId,
title: entry.title,
body: entry.body,
notificationId: entry.data?.notificationId,
}
: {
pluginId: entry.data?.pluginId,
title: entry.title,
body: entry.body,
},
),
).toEqual(expected);
}
export async function setPluginNotificationSwitch(
page: Page,
pluginLabel: string,
checked: boolean,
): Promise<void> {
const toggle = page.getByRole("switch", { name: pluginLabel, exact: true });
await expect(toggle).toBeVisible();
await expect(toggle).toBeEnabled();
await expect(toggle).toHaveAttribute("aria-checked", String(!checked));
await toggle.click();
await expect(toggle).toHaveAttribute("aria-checked", String(checked));
}
export async function expectRecordedAgentNotifications(
page: Page,
expected: ReadonlyArray<{ agentId: string; reason: string }>,
): Promise<void> {
await expect
.poll(async () => (await readRecordedBrowserNotifications(page)).length)
.toBe(expected.length);
const notifications = await readRecordedBrowserNotifications(page);
expect(
notifications.map((entry) => ({
agentId: entry.data?.agentId,
reason: entry.data?.reason,
})),
).toEqual(expected);
}
export async function openNotificationSettings(page: Page): Promise<void> {
await openSettingsSection(page, "notifications");
await expect(
page.getByRole("switch", { name: "Enable notifications", exact: true }),
).toBeVisible();
}
export function notificationSwitch(page: Page, name: NotificationSwitchName) {
return page.getByRole("switch", { name, exact: true });
}
export async function expectNotificationSwitchState(
page: Page,
name: NotificationSwitchName,
expected: { checked: boolean; disabled?: boolean },
): Promise<void> {
const toggle = notificationSwitch(page, name);
await expect(toggle).toBeVisible();
await expect(toggle).toHaveAttribute("aria-checked", String(expected.checked));
if (expected.disabled) {
await expect(toggle).toBeDisabled();
} else {
await expect(toggle).toBeEnabled();
}
}
export async function expectDefaultNotificationSettings(page: Page): Promise<void> {
await expectNotificationSwitchState(page, "Enable notifications", {
checked: true,
disabled: false,
});
await expectNotificationSwitchState(page, "Agent needs permission", {
checked: true,
disabled: false,
});
await expectNotificationSwitchState(page, "Agent errored", {
checked: true,
disabled: false,
});
await expectNotificationSwitchState(page, "Agent finished", {
checked: false,
disabled: false,
});
await expectNotificationSwitchState(page, "Terminal needs input", {
checked: true,
disabled: false,
});
await expectNotificationSwitchState(page, "Terminal finished", {
checked: false,
disabled: false,
});
await expectNotificationSwitchState(page, "Plugin notifications", {
checked: true,
disabled: false,
});
}
export async function setNotificationSwitch(
page: Page,
name: NotificationSwitchName,
checked: boolean,
): Promise<void> {
const toggle = notificationSwitch(page, name);
await expect(toggle).toBeEnabled();
await expect(toggle).toHaveAttribute("aria-checked", String(!checked));
await toggle.click();
await expect(toggle).toHaveAttribute("aria-checked", String(checked));
}
export async function expectNotificationSubControlsDisabled(
page: Page,
disabled: boolean,
): Promise<void> {
const subSwitches: NotificationSwitchName[] = [
"Agent needs permission",
"Agent errored",
"Agent finished",
"Terminal needs input",
"Terminal finished",
"Plugin notifications",
];
for (const name of subSwitches) {
const toggle = notificationSwitch(page, name);
if (disabled) {
await expect(toggle).toBeDisabled();
} else {
await expect(toggle).toBeEnabled();
}
}
}
@@ -32,12 +32,6 @@ export interface SeedDaemonClient {
config: import("@getpaseo/protocol/messages").MutableDaemonConfigPatch,
): Promise<{ config: import("@getpaseo/protocol/messages").MutableDaemonConfig }>;
getDaemonConfig(): Promise<{ config: import("@getpaseo/protocol/messages").MutableDaemonConfig }>;
installDirectoryPlugin(
directoryPath: string,
id?: string,
): Promise<import("@getpaseo/protocol/messages").PluginListItem>;
removePlugin(pluginId: string): Promise<void>;
invokePluginRpc(pluginId: string, method: string, input: unknown): Promise<unknown>;
connect(): Promise<void>;
close(): Promise<void>;
addProject(cwd: string): Promise<{
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@getpaseo/app",
"version": "0.17.5",
"version": "0.17.6",
"private": true,
"main": "index.ts",
"scripts": {
@@ -1,117 +0,0 @@
import { DEFAULT_NOTIFICATION_PREFERENCES } from "@getpaseo/protocol/notification-preferences";
import { describe, expect, it } from "vitest";
import {
collectNotificationPluginIds,
collectNotificationPlugins,
hasConnectedHostMissingPushPreferences,
setNotificationEventEnabled,
setNotificationPluginMuted,
} from "./notifications-model";
describe("notifications settings model", () => {
it("unions installed plugin IDs and muted plugin IDs in sorted unique order", () => {
const installed = [{ id: "zeta-plugin" }, { id: "alpha-plugin" }, { id: "zeta-plugin" }];
const muted = ["beta-removed-plugin", "alpha-plugin"];
expect(collectNotificationPluginIds(installed, muted)).toEqual([
"alpha-plugin",
"beta-removed-plugin",
"zeta-plugin",
]);
});
it("merges server-only configured plugins and display names with client-bundle and muted plugin IDs", () => {
const configuredPlugins = [
{ id: "server-pipeline", name: "Server Pipeline" },
{ id: "shared-plugin", name: "Shared Plugin" },
{ id: "headless-id-only" },
];
const installedPlugins = [{ id: "shared-plugin" }, { id: "client-only-plugin" }];
const mutedPluginIds = ["removed-muted-plugin", "server-pipeline"];
expect(
collectNotificationPlugins({
configuredPlugins,
installedPlugins,
mutedPluginIds,
}),
).toEqual([
{ id: "client-only-plugin", label: "client-only-plugin" },
{ id: "headless-id-only", label: "headless-id-only" },
{ id: "removed-muted-plugin", label: "removed-muted-plugin" },
{ id: "server-pipeline", label: "Server Pipeline" },
{ id: "shared-plugin", label: "Shared Plugin" },
]);
});
it("mutes and unmutes individual plugins while keeping muted IDs normalized", () => {
const mutedOnce = setNotificationPluginMuted(
DEFAULT_NOTIFICATION_PREFERENCES,
"ci-plugin",
true,
);
expect(mutedOnce.plugins.muted).toEqual(["ci-plugin"]);
const mutedTwice = setNotificationPluginMuted(mutedOnce, "alerts-plugin", true);
expect(mutedTwice.plugins.muted).toEqual(["alerts-plugin", "ci-plugin"]);
const unmuted = setNotificationPluginMuted(mutedTwice, "ci-plugin", false);
expect(unmuted.plugins.muted).toEqual(["alerts-plugin"]);
});
it("updates individual built-in event switches without mutating other preferences", () => {
const next = setNotificationEventEnabled(
DEFAULT_NOTIFICATION_PREFERENCES,
"agentFinished",
true,
);
expect(next.events.agentFinished).toBe(true);
expect(next.events.agentPermission).toBe(true);
expect(next.events.agentError).toBe(true);
expect(DEFAULT_NOTIFICATION_PREFERENCES.events.agentFinished).toBe(false);
});
it("detects when any connected host with serverInfo lacks pushNotificationPreferences", () => {
const hosts = [{ serverId: "srv-new" }, { serverId: "srv-old" }];
expect(
hasConnectedHostMissingPushPreferences(hosts, {
"srv-new": {
serverInfo: {
serverId: "srv-new",
hostname: "new-host",
version: "0.18.0",
machineKind: null,
capabilities: undefined,
features: { pushNotificationPreferences: true },
},
},
"srv-old": {
serverInfo: {
serverId: "srv-old",
hostname: "old-host",
version: "0.17.0",
machineKind: null,
capabilities: undefined,
features: {},
},
},
}),
).toBe(true);
expect(
hasConnectedHostMissingPushPreferences([{ serverId: "srv-new" }], {
"srv-new": {
serverInfo: {
serverId: "srv-new",
hostname: "new-host",
version: "0.18.0",
machineKind: null,
capabilities: undefined,
features: { pushNotificationPreferences: true },
},
},
}),
).toBe(false);
});
});
@@ -1,104 +0,0 @@
import {
normalizeNotificationPreferences,
type NotificationPreferences,
} from "@getpaseo/protocol/notification-preferences";
import type { HostFeatureSessionState } from "@/runtime/host-features";
export type NotificationEventKey = keyof NotificationPreferences["events"];
export interface NotificationPluginEntry {
id: string;
label: string;
}
export function collectNotificationPlugins(input: {
configuredPlugins?: readonly { id: string; name?: string }[];
installedPlugins: readonly { id: string; name?: string }[];
mutedPluginIds: readonly string[];
}): NotificationPluginEntry[] {
const byId = new Map<string, string>();
const recordPlugin = (id: string, name?: string) => {
const trimmedId = id.trim();
if (trimmedId.length === 0) {
return;
}
const trimmedName = typeof name === "string" ? name.trim() : "";
const existing = byId.get(trimmedId);
if (!existing || existing === trimmedId) {
byId.set(trimmedId, trimmedName.length > 0 ? trimmedName : trimmedId);
}
};
for (const plugin of input.configuredPlugins ?? []) {
recordPlugin(plugin.id, plugin.name);
}
for (const plugin of input.installedPlugins) {
recordPlugin(plugin.id, plugin.name);
}
for (const mutedId of input.mutedPluginIds) {
recordPlugin(mutedId);
}
return Array.from(byId.entries())
.sort(([leftId], [rightId]) => leftId.localeCompare(rightId))
.map(([id, label]) => ({ id, label }));
}
export function collectNotificationPluginIds(
installedPlugins: readonly { id: string }[],
mutedPluginIds: readonly string[],
): string[] {
return collectNotificationPlugins({ installedPlugins, mutedPluginIds }).map((entry) => entry.id);
}
export function setNotificationEventEnabled(
preferences: NotificationPreferences,
eventKey: NotificationEventKey,
enabled: boolean,
): NotificationPreferences {
return normalizeNotificationPreferences({
...preferences,
events: {
...preferences.events,
[eventKey]: enabled,
},
});
}
export function setNotificationPluginMuted(
preferences: NotificationPreferences,
pluginId: string,
muted: boolean,
): NotificationPreferences {
const currentMuted = new Set(preferences.plugins.muted);
if (muted) {
currentMuted.add(pluginId);
} else {
currentMuted.delete(pluginId);
}
return normalizeNotificationPreferences({
...preferences,
plugins: {
...preferences.plugins,
muted: Array.from(currentMuted),
},
});
}
export function hasConnectedHostMissingPushPreferences(
hosts: readonly { serverId: string }[],
sessions: HostFeatureSessionState["sessions"],
): boolean {
for (const host of hosts) {
const serverInfo = sessions[host.serverId]?.serverInfo;
if (!serverInfo) {
continue;
}
// COMPAT(pushNotificationPreferences): added in v0.18.0, remove gate after 2027-06-01.
if (serverInfo.features?.pushNotificationPreferences !== true) {
return true;
}
}
return false;
}
@@ -1,311 +0,0 @@
import { AppearanceText as Text } from "@/appearance/text";
import { useCallback, useMemo } from "react";
import { useTranslation } from "react-i18next";
import { View } from "react-native";
import { StyleSheet } from "react-native-unistyles";
import { normalizeNotificationPreferences } from "@getpaseo/protocol/notification-preferences";
import { SettingsSection } from "@/components/settings/headings/settings-section";
import {
collectNotificationPlugins,
hasConnectedHostMissingPushPreferences,
setNotificationEventEnabled,
setNotificationPluginMuted,
type NotificationEventKey,
} from "@/components/settings/notifications-model";
import { Alert } from "@/components/ui/alert";
import { Switch } from "@/components/ui/switch";
import { isNative } from "@/constants/platform";
import { DesktopNotificationsSection } from "@/desktop/components/desktop-notifications-section";
import { useAppSettings } from "@/hooks/use-settings";
import { useConfiguredPluginsAcrossHosts } from "@/plugins/plugin-list";
import { useInstalledPlugins } from "@/plugins/registry";
import { useHosts } from "@/runtime/host-runtime";
import { useSessionStore } from "@/stores/session-store";
import { settingsStyles } from "@/styles/settings";
const EVENT_KEYS: readonly NotificationEventKey[] = [
"agentPermission",
"agentError",
"agentFinished",
"terminalNeedsInput",
"terminalFinished",
];
interface EventSwitchRowProps {
eventKey: NotificationEventKey;
label: string;
description: string;
value: boolean;
disabled: boolean;
showBorder: boolean;
onChange: (eventKey: NotificationEventKey, value: boolean) => void;
}
function EventSwitchRow({
eventKey,
label,
description,
value,
disabled,
showBorder,
onChange,
}: EventSwitchRowProps) {
const handleChange = useCallback(
(nextValue: boolean) => {
onChange(eventKey, nextValue);
},
[eventKey, onChange],
);
const rowStyle = useMemo(
() => [settingsStyles.row, showBorder ? settingsStyles.rowBorder : null],
[showBorder],
);
return (
<View style={rowStyle}>
<View style={settingsStyles.rowContent}>
<Text style={settingsStyles.rowTitle}>{label}</Text>
<Text style={settingsStyles.rowHint}>{description}</Text>
</View>
<Switch
value={value}
onValueChange={handleChange}
disabled={disabled}
accessibilityLabel={label}
testID={`notifications-event-${eventKey}-switch`}
/>
</View>
);
}
interface PluginSwitchRowProps {
pluginId: string;
label: string;
muted: boolean;
disabled: boolean;
onToggleMuted: (pluginId: string, muted: boolean) => void;
}
function PluginSwitchRow({
pluginId,
label,
muted,
disabled,
onToggleMuted,
}: PluginSwitchRowProps) {
const handleChange = useCallback(
(enabled: boolean) => {
onToggleMuted(pluginId, !enabled);
},
[onToggleMuted, pluginId],
);
return (
<View style={[settingsStyles.row, settingsStyles.rowBorder]}>
<View style={settingsStyles.rowContent}>
<Text style={settingsStyles.rowTitle}>{label}</Text>
{label !== pluginId ? <Text style={settingsStyles.rowHint}>{pluginId}</Text> : null}
</View>
<Switch
value={!muted}
onValueChange={handleChange}
disabled={disabled}
accessibilityLabel={label}
testID={`notifications-plugin-switch-${pluginId}`}
/>
</View>
);
}
export function NotificationsSection() {
const { t } = useTranslation();
const { settings, updateSettings } = useAppSettings();
const preferences = settings.notifications;
const configuredPlugins = useConfiguredPluginsAcrossHosts();
const installedPlugins = useInstalledPlugins();
const hosts = useHosts();
const sessions = useSessionStore((state) => state.sessions);
const plugins = useMemo(
() =>
collectNotificationPlugins({
configuredPlugins,
installedPlugins,
mutedPluginIds: preferences.plugins.muted,
}),
[configuredPlugins, installedPlugins, preferences.plugins.muted],
);
const mutedPluginIds = useMemo(
() => new Set(preferences.plugins.muted),
[preferences.plugins.muted],
);
const showLegacyHostHint = useMemo(
() => isNative && hasConnectedHostMissingPushPreferences(hosts, sessions),
[hosts, sessions],
);
const handleMasterEnabledChange = useCallback(
(enabled: boolean) => {
void updateSettings((current) => ({
notifications: normalizeNotificationPreferences({
...current.notifications,
enabled,
}),
}));
},
[updateSettings],
);
const handleEventChange = useCallback(
(eventKey: NotificationEventKey, enabled: boolean) => {
void updateSettings((current) => ({
notifications: setNotificationEventEnabled(current.notifications, eventKey, enabled),
}));
},
[updateSettings],
);
const handlePluginsEnabledChange = useCallback(
(enabled: boolean) => {
void updateSettings((current) => ({
notifications: normalizeNotificationPreferences({
...current.notifications,
plugins: {
...current.notifications.plugins,
enabled,
},
}),
}));
},
[updateSettings],
);
const handlePluginMutedChange = useCallback(
(pluginId: string, muted: boolean) => {
void updateSettings((current) => ({
notifications: setNotificationPluginMuted(current.notifications, pluginId, muted),
}));
},
[updateSettings],
);
const subCardStyle = useMemo(
() => [settingsStyles.card, !preferences.enabled ? styles.disabledCard : null],
[preferences.enabled],
);
const showEmptyPluginsRow = preferences.plugins.enabled && plugins.length === 0;
const showPluginRows = preferences.plugins.enabled && plugins.length > 0;
return (
<View>
<SettingsSection
title={t("settings.notifications.title")}
testID="notifications-master-section"
>
<View style={settingsStyles.card} testID="notifications-master-card">
<View style={settingsStyles.row}>
<View style={settingsStyles.rowContent}>
<Text style={settingsStyles.rowTitle}>
{t("settings.notifications.enabled.label")}
</Text>
<Text style={settingsStyles.rowHint}>
{preferences.enabled
? t("settings.notifications.enabled.description")
: t("settings.notifications.enabled.pausedDescription")}
</Text>
</View>
<Switch
value={preferences.enabled}
onValueChange={handleMasterEnabledChange}
accessibilityLabel={t("settings.notifications.enabled.label")}
testID="notifications-master-switch"
/>
</View>
</View>
{showLegacyHostHint ? (
<Alert
size="sm"
variant="info"
title={t("settings.notifications.legacyHostTitle")}
description={t("settings.notifications.legacyHostHint")}
testID="notifications-legacy-host-alert"
/>
) : null}
</SettingsSection>
<SettingsSection
title={t("settings.notifications.events.title")}
testID="notifications-events-section"
>
<View style={subCardStyle} testID="notifications-events-card">
{EVENT_KEYS.map((eventKey, index) => (
<EventSwitchRow
key={eventKey}
eventKey={eventKey}
label={t(`settings.notifications.events.${eventKey}.label`)}
description={t(`settings.notifications.events.${eventKey}.description`)}
value={preferences.events[eventKey]}
disabled={!preferences.enabled}
showBorder={index > 0}
onChange={handleEventChange}
/>
))}
</View>
</SettingsSection>
<SettingsSection
title={t("settings.notifications.plugins.title")}
testID="notifications-plugins-section"
>
<View style={subCardStyle} testID="notifications-plugins-card">
<View style={settingsStyles.row}>
<View style={settingsStyles.rowContent}>
<Text style={settingsStyles.rowTitle}>
{t("settings.notifications.plugins.enabled.label")}
</Text>
<Text style={settingsStyles.rowHint}>
{t("settings.notifications.plugins.enabled.description")}
</Text>
</View>
<Switch
value={preferences.plugins.enabled}
onValueChange={handlePluginsEnabledChange}
disabled={!preferences.enabled}
accessibilityLabel={t("settings.notifications.plugins.enabled.label")}
testID="notifications-plugins-enabled-switch"
/>
</View>
{showEmptyPluginsRow ? (
<View style={[settingsStyles.row, settingsStyles.rowBorder]}>
<View style={settingsStyles.rowContent}>
<Text style={settingsStyles.rowHint} testID="notifications-plugins-empty">
{t("settings.notifications.plugins.empty")}
</Text>
</View>
</View>
) : null}
{showPluginRows
? plugins.map((plugin) => (
<PluginSwitchRow
key={plugin.id}
pluginId={plugin.id}
label={plugin.label}
muted={mutedPluginIds.has(plugin.id)}
disabled={!preferences.enabled}
onToggleMuted={handlePluginMutedChange}
/>
))
: null}
</View>
</SettingsSection>
<DesktopNotificationsSection />
</View>
);
}
const styles = StyleSheet.create((theme) => ({
disabledCard: {
opacity: theme.opacity[50],
},
}));
+131 -65
View File
@@ -1,7 +1,6 @@
import { useRef, ReactNode, useCallback, useEffect } from "react";
import { Buffer } from "buffer";
import { AppState } from "react-native";
import { isNative } from "@/constants/platform";
import { observeOpenWorkspaceAgentIds } from "@/stores/workspace-layout-store";
import { useQueryClient } from "@tanstack/react-query";
import { useTranslation } from "react-i18next";
@@ -12,22 +11,21 @@ import {
createSetAgentInitializing,
refreshAgentInitializationTimeout,
} from "@/hooks/use-agent-initialization";
import type { StreamItem } from "@/types/stream";
import { planTimelineTailFetch } from "@/timeline/timeline-sync-plan";
import { requestTimelineReplacement } from "@/timeline/timeline-replacement";
import { type ViewedTimelineOwner } from "@/timeline/viewed-timeline-sync";
import type { SessionOutboundMessage } from "@getpaseo/protocol/messages";
import { parseServerInfoStatusPayload } from "@getpaseo/protocol/messages";
import type { AgentAttentionNotificationPayload } from "@getpaseo/protocol/agent-attention-notification";
import {
deliverAgentAttentionOsNotification,
deliverPluginOsNotification,
deliverTerminalAttentionOsNotification,
getCurrentNotificationPreferences,
} from "./session-notifications";
buildAgentAttentionNotificationPayload,
type AgentAttentionReason,
type AgentAttentionNotificationPayload,
type NotificationPermissionRequest,
} from "@getpaseo/protocol/agent-attention-notification";
import type { DaemonClient } from "@getpaseo/client/internal/daemon-client";
import type { AgentPermissionResponse } from "@getpaseo/protocol/agent-types";
import { useHostFeature } from "@/runtime/host-features";
import { getHostRuntimeStore, useHostRuntimeIsConnected } from "@/runtime/host-runtime";
import { useVoiceAudioEngineOptional, useVoiceRuntimeOptional } from "@/contexts/voice-context";
import type { AudioPlaybackSource } from "@/audio";
@@ -35,9 +33,10 @@ import {
selectAgentTimelineState,
toDaemonServerInfo,
useSessionStore,
type SessionState,
} from "@/stores/session-store";
import { sendOsNotification } from "@/utils/os-notifications";
import { getIsAppVisible } from "@/utils/app-visibility";
import { getIsAppActivelyVisible, getIsAppVisible } from "@/utils/app-visibility";
import {
getInitKey,
getInitDeferred,
@@ -99,6 +98,71 @@ function buildAudioPlaybackSource(chunks: BufferedAudioChunk[]): AudioPlaybackSo
};
}
const findLatestAssistantMessageText = (items: StreamItem[]): string | null => {
for (let i = items.length - 1; i >= 0; i -= 1) {
const item = items[i];
if (item.kind === "assistant_message") {
return item.text;
}
}
return null;
};
const getLatestPermissionRequest = (
session: SessionState | undefined,
agentId: string,
): NotificationPermissionRequest | null => {
if (!session) {
return null;
}
let latest: NotificationPermissionRequest | null = null;
for (const pending of session.pendingPermissions.values()) {
if (pending.agentId === agentId) {
latest = pending.request;
}
}
if (latest) {
return latest;
}
const agentPending = session.agents.get(agentId)?.pendingPermissions;
if (agentPending && agentPending.length > 0) {
return agentPending[agentPending.length - 1] as NotificationPermissionRequest;
}
return null;
};
interface AgentAttentionNotificationInput {
notification?: AgentAttentionNotificationPayload;
reason: AgentAttentionReason;
serverId: string;
workspaceId: string | undefined;
agentId: string;
assistantMessage: string | null;
permissionRequest: NotificationPermissionRequest | null;
}
function resolveAgentAttentionNotification(
input: AgentAttentionNotificationInput,
): AgentAttentionNotificationPayload | null {
if (input.notification) {
return input.notification.data.workspaceId ? input.notification : null;
}
if (!input.workspaceId) {
return null;
}
return buildAgentAttentionNotificationPayload({
reason: input.reason,
serverId: input.serverId,
workspaceId: input.workspaceId,
agentId: input.agentId,
assistantMessage: input.reason === "finished" ? input.assistantMessage : null,
permissionRequest: input.reason === "permission" ? input.permissionRequest : null,
});
}
function notifyVoiceAbortFailure(
data: Extract<SessionOutboundMessage, { type: "activity_log" }>["payload"],
notifyError: (message: string) => void,
@@ -138,10 +202,6 @@ function SessionProviderInternal({ children, serverId, client }: SessionProvider
const voiceAudioEngine = useVoiceAudioEngineOptional();
const queryClient = useQueryClient();
const isConnected = useHostRuntimeIsConnected(serverId);
// COMPAT(pluginNotifications): added in v0.18.0, remove gate after 2027-06-01.
const supportsPluginNotifications =
useHostFeature(serverId, "pluginNotifications") ||
client.getLastServerInfoMessage()?.features?.pluginNotifications === true;
const toast = useToast();
// Zustand store actions
@@ -191,10 +251,7 @@ function SessionProviderInternal({ children, serverId, client }: SessionProvider
focusedAgentId,
focusedTerminalId,
});
useEffect(
() => startPushNotifications({ client, serverId, queryClient }),
[client, queryClient, serverId],
);
useEffect(() => startPushNotifications({ client, serverId }), [client, serverId]);
const notifyAgentAttention = useCallback(
(params: {
@@ -203,17 +260,52 @@ function SessionProviderInternal({ children, serverId, client }: SessionProvider
timestamp: string;
notification?: AgentAttentionNotificationPayload;
}) => {
deliverAgentAttentionOsNotification({
const appState = appStateRef.current;
const session = useSessionStore.getState().sessions[serverId];
const attentionFocusedAgentId = session?.focusedAgentId ?? null;
if (params.reason === "error") {
return;
}
const isActivelyVisible = getIsAppActivelyVisible(appState);
const isAwayFromAgent = !isActivelyVisible || attentionFocusedAgentId !== params.agentId;
if (!isAwayFromAgent) {
return;
}
const timestampMs = new Date(params.timestamp).getTime();
const lastNotified = attentionNotifiedRef.current.get(params.agentId);
if (lastNotified && lastNotified >= timestampMs) {
return;
}
attentionNotifiedRef.current.set(params.agentId, timestampMs);
const head = session?.agentStreamHead.get(params.agentId) ?? [];
const tail = session?.agentStreamTail.get(params.agentId) ?? [];
const assistantMessage =
findLatestAssistantMessageText(head) ?? findLatestAssistantMessageText(tail);
const permissionRequest = getLatestPermissionRequest(session, params.agentId);
const workspaceId = session?.agents?.get(params.agentId)?.workspaceId;
const notification = resolveAgentAttentionNotification({
notification: params.notification,
reason: params.reason,
serverId,
params,
appState: appStateRef.current,
session: useSessionStore.getState().sessions[serverId],
attentionNotified: attentionNotifiedRef.current,
preferences: getCurrentNotificationPreferences(queryClient),
sendNotification: sendOsNotification,
workspaceId,
agentId: params.agentId,
assistantMessage,
permissionRequest,
});
if (!notification) {
return;
}
void sendOsNotification({
title: notification.title,
body: notification.body,
data: notification.data,
});
},
[queryClient, serverId],
[serverId],
);
useEffect(() => {
@@ -555,11 +647,20 @@ function SessionProviderInternal({ children, serverId, client }: SessionProvider
if (message.type !== "terminal_attention_required") {
return;
}
deliverTerminalAttentionOsNotification({
serverId,
payload: message.payload,
preferences: getCurrentNotificationPreferences(queryClient),
sendNotification: sendOsNotification,
if (!message.payload.shouldNotify) {
return;
}
void sendOsNotification({
title: message.payload.title,
body: message.payload.body,
// serverId + workspaceId + terminalId route a tap to the terminal tab; cwd is
// carried as a fallback identifier when the daemon resolved no workspace.
data: {
serverId: message.payload.serverId ?? serverId,
terminalId: message.payload.terminalId,
cwd: message.payload.cwd,
...(message.payload.workspaceId ? { workspaceId: message.payload.workspaceId } : {}),
},
});
});
@@ -597,41 +698,6 @@ function SessionProviderInternal({ children, serverId, client }: SessionProvider
voiceAudioEngine,
]);
useEffect(() => {
// Native apps receive plugin alerts via remote push only (`sendOsNotification` is a no-op
// on native). Subscribing on native would mark the phone as the active in-app recipient and
// suppress its own Expo push without rendering anything in-app.
// COMPAT(pluginNotifications): added in v0.18.0, remove gate after 2027-06-01.
if (isNative || !supportsPluginNotifications) {
return;
}
const pluginNotificationsFeed = client.observeEvents(["plugin.notification"], {
notifications: true,
});
const unsubPluginNotification = pluginNotificationsFeed.subscribe({
snapshot: () => {},
update: (message) => {
if (message.type !== "plugin.notification") {
return;
}
deliverPluginOsNotification({
serverId,
payload: message.payload,
preferences: getCurrentNotificationPreferences(queryClient),
sendNotification: sendOsNotification,
});
},
});
return () => {
unsubPluginNotification();
void pluginNotificationsFeed
.release()
.catch((error) =>
console.warn("[Session] Failed to release plugin notifications feed", error),
);
};
}, [client, queryClient, serverId, supportsPluginNotifications]);
const _cancelAgentRun = useCallback(
(agentId: string) => {
if (!client) {
@@ -1,376 +0,0 @@
import { QueryClient } from "@tanstack/react-query";
import {
DEFAULT_NOTIFICATION_PREFERENCES,
type NotificationPreferences,
} from "@getpaseo/protocol/notification-preferences";
import { describe, expect, it } from "vitest";
import { APP_SETTINGS_QUERY_KEY, DEFAULT_CLIENT_SETTINGS } from "@/hooks/use-settings/storage";
import {
deliverAgentAttentionOsNotification,
deliverPluginOsNotification,
deliverTerminalAttentionOsNotification,
getCurrentNotificationPreferences,
} from "./session-notifications";
function createNotificationRecorder() {
const sent: Array<{ title: string; body?: string; data?: Record<string, unknown> }> = [];
return {
sent,
sendNotification: async (payload: {
title: string;
body?: string;
data?: Record<string, unknown>;
}) => {
sent.push(payload);
return true;
},
};
}
function makeAgentAttentionParams(reason: "permission" | "error" | "finished", index = 1) {
return {
agentId: `agent-${reason}-${index}`,
reason,
timestamp: new Date(1_700_000_000_000 + index * 1000).toISOString(),
notification: {
title: `Agent ${reason}`,
body: `Body for ${reason}`,
data: {
serverId: "srv-1",
workspaceId: "ws-1",
agentId: `agent-${reason}-${index}`,
reason,
},
},
};
}
describe("session OS notification filtering", () => {
it("normalizes notification preferences from query cache or falls back to defaults", () => {
const emptyClient = new QueryClient();
expect(getCurrentNotificationPreferences(emptyClient)).toEqual(
DEFAULT_NOTIFICATION_PREFERENCES,
);
const populatedClient = new QueryClient();
const custom: NotificationPreferences = {
...DEFAULT_NOTIFICATION_PREFERENCES,
events: {
...DEFAULT_NOTIFICATION_PREFERENCES.events,
agentFinished: true,
},
};
populatedClient.setQueryData(APP_SETTINGS_QUERY_KEY, {
...DEFAULT_CLIENT_SETTINGS,
notifications: custom,
});
expect(getCurrentNotificationPreferences(populatedClient)).toEqual(custom);
});
it("with default preferences, notifies on permission, error, and terminalNeedsInput, and skips finished and terminalFinished", () => {
const recorder = createNotificationRecorder();
const attentionNotified = new Map<string, number>();
const preferences = DEFAULT_NOTIFICATION_PREFERENCES;
expect(
deliverAgentAttentionOsNotification({
serverId: "srv-1",
params: makeAgentAttentionParams("permission", 1),
isActivelyVisible: false,
session: undefined,
attentionNotified,
preferences,
sendNotification: recorder.sendNotification,
}),
).toBe(true);
expect(
deliverAgentAttentionOsNotification({
serverId: "srv-1",
params: makeAgentAttentionParams("error", 2),
isActivelyVisible: false,
session: undefined,
attentionNotified,
preferences,
sendNotification: recorder.sendNotification,
}),
).toBe(true);
expect(
deliverAgentAttentionOsNotification({
serverId: "srv-1",
params: makeAgentAttentionParams("finished", 3),
isActivelyVisible: false,
session: undefined,
attentionNotified,
preferences,
sendNotification: recorder.sendNotification,
}),
).toBe(false);
expect(
deliverTerminalAttentionOsNotification({
serverId: "srv-1",
payload: {
serverId: "srv-1",
terminalId: "term-1",
cwd: "/repo",
workspaceId: "ws-1",
reason: "needs_input",
title: "Terminal waiting for input",
body: "zsh",
shouldNotify: true,
},
preferences,
sendNotification: recorder.sendNotification,
}),
).toBe(true);
expect(
deliverTerminalAttentionOsNotification({
serverId: "srv-1",
payload: {
serverId: "srv-1",
terminalId: "term-1",
cwd: "/repo",
workspaceId: "ws-1",
reason: "finished",
title: "Command finished",
body: "zsh",
shouldNotify: true,
},
preferences,
sendNotification: recorder.sendNotification,
}),
).toBe(false);
expect(recorder.sent.map((item) => item.title)).toEqual([
"Agent permission",
"Agent error",
"Terminal waiting for input",
]);
});
it("delivers finished notifications when agentFinished and terminalFinished are enabled", () => {
const recorder = createNotificationRecorder();
const attentionNotified = new Map<string, number>();
const preferences: NotificationPreferences = {
...DEFAULT_NOTIFICATION_PREFERENCES,
events: {
...DEFAULT_NOTIFICATION_PREFERENCES.events,
agentFinished: true,
terminalFinished: true,
},
};
expect(
deliverAgentAttentionOsNotification({
serverId: "srv-1",
params: makeAgentAttentionParams("finished", 1),
isActivelyVisible: false,
session: undefined,
attentionNotified,
preferences,
sendNotification: recorder.sendNotification,
}),
).toBe(true);
expect(
deliverTerminalAttentionOsNotification({
serverId: "srv-1",
payload: {
serverId: "srv-1",
terminalId: "term-1",
cwd: "/repo",
workspaceId: "ws-1",
reason: "finished",
title: "Command finished",
body: "zsh",
shouldNotify: true,
},
preferences,
sendNotification: recorder.sendNotification,
}),
).toBe(true);
expect(recorder.sent.map((item) => item.title)).toEqual(["Agent finished", "Command finished"]);
});
it("blocks all agent and terminal notifications when master enabled is false", () => {
const recorder = createNotificationRecorder();
const attentionNotified = new Map<string, number>();
const preferences: NotificationPreferences = {
enabled: false,
events: {
agentPermission: true,
agentError: true,
agentFinished: true,
terminalNeedsInput: true,
terminalFinished: true,
},
plugins: {
enabled: true,
muted: [],
},
};
for (const reason of ["permission", "error", "finished"] as const) {
expect(
deliverAgentAttentionOsNotification({
serverId: "srv-1",
params: makeAgentAttentionParams(reason),
isActivelyVisible: false,
session: undefined,
attentionNotified,
preferences,
sendNotification: recorder.sendNotification,
}),
).toBe(false);
}
for (const reason of ["needs_input", "finished"] as const) {
expect(
deliverTerminalAttentionOsNotification({
serverId: "srv-1",
payload: {
serverId: "srv-1",
terminalId: "term-1",
cwd: "/repo",
workspaceId: "ws-1",
reason,
title: `Terminal ${reason}`,
body: "zsh",
shouldNotify: true,
},
preferences,
sendNotification: recorder.sendNotification,
}),
).toBe(false);
}
expect(recorder.sent).toEqual([]);
});
it("filters plugin.notification OS notifications across master, plugin switch, per-plugin mute, and all-builtins-off combinations", () => {
const recorder = createNotificationRecorder();
const basePayload = {
serverId: "srv-1",
pluginId: "ci-alerts",
notificationId: "notif-1",
title: "Build failed",
body: "Check logs",
open: { type: "screen" as const, screenId: "report", params: { buildId: "42" } },
data: { buildId: 42 },
shouldNotify: true,
};
// shouldNotify: false -> not delivered
expect(
deliverPluginOsNotification({
serverId: "srv-1",
payload: { ...basePayload, shouldNotify: false },
preferences: DEFAULT_NOTIFICATION_PREFERENCES,
sendNotification: recorder.sendNotification,
}),
).toBe(false);
// Master off -> blocks plugin notification
expect(
deliverPluginOsNotification({
serverId: "srv-1",
payload: basePayload,
preferences: { ...DEFAULT_NOTIFICATION_PREFERENCES, enabled: false },
sendNotification: recorder.sendNotification,
}),
).toBe(false);
// Plugins switch off -> blocks plugin notification
expect(
deliverPluginOsNotification({
serverId: "srv-1",
payload: basePayload,
preferences: {
...DEFAULT_NOTIFICATION_PREFERENCES,
plugins: { enabled: false, muted: [] },
},
sendNotification: recorder.sendNotification,
}),
).toBe(false);
// Per-plugin mute -> blocks muted plugin while allowing unmuted plugin
const mutedPreferences: NotificationPreferences = {
...DEFAULT_NOTIFICATION_PREFERENCES,
plugins: {
enabled: true,
muted: ["ci-alerts"],
},
};
expect(
deliverPluginOsNotification({
serverId: "srv-1",
payload: basePayload,
preferences: mutedPreferences,
sendNotification: recorder.sendNotification,
}),
).toBe(false);
expect(
deliverPluginOsNotification({
serverId: "srv-1",
payload: { ...basePayload, pluginId: "deploy-watch", notificationId: "notif-2" },
preferences: mutedPreferences,
sendNotification: recorder.sendNotification,
}),
).toBe(true);
// All built-in events off + plugins on -> delivers plugin notification
const onlyPluginsPreferences: NotificationPreferences = {
enabled: true,
events: {
agentPermission: false,
agentError: false,
agentFinished: false,
terminalNeedsInput: false,
terminalFinished: false,
},
plugins: {
enabled: true,
muted: [],
},
};
expect(
deliverPluginOsNotification({
serverId: "srv-1",
payload: basePayload,
preferences: onlyPluginsPreferences,
sendNotification: recorder.sendNotification,
}),
).toBe(true);
expect(recorder.sent).toEqual([
{
title: "Build failed",
body: "Check logs",
data: {
kind: "plugin",
serverId: "srv-1",
pluginId: "deploy-watch",
notificationId: "notif-2",
open: { type: "screen", screenId: "report", params: { buildId: "42" } },
data: { buildId: 42 },
},
},
{
title: "Build failed",
body: "Check logs",
data: {
kind: "plugin",
serverId: "srv-1",
pluginId: "ci-alerts",
notificationId: "notif-1",
open: { type: "screen", screenId: "report", params: { buildId: "42" } },
data: { buildId: 42 },
},
},
]);
});
});
@@ -1,235 +0,0 @@
import {
buildAgentAttentionNotificationPayload,
type AgentAttentionNotificationPayload,
type AgentAttentionReason,
type NotificationPermissionRequest,
} from "@getpaseo/protocol/agent-attention-notification";
import type { SessionOutboundMessage } from "@getpaseo/protocol/messages";
import {
normalizeNotificationPreferences,
shouldDeliverNotification,
type NotificationPreferences,
} from "@getpaseo/protocol/notification-preferences";
import type { QueryClient } from "@tanstack/react-query";
import { APP_SETTINGS_QUERY_KEY, type AppSettings } from "@/hooks/use-settings/storage";
import type { SessionState } from "@/stores/session-store";
import type { StreamItem } from "@/types/stream";
import { getIsAppActivelyVisible } from "@/utils/app-visibility";
type TerminalAttentionPayload = Extract<
SessionOutboundMessage,
{ type: "terminal_attention_required" }
>["payload"];
type PluginNotificationPayload = Extract<
SessionOutboundMessage,
{ type: "plugin.notification" }
>["payload"];
export type OsNotificationSender = (payload: {
title: string;
body?: string;
data?: Record<string, unknown>;
}) => Promise<boolean>;
export function getCurrentNotificationPreferences(
queryClient: Pick<QueryClient, "getQueryData">,
): NotificationPreferences {
return normalizeNotificationPreferences(
queryClient.getQueryData<AppSettings>(APP_SETTINGS_QUERY_KEY)?.notifications,
);
}
const findLatestAssistantMessageText = (items: StreamItem[]): string | null => {
for (let i = items.length - 1; i >= 0; i -= 1) {
const item = items[i];
if (item.kind === "assistant_message") {
return item.text;
}
}
return null;
};
const getLatestPermissionRequest = (
session: SessionState | undefined,
agentId: string,
): NotificationPermissionRequest | null => {
if (!session) {
return null;
}
let latest: NotificationPermissionRequest | null = null;
for (const pending of session.pendingPermissions.values()) {
if (pending.agentId === agentId) {
latest = pending.request;
}
}
if (latest) {
return latest;
}
const agentPending = session.agents.get(agentId)?.pendingPermissions;
if (agentPending && agentPending.length > 0) {
return agentPending[agentPending.length - 1] as NotificationPermissionRequest;
}
return null;
};
interface AgentAttentionNotificationInput {
notification?: AgentAttentionNotificationPayload;
reason: AgentAttentionReason;
serverId: string;
workspaceId: string | undefined;
agentId: string;
assistantMessage: string | null;
permissionRequest: NotificationPermissionRequest | null;
}
export function resolveAgentAttentionNotification(
input: AgentAttentionNotificationInput,
): AgentAttentionNotificationPayload | null {
if (input.notification) {
return input.notification.data.workspaceId ? input.notification : null;
}
if (!input.workspaceId) {
return null;
}
return buildAgentAttentionNotificationPayload({
reason: input.reason,
serverId: input.serverId,
workspaceId: input.workspaceId,
agentId: input.agentId,
assistantMessage: input.reason === "finished" ? input.assistantMessage : null,
permissionRequest: input.reason === "permission" ? input.permissionRequest : null,
});
}
export function deliverAgentAttentionOsNotification(input: {
serverId: string;
params: {
agentId: string;
reason: "finished" | "error" | "permission";
timestamp: string;
notification?: AgentAttentionNotificationPayload;
};
appState?: string;
isActivelyVisible?: boolean;
session: SessionState | undefined;
attentionNotified: Map<string, number>;
preferences: NotificationPreferences;
sendNotification: OsNotificationSender;
}): boolean {
const attentionFocusedAgentId = input.session?.focusedAgentId ?? null;
const isActivelyVisible =
input.isActivelyVisible ?? getIsAppActivelyVisible(input.appState ?? "active");
const isAwayFromAgent = !isActivelyVisible || attentionFocusedAgentId !== input.params.agentId;
if (!isAwayFromAgent) {
return false;
}
if (
!shouldDeliverNotification(input.preferences, {
kind: "agent",
reason: input.params.reason,
})
) {
return false;
}
const timestampMs = new Date(input.params.timestamp).getTime();
const lastNotified = input.attentionNotified.get(input.params.agentId);
if (lastNotified && lastNotified >= timestampMs) {
return false;
}
input.attentionNotified.set(input.params.agentId, timestampMs);
const head = input.session?.agentStreamHead.get(input.params.agentId) ?? [];
const tail = input.session?.agentStreamTail.get(input.params.agentId) ?? [];
const assistantMessage =
findLatestAssistantMessageText(head) ?? findLatestAssistantMessageText(tail);
const permissionRequest = getLatestPermissionRequest(input.session, input.params.agentId);
const workspaceId = input.session?.agents?.get(input.params.agentId)?.workspaceId;
const notification = resolveAgentAttentionNotification({
notification: input.params.notification,
reason: input.params.reason,
serverId: input.serverId,
workspaceId,
agentId: input.params.agentId,
assistantMessage,
permissionRequest,
});
if (!notification) {
return false;
}
void input.sendNotification({
title: notification.title,
body: notification.body,
data: notification.data,
});
return true;
}
export function deliverTerminalAttentionOsNotification(input: {
serverId: string;
payload: TerminalAttentionPayload;
preferences: NotificationPreferences;
sendNotification: OsNotificationSender;
}): boolean {
if (!input.payload.shouldNotify) {
return false;
}
if (
!shouldDeliverNotification(input.preferences, {
kind: "terminal",
reason: input.payload.reason,
})
) {
return false;
}
void input.sendNotification({
title: input.payload.title,
body: input.payload.body,
data: {
serverId: input.payload.serverId ?? input.serverId,
terminalId: input.payload.terminalId,
cwd: input.payload.cwd,
...(input.payload.workspaceId ? { workspaceId: input.payload.workspaceId } : {}),
},
});
return true;
}
export function deliverPluginOsNotification(input: {
serverId: string;
payload: PluginNotificationPayload;
preferences: NotificationPreferences;
sendNotification: OsNotificationSender;
}): boolean {
if (!input.payload.shouldNotify) {
return false;
}
if (
!shouldDeliverNotification(input.preferences, {
kind: "plugin",
pluginId: input.payload.pluginId,
})
) {
return false;
}
void input.sendNotification({
title: input.payload.title,
body: input.payload.body,
data: {
kind: "plugin",
serverId: input.payload.serverId ?? input.serverId,
pluginId: input.payload.pluginId,
notificationId: input.payload.notificationId,
...(input.payload.open ? { open: input.payload.open } : {}),
...(input.payload.data ? { data: input.payload.data } : {}),
},
});
return true;
}
@@ -17,7 +17,7 @@ const ThemedRotateCw = withUnistyles(RotateCw, (theme) => ({
color: theme.colors.foregroundMuted,
}));
export function DesktopNotificationsSection({ title }: { title?: string } = {}) {
export function DesktopNotificationsSection() {
const { t } = useTranslation();
const { settings, isSaving, updateSettings } = useDesktopSettings();
const {
@@ -85,10 +85,7 @@ export function DesktopNotificationsSection({ title }: { title?: string } = {})
const notificationsGranted = snapshot?.notifications.state === "granted";
return (
<SettingsSection
title={title ?? t("settings.notifications.desktop.title")}
trailing={refreshButton}
>
<SettingsSection title={t("settings.notifications.title")} trailing={refreshButton}>
<View style={settingsStyles.card}>
<DesktopPermissionRow
title={t("settings.notifications.permission")}
@@ -55,10 +55,6 @@ import {
type WorkspaceTitleSource,
} from "./storage";
export {
DEFAULT_NOTIFICATION_PREFERENCES,
type NotificationPreferences,
} from "@getpaseo/protocol/notification-preferences";
export {
APP_SETTINGS_KEY,
DEFAULT_APP_SETTINGS,
@@ -1,6 +1,5 @@
import { describe, expect, it } from "vitest";
import { QueryClient } from "@tanstack/react-query";
import { DEFAULT_NOTIFICATION_PREFERENCES } from "@getpaseo/protocol/notification-preferences";
import {
APP_SETTINGS_KEY,
APP_SETTINGS_QUERY_KEY,
@@ -1214,68 +1213,3 @@ describe("font family CSS safety", () => {
},
);
});
describe("notification preferences storage", () => {
it("defaults notifications to DEFAULT_NOTIFICATION_PREFERENCES when storage is empty", async () => {
const deps = makeDeps();
const settings = await loadAppSettingsFromStorage(deps);
expect(settings.notifications).toEqual(DEFAULT_NOTIFICATION_PREFERENCES);
});
it("persists and reloads custom notification preferences", async () => {
const deps = makeDeps();
const queryClient = new QueryClient();
const notifications = {
enabled: true,
events: {
agentPermission: true,
agentError: false,
agentFinished: true,
terminalNeedsInput: false,
terminalFinished: true,
},
plugins: {
enabled: true,
muted: ["ci-bot", "deploy-bot"],
},
};
await saveAppSettings({ queryClient, deps, updates: { notifications } });
expect((await loadAppSettingsFromStorage(deps)).notifications).toEqual(notifications);
});
it("normalizes partial and malformed notification preferences on load", async () => {
const deps = makeDeps({
storage: createInMemoryKeyValueStorage({
[APP_SETTINGS_KEY]: JSON.stringify({
vimKeybindings: true,
notifications: {
enabled: "invalid",
events: {
agentFinished: true,
agentError: "nope",
},
plugins: {
enabled: true,
muted: [" zeta ", "", 42, "alpha", "zeta"],
},
},
}),
}),
});
const settings = await loadAppSettingsFromStorage(deps);
expect(settings.vimKeybindings).toBe(true);
expect(settings.notifications).toEqual({
enabled: true,
events: {
...DEFAULT_NOTIFICATION_PREFERENCES.events,
agentFinished: true,
},
plugins: {
enabled: true,
muted: ["alpha", "zeta"],
},
});
});
});
@@ -1,10 +1,5 @@
import { isSyntaxThemeId, type SyntaxThemeId } from "@getpaseo/highlight";
import type { ActiveTurnBehavior } from "@getpaseo/protocol/messages";
import {
DEFAULT_NOTIFICATION_PREFERENCES,
normalizeNotificationPreferences,
type NotificationPreferences,
} from "@getpaseo/protocol/notification-preferences";
import type { QueryClient } from "@tanstack/react-query";
import type { DesktopSettings } from "@/desktop/settings/desktop-settings";
import type { AppLanguage } from "@/i18n/locales";
@@ -121,7 +116,6 @@ export interface AppSettings {
/** Desktop-only preferences for implicit opens into the ordinary side pane. */
openInSidePane: OpenInSidePanePreferences;
pullRequestOpenLocation: PullRequestOpenLocation;
notifications: NotificationPreferences;
}
export type AppSettingsUpdate =
@@ -179,7 +173,6 @@ export const DEFAULT_CLIENT_SETTINGS: AppSettings = {
filePanelAssociations: {},
openInSidePane: DEFAULT_OPEN_IN_SIDE_PANE_PREFERENCES,
pullRequestOpenLocation: "explorer",
notifications: DEFAULT_NOTIFICATION_PREFERENCES,
};
export const DEFAULT_APP_SETTINGS: Settings = {
@@ -309,10 +302,6 @@ const StoredAppSettingsSchema = z
legacyPullRequestsInSidePane: undefined,
}),
pullRequestOpenLocation: z.enum(["main", "side", "explorer"]).optional(),
notifications: z
.unknown()
.transform((value) => normalizeNotificationPreferences(value))
.catch(DEFAULT_NOTIFICATION_PREFERENCES),
// COMPAT(explorerSidebarRouting): replaced by source-specific side-pane preferences in v0.6.
openSupportingTabsInSidePanel: z.boolean().optional().catch(undefined),
// COMPAT(rendererDesktopSettings): these fields used to share this renderer-owned key.
-41
View File
@@ -2476,47 +2476,6 @@ export const ar: TranslationResources = {
},
notifications: {
title: "الإشعارات",
enabled: {
label: "تفعيل الإشعارات",
description: "تلقّي الإشعارات من الوكلاء والطرفيات والإضافات على هذا الجهاز",
pausedDescription: "جميع الإشعارات، بما في ذلك الإضافات، متوقفة مؤقتًا على هذا الجهاز",
},
events: {
title: "الأحداث",
agentPermission: {
label: "الوكيل يحتاج إلى إذن",
description: "الموافقات والخطط والأسئلة",
},
agentError: {
label: "تعطّل الوكيل بخطأ",
description: "عندما يتوقف الوكيل بسبب خطأ",
},
agentFinished: {
label: "انتهى الوكيل",
description: "عندما يكمل الوكيل دورة عمل",
},
terminalNeedsInput: {
label: "الطرفية تنتظر إدخالًا",
description: "عندما ينتظر أمر الطرفية إدخالًا",
},
terminalFinished: {
label: "انتهى أمر الطرفية",
description: "عندما ينتهي أمر في الطرفية",
},
},
plugins: {
title: "الإضافات",
enabled: {
label: "إشعارات الإضافات",
description: "السماح للإضافات المثبتة بإرسال إشعارات",
},
empty: "تظهر الإضافات المثبتة هنا لكتمها بشكل فردي",
},
legacyHostTitle: "حدّث المضيف لتفضيلات الإشعارات الفورية",
legacyHostHint: "حدّث المضيفين المتصلين لمزامنة تفضيلات الإشعارات المخصصة من هذا الجهاز",
desktop: {
title: "النظام",
},
permission: "إذن الإشعارات",
refreshAccessibility: "تحديث إذن الإشعارات",
playSound: "تشغيل صوت",
-42
View File
@@ -2508,48 +2508,6 @@ export const en = {
},
notifications: {
title: "Notifications",
enabled: {
label: "Enable notifications",
description: "Receive notifications from agents, terminals, and plugins on this device",
pausedDescription: "All notifications, including plugins, are paused on this device",
},
events: {
title: "Events",
agentPermission: {
label: "Agent needs permission",
description: "Approvals, plans, and questions",
},
agentError: {
label: "Agent errored",
description: "When an agent stops with an error",
},
agentFinished: {
label: "Agent finished",
description: "When an agent completes a turn",
},
terminalNeedsInput: {
label: "Terminal needs input",
description: "When a terminal command is waiting for input",
},
terminalFinished: {
label: "Terminal finished",
description: "When a terminal command finishes",
},
},
plugins: {
title: "Plugins",
enabled: {
label: "Plugin notifications",
description: "Allow installed plugins to send notifications",
},
empty: "Installed plugins appear here so you can mute them individually",
},
legacyHostTitle: "Update host for push preferences",
legacyHostHint:
"Update connected hosts to sync custom push notification preferences from this device",
desktop: {
title: "System",
},
permission: "Notification permission",
refreshAccessibility: "Refresh notification permission",
playSound: "Play sound",
-43
View File
@@ -2496,49 +2496,6 @@ export const es: TranslationResources = {
},
notifications: {
title: "Notificaciones",
enabled: {
label: "Activar notificaciones",
description: "Recibe notificaciones de agentes, terminales y plugins en este dispositivo",
pausedDescription:
"Todas las notificaciones, incluidas las de plugins, están en pausa en este dispositivo",
},
events: {
title: "Eventos",
agentPermission: {
label: "El agente necesita permiso",
description: "Aprobaciones, planes y preguntas",
},
agentError: {
label: "Error del agente",
description: "Cuando un agente se detiene con un error",
},
agentFinished: {
label: "El agente terminó",
description: "Cuando un agente completa un turno",
},
terminalNeedsInput: {
label: "La terminal necesita entrada",
description: "Cuando un comando de terminal espera entrada",
},
terminalFinished: {
label: "La terminal terminó",
description: "Cuando finaliza un comando de terminal",
},
},
plugins: {
title: "Plugins",
enabled: {
label: "Notificaciones de plugins",
description: "Permitir que los plugins instalados envíen notificaciones",
},
empty: "Los plugins instalados aparecen aquí para que puedas silenciarlos individualmente",
},
legacyHostTitle: "Actualiza el host para preferencias push",
legacyHostHint:
"Actualiza los hosts conectados para sincronizar preferencias de notificaciones push desde este dispositivo",
desktop: {
title: "Sistema",
},
permission: "Permiso de notificaciones",
refreshAccessibility: "Actualizar permiso de notificaciones",
playSound: "Reproducir sonido",
-44
View File
@@ -2495,50 +2495,6 @@ export const fr: TranslationResources = {
},
notifications: {
title: "Notifications",
enabled: {
label: "Activer les notifications",
description: "Recevoir les notifications des agents, terminaux et plugins sur cet appareil",
pausedDescription:
"Toutes les notifications, y compris celles des plugins, sont suspendues sur cet appareil",
},
events: {
title: "Événements",
agentPermission: {
label: "L’agent demande une autorisation",
description: "Approbations, plans et questions",
},
agentError: {
label: "Erreur de l’agent",
description: "Quand un agent s’arrête avec une erreur",
},
agentFinished: {
label: "L’agent a terminé",
description: "Quand un agent termine un tour",
},
terminalNeedsInput: {
label: "Le terminal attend une saisie",
description: "Quand une commande de terminal attend une saisie",
},
terminalFinished: {
label: "Le terminal a terminé",
description: "Quand une commande de terminal se termine",
},
},
plugins: {
title: "Plugins",
enabled: {
label: "Notifications des plugins",
description: "Autoriser les plugins installés à envoyer des notifications",
},
empty:
"Les plugins installés apparaissent ici pour les mettre en sourdine individuellement",
},
legacyHostTitle: "Mettez à jour l’hôte pour les préférences push",
legacyHostHint:
"Mettez à jour les hôtes connectés pour synchroniser les préférences de notifications push de cet appareil",
desktop: {
title: "Système",
},
permission: "Autorisation des notifications",
refreshAccessibility: "Actualiser l’autorisation des notifications",
playSound: "Émettre un son",
-42
View File
@@ -2465,48 +2465,6 @@ export const ja: TranslationResources = {
},
notifications: {
title: "通知",
enabled: {
label: "通知を有効にする",
description: "このデバイスでエージェント、ターミナル、プラグインからの通知を受け取ります",
pausedDescription: "プラグインを含むすべての通知がこのデバイスで一時停止されています",
},
events: {
title: "イベント",
agentPermission: {
label: "エージェントが権限を要求",
description: "承認、プラン、質問",
},
agentError: {
label: "エージェントのエラー",
description: "エージェントがエラーで停止したとき",
},
agentFinished: {
label: "エージェントが完了",
description: "エージェントがターンを完了したとき",
},
terminalNeedsInput: {
label: "ターミナルが入力を待機",
description: "ターミナルコマンドが入力を待っているとき",
},
terminalFinished: {
label: "ターミナルが完了",
description: "ターミナルコマンドが完了したとき",
},
},
plugins: {
title: "プラグイン",
enabled: {
label: "プラグイン通知",
description: "インストール済みプラグインによる通知の送信を許可します",
},
empty: "インストールされたプラグインがここに表示され、個別にミュートできます",
},
legacyHostTitle: "プッシュ通知設定にはホストの更新が必要です",
legacyHostHint:
"このデバイスのカスタムプッシュ通知設定を同期するには、接続中のホストを更新してください",
desktop: {
title: "システム",
},
permission: "通知の権限",
refreshAccessibility: "通知の権限を更新",
playSound: "サウンドを再生",
-41
View File
@@ -2452,47 +2452,6 @@ export const ko: TranslationResources = {
},
notifications: {
title: "알림",
enabled: {
label: "알림 사용",
description: "이 기기에서 에이전트, 터미널, 플러그인 알림을 받습니다",
pausedDescription: "플러그인을 포함한 모든 알림이 이 기기에서 일시 중지되었습니다",
},
events: {
title: "이벤트",
agentPermission: {
label: "에이전트 권한 필요",
description: "승인, 계획 및 질문",
},
agentError: {
label: "에이전트 오류",
description: "에이전트가 오류로 중단될 때",
},
agentFinished: {
label: "에이전트 완료",
description: "에이전트가 턴을 완료할 때",
},
terminalNeedsInput: {
label: "터미널 입력 대기",
description: "터미널 명령이 입력을 기다릴 때",
},
terminalFinished: {
label: "터미널 완료",
description: "터미널 명령이 완료될 때",
},
},
plugins: {
title: "플러그인",
enabled: {
label: "플러그인 알림",
description: "설치된 플러그인이 알림을 보낼 수 있도록 허용",
},
empty: "설치된 플러그인이 여기에 표시되어 개별적으로 음소거할 수 있습니다",
},
legacyHostTitle: "푸시 설정을 위해 호스트 업데이트 필요",
legacyHostHint: "이 기기의 맞춤 푸시 알림 설정을 동기화하려면 연결된 호스트를 업데이트하세요",
desktop: {
title: "시스템",
},
permission: "알림 권한",
refreshAccessibility: "알림 권한 새로 고침",
playSound: "소리 재생",
-44
View File
@@ -2480,50 +2480,6 @@ export const ptBR: TranslationResources = {
},
notifications: {
title: "Notificações",
enabled: {
label: "Ativar notificações",
description: "Receba notificações de agentes, terminais e plugins neste dispositivo",
pausedDescription:
"Todas as notificações, incluindo as de plugins, estão pausadas neste dispositivo",
},
events: {
title: "Eventos",
agentPermission: {
label: "Agente precisa de permissão",
description: "Aprovações, planos e perguntas",
},
agentError: {
label: "Erro no agente",
description: "Quando um agente para com erro",
},
agentFinished: {
label: "Agente concluiu",
description: "Quando um agente conclui um turno",
},
terminalNeedsInput: {
label: "Terminal aguarda entrada",
description: "Quando um comando do terminal aguarda entrada",
},
terminalFinished: {
label: "Terminal concluiu",
description: "Quando um comando do terminal termina",
},
},
plugins: {
title: "Plugins",
enabled: {
label: "Notificações de plugins",
description: "Permitir que plugins instalados enviem notificações",
},
empty:
"Os plugins instalados aparecem aqui para que você possa silenciá-los individualmente",
},
legacyHostTitle: "Atualize o host para preferências de push",
legacyHostHint:
"Atualize os hosts conectados para sincronizar as preferências de notificações push deste dispositivo",
desktop: {
title: "Sistema",
},
permission: "Permissão de notificações",
refreshAccessibility: "Atualizar permissão de notificações",
playSound: "Reproduzir som",
-43
View File
@@ -2481,49 +2481,6 @@ export const ru: TranslationResources = {
},
notifications: {
title: "Уведомления",
enabled: {
label: "Включить уведомления",
description: "Получать уведомления от агентов, терминалов и плагинов на этом устройстве",
pausedDescription:
"Все уведомления, включая уведомления от плагинов, приостановлены на этом устройстве",
},
events: {
title: "События",
agentPermission: {
label: "Агенту требуется разрешение",
description: "Подтверждения, планы и вопросы",
},
agentError: {
label: "Ошибка агента",
description: "Когда агент останавливается из-за ошибки",
},
agentFinished: {
label: "Агент завершил работу",
description: "Когда агент завершает ход",
},
terminalNeedsInput: {
label: "Терминал ожидает ввода",
description: "Когда команда в терминале ждёт ввода",
},
terminalFinished: {
label: "Терминал завершил команду",
description: "Когда команда в терминале завершается",
},
},
plugins: {
title: "Плагины",
enabled: {
label: "Уведомления плагинов",
description: "Разрешить установленным плагинам отправлять уведомления",
},
empty: "Установленные плагины появятся здесь, чтобы вы могли отключать их по отдельности",
},
legacyHostTitle: "Обновите хост для настроек push-уведомлений",
legacyHostHint:
"Обновите подключённые хосты для синхронизации настроек push-уведомлений с этого устройства",
desktop: {
title: "Система",
},
permission: "Разрешение на уведомления",
refreshAccessibility: "Обновить разрешение на уведомления",
playSound: "Воспроизводить звук",
-41
View File
@@ -2416,47 +2416,6 @@ export const zhCN: TranslationResources = {
},
notifications: {
title: "通知",
enabled: {
label: "启用通知",
description: "在此设备上接收来自智能体、终端和插件的通知",
pausedDescription: "此设备上的所有通知(包括插件通知)均已暂停",
},
events: {
title: "事件",
agentPermission: {
label: "智能体需要权限",
description: "审批、计划与提问",
},
agentError: {
label: "智能体出错",
description: "当智能体因错误停止时",
},
agentFinished: {
label: "智能体已完成",
description: "当智能体完成一轮回复时",
},
terminalNeedsInput: {
label: "终端等待输入",
description: "当终端命令正在等待输入时",
},
terminalFinished: {
label: "终端命令完成",
description: "当终端命令执行结束时",
},
},
plugins: {
title: "插件",
enabled: {
label: "插件通知",
description: "允许已安装的插件发送通知",
},
empty: "已安装的插件会显示在这里,方便你单独静音",
},
legacyHostTitle: "更新主机以同步推送偏好",
legacyHostHint: "更新已连接的主机,以同步此设备上的自定义推送通知偏好设置",
desktop: {
title: "系统",
},
permission: "通知权限",
refreshAccessibility: "刷新通知权限",
playSound: "播放声音",
@@ -52,26 +52,6 @@ describe("notification open", () => {
{ serverId: "h", workspaceId: "w", terminalId: "t", agentId: "a" },
{ kind: "terminal", serverId: "h", workspaceId: "w", terminalId: "t" },
],
[{ kind: "plugin", serverId: "h", pluginId: "p" }, null],
[{ kind: "plugin", serverId: "h", notificationId: "n" }, null],
[
{
kind: "plugin",
serverId: "h",
pluginId: "ci",
notificationId: "n-1",
open: { type: "screen", screenId: "report", params: { id: "42" } },
data: { buildId: 42 },
},
{
kind: "plugin",
serverId: "h",
pluginId: "ci",
notificationId: "n-1",
open: { type: "screen", screenId: "report", params: { id: "42" } },
data: { buildId: 42 },
},
],
])("parses %j", (data, expected) => {
expect(parseNotificationOpenTarget(data)).toEqual(expected);
});
+1 -69
View File
@@ -1,5 +1,3 @@
import type { JsonValue } from "@getpaseo/protocol/agent-types";
import type { PluginNotificationOpenTarget } from "@getpaseo/protocol/messages";
import { buildHostRootRoute } from "@/utils/host-routes";
import type { NotificationOpenSource, NotificationTap } from "./source";
@@ -8,14 +6,6 @@ export const WEB_NOTIFICATION_CLICK_EVENT = "paseo:web-notification-click";
export type NotificationOpenTarget =
| { kind: "agent"; serverId: string; agentId: string }
| { kind: "terminal"; serverId: string; workspaceId: string; terminalId: string }
| {
kind: "plugin";
serverId: string;
pluginId: string;
notificationId: string;
open?: PluginNotificationOpenTarget;
data?: Record<string, JsonValue>;
}
| { kind: "host"; serverId: string };
function readId(data: object, key: string): string {
@@ -23,59 +13,10 @@ function readId(data: object, key: string): string {
return typeof value === "string" ? value.trim() : "";
}
function isPlainRecord(value: unknown): value is Record<string, unknown> {
return typeof value === "object" && value !== null && !Array.isArray(value);
}
function parsePluginOpenTarget(raw: unknown): PluginNotificationOpenTarget | undefined {
if (!isPlainRecord(raw)) return undefined;
const type = readId(raw, "type");
if (type === "agent") {
const agentId = readId(raw, "agentId");
return agentId ? { type: "agent", agentId } : undefined;
}
if (type === "workspace") {
const workspaceId = readId(raw, "workspaceId");
return workspaceId ? { type: "workspace", workspaceId } : undefined;
}
if (type === "screen") {
const screenId = readId(raw, "screenId");
if (!screenId) return undefined;
const rawParams = Reflect.get(raw, "params");
if (rawParams === undefined) {
return { type: "screen", screenId };
}
if (!isPlainRecord(rawParams)) return undefined;
const params: Record<string, string> = {};
for (const [key, value] of Object.entries(rawParams)) {
if (!key.trim() || typeof value !== "string") return undefined;
params[key] = value;
}
return { type: "screen", screenId, params };
}
return undefined;
}
export function parseNotificationOpenTarget(data: unknown): NotificationOpenTarget | null {
if (!isPlainRecord(data)) return null;
if (typeof data !== "object" || data === null || Array.isArray(data)) return null;
const serverId = readId(data, "serverId");
if (!serverId) return null;
if (readId(data, "kind") === "plugin") {
const pluginId = readId(data, "pluginId");
const notificationId = readId(data, "notificationId");
if (!pluginId || !notificationId) return null;
const open = parsePluginOpenTarget(Reflect.get(data, "open"));
const rawData = Reflect.get(data, "data");
const payloadData = isPlainRecord(rawData) ? (rawData as Record<string, JsonValue>) : undefined;
return {
kind: "plugin",
serverId,
pluginId,
notificationId,
...(open ? { open } : {}),
...(payloadData ? { data: payloadData } : {}),
};
}
const workspaceId = readId(data, "workspaceId");
const terminalId = readId(data, "terminalId");
if (workspaceId && terminalId) return { kind: "terminal", serverId, workspaceId, terminalId };
@@ -89,9 +30,6 @@ interface NotificationOpenRouterDeps {
openAgent: (target: { serverId: string; agentId: string }) => void;
openRoute: (route: string) => void;
openTerminal: (target: Extract<NotificationOpenTarget, { kind: "terminal" }>) => void;
openPlugin?: (
target: Extract<NotificationOpenTarget, { kind: "plugin" }>,
) => void | Promise<void>;
whenReadyToNavigate: () => Promise<void>;
}
@@ -107,12 +45,6 @@ export function createNotificationOpenRouter(deps: NotificationOpenRouterDeps) {
deps.openAgent({ serverId: target.serverId, agentId: target.agentId });
} else if (target?.kind === "terminal") {
deps.openTerminal(target);
} else if (target?.kind === "plugin") {
if (deps.openPlugin) {
await deps.openPlugin(target);
} else {
deps.openRoute(buildHostRootRoute(target.serverId));
}
} else if (target?.kind === "host") {
deps.openRoute(buildHostRootRoute(target.serverId));
}
@@ -1,31 +1,16 @@
import { useEffect } from "react";
import { router, usePathname, useRootNavigationState, type Href } from "expo-router";
import { openPluginNotification } from "@/plugins/notification-open";
import { pluginRegistry } from "@/plugins/registry";
import { getHostRuntimeStore, useHostRegistryStatus } from "@/runtime/host-runtime";
import { useHostRegistryStatus } from "@/runtime/host-runtime";
import {
navigateToWorkspace,
useIsLastWorkspaceSelectionHydrated,
} from "@/stores/navigation-active-workspace-store";
import { useSidebarViewStore } from "@/stores/sidebar-view-store";
import { navigateToAgent } from "@/utils/navigate-to-agent";
import { createNotificationOpenRouter } from "../model";
import { createNotificationOpenSource } from "../source";
let ready = false;
const waiters = new Set<() => void>();
function navigateFromNotification(route: string): void {
if (!route.startsWith("/settings")) {
if (router.canDismiss()) {
router.dismissAll();
}
router.replace(route as Href);
return;
}
router.navigate(route as Href);
}
const notificationRouter = createNotificationOpenRouter({
source: createNotificationOpenSource(),
openAgent: (target) => navigateToAgent({ ...target, pin: true }),
@@ -35,18 +20,6 @@ const notificationRouter = createNotificationOpenRouter({
workspaceId,
target: { kind: "terminal", terminalId },
}),
openPlugin: (target) =>
openPluginNotification(target, {
registry: pluginRegistry,
openAgent: (agentTarget) => navigateToAgent({ ...agentTarget, pin: true }),
openWorkspace: (workspaceTarget) => navigateToWorkspace(workspaceTarget),
openRoute: navigateFromNotification,
isHostRegistered: (targetServerId) =>
getHostRuntimeStore()
.getHosts()
.some((host) => host.serverId === targetServerId),
focusHost: (targetServerId) => useSidebarViewStore.getState().focusHost(targetServerId),
}),
openRoute: (route) => router.navigate(route as Href),
whenReadyToNavigate: () =>
ready
@@ -37,7 +37,6 @@ function installation(): InstalledPlugin {
themes: [],
timelineTransformers: [],
timelineRenderers: [],
notificationOpenHandlers: [],
};
}
@@ -7,7 +7,6 @@ import type { SessionOutboundMessage } from "@getpaseo/protocol/messages";
import { settingsRpc } from "@getpaseo/plugin";
import { syncPluginCatalog } from "./catalog-sync-model";
import { createPluginHosts } from "./hosts";
import { openPluginNotification } from "./notification-open";
import { PluginRegistry } from "./registry";
import { pluginSettingsKey } from "./settings/query";
import type { InstalledPlugin } from "./types";
@@ -392,22 +391,13 @@ it("replaces changed bundles on reconnect and disposes the old installation", as
});
it("replaces an explicitly reloaded bundle even when its source is unchanged", async () => {
let catalogChanges = 0;
const h = harness();
const stop = h.sync({
onCatalogChanged: () => {
catalogChanges++;
},
});
cleanups.push(stop);
await expect.poll(() => h.registry.getSnapshot().length).toBe(1);
const h = await connected();
const plugin = h.installed();
h.client.update({
type: "status",
payload: { status: "plugin_catalog_changed", pluginId: "reports" },
});
await expect.poll(() => h.installed() === plugin).toBe(false);
expect(catalogChanges).toBe(1);
expect(h.disposals()).toBe(1);
expect(h.evaluations()).toBe(2);
});
@@ -514,55 +504,3 @@ it("ignores an in-flight catalog snapshot after disconnect", async () => {
expect(h.client.settings.reads).toBe(1);
expect(h.evaluations()).toBe(1);
});
it("keeps catalog loading before server_info arrives so cold-launch plugin taps wait for onNotificationOpen", async () => {
const h = harness();
h.client.catalog = [
{
id: "ci-alerts",
requirements: { paseo: `>=${appPackage.version}` },
clientBundle: `(function() { return { default: function(plugin) {
plugin.addScreen({ id: "alert", title: "Alert", Component: function() { return null; } });
plugin.onNotificationOpen(function(ctx) {
ctx.openScreen({ screenId: "alert", params: { buildId: String(ctx.event.data && ctx.event.data.buildId || "") } });
});
return function() {};
} }; })`,
},
];
// Before server_info arrives: supported is null (unknown) and connected is false.
const stopUnknown = h.sync({ connected: false, supported: null });
expect(h.registry.getCatalogStatus("host")).toBe("loading");
const openedRoutes: string[] = [];
const pendingTap = openPluginNotification(
{
kind: "plugin",
serverId: "host",
pluginId: "ci-alerts",
notificationId: "notif-cold",
open: { type: "screen", screenId: "fallback" },
data: { buildId: 77 },
},
{
registry: h.registry,
timeoutMs: 1_000,
openAgent: () => undefined,
openWorkspace: () => undefined,
openRoute: (route) => openedRoutes.push(route),
},
);
// Tap stays pending while server_info has not arrived (does not jump to fallback).
await Promise.resolve();
expect(openedRoutes).toEqual([]);
// Host connects and advertises plugin support -> catalog loads and invokes onNotificationOpen.
stopUnknown();
h.sync({ connected: true, supported: true });
await pendingTap;
expect(h.registry.getCatalogStatus("host")).toBe("ready");
expect(openedRoutes).toEqual(["/h/host/plugin/ci-alerts/surface/alert?param.buildId=77"]);
});
+1 -10
View File
@@ -8,13 +8,11 @@ interface CatalogSyncInput {
client: DaemonClient;
audio: Pick<AudioEngine, "play"> | null;
connected: boolean;
/** `null` while `server_info` has not yet arrived for this host. */
supported: boolean | null;
supported: boolean;
registry: Pick<
PluginRegistry,
"installCatalog" | "getSnapshot" | "removeHost" | "setCatalogStatus"
>;
onCatalogChanged?: () => void;
}
export function syncPluginCatalog({
@@ -24,13 +22,7 @@ export function syncPluginCatalog({
connected,
supported,
registry,
onCatalogChanged,
}: CatalogSyncInput): () => void {
if (supported === null) {
// Plugin support is unknown until `server_info` arrives; keep status "loading" so cold-launch
// plugin notification taps wait instead of falling back prematurely.
return () => {};
}
if (!supported || !audio) {
registry.removeHost(serverId);
registry.setCatalogStatus(serverId, "ready");
@@ -96,7 +88,6 @@ export function syncPluginCatalog({
}
}
if (message.payload.status === "plugin_catalog_changed") {
onCatalogChanged?.();
const pluginId = message.payload.pluginId;
if (typeof pluginId === "string") void refresh(pluginId);
}
+3 -9
View File
@@ -1,10 +1,8 @@
import { useVoiceAudioEngineOptional } from "@/contexts/voice-context";
import { useEffect } from "react";
import { useQueryClient } from "@tanstack/react-query";
import type { DaemonClient } from "@getpaseo/client/internal/daemon-client";
import { useHostFeatureAvailability } from "@/runtime/host-features";
import { useHostFeature } from "@/runtime/host-features";
import { useHostRuntimeIsConnected } from "@/runtime/host-runtime";
import { pluginListQueryKey } from "./plugin-list";
import { pluginRegistry } from "./registry";
import { syncPluginCatalog } from "./catalog-sync-model";
@@ -17,8 +15,7 @@ export function PluginCatalogSync({
}) {
const audio = useVoiceAudioEngineOptional();
const connected = useHostRuntimeIsConnected(serverId);
const supported = useHostFeatureAvailability(serverId, "plugins");
const queryClient = useQueryClient();
const supported = useHostFeature(serverId, "plugins");
useEffect(
() =>
@@ -29,11 +26,8 @@ export function PluginCatalogSync({
connected,
supported,
registry: pluginRegistry,
onCatalogChanged: () => {
void queryClient.invalidateQueries({ queryKey: pluginListQueryKey(serverId) });
},
}),
[audio, client, connected, queryClient, serverId, supported],
[audio, client, connected, serverId, supported],
);
useEffect(() => () => pluginRegistry.removeHost(serverId), [serverId]);
@@ -148,7 +148,6 @@ function plugin(onAgentSelect: AgentCommandItem["onSelect"]): InstalledPlugin {
themes: [],
timelineTransformers: [],
timelineRenderers: [],
notificationOpenHandlers: [],
};
}
@@ -58,7 +58,6 @@ function installed(): InstalledPlugin {
themes: [],
timelineTransformers: [],
timelineRenderers: [],
notificationOpenHandlers: [],
};
}
@@ -68,7 +68,6 @@ function plugin(): InstalledPlugin {
themes: [],
timelineTransformers: [],
timelineRenderers: [],
notificationOpenHandlers: [],
};
}
@@ -110,7 +110,6 @@ describe("evaluatePluginClientBundle", () => {
plugin.addTheme({ id: "night", name: "Night", appearance: "dark", colors: { background: "#000", foreground: "#fff", raised: "#111", control: "#222", border: "#333", mutedForeground: "#aaa", ring: "#555" } }),
plugin.addTimelineTransformer({ id: "transformer", query: { itemType: "tool_call" }, transform() { return { items: [] }; } }),
plugin.addTimelineRenderer({ kind: "card", version: 1, schema, Component }),
plugin.onNotificationOpen(function handleOpen() {}),
];
`),
{
@@ -142,7 +141,6 @@ describe("evaluatePluginClientBundle", () => {
plugin.themes,
plugin.timelineTransformers,
plugin.timelineRenderers,
plugin.notificationOpenHandlers,
].every((items) => items.length === 1),
).toBe(true);
expect(pillCount).toBe(1);
@@ -164,7 +162,6 @@ describe("evaluatePluginClientBundle", () => {
plugin.themes,
plugin.timelineTransformers,
plugin.timelineRenderers,
plugin.notificationOpenHandlers,
].every((items) => items.length === 0),
).toBe(true);
expect(pillCount).toBe(0);
-9
View File
@@ -24,7 +24,6 @@ import {
type PluginSurfaceProps,
type PluginTimelineRendererContribution,
type PluginTimelineTransformerContribution,
type PluginNotificationOpenHandler,
type PluginButtonRegistration,
} from "@getpaseo/plugin/client";
import type {
@@ -146,7 +145,6 @@ export function runPluginClientBundle(
themes: [],
timelineTransformers: [],
timelineRenderers: [],
notificationOpenHandlers: [],
};
const surfaceIds = new Set<string>();
const sidebarViewIds = new Set<string>();
@@ -567,12 +565,6 @@ export function runPluginClientBundle(
timelineRendererIds.delete(rendererId),
);
},
onNotificationOpen(handler: PluginNotificationOpenHandler) {
if (typeof handler !== "function") {
throw new Error("onNotificationOpen takes a callback function");
}
return register(collector.notificationOpenHandlers, handler, () => {});
},
addComposerPill(contribution) {
if (stopped) throw new Error("Plugin has stopped");
return trackButton(runtime.addComposerPill(contribution));
@@ -673,6 +665,5 @@ export function runPluginClientBundle(
themes: collector.themes,
timelineTransformers: collector.timelineTransformers,
timelineRenderers: collector.timelineRenderers,
notificationOpenHandlers: collector.notificationOpenHandlers,
};
}
@@ -61,7 +61,6 @@ function installation(invoked: string[]): InstalledPlugin {
themes: [],
timelineTransformers: [],
timelineRenderers: [],
notificationOpenHandlers: [],
};
}
@@ -1,344 +0,0 @@
import { QueryClient } from "@tanstack/react-query";
import { PluginTranslationRuntime } from "@getpaseo/plugin/client/host";
import { createPaseoApi } from "@getpaseo/client";
import { DaemonClient } from "@getpaseo/client/internal/daemon-client";
import type { PluginNotificationOpenHandler } from "@getpaseo/plugin/client";
import { describe, expect, it } from "vitest";
import {
openPluginNotification,
type PluginNotificationOpenRegistry,
type PluginNotificationTarget,
} from "./notification-open";
import type { PluginCatalogStatus } from "./registry";
import type { InstalledPlugin } from "./types";
class FakePluginRegistry implements PluginNotificationOpenRegistry {
private plugins: InstalledPlugin[] = [];
private statuses = new Map<string, PluginCatalogStatus>();
private listeners = new Set<() => void>();
getSnapshot(): readonly InstalledPlugin[] {
return this.plugins;
}
getCatalogStatus(serverId: string): PluginCatalogStatus {
return this.statuses.get(serverId) ?? "loading";
}
setCatalogStatus(serverId: string, status: PluginCatalogStatus): void {
this.statuses.set(serverId, status);
this.notify();
}
install(plugin: InstalledPlugin): void {
this.plugins = [
...this.plugins.filter((p) => !(p.serverId === plugin.serverId && p.id === plugin.id)),
plugin,
];
this.notify();
}
subscribe(listener: () => void): () => void {
this.listeners.add(listener);
return () => this.listeners.delete(listener);
}
private notify(): void {
for (const listener of this.listeners) listener();
}
}
function makeInstalledPlugin(input: {
serverId: string;
pluginId: string;
screens?: string[];
handlers?: PluginNotificationOpenHandler[];
}): InstalledPlugin {
return {
id: input.pluginId,
serverId: input.serverId,
lifetime: new AbortController(),
locale: "en",
i18n: new PluginTranslationRuntime({
getLocale: () => "en",
subscribe: () => () => {},
}),
paseo: createPaseoApi(
new DaemonClient({
url: "ws://127.0.0.1:1",
clientId: `plugin-notification-test-${input.pluginId}`,
clientType: "cli",
}),
),
invoke: async () => undefined,
subscribe: () => {
throw new Error("not used");
},
clientBundle: "",
queryClient: new QueryClient(),
cleanup: () => {},
surfaces: (input.screens ?? ["main"]).map((id) => ({
id,
title: id,
Component: () => null,
})),
settingsScreens: [],
sidebarViews: [],
sidebarItems: { header: [], footer: [] },
legacySidebarItems: [],
workspaceRowBadgeItems: [],
filePanels: [],
composerItems: [],
newWorkspaceItems: [],
workspacePanels: [],
commandCenterItems: [],
clientSlashCommands: [],
attachmentSources: [],
themes: [],
timelineTransformers: [],
timelineRenderers: [],
notificationOpenHandlers: input.handlers ?? [],
};
}
function createHarness(registry = new FakePluginRegistry()) {
const agents: Array<{ serverId: string; agentId: string }> = [];
const workspaces: Array<{ serverId: string; workspaceId: string }> = [];
const routes: string[] = [];
const focusedHosts: string[] = [];
const errors: Array<{ error: unknown; serverId: string; pluginId: string }> = [];
return {
registry,
agents,
workspaces,
routes,
focusedHosts,
errors,
dispatch: (target: PluginNotificationTarget, timeoutMs = 100) =>
openPluginNotification(target, {
registry,
timeoutMs,
openAgent: (item) => {
agents.push(item);
return `/h/${item.serverId}/agent/${item.agentId}`;
},
openWorkspace: (item) => {
workspaces.push(item);
return `/h/${item.serverId}/workspace/${item.workspaceId}`;
},
openRoute: (route) => {
routes.push(route);
},
focusHost: (serverId) => {
focusedHosts.push(serverId);
},
onError: (error, context) => {
errors.push({ error, ...context });
},
}),
};
}
describe("openPluginNotification", () => {
it("invokes onNotificationOpen immediately on warm tap when plugin is already installed", async () => {
const harness = createHarness();
const receivedEvents: unknown[] = [];
harness.registry.setCatalogStatus("srv-1", "ready");
harness.registry.install(
makeInstalledPlugin({
serverId: "srv-1",
pluginId: "ci-alerts",
screens: ["report"],
handlers: [
({ event, openScreen, navigation }) => {
receivedEvents.push(event);
if (typeof event.data?.agentId === "string") {
navigation.openAgent({ agentId: event.data.agentId, focusHost: true });
} else {
openScreen({
screenId: "report",
params: { buildId: String(event.data?.buildId ?? "") },
});
}
},
],
}),
);
await harness.dispatch({
kind: "plugin",
serverId: "srv-1",
pluginId: "ci-alerts",
notificationId: "notif-42",
open: { type: "workspace", workspaceId: "ws-ignored-because-handler-ran" },
data: { buildId: 42 },
});
expect(receivedEvents).toEqual([
{
type: "opened",
notificationId: "notif-42",
data: { buildId: 42 },
},
]);
expect(harness.routes).toEqual(["/h/srv-1/plugin/ci-alerts/surface/report?param.buildId=42"]);
expect(harness.workspaces).toEqual([]);
});
it("waits for plugin catalog readiness on cold launch before invoking onNotificationOpen", async () => {
const harness = createHarness();
// Catalog is still "loading" on cold launch
expect(harness.registry.getCatalogStatus("srv-1")).toBe("loading");
const pending = harness.dispatch(
{
kind: "plugin",
serverId: "srv-1",
pluginId: "ci-alerts",
notificationId: "notif-cold",
data: { agentId: "agent-99" },
},
1_000,
);
// Nothing dispatched while catalog is still loading
await Promise.resolve();
expect(harness.agents).toEqual([]);
// Catalog finishes loading and installs the plugin
harness.registry.install(
makeInstalledPlugin({
serverId: "srv-1",
pluginId: "ci-alerts",
handlers: [
({ event, navigation }) => {
if (typeof event.data?.agentId === "string") {
navigation.openAgent({ agentId: event.data.agentId, focusHost: true });
}
},
],
}),
);
harness.registry.setCatalogStatus("srv-1", "ready");
await pending;
expect(harness.agents).toEqual([{ serverId: "srv-1", agentId: "agent-99" }]);
expect(harness.focusedHosts).toEqual(["srv-1"]);
});
it("falls back to declarative open targets (agent, workspace, screen, host root) when no handler is registered or catalog times out", async () => {
const harness = createHarness();
harness.registry.setCatalogStatus("srv-1", "ready");
harness.registry.install(
makeInstalledPlugin({
serverId: "srv-1",
pluginId: "declarative-plugin",
screens: ["details"],
handlers: [],
}),
);
await harness.dispatch({
kind: "plugin",
serverId: "srv-1",
pluginId: "declarative-plugin",
notificationId: "n-agent",
open: { type: "agent", agentId: "agent-1" },
});
expect(harness.agents).toEqual([{ serverId: "srv-1", agentId: "agent-1" }]);
await harness.dispatch({
kind: "plugin",
serverId: "srv-1",
pluginId: "declarative-plugin",
notificationId: "n-workspace",
open: { type: "workspace", workspaceId: "ws-1" },
});
expect(harness.workspaces).toEqual([{ serverId: "srv-1", workspaceId: "ws-1" }]);
await harness.dispatch({
kind: "plugin",
serverId: "srv-1",
pluginId: "declarative-plugin",
notificationId: "n-screen",
open: { type: "screen", screenId: "details", params: { tab: "logs" } },
});
expect(harness.routes).toEqual([
"/h/srv-1/plugin/declarative-plugin/surface/details?param.tab=logs",
]);
// Timeout waiting for an offline host catalog falls back to declarative open or host root
await harness.dispatch(
{
kind: "plugin",
serverId: "srv-loading",
pluginId: "missing-plugin",
notificationId: "n-host",
},
10,
);
expect(harness.routes).toEqual([
"/h/srv-1/plugin/declarative-plugin/surface/details?param.tab=logs",
"/h/srv-loading",
]);
});
it("catches and reports errors thrown by onNotificationOpen handlers without crashing", async () => {
const harness = createHarness();
harness.registry.setCatalogStatus("srv-1", "ready");
harness.registry.install(
makeInstalledPlugin({
serverId: "srv-1",
pluginId: "buggy-plugin",
screens: ["main"],
handlers: [
() => {
throw new Error("boom in first handler");
},
({ openScreen }) => {
openScreen({ screenId: "main" });
},
],
}),
);
await harness.dispatch({
kind: "plugin",
serverId: "srv-1",
pluginId: "buggy-plugin",
notificationId: "n-err",
});
expect(harness.errors).toHaveLength(1);
expect(harness.routes).toEqual(["/h/srv-1/plugin/buggy-plugin/surface/main"]);
});
it("falls back to declarative open when every registered onNotificationOpen handler throws", async () => {
const harness = createHarness();
harness.registry.setCatalogStatus("srv-1", "ready");
harness.registry.install(
makeInstalledPlugin({
serverId: "srv-1",
pluginId: "failing-plugin",
handlers: [
() => {
throw new Error("handler boom");
},
],
}),
);
await harness.dispatch({
kind: "plugin",
serverId: "srv-1",
pluginId: "failing-plugin",
notificationId: "n-throw-fallback",
open: { type: "agent", agentId: "agent-fallback" },
});
expect(harness.errors).toHaveLength(1);
expect(harness.agents).toEqual([{ serverId: "srv-1", agentId: "agent-fallback" }]);
});
});
@@ -1,223 +0,0 @@
import type {
PluginCommandCapabilities,
PluginNotificationOpenContext,
PluginNotificationOpenEvent,
} from "@getpaseo/plugin/client";
import type { NotificationOpenTarget } from "@/notification-open/model";
import { buildHostRootRoute, parseServerIdFromPathname } from "@/utils/host-routes";
import { createPluginCapabilities } from "./actions";
import { cloneAndFreeze } from "./freeze";
import type { PluginCatalogStatus } from "./registry";
import { buildPluginSurfaceRoute, parsePluginScreenParams } from "./routes";
import type { InstalledPlugin } from "./types";
export const PLUGIN_NOTIFICATION_CATALOG_TIMEOUT_MS = 8_000;
export type PluginNotificationTarget = Extract<NotificationOpenTarget, { kind: "plugin" }>;
export interface PluginNotificationOpenRegistry {
getSnapshot(): readonly InstalledPlugin[];
getCatalogStatus(serverId: string): PluginCatalogStatus;
subscribe(listener: () => void): () => void;
}
export interface PluginNotificationOpenDependencies {
registry: PluginNotificationOpenRegistry;
timeoutMs?: number;
createCapabilities?: (plugin: InstalledPlugin) => PluginCommandCapabilities;
isHostRegistered?: (serverId: string) => boolean;
focusHost?: (serverId: string) => void;
openAgent: (input: { serverId: string; agentId: string }) => string | void;
openWorkspace: (input: { serverId: string; workspaceId: string }) => string | void;
openRoute: (route: string) => void;
onError?: (error: unknown, context: { serverId: string; pluginId: string }) => void;
}
function findInstalledPlugin(
registry: PluginNotificationOpenRegistry,
serverId: string,
pluginId: string,
): InstalledPlugin | null {
return (
registry
.getSnapshot()
.find((plugin) => plugin.serverId === serverId && plugin.id === pluginId) ?? null
);
}
async function waitForPluginInstallation(
registry: PluginNotificationOpenRegistry,
serverId: string,
pluginId: string,
timeoutMs: number,
): Promise<InstalledPlugin | null> {
const existing = findInstalledPlugin(registry, serverId, pluginId);
if (existing) {
return existing;
}
if (registry.getCatalogStatus(serverId) !== "loading" || timeoutMs <= 0) {
return null;
}
let resolvePromise!: (plugin: InstalledPlugin | null) => void;
const promise = new Promise<InstalledPlugin | null>((resolve) => {
resolvePromise = resolve;
});
let settled = false;
let unsubscribe = () => {};
const finish = (plugin: InstalledPlugin | null) => {
if (settled) return;
settled = true;
clearTimeout(timer);
unsubscribe();
resolvePromise(plugin);
};
const check = () => {
const found = findInstalledPlugin(registry, serverId, pluginId);
if (found) {
finish(found);
return;
}
if (registry.getCatalogStatus(serverId) !== "loading") {
finish(null);
}
};
const timer = setTimeout(() => {
finish(findInstalledPlugin(registry, serverId, pluginId));
}, timeoutMs);
unsubscribe = registry.subscribe(check);
check();
return promise;
}
function applyDeclarativeFallback(
target: PluginNotificationTarget,
deps: Pick<PluginNotificationOpenDependencies, "openAgent" | "openWorkspace" | "openRoute">,
): void {
const open = target.open;
if (open?.type === "agent") {
deps.openAgent({ serverId: target.serverId, agentId: open.agentId });
return;
}
if (open?.type === "workspace") {
deps.openWorkspace({ serverId: target.serverId, workspaceId: open.workspaceId });
return;
}
if (open?.type === "screen") {
try {
const params = parsePluginScreenParams(open.params);
deps.openRoute(
buildPluginSurfaceRoute(
target.serverId,
target.pluginId,
{ kind: "surface", id: open.screenId },
params,
),
);
return;
} catch {
// Fall back to host root route if params are malformed.
}
}
deps.openRoute(buildHostRootRoute(target.serverId));
}
export async function openPluginNotification(
target: PluginNotificationTarget,
deps: PluginNotificationOpenDependencies,
): Promise<void> {
const registry = deps.registry;
const timeoutMs = deps.timeoutMs ?? PLUGIN_NOTIFICATION_CATALOG_TIMEOUT_MS;
const plugin = await waitForPluginInstallation(
registry,
target.serverId,
target.pluginId,
timeoutMs,
);
if (plugin && plugin.notificationOpenHandlers.length > 0) {
const capabilities =
deps.createCapabilities?.(plugin) ??
createPluginCapabilities(plugin, {
openSettings(pluginId, screenId) {
deps.openRoute(
`/settings/hosts/${encodeURIComponent(plugin.serverId)}/plugins/${encodeURIComponent(pluginId)}/${encodeURIComponent(screenId)}`,
);
},
openSurface(pluginId, surfaceId, params) {
deps.openRoute(
buildPluginSurfaceRoute(
plugin.serverId,
pluginId,
{ kind: "surface", id: surfaceId },
params,
),
);
},
openWorkspacePanel() {
throw new Error("No active workspace");
},
openAgentPanel() {
throw new Error("No active workspace");
},
});
const focusRouteHost = (route: string | void, fallbackServerId: string) => {
if (!deps.focusHost) return;
const destinationServerId =
(typeof route === "string" ? parseServerIdFromPathname(route) : null) ?? fallbackServerId;
if (!deps.isHostRegistered || deps.isHostRegistered(destinationServerId)) {
deps.focusHost(destinationServerId);
}
};
const event: PluginNotificationOpenEvent = Object.freeze({
type: "opened" as const,
notificationId: target.notificationId,
data: target.data ? cloneAndFreeze(target.data) : undefined,
});
const context: PluginNotificationOpenContext = {
...capabilities,
event,
navigation: {
openAgent: ({ agentId, serverId: targetServerId, focusHost }) => {
const resolvedServerId = targetServerId ?? target.serverId;
const route = deps.openAgent({ serverId: resolvedServerId, agentId });
if (focusHost) {
focusRouteHost(route, resolvedServerId);
}
},
openWorkspace: ({ workspaceId, serverId: targetServerId, focusHost }) => {
const resolvedServerId = targetServerId ?? target.serverId;
const route = deps.openWorkspace({ serverId: resolvedServerId, workspaceId });
if (focusHost) {
focusRouteHost(route, resolvedServerId);
}
},
},
};
let anySucceeded = false;
for (const handler of plugin.notificationOpenHandlers) {
try {
await handler(context);
anySucceeded = true;
} catch (error) {
if (deps.onError) {
deps.onError(error, { serverId: target.serverId, pluginId: target.pluginId });
} else {
console.warn(
`[Plugins] onNotificationOpen handler failed for ${target.serverId}/${target.pluginId}`,
error,
);
}
}
}
if (anySucceeded) {
return;
}
}
applyDeclarativeFallback(target, deps);
}
+3 -44
View File
@@ -1,13 +1,7 @@
import { useMemo } from "react";
import type { PluginListItem } from "@getpaseo/protocol/messages";
import { useFetchQueries, useFetchQuery } from "@/data/query";
import { useHostFeature, useHostFeatureMap } from "@/runtime/host-features";
import {
getHostRuntimeStore,
useHostRuntimeClient,
useHostRuntimeIsConnected,
useHosts,
} from "@/runtime/host-runtime";
import { useFetchQuery } from "@/data/query";
import { useHostFeature } from "@/runtime/host-features";
import { useHostRuntimeClient, useHostRuntimeIsConnected } from "@/runtime/host-runtime";
export function pluginListQueryKey(serverId: string) {
return ["plugins", serverId] as const;
@@ -44,38 +38,3 @@ export function usePluginDisplayName(
const plugin = plugins.data?.find((candidate) => candidate.id === target.pluginId);
return plugin ? pluginDisplayName(plugin) : target.pluginId;
}
/** Configured plugins across all connected hosts advertising `pluginManagement`, including server-only plugins. */
export function useConfiguredPluginsAcrossHosts(): readonly Pick<PluginListItem, "id" | "name">[] {
const hosts = useHosts();
const serverIds = useMemo(() => hosts.map((host) => host.serverId), [hosts]);
const featureMap = useHostFeatureMap(serverIds, "pluginManagement");
const queries = useFetchQueries(
hosts.map((host) => {
const serverId = host.serverId;
const client = getHostRuntimeStore().getClient(serverId);
const supported = featureMap.get(serverId) === true;
return {
queryKey: pluginListQueryKey(serverId),
queryFn: async () => {
const currentClient = getHostRuntimeStore().getClient(serverId);
if (!currentClient) throw new Error("Plugin host is offline");
return currentClient.listPlugins();
},
enabled: Boolean(client?.isConnected && supported),
dataShape: "list" as const,
staleTimeMs: 1_000,
};
}),
);
return useMemo(
() =>
queries.flatMap((query) =>
(query.data ?? []).map((plugin) => ({
id: plugin.id,
name: pluginDisplayName(plugin),
})),
),
[queries],
);
}
-1
View File
@@ -136,7 +136,6 @@ export class PluginRegistry {
themes: [],
timelineTransformers: [],
timelineRenderers: [],
notificationOpenHandlers: [],
};
const unsubscribeTranslations = installation.i18n.subscribe(() => this.publish());
installation.lifetime.signal.addEventListener("abort", unsubscribeTranslations, {
@@ -48,7 +48,6 @@ function installed(
themes: [],
timelineTransformers: [],
timelineRenderers: [],
notificationOpenHandlers: [],
};
}
@@ -67,7 +67,6 @@ function installation(
themes: [],
timelineTransformers: [],
timelineRenderers: [],
notificationOpenHandlers: [],
};
}
-1
View File
@@ -81,7 +81,6 @@ function installed(serverId: string, themes: PluginThemeContribution[]): Install
themes,
timelineTransformers: [],
timelineRenderers: [],
notificationOpenHandlers: [],
};
}
@@ -47,7 +47,6 @@ function plugin(input: {
},
],
timelineRenderers: [],
notificationOpenHandlers: [],
};
}
-3
View File
@@ -22,7 +22,6 @@ import type {
PluginSettingsScreenContribution as SDKPluginSettingsScreenContribution,
PluginTimelineRendererContribution,
PluginTimelineTransformerContribution,
PluginNotificationOpenHandler,
PluginPanelLocation,
PluginWorkspacePanelContribution as SDKPluginWorkspacePanelContribution,
} from "@getpaseo/plugin/client";
@@ -71,7 +70,6 @@ export interface EvaluatedPlugin {
themes: PluginThemeContribution[];
timelineTransformers: PluginTimelineTransformerContribution[];
timelineRenderers: PluginTimelineRendererContribution[];
notificationOpenHandlers: PluginNotificationOpenHandler[];
}
export interface InstalledPlugin extends EvaluatedPlugin {
@@ -107,6 +105,5 @@ export type {
PluginThemeContribution,
PluginTimelineRendererContribution,
PluginTimelineTransformerContribution,
PluginNotificationOpenHandler,
PluginWorkspacePanelContribution,
};
@@ -44,7 +44,6 @@ function installed(): InstalledPlugin {
themes: [],
timelineTransformers: [],
timelineRenderers: [],
notificationOpenHandlers: [],
};
}
@@ -1,64 +0,0 @@
import AsyncStorage from "@react-native-async-storage/async-storage";
import Constants from "expo-constants";
import * as Notifications from "expo-notifications";
import { Platform } from "react-native";
import { z } from "zod";
import { readValidatedString } from "@/storage/validated-storage";
const STORAGE_PREFIX = "@paseo:expo-push-token:";
const ExpoPushTokenSchema = z.string().trim().min(1);
function storageKey(serverId: string): string {
return `${STORAGE_PREFIX}${serverId}`;
}
function getExpoProjectId(): string | null {
const fromEas = ExpoPushTokenSchema.safeParse(Constants.easConfig?.projectId);
if (fromEas.success) return fromEas.data;
const fromExtra = ExpoPushTokenSchema.safeParse(Constants.expoConfig?.extra?.eas?.projectId);
return fromExtra.success ? fromExtra.data : null;
}
async function ensurePushPermission(): Promise<boolean> {
const existing = await Notifications.getPermissionsAsync();
if (existing.status === Notifications.PermissionStatus.GRANTED) return true;
if (!existing.canAskAgain) return false;
const requested = await Notifications.requestPermissionsAsync();
return requested.status === Notifications.PermissionStatus.GRANTED;
}
export async function readCachedExpoPushToken(serverId: string): Promise<string | null> {
return readValidatedString(AsyncStorage, storageKey(serverId), ExpoPushTokenSchema);
}
export async function removeCachedExpoPushToken(serverId: string): Promise<void> {
await AsyncStorage.removeItem(storageKey(serverId));
}
export async function resolveExpoPushToken(serverId: string): Promise<string | null> {
const key = storageKey(serverId);
const cached = await readValidatedString(AsyncStorage, key, ExpoPushTokenSchema);
if (!(await ensurePushPermission())) {
await AsyncStorage.removeItem(key);
return null;
}
if (Platform.OS === "android") {
await Notifications.setNotificationChannelAsync("default", {
name: "default",
importance: Notifications.AndroidImportance.DEFAULT,
});
}
const projectId = getExpoProjectId();
if (!projectId) {
console.warn("[PushNotifications] Missing EAS projectId; cannot fetch Expo push token");
return cached;
}
const result = await Notifications.getExpoPushTokenAsync({ projectId });
const token = result.data.trim();
if (!token) return cached;
await AsyncStorage.setItem(key, token);
return token;
}
@@ -1,297 +0,0 @@
import { QueryClient } from "@tanstack/react-query";
import {
DEFAULT_NOTIFICATION_PREFERENCES,
type NotificationPreferences,
} from "@getpaseo/protocol/notification-preferences";
import type { ServerInfoStatusPayload, SessionOutboundMessage } from "@getpaseo/protocol/messages";
import type { ConnectionState } from "@getpaseo/client/internal/daemon-client";
import { describe, expect, it } from "vitest";
import { createFakeDesktopBridge, createInMemoryKeyValueStorage } from "@/hooks/use-settings/fakes";
import {
APP_SETTINGS_QUERY_KEY,
DEFAULT_CLIENT_SETTINGS,
saveAppSettings,
type AppSettings,
type SettingsDeps,
} from "@/hooks/use-settings/storage";
import { startSubscription } from "./subscriptions";
import type { PushNotificationClient } from "./types";
function createFakePushClient(options?: {
isConnected?: boolean;
pushNotificationPreferences?: boolean;
}) {
let connected = options?.isConnected ?? true;
let serverInfo: ServerInfoStatusPayload = {
status: "server_info",
serverId: "srv-test",
hostname: "test-host",
version: "0.18.0",
...(options?.pushNotificationPreferences !== undefined
? {
features: {
pushNotificationPreferences: options.pushNotificationPreferences,
},
}
: {}),
};
const connectionListeners = new Set<(state: ConnectionState) => void>();
const statusListeners = new Set<(message: SessionOutboundMessage) => void>();
const registrations: Array<{
token: string;
preferencesProvided: boolean;
preferences: NotificationPreferences | undefined;
}> = [];
const client: PushNotificationClient = {
get isConnected() {
return connected;
},
registerPushToken(token: string, preferences?: NotificationPreferences) {
registrations.push({
token,
preferencesProvided: arguments.length >= 2 && preferences !== undefined,
preferences,
});
},
async unregisterPushToken() {},
getLastServerInfoMessage() {
return serverInfo;
},
subscribeConnectionStatus(listener: (state: ConnectionState) => void) {
connectionListeners.add(listener);
return () => {
connectionListeners.delete(listener);
};
},
on(type: "status", handler: (message: SessionOutboundMessage) => void) {
if (type === "status") {
statusListeners.add(handler);
}
return () => {
statusListeners.delete(handler);
};
},
};
return {
client,
registrations,
setConnected(nextConnected: boolean) {
connected = nextConnected;
const state: ConnectionState = nextConnected
? { status: "connected" }
: { status: "disconnected" };
for (const listener of connectionListeners) {
listener(state);
}
},
emitServerInfo(nextFeatures?: ServerInfoStatusPayload["features"]) {
serverInfo = {
status: "server_info",
serverId: "srv-test",
hostname: "test-host",
version: "0.18.0",
...(nextFeatures ? { features: nextFeatures } : {}),
};
const message: Extract<SessionOutboundMessage, { type: "status" }> = {
type: "status",
payload: serverInfo,
};
for (const listener of statusListeners) {
listener(message);
}
},
};
}
function makeSettingsEnv(initialNotifications?: NotificationPreferences): {
queryClient: QueryClient;
settingsDeps: SettingsDeps;
} {
const queryClient = new QueryClient();
const settings: AppSettings = {
...DEFAULT_CLIENT_SETTINGS,
...(initialNotifications ? { notifications: initialNotifications } : {}),
};
queryClient.setQueryData<AppSettings>(APP_SETTINGS_QUERY_KEY, settings);
const settingsDeps: SettingsDeps = {
storage: createInMemoryKeyValueStorage(),
desktop: createFakeDesktopBridge(),
};
return { queryClient, settingsDeps };
}
async function flushMicrotasks(): Promise<void> {
await Promise.resolve();
await Promise.resolve();
await Promise.resolve();
}
describe("startSubscription push notification preferences sync", () => {
it("sends current notification preferences on connect when pushNotificationPreferences is supported", async () => {
const fake = createFakePushClient({
isConnected: true,
pushNotificationPreferences: true,
});
const { queryClient, settingsDeps } = makeSettingsEnv();
const stop = startSubscription({
client: fake.client,
serverId: "srv-test",
queryClient,
settingsDeps,
resolveToken: async () => "ExponentPushToken[device-1]",
});
await flushMicrotasks();
expect(fake.registrations).toEqual([
{
token: "ExponentPushToken[device-1]",
preferencesProvided: true,
preferences: DEFAULT_NOTIFICATION_PREFERENCES,
},
]);
stop();
});
it("re-syncs preferences immediately when AppSettings.notifications changes while connected", async () => {
const fake = createFakePushClient({
isConnected: true,
pushNotificationPreferences: true,
});
const { queryClient, settingsDeps } = makeSettingsEnv();
const stop = startSubscription({
client: fake.client,
serverId: "srv-test",
queryClient,
settingsDeps,
resolveToken: async () => "ExponentPushToken[device-1]",
});
await flushMicrotasks();
expect(fake.registrations).toHaveLength(1);
const updatedPreferences: NotificationPreferences = {
...DEFAULT_NOTIFICATION_PREFERENCES,
events: {
...DEFAULT_NOTIFICATION_PREFERENCES.events,
agentFinished: true,
},
plugins: {
enabled: true,
muted: ["ci-watchdog"],
},
};
await saveAppSettings({
queryClient,
deps: settingsDeps,
updates: { notifications: updatedPreferences },
});
expect(fake.registrations).toHaveLength(2);
expect(fake.registrations[1]).toEqual({
token: "ExponentPushToken[device-1]",
preferencesProvided: true,
preferences: updatedPreferences,
});
stop();
});
it("omits preferences against older daemons without pushNotificationPreferences", async () => {
const fake = createFakePushClient({
isConnected: true,
pushNotificationPreferences: undefined,
});
const { queryClient, settingsDeps } = makeSettingsEnv();
const stop = startSubscription({
client: fake.client,
serverId: "srv-test",
queryClient,
settingsDeps,
resolveToken: async () => "ExponentPushToken[legacy-device]",
});
await flushMicrotasks();
expect(fake.registrations).toEqual([
{
token: "ExponentPushToken[legacy-device]",
preferencesProvided: false,
preferences: undefined,
},
]);
await saveAppSettings({
queryClient,
deps: settingsDeps,
updates: {
notifications: {
...DEFAULT_NOTIFICATION_PREFERENCES,
enabled: false,
},
},
});
for (const registration of fake.registrations) {
expect(registration.preferencesProvided).toBe(false);
expect(registration.preferences).toBeUndefined();
}
stop();
});
it("re-syncs preferences on reconnect and when server_info upgrades pushNotificationPreferences", async () => {
const fake = createFakePushClient({
isConnected: true,
pushNotificationPreferences: false,
});
const { queryClient, settingsDeps } = makeSettingsEnv();
const stop = startSubscription({
client: fake.client,
serverId: "srv-test",
queryClient,
settingsDeps,
resolveToken: async () => "ExponentPushToken[upgrade-device]",
});
await flushMicrotasks();
expect(fake.registrations).toEqual([
{
token: "ExponentPushToken[upgrade-device]",
preferencesProvided: false,
preferences: undefined,
},
]);
fake.emitServerInfo({ pushNotificationPreferences: true });
expect(fake.registrations).toHaveLength(2);
expect(fake.registrations[1]).toEqual({
token: "ExponentPushToken[upgrade-device]",
preferencesProvided: true,
preferences: DEFAULT_NOTIFICATION_PREFERENCES,
});
fake.setConnected(false);
fake.setConnected(true);
expect(fake.registrations).toHaveLength(3);
expect(fake.registrations[2]).toEqual({
token: "ExponentPushToken[upgrade-device]",
preferencesProvided: true,
preferences: DEFAULT_NOTIFICATION_PREFERENCES,
});
stop();
});
});
@@ -1,90 +1,70 @@
import { parseServerInfoStatusPayload } from "@getpaseo/protocol/messages";
import {
DEFAULT_NOTIFICATION_PREFERENCES,
normalizeNotificationPreferences,
type NotificationPreferences,
} from "@getpaseo/protocol/notification-preferences";
import type { QueryClient } from "@tanstack/react-query";
import { queryClient as appQueryClient } from "@/data/query-client";
import {
APP_SETTINGS_QUERY_KEY,
loadAppSettingsFromStorage as loadAppSettingsFromStoragePure,
type AppSettings,
type SettingsDeps,
} from "@/hooks/use-settings/storage";
import AsyncStorage from "@react-native-async-storage/async-storage";
import Constants from "expo-constants";
import * as Notifications from "expo-notifications";
import { Platform } from "react-native";
import { z } from "zod";
import { readValidatedString } from "@/storage/validated-storage";
import type { RevokePushNotificationsInput, StartPushNotificationsInput } from "./types";
async function defaultResolveToken(serverId: string): Promise<string | null> {
const { resolveExpoPushToken } = await import("./expo-token");
return resolveExpoPushToken(serverId);
const STORAGE_PREFIX = "@paseo:expo-push-token:";
const ExpoPushTokenSchema = z.string().trim().min(1);
function storageKey(serverId: string): string {
return `${STORAGE_PREFIX}${serverId}`;
}
async function loadInitialAppSettings(settingsDeps?: SettingsDeps): Promise<AppSettings> {
if (settingsDeps) {
return loadAppSettingsFromStoragePure(settingsDeps);
}
const { loadAppSettingsFromStorage } = await import("@/hooks/use-settings");
return loadAppSettingsFromStorage();
function getExpoProjectId(): string | null {
const fromEas = ExpoPushTokenSchema.safeParse(Constants.easConfig?.projectId);
if (fromEas.success) return fromEas.data;
const fromExtra = ExpoPushTokenSchema.safeParse(Constants.expoConfig?.extra?.eas?.projectId);
return fromExtra.success ? fromExtra.data : null;
}
function readCachedPreferences(queryClient: QueryClient): NotificationPreferences | null {
const cached = queryClient.getQueryData<AppSettings>(APP_SETTINGS_QUERY_KEY);
if (!cached) {
async function ensurePushPermission(): Promise<boolean> {
const existing = await Notifications.getPermissionsAsync();
if (existing.status === Notifications.PermissionStatus.GRANTED) return true;
if (!existing.canAskAgain) return false;
const requested = await Notifications.requestPermissionsAsync();
return requested.status === Notifications.PermissionStatus.GRANTED;
}
async function resolveToken(serverId: string): Promise<string | null> {
const key = storageKey(serverId);
const cached = await readValidatedString(AsyncStorage, key, ExpoPushTokenSchema);
if (!(await ensurePushPermission())) {
await AsyncStorage.removeItem(key);
return null;
}
return normalizeNotificationPreferences(cached.notifications);
if (Platform.OS === "android") {
await Notifications.setNotificationChannelAsync("default", {
name: "default",
importance: Notifications.AndroidImportance.DEFAULT,
});
}
const projectId = getExpoProjectId();
if (!projectId) {
console.warn("[PushNotifications] Missing EAS projectId; cannot fetch Expo push token");
return cached;
}
const result = await Notifications.getExpoPushTokenAsync({ projectId });
const token = result.data.trim();
if (!token) return cached;
await AsyncStorage.setItem(key, token);
return token;
}
export function startSubscription(input: StartPushNotificationsInput): () => void {
let stopped = false;
let token: string | null = null;
let lastRegisteredSignature: string | null = null;
const queryClient = input.queryClient ?? appQueryClient;
const resolveToken = input.resolveToken ?? defaultResolveToken;
const initialCached = readCachedPreferences(queryClient);
let preferences: NotificationPreferences = initialCached ?? DEFAULT_NOTIFICATION_PREFERENCES;
let preferencesReady = initialCached !== null;
const register = (force = false) => {
if (stopped || !token || !preferencesReady || !input.client.isConnected) {
return;
}
// COMPAT(pushNotificationPreferences): added in v0.18.0, remove gate after 2027-06-01.
const supportsPreferences =
input.client.getLastServerInfoMessage()?.features?.pushNotificationPreferences === true;
const signature = supportsPreferences
? `${token}:${JSON.stringify(preferences)}`
: `${token}:legacy`;
if (!force && signature === lastRegisteredSignature) {
return;
}
lastRegisteredSignature = signature;
if (supportsPreferences) {
input.client.registerPushToken(token, preferences);
} else {
const register = () => {
if (!stopped && token && input.client.isConnected) {
input.client.registerPushToken(token);
}
};
if (!preferencesReady) {
void loadInitialAppSettings(input.settingsDeps)
.then((loaded) => {
if (stopped) return undefined;
const latestCached = readCachedPreferences(queryClient);
preferences = latestCached ?? normalizeNotificationPreferences(loaded.notifications);
preferencesReady = true;
register();
return undefined;
})
.catch(() => {
if (stopped) return undefined;
preferencesReady = true;
register();
return undefined;
});
}
void resolveToken(input.serverId)
.then((resolved) => {
if (stopped) return undefined;
@@ -94,46 +74,19 @@ export function startSubscription(input: StartPushNotificationsInput): () => voi
})
.catch((error) => console.warn("[PushNotifications] Failed to register push token", error));
const unsubscribeConnection = input.client.subscribeConnectionStatus((state) => {
if (state.status === "connected") {
lastRegisteredSignature = null;
register(true);
} else {
lastRegisteredSignature = null;
}
});
const unsubscribeStatus =
input.client.on?.("status", (message) => {
if (message.type === "status" && parseServerInfoStatusPayload(message.payload)) {
register();
}
}) ?? (() => undefined);
const unsubscribeQueryCache = queryClient.getQueryCache().subscribe((event) => {
if (event.query.queryKey[0] !== APP_SETTINGS_QUERY_KEY[0]) {
return;
}
const nextPreferences = readCachedPreferences(queryClient);
if (!nextPreferences) {
return;
}
preferences = nextPreferences;
preferencesReady = true;
register();
const unsubscribe = input.client.subscribeConnectionStatus((state) => {
if (state.status === "connected") register();
});
return () => {
stopped = true;
unsubscribeConnection();
unsubscribeStatus();
unsubscribeQueryCache();
unsubscribe();
};
}
export async function revokeSubscription(input: RevokePushNotificationsInput): Promise<void> {
const { readCachedExpoPushToken, removeCachedExpoPushToken } = await import("./expo-token");
const token = await readCachedExpoPushToken(input.serverId);
const key = storageKey(input.serverId);
const token = await readValidatedString(AsyncStorage, key, ExpoPushTokenSchema);
if (
token &&
input.client?.isConnected &&
@@ -145,5 +98,5 @@ export async function revokeSubscription(input: RevokePushNotificationsInput): P
console.warn("[PushNotifications] Failed to revoke push token", error);
}
}
await removeCachedExpoPushToken(input.serverId);
await AsyncStorage.removeItem(key);
}
@@ -1,31 +1,11 @@
import type { DaemonClient } from "@getpaseo/client/internal/daemon-client";
import type { SessionOutboundMessage } from "@getpaseo/protocol/messages";
import type { QueryClient } from "@tanstack/react-query";
import type { SettingsDeps } from "@/hooks/use-settings/storage";
export type PushNotificationClient = Pick<
DaemonClient,
| "isConnected"
| "registerPushToken"
| "unregisterPushToken"
| "subscribeConnectionStatus"
| "getLastServerInfoMessage"
> & {
on?: (type: "status", handler: (message: SessionOutboundMessage) => void) => () => void;
};
export interface StartPushNotificationsInput {
client: PushNotificationClient;
client: DaemonClient;
serverId: string;
queryClient?: QueryClient;
settingsDeps?: SettingsDeps;
resolveToken?: (serverId: string) => Promise<string | null>;
}
export interface RevokePushNotificationsInput {
client: Pick<
DaemonClient,
"isConnected" | "unregisterPushToken" | "getLastServerInfoMessage"
> | null;
client: DaemonClient | null;
serverId: string;
}
-11
View File
@@ -38,17 +38,6 @@ export function useHostFeature(
return useSessionStore((state) => selectHostFeature(state, normalizedServerId, feature));
}
export function useHostFeatureAvailability(
serverId: string | null | undefined,
feature: HostFeatureName,
): boolean | null {
const normalizedServerId = serverId?.trim() ?? "";
return useSessionStore((state) => {
const serverInfo = state.sessions[normalizedServerId]?.serverInfo;
return serverInfo ? hostSupportsFeature(serverInfo, feature) : null;
});
}
export function useHostFeatureMap(
serverIds: readonly string[],
feature: HostFeatureName,
+3 -2
View File
@@ -74,7 +74,7 @@ import { CommunityLinks } from "@/components/community-links";
import { SegmentedControl } from "@/components/ui/segmented-control";
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem } from "@/components/ui/dropdown-menu";
import { DesktopPermissionsSection } from "@/desktop/components/desktop-permissions-section";
import { NotificationsSection } from "@/components/settings/notifications-section";
import { DesktopNotificationsSection } from "@/desktop/components/desktop-notifications-section";
import { BrowserDataSection } from "@/desktop/browser/settings/browser-data-section";
import { IntegrationsSection } from "@/desktop/components/integrations-section";
import { isElectronRuntime } from "@/desktop/host";
@@ -184,6 +184,7 @@ const SIDEBAR_SECTION_ITEMS: SidebarSectionItem[] = [
id: "notifications",
labelKey: "settings.sections.notifications",
icon: Bell,
desktopOnly: true,
},
{ id: "about", labelKey: "settings.sections.about", icon: Info },
];
@@ -1545,7 +1546,7 @@ export default function SettingsScreen({ view }: SettingsScreenProps) {
case "notifications":
return (
<>
<NotificationsSection />
<DesktopNotificationsSection />
{isDesktopApp ? <DesktopPermissionsSection /> : null}
</>
);
+4 -4
View File
@@ -1,6 +1,6 @@
{
"name": "@getpaseo/cli",
"version": "0.17.5",
"version": "0.17.6",
"description": "Paseo CLI - control your AI coding agents from the command line",
"license": "Apache-2.0",
"bin": {
@@ -29,9 +29,9 @@
},
"dependencies": {
"@clack/prompts": "^1.0.0",
"@getpaseo/client": "0.17.5",
"@getpaseo/protocol": "0.17.5",
"@getpaseo/server": "0.17.5",
"@getpaseo/client": "0.17.6",
"@getpaseo/protocol": "0.17.6",
"@getpaseo/server": "0.17.6",
"chalk": "^5.3.0",
"commander": "^12.0.0",
"mime-types": "^2.1.35",
+3 -3
View File
@@ -1,6 +1,6 @@
{
"name": "@getpaseo/client",
"version": "0.17.5",
"version": "0.17.6",
"description": "Paseo client SDK package",
"license": "Apache-2.0",
"files": [
@@ -49,8 +49,8 @@
"measure:diff-materialization": "tsx scripts/measure-diff-materialization.ts"
},
"dependencies": {
"@getpaseo/protocol": "0.17.5",
"@getpaseo/relay": "0.17.5",
"@getpaseo/protocol": "0.17.6",
"@getpaseo/relay": "0.17.6",
"ws": "^8.20.0",
"zod": "^4.4.3"
},
-41
View File
@@ -1528,47 +1528,6 @@ test("waits for the daemon to acknowledge push token revocation", async () => {
await revocation;
});
test("registers a push token with or without notification preferences", async () => {
const mock = createMockTransport();
const client = new DaemonClient({
url: "ws://test",
clientId: "clsk_push_preferences",
reconnect: { enabled: false },
transportFactory: () => mock.transport,
});
clients.push(client);
const connectPromise = client.connect();
mock.triggerOpen({ features: { pushNotificationPreferences: true } });
await connectPromise;
client.registerPushToken("ExponentPushToken[legacy-call]");
expect(parseSentFrame(mock.sent.at(-1))).toEqual({
type: "register_push_token",
token: "ExponentPushToken[legacy-call]",
});
const preferences = {
enabled: true,
events: {
agentPermission: true,
agentError: true,
agentFinished: true,
terminalNeedsInput: true,
terminalFinished: false,
},
plugins: {
enabled: true,
muted: ["review-bot"],
},
};
client.registerPushToken("ExponentPushToken[with-prefs]", preferences);
expect(parseSentFrame(mock.sent.at(-1))).toEqual({
type: "register_push_token",
token: "ExponentPushToken[with-prefs]",
preferences,
});
});
test("bounds the wait for push token revocation", async () => {
useHeartbeatClock();
const mock = createMockTransport();
+1 -3
View File
@@ -34,7 +34,6 @@ import type { SessionEventSubscription } from "@getpaseo/protocol/messages";
import type { LocalSpeechModel } from "@getpaseo/protocol/speech/rpc-schemas";
import { CLIENT_CAPS, type ClientCapability } from "@getpaseo/protocol/client-capabilities";
import type { AgentAttentionNotificationPayload } from "@getpaseo/protocol/agent-attention-notification";
import type { NotificationPreferences } from "@getpaseo/protocol/notification-preferences";
import { MAX_WEBSOCKET_MESSAGE_BYTES } from "@getpaseo/protocol/websocket-message-limit";
import {
AgentCreateFailedStatusPayloadSchema,
@@ -2593,11 +2592,10 @@ export class DaemonClient {
});
}
registerPushToken(token: string, preferences?: NotificationPreferences): void {
registerPushToken(token: string): void {
this.sendSessionMessage({
type: "register_push_token",
token,
...(preferences !== undefined ? { preferences } : {}),
});
}
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@getpaseo/desktop",
"version": "0.17.5",
"version": "0.17.6",
"private": true,
"description": "Paseo desktop app (Electron wrapper)",
"homepage": "https://paseo.sh",
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@getpaseo/expo-two-way-audio",
"version": "0.17.5",
"version": "0.17.6",
"description": "Native module for two way audio streaming",
"keywords": [
"ExpoTwoWayAudio",
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@getpaseo/highlight",
"version": "0.17.5",
"version": "0.17.6",
"license": "Apache-2.0",
"files": [
"dist",
+5 -5
View File
@@ -1,6 +1,6 @@
{
"name": "@getpaseo/plugin",
"version": "0.17.5",
"version": "0.17.6",
"description": "Paseo plugin SDK package",
"license": "Apache-2.0",
"files": [
@@ -83,8 +83,8 @@
"use-sync-external-store": "^1.6.0"
},
"devDependencies": {
"@getpaseo/client": "0.17.5",
"@getpaseo/protocol": "0.17.5",
"@getpaseo/client": "0.17.6",
"@getpaseo/protocol": "0.17.6",
"@types/node": "^20.9.0",
"@types/react": "~19.2.0",
"react": "19.2.3",
@@ -94,8 +94,8 @@
"zod": "^4.4.3"
},
"peerDependencies": {
"@getpaseo/client": "0.17.5",
"@getpaseo/protocol": "0.17.5",
"@getpaseo/client": "0.17.6",
"@getpaseo/protocol": "0.17.6",
"react": ">=19.1.0 <20",
"react-native": ">=0.81.5",
"zod": "^4.4.3"
-85
View File
@@ -694,88 +694,3 @@ describe("worktree manager SDK boundary", () => {
).toEqual([]);
});
});
describe("plugin notifications SDK boundary", () => {
it("types server notification sends and client tap handlers with capabilities and cleanup", () => {
expect(
typeErrors(`
import type {
PluginServerContext,
PluginNotifications,
PluginNotificationSendInput,
PluginNotificationSendResult,
PluginNotificationOpenTarget,
} from "@getpaseo/plugin/server";
import type {
PluginClientContext,
PluginHostNavigationActions,
PluginNotificationOpenContext,
PluginNotificationOpenEvent,
PluginNotificationOpenHandler,
} from "@getpaseo/plugin/client";
export async function sendFromServer(server: PluginServerContext) {
const notifications: PluginNotifications = server.notifications;
const target: PluginNotificationOpenTarget = {
type: "screen",
screenId: "details",
params: { id: "42" },
};
const input: PluginNotificationSendInput = {
title: "Build failed",
body: "Check the logs",
key: "build:42",
open: target,
data: { buildId: 42, ok: false, tags: ["ci"] },
};
const result: PluginNotificationSendResult = await notifications.send(input);
if (result.status === "sent") {
const id: string = result.notificationId;
void id;
}
await server.notifications.send({
title: "Agent ready",
body: "Done",
open: { type: "agent", agentId: "agent-1" },
});
await server.notifications.send({
title: "Workspace ready",
body: "Done",
open: { type: "workspace", workspaceId: "ws-1" },
});
// @ts-expect-error data must be JSON values
await server.notifications.send({ title: "Bad", body: "Bad", data: { fn: () => {} } });
// @ts-expect-error open target requires a known type discriminant
await server.notifications.send({ title: "Bad", body: "Bad", open: { type: "unknown" } });
}
export function contributeClient(client: PluginClientContext) {
const handler: PluginNotificationOpenHandler = (context: PluginNotificationOpenContext) => {
const navigation: PluginHostNavigationActions = context.navigation;
void navigation;
const event: PluginNotificationOpenEvent = context.event;
const kind: "opened" = event.type;
const id: string = event.notificationId;
void kind;
void id;
// @ts-expect-error event fields are read-only
event.notificationId = "other";
if (event.data) {
// @ts-expect-error event data record is read-only
event.data.extra = "nope";
}
if (typeof event.data?.agentId === "string") {
context.navigation.openAgent({ agentId: event.data.agentId, focusHost: true });
} else if (typeof event.data?.workspaceId === "string") {
context.navigation.openWorkspace({ workspaceId: event.data.workspaceId });
} else {
context.openScreen({ screenId: "main", params: { from: "notification" } });
}
};
const cleanup = client.onNotificationOpen(handler);
return cleanup;
}
`),
).toEqual([]);
});
});
+13 -18
View File
@@ -33,7 +33,6 @@ import type {
PluginCleanup,
} from "../contracts.js";
import type { PluginIconProps, PluginSerializableIcon } from "../icons.js";
import type { PluginNotificationOpenHandler } from "./notifications.js";
export interface PluginHostProps {
theme: PluginTheme;
@@ -47,24 +46,9 @@ export interface PluginHostProps {
};
}
export interface PluginHostNavigationActions {
readonly openAgent: (input: {
readonly agentId: string;
readonly serverId?: string;
/** Select only the destination host in the sidebar and clear project/label filters. */
readonly focusHost?: boolean;
}) => void;
readonly openWorkspace: (input: {
readonly workspaceId: string;
readonly serverId?: string;
/** Select only the destination host in the sidebar and clear project/label filters. */
readonly focusHost?: boolean;
}) => void;
}
interface PluginNavigableHostProps extends PluginHostProps {
/** Client-owned navigation. Undefined on older hosts; hide dependent affordances when absent. */
readonly navigation?: PluginHostNavigationActions & {
readonly navigation?: {
/** This client supports the focusHost option on agent/workspace navigation. */
readonly supportsFocusHost?: boolean;
/** Present only on Electron. The browser runs locally; serverId selects workspace ownership. */
@@ -73,6 +57,18 @@ interface PluginNavigableHostProps extends PluginHostProps {
readonly workspaceId: string;
readonly serverId?: string;
}) => void;
readonly openAgent: (input: {
readonly agentId: string;
readonly serverId?: string;
/** Select only the destination host in the sidebar and clear project/label filters. */
readonly focusHost?: boolean;
}) => void;
readonly openWorkspace: (input: {
readonly workspaceId: string;
readonly serverId?: string;
/** Select only the destination host in the sidebar and clear project/label filters. */
readonly focusHost?: boolean;
}) => void;
};
}
@@ -268,7 +264,6 @@ export interface PluginClientContext extends PluginCommandCapabilities, PluginCl
addTimelineRenderer<Schema extends ZodType>(
contribution: PluginTimelineRendererContribution<Schema>,
): PluginCleanup;
onNotificationOpen(handler: PluginNotificationOpenHandler): PluginCleanup;
openPanel(id: string, options: PluginClientOpenPanelOptions): void;
/**
* Subscribes to a plugin subscription on this client's host. Paseo re-subscribes after a
-6
View File
@@ -1,6 +1,5 @@
export type {
PluginHostProps,
PluginHostNavigationActions,
PluginTab,
PluginPanelProps,
PluginWorkspacePanelParams,
@@ -46,11 +45,6 @@ export type {
PluginClientSlashCommandContribution,
SettingsState,
} from "./contracts.js";
export type {
PluginNotificationOpenEvent,
PluginNotificationOpenContext,
PluginNotificationOpenHandler,
} from "./notifications.js";
export type {
PluginButton,
PluginButtonBehavior,
@@ -1,17 +0,0 @@
import type { JsonValue } from "@getpaseo/protocol/agent-types";
import type { PluginCommandCapabilities, PluginHostNavigationActions } from "./contracts.js";
export interface PluginNotificationOpenEvent {
readonly type: "opened";
readonly notificationId: string;
readonly data: Readonly<Record<string, JsonValue>> | undefined;
}
export interface PluginNotificationOpenContext extends PluginCommandCapabilities {
readonly event: PluginNotificationOpenEvent;
readonly navigation: PluginHostNavigationActions;
}
export type PluginNotificationOpenHandler = (
context: PluginNotificationOpenContext,
) => void | Promise<void>;
-2
View File
@@ -5,7 +5,6 @@ import type { PluginCleanup } from "../contracts.js";
import type { ProviderRegistration } from "./provider.js";
import type { UsageSourceRegistration } from "./usage.js";
import type { PluginLifecycleRegistration } from "./lifecycle.js";
import type { PluginNotifications } from "./notifications.js";
import type { WorktreeManagerRegistration } from "./worktree.js";
export interface PluginHandlerContext {
@@ -67,7 +66,6 @@ export interface PluginServerContext extends PluginLifecycleRegistration {
registerProvider(provider: ProviderRegistration): void;
registerUsageSource(source: UsageSourceRegistration): void;
registerWorktreeManager(manager: WorktreeManagerRegistration): () => void;
notifications: PluginNotifications;
}
export type PluginServerContribution = (server: PluginServerContext) => PluginCleanup;
-6
View File
@@ -39,12 +39,6 @@ export type { SpawnProcessOptions } from "./process.js";
export { defineAgentTool } from "./agent-tools.js";
export type { AgentToolDefinition, AgentToolResult, AgentToolContext } from "./agent-tools.js";
export type {
PluginNotifications,
PluginNotificationSendInput,
PluginNotificationSendResult,
PluginNotificationOpenTarget,
} from "./notifications.js";
export type {
PluginWorktreeContext,
PluginWorktreeCreateInput,
@@ -1,26 +0,0 @@
import type { JsonValue } from "@getpaseo/protocol/agent-types";
export type PluginNotificationOpenTarget =
| { type: "agent"; agentId: string }
| { type: "workspace"; workspaceId: string }
| { type: "screen"; screenId: string; params?: Record<string, string> };
export interface PluginNotificationSendInput {
title: string;
body: string;
/** Identical keys from the same plugin within 60 s are dropped as deduplicated. */
key?: string;
/** Declarative navigation on tap when no client `onNotificationOpen` handler handles it. */
open?: PluginNotificationOpenTarget;
/** JSON payload delivered to `client.onNotificationOpen` on tap (<= 1024 UTF-8 bytes). */
data?: Record<string, JsonValue>;
}
export type PluginNotificationSendResult =
| { status: "sent"; notificationId: string }
| { status: "deduplicated" }
| { status: "rate_limited" };
export interface PluginNotifications {
send(input: PluginNotificationSendInput): Promise<PluginNotificationSendResult>;
}
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@getpaseo/protocol",
"version": "0.17.5",
"version": "0.17.6",
"description": "Paseo shared protocol schemas and wire types",
"license": "Apache-2.0",
"files": [
-85
View File
@@ -1,9 +1,4 @@
import { describe, expect, test } from "vitest";
import {
DEFAULT_NOTIFICATION_PREFERENCES,
normalizeNotificationPreferences,
type NotificationPreferences,
} from "./notification-preferences.js";
import {
AgentTimelineItemPayloadSchema,
SendAgentMessageRequestSchema,
@@ -636,83 +631,3 @@ describe("terminal collection protocol compatibility", () => {
).toMatchObject({ payload: { terminals: [{ isScript: true, createdAt: null }] } });
});
});
describe("push notification preferences protocol compatibility", () => {
test("accepts register_push_token with or without notification preferences", () => {
expect(
SessionInboundMessageSchema.parse({
type: "register_push_token",
token: "ExponentPushToken[legacy]",
}),
).toEqual({
type: "register_push_token",
token: "ExponentPushToken[legacy]",
});
const preferences: NotificationPreferences = {
...DEFAULT_NOTIFICATION_PREFERENCES,
events: {
...DEFAULT_NOTIFICATION_PREFERENCES.events,
agentFinished: true,
},
plugins: {
enabled: true,
muted: ["review-bot"],
},
};
expect(
SessionInboundMessageSchema.parse({
type: "register_push_token",
token: "ExponentPushToken[modern]",
preferences,
}),
).toEqual({
type: "register_push_token",
token: "ExponentPushToken[modern]",
preferences,
});
const partialParsed = SessionInboundMessageSchema.parse({
type: "register_push_token",
token: "ExponentPushToken[partial]",
preferences: {
events: { agentFinished: true },
plugins: { muted: ["zeta-plugin", "alpha-plugin"] },
},
});
expect(partialParsed).toEqual({
type: "register_push_token",
token: "ExponentPushToken[partial]",
preferences: {
events: { agentFinished: true },
plugins: { muted: ["zeta-plugin", "alpha-plugin"] },
},
});
if (partialParsed.type !== "register_push_token") {
throw new Error("Expected register_push_token message");
}
expect(normalizeNotificationPreferences(partialParsed.preferences)).toEqual({
...DEFAULT_NOTIFICATION_PREFERENCES,
events: {
...DEFAULT_NOTIFICATION_PREFERENCES.events,
agentFinished: true,
},
plugins: {
enabled: true,
muted: ["alpha-plugin", "zeta-plugin"],
},
});
});
test("parses pushNotificationPreferences feature flag on server_info", () => {
const parsed = parseServerInfoStatusPayload({
status: "server_info",
serverId: "srv-1",
features: {
pushNotificationPreferences: true,
},
});
expect(parsed.features?.pushNotificationPreferences).toBe(true);
});
});
-54
View File
@@ -43,18 +43,6 @@ export {
} from "./plugin-config.js";
import { TerminalProfileSchema } from "./terminal-profile.js";
export { TerminalProfileSchema, type TerminalProfile } from "./terminal-profile.js";
import { NotificationPreferencesSchema } from "./notification-preferences.js";
export {
DEFAULT_NOTIFICATION_PREFERENCES,
NotificationEventsPreferencesSchema,
NotificationPluginsPreferencesSchema,
NotificationPreferencesSchema,
normalizeNotificationPreferences,
shouldDeliverNotification,
type NotificationKind,
type NotificationPreferences,
type NotificationPreferencesInput,
} from "./notification-preferences.js";
import { z } from "zod";
import { TerminalActivitySchema } from "./terminal-activity.js";
import { CLIENT_CAPS } from "./client-capabilities.js";
@@ -3304,7 +3292,6 @@ export const ListCommandsRequestSchema = z.object({
export const RegisterPushTokenMessageSchema = z.object({
type: z.literal("register_push_token"),
token: z.string(),
preferences: NotificationPreferencesSchema.optional(),
});
export const PushUnregisterRequestSchema = z.object({
@@ -3548,7 +3535,6 @@ export const SessionEventSubscriptionSchema = z.enum([
"agent.provider_subagents.update",
"agent.background_work.update",
"terminal_attention_required",
"plugin.notification",
"status.server_info",
"status.daemon_config_changed",
"status.plugin_catalog_changed",
@@ -4078,8 +4064,6 @@ export const ServerInfoStatusPayloadSchema = z
relayConfig: z.boolean().optional(),
// COMPAT(pushTokenRevocation): added in v0.3.2, remove gate after 2027-02-10.
pushTokenRevocation: z.boolean().optional(),
// COMPAT(pushNotificationPreferences): added in v0.18.0, remove gate after 2027-06-01.
pushNotificationPreferences: z.boolean().optional(),
// COMPAT(plugins): added in v0.3.0, remove gate after 2027-08-07.
plugins: z.boolean().optional(),
// COMPAT(pluginManagement): added in v0.4.0, remove gate after 2027-08-14.
@@ -4102,8 +4086,6 @@ export const ServerInfoStatusPayloadSchema = z
pluginTimelineItems: z.boolean().optional(),
// COMPAT(pluginSubscriptions): added in v0.15.0, remove gate after 2027-05-02.
pluginSubscriptions: z.boolean().optional(),
// COMPAT(pluginNotifications): added in v0.18.0, remove gate after 2027-06-01.
pluginNotifications: z.boolean().optional(),
// COMPAT(skillManagement): added in v0.4.0, remove gate after 2027-08-16.
skillManagement: z.boolean().optional(),
// COMPAT(idleRuntimeCleanupSetting): added in v0.13.0, remove gate after 2027-04-26.
@@ -7379,41 +7361,6 @@ export const TerminalAttentionRequiredSchema = z.object({
}),
});
export const PluginNotificationOpenTargetSchema = z.discriminatedUnion("type", [
z.object({
type: z.literal("agent"),
agentId: z.string(),
}),
z.object({
type: z.literal("workspace"),
workspaceId: z.string(),
}),
z.object({
type: z.literal("screen"),
screenId: z.string(),
params: z.record(z.string(), z.string()).optional(),
}),
]);
export type PluginNotificationOpenTarget = z.infer<typeof PluginNotificationOpenTargetSchema>;
export const PluginNotificationMessageSchema = z.object({
type: z.literal("plugin.notification"),
payload: z.object({
subscriptionId: z.string().optional(),
serverId: z.string().optional(),
pluginId: z.string(),
notificationId: z.string(),
title: z.string(),
body: z.string(),
open: PluginNotificationOpenTargetSchema.optional(),
data: z.record(z.string(), JsonWireValueSchema).optional(),
shouldNotify: z.boolean(),
}),
});
export type PluginNotificationMessage = z.infer<typeof PluginNotificationMessageSchema>;
export const DaemonUpdateResponseSchema = z.object({
type: z.literal("daemon.update.response"),
payload: z.object({
@@ -8008,7 +7955,6 @@ export const SessionOutboundMessageSchema = z.discriminatedUnion("type", [
CaptureTerminalResponseSchema,
TerminalStreamExitSchema,
TerminalAttentionRequiredSchema,
PluginNotificationMessageSchema,
ChatCreateResponseSchema,
ChatListResponseSchema,
ChatInspectResponseSchema,
@@ -1,181 +0,0 @@
import { describe, expect, it } from "vitest";
import {
DEFAULT_NOTIFICATION_PREFERENCES,
NotificationPreferencesSchema,
type NotificationPreferences,
normalizeNotificationPreferences,
shouldDeliverNotification,
} from "./notification-preferences.js";
describe("notification-preferences", () => {
it("defines default preferences with master, permission, error, terminalNeedsInput, and plugins on, and finished events off", () => {
expect(DEFAULT_NOTIFICATION_PREFERENCES).toEqual({
enabled: true,
events: {
agentPermission: true,
agentError: true,
agentFinished: false,
terminalNeedsInput: true,
terminalFinished: false,
},
plugins: {
enabled: true,
muted: [],
},
});
expect(NotificationPreferencesSchema.parse(DEFAULT_NOTIFICATION_PREFERENCES)).toEqual(
DEFAULT_NOTIFICATION_PREFERENCES,
);
});
it("normalizes undefined, partial, and malformed preference payloads to defaults", () => {
expect(normalizeNotificationPreferences()).toEqual(DEFAULT_NOTIFICATION_PREFERENCES);
expect(normalizeNotificationPreferences(null)).toEqual(DEFAULT_NOTIFICATION_PREFERENCES);
expect(normalizeNotificationPreferences("invalid")).toEqual(DEFAULT_NOTIFICATION_PREFERENCES);
const normalized = normalizeNotificationPreferences({
enabled: false,
events: {
agentFinished: true,
agentError: "not-a-bool",
},
plugins: {
muted: [" review-bot ", "review-bot", "", 42, "ci-watcher"],
},
});
expect(normalized).toEqual({
enabled: false,
events: {
agentPermission: true,
agentError: true,
agentFinished: true,
terminalNeedsInput: true,
terminalFinished: false,
},
plugins: {
enabled: true,
muted: ["ci-watcher", "review-bot"],
},
});
});
it("canonicalizes plugins.muted order so reordered arrays normalize to identical structures", () => {
const a = normalizeNotificationPreferences({
plugins: { muted: ["zeta", "alpha", "beta"] },
});
const b = normalizeNotificationPreferences({
plugins: { muted: ["beta", "zeta", "alpha"] },
});
expect(a.plugins.muted).toEqual(["alpha", "beta", "zeta"]);
expect(a).toEqual(b);
});
it("returns fresh cloned objects from normalizeNotificationPreferences so callers cannot mutate defaults", () => {
const first = normalizeNotificationPreferences();
first.events.agentFinished = true;
first.plugins.muted.push("mutated-plugin");
expect(DEFAULT_NOTIFICATION_PREFERENCES.events.agentFinished).toBe(false);
expect(DEFAULT_NOTIFICATION_PREFERENCES.plugins.muted).toEqual([]);
expect(normalizeNotificationPreferences()).toEqual(DEFAULT_NOTIFICATION_PREFERENCES);
});
it("delivers permission, error, terminal needs_input, and unmuted plugins under default preferences while blocking finished events", () => {
const prefs = DEFAULT_NOTIFICATION_PREFERENCES;
expect(shouldDeliverNotification(prefs, { kind: "agent", reason: "permission" })).toBe(true);
expect(shouldDeliverNotification(prefs, { kind: "agent", reason: "error" })).toBe(true);
expect(shouldDeliverNotification(prefs, { kind: "agent", reason: "finished" })).toBe(false);
expect(shouldDeliverNotification(prefs, { kind: "terminal", reason: "needs_input" })).toBe(
true,
);
expect(shouldDeliverNotification(prefs, { kind: "terminal", reason: "finished" })).toBe(false);
expect(shouldDeliverNotification(prefs, { kind: "plugin", pluginId: "review-bot" })).toBe(true);
});
it("blocks every built-in event and every plugin when master enabled is false", () => {
const prefs: NotificationPreferences = {
enabled: false,
events: {
agentPermission: true,
agentError: true,
agentFinished: true,
terminalNeedsInput: true,
terminalFinished: true,
},
plugins: {
enabled: true,
muted: [],
},
};
expect(shouldDeliverNotification(prefs, { kind: "agent", reason: "permission" })).toBe(false);
expect(shouldDeliverNotification(prefs, { kind: "agent", reason: "error" })).toBe(false);
expect(shouldDeliverNotification(prefs, { kind: "agent", reason: "finished" })).toBe(false);
expect(shouldDeliverNotification(prefs, { kind: "terminal", reason: "needs_input" })).toBe(
false,
);
expect(shouldDeliverNotification(prefs, { kind: "terminal", reason: "finished" })).toBe(false);
expect(shouldDeliverNotification(prefs, { kind: "plugin", pluginId: "review-bot" })).toBe(
false,
);
});
it("allows unmuted plugins when master is on and all built-in events are turned off", () => {
const prefs: NotificationPreferences = {
enabled: true,
events: {
agentPermission: false,
agentError: false,
agentFinished: false,
terminalNeedsInput: false,
terminalFinished: false,
},
plugins: {
enabled: true,
muted: ["noisy-plugin"],
},
};
expect(shouldDeliverNotification(prefs, { kind: "agent", reason: "permission" })).toBe(false);
expect(shouldDeliverNotification(prefs, { kind: "agent", reason: "error" })).toBe(false);
expect(shouldDeliverNotification(prefs, { kind: "agent", reason: "finished" })).toBe(false);
expect(shouldDeliverNotification(prefs, { kind: "terminal", reason: "needs_input" })).toBe(
false,
);
expect(shouldDeliverNotification(prefs, { kind: "terminal", reason: "finished" })).toBe(false);
expect(shouldDeliverNotification(prefs, { kind: "plugin", pluginId: "review-bot" })).toBe(true);
expect(shouldDeliverNotification(prefs, { kind: "plugin", pluginId: "noisy-plugin" })).toBe(
false,
);
});
it("blocks all plugins when plugins.enabled is false while still respecting built-in event toggles", () => {
const prefs: NotificationPreferences = {
enabled: true,
events: {
agentPermission: true,
agentError: false,
agentFinished: true,
terminalNeedsInput: false,
terminalFinished: true,
},
plugins: {
enabled: false,
muted: [],
},
};
expect(shouldDeliverNotification(prefs, { kind: "agent", reason: "permission" })).toBe(true);
expect(shouldDeliverNotification(prefs, { kind: "agent", reason: "error" })).toBe(false);
expect(shouldDeliverNotification(prefs, { kind: "agent", reason: "finished" })).toBe(true);
expect(shouldDeliverNotification(prefs, { kind: "terminal", reason: "needs_input" })).toBe(
false,
);
expect(shouldDeliverNotification(prefs, { kind: "terminal", reason: "finished" })).toBe(true);
expect(shouldDeliverNotification(prefs, { kind: "plugin", pluginId: "review-bot" })).toBe(
false,
);
});
});
@@ -1,166 +0,0 @@
import { z } from "zod";
export interface NotificationPreferences {
enabled: boolean;
events: {
agentPermission: boolean;
agentError: boolean;
agentFinished: boolean;
terminalNeedsInput: boolean;
terminalFinished: boolean;
};
plugins: {
enabled: boolean;
muted: string[];
};
}
export const NotificationEventsPreferencesSchema = z.object({
agentPermission: z.boolean().optional(),
agentError: z.boolean().optional(),
agentFinished: z.boolean().optional(),
terminalNeedsInput: z.boolean().optional(),
terminalFinished: z.boolean().optional(),
});
export const NotificationPluginsPreferencesSchema = z.object({
enabled: z.boolean().optional(),
muted: z.array(z.string()).optional(),
});
export const NotificationPreferencesSchema = z.object({
enabled: z.boolean().optional(),
events: NotificationEventsPreferencesSchema.optional(),
plugins: NotificationPluginsPreferencesSchema.optional(),
});
export type NotificationPreferencesInput = z.infer<typeof NotificationPreferencesSchema>;
export const DEFAULT_NOTIFICATION_PREFERENCES: NotificationPreferences = {
enabled: true,
events: {
agentPermission: true,
agentError: true,
agentFinished: false,
terminalNeedsInput: true,
terminalFinished: false,
},
plugins: {
enabled: true,
muted: [],
},
};
export type NotificationKind =
| { kind: "agent"; reason: "permission" | "error" | "finished" }
| { kind: "terminal"; reason: "needs_input" | "finished" }
| { kind: "plugin"; pluginId: string };
export function normalizeNotificationPreferences(raw?: unknown): NotificationPreferences {
if (!raw || typeof raw !== "object") {
return {
enabled: DEFAULT_NOTIFICATION_PREFERENCES.enabled,
events: { ...DEFAULT_NOTIFICATION_PREFERENCES.events },
plugins: {
enabled: DEFAULT_NOTIFICATION_PREFERENCES.plugins.enabled,
muted: [...DEFAULT_NOTIFICATION_PREFERENCES.plugins.muted],
},
};
}
const candidate = raw as {
enabled?: unknown;
events?: unknown;
plugins?: unknown;
};
const eventsCandidate =
candidate.events && typeof candidate.events === "object"
? (candidate.events as Record<string, unknown>)
: {};
const pluginsCandidate =
candidate.plugins && typeof candidate.plugins === "object"
? (candidate.plugins as { enabled?: unknown; muted?: unknown })
: {};
const muted = Array.isArray(pluginsCandidate.muted)
? Array.from(
new Set(
pluginsCandidate.muted
.filter((item): item is string => typeof item === "string")
.map((item) => item.trim())
.filter((item) => item.length > 0),
),
).sort()
: [...DEFAULT_NOTIFICATION_PREFERENCES.plugins.muted];
return {
enabled:
typeof candidate.enabled === "boolean"
? candidate.enabled
: DEFAULT_NOTIFICATION_PREFERENCES.enabled,
events: {
agentPermission:
typeof eventsCandidate.agentPermission === "boolean"
? eventsCandidate.agentPermission
: DEFAULT_NOTIFICATION_PREFERENCES.events.agentPermission,
agentError:
typeof eventsCandidate.agentError === "boolean"
? eventsCandidate.agentError
: DEFAULT_NOTIFICATION_PREFERENCES.events.agentError,
agentFinished:
typeof eventsCandidate.agentFinished === "boolean"
? eventsCandidate.agentFinished
: DEFAULT_NOTIFICATION_PREFERENCES.events.agentFinished,
terminalNeedsInput:
typeof eventsCandidate.terminalNeedsInput === "boolean"
? eventsCandidate.terminalNeedsInput
: DEFAULT_NOTIFICATION_PREFERENCES.events.terminalNeedsInput,
terminalFinished:
typeof eventsCandidate.terminalFinished === "boolean"
? eventsCandidate.terminalFinished
: DEFAULT_NOTIFICATION_PREFERENCES.events.terminalFinished,
},
plugins: {
enabled:
typeof pluginsCandidate.enabled === "boolean"
? pluginsCandidate.enabled
: DEFAULT_NOTIFICATION_PREFERENCES.plugins.enabled,
muted,
},
};
}
export function shouldDeliverNotification(
prefs: NotificationPreferences,
target: NotificationKind,
): boolean {
if (!prefs.enabled) {
return false;
}
switch (target.kind) {
case "agent":
switch (target.reason) {
case "permission":
return prefs.events.agentPermission;
case "error":
return prefs.events.agentError;
case "finished":
return prefs.events.agentFinished;
}
break;
case "terminal":
switch (target.reason) {
case "needs_input":
return prefs.events.terminalNeedsInput;
case "finished":
return prefs.events.terminalFinished;
}
break;
case "plugin":
if (!prefs.plugins.enabled) {
return false;
}
return !prefs.plugins.muted.includes(target.pluginId);
}
}
@@ -1,6 +1,6 @@
{
"name": "react-native-enriched-markdown",
"version": "0.17.5",
"version": "0.17.6",
"private": true,
"description": "Markdown-based Rich Text solution for React Native",
"main": "./lib/module/index",
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@getpaseo/relay",
"version": "0.17.5",
"version": "0.17.6",
"description": "Paseo relay for bridging daemon and client connections",
"license": "Apache-2.0",
"files": [
+6 -6
View File
@@ -1,6 +1,6 @@
{
"name": "@getpaseo/server",
"version": "0.17.5",
"version": "0.17.6",
"description": "Paseo backend server",
"license": "Apache-2.0",
"files": [
@@ -109,11 +109,11 @@
"@agentclientprotocol/sdk": "^0.17.1",
"@anthropic-ai/claude-agent-sdk": "0.3.326",
"@anthropic-ai/sdk": "^0.104.2",
"@getpaseo/client": "0.17.5",
"@getpaseo/highlight": "0.17.5",
"@getpaseo/plugin": "0.17.5",
"@getpaseo/protocol": "0.17.5",
"@getpaseo/relay": "0.17.5",
"@getpaseo/client": "0.17.6",
"@getpaseo/highlight": "0.17.6",
"@getpaseo/plugin": "0.17.6",
"@getpaseo/protocol": "0.17.6",
"@getpaseo/relay": "0.17.6",
"@isaacs/ttlcache": "^2.1.4",
"@modelcontextprotocol/node": "2.1.2",
"@modelcontextprotocol/sdk": "1.29.0",
@@ -226,9 +226,9 @@ describe("computeNotificationPlan", () => {
});
describe("isPushEligibleAttentionReason", () => {
it("allows push for finished, permission, and error", () => {
it("allows push for finished and permission but not error", () => {
expect(isPushEligibleAttentionReason("finished")).toBe(true);
expect(isPushEligibleAttentionReason("permission")).toBe(true);
expect(isPushEligibleAttentionReason("error")).toBe(true);
expect(isPushEligibleAttentionReason("error")).toBe(false);
});
});
@@ -75,6 +75,6 @@ export function computeNotificationPlan({
return { inAppRecipientIndex: null, shouldPush: pushEligible };
}
export function isPushEligibleAttentionReason(_reason: AgentAttentionReason): boolean {
return true;
export function isPushEligibleAttentionReason(reason: AgentAttentionReason): boolean {
return reason !== "error";
}
@@ -29,8 +29,6 @@ import {
} from "./providers/codex-app-server-agent.js";
import { spawnProcess } from "../../utils/spawn.js";
import { createFakeCodexAppServer } from "./providers/codex/test-utils/fake-app-server.js";
import { PiRpcAgentClient } from "./providers/pi/agent.js";
import { FakePi } from "./providers/pi/test-utils/fake-pi.js";
import { InMemoryAgentTimelineStore } from "./agent-timeline-store.js";
import { limitAgentTimelineItemContent } from "./agent-timeline-content.js";
import { buildStoredAgentPayload, toAgentPayload } from "./agent-projections.js";
@@ -1773,51 +1771,6 @@ test("steers a tracked autonomous turn without creating a replacement run", asyn
}
});
test("steers a run Pi started by itself instead of aborting it", async () => {
const runtime = new FakePi();
const manager = new AgentManager({
clients: {
pi: new PiRpcAgentClient({
runtime,
logger,
runtimeSettings: { command: { mode: "replace", argv: [process.execPath] } },
}),
},
logger,
});
const workdir = mkdtempSync(join(tmpdir(), "agent-manager-pi-autonomous-steer-"));
let agentId: string | null = null;
try {
const agent = await manager.createAgent({ provider: "pi", cwd: workdir }, undefined, {
workspaceId: undefined,
});
agentId = agent.id;
const fakeSession = runtime.latestSession();
// An extension message or a process exit notice starts a run without a Paseo prompt.
fakeSession.emit({ type: "agent_start" });
fakeSession.emit({ type: "turn_start" });
await vi.waitFor(() =>
expect(manager.getAgent(agent.id)?.activeTurnId).toEqual(expect.any(String)),
);
const result = await startAgentRun(manager, agent.id, "message from another agent", logger, {
activeTurnBehavior: "steer",
replaceRunning: true,
});
expect(result).toEqual({ disposition: "steered" });
expect(fakeSession.steerCalls).toEqual([
{ message: "message from another agent", imageCount: 0 },
]);
expect(fakeSession.controlRequests).toEqual([]);
expect(fakeSession.prompts).toEqual([]);
} finally {
if (agentId) await manager.closeAgent(agentId).catch(() => undefined);
rmSync(workdir, { recursive: true, force: true });
}
});
test("isolated rewind falls back from steering to the normal replacement path", async () => {
const session = new SteeringTestSession({ provider: "claude", cwd: process.cwd() });
session.steerResult = "unavailable";
@@ -27,9 +27,6 @@ import { PiExtensionHost } from "./extensions/host.js";
import type { PiModel, PiThinkingLevel } from "./rpc-types.js";
import type { PiUsagePollScheduler } from "./usage-poller.js";
// A run Pi starts by itself carries the id the session assigns to it.
const AUTONOMOUS_TURN_ID = expect.stringMatching(/^autonomous-/);
const ONE_BY_ONE_PNG_BASE64 =
"iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+/p9sAAAAASUVORK5CYII=";
@@ -1134,15 +1131,13 @@ describe("PiRpcAgentSession", () => {
error: null,
},
]);
expect(events.turnLifecycleEvents()).toEqual([
{ type: "turn_started", turnId: AUTONOMOUS_TURN_ID },
]);
expect(events.turnLifecycleEvents()).toEqual([{ type: "turn_started", turnId: undefined }]);
fakeSession.settleTurn();
expect(events.turnLifecycleEvents()).toEqual([
{ type: "turn_started", turnId: AUTONOMOUS_TURN_ID },
{ type: "turn_completed", turnId: AUTONOMOUS_TURN_ID },
{ type: "turn_started", turnId: undefined },
{ type: "turn_completed", turnId: undefined },
]);
});
@@ -1226,14 +1221,12 @@ describe("PiRpcAgentSession", () => {
const stopping = session.interrupt();
await turnFinished.promise;
expect(events.turnLifecycleEvents()).toEqual([
{ type: "turn_started", turnId: AUTONOMOUS_TURN_ID },
]);
expect(events.turnLifecycleEvents()).toEqual([{ type: "turn_started", turnId: undefined }]);
abortFinished.resolve();
await stopping;
expect(events.turnLifecycleEvents()).toEqual([
{ type: "turn_started", turnId: AUTONOMOUS_TURN_ID },
{ type: "turn_canceled", turnId: AUTONOMOUS_TURN_ID },
{ type: "turn_started", turnId: undefined },
{ type: "turn_canceled", turnId: undefined },
]);
const { turnId } = await session.startTurn("follow-up");
@@ -1263,10 +1256,10 @@ describe("PiRpcAgentSession", () => {
fakeSession.finishTurn({ role: "assistant", stopReason: "stop", content: [] });
expect(events.turnLifecycleEvents()).toEqual([
{ type: "turn_started", turnId: AUTONOMOUS_TURN_ID },
{ type: "turn_completed", turnId: AUTONOMOUS_TURN_ID },
{ type: "turn_started", turnId: AUTONOMOUS_TURN_ID },
{ type: "turn_completed", turnId: AUTONOMOUS_TURN_ID },
{ type: "turn_started", turnId: undefined },
{ type: "turn_completed", turnId: undefined },
{ type: "turn_started", turnId: undefined },
{ type: "turn_completed", turnId: undefined },
]);
});
@@ -1292,8 +1285,8 @@ describe("PiRpcAgentSession", () => {
expect(events.turnLifecycleEvents()).toEqual([
{ type: "turn_started", turnId },
{ type: "turn_completed", turnId },
{ type: "turn_started", turnId: AUTONOMOUS_TURN_ID },
{ type: "turn_failed", turnId: AUTONOMOUS_TURN_ID },
{ type: "turn_started", turnId: undefined },
{ type: "turn_failed", turnId: undefined },
]);
});
@@ -1315,8 +1308,8 @@ describe("PiRpcAgentSession", () => {
await expect(session.interrupt()).rejects.toThrow("Pi process exited");
expect(events.turnLifecycleEvents()).toEqual([
{ type: "turn_started", turnId: AUTONOMOUS_TURN_ID },
{ type: "turn_failed", turnId: AUTONOMOUS_TURN_ID },
{ type: "turn_started", turnId: undefined },
{ type: "turn_failed", turnId: undefined },
]);
await expect(events.nextTurnFailure()).resolves.toMatchObject({ error: "Pi process exited" });
});
@@ -1338,7 +1331,7 @@ describe("PiRpcAgentSession", () => {
await expect(session.interrupt()).rejects.toThrow("Abort failed");
await expect(events.nextTurnFailure()).resolves.toMatchObject({
turnId: AUTONOMOUS_TURN_ID,
turnId: undefined,
error: expect.stringContaining("Provider disconnected"),
});
});
@@ -2239,11 +2232,11 @@ describe("PiRpcAgentSession", () => {
await expect(events.nextTurnFailure()).resolves.toMatchObject({
error: "Pi exited",
turnId: AUTONOMOUS_TURN_ID,
turnId: undefined,
});
expect(events.turnLifecycleEvents()).toEqual([
{ type: "turn_started", turnId: AUTONOMOUS_TURN_ID },
{ type: "turn_failed", turnId: AUTONOMOUS_TURN_ID },
{ type: "turn_started", turnId: undefined },
{ type: "turn_failed", turnId: undefined },
]);
});
@@ -2525,37 +2518,6 @@ describe("PiRpcAgentSession", () => {
});
describe("PiRpcAgentSession steering", () => {
test("steers a run Pi started by itself instead of refusing it", async () => {
const { pi, session, events } = await createSession();
const fakeSession = pi.latestSession();
fakeSession.emit({ type: "agent_start" });
fakeSession.emit({ type: "turn_start" });
const [started] = events.turnLifecycleEvents();
// The manager keeps a provider turn id and steers with it.
const result = await session.steerActiveTurn("join the running work", {
expectedTurnId: started?.turnId ?? "autonomous-assigned-by-manager",
});
expect(started?.turnId).toEqual(expect.any(String));
expect(result).toEqual({ status: "accepted" });
expect(fakeSession.steerCalls).toEqual([{ message: "join the running work", imageCount: 0 }]);
fakeSession.finishAgentRun({
message: { role: "assistant", stopReason: "stop", content: [{ type: "text", text: "done" }] },
willRetry: false,
});
fakeSession.settleTurn();
await flushTurnScheduling();
expect(events.turnCompletedEvents()).toEqual([
expect.objectContaining({ turnId: started?.turnId }),
]);
const idle = await session.steerActiveTurn("after the run", {
expectedTurnId: started?.turnId ?? "autonomous-assigned-by-manager",
});
expect(idle).toEqual({ status: "unavailable" });
});
test("steers the active Pi turn and correlates the echoed user message", async () => {
const { pi, session, events } = await createSession();
const fakeSession = pi.latestSession();
@@ -1194,9 +1194,6 @@ export class PiRpcAgentSession implements AgentSession {
private activeAssistantMessageId: string | null = null;
private activeTurnStarted = false;
private activeTurnStartedEmitted = false;
// A run Pi starts by itself (extension message, process exit notice, answered ask) has no
// Paseo turn. This id names it, so the manager can steer it like a Paseo turn.
private autonomousTurnId: string | null = null;
private pendingSettledMessages: PiAgentMessage[] | null = null;
private activeNoTurnPromptText: string | null = null;
private readonly pendingNoTurnOutputs: Array<{ turnId: string; message: string }> = [];
@@ -1321,7 +1318,6 @@ export class PiRpcAgentSession implements AgentSession {
this.activeAssistantMessageId = null;
this.activeTurnStarted = false;
this.activeTurnStartedEmitted = false;
this.autonomousTurnId = null;
this.pendingSettledMessages = null;
this.activePromptRequestId = null;
this.pendingSteerSubmissions.length = 0;
@@ -1368,7 +1364,6 @@ export class PiRpcAgentSession implements AgentSession {
this.activeClientMessageId = null;
this.activeTurnStarted = false;
this.activeTurnStartedEmitted = false;
this.autonomousTurnId = null;
this.pendingSettledMessages = null;
this.activeAssistantMessageId = null;
this.pendingSteerSubmissions.length = 0;
@@ -1398,11 +1393,11 @@ export class PiRpcAgentSession implements AgentSession {
prompt: AgentPromptInput,
options: SteerActiveTurnOptions,
): Promise<SteerResult> {
if (this.closed || this.currentTurnIdForEvent() !== options.expectedTurnId) {
if (this.closed || this.activeTurnId !== options.expectedTurnId) {
return { status: "unavailable" };
}
const payload = await convertPromptInput(prompt, { model: this.state.model });
if (this.closed || this.currentTurnIdForEvent() !== options.expectedTurnId)
if (this.closed || this.activeTurnId !== options.expectedTurnId)
return { status: "unavailable" };
// Pi rejects steer RPCs that are extension commands, so slash inputs keep the
// interrupt-and-replace fallback where they can run directly.
@@ -1420,7 +1415,7 @@ export class PiRpcAgentSession implements AgentSession {
}
// The steer is already queued inside pi; if the turn moved on meanwhile its fate
// is ambiguous, so surface it instead of replacing the wrong turn.
if (this.closed || this.currentTurnIdForEvent() !== options.expectedTurnId) {
if (this.closed || this.activeTurnId !== options.expectedTurnId) {
return { status: "unavailable" };
}
this.pendingSteerSubmissions.push({
@@ -1554,7 +1549,7 @@ export class PiRpcAgentSession implements AgentSession {
}
async interrupt(): Promise<void> {
const turnId = this.currentTurnIdForEvent();
const turnId = this.activeTurnId ?? undefined;
const interruption: typeof this.interruptingTurn =
this.activeTurnId || this.activeTurnStarted ? { turnId, error: null } : null;
this.interruptingTurn = interruption;
@@ -1580,7 +1575,6 @@ export class PiRpcAgentSession implements AgentSession {
this.activeClientMessageId = null;
this.activeTurnStarted = false;
this.activeTurnStartedEmitted = false;
this.autonomousTurnId = null;
this.pendingSettledMessages = null;
this.activeAssistantMessageId = null;
this.pendingSteerSubmissions.length = 0;
@@ -1598,14 +1592,13 @@ export class PiRpcAgentSession implements AgentSession {
interruption &&
this.interruptingTurn === interruption &&
(this.activeTurnId || this.activeTurnStarted) &&
this.currentTurnIdForEvent() === turnId
(this.activeTurnId ?? undefined) === turnId
) {
this.usagePoller.stopTurn();
this.activeTurnId = null;
this.activeClientMessageId = null;
this.activeTurnStarted = false;
this.activeTurnStartedEmitted = false;
this.autonomousTurnId = null;
this.pendingSettledMessages = null;
this.activeAssistantMessageId = null;
this.pendingSteerSubmissions.length = 0;
@@ -1789,13 +1782,7 @@ export class PiRpcAgentSession implements AgentSession {
}
private currentTurnIdForEvent(): string | undefined {
return this.activeTurnId ?? this.autonomousTurnId ?? undefined;
}
private claimAutonomousTurnId(): void {
if (!this.activeTurnId && !this.autonomousTurnId) {
this.autonomousTurnId = `autonomous-${randomUUID()}`;
}
return this.activeTurnId ?? undefined;
}
private async completeNoTurnPrompt(turnId: string): Promise<void> {
@@ -2223,13 +2210,12 @@ export class PiRpcAgentSession implements AgentSession {
if (!this.activeTurnId && !this.activeTurnStarted) {
return;
}
const turnId = this.currentTurnIdForEvent();
const turnId = this.activeTurnId ?? undefined;
this.usagePoller.stopTurn();
this.activeTurnId = null;
this.activeClientMessageId = null;
this.activeTurnStarted = false;
this.activeTurnStartedEmitted = false;
this.autonomousTurnId = null;
this.pendingSettledMessages = null;
this.pendingSteerSubmissions.length = 0;
this.clearNoTurnBuffers();
@@ -2260,7 +2246,6 @@ export class PiRpcAgentSession implements AgentSession {
return;
case "agent_start":
this.activeTurnStarted = true;
this.claimAutonomousTurnId();
this.clearNoTurnBuffers();
this.emit({
type: "thread_started",
@@ -2271,7 +2256,6 @@ export class PiRpcAgentSession implements AgentSession {
case "turn_start":
this.firstToken.requestSent(Date.now());
this.activeTurnStarted = true;
this.claimAutonomousTurnId();
this.clearNoTurnBuffers();
if (this.activeTurnStartedEmitted) {
return;
@@ -2280,7 +2264,7 @@ export class PiRpcAgentSession implements AgentSession {
this.emit({
type: "turn_started",
provider: this.provider,
turnId: this.currentTurnIdForEvent(),
turnId,
});
return;
case "message_start":
@@ -2602,7 +2586,6 @@ export class PiRpcAgentSession implements AgentSession {
this.activeAssistantMessageId = null;
this.activeTurnStarted = false;
this.activeTurnStartedEmitted = false;
this.autonomousTurnId = null;
this.pendingSettledMessages = null;
this.pendingSteerSubmissions.length = 0;
this.clearNoTurnBuffers();
@@ -404,7 +404,6 @@ const OUTBOUND_PERMISSION = {
"plugin.logs.get.response": "daemon.manage",
"plugin.reload.response": "daemon.manage",
"plugin.remove.response": "daemon.manage",
"plugin.notification": "workspace.read",
"plugin.rpc.invoke.response": "daemon.manage",
"plugin.rpc.subscribe.response": "daemon.manage",
"plugin.rpc.event": "daemon.manage",
+1 -3
View File
@@ -150,7 +150,7 @@ import { applyTerminalAgentHookSetting } from "../terminal/agent-hooks/terminal-
import { loadOrCreateDaemonKeyPair } from "./daemon-keypair.js";
import { createRelayRuntime, type RelayRuntime } from "./relay-runtime.js";
import { admitSecuredRelaySocket } from "./websocket/secure-relay-ingress.js";
import type { PushNotifications, PushNotificationSender } from "./push/index.js";
import type { PushNotificationSender } from "./push/index.js";
import { getOrCreateServerId } from "./server-id.js";
import { resolveDaemonVersion } from "./daemon-version.js";
import type { AgentClient, AgentProvider } from "./agent/agent-sdk-types.js";
@@ -443,7 +443,6 @@ export interface PaseoDaemonConfig {
log?: PersistedConfig["log"];
onLifecycleIntent?: (intent: DaemonLifecycleIntent) => void;
pushNotificationSender?: PushNotificationSender;
pushNotifications?: PushNotifications;
managedProcesses?: ManagedProcessRegistry;
configReload?: {
env: NodeJS.ProcessEnv;
@@ -1954,7 +1953,6 @@ export async function createPaseoDaemon(
orchestrationSkills,
workspaceLabelService,
workspaceArchiveOperations,
config.pushNotifications,
);
pluginRuntime.bindPaseoSessionHost(wsServer);
await pluginRuntime.start();
@@ -1,30 +1,16 @@
import { mkdtempSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import path from "node:path";
import pino from "pino";
import { afterEach, beforeEach, describe, expect, test } from "vitest";
import {
DEFAULT_NOTIFICATION_PREFERENCES,
type NotificationKind,
} from "@getpaseo/protocol/notification-preferences";
import { createTestPaseoDaemon, type TestPaseoDaemon } from "./test-utils/paseo-daemon.js";
import { DaemonClient } from "./test-utils/daemon-client.js";
import type { AgentStreamEventPayload } from "@getpaseo/protocol/messages";
import type { AgentSnapshotPayload } from "./messages.js";
import {
createPushNotifications,
type PushNotificationSender,
type PushPayload,
} from "./push/index.js";
import type { PushNotificationSender, PushPayload } from "./push/index.js";
import { PRESENCE_THRESHOLD_MS } from "./agent-attention-policy.js";
class RecordingPushNotificationSender implements PushNotificationSender {
readonly sent: PushPayload[] = [];
readonly sentWithKind: Array<{ payload: PushPayload; kind?: NotificationKind }> = [];
async send(payload: PushPayload, kind?: NotificationKind): Promise<void> {
async send(payload: PushPayload): Promise<void> {
this.sent.push(payload);
this.sentWithKind.push({ payload, kind });
}
}
@@ -71,7 +57,6 @@ describe("client activity tracking", () => {
messageQueueLimit: null,
});
await client.connect();
await client.observeEvents(["agent_attention_required"], { notifications: true }).ready;
return client;
}
@@ -712,123 +697,5 @@ describe("client activity tracking", () => {
expect(attention2.shouldNotify).toBe(false);
expect(pushNotifications.sent).toEqual([]);
}, 120000);
test("pushes error attention when clients are stale and filters per registered token preferences while preserving sidebar attention state", async () => {
await daemon.close();
const home = mkdtempSync(path.join(tmpdir(), "paseo-e2e-push-prefs-"));
try {
const deliveries: Array<{ tokens: string[]; payload: PushPayload }> = [];
const realPushNotifications = createPushNotifications({
logger: pino({ level: "silent" }),
filePath: path.join(home, "push-tokens.json"),
deliver: async (tokens, payload) => {
deliveries.push({ tokens, payload });
},
});
daemon = await createTestPaseoDaemon({
pushNotifications: realPushNotifications,
});
client1 = await createClient(); // Phone A
client2 = await createClient(); // Phone B
// Phone A wants agentFinished, mutes agentError
client1.registerPushToken("ExponentPushToken[phone-a]", {
...DEFAULT_NOTIFICATION_PREFERENCES,
events: {
...DEFAULT_NOTIFICATION_PREFERENCES.events,
agentFinished: true,
agentError: false,
},
});
// Phone B uses defaults (agentFinished: false, agentError: true)
client2.registerPushToken("ExponentPushToken[phone-b]", DEFAULT_NOTIFICATION_PREFERENCES);
const staleTime = new Date(Date.now() - PRESENCE_THRESHOLD_MS - 5_000).toISOString();
client1.sendHeartbeat({
deviceType: "mobile",
focusedAgentId: null,
lastActivityAt: staleTime,
appVisible: false,
});
client2.sendHeartbeat({
deviceType: "mobile",
focusedAgentId: null,
lastActivityAt: staleTime,
appVisible: false,
});
const finishedAgent = await createAgent({
client: client1,
title: "Finished Prefs Agent",
});
const finishedAttentionPromise = waitForAttentionRequired(client1, finishedAgent.id);
await client1.sendMessage(finishedAgent.id, "Say 'hello' and nothing else");
const finishedAttention = await finishedAttentionPromise;
expect(finishedAttention.reason).toBe("finished");
expect(finishedAttention.shouldNotify).toBe(false);
const errorAgent = await createAgent({
client: client1,
title: "Error Prefs Agent",
});
const errorAttentionPromise = waitForAttentionRequired(client1, errorAgent.id);
await client1.sendMessage(errorAgent.id, "Emit a turn failure");
const errorAttention = await errorAttentionPromise;
expect(errorAttention.reason).toBe("error");
expect(errorAttention.shouldNotify).toBe(false);
const summarizedDeliveries: Array<{
tokens: string[];
agentId: unknown;
reason: unknown;
}> = [];
for (const delivery of deliveries) {
summarizedDeliveries.push({
tokens: delivery.tokens,
agentId: delivery.payload.data.agentId,
reason: delivery.payload.data.reason,
});
}
expect(summarizedDeliveries).toEqual([
{
tokens: ["ExponentPushToken[phone-a]"],
agentId: finishedAgent.id,
reason: "finished",
},
{
tokens: ["ExponentPushToken[phone-b]"],
agentId: errorAgent.id,
reason: "error",
},
]);
// Sidebar attention state is unaffected by notification preferences.
const snapshots = await client1.fetchAgents();
let finishedSnapshot: AgentSnapshotPayload | undefined;
let errorSnapshot: AgentSnapshotPayload | undefined;
for (const entry of snapshots.entries) {
if (entry.agent.id === finishedAgent.id) {
finishedSnapshot = entry.agent;
}
if (entry.agent.id === errorAgent.id) {
errorSnapshot = entry.agent;
}
}
expect(finishedSnapshot).toMatchObject({
requiresAttention: true,
attentionReason: "finished",
});
expect(errorSnapshot).toMatchObject({
requiresAttention: true,
attentionReason: "error",
});
} finally {
rmSync(home, { recursive: true, force: true });
}
}, 120000);
});
});
@@ -1,227 +0,0 @@
import { describe, expect, it } from "vitest";
import {
MAX_PLUGIN_NOTIFICATION_BODY_CHARS,
MAX_PLUGIN_NOTIFICATION_DATA_BYTES,
MAX_PLUGIN_NOTIFICATION_KEY_CHARS,
MAX_PLUGIN_NOTIFICATION_OPEN_BYTES,
MAX_PLUGIN_NOTIFICATION_OPEN_ID_CHARS,
MAX_PLUGIN_NOTIFICATION_TITLE_CHARS,
PLUGIN_NOTIFICATION_BURST_CAPACITY,
PLUGIN_NOTIFICATION_DEDUP_WINDOW_MS,
PLUGIN_NOTIFICATION_REFILL_INTERVAL_MS,
PluginNotificationDispatcher,
type ValidatedPluginNotification,
} from "./notifications.js";
function createTestDispatcher(initialNowMs = 1_000_000) {
let nowMs = initialNowMs;
let nextId = 0;
const delivered: ValidatedPluginNotification[] = [];
const dispatcher = new PluginNotificationDispatcher({
now: () => nowMs,
createId: () => `notif-${++nextId}`,
deliver: (notification) => {
delivered.push(notification);
},
});
return {
dispatcher,
delivered,
advanceTime: (deltaMs: number) => {
nowMs += deltaMs;
},
};
}
describe("PluginNotificationDispatcher", () => {
it("validates title, body, key, open target, and 1024-byte JSON data limit", async () => {
const { dispatcher, delivered } = createTestDispatcher();
await expect(dispatcher.dispatch("plugin-a", { title: " ", body: "valid" })).rejects.toThrow(
"Plugin notification title is required",
);
await expect(
dispatcher.dispatch("plugin-a", {
title: "valid",
body: "valid",
key: "k".repeat(MAX_PLUGIN_NOTIFICATION_KEY_CHARS + 1),
}),
).rejects.toThrow(`must be 1 to ${MAX_PLUGIN_NOTIFICATION_KEY_CHARS} characters`);
await expect(
dispatcher.dispatch("plugin-a", {
title: "valid",
body: "valid",
open: { type: "agent", agentId: " " },
}),
).rejects.toThrow(
`open.agentId must be 1 to ${MAX_PLUGIN_NOTIFICATION_OPEN_ID_CHARS} characters`,
);
await expect(
dispatcher.dispatch("plugin-a", {
title: "valid",
body: "valid",
open: { type: "agent", agentId: "a".repeat(MAX_PLUGIN_NOTIFICATION_OPEN_ID_CHARS + 1) },
}),
).rejects.toThrow(
`open.agentId must be 1 to ${MAX_PLUGIN_NOTIFICATION_OPEN_ID_CHARS} characters`,
);
await expect(
dispatcher.dispatch("plugin-a", {
title: "valid",
body: "valid",
open: {
type: "screen",
screenId: "main",
params: { log: "z".repeat(MAX_PLUGIN_NOTIFICATION_OPEN_BYTES) },
},
}),
).rejects.toThrow(`open must not exceed ${MAX_PLUGIN_NOTIFICATION_OPEN_BYTES} UTF-8 bytes`);
await expect(
dispatcher.dispatch("plugin-a", {
title: "valid",
body: "valid",
open: { type: "screen", screenId: "main", params: { bad: 123 } },
}),
).rejects.toThrow("open.params must be an object of strings");
const oversizedData = {
blob: "a".repeat(MAX_PLUGIN_NOTIFICATION_DATA_BYTES),
};
await expect(
dispatcher.dispatch("plugin-a", {
title: "valid",
body: "valid",
data: oversizedData,
}),
).rejects.toThrow(`must not exceed ${MAX_PLUGIN_NOTIFICATION_DATA_BYTES} UTF-8 bytes`);
// Multibyte UTF-8 characters count by UTF-8 byte length, not JS string length
const multibyteOversized = {
emoji: "🚀".repeat(260), // 260 * 4 = 1040 UTF-8 bytes (> 1024)
};
await expect(
dispatcher.dispatch("plugin-a", {
title: "valid",
body: "valid",
data: multibyteOversized,
}),
).rejects.toThrow(`must not exceed ${MAX_PLUGIN_NOTIFICATION_DATA_BYTES} UTF-8 bytes`);
expect(delivered).toEqual([]);
const validResult = await dispatcher.dispatch("plugin-a", {
title: " Build finished ",
body: " All checks passed ",
key: " build:1 ",
open: { type: "screen", screenId: " report ", params: { buildId: "1" } },
data: { buildId: 1, ok: true },
});
expect(validResult).toEqual({ status: "sent", notificationId: "notif-1" });
expect(delivered).toEqual([
{
pluginId: "plugin-a",
notificationId: "notif-1",
title: "Build finished",
body: "All checks passed",
open: { type: "screen", screenId: "report", params: { buildId: "1" } },
data: { buildId: 1, ok: true },
},
]);
const longResult = await dispatcher.dispatch("plugin-a", {
title: "T".repeat(MAX_PLUGIN_NOTIFICATION_TITLE_CHARS + 50),
body: "Error stack line: ".repeat(120),
});
expect(longResult).toEqual({ status: "sent", notificationId: "notif-2" });
expect(delivered[1]?.title.length).toBe(MAX_PLUGIN_NOTIFICATION_TITLE_CHARS);
expect(delivered[1]?.title.endsWith("...")).toBe(true);
expect(delivered[1]?.body.length).toBeLessThanOrEqual(MAX_PLUGIN_NOTIFICATION_BODY_CHARS);
expect(delivered[1]?.body.endsWith("...")).toBe(true);
});
it("deduplicates identical (pluginId, key) within 60s and allows different plugins or expired keys", async () => {
const { dispatcher, delivered, advanceTime } = createTestDispatcher();
await expect(
dispatcher.dispatch("plugin-a", { title: "First", body: "1", key: "job-1" }),
).resolves.toEqual({ status: "sent", notificationId: "notif-1" });
// Same plugin + key within 60s -> deduplicated
advanceTime(PLUGIN_NOTIFICATION_DEDUP_WINDOW_MS - 1);
await expect(
dispatcher.dispatch("plugin-a", { title: "Duplicate", body: "2", key: "job-1" }),
).resolves.toEqual({ status: "deduplicated" });
// Different plugin with same key -> sent
await expect(
dispatcher.dispatch("plugin-b", { title: "Other plugin", body: "1", key: "job-1" }),
).resolves.toEqual({ status: "sent", notificationId: "notif-2" });
// After 60s window expires -> sent again
advanceTime(1);
await expect(
dispatcher.dispatch("plugin-a", { title: "After expiry", body: "3", key: "job-1" }),
).resolves.toEqual({ status: "sent", notificationId: "notif-3" });
// Clearing plugin state resets dedup immediately
await expect(
dispatcher.dispatch("plugin-a", { title: "Again", body: "4", key: "job-1" }),
).resolves.toEqual({ status: "deduplicated" });
dispatcher.clearPlugin("plugin-a");
await expect(
dispatcher.dispatch("plugin-a", { title: "After clear", body: "5", key: "job-1" }),
).resolves.toEqual({ status: "sent", notificationId: "notif-4" });
expect(delivered.map((item) => item.notificationId)).toEqual([
"notif-1",
"notif-2",
"notif-3",
"notif-4",
]);
});
it("enforces per-plugin token-bucket rate limit (burst 10, refill 1 per 6s)", async () => {
const { dispatcher, delivered, advanceTime } = createTestDispatcher();
for (let i = 1; i <= PLUGIN_NOTIFICATION_BURST_CAPACITY; i++) {
await expect(
dispatcher.dispatch("plugin-a", { title: `Msg ${i}`, body: "ok" }),
).resolves.toEqual({ status: "sent", notificationId: `notif-${i}` });
}
// 11th in burst -> rate_limited (and does not record dedup key)
await expect(
dispatcher.dispatch("plugin-a", {
title: "Overflow",
body: "blocked",
key: "overflow-key",
}),
).resolves.toEqual({ status: "rate_limited" });
// Another plugin has its own bucket
await expect(dispatcher.dispatch("plugin-b", { title: "Other", body: "ok" })).resolves.toEqual({
status: "sent",
notificationId: `notif-${PLUGIN_NOTIFICATION_BURST_CAPACITY + 1}`,
});
// Advance 6s -> 1 token refilled for plugin-a, and "overflow-key" was not burned
advanceTime(PLUGIN_NOTIFICATION_REFILL_INTERVAL_MS);
await expect(
dispatcher.dispatch("plugin-a", {
title: "Refilled",
body: "allowed",
key: "overflow-key",
}),
).resolves.toEqual({
status: "sent",
notificationId: `notif-${PLUGIN_NOTIFICATION_BURST_CAPACITY + 2}`,
});
expect(delivered).toHaveLength(PLUGIN_NOTIFICATION_BURST_CAPACITY + 2);
});
});
@@ -1,313 +0,0 @@
import { randomUUID } from "node:crypto";
import type {
PluginNotificationOpenTarget,
PluginNotificationSendResult,
} from "@getpaseo/plugin/server";
import type { JsonValue } from "@getpaseo/protocol/agent-types";
export const MAX_PLUGIN_NOTIFICATION_TITLE_CHARS = 160;
export const MAX_PLUGIN_NOTIFICATION_BODY_CHARS = 500;
export const MAX_PLUGIN_NOTIFICATION_KEY_CHARS = 128;
export const MAX_PLUGIN_NOTIFICATION_OPEN_ID_CHARS = 256;
export const MAX_PLUGIN_NOTIFICATION_OPEN_BYTES = 1024;
export const MAX_PLUGIN_NOTIFICATION_DATA_BYTES = 1024;
export const PLUGIN_NOTIFICATION_DEDUP_WINDOW_MS = 60_000;
export const MAX_DEDUP_KEYS_PER_PLUGIN = 512;
export const PLUGIN_NOTIFICATION_BURST_CAPACITY = 10;
export const PLUGIN_NOTIFICATION_REFILL_INTERVAL_MS = 6_000;
const ALLOWED_INPUT_KEYS = new Set(["title", "body", "key", "open", "data"]);
export interface NormalizedPluginNotificationInput {
title: string;
body: string;
key?: string;
open?: PluginNotificationOpenTarget;
data?: Record<string, JsonValue>;
}
export interface ValidatedPluginNotification {
pluginId: string;
notificationId: string;
title: string;
body: string;
open?: PluginNotificationOpenTarget;
data?: Record<string, JsonValue>;
}
function isPlainObject(value: unknown): value is Record<string, unknown> {
if (typeof value !== "object" || value === null || Array.isArray(value)) {
return false;
}
const proto = Object.getPrototypeOf(value);
return proto === Object.prototype || proto === null;
}
function isJsonValue(value: unknown, seen = new Set<object>()): value is JsonValue {
if (value === null || typeof value === "boolean" || typeof value === "string") {
return true;
}
if (typeof value === "number") {
return Number.isFinite(value);
}
if (typeof value !== "object") {
return false;
}
if (seen.has(value)) {
return false;
}
seen.add(value);
try {
if (Array.isArray(value)) {
return value.every((item) => isJsonValue(item, seen));
}
if (!isPlainObject(value)) {
return false;
}
return Object.values(value).every((item) => isJsonValue(item, seen));
} finally {
seen.delete(value);
}
}
function truncateText(text: string, maxChars: number): string {
if (text.length <= maxChars) {
return text;
}
const trimmed = text.slice(0, Math.max(0, maxChars - 3)).trimEnd();
return trimmed.length > 0 ? `${trimmed}...` : text.slice(0, maxChars);
}
function validateOpenTargetId(raw: unknown, field: string): string {
if (typeof raw !== "string") {
throw new Error(`Plugin notification ${field} must be a non-empty string`);
}
const trimmed = raw.trim();
if (!trimmed || trimmed.length > MAX_PLUGIN_NOTIFICATION_OPEN_ID_CHARS) {
throw new Error(
`Plugin notification ${field} must be 1 to ${MAX_PLUGIN_NOTIFICATION_OPEN_ID_CHARS} characters`,
);
}
return trimmed;
}
function validateOpenTarget(raw: unknown): PluginNotificationOpenTarget {
if (!isPlainObject(raw) || typeof raw.type !== "string") {
throw new Error("Invalid plugin notification open target");
}
let target: PluginNotificationOpenTarget;
if (raw.type === "agent") {
if (Object.keys(raw).some((key) => key !== "type" && key !== "agentId")) {
throw new Error("Plugin notification open.agentId must be a non-empty string");
}
target = { type: "agent", agentId: validateOpenTargetId(raw.agentId, "open.agentId") };
} else if (raw.type === "workspace") {
if (Object.keys(raw).some((key) => key !== "type" && key !== "workspaceId")) {
throw new Error("Plugin notification open.workspaceId must be a non-empty string");
}
target = {
type: "workspace",
workspaceId: validateOpenTargetId(raw.workspaceId, "open.workspaceId"),
};
} else if (raw.type === "screen") {
if (Object.keys(raw).some((key) => key !== "type" && key !== "screenId" && key !== "params")) {
throw new Error("Plugin notification open.screenId must be a non-empty string");
}
const screenId = validateOpenTargetId(raw.screenId, "open.screenId");
if (raw.params === undefined) {
target = { type: "screen", screenId };
} else {
if (!isPlainObject(raw.params)) {
throw new Error("Plugin notification open.params must be an object of strings");
}
const params: Record<string, string> = {};
for (const [key, value] of Object.entries(raw.params)) {
if (!key.trim() || typeof value !== "string") {
throw new Error("Plugin notification open.params must be an object of strings");
}
params[key] = value;
}
target = { type: "screen", screenId, params };
}
} else {
throw new Error(`Invalid plugin notification open target type: ${raw.type}`);
}
if (Buffer.byteLength(JSON.stringify(target), "utf8") > MAX_PLUGIN_NOTIFICATION_OPEN_BYTES) {
throw new Error(
`Plugin notification open must not exceed ${MAX_PLUGIN_NOTIFICATION_OPEN_BYTES} UTF-8 bytes`,
);
}
return target;
}
function validateNotificationKey(raw: unknown): string | undefined {
if (raw === undefined) {
return undefined;
}
if (typeof raw !== "string") {
throw new Error("Plugin notification key must be a string");
}
const trimmedKey = raw.trim();
if (!trimmedKey || trimmedKey.length > MAX_PLUGIN_NOTIFICATION_KEY_CHARS) {
throw new Error(
`Plugin notification key must be 1 to ${MAX_PLUGIN_NOTIFICATION_KEY_CHARS} characters`,
);
}
return trimmedKey;
}
function validateNotificationData(raw: unknown): Record<string, JsonValue> | undefined {
if (raw === undefined) {
return undefined;
}
if (!isPlainObject(raw) || !isJsonValue(raw)) {
throw new Error("Plugin notification data must be a plain JSON object");
}
const serialized = JSON.stringify(raw);
if (Buffer.byteLength(serialized, "utf8") > MAX_PLUGIN_NOTIFICATION_DATA_BYTES) {
throw new Error(
`Plugin notification data must not exceed ${MAX_PLUGIN_NOTIFICATION_DATA_BYTES} UTF-8 bytes`,
);
}
return JSON.parse(serialized) as Record<string, JsonValue>;
}
export function validatePluginNotificationSendInput(
raw: unknown,
): NormalizedPluginNotificationInput {
if (!isPlainObject(raw)) {
throw new Error("Plugin notification input must be an object");
}
for (const key of Object.keys(raw)) {
if (!ALLOWED_INPUT_KEYS.has(key)) {
throw new Error(`Unknown plugin notification field: ${key}`);
}
}
if (typeof raw.title !== "string" || !raw.title.trim()) {
throw new Error("Plugin notification title is required");
}
const title = truncateText(raw.title.trim(), MAX_PLUGIN_NOTIFICATION_TITLE_CHARS);
if (typeof raw.body !== "string") {
throw new Error("Plugin notification body must be a string");
}
const body = truncateText(raw.body.trim(), MAX_PLUGIN_NOTIFICATION_BODY_CHARS);
const key = validateNotificationKey(raw.key);
const open = raw.open !== undefined ? validateOpenTarget(raw.open) : undefined;
const data = validateNotificationData(raw.data);
return {
title,
body,
...(key !== undefined ? { key } : {}),
...(open !== undefined ? { open } : {}),
...(data !== undefined ? { data } : {}),
};
}
export class PluginNotificationDispatcher {
private readonly dedupByPlugin = new Map<string, Map<string, number>>();
private readonly bucketsByPlugin = new Map<string, { tokens: number; lastRefillMs: number }>();
private readonly now: () => number;
private readonly createId: () => string;
private readonly deliver: (notification: ValidatedPluginNotification) => void | Promise<void>;
constructor(options: {
deliver: (notification: ValidatedPluginNotification) => void | Promise<void>;
now?: () => number;
createId?: () => string;
}) {
this.deliver = options.deliver;
this.now = options.now ?? Date.now;
this.createId = options.createId ?? randomUUID;
}
async dispatch(pluginId: string, rawInput: unknown): Promise<PluginNotificationSendResult> {
const input = validatePluginNotificationSendInput(rawInput);
const nowMs = this.now();
if (input.key !== undefined) {
const dedup = this.dedupByPlugin.get(pluginId);
if (dedup) {
this.evictExpiredKeys(dedup, nowMs);
const expiresAt = dedup.get(input.key);
if (expiresAt !== undefined && expiresAt > nowMs) {
return { status: "deduplicated" };
}
}
}
if (!this.tryConsumeToken(pluginId, nowMs)) {
return { status: "rate_limited" };
}
if (input.key !== undefined) {
let dedup = this.dedupByPlugin.get(pluginId);
if (!dedup) {
dedup = new Map();
this.dedupByPlugin.set(pluginId, dedup);
} else {
this.evictExpiredKeys(dedup, nowMs);
}
while (dedup.size >= MAX_DEDUP_KEYS_PER_PLUGIN) {
const oldestKey = dedup.keys().next().value;
if (oldestKey === undefined) break;
dedup.delete(oldestKey);
}
dedup.set(input.key, nowMs + PLUGIN_NOTIFICATION_DEDUP_WINDOW_MS);
}
const notificationId = this.createId();
await this.deliver({
pluginId,
notificationId,
title: input.title,
body: input.body,
...(input.open ? { open: input.open } : {}),
...(input.data ? { data: input.data } : {}),
});
return { status: "sent", notificationId };
}
clearPlugin(pluginId: string): void {
this.dedupByPlugin.delete(pluginId);
this.bucketsByPlugin.delete(pluginId);
}
clearAll(): void {
this.dedupByPlugin.clear();
this.bucketsByPlugin.clear();
}
private evictExpiredKeys(dedup: Map<string, number>, nowMs: number): void {
for (const [key, expiresAt] of dedup) {
if (expiresAt <= nowMs) {
dedup.delete(key);
}
}
}
private tryConsumeToken(pluginId: string, nowMs: number): boolean {
let bucket = this.bucketsByPlugin.get(pluginId);
if (!bucket) {
bucket = {
tokens: PLUGIN_NOTIFICATION_BURST_CAPACITY,
lastRefillMs: nowMs,
};
this.bucketsByPlugin.set(pluginId, bucket);
} else {
const elapsedMs = Math.max(0, nowMs - bucket.lastRefillMs);
const refilled = elapsedMs / PLUGIN_NOTIFICATION_REFILL_INTERVAL_MS;
bucket.tokens = Math.min(PLUGIN_NOTIFICATION_BURST_CAPACITY, bucket.tokens + refilled);
bucket.lastRefillMs = nowMs;
}
if (bucket.tokens < 1) {
return false;
}
bucket.tokens -= 1;
return true;
}
}
@@ -1,336 +0,0 @@
import { mkdtemp, rm, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import path from "node:path";
import pino from "pino";
import { afterEach, describe, expect, test } from "vitest";
import {
DEFAULT_NOTIFICATION_PREFERENCES,
type NotificationPreferences,
} from "@getpaseo/protocol/notification-preferences";
import type { SessionOutboundMessage } from "@getpaseo/protocol/messages";
import { PRESENCE_THRESHOLD_MS } from "../agent-attention-policy.js";
import { resolveDaemonVersion } from "../daemon-version.js";
import { createPushNotifications, type PushPayload } from "../push/index.js";
import { DaemonClient } from "../test-utils/daemon-client.js";
import { createTestPaseoDaemon } from "../test-utils/paseo-daemon.js";
const roots: string[] = [];
afterEach(async () => {
await Promise.all(roots.splice(0).map((root) => rm(root, { recursive: true, force: true })));
});
async function writeNotificationPlugin(pluginId: string): Promise<string> {
const dir = await mkdtemp(path.join(tmpdir(), `paseo-${pluginId}-`));
roots.push(dir);
await writeFile(
path.join(dir, "paseo-plugin.json"),
JSON.stringify({
id: pluginId,
requirements: { paseo: `>=${resolveDaemonVersion(import.meta.url)}` },
}),
);
await writeFile(
path.join(dir, "index.server.ts"),
`import { defineRpc } from "@getpaseo/plugin";
import type {
PluginNotificationSendInput,
PluginServerContext,
} from "@getpaseo/plugin/server";
import { z } from "zod";
const sendRpc = defineRpc({
name: "notify",
input: z.unknown(),
output: z.unknown(),
});
export default function contribute(server: PluginServerContext) {
server.handle(sendRpc, async (input) => {
return await server.notifications.send(input as PluginNotificationSendInput);
});
return () => undefined;
}
`,
);
return dir;
}
describe("plugin notifications E2E", () => {
test("delivers in-app plugin.notification when client is present, suppresses when focused on target agent, and enforces dedup, rate limit, and 1024-byte data limit", async () => {
const home = await mkdtemp(path.join(tmpdir(), "paseo-plugin-notif-home-"));
roots.push(home);
const deliveries: Array<{ tokens: string[]; payload: PushPayload }> = [];
const pushNotifications = createPushNotifications({
logger: pino({ level: "silent" }),
filePath: path.join(home, "push-tokens.json"),
deliver: async (tokens, payload) => {
deliveries.push({ tokens, payload });
},
});
const daemon = await createTestPaseoDaemon({
pushNotifications,
});
const client = new DaemonClient({
url: `ws://127.0.0.1:${daemon.port}/ws`,
appVersion: "0.18.0",
});
try {
await client.connect();
expect(client.getLastServerInfoMessage()?.features?.pluginNotifications).toBe(true);
await client.patchDaemonConfig({ pluginsEnabled: true });
const pluginDir = await writeNotificationPlugin("ci-alerts");
await expect(client.installDirectoryPlugin(pluginDir)).resolves.toMatchObject({
id: "ci-alerts",
status: "running",
});
const received: Array<
Extract<SessionOutboundMessage, { type: "plugin.notification" }>["payload"]
> = [];
const feed = client.observeEvents(["plugin.notification"], { notifications: true });
feed.subscribe({
snapshot: () => undefined,
update: (message) => {
if (message.type === "plugin.notification") {
received.push(message.payload);
}
},
});
await feed.ready;
// Client is present and looking at agent-other -> shouldNotify: true, no push
client.sendHeartbeat({
deviceType: "web",
focusedAgentId: "agent-other",
lastActivityAt: new Date().toISOString(),
appVisible: true,
});
const first = (await client.invokePluginRpc("ci-alerts", "notify", {
title: "Build failed",
body: "Main branch check failed",
key: "build:101",
open: { type: "agent", agentId: "agent-target" },
data: { buildId: 101, branch: "main" },
})) as { status: string; notificationId?: string };
expect(first).toEqual({
status: "sent",
notificationId: expect.any(String),
});
await expect.poll(() => received.length).toBe(1);
expect(received[0]).toMatchObject({
pluginId: "ci-alerts",
notificationId: first.notificationId,
title: "Build failed",
body: "Main branch check failed",
open: { type: "agent", agentId: "agent-target" },
data: { buildId: 101, branch: "main" },
shouldNotify: true,
});
expect(deliveries).toEqual([]);
// Duplicate key within 60 s -> deduplicated, no new event emitted
const duplicate = await client.invokePluginRpc("ci-alerts", "notify", {
title: "Build failed again",
body: "Same key",
key: "build:101",
});
expect(duplicate).toEqual({ status: "deduplicated" });
expect(received).toHaveLength(1);
// Oversized data (> 1024 UTF-8 bytes) -> rejected over IPC via notification.error
await expect(
client.invokePluginRpc("ci-alerts", "notify", {
title: "Oversized",
body: "Too big",
data: { blob: "x".repeat(1025) },
}),
).rejects.toThrow("must not exceed 1024 UTF-8 bytes");
// Present client actively focused on open.agentId -> shouldNotify: false, no push
client.sendHeartbeat({
deviceType: "web",
focusedAgentId: "agent-target",
lastActivityAt: new Date().toISOString(),
appVisible: true,
});
const focusedSend = (await client.invokePluginRpc("ci-alerts", "notify", {
title: "Agent update",
body: "You are already watching this agent",
open: { type: "agent", agentId: "agent-target" },
})) as { status: string; notificationId?: string };
expect(focusedSend.status).toBe("sent");
await expect.poll(() => received.length).toBe(2);
expect(received[1]).toMatchObject({
notificationId: focusedSend.notificationId,
shouldNotify: false,
});
// Consume remaining 8 tokens in the 10-token burst bucket
for (let i = 3; i <= 10; i++) {
await expect(
client.invokePluginRpc("ci-alerts", "notify", {
title: `Burst ${i}`,
body: "Counting tokens",
}),
).resolves.toMatchObject({ status: "sent" });
}
await expect.poll(() => received.length).toBe(10);
// 11th notification in burst -> rate_limited
const rateLimited = await client.invokePluginRpc("ci-alerts", "notify", {
title: "Burst 11",
body: "Should be rate limited",
});
expect(rateLimited).toEqual({ status: "rate_limited" });
expect(received).toHaveLength(10);
await feed.release();
} finally {
await client.close().catch(() => undefined);
await daemon.close();
}
}, 60_000);
test("filters Expo push notifications per device token using two-knob preferences and per-plugin mute when away", async () => {
const home = await mkdtemp(path.join(tmpdir(), "paseo-plugin-push-home-"));
roots.push(home);
const deliveries: Array<{ tokens: string[]; payload: PushPayload }> = [];
const pushNotifications = createPushNotifications({
logger: pino({ level: "silent" }),
filePath: path.join(home, "push-tokens.json"),
deliver: async (tokens, payload) => {
deliveries.push({ tokens, payload });
},
});
const daemon = await createTestPaseoDaemon({
pushNotifications,
});
const client = new DaemonClient({
url: `ws://127.0.0.1:${daemon.port}/ws`,
appVersion: "0.18.0",
});
try {
await client.connect();
await client.patchDaemonConfig({ pluginsEnabled: true });
const alphaDir = await writeNotificationPlugin("plugin-alpha");
const betaDir = await writeNotificationPlugin("plugin-beta");
await client.installDirectoryPlugin(alphaDir);
await client.installDirectoryPlugin(betaDir);
// Token 1: master switch off -> blocks everything including plugins
const masterOffPrefs: NotificationPreferences = {
...DEFAULT_NOTIFICATION_PREFERENCES,
enabled: false,
};
client.registerPushToken("ExponentPushToken[master-off]", masterOffPrefs);
// Token 2: master on, all built-in events off, plugins on -> allows all non-muted plugins
const onlyPluginsPrefs: NotificationPreferences = {
enabled: true,
events: {
agentPermission: false,
agentError: false,
agentFinished: false,
terminalNeedsInput: false,
terminalFinished: false,
},
plugins: {
enabled: true,
muted: [],
},
};
client.registerPushToken("ExponentPushToken[only-plugins]", onlyPluginsPrefs);
// Token 3: master on, plugins on, plugin-alpha muted -> blocks plugin-alpha, allows plugin-beta
const mutedAlphaPrefs: NotificationPreferences = {
...DEFAULT_NOTIFICATION_PREFERENCES,
plugins: {
enabled: true,
muted: ["plugin-alpha"],
},
};
client.registerPushToken("ExponentPushToken[muted-alpha]", mutedAlphaPrefs);
// Token 4: master on, plugins off -> blocks all plugins
const pluginsOffPrefs: NotificationPreferences = {
...DEFAULT_NOTIFICATION_PREFERENCES,
plugins: {
enabled: false,
muted: [],
},
};
client.registerPushToken("ExponentPushToken[plugins-off]", pluginsOffPrefs);
// Mark client stale/away so daemon sends push notifications
const staleTime = new Date(Date.now() - PRESENCE_THRESHOLD_MS - 5_000).toISOString();
client.sendHeartbeat({
deviceType: "mobile",
focusedAgentId: null,
lastActivityAt: staleTime,
appVisible: false,
});
const alphaSend = (await client.invokePluginRpc("plugin-alpha", "notify", {
title: "Alpha alert",
body: "From alpha",
open: { type: "screen", screenId: "dashboard", params: { tab: "alerts" } },
data: { source: "alpha" },
})) as { status: string; notificationId: string };
expect(alphaSend.status).toBe("sent");
const betaSend = (await client.invokePluginRpc("plugin-beta", "notify", {
title: "Beta alert",
body: "From beta",
open: { type: "workspace", workspaceId: "wks_123" },
data: { source: "beta" },
})) as { status: string; notificationId: string };
expect(betaSend.status).toBe("sent");
await expect.poll(() => deliveries.length).toBe(2);
expect(deliveries[0]).toEqual({
tokens: ["ExponentPushToken[only-plugins]"],
payload: {
title: "Alpha alert",
body: "From alpha",
data: {
kind: "plugin",
serverId: expect.any(String),
pluginId: "plugin-alpha",
notificationId: alphaSend.notificationId,
open: { type: "screen", screenId: "dashboard", params: { tab: "alerts" } },
data: { source: "alpha" },
},
},
});
expect(deliveries[1]).toEqual({
tokens: ["ExponentPushToken[only-plugins]", "ExponentPushToken[muted-alpha]"],
payload: {
title: "Beta alert",
body: "From beta",
data: {
kind: "plugin",
serverId: expect.any(String),
pluginId: "plugin-beta",
notificationId: betaSend.notificationId,
open: { type: "workspace", workspaceId: "wks_123" },
data: { source: "beta" },
},
},
});
} finally {
await client.close().catch(() => undefined);
await daemon.close();
}
}, 60_000);
});
@@ -1,5 +1,5 @@
import type { JsonValue } from "@getpaseo/protocol/agent-types";
import type { PluginHookAgent, PluginNotificationSendResult } from "@getpaseo/plugin/server";
import type { PluginHookAgent } from "@getpaseo/plugin/server";
import { UsageScopeSchema, type UsageScope } from "@getpaseo/plugin/server/usage";
import type {
ProviderConnectRequest,
@@ -120,8 +120,6 @@ export type PluginProcessRequest =
input: ProviderInput;
}
| { type: "provider.close"; connectionId: string }
| { type: "notification.result"; requestId: string; result: PluginNotificationSendResult }
| { type: "notification.error"; requestId: string; error: string }
| { type: "shutdown" }
| { type: "paseo_frame"; data: string | Uint8Array; isBinary: boolean }
| { type: "paseo_close" };
@@ -164,7 +162,6 @@ export type PluginProcessMessage =
}
| { type: "provider.event"; connectionId: string; event: ProviderEvent }
| { type: "provider.closed"; connectionId: string; error?: string }
| { type: "notification.send"; requestId: string; input: unknown }
| { type: "paseo_frame"; data: string | Uint8Array; isBinary: boolean }
| { type: "paseo_close" };
@@ -382,29 +379,6 @@ export const PluginProcessRequestSchema: z.ZodType<PluginProcessRequest> = z.dis
})
.strict(),
z.object({ type: z.literal("provider.close"), connectionId: z.string().min(1) }).strict(),
z
.object({
type: z.literal("notification.result"),
requestId: z.string().min(1),
result: z.discriminatedUnion("status", [
z
.object({
status: z.literal("sent"),
notificationId: z.string().min(1),
})
.strict(),
z.object({ status: z.literal("deduplicated") }).strict(),
z.object({ status: z.literal("rate_limited") }).strict(),
]),
})
.strict(),
z
.object({
type: z.literal("notification.error"),
requestId: z.string().min(1),
error: z.string(),
})
.strict(),
z.object({ type: z.literal("shutdown") }).strict(),
z.object({ type: z.literal("paseo_frame"), ...frameFields }).strict(),
z.object({ type: z.literal("paseo_close") }).strict(),
@@ -505,13 +479,6 @@ export const PluginProcessMessageSchema: z.ZodType<PluginProcessMessage> = z.dis
error: z.string().optional(),
})
.strict(),
z
.object({
type: z.literal("notification.send"),
requestId: z.string().min(1),
input: z.unknown(),
})
.strict(),
z.object({ type: z.literal("paseo_frame"), ...frameFields }).strict(),
z.object({ type: z.literal("paseo_close") }).strict(),
],
@@ -14,9 +14,6 @@ import type {
} from "@getpaseo/plugin";
import type {
PluginHandlerContext,
PluginNotificationSendInput,
PluginNotificationSendResult,
PluginNotifications,
PluginServerContext,
PluginServerContribution,
PluginWorktreeCreateInput,
@@ -24,7 +21,6 @@ import type {
PluginWorktreeRestoreRequest,
WorktreeManagerRegistration,
} from "@getpaseo/plugin/server";
import { randomUUID } from "node:crypto";
import { assertPluginWireValue } from "@getpaseo/protocol/binary-frames/index";
import {
PluginSubscriptionHandlers,
@@ -131,13 +127,6 @@ export function createPluginWorker(options: {
>();
const pendingProviderConnections = new Map<string, { tombstoned: boolean }>();
const installationRequests = new Map<string, AbortController>();
const notificationRequests = new Map<
string,
{
resolve: (result: PluginNotificationSendResult) => void;
reject: (error: Error) => void;
}
>();
let cleanup: (() => void | Promise<void>) | null = null;
let daemonClient: DaemonClient | null = null;
let paseo: PaseoApi | null = null;
@@ -283,29 +272,6 @@ export function createPluginWorker(options: {
};
}
const notifications: PluginNotifications = {
send(input: PluginNotificationSendInput): Promise<PluginNotificationSendResult> {
if (stopping) {
return Promise.reject(new Error("Plugin is stopping"));
}
let payload: unknown;
try {
payload = jsonTransportValue(input);
} catch (error) {
return Promise.reject(error instanceof Error ? error : new Error(String(error)));
}
const requestId = randomUUID();
return new Promise<PluginNotificationSendResult>((resolve, reject) => {
notificationRequests.set(requestId, { resolve, reject });
send({
type: "notification.send",
requestId,
input: payload,
});
});
},
};
function providerMetadata(provider: ProviderRegistration) {
return {
id: provider.id,
@@ -518,7 +484,6 @@ export function createPluginWorker(options: {
registerUsageSource,
registerWorktreeManager,
registerSettings,
notifications,
addHook: hooks.addHook,
on: hooks.on,
before: hooks.before,
@@ -566,9 +531,6 @@ export function createPluginWorker(options: {
for (const request of installationRequests.values())
request.abort(new Error("Plugin is stopping"));
for (const request of worktreeRequests.values()) request.abort(new Error("Plugin is stopping"));
for (const pending of notificationRequests.values())
pending.reject(new Error("Plugin is stopping"));
notificationRequests.clear();
worktreeManager = null;
const currentCleanup = cleanup;
cleanup = null;
@@ -720,59 +682,6 @@ export function createPluginWorker(options: {
return handleInstallationMessage(message);
}
function handleNotificationMessage(
message: PluginProcessRequest,
): message is Extract<
PluginProcessRequest,
{ type: "notification.result" | "notification.error" }
> {
if (message.type !== "notification.result" && message.type !== "notification.error") {
return false;
}
const pending = notificationRequests.get(message.requestId);
if (!pending) return true;
notificationRequests.delete(message.requestId);
if (message.type === "notification.result") pending.resolve(message.result);
else pending.reject(new Error(message.error));
return true;
}
function handleProviderConnectOrSend(
message: PluginProcessRequest,
): message is Extract<
PluginProcessRequest,
{ type: "provider.connect" | "provider.send" | "provider.close" }
> {
if (message.type === "provider.connect") {
void connectProvider(message).catch((error) => {
if (stopping) return;
send({
type: "provider.connect_failed",
connectionId: message.connectionId,
error: describeError(error),
});
});
return true;
}
if (message.type === "provider.send") {
void sendProviderInput(message).catch((error) => {
if (stopping) return;
send({
type: "provider.rejected",
connectionId: message.connectionId,
acceptanceId: message.acceptanceId,
error: describeError(error),
});
});
return true;
}
if (message.type === "provider.close") {
void closeProviderConnection(message.connectionId);
return true;
}
return false;
}
function handleMessage(rawMessage: unknown): void {
const parsed = PluginProcessRequestSchema.safeParse(rawMessage);
if (!parsed.success) {
@@ -810,7 +719,6 @@ export function createPluginWorker(options: {
void shutdown();
return;
}
if (handleNotificationMessage(message)) return;
if (stopping) {
rejectWhileStopping(message);
return;
@@ -821,7 +729,33 @@ export function createPluginWorker(options: {
handleUsageRequest(message);
return;
}
if (handleProviderConnectOrSend(message)) return;
if (message.type === "provider.connect") {
void connectProvider(message).catch((error) => {
if (stopping) return;
send({
type: "provider.connect_failed",
connectionId: message.connectionId,
error: describeError(error),
});
});
return;
}
if (message.type === "provider.send") {
void sendProviderInput(message).catch((error) => {
if (stopping) return;
send({
type: "provider.rejected",
connectionId: message.connectionId,
acceptanceId: message.acceptanceId,
error: describeError(error),
});
});
return;
}
if (message.type === "provider.close") {
void closeProviderConnection(message.connectionId);
return;
}
if (message.type === "paseo_frame" || message.type === "paseo_close") return;
if (isHookMessage(message)) {
handleHookMessage(message);
@@ -2228,18 +2228,13 @@ const examples = (await readdir(examplesDirectory, { withFileTypes: true }))
.filter((entry) => entry.isDirectory() && entry.name !== "markdown-panel")
.map((entry) => entry.name);
const exampleDaemonVersions: Record<string, string> = {
"sidebar-views": "0.16.0",
notifications: "0.18.0-beta.1",
};
it.each(examples)("builds and loads the %s plugin example", async (example) => {
const settingsDirectory = await mkdtemp(path.join(tmpdir(), "paseo-example-settings-"));
temporaryDirectories.push(settingsDirectory);
const runtime = createTestRuntime(
{ settingsDirectory },
undefined,
exampleDaemonVersions[example] ?? resolveDaemonVersion(import.meta.url),
example === "sidebar-views" ? "0.16.0" : resolveDaemonVersion(import.meta.url),
);
try {
await runtime.startPlugin(example, path.join(examplesDirectory, example));

Some files were not shown because too many files have changed in this diff Show More