mirror of
https://github.com/getpaseo/paseo.git
synced 2026-11-27 02:35:31 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
39410ae7d0 | ||
|
|
e6f0ad272d | ||
|
|
02e4b8e3e9 | ||
|
|
203398fa44 | ||
|
|
21c2e55dd1 | ||
|
|
74c33b03d3 | ||
|
|
e4dc119df8 | ||
|
|
903b71180f | ||
|
|
4201a4de35 | ||
|
|
3c0553d9db | ||
|
|
2be71aedcb | ||
|
|
a27f0819c8 | ||
|
|
46eb98d604 | ||
|
|
7d3e045ff8 | ||
|
|
20b70e37e7 | ||
|
|
fcac35d3b9 | ||
|
|
2636c4384f | ||
|
|
17c08edccf | ||
|
|
0687c370ec | ||
|
|
a7dbeadd5f |
@@ -1,29 +1,5 @@
|
||||
# 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))
|
||||
|
||||
@@ -1,29 +1,5 @@
|
||||
# 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))
|
||||
|
||||
+12
-2
@@ -10,10 +10,20 @@ 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. Notification generation, presence, and push
|
||||
eligibility remain daemon concerns.
|
||||
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.
|
||||
|
||||
## Native delivery
|
||||
|
||||
|
||||
+21
-1
@@ -1,7 +1,7 @@
|
||||
# Plugins
|
||||
|
||||
Local plugins contribute daemon RPCs, native app surfaces, workspace panels, Command Center items,
|
||||
client slash commands, timeline items, header buttons, composer pills, app themes, composer attachment sources, and settings screens.
|
||||
client slash commands, timeline items, notifications, 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,6 +549,26 @@ 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
|
||||
|
||||
@@ -1,12 +0,0 @@
|
||||
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,12 +0,0 @@
|
||||
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,12 +0,0 @@
|
||||
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,12 +0,0 @@
|
||||
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
@@ -1 +1 @@
|
||||
sha256-6XXAVBTH6rIdg5eQ9cUeUwV22ikVqTtdWo7i9DYO+/M=
|
||||
sha256-B2hX/4xDGTtFC2LBRL/0US3YERfM/cDXvu8cjztpsd8=
|
||||
|
||||
Generated
+29
-29
@@ -1,12 +1,12 @@
|
||||
{
|
||||
"name": "paseo",
|
||||
"version": "0.17.6",
|
||||
"version": "0.17.5",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "paseo",
|
||||
"version": "0.17.6",
|
||||
"version": "0.17.5",
|
||||
"hasInstallScript": true,
|
||||
"license": "Apache-2.0",
|
||||
"workspaces": [
|
||||
@@ -37541,7 +37541,7 @@
|
||||
},
|
||||
"packages/app": {
|
||||
"name": "@getpaseo/app",
|
||||
"version": "0.17.6",
|
||||
"version": "0.17.5",
|
||||
"dependencies": {
|
||||
"@codemirror/commands": "6.10.4",
|
||||
"@codemirror/language": "6.12.4",
|
||||
@@ -39694,13 +39694,13 @@
|
||||
},
|
||||
"packages/cli": {
|
||||
"name": "@getpaseo/cli",
|
||||
"version": "0.17.6",
|
||||
"version": "0.17.5",
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"@clack/prompts": "^1.0.0",
|
||||
"@getpaseo/client": "0.17.6",
|
||||
"@getpaseo/protocol": "0.17.6",
|
||||
"@getpaseo/server": "0.17.6",
|
||||
"@getpaseo/client": "0.17.5",
|
||||
"@getpaseo/protocol": "0.17.5",
|
||||
"@getpaseo/server": "0.17.5",
|
||||
"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.6",
|
||||
"version": "0.17.5",
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"@getpaseo/protocol": "0.17.6",
|
||||
"@getpaseo/relay": "0.17.6",
|
||||
"@getpaseo/protocol": "0.17.5",
|
||||
"@getpaseo/relay": "0.17.5",
|
||||
"ws": "^8.20.0",
|
||||
"zod": "^4.4.3"
|
||||
},
|
||||
@@ -39963,7 +39963,7 @@
|
||||
},
|
||||
"packages/desktop": {
|
||||
"name": "@getpaseo/desktop",
|
||||
"version": "0.17.6",
|
||||
"version": "0.17.5",
|
||||
"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.6",
|
||||
"version": "0.17.5",
|
||||
"license": "MIT",
|
||||
"devDependencies": {
|
||||
"@types/jest": "^29.5.14",
|
||||
@@ -40252,7 +40252,7 @@
|
||||
},
|
||||
"packages/highlight": {
|
||||
"name": "@getpaseo/highlight",
|
||||
"version": "0.17.6",
|
||||
"version": "0.17.5",
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"@codemirror/language": "6.12.4",
|
||||
@@ -40282,7 +40282,7 @@
|
||||
},
|
||||
"packages/plugin": {
|
||||
"name": "@getpaseo/plugin",
|
||||
"version": "0.17.6",
|
||||
"version": "0.17.5",
|
||||
"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.6",
|
||||
"@getpaseo/protocol": "0.17.6",
|
||||
"@getpaseo/client": "0.17.5",
|
||||
"@getpaseo/protocol": "0.17.5",
|
||||
"@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.6",
|
||||
"@getpaseo/protocol": "0.17.6",
|
||||
"@getpaseo/client": "0.17.5",
|
||||
"@getpaseo/protocol": "0.17.5",
|
||||
"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.6",
|
||||
"version": "0.17.5",
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"semver": "^7.8.5",
|
||||
@@ -40351,7 +40351,7 @@
|
||||
}
|
||||
},
|
||||
"packages/react-native-enriched-markdown": {
|
||||
"version": "0.17.6",
|
||||
"version": "0.17.5",
|
||||
"hasInstallScript": true,
|
||||
"license": "MIT",
|
||||
"peerDependencies": {
|
||||
@@ -40367,7 +40367,7 @@
|
||||
},
|
||||
"packages/relay": {
|
||||
"name": "@getpaseo/relay",
|
||||
"version": "0.17.6",
|
||||
"version": "0.17.5",
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"@noble/ciphers": "^2.4.0",
|
||||
@@ -40589,17 +40589,17 @@
|
||||
},
|
||||
"packages/server": {
|
||||
"name": "@getpaseo/server",
|
||||
"version": "0.17.6",
|
||||
"version": "0.17.5",
|
||||
"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.6",
|
||||
"@getpaseo/highlight": "0.17.6",
|
||||
"@getpaseo/plugin": "0.17.6",
|
||||
"@getpaseo/protocol": "0.17.6",
|
||||
"@getpaseo/relay": "0.17.6",
|
||||
"@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",
|
||||
"@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.6",
|
||||
"version": "0.17.5",
|
||||
"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.6",
|
||||
"version": "0.17.5",
|
||||
"dependencies": {
|
||||
"@getpaseo/plugin": "*",
|
||||
"zod": "^4.4.3"
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "paseo",
|
||||
"version": "0.17.6",
|
||||
"version": "0.17.5",
|
||||
"private": true,
|
||||
"description": "Paseo: voice-controlled development environment for local AI coding agents",
|
||||
"keywords": [
|
||||
|
||||
@@ -0,0 +1,245 @@
|
||||
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: ";
|
||||
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();
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,269 @@
|
||||
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,6 +32,12 @@ 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,6 +1,6 @@
|
||||
{
|
||||
"name": "@getpaseo/app",
|
||||
"version": "0.17.6",
|
||||
"version": "0.17.5",
|
||||
"private": true,
|
||||
"main": "index.ts",
|
||||
"scripts": {
|
||||
|
||||
@@ -0,0 +1,117 @@
|
||||
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);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,104 @@
|
||||
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;
|
||||
}
|
||||
@@ -0,0 +1,311 @@
|
||||
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],
|
||||
},
|
||||
}));
|
||||
@@ -1,6 +1,7 @@
|
||||
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";
|
||||
@@ -11,21 +12,22 @@ 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 {
|
||||
buildAgentAttentionNotificationPayload,
|
||||
type AgentAttentionReason,
|
||||
type AgentAttentionNotificationPayload,
|
||||
type NotificationPermissionRequest,
|
||||
} from "@getpaseo/protocol/agent-attention-notification";
|
||||
deliverAgentAttentionOsNotification,
|
||||
deliverPluginOsNotification,
|
||||
deliverTerminalAttentionOsNotification,
|
||||
getCurrentNotificationPreferences,
|
||||
} from "./session-notifications";
|
||||
|
||||
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";
|
||||
@@ -33,10 +35,9 @@ import {
|
||||
selectAgentTimelineState,
|
||||
toDaemonServerInfo,
|
||||
useSessionStore,
|
||||
type SessionState,
|
||||
} from "@/stores/session-store";
|
||||
import { sendOsNotification } from "@/utils/os-notifications";
|
||||
import { getIsAppActivelyVisible, getIsAppVisible } from "@/utils/app-visibility";
|
||||
import { getIsAppVisible } from "@/utils/app-visibility";
|
||||
import {
|
||||
getInitKey,
|
||||
getInitDeferred,
|
||||
@@ -98,71 +99,6 @@ 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,
|
||||
@@ -202,6 +138,10 @@ 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
|
||||
@@ -251,7 +191,10 @@ function SessionProviderInternal({ children, serverId, client }: SessionProvider
|
||||
focusedAgentId,
|
||||
focusedTerminalId,
|
||||
});
|
||||
useEffect(() => startPushNotifications({ client, serverId }), [client, serverId]);
|
||||
useEffect(
|
||||
() => startPushNotifications({ client, serverId, queryClient }),
|
||||
[client, queryClient, serverId],
|
||||
);
|
||||
|
||||
const notifyAgentAttention = useCallback(
|
||||
(params: {
|
||||
@@ -260,52 +203,17 @@ function SessionProviderInternal({ children, serverId, client }: SessionProvider
|
||||
timestamp: string;
|
||||
notification?: AgentAttentionNotificationPayload;
|
||||
}) => {
|
||||
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,
|
||||
deliverAgentAttentionOsNotification({
|
||||
serverId,
|
||||
workspaceId,
|
||||
agentId: params.agentId,
|
||||
assistantMessage,
|
||||
permissionRequest,
|
||||
});
|
||||
if (!notification) {
|
||||
return;
|
||||
}
|
||||
|
||||
void sendOsNotification({
|
||||
title: notification.title,
|
||||
body: notification.body,
|
||||
data: notification.data,
|
||||
params,
|
||||
appState: appStateRef.current,
|
||||
session: useSessionStore.getState().sessions[serverId],
|
||||
attentionNotified: attentionNotifiedRef.current,
|
||||
preferences: getCurrentNotificationPreferences(queryClient),
|
||||
sendNotification: sendOsNotification,
|
||||
});
|
||||
},
|
||||
[serverId],
|
||||
[queryClient, serverId],
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
@@ -647,20 +555,11 @@ function SessionProviderInternal({ children, serverId, client }: SessionProvider
|
||||
if (message.type !== "terminal_attention_required") {
|
||||
return;
|
||||
}
|
||||
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 } : {}),
|
||||
},
|
||||
deliverTerminalAttentionOsNotification({
|
||||
serverId,
|
||||
payload: message.payload,
|
||||
preferences: getCurrentNotificationPreferences(queryClient),
|
||||
sendNotification: sendOsNotification,
|
||||
});
|
||||
});
|
||||
|
||||
@@ -698,6 +597,41 @@ 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) {
|
||||
|
||||
@@ -0,0 +1,376 @@
|
||||
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 },
|
||||
},
|
||||
},
|
||||
]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,235 @@
|
||||
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() {
|
||||
export function DesktopNotificationsSection({ title }: { title?: string } = {}) {
|
||||
const { t } = useTranslation();
|
||||
const { settings, isSaving, updateSettings } = useDesktopSettings();
|
||||
const {
|
||||
@@ -85,7 +85,10 @@ export function DesktopNotificationsSection() {
|
||||
const notificationsGranted = snapshot?.notifications.state === "granted";
|
||||
|
||||
return (
|
||||
<SettingsSection title={t("settings.notifications.title")} trailing={refreshButton}>
|
||||
<SettingsSection
|
||||
title={title ?? t("settings.notifications.desktop.title")}
|
||||
trailing={refreshButton}
|
||||
>
|
||||
<View style={settingsStyles.card}>
|
||||
<DesktopPermissionRow
|
||||
title={t("settings.notifications.permission")}
|
||||
|
||||
@@ -55,6 +55,10 @@ import {
|
||||
type WorkspaceTitleSource,
|
||||
} from "./storage";
|
||||
|
||||
export {
|
||||
DEFAULT_NOTIFICATION_PREFERENCES,
|
||||
type NotificationPreferences,
|
||||
} from "@getpaseo/protocol/notification-preferences";
|
||||
export {
|
||||
APP_SETTINGS_KEY,
|
||||
DEFAULT_APP_SETTINGS,
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
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,
|
||||
@@ -1213,3 +1214,68 @@ 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,5 +1,10 @@
|
||||
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";
|
||||
@@ -116,6 +121,7 @@ export interface AppSettings {
|
||||
/** Desktop-only preferences for implicit opens into the ordinary side pane. */
|
||||
openInSidePane: OpenInSidePanePreferences;
|
||||
pullRequestOpenLocation: PullRequestOpenLocation;
|
||||
notifications: NotificationPreferences;
|
||||
}
|
||||
|
||||
export type AppSettingsUpdate =
|
||||
@@ -173,6 +179,7 @@ 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 = {
|
||||
@@ -302,6 +309,10 @@ 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.
|
||||
|
||||
@@ -2476,6 +2476,47 @@ 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: "تشغيل صوت",
|
||||
|
||||
@@ -2508,6 +2508,48 @@ 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",
|
||||
|
||||
@@ -2496,6 +2496,49 @@ 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",
|
||||
|
||||
@@ -2495,6 +2495,50 @@ 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",
|
||||
|
||||
@@ -2465,6 +2465,48 @@ 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: "サウンドを再生",
|
||||
|
||||
@@ -2452,6 +2452,47 @@ 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: "소리 재생",
|
||||
|
||||
@@ -2480,6 +2480,50 @@ 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",
|
||||
|
||||
@@ -2481,6 +2481,49 @@ 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: "Воспроизводить звук",
|
||||
|
||||
@@ -2416,6 +2416,47 @@ 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,6 +52,26 @@ 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,3 +1,5 @@
|
||||
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";
|
||||
|
||||
@@ -6,6 +8,14 @@ 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 {
|
||||
@@ -13,10 +23,59 @@ 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 (typeof data !== "object" || data === null || Array.isArray(data)) return null;
|
||||
if (!isPlainRecord(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 };
|
||||
@@ -30,6 +89,9 @@ 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>;
|
||||
}
|
||||
|
||||
@@ -45,6 +107,12 @@ 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,16 +1,31 @@
|
||||
import { useEffect } from "react";
|
||||
import { router, usePathname, useRootNavigationState, type Href } from "expo-router";
|
||||
import { useHostRegistryStatus } from "@/runtime/host-runtime";
|
||||
import { openPluginNotification } from "@/plugins/notification-open";
|
||||
import { pluginRegistry } from "@/plugins/registry";
|
||||
import { getHostRuntimeStore, 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 }),
|
||||
@@ -20,6 +35,18 @@ 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,6 +37,7 @@ function installation(): InstalledPlugin {
|
||||
themes: [],
|
||||
timelineTransformers: [],
|
||||
timelineRenderers: [],
|
||||
notificationOpenHandlers: [],
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -7,6 +7,7 @@ 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";
|
||||
@@ -391,13 +392,22 @@ 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 () => {
|
||||
const h = await connected();
|
||||
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 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);
|
||||
});
|
||||
@@ -504,3 +514,55 @@ 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"]);
|
||||
});
|
||||
|
||||
@@ -8,11 +8,13 @@ interface CatalogSyncInput {
|
||||
client: DaemonClient;
|
||||
audio: Pick<AudioEngine, "play"> | null;
|
||||
connected: boolean;
|
||||
supported: boolean;
|
||||
/** `null` while `server_info` has not yet arrived for this host. */
|
||||
supported: boolean | null;
|
||||
registry: Pick<
|
||||
PluginRegistry,
|
||||
"installCatalog" | "getSnapshot" | "removeHost" | "setCatalogStatus"
|
||||
>;
|
||||
onCatalogChanged?: () => void;
|
||||
}
|
||||
|
||||
export function syncPluginCatalog({
|
||||
@@ -22,7 +24,13 @@ 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");
|
||||
@@ -88,6 +96,7 @@ export function syncPluginCatalog({
|
||||
}
|
||||
}
|
||||
if (message.payload.status === "plugin_catalog_changed") {
|
||||
onCatalogChanged?.();
|
||||
const pluginId = message.payload.pluginId;
|
||||
if (typeof pluginId === "string") void refresh(pluginId);
|
||||
}
|
||||
|
||||
@@ -1,8 +1,10 @@
|
||||
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 { useHostFeature } from "@/runtime/host-features";
|
||||
import { useHostFeatureAvailability } 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";
|
||||
|
||||
@@ -15,7 +17,8 @@ export function PluginCatalogSync({
|
||||
}) {
|
||||
const audio = useVoiceAudioEngineOptional();
|
||||
const connected = useHostRuntimeIsConnected(serverId);
|
||||
const supported = useHostFeature(serverId, "plugins");
|
||||
const supported = useHostFeatureAvailability(serverId, "plugins");
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
useEffect(
|
||||
() =>
|
||||
@@ -26,8 +29,11 @@ export function PluginCatalogSync({
|
||||
connected,
|
||||
supported,
|
||||
registry: pluginRegistry,
|
||||
onCatalogChanged: () => {
|
||||
void queryClient.invalidateQueries({ queryKey: pluginListQueryKey(serverId) });
|
||||
},
|
||||
}),
|
||||
[audio, client, connected, serverId, supported],
|
||||
[audio, client, connected, queryClient, serverId, supported],
|
||||
);
|
||||
|
||||
useEffect(() => () => pluginRegistry.removeHost(serverId), [serverId]);
|
||||
|
||||
@@ -148,6 +148,7 @@ function plugin(onAgentSelect: AgentCommandItem["onSelect"]): InstalledPlugin {
|
||||
themes: [],
|
||||
timelineTransformers: [],
|
||||
timelineRenderers: [],
|
||||
notificationOpenHandlers: [],
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -58,6 +58,7 @@ function installed(): InstalledPlugin {
|
||||
themes: [],
|
||||
timelineTransformers: [],
|
||||
timelineRenderers: [],
|
||||
notificationOpenHandlers: [],
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -68,6 +68,7 @@ function plugin(): InstalledPlugin {
|
||||
themes: [],
|
||||
timelineTransformers: [],
|
||||
timelineRenderers: [],
|
||||
notificationOpenHandlers: [],
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -110,6 +110,7 @@ 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() {}),
|
||||
];
|
||||
`),
|
||||
{
|
||||
@@ -141,6 +142,7 @@ describe("evaluatePluginClientBundle", () => {
|
||||
plugin.themes,
|
||||
plugin.timelineTransformers,
|
||||
plugin.timelineRenderers,
|
||||
plugin.notificationOpenHandlers,
|
||||
].every((items) => items.length === 1),
|
||||
).toBe(true);
|
||||
expect(pillCount).toBe(1);
|
||||
@@ -162,6 +164,7 @@ describe("evaluatePluginClientBundle", () => {
|
||||
plugin.themes,
|
||||
plugin.timelineTransformers,
|
||||
plugin.timelineRenderers,
|
||||
plugin.notificationOpenHandlers,
|
||||
].every((items) => items.length === 0),
|
||||
).toBe(true);
|
||||
expect(pillCount).toBe(0);
|
||||
|
||||
@@ -24,6 +24,7 @@ import {
|
||||
type PluginSurfaceProps,
|
||||
type PluginTimelineRendererContribution,
|
||||
type PluginTimelineTransformerContribution,
|
||||
type PluginNotificationOpenHandler,
|
||||
type PluginButtonRegistration,
|
||||
} from "@getpaseo/plugin/client";
|
||||
import type {
|
||||
@@ -145,6 +146,7 @@ export function runPluginClientBundle(
|
||||
themes: [],
|
||||
timelineTransformers: [],
|
||||
timelineRenderers: [],
|
||||
notificationOpenHandlers: [],
|
||||
};
|
||||
const surfaceIds = new Set<string>();
|
||||
const sidebarViewIds = new Set<string>();
|
||||
@@ -565,6 +567,12 @@ 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));
|
||||
@@ -665,5 +673,6 @@ export function runPluginClientBundle(
|
||||
themes: collector.themes,
|
||||
timelineTransformers: collector.timelineTransformers,
|
||||
timelineRenderers: collector.timelineRenderers,
|
||||
notificationOpenHandlers: collector.notificationOpenHandlers,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -61,6 +61,7 @@ function installation(invoked: string[]): InstalledPlugin {
|
||||
themes: [],
|
||||
timelineTransformers: [],
|
||||
timelineRenderers: [],
|
||||
notificationOpenHandlers: [],
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,344 @@
|
||||
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" }]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,223 @@
|
||||
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);
|
||||
}
|
||||
@@ -1,7 +1,13 @@
|
||||
import { useMemo } from "react";
|
||||
import type { PluginListItem } from "@getpaseo/protocol/messages";
|
||||
import { useFetchQuery } from "@/data/query";
|
||||
import { useHostFeature } from "@/runtime/host-features";
|
||||
import { useHostRuntimeClient, useHostRuntimeIsConnected } from "@/runtime/host-runtime";
|
||||
import { useFetchQueries, useFetchQuery } from "@/data/query";
|
||||
import { useHostFeature, useHostFeatureMap } from "@/runtime/host-features";
|
||||
import {
|
||||
getHostRuntimeStore,
|
||||
useHostRuntimeClient,
|
||||
useHostRuntimeIsConnected,
|
||||
useHosts,
|
||||
} from "@/runtime/host-runtime";
|
||||
|
||||
export function pluginListQueryKey(serverId: string) {
|
||||
return ["plugins", serverId] as const;
|
||||
@@ -38,3 +44,38 @@ 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],
|
||||
);
|
||||
}
|
||||
|
||||
@@ -136,6 +136,7 @@ export class PluginRegistry {
|
||||
themes: [],
|
||||
timelineTransformers: [],
|
||||
timelineRenderers: [],
|
||||
notificationOpenHandlers: [],
|
||||
};
|
||||
const unsubscribeTranslations = installation.i18n.subscribe(() => this.publish());
|
||||
installation.lifetime.signal.addEventListener("abort", unsubscribeTranslations, {
|
||||
|
||||
@@ -48,6 +48,7 @@ function installed(
|
||||
themes: [],
|
||||
timelineTransformers: [],
|
||||
timelineRenderers: [],
|
||||
notificationOpenHandlers: [],
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -67,6 +67,7 @@ function installation(
|
||||
themes: [],
|
||||
timelineTransformers: [],
|
||||
timelineRenderers: [],
|
||||
notificationOpenHandlers: [],
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -81,6 +81,7 @@ function installed(serverId: string, themes: PluginThemeContribution[]): Install
|
||||
themes,
|
||||
timelineTransformers: [],
|
||||
timelineRenderers: [],
|
||||
notificationOpenHandlers: [],
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -47,6 +47,7 @@ function plugin(input: {
|
||||
},
|
||||
],
|
||||
timelineRenderers: [],
|
||||
notificationOpenHandlers: [],
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -22,6 +22,7 @@ import type {
|
||||
PluginSettingsScreenContribution as SDKPluginSettingsScreenContribution,
|
||||
PluginTimelineRendererContribution,
|
||||
PluginTimelineTransformerContribution,
|
||||
PluginNotificationOpenHandler,
|
||||
PluginPanelLocation,
|
||||
PluginWorkspacePanelContribution as SDKPluginWorkspacePanelContribution,
|
||||
} from "@getpaseo/plugin/client";
|
||||
@@ -70,6 +71,7 @@ export interface EvaluatedPlugin {
|
||||
themes: PluginThemeContribution[];
|
||||
timelineTransformers: PluginTimelineTransformerContribution[];
|
||||
timelineRenderers: PluginTimelineRendererContribution[];
|
||||
notificationOpenHandlers: PluginNotificationOpenHandler[];
|
||||
}
|
||||
|
||||
export interface InstalledPlugin extends EvaluatedPlugin {
|
||||
@@ -105,5 +107,6 @@ export type {
|
||||
PluginThemeContribution,
|
||||
PluginTimelineRendererContribution,
|
||||
PluginTimelineTransformerContribution,
|
||||
PluginNotificationOpenHandler,
|
||||
PluginWorkspacePanelContribution,
|
||||
};
|
||||
|
||||
@@ -44,6 +44,7 @@ function installed(): InstalledPlugin {
|
||||
themes: [],
|
||||
timelineTransformers: [],
|
||||
timelineRenderers: [],
|
||||
notificationOpenHandlers: [],
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,64 @@
|
||||
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;
|
||||
}
|
||||
@@ -0,0 +1,297 @@
|
||||
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,70 +1,90 @@
|
||||
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 { 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 type { RevokePushNotificationsInput, StartPushNotificationsInput } from "./types";
|
||||
|
||||
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 defaultResolveToken(serverId: string): Promise<string | null> {
|
||||
const { resolveExpoPushToken } = await import("./expo-token");
|
||||
return resolveExpoPushToken(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 loadInitialAppSettings(settingsDeps?: SettingsDeps): Promise<AppSettings> {
|
||||
if (settingsDeps) {
|
||||
return loadAppSettingsFromStoragePure(settingsDeps);
|
||||
}
|
||||
const { loadAppSettingsFromStorage } = await import("@/hooks/use-settings");
|
||||
return loadAppSettingsFromStorage();
|
||||
}
|
||||
|
||||
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);
|
||||
function readCachedPreferences(queryClient: QueryClient): NotificationPreferences | null {
|
||||
const cached = queryClient.getQueryData<AppSettings>(APP_SETTINGS_QUERY_KEY);
|
||||
if (!cached) {
|
||||
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;
|
||||
return normalizeNotificationPreferences(cached.notifications);
|
||||
}
|
||||
|
||||
export function startSubscription(input: StartPushNotificationsInput): () => void {
|
||||
let stopped = false;
|
||||
let token: string | null = null;
|
||||
const register = () => {
|
||||
if (!stopped && token && input.client.isConnected) {
|
||||
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 {
|
||||
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;
|
||||
@@ -74,19 +94,46 @@ export function startSubscription(input: StartPushNotificationsInput): () => voi
|
||||
})
|
||||
.catch((error) => console.warn("[PushNotifications] Failed to register push token", error));
|
||||
|
||||
const unsubscribe = input.client.subscribeConnectionStatus((state) => {
|
||||
if (state.status === "connected") register();
|
||||
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();
|
||||
});
|
||||
|
||||
return () => {
|
||||
stopped = true;
|
||||
unsubscribe();
|
||||
unsubscribeConnection();
|
||||
unsubscribeStatus();
|
||||
unsubscribeQueryCache();
|
||||
};
|
||||
}
|
||||
|
||||
export async function revokeSubscription(input: RevokePushNotificationsInput): Promise<void> {
|
||||
const key = storageKey(input.serverId);
|
||||
const token = await readValidatedString(AsyncStorage, key, ExpoPushTokenSchema);
|
||||
const { readCachedExpoPushToken, removeCachedExpoPushToken } = await import("./expo-token");
|
||||
const token = await readCachedExpoPushToken(input.serverId);
|
||||
if (
|
||||
token &&
|
||||
input.client?.isConnected &&
|
||||
@@ -98,5 +145,5 @@ export async function revokeSubscription(input: RevokePushNotificationsInput): P
|
||||
console.warn("[PushNotifications] Failed to revoke push token", error);
|
||||
}
|
||||
}
|
||||
await AsyncStorage.removeItem(key);
|
||||
await removeCachedExpoPushToken(input.serverId);
|
||||
}
|
||||
|
||||
@@ -1,11 +1,31 @@
|
||||
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: DaemonClient;
|
||||
client: PushNotificationClient;
|
||||
serverId: string;
|
||||
queryClient?: QueryClient;
|
||||
settingsDeps?: SettingsDeps;
|
||||
resolveToken?: (serverId: string) => Promise<string | null>;
|
||||
}
|
||||
|
||||
export interface RevokePushNotificationsInput {
|
||||
client: DaemonClient | null;
|
||||
client: Pick<
|
||||
DaemonClient,
|
||||
"isConnected" | "unregisterPushToken" | "getLastServerInfoMessage"
|
||||
> | null;
|
||||
serverId: string;
|
||||
}
|
||||
|
||||
@@ -38,6 +38,17 @@ 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,
|
||||
|
||||
@@ -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 { DesktopNotificationsSection } from "@/desktop/components/desktop-notifications-section";
|
||||
import { NotificationsSection } from "@/components/settings/notifications-section";
|
||||
import { BrowserDataSection } from "@/desktop/browser/settings/browser-data-section";
|
||||
import { IntegrationsSection } from "@/desktop/components/integrations-section";
|
||||
import { isElectronRuntime } from "@/desktop/host";
|
||||
@@ -184,7 +184,6 @@ const SIDEBAR_SECTION_ITEMS: SidebarSectionItem[] = [
|
||||
id: "notifications",
|
||||
labelKey: "settings.sections.notifications",
|
||||
icon: Bell,
|
||||
desktopOnly: true,
|
||||
},
|
||||
{ id: "about", labelKey: "settings.sections.about", icon: Info },
|
||||
];
|
||||
@@ -1546,7 +1545,7 @@ export default function SettingsScreen({ view }: SettingsScreenProps) {
|
||||
case "notifications":
|
||||
return (
|
||||
<>
|
||||
<DesktopNotificationsSection />
|
||||
<NotificationsSection />
|
||||
{isDesktopApp ? <DesktopPermissionsSection /> : null}
|
||||
</>
|
||||
);
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@getpaseo/cli",
|
||||
"version": "0.17.6",
|
||||
"version": "0.17.5",
|
||||
"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.6",
|
||||
"@getpaseo/protocol": "0.17.6",
|
||||
"@getpaseo/server": "0.17.6",
|
||||
"@getpaseo/client": "0.17.5",
|
||||
"@getpaseo/protocol": "0.17.5",
|
||||
"@getpaseo/server": "0.17.5",
|
||||
"chalk": "^5.3.0",
|
||||
"commander": "^12.0.0",
|
||||
"mime-types": "^2.1.35",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@getpaseo/client",
|
||||
"version": "0.17.6",
|
||||
"version": "0.17.5",
|
||||
"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.6",
|
||||
"@getpaseo/relay": "0.17.6",
|
||||
"@getpaseo/protocol": "0.17.5",
|
||||
"@getpaseo/relay": "0.17.5",
|
||||
"ws": "^8.20.0",
|
||||
"zod": "^4.4.3"
|
||||
},
|
||||
|
||||
@@ -1528,6 +1528,47 @@ 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();
|
||||
|
||||
@@ -34,6 +34,7 @@ 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,
|
||||
@@ -2592,10 +2593,11 @@ export class DaemonClient {
|
||||
});
|
||||
}
|
||||
|
||||
registerPushToken(token: string): void {
|
||||
registerPushToken(token: string, preferences?: NotificationPreferences): void {
|
||||
this.sendSessionMessage({
|
||||
type: "register_push_token",
|
||||
token,
|
||||
...(preferences !== undefined ? { preferences } : {}),
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@getpaseo/desktop",
|
||||
"version": "0.17.6",
|
||||
"version": "0.17.5",
|
||||
"private": true,
|
||||
"description": "Paseo desktop app (Electron wrapper)",
|
||||
"homepage": "https://paseo.sh",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@getpaseo/expo-two-way-audio",
|
||||
"version": "0.17.6",
|
||||
"version": "0.17.5",
|
||||
"description": "Native module for two way audio streaming",
|
||||
"keywords": [
|
||||
"ExpoTwoWayAudio",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@getpaseo/highlight",
|
||||
"version": "0.17.6",
|
||||
"version": "0.17.5",
|
||||
"license": "Apache-2.0",
|
||||
"files": [
|
||||
"dist",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@getpaseo/plugin",
|
||||
"version": "0.17.6",
|
||||
"version": "0.17.5",
|
||||
"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.6",
|
||||
"@getpaseo/protocol": "0.17.6",
|
||||
"@getpaseo/client": "0.17.5",
|
||||
"@getpaseo/protocol": "0.17.5",
|
||||
"@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.6",
|
||||
"@getpaseo/protocol": "0.17.6",
|
||||
"@getpaseo/client": "0.17.5",
|
||||
"@getpaseo/protocol": "0.17.5",
|
||||
"react": ">=19.1.0 <20",
|
||||
"react-native": ">=0.81.5",
|
||||
"zod": "^4.4.3"
|
||||
|
||||
@@ -694,3 +694,88 @@ 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([]);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -33,6 +33,7 @@ import type {
|
||||
PluginCleanup,
|
||||
} from "../contracts.js";
|
||||
import type { PluginIconProps, PluginSerializableIcon } from "../icons.js";
|
||||
import type { PluginNotificationOpenHandler } from "./notifications.js";
|
||||
|
||||
export interface PluginHostProps {
|
||||
theme: PluginTheme;
|
||||
@@ -46,9 +47,24 @@ 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?: {
|
||||
readonly navigation?: PluginHostNavigationActions & {
|
||||
/** 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. */
|
||||
@@ -57,18 +73,6 @@ 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;
|
||||
};
|
||||
}
|
||||
|
||||
@@ -264,6 +268,7 @@ 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
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
export type {
|
||||
PluginHostProps,
|
||||
PluginHostNavigationActions,
|
||||
PluginTab,
|
||||
PluginPanelProps,
|
||||
PluginWorkspacePanelParams,
|
||||
@@ -45,6 +46,11 @@ export type {
|
||||
PluginClientSlashCommandContribution,
|
||||
SettingsState,
|
||||
} from "./contracts.js";
|
||||
export type {
|
||||
PluginNotificationOpenEvent,
|
||||
PluginNotificationOpenContext,
|
||||
PluginNotificationOpenHandler,
|
||||
} from "./notifications.js";
|
||||
export type {
|
||||
PluginButton,
|
||||
PluginButtonBehavior,
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
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>;
|
||||
@@ -5,6 +5,7 @@ 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 {
|
||||
@@ -66,6 +67,7 @@ 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;
|
||||
|
||||
@@ -39,6 +39,12 @@ 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,
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
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,6 +1,6 @@
|
||||
{
|
||||
"name": "@getpaseo/protocol",
|
||||
"version": "0.17.6",
|
||||
"version": "0.17.5",
|
||||
"description": "Paseo shared protocol schemas and wire types",
|
||||
"license": "Apache-2.0",
|
||||
"files": [
|
||||
|
||||
@@ -1,4 +1,9 @@
|
||||
import { describe, expect, test } from "vitest";
|
||||
import {
|
||||
DEFAULT_NOTIFICATION_PREFERENCES,
|
||||
normalizeNotificationPreferences,
|
||||
type NotificationPreferences,
|
||||
} from "./notification-preferences.js";
|
||||
import {
|
||||
AgentTimelineItemPayloadSchema,
|
||||
SendAgentMessageRequestSchema,
|
||||
@@ -631,3 +636,83 @@ 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);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -43,6 +43,18 @@ 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";
|
||||
@@ -3292,6 +3304,7 @@ 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({
|
||||
@@ -3535,6 +3548,7 @@ 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",
|
||||
@@ -4064,6 +4078,8 @@ 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.
|
||||
@@ -4086,6 +4102,8 @@ 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.
|
||||
@@ -7361,6 +7379,41 @@ 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({
|
||||
@@ -7955,6 +8008,7 @@ export const SessionOutboundMessageSchema = z.discriminatedUnion("type", [
|
||||
CaptureTerminalResponseSchema,
|
||||
TerminalStreamExitSchema,
|
||||
TerminalAttentionRequiredSchema,
|
||||
PluginNotificationMessageSchema,
|
||||
ChatCreateResponseSchema,
|
||||
ChatListResponseSchema,
|
||||
ChatInspectResponseSchema,
|
||||
|
||||
@@ -0,0 +1,181 @@
|
||||
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,
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,166 @@
|
||||
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.6",
|
||||
"version": "0.17.5",
|
||||
"private": true,
|
||||
"description": "Markdown-based Rich Text solution for React Native",
|
||||
"main": "./lib/module/index",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@getpaseo/relay",
|
||||
"version": "0.17.6",
|
||||
"version": "0.17.5",
|
||||
"description": "Paseo relay for bridging daemon and client connections",
|
||||
"license": "Apache-2.0",
|
||||
"files": [
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@getpaseo/server",
|
||||
"version": "0.17.6",
|
||||
"version": "0.17.5",
|
||||
"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.6",
|
||||
"@getpaseo/highlight": "0.17.6",
|
||||
"@getpaseo/plugin": "0.17.6",
|
||||
"@getpaseo/protocol": "0.17.6",
|
||||
"@getpaseo/relay": "0.17.6",
|
||||
"@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",
|
||||
"@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 and permission but not error", () => {
|
||||
it("allows push for finished, permission, and error", () => {
|
||||
expect(isPushEligibleAttentionReason("finished")).toBe(true);
|
||||
expect(isPushEligibleAttentionReason("permission")).toBe(true);
|
||||
expect(isPushEligibleAttentionReason("error")).toBe(false);
|
||||
expect(isPushEligibleAttentionReason("error")).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -75,6 +75,6 @@ export function computeNotificationPlan({
|
||||
return { inAppRecipientIndex: null, shouldPush: pushEligible };
|
||||
}
|
||||
|
||||
export function isPushEligibleAttentionReason(reason: AgentAttentionReason): boolean {
|
||||
return reason !== "error";
|
||||
export function isPushEligibleAttentionReason(_reason: AgentAttentionReason): boolean {
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -29,6 +29,8 @@ 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";
|
||||
@@ -1771,6 +1773,51 @@ 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,6 +27,9 @@ 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=";
|
||||
|
||||
@@ -1131,13 +1134,15 @@ describe("PiRpcAgentSession", () => {
|
||||
error: null,
|
||||
},
|
||||
]);
|
||||
expect(events.turnLifecycleEvents()).toEqual([{ type: "turn_started", turnId: undefined }]);
|
||||
expect(events.turnLifecycleEvents()).toEqual([
|
||||
{ type: "turn_started", turnId: AUTONOMOUS_TURN_ID },
|
||||
]);
|
||||
|
||||
fakeSession.settleTurn();
|
||||
|
||||
expect(events.turnLifecycleEvents()).toEqual([
|
||||
{ type: "turn_started", turnId: undefined },
|
||||
{ type: "turn_completed", turnId: undefined },
|
||||
{ type: "turn_started", turnId: AUTONOMOUS_TURN_ID },
|
||||
{ type: "turn_completed", turnId: AUTONOMOUS_TURN_ID },
|
||||
]);
|
||||
});
|
||||
|
||||
@@ -1221,12 +1226,14 @@ describe("PiRpcAgentSession", () => {
|
||||
|
||||
const stopping = session.interrupt();
|
||||
await turnFinished.promise;
|
||||
expect(events.turnLifecycleEvents()).toEqual([{ type: "turn_started", turnId: undefined }]);
|
||||
expect(events.turnLifecycleEvents()).toEqual([
|
||||
{ type: "turn_started", turnId: AUTONOMOUS_TURN_ID },
|
||||
]);
|
||||
abortFinished.resolve();
|
||||
await stopping;
|
||||
expect(events.turnLifecycleEvents()).toEqual([
|
||||
{ type: "turn_started", turnId: undefined },
|
||||
{ type: "turn_canceled", turnId: undefined },
|
||||
{ type: "turn_started", turnId: AUTONOMOUS_TURN_ID },
|
||||
{ type: "turn_canceled", turnId: AUTONOMOUS_TURN_ID },
|
||||
]);
|
||||
|
||||
const { turnId } = await session.startTurn("follow-up");
|
||||
@@ -1256,10 +1263,10 @@ describe("PiRpcAgentSession", () => {
|
||||
fakeSession.finishTurn({ role: "assistant", stopReason: "stop", content: [] });
|
||||
|
||||
expect(events.turnLifecycleEvents()).toEqual([
|
||||
{ type: "turn_started", turnId: undefined },
|
||||
{ type: "turn_completed", turnId: undefined },
|
||||
{ type: "turn_started", turnId: undefined },
|
||||
{ type: "turn_completed", turnId: undefined },
|
||||
{ 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 },
|
||||
]);
|
||||
});
|
||||
|
||||
@@ -1285,8 +1292,8 @@ describe("PiRpcAgentSession", () => {
|
||||
expect(events.turnLifecycleEvents()).toEqual([
|
||||
{ type: "turn_started", turnId },
|
||||
{ type: "turn_completed", turnId },
|
||||
{ type: "turn_started", turnId: undefined },
|
||||
{ type: "turn_failed", turnId: undefined },
|
||||
{ type: "turn_started", turnId: AUTONOMOUS_TURN_ID },
|
||||
{ type: "turn_failed", turnId: AUTONOMOUS_TURN_ID },
|
||||
]);
|
||||
});
|
||||
|
||||
@@ -1308,8 +1315,8 @@ describe("PiRpcAgentSession", () => {
|
||||
|
||||
await expect(session.interrupt()).rejects.toThrow("Pi process exited");
|
||||
expect(events.turnLifecycleEvents()).toEqual([
|
||||
{ type: "turn_started", turnId: undefined },
|
||||
{ type: "turn_failed", turnId: undefined },
|
||||
{ type: "turn_started", turnId: AUTONOMOUS_TURN_ID },
|
||||
{ type: "turn_failed", turnId: AUTONOMOUS_TURN_ID },
|
||||
]);
|
||||
await expect(events.nextTurnFailure()).resolves.toMatchObject({ error: "Pi process exited" });
|
||||
});
|
||||
@@ -1331,7 +1338,7 @@ describe("PiRpcAgentSession", () => {
|
||||
|
||||
await expect(session.interrupt()).rejects.toThrow("Abort failed");
|
||||
await expect(events.nextTurnFailure()).resolves.toMatchObject({
|
||||
turnId: undefined,
|
||||
turnId: AUTONOMOUS_TURN_ID,
|
||||
error: expect.stringContaining("Provider disconnected"),
|
||||
});
|
||||
});
|
||||
@@ -2232,11 +2239,11 @@ describe("PiRpcAgentSession", () => {
|
||||
|
||||
await expect(events.nextTurnFailure()).resolves.toMatchObject({
|
||||
error: "Pi exited",
|
||||
turnId: undefined,
|
||||
turnId: AUTONOMOUS_TURN_ID,
|
||||
});
|
||||
expect(events.turnLifecycleEvents()).toEqual([
|
||||
{ type: "turn_started", turnId: undefined },
|
||||
{ type: "turn_failed", turnId: undefined },
|
||||
{ type: "turn_started", turnId: AUTONOMOUS_TURN_ID },
|
||||
{ type: "turn_failed", turnId: AUTONOMOUS_TURN_ID },
|
||||
]);
|
||||
});
|
||||
|
||||
@@ -2518,6 +2525,37 @@ 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,6 +1194,9 @@ 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 }> = [];
|
||||
@@ -1318,6 +1321,7 @@ 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;
|
||||
@@ -1364,6 +1368,7 @@ 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;
|
||||
@@ -1393,11 +1398,11 @@ export class PiRpcAgentSession implements AgentSession {
|
||||
prompt: AgentPromptInput,
|
||||
options: SteerActiveTurnOptions,
|
||||
): Promise<SteerResult> {
|
||||
if (this.closed || this.activeTurnId !== options.expectedTurnId) {
|
||||
if (this.closed || this.currentTurnIdForEvent() !== options.expectedTurnId) {
|
||||
return { status: "unavailable" };
|
||||
}
|
||||
const payload = await convertPromptInput(prompt, { model: this.state.model });
|
||||
if (this.closed || this.activeTurnId !== options.expectedTurnId)
|
||||
if (this.closed || this.currentTurnIdForEvent() !== 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.
|
||||
@@ -1415,7 +1420,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.activeTurnId !== options.expectedTurnId) {
|
||||
if (this.closed || this.currentTurnIdForEvent() !== options.expectedTurnId) {
|
||||
return { status: "unavailable" };
|
||||
}
|
||||
this.pendingSteerSubmissions.push({
|
||||
@@ -1549,7 +1554,7 @@ export class PiRpcAgentSession implements AgentSession {
|
||||
}
|
||||
|
||||
async interrupt(): Promise<void> {
|
||||
const turnId = this.activeTurnId ?? undefined;
|
||||
const turnId = this.currentTurnIdForEvent();
|
||||
const interruption: typeof this.interruptingTurn =
|
||||
this.activeTurnId || this.activeTurnStarted ? { turnId, error: null } : null;
|
||||
this.interruptingTurn = interruption;
|
||||
@@ -1575,6 +1580,7 @@ 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;
|
||||
@@ -1592,13 +1598,14 @@ export class PiRpcAgentSession implements AgentSession {
|
||||
interruption &&
|
||||
this.interruptingTurn === interruption &&
|
||||
(this.activeTurnId || this.activeTurnStarted) &&
|
||||
(this.activeTurnId ?? undefined) === turnId
|
||||
this.currentTurnIdForEvent() === 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;
|
||||
@@ -1782,7 +1789,13 @@ export class PiRpcAgentSession implements AgentSession {
|
||||
}
|
||||
|
||||
private currentTurnIdForEvent(): string | undefined {
|
||||
return this.activeTurnId ?? undefined;
|
||||
return this.activeTurnId ?? this.autonomousTurnId ?? undefined;
|
||||
}
|
||||
|
||||
private claimAutonomousTurnId(): void {
|
||||
if (!this.activeTurnId && !this.autonomousTurnId) {
|
||||
this.autonomousTurnId = `autonomous-${randomUUID()}`;
|
||||
}
|
||||
}
|
||||
|
||||
private async completeNoTurnPrompt(turnId: string): Promise<void> {
|
||||
@@ -2210,12 +2223,13 @@ export class PiRpcAgentSession implements AgentSession {
|
||||
if (!this.activeTurnId && !this.activeTurnStarted) {
|
||||
return;
|
||||
}
|
||||
const turnId = this.activeTurnId ?? undefined;
|
||||
const turnId = this.currentTurnIdForEvent();
|
||||
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();
|
||||
@@ -2246,6 +2260,7 @@ export class PiRpcAgentSession implements AgentSession {
|
||||
return;
|
||||
case "agent_start":
|
||||
this.activeTurnStarted = true;
|
||||
this.claimAutonomousTurnId();
|
||||
this.clearNoTurnBuffers();
|
||||
this.emit({
|
||||
type: "thread_started",
|
||||
@@ -2256,6 +2271,7 @@ export class PiRpcAgentSession implements AgentSession {
|
||||
case "turn_start":
|
||||
this.firstToken.requestSent(Date.now());
|
||||
this.activeTurnStarted = true;
|
||||
this.claimAutonomousTurnId();
|
||||
this.clearNoTurnBuffers();
|
||||
if (this.activeTurnStartedEmitted) {
|
||||
return;
|
||||
@@ -2264,7 +2280,7 @@ export class PiRpcAgentSession implements AgentSession {
|
||||
this.emit({
|
||||
type: "turn_started",
|
||||
provider: this.provider,
|
||||
turnId,
|
||||
turnId: this.currentTurnIdForEvent(),
|
||||
});
|
||||
return;
|
||||
case "message_start":
|
||||
@@ -2586,6 +2602,7 @@ 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,6 +404,7 @@ 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",
|
||||
|
||||
@@ -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 { PushNotificationSender } from "./push/index.js";
|
||||
import type { PushNotifications, 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,6 +443,7 @@ export interface PaseoDaemonConfig {
|
||||
log?: PersistedConfig["log"];
|
||||
onLifecycleIntent?: (intent: DaemonLifecycleIntent) => void;
|
||||
pushNotificationSender?: PushNotificationSender;
|
||||
pushNotifications?: PushNotifications;
|
||||
managedProcesses?: ManagedProcessRegistry;
|
||||
configReload?: {
|
||||
env: NodeJS.ProcessEnv;
|
||||
@@ -1953,6 +1954,7 @@ export async function createPaseoDaemon(
|
||||
orchestrationSkills,
|
||||
workspaceLabelService,
|
||||
workspaceArchiveOperations,
|
||||
config.pushNotifications,
|
||||
);
|
||||
pluginRuntime.bindPaseoSessionHost(wsServer);
|
||||
await pluginRuntime.start();
|
||||
|
||||
@@ -1,16 +1,30 @@
|
||||
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 type { PushNotificationSender, PushPayload } from "./push/index.js";
|
||||
import {
|
||||
createPushNotifications,
|
||||
type PushNotificationSender,
|
||||
type 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): Promise<void> {
|
||||
async send(payload: PushPayload, kind?: NotificationKind): Promise<void> {
|
||||
this.sent.push(payload);
|
||||
this.sentWithKind.push({ payload, kind });
|
||||
}
|
||||
}
|
||||
|
||||
@@ -57,6 +71,7 @@ describe("client activity tracking", () => {
|
||||
messageQueueLimit: null,
|
||||
});
|
||||
await client.connect();
|
||||
await client.observeEvents(["agent_attention_required"], { notifications: true }).ready;
|
||||
return client;
|
||||
}
|
||||
|
||||
@@ -697,5 +712,123 @@ 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);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -0,0 +1,227 @@
|
||||
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);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,313 @@
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,336 @@
|
||||
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 } from "@getpaseo/plugin/server";
|
||||
import type { PluginHookAgent, PluginNotificationSendResult } from "@getpaseo/plugin/server";
|
||||
import { UsageScopeSchema, type UsageScope } from "@getpaseo/plugin/server/usage";
|
||||
import type {
|
||||
ProviderConnectRequest,
|
||||
@@ -120,6 +120,8 @@ 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" };
|
||||
@@ -162,6 +164,7 @@ 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" };
|
||||
|
||||
@@ -379,6 +382,29 @@ 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(),
|
||||
@@ -479,6 +505,13 @@ 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,6 +14,9 @@ import type {
|
||||
} from "@getpaseo/plugin";
|
||||
import type {
|
||||
PluginHandlerContext,
|
||||
PluginNotificationSendInput,
|
||||
PluginNotificationSendResult,
|
||||
PluginNotifications,
|
||||
PluginServerContext,
|
||||
PluginServerContribution,
|
||||
PluginWorktreeCreateInput,
|
||||
@@ -21,6 +24,7 @@ import type {
|
||||
PluginWorktreeRestoreRequest,
|
||||
WorktreeManagerRegistration,
|
||||
} from "@getpaseo/plugin/server";
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { assertPluginWireValue } from "@getpaseo/protocol/binary-frames/index";
|
||||
import {
|
||||
PluginSubscriptionHandlers,
|
||||
@@ -127,6 +131,13 @@ 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;
|
||||
@@ -272,6 +283,29 @@ 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,
|
||||
@@ -484,6 +518,7 @@ export function createPluginWorker(options: {
|
||||
registerUsageSource,
|
||||
registerWorktreeManager,
|
||||
registerSettings,
|
||||
notifications,
|
||||
addHook: hooks.addHook,
|
||||
on: hooks.on,
|
||||
before: hooks.before,
|
||||
@@ -531,6 +566,9 @@ 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;
|
||||
@@ -682,6 +720,59 @@ 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) {
|
||||
@@ -719,6 +810,7 @@ export function createPluginWorker(options: {
|
||||
void shutdown();
|
||||
return;
|
||||
}
|
||||
if (handleNotificationMessage(message)) return;
|
||||
if (stopping) {
|
||||
rejectWhileStopping(message);
|
||||
return;
|
||||
@@ -729,33 +821,7 @@ export function createPluginWorker(options: {
|
||||
handleUsageRequest(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 (handleProviderConnectOrSend(message)) return;
|
||||
if (message.type === "paseo_frame" || message.type === "paseo_close") return;
|
||||
if (isHookMessage(message)) {
|
||||
handleHookMessage(message);
|
||||
|
||||
@@ -2228,13 +2228,18 @@ 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,
|
||||
example === "sidebar-views" ? "0.16.0" : resolveDaemonVersion(import.meta.url),
|
||||
exampleDaemonVersions[example] ?? 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
Reference in New Issue
Block a user