mirror of
https://github.com/getpaseo/paseo.git
synced 2026-11-26 10:15:46 +00:00
Compare commits
8
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
8fbfa1aefb | ||
|
|
1249ee7415 | ||
|
|
7f1e41a72c | ||
|
|
3340159489 | ||
|
|
1e70da05dc | ||
|
|
099f77e9b4 | ||
|
|
69d3cc2716 | ||
|
|
e7e5934acb |
+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
|
||||
|
||||
@@ -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<{
|
||||
|
||||
@@ -56,6 +56,7 @@ const SECTION_LABELS = {
|
||||
browser: "Browser",
|
||||
shortcuts: "Shortcuts",
|
||||
integrations: "Integrations",
|
||||
notifications: "Notifications",
|
||||
permissions: "Permissions",
|
||||
diagnostics: "Diagnostics",
|
||||
about: "About",
|
||||
|
||||
@@ -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,
|
||||
@@ -1212,3 +1213,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.
|
||||
|
||||
@@ -2445,6 +2445,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: "تشغيل صوت",
|
||||
|
||||
@@ -2477,6 +2477,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",
|
||||
|
||||
@@ -2460,6 +2460,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",
|
||||
|
||||
@@ -2459,6 +2459,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",
|
||||
|
||||
@@ -2433,6 +2433,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: "サウンドを再生",
|
||||
|
||||
@@ -2420,6 +2420,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: "소리 재생",
|
||||
|
||||
@@ -2445,6 +2445,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",
|
||||
|
||||
@@ -2446,6 +2446,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: "Воспроизводить звук",
|
||||
|
||||
@@ -2386,6 +2386,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,
|
||||
|
||||
@@ -81,7 +81,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";
|
||||
@@ -217,8 +217,7 @@ const SIDEBAR_SECTION_ITEMS: SidebarSectionItem[] = [
|
||||
id: "notifications",
|
||||
labelKey: "settings.sections.notifications",
|
||||
icon: Bell,
|
||||
desktopOnly: true,
|
||||
Content: DesktopNotificationsSection,
|
||||
Content: NotificationsSection,
|
||||
},
|
||||
{
|
||||
id: "permissions",
|
||||
|
||||
@@ -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 } : {}),
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -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,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);
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
@@ -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));
|
||||
|
||||
@@ -60,6 +60,7 @@ import {
|
||||
import { PluginSessionSocket } from "./session-socket.js";
|
||||
import { InternalPluginChild } from "./internal-child.js";
|
||||
import { evaluateBundle } from "./bundle-evaluator.js";
|
||||
import { PluginNotificationDispatcher, type ValidatedPluginNotification } from "./notifications.js";
|
||||
|
||||
const REQUEST_TIMEOUT_MS = 30_000;
|
||||
const WORKTREE_MANAGER_TIMEOUT_MS = 120_000;
|
||||
@@ -278,6 +279,7 @@ export interface PluginPaseoSessionHost {
|
||||
pluginId: string,
|
||||
socket: PluginSessionSocket,
|
||||
): Promise<{ closed: Promise<void> }>;
|
||||
sendPluginNotification?(notification: ValidatedPluginNotification): void | Promise<void>;
|
||||
}
|
||||
|
||||
function resolveWorkerUrl(): URL {
|
||||
@@ -374,6 +376,7 @@ export class PluginRuntime {
|
||||
private readonly spawnChild: () => PluginChild;
|
||||
private sessionHost: PluginPaseoSessionHost | null;
|
||||
private readonly listeners = new Set<(pluginId: string, error?: string) => void>();
|
||||
private readonly notifications: PluginNotificationDispatcher;
|
||||
/** What `agent.open.before` plugins attached to each live session. */
|
||||
readonly sessionAttachments: SessionAttachments;
|
||||
|
||||
@@ -385,6 +388,9 @@ export class PluginRuntime {
|
||||
this.logger = logger.child({ module: "plugins" });
|
||||
this.spawnChild = dependencies.spawnChild ?? spawnPluginChild;
|
||||
this.sessionHost = dependencies.sessionHost ?? null;
|
||||
this.notifications = new PluginNotificationDispatcher({
|
||||
deliver: (notification) => this.sessionHost?.sendPluginNotification?.(notification),
|
||||
});
|
||||
this.sessionAttachments = new SessionAttachments(
|
||||
{
|
||||
sessionOpenPlugins: () => this.sessionOpenPlugins(),
|
||||
@@ -457,6 +463,7 @@ export class PluginRuntime {
|
||||
const loaded = this.plugins.get(pluginId);
|
||||
if (!loaded) return false;
|
||||
this.plugins.delete(pluginId);
|
||||
this.notifications.clearPlugin(pluginId);
|
||||
this.rejectPending(loaded, `Plugin stopped: ${pluginId}`);
|
||||
await this.stopPlugin(loaded);
|
||||
return true;
|
||||
@@ -1036,6 +1043,7 @@ export class PluginRuntime {
|
||||
async stopAll(): Promise<void> {
|
||||
const loaded = [...this.plugins.values()];
|
||||
this.plugins.clear();
|
||||
this.notifications.clearAll();
|
||||
for (const plugin of loaded) {
|
||||
this.rejectPending(plugin, `Plugin stopped: ${plugin.id}`);
|
||||
}
|
||||
@@ -1306,6 +1314,10 @@ export class PluginRuntime {
|
||||
subscription?.closed(message.error);
|
||||
return;
|
||||
}
|
||||
if (message.type === "notification.send") {
|
||||
void this.handleNotificationSend(loaded, message);
|
||||
return;
|
||||
}
|
||||
if (message.type !== "result" && message.type !== "error") return;
|
||||
const pending = loaded.pending.get(message.requestId);
|
||||
if (!pending) return;
|
||||
@@ -1315,6 +1327,30 @@ export class PluginRuntime {
|
||||
else pending.reject(new Error(message.error));
|
||||
}
|
||||
|
||||
private async handleNotificationSend(
|
||||
loaded: LoadedPlugin,
|
||||
message: Extract<PluginProcessMessage, { type: "notification.send" }>,
|
||||
): Promise<void> {
|
||||
try {
|
||||
const result = await this.notifications.dispatch(loaded.id, message.input);
|
||||
if (loaded.child?.connected) {
|
||||
await send(loaded.child, {
|
||||
type: "notification.result",
|
||||
requestId: message.requestId,
|
||||
result,
|
||||
}).catch(() => undefined);
|
||||
}
|
||||
} catch (error) {
|
||||
if (loaded.child?.connected) {
|
||||
await send(loaded.child, {
|
||||
type: "notification.error",
|
||||
requestId: message.requestId,
|
||||
error: describeError(error),
|
||||
}).catch(() => undefined);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private handleProviderMessage(loaded: LoadedPlugin, message: PluginProcessMessage): void {
|
||||
if (!("connectionId" in message)) return;
|
||||
const state = loaded.providerConnections.get(message.connectionId);
|
||||
@@ -1610,6 +1646,7 @@ export class PluginRuntime {
|
||||
if (wasPublished) {
|
||||
this.plugins.delete(loaded.id);
|
||||
}
|
||||
this.notifications.clearPlugin(loaded.id);
|
||||
this.rejectPending(loaded, `Plugin process exited: ${loaded.id}`);
|
||||
for (const state of loaded.providerConnections.values()) {
|
||||
this.failRemoteProviderConnection(state, new Error(`Plugin process exited: ${loaded.id}`));
|
||||
|
||||
@@ -3,6 +3,10 @@ import { tmpdir } from "node:os";
|
||||
import path from "node:path";
|
||||
import type pino from "pino";
|
||||
import { afterEach, describe, expect, test } from "vitest";
|
||||
import {
|
||||
DEFAULT_NOTIFICATION_PREFERENCES,
|
||||
type NotificationPreferences,
|
||||
} from "@getpaseo/protocol/notification-preferences";
|
||||
|
||||
import { createPushNotifications } from "./index.js";
|
||||
|
||||
@@ -64,4 +68,97 @@ describe("push notifications", () => {
|
||||
|
||||
expect(deliveries).toEqual([]);
|
||||
});
|
||||
|
||||
test("tokens registered without preferences retain legacy push filtering while explicit defaults apply new defaults", async () => {
|
||||
const home = mkdtempSync(path.join(tmpdir(), "paseo-push-notifications-"));
|
||||
homes.push(home);
|
||||
const deliveries: string[][] = [];
|
||||
const pushNotifications = createPushNotifications({
|
||||
logger: createLogger(),
|
||||
filePath: path.join(home, "push-tokens.json"),
|
||||
now: () => Date.parse("2026-08-10T00:00:00.000Z"),
|
||||
deliver: async (tokens) => deliveries.push(tokens),
|
||||
});
|
||||
|
||||
pushNotifications.renew("ExponentPushToken[legacy-device]");
|
||||
pushNotifications.renew("ExponentPushToken[modern-device]", DEFAULT_NOTIFICATION_PREFERENCES);
|
||||
|
||||
// Legacy tokens keep finished pushes and skip error pushes; modern defaults flip that.
|
||||
await pushNotifications.send(
|
||||
{ title: "Agent finished", body: "Done" },
|
||||
{ kind: "agent", reason: "finished" },
|
||||
);
|
||||
expect(deliveries).toEqual([["ExponentPushToken[legacy-device]"]]);
|
||||
|
||||
await pushNotifications.send(
|
||||
{ title: "Agent needs attention", body: "Encountered an error." },
|
||||
{ kind: "agent", reason: "error" },
|
||||
);
|
||||
expect(deliveries).toEqual([
|
||||
["ExponentPushToken[legacy-device]"],
|
||||
["ExponentPushToken[modern-device]"],
|
||||
]);
|
||||
});
|
||||
|
||||
test("per-token filtering delivers to eligible tokens and skips ineligible ones in the same send call", async () => {
|
||||
const home = mkdtempSync(path.join(tmpdir(), "paseo-push-notifications-"));
|
||||
homes.push(home);
|
||||
const deliveries: string[][] = [];
|
||||
const pushNotifications = createPushNotifications({
|
||||
logger: createLogger(),
|
||||
filePath: path.join(home, "push-tokens.json"),
|
||||
now: () => Date.parse("2026-08-10T00:00:00.000Z"),
|
||||
deliver: async (tokens) => deliveries.push(tokens),
|
||||
});
|
||||
|
||||
const phoneAPrefs: NotificationPreferences = {
|
||||
...DEFAULT_NOTIFICATION_PREFERENCES,
|
||||
events: {
|
||||
...DEFAULT_NOTIFICATION_PREFERENCES.events,
|
||||
agentFinished: true,
|
||||
},
|
||||
plugins: {
|
||||
enabled: true,
|
||||
muted: ["muted-on-a"],
|
||||
},
|
||||
};
|
||||
const phoneBPrefs: NotificationPreferences = {
|
||||
...DEFAULT_NOTIFICATION_PREFERENCES,
|
||||
events: {
|
||||
...DEFAULT_NOTIFICATION_PREFERENCES.events,
|
||||
agentFinished: false,
|
||||
},
|
||||
plugins: {
|
||||
enabled: true,
|
||||
muted: [],
|
||||
},
|
||||
};
|
||||
const phoneCPrefs: NotificationPreferences = {
|
||||
...DEFAULT_NOTIFICATION_PREFERENCES,
|
||||
enabled: false,
|
||||
events: {
|
||||
agentPermission: true,
|
||||
agentError: true,
|
||||
agentFinished: true,
|
||||
terminalNeedsInput: true,
|
||||
terminalFinished: true,
|
||||
},
|
||||
};
|
||||
|
||||
pushNotifications.renew("ExponentPushToken[phone-a]", phoneAPrefs);
|
||||
pushNotifications.renew("ExponentPushToken[phone-b]", phoneBPrefs);
|
||||
pushNotifications.renew("ExponentPushToken[phone-c]", phoneCPrefs);
|
||||
|
||||
await pushNotifications.send(
|
||||
{ title: "Agent finished", body: "Done" },
|
||||
{ kind: "agent", reason: "finished" },
|
||||
);
|
||||
expect(deliveries).toEqual([["ExponentPushToken[phone-a]"]]);
|
||||
|
||||
await pushNotifications.send(
|
||||
{ title: "Plugin alert", body: "Check failed" },
|
||||
{ kind: "plugin", pluginId: "muted-on-a" },
|
||||
);
|
||||
expect(deliveries).toEqual([["ExponentPushToken[phone-a]"], ["ExponentPushToken[phone-b]"]]);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,4 +1,11 @@
|
||||
import type pino from "pino";
|
||||
import {
|
||||
normalizeNotificationPreferences,
|
||||
shouldDeliverNotification,
|
||||
type NotificationKind,
|
||||
type NotificationPreferences,
|
||||
type NotificationPreferencesInput,
|
||||
} from "@getpaseo/protocol/notification-preferences";
|
||||
|
||||
import { PushService, type PushPayload } from "./push-service.js";
|
||||
import { PushTokenStore } from "./token-store.js";
|
||||
@@ -7,10 +14,28 @@ export type { PushPayload };
|
||||
|
||||
const PUSH_TOKEN_LEASE_MS = 48 * 60 * 60 * 1000;
|
||||
|
||||
// COMPAT(pushNotificationPreferences): added in v0.18.0, remove after 2027-06-01.
|
||||
// Mobile apps predating notification preferences cannot opt back into finished pushes, so
|
||||
// tokens registered without explicit preferences retain the pre-v0.18 push filter.
|
||||
const LEGACY_PUSH_NOTIFICATION_PREFERENCES: NotificationPreferences = {
|
||||
enabled: true,
|
||||
events: {
|
||||
agentPermission: true,
|
||||
agentError: false,
|
||||
agentFinished: true,
|
||||
terminalNeedsInput: true,
|
||||
terminalFinished: true,
|
||||
},
|
||||
plugins: {
|
||||
enabled: true,
|
||||
muted: [],
|
||||
},
|
||||
};
|
||||
|
||||
export interface PushNotifications {
|
||||
renew(token: string): void;
|
||||
renew(token: string, preferences?: NotificationPreferencesInput): void;
|
||||
revoke(token: string): void;
|
||||
send(payload: PushPayload): Promise<void>;
|
||||
send(payload: PushPayload, kind?: NotificationKind): Promise<void>;
|
||||
}
|
||||
|
||||
export type PushNotificationSender = Pick<PushNotifications, "send">;
|
||||
@@ -29,15 +54,27 @@ export function createPushNotifications(options: {
|
||||
((tokens: string[], payload: PushPayload) => service.sendPush(tokens, payload));
|
||||
|
||||
return {
|
||||
renew(token) {
|
||||
store.renewToken(token);
|
||||
renew(token, preferences) {
|
||||
store.renewToken(token, preferences);
|
||||
},
|
||||
revoke(token) {
|
||||
store.revokeToken(token);
|
||||
},
|
||||
async send(payload) {
|
||||
const tokens = store.getActiveTokens();
|
||||
options.logger.info({ tokenCount: tokens.length }, "Sending push notification");
|
||||
async send(payload, kind) {
|
||||
const subscriptions = store.getActiveSubscriptions();
|
||||
const tokens = subscriptions
|
||||
.filter((entry) => {
|
||||
const preferences =
|
||||
entry.preferences !== undefined
|
||||
? normalizeNotificationPreferences(entry.preferences)
|
||||
: LEGACY_PUSH_NOTIFICATION_PREFERENCES;
|
||||
return kind ? shouldDeliverNotification(preferences, kind) : preferences.enabled;
|
||||
})
|
||||
.map((entry) => entry.token);
|
||||
options.logger.info(
|
||||
{ tokenCount: tokens.length, activeTokenCount: subscriptions.length, kind },
|
||||
"Sending push notification",
|
||||
);
|
||||
if (tokens.length === 0) return;
|
||||
await deliver(tokens, payload);
|
||||
},
|
||||
|
||||
@@ -3,6 +3,10 @@ import { tmpdir } from "node:os";
|
||||
import path from "node:path";
|
||||
import type pino from "pino";
|
||||
import { describe, expect, test } from "vitest";
|
||||
import {
|
||||
DEFAULT_NOTIFICATION_PREFERENCES,
|
||||
type NotificationPreferences,
|
||||
} from "@getpaseo/protocol/notification-preferences";
|
||||
|
||||
import { PRIVATE_FILE_MODE } from "../private-files.js";
|
||||
import { createPushNotifications } from "./index.js";
|
||||
@@ -101,4 +105,85 @@ describe("PushTokenStore persistence", () => {
|
||||
expect(store.getActiveTokens()).toEqual([]);
|
||||
expect(JSON.parse(persisted)).toEqual({ subscriptions: [] });
|
||||
});
|
||||
|
||||
test("persists preference updates immediately even within the half-lease throttle window and reloads them from disk", () => {
|
||||
const home = mkdtempSync(path.join(tmpdir(), "paseo-push-token-prefs-"));
|
||||
const tokenPath = path.join(home, "push-tokens.json");
|
||||
let now = Date.parse("2026-08-10T00:00:00.000Z");
|
||||
const leaseMs = 48 * 60 * 60 * 1000;
|
||||
let writeCount = 0;
|
||||
|
||||
try {
|
||||
const store = new PushTokenStore(
|
||||
createLogger(),
|
||||
tokenPath,
|
||||
() => now,
|
||||
leaseMs,
|
||||
(filePath, payload) => {
|
||||
writeCount += 1;
|
||||
writeFileSync(filePath, payload);
|
||||
},
|
||||
);
|
||||
|
||||
const initialPrefs: NotificationPreferences = {
|
||||
...DEFAULT_NOTIFICATION_PREFERENCES,
|
||||
events: {
|
||||
...DEFAULT_NOTIFICATION_PREFERENCES.events,
|
||||
agentFinished: false,
|
||||
},
|
||||
};
|
||||
store.renewToken("ExponentPushToken[device-1]", initialPrefs);
|
||||
expect(writeCount).toBe(1);
|
||||
|
||||
// Same preferences within the half-lease window are throttled.
|
||||
now += 1_000;
|
||||
store.renewToken("ExponentPushToken[device-1]", initialPrefs);
|
||||
expect(writeCount).toBe(1);
|
||||
|
||||
// Heartbeat renewal without preferences preserves existing preferences and is throttled.
|
||||
now += 1_000;
|
||||
store.renewToken("ExponentPushToken[device-1]");
|
||||
expect(writeCount).toBe(1);
|
||||
|
||||
// Changing preferences within the half-lease window persists immediately.
|
||||
const updatedPrefs: NotificationPreferences = {
|
||||
...DEFAULT_NOTIFICATION_PREFERENCES,
|
||||
events: {
|
||||
...DEFAULT_NOTIFICATION_PREFERENCES.events,
|
||||
agentFinished: true,
|
||||
},
|
||||
plugins: {
|
||||
enabled: true,
|
||||
muted: ["alpha-plugin", "noisy-plugin"],
|
||||
},
|
||||
};
|
||||
now += 1_000;
|
||||
const lastPersistedNow = now;
|
||||
store.renewToken("ExponentPushToken[device-1]", updatedPrefs);
|
||||
expect(writeCount).toBe(2);
|
||||
|
||||
// Reordered muted plugin IDs normalize to the same canonical order and do not rewrite disk.
|
||||
now += 1_000;
|
||||
store.renewToken("ExponentPushToken[device-1]", {
|
||||
...updatedPrefs,
|
||||
plugins: {
|
||||
enabled: true,
|
||||
muted: ["noisy-plugin", "alpha-plugin"],
|
||||
},
|
||||
});
|
||||
expect(writeCount).toBe(2);
|
||||
|
||||
// Reload from disk and verify preferences survived.
|
||||
const reloaded = new PushTokenStore(createLogger(), tokenPath, () => now, leaseMs);
|
||||
expect(reloaded.getActiveSubscriptions()).toEqual([
|
||||
{
|
||||
token: "ExponentPushToken[device-1]",
|
||||
expiresAt: lastPersistedNow + leaseMs,
|
||||
preferences: updatedPrefs,
|
||||
},
|
||||
]);
|
||||
} finally {
|
||||
rmSync(home, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,8 +1,73 @@
|
||||
import type pino from "pino";
|
||||
import { existsSync, readFileSync } from "node:fs";
|
||||
import {
|
||||
normalizeNotificationPreferences,
|
||||
type NotificationPreferences,
|
||||
type NotificationPreferencesInput,
|
||||
} from "@getpaseo/protocol/notification-preferences";
|
||||
|
||||
import { ensurePrivateFile, writePrivateFileAtomicSync } from "../private-files.js";
|
||||
|
||||
export interface PushTokenSubscription {
|
||||
token: string;
|
||||
expiresAt: number;
|
||||
preferences?: NotificationPreferences;
|
||||
}
|
||||
|
||||
interface StoredSubscriptionEntry {
|
||||
expiresAt: number;
|
||||
preferences?: NotificationPreferences;
|
||||
}
|
||||
|
||||
function areNotificationPreferencesEqual(
|
||||
left: NotificationPreferences | undefined,
|
||||
right: NotificationPreferences | undefined,
|
||||
): boolean {
|
||||
if (left === right) return true;
|
||||
if (!left || !right) return false;
|
||||
if (left.enabled !== right.enabled) return false;
|
||||
if (
|
||||
left.events.agentPermission !== right.events.agentPermission ||
|
||||
left.events.agentError !== right.events.agentError ||
|
||||
left.events.agentFinished !== right.events.agentFinished ||
|
||||
left.events.terminalNeedsInput !== right.events.terminalNeedsInput ||
|
||||
left.events.terminalFinished !== right.events.terminalFinished
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
if (left.plugins.enabled !== right.plugins.enabled) return false;
|
||||
if (left.plugins.muted.length !== right.plugins.muted.length) return false;
|
||||
return left.plugins.muted.every((pluginId, index) => pluginId === right.plugins.muted[index]);
|
||||
}
|
||||
|
||||
function parsePersistedSubscription(value: unknown): [string, StoredSubscriptionEntry] | null {
|
||||
if (!value || typeof value !== "object") return null;
|
||||
const candidate = value as {
|
||||
token?: unknown;
|
||||
expiresAt?: unknown;
|
||||
preferences?: unknown;
|
||||
};
|
||||
if (typeof candidate.token !== "string" || typeof candidate.expiresAt !== "string") {
|
||||
return null;
|
||||
}
|
||||
const token = candidate.token.trim();
|
||||
const expiresAt = Date.parse(candidate.expiresAt);
|
||||
if (!token || !Number.isFinite(expiresAt)) {
|
||||
return null;
|
||||
}
|
||||
const preferences =
|
||||
candidate.preferences && typeof candidate.preferences === "object"
|
||||
? normalizeNotificationPreferences(candidate.preferences)
|
||||
: undefined;
|
||||
return [
|
||||
token,
|
||||
{
|
||||
expiresAt,
|
||||
...(preferences !== undefined ? { preferences } : {}),
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Store for Expo push tokens.
|
||||
*
|
||||
@@ -10,7 +75,7 @@ import { ensurePrivateFile, writePrivateFileAtomicSync } from "../private-files.
|
||||
*/
|
||||
export class PushTokenStore {
|
||||
private readonly logger: pino.Logger;
|
||||
private subscriptions = new Map<string, number>();
|
||||
private subscriptions = new Map<string, StoredSubscriptionEntry>();
|
||||
private readonly filePath: string;
|
||||
private readonly now: () => number;
|
||||
private readonly leaseMs: number;
|
||||
@@ -31,14 +96,30 @@ export class PushTokenStore {
|
||||
this.loadFromDisk();
|
||||
}
|
||||
|
||||
renewToken(token: string): void {
|
||||
renewToken(token: string, preferences?: NotificationPreferencesInput): void {
|
||||
const normalized = token.trim();
|
||||
if (!normalized) return;
|
||||
const now = this.now();
|
||||
const currentExpiry = this.subscriptions.get(normalized);
|
||||
if (currentExpiry !== undefined && currentExpiry - now > this.leaseMs / 2) return;
|
||||
const current = this.subscriptions.get(normalized);
|
||||
const normalizedPreferences =
|
||||
preferences !== undefined ? normalizeNotificationPreferences(preferences) : undefined;
|
||||
const nextPreferences = normalizedPreferences ?? current?.preferences;
|
||||
const preferencesChanged =
|
||||
normalizedPreferences !== undefined &&
|
||||
!areNotificationPreferencesEqual(current?.preferences, normalizedPreferences);
|
||||
|
||||
if (
|
||||
current !== undefined &&
|
||||
current.expiresAt - now > this.leaseMs / 2 &&
|
||||
!preferencesChanged
|
||||
) {
|
||||
return;
|
||||
}
|
||||
const next = new Map(this.subscriptions);
|
||||
next.set(normalized, now + this.leaseMs);
|
||||
next.set(normalized, {
|
||||
expiresAt: now + this.leaseMs,
|
||||
...(nextPreferences !== undefined ? { preferences: nextPreferences } : {}),
|
||||
});
|
||||
this.persist(next);
|
||||
this.subscriptions = next;
|
||||
this.logger.debug({ total: this.subscriptions.size }, "Renewed token");
|
||||
@@ -55,11 +136,11 @@ export class PushTokenStore {
|
||||
this.logger.debug({ total: this.subscriptions.size }, "Revoked token");
|
||||
}
|
||||
|
||||
getActiveTokens(): string[] {
|
||||
getActiveSubscriptions(): PushTokenSubscription[] {
|
||||
const now = this.now();
|
||||
const active = new Map(this.subscriptions);
|
||||
for (const [token, expiresAt] of this.subscriptions) {
|
||||
if (expiresAt <= now) {
|
||||
for (const [token, entry] of this.subscriptions) {
|
||||
if (entry.expiresAt <= now) {
|
||||
active.delete(token);
|
||||
}
|
||||
}
|
||||
@@ -72,7 +153,15 @@ export class PushTokenStore {
|
||||
// are still excluded from this delivery.
|
||||
}
|
||||
}
|
||||
return Array.from(active.keys());
|
||||
return Array.from(active, ([token, entry]) => ({
|
||||
token,
|
||||
expiresAt: entry.expiresAt,
|
||||
...(entry.preferences !== undefined ? { preferences: entry.preferences } : {}),
|
||||
}));
|
||||
}
|
||||
|
||||
getActiveTokens(): string[] {
|
||||
return this.getActiveSubscriptions().map((entry) => entry.token);
|
||||
}
|
||||
|
||||
private loadFromDisk(): void {
|
||||
@@ -83,17 +172,12 @@ export class PushTokenStore {
|
||||
ensurePrivateFile(this.filePath);
|
||||
const raw = readFileSync(this.filePath, "utf-8");
|
||||
const parsed = JSON.parse(raw) as { subscriptions?: unknown; tokens?: unknown };
|
||||
const loaded = new Map<string, number>();
|
||||
const loaded = new Map<string, StoredSubscriptionEntry>();
|
||||
const subscriptions = Array.isArray(parsed.subscriptions) ? parsed.subscriptions : [];
|
||||
for (const value of subscriptions) {
|
||||
if (!value || typeof value !== "object") continue;
|
||||
const candidate = value as { token?: unknown; expiresAt?: unknown };
|
||||
if (typeof candidate.token !== "string" || typeof candidate.expiresAt !== "string")
|
||||
continue;
|
||||
const token = candidate.token.trim();
|
||||
const expiresAt = Date.parse(candidate.expiresAt);
|
||||
if (token && Number.isFinite(expiresAt)) {
|
||||
loaded.set(token, expiresAt);
|
||||
const parsedEntry = parsePersistedSubscription(value);
|
||||
if (parsedEntry) {
|
||||
loaded.set(parsedEntry[0], parsedEntry[1]);
|
||||
}
|
||||
}
|
||||
this.subscriptions = loaded;
|
||||
@@ -106,7 +190,13 @@ export class PushTokenStore {
|
||||
const expiresAt = this.now() + this.leaseMs;
|
||||
for (const token of legacyTokens) {
|
||||
const normalized = token.trim();
|
||||
if (normalized) migrated.set(normalized, expiresAt);
|
||||
if (normalized) {
|
||||
const existing = migrated.get(normalized);
|
||||
migrated.set(normalized, {
|
||||
expiresAt,
|
||||
...(existing?.preferences !== undefined ? { preferences: existing.preferences } : {}),
|
||||
});
|
||||
}
|
||||
}
|
||||
this.persist(migrated);
|
||||
this.subscriptions = migrated;
|
||||
@@ -118,14 +208,15 @@ export class PushTokenStore {
|
||||
}
|
||||
}
|
||||
|
||||
private persist(subscriptions: ReadonlyMap<string, number>): void {
|
||||
private persist(subscriptions: ReadonlyMap<string, StoredSubscriptionEntry>): void {
|
||||
try {
|
||||
const payload =
|
||||
JSON.stringify(
|
||||
{
|
||||
subscriptions: Array.from(subscriptions, ([token, expiresAt]) => ({
|
||||
subscriptions: Array.from(subscriptions, ([token, entry]) => ({
|
||||
token,
|
||||
expiresAt: new Date(expiresAt).toISOString(),
|
||||
expiresAt: new Date(entry.expiresAt).toISOString(),
|
||||
...(entry.preferences !== undefined ? { preferences: entry.preferences } : {}),
|
||||
})),
|
||||
},
|
||||
null,
|
||||
|
||||
@@ -2095,6 +2095,43 @@ test("push token registration can be revoked by the connected client", async ()
|
||||
]);
|
||||
});
|
||||
|
||||
test("push token registration forwards notification preferences to pushNotifications.renew", async () => {
|
||||
const renewed: Array<{ token: string; preferences: unknown }> = [];
|
||||
const session = createSessionForTest({
|
||||
pushNotifications: asPushNotifications({
|
||||
renew: (token: string, preferences?: unknown) => renewed.push({ token, preferences }),
|
||||
}),
|
||||
});
|
||||
|
||||
const preferences = {
|
||||
enabled: true,
|
||||
events: {
|
||||
agentPermission: true,
|
||||
agentError: true,
|
||||
agentFinished: true,
|
||||
terminalNeedsInput: true,
|
||||
terminalFinished: false,
|
||||
},
|
||||
plugins: {
|
||||
enabled: true,
|
||||
muted: ["review-bot"],
|
||||
},
|
||||
};
|
||||
|
||||
await session.handleMessage({
|
||||
type: "register_push_token",
|
||||
token: "ExponentPushToken[prefs-device]",
|
||||
preferences,
|
||||
});
|
||||
|
||||
expect(renewed).toEqual([
|
||||
{
|
||||
token: "ExponentPushToken[prefs-device]",
|
||||
preferences,
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
test("push token revocation only acknowledges durable removal", async () => {
|
||||
const renewed: string[] = [];
|
||||
const messages: SessionOutboundMessage[] = [];
|
||||
|
||||
@@ -3701,7 +3701,7 @@ export class Session {
|
||||
await this.handleListCommandsRequest(msg);
|
||||
return;
|
||||
case "register_push_token":
|
||||
this.handleRegisterPushToken(msg.token);
|
||||
this.handleRegisterPushToken(msg.token, msg.preferences);
|
||||
return;
|
||||
case "push.unregister.request":
|
||||
this.pushNotifications.revoke(msg.token);
|
||||
@@ -5653,9 +5653,12 @@ export class Session {
|
||||
/**
|
||||
* Handle push token registration
|
||||
*/
|
||||
private handleRegisterPushToken(token: string): void {
|
||||
private handleRegisterPushToken(
|
||||
token: string,
|
||||
preferences?: Parameters<PushNotifications["renew"]>[1],
|
||||
): void {
|
||||
this.currentClientMetadata().pushToken = token;
|
||||
this.pushNotifications.renew(token);
|
||||
this.pushNotifications.renew(token, preferences);
|
||||
this.sessionLogger.info("Registered push token");
|
||||
}
|
||||
|
||||
@@ -9498,7 +9501,8 @@ export class Session {
|
||||
): void {
|
||||
if (
|
||||
message.type !== "agent_attention_required" &&
|
||||
message.type !== "terminal_attention_required"
|
||||
message.type !== "terminal_attention_required" &&
|
||||
message.type !== "plugin.notification"
|
||||
) {
|
||||
subscription.owner.emit(message);
|
||||
return;
|
||||
@@ -9507,11 +9511,13 @@ export class Session {
|
||||
message.payload.shouldNotify &&
|
||||
subscription.notifications &&
|
||||
!notified.has(subscription.owner.source);
|
||||
subscription.owner.emit(
|
||||
message.type === "agent_attention_required"
|
||||
? { ...message, payload: { ...message.payload, shouldNotify } }
|
||||
: { ...message, payload: { ...message.payload, shouldNotify } },
|
||||
);
|
||||
if (message.type === "agent_attention_required") {
|
||||
subscription.owner.emit({ ...message, payload: { ...message.payload, shouldNotify } });
|
||||
} else if (message.type === "terminal_attention_required") {
|
||||
subscription.owner.emit({ ...message, payload: { ...message.payload, shouldNotify } });
|
||||
} else {
|
||||
subscription.owner.emit({ ...message, payload: { ...message.payload, shouldNotify } });
|
||||
}
|
||||
if (shouldNotify) notified.add(subscription.owner.source);
|
||||
}
|
||||
|
||||
@@ -9739,6 +9745,23 @@ function isValidGitHubRepoSegment(value: string): boolean {
|
||||
return /^[A-Za-z0-9._-]+$/u.test(value);
|
||||
}
|
||||
|
||||
function statusEventCategory(
|
||||
status: Extract<SessionOutboundMessage, { type: "status" }>["payload"]["status"],
|
||||
): SessionEventSubscription | null {
|
||||
switch (status) {
|
||||
case "server_info":
|
||||
return "status.server_info";
|
||||
case "daemon_config_changed":
|
||||
return "status.daemon_config_changed";
|
||||
case "plugin_catalog_changed":
|
||||
return "status.plugin_catalog_changed";
|
||||
case "plugin_settings_changed":
|
||||
return "status.plugin_settings_changed";
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function sessionEventCategory(message: SessionOutboundMessage): SessionEventSubscription | null {
|
||||
switch (message.type) {
|
||||
case "project.update":
|
||||
@@ -9752,23 +9775,13 @@ function sessionEventCategory(message: SessionOutboundMessage): SessionEventSubs
|
||||
case "agent.provider_subagents.update":
|
||||
case "agent.background_work.update":
|
||||
case "terminal_attention_required":
|
||||
case "plugin.notification":
|
||||
case "activity_log":
|
||||
case "hub.execution.agent.update":
|
||||
case "hub.execution.agent.stream":
|
||||
return message.type;
|
||||
case "status":
|
||||
switch (message.payload.status) {
|
||||
case "server_info":
|
||||
return "status.server_info";
|
||||
case "daemon_config_changed":
|
||||
return "status.daemon_config_changed";
|
||||
case "plugin_catalog_changed":
|
||||
return "status.plugin_catalog_changed";
|
||||
case "plugin_settings_changed":
|
||||
return "status.plugin_settings_changed";
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
return statusEventCategory(message.payload.status);
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
@@ -9791,6 +9804,7 @@ function legacyWantsEvent(
|
||||
return capabilities.has(CLIENT_CAPS.providerSubagents);
|
||||
// Old apps parse outbound messages strictly and do not know this type.
|
||||
case "agent.background_work.update":
|
||||
case "plugin.notification":
|
||||
return false;
|
||||
default:
|
||||
return true;
|
||||
|
||||
@@ -12,7 +12,7 @@ import {
|
||||
} from "../bootstrap.js";
|
||||
import type { AgentClient, AgentProvider } from "../agent/agent-sdk-types.js";
|
||||
import { createTestAgentClients } from "./fake-agent-client.js";
|
||||
import type { PushNotificationSender } from "../push/index.js";
|
||||
import type { PushNotifications, PushNotificationSender } from "../push/index.js";
|
||||
import type { AgentProfile } from "@getpaseo/protocol/messages";
|
||||
import type { TailscaleNetwork } from "../listeners.js";
|
||||
|
||||
@@ -50,6 +50,7 @@ interface TestPaseoDaemonOptions {
|
||||
dictationFinalTimeoutMs?: number;
|
||||
auth?: PaseoDaemonConfig["auth"];
|
||||
pushNotificationSender?: PushNotificationSender;
|
||||
pushNotifications?: PushNotifications;
|
||||
serviceProxy?: PaseoDaemonConfig["serviceProxy"];
|
||||
webUi?: PaseoDaemonConfig["webUi"];
|
||||
trustedProxies?: PaseoDaemonConfig["trustedProxies"];
|
||||
@@ -215,6 +216,7 @@ async function prepareTestDaemonConfig(
|
||||
appBaseUrl: "https://app.paseo.sh",
|
||||
auth: options.auth,
|
||||
pushNotificationSender: options.pushNotificationSender,
|
||||
pushNotifications: options.pushNotifications,
|
||||
serviceProxy: options.serviceProxy,
|
||||
webUi: options.webUi,
|
||||
trustedProxies: options.trustedProxies,
|
||||
|
||||
@@ -1,3 +1,10 @@
|
||||
import { mkdtempSync, rmSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import path from "node:path";
|
||||
import {
|
||||
DEFAULT_NOTIFICATION_PREFERENCES,
|
||||
type NotificationKind,
|
||||
} from "@getpaseo/protocol/notification-preferences";
|
||||
import { createWorkspaceRuntimeStore } from "./workspace-runtime-store/index.js";
|
||||
import { SessionDelivery } from "./session/owned-subscriptions/index.js";
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
@@ -11,7 +18,11 @@ import type { ScheduleService } from "./schedule/service.js";
|
||||
import type { CheckoutDiffManager } from "./checkout-diff-manager.js";
|
||||
import { asInternals, createStub } from "./test-utils/class-mocks.js";
|
||||
import { createProviderSnapshotManagerStub } from "./test-utils/session-stubs.js";
|
||||
import type { PushNotificationSender, PushPayload } from "./push/index.js";
|
||||
import {
|
||||
createPushNotifications,
|
||||
type PushNotificationSender,
|
||||
type PushPayload,
|
||||
} from "./push/index.js";
|
||||
import type { WorkspaceAutoName } from "./workspace-auto-name.js";
|
||||
|
||||
const WORKSPACE_ID = "workspace-1";
|
||||
@@ -77,14 +88,20 @@ function createWorkspaceAutoNameStub(): WorkspaceAutoName {
|
||||
|
||||
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 });
|
||||
}
|
||||
}
|
||||
|
||||
function createServer(agentManagerOverrides?: Record<string, unknown>) {
|
||||
function createServer(
|
||||
agentManagerOverrides?: Record<string, unknown>,
|
||||
customPushSender?: PushNotificationSender,
|
||||
) {
|
||||
const pushNotifications = new RecordingPushNotificationSender();
|
||||
const sender = customPushSender ?? pushNotifications;
|
||||
const agentManager = {
|
||||
subscribe: vi.fn(() => () => {}),
|
||||
onStop: () => () => {},
|
||||
@@ -148,7 +165,7 @@ function createServer(agentManagerOverrides?: Record<string, unknown>) {
|
||||
undefined,
|
||||
undefined,
|
||||
undefined,
|
||||
pushNotifications,
|
||||
sender,
|
||||
createProviderSnapshotManagerStub().manager,
|
||||
);
|
||||
|
||||
@@ -357,7 +374,7 @@ describe("VoiceAssistantWebSocketServer notification payloads", () => {
|
||||
expect(pushNotifications.sent).toHaveLength(1);
|
||||
});
|
||||
|
||||
it("does not push error attention when the only connected client has never sent a heartbeat", async () => {
|
||||
it("pushes error attention with agent error NotificationKind when the only connected client has never sent a heartbeat", async () => {
|
||||
const { server, pushNotifications } = createServer();
|
||||
const ws = connectClient(server, null);
|
||||
|
||||
@@ -369,7 +386,76 @@ describe("VoiceAssistantWebSocketServer notification payloads", () => {
|
||||
});
|
||||
|
||||
expect(readAttentionRequiredMessage(ws).shouldNotify).toBe(false);
|
||||
expect(pushNotifications.sent).toEqual([]);
|
||||
expect(pushNotifications.sentWithKind).toEqual([
|
||||
{
|
||||
payload: {
|
||||
title: "Agent needs attention",
|
||||
body: "Encountered an error.",
|
||||
data: {
|
||||
serverId: "srv-test",
|
||||
workspaceId: WORKSPACE_ID,
|
||||
agentId: "agent-no-heartbeat",
|
||||
reason: "error",
|
||||
},
|
||||
},
|
||||
kind: { kind: "agent", reason: "error" },
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it("filters agent finished, permission, and error pushes per token preferences", async () => {
|
||||
const home = mkdtempSync(path.join(tmpdir(), "paseo-ws-agent-prefs-"));
|
||||
try {
|
||||
const deliveries: Array<{ tokens: string[]; payload: PushPayload }> = [];
|
||||
const realPush = createPushNotifications({
|
||||
logger: createStub<pino.Logger>(createLogger()),
|
||||
filePath: path.join(home, "push-tokens.json"),
|
||||
deliver: async (tokens, payload) => {
|
||||
deliveries.push({ tokens, payload });
|
||||
},
|
||||
});
|
||||
// Phone A: explicit default preferences (permission: true, error: true, finished: false)
|
||||
realPush.renew("ExponentPushToken[phone-default]", DEFAULT_NOTIFICATION_PREFERENCES);
|
||||
// Phone B: finished enabled, error disabled
|
||||
realPush.renew("ExponentPushToken[phone-finished-only]", {
|
||||
...DEFAULT_NOTIFICATION_PREFERENCES,
|
||||
events: {
|
||||
...DEFAULT_NOTIFICATION_PREFERENCES.events,
|
||||
agentPermission: false,
|
||||
agentError: false,
|
||||
agentFinished: true,
|
||||
},
|
||||
});
|
||||
|
||||
const { server } = createServer(undefined, realPush);
|
||||
|
||||
await asInternals<WebSocketServerInternals>(server).broadcastAgentAttention({
|
||||
agentId: "agent-1",
|
||||
provider: "claude",
|
||||
reason: "finished",
|
||||
attentionTimestamp: new Date(1_000),
|
||||
});
|
||||
await asInternals<WebSocketServerInternals>(server).broadcastAgentAttention({
|
||||
agentId: "agent-1",
|
||||
provider: "claude",
|
||||
reason: "permission",
|
||||
attentionTimestamp: new Date(2_000),
|
||||
});
|
||||
await asInternals<WebSocketServerInternals>(server).broadcastAgentAttention({
|
||||
agentId: "agent-1",
|
||||
provider: "claude",
|
||||
reason: "error",
|
||||
attentionTimestamp: new Date(3_000),
|
||||
});
|
||||
|
||||
expect(deliveries.map((d) => ({ tokens: d.tokens, reason: d.payload.data.reason }))).toEqual([
|
||||
{ tokens: ["ExponentPushToken[phone-finished-only]"], reason: "finished" },
|
||||
{ tokens: ["ExponentPushToken[phone-default]"], reason: "permission" },
|
||||
{ tokens: ["ExponentPushToken[phone-default]"], reason: "error" },
|
||||
]);
|
||||
} finally {
|
||||
rmSync(home, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
it("notifies once while an agent's finish stays unread", async () => {
|
||||
const { server, pushNotifications } = createServer();
|
||||
|
||||
@@ -1156,6 +1156,7 @@ describe("relay external socket reconnect behavior", () => {
|
||||
expect(serverInfo.features?.hopliteProvider).toBe(false);
|
||||
expect(serverInfo.features?.fxProvider).toBe(false);
|
||||
expect(serverInfo.features?.pluginLogs).toBe(true);
|
||||
expect(serverInfo.features?.pushNotificationPreferences).toBe(true);
|
||||
expect(serverInfo.features?.workspaceMarkUnread).toBe(true);
|
||||
expect(serverInfo.features?.["terminal-input-mode-replay"]).toBe(true);
|
||||
expect(serverInfo.features?.["terminal-size-ownership"]).toBe(true);
|
||||
|
||||
@@ -1,3 +1,10 @@
|
||||
import { mkdtempSync, rmSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import path from "node:path";
|
||||
import {
|
||||
DEFAULT_NOTIFICATION_PREFERENCES,
|
||||
type NotificationKind,
|
||||
} from "@getpaseo/protocol/notification-preferences";
|
||||
import { createWorkspaceRuntimeStore } from "./workspace-runtime-store/index.js";
|
||||
import { SessionDelivery } from "./session/owned-subscriptions/index.js";
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
@@ -17,7 +24,11 @@ import type {
|
||||
import type { PersistedWorkspaceRecord, WorkspaceRegistry } from "./workspace-registry.js";
|
||||
import { asInternals, createStub } from "./test-utils/class-mocks.js";
|
||||
import { createProviderSnapshotManagerStub } from "./test-utils/session-stubs.js";
|
||||
import type { PushNotificationSender, PushPayload } from "./push/index.js";
|
||||
import {
|
||||
createPushNotifications,
|
||||
type PushNotificationSender,
|
||||
type PushPayload,
|
||||
} from "./push/index.js";
|
||||
import type { WorkspaceAutoName } from "./workspace-auto-name.js";
|
||||
|
||||
const wsModuleMock = vi.hoisted(() => {
|
||||
@@ -51,9 +62,11 @@ import { VoiceAssistantWebSocketServer } from "./websocket-server.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 });
|
||||
}
|
||||
}
|
||||
|
||||
@@ -115,8 +128,13 @@ function createWorkspaceRegistry(records: PersistedWorkspaceRecord[]): Workspace
|
||||
});
|
||||
}
|
||||
|
||||
function createServer(terminalManager: TerminalManager, workspaceRegistry?: WorkspaceRegistry) {
|
||||
function createServer(
|
||||
terminalManager: TerminalManager,
|
||||
workspaceRegistry?: WorkspaceRegistry,
|
||||
customPushSender?: PushNotificationSender,
|
||||
) {
|
||||
const pushNotifications = new RecordingPushNotificationSender();
|
||||
const sender = customPushSender ?? pushNotifications;
|
||||
const agentManager = {
|
||||
setAgentAttentionCallback: vi.fn(),
|
||||
subscribe: vi.fn(() => () => {}),
|
||||
@@ -179,7 +197,7 @@ function createServer(terminalManager: TerminalManager, workspaceRegistry?: Work
|
||||
undefined,
|
||||
undefined,
|
||||
undefined,
|
||||
pushNotifications,
|
||||
sender,
|
||||
createProviderSnapshotManagerStub().manager,
|
||||
);
|
||||
|
||||
@@ -502,5 +520,67 @@ describe("VoiceAssistantWebSocketServer terminal attention notifications", () =>
|
||||
terminalId: "term-1",
|
||||
workspaceId: "ws-1",
|
||||
});
|
||||
expect(pushNotifications.sentWithKind[0]?.kind).toEqual({
|
||||
kind: "terminal",
|
||||
reason: "finished",
|
||||
});
|
||||
});
|
||||
|
||||
it("filters terminal needs_input and finished pushes per token preferences", async () => {
|
||||
const home = mkdtempSync(path.join(tmpdir(), "paseo-ws-terminal-prefs-"));
|
||||
try {
|
||||
const deliveries: Array<{ tokens: string[]; title: string }> = [];
|
||||
const realPush = createPushNotifications({
|
||||
logger: createStub<pino.Logger>(createLogger()),
|
||||
filePath: path.join(home, "push-tokens.json"),
|
||||
deliver: async (tokens, payload) => {
|
||||
deliveries.push({ tokens, title: payload.title });
|
||||
},
|
||||
});
|
||||
// Token with explicit default preferences: terminalNeedsInput: true, terminalFinished: false
|
||||
realPush.renew("ExponentPushToken[phone-default]", DEFAULT_NOTIFICATION_PREFERENCES);
|
||||
// Token with terminalFinished: true, terminalNeedsInput: false
|
||||
realPush.renew("ExponentPushToken[phone-terminal-finished]", {
|
||||
...DEFAULT_NOTIFICATION_PREFERENCES,
|
||||
events: {
|
||||
...DEFAULT_NOTIFICATION_PREFERENCES.events,
|
||||
terminalNeedsInput: false,
|
||||
terminalFinished: true,
|
||||
},
|
||||
});
|
||||
|
||||
const { manager, emit } = createTerminalManager();
|
||||
createServer(manager, createWorkspaceRegistry([workspaceRecord()]), realPush);
|
||||
|
||||
emit(
|
||||
transition({
|
||||
previousState: "working",
|
||||
previousChangedAt: 0,
|
||||
state: "attention",
|
||||
changedAt: 15_000,
|
||||
}),
|
||||
);
|
||||
await flushAsync();
|
||||
|
||||
emit(
|
||||
transition({
|
||||
previousState: "working",
|
||||
previousChangedAt: 15_000,
|
||||
state: "idle",
|
||||
changedAt: 30_000,
|
||||
}),
|
||||
);
|
||||
await flushAsync();
|
||||
|
||||
expect(deliveries).toEqual([
|
||||
{ tokens: ["ExponentPushToken[phone-default]"], title: "Terminal needs input" },
|
||||
{
|
||||
tokens: ["ExponentPushToken[phone-terminal-finished]"],
|
||||
title: "Terminal finished",
|
||||
},
|
||||
]);
|
||||
} finally {
|
||||
rmSync(home, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
@@ -573,6 +573,24 @@ function requireWebSocketServices(params: {
|
||||
/**
|
||||
* WebSocket server that only accepts sockets + parses/forwards messages to the session layer.
|
||||
*/
|
||||
function initPushNotifications(
|
||||
logger: pino.Logger,
|
||||
paseoHome: string,
|
||||
pushNotifications?: PushNotifications,
|
||||
pushNotificationSender?: PushNotificationSender,
|
||||
): { pushNotifications: PushNotifications; pushNotificationSender: PushNotificationSender } {
|
||||
const notifications =
|
||||
pushNotifications ??
|
||||
createPushNotifications({
|
||||
logger: logger.child({ module: "push" }),
|
||||
filePath: join(paseoHome, "push-tokens.json"),
|
||||
});
|
||||
return {
|
||||
pushNotifications: notifications,
|
||||
pushNotificationSender: pushNotificationSender ?? notifications,
|
||||
};
|
||||
}
|
||||
|
||||
export class VoiceAssistantWebSocketServer {
|
||||
private readonly logger: pino.Logger;
|
||||
private readonly wss: WebSocketServer;
|
||||
@@ -726,6 +744,7 @@ export class VoiceAssistantWebSocketServer {
|
||||
orchestrationSkills?: SessionOptions["orchestrationSkills"],
|
||||
workspaceLabelService?: WorkspaceLabelService,
|
||||
workspaceArchiveOperations?: WorkspaceArchiveOperations,
|
||||
pushNotifications?: PushNotifications,
|
||||
) {
|
||||
this.logger = logger.child({ module: "websocket-server" });
|
||||
this.workspaceSetupRuntime = workspaceSetupRuntime;
|
||||
@@ -861,12 +880,14 @@ export class VoiceAssistantWebSocketServer {
|
||||
unsubscribeChange();
|
||||
};
|
||||
|
||||
const pushLogger = this.logger.child({ module: "push" });
|
||||
this.pushNotifications = createPushNotifications({
|
||||
logger: pushLogger,
|
||||
filePath: join(paseoHome, "push-tokens.json"),
|
||||
});
|
||||
this.pushNotificationSender = pushNotificationSender ?? this.pushNotifications;
|
||||
const push = initPushNotifications(
|
||||
this.logger,
|
||||
paseoHome,
|
||||
pushNotifications,
|
||||
pushNotificationSender,
|
||||
);
|
||||
this.pushNotifications = push.pushNotifications;
|
||||
this.pushNotificationSender = push.pushNotificationSender;
|
||||
|
||||
this.agentManager.setAgentAttentionCallback((params) => {
|
||||
void this.broadcastAgentAttention(params).catch((err) => {
|
||||
@@ -2153,6 +2174,8 @@ export class VoiceAssistantWebSocketServer {
|
||||
...(this.advertiseRelayConfig ? { relayConfig: true } : {}),
|
||||
// COMPAT(pushTokenRevocation): added in v0.3.2, remove gate after 2027-02-10.
|
||||
pushTokenRevocation: true,
|
||||
// COMPAT(pushNotificationPreferences): added in v0.18.0, remove gate after 2027-06-01.
|
||||
pushNotificationPreferences: true,
|
||||
// COMPAT(plugins): added in v0.3.0, remove gate after 2027-08-07.
|
||||
plugins: true,
|
||||
pluginManagement: true,
|
||||
@@ -2168,6 +2191,8 @@ export class VoiceAssistantWebSocketServer {
|
||||
pluginTimelineItems: true,
|
||||
// COMPAT(pluginSubscriptions): added in v0.15.0, remove gate after 2027-05-02.
|
||||
pluginSubscriptions: true,
|
||||
// COMPAT(pluginNotifications): added in v0.18.0, remove gate after 2027-06-01.
|
||||
pluginNotifications: true,
|
||||
// COMPAT(skillManagement): added in v0.4.0, remove gate after 2027-08-16.
|
||||
skillManagement: true,
|
||||
// COMPAT(idleRuntimeCleanupSetting): added in v0.13.0, remove gate after 2027-04-26.
|
||||
@@ -3026,9 +3051,11 @@ export class VoiceAssistantWebSocketServer {
|
||||
);
|
||||
|
||||
if (plan.shouldPush) {
|
||||
void this.pushNotificationSender.send(notification).catch((err) => {
|
||||
this.logger.warn({ err, agentId: params.agentId }, "Failed to send push notification");
|
||||
});
|
||||
void this.pushNotificationSender
|
||||
.send(notification, { kind: "agent", reason: params.reason })
|
||||
.catch((err) => {
|
||||
this.logger.warn({ err, agentId: params.agentId }, "Failed to send push notification");
|
||||
});
|
||||
}
|
||||
|
||||
for (const { ws } of clientEntries) {
|
||||
@@ -3145,16 +3172,19 @@ export class VoiceAssistantWebSocketServer {
|
||||
|
||||
if (plan.shouldPush) {
|
||||
void this.pushNotificationSender
|
||||
.send({
|
||||
title,
|
||||
body,
|
||||
data: {
|
||||
serverId: this.serverId,
|
||||
terminalId: params.terminalId,
|
||||
cwd: params.cwd,
|
||||
...(workspaceId ? { workspaceId } : {}),
|
||||
.send(
|
||||
{
|
||||
title,
|
||||
body,
|
||||
data: {
|
||||
serverId: this.serverId,
|
||||
terminalId: params.terminalId,
|
||||
cwd: params.cwd,
|
||||
...(workspaceId ? { workspaceId } : {}),
|
||||
},
|
||||
},
|
||||
})
|
||||
{ kind: "terminal", reason: params.reason },
|
||||
)
|
||||
.catch((err) => {
|
||||
this.logger.warn(
|
||||
{ err, terminalId: params.terminalId },
|
||||
@@ -3185,6 +3215,95 @@ export class VoiceAssistantWebSocketServer {
|
||||
else this.sendToClient(ws, message);
|
||||
}
|
||||
}
|
||||
|
||||
public sendPluginNotification(params: {
|
||||
pluginId: string;
|
||||
notificationId: string;
|
||||
title: string;
|
||||
body: string;
|
||||
open?: import("@getpaseo/protocol/messages").PluginNotificationOpenTarget;
|
||||
data?: Record<string, import("@getpaseo/protocol/agent-types").JsonValue>;
|
||||
}): void {
|
||||
const clientEntries: Array<{
|
||||
ws: WebSocketLike;
|
||||
state: ClientPresenceState;
|
||||
}> = [];
|
||||
|
||||
for (const [ws, connection] of this.sessions) {
|
||||
if (this.pluginSocketIds.has(ws)) {
|
||||
continue;
|
||||
}
|
||||
if (!connection.session.wantsSourceEvent(ws, "plugin.notification")) {
|
||||
continue;
|
||||
}
|
||||
clientEntries.push({
|
||||
ws,
|
||||
state: this.getClientActivityState(connection.session, ws),
|
||||
});
|
||||
}
|
||||
|
||||
const notificationEntries = clientEntries.filter(({ ws }) =>
|
||||
this.sessions.get(ws)?.session.wantsSourceNotification(ws, "plugin.notification"),
|
||||
);
|
||||
const allStates = notificationEntries.map((entry) => entry.state);
|
||||
const nowMs = Date.now();
|
||||
const focusTarget =
|
||||
params.open?.type === "agent" ? { kind: "agent" as const, id: params.open.agentId } : null;
|
||||
|
||||
const plan = computeNotificationPlan({
|
||||
allStates,
|
||||
focusTarget,
|
||||
pushEligible: true,
|
||||
nowMs,
|
||||
});
|
||||
|
||||
if (plan.shouldPush) {
|
||||
void this.pushNotificationSender
|
||||
.send(
|
||||
{
|
||||
title: params.title,
|
||||
body: params.body,
|
||||
data: {
|
||||
kind: "plugin",
|
||||
serverId: this.serverId,
|
||||
pluginId: params.pluginId,
|
||||
notificationId: params.notificationId,
|
||||
...(params.open ? { open: params.open } : {}),
|
||||
...(params.data ? { data: params.data } : {}),
|
||||
},
|
||||
},
|
||||
{ kind: "plugin", pluginId: params.pluginId },
|
||||
)
|
||||
.catch((err) => {
|
||||
this.logger.warn(
|
||||
{ err, pluginId: params.pluginId, notificationId: params.notificationId },
|
||||
"Failed to send plugin push notification",
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
for (const { ws } of clientEntries) {
|
||||
const shouldNotify =
|
||||
plan.inAppRecipientIndex !== null &&
|
||||
notificationEntries[plan.inAppRecipientIndex]?.ws === ws;
|
||||
const message = wrapSessionMessage({
|
||||
type: "plugin.notification",
|
||||
payload: {
|
||||
serverId: this.serverId,
|
||||
pluginId: params.pluginId,
|
||||
notificationId: params.notificationId,
|
||||
title: params.title,
|
||||
body: params.body,
|
||||
...(params.open ? { open: params.open } : {}),
|
||||
...(params.data ? { data: params.data } : {}),
|
||||
shouldNotify,
|
||||
},
|
||||
});
|
||||
if (message.type === "session" && this.sessions.get(ws)?.session.delivery.isModern(ws))
|
||||
this.sessions.get(ws)!.session.publishToSource(ws, message.message);
|
||||
else this.sendToClient(ws, message);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
interface SocketRequestMetadata {
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
# Notifications plugin example
|
||||
|
||||
Sends notifications from a server lifecycle hook (`agent.turn.after`) and a plugin RPC (`alerts.send`),
|
||||
and handles notification taps on the client with `client.onNotificationOpen`.
|
||||
|
||||
```bash
|
||||
paseo plugin add /absolute/path/to/paseo/plugin-examples/notifications
|
||||
```
|
||||
|
||||
- `index.server.ts` calls `server.notifications.send` with a deduplication `key`, a declarative
|
||||
`open` fallback target, and structured `data`.
|
||||
- `index.client.tsx` registers the `alert` screen and a `client.onNotificationOpen` callback that
|
||||
navigates to an agent or opens the `alert` screen with the notification's payload.
|
||||
@@ -0,0 +1,70 @@
|
||||
import { useRpc, type PluginScreenProps } from "@getpaseo/plugin/client";
|
||||
import { useCallback, useMemo, useState } from "react";
|
||||
import { Pressable, Text, View } from "react-native";
|
||||
import { sendBuildAlert } from "../shared/alerts";
|
||||
|
||||
export function AlertScreen({ params, theme, layout }: PluginScreenProps) {
|
||||
const triggerAlert = useRpc(sendBuildAlert);
|
||||
const [lastStatus, setLastStatus] = useState<string | null>(null);
|
||||
const buildId = params.buildId ?? "none";
|
||||
const notificationId = params.notificationId ?? "none";
|
||||
const summary = params.summary ?? "No build alert selected.";
|
||||
|
||||
const handleSendSampleAlert = useCallback(async () => {
|
||||
const result = await triggerAlert({
|
||||
buildId: "101",
|
||||
title: "Build #101 failed",
|
||||
body: "Integration suite timed out on main",
|
||||
});
|
||||
setLastStatus(result.status);
|
||||
}, [triggerAlert]);
|
||||
|
||||
const styles = useMemo(
|
||||
() => ({
|
||||
container: {
|
||||
flex: 1,
|
||||
padding: layout.compact ? 16 : 24,
|
||||
gap: 12,
|
||||
backgroundColor: theme.colors.surface0,
|
||||
},
|
||||
heading: {
|
||||
fontSize: 18,
|
||||
fontWeight: "600" as const,
|
||||
color: theme.colors.foreground,
|
||||
},
|
||||
body: {
|
||||
fontSize: 14,
|
||||
color: theme.colors.foreground,
|
||||
},
|
||||
meta: {
|
||||
fontSize: 13,
|
||||
color: theme.colors.foregroundMuted,
|
||||
},
|
||||
button: {
|
||||
alignSelf: "flex-start" as const,
|
||||
paddingHorizontal: 14,
|
||||
paddingVertical: 8,
|
||||
borderRadius: 8,
|
||||
backgroundColor: theme.colors.surface2,
|
||||
},
|
||||
buttonLabel: {
|
||||
fontSize: 14,
|
||||
fontWeight: "500" as const,
|
||||
color: theme.colors.foreground,
|
||||
},
|
||||
}),
|
||||
[layout.compact, theme.colors],
|
||||
);
|
||||
|
||||
return (
|
||||
<View style={styles.container}>
|
||||
<Text style={styles.heading}>{`Build alert #${buildId}`}</Text>
|
||||
<Text style={styles.body}>{summary}</Text>
|
||||
<Text style={styles.meta}>{`Notification ID: ${notificationId}`}</Text>
|
||||
{lastStatus ? <Text style={styles.meta}>{`Last send status: ${lastStatus}`}</Text> : null}
|
||||
<Pressable accessibilityRole="button" style={styles.button} onPress={handleSendSampleAlert}>
|
||||
<Text style={styles.buttonLabel}>Send sample build alert</Text>
|
||||
</Pressable>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
import type { PluginClientContext } from "@getpaseo/plugin/client";
|
||||
import { AlertScreen } from "./client/alert-screen";
|
||||
|
||||
export default function contribute(client: PluginClientContext) {
|
||||
const removeScreen = client.addScreen({
|
||||
id: "alert",
|
||||
title: (params) => (params.buildId ? `Build #${params.buildId}` : "Build alerts"),
|
||||
Component: AlertScreen,
|
||||
});
|
||||
|
||||
const removeOpenHandler = client.onNotificationOpen(({ event, openScreen, navigation }) => {
|
||||
if (event.data?.kind === "agent" && typeof event.data.agentId === "string") {
|
||||
navigation.openAgent({ agentId: event.data.agentId, focusHost: true });
|
||||
return;
|
||||
}
|
||||
const buildId = typeof event.data?.buildId === "string" ? event.data.buildId : "latest";
|
||||
const summary =
|
||||
typeof event.data?.summary === "string"
|
||||
? event.data.summary
|
||||
: "Opened from plugin notification";
|
||||
openScreen({
|
||||
screenId: "alert",
|
||||
params: {
|
||||
buildId,
|
||||
notificationId: event.notificationId,
|
||||
summary,
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
return () => {
|
||||
removeOpenHandler();
|
||||
removeScreen();
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
import type { PluginServerContext } from "@getpaseo/plugin/server";
|
||||
import { sendBuildAlert } from "./shared/alerts";
|
||||
|
||||
export default function contribute(server: PluginServerContext) {
|
||||
const unhook = server.addHook("agent.turn.after", async ({ agent, outcome }) => {
|
||||
if (outcome.kind !== "failed" || agent.background) {
|
||||
return;
|
||||
}
|
||||
await server.notifications.send({
|
||||
title: agent.title ?? "Agent turn failed",
|
||||
body: outcome.error.message,
|
||||
key: `agent-failed:${agent.id}`,
|
||||
open: { type: "agent", agentId: agent.id },
|
||||
data: { kind: "agent", agentId: agent.id },
|
||||
});
|
||||
});
|
||||
|
||||
server.handle(sendBuildAlert, async ({ buildId, title, body, key }) => {
|
||||
return await server.notifications.send({
|
||||
title,
|
||||
body,
|
||||
key,
|
||||
open: {
|
||||
type: "screen",
|
||||
screenId: "alert",
|
||||
params: { buildId, summary: body },
|
||||
},
|
||||
data: {
|
||||
kind: "build",
|
||||
buildId,
|
||||
summary: body,
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
return () => {
|
||||
unhook();
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
{
|
||||
"id": "notifications-example",
|
||||
"name": "Build alerts",
|
||||
"description": "Sends build and agent failure notifications and opens the alert screen on tap.",
|
||||
"requirements": {
|
||||
"paseo": ">=0.18.0-beta.1"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
import { defineRpc } from "@getpaseo/plugin";
|
||||
import { z } from "zod";
|
||||
|
||||
export const sendBuildAlert = defineRpc({
|
||||
name: "alerts.send",
|
||||
input: z.object({
|
||||
buildId: z.string(),
|
||||
title: z.string(),
|
||||
body: z.string(),
|
||||
key: z.string().optional(),
|
||||
}),
|
||||
output: z.discriminatedUnion("status", [
|
||||
z.object({
|
||||
status: z.literal("sent"),
|
||||
notificationId: z.string(),
|
||||
}),
|
||||
z.object({
|
||||
status: z.literal("deduplicated"),
|
||||
}),
|
||||
z.object({
|
||||
status: z.literal("rate_limited"),
|
||||
}),
|
||||
]),
|
||||
});
|
||||
@@ -23,6 +23,7 @@ Local plugins are directory sources installed into one Paseo daemon. A plugin ca
|
||||
- [buttons](#header-buttons) in the workspace header and [fields](#new-workspace-items) on the New workspace screen;
|
||||
- [settings screens](#settings-screens) and light and dark themes in Settings → Appearance;
|
||||
- transformed and daemon-pushed agent timeline rows;
|
||||
- [notifications](#notifications) delivered to desktop, web, and mobile clients with custom tap routing;
|
||||
- schema-validated RPC handlers and event streams running beside the daemon;
|
||||
- [hooks](/docs/plugins/hooks) that change or observe workspace, worktree, and agent operations;
|
||||
- [agent providers](/docs/plugins/providers), [usage sources](#usage-sources), and [worktree managers](#worktree-managers);
|
||||
@@ -881,6 +882,78 @@ export default function contribute(client: PluginClientContext) {
|
||||
|
||||
Cleanup can be async. Release timers, watchers, sockets, and other resources created by the plugin. Reload, disable, and removal dispose the affected installation. Stopping a server plugin also closes its daemon session and stops its subprocess. Client installations follow [Hosts and lifecycle](#hosts-and-lifecycle), including retention during a temporary disconnect.
|
||||
|
||||
## Notifications {#notifications}
|
||||
|
||||
**Requires Paseo 0.18.** Call `server.notifications.send()` from a server hook, RPC handler, or background watcher to notify the user on their active desktop/web client or via mobile push when away.
|
||||
|
||||
```ts
|
||||
// index.server.ts
|
||||
import type { PluginServerContext } from "@getpaseo/plugin/server";
|
||||
|
||||
export default function contribute(server: PluginServerContext) {
|
||||
const unhook = server.addHook("agent.turn.after", async ({ agent, outcome }) => {
|
||||
if (outcome.kind !== "failed" || agent.background) return;
|
||||
await server.notifications.send({
|
||||
title: agent.title ?? "Agent failed",
|
||||
body: outcome.error.message,
|
||||
key: `agent-failed:${agent.id}`,
|
||||
open: { type: "agent", agentId: agent.id },
|
||||
data: { agentId: agent.id },
|
||||
});
|
||||
});
|
||||
return () => unhook();
|
||||
}
|
||||
```
|
||||
|
||||
### Send input and limits
|
||||
|
||||
| Field | Required | Limit / behavior |
|
||||
| ------- | -------- | ----------------------------------------------------------------------------------------------------------------- |
|
||||
| `title` | Yes | Non-empty string after trimming; truncated to 160 characters if longer. |
|
||||
| `body` | Yes | Trimmed string; truncated to 500 characters if longer. |
|
||||
| `key` | No | Trimmed string, 1–128 characters. An identical key from the same plugin within 60 seconds returns `deduplicated`. |
|
||||
| `open` | No | Declarative tap target (IDs up to 256 chars, serialized up to 1,024 UTF-8 bytes) used when no handler handles it. |
|
||||
| `data` | No | Plain JSON object up to 1,024 UTF-8 bytes when serialized, passed to `client.onNotificationOpen`. |
|
||||
|
||||
Declarative `open` targets require no client entry:
|
||||
|
||||
- `{ type: "agent", agentId: string }` opens and focuses the agent. When an active visible client is already focused on that agent, Paseo suppresses the notification.
|
||||
- `{ type: "workspace", workspaceId: string }` opens the workspace.
|
||||
- `{ type: "screen", screenId: string, params?: Record<string, string> }` opens your plugin's screen with URL params.
|
||||
|
||||
`server.notifications.send()` resolves to one of:
|
||||
|
||||
- `{ status: "sent", notificationId: string }` when accepted by the daemon for delivery (even if muted on a user's device).
|
||||
- `{ status: "deduplicated" }` when `key` matched a notification sent by your plugin within the last 60 seconds.
|
||||
- `{ status: "rate_limited" }` when your plugin exceeds its per-plugin token bucket (burst of 10, refilling 1 every 6 seconds).
|
||||
|
||||
Invalid fields, an empty `title`, or `open`/`data` larger than 1,024 UTF-8 bytes reject the returned promise. Users can mute all plugin notifications or mute individual plugins in **Settings → Notifications**.
|
||||
|
||||
### Handle notification taps on the client
|
||||
|
||||
Register `client.onNotificationOpen(handler)` in `index.client.tsx` when you need custom tap routing based on `data`:
|
||||
|
||||
```tsx
|
||||
// index.client.tsx
|
||||
import type { PluginClientContext } from "@getpaseo/plugin/client";
|
||||
|
||||
export default function contribute(client: PluginClientContext) {
|
||||
const unsub = client.onNotificationOpen(({ event, openScreen, navigation }) => {
|
||||
if (typeof event.data?.agentId === "string") {
|
||||
navigation.openAgent({ agentId: event.data.agentId, focusHost: true });
|
||||
} else {
|
||||
openScreen({
|
||||
screenId: "alert",
|
||||
params: { notificationId: event.notificationId },
|
||||
});
|
||||
}
|
||||
});
|
||||
return () => unsub();
|
||||
}
|
||||
```
|
||||
|
||||
The handler receives `PluginCommandCapabilities` (`paseo`, `rpc`, `openScreen`, `composers`, `openSettings`), `navigation.openAgent`, `navigation.openWorkspace`, and `event: { type: "opened", notificationId, data }`. Registering `onNotificationOpen` takes ownership of all notification taps for that plugin. On cold launch from a notification tap, Paseo waits for the target host's plugin catalog to finish loading before invoking your handler; if the plugin has no registered handler, every registered handler throws, or the catalog cannot load in time, Paseo falls back to the notification's declarative `open` target. See `plugin-examples/notifications`.
|
||||
|
||||
## Lifecycle hooks
|
||||
|
||||
Register async handlers with `server.addHook(name, handler)`. See [Hooks](/docs/plugins/hooks) for names, payloads, ordering, errors, and complete examples.
|
||||
|
||||
@@ -21,6 +21,7 @@ nav: 参考
|
||||
- 工作区标题栏中的[按钮](#header-buttons),以及新建工作区界面上的[字段](#new-workspace-items);
|
||||
- [设置界面](#settings-screens),以及 **设置 → 外观** 中的浅色和深色主题;
|
||||
- 经过转换的、以及由 daemon 推送的 Agent 时间线行;
|
||||
- 面向活跃客户端或移动推送的[通知](#notifications)以及自定义点击处理函数;
|
||||
- 在 daemon 旁运行、经过 schema 校验的 RPC 处理函数和事件流;
|
||||
- 修改或观察工作区、worktree 和 Agent 操作的[钩子](/docs/plugins/hooks);
|
||||
- [Agent Provider](/docs/plugins/providers)、[用量来源](#usage-sources)和 [worktree 管理器](#worktree-managers);
|
||||
@@ -676,6 +677,78 @@ export default function contribute(client: PluginClientContext) {
|
||||
|
||||
清理函数可以是异步的。请释放插件创建的计时器、监听器、套接字和其他资源。重新加载、停用和移除会销毁受影响的插件安装。停止服务端插件还会关闭它的 daemon 会话并停止其子进程。客户端安装遵循[主机与生命周期](#hosts-and-lifecycle)中的规则,包括在暂时断开连接时保留安装。
|
||||
|
||||
## 通知 {#notifications}
|
||||
|
||||
**需要 Paseo 0.18**。在服务端钩子、RPC 处理函数或后台监听器中调用 `server.notifications.send()`,可在用户当前活跃的桌面/Web 客户端上发送系统通知,或在用户离开时发送移动端推送通知。
|
||||
|
||||
```ts
|
||||
// index.server.ts
|
||||
import type { PluginServerContext } from "@getpaseo/plugin/server";
|
||||
|
||||
export default function contribute(server: PluginServerContext) {
|
||||
const unhook = server.addHook("agent.turn.after", async ({ agent, outcome }) => {
|
||||
if (outcome.kind !== "failed" || agent.background) return;
|
||||
await server.notifications.send({
|
||||
title: agent.title ?? "Agent failed",
|
||||
body: outcome.error.message,
|
||||
key: `agent-failed:${agent.id}`,
|
||||
open: { type: "agent", agentId: agent.id },
|
||||
data: { agentId: agent.id },
|
||||
});
|
||||
});
|
||||
return () => unhook();
|
||||
}
|
||||
```
|
||||
|
||||
### 发送输入与限制 {#send-input-and-limits}
|
||||
|
||||
| 字段 | 必填 | 限制 / 行为 |
|
||||
| ------- | ---- | ----------------------------------------------------------------------------------------------- |
|
||||
| `title` | 是 | 去除首尾空白后的非空字符串;超过 160 个字符时自动截断。 |
|
||||
| `body` | 是 | 去除首尾空白的字符串;超过 500 个字符时自动截断。 |
|
||||
| `key` | 否 | 去除首尾空白的字符串,1–128 个字符。同一插件在 60 秒内发送相同 `key` 会返回 `deduplicated`。 |
|
||||
| `open` | 否 | 声明式点击目标(ID 最多 256 个字符,序列化后不超过 1,024 UTF-8 字节),在未由处理函数处理时用。 |
|
||||
| `data` | 否 | 序列化后不超过 1,024 UTF-8 字节的纯 JSON 对象,点击通知时传递给 `client.onNotificationOpen`。 |
|
||||
|
||||
声明式 `open` 目标无需客户端入口:
|
||||
|
||||
- `{ type: "agent", agentId: string }` 打开并聚焦该 Agent。若当前活跃可见客户端已聚焦在该 Agent 上,Paseo 会抑制该通知。
|
||||
- `{ type: "workspace", workspaceId: string }` 打开该工作区。
|
||||
- `{ type: "screen", screenId: string, params?: Record<string, string> }` 携带 URL 参数打开插件界面。
|
||||
|
||||
`server.notifications.send()` 会解析为以下结果之一:
|
||||
|
||||
- `{ status: "sent", notificationId: string }`:daemon 已受理并进入投递流程(即使某台设备静音了该通知)。
|
||||
- `{ status: "deduplicated" }`:`key` 与当前插件在过去 60 秒内发送的通知重复。
|
||||
- `{ status: "rate_limited" }`:当前插件超出了单插件令牌桶限制(突发容量 10,每 6 秒补充 1 个)。
|
||||
|
||||
字段非法、`title` 为空,或 `open`/`data` 超过 1,024 UTF-8 字节会使返回的 Promise 被拒绝。用户可以在 **设置 → 通知** 中关闭全部插件通知或静音单个插件。
|
||||
|
||||
### 在客户端处理通知点击 {#handle-notification-taps-on-the-client}
|
||||
|
||||
如需根据 `data` 自定义点击跳转逻辑,请在 `index.client.tsx` 中注册 `client.onNotificationOpen(handler)`:
|
||||
|
||||
```tsx
|
||||
// index.client.tsx
|
||||
import type { PluginClientContext } from "@getpaseo/plugin/client";
|
||||
|
||||
export default function contribute(client: PluginClientContext) {
|
||||
const unsub = client.onNotificationOpen(({ event, openScreen, navigation }) => {
|
||||
if (typeof event.data?.agentId === "string") {
|
||||
navigation.openAgent({ agentId: event.data.agentId, focusHost: true });
|
||||
} else {
|
||||
openScreen({
|
||||
screenId: "alert",
|
||||
params: { notificationId: event.notificationId },
|
||||
});
|
||||
}
|
||||
});
|
||||
return () => unsub();
|
||||
}
|
||||
```
|
||||
|
||||
处理函数接收 `PluginCommandCapabilities`(`paseo`、`rpc`、`openScreen`、`composers`、`openSettings`)、`navigation.openAgent`、`navigation.openWorkspace` 以及 `event: { type: "opened", notificationId, data }`。注册 `onNotificationOpen` 后,该处理函数会接管此插件的所有通知点击。通过通知点击冷启动应用时,Paseo 会等待目标主机的插件目录加载完成后再调用你的处理函数;若插件未注册处理函数、所有已注册处理函数均抛出错误,或目录未能在时限内加载完成,Paseo 会回退到通知的声明式 `open` 目标。完整示例见 `plugin-examples/notifications`。
|
||||
|
||||
## 生命周期钩子 {#lifecycle-hooks}
|
||||
|
||||
使用 `server.addHook(name, handler)` 注册异步处理函数。请参阅[钩子](/docs/plugins/hooks),了解命名、载荷、顺序、错误处理和完整示例。
|
||||
|
||||
Reference in New Issue
Block a user