Compare commits

..
Author SHA1 Message Date
Mohamed Boudra 89773d2ec3 fix(app): surface and retry client plugin bypass persistence errors 2026-12-02 11:35:41 +01:00
Mohamed Boudra 8fcd4e151d chore(app): simplify General setup row copy 2026-12-02 11:25:43 +01:00
Mohamed Boudra 3e17a0e125 feat(app): add General settings toggle to bypass client plugin approval 2026-12-02 11:17:03 +01:00
Mohamed Boudra a5fe858831 test(desktop): wait deterministically for seeded plugin approval at startup 2026-12-02 10:19:37 +01:00
Mohamed Boudra 64db9df945 fix(app): address plugin approval review findings and desktop E2E startup 2026-12-02 10:13:43 +01:00
Mohamed Boudra 51601d45cf test(app): approve client plugins via UI in browser E2E specs 2026-12-02 09:49:09 +01:00
Mohamed Boudra d7d6523333 feat(app): require one-time approval before running client plugins
Add a per-host, per-plugin client execution consent model and sequential confirmation sheet before evaluating plugin client bundles.

- Enforce fail-closed execution approval inside PluginRegistry before runPluginClientBundle runs and hydrate stored decisions before catalog reconciliation.
- Queue multiple unreviewed client plugins sequentially in one persistent AdaptiveModalSheet with monotonic request IDs and steady layout geometry.
- Persist approved and declined decisions per (host, plugin) across reloads and reconnects, clear host trust on host removal or relay identity key replacement, and clear plugin decisions on uninstall.
- Surface blocked plugins in Settings -> Plugins and plugin surfaces so users can allow or block client execution on this device.
2026-12-02 09:49:09 +01:00
158 changed files with 3828 additions and 5323 deletions
+2 -2
View File
@@ -178,9 +178,9 @@ the switch. Promoting the switch cuts the running turn once the target is known
already on the target takes the message and its settings as a plain prompt. A switch that fails keeps
the message and holds the queue; the reason is in the daemon log.
The queue is saved in `$PASEO_HOME/paseo.db` ([data model](data-model.md#agent-message-queues)),
The queue is saved in `$PASEO_HOME/agent-queues/` ([data model](data-model.md#directory-layout)),
and a message is saved before its receipt is sent. Inline images are first saved as uploads, so the
queue holds references. An empty message is refused, and a recipient holds at most 100
queue file holds references. An empty message is refused, and a recipient holds at most 100
messages.
A message is marked `dispatching` before the provider can receive it and removed when the provider
+5 -9
View File
@@ -34,7 +34,7 @@ Workspace archive runs lifecycle teardown from the exact `cwd` but removes only
`worktreeRoot` after its last active reference disappears. Worktree recovery recreates that backing
checkout from `mainRepoRoot`, then restores the relative path from `worktreeRoot` to `cwd`.
Paseo persists most stores as JSON files, and agent timelines and agent message queues in the [daemon database](#daemon-database). JSON data is validated at runtime with Zod schemas. Most JSON stores write atomically (write to temp file, then rename); a few still use plain `writeFile` — see each section. JSON stores have no schema-versioning/migration framework — schemas rely on optional fields with defaults for forward compatibility, with a small amount of inline normalization in `persisted-config.ts` for legacy provider/speech entries.
Paseo persists most stores as JSON files, and agent timelines in the [daemon database](#daemon-database). JSON data is validated at runtime with Zod schemas. Most JSON stores write atomically (write to temp file, then rename); a few still use plain `writeFile` — see each section. JSON stores have no schema-versioning/migration framework — schemas rely on optional fields with defaults for forward compatibility, with a small amount of inline normalization in `persisted-config.ts` for legacy provider/speech entries.
All server-side stores live under `$PASEO_HOME` (defaults to `~/.paseo`).
@@ -60,6 +60,9 @@ $PASEO_HOME/
│ └── {agentId}.json # One file per agent
├── schedules/
│ └── {scheduleId}.json # One file per schedule
├── agent-queues/
│ ├── {agentId}.json # Undelivered messages for one agent; removed when empty
│ └── {agentId}.json.corrupt.{ms} # Unreadable queue file, set aside at startup
├── projects/
│ ├── projects.json # Project registry
│ ├── workspaces.json # Workspace registry
@@ -185,7 +188,7 @@ Terminal activity contributes to the workspace status bucket **per `workspaceId`
## Daemon database
`$PASEO_HOME/paseo.db` is one SQLite file that the daemon opens at startup with `node:sqlite`
(`packages/server/src/server/database/`). Agent timelines and agent message queues live here. Each store is a
(`packages/server/src/server/database/`). Agent timelines are its only store today. Each store is a
`SchemaModule`: its own table-name prefix and an append-only list of migrations.
- **Migrations.** Startup runs every module's pending migrations in one transaction, so a failed
@@ -219,13 +222,6 @@ of a streamed assistant or reasoning message is stored as one chunk per source e
row, so a chunk never rewrites the message. An earlier file store rewrote the whole transcript on
every update. See [owned history](timeline-sync.md#owned-history).
### Agent message queues
`AgentMessageQueueStore` stores undelivered per-recipient messages in `agent_message_queue_items`
and monotonic per-recipient sequence counters in `agent_message_queue_recipients`. Message text and
structured payloads are stored as JSON strings so NUL bytes and lone surrogates round-trip through
`node:sqlite`. See [agent-lifecycle.md](agent-lifecycle.md).
---
## 2. Daemon Configuration
@@ -20,7 +20,9 @@ import {
} from "../support/helpers/composer";
import { openCommandCenter, closeCommandCenter } from "../support/helpers/command-center";
import { approveClientPluginsInUi } from "../support/helpers/plugin-execution-approval";
import {
PROMPT_PLUGIN_ID,
expectPromptsDrawnByPlugin,
withPromptTimelinePlugin,
} from "../support/helpers/plugin-timeline";
@@ -279,6 +281,7 @@ test("finds text in a prompt a timeline plugin draws", async ({ page }, testInfo
await agent.client.waitForFinish(agent.agentId, 15_000);
await withPromptTimelinePlugin(async () => {
await openAgentRoute(page, agent);
await approveClientPluginsInUi(page, [PROMPT_PLUGIN_ID]);
await expectPromptsDrawnByPlugin(page);
await openChatFind(page);
await query(page).fill("scope-needle");
@@ -25,7 +25,9 @@ import {
expectReadingStreamedMarkdown,
} from "../support/helpers/chat-outline";
import { createCreationScenario } from "../support/helpers/creation";
import { approveClientPluginsInUi } from "../support/helpers/plugin-execution-approval";
import {
PROMPT_PLUGIN_ID,
attachPromptTimelineEvidence,
expectPromptsDrawnByPlugin,
expectVirtualizedPluginPromptVisible,
@@ -118,6 +120,7 @@ test.describe("desktop chat outline", () => {
await withPromptTimelinePlugin(async () => {
await page.setViewportSize(WIDE_VIEWPORT);
await openAgentTimeline(page, agent);
await approveClientPluginsInUi(page, [PROMPT_PLUGIN_ID]);
await expectChatOutlinePrompts(page, 80);
await expectPromptsDrawnByPlugin(page);
await expectTimelinePromptNotMounted(page, agent.prompts[39]);
@@ -148,6 +151,7 @@ test.describe("desktop chat outline", () => {
const history = await holdOlderHistoryPages(page, agent);
await page.setViewportSize(WIDE_VIEWPORT);
await openAgentTimeline(page, agent);
await approveClientPluginsInUi(page, [PROMPT_PLUGIN_ID]);
await expectChatOutlinePrompts(page, 80);
await scrollThroughOlderHistoryPages(page, 2, history);
await scrollTimelineToNewestLoadedEdge(page);
@@ -1,4 +1,5 @@
import { expect, test, type Page } from "../support/fixtures";
import { approveClientPluginsInUi } from "../support/helpers/plugin-execution-approval";
import { withDirectoryPlugin } from "../support/helpers/plugin-timeline";
import {
attachImageFromMenu,
@@ -158,6 +159,7 @@ test.describe("Client slash commands", () => {
}`,
run: async () => {
await withOpenReadyMockAgent(page, { title: "Attached slash command" }, async () => {
await approveClientPluginsInUi(page, ["attachment-slash-e2e"]);
const input = composerLocator(page);
await input.fill("/pict");
await expect(
@@ -21,7 +21,6 @@ import {
expectAttachButtonDisabled,
fillComposerDraft,
dropFileOnComposer,
pasteFilesIntoComposer,
sendDraftToQueue,
expectQueuedMessageButton,
startRunningMockAgent,
@@ -153,7 +152,7 @@ test.describe("Composer attachments", () => {
// needed before this can be exercised end-to-end.
});
test("attaches files from the menu, clipboard, and drag and drop", async ({
test("attaches, previews, and removes an image before dropping a file", async ({
page,
withWorkspace,
}) => {
@@ -186,19 +185,6 @@ test.describe("Composer attachments", () => {
await expectComposerFocused(page);
});
await test.step("paste a Markdown file into the composer", async () => {
const file = {
name: "notes.md",
mimeType: "text/markdown",
buffer: Buffer.from("# Clipboard notes"),
};
const handled = await pasteFilesIntoComposer(page, [file]);
await expect(page.getByText(file.name, { exact: true })).toBeVisible();
await expect(page.getByRole("button", { name: file.name, exact: true })).toBeVisible();
expect(handled).toBe(true);
await expectComposerDraft(page, "");
});
await test.step("dropping an image focuses the composer", async () => {
await blurComposerInput(page);
await expectComposerNotFocused(page);
@@ -206,15 +192,6 @@ test.describe("Composer attachments", () => {
await expectAttachmentPill(page, "composer-image-attachment-pill");
await expectComposerFocused(page);
});
await test.step("paste a file and an image together", async () => {
await removeAttachmentPill(page, "composer-image-attachment-pill", "Remove image attachment");
await expect(page.getByTestId("composer-image-attachment-pill")).toHaveCount(0);
const file = { ...TEST_JSON, name: "clipboard.json" };
await pasteFilesIntoComposer(page, [file, TEST_IMAGE]);
await expect(page.getByRole("button", { name: file.name, exact: true })).toBeVisible();
await expectAttachmentPill(page, "composer-image-attachment-pill");
});
});
test("dropped JSON file renders as a file attachment in New Workspace", async ({ page }) => {
@@ -172,7 +172,7 @@ test("retrying failed agent initialization keeps the plugin metadata set on New
startup,
composerMetadata,
}) => {
await creation.openWorkspaceForm("local");
await creation.openWorkspaceForm("local", { approvePlugins: ["composer-metadata"] });
await composerMetadata.set({ "composer-metadata.tag": "kept" });
await creation.submitPrompt("Start the tagged task.", "Create");
await creation.expectAgentStillStarting();
@@ -15,6 +15,7 @@ import {
setNotificationSwitch,
setPluginNotificationSwitch,
} from "../support/helpers/notification-settings";
import { approveClientPluginsInUi } from "../support/helpers/plugin-execution-approval";
import { copyPluginExample } from "../support/helpers/plugin-fixture";
import { seedWorkspace, type SeedDaemonClient } from "../support/helpers/seed-client";
@@ -173,6 +174,7 @@ test.describe("Settings → Notifications and OS notification filtering", () =>
await seeded.client.patchDaemonConfig({ pluginsEnabled: true });
await seeded.client.installDirectoryPlugin(pluginExample.directory);
installedPlugin = true;
await approveClientPluginsInUi(page, ["notifications-example"]);
const pluginToggle = page.getByRole("switch", { name: "Build alerts", exact: true });
await expect(pluginToggle).toBeVisible();
@@ -0,0 +1,279 @@
import path from "node:path";
import { expect, test } from "../support/fixtures";
import { gotoAppShell, openSettings } from "../support/helpers/app";
import { openHostSection } from "../support/helpers/settings";
import { getServerId } from "../support/helpers/server-id";
import { waitForSettledPosition } from "../support/helpers/sheet-layout";
import { openPluginPage, openPluginPageActions } from "../support/helpers/plugin-gallery";
import {
allowPluginExecution,
cancelPluginExecutionBypassConfirm,
confirmPluginExecutionBypass,
declinePluginExecution,
ensureArtifactsDir,
expectExecutedPluginMarkers,
expectExecutedPluginMarkersContain,
expectPluginApprovalPrompt,
expectPluginExecutionBypass,
getExecutedPluginMarkers,
openPluginExecutionBypassConfirm,
pluginApprovalSheet,
pluginExecutionBypassConfirmModal,
pluginExecutionBypassSwitch,
reloadKeepingPersistedState,
setPluginExecutionBypass,
withInstalledClientPlugins,
type ClientProbePluginSpec,
} from "../support/helpers/plugin-execution-approval";
const REPO_ROOT = path.resolve(__dirname, "../../../..");
const ALPHA: ClientProbePluginSpec = {
id: "alpha-probe",
name: "Alpha Probe",
sidebarTitle: "Alpha Probe",
markerKey: "alpha-probe",
};
const BETA: ClientProbePluginSpec = {
id: "beta-probe",
name: "Beta Probe",
sidebarTitle: "Beta Probe",
markerKey: "beta-probe",
};
const GAMMA: ClientProbePluginSpec = {
id: "gamma-probe",
name: "Gamma Probe",
sidebarTitle: "Gamma Probe",
markerKey: "gamma-probe",
};
test("prompts sequentially before evaluating stacked client plugins, holds layout steady, persists decisions, and lets settings allow or block them", async ({
page,
}) => {
test.setTimeout(120_000);
await page.setViewportSize({ width: 1440, height: 900 });
const artifacts = await ensureArtifactsDir(REPO_ROOT);
await withInstalledClientPlugins([ALPHA, BETA, GAMMA], async () => {
await gotoAppShell(page);
await test.step("no client plugin executes before user approval", async () => {
await expectPluginApprovalPrompt(page, { pluginId: ALPHA.id, progress: "1 of 3" });
expect(await getExecutedPluginMarkers(page)).toEqual([]);
await expect(page.getByText(ALPHA.sidebarTitle, { exact: true })).toHaveCount(0);
await expect(page.getByText(BETA.sidebarTitle, { exact: true })).toHaveCount(0);
await expect(page.getByText(GAMMA.sidebarTitle, { exact: true })).toHaveCount(0);
await page.screenshot({ path: path.join(artifacts, "02-after-prompt-1-of-3.png") });
});
await test.step("approving the first advances in place with steady button geometry", async () => {
const sheet = pluginApprovalSheet(page);
const allowButton = sheet.getByRole("button", { name: "Allow", exact: true });
const declineButton = sheet.getByRole("button", { name: "Don't allow", exact: true });
const beforeAllow = await allowButton.boundingBox();
const beforeDecline = await declineButton.boundingBox();
expect(beforeAllow).not.toBeNull();
expect(beforeDecline).not.toBeNull();
await allowPluginExecution(page);
await expectPluginApprovalPrompt(page, { pluginId: BETA.id, progress: "2 of 3" });
await expectExecutedPluginMarkers(page, [ALPHA.markerKey]);
await expect(page.getByText(ALPHA.sidebarTitle, { exact: true })).toBeVisible();
await expect(page.getByText(BETA.sidebarTitle, { exact: true })).toHaveCount(0);
const afterAllow = await allowButton.boundingBox();
const afterDecline = await declineButton.boundingBox();
expect(afterAllow).toEqual(beforeAllow);
expect(afterDecline).toEqual(beforeDecline);
await page.screenshot({ path: path.join(artifacts, "03-after-prompt-2-of-3.png") });
});
await test.step("declining the second and approving the third settles cleanly", async () => {
await declinePluginExecution(page);
await expectPluginApprovalPrompt(page, { pluginId: GAMMA.id, progress: "3 of 3" });
expect(await getExecutedPluginMarkers(page)).toEqual([ALPHA.markerKey]);
await allowPluginExecution(page);
await expect(pluginApprovalSheet(page)).toHaveCount(0);
await expectExecutedPluginMarkers(page, [ALPHA.markerKey, GAMMA.markerKey]);
await expect(page.getByText(ALPHA.sidebarTitle, { exact: true })).toBeVisible();
await expect(page.getByText(GAMMA.sidebarTitle, { exact: true })).toBeVisible();
await expect(page.getByText(BETA.sidebarTitle, { exact: true })).toHaveCount(0);
await page.screenshot({
path: path.join(artifacts, "04-after-settled-approved-and-declined.png"),
});
});
await test.step("reloading keeps approved plugins active and declined blocked without re-prompting", async () => {
await reloadKeepingPersistedState(page);
await expect(page.getByText(ALPHA.sidebarTitle, { exact: true })).toBeVisible({
timeout: 30_000,
});
await expect(page.getByText(GAMMA.sidebarTitle, { exact: true })).toBeVisible();
await expect(pluginApprovalSheet(page)).toHaveCount(0);
expect(await getExecutedPluginMarkers(page)).toEqual([ALPHA.markerKey, GAMMA.markerKey]);
await expect(page.getByText(BETA.sidebarTitle, { exact: true })).toHaveCount(0);
});
await test.step("settings surfaces the declined plugin and lets the user allow or block it", async () => {
await openSettings(page);
await openHostSection(page, getServerId(), "plugins");
await expect(page.getByTestId(`plugin-row-${BETA.id}`)).toContainText("blocked");
await openPluginPage(page, BETA.name, BETA.id);
await expect(page.getByTestId("plugin-client-blocked-alert")).toBeVisible();
await page.screenshot({ path: path.join(artifacts, "05-after-settings-blocked-plugin.png") });
await page.getByTestId("plugin-client-execution-allow").click();
await expect(page.getByTestId("plugin-client-blocked-alert")).toHaveCount(0);
await expectExecutedPluginMarkersContain(page, BETA.markerKey);
await openPluginPageActions(page, BETA.name);
await page.getByRole("menuitem", { name: "Block on this device", exact: true }).click();
await expect(page.getByTestId("plugin-client-blocked-alert")).toBeVisible();
});
});
});
test("presents the queued approval bottom sheet cleanly on compact viewports and closes cleanly on dismiss", async ({
page,
}) => {
test.setTimeout(120_000);
await page.setViewportSize({ width: 390, height: 844 });
const artifacts = await ensureArtifactsDir(REPO_ROOT);
await withInstalledClientPlugins([ALPHA, BETA], async () => {
await gotoAppShell(page);
await test.step("shows the first prompt in a compact bottom sheet", async () => {
await expectPluginApprovalPrompt(page, { pluginId: ALPHA.id, progress: "1 of 2" });
await waitForSettledPosition(pluginApprovalSheet(page));
expect(await getExecutedPluginMarkers(page)).toEqual([]);
await page.screenshot({ path: path.join(artifacts, "06-after-compact-sheet-1-of-2.png") });
});
await test.step("approves the first and dismisses the remaining queue cleanly", async () => {
await allowPluginExecution(page);
await expectPluginApprovalPrompt(page, { pluginId: BETA.id, progress: "2 of 2" });
await expectExecutedPluginMarkers(page, [ALPHA.markerKey]);
await page.getByRole("button", { name: "Close", exact: true }).click();
await expect(pluginApprovalSheet(page)).toHaveCount(0);
expect(await getExecutedPluginMarkers(page)).toEqual([ALPHA.markerKey]);
});
});
});
test("lets Settings -> General toggle bypass client plugin approval, persists across reload, and restores prompting when turned off", async ({
page,
}) => {
test.setTimeout(120_000);
await page.setViewportSize({ width: 1440, height: 900 });
const artifacts = await ensureArtifactsDir(REPO_ROOT);
await withInstalledClientPlugins([ALPHA, BETA], async ({ install }) => {
await gotoAppShell(page);
await test.step("approve one plugin and decline the other before opening Settings -> General", async () => {
await expectPluginApprovalPrompt(page, { pluginId: ALPHA.id, progress: "1 of 2" });
await allowPluginExecution(page);
await expectPluginApprovalPrompt(page, { pluginId: BETA.id, progress: "2 of 2" });
await declinePluginExecution(page);
await expect(pluginApprovalSheet(page)).toHaveCount(0);
await expectExecutedPluginMarkers(page, [ALPHA.markerKey]);
});
await test.step("General settings shows the minimal bypass toggle off by default", async () => {
await openSettings(page);
const row = page.getByTestId("settings-plugin-execution-bypass-row");
await expect(row).toBeVisible();
await expect(row).toContainText("Run plugins without asking");
await expect(row).not.toContainText("Unsafe");
await expect(row).toContainText(
"Any connected host can run plugin code inside Paseo and reach your other hosts",
);
await expectPluginExecutionBypass(page, false);
await page.screenshot({
path: path.join(artifacts, "settings-general-plugin-bypass-off-desktop.png"),
});
});
await test.step("turning bypass on requires confirmation and canceling keeps it off", async () => {
await openPluginExecutionBypassConfirm(page);
const modal = pluginExecutionBypassConfirmModal(page);
await expect(modal).toContainText("Run plugins without asking?");
await expect(modal).toContainText(
"Any connected host can run plugin code inside Paseo and reach your other connected hosts.",
);
await expectPluginExecutionBypass(page, false);
await expect(modal.getByRole("dialog")).toHaveCSS("opacity", "1");
await page.screenshot({
path: path.join(artifacts, "settings-general-plugin-bypass-confirm-desktop.png"),
});
await cancelPluginExecutionBypassConfirm(page);
expect(await getExecutedPluginMarkers(page)).toEqual([ALPHA.markerKey]);
});
await test.step("confirming turns bypass on and runs declined and newly installed plugins without prompting", async () => {
await openPluginExecutionBypassConfirm(page);
await confirmPluginExecutionBypass(page);
await expectExecutedPluginMarkersContain(page, BETA.markerKey);
await expect(pluginApprovalSheet(page)).toHaveCount(0);
await install(GAMMA);
await expectExecutedPluginMarkersContain(page, GAMMA.markerKey);
await expect(pluginApprovalSheet(page)).toHaveCount(0);
// Let the 180ms switch track animation settle before capturing the ON screenshot.
await page.waitForTimeout(300);
await page.screenshot({
path: path.join(artifacts, "settings-general-plugin-bypass-on-desktop.png"),
});
});
await test.step("reloading preserves bypass on and runs all plugins without prompting", async () => {
await reloadKeepingPersistedState(page);
await expectPluginExecutionBypass(page, true);
await expectExecutedPluginMarkersContain(page, ALPHA.markerKey);
await expectExecutedPluginMarkersContain(page, BETA.markerKey);
await expectExecutedPluginMarkersContain(page, GAMMA.markerKey);
await expect(pluginApprovalSheet(page)).toHaveCount(0);
});
await test.step("turning bypass off needs no confirmation, restores prompting for unreviewed plugins, and persists across reload", async () => {
await setPluginExecutionBypass(page, false);
await expectPluginApprovalPrompt(page, { pluginId: GAMMA.id });
await declinePluginExecution(page);
await expect(pluginApprovalSheet(page)).toHaveCount(0);
await reloadKeepingPersistedState(page);
await expectPluginExecutionBypass(page, false);
await expect(pluginApprovalSheet(page)).toHaveCount(0);
await expectExecutedPluginMarkers(page, [ALPHA.markerKey]);
});
await test.step("compact mobile viewport renders the General toggle and confirm sheet cleanly", async () => {
await page.setViewportSize({ width: 390, height: 844 });
const row = page.getByTestId("settings-plugin-execution-bypass-row");
const toggle = pluginExecutionBypassSwitch(page);
await expect(row).toBeVisible();
await expect(toggle).toBeVisible();
const rowBox = await row.boundingBox();
const toggleBox = await toggle.boundingBox();
expect(rowBox).not.toBeNull();
expect(toggleBox).not.toBeNull();
expect(toggleBox!.x + toggleBox!.width).toBeLessThanOrEqual(390);
await page.screenshot({
path: path.join(artifacts, "settings-general-plugin-bypass-compact.png"),
});
await openPluginExecutionBypassConfirm(page);
await waitForSettledPosition(pluginExecutionBypassConfirmModal(page));
await page.screenshot({
path: path.join(artifacts, "settings-general-plugin-bypass-confirm-compact.png"),
});
await cancelPluginExecutionBypassConfirm(page);
});
});
});
@@ -3,6 +3,7 @@ import { readFile, writeFile } from "node:fs/promises";
import path from "node:path";
import type { Frame, TestInfo } from "@playwright/test";
import { expect, test, type Page } from "../support/fixtures";
import { approveClientPluginsInUi } from "../support/helpers/plugin-execution-approval";
import { copyPluginExample } from "../support/helpers/plugin-fixture";
import { connectNewWorkspaceDaemonClient } from "../support/helpers/new-workspace";
import { seedWorkspace } from "../support/helpers/seed-client";
@@ -172,6 +173,7 @@ test("directory examples mount the PDF frame and write Markdown through the file
await page.setViewportSize(WIDE);
const gate = await installDaemonWebSocketGate(page);
await gotoWorkspace(page, workspace.workspaceId);
await approveClientPluginsInUi(page, ["pdf-panel", "markdown-panel"]);
await openFileExplorer(page);
await openFile(page, "report.pdf");
await expect(page.getByTitle("Document preview", { exact: true })).toHaveAttribute(
@@ -6,6 +6,7 @@ import { expectFileTabOpen, openFileExplorer } from "../support/helpers/file-exp
import {
BUILTIN_MARKDOWN_OPTION,
MARKDOWN_PANEL_ID,
MARKDOWN_PANEL_PLUGIN_ID,
PLUGIN_MARKDOWN_OPTION,
expectBuiltinMarkdown,
expectPluginMarkdown,
@@ -14,6 +15,7 @@ import {
openMarkdown,
storedFilePanelAssociations,
} from "../support/helpers/markdown-file-panel-plugin";
import { approveClientPluginsInUi } from "../support/helpers/plugin-execution-approval";
async function choosePanel(page: Page, option: string, options: { remember: boolean }) {
await page.getByRole("radio", { name: option, exact: true }).click();
@@ -110,6 +112,7 @@ test("asks once which panel opens Markdown and remembers it when told to", async
try {
await page.setViewportSize({ width: 1280, height: 900 });
await gotoWorkspace(page, workspace.workspaceId);
await approveClientPluginsInUi(page, [MARKDOWN_PANEL_PLUGIN_ID]);
await openFileExplorer(page);
// First open: the built-in renders under the picker.
@@ -6,6 +6,7 @@ import { gotoWorkspace } from "../support/helpers/launcher";
import {
BUILTIN_MARKDOWN_OPTION,
MARKDOWN_PANEL_ID,
MARKDOWN_PANEL_PLUGIN_ID,
PLUGIN_MARKDOWN_OPTION,
expectPluginMarkdown,
filePanelPicker,
@@ -13,6 +14,7 @@ import {
openMarkdown,
storedFilePanelAssociations,
} from "../support/helpers/markdown-file-panel-plugin";
import { approveClientPluginsInUi } from "../support/helpers/plugin-execution-approval";
import { seedWorkspace } from "../support/helpers/seed-client";
import { openSettingsSection } from "../support/helpers/settings";
@@ -59,6 +61,7 @@ test("Settings > Files chooses which panel opens .md and asks again on request",
try {
await page.setViewportSize({ width: 1280, height: 900 });
await gotoWorkspace(page, workspace.workspaceId);
await approveClientPluginsInUi(page, [MARKDOWN_PANEL_PLUGIN_ID]);
await openFilesSettings(page);
// Nothing remembered: the row asks every time and has nothing to forget.
@@ -3,6 +3,7 @@ import { tmpdir } from "node:os";
import path from "node:path";
import { expect, test, type Page } from "../support/fixtures";
import { installDaemonWebSocketGate } from "../support/helpers/daemon-websocket-gate";
import { approveClientPluginsInUi } from "../support/helpers/plugin-execution-approval";
import { pluginRequirements } from "../support/helpers/plugin-fixture";
import { connectNewWorkspaceDaemonClient } from "../support/helpers/new-workspace";
import { seedWorkspace } from "../support/helpers/seed-client";
@@ -131,6 +132,7 @@ test("directory plugins render PDF bytes and write Markdown through the file han
await page.setViewportSize({ width: 1280, height: 900 });
const gate = await installDaemonWebSocketGate(page);
await gotoWorkspace(page, workspace.workspaceId);
await approveClientPluginsInUi(page, [PLUGIN_ID]);
await openFileExplorer(page);
await openWorkspaceFile(page, "report.pdf");
await expect(page.getByText("PDF plugin: report.pdf", { exact: true })).toBeVisible();
@@ -9,6 +9,7 @@ import {
expectRemovedPlugin,
} from "../support/helpers/plugin-reconnect";
import { verifyPluginTranslations } from "../support/helpers/plugin-translations";
import { approveClientPluginsInUi } from "../support/helpers/plugin-execution-approval";
import { pluginRequirements } from "../support/helpers/plugin-fixture";
import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
@@ -98,6 +99,7 @@ export default function contribute(plugin) {
async function openHostUiPlugin(page: Page): Promise<void> {
await gotoAppShell(page);
await approveClientPluginsInUi(page, [PLUGIN_ID]);
await page.getByRole("button", { name: "Host UI", exact: true }).click();
}
@@ -6,6 +6,7 @@ import { expect, test, type Page } from "../support/fixtures";
import { openCommandCenter } from "../support/helpers/command-center";
import { gotoAppShell } from "../support/helpers/app";
import { connectNewWorkspaceDaemonClient } from "../support/helpers/new-workspace";
import { approveClientPluginsInUi } from "../support/helpers/plugin-execution-approval";
import { pluginRequirements } from "../support/helpers/plugin-fixture";
import { seedWorkspace } from "../support/helpers/seed-client";
import { getServerId } from "../support/helpers/server-id";
@@ -87,6 +88,7 @@ test.describe("plugin icons", () => {
await client.installDirectoryPlugin(directory);
await page.setViewportSize({ width: 1280, height: 800 });
await gotoAppShell(page);
await approveClientPluginsInUi(page, [PLUGIN_ID]);
const target = { serverId: getServerId(), workspaceId: workspace.workspaceId };
await waitForWorkspaceInSidebar(page, target);
await switchWorkspaceViaSidebar({ page, ...target });
@@ -1,5 +1,6 @@
import { existsSync } from "node:fs";
import overviewCorpus from "../../../protocol/tests/fixtures/plugin-overview.json";
import { approveClientPluginsInUi } from "../support/helpers/plugin-execution-approval";
import { pluginRequirements } from "../support/helpers/plugin-fixture";
import { execFileSync } from "node:child_process";
import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";
@@ -500,6 +501,7 @@ async function installLocalPluginWithStatusExamples(
const catalog = observePluginCatalog(page);
await gotoAppShell(page);
await approveClientPluginsInUi(page, ["failed-preview-plugin"]);
await openPluginSettings(page);
await catalog.waitForInitialFetch();
await expectPluginFailed(page, "failed-preview-plugin");
@@ -514,6 +516,7 @@ async function installLocalPluginWithStatusExamples(
await openSourceInstall(page);
await expectPluginSourceDocsOpen(page);
await submitSourceInstall(page, directory);
await approveClientPluginsInUi(page, ["e2e-plugin"]);
await expectSourceInstalled(page, "e2e-plugin");
await expectPluginOn(page, "e2e-plugin");
await expectPluginHealthy(page, "e2e-plugin");
@@ -605,6 +608,7 @@ async function toggleRemoveAndReinstallLocalPlugin(page: Page, directory: string
await expectPluginRemoved(page, "e2e-plugin");
await installFromSource(page, directory, "e2e-plugin");
await approveClientPluginsInUi(page, ["e2e-plugin"]);
await expectPluginOn(page, "e2e-plugin");
await gotoAppShell(page);
await openContribution(page, "Plugin v3", "Plugin v3 cleanup 7");
@@ -659,6 +663,10 @@ async function retryGitInstallAndInspectRows(
await capturePluginInstallForm(page, testInfo, "compact-error");
await submitSourceInstall(page, pathToFileURL(repository).href);
await approveClientPluginsInUi(page, [
"compact-plugin-with-a-realistically-long-name",
"git-e2e-plugin",
]);
await expectSourceInstalled(page, "git-e2e-plugin");
await expectPluginsOn(page);
await expectPluginOn(page, "git-e2e-plugin");
@@ -724,6 +732,7 @@ async function prepareLegacyPluginHost(
pluginGitManagement: true,
});
await gotoAppShell(page);
await approveClientPluginsInUi(page, ["legacy-source-plugin"]);
await openPluginSettings(page);
return directory;
@@ -906,6 +915,7 @@ test("keeps Reload pending past a minute while the plugin queue is busy", async
// Plugins on is a precondition here, not the subject: set it through the daemon.
await client.patchDaemonConfig({ pluginsEnabled: true });
await client.installPluginSource({ source: pluginDirectory });
await approveClientPluginsInUi(page, ["e2e-plugin"]);
// Installed before Plugins opens, so it opens on the Installed tab.
await openPluginSettings(page);
await expectPluginOn(page, "e2e-plugin");
@@ -928,6 +938,7 @@ test("keeps Reload pending past a minute while the plugin queue is busy", async
await capturePluginSurface(page, testInfo, "plugin-reload-past-deadline.png");
await queue.release();
await approveClientPluginsInUi(page, ["gated-build-plugin"]);
// The daemon's answer only arrives once the plugin really started again.
await reload.waitForResponse();
expect(reload.requestCount()).toBe(1);
@@ -1,3 +1,4 @@
import { approveClientPluginsInUi } from "../support/helpers/plugin-execution-approval";
import { copyPluginExample } from "../support/helpers/plugin-fixture";
import { expect, test as base, type Page } from "../support/fixtures";
import { gotoAppShell } from "../support/helpers/app";
@@ -119,6 +120,7 @@ const test = base.extend<{ modalExample: Page }>({
async function openWideExamples(page: Page) {
await page.setViewportSize({ width: 1100, height: 800 });
await gotoAppShell(page);
await approveClientPluginsInUi(page, ["modal-ui-example"]);
await page.getByRole("button", { name: "Modal examples", exact: true }).click();
}
@@ -1,7 +1,8 @@
import { expect, test, type Page } from "../support/fixtures";
import { composerLocator, submitMessageWithButton } from "../support/helpers/composer";
import { seedMockAgentWorkspace, openAgentRoute } from "../support/helpers/mock-agent";
import { withPopoverTimelinePlugin } from "../support/helpers/plugin-timeline";
import { approveClientPluginsInUi } from "../support/helpers/plugin-execution-approval";
import { POPOVER_PLUGIN_ID, withPopoverTimelinePlugin } from "../support/helpers/plugin-timeline";
async function openPreviewWhileTyping(page: Page): Promise<void> {
await composerLocator(page).focus();
@@ -25,6 +26,7 @@ test("Escape dismisses a plugin preview before interrupting the agent", async ({
try {
await withPopoverTimelinePlugin(async () => {
await openAgentRoute(page, agent);
await approveClientPluginsInUi(page, [POPOVER_PLUGIN_ID]);
await submitMessageWithButton(page, "Show the plugin preview.");
await agent.client.waitForFinish(agent.agentId, 30_000);
await expect(page.getByRole("button", { name: "Hover plugin preview" })).toBeVisible();
@@ -12,7 +12,7 @@ test("shows which runtime is incompatible and recovers after the requirement is
}) => {
await openRequirementHost(page, requirementHost);
await expectAppMismatch(page);
await correctRequirementAndReload(page, requirementHost.directory);
await correctRequirementAndReload(page, requirementHost.directory, { approvePrompt: true });
await rejectDaemonMismatch(page, requirementHost.directory);
await correctRequirementAndReload(page, requirementHost.directory);
});
@@ -9,6 +9,7 @@ import {
LEGACY_PLUGIN_ID,
SHOWCASE_PLUGIN_ID,
WIDE,
approveSidebarPluginsInUi,
closeScreen,
expectRowActive,
footerItem,
@@ -182,6 +183,7 @@ test.describe("Plugin sidebar items", () => {
}) => {
await page.setViewportSize({ width: 390, height: 600 });
await gotoAppShell(page);
await approveSidebarPluginsInUi(page);
await page.getByRole("button", { name: "Open menu", exact: true }).first().click();
await expect(botRow(page, "status")).toBeAttached();
const workspace = visibleTestId(page, `sidebar-workspace-row-${getServerId()}:${workspaceId}`);
@@ -213,6 +215,7 @@ test.describe("Plugin sidebar items", () => {
}) => {
await page.setViewportSize({ width: 1280, height: 480 });
await gotoAppShell(page);
await approveSidebarPluginsInUi(page);
await expect(botRow(page, "status")).toBeAttached();
const workspace = visibleTestId(page, `sidebar-workspace-row-${getServerId()}:${workspaceId}`);
await expect(workspace).toBeInViewport({ ratio: 1 });
@@ -240,6 +243,7 @@ test.describe("Plugin sidebar items", () => {
test("a restored plugin screen waits for its catalog before rendering", async ({ page }) => {
await page.setViewportSize(WIDE);
await gotoWorkspace(page, workspaceId);
await approveSidebarPluginsInUi(page);
const row = headerRow(page, SHOWCASE_PLUGIN_ID, "deploys");
await expect(row).toBeVisible({ timeout: 30_000 });
await row.click();
@@ -278,6 +282,7 @@ test.describe("Plugin sidebar items", () => {
await seedSidebarFooterPreferences(page, [{ key: "usage", visible: true }]);
await page.setViewportSize(WIDE);
await gotoWorkspace(page, workspaceId);
await approveSidebarPluginsInUi(page);
const row = headerRow(page, SHOWCASE_PLUGIN_ID, "deploys");
const sync = footerItem(page, SHOWCASE_PLUGIN_ID, "sync");
await expect(row).toBeVisible({ timeout: 30_000 });
@@ -365,6 +370,7 @@ test.describe("Plugin sidebar items", () => {
test("a plugin screen reads workspaces through the state hooks", async ({ page }) => {
await page.setViewportSize(WIDE);
await gotoWorkspace(page, workspaceId);
await approveSidebarPluginsInUi(page);
await expect(headerRow(page, SHOWCASE_PLUGIN_ID, "deploys")).toBeVisible({ timeout: 30_000 });
await runCommand(page, "Open plugin workspaces");
await expect(screenTitle(page)).toHaveText("Workspaces");
@@ -375,6 +381,7 @@ test.describe("Plugin sidebar items", () => {
test("a plugin screen keeps the sidebar toggle before its title", async ({ page }) => {
await page.setViewportSize(WIDE);
await gotoWorkspace(page, workspaceId);
await approveSidebarPluginsInUi(page);
await expect(headerRow(page, SHOWCASE_PLUGIN_ID, "deploys")).toBeVisible({ timeout: 30_000 });
await runCommand(page, "Open plugin workspaces");
await expect(screenTitle(page)).toHaveText("Workspaces");
@@ -394,6 +401,7 @@ test.describe("Plugin sidebar items", () => {
test("a header row's shortcut hint presses the row", async ({ page }) => {
await page.setViewportSize(WIDE);
await gotoWorkspace(page, workspaceId);
await approveSidebarPluginsInUi(page);
const newWorkspace = visibleTestId(page, "sidebar-global-new-workspace");
await expect(newWorkspace).toBeVisible({ timeout: 30_000 });
await newWorkspace.hover();
@@ -419,6 +427,7 @@ test.describe("Plugin sidebar items", () => {
);
await page.setViewportSize(WIDE);
await gotoWorkspace(page, workspaceId);
await approveSidebarPluginsInUi(page);
const entry = headerRow(page, LEGACY_PLUGIN_ID, "entry");
await expect(entry).toBeVisible({ timeout: 30_000 });
let entryIcon = "";
@@ -503,6 +512,7 @@ test.describe("Plugin sidebar items", () => {
test.setTimeout(180_000);
await page.setViewportSize(WIDE);
await gotoWorkspace(page, workspaceId);
await approveSidebarPluginsInUi(page);
const bot1 = botRow(page, "bot-1");
const bot2 = botRow(page, "bot-2");
const status = botRow(page, "status");
@@ -587,6 +597,7 @@ test.describe("Plugin sidebar items", () => {
test.setTimeout(120_000);
await page.setViewportSize(WIDE);
await gotoWorkspace(page, workspaceId);
await approveSidebarPluginsInUi(page);
await expect(botRow(page, "bot-1")).toBeVisible({ timeout: 30_000 });
const alerts = footerItem(page, BOTS_PLUGIN_ID, "alerts");
await expect(alerts).toHaveCount(0);
@@ -606,6 +617,7 @@ test.describe("Plugin sidebar items", () => {
const alerts = footerItem(page, BOTS_PLUGIN_ID, "alerts");
await page.setViewportSize(WIDE);
await gotoWorkspace(page, workspaceId);
await approveSidebarPluginsInUi(page);
await expect(botRow(page, "bot-1")).toBeVisible({ timeout: 30_000 });
await runCommand(page, "Add bot alerts");
@@ -4,6 +4,7 @@ import { expect, test, type Page } from "../support/fixtures";
import { gotoAppShell } from "../support/helpers/app";
import { openCommandCenter } from "../support/helpers/command-center";
import { connectNewWorkspaceDaemonClient } from "../support/helpers/new-workspace";
import { approveClientPluginsInUi } from "../support/helpers/plugin-execution-approval";
import { copyPluginExample } from "../support/helpers/plugin-fixture";
import { seedWorkspace, type SeededWorkspace } from "../support/helpers/seed-client";
import { getServerId } from "../support/helpers/server-id";
@@ -34,6 +35,7 @@ async function withExample(
await client.installDirectoryPlugin(copy.directory);
await page.setViewportSize({ width: 1280, height: 800 });
await gotoAppShell(page);
await approveClientPluginsInUi(page, [example.id]);
const target = { serverId: getServerId(), workspaceId: workspace.workspaceId };
await waitForWorkspaceInSidebar(page, target);
await switchWorkspaceViaSidebar({ page, ...target });
@@ -1,3 +1,4 @@
import { approveClientPluginsInUi } from "../support/helpers/plugin-execution-approval";
import { pluginRequirements } from "../support/helpers/plugin-fixture";
import { mkdtemp, rm, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
@@ -63,8 +64,11 @@ const MOCHA_MUTED_FOREGROUND = "rgb(166, 173, 200)";
const LATTE_MUTED_FOREGROUND = "rgb(108, 111, 133)";
const LATTE_RING = "rgb(156, 160, 176)";
async function selectTheme(page: Page, name: string) {
async function selectTheme(page: Page, name: string, approvePluginId?: string) {
await page.goto("/settings");
if (approvePluginId) {
await approveClientPluginsInUi(page, [approvePluginId]);
}
await openSettingsSection(page, "appearance");
const theme = page.getByRole("radio", { name, exact: true });
await expect(theme).toBeVisible({ timeout: 30_000 });
@@ -108,7 +112,7 @@ test("keeps plugin workspace timestamps readable on state surfaces and honors ov
try {
await client.patchDaemonConfig({ pluginsEnabled: true });
await client.installDirectoryPlugin(directory);
await selectTheme(page, "Solarized Dark");
await selectTheme(page, "Solarized Dark", PLUGIN_ID);
await openAgentRoute(page, selected);
const selectedRow = page.getByTestId(
`sidebar-workspace-row-${getServerId()}:${selected.workspaceId}`,
@@ -160,6 +164,7 @@ test("applies a contributed theme and falls back when its plugin is gone", async
await client.patchDaemonConfig({ pluginsEnabled: true });
await client.installDirectoryPlugin(directory);
await page.goto("/settings");
await approveClientPluginsInUi(page, [PLUGIN_ID]);
await expect(page.getByTestId("settings-sidebar")).toBeVisible();
await openSettingsSection(page, "appearance");
@@ -263,6 +268,7 @@ test("reaches the last theme when a plugin contributes more themes than fit", as
await client.installDirectoryPlugin(directory);
await page.setViewportSize({ width: 1280, height: 720 });
await page.goto("/settings");
await approveClientPluginsInUi(page, [MANY_THEMES_PLUGIN_ID]);
await expect(page.getByTestId("settings-sidebar")).toBeVisible();
await openSettingsSection(page, "appearance");
@@ -8,6 +8,7 @@ import { submitMessageWithButton } from "../support/helpers/composer";
import { openFileExplorer, openFileFromExplorer } from "../support/helpers/file-explorer";
import { openAgentRoute, seedMockAgentWorkspace } from "../support/helpers/mock-agent";
import { connectNewWorkspaceDaemonClient } from "../support/helpers/new-workspace";
import { approveClientPluginsInUi } from "../support/helpers/plugin-execution-approval";
import { copyPluginExample } from "../support/helpers/plugin-fixture";
import { runCommand } from "../support/helpers/plugin-sidebar-items";
import {
@@ -214,6 +215,7 @@ test("the workspace layout example arranges a wide workspace", async ({ page })
await withLayoutExample(undefined, async ({ agentId, workspaceId }) => {
await page.setViewportSize(WIDE);
await openAgentRoute(page, { workspaceId, agentId });
await approveClientPluginsInUi(page, ["workspace-layout"]);
await test.step("/aside opens the child agent's chat in the Explorer", async () => {
await sendToMainChat(page, "/aside hey");
@@ -264,6 +266,7 @@ test("the workspace layout example opens over a phone's chat", async ({ page })
await withLayoutExample(promptMentioning(FILE_LINK), async ({ agentId, workspaceId }) => {
await page.setViewportSize(COMPACT);
await openAgentRoute(page, { workspaceId, agentId });
await approveClientPluginsInUi(page, ["workspace-layout"]);
await test.step("/aside opens the Explorer over the chat", async () => {
await submitMessageWithButton(page, "/aside hey");
@@ -302,6 +305,7 @@ test("a file a plugin opens in another workspace waits there on a phone", async
await page.setViewportSize(COMPACT);
// Visiting the first workspace leaves its screen mounted behind the second.
await openAgentRoute(page, first);
await approveClientPluginsInUi(page, ["workspace-layout"]);
await expect(composerIn(page.locator("body"))).toBeEditable({ timeout: 30_000 });
await switchToWorkspace(page, second.workspaceId);
@@ -1,3 +1,4 @@
import { approveClientPluginsInUi } from "../support/helpers/plugin-execution-approval";
import { pluginRequirements } from "../support/helpers/plugin-fixture";
import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
@@ -297,6 +298,7 @@ test.describe("plugin workspace panels and Command Center", () => {
await primaryClient.installDirectoryPlugin(directory);
await page.setViewportSize(WIDE_VIEWPORT);
await gotoAppShell(page);
await approveClientPluginsInUi(page, [PLUGIN_ID]);
await addConnectedHostAndReload(page, {
serverId: secondaryDaemon.serverId,
label: "Secondary plugin host",
@@ -5,6 +5,7 @@ import type { Page } from "@playwright/test";
import { expect, test } from "../support/fixtures";
import { gotoAppShell } from "../support/helpers/app";
import { connectNewWorkspaceDaemonClient } from "../support/helpers/new-workspace";
import { approveClientPluginsInUi } from "../support/helpers/plugin-execution-approval";
import { pluginRequirements } from "../support/helpers/plugin-fixture";
import { seedWorkspace } from "../support/helpers/seed-client";
import {
@@ -95,6 +96,7 @@ test("a plugin badge shows on workspace rows, hides quietly, and follows its Sho
await page.setViewportSize({ width: 1280, height: 900 });
await gotoAppShell(page);
await approveClientPluginsInUi(page, [PLUGIN_ID]);
await test.step("the badge draws on the row; a null item and a throwing item draw nothing", async () => {
await expect(badge(page, "review")).toBeVisible();
@@ -15,6 +15,7 @@ import {
openSettingsHost,
openSettingsHostSection,
} from "../support/helpers/settings";
import { approveClientPluginsInUi } from "../support/helpers/plugin-execution-approval";
import { copyPluginExample } from "../support/helpers/plugin-fixture";
const CUSTOM_PROVIDER = {
@@ -202,6 +203,7 @@ test.describe("provider removal", () => {
await client.installDirectoryPlugin(plugin.directory);
await gotoAppShell(page);
await approveClientPluginsInUi(page, [PLUGIN_PROVIDER.pluginId]);
await openSettings(page);
await openSettingsHost(page, getServerId());
await openSettingsHostSection(page, getServerId(), "providers");
@@ -19,6 +19,7 @@ import {
} from "../support/helpers/composer";
import { connectDaemonClient } from "../support/helpers/daemon-client-loader";
import { openAgentRoute, seedMockAgentWorkspace } from "../support/helpers/mock-agent";
import { approveClientPluginsInUi } from "../support/helpers/plugin-execution-approval";
import { copyPluginExample } from "../support/helpers/plugin-fixture";
import { userScrollsTimelineToHistoryStart } from "../support/helpers/timeline-pagination";
@@ -266,6 +267,7 @@ test.describe.serial("Provider switching in chat", () => {
try {
await openAgentRoute(page, workspace);
await approveClientPluginsInUi(page, [DIRECT_PROVIDER.pluginId]);
await expectComposerVisible(page);
await expectComposerMode(page, "Load test");
@@ -461,6 +463,7 @@ test.describe.serial("Provider switching in chat", () => {
try {
await openAgentRoute(page, workspace);
await approveClientPluginsInUi(page, [DIRECT_PROVIDER.pluginId]);
await expectComposerVisible(page);
await submitMessage(page, runningPrompt);
@@ -513,6 +516,7 @@ test.describe.serial("Provider switching in chat", () => {
try {
await openAgentRoute(page, workspace);
await approveClientPluginsInUi(page, [DIRECT_PROVIDER.pluginId]);
await expectComposerVisible(page);
await submitMessage(page, "Run a one-minute mock turn first.");
await expectAgentReadyToInterrupt(page);
@@ -567,6 +571,7 @@ test.describe.serial("Provider switching in chat", () => {
try {
await openAgentRoute(page, workspace);
await approveClientPluginsInUi(page, [DIRECT_PROVIDER.pluginId]);
await expectComposerVisible(page);
await submitMessageWithButton(page, preSwitchPrompt);
@@ -13,7 +13,7 @@ import {
test("a refresh clears a failed update from the provider's page and its row", async ({
providerUpdateFailure: { page, otherClient },
}) => {
await openProviderInstallation(page);
await openProviderInstallation(page, { approvePlugin: true });
await test.step("Refresh on the page clears the failure", async () => {
await runFailingUpdate(page);
@@ -9,7 +9,11 @@ import {
expectCompactSidebarOpen,
} from "../support/helpers/usage-sidebar-item";
import { gotoAppShell } from "../support/helpers/app";
import { SHOWCASE_PLUGIN_ID, installSidebarPlugins } from "../support/helpers/plugin-sidebar-items";
import {
SHOWCASE_PLUGIN_ID,
approveSidebarPluginsInUi,
installSidebarPlugins,
} from "../support/helpers/plugin-sidebar-items";
import {
expectFooterIconRow,
expectFooterSeparator,
@@ -227,6 +231,7 @@ test.describe("Sidebar footer rows in Appearance settings", () => {
{ key: "import", visible: false },
]);
await gotoAppShell(page);
await approveSidebarPluginsInUi(page);
await test.step("the Footer card lists only the footer rows", async () => {
await openSidebarNavSettings(page);
@@ -2,8 +2,6 @@ import path from "node:path";
import type { Page, TestInfo } from "@playwright/test";
import { test, expect } from "../support/fixtures";
import { gotoAppShell } from "../support/helpers/app";
import { addConnectedHostsAndReload } from "../support/helpers/hosts";
import { startIsolatedHostDaemon } from "../support/helpers/isolated-host-daemon";
import {
closeMobileAgentSidebar,
expectMobileAgentSidebarHidden,
@@ -143,7 +141,6 @@ async function withPaseoOwnedWorktree(
async function readCachedRowIds(
page: Page,
rowKind: "workspace" | "checkpoint",
hostServerId = getServerId(),
): Promise<string[]> {
return page.evaluate(
async ({ serverId, kind }) => {
@@ -172,7 +169,7 @@ async function readCachedRowIds(
database.close();
}
},
{ serverId: hostServerId, kind: rowKind },
{ serverId: getServerId(), kind: rowKind },
);
}
@@ -320,60 +317,7 @@ async function expectRecoveredWorkspacesAfterReload(
});
}
async function expectTimeSortingAvailable(page: Page): Promise<void> {
await page.getByLabel("Display preferences", { exact: true }).click();
await page.getByRole("menuitem", { name: /^Sort/ }).click();
await expect(page.getByRole("menuitem", { name: "Created", exact: true })).toBeVisible();
await expect(page.getByRole("menuitem", { name: "Last prompt", exact: true })).toBeVisible();
await page.getByRole("menuitem", { name: "Created", exact: true }).click();
await page.getByLabel("Display preferences", { exact: true }).click();
await expect(page.getByRole("menuitem", { name: /^Sort/ })).toContainText("Created");
await page.keyboard.press("Escape");
}
async function cacheSecondaryHostWorkspace(page: Page, serverId: string, workspaceId: string) {
await expect(page.getByTestId(`sidebar-workspace-row-${serverId}:${workspaceId}`)).toBeVisible();
await expect.poll(() => readCachedRowIds(page, "workspace", serverId)).toContain(workspaceId);
}
test.describe("Sidebar workspace list", () => {
test("keeps time sorting when a host's cached workspaces load offline", async ({ page }) => {
test.setTimeout(120_000);
const laptop = await startIsolatedHostDaemon("sidebar-sort-laptop");
try {
const other = await startIsolatedHostDaemon("sidebar-sort-other");
try {
const workspace = await seedWorkspace({
repoPrefix: "sidebar-sort-laptop-",
port: laptop.port,
});
try {
await gotoAppShell(page);
const hosts = [
{ ...laptop, label: "Laptop" },
{ ...other, label: "Other host" },
];
await test.step("cache the laptop workspace while its host is online", async () => {
await addConnectedHostsAndReload(page, hosts);
await cacheSecondaryHostWorkspace(page, laptop.serverId, workspace.workspaceId);
await expectTimeSortingAvailable(page);
});
await test.step("reopen the sidebar with the laptop offline", async () => {
await laptop.close();
await addConnectedHostsAndReload(page, hosts);
await cacheSecondaryHostWorkspace(page, laptop.serverId, workspace.workspaceId);
await expectTimeSortingAvailable(page);
});
} finally {
await workspace.cleanup();
}
} finally {
await other.close();
}
} finally {
await laptop.close();
}
});
test("recovers missing workspaces from a damaged legacy cache after reload", async ({
page,
}, testInfo) => {
@@ -11,6 +11,7 @@ import { getActiveTabTestId } from "../support/helpers/launcher";
import type { Page, Locator } from "@playwright/test";
import { test, expect } from "../support/fixtures";
import { expectComposerVisible } from "../support/helpers/composer";
import { approveClientPluginsInUi } from "../support/helpers/plugin-execution-approval";
import { withDirectoryPlugin } from "../support/helpers/plugin-timeline";
import { openAgentRoute, seedMockAgentWorkspace } from "../support/helpers/mock-agent";
import { getE2EDaemonPort } from "../support/helpers/daemon-port";
@@ -188,6 +189,7 @@ export default function contribute(client) {
run: async () => {
await page.setViewportSize({ width: 1280, height: 1000 });
await openAgentRoute(page, agent);
await approveClientPluginsInUi(page, ["reply-fold-e2e"]);
await expectComposerVisible(page);
for (const width of [1280, 390]) {
await page.setViewportSize({ width, height: 1000 });
@@ -6,6 +6,7 @@ import appPackage from "../../../package.json";
import { expect, test as base, type Page } from "../fixtures";
import { gotoAppShell } from "./app";
import { addConnectedHostAndReload } from "./hosts";
import { approveClientPluginsInUi } from "./plugin-execution-approval";
import { pluginRequirements } from "./plugin-fixture";
const pluginId = "builtin-settings";
@@ -69,6 +70,7 @@ export async function openBuiltinPluginSettings(
label: "Built-in settings host",
destination: `/settings/hosts/${host.serverId}/plugins/${pluginId}/${screenId}`,
});
await approveClientPluginsInUi(page, [pluginId]);
}
export async function expectBuiltinPluginSettings(page: Page) {
+14 -40
View File
@@ -178,50 +178,24 @@ export async function attachFileFromMenu(
await (await chooserPromise).setFiles(file);
}
interface TransferFile {
name: string;
mimeType: string;
buffer: Buffer;
}
function createFileTransfer(page: Page, files: TransferFile[]) {
return page.evaluateHandle(
(entries) => {
export async function dropFileOnComposer(
page: Page,
file: { name: string; mimeType: string; buffer: Buffer },
): Promise<void> {
const dataTransfer = await page.evaluateHandle(
({ name, mimeType, base64 }) => {
const bytes = Uint8Array.from(atob(base64), (char) => char.charCodeAt(0));
const droppedFile = new File([bytes], name, { type: mimeType });
const transfer = new DataTransfer();
for (const { name, mimeType, base64 } of entries) {
const bytes = Uint8Array.from(atob(base64), (char) => char.charCodeAt(0));
transfer.items.add(new File([bytes], name, { type: mimeType }));
}
transfer.items.add(droppedFile);
return transfer;
},
files.map(({ name, mimeType, buffer }) => ({
name,
mimeType,
base64: buffer.toString("base64"),
})),
{
name: file.name,
mimeType: file.mimeType,
base64: file.buffer.toString("base64"),
},
);
}
export async function pasteFilesIntoComposer(page: Page, files: TransferFile[]): Promise<boolean> {
const clipboardData = await createFileTransfer(page, files);
try {
const input = composerInput(page);
await input.focus();
return await input.evaluate((element, transfer) => {
const event = new ClipboardEvent("paste", {
clipboardData: transfer,
bubbles: true,
cancelable: true,
});
return !element.dispatchEvent(event);
}, clipboardData);
} finally {
await clipboardData.dispose();
}
}
export async function dropFileOnComposer(page: Page, file: TransferFile): Promise<void> {
const dataTransfer = await createFileTransfer(page, [file]);
const composerRoot = page.getByTestId("message-input-root").filter({ visible: true }).first();
await expect(composerRoot).toBeVisible({ timeout: 10_000 });
+8 -1
View File
@@ -2,6 +2,7 @@ import type { WorkspaceCreateRequest } from "@getpaseo/protocol/messages";
import { expect, type Page } from "@playwright/test";
import { daemonWsRoutePattern } from "./daemon-port";
import { gotoAppShell } from "./app";
import { approveClientPluginsInUi } from "./plugin-execution-approval";
import { gotoWorkspace } from "./launcher";
import { fillComposerDraft } from "./composer";
import { createAgentTabFromMenu } from "./workspace-tabs";
@@ -146,8 +147,14 @@ export async function createCreationScenario(page: Page) {
const evictionWorkspaceIds = new Set<string>();
return {
cleanup: project.cleanup,
async openWorkspaceForm(isolation: "local" | "worktree") {
async openWorkspaceForm(
isolation: "local" | "worktree",
options?: { approvePlugins?: readonly string[] },
) {
await gotoAppShell(page);
if (options?.approvePlugins?.length) {
await approveClientPluginsInUi(page, options.approvePlugins);
}
await waitForSidebarHydration(page);
await openNewWorkspaceComposer(page, project);
await selectWorkspaceIsolation(page, isolation);
@@ -5,6 +5,7 @@ import { expect, type Page, type TestInfo } from "@playwright/test";
import { gotoWorkspace } from "./launcher";
import { buildAgentRoute } from "./mock-agent";
import { connectNewWorkspaceDaemonClient } from "./new-workspace";
import { approveClientPluginsInUi } from "./plugin-execution-approval";
import { pluginRequirements } from "./plugin-fixture";
import { seedWorkspace } from "./seed-client";
import { ensureExplorerSidebar } from "./workspace-tabs";
@@ -63,6 +64,7 @@ export async function withExplorerPanelPlugins(
await client.installDirectoryPlugin(second);
await page.setViewportSize({ width: 1280, height: 900 });
await gotoWorkspace(page, workspace.workspaceId);
await approveClientPluginsInUi(page, ["explorer-review", "explorer-other"]);
await run(workspace);
} finally {
@@ -134,7 +134,7 @@ export async function addProjectFromSetup(page: Page, projectPath: string): Prom
export async function showSetupAgainFromSettings(page: Page): Promise<void> {
await page.locator('[data-testid="sidebar-settings"]:visible').first().click();
await page.getByRole("button", { name: "Show setup again", exact: true }).click();
await page.getByRole("button", { name: "Show", exact: true }).click();
}
export async function goToSetupStep(page: Page, label: string): Promise<void> {
@@ -1,5 +1,6 @@
import type { Locator, TestInfo } from "@playwright/test";
import { test, expect, type Page } from "@playwright/test";
import { approveClientPluginsInUi } from "./plugin-execution-approval";
import { copyPluginExample } from "./plugin-fixture";
import { gotoAppShell } from "./app";
import { buildAgentRoute } from "./mock-agent";
@@ -73,6 +74,7 @@ export async function withButtonAuthorExample(
await client.installDirectoryPlugin(example.directory);
await page.setViewportSize(WIDE);
await gotoAppShell(page);
await approveClientPluginsInUi(page, ["button-examples"]);
await page.goto(buildAgentRoute(workspace.workspaceId, agent.id));
await run({
@@ -17,6 +17,7 @@ import {
} from "./compact-workspace-scripts";
import { connectNewWorkspaceDaemonClient } from "./new-workspace";
import { seedWorkspace } from "./seed-client";
import { approveClientPluginsInUi } from "./plugin-execution-approval";
import { pluginRequirements } from "./plugin-fixture";
const PLUGIN_ID = "button-showcase";
@@ -354,6 +355,7 @@ export async function withButtonShowcase(
try {
await page.setViewportSize(WIDE);
await gotoAppShell(page);
await approveClientPluginsInUi(page, [PLUGIN_ID]);
await page.goto(buildAgentRoute(workspace.workspaceId, agent.id));
await expect(page.getByRole("button", { name: "Run review", exact: true })).toBeVisible();
@@ -5,6 +5,7 @@ import { expect, test, type Page } from "@playwright/test";
import { gotoAppShell } from "./app";
import { openAgentRoute } from "./mock-agent";
import { connectNewWorkspaceDaemonClient } from "./new-workspace";
import { approveClientPluginsInUi } from "./plugin-execution-approval";
import { copyPluginExample, pluginRequirements } from "./plugin-fixture";
import { seedWorkspace } from "./seed-client";
@@ -39,6 +40,7 @@ export async function withComposerControlsExample(
await client.patchDaemonConfig({ pluginsEnabled: true });
await client.installDirectoryPlugin(example.directory);
await gotoAppShell(page);
await approveClientPluginsInUi(page, [PLUGIN_ID]);
await openAgentRoute(page, { workspaceId: workspace.workspaceId, agentId: agent.id });
await run({
narrowTheWindow: () =>
@@ -217,6 +219,7 @@ async function withToolbarPlugin(
await client.patchDaemonConfig({ pluginsEnabled: true });
await client.installDirectoryPlugin(directory);
await gotoAppShell(page);
await approveClientPluginsInUi(page, [ONE_TOGGLE_PLUGIN_ID]);
await openAgentRoute(page, { workspaceId: workspace.workspaceId, agentId: agent.id });
await expect(toolbar(page)).toBeVisible({ timeout: 30_000 });
await run({
@@ -13,6 +13,7 @@ import { gotoWorkspace } from "./launcher";
import { openCommandCenter } from "./command-center";
import { openAgentRoute, seedMockAgentWorkspace } from "./mock-agent";
import { connectNewWorkspaceDaemonClient, openGlobalNewWorkspaceComposer } from "./new-workspace";
import { approveClientPluginsInUi } from "./plugin-execution-approval";
import { copyPluginExample, pluginRequirements } from "./plugin-fixture";
import { seedWorkspace } from "./seed-client";
import {
@@ -86,6 +87,7 @@ export async function withComposerToolsExample(
await client.installDirectoryPlugin(example.directory);
await page.setViewportSize(WIDE);
await gotoAppShell(page);
await approveClientPluginsInUi(page, ["composer-controls-example"]);
await openAgentRoute(page, { workspaceId: workspace.workspaceId, agentId: agent.id });
await run({
openComposerToolsInExplorer: () =>
@@ -213,6 +215,7 @@ export async function withPluginWritingToAnotherWorkspace(
await client.installDirectoryPlugin(directory);
await page.setViewportSize(WIDE);
await gotoAppShell(page);
await approveClientPluginsInUi(page, ["composer-ref"]);
await run({
openTargetAgent: () =>
test.step("open the agent the plugin will write to", async () => {
@@ -356,6 +359,7 @@ export default function contribute(client) {
await client.installDirectoryPlugin(directory);
await page.setViewportSize(WIDE);
await gotoAppShell(page);
await approveClientPluginsInUi(page, ["composer-focus"]);
await run({
openOtherAgent: () =>
test.step("open another agent, so the target's tab is not showing", async () => {
@@ -479,6 +483,7 @@ export default function contribute(client) {
await client.installDirectoryPlugin(directory);
await page.setViewportSize(WIDE);
await gotoAppShell(page);
await approveClientPluginsInUi(page, ["held-composer"]);
await run({
openNewWorkspace: () =>
test.step("open the New workspace composer", async () => {
@@ -596,6 +601,7 @@ export async function withPluginFocusingASubagent(
try {
await page.setViewportSize(COMPACT);
await gotoAppShell(page);
await approveClientPluginsInUi(page, ["focus-agent"]);
await run({
keepParentInExplorerOnCompactScreen: () =>
test.step("move the parent into the Explorer, then narrow the window", async () => {
@@ -740,6 +746,7 @@ export async function withPluginFocusingAnAgentWithContextUsage(
try {
await page.setViewportSize(COMPACT);
await gotoAppShell(page);
await approveClientPluginsInUi(page, ["focus-agent"]);
await run({
openContextUsageOnPhone: () =>
test.step("open the agent's context usage on a phone", async () => {
@@ -8,6 +8,7 @@ import { expect, test as base, type Page } from "../fixtures";
import appPackage from "../../../package.json";
import { gotoAppShell, openSettings } from "./app";
import { addConnectedHostAndReload } from "./hosts";
import { approveClientPluginsInUi } from "./plugin-execution-approval";
import { pluginRequirements } from "./plugin-fixture";
import {
expectToast,
@@ -396,6 +397,7 @@ export async function installListingFromRow(page: Page) {
const sheet = page.getByTestId("plugin-install-sheet");
await expect(sheet).toContainText("Acme");
await sheet.getByTestId("plugin-install-confirm").click();
await approveClientPluginsInUi(page, ["directory-example"]);
await expect(listingRow(page).getByTestId(`plugin-uninstall-${LISTING.id}`)).toBeVisible({
timeout: 60_000,
});
@@ -430,6 +432,7 @@ export async function uninstallFromPage(page: Page) {
export async function installFromPage(page: Page) {
await page.getByTestId(`plugin-install-${LISTING.id}`).filter({ visible: true }).click();
await page.getByTestId("plugin-install-confirm").click();
await approveClientPluginsInUi(page, ["directory-example"]);
await expect(
page.getByRole("button", { name: `Actions for ${LISTING.name}`, exact: true }),
).toBeVisible({ timeout: 60_000 });
@@ -0,0 +1,284 @@
import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import path from "node:path";
import { expect, type Locator, type Page } from "@playwright/test";
import { connectNewWorkspaceDaemonClient } from "./new-workspace";
import { pluginRequirements } from "./plugin-fixture";
export interface ClientProbePluginSpec {
id: string;
name: string;
sidebarTitle: string;
markerKey: string;
}
export async function createClientProbePlugin(spec: ClientProbePluginSpec): Promise<{
directory: string;
cleanup: () => Promise<void>;
}> {
const directory = await mkdtemp(path.join(tmpdir(), `paseo-plugin-approval-${spec.id}-`));
await writeFile(
path.join(directory, "paseo-plugin.json"),
JSON.stringify({
id: spec.id,
name: spec.name,
requirements: pluginRequirements,
}),
);
await writeFile(
path.join(directory, "index.server.ts"),
`export default function contribute() { return () => {}; }\n`,
);
await writeFile(
path.join(directory, "index.client.tsx"),
`import React from "react";
import { Text, View } from "react-native";
import { SidebarRow } from "@getpaseo/plugin/client/ui";
const executed = (globalThis.__paseoPluginExecutions = globalThis.__paseoPluginExecutions || []);
executed.push(${JSON.stringify(spec.markerKey)});
function ProbeScreen({ theme }) {
return (
<View style={{ flex: 1, padding: 24 }}>
<Text style={{ color: theme.colors.foreground }}>${spec.name} screen</Text>
</View>
);
}
function ProbeItem({ currentScreen, openScreen }) {
return (
<SidebarRow
icon="Puzzle"
active={currentScreen?.screenId === "main"}
onPress={() => openScreen({ screenId: "main" })}
/>
);
}
export default function contribute(client) {
client.addScreen({ id: "main", title: ${JSON.stringify(spec.sidebarTitle)}, Component: ProbeScreen });
client.addSidebarHeaderItem({
id: "main",
title: ${JSON.stringify(spec.sidebarTitle)},
Component: ProbeItem,
});
return () => {};
}
`,
);
return {
directory,
cleanup: () => rm(directory, { recursive: true, force: true }),
};
}
export interface InstalledClientPluginsContext {
install: (spec: ClientProbePluginSpec) => Promise<void>;
}
export async function withInstalledClientPlugins<T>(
specs: readonly ClientProbePluginSpec[],
run: (ctx: InstalledClientPluginsContext) => Promise<T>,
): Promise<T> {
const client = await connectNewWorkspaceDaemonClient({ ownProjects: false });
const previous = await client.getDaemonConfig();
const created: Array<{ id: string; cleanup: () => Promise<void> }> = [];
const install = async (spec: ClientProbePluginSpec) => {
const fixture = await createClientProbePlugin(spec);
created.push({ id: spec.id, cleanup: fixture.cleanup });
await client.installDirectoryPlugin(fixture.directory);
};
try {
await client.patchDaemonConfig({ pluginsEnabled: true });
for (const spec of specs) {
await install(spec);
}
return await run({ install });
} finally {
for (const item of created.toReversed()) {
await client.removePlugin(item.id).catch(() => undefined);
}
await client
.patchDaemonConfig({ pluginsEnabled: previous.config.pluginsEnabled ?? false })
.catch(() => undefined);
await client.close().catch(() => undefined);
for (const item of created) {
await item.cleanup().catch(() => undefined);
}
}
}
export function pluginExecutionBypassSwitch(page: Page): Locator {
return page.getByRole("switch", { name: "Run plugins without asking", exact: true });
}
export function pluginExecutionBypassConfirmModal(page: Page): Locator {
return page.getByTestId("plugin-execution-bypass-confirm-modal");
}
export async function expectPluginExecutionBypass(page: Page, enabled: boolean): Promise<void> {
const toggle = pluginExecutionBypassSwitch(page);
await expect(toggle).toBeVisible({ timeout: 30_000 });
await expect(toggle).toHaveAttribute("aria-checked", String(enabled));
}
export async function openPluginExecutionBypassConfirm(page: Page): Promise<void> {
const toggle = pluginExecutionBypassSwitch(page);
await expect(toggle).toHaveAttribute("aria-checked", "false");
await toggle.click();
await expect(pluginExecutionBypassConfirmModal(page)).toBeVisible();
}
export async function cancelPluginExecutionBypassConfirm(page: Page): Promise<void> {
const modal = pluginExecutionBypassConfirmModal(page);
await expect(modal).toBeVisible();
await page.getByRole("button", { name: "Cancel", exact: true }).click();
await expect(modal).toHaveCount(0);
await expectPluginExecutionBypass(page, false);
}
export async function confirmPluginExecutionBypass(page: Page): Promise<void> {
const modal = pluginExecutionBypassConfirmModal(page);
await expect(modal).toBeVisible();
await page.getByRole("button", { name: "Turn on", exact: true }).click();
await expect(modal).toHaveCount(0);
await expectPluginExecutionBypass(page, true);
}
export async function setPluginExecutionBypass(page: Page, enabled: boolean): Promise<void> {
if (enabled) {
await openPluginExecutionBypassConfirm(page);
await confirmPluginExecutionBypass(page);
return;
}
const toggle = pluginExecutionBypassSwitch(page);
await expect(toggle).toHaveAttribute("aria-checked", "true");
await toggle.click();
await expect(pluginExecutionBypassConfirmModal(page)).toHaveCount(0);
await expectPluginExecutionBypass(page, false);
}
export function pluginApprovalSheet(page: Page): Locator {
return page.getByTestId("plugin-execution-approval");
}
export async function expectPluginApprovalPrompt(
page: Page,
expected: { pluginId: string; progress?: string },
): Promise<void> {
await expect(pluginApprovalSheet(page)).toBeVisible({ timeout: 30_000 });
await expect(page.getByTestId("plugin-execution-approval-plugin")).toContainText(
expected.pluginId,
);
if (expected.progress) {
await expect(page.getByTestId("plugin-execution-approval-progress")).toHaveText(
expected.progress,
);
}
}
export async function allowPluginExecution(page: Page): Promise<void> {
await page.getByRole("button", { name: "Allow", exact: true }).click();
}
export async function declinePluginExecution(page: Page): Promise<void> {
await page.getByRole("button", { name: "Don't allow", exact: true }).click();
}
async function readPromptIdentity(
page: Page,
): Promise<{ pluginText: string; hostText: string; key: string } | null> {
const pluginLocator = page.getByTestId("plugin-execution-approval-plugin");
const hostLocator = page.getByTestId("plugin-execution-approval-host");
if (!(await pluginLocator.isVisible().catch(() => false))) return null;
if (!(await hostLocator.isVisible().catch(() => false))) return null;
const pluginText = (await pluginLocator.textContent().catch(() => ""))?.trim() ?? "";
const hostText = (await hostLocator.textContent().catch(() => ""))?.trim() ?? "";
if (!pluginText || !hostText) return null;
return { pluginText, hostText, key: `${pluginText}\0${hostText}` };
}
async function waitForNextApprovalTarget(
page: Page,
previousKey: string | null,
): Promise<{ pluginText: string; hostText: string; key: string }> {
let matched: { pluginText: string; hostText: string; key: string } | null = null;
await expect
.poll(
async () => {
const current = await readPromptIdentity(page);
if (!current || current.key === previousKey) return false;
matched = current;
return true;
},
{ timeout: 30_000, message: "Expected next plugin execution approval prompt" },
)
.toBe(true);
if (!matched) {
throw new Error("Expected next plugin execution approval prompt");
}
return matched;
}
/**
* Approves every expected client plugin through the real confirmation sheet UI.
* Handles stacked plugins and multi-host arrivals in any order, then waits for the sheet to close.
*/
export async function approveClientPluginsInUi(
page: Page,
pluginIds: readonly string[],
): Promise<void> {
const remaining = [...pluginIds];
let previousKey: string | null = null;
while (remaining.length > 0) {
await expect(pluginApprovalSheet(page)).toBeVisible({ timeout: 30_000 });
const target = await waitForNextApprovalTarget(page, previousKey);
const matchedIndex = remaining.findIndex((id) => target.pluginText.includes(id));
if (matchedIndex === -1) {
throw new Error(
`Unexpected plugin execution prompt "${target.pluginText}" on "${target.hostText}"; expected one of: ${remaining.join(", ")}`,
);
}
remaining.splice(matchedIndex, 1);
previousKey = target.key;
await allowPluginExecution(page);
}
await expect(pluginApprovalSheet(page)).toHaveCount(0);
}
export async function getExecutedPluginMarkers(page: Page): Promise<string[]> {
return page.evaluate(() => {
const raw = (globalThis as { __paseoPluginExecutions?: unknown }).__paseoPluginExecutions;
return Array.isArray(raw) ? raw.filter((item): item is string => typeof item === "string") : [];
});
}
export async function expectExecutedPluginMarkers(
page: Page,
expected: readonly string[],
): Promise<void> {
await expect.poll(() => getExecutedPluginMarkers(page)).toEqual(expected);
}
export async function expectExecutedPluginMarkersContain(
page: Page,
marker: string,
): Promise<void> {
await expect.poll(() => getExecutedPluginMarkers(page)).toContain(marker);
}
export async function reloadKeepingPersistedState(page: Page): Promise<void> {
await page.evaluate(() => {
const nonce = localStorage.getItem("@paseo:e2e-seed-nonce");
if (!nonce) throw new Error("Expected e2e seed nonce before reload");
localStorage.setItem("@paseo:e2e-disable-default-seed-once", nonce);
});
await page.reload();
}
export async function ensureArtifactsDir(repoRoot: string): Promise<string> {
const dir = path.join(repoRoot, ".artifacts");
await mkdir(dir, { recursive: true });
return dir;
}
@@ -6,6 +6,7 @@ import { gotoAppShell } from "./app";
import { addConnectedHostAndReload } from "./hosts";
import { startIsolatedHostDaemon } from "./isolated-host-daemon";
import { connectNewWorkspaceDaemonClient } from "./new-workspace";
import { approveClientPluginsInUi } from "./plugin-execution-approval";
import { pluginRequirements } from "./plugin-fixture";
const id = "host-clients";
@@ -98,6 +99,7 @@ export async function installHostClientsScenario(page: Page) {
await primary.patchDaemonConfig({ pluginsEnabled: true });
await primary.installDirectoryPlugin(directory);
await gotoAppShell(page);
await approveClientPluginsInUi(page, [id]);
await openHostClients(page);
await addConnectedHostAndReload(page, {
serverId: secondary.serverId,
@@ -12,6 +12,7 @@ import {
openProjectViaDaemon,
submitNewWorkspacePrompt,
} from "./new-workspace";
import { approveClientPluginsInUi } from "./plugin-execution-approval";
import { copyPluginExample } from "./plugin-fixture";
import { getServerId } from "./server-id";
import { createTempGitRepo } from "./workspace";
@@ -147,6 +148,7 @@ export async function withNewWorkspaceIssuesExample(
const other = otherRepo ? await openProjectViaDaemon(client, otherRepo.path) : null;
let target = project;
await gotoAppShell(page);
await approveClientPluginsInUi(page, [PLUGIN_ID]);
await waitForSidebarHydration(page);
await openNewWorkspaceComposer(page, project);
// The sidebar rows used to reach the screen exist only at desktop width.
@@ -6,6 +6,7 @@ import { gotoAppShell, openSettings } from "./app";
import { openModelPicker } from "./agent-profiles";
import { openAgentRoute } from "./mock-agent";
import { connectNewWorkspaceDaemonClient, openGlobalNewWorkspaceComposer } from "./new-workspace";
import { approveClientPluginsInUi } from "./plugin-execution-approval";
import { copyPluginExample } from "./plugin-fixture";
import { seedWorkspace, type SeededWorkspace } from "./seed-client";
import { getServerId } from "./server-id";
@@ -76,6 +77,7 @@ export const test = base.extend<{ providerIcons: ProviderIconJourney }>({
try {
await page.setViewportSize(WIDE);
await gotoAppShell(page);
await approveClientPluginsInUi(page, ["provider-direct-example"]);
const iconPaths = await readIconPaths(page, plugin.directory);
await provide({ page, testInfo, iconPaths, workspace });
} finally {
@@ -7,6 +7,7 @@ import { expect, type Page } from "../fixtures";
import { gotoAppShell } from "./app";
import { installDaemonWebSocketGate } from "./daemon-websocket-gate";
import { connectDaemonClient } from "./daemon-client-loader";
import { approveClientPluginsInUi } from "./plugin-execution-approval";
import { copyPluginExample, pluginRequirements } from "./plugin-fixture";
const PLUGIN_ID = "retained-plugin-e2e";
@@ -76,6 +77,7 @@ async function createProbe(page: Page) {
async open() {
await page.setViewportSize({ width: 1100, height: 800 });
await gotoAppShell(page);
await approveClientPluginsInUi(page, [PLUGIN_ID]);
await page.getByRole("button", { name: "Reconnect probe", exact: true }).click();
await expect(page.getByText("Stored title: Agent monitor", { exact: true })).toBeVisible();
},
@@ -8,6 +8,7 @@ import { connectDaemonClient } from "./daemon-client-loader";
import { addConnectedHostAndReload } from "./hosts";
import { gotoAppShell, openSettings } from "./app";
import { openHostSection, selectSettingsHost } from "./settings";
import { approveClientPluginsInUi } from "./plugin-execution-approval";
import { pluginRequirements } from "./plugin-fixture";
import {
backToPlugins,
@@ -108,9 +109,16 @@ export async function expectAppMismatch(page: Page) {
).toBeVisible();
}
export async function correctRequirementAndReload(page: Page, directory: string) {
export async function correctRequirementAndReload(
page: Page,
directory: string,
options?: { approvePrompt?: boolean },
) {
await writeRequirements(directory, pluginRequirements.paseo);
await reloadRequirementsPlugin(page);
if (options?.approvePrompt) {
await approveClientPluginsInUi(page, [PLUGIN_ID]);
}
await backToPlugins(page, PLUGIN_ID);
await expectPluginHealthy(page, PLUGIN_ID);
await expect(page.getByText(/Your app is/)).toHaveCount(0);
@@ -1,6 +1,7 @@
import { mkdtemp, rm, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import path from "node:path";
import { approveClientPluginsInUi } from "./plugin-execution-approval";
import { copyPluginExample, pluginRequirements } from "./plugin-fixture";
import { expect, test as base, type Page } from "../fixtures";
import { gotoAppShell, openSettings } from "./app";
@@ -99,11 +100,13 @@ export const test = base.extend<{ settingsPlugin: SettingsClient }>({
export async function openDisplaySettings(page: Page) {
await gotoAppShell(page);
await approveClientPluginsInUi(page, ["settings-example", TABBED_PLUGIN_ID]);
await openSettings(page);
await openSettingsExamplePage(page);
}
export async function openCompactDisplaySettings(page: Page) {
await gotoAppShell(page);
await approveClientPluginsInUi(page, ["settings-example", TABBED_PLUGIN_ID]);
await openCompactSettings(page, new URL(page.url()).pathname);
await openSettingsExamplePage(page);
}
@@ -120,6 +123,7 @@ async function expectSettingsExampleScreen(page: Page) {
}
export async function openPluginsPage(page: Page) {
await gotoAppShell(page);
await approveClientPluginsInUi(page, ["settings-example", TABBED_PLUGIN_ID]);
await openSettings(page);
await openHostSection(page, getServerId(), "plugins");
}
@@ -183,6 +187,7 @@ export async function expectSettingsTab(page: Page, title: "General" | "Advanced
}
export async function openTabbedSettingsLink(page: Page, title: "General" | "Advanced") {
await gotoAppShell(page);
await approveClientPluginsInUi(page, ["settings-example", TABBED_PLUGIN_ID]);
await page.goto(`${pluginPageRoute(TABBED_PLUGIN_ID)}/${title.toLowerCase()}`);
await expectSettingsTab(page, title);
}
@@ -4,11 +4,16 @@ import path from "node:path";
import { expect, type Locator, type Page } from "@playwright/test";
import { openCommandCenter } from "./command-center";
import { connectNewWorkspaceDaemonClient } from "./new-workspace";
import { approveClientPluginsInUi } from "./plugin-execution-approval";
import { pluginRequirements } from "./plugin-fixture";
export const SHOWCASE_PLUGIN_ID = "sidebar-showcase";
export const LEGACY_PLUGIN_ID = "legacy-sidebar";
export const BOTS_PLUGIN_ID = "sidebar-bots";
export async function approveSidebarPluginsInUi(page: Page): Promise<void> {
await approveClientPluginsInUi(page, [SHOWCASE_PLUGIN_ID, LEGACY_PLUGIN_ID, BOTS_PLUGIN_ID]);
}
export const WIDE = { width: 1440, height: 900 };
export const COMPACT = { width: 390, height: 844 };
@@ -2,6 +2,7 @@ import { mkdtemp, rm, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import path from "node:path";
import { expect, type Page, type TestInfo } from "@playwright/test";
import { approveClientPluginsInUi } from "./plugin-execution-approval";
import { copyPluginExample, pluginRequirements } from "./plugin-fixture";
import { connectNewWorkspaceDaemonClient } from "./new-workspace";
import { openAgentRoute, seedMockAgentWorkspace, type MockAgentWorkspace } from "./mock-agent";
@@ -110,7 +111,8 @@ export default function contribute(client) {
return () => {};
}`;
const PROMPT_PLUGIN_ID = "timeline-prompt-e2e";
export const PROMPT_PLUGIN_ID = "timeline-prompt-e2e";
export const POPOVER_PLUGIN_ID = "timeline-popover-e2e";
function promptClientSource(prompts?: readonly string[]): string {
return `import React from "react";
@@ -201,6 +203,7 @@ export async function withTimelinePlugin(
run: async () => {
try {
await openAgentRoute(page, agent);
await approveClientPluginsInUi(page, [PLUGIN_ID]);
await expect(
page.getByRole("textbox", { name: "Message agent..." }).first(),
).toBeVisible();
@@ -356,6 +359,7 @@ export async function viewInlineThinkingExample(page: Page, info: TestInfo): Pro
await client.patchDaemonConfig({ pluginsEnabled: true });
await client.installDirectoryPlugin(example.directory);
await openAgentRoute(page, agent);
await approveClientPluginsInUi(page, ["inline-thinking"]);
await expect(page.getByRole("textbox", { name: "Message agent..." }).first()).toBeVisible();
await requestPluginTimeline(agent);
const thought = page.getByText(/^Need to find the scroll container/);
@@ -423,6 +427,7 @@ export default function contribute(client) {
}`,
run: async () => {
await openAgentRoute(page, agent);
await approveClientPluginsInUi(page, ["timeline-local-ids"]);
await expect(page.getByRole("textbox", { name: "Message agent..." }).first()).toBeVisible();
await run();
},
@@ -6,6 +6,7 @@ import type { TestInfo, BrowserContext } from "@playwright/test";
import { expect, type Page } from "../fixtures";
import { gotoAppShell, openSettings } from "./app";
import { connectNewWorkspaceDaemonClient } from "./new-workspace";
import { approveClientPluginsInUi } from "./plugin-execution-approval";
import { copyPluginExample } from "./plugin-fixture";
async function chooseChinese(page: Page) {
@@ -40,6 +41,7 @@ export async function verifyPluginTranslations(page: Page, info: TestInfo) {
await client.installDirectoryPlugin(example.directory);
await page.setViewportSize({ width: 1440, height: 1000 });
await gotoAppShell(page);
await approveClientPluginsInUi(page, ["translation-notes"]);
await page.getByRole("button", { name: "Workspace notes", exact: true }).click();
await expect(page.getByText("App language: en", { exact: true })).toBeVisible();
await page
@@ -125,6 +127,7 @@ export async function verifyPluginToolTranslations(page: Page, info: TestInfo) {
await client.installDirectoryPlugin(example.directory);
await page.setViewportSize({ width: 1440, height: 1000 });
await gotoAppShell(page);
await approveClientPluginsInUi(page, ["translation-notes"]);
await page.goto(buildAgentRoute(workspace.workspaceId, agent.id));
const commandCenter = await openCommandCenter(page);
await commandCenter.getByTestId("command-center-input").fill("Show notes tools");
@@ -4,6 +4,7 @@ import type { DaemonClient as InternalDaemonClient } from "@getpaseo/client/inte
import { expect, test as base, type Page } from "../fixtures";
import { gotoAppShell, openSettings } from "./app";
import { connectDaemonClient } from "./daemon-client-loader";
import { approveClientPluginsInUi } from "./plugin-execution-approval";
import { copyPluginExample, pluginRequirements } from "./plugin-fixture";
import { getServerId } from "./server-id";
import { leaveProviderDetail, openSettingsHostSection } from "./settings";
@@ -84,8 +85,14 @@ export const test = base.extend<{ providerUpdateFailure: ProviderUpdateFailure }
},
});
export async function openProviderInstallation(page: Page): Promise<void> {
export async function openProviderInstallation(
page: Page,
options?: { approvePlugin?: boolean },
): Promise<void> {
await gotoAppShell(page);
if (options?.approvePlugin) {
await approveClientPluginsInUi(page, [PLUGIN_ID]);
}
await openSettings(page);
await openSettingsHostSection(page, getServerId(), "providers");
await page
@@ -1,6 +1,7 @@
import { readFile, writeFile } from "node:fs/promises";
import path from "node:path";
import { expect, type Page } from "@playwright/test";
import { approveClientPluginsInUi } from "./plugin-execution-approval";
import { copyPluginExample } from "./plugin-fixture";
import { connectNewWorkspaceDaemonClient } from "./new-workspace";
import { seedWorkspace } from "./seed-client";
@@ -33,6 +34,7 @@ export async function withSidebarViews(
await client.installDirectoryPlugin(example.directory);
await page.setViewportSize({ width: 1280, height: 900 });
await gotoWorkspace(page, workspace.workspaceId);
await approveClientPluginsInUi(page, ["sidebar-views"]);
await run(sidebarViews(page, workspace.workspaceId, client));
} finally {
await client.removePlugin("sidebar-views");
+2
View File
@@ -65,6 +65,7 @@ import { WorkspaceShortcutTargetsSubscriber } from "@/components/workspace-short
import { FloatingPanelPortalHost } from "@/components/ui/floating-panel-portal";
import { HostChooserModal, useHostChooser } from "@/hosts/host-chooser";
import { HostConfirmationSheet } from "@/hosts/host-confirmation-sheet";
import { PluginExecutionApprovalSheet } from "@/plugins/execution-approval/sheet";
import { HEADER_INNER_HEIGHT, useIsCompactFormFactor } from "@/constants/layout";
import {
canDesktopAppSidebarShare,
@@ -568,6 +569,7 @@ function AppContainer({ children, chromeEnabled: chromeEnabledOverride }: AppCon
<AddProjectFlowHost />
<HostChooserModal />
<HostConfirmationSheet />
<PluginExecutionApprovalSheet />
<ProviderSettingsHost />
<WorkspaceSetupDialog />
<KeyboardShortcutsDialog />
@@ -1,4 +1,4 @@
import { getFileExtension, getMimeTypeFromPath } from "@/attachments/file-types";
import { getFileExtension } from "@/attachments/file-types";
import { copyDesktopAttachmentFile } from "@/desktop/attachments/desktop-file-commands";
import { readDesktopFileBase64 } from "@/desktop/attachments/desktop-preview-url";
@@ -8,14 +8,6 @@ export interface SelectedFile {
readBytes(): Promise<Uint8Array>;
}
export function selectedFileFromWebFile(file: File): SelectedFile {
return {
fileName: file.name,
mimeType: file.type || getMimeTypeFromPath(file.name),
readBytes: async () => new Uint8Array(await file.arrayBuffer()),
};
}
function base64ToUint8Array(base64: string): Uint8Array {
const binaryString = atob(base64);
const bytes = new Uint8Array(binaryString.length);
-59
View File
@@ -995,65 +995,6 @@ describe("attachments restored from a queued message", () => {
expect(client.calls[0]?.options.attachments).toEqual([uploadedImage]);
});
it("clears the optimistic timeline bubble when a direct send is queued behind a boundary", async () => {
const client = createFakeSendClient();
client.sendAgentMessage = async (agentId, text, options) => {
client.calls.push({ agentId, text, options });
return { deliveryStatus: "queued", messageId: options.messageId };
};
const stream = createFakeStream();
await dispatchComposerAgentMessage({
client,
agentId: "agent",
text: "follow up",
attachments: [],
submission: stream,
activeTurnBehavior: "interrupt",
});
expect(stream.tail.get("agent") ?? []).toEqual([]);
expect(stream.head.get("agent") ?? []).toEqual([]);
});
it("clears the optimistic timeline bubble and settles staged switch via queued callback when a direct provider switch is queued", async () => {
const client = createFakeSendClient();
client.switchAgentProvider = async () => ({
deliveryStatus: "queued",
agent: undefined,
});
const stream = createFakeStream();
let committed = 0;
let queued = 0;
await dispatchComposerAgentMessage({
client,
agentId: "agent",
text: "switch later",
attachments: [],
submission: stream,
currentProvider: "claude",
stagedProviderSwitch: {
provider: "codex",
model: null,
thinkingOptionId: null,
modeId: null,
providerOptions: {},
},
onProviderSwitchCommitted: () => {
committed += 1;
},
onProviderSwitchQueued: () => {
queued += 1;
},
});
expect(committed).toBe(0);
expect(queued).toBe(1);
expect(stream.tail.get("agent") ?? []).toEqual([]);
expect(stream.head.get("agent") ?? []).toEqual([]);
});
it("counts a restored forge item as selected and toggles it off", () => {
expect(isAttachmentSelectedForForgeItem([restoredIssue], issueItem)).toBe(true);
expect(isAttachmentSelectedForForgeItem([restoredIssue], prItem)).toBe(false);
+1 -20
View File
@@ -217,7 +217,6 @@ export interface DispatchComposerAgentMessageInput {
currentModel?: string | null;
stagedProviderSwitch?: StagedProviderSwitch | null;
onProviderSwitchCommitted?: (agent: AgentSnapshotPayload | undefined) => void | Promise<void>;
onProviderSwitchQueued?: () => void;
}
function buildPendingProviderSwitch(
@@ -243,15 +242,6 @@ function buildPendingProviderSwitch(
});
}
function isQueuedDeliveryResult(result: unknown): boolean {
return (
typeof result === "object" &&
result !== null &&
"deliveryStatus" in result &&
result.deliveryStatus === "queued"
);
}
export async function dispatchComposerAgentMessage(
input: DispatchComposerAgentMessageInput,
): Promise<void> {
@@ -291,25 +281,16 @@ export async function dispatchComposerAgentMessage(
...(imagePayload.images ? { images: imagePayload.images } : {}),
attachments: [...wirePayload.attachments, ...(imagePayload.attachments ?? [])],
});
if (isQueuedDeliveryResult(result)) {
input.submission.reject(input.agentId, clientMessageId);
input.onProviderSwitchQueued?.();
return;
}
input.submission.accept(input.agentId, clientMessageId);
await input.onProviderSwitchCommitted?.(result.agent);
return;
}
const result = await input.client.sendAgentMessage(input.agentId, input.text, {
await input.client.sendAgentMessage(input.agentId, input.text, {
messageId: clientMessageId,
...(input.activeTurnBehavior ? { activeTurnBehavior: input.activeTurnBehavior } : {}),
...(imagePayload.images ? { images: imagePayload.images } : {}),
attachments: [...wirePayload.attachments, ...(imagePayload.attachments ?? [])],
});
if (isQueuedDeliveryResult(result)) {
input.submission.reject(input.agentId, clientMessageId);
return;
}
input.submission.accept(input.agentId, clientMessageId);
} catch (error) {
input.submission.reject(input.agentId, clientMessageId);
@@ -3,11 +3,7 @@ import {
isRasterImageFile,
isRasterImagePath,
} from "@/attachments/file-types";
import {
readDesktopFileBytes,
selectedFileFromWebFile,
type SelectedFile,
} from "@/attachments/selected-file";
import { readDesktopFileBytes, type SelectedFile } from "@/attachments/selected-file";
import type { DroppedItem } from "@/components/file-drop/types";
interface DroppedAttachmentsRuntime {
@@ -40,7 +36,12 @@ export function droppedItemsToSelectedFiles(
if (isRasterImageFile(item.file)) {
continue;
}
files.push(selectedFileFromWebFile(item.file));
const file = item.file;
files.push({
fileName: file.name,
mimeType: file.type || getMimeTypeFromPath(file.name),
readBytes: async () => new Uint8Array(await file.arrayBuffer()),
});
continue;
}
+1 -14
View File
@@ -166,7 +166,7 @@ import type {
WorkspaceFileComposerAttachment,
WorkspaceComposerAttachment,
} from "@/attachments/types";
import { selectedFileFromWebFile, type SelectedFile } from "@/attachments/selected-file";
import type { SelectedFile } from "@/attachments/selected-file";
import { resolveComposerAttachmentSubmitFormat } from "@/composer/attachments/submit";
import { ComposerInputProvider, type ComposerInput } from "@/composer/session";
import type { ComposerFocusOptions } from "@/composer/model";
@@ -1775,11 +1775,6 @@ function ComposerContentImpl({
}
}
},
onProviderSwitchQueued: () => {
if (stagedProviderSwitch) {
settleStagedProviderSwitch(serverId, targetAgentId, stagedProviderSwitch);
}
},
activeTurnBehavior,
activeTurnId:
activeTurnBehavior === "steer"
@@ -2046,13 +2041,6 @@ function ComposerContentImpl({
[addFiles, client, t],
);
const handlePasteFiles = useCallback(
(files: File[]) => {
void uploadSelectedFiles(files.map(selectedFileFromWebFile));
},
[uploadSelectedFiles],
);
const handlePickFile = useCallback(async () => {
if (!client) {
toastErrorRef.current(t("composer.errors.daemonClientDisconnected"));
@@ -2710,7 +2698,6 @@ function ComposerContentImpl({
attachmentMenuItems={attachmentMenuItems}
onAttachButtonRef={handleAttachButtonRef}
onAddImages={addImages}
onPasteFiles={handlePasteFiles}
onPasteImages={handleNativePasteImages}
client={client}
isReadyForDictation={isDictationReady}
+2 -29
View File
@@ -21,7 +21,6 @@ import {
useRef,
useCallback,
useEffect,
useEffectEvent,
useLayoutEffect,
useImperativeHandle,
useMemo,
@@ -65,7 +64,6 @@ import {
collectImageFilesFromClipboardData,
filesToImageAttachments,
} from "@/utils/image-attachments-from-files";
import { isRasterImageFile } from "@/attachments/file-types";
import type { ComposerAttachment } from "@/attachments/types";
import type { ImageAttachment, MessagePayload, TextReplacement } from "@/composer/types";
import { focusWithRetries } from "@/utils/web-focus";
@@ -83,7 +81,7 @@ import { formatShortcut, type ShortcutKey } from "@/utils/format-shortcut";
import { getShortcutOs } from "@/utils/shortcut-platform";
import type { MessageInputKeyboardActionKind } from "@/keyboard/actions";
import { isImeComposingKeyboardEvent } from "@/utils/keyboard-ime";
import { getIsElectron, isNative, isWeb } from "@/constants/platform";
import { isNative, isWeb } from "@/constants/platform";
import { useIsCompactFormFactor } from "@/constants/layout";
import { useComposerKeyboardScope } from "@/composer/keyboard-scope";
import { RenderProfile } from "@/utils/render-profiler";
@@ -175,7 +173,6 @@ export interface MessageInputProps {
attachmentMenuItems: AttachmentMenuItem[];
onAttachButtonRef?: (node: View | null) => void;
onAddImages?: (images: ImageAttachment[]) => void;
onPasteFiles?: (files: File[]) => void;
onPasteImages?: (files: readonly NativePastedFile[]) => void;
client: DaemonClient | null;
/** Dictation start gate from host runtime (socket connected + directory ready). */
@@ -523,36 +520,22 @@ function getTextInputNativeElement(current: ComposerTextInputHandle | null): HTM
interface PasteEffectArgs {
textarea: HTMLElement | null;
isConnected: boolean;
isSubmitLoading: boolean;
disabled: boolean;
isDictating: boolean;
isRealtimeVoiceForCurrentAgent: boolean;
onAddImages: ((images: ImageAttachment[]) => void) | undefined;
onPasteFiles: ((files: File[]) => void) | undefined;
}
function usePasteEffect(args: PasteEffectArgs): void {
const {
textarea,
isConnected,
isSubmitLoading,
disabled,
isDictating,
isRealtimeVoiceForCurrentAgent,
onAddImages,
onPasteFiles,
} = args;
const pasteFiles = useEffectEvent((clipboardData: DataTransfer | null) => {
if (!isConnected || isSubmitLoading || !onPasteFiles || getIsElectron()) return false;
const files = Array.from(clipboardData?.files ?? []).filter((file) => !isRasterImageFile(file));
if (files.length === 0) return false;
onPasteFiles(files);
return true;
});
useEffect(() => {
if (!isWeb) return;
@@ -563,13 +546,8 @@ function usePasteEffect(args: PasteEffectArgs): void {
if (disabled || isDictating || isRealtimeVoiceForCurrentAgent) return;
const imageFiles = collectImageFilesFromClipboardData(event.clipboardData);
const didPasteFiles = pasteFiles(event.clipboardData);
if (didPasteFiles) event.preventDefault();
if (imageFiles.length === 0) {
if (!didPasteFiles && pasteLinkedClipboardText(textarea, event.clipboardData)) {
event.preventDefault();
}
if (pasteLinkedClipboardText(textarea, event.clipboardData)) event.preventDefault();
return;
}
if (!isConnected || !onAddImages) return;
@@ -1213,7 +1191,6 @@ interface ResolvedMessageInputProps {
attachmentMenuItems: AttachmentMenuItem[];
onAttachButtonRef: ((node: View | null) => void) | undefined;
onAddImages: ((images: ImageAttachment[]) => void) | undefined;
onPasteFiles: ((files: File[]) => void) | undefined;
onPasteImages: ((files: readonly NativePastedFile[]) => void) | undefined;
client: DaemonClient | null;
isReadyForDictation: boolean | undefined;
@@ -1262,7 +1239,6 @@ function resolveMessageInputProps(props: MessageInputProps): ResolvedMessageInpu
attachmentMenuItems: props.attachmentMenuItems,
onAttachButtonRef: props.onAttachButtonRef,
onAddImages: props.onAddImages,
onPasteFiles: props.onPasteFiles,
onPasteImages: props.onPasteImages,
client: props.client,
isReadyForDictation: props.isReadyForDictation,
@@ -1345,7 +1321,6 @@ export const MessageInput = forwardRef<MessageInputRef, MessageInputProps>(
attachmentMenuItems,
onAttachButtonRef,
onAddImages,
onPasteFiles,
onPasteImages,
client,
isReadyForDictation,
@@ -1899,8 +1874,6 @@ export const MessageInput = forwardRef<MessageInputRef, MessageInputProps>(
isDictating,
isRealtimeVoiceForCurrentAgent,
onAddImages,
onPasteFiles,
isSubmitLoading,
});
const handleSelectionChange = useCallback(
+10 -6
View File
@@ -4,11 +4,7 @@ import { File } from "expo-file-system";
import { getDesktopHost, isElectronRuntime } from "@/desktop/host";
import { isWeb } from "@/constants/platform";
import { getMimeTypeFromPath } from "@/attachments/file-types";
import {
readDesktopFileBytes,
selectedFileFromWebFile,
type SelectedFile,
} from "@/attachments/selected-file";
import { readDesktopFileBytes, type SelectedFile } from "@/attachments/selected-file";
async function pickFilesWithDesktopDialog(): Promise<SelectedFile[] | null> {
const dialog = getDesktopHost()?.dialog;
@@ -56,7 +52,15 @@ function pickFilesWithWebInput(): Promise<SelectedFile[] | null> {
return;
}
resolve(files.map(selectedFileFromWebFile));
const result: SelectedFile[] = [];
for (const file of files) {
result.push({
fileName: file.name,
mimeType: file.type || getMimeTypeFromPath(file.name),
readBytes: async () => new Uint8Array(await file.arrayBuffer()),
});
}
resolve(result);
});
input.addEventListener("cancel", () => {
@@ -1,4 +1,4 @@
import { useHostFeatureAvailabilityMap } from "@/runtime/host-features";
import { useHostFeatureMap } from "@/runtime/host-features";
import { useCallback, useEffect, useMemo } from "react";
import { useStoreWithEqualityFn } from "zustand/traditional";
import { useCreateFlowStore } from "@/stores/create-flow-store";
@@ -142,9 +142,8 @@ export function useSidebarWorkspacesList(options?: {
const workspaceSort = useSidebarViewStore((state) => state.workspaceSort);
const groupMode = useSidebarViewStore((state) => state.groupMode);
const sortSupport = useHostFeatureAvailabilityMap(directoryServerIds, "workspaceSortTimes");
// Cached workspaces are visible before their host sends server info.
const workspaceSortSupported = ![...sortSupport.values()].includes(false);
const sortSupport = useHostFeatureMap(directoryServerIds, "workspaceSortTimes");
const workspaceSortSupported = [...sortSupport.values()].every(Boolean);
const sort =
groupMode === "project" && (workspaceSort === "manual" || workspaceSortSupported)
? workspaceSort
+12 -3
View File
@@ -2815,9 +2815,18 @@ export const ar: TranslationResources = {
title: "عام",
sending: "الإرسال",
setup: {
label: "الإعداد الأولي",
description: "أعد المرور على المظهر والمزوّدين والمشاريع وإقران الهاتف",
action: "إظهار الإعداد مجددًا",
label: "الإعداد",
description: "أعد تشغيل دليل الترحيب",
action: "عرض",
},
pluginExecutionBypass: {
label: "تشغيل الإضافات دون سؤال",
description:
"يمكن لأي مضيف متصل تشغيل تعليمات الإضافات داخل Paseo والوصول إلى المضيفين الآخرين",
confirmTitle: "تشغيل الإضافات دون سؤال؟",
confirmMessage:
"يمكن لأي مضيف متصل تشغيل تعليمات الإضافات داخل Paseo والوصول إلى المضيفين المتصلين الآخرين. فعّل هذا الخيار فقط إذا كنت تثق بكل مضيف تتصل به.",
confirmAction: "تفعيل",
},
browserData: {
title: "بيانات المتصفح",
+30 -3
View File
@@ -2772,6 +2772,24 @@ export const en = {
unavailable: "This plugin settings screen is unavailable.",
backToPlugins: "Back to plugins",
},
clientExecution: {
promptTitle: "Allow plugin in this app?",
promptDescription:
"This plugin runs unsandboxed code in Paseo and can reach your connected hosts. Only allow plugins you trust.",
pluginLabel: "Plugin",
hostLabel: "Host",
queueProgress: "{{step}} of {{total}}",
allow: "Allow",
decline: "Don't allow",
blockedBadge: "blocked",
blockedTitle: "Blocked on this device",
blockedDescription: "This plugin runs on the host, but its app code is blocked here.",
surfaceBlocked: "App code for this plugin is blocked on this device.",
allowAction: "Allow on this device",
blockAction: "Block on this device",
allowedToast: "Allowed {{name}} on this device",
blockedToast: "Blocked {{name}} on this device",
},
trustedTitle: "Plugins are trusted code",
trustedDescription:
"They run on this host and inside the app without sandboxing. Install only code you trust.",
@@ -2913,9 +2931,18 @@ export const en = {
title: "General",
sending: "Sending",
setup: {
label: "First-run setup",
description: "Walk through appearance, providers, projects and phone pairing again",
action: "Show setup again",
label: "Setup",
description: "Run the welcome guide again",
action: "Show",
},
pluginExecutionBypass: {
label: "Run plugins without asking",
description:
"Any connected host can run plugin code inside Paseo and reach your other hosts",
confirmTitle: "Run plugins without asking?",
confirmMessage:
"Any connected host can run plugin code inside Paseo and reach your other connected hosts. Only turn this on if you trust every host you connect to.",
confirmAction: "Turn on",
},
browserData: {
title: "Browser data",
+11 -3
View File
@@ -2837,10 +2837,18 @@ export const es: TranslationResources = {
title: "General",
sending: "Envío",
setup: {
label: "Configuración inicial",
label: "Configuración",
description: "Volver a abrir la guía de bienvenida",
action: "Mostrar",
},
pluginExecutionBypass: {
label: "Ejecutar plugins sin preguntar",
description:
"Vuelve a recorrer apariencia, proveedores, proyectos y emparejamiento del teléfono",
action: "Mostrar configuración de nuevo",
"Cualquier host conectado puede ejecutar código de plugins en Paseo y acceder a tus otros hosts",
confirmTitle: "¿Ejecutar plugins sin preguntar?",
confirmMessage:
"Cualquier host conectado puede ejecutar código de plugins en Paseo y acceder a tus otros hosts conectados. Actívalo solo si confías en cada host al que te conectas.",
confirmAction: "Activar",
},
browserData: {
title: "Datos del navegador",
+11 -3
View File
@@ -2838,10 +2838,18 @@ export const fr: TranslationResources = {
title: "Général",
sending: "Envoi",
setup: {
label: "Configuration initiale",
label: "Configuration",
description: "Rouvrir le guide de bienvenue",
action: "Afficher",
},
pluginExecutionBypass: {
label: "Exécuter les plugins sans demander",
description:
"Reprendre l'apparence, les fournisseurs, les projets et l'appairage du téléphone",
action: "Afficher la configuration",
"Tout hôte connecté peut exécuter du code de plugin dans Paseo et accéder à vos autres hôtes",
confirmTitle: "Exécuter les plugins sans demander ?",
confirmMessage:
"Tout hôte connecté peut exécuter du code de plugin dans Paseo et accéder à vos autres hôtes connectés. Activez cette option uniquement si vous faites confiance à chaque hôte auquel vous vous connectez.",
confirmAction: "Activer",
},
browserData: {
title: "Données du navigateur",
+11 -3
View File
@@ -2805,10 +2805,18 @@ export const ja: TranslationResources = {
title: "一般",
sending: "送信",
setup: {
label: "初回セットアップ",
label: "セットアップ",
description: "ようこそガイドをもう一度開く",
action: "表示",
},
pluginExecutionBypass: {
label: "確認せずにプラグインを実行",
description:
"外観、プロバイダー、プロジェクト、スマートフォンのペアリングをもう一度設定します",
action: "セットアップを再表示",
"接続中のどのホストも Paseo 内でプラグインコードを実行し、他のホストにアクセスできます",
confirmTitle: "確認せずにプラグインを実行しますか?",
confirmMessage:
"接続中のどのホストも Paseo 内でプラグインコードを実行し、接続中の他のホストにアクセスできます。接続するすべてのホストを信頼する場合にのみオンにしてください。",
confirmAction: "オンにする",
},
browserData: {
title: "ブラウザーデータ",
+12 -3
View File
@@ -2791,9 +2791,18 @@ export const ko: TranslationResources = {
title: "일반",
sending: "전송",
setup: {
label: "초기 설정",
description: "모양, 제공자, 프로젝트, 휴대폰 페어링을 다시 진행합니다",
action: "설정 다시 보기",
label: "설정",
description: "시작 가이드를 다시 엽니다",
action: "보기",
},
pluginExecutionBypass: {
label: "확인 없이 플러그인 실행",
description:
"연결된 모든 호스트가 Paseo 내에서 플러그인 코드를 실행하고 다른 호스트에 접근할 수 있습니다",
confirmTitle: "확인 없이 플러그인을 실행할까요?",
confirmMessage:
"연결된 모든 호스트가 Paseo 내에서 플러그인 코드를 실행하고 연결된 다른 호스트에 접근할 수 있습니다. 연결하는 모든 호스트를 신뢰하는 경우에만 켜세요.",
confirmAction: "켜기",
},
browserData: {
title: "브라우저 데이터",
@@ -24,6 +24,24 @@ export const pluginSettings = {
backToPlugins: "العودة إلى الإضافات",
},
title: "الإضافات",
clientExecution: {
promptTitle: "السماح للإضافة بالعمل في هذا التطبيق؟",
promptDescription:
"تشغّل هذه الإضافة تعليمات برمجية غير معزولة داخل Paseo ويمكنها الوصول إلى المضيفين المتصلين. اسمح فقط بالإضافات التي تثق بها.",
pluginLabel: "الإضافة",
hostLabel: "المضيف",
queueProgress: "{{step}} من {{total}}",
allow: "سماح",
decline: "عدم السماح",
blockedBadge: "محظورة",
blockedTitle: "محظورة على هذا الجهاز",
blockedDescription: "تعمل هذه الإضافة على المضيف، لكن تعليماتها في التطبيق محظورة هنا.",
surfaceBlocked: "تعليمات التطبيق لهذه الإضافة محظورة على هذا الجهاز.",
allowAction: "السماح على هذا الجهاز",
blockAction: "الحظر على هذا الجهاز",
allowedToast: "تم السماح لـ {{name}} على هذا الجهاز",
blockedToast: "تم حظر {{name}} على هذا الجهاز",
},
trustedTitle: "الإضافات تعليمات برمجية موثوقة",
trustedDescription:
"تعمل على هذا المضيف وداخل التطبيق دون عزل. ثبّت فقط التعليمات البرمجية التي تثق بها.",
@@ -82,6 +100,25 @@ export const pluginSettings = {
backToPlugins: "Volver a plugins",
},
title: "Plugins",
clientExecution: {
promptTitle: "¿Permitir este plugin en la app?",
promptDescription:
"Este plugin ejecuta código sin aislamiento en Paseo y puede acceder a tus hosts conectados. Permite solo plugins de confianza.",
pluginLabel: "Plugin",
hostLabel: "Host",
queueProgress: "{{step}} de {{total}}",
allow: "Permitir",
decline: "No permitir",
blockedBadge: "bloqueado",
blockedTitle: "Bloqueado en este dispositivo",
blockedDescription:
"Este plugin se ejecuta en el host, pero su código en la app está bloqueado aquí.",
surfaceBlocked: "El código de la app para este plugin está bloqueado en este dispositivo.",
allowAction: "Permitir en este dispositivo",
blockAction: "Bloquear en este dispositivo",
allowedToast: "{{name}} permitido en este dispositivo",
blockedToast: "{{name}} bloqueado en este dispositivo",
},
trustedTitle: "Los plugins son código de confianza",
trustedDescription:
"Se ejecutan en este host y dentro de la app sin aislamiento. Instala solo código de confianza.",
@@ -140,6 +177,25 @@ export const pluginSettings = {
backToPlugins: "Retour aux plugins",
},
title: "Plugins",
clientExecution: {
promptTitle: "Autoriser ce plugin dans l’app ?",
promptDescription:
"Ce plugin exécute du code sans isolation dans Paseo et peut atteindre vos hôtes connectés. N’autorisez que les plugins fiables.",
pluginLabel: "Plugin",
hostLabel: "Hôte",
queueProgress: "{{step}} sur {{total}}",
allow: "Autoriser",
decline: "Refuser",
blockedBadge: "bloqué",
blockedTitle: "Bloqué sur cet appareil",
blockedDescription:
"Ce plugin s’exécute sur l’hôte, mais son code dans l’app est bloqué ici.",
surfaceBlocked: "Le code applicatif de ce plugin est bloqué sur cet appareil.",
allowAction: "Autoriser sur cet appareil",
blockAction: "Bloquer sur cet appareil",
allowedToast: "{{name}} autorisé sur cet appareil",
blockedToast: "{{name}} bloqué sur cet appareil",
},
trustedTitle: "Les plugins sont du code de confiance",
trustedDescription:
"Ils s’exécutent sur cet hôte et dans l’app sans isolation. N’installez que du code fiable.",
@@ -198,6 +254,25 @@ export const pluginSettings = {
backToPlugins: "プラグインに戻る",
},
title: "プラグイン",
clientExecution: {
promptTitle: "このアプリでプラグインを許可しますか?",
promptDescription:
"このプラグインは Paseo 内で分離されずにコードを実行し、接続中のホストにアクセスできます。信頼できるプラグインのみ許可してください。",
pluginLabel: "プラグイン",
hostLabel: "ホスト",
queueProgress: "{{step}} / {{total}}",
allow: "許可",
decline: "許可しない",
blockedBadge: "ブロック中",
blockedTitle: "このデバイスでブロックされています",
blockedDescription:
"このプラグインはホストで動作していますが、アプリ側コードはここでブロックされています。",
surfaceBlocked: "このプラグインのアプリ側コードはこのデバイスでブロックされています。",
allowAction: "このデバイスで許可",
blockAction: "このデバイスでブロック",
allowedToast: "このデバイスで {{name}} を許可しました",
blockedToast: "このデバイスで {{name}} をブロックしました",
},
trustedTitle: "プラグインは信頼済みコードです",
trustedDescription:
"ホストとアプリ内で分離されずに実行されます。信頼できるコードのみインストールしてください。",
@@ -256,6 +331,25 @@ export const pluginSettings = {
backToPlugins: "플러그인으로 돌아가기",
},
title: "플러그인",
clientExecution: {
promptTitle: "이 앱에서 플러그인 실행을 허용할까요?",
promptDescription:
"이 플러그인은 Paseo 내에서 격리 없이 코드를 실행하며 연결된 호스트에 접근할 수 있습니다. 신뢰하는 플러그인만 허용하세요.",
pluginLabel: "플러그인",
hostLabel: "호스트",
queueProgress: "{{step}} / {{total}}",
allow: "허용",
decline: "허용 안 함",
blockedBadge: "차단됨",
blockedTitle: "이 기기에서 차단됨",
blockedDescription:
"이 플러그인은 호스트에서 실행 중이지만 앱 코드는 이 기기에서 차단되어 있습니다.",
surfaceBlocked: "이 플러그인의 앱 코드는 이 기기에서 차단되어 있습니다.",
allowAction: "이 기기에서 허용",
blockAction: "이 기기에서 차단",
allowedToast: "이 기기에서 {{name}} 실행을 허용했습니다",
blockedToast: "이 기기에서 {{name}} 실행을 차단했습니다",
},
trustedTitle: "플러그인은 신뢰하는 코드입니다",
trustedDescription: "호스트와 앱 안에서 격리 없이 실행됩니다. 신뢰하는 코드만 설치하세요.",
globalTitle: "플러그인 활성화",
@@ -313,6 +407,24 @@ export const pluginSettings = {
backToPlugins: "Voltar para plugins",
},
title: "Plugins",
clientExecution: {
promptTitle: "Permitir plugin neste app?",
promptDescription:
"Este plugin executa código sem isolamento no Paseo e pode acessar seus hosts conectados. Permita apenas plugins confiáveis.",
pluginLabel: "Plugin",
hostLabel: "Host",
queueProgress: "{{step}} de {{total}}",
allow: "Permitir",
decline: "Não permitir",
blockedBadge: "bloqueado",
blockedTitle: "Bloqueado neste dispositivo",
blockedDescription: "Este plugin roda no host, mas o código no app está bloqueado aqui.",
surfaceBlocked: "O código do app para este plugin está bloqueado neste dispositivo.",
allowAction: "Permitir neste dispositivo",
blockAction: "Bloquear neste dispositivo",
allowedToast: "{{name}} permitido neste dispositivo",
blockedToast: "{{name}} bloqueado neste dispositivo",
},
trustedTitle: "Plugins são código confiável",
trustedDescription:
"Eles rodam neste host e dentro do app sem isolamento. Instale apenas código confiável.",
@@ -371,6 +483,25 @@ export const pluginSettings = {
backToPlugins: "Вернуться к плагинам",
},
title: "Плагины",
clientExecution: {
promptTitle: "Разрешить плагин в этом приложении?",
promptDescription:
"Этот плагин выполняет код в Paseo без изоляции и может обращаться к подключённым хостам. Разрешайте только доверенные плагины.",
pluginLabel: "Плагин",
hostLabel: "Хост",
queueProgress: "{{step}} из {{total}}",
allow: "Разрешить",
decline: "Не разрешать",
blockedBadge: "заблокирован",
blockedTitle: "Заблокирован на этом устройстве",
blockedDescription:
"Этот плагин работает на хосте, но его код в приложении здесь заблокирован.",
surfaceBlocked: "Код этого плагина для приложения заблокирован на этом устройстве.",
allowAction: "Разрешить на этом устройстве",
blockAction: "Заблокировать на этом устройстве",
allowedToast: "{{name}} разрешён на этом устройстве",
blockedToast: "{{name}} заблокирован на этом устройстве",
},
trustedTitle: "Плагины — доверенный код",
trustedDescription:
"Они выполняются на хосте и в приложении без изоляции. Устанавливайте только доверенный код.",
@@ -429,6 +560,24 @@ export const pluginSettings = {
backToPlugins: "返回插件",
},
title: "插件",
clientExecution: {
promptTitle: "允许在此应用中运行此插件?",
promptDescription:
"此插件会在 Paseo 中以无隔离方式运行代码,并可访问你已连接的主机。仅允许你信任的插件。",
pluginLabel: "插件",
hostLabel: "主机",
queueProgress: "{{step}} / {{total}}",
allow: "允许",
decline: "不允许",
blockedBadge: "已阻止",
blockedTitle: "已在此设备上阻止",
blockedDescription: "此插件正在主机上运行,但其应用端代码已在此处被阻止。",
surfaceBlocked: "此插件的应用端代码已在此设备上被阻止。",
allowAction: "在此设备上允许",
blockAction: "在此设备上阻止",
allowedToast: "已在此设备上允许 {{name}}",
blockedToast: "已在此设备上阻止 {{name}}",
},
trustedTitle: "插件是受信任的代码",
trustedDescription: "它们会在此主机和应用内运行,且没有隔离。请仅安装你信任的代码。",
globalTitle: "启用插件",
+12 -3
View File
@@ -2822,9 +2822,18 @@ export const ptBR: TranslationResources = {
title: "Geral",
sending: "Envio",
setup: {
label: "Configuração inicial",
description: "Rever aparência, provedores, projetos e pareamento do celular",
action: "Mostrar configuração novamente",
label: "Configuração",
description: "Abrir o guia de boas-vindas novamente",
action: "Mostrar",
},
pluginExecutionBypass: {
label: "Executar plugins sem perguntar",
description:
"Qualquer host conectado pode executar código de plugin no Paseo e acessar seus outros hosts",
confirmTitle: "Executar plugins sem perguntar?",
confirmMessage:
"Qualquer host conectado pode executar código de plugin no Paseo e acessar seus outros hosts conectados. Ative esta opção apenas se você confia em todos os hosts aos quais se conecta.",
confirmAction: "Ativar",
},
browserData: {
title: "Dados do navegador",
+12 -3
View File
@@ -2825,9 +2825,18 @@ export const ru: TranslationResources = {
title: "Основные",
sending: "Отправка",
setup: {
label: "Первоначальная настройка",
description: "Снова пройти оформление, провайдеры, проекты и привязку телефона",
action: "Показать настройку снова",
label: "Настройка",
description: "Открыть приветственное руководство снова",
action: "Показать",
},
pluginExecutionBypass: {
label: "Запускать плагины без запроса",
description:
"Любой подключённый хост может выполнять код плагинов в Paseo и обращаться к другим вашим хостам",
confirmTitle: "Запускать плагины без запроса?",
confirmMessage:
"Любой подключённый хост может выполнять код плагинов в Paseo и обращаться к другим подключённым хостам. Включайте эту настройку, только если доверяете каждому хосту, к которому подключаетесь.",
confirmAction: "Включить",
},
browserData: {
title: "Данные браузера",
+11 -3
View File
@@ -2753,9 +2753,17 @@ export const zhCN: TranslationResources = {
title: "通用",
sending: "发送",
setup: {
label: "首次设置",
description: "重新设置外观、提供方、项目和手机配对",
action: "再次显示设置",
label: "设置",
description: "重新打开欢迎指南",
action: "显示",
},
pluginExecutionBypass: {
label: "无需询问直接运行插件",
description: "任何已连接的主机都可以在 Paseo 内运行插件代码,并访问您的其他主机",
confirmTitle: "无需询问直接运行插件?",
confirmMessage:
"任何已连接的主机都可以在 Paseo 内运行插件代码,并访问您连接的其他主机。仅在信任您连接的每个主机时开启此选项。",
confirmAction: "开启",
},
browserData: {
title: "浏览器数据",
@@ -8,6 +8,7 @@ import { settingsRpc } from "@getpaseo/plugin";
import { syncPluginCatalog } from "./catalog-sync-model";
import { createPluginHosts } from "./hosts";
import { openPluginNotification } from "./notification-open";
import { PluginExecutionApprovals } from "./execution-approval/store";
import { PluginRegistry } from "./registry";
import { pluginSettingsKey } from "./settings/query";
import type { InstalledPlugin } from "./types";
@@ -47,7 +48,14 @@ class SettingsStore {
/** In-memory daemon port; it delivers owned snapshots and stops updates on release. */
class CatalogClient extends DaemonClient {
catalog = catalog("one");
installedPlugins: Array<{
id: string;
path: string;
enabled: boolean;
status: "running" | "disabled" | "failed";
}> = [];
fetches = 0;
listFetches = 0;
releases = 0;
events: Parameters<DaemonClient["observeEvents"]>[0] = [];
private readonly observers = new Set<Observer>();
@@ -61,6 +69,11 @@ class CatalogClient extends DaemonClient {
return this.catalog;
}
override async listPlugins() {
this.listFetches++;
return this.installedPlugins;
}
override observeEvents(events: Parameters<DaemonClient["observeEvents"]>[0]): Observation {
this.events = events;
const snapshot = { requestId: "events", subscriptionId: "catalog" };
@@ -129,6 +142,7 @@ function harness() {
const registry = new PluginRegistry({
localeSource: { getLocale: () => "en", subscribe: () => () => {} },
version: appPackage.version,
isExecutionApproved: null,
createRuntime(installation) {
evaluations++;
return {
@@ -569,3 +583,251 @@ it("keeps catalog loading before server_info arrives so cold-launch plugin taps
expect(h.registry.getCatalogStatus("host")).toBe("ready");
expect(openedRoutes).toEqual(["/h/host/plugin/ci-alerts/surface/alert?param.buildId=77"]);
});
function memoryApprovalStorage(initial?: Record<string, Record<string, "approved" | "declined">>) {
const values = new Map<string, string>();
if (initial) {
values.set("@paseo:plugin-execution-approvals", JSON.stringify(initial));
}
return {
async getItem(key: string) {
return values.get(key) ?? null;
},
async setItem(key: string, value: string) {
values.set(key, value);
},
async removeItem(key: string) {
values.delete(key);
},
};
}
function approvalHarness(initial?: Record<string, Record<string, "approved" | "declined">>) {
const approvals = new PluginExecutionApprovals(memoryApprovalStorage(initial));
const executed: string[] = [];
let disposals = 0;
const registry = new PluginRegistry({
localeSource: { getLocale: () => "en", subscribe: () => () => {} },
version: appPackage.version,
isExecutionApproved: (serverId, pluginId) => approvals.isApproved(serverId, pluginId),
createRuntime(installation) {
executed.push(`${installation.serverId}/${installation.id}`);
return {
hosts: createPluginHosts(
{
getHosts: () => [],
getSnapshot: () => null,
subscribeAll: () => () => {},
subscribeHostList: () => () => {},
},
installation.lifetime.signal,
),
paseo: getPluginClientApi(installation).paseo,
i18n: installation.i18n,
rpc: async () => {
throw new Error("Unexpected runtime RPC");
},
openSettings: () => {
disposals += 1;
},
openScreen() {},
openSurface() {},
composers: () => [],
async playAudio() {},
workspaceLayout: () => {
throw new Error("Layouts are not used here");
},
openPanel() {},
addComposerPill: () => ({ update() {}, remove() {} }),
addHeaderButton: () => ({ update() {}, remove() {} }),
subscribe: () => {
throw new Error("Subscriptions are not used here");
},
};
},
});
const client = new CatalogClient();
cleanups.push(() => {
registry.removeHost("host");
approvals.clearHost("host");
});
return {
approvals,
registry,
client,
executed,
disposals: () => disposals,
sync(options: Partial<Parameters<typeof syncPluginCatalog>[0]> = {}) {
const stop = syncPluginCatalog({
serverId: "host",
client,
audio,
connected: true,
supported: true,
registry,
approvals,
...options,
});
cleanups.push(stop);
return stop;
},
};
}
function probeEntry(id: string, requirements = { paseo: `>=${appPackage.version}` }) {
return {
id,
requirements,
clientBundle: `(function() { return { default: function(plugin) {
return function() { plugin.openSettings("cleanup"); };
} }; })`,
};
}
it("never evaluates unapproved client bundles before explicit user approval", async () => {
const h = approvalHarness();
h.client.catalog = [probeEntry("alpha"), probeEntry("beta")];
h.sync();
await expect.poll(() => h.approvals.getQueueState().current?.pluginId).toBe("alpha");
expect(h.approvals.getQueueState().totalInBatch).toBe(2);
expect(h.executed).toEqual([]);
expect(h.registry.getSnapshot()).toEqual([]);
// Approve alpha -> alpha evaluates immediately without refetching; beta advances to front.
h.approvals.answer(h.approvals.getQueueState().current!.id, "approved");
expect(h.executed).toEqual(["host/alpha"]);
expect(h.registry.getSnapshot().map((plugin) => plugin.id)).toEqual(["alpha"]);
expect(h.client.fetches).toBe(1);
expect(h.approvals.getQueueState().current?.pluginId).toBe("beta");
// Decline beta -> beta never evaluates and queue closes.
h.approvals.answer(h.approvals.getQueueState().current!.id, "declined");
expect(h.executed).toEqual(["host/alpha"]);
expect(h.approvals.getQueueState().current).toBeNull();
});
it("disposes running client plugins immediately when approval is revoked or host trust resets", async () => {
const h = approvalHarness({ host: { alpha: "approved" } });
h.client.catalog = [probeEntry("alpha")];
h.sync();
await expect.poll(() => h.registry.getSnapshot().map((plugin) => plugin.id)).toEqual(["alpha"]);
expect(h.approvals.getQueueState().current).toBeNull();
// Revoking approval disposes alpha immediately.
h.approvals.setDecision("host", "alpha", "declined");
expect(h.registry.getSnapshot()).toEqual([]);
expect(h.disposals()).toBe(1);
// Re-allowing activates alpha again immediately.
h.approvals.setDecision("host", "alpha", "approved");
expect(h.registry.getSnapshot().map((plugin) => plugin.id)).toEqual(["alpha"]);
// Clearing host trust (e.g. host key change) disposes alpha and re-prompts.
h.approvals.clearHost("host");
expect(h.registry.getSnapshot()).toEqual([]);
expect(h.disposals()).toBe(2);
expect(h.approvals.getQueueState().current?.pluginId).toBe("alpha");
});
it("does not prompt for incompatible plugins and drops queued prompts on disconnect", async () => {
const h = approvalHarness();
h.client.catalog = [probeEntry("future-only", { paseo: ">=99.0.0" }), probeEntry("compatible")];
const stop = h.sync();
await expect.poll(() => h.approvals.getQueueState().current?.pluginId).toBe("compatible");
expect(h.approvals.getQueueState().totalInBatch).toBe(1);
expect(h.registry.getEvaluationError("host", "future-only")).toContain(">=99.0.0");
expect(h.executed).toEqual([]);
stop();
expect(h.approvals.getQueueState().current).toBeNull();
});
it("disposes retained client plugins immediately when blocked while the host is offline", async () => {
const h = approvalHarness({ host: { alpha: "approved" } });
h.client.catalog = [probeEntry("alpha")];
const stopConnected = h.sync();
await expect.poll(() => h.registry.getSnapshot().map((plugin) => plugin.id)).toEqual(["alpha"]);
stopConnected();
// Host drops offline: alpha stays retained until blocked.
const stopOffline = h.sync({ connected: false });
expect(h.registry.getSnapshot().map((plugin) => plugin.id)).toEqual(["alpha"]);
h.approvals.setDecision("host", "alpha", "declined");
expect(h.registry.getSnapshot()).toEqual([]);
expect(h.disposals()).toBe(1);
stopOffline();
});
it("clears saved decisions after external uninstall while preserving decisions for disabled plugins", async () => {
const h = approvalHarness({ host: { alpha: "approved", beta: "approved" } });
h.client.catalog = [probeEntry("alpha"), probeEntry("beta")];
h.client.installedPlugins = [
{ id: "alpha", path: "/tmp/alpha", enabled: true, status: "running" },
{ id: "beta", path: "/tmp/beta", enabled: true, status: "running" },
];
h.sync({ pluginManagementSupported: true });
await expect
.poll(() => h.registry.getSnapshot().map((plugin) => plugin.id))
.toEqual(["alpha", "beta"]);
expect(h.client.listFetches).toBe(0);
// beta is disabled (stays in installedPlugins), alpha is uninstalled via CLI/another device.
h.client.catalog = [];
h.client.installedPlugins = [
{ id: "beta", path: "/tmp/beta", enabled: false, status: "disabled" },
];
h.client.update({
type: "status",
payload: { status: "plugin_catalog_changed", pluginId: "alpha" },
});
await expect.poll(() => h.client.listFetches).toBe(1);
expect(h.approvals.getDecision("host", "alpha")).toBeNull();
expect(h.approvals.getDecision("host", "beta")).toBe("approved");
// Reinstalling alpha requires a fresh prompt; re-enabling beta runs without prompting.
h.client.catalog = [probeEntry("alpha"), probeEntry("beta")];
h.client.installedPlugins = [
{ id: "alpha", path: "/tmp/alpha", enabled: true, status: "running" },
{ id: "beta", path: "/tmp/beta", enabled: true, status: "running" },
];
h.client.update({
type: "status",
payload: { status: "plugin_catalog_changed", pluginId: "alpha" },
});
await expect.poll(() => h.approvals.getQueueState().current?.pluginId).toBe("alpha");
expect(h.registry.getSnapshot().map((plugin) => plugin.id)).toEqual(["beta"]);
});
it("activates queued and declined plugins immediately when bypass turns on, and disposes unapproved plugins when turned off", async () => {
const h = approvalHarness({ host: { approved: "approved", declined: "declined" } });
h.client.catalog = [probeEntry("approved"), probeEntry("declined"), probeEntry("pending")];
h.sync();
await expect.poll(() => h.approvals.getQueueState().current?.pluginId).toBe("pending");
expect(h.registry.getSnapshot().map((plugin) => plugin.id)).toEqual(["approved"]);
// Bypass ON: pending prompt dismisses and all compatible client plugins activate immediately.
h.approvals.setBypassEnabled(true);
expect(h.approvals.getQueueState().current).toBeNull();
expect(h.registry.getSnapshot().map((plugin) => plugin.id)).toEqual([
"approved",
"declined",
"pending",
]);
expect(h.client.fetches).toBe(1);
// Bypass OFF: declined and unreviewed plugins dispose immediately, unreviewed prompts again.
h.approvals.setBypassEnabled(false);
expect(h.registry.getSnapshot().map((plugin) => plugin.id)).toEqual(["approved"]);
expect(h.disposals()).toBe(2);
expect(h.approvals.getQueueState().current?.pluginId).toBe("pending");
expect(h.approvals.getQueueState().pendingCount).toBe(1);
});
+72 -8
View File
@@ -1,8 +1,11 @@
import type { AudioEngine } from "@/audio";
import type { DaemonClient } from "@getpaseo/client/internal/daemon-client";
import type { PluginExecutionApprovals } from "./execution-approval/store";
import type { PluginRegistry } from "./registry";
import { pluginSettingsKey, pluginSettingsPrefix } from "./settings/query";
type CatalogPlugin = Awaited<ReturnType<DaemonClient["getPluginCatalog"]>>[number];
interface CatalogSyncInput {
serverId: string;
client: DaemonClient;
@@ -10,10 +13,17 @@ interface CatalogSyncInput {
connected: boolean;
/** `null` while `server_info` has not yet arrived for this host. */
supported: boolean | null;
pluginManagementSupported?: boolean;
registry: Pick<
PluginRegistry,
"installCatalog" | "getSnapshot" | "removeHost" | "setCatalogStatus"
>;
> &
Partial<Pick<PluginRegistry, "isCompatible" | "pruneDisallowed">>;
approvals?: Pick<
PluginExecutionApprovals,
"load" | "reconcileHostPlugins" | "clearHostPending" | "subscribe"
> &
Partial<Pick<PluginExecutionApprovals, "getDecidedPluginIds" | "pruneHostPlugins">>;
onCatalogChanged?: () => void;
}
@@ -23,7 +33,9 @@ export function syncPluginCatalog({
audio,
connected,
supported,
pluginManagementSupported = false,
registry,
approvals,
onCatalogChanged,
}: CatalogSyncInput): () => void {
if (supported === null) {
@@ -32,27 +44,74 @@ export function syncPluginCatalog({
return () => {};
}
if (!supported || !audio) {
approvals?.clearHostPending(serverId);
registry.removeHost(serverId);
registry.setCatalogStatus(serverId, "ready");
return () => {};
}
// A dropped socket reconnects on the same client, so installations keep rendering offline.
if (!connected) return () => {};
// Keep enforcing local block decisions immediately while disconnected.
if (!connected) {
approvals?.clearHostPending(serverId);
return (
approvals?.subscribe(() => {
registry.pruneDisallowed?.(serverId);
}) ?? (() => {})
);
}
registry.setCatalogStatus(serverId, "loading");
const installationOptions = { client, audio };
let cancelled = false;
let latestCatalog: CatalogPlugin[] | null = null;
let applying = false;
let refreshQueue = Promise.resolve();
function applyCatalog(replacePluginId?: string) {
if (cancelled || !latestCatalog || applying) return;
applying = true;
try {
if (approvals) {
const promptableIds = latestCatalog
.filter(
(entry) => Boolean(entry.clientBundle) && (registry.isCompatible?.(entry) ?? true),
)
.map((entry) => entry.id);
approvals.reconcileHostPlugins(serverId, promptableIds);
}
registry.installCatalog(serverId, latestCatalog, { ...installationOptions, replacePluginId });
} finally {
applying = false;
}
}
function refresh(replacePluginId?: string) {
refreshQueue = refreshQueue.then(() => {
if (cancelled) return undefined;
registry.setCatalogStatus(serverId, "loading");
return client
.getPluginCatalog()
.then((catalog) => {
if (!cancelled) {
registry.installCatalog(serverId, catalog, { ...installationOptions, replacePluginId });
registry.setCatalogStatus(serverId, "ready");
return Promise.all([client.getPluginCatalog(), approvals?.load()])
.then(async ([catalog]) => {
if (cancelled) return undefined;
if (
approvals?.getDecidedPluginIds &&
approvals.pruneHostPlugins &&
pluginManagementSupported
) {
const catalogIds = new Set(catalog.map((entry) => entry.id));
const missingDecided = approvals
.getDecidedPluginIds(serverId)
.some((id) => !catalogIds.has(id));
if (missingDecided) {
const installed = await client.listPlugins().catch(() => null);
if (cancelled) return undefined;
if (installed !== null) {
approvals.pruneHostPlugins(
serverId,
installed.map((item) => item.id),
);
}
}
}
latestCatalog = catalog;
applyCatalog(replacePluginId);
registry.setCatalogStatus(serverId, "ready");
return undefined;
})
.catch((error) => {
@@ -65,6 +124,9 @@ export function syncPluginCatalog({
});
return refreshQueue;
}
const unsubscribeApprovals = approvals?.subscribe(() => {
applyCatalog();
});
const observation = client.observeEvents([
"status.plugin_catalog_changed",
"status.plugin_settings_changed",
@@ -104,6 +166,8 @@ export function syncPluginCatalog({
});
return () => {
cancelled = true;
unsubscribeApprovals?.();
approvals?.clearHostPending(serverId);
void observation
.release()
.catch((error) => console.warn("[Plugins] Failed to release catalog", error));
+13 -3
View File
@@ -2,8 +2,9 @@ import { useVoiceAudioEngineOptional } from "@/contexts/voice-context";
import { useEffect } from "react";
import { useQueryClient } from "@tanstack/react-query";
import type { DaemonClient } from "@getpaseo/client/internal/daemon-client";
import { useHostFeatureAvailability } from "@/runtime/host-features";
import { useHostFeature, useHostFeatureAvailability } from "@/runtime/host-features";
import { useHostRuntimeIsConnected } from "@/runtime/host-runtime";
import { pluginExecutionApprovals } from "./execution-approval";
import { pluginListQueryKey } from "./plugin-list";
import { pluginRegistry } from "./registry";
import { syncPluginCatalog } from "./catalog-sync-model";
@@ -18,6 +19,7 @@ export function PluginCatalogSync({
const audio = useVoiceAudioEngineOptional();
const connected = useHostRuntimeIsConnected(serverId);
const supported = useHostFeatureAvailability(serverId, "plugins");
const pluginManagementSupported = useHostFeature(serverId, "pluginManagement");
const queryClient = useQueryClient();
useEffect(
@@ -28,14 +30,22 @@ export function PluginCatalogSync({
audio,
connected,
supported,
pluginManagementSupported,
registry: pluginRegistry,
approvals: pluginExecutionApprovals,
onCatalogChanged: () => {
void queryClient.invalidateQueries({ queryKey: pluginListQueryKey(serverId) });
},
}),
[audio, client, connected, queryClient, serverId, supported],
[audio, client, connected, pluginManagementSupported, queryClient, serverId, supported],
);
useEffect(() => () => pluginRegistry.removeHost(serverId), [serverId]);
useEffect(
() => () => {
pluginExecutionApprovals.clearHostPending(serverId);
pluginRegistry.removeHost(serverId);
},
[serverId],
);
return null;
}
@@ -0,0 +1,55 @@
import AsyncStorage from "@react-native-async-storage/async-storage";
import { useCallback, useEffect, useSyncExternalStore } from "react";
import type { PluginExecutionDecision } from "./storage";
import {
PluginExecutionApprovals,
type PluginExecutionApprovalQueueState,
type PluginExecutionApprovalRequest,
} from "./store";
export type {
PluginExecutionApprovalQueueState,
PluginExecutionApprovalRequest,
PluginExecutionDecision,
};
export { PluginExecutionApprovals };
export const pluginExecutionApprovals = new PluginExecutionApprovals(AsyncStorage);
export function usePluginExecutionApprovalQueue(): PluginExecutionApprovalQueueState {
return useSyncExternalStore(
pluginExecutionApprovals.subscribe,
pluginExecutionApprovals.getQueueState,
pluginExecutionApprovals.getQueueState,
);
}
/**
* Returns whether per-plugin client execution prompts are bypassed on this device,
* or `null` while storage hydration is still in flight.
*/
export function usePluginExecutionApprovalBypass(): boolean | null {
useEffect(() => {
void pluginExecutionApprovals.load();
}, []);
return useSyncExternalStore(
pluginExecutionApprovals.subscribe,
pluginExecutionApprovals.getBypassState,
pluginExecutionApprovals.getBypassState,
);
}
/**
* Returns the active per-plugin decision enforced on this device, or `null` when
* unreviewed or when per-plugin approval prompts are bypassed on this device.
*/
export function usePluginExecutionDecision(
serverId: string,
pluginId: string,
): PluginExecutionDecision | null {
const read = useCallback(
() => pluginExecutionApprovals.getEffectiveDecision(serverId, pluginId),
[pluginId, serverId],
);
return useSyncExternalStore(pluginExecutionApprovals.subscribe, read, read);
}
@@ -0,0 +1,180 @@
import { useCallback, useMemo, useState } from "react";
import { Text, View } from "react-native";
import { StyleSheet } from "react-native-unistyles";
import { useTranslation } from "react-i18next";
import { AdaptiveModalSheet, type SheetHeader } from "@/components/adaptive-modal-sheet";
import { Button } from "@/components/ui/button";
import { usePluginDisplayName } from "@/plugins/plugin-list";
import { useHosts } from "@/runtime/host-runtime";
import { settingsStyles } from "@/styles/settings";
import {
pluginExecutionApprovals,
usePluginExecutionApprovalQueue,
type PluginExecutionApprovalQueueState,
} from "./index";
/**
* Shows the sequential client plugin execution prompt queue. Mount once at the app root.
*
* Keeps one `<AdaptiveModalSheet>` mounted across queued items so advancing from one plugin to
* the next swaps details in place without flickering the backdrop or dismissing/re-presenting
* native bottom sheets.
*/
export function PluginExecutionApprovalSheet() {
const { t } = useTranslation();
const queue = usePluginExecutionApprovalQueue();
const hosts = useHosts();
// Retain the last visible prompt during the sheet's exit animation so closing never blanks mid-fade.
const [retained, setRetained] = useState<PluginExecutionApprovalQueueState | null>(null);
if (queue.current !== null && retained !== queue) {
setRetained(queue);
}
const displayed = queue.current !== null ? queue : retained;
const request = displayed?.current ?? null;
const visible = queue.current !== null;
const displayName = usePluginDisplayName(
request ? { serverId: request.serverId, pluginId: request.pluginId } : null,
);
const hostLabel = request
? (hosts.find((host) => host.serverId === request.serverId)?.label ?? request.serverId)
: "";
const requestId = request?.id ?? null;
const allow = useCallback(() => {
if (requestId !== null) {
pluginExecutionApprovals.answer(requestId, "approved");
}
}, [requestId]);
const decline = useCallback(() => {
if (requestId !== null) {
pluginExecutionApprovals.answer(requestId, "declined");
}
}, [requestId]);
const dismiss = useCallback(() => {
pluginExecutionApprovals.dismissQueue();
}, []);
const handleDismiss = useCallback(() => {
setRetained(null);
}, []);
const progressText =
displayed && displayed.totalInBatch > 1
? t("settings.plugins.clientExecution.queueProgress", {
step: displayed.step,
total: displayed.totalInBatch,
})
: null;
const header = useMemo<SheetHeader>(
() => ({
title: t("settings.plugins.clientExecution.promptTitle"),
actions: progressText ? (
<Text style={styles.progress} testID="plugin-execution-approval-progress">
{progressText}
</Text>
) : undefined,
}),
[progressText, t],
);
return (
<AdaptiveModalSheet
header={header}
visible={visible}
onClose={dismiss}
onDismiss={handleDismiss}
testID="plugin-execution-approval"
>
{request ? (
<>
<Text style={styles.confirmText}>
{t("settings.plugins.clientExecution.promptDescription")}
</Text>
<View style={settingsStyles.card}>
<DetailRow
label={t("settings.plugins.clientExecution.pluginLabel")}
value={formatPluginIdentity(displayName, request.pluginId)}
testID="plugin-execution-approval-plugin"
/>
<DetailRow
label={t("settings.plugins.clientExecution.hostLabel")}
value={formatHostIdentity(hostLabel, request.serverId)}
testID="plugin-execution-approval-host"
showBorder
/>
</View>
<View style={styles.confirmActions}>
<Button
variant="secondary"
style={FLEX_1_STYLE}
onPress={decline}
testID="plugin-execution-approval-decline"
>
{t("settings.plugins.clientExecution.decline")}
</Button>
<Button
variant="default"
style={FLEX_1_STYLE}
onPress={allow}
testID="plugin-execution-approval-allow"
>
{t("settings.plugins.clientExecution.allow")}
</Button>
</View>
</>
) : null}
</AdaptiveModalSheet>
);
}
function formatPluginIdentity(displayName: string | undefined, pluginId: string): string {
if (!displayName || displayName === pluginId) return pluginId;
return `${displayName} (${pluginId})`;
}
function formatHostIdentity(label: string, serverId: string): string {
return label === serverId ? serverId : `${label} (${serverId})`;
}
function DetailRow({
label,
value,
showBorder = false,
testID,
}: {
label: string;
value: string;
showBorder?: boolean;
testID?: string;
}) {
return (
<View style={[settingsStyles.row, showBorder && settingsStyles.rowBorder]}>
<View style={settingsStyles.rowContent}>
<Text style={settingsStyles.rowTitle}>{label}</Text>
<Text style={settingsStyles.rowHint} numberOfLines={1} selectable testID={testID}>
{value}
</Text>
</View>
</View>
);
}
const styles = StyleSheet.create((theme) => ({
progress: {
color: theme.colors.foregroundMuted,
fontSize: theme.fontSize.sm,
},
confirmText: {
color: theme.colors.foregroundMuted,
fontSize: theme.fontSize.base,
},
confirmActions: {
flexDirection: "row",
alignItems: "center",
gap: theme.spacing[2],
marginTop: theme.spacing[4],
},
}));
const FLEX_1_STYLE = { flex: 1 };
@@ -0,0 +1,64 @@
import { z } from "zod";
import { readValidatedJson, type ValidatedStorage } from "@/storage/validated-storage";
export const PLUGIN_EXECUTION_APPROVALS_STORAGE_KEY = "@paseo:plugin-execution-approvals";
export const PLUGIN_EXECUTION_BYPASS_STORAGE_KEY = "@paseo:plugin-execution-approval-bypass";
export const PluginExecutionDecisionSchema = z.enum(["approved", "declined"]);
export type PluginExecutionDecision = z.infer<typeof PluginExecutionDecisionSchema>;
const StoredPluginExecutionApprovalsSchema = z.record(
z.string().min(1),
z.record(z.string().min(1), PluginExecutionDecisionSchema),
);
const StoredPluginExecutionBypassSchema = z.boolean();
export type StoredPluginExecutionApprovals = z.infer<typeof StoredPluginExecutionApprovalsSchema>;
export interface PluginExecutionApprovalStorage extends ValidatedStorage {
setItem(key: string, value: string): Promise<void>;
}
export async function loadPluginExecutionApprovals(
storage: PluginExecutionApprovalStorage,
): Promise<StoredPluginExecutionApprovals> {
const stored = await readValidatedJson(
storage,
PLUGIN_EXECUTION_APPROVALS_STORAGE_KEY,
StoredPluginExecutionApprovalsSchema,
);
return stored ?? {};
}
export async function savePluginExecutionApprovals(
storage: PluginExecutionApprovalStorage,
approvals: StoredPluginExecutionApprovals,
): Promise<void> {
if (Object.keys(approvals).length === 0) {
await storage.removeItem(PLUGIN_EXECUTION_APPROVALS_STORAGE_KEY);
return;
}
await storage.setItem(PLUGIN_EXECUTION_APPROVALS_STORAGE_KEY, JSON.stringify(approvals));
}
export async function loadPluginExecutionBypass(
storage: PluginExecutionApprovalStorage,
): Promise<boolean> {
const stored = await readValidatedJson(
storage,
PLUGIN_EXECUTION_BYPASS_STORAGE_KEY,
StoredPluginExecutionBypassSchema,
);
return stored ?? false;
}
export async function savePluginExecutionBypass(
storage: PluginExecutionApprovalStorage,
bypass: boolean,
): Promise<void> {
if (!bypass) {
await storage.removeItem(PLUGIN_EXECUTION_BYPASS_STORAGE_KEY);
return;
}
await storage.setItem(PLUGIN_EXECUTION_BYPASS_STORAGE_KEY, JSON.stringify(true));
}
@@ -0,0 +1,405 @@
import { describe, expect, it } from "vitest";
import { PluginExecutionApprovals } from "./store";
import type { PluginExecutionApprovalStorage } from "./storage";
class MemoryStorage implements PluginExecutionApprovalStorage {
readonly values = new Map<string, string>();
writes = 0;
async getItem(key: string): Promise<string | null> {
return this.values.get(key) ?? null;
}
async setItem(key: string, value: string): Promise<void> {
this.writes += 1;
this.values.set(key, value);
}
async removeItem(key: string): Promise<void> {
this.values.delete(key);
}
}
describe("PluginExecutionApprovals", () => {
it("fails closed before storage hydrates and loads persisted decisions once hydrated", async () => {
const storage = new MemoryStorage();
const first = new PluginExecutionApprovals(storage);
await first.load();
first.reconcileHostPlugins("host-a", ["alpha", "beta"]);
first.answer(first.getQueueState().current!.id, "approved");
first.answer(first.getQueueState().current!.id, "declined");
await first.flushPersistence();
const reloaded = new PluginExecutionApprovals(storage);
expect(reloaded.isHydrated()).toBe(false);
expect(reloaded.isApproved("host-a", "alpha")).toBe(false);
await reloaded.load();
expect(reloaded.isHydrated()).toBe(true);
expect(reloaded.isApproved("host-a", "alpha")).toBe(true);
expect(reloaded.getDecision("host-a", "alpha")).toBe("approved");
expect(reloaded.getDecision("host-a", "beta")).toBe("declined");
expect(reloaded.isApproved("host-b", "alpha")).toBe(false);
// Reconciling already-decided plugins does not enqueue any prompts.
reloaded.reconcileHostPlugins("host-a", ["alpha", "beta"]);
expect(reloaded.getQueueState().current).toBeNull();
});
it("queues stacked plugins sequentially, tracks batch progress, and ignores stale request IDs", async () => {
const storage = new MemoryStorage();
const approvals = new PluginExecutionApprovals(storage);
await approvals.load();
approvals.reconcileHostPlugins("host-a", ["alpha", "beta", "gamma"]);
const firstState = approvals.getQueueState();
expect(firstState.current).toMatchObject({ serverId: "host-a", pluginId: "alpha" });
expect(firstState.step).toBe(1);
expect(firstState.totalInBatch).toBe(3);
expect(firstState.pendingCount).toBe(3);
// Stable snapshot reference when nothing changed.
expect(approvals.getQueueState()).toBe(firstState);
const firstId = firstState.current!.id;
// Duplicate reconciliation does not duplicate queued items.
approvals.reconcileHostPlugins("host-a", ["alpha", "beta", "gamma"]);
expect(approvals.getQueueState().pendingCount).toBe(3);
// Answer the first item.
approvals.answer(firstId, "approved");
const secondState = approvals.getQueueState();
expect(secondState.current).toMatchObject({ serverId: "host-a", pluginId: "beta" });
expect(secondState.step).toBe(2);
expect(secondState.totalInBatch).toBe(3);
expect(approvals.isApproved("host-a", "alpha")).toBe(true);
expect(approvals.isApproved("host-a", "beta")).toBe(false);
// Re-answering the stale first request ID must NOT answer beta!
approvals.answer(firstId, "approved");
expect(approvals.getQueueState().current?.pluginId).toBe("beta");
expect(approvals.getDecision("host-a", "beta")).toBeNull();
// Decline beta, then approve gamma.
approvals.answer(secondState.current!.id, "declined");
expect(approvals.getDecision("host-a", "beta")).toBe("declined");
expect(approvals.getQueueState()).toMatchObject({
current: { serverId: "host-a", pluginId: "gamma" },
step: 3,
totalInBatch: 3,
pendingCount: 1,
});
approvals.answer(approvals.getQueueState().current!.id, "approved");
expect(approvals.getQueueState()).toEqual({
current: null,
step: 0,
totalInBatch: 0,
pendingCount: 0,
});
});
it("isolates approvals per host and supports multi-host queued prompts", async () => {
const storage = new MemoryStorage();
const approvals = new PluginExecutionApprovals(storage);
await approvals.load();
approvals.reconcileHostPlugins("host-a", ["shared-plugin"]);
approvals.reconcileHostPlugins("host-b", ["shared-plugin"]);
expect(approvals.getQueueState()).toMatchObject({
current: { serverId: "host-a", pluginId: "shared-plugin" },
step: 1,
totalInBatch: 2,
});
approvals.answer(approvals.getQueueState().current!.id, "approved");
expect(approvals.isApproved("host-a", "shared-plugin")).toBe(true);
expect(approvals.isApproved("host-b", "shared-plugin")).toBe(false);
expect(approvals.getQueueState()).toMatchObject({
current: { serverId: "host-b", pluginId: "shared-plugin" },
step: 2,
totalInBatch: 2,
});
});
it("dismisses the active queue by declining remaining prompts cleanly", async () => {
const storage = new MemoryStorage();
const approvals = new PluginExecutionApprovals(storage);
await approvals.load();
approvals.reconcileHostPlugins("host-a", ["alpha", "beta", "gamma"]);
approvals.answer(approvals.getQueueState().current!.id, "approved");
approvals.dismissQueue();
expect(approvals.getQueueState()).toEqual({
current: null,
step: 0,
totalInBatch: 0,
pendingCount: 0,
});
expect(approvals.getDecision("host-a", "alpha")).toBe("approved");
expect(approvals.getDecision("host-a", "beta")).toBe("declined");
expect(approvals.getDecision("host-a", "gamma")).toBe("declined");
});
it("prunes stale queued prompts when plugins disappear or a host disconnects", async () => {
const storage = new MemoryStorage();
const approvals = new PluginExecutionApprovals(storage);
await approvals.load();
approvals.reconcileHostPlugins("host-a", ["alpha", "beta"]);
approvals.reconcileHostPlugins("host-b", ["gamma"]);
expect(approvals.getQueueState().totalInBatch).toBe(3);
// beta removed from host-a while alpha is showing.
approvals.reconcileHostPlugins("host-a", ["alpha"]);
expect(approvals.getQueueState()).toMatchObject({
current: { serverId: "host-a", pluginId: "alpha" },
step: 1,
totalInBatch: 2,
pendingCount: 2,
});
// host-a disconnects: its pending prompts are dropped, host-b's stays.
approvals.clearHostPending("host-a");
expect(approvals.getQueueState()).toMatchObject({
current: { serverId: "host-b", pluginId: "gamma" },
step: 1,
totalInBatch: 1,
pendingCount: 1,
});
});
it("clears persisted decisions and pending prompts on host trust reset or plugin removal", async () => {
const storage = new MemoryStorage();
const approvals = new PluginExecutionApprovals(storage);
await approvals.load();
approvals.setDecision("host-a", "alpha", "approved");
approvals.setDecision("host-a", "beta", "declined");
approvals.setDecision("host-b", "alpha", "approved");
approvals.reconcileHostPlugins("host-a", ["gamma"]);
approvals.clearPlugin("host-a", "beta");
expect(approvals.getDecision("host-a", "beta")).toBeNull();
expect(approvals.getDecision("host-a", "alpha")).toBe("approved");
approvals.clearHost("host-a");
expect(approvals.getDecision("host-a", "alpha")).toBeNull();
expect(approvals.getQueueState().current).toBeNull();
expect(approvals.getDecision("host-b", "alpha")).toBe("approved");
await approvals.flushPersistence();
const reloaded = new PluginExecutionApprovals(storage);
await reloaded.load();
expect(reloaded.getDecision("host-a", "alpha")).toBeNull();
expect(reloaded.getDecision("host-b", "alpha")).toBe("approved");
});
it("fails closed and clears corrupt persisted data", async () => {
const storage = new MemoryStorage();
storage.values.set("@paseo:plugin-execution-approvals", "{not valid json");
const approvals = new PluginExecutionApprovals(storage);
await approvals.load();
expect(approvals.isHydrated()).toBe(true);
expect(approvals.isApproved("host-a", "alpha")).toBe(false);
expect(storage.values.has("@paseo:plugin-execution-approvals")).toBe(false);
});
it("preserves mutations made while storage hydration is still in flight", async () => {
const deferred = Promise.withResolvers<string | null>();
const storage: PluginExecutionApprovalStorage = {
getItem: () => deferred.promise,
setItem: async () => undefined,
removeItem: async () => undefined,
};
const approvals = new PluginExecutionApprovals(storage);
const loading = approvals.load();
approvals.setDecision("host-a", "alpha", "declined");
approvals.clearHost("host-b");
deferred.resolve(
JSON.stringify({
"host-a": { alpha: "approved", gamma: "approved" },
"host-b": { beta: "approved" },
}),
);
await loading;
expect(approvals.getDecision("host-a", "alpha")).toBe("declined");
expect(approvals.getDecision("host-a", "gamma")).toBe("approved");
expect(approvals.getDecision("host-b", "beta")).toBeNull();
});
it("prunes uninstalled plugins while keeping disabled plugins that remain listed", async () => {
const storage = new MemoryStorage();
const approvals = new PluginExecutionApprovals(storage);
await approvals.load();
approvals.setDecision("host-a", "alpha", "approved");
approvals.setDecision("host-a", "disabled-plugin", "declined");
approvals.setDecision("host-b", "alpha", "approved");
expect(approvals.getDecidedPluginIds("host-a").sort()).toEqual(["alpha", "disabled-plugin"]);
// alpha was uninstalled; disabled-plugin is still listed on the host.
approvals.pruneHostPlugins("host-a", ["disabled-plugin"]);
expect(approvals.getDecision("host-a", "alpha")).toBeNull();
expect(approvals.getDecision("host-a", "disabled-plugin")).toBe("declined");
expect(approvals.getDecision("host-b", "alpha")).toBe("approved");
await approvals.flushPersistence();
const reloaded = new PluginExecutionApprovals(storage);
await reloaded.load();
expect(reloaded.getDecision("host-a", "alpha")).toBeNull();
expect(reloaded.getDecision("host-a", "disabled-plugin")).toBe("declined");
});
it("supports bypassing approval prompts, dismisses pending prompts without declining them, and restores enforcement when turned off", async () => {
const storage = new MemoryStorage();
const approvals = new PluginExecutionApprovals(storage);
expect(approvals.getBypassState()).toBeNull();
expect(approvals.isBypassEnabled()).toBe(false);
await approvals.load();
expect(approvals.getBypassState()).toBe(false);
expect(approvals.isBypassEnabled()).toBe(false);
approvals.setDecision("host-a", "approved-plugin", "approved");
approvals.setDecision("host-a", "declined-plugin", "declined");
approvals.reconcileHostPlugins("host-a", [
"approved-plugin",
"declined-plugin",
"pending-plugin",
]);
expect(approvals.getQueueState().current?.pluginId).toBe("pending-plugin");
// Enabling bypass dismisses the pending queue cleanly without marking pending plugins declined.
approvals.setBypassEnabled(true);
expect(approvals.getBypassState()).toBe(true);
expect(approvals.isBypassEnabled()).toBe(true);
expect(approvals.getQueueState().current).toBeNull();
expect(approvals.getDecision("host-a", "pending-plugin")).toBeNull();
expect(approvals.getDecision("host-a", "declined-plugin")).toBe("declined");
expect(approvals.getEffectiveDecision("host-a", "declined-plugin")).toBeNull();
expect(approvals.getEffectiveDecision("host-a", "approved-plugin")).toBeNull();
expect(approvals.isApproved("host-a", "approved-plugin")).toBe(true);
expect(approvals.isApproved("host-a", "declined-plugin")).toBe(true);
expect(approvals.isApproved("host-a", "pending-plugin")).toBe(true);
// Reconciling new unreviewed plugins while bypass is on does not enqueue prompts.
approvals.reconcileHostPlugins("host-a", ["approved-plugin", "pending-plugin", "new-plugin"]);
expect(approvals.getQueueState().current).toBeNull();
// Bypass persists across reloads and fails closed until storage hydrates.
await approvals.flushPersistence();
const reloaded = new PluginExecutionApprovals(storage);
expect(reloaded.getBypassState()).toBeNull();
expect(reloaded.isApproved("host-a", "pending-plugin")).toBe(false);
await reloaded.load();
expect(reloaded.getBypassState()).toBe(true);
expect(reloaded.isBypassEnabled()).toBe(true);
expect(reloaded.isApproved("host-a", "pending-plugin")).toBe(true);
expect(reloaded.isApproved("host-a", "declined-plugin")).toBe(true);
// Turning bypass off restores per-host, per-plugin enforcement and preserves saved decisions.
reloaded.setBypassEnabled(false);
expect(reloaded.getBypassState()).toBe(false);
expect(reloaded.getEffectiveDecision("host-a", "approved-plugin")).toBe("approved");
expect(reloaded.getEffectiveDecision("host-a", "declined-plugin")).toBe("declined");
expect(reloaded.isApproved("host-a", "approved-plugin")).toBe(true);
expect(reloaded.isApproved("host-a", "declined-plugin")).toBe(false);
expect(reloaded.isApproved("host-a", "pending-plugin")).toBe(false);
reloaded.reconcileHostPlugins("host-a", [
"approved-plugin",
"declined-plugin",
"pending-plugin",
]);
expect(reloaded.getQueueState().current?.pluginId).toBe("pending-plugin");
await reloaded.flushPersistence();
const reloadedOff = new PluginExecutionApprovals(storage);
await reloadedOff.load();
expect(reloadedOff.isBypassEnabled()).toBe(false);
expect(reloadedOff.isApproved("host-a", "approved-plugin")).toBe(true);
expect(reloadedOff.isApproved("host-a", "pending-plugin")).toBe(false);
});
it("fails closed on corrupt bypass storage and preserves pre-hydration bypass edits", async () => {
const storage = new MemoryStorage();
storage.values.set(
"@paseo:plugin-execution-approvals",
JSON.stringify({ "host-a": { alpha: "approved" } }),
);
storage.values.set("@paseo:plugin-execution-approval-bypass", "{bad json");
const approvals = new PluginExecutionApprovals(storage);
await approvals.load();
expect(approvals.isBypassEnabled()).toBe(false);
expect(approvals.isApproved("host-a", "alpha")).toBe(true);
expect(storage.values.has("@paseo:plugin-execution-approval-bypass")).toBe(false);
// Pre-hydration toggle wins over older stored value.
const deferred = Promise.withResolvers<string | null>();
const asyncStorage: PluginExecutionApprovalStorage = {
getItem: async (key) =>
key === "@paseo:plugin-execution-approval-bypass" ? deferred.promise : null,
setItem: async () => undefined,
removeItem: async () => undefined,
};
const racing = new PluginExecutionApprovals(asyncStorage);
const loading = racing.load();
racing.setBypassEnabled(true);
expect(racing.getBypassState()).toBe(true);
expect(racing.isApproved("host-a", "beta")).toBe(true);
deferred.resolve(JSON.stringify(false));
await loading;
expect(racing.isBypassEnabled()).toBe(true);
expect(racing.isApproved("host-a", "beta")).toBe(true);
});
it("rolls back turning bypass on and surfaces errors when bypass persistence fails", async () => {
let failSet = true;
let failRemove = true;
const values = new Map<string, string>();
const flakyStorage: PluginExecutionApprovalStorage = {
getItem: async (key) => values.get(key) ?? null,
setItem: async (key, value) => {
if (failSet) throw new Error("disk full");
values.set(key, value);
},
removeItem: async (key) => {
if (failRemove) throw new Error("io error");
values.delete(key);
},
};
const approvals = new PluginExecutionApprovals(flakyStorage);
await approvals.load();
// Turning ON rolls back to fail-closed when persistence fails.
await expect(approvals.setBypassEnabled(true)).rejects.toThrow("disk full");
expect(approvals.isBypassEnabled()).toBe(false);
expect(approvals.isApproved("host-a", "alpha")).toBe(false);
// Turning ON succeeds once storage recovers.
failSet = false;
await expect(approvals.setBypassEnabled(true)).resolves.toBeUndefined();
expect(approvals.isBypassEnabled()).toBe(true);
expect(values.get("@paseo:plugin-execution-approval-bypass")).toBe("true");
// Turning OFF enforces fail-closed in memory even when removeItem fails, and surfaces the error for retry.
await expect(approvals.setBypassEnabled(false)).rejects.toThrow("io error");
expect(approvals.isBypassEnabled()).toBe(false);
expect(approvals.isApproved("host-a", "alpha")).toBe(false);
// Retrying OFF succeeds and clears persisted bypass once storage recovers.
failRemove = false;
await expect(approvals.setBypassEnabled(false)).resolves.toBeUndefined();
expect(values.has("@paseo:plugin-execution-approval-bypass")).toBe(false);
});
});
@@ -0,0 +1,437 @@
import {
loadPluginExecutionApprovals,
loadPluginExecutionBypass,
savePluginExecutionApprovals,
savePluginExecutionBypass,
type PluginExecutionApprovalStorage,
type PluginExecutionDecision,
type StoredPluginExecutionApprovals,
} from "./storage";
export interface PluginExecutionApprovalRequest {
/** Monotonic ID so an answer for an older prompt can never answer a newer one. */
id: number;
serverId: string;
pluginId: string;
}
export interface PluginExecutionApprovalQueueState {
/** The prompt currently at the front of the queue, or null when idle. */
current: PluginExecutionApprovalRequest | null;
/** Number of prompts waiting in the queue, including `current`. */
pendingCount: number;
/** 1-based position in the active review batch, or 0 when idle. */
step: number;
/** Total prompts in the active review batch, or 0 when idle. */
totalInBatch: number;
}
const IDLE_QUEUE_STATE: PluginExecutionApprovalQueueState = {
current: null,
pendingCount: 0,
step: 0,
totalInBatch: 0,
};
function pluginKey(serverId: string, pluginId: string): string {
return `${serverId}\0${pluginId}`;
}
/**
* Owns per-host client plugin execution consent and the sequential review queue.
*
* Decisions persist across reloads and reconnects keyed by `(serverId, pluginId)`.
* Unreviewed and unhydrated entries fail closed so no client bundle can execute
* before explicit user approval.
*/
export class PluginExecutionApprovals {
private readonly decisions = new Map<string, Map<string, PluginExecutionDecision>>();
private readonly queue: PluginExecutionApprovalRequest[] = [];
private readonly listeners = new Set<() => void>();
private queueState: PluginExecutionApprovalQueueState = IDLE_QUEUE_STATE;
private nextRequestId = 1;
private completedInBatch = 0;
private hydrated = false;
private bypass = false;
private loadPromise: Promise<void> | null = null;
/** Local edits recorded before storage hydration finishes win over older stored entries. */
private readonly preHydrationOverrides = new Map<string, PluginExecutionDecision | null>();
private readonly preHydrationClearedHosts = new Set<string>();
private preHydrationBypass: boolean | null = null;
private persistChain: Promise<void> = Promise.resolve();
private persistPending = false;
private bypassPersistChain: Promise<void> = Promise.resolve();
private bypassWriteGeneration = 0;
private bypassPersistDirty = false;
constructor(private readonly storage: PluginExecutionApprovalStorage) {}
subscribe = (listener: () => void): (() => void) => {
this.listeners.add(listener);
return () => {
this.listeners.delete(listener);
};
};
isHydrated(): boolean {
return this.hydrated;
}
load(): Promise<void> {
if (this.hydrated) return Promise.resolve();
this.loadPromise ??= this.hydrate();
return this.loadPromise;
}
getQueueState = (): PluginExecutionApprovalQueueState => this.queueState;
isBypassEnabled(): boolean {
return this.bypass;
}
/** Returns `null` before storage hydrates unless modified locally so switches avoid flashing. */
getBypassState = (): boolean | null =>
!this.hydrated && this.preHydrationBypass === null ? null : this.bypass;
setBypassEnabled(enabled: boolean): Promise<void> {
const previous = this.bypass;
const recordedPreHydration = !this.hydrated && this.preHydrationBypass !== enabled;
if (!this.hydrated) {
this.preHydrationBypass = enabled;
}
this.bypass = enabled;
const removedPending = enabled ? this.pruneQueue(() => true) : false;
if (
previous === enabled &&
!removedPending &&
!recordedPreHydration &&
!this.bypassPersistDirty
) {
return Promise.resolve();
}
this.publish();
const generation = ++this.bypassWriteGeneration;
const run = this.bypassPersistChain.then(async () => {
if (generation !== this.bypassWriteGeneration) return undefined;
await savePluginExecutionBypass(this.storage, enabled);
if (generation === this.bypassWriteGeneration) {
this.bypassPersistDirty = false;
}
return undefined;
});
this.bypassPersistChain = run.catch(() => undefined);
return run.catch((error) => {
console.warn("[Plugins] Failed to save client execution approval bypass", error);
if (generation === this.bypassWriteGeneration) {
if (enabled) {
// Enabling bypass failed to persist; roll back to fail-closed.
this.bypass = false;
if (!this.hydrated) {
this.preHydrationBypass = false;
}
this.bypassPersistDirty = false;
this.publish();
} else {
// Disabling bypass stays enforced in memory; mark dirty so a retry persists cleanly.
this.bypassPersistDirty = true;
}
}
throw error;
});
}
getDecision(serverId: string, pluginId: string): PluginExecutionDecision | null {
return this.decisions.get(serverId)?.get(pluginId) ?? null;
}
getEffectiveDecision(serverId: string, pluginId: string): PluginExecutionDecision | null {
return this.bypass ? null : this.getDecision(serverId, pluginId);
}
getDecidedPluginIds(serverId: string): string[] {
const hostMap = this.decisions.get(serverId);
return hostMap ? [...hostMap.keys()] : [];
}
isApproved(serverId: string, pluginId: string): boolean {
if (!this.hydrated) {
if (this.preHydrationBypass === true) {
return true;
}
if (!this.preHydrationOverrides.has(pluginKey(serverId, pluginId))) {
return false;
}
return this.getDecision(serverId, pluginId) === "approved";
}
if (this.bypass) {
return true;
}
return this.getDecision(serverId, pluginId) === "approved";
}
/**
* Aligns queued prompts for `serverId` with the host's current compatible client plugins.
* Plugins no longer present are pruned; unreviewed plugins are enqueued in arrival order.
*/
reconcileHostPlugins(serverId: string, pluginIds: readonly string[]): void {
if (!this.hydrated) return;
if (this.bypass) {
if (this.pruneQueue((item) => item.serverId === serverId)) {
this.publish();
}
return;
}
const activeIds = new Set(pluginIds);
let changed = this.pruneQueue(
(item) => item.serverId === serverId && !activeIds.has(item.pluginId),
);
for (const pluginId of pluginIds) {
if (this.getDecision(serverId, pluginId) !== null) continue;
if (this.queue.some((item) => item.serverId === serverId && item.pluginId === pluginId)) {
continue;
}
this.queue.push({ id: this.nextRequestId++, serverId, pluginId });
changed = true;
}
if (changed) {
this.publish();
}
}
/** Answers the active prompt with `requestId`; answers for any other ID are ignored. */
answer(requestId: number, decision: PluginExecutionDecision): void {
const current = this.queue[0];
if (!current || current.id !== requestId) return;
this.queue.shift();
if (this.queue.length > 0) {
this.completedInBatch += 1;
} else {
this.completedInBatch = 0;
}
this.recordDecision(current.serverId, current.pluginId, decision);
this.schedulePersist();
this.publish();
}
/**
* Declines every remaining queued prompt and empties the queue so dismissing the
* modal or bottom sheet always closes cleanly on every platform.
*/
dismissQueue(): void {
if (this.queue.length === 0) return;
const remaining = this.queue.splice(0);
this.completedInBatch = 0;
for (const item of remaining) {
this.recordDecision(item.serverId, item.pluginId, "declined");
}
this.schedulePersist();
this.publish();
}
/** Directly records a user decision (e.g. Allow or Block from Settings -> Plugins). */
setDecision(serverId: string, pluginId: string, decision: PluginExecutionDecision): void {
const previous = this.getDecision(serverId, pluginId);
const removedPending = this.pruneQueue(
(item) => item.serverId === serverId && item.pluginId === pluginId,
);
if (previous === decision && !removedPending) return;
this.recordDecision(serverId, pluginId, decision);
this.schedulePersist();
this.publish();
}
/** Clears a plugin's saved decision and any pending prompt (e.g. after explicit uninstall). */
clearPlugin(serverId: string, pluginId: string): void {
const hadDecision = this.removeDecision(serverId, pluginId);
const removedPending = this.pruneQueue(
(item) => item.serverId === serverId && item.pluginId === pluginId,
);
if (!hadDecision && !removedPending) return;
this.schedulePersist();
this.publish();
}
/**
* Clears saved decisions and pending prompts for plugins no longer present in the host's
* installed plugin list (e.g. uninstalled via CLI or another client). Disabled plugins stay
* in `installedPluginIds` and keep their decisions.
*/
pruneHostPlugins(serverId: string, installedPluginIds: readonly string[]): void {
if (!this.hydrated) return;
const installed = new Set(installedPluginIds);
let hadDecision = false;
const hostMap = this.decisions.get(serverId);
if (hostMap) {
for (const pluginId of hostMap.keys()) {
if (!installed.has(pluginId) && this.removeDecision(serverId, pluginId)) {
hadDecision = true;
}
}
}
const removedPending = this.pruneQueue(
(item) => item.serverId === serverId && !installed.has(item.pluginId),
);
if (!hadDecision && !removedPending) return;
this.schedulePersist();
this.publish();
}
/** Drops transient queued prompts for a disconnected or unmounted host without forgetting trust. */
clearHostPending(serverId: string): void {
if (!this.pruneQueue((item) => item.serverId === serverId)) return;
this.publish();
}
/** Clears all persisted decisions and pending prompts for a removed or re-keyed host. */
clearHost(serverId: string): void {
if (!this.hydrated) {
this.preHydrationClearedHosts.add(serverId);
for (const key of this.preHydrationOverrides.keys()) {
if (key.startsWith(`${serverId}\0`)) {
this.preHydrationOverrides.delete(key);
}
}
}
const hadDecisions = this.decisions.delete(serverId);
const removedPending = this.pruneQueue((item) => item.serverId === serverId);
if (!hadDecisions && !removedPending) return;
this.schedulePersist();
this.publish();
}
/** Waits for any queued storage writes to settle; useful in tests. */
flushPersistence(): Promise<void> {
return Promise.all([this.persistChain, this.bypassPersistChain]).then(() => undefined);
}
private async hydrate(): Promise<void> {
const [loaded, loadedBypass] = await Promise.all([
loadPluginExecutionApprovals(this.storage).catch((error) => {
console.warn("[Plugins] Failed to load client execution approvals", error);
return {} as StoredPluginExecutionApprovals;
}),
loadPluginExecutionBypass(this.storage).catch((error) => {
console.warn("[Plugins] Failed to load client execution approval bypass", error);
return false;
}),
]);
for (const [serverId, entries] of Object.entries(loaded)) {
if (this.preHydrationClearedHosts.has(serverId)) continue;
for (const [pluginId, decision] of Object.entries(entries)) {
if (this.preHydrationOverrides.has(pluginKey(serverId, pluginId))) continue;
this.writeDecisionToMap(serverId, pluginId, decision);
}
}
this.bypass = this.preHydrationBypass ?? loadedBypass;
const hadPreHydrationDecisionEdits =
this.preHydrationOverrides.size > 0 || this.preHydrationClearedHosts.size > 0;
this.preHydrationOverrides.clear();
this.preHydrationClearedHosts.clear();
this.preHydrationBypass = null;
if (this.bypass) {
this.pruneQueue(() => true);
}
this.hydrated = true;
if (hadPreHydrationDecisionEdits) {
this.schedulePersist();
}
this.publish();
}
private recordDecision(
serverId: string,
pluginId: string,
decision: PluginExecutionDecision,
): void {
if (!this.hydrated) {
this.preHydrationOverrides.set(pluginKey(serverId, pluginId), decision);
}
this.writeDecisionToMap(serverId, pluginId, decision);
}
private writeDecisionToMap(
serverId: string,
pluginId: string,
decision: PluginExecutionDecision,
): void {
let hostMap = this.decisions.get(serverId);
if (!hostMap) {
hostMap = new Map();
this.decisions.set(serverId, hostMap);
}
hostMap.set(pluginId, decision);
}
private removeDecision(serverId: string, pluginId: string): boolean {
if (!this.hydrated) {
this.preHydrationOverrides.set(pluginKey(serverId, pluginId), null);
}
const hostMap = this.decisions.get(serverId);
if (!hostMap || !hostMap.delete(pluginId)) return false;
if (hostMap.size === 0) {
this.decisions.delete(serverId);
}
return true;
}
private pruneQueue(predicate: (item: PluginExecutionApprovalRequest) => boolean): boolean {
let removed = false;
for (let index = this.queue.length - 1; index >= 0; index -= 1) {
if (predicate(this.queue[index]!)) {
this.queue.splice(index, 1);
removed = true;
}
}
if (this.queue.length === 0) {
this.completedInBatch = 0;
}
return removed;
}
private serializeDecisions(): StoredPluginExecutionApprovals {
const serialized: StoredPluginExecutionApprovals = {};
for (const [serverId, hostMap] of this.decisions) {
if (hostMap.size === 0) continue;
const entries: Record<string, PluginExecutionDecision> = {};
for (const [pluginId, decision] of hostMap) {
entries[pluginId] = decision;
}
serialized[serverId] = entries;
}
return serialized;
}
private schedulePersist(): void {
if (!this.hydrated || this.persistPending) return;
this.persistPending = true;
this.persistChain = this.persistChain
.then(async () => {
while (this.persistPending) {
this.persistPending = false;
await savePluginExecutionApprovals(this.storage, this.serializeDecisions());
}
return undefined;
})
.catch((error) => {
console.warn("[Plugins] Failed to save client execution approvals", error);
});
}
private publish(): void {
const current = this.queue[0] ?? null;
const pendingCount = this.queue.length;
const step = current ? this.completedInBatch + 1 : 0;
const totalInBatch = current ? this.completedInBatch + pendingCount : 0;
if (
this.queueState.current !== current ||
this.queueState.pendingCount !== pendingCount ||
this.queueState.step !== step ||
this.queueState.totalInBatch !== totalInBatch
) {
this.queueState = current ? { current, pendingCount, step, totalInBatch } : IDLE_QUEUE_STATE;
}
for (const listener of this.listeners) {
listener();
}
}
}
+3 -1
View File
@@ -4,6 +4,7 @@ import { useTranslation } from "react-i18next";
import type { PluginListItem } from "@getpaseo/protocol/messages";
import { useToast } from "@/contexts/toast-api-context";
import { useHostRuntimeClient } from "@/runtime/host-runtime";
import { pluginExecutionApprovals } from "@/plugins/execution-approval";
import { pluginDisplayName, pluginListQueryKey } from "@/plugins/plugin-list";
import { confirmDialog } from "@/utils/confirm-dialog";
import { pluginErrorText } from "./error-text";
@@ -52,7 +53,8 @@ export function usePluginActions(serverId: string) {
try {
if (action === "remove") {
await client.removePlugin(plugin.id);
// A failed update belonged to this installation, not to a later one with the same ID.
// A failed update or saved client approval belonged to this installation, not a later one.
pluginExecutionApprovals.clearPlugin(serverId, plugin.id);
dismissFailedOperation(serverId, plugin.id);
queryClient.setQueryData<PluginListItem[]>(pluginListQueryKey(serverId), (plugins) =>
plugins?.filter((candidate) => candidate.id !== plugin.id),
@@ -14,6 +14,7 @@ import { Switch } from "@/components/ui/switch";
import { useToast } from "@/contexts/toast-api-context";
import { useHostRuntimeClient } from "@/runtime/host-runtime";
import { usePluginEvaluationError } from "@/plugins/registry";
import { usePluginExecutionDecision } from "@/plugins/execution-approval";
import { pluginDisplayName } from "@/plugins/plugin-list";
import { settingsStyles } from "@/styles/settings";
import { usePluginActions } from "./actions";
@@ -143,6 +144,8 @@ function InstalledRow({
const name = pluginDisplayName(plugin);
const error = usePluginEvaluationError(serverId, plugin.id) ?? plugin.error;
const failed = error !== undefined || plugin.status === "failed";
const clientDecision = usePluginExecutionDecision(serverId, plugin.id);
const clientBlocked = !failed && plugin.enabled && clientDecision === "declined";
const open = useCallback(
() => router.push(buildPluginPageRoute(serverId, plugin.id)),
[plugin.id, serverId],
@@ -152,13 +155,21 @@ function InstalledRow({
[onPrepareOpen, plugin],
);
const toggle = useCallback((enabled: boolean) => onToggle(plugin, enabled), [onToggle, plugin]);
const badge = useMemo(
() =>
failed ? (
<StatusBadge label={t("settings.plugins.status.failed")} variant="error" size="xs" />
) : null,
[failed, t],
);
const badge = useMemo(() => {
if (failed) {
return <StatusBadge label={t("settings.plugins.status.failed")} variant="error" size="xs" />;
}
if (clientBlocked) {
return (
<StatusBadge
label={t("settings.plugins.clientExecution.blockedBadge")}
variant="warning"
size="xs"
/>
);
}
return null;
}, [clientBlocked, failed, t]);
return (
<PluginRow
name={name}
@@ -17,6 +17,8 @@ import {
PackagePlus,
Power,
RotateCw,
ShieldCheck,
ShieldOff,
Trash2,
} from "lucide-react-native";
import type { PluginListItem, PluginLogEntry } from "@getpaseo/protocol/messages";
@@ -52,6 +54,11 @@ import { useFetchQuery } from "@/data/query";
import { useDaemonConfig } from "@/hooks/use-daemon-config";
import { useHostFeature } from "@/runtime/host-features";
import { useHostRuntimeClient } from "@/runtime/host-runtime";
import {
pluginExecutionApprovals,
usePluginExecutionDecision,
type PluginExecutionDecision,
} from "@/plugins/execution-approval";
import { pluginDisplayName } from "@/plugins/plugin-list";
import type { Theme } from "@/styles/theme";
import { openExternalUrl } from "@/utils/open-external-url";
@@ -67,6 +74,8 @@ const ThemedPackagePlus = withUnistyles(PackagePlus);
const ThemedPower = withUnistyles(Power);
const ThemedArrow = withUnistyles(ArrowUpRight);
const ThemedRotate = withUnistyles(RotateCw);
const ThemedShieldCheck = withUnistyles(ShieldCheck);
const ThemedShieldOff = withUnistyles(ShieldOff);
const ThemedLogs = withUnistyles(FileText);
const ThemedTrash = withUnistyles(Trash2);
const ThemedBug = withUnistyles(Bug);
@@ -81,6 +90,8 @@ const installIcon = <ThemedPackagePlus size={14} uniProps={mutedIconColorMapping
const powerIcon = <ThemedPower size={14} uniProps={mutedIconColorMapping} />;
const linkIcon = <ThemedArrow size={14} uniProps={mutedIconColorMapping} />;
const reloadIcon = <ThemedRotate size={14} uniProps={mutedIconColorMapping} />;
const shieldAllowIcon = <ThemedShieldCheck size={14} uniProps={mutedIconColorMapping} />;
const shieldBlockIcon = <ThemedShieldOff size={14} uniProps={mutedIconColorMapping} />;
const logsIcon = <ThemedLogs size={14} uniProps={mutedIconColorMapping} />;
const removeIcon = <ThemedTrash size={14} uniProps={dangerIconMapping} />;
const bugIcon = <ThemedBug size={14} uniProps={mutedIconColorMapping} />;
@@ -268,17 +279,21 @@ function ListingMenuItems({
function InstalledMenuHeader({
plugin,
logsSupported,
clientDecision,
pendingAction,
hasListingLinks,
onReload,
onOpenLogs,
onToggleClientExecution,
}: {
plugin: PluginListItem;
logsSupported: boolean;
clientDecision: PluginExecutionDecision | null;
pendingAction?: PluginAction;
hasListingLinks: boolean;
onReload(): void;
onOpenLogs(): void;
onToggleClientExecution(): void;
}) {
const { t } = useTranslation();
return (
@@ -297,6 +312,16 @@ function InstalledMenuHeader({
{t("settings.plugins.logs.action")}
</DropdownMenuItem>
) : null}
{clientDecision !== null ? (
<DropdownMenuItem
leading={clientDecision === "approved" ? shieldBlockIcon : shieldAllowIcon}
onSelect={onToggleClientExecution}
>
{clientDecision === "approved"
? t("settings.plugins.clientExecution.blockAction")
: t("settings.plugins.clientExecution.allowAction")}
</DropdownMenuItem>
) : null}
{hasListingLinks ? <DropdownMenuSeparator /> : null}
</>
);
@@ -334,6 +359,23 @@ function listingNpmUrl(listing?: PluginListing): string | undefined {
return undefined;
}
function usePluginClientExecutionToggle(serverId: string, plugin?: PluginListItem) {
const { t } = useTranslation();
const toast = useToast();
const decision = usePluginExecutionDecision(serverId, plugin?.id ?? "");
const toggle = useCallback(() => {
if (!plugin || decision === null) return;
const nextDecision: PluginExecutionDecision = decision === "approved" ? "declined" : "approved";
pluginExecutionApprovals.setDecision(serverId, plugin.id, nextDecision);
const toastKey =
nextDecision === "approved"
? "settings.plugins.clientExecution.allowedToast"
: "settings.plugins.clientExecution.blockedToast";
toast.show(t(toastKey, { name: pluginDisplayName(plugin) }), { variant: "success" });
}, [decision, plugin, serverId, t, toast]);
return { decision, toggle };
}
/** One plugin's actions menu on its page (works for both installed plugins and directory listings). */
export function PluginActionsMenu({
serverId,
@@ -355,6 +397,8 @@ export function PluginActionsMenu({
const { t } = useTranslation();
// COMPAT(pluginLogs): added in v0.4.0, remove gate after 2027-08-16.
const logsSupported = useHostFeature(serverId, "pluginLogs");
const { decision: clientDecision, toggle: toggleClientExecution } =
usePluginClientExecutionToggle(serverId, plugin);
const [logsOpen, setLogsOpen] = useState(false);
const reload = useCallback(() => onAction?.("reload"), [onAction]);
const remove = useCallback(() => onAction?.("remove"), [onAction]);
@@ -382,10 +426,12 @@ export function PluginActionsMenu({
<InstalledMenuHeader
plugin={plugin}
logsSupported={logsSupported}
clientDecision={clientDecision}
pendingAction={pendingAction}
hasListingLinks={hasListingLinks}
onReload={reload}
onOpenLogs={openLogs}
onToggleClientExecution={toggleClientExecution}
/>
) : null}
<ListingMenuItems
@@ -32,6 +32,7 @@ import {
} from "@/constants/layout";
import { useToast } from "@/contexts/toast-api-context";
import { useContainerWidthBelow } from "@/hooks/use-container-width";
import { pluginExecutionApprovals, usePluginExecutionDecision } from "@/plugins/execution-approval";
import { pluginDisplayName } from "@/plugins/plugin-list";
import {
useInstalledPlugin,
@@ -508,6 +509,41 @@ function PluginTabPanel({
);
}
function PluginClientBlockedAlert({
serverId,
plugin,
}: {
serverId: string;
plugin: PluginListItem;
}) {
const { t } = useTranslation();
const toast = useToast();
const decision = usePluginExecutionDecision(serverId, plugin.id);
const allow = useCallback(() => {
pluginExecutionApprovals.setDecision(serverId, plugin.id, "approved");
toast.show(
t("settings.plugins.clientExecution.allowedToast", { name: pluginDisplayName(plugin) }),
{ variant: "success" },
);
}, [plugin, serverId, t, toast]);
if (!plugin.enabled || decision !== "declined") return null;
return (
<View style={styles.block}>
<Alert
size="sm"
variant="warning"
title={t("settings.plugins.clientExecution.blockedTitle")}
description={t("settings.plugins.clientExecution.blockedDescription")}
testID="plugin-client-blocked-alert"
>
<Button variant="outline" onPress={allow} testID="plugin-client-execution-allow">
{t("settings.plugins.clientExecution.allowAction")}
</Button>
</Alert>
</View>
);
}
function UnlistedPluginView({
compact,
onBack,
@@ -555,6 +591,7 @@ function UnlistedPluginView({
) : null}
</View>
{plugin ? <PluginsOffAlert serverId={serverId} /> : null}
{plugin ? <PluginClientBlockedAlert serverId={serverId} plugin={plugin} /> : null}
{model.description ? <Text style={styles.description}>{model.description}</Text> : null}
{model.error ? (
<View style={styles.block}>
@@ -690,6 +727,7 @@ function ListedPluginLayout({
/>
</View>
{plugin ? <PluginsOffAlert serverId={serverId} /> : null}
{plugin ? <PluginClientBlockedAlert serverId={serverId} plugin={plugin} /> : null}
{model.description ? <Text style={styles.description}>{model.description}</Text> : null}
{model.error ? (
<View style={styles.block}>
@@ -39,6 +39,7 @@ function registry(
const plugins = new PluginRegistry({
localeSource,
version: "0.8.0",
isExecutionApproved: null,
createRuntime: (installation) => {
setupClients.set(installation.id, installation.paseo);
return {
@@ -14,6 +14,7 @@ function registry(version: string) {
const result = new PluginRegistry({
localeSource: { getLocale: () => "en", subscribe: () => () => {} },
version,
isExecutionApproved: null,
createRuntime(installation) {
starts++;
return {
@@ -1,6 +1,7 @@
import appPackage from "../../package.json";
import { afterEach, describe, expect, it, vi } from "vitest";
import type { DaemonClient } from "@getpaseo/client/internal/daemon-client";
import { pluginExecutionApprovals } from "./execution-approval";
import { pluginRegistry as registry } from "./registry";
const audio = { play: async () => 0 };
@@ -29,6 +30,9 @@ const pluginRegistry = {
catalog: Parameters<typeof registry.installCatalog>[1],
options: { replacePluginId?: string; client?: DaemonClient } = {},
) {
for (const entry of catalog) {
pluginExecutionApprovals.setDecision(serverId, entry.id, "approved");
}
return registry.installCatalog(
serverId,
catalog.map((entry) => ({ ...entry, requirements: { paseo: `>=${appPackage.version}` } })),
@@ -72,6 +76,8 @@ function installedPluginIds(): string[] {
afterEach(() => {
pluginRegistry.removeHost("host-a");
pluginRegistry.removeHost("host-b");
pluginExecutionApprovals.clearHost("host-a");
pluginExecutionApprovals.clearHost("host-b");
Reflect.deleteProperty(globalThis, "__pluginCleanups");
});
+44
View File
@@ -10,6 +10,7 @@ import { resolveAppVersion } from "@/utils/app-version";
import { createPluginClientRuntime } from "./client-runtime";
import { createPluginSubscribe } from "./subscriptions";
import { runPluginClientBundle } from "./evaluate";
import { pluginExecutionApprovals } from "./execution-approval";
import type { InstalledPlugin } from "./types";
type CatalogPlugin = Awaited<ReturnType<DaemonClient["getPluginCatalog"]>>[number];
@@ -30,9 +31,30 @@ export class PluginRegistry {
localeSource: import("@getpaseo/plugin/client/host").PluginLocaleSource;
version: string | null;
createRuntime: typeof createPluginClientRuntime;
/**
* Checks whether `(serverId, pluginId)` is approved to evaluate client code.
* Required so no caller can omit the gate; pass `null` only in unit tests that
* exercise unrelated registry mechanics.
*/
isExecutionApproved: ((serverId: string, pluginId: string) => boolean) | null;
},
) {}
isCompatible(entry: Pick<CatalogPlugin, "id" | "requirements">): boolean {
try {
assertPluginCompatibility({ ...entry, version: this.dependencies.version, runtime: "app" });
return true;
} catch {
return false;
}
}
private isAllowed(serverId: string, pluginId: string): boolean {
return this.dependencies.isExecutionApproved === null
? true
: this.dependencies.isExecutionApproved(serverId, pluginId);
}
subscribe = (listener: () => void): (() => void) => {
this.listeners.add(listener);
return () => this.listeners.delete(listener);
@@ -73,6 +95,7 @@ export class PluginRegistry {
.map((plugin) => `${plugin.id}\0${plugin.clientBundle}`);
const preserved = catalog.flatMap((entry) => {
if (!sameClient) return [];
if (!this.isAllowed(serverId, entry.id)) return [];
const existing = previous.find(
(plugin) =>
plugin.id !== options.replacePluginId &&
@@ -95,6 +118,10 @@ export class PluginRegistry {
try {
if (!entry.clientBundle) return [];
assertPluginCompatibility({ ...entry, version: this.dependencies.version, runtime: "app" });
if (!this.isAllowed(serverId, entry.id)) {
this.evaluationErrors.delete(key);
return [];
}
const existing = preserved.find(
(plugin) => plugin.id === entry.id && plugin.clientBundle === entry.clientBundle,
);
@@ -197,6 +224,21 @@ export class PluginRegistry {
);
}
/** Disposes any active installations for `serverId` that are no longer approved (e.g. blocked offline). */
pruneDisallowed(serverId: string): void {
const previous = this.byHost.get(serverId);
if (!previous || previous.length === 0) return;
const kept = previous.filter((plugin) => this.isAllowed(serverId, plugin.id));
const removed = previous.filter((plugin) => !this.isAllowed(serverId, plugin.id));
if (removed.length === 0) return;
for (const plugin of removed) {
this.evaluationErrors.delete(`${serverId}/${plugin.id}`);
}
this.byHost.set(serverId, kept);
this.publish();
for (const plugin of removed) this.dispose(plugin);
}
removeHost(serverId: string): void {
const hadCatalog = this.catalogStatuses.delete(serverId);
const installed = this.byHost.get(serverId);
@@ -262,6 +304,8 @@ export const pluginRegistry = new PluginRegistry({
},
version: resolveAppVersion(),
createRuntime: createPluginClientRuntime,
isExecutionApproved: (serverId, pluginId) =>
pluginExecutionApprovals.isApproved(serverId, pluginId),
});
export function useInstalledPlugins(): InstalledPlugin[] {
+45 -2
View File
@@ -3,6 +3,7 @@ import type { PluginIcon, PluginScreenParams, PluginScreenProps } from "@getpase
import type { PluginTheme } from "@getpaseo/plugin";
import { X } from "lucide-react-native";
import { useCallback, useMemo, type ComponentType } from "react";
import { useTranslation } from "react-i18next";
import { Text, View } from "react-native";
import { StyleSheet, withUnistyles } from "react-native-unistyles";
import { HeaderIconBadge } from "@/components/headers/header-icon-badge";
@@ -13,6 +14,7 @@ import { ScreenTitle } from "@/components/headers/screen-title";
import { SidebarMenuToggle } from "@/components/headers/sidebar-menu-toggle";
import { HostFilter } from "@/components/hosts/host-filter";
import type { HostPickerHost } from "@/components/hosts/host-picker";
import { Button } from "@/components/ui/button";
import { LoadingSpinner } from "@/components/ui/loading-spinner";
import { useIsCompactFormFactor } from "@/constants/layout";
import {
@@ -25,6 +27,7 @@ import type { ShortcutKey } from "@/utils/format-shortcut";
import { usePluginHostNavigation } from "./host-navigation";
import { PluginIconView } from "./icons";
import { toPluginTheme } from "./theme";
import { pluginExecutionApprovals, usePluginExecutionDecision } from "./execution-approval";
import { useInstalledPlugin, usePluginCatalogStatus, usePluginInstallations } from "./registry";
import { buildPluginSurfaceRoute, pluginScreenParamsFromRoute } from "./routes";
import {
@@ -57,7 +60,16 @@ const SURFACE_ERRORS = {
unavailable: "This plugin surface is unavailable.",
} as const;
function PluginSurfacePlaceholder({ status }: { status: PluginSurfacePlaceholderStatus }) {
function PluginSurfacePlaceholder({
status,
blocked,
onAllow,
}: {
status: PluginSurfacePlaceholderStatus;
blocked: boolean;
onAllow(): void;
}) {
const { t } = useTranslation();
if (status === "loading") {
return (
<View
@@ -70,6 +82,18 @@ function PluginSurfacePlaceholder({ status }: { status: PluginSurfacePlaceholder
</View>
);
}
if (blocked && status === "unavailable") {
return (
<View style={styles.blockedState}>
<Text style={styles.blockedText}>
{t("settings.plugins.clientExecution.surfaceBlocked")}
</Text>
<Button variant="outline" onPress={onAllow}>
{t("settings.plugins.clientExecution.allowAction")}
</Button>
</View>
);
}
return <Text style={styles.errorText}>{SURFACE_ERRORS[status]}</Text>;
}
@@ -169,7 +193,13 @@ export function PluginSurfaceScreen() {
const client = useHostRuntimeClient(serverId);
const connectionStatus = useHostRuntimeConnectionStatus(serverId);
const catalogStatus = usePluginCatalogStatus(serverId);
const clientDecision = usePluginExecutionDecision(serverId, pluginId);
const placeholderStatus = resolvePluginSurfacePlaceholder({ connectionStatus, catalogStatus });
const allowPlugin = useCallback(() => {
if (serverId && pluginId) {
pluginExecutionApprovals.setDecision(serverId, pluginId, "approved");
}
}, [pluginId, serverId]);
const compact = useIsCompactFormFactor();
const { sidebarItem, surface } = useMemo(
() => resolvePluginSurfaceContribution(plugin, identity),
@@ -273,7 +303,11 @@ export function PluginSurfaceScreen() {
/>
</SurfaceErrorBoundary>
) : (
<PluginSurfacePlaceholder status={placeholderStatus} />
<PluginSurfacePlaceholder
status={placeholderStatus}
blocked={clientDecision === "declined"}
onAllow={allowPlugin}
/>
)}
</View>
</View>
@@ -297,4 +331,13 @@ const styles = StyleSheet.create((theme) => ({
color: theme.colors.statusDanger,
padding: theme.spacing[4],
},
blockedState: {
padding: theme.spacing[6],
alignItems: "flex-start",
gap: theme.spacing[3],
},
blockedText: {
color: theme.colors.foregroundMuted,
fontSize: theme.fontSize.base,
},
}));
@@ -38,6 +38,7 @@ vi.mock("../icons", () => ({
pluginIconComponent: () => () => null,
}));
import { pluginExecutionApprovals } from "../execution-approval";
import { pluginRegistry } from "../registry";
import { PluginTimelineItemView } from "./view";
@@ -109,11 +110,13 @@ const daemonClient = {} as DaemonClient;
beforeEach(() => {
vi.stubGlobal("React", React);
vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
pluginExecutionApprovals.setDecision("host-1", "reports", "approved");
});
afterEach(() => {
for (const root of roots.splice(0)) act(() => root.unmount());
for (const container of containers.splice(0)) container.remove();
pluginRegistry.removeHost("host-1");
pluginExecutionApprovals.clearHost("host-1");
selectedHost.client = null;
vi.restoreAllMocks();
vi.unstubAllGlobals();
@@ -23,6 +23,7 @@ import { seedSessionHosts, seedSessionWorkspaces } from "@/test/seed-session";
import { createPluginAgentActionContext, createPluginWorkspaceActionContext } from "../actions";
import { createPluginClientStateSource } from "../client-state/source";
import { buildPluginCommandCenterContributions } from "../command-center/contributions";
import { pluginExecutionApprovals } from "../execution-approval";
import { pluginRegistry } from "../registry";
import { pluginWorkspaceLayoutSource } from "./index";
@@ -92,6 +93,8 @@ const REVIEW_PANELS = [
let daemon: ReturnType<typeof createFakeDaemon>;
function install(reviewPanels = REVIEW_PANELS): void {
pluginExecutionApprovals.setDecision(SERVER_ID, "review", "approved");
pluginExecutionApprovals.setDecision(SERVER_ID, "other", "approved");
pluginRegistry.installCatalog(
SERVER_ID,
[bundle("review", reviewPanels), bundle("other", workspacePanel("board"))],
@@ -273,6 +276,7 @@ afterEach(() => {
const layout = useWorkspaceLayoutStore.getState().layoutByWorkspace[WORKSPACE_KEY];
for (const open of layout ? collectAllTabs(layout.root) : []) setModified(open.tabId, false);
pluginRegistry.removeHost(SERVER_ID);
pluginExecutionApprovals.clearHost(SERVER_ID);
seedSessionHosts([]);
});
@@ -1,6 +1,7 @@
import appPackage from "../../../package.json";
import { describe, expect, it, vi } from "vitest";
import type { DaemonClient } from "@getpaseo/client/internal/daemon-client";
import { pluginExecutionApprovals } from "../execution-approval";
import { pluginRegistry } from "../registry";
import { panelTargetSupportsHost, resolvePluginPanelOpenLocation } from "./locations";
@@ -34,6 +35,7 @@ function install(locations: readonly ("workspace" | "explorer")[]) {
return function() {};
}};
})`;
pluginExecutionApprovals.setDecision("host-1", "review", "approved");
pluginRegistry.installCatalog(
"host-1",
[{ id: "review", requirements: { paseo: `>=${appPackage.version}` }, clientBundle: bundle }],
@@ -5874,4 +5874,48 @@ describe("HostRuntimeStore initial connection hint bootstrap", () => {
expect(seenProbes).not.toContainEqual(expect.objectContaining({ endpoint: "metro-host:8081" }));
expect(store.getHosts()).toHaveLength(0);
});
it("resets host trust on host removal and relay identity key replacement", async () => {
const resetHosts: string[] = [];
const store = new HostRuntimeStore({
storage: createMemoryHostRuntimeStorage(),
onHostTrustReset: (serverId) => resetHosts.push(serverId),
deps: {
createClient: () => new FakeDaemonClient() as unknown as DaemonClient,
connectToDaemon: async ({ host }) => ({
client: makeConnectedProbeClient(5) as unknown as DaemonClient,
serverId: host.serverId,
hostname: host.label ?? null,
}),
getClientId: async () => "cid_test_trust_reset",
},
});
const offerUrl = (key: string) => {
const encoded = Buffer.from(
JSON.stringify({
v: 2,
serverId: "srv_rotated",
daemonPublicKeyB64: key,
relay: { endpoint: "127.0.0.1:59998", useTls: false },
}),
"utf8",
).toString("base64url");
return `paseo://pair#offer=${encoded}`;
};
const initialImport = store.importConnectionLink(offerUrl("old-daemon-key"), "openProject");
await vi.waitFor(() => expect(store.getPendingHostConfirmation()).not.toBeNull());
store.answerHostConfirmation(store.getPendingHostConfirmation()!.id, true);
await initialImport;
expect(resetHosts).toEqual([]);
const rotatedImport = store.importConnectionLink(offerUrl("new-daemon-key"), "openProject");
await vi.waitFor(() => expect(store.getPendingHostConfirmation()?.kind).toBe("keyChanged"));
store.answerHostConfirmation(store.getPendingHostConfirmation()!.id, true);
await rotatedImport;
expect(resetHosts).toEqual(["srv_rotated"]);
await store.removeHost("srv_rotated");
expect(resetHosts).toEqual(["srv_rotated", "srv_rotated"]);
});
});
+11 -2
View File
@@ -1,4 +1,5 @@
import { createHostPluginClientBundleStore } from "@/plugins/client-bundles";
import { pluginExecutionApprovals } from "@/plugins/execution-approval";
import { watchdog } from "@/watchdog";
import { createHostLogger } from "./host-logger";
import { createHostChannelTransport } from "@getpaseo/client/internal/hosts";
@@ -1932,17 +1933,21 @@ export class HostRuntimeStore {
private storage: HostRuntimeStorage;
private replicaCache: ReplicaCache;
private readonly revokePushNotifications: typeof revokePushNotifications;
private readonly onHostTrustReset: (serverId: string) => void;
constructor(input?: {
deps?: HostRuntimeControllerDeps;
storage?: HostRuntimeStorage;
replicaRowStore?: ReplicaRowStore;
revokePushNotifications?: typeof revokePushNotifications;
onHostTrustReset?: (serverId: string) => void;
}) {
this.deps = input?.deps ?? createDefaultDeps((serverId) => this.getClient(serverId));
this.storage = input?.storage ?? AsyncStorage;
this.replicaCache = new ReplicaCache(input?.replicaRowStore ?? createReplicaRowStore());
this.revokePushNotifications = input?.revokePushNotifications ?? revokePushNotifications;
this.onHostTrustReset =
input?.onHostTrustReset ?? ((serverId) => pluginExecutionApprovals.clearHost(serverId));
}
// --- Host registry ---
@@ -2550,6 +2555,7 @@ export class HostRuntimeStore {
async removeHost(serverId: string): Promise<void> {
await this.revokePushNotifications({ client: this.getClient(serverId), serverId });
this.onHostTrustReset(serverId);
const remaining = this.hosts.filter((daemon) => daemon.serverId !== serverId);
this.unreadableHosts = forgetUnreadableHost(this.unreadableHosts, serverId);
this.setHostsAndSync(remaining);
@@ -2594,7 +2600,7 @@ export class HostRuntimeStore {
existingClient?: DaemonClient;
}): Promise<HostProfile> {
const now = new Date().toISOString();
const next = upsertHostConnectionInProfiles({
const { profiles: next, identityReplaced } = upsertHostConnectionInProfiles({
profiles: this.hosts,
serverId: input.serverId,
label: input.label,
@@ -2602,6 +2608,9 @@ export class HostRuntimeStore {
password: input.password,
now,
});
if (identityReplaced) {
this.onHostTrustReset(input.serverId);
}
this.setHostsAndSync(next, {
initialConnectionByServerId: input.existingClient
? new Map([
@@ -2772,7 +2781,7 @@ export class HostRuntimeStore {
if (this.hostObservations.get(serverId)?.client !== client) return;
for (const target of directory.hosts) {
if (!target.serverId || target.serverId === serverId) continue;
const next = upsertHostConnectionInProfiles({
const { profiles: next } = upsertHostConnectionInProfiles({
profiles: this.hosts,
serverId: target.serverId,
label: target.label ?? undefined,
@@ -151,17 +151,6 @@ describe("createWorkspaceAgentInBackground", () => {
expect(draftText()).toBe("a different idea");
});
it("keeps text typed while workspace creation was pending that has not been published yet", () => {
const clearConsumedDraft = captureCleanup();
useDraftStore.getState().stageDraftText({ draftKey: DRAFT_KEY, text: "Keep this newer draft" });
// Creation completes before the staged text is published after the next paint.
clearConsumedDraft();
useDraftStore.getState().flushDraftText(DRAFT_KEY);
expect(draftText()).toBe("Keep this newer draft");
});
it("keeps a newer draft written while workspace creation was pending", async () => {
useWorkspaceAttachmentsStore.getState().addWorkspaceAttachment({
scopeKey: SCOPE_KEY,
@@ -40,8 +40,6 @@ export function captureWorkspaceDraftCleanup(input: WorkspaceDraftCleanupInput):
const attachments = useWorkspaceAttachmentsStore.getState().attachmentsByScope[scopeKey];
return () => {
// Text typed into a newer draft is published after the next paint; it is newer state too.
useDraftStore.getState().flushDraftText(input.draftKey);
// These stores update independently. A context-only edit does not bump the text version.
// Any newer draft state owns the whole draft, including its unchanged context.
if (
+158 -4
View File
@@ -43,7 +43,7 @@ import { SidebarHeaderRow } from "@/components/sidebar/sidebar-header-row";
import { HostPicker as SharedHostPicker } from "@/components/hosts/host-picker";
import { HostStatusIcon } from "@/hosts/host-status-icon";
import type { SurfaceBackdrop } from "@/styles/surface-backdrop";
import { SettingsSection } from "@/components/settings/headings/settings-section";
import { SettingsCard, SettingsRow, SettingsSection, SettingsSwitch } from "@/components/settings";
import { AppearanceSection } from "@/screens/settings/appearance/appearance-section";
import { OpenLocationSection } from "@/screens/settings/open-location/open-location-section";
import { TerminalSection } from "@/screens/settings/terminal/terminal-section";
@@ -70,7 +70,9 @@ import { PageLayout } from "@/components/page-layout";
import { KeyboardShortcutsSection } from "@/screens/settings/keyboard-shortcuts-section";
import { EditorSection } from "@/screens/settings/editor-section";
import { FilesSection } from "@/screens/settings/files-section";
import { AdaptiveModalSheet, type SheetHeader } from "@/components/adaptive-modal-sheet";
import { Button } from "@/components/ui/button";
import { Switch } from "@/components/ui/switch";
import { CommunityLinks } from "@/components/community-links";
import { SegmentedControl } from "@/components/ui/segmented-control";
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem } from "@/components/ui/dropdown-menu";
@@ -107,6 +109,10 @@ import {
HostTerminalsPage,
} from "@/screens/settings/host-page";
import { ClientHostDetailPage, ClientHostsSection } from "@/screens/settings/client-hosts-page";
import {
pluginExecutionApprovals,
usePluginExecutionApprovalBypass,
} from "@/plugins/execution-approval";
import {
PluginGalleryMenu,
PluginGalleryPage,
@@ -327,7 +333,7 @@ function GeneralSection({ settings, handleLanguageChange }: GeneralSectionProps)
: settings.language;
return (
<SettingsSection title={t("settings.general.title")}>
<View style={settingsStyles.card}>
<SettingsCard>
<View style={settingsStyles.row}>
<View style={settingsStyles.rowContent}>
<Text style={settingsStyles.rowTitle}>{t("settings.general.language.label")}</Text>
@@ -351,7 +357,8 @@ function GeneralSection({ settings, handleLanguageChange }: GeneralSectionProps)
</DropdownMenu>
</View>
{isNative ? null : <ShowSetupAgainRow />}
</View>
<PluginExecutionBypassRow />
</SettingsCard>
</SettingsSection>
);
}
@@ -360,7 +367,7 @@ function ShowSetupAgainRow() {
const { t } = useTranslation();
const openOnboarding = useOpenOnboarding();
return (
<View style={[settingsStyles.row, settingsStyles.rowBorder]}>
<View style={settingsStyles.row}>
<View style={settingsStyles.rowContent}>
<Text style={settingsStyles.rowTitle}>{t("settings.general.setup.label")}</Text>
<Text style={settingsStyles.rowHint}>{t("settings.general.setup.description")}</Text>
@@ -372,6 +379,136 @@ function ShowSetupAgainRow() {
);
}
function PluginExecutionBypassRow() {
const { t } = useTranslation();
const bypass = usePluginExecutionApprovalBypass();
const [confirming, setConfirming] = useState(false);
const [saving, setSaving] = useState(false);
const [saveError, setSaveError] = useState<string | null>(null);
const [failedDisablePersist, setFailedDisablePersist] = useState(false);
const mountedRef = useRef(true);
useEffect(() => {
mountedRef.current = true;
return () => {
mountedRef.current = false;
};
}, []);
const persistBypass = useCallback(
async (enabled: boolean) => {
setSaving(true);
setSaveError(null);
try {
await pluginExecutionApprovals.setBypassEnabled(enabled);
if (!mountedRef.current) return;
setFailedDisablePersist(false);
} catch {
if (!mountedRef.current) return;
setSaveError(t("common.errors.unableToSave"));
setFailedDisablePersist(!enabled);
} finally {
if (mountedRef.current) {
setSaving(false);
}
}
},
[t],
);
const handleChange = useCallback(
(enabled: boolean) => {
if (enabled) {
setConfirming(true);
return;
}
void persistBypass(false);
},
[persistBypass],
);
const handleCancel = useCallback(() => {
setConfirming(false);
}, []);
const handleConfirm = useCallback(() => {
setConfirming(false);
void persistBypass(true);
}, [persistBypass]);
const handleRetryDisable = useCallback(() => {
void persistBypass(false);
}, [persistBypass]);
const confirmHeader = useMemo<SheetHeader>(
() => ({ title: t("settings.general.pluginExecutionBypass.confirmTitle") }),
[t],
);
const label = t("settings.general.pluginExecutionBypass.label");
const hint = t("settings.general.pluginExecutionBypass.description");
return (
<>
{failedDisablePersist ? (
<SettingsRow
label={label}
hint={hint}
error={saveError ?? undefined}
testID="settings-plugin-execution-bypass-row"
>
<View style={styles.bypassControls}>
<Button variant="outline" onPress={handleRetryDisable} disabled={saving}>
{t("common.actions.retry")}
</Button>
<Switch
value={bypass}
onValueChange={handleChange}
disabled={saving}
accessibilityLabel={label}
/>
</View>
</SettingsRow>
) : (
<SettingsSwitch
label={label}
hint={hint}
value={bypass}
onValueChange={handleChange}
disabled={saving}
error={saveError ?? undefined}
testID="settings-plugin-execution-bypass-row"
/>
)}
{confirming ? (
<AdaptiveModalSheet
header={confirmHeader}
visible
onClose={handleCancel}
testID="plugin-execution-bypass-confirm-modal"
>
<Text style={styles.confirmText}>
{t("settings.general.pluginExecutionBypass.confirmMessage")}
</Text>
<View style={styles.confirmActions}>
<Button variant="secondary" style={FLEX_1_STYLE} onPress={handleCancel}>
{t("common.actions.cancel")}
</Button>
<Button
variant="destructive"
style={FLEX_1_STYLE}
onPress={handleConfirm}
testID="plugin-execution-bypass-confirm"
>
{t("settings.general.pluginExecutionBypass.confirmAction")}
</Button>
</View>
</AdaptiveModalSheet>
) : null}
</>
);
}
interface DiagnosticsSectionProps {
voiceAudioEngine: ReturnType<typeof useVoiceAudioEngineOptional>;
isPlaybackTestRunning: boolean;
@@ -1718,8 +1855,25 @@ const styles = StyleSheet.create((theme) => ({
color: theme.colors.foregroundMuted,
fontSize: theme.fontSize.base,
},
confirmText: {
color: theme.colors.foregroundMuted,
fontSize: theme.fontSize.base,
},
confirmActions: {
flexDirection: "row",
alignItems: "center",
gap: theme.spacing[2],
marginTop: theme.spacing[4],
},
bypassControls: {
flexDirection: "row",
alignItems: "center",
gap: theme.spacing[2],
},
}));
const FLEX_1_STYLE = { flex: 1 } as const;
const desktopStyles = StyleSheet.create({
row: {
flex: 1,
+89 -15
View File
@@ -326,7 +326,7 @@ describe("upsertHostConnectionInProfiles", () => {
connections: [directC],
preferredConnectionId: directC.id,
};
const profiles = upsertHostConnectionInProfiles({
const { profiles } = upsertHostConnectionInProfiles({
profiles: savedC ? [b, c] : [b],
serverId: "srv_c",
label: "Fleet C",
@@ -346,13 +346,15 @@ describe("upsertHostConnectionInProfiles", () => {
serverId: "srv_b",
label: "Fleet B",
connection: route,
}),
}).profiles,
).toBe(profiles);
},
);
it("gives a newly discovered host the default appearance", () => {
const [profile] = upsertHostConnectionInProfiles({
const {
profiles: [profile],
} = upsertHostConnectionInProfiles({
profiles: [],
serverId: "srv_new",
connection,
@@ -369,7 +371,9 @@ describe("upsertHostConnectionInProfiles", () => {
connections: [],
};
const [profile] = upsertHostConnectionInProfiles({
const {
profiles: [profile],
} = upsertHostConnectionInProfiles({
profiles: [existing],
serverId: "srv_known",
connection,
@@ -400,7 +404,9 @@ describe("upsertHostConnectionInProfiles", () => {
useTls: true,
};
const [profile] = upsertHostConnectionInProfiles({
const {
profiles: [profile],
} = upsertHostConnectionInProfiles({
profiles: [existing],
serverId: "srv_known",
connection: replacement,
@@ -433,11 +439,15 @@ describe("relay daemon identity", () => {
it("replaces the key on the same relay and clears the saved password", () => {
const rotated: HostConnection = { ...savedRelay, daemonPublicKeyB64: "pk_new" };
const [profile] = upsertHostConnectionInProfiles({
const {
profiles: [profile],
identityReplaced,
} = upsertHostConnectionInProfiles({
profiles: [saved],
serverId: "srv",
connection: rotated,
});
expect(identityReplaced).toBe(true);
expect(profile.connections).toEqual([direct, rotated]);
expect(profile.password).toBeUndefined();
expect(profile.label).toBe("MacBook Pro");
@@ -451,11 +461,15 @@ describe("relay daemon identity", () => {
useTls: true,
daemonPublicKeyB64: "pk_new",
};
const [profile] = upsertHostConnectionInProfiles({
const {
profiles: [profile],
identityReplaced,
} = upsertHostConnectionInProfiles({
profiles: [saved],
serverId: "srv",
connection: elsewhere,
});
expect(identityReplaced).toBe(true);
expect(profile.connections).toEqual([direct, elsewhere]);
expect(profile.preferredConnectionId).toBe(elsewhere.id);
expect(profile.password).toBeUndefined();
@@ -463,12 +477,16 @@ describe("relay daemon identity", () => {
it("keeps a password supplied with the new key", () => {
const rotated: HostConnection = { ...savedRelay, daemonPublicKeyB64: "pk_new" };
const [profile] = upsertHostConnectionInProfiles({
const {
profiles: [profile],
identityReplaced,
} = upsertHostConnectionInProfiles({
profiles: [saved],
serverId: "srv",
connection: rotated,
password: "new-secret",
});
expect(identityReplaced).toBe(true);
expect(profile.password).toBe("new-secret");
});
@@ -478,22 +496,30 @@ describe("relay daemon identity", () => {
id: "relay:wss:other.example.com:443",
relayEndpoint: "other.example.com:443",
};
const [profile] = upsertHostConnectionInProfiles({
const {
profiles: [profile],
identityReplaced,
} = upsertHostConnectionInProfiles({
profiles: [saved],
serverId: "srv",
connection: elsewhere,
});
expect(identityReplaced).toBe(false);
expect(profile.connections).toEqual([direct, savedRelay, elsewhere]);
expect(profile.password).toBe("saved-secret");
});
it("keeps the saved password when a direct host gets its first relay route", () => {
const directOnly: HostProfile = { ...saved, connections: [direct] };
const [profile] = upsertHostConnectionInProfiles({
const {
profiles: [profile],
identityReplaced,
} = upsertHostConnectionInProfiles({
profiles: [directOnly],
serverId: "srv",
connection: savedRelay,
});
expect(identityReplaced).toBe(false);
expect(profile.connections).toEqual([direct, savedRelay]);
expect(profile.password).toBe("saved-secret");
});
@@ -536,7 +562,7 @@ describe("relay endpoint security pin", () => {
});
it("is kept when the same daemon identity is paired again without it", () => {
const profiles = upsertHostConnectionInProfiles({
const { profiles } = upsertHostConnectionInProfiles({
profiles: [{ ...makeHost("srv"), connections: [pinned], preferredConnectionId: pinned.id }],
serverId: "srv",
connection: unpinned,
@@ -548,7 +574,7 @@ describe("relay endpoint security pin", () => {
const profiles = [
{ ...makeHost("srv"), connections: [unpinned], preferredConnectionId: unpinned.id },
];
const next = upsertHostConnectionInProfiles({
const { profiles: next } = upsertHostConnectionInProfiles({
profiles,
serverId: "srv",
connection: pinned,
@@ -566,7 +592,7 @@ describe("relay endpoint security pin", () => {
daemonPublicKeyB64: "pk_a",
minimumSecurityMode: "protected",
};
const profiles = upsertHostConnectionInProfiles({
const { profiles } = upsertHostConnectionInProfiles({
profiles: [
{ ...makeHost("srv"), connections: [unpinned], preferredConnectionId: unpinned.id },
],
@@ -584,7 +610,7 @@ describe("relay endpoint security pin", () => {
useTls: true,
daemonPublicKeyB64: "pk_a",
};
const profiles = upsertHostConnectionInProfiles({
const { profiles } = upsertHostConnectionInProfiles({
profiles: [{ ...makeHost("srv"), connections: [pinned], preferredConnectionId: pinned.id }],
serverId: "srv",
connection: elsewhere,
@@ -597,11 +623,12 @@ describe("relay endpoint security pin", () => {
it("does not carry over to a different daemon identity", () => {
const rotated: HostConnection = { ...unpinned, daemonPublicKeyB64: "pk_b" };
const profiles = upsertHostConnectionInProfiles({
const { profiles, identityReplaced } = upsertHostConnectionInProfiles({
profiles: [{ ...makeHost("srv"), connections: [pinned], preferredConnectionId: pinned.id }],
serverId: "srv",
connection: rotated,
});
expect(identityReplaced).toBe(true);
expect(profiles[0].connections).toEqual([rotated]);
});
@@ -765,3 +792,50 @@ describe("hostConnectionUri", () => {
).toBeNull();
});
});
describe("upsertHostConnectionInProfiles identity replacement", () => {
it("reports identityReplaced only when a relay connection replaces a saved host's daemon public key", () => {
const saved: HostProfile = {
...makeHost("srv-host"),
connections: [
{
id: "relay:relay.example.test:443",
type: "relay",
relayEndpoint: "relay.example.test:443",
daemonPublicKeyB64: "old-key",
},
],
};
expect(
upsertHostConnectionInProfiles({
profiles: [saved],
serverId: "srv-host",
connection: {
id: "relay:relay.example.test:443",
type: "relay",
relayEndpoint: "relay.example.test:443",
daemonPublicKeyB64: "old-key",
},
}).identityReplaced,
).toBe(false);
expect(
upsertHostConnectionInProfiles({
profiles: [saved],
serverId: "srv-host",
connection: {
id: "relay:relay.example.test:443",
type: "relay",
relayEndpoint: "relay.example.test:443",
daemonPublicKeyB64: "new-key",
},
}).identityReplaced,
).toBe(true);
expect(
upsertHostConnectionInProfiles({
profiles: [saved],
serverId: "srv-host",
connection: { id: "direct:127.0.0.1:6767", type: "directTcp", endpoint: "127.0.0.1:6767" },
}).identityReplaced,
).toBe(false);
});
});
+13 -4
View File
@@ -298,6 +298,15 @@ function hasProfileChanged(input: {
);
}
export interface UpsertHostConnectionResult {
profiles: HostProfile[];
/**
* True when inserting the connection replaced a previously saved relay daemon key,
* indicating a new cryptographic daemon identity for that host.
*/
identityReplaced: boolean;
}
export function upsertHostConnectionInProfiles(input: {
profiles: HostProfile[];
serverId: string;
@@ -305,7 +314,7 @@ export function upsertHostConnectionInProfiles(input: {
connection: HostConnection;
password?: string;
now?: string;
}): HostProfile[] {
}): UpsertHostConnectionResult {
const serverId = input.serverId.trim();
if (!serverId) {
throw new Error("serverId is required");
@@ -343,7 +352,7 @@ export function upsertHostConnectionInProfiles(input: {
createdAt: now,
updatedAt: now,
};
return [...existing, profile];
return { profiles: [...existing, profile], identityReplaced: false };
}
const matchedProfiles = matchingIndexes.map((index) => existing[index]);
@@ -385,7 +394,7 @@ export function upsertHostConnectionInProfiles(input: {
});
if (!changed) {
return existing;
return { profiles: existing, identityReplaced };
}
const nextProfile: HostProfile = {
@@ -404,7 +413,7 @@ export function upsertHostConnectionInProfiles(input: {
const matchingIndexSet = new Set(matchingIndexes);
const next = existing.filter((_daemon, index) => !matchingIndexSet.has(index));
next.splice(firstIndex, 0, nextProfile);
return next;
return { profiles: next, identityReplaced };
}
export function connectionFromListen(listen: string): HostConnection | null {
@@ -81,11 +81,6 @@ describe("buildAgentLsFetchOptions", () => {
});
});
it("preserves empty values and punctuation in repeated label filters", () => {
const options = buildAgentLsFetchOptions({ label: ["tag=v=1,rc", "empty="] });
expect(options.filter?.labels).toEqual({ tag: "v=1,rc", empty: "" });
});
it("asks the daemon for internal agents only with --internal", () => {
expect(buildAgentLsFetchOptions({ background: true, global: true })).toEqual({
filter: { includeBackground: true },
@@ -131,17 +126,6 @@ describe("buildAgentLsFetchOptions", () => {
});
describe("runLsCommand", () => {
it.each(["team", "=blue", " =blue"])(
"rejects the whole listing when a label filter is malformed (%j)",
async (label) => {
await expect(
listAgents({ daemonTarget, label: ["bot=worker", label] }, async () =>
createPagingClient(),
),
).rejects.toMatchObject({ code: "INVALID_LABEL", message: `Invalid label format: ${label}` });
},
);
it("includes agent snapshot metadata in JSON listings", async () => {
const result = await listAgents({ daemonTarget, global: true }, async () =>
createPagingClient(),

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