diff --git a/docs/plugins.md b/docs/plugins.md index 4e1985ea81..f74b4b0022 100644 --- a/docs/plugins.md +++ b/docs/plugins.md @@ -240,8 +240,9 @@ Do not put any other code modules in the plugin root. Shared files import contract helpers and types from `@getpaseo/plugin`. Server handler files import `PluginHandlerContext` from `@getpaseo/plugin/server`. Client files import Paseo UI from -`@getpaseo/plugin/client/react-native`. Its `Icon` resolves a Lucide name using the client's installed icon -set; an unknown name renders nothing so it cannot break the plugin surface. +`@getpaseo/plugin/client/react-native`. Its `Icon` draws a Lucide name from the client's installed +icon set, or any `PluginIcon` through its `icon` prop; an unknown name or unsafe SVG renders nothing +so it cannot break the plugin surface. Its controlled modal keeps presentation metadata on `` and body UI in ``. Body layout, sheet-aware scrolling, and clipboard actions follow the [host UI contract](../public-docs/plugins/reference.md#host-ui). @@ -332,7 +333,7 @@ created by plugin code. Paseo removes registered contributions, unmounts surface state, rejects pending RPCs, closes the plugin's daemon session, and stops the subprocess. Cleanup errors are logged and do not interrupt host teardown. -Paseo owns the route, screen header, Lucide icon validation, close action, theme DTO, layout facts, +Paseo owns the route, screen header, icon validation, close action, theme DTO, layout facts, and render error boundary. The contributed component owns the complete body below the header. The plugin owns the header's text through the screen's `title` (`resolvePluginScreenTitle` in `plugins/surface-contribution.ts`). A legacy `addSidebarItem` route (`/sidebar/`) shows the @@ -400,6 +401,25 @@ See the public [navigation fields](../public-docs/plugins/reference.md#screens-a and [external links and workspace browsers](../public-docs/plugins/reference.md#external-links-and-workspace-browsers) for the author-facing contract. +### Plugin icons + +The [public reference](../public-docs/plugins/reference.md#icons) owns the author API: a contribution +`icon` is a Lucide name, `{ svg }`, or a component. + +- `findSvgIconProblem` in the SDK root (`packages/plugin/src/icons.ts`) is the only SVG rule set. + The daemon applies it to provider and usage-source icon files; the app applies it to inline + icons. Change the rules there, never at a call site. +- The app validates each icon once, at registration, through `parsePluginIcon` in + `packages/app/src/plugins/icons.ts`. Rendering trusts the stored icon. +- That module is the only code that branches on the icon form. Surfaces draw with + `PluginIconView`, or take a stable component from `pluginIconComponent` when their slot expects + one. Lucide and SVG icons receive only size and color, so the host props a button passes to its + component icon never reach an SVG element. +- Attachment sources take `PluginSerializableIcon`: composer drafts persist the source's icon with + each attachment, and a component cannot be stored. +- The plugin compiler loads `.svg` imports as text, so `import icon from "./client/icon.svg"` is the + markup string. + ## Lifecycle hooks Server entries register lifecycle observers with `server.on()` and request transforms with @@ -491,15 +511,13 @@ provider implementation. The public [provider plugin guide](../public-docs/plugi owns author workflow, lifecycle, testing, and distribution guidance. `ProviderRegistration.icon` is a file path relative to the plugin directory, such as `icon.svg`. -It must resolve inside that directory to a regular SVG file no larger than 64 KiB. The SVG must be -self-contained: scripts, styles, `foreignObject`, event-handler attributes, JavaScript URLs, and -external `href` or `xlink:href` references are rejected. Fragment references such as `#mark` are -allowed. Paseo reads and sanitizes the file when the plugin starts; the string is never an inline -SVG or URL. +It must resolve inside that directory to a regular file that passes the shared SVG icon rules +(see [Plugin icons](#plugin-icons)). Paseo reads and validates the file when the plugin starts; the +string is never inline SVG or a URL. ## Usage sources -Register a usage source from `index.server.ts` with `server.registerUsageSource()`. Import `UsageSourceRegistration` and normalization helpers from `@getpaseo/plugin/server/usage`. The plugin owns account discovery, harness labels, and credential-store reads; the daemon owns account grouping and the fetch cache. Agent popovers use only the agent's own login. The host-wide Usage modal falls back across an account's logins; any success shows usage only, and all failures show every login's labeled error and remedy. Follow the [usage source discovery contract](../public-docs/plugins/reference.md#usage-sources). The resolved launch environment crosses into the trusted, unsandboxed plugin subprocess for session discovery. Usage queries never run lifecycle hooks. Inputs are validated in the plugin process and remain daemon-side. `icon` uses the same sanitized SVG file rules as provider icons. +Register a usage source from `index.server.ts` with `server.registerUsageSource()`. Import `UsageSourceRegistration` and normalization helpers from `@getpaseo/plugin/server/usage`. The plugin owns account discovery, harness labels, and credential-store reads; the daemon owns account grouping and the fetch cache. Agent popovers use only the agent's own login. The host-wide Usage modal falls back across an account's logins; any success shows usage only, and all failures show every login's labeled error and remedy. Follow the [usage source discovery contract](../public-docs/plugins/reference.md#usage-sources). The resolved launch environment crosses into the trusted, unsandboxed plugin subprocess for session discovery. Usage queries never run lifecycle hooks. Inputs are validated in the plugin process and remain daemon-side. `icon` uses the same SVG file rules as provider icons. The daemon calls discovery for `usage.list_reports`; the client gates this RPC on `server_info.features.usageSources`. The old `provider.usage.list` RPC maps discovered reports for older clients. diff --git a/packages/app/e2e/browser/plugin-icons.spec.ts b/packages/app/e2e/browser/plugin-icons.spec.ts new file mode 100644 index 0000000000..0a66cd797d --- /dev/null +++ b/packages/app/e2e/browser/plugin-icons.spec.ts @@ -0,0 +1,138 @@ +import { mkdtemp, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import type { Locator, TestInfo } from "@playwright/test"; +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 { pluginRequirements } from "../support/helpers/plugin-fixture"; +import { seedWorkspace } from "../support/helpers/seed-client"; +import { getServerId } from "../support/helpers/server-id"; +import { + switchWorkspaceViaSidebar, + waitForWorkspaceInSidebar, +} from "../support/helpers/workspace-ui"; + +const PLUGIN_ID = "plugin-icons-e2e"; +const SVG_PATH = "M4 12l5 5L20 6"; + +const pluginClientSource = `import React from "react"; +import { Text, View } from "react-native"; + +const checkIcon = ''; + +function BadgeIcon({ size, color }) { + return ; +} + +function Panel() { + return Plugin icon panel; +} + +const panels = [ + { id: "lucide", title: "Lucide icon panel", icon: "Scan" }, + { id: "svg", title: "SVG icon panel", icon: { svg: checkIcon } }, + { id: "component", title: "Component icon panel", icon: BadgeIcon }, +]; + +export default function contribute(client) { + for (const panel of panels) { + client.addWorkspacePanel({ ...panel, context: "workspace", Component: Panel }); + client.addCommandCenterItem({ + id: panel.id, + title: "Open " + panel.title, + icon: panel.icon, + context: "workspace", + onSelect({ openPanel }) { openPanel(panel.id); }, + }); + } + return () => {}; +}`; + +function pluginTab(page: Page, panelId: string): Locator { + const identity = `${PLUGIN_ID.length}_${PLUGIN_ID}_${panelId.length}_${panelId}`; + return page.getByTestId(`workspace-tab-plugin_workspace_${identity}`).filter({ visible: true }); +} + +async function runCommand(page: Page, title: string): Promise { + const panel = await openCommandCenter(page); + await panel.getByTestId("command-center-input").fill(title); + await panel.getByRole("button", { name: title, exact: true }).click(); + await expect(panel).not.toBeVisible(); +} + +async function capture(page: Page, testInfo: TestInfo, name: string): Promise { + const screenshot = testInfo.outputPath(`${name}.png`); + await page.screenshot({ path: screenshot }); + await testInfo.attach(name, { path: screenshot, contentType: "image/png" }); +} + +test.describe("plugin icons", () => { + test.describe.configure({ timeout: 180_000 }); + + test("renders a Lucide name, inline SVG, and a component", async ({ page }, testInfo) => { + const directory = await mkdtemp(path.join(tmpdir(), "paseo-plugin-icons-e2e-")); + const client = await connectNewWorkspaceDaemonClient({ ownProjects: false }); + const previous = await client.getDaemonConfig(); + const workspace = await seedWorkspace({ repoPrefix: "plugin-icons-" }); + await writeFile( + path.join(directory, "paseo-plugin.json"), + JSON.stringify({ id: PLUGIN_ID, requirements: pluginRequirements }), + ); + await writeFile(path.join(directory, "index.client.tsx"), pluginClientSource); + + try { + await client.patchDaemonConfig({ pluginsEnabled: true }); + await client.installDirectoryPlugin(directory); + await page.setViewportSize({ width: 1280, height: 800 }); + await gotoAppShell(page); + const target = { serverId: getServerId(), workspaceId: workspace.workspaceId }; + await waitForWorkspaceInSidebar(page, target); + await switchWorkspaceViaSidebar({ page, ...target }); + + await test.step("Command Center rows draw each icon form", async () => { + const panel = await openCommandCenter(page); + await panel.getByTestId("command-center-input").fill("icon panel"); + for (const title of ["Lucide icon panel", "SVG icon panel", "Component icon panel"]) { + await expect( + panel.getByRole("button", { name: `Open ${title}`, exact: true }), + ).toBeVisible(); + } + await expect( + panel + .getByRole("button", { name: "Open SVG icon panel", exact: true }) + .locator(`path[d="${SVG_PATH}"]`), + ).toBeVisible(); + await expect( + panel + .getByRole("button", { name: "Open Component icon panel", exact: true }) + .getByTestId("plugin-component-icon"), + ).toBeVisible(); + await capture(page, testInfo, "command-center-icons"); + await page.keyboard.press("Escape"); + }); + + await test.step("workspace panel tabs draw each icon form", async () => { + await runCommand(page, "Open Lucide icon panel"); + await runCommand(page, "Open SVG icon panel"); + await runCommand(page, "Open Component icon panel"); + await expect(pluginTab(page, "lucide").locator("svg")).toBeVisible(); + await expect(pluginTab(page, "svg").locator(`path[d="${SVG_PATH}"]`)).toBeVisible(); + await expect( + pluginTab(page, "component").getByTestId("plugin-component-icon"), + ).toBeVisible(); + await capture(page, testInfo, "workspace-tab-icons"); + }); + } finally { + try { + await client.removePlugin(PLUGIN_ID); + } finally { + await client.patchDaemonConfig({ pluginsEnabled: previous.config.pluginsEnabled }); + await workspace.cleanup(); + await client.close(); + await rm(directory, { recursive: true, force: true }); + } + } + }); +}); diff --git a/packages/app/src/plugins/attachments/model.ts b/packages/app/src/plugins/attachments/model.ts index 29798b2d31..eef5665e71 100644 --- a/packages/app/src/plugins/attachments/model.ts +++ b/packages/app/src/plugins/attachments/model.ts @@ -1,6 +1,10 @@ import { z } from "zod"; import type { AgentAttachment } from "@getpaseo/protocol/messages"; -import { PluginAttachmentItemSchema, type PluginAttachmentItem } from "@getpaseo/plugin"; +import { + PluginAttachmentItemSchema, + type PluginAttachmentItem, + type PluginSerializableIcon, +} from "@getpaseo/plugin"; import type { UserComposerAttachment } from "@/attachments/types"; export const PluginResourceComposerAttachmentSchema = z.object({ @@ -8,7 +12,8 @@ export const PluginResourceComposerAttachmentSchema = z.object({ pluginId: z.string().min(1), sourceId: z.string().min(1), sourceTitle: z.string().min(1), - sourceIcon: z.string().min(1), + // Validated when the source registered; a draft keeps the icon its source had then. + sourceIcon: z.union([z.string().min(1), z.object({ svg: z.string().min(1) })]), item: PluginAttachmentItemSchema, }); @@ -20,7 +25,7 @@ export interface PluginResourceSourceIdentity { pluginId: string; sourceId: string; sourceTitle: string; - sourceIcon: string; + sourceIcon: PluginSerializableIcon; } export function createPluginResourceAttachment( diff --git a/packages/app/src/plugins/attachments/picker.tsx b/packages/app/src/plugins/attachments/picker.tsx index a63c1eb4e0..606fba5885 100644 --- a/packages/app/src/plugins/attachments/picker.tsx +++ b/packages/app/src/plugins/attachments/picker.tsx @@ -2,15 +2,18 @@ import { useCallback, useMemo, useState, type ReactElement, type RefObject } fro import { View } from "react-native"; import { withUnistyles } from "react-native-unistyles"; import type { DaemonClient } from "@getpaseo/client/internal/daemon-client"; -import type { PluginAttachmentItem, PluginAttachmentSourceContribution } from "@getpaseo/plugin"; +import type { + PluginAttachmentItem, + PluginAttachmentSourceContribution, + PluginSerializableIcon, +} from "@getpaseo/plugin"; import { searchPluginAttachments } from "@getpaseo/plugin/client/host"; -import type { LucideIcon } from "lucide-react-native"; import type { UserComposerAttachment } from "@/attachments/types"; import type { AttachmentMenuItem } from "@/composer/input/input"; import { Combobox, type ComboboxOption } from "@/components/ui/combobox"; import { useFetchQuery } from "@/data/query"; import { ICON_SIZE, type Theme } from "@/styles/theme"; -import { resolvePluginIcon } from "../icons"; +import { PluginIconView } from "../icons"; import { useInstalledPlugins } from "../registry"; import type { InstalledPlugin } from "../types"; import { createPluginResourceAttachment, togglePluginResourceAttachment } from "./model"; @@ -19,8 +22,8 @@ const SEARCH_STALE_TIME_MS = 30_000; const EMPTY_ATTACHMENT_ITEMS: PluginAttachmentItem[] = []; const iconColorMapping = (theme: Theme) => ({ color: theme.colors.foregroundMuted }); -function SourceIcon({ Icon, color = "" }: { Icon: LucideIcon; color?: string }) { - return ; +function SourceIcon({ icon, color = "" }: { icon: PluginSerializableIcon; color?: string }) { + return ; } const ThemedSourceIcon = withUnistyles(SourceIcon); @@ -145,15 +148,12 @@ export function usePluginAttachmentPicker( ); const menuItems = useMemo( () => - sources.map(({ key, source }) => { - const Icon = resolvePluginIcon(source.icon); - return { - id: `plugin:${key}`, - label: `Attach ${source.title}`, - icon: , - onSelect: () => setActiveKey(key), - }; - }), + sources.map(({ key, source }) => ({ + id: `plugin:${key}`, + label: `Attach ${source.title}`, + icon: , + onSelect: () => setActiveKey(key), + })), [sources], ); if (!active) return { menuItems, picker: null }; diff --git a/packages/app/src/plugins/attachments/pill.tsx b/packages/app/src/plugins/attachments/pill.tsx index 18fb926b59..774a7d359d 100644 --- a/packages/app/src/plugins/attachments/pill.tsx +++ b/packages/app/src/plugins/attachments/pill.tsx @@ -3,19 +3,14 @@ import { withUnistyles } from "react-native-unistyles"; import { AttachmentLabel, AttachmentPill } from "@/components/attachment-pill"; import type { ComposerAttachment } from "@/attachments/types"; import { ICON_SIZE, type Theme } from "@/styles/theme"; -import { resolvePluginIcon } from "../icons"; +import type { PluginSerializableIcon } from "@getpaseo/plugin"; +import { PluginIconView } from "../icons"; import type { PluginResourceComposerAttachment } from "./model"; const iconColorMapping = (theme: Theme) => ({ color: theme.colors.foregroundMuted }); -function ResourceIcon({ - Icon, - color = "", -}: { - Icon: ReturnType; - color?: string; -}) { - return ; +function ResourceIcon({ icon, color = "" }: { icon: PluginSerializableIcon; color?: string }) { + return ; } const ThemedResourceIcon = withUnistyles(ResourceIcon); @@ -39,12 +34,11 @@ export function PluginResourceAttachmentPill({ openLabel, removeLabel, }: PluginResourceAttachmentPillProps) { - const Icon = resolvePluginIcon(attachment.sourceIcon); const handleOpen = useCallback(() => onOpen(attachment), [attachment, onOpen]); const handleRemove = useCallback(() => onRemove(index), [index, onRemove]); const icon = useMemo( - () => , - [Icon], + () => , + [attachment.sourceIcon], ); return ( parsePluginIcon("Plugin button", icon), +}); diff --git a/packages/app/src/plugins/buttons/validation.ts b/packages/app/src/plugins/buttons/validation.ts index 650c21fac2..72e656a271 100644 --- a/packages/app/src/plugins/buttons/validation.ts +++ b/packages/app/src/plugins/buttons/validation.ts @@ -1,7 +1,8 @@ import type { PluginButton, PluginButtonBehavior, PluginButtonIcon } from "@getpaseo/plugin/client"; export interface ButtonValidation { - validateIconName(name: string): void; + /** Returns the normalized icon, or throws naming why the icon is unusable. */ + parseIcon(icon: PluginButtonIcon): PluginButtonIcon; } export function requireButtonId(value: string): string { @@ -29,12 +30,6 @@ function isComponent(value: unknown): boolean { ); } -function validateIcon(icon: PluginButtonIcon, validation: ButtonValidation): void { - if (typeof icon === "string") validation.validateIconName(icon); - else if (!isComponent(icon)) - throw new Error("Plugin button icon must be a Lucide name or component"); -} - function validateBehavior( behavior: PluginButtonBehavior, validation: ButtonValidation, @@ -57,9 +52,9 @@ function validateBehavior( ids.add(item.id); if (item.kind === "separator") return { ...item }; if (item.kind !== "item") throw new Error("Invalid plugin button menu entry"); - if (item.icon !== undefined) validateIcon(item.icon, validation); return { ...item, + icon: item.icon === undefined ? undefined : validation.parseIcon(item.icon), title: requireText(item.title, "menu item title"), visible: optionalBoolean(item.visible, true), disabled: optionalBoolean(item.disabled, false), @@ -83,9 +78,9 @@ export function validateButton( button: PluginButton, validation: ButtonValidation, ): ResolvedPluginButton { - validateIcon(button.icon, validation); return { ...button, + icon: validation.parseIcon(button.icon), title: requireText(button.title, "title"), label: button.label === undefined ? undefined : requireText(button.label, "label"), visible: optionalBoolean(button.visible, true), diff --git a/packages/app/src/plugins/buttons/view.tsx b/packages/app/src/plugins/buttons/view.tsx index 7eae9a046d..1a092c6cf1 100644 --- a/packages/app/src/plugins/buttons/view.tsx +++ b/packages/app/src/plugins/buttons/view.tsx @@ -32,7 +32,7 @@ import { useToast } from "@/contexts/toast-context"; import { useHostRuntimeClient, useHosts } from "@/runtime/host-runtime"; import type { Theme } from "@/styles/theme"; import { createPluginClientStateSource } from "../client-state/source"; -import { Icon } from "../icons"; +import { pluginIconComponent } from "../icons"; import { PluginEnvironmentProvider, PluginPopoverContent, @@ -79,6 +79,7 @@ function ButtonEnvironment({ view, children }: { view: ButtonView; children: Rea function ButtonIcon({ view, icon }: { view: ButtonView; icon: PluginButtonIcon }) { const color = view.props.theme.colors.foregroundMuted; const size = view.entry.placement === "composer" ? 14 : 16; + const Icon = pluginIconComponent(icon); return ( - {typeof icon === "string" ? ( - - ) : ( - renderCustomIcon(icon, view, size, color) - )} + ); } -function renderCustomIcon( - CustomIcon: Exclude, - view: ButtonView, - size: number, - color: string, -) { - return ; -} - function pressButton(view: ButtonView, path: readonly string[]) { void pluginButtonStore.run(view.entry.key, path).catch((error: unknown) => { view.toast.error(error instanceof Error ? error.message : String(error)); diff --git a/packages/app/src/plugins/command-center/contributions.ts b/packages/app/src/plugins/command-center/contributions.ts index be4cb8068a..400e2ded86 100644 --- a/packages/app/src/plugins/command-center/contributions.ts +++ b/packages/app/src/plugins/command-center/contributions.ts @@ -1,7 +1,7 @@ import type { PluginClientStateSource } from "@getpaseo/plugin/client/host"; import type { CommandCenterContribution } from "@/command-center/contributions"; import { getCommandCenterIcon } from "@/command-center/icon"; -import { resolvePluginIcon } from "../icons"; +import { pluginIconComponent } from "../icons"; import { resolvePluginPanelOpenLocation } from "../workspace-panels/locations"; import type { InstalledPlugin } from "../types"; import { createPluginCapabilities, type PluginNavigation } from "../actions"; @@ -83,7 +83,7 @@ export function buildPluginCommandCenterContributions( kind: "action", title: item.title, sectionTitle: plugin.id, - icon: getCommandCenterIcon(resolvePluginIcon(item.icon)), + icon: getCommandCenterIcon(pluginIconComponent(item.icon)), }, run, }); diff --git a/packages/app/src/plugins/evaluate.test.ts b/packages/app/src/plugins/evaluate.test.ts index 310ef5f7b9..cf9b4e049c 100644 --- a/packages/app/src/plugins/evaluate.test.ts +++ b/packages/app/src/plugins/evaluate.test.ts @@ -381,6 +381,72 @@ describe("evaluatePluginClientBundle", () => { ).toEqual([{ id: "open-review", title: "Open review", icon: "Scan", context: "agent" }]); }); + it("registers inline SVG and component icons", () => { + const svg = ''; + const plugin = evaluatePluginClientBundle( + "review", + bundle(` + function ReviewPanel() { return null; } + function BadgeIcon() { return null; } + plugin.addWorkspacePanel({ + id: "review", + title: "Review", + icon: { svg: ${JSON.stringify(` ${svg}\n`)} }, + context: "workspace", + Component: ReviewPanel, + }); + plugin.addCommandCenterItem({ + id: "open-review", + title: "Open review", + icon: BadgeIcon, + context: "global", + onSelect() {}, + }); + plugin.addAttachmentSource({ + id: "issues", + title: "Issues", + icon: { svg: ${JSON.stringify(svg)} }, + pickerTitle: "Attach issue", + searchPlaceholder: "Search", + search: { name: "issues.search", input: {}, output: {} }, + }); + `), + ); + + expect(plugin.workspacePanels[0]?.icon).toEqual({ svg }); + expect(plugin.commandCenterItems[0]?.icon).toHaveProperty("name", "BadgeIcon"); + expect(plugin.attachmentSources[0]?.icon).toEqual({ svg }); + }); + + it.each([ + [ + "workspace panel", + `plugin.addWorkspacePanel({ id: "review", title: "Review", icon: ICON, context: "workspace", Component() { return null; } })`, + "Workspace panel review has an invalid icon: script elements are not allowed", + ], + [ + "Command Center item", + `plugin.addCommandCenterItem({ id: "review", title: "Review", icon: ICON, context: "global", onSelect() {} })`, + "Command Center item review has an invalid icon: script elements are not allowed", + ], + [ + "settings screen", + `plugin.addSettingsScreen({ id: "review", title: "Review", icon: ICON, Component() { return null; } })`, + "Settings screen review has an invalid icon: script elements are not allowed", + ], + [ + "attachment source", + `plugin.addAttachmentSource({ id: "review", title: "Review", icon: ICON, pickerTitle: "Pick", searchPlaceholder: "Search", search: { name: "issues.search", input: {}, output: {} } })`, + "Attachment source review has an invalid icon: script elements are not allowed", + ], + ])("fails the plugin when a %s registers an unsafe SVG", (_kind, registration, message) => { + const icon = JSON.stringify({ svg: "" }); + + expect(() => + evaluatePluginClientBundle("review", bundle(registration.replace("ICON", icon))), + ).toThrow(message); + }); + it("normalizes and validates workspace panel locations", () => { const plugin = evaluatePluginClientBundle( "review", diff --git a/packages/app/src/plugins/evaluate.ts b/packages/app/src/plugins/evaluate.ts index a2703b6ad2..a7d3f04793 100644 --- a/packages/app/src/plugins/evaluate.ts +++ b/packages/app/src/plugins/evaluate.ts @@ -33,7 +33,7 @@ import { } from "@getpaseo/plugin/client"; import type { EvaluatedPlugin, PluginSidebarSection } from "./types"; import type { ComponentType } from "react"; -import { resolvePluginIcon } from "./icons"; +import { parsePluginIcon, parseSerializablePluginIcon } from "./icons"; import { pluginReactNativeRuntime } from "./react-native/runtime"; import { parsePluginThemeContribution } from "./themes"; @@ -199,9 +199,9 @@ export function runPluginClientBundle( if (settingsScreenIds.has(screenId)) throw new Error(`Duplicate settings screen: ${screenId}`); if (!contribution.title.trim()) throw new Error(`Invalid settings screen: ${screenId}`); - resolvePluginIcon(contribution.icon); + const icon = parsePluginIcon(`Settings screen ${screenId}`, contribution.icon); settingsScreenIds.add(screenId); - return register(collector.settingsScreens, { ...contribution, id: screenId }, () => + return register(collector.settingsScreens, { ...contribution, id: screenId, icon }, () => settingsScreenIds.delete(screenId), ); }, @@ -241,12 +241,10 @@ export function runPluginClientBundle( // COMPAT(pluginSidebarAliases): added in v0.11.0, remove after 2027-03-29 addSidebarItem(contribution: PluginSidebarContribution) { const normalizedId = requireId(contribution.id, "sidebar item id"); - if (!contribution.icon.trim()) throw new Error(`Sidebar item ${normalizedId} has no icon`); - resolvePluginIcon(contribution.icon.trim()); const legacy = { id: normalizedId, title: contribution.title.trim(), - icon: contribution.icon.trim(), + icon: parsePluginIcon(`Sidebar item ${normalizedId}`, contribution.icon), surface: requireId(contribution.surface, "sidebar surface id"), }; // Shares the header's ids: the sidebar orders both kinds of item under one key. @@ -262,16 +260,14 @@ export function runPluginClientBundle( throw new Error(`Duplicate workspace panel: ${normalizedId}`); } const title = contribution.title.trim(); - const icon = contribution.icon.trim(); if (!title) throw new Error(`Workspace panel ${normalizedId} has no title`); - if (!icon) throw new Error(`Workspace panel ${normalizedId} has no icon`); + const icon = parsePluginIcon(`Workspace panel ${normalizedId}`, contribution.icon); if (contribution.context !== "workspace" && contribution.context !== "agent") { throw new Error(`Workspace panel ${normalizedId} has invalid context`); } if (typeof contribution.Component !== "function") { throw new Error(`Workspace panel ${normalizedId} is not a component`); } - resolvePluginIcon(icon); const locations = normalizePanelLocations(normalizedId, contribution.locations); workspacePanelIds.add(normalizedId); return register( @@ -292,9 +288,8 @@ export function runPluginClientBundle( throw new Error(`Duplicate Command Center item: ${normalizedId}`); } const title = contribution.title.trim(); - const icon = contribution.icon.trim(); if (!title) throw new Error(`Command Center item ${normalizedId} has no title`); - if (!icon) throw new Error(`Command Center item ${normalizedId} has no icon`); + const icon = parsePluginIcon(`Command Center item ${normalizedId}`, contribution.icon); if ( contribution.context !== "global" && contribution.context !== "workspace" && @@ -305,7 +300,6 @@ export function runPluginClientBundle( if (typeof contribution.onSelect !== "function") { throw new Error(`Command Center item ${normalizedId} has no callback`); } - resolvePluginIcon(icon); commandCenterItemIds.add(normalizedId); return register( collector.commandCenterItems, @@ -350,18 +344,19 @@ export function runPluginClientBundle( throw new Error(`Duplicate attachment source: ${normalizedId}`); } const title = contribution.title.trim(); - const icon = contribution.icon.trim(); const pickerTitle = contribution.pickerTitle.trim(); const searchPlaceholder = contribution.searchPlaceholder.trim(); const method = contribution.search.name.trim(); if (!title) throw new Error(`Attachment source ${normalizedId} has no title`); - if (!icon) throw new Error(`Attachment source ${normalizedId} has no icon`); + const icon = parseSerializablePluginIcon( + `Attachment source ${normalizedId}`, + contribution.icon, + ); if (!pickerTitle) throw new Error(`Attachment source ${normalizedId} has no picker title`); if (!searchPlaceholder) { throw new Error(`Attachment source ${normalizedId} has no search placeholder`); } if (!method) throw new Error(`Attachment source ${normalizedId} has no search RPC`); - resolvePluginIcon(icon); attachmentSourceIds.add(normalizedId); return register( collector.attachmentSources, diff --git a/packages/app/src/plugins/icons.test.ts b/packages/app/src/plugins/icons.test.ts deleted file mode 100644 index 4a4969d6fb..0000000000 --- a/packages/app/src/plugins/icons.test.ts +++ /dev/null @@ -1,18 +0,0 @@ -import { Settings } from "lucide-react-native"; -import { describe, expect, it } from "vitest"; -import { Icon } from "./icons"; - -describe("Icon", () => { - it("renders a host Lucide icon with the requested presentation", () => { - expect(Icon({ name: "Settings", size: 18, color: "#123456" })).toMatchObject({ - type: Settings, - props: { size: 18, color: "#123456" }, - }); - }); - - it("renders nothing for an unknown icon name", () => { - expect(Icon({ name: "NotALucideIcon" })).toBeNull(); - expect(Icon({ name: "Icon" })).toBeNull(); - expect(Icon({ name: "createLucideIcon" })).toBeNull(); - }); -}); diff --git a/packages/app/src/plugins/icons.test.tsx b/packages/app/src/plugins/icons.test.tsx new file mode 100644 index 0000000000..0fa189d137 --- /dev/null +++ b/packages/app/src/plugins/icons.test.tsx @@ -0,0 +1,104 @@ +import { Settings } from "lucide-react-native"; +import React, { isValidElement, type ReactElement, type ReactNode } from "react"; +import { SvgXml } from "react-native-svg"; +import { describe, expect, it } from "vitest"; +import type { PluginIconProps } from "@getpaseo/plugin"; +import { Icon, parsePluginIcon, parseSerializablePluginIcon, PluginIconView } from "./icons"; + +const SVG = ''; +const SVG_ICON = { svg: SVG }; + +const GLYPHS = new Set([Settings, SvgXml]); + +/** Expands function components down to what reaches the screen: a Lucide glyph, SvgXml, or DOM. */ +function draw(node: ReactNode): ReactElement | null { + if (!isValidElement(node)) return null; + const { type } = node; + if (typeof type !== "function" || GLYPHS.has(type)) return node; + return draw((type as (props: unknown) => ReactNode)(node.props)); +} + +function BadgeIcon({ size, color }: PluginIconProps) { + return ; +} + +describe("PluginIconView", () => { + it("draws a Lucide name as that Lucide icon", () => { + expect(draw()).toMatchObject({ + type: Settings, + props: { size: 18, color: "#123456" }, + }); + }); + + it("draws inline SVG sized to the surface, with color reaching currentColor", () => { + expect(draw()).toMatchObject({ + type: SvgXml, + props: { xml: SVG, width: 18, height: 18, color: "#123456" }, + }); + }); + + it("draws a component with the surface's size and color", () => { + expect(draw()).toMatchObject({ + type: "span", + props: { "data-size": 18, "data-color": "#123456" }, + }); + }); +}); + +describe("parsePluginIcon", () => { + it("normalizes each icon form", () => { + expect(parsePluginIcon("Workspace panel files", " Settings ")).toBe("Settings"); + expect(parsePluginIcon("Workspace panel files", { svg: `\n${SVG}\n` })).toEqual({ svg: SVG }); + expect(parsePluginIcon("Workspace panel files", BadgeIcon)).toBe(BadgeIcon); + }); + + it.each([ + ["", "Workspace panel files has no icon"], + [ + "NotALucideIcon", + 'Workspace panel files has an invalid icon: unknown Lucide icon "NotALucideIcon"', + ], + [ + { svg: "" }, + "Workspace panel files has an invalid icon: script elements are not allowed", + ], + [{ svg: "hello" }, "Workspace panel files has an invalid icon: not an SVG document"], + [ + { path: "icon.svg" }, + "Workspace panel files has an invalid icon: expected a Lucide icon name, { svg }, or a component", + ], + ])("rejects %j", (icon, message) => { + expect(() => parsePluginIcon("Workspace panel files", icon as never)).toThrow(message); + }); + + it("refuses a component where the icon is stored as data", () => { + expect(() => + parseSerializablePluginIcon("Attachment source issues", BadgeIcon as never), + ).toThrow( + "Attachment source issues has an invalid icon: expected a Lucide icon name or { svg }", + ); + }); +}); + +describe("Icon", () => { + it("renders a host Lucide icon by name with the requested presentation", () => { + expect(draw(Icon({ name: "Settings", size: 18, color: "#123456" }))).toMatchObject({ + type: Settings, + props: { size: 18, color: "#123456" }, + }); + }); + + it("renders a plugin's own SVG through the icon prop", () => { + expect(draw(Icon({ icon: { svg: SVG }, size: 18, color: "#123456" }))).toMatchObject({ + type: SvgXml, + props: { xml: SVG, width: 18, color: "#123456" }, + }); + }); + + it("renders nothing for an unusable icon", () => { + expect(Icon({ name: "NotALucideIcon" })).toBeNull(); + expect(Icon({ name: "Icon" })).toBeNull(); + expect(Icon({ name: "createLucideIcon" })).toBeNull(); + expect(Icon({ icon: { svg: '' } })).toBeNull(); + }); +}); diff --git a/packages/app/src/plugins/icons.ts b/packages/app/src/plugins/icons.ts index 3c5ec581ce..ba67d8fa35 100644 --- a/packages/app/src/plugins/icons.ts +++ b/packages/app/src/plugins/icons.ts @@ -1,24 +1,150 @@ -import { createElement, type ReactElement } from "react"; +import { createElement, type ComponentType, type ReactElement } from "react"; import * as LucideIcons from "lucide-react-native"; -import type { PluginIconProps } from "@getpaseo/plugin/client"; import type { LucideIcon } from "lucide-react-native"; +import { + findSvgIconProblem, + type PluginIconProps, + type PluginSerializableIcon, + type PluginSvgIcon, +} from "@getpaseo/plugin"; +import type { PluginIcon } from "@getpaseo/plugin/client"; +import type { IconProps } from "@getpaseo/plugin/client/react-native"; +import { SvgIcon } from "@/components/provider-icons"; -function findPluginIcon(name: string): LucideIcon | null { +/** Host surfaces may thin a Lucide stroke; SVG and plugin components ignore it. */ +type HostIconProps = PluginIconProps & { strokeWidth?: number }; +/** A host-drawn icon. A plain function, so it stands in for any plugin icon component type. */ +type HostIcon = (props: HostIconProps) => ReactElement | null; + +const lucideIconComponents = new Map(); +const svgIconComponents = new Map(); + +function findLucideIcon(name: string): LucideIcon | null { const candidate = Reflect.get(LucideIcons, name); if (candidate === LucideIcons.Icon || candidate === LucideIcons.createLucideIcon) return null; - const isComponent = - typeof candidate === "function" || - (typeof candidate === "object" && candidate !== null && "$$typeof" in candidate); - return isComponent ? (candidate as LucideIcon) : null; + return isComponent(candidate) ? (candidate as LucideIcon) : null; } -export function resolvePluginIcon(name: string): LucideIcon { - const icon = findPluginIcon(name); - if (!icon) throw new Error(`Unknown Lucide icon: ${name}`); +function isComponent(value: unknown): boolean { + return ( + typeof value === "function" || + (typeof value === "object" && value !== null && "$$typeof" in value) + ); +} + +function isSvgIcon(icon: unknown): icon is PluginSvgIcon { + return ( + typeof icon === "object" && + icon !== null && + !("$$typeof" in icon) && + typeof Reflect.get(icon, "svg") === "string" + ); +} + +function isComponentIcon( + icon: PluginIcon, +): icon is ComponentType { + return isComponent(icon); +} + +function invalidIcon(owner: string, reason: string): Error { + return new Error(`${owner} has an invalid icon: ${reason}`); +} + +/** Validates an icon that is stored with the data it labels. Returns the normalized icon. */ +export function parseSerializablePluginIcon( + owner: string, + icon: PluginSerializableIcon, +): PluginSerializableIcon { + if (typeof icon === "string") { + const name = icon.trim(); + if (!name) throw new Error(`${owner} has no icon`); + if (!findLucideIcon(name)) throw invalidIcon(owner, `unknown Lucide icon "${name}"`); + return name; + } + if (!isSvgIcon(icon)) throw invalidIcon(owner, "expected a Lucide icon name or { svg }"); + const svg = icon.svg.trim(); + const problem = findSvgIconProblem(svg); + if (problem) throw invalidIcon(owner, problem); + return { svg }; +} + +/** Validates a contribution's icon once, at registration. Rendering trusts the result. */ +export function parsePluginIcon( + owner: string, + icon: PluginIcon, +): PluginIcon { + if (isComponentIcon(icon)) return icon; + if (typeof icon !== "string" && !isSvgIcon(icon)) { + throw invalidIcon(owner, "expected a Lucide icon name, { svg }, or a component"); + } + return parseSerializablePluginIcon(owner, icon); +} + +function MissingIcon(): null { + return null; +} + +function createLucideIcon(name: string, Lucide: LucideIcon): HostIcon { + function PluginLucideIcon({ size, color, strokeWidth }: HostIconProps) { + return createElement(Lucide, { size, color, strokeWidth }); + } + PluginLucideIcon.displayName = `PluginLucideIcon(${name})`; + return PluginLucideIcon; +} + +function lucideIconComponent(name: string): HostIcon { + const cached = lucideIconComponents.get(name); + if (cached) return cached; + const Lucide = findLucideIcon(name); + if (!Lucide) return MissingIcon; + const icon = createLucideIcon(name, Lucide); + lucideIconComponents.set(name, icon); return icon; } -export function Icon({ name, size, color }: PluginIconProps): ReactElement | null { - const icon = findPluginIcon(name); - return icon ? createElement(icon, { size, color }) : null; +function svgIconComponent(svg: string): HostIcon { + const cached = svgIconComponents.get(svg); + if (cached) return cached; + function PluginSvgIcon({ size, color }: PluginIconProps) { + return createElement(SvgIcon, { svg, size, color }); + } + svgIconComponents.set(svg, PluginSvgIcon); + return PluginSvgIcon; +} + +/** + * A stable component for a registered icon, for surfaces that take an icon component. Lucide and + * SVG icons draw from `size` and `color` only; a plugin component receives every prop. + */ +export function pluginIconComponent( + icon: PluginIcon, +): ComponentType { + if (typeof icon === "string") return lucideIconComponent(icon); + if (isSvgIcon(icon)) return svgIconComponent(icon.svg); + return icon; +} + +export interface PluginIconViewProps extends PluginIconProps { + icon: PluginIcon; +} + +/** Draws a registered plugin icon. `color` tints Lucide icons and `currentColor` in SVG. */ +export function PluginIconView({ icon, size, color }: PluginIconViewProps): ReactElement { + return createElement(pluginIconComponent(icon), { size, color }); +} + +function isRenderable(icon: PluginIcon): boolean { + if (typeof icon === "string") return findLucideIcon(icon) !== null; + if (isSvgIcon(icon)) return findSvgIconProblem(icon.svg) === null; + return isComponent(icon); +} + +/** The kit `Icon`. Plugin code passes it anything, so an unusable icon renders nothing. */ +export function Icon(props: IconProps): ReactElement | null { + const icon = props.icon === undefined ? props.name : props.icon; + if (!isRenderable(icon)) return null; + const size = props.size ?? 24; + const color = props.color ?? "currentColor"; + return createElement(PluginIconView, { icon, size, color }); } diff --git a/packages/app/src/plugins/sidebar-groups.ts b/packages/app/src/plugins/sidebar-groups.ts index c764a53dcc..2d4411acad 100644 --- a/packages/app/src/plugins/sidebar-groups.ts +++ b/packages/app/src/plugins/sidebar-groups.ts @@ -9,6 +9,7 @@ import type { PluginSidebarItemContribution, PluginSidebarSection, } from "./types"; +import type { PluginIcon } from "@getpaseo/plugin/client"; export interface PluginSidebarTarget { plugin: InstalledPlugin; @@ -36,7 +37,7 @@ export type PluginSidebarGroup = | (PluginSidebarGroupBase & { kind: "item"; targets: PluginSidebarTarget[] }) | (PluginSidebarGroupBase & { kind: "legacy"; - icon: string; + icon: PluginIcon; targets: PluginLegacySidebarTarget[]; }); diff --git a/packages/app/src/plugins/sidebar-items/kit.tsx b/packages/app/src/plugins/sidebar-items/kit.tsx index 5796d572ca..6b29cbea42 100644 --- a/packages/app/src/plugins/sidebar-items/kit.tsx +++ b/packages/app/src/plugins/sidebar-items/kit.tsx @@ -1,16 +1,12 @@ -import type { SidebarIcon, SidebarRowProps } from "@getpaseo/plugin/client/ui"; -import { useCallback, useEffect, useRef } from "react"; +import type { SidebarRowProps } from "@getpaseo/plugin/client/ui"; +import { useCallback, useEffect, useMemo, useRef } from "react"; import { View } from "react-native"; import { StyleSheet } from "react-native-unistyles"; import { SidebarHeaderRow } from "@/components/sidebar/sidebar-header-row"; import { SidebarSeparator as AppSidebarSeparator } from "@/components/sidebar/sidebar-separator"; -import { resolvePluginIcon } from "../icons"; +import { parsePluginIcon, pluginIconComponent } from "../icons"; import { useSidebarItemFrame } from "./frame"; -function resolveIcon(icon: SidebarIcon) { - return typeof icon === "string" ? resolvePluginIcon(icon) : icon; -} - /** * An item may render several rows. Any press inside a row, on the row or on its trailing content, * makes that row the popover anchor: the capture-phase responder check runs before the pressed @@ -29,6 +25,11 @@ export function SidebarRow({ id, icon, label, onPress, active, trailing }: Sideb anchorTo(rowRef.current); return false; }, [anchorTo]); + // Rows get their icon at render, not registration, so an invalid icon throws to the item's boundary. + const iconComponent = useMemo( + () => (icon ? pluginIconComponent(parsePluginIcon("Sidebar row", icon)) : null), + [icon], + ); // Keyboard activation skips the responder system, so the row's own press anchors as well. const handlePress = useCallback(() => { anchorTo(rowRef.current); @@ -37,7 +38,7 @@ export function SidebarRow({ id, icon, label, onPress, active, trailing }: Sideb return ( ; - color?: string; -}) { - return ; +function PluginHeaderIcon({ icon, color = "" }: { icon: PluginIcon; color?: string }) { + return ; } const ThemedPluginHeaderIcon = withUnistyles(PluginHeaderIcon); @@ -162,7 +156,7 @@ export function PluginSurfaceScreen() { : (sidebarItem?.title ?? (pluginId || "Plugin")), [params, pluginId, sidebarItem, surface], ); - const Icon = sidebarItem ? resolvePluginIcon(sidebarItem.icon) : null; + const icon = sidebarItem?.icon ?? null; const close = useCallback(() => { if (router.canGoBack()) router.back(); else router.replace(`/h/${encodeURIComponent(serverId)}`); @@ -172,15 +166,15 @@ export function PluginSurfaceScreen() { const headerLeft = useMemo( () => ( <> - {Icon ? ( + {icon ? ( - + ) : null} {title} ), - [Icon, title], + [icon, title], ); const hostFilter = useMemo( () => diff --git a/packages/app/src/plugins/timeline/view.test.tsx b/packages/app/src/plugins/timeline/view.test.tsx index d915216105..ff3ba9fd6b 100644 --- a/packages/app/src/plugins/timeline/view.test.tsx +++ b/packages/app/src/plugins/timeline/view.test.tsx @@ -33,7 +33,7 @@ vi.mock("../client-runtime", () => ({ })); vi.mock("../icons", () => ({ Icon: () => null, - resolvePluginIcon: () => () => null, + pluginIconComponent: () => () => null, })); import { pluginRegistry } from "../registry"; diff --git a/packages/app/src/plugins/workspace-panels/panel.tsx b/packages/app/src/plugins/workspace-panels/panel.tsx index 998f7e90ff..48a83686be 100644 --- a/packages/app/src/plugins/workspace-panels/panel.tsx +++ b/packages/app/src/plugins/workspace-panels/panel.tsx @@ -17,7 +17,7 @@ import { normalizeWorkspaceOpaqueId } from "@/utils/workspace-identity"; import { usePluginHostNavigation } from "../host-navigation"; import { createPluginClientStateSource } from "../client-state/source"; import { toPluginTheme } from "../theme"; -import { resolvePluginIcon } from "../icons"; +import { pluginIconComponent } from "../icons"; import { useInstalledPlugin } from "../registry"; import { PluginInstallationProvider } from "../installation-provider"; import { SurfaceErrorBoundary } from "../surface-error-boundary"; @@ -144,7 +144,7 @@ function usePluginPanelDescriptor( subtitle: target.pluginId, tooltip: panel.title, titleState: "ready", - icon: resolvePluginIcon(panel.icon), + icon: pluginIconComponent(panel.icon), statusBucket: null, }; } diff --git a/packages/app/src/screens/settings/sidebar/sidebar-nav-section.tsx b/packages/app/src/screens/settings/sidebar/sidebar-nav-section.tsx index 7952a2b1ee..21633e7a10 100644 --- a/packages/app/src/screens/settings/sidebar/sidebar-nav-section.tsx +++ b/packages/app/src/screens/settings/sidebar/sidebar-nav-section.tsx @@ -1,4 +1,4 @@ -import { useCallback, useMemo, type ReactElement } from "react"; +import { useCallback, useMemo, type ComponentType, type ReactElement } from "react"; import { Text, View } from "react-native"; import { useTranslation } from "react-i18next"; import type { TFunction } from "i18next"; @@ -26,7 +26,7 @@ import { type SidebarNavItem, type SidebarSection, } from "@/sidebar-nav/model"; -import { resolvePluginIcon } from "@/plugins/icons"; +import { pluginIconComponent } from "@/plugins/icons"; import { useSidebarNavItems } from "@/sidebar-nav/use-sidebar-nav-items"; import { settingsStyles } from "@/styles/settings"; import { ICON_SIZE, type Theme } from "@/styles/theme"; @@ -50,15 +50,17 @@ const BUILTIN_ICONS: Record = { /** Plugin items register no icon, so they share this one; a legacy `addSidebarItem` keeps its own. */ const PLUGIN_ICON = Blocks; -function NavIcon({ Icon, color = "" }: { Icon: LucideIcon; color?: string }) { +type NavIconComponent = ComponentType<{ size: number; color: string }>; + +function NavIcon({ Icon, color = "" }: { Icon: NavIconComponent; color?: string }) { return ; } const ThemedNavIcon = withUnistyles(NavIcon); -function navItemIcon(item: SidebarNavItem): LucideIcon { +function navItemIcon(item: SidebarNavItem): NavIconComponent { if (item.kind === "builtin") return BUILTIN_ICONS[item.id]; - return item.group.kind === "legacy" ? resolvePluginIcon(item.group.icon) : PLUGIN_ICON; + return item.group.kind === "legacy" ? pluginIconComponent(item.group.icon) : PLUGIN_ICON; } function navItemLabel(t: TFunction, item: SidebarNavItem): string { diff --git a/packages/app/src/workspace-tabs/launcher/index.tsx b/packages/app/src/workspace-tabs/launcher/index.tsx index ea983b4bd8..afbefcb042 100644 --- a/packages/app/src/workspace-tabs/launcher/index.tsx +++ b/packages/app/src/workspace-tabs/launcher/index.tsx @@ -11,7 +11,7 @@ import { useTranslation } from "react-i18next"; import { Globe, SquarePen, SquareTerminal } from "lucide-react-native"; import invariant from "tiny-invariant"; import { useDaemonConfig } from "@/hooks/use-daemon-config"; -import { resolvePluginIcon } from "@/plugins/icons"; +import { pluginIconComponent } from "@/plugins/icons"; import { useInstalledPlugins } from "@/plugins/registry"; import { pluginPanelSupportsLocation } from "@/plugins/workspace-panels/locations"; import { buildSettingsHostSectionRoute } from "@/utils/host-routes"; @@ -212,7 +212,7 @@ export function useWorkspaceTabLaunchCatalog(input: { pluginItems.push({ id: `plugin:${plugin.id}:${panel.id}`, label: panel.title, - Icon: resolvePluginIcon(panel.icon), + Icon: pluginIconComponent(panel.icon), disabled: false, panelKind: "plugin", launch: launchSelection(selection), diff --git a/packages/plugin/src/client/buttons.ts b/packages/plugin/src/client/buttons.ts index f5272e7ae4..76e5531143 100644 --- a/packages/plugin/src/client/buttons.ts +++ b/packages/plugin/src/client/buttons.ts @@ -1,16 +1,16 @@ import type { ComponentType } from "react"; -import type { PluginHostProps } from "./contracts.js"; +import type { PluginIconProps } from "../icons.js"; +import type { PluginHostProps, PluginIcon } from "./contracts.js"; export type PluginButtonContext = | { context: "workspace"; workspaceId: string } | { context: "agent"; workspaceId: string; agentId: string }; -export type PluginButtonIconProps = PluginHostProps & - PluginButtonContext & { size: number; color: string }; +export type PluginButtonIconProps = PluginHostProps & PluginButtonContext & PluginIconProps; export type PluginButtonContentProps = PluginHostProps & PluginButtonContext & { close(): void }; -export type PluginButtonIcon = string | ComponentType; +export type PluginButtonIcon = PluginIcon; export type PluginButtonBehavior = | { kind: "action"; onPress(): void | Promise } diff --git a/packages/plugin/src/client/contracts.ts b/packages/plugin/src/client/contracts.ts index 5bc82d8a58..28790e77bb 100644 --- a/packages/plugin/src/client/contracts.ts +++ b/packages/plugin/src/client/contracts.ts @@ -17,6 +17,7 @@ import type { PluginTimelineTransformResult, PluginCleanup, } from "../contracts.js"; +import type { PluginIconProps, PluginSerializableIcon } from "../icons.js"; export interface PluginHostProps { theme: PluginTheme; @@ -87,11 +88,13 @@ export interface PluginSidebarItemContribution { Component: ComponentType; } -export interface PluginIconProps { - name: string; - size?: number; - color?: string; -} +/** + * A Lucide icon name, inline SVG markup, or a component. Components receive the surface's size + * and color; buttons widen the props with their host and target context. + */ +export type PluginIcon = + | PluginSerializableIcon + | ComponentType; export type PluginPanelLocation = "workspace" | "explorer"; @@ -102,7 +105,7 @@ export interface PluginOpenPanelOptions { interface PluginWorkspacePanelBase { id: string; title: string; - icon: string; + icon: PluginIcon; locations?: readonly PluginPanelLocation[]; } @@ -168,7 +171,7 @@ export type PluginWorkspacePanelContribution = export interface PluginSettingsScreenContribution { id: string; title: string; - icon: string; + icon: PluginIcon; Component: ComponentType; } @@ -190,7 +193,7 @@ export interface PluginSurfaceContribution { export interface PluginSidebarContribution { id: string; title: string; - icon: string; + icon: PluginIcon; surface: string; } @@ -259,7 +262,7 @@ export interface PluginAgentCommandContext extends PluginCommandCapabilities { interface PluginCommandCenterItemBase { id: string; title: string; - icon: string; + icon: PluginIcon; keywords?: readonly string[]; } diff --git a/packages/plugin/src/client/index.ts b/packages/plugin/src/client/index.ts index 810462354f..93d57d0cc1 100644 --- a/packages/plugin/src/client/index.ts +++ b/packages/plugin/src/client/index.ts @@ -8,7 +8,7 @@ export type { PluginScreenLocation, PluginSidebarItemProps, PluginSidebarItemContribution, - PluginIconProps, + PluginIcon, PluginPanelLocation, PluginOpenPanelOptions, PluginWorkspacePanelProps, @@ -45,6 +45,7 @@ export type { PluginComposerPillContribution, PluginHeaderButtonContribution, } from "./buttons.js"; +export type { PluginIconProps, PluginSerializableIcon, PluginSvgIcon } from "../icons.js"; export { usePaseo } from "./paseo-context.js"; export { useAgent, useWorkspace } from "./client-state.js"; export { useRpc } from "./rpc-context.js"; diff --git a/packages/plugin/src/client/react-native.ts b/packages/plugin/src/client/react-native.ts index ea196c433f..f5862b31d1 100644 --- a/packages/plugin/src/client/react-native.ts +++ b/packages/plugin/src/client/react-native.ts @@ -17,7 +17,8 @@ import type { TextInput as NativeTextInput, TextInputProps, } from "react-native"; -import type { PluginIconProps } from "./contracts.js"; +import type { PluginIconProps } from "../icons.js"; +import type { PluginIcon } from "./contracts.js"; export interface ModalProps { title: string; @@ -53,12 +54,16 @@ export interface ToastApi { error(message: string): void; } -export declare const Icon: ComponentType; +/** Renders a Lucide icon by `name`, or any plugin icon by `icon`. An unusable icon renders nothing. */ +export type IconProps = Partial & + ({ name: string; icon?: never } | { icon: PluginIcon; name?: never }); + +export declare const Icon: ComponentType; export declare const Modal: ModalComponent; export declare function useToast(): ToastApi; export declare function useRevealedText(text: string, phase: "streaming" | "complete"): string; -export type { PluginIconProps } from "./contracts.js"; +export type { PluginIconProps } from "../icons.js"; /** React Native scrolling with the host's sheet gestures when rendered inside a sheet. */ export declare const ScrollView: ForwardRefExoticComponent< diff --git a/packages/plugin/src/client/ui.ts b/packages/plugin/src/client/ui.ts index 6686d8292b..8d5e3ff686 100644 --- a/packages/plugin/src/client/ui.ts +++ b/packages/plugin/src/client/ui.ts @@ -1,4 +1,5 @@ import type { ComponentType, ReactNode, Ref } from "react"; +import type { PluginIcon } from "./contracts.js"; export interface SettingsSectionProps { title: string; @@ -64,14 +65,14 @@ export interface ExternalLinkProps { } export declare const ExternalLink: ComponentType; -export type SidebarIcon = string | ComponentType<{ size: number; color: string }>; +export type SidebarIcon = PluginIcon; export interface SidebarRowProps { /** * Tells rows of one item apart when the item renders several: "bot-2". Unique within the item. * Omit it when the item renders one row. */ id?: string; - /** A Lucide icon name or a component. */ + /** A Lucide icon name, inline SVG, or a component. */ icon?: SidebarIcon; /** Defaults to the item's registered title. */ label?: string; diff --git a/packages/plugin/src/contracts.ts b/packages/plugin/src/contracts.ts index 98df0758a6..6694f05aea 100644 --- a/packages/plugin/src/contracts.ts +++ b/packages/plugin/src/contracts.ts @@ -1,4 +1,5 @@ import type { JsonValue } from "@getpaseo/protocol/agent-types"; +import type { PluginSerializableIcon } from "./icons.js"; import type { PluginRpcContract } from "./rpc.js"; export interface PluginTheme { @@ -73,7 +74,7 @@ export interface PluginThemeContribution { export interface PluginAttachmentSourceContribution { id: string; title: string; - icon: string; + icon: PluginSerializableIcon; pickerTitle: string; searchPlaceholder: string; search: PluginRpcContract; diff --git a/packages/plugin/src/icons.test.ts b/packages/plugin/src/icons.test.ts new file mode 100644 index 0000000000..fd8ddbc9fb --- /dev/null +++ b/packages/plugin/src/icons.test.ts @@ -0,0 +1,53 @@ +import { describe, expect, it } from "vitest"; +import { findSvgIconProblem } from "./icons.js"; + +describe("findSvgIconProblem", () => { + it.each([ + ["a plain SVG", ''], + ["leading whitespace", '\n '], + [ + "a fragment reference", + '', + ], + ["currentColor fills", ''], + ])("accepts %s", (_name, svg) => { + expect(findSvgIconProblem(svg)).toBeNull(); + }); + + it.each([ + ["a non-SVG document", "hello", "not an SVG document"], + ["an element", "", "not an SVG document"], + ["a script", "", "script elements are not allowed"], + ["a foreign object", "", "foreignObject elements are not allowed"], + ["a style", "", "style elements are not allowed"], + [ + "an event handler", + '', + "event-handler attributes are not allowed", + ], + [ + "a javascript URL", + '', + "javascript URLs are not allowed", + ], + [ + "an external href", + '', + "external href references are not allowed", + ], + [ + "an external xlink:href", + "", + "external href references are not allowed", + ], + ["markup over 64 KiB", `${" ".repeat(64 * 1024)}`, "exceeds 64 KiB"], + ])("rejects %s", (_name, svg, reason) => { + expect(findSvgIconProblem(svg)).toBe(reason); + }); + + it("measures the size in UTF-8 bytes", () => { + const multibyte = "é".repeat(32 * 1024); + + expect(findSvgIconProblem(`${multibyte}`)).toBe("exceeds 64 KiB"); + }); +}); diff --git a/packages/plugin/src/icons.ts b/packages/plugin/src/icons.ts new file mode 100644 index 0000000000..558aa2497d --- /dev/null +++ b/packages/plugin/src/icons.ts @@ -0,0 +1,38 @@ +/** What a component icon receives from the surface that draws it. */ +export interface PluginIconProps { + size: number; + color: string; +} + +/** Inline SVG markup. Paseo validates it when the contribution registers. */ +export interface PluginSvgIcon { + svg: string; +} + +/** An icon that can be stored or sent: a Lucide icon name, or inline SVG. */ +export type PluginSerializableIcon = string | PluginSvgIcon; + +export const PLUGIN_SVG_ICON_MAX_BYTES = 64 * 1024; + +const EXTERNAL_HREF = /\s(?:href|xlink:href)\s*=\s*(?:(["'])(.*?)\1|([^\s>]+))/gi; + +/** + * Why Paseo refuses to render this SVG, or null when it is a self-contained document. + * The daemon applies it to provider and usage-source icon files; the app to inline plugin icons. + */ +export function findSvgIconProblem(svg: string): string | null { + if (new TextEncoder().encode(svg).byteLength > PLUGIN_SVG_ICON_MAX_BYTES) { + return "exceeds 64 KiB"; + } + if (!/^\s*)/i.test(svg)) return "not an SVG document"; + if (/)/i.test(svg)) return "script elements are not allowed"; + if (/)/i.test(svg)) return "foreignObject elements are not allowed"; + if (/)/i.test(svg)) return "style elements are not allowed"; + if (/\son[a-z0-9_-]*\s*=/i.test(svg)) return "event-handler attributes are not allowed"; + if (/javascript\s*:/i.test(svg)) return "javascript URLs are not allowed"; + for (const match of svg.matchAll(EXTERNAL_HREF)) { + const href = match[2] ?? match[3] ?? ""; + if (!href.startsWith("#")) return "external href references are not allowed"; + } + return null; +} diff --git a/packages/plugin/src/index.ts b/packages/plugin/src/index.ts index 48deede303..29f5e72089 100644 --- a/packages/plugin/src/index.ts +++ b/packages/plugin/src/index.ts @@ -20,3 +20,10 @@ export { type PluginAttachmentSearchPayload, } from "./attachments.js"; export { defineRpc, type PluginRpcContract, type RpcInput, type RpcOutput } from "./rpc.js"; +export { + findSvgIconProblem, + PLUGIN_SVG_ICON_MAX_BYTES, + type PluginIconProps, + type PluginSerializableIcon, + type PluginSvgIcon, +} from "./icons.js"; diff --git a/packages/server/src/server/plugins/compiler.test.ts b/packages/server/src/server/plugins/compiler.test.ts index fc86f85db3..6f694fbaa3 100644 --- a/packages/server/src/server/plugins/compiler.test.ts +++ b/packages/server/src/server/plugins/compiler.test.ts @@ -534,6 +534,25 @@ export type Value = string;`, expect(clientBundle).not.toContain("React.createElement"); }); + it("imports an SVG file from a runtime directory as its markup", async () => { + const entries = await createSplitPlugin(); + const svg = ''; + await writeFile(path.join(entries.directory, "client", "icon.svg"), svg); + await writeFile( + entries.client, + `import icon from "./client/icon.svg"; +export default function contribute(client) { + client.addCommandCenterItem({ id: "open", title: "Open", icon: { svg: icon }, context: "global", onSelect() {} }); + return () => undefined; +}`, + ); + const { clientBundle } = await compilePlugin(entries); + const registered: unknown[] = []; + const exports = new Function(`return ${clientBundle}`)()(() => undefined); + exports.default({ addCommandCenterItem: (item: unknown) => registered.push(item) }); + expect(registered).toMatchObject([{ icon: { svg } }]); + }); + it("lowers async callbacks before Hermes evaluates the client bundle", async () => { const entries = await createSplitPlugin(); await writeFile( diff --git a/packages/server/src/server/plugins/compiler.ts b/packages/server/src/server/plugins/compiler.ts index b48449bb50..4cf89a902c 100644 --- a/packages/server/src/server/plugins/compiler.ts +++ b/packages/server/src/server/plugins/compiler.ts @@ -393,6 +393,8 @@ async function compileTarget(entryPath: string, target: PluginBuildTarget): Prom bundle: true, format: "cjs", jsx: "automatic", + // `import icon from "./icon.svg"` yields the markup for an inline `{ svg }` icon. + loader: { ".svg": "text" }, platform: target === "server" ? "node" : "neutral", target: target === "server" ? "node20" : "es2020", // The neutral platform reads no package.json entry fields, so packages without diff --git a/packages/server/src/server/plugins/provider-icon.test.ts b/packages/server/src/server/plugins/provider-icon.test.ts index 4faf9d289c..f8040ec869 100644 --- a/packages/server/src/server/plugins/provider-icon.test.ts +++ b/packages/server/src/server/plugins/provider-icon.test.ts @@ -29,18 +29,14 @@ describe("readPluginProviderIcon", () => { }); test.each([ - ["non-SVG document", "hello", "file is not an SVG document"], - ["script", "", "script elements"], - ["foreign object", "", "foreignObject elements"], - ["style", "", "style elements"], - ["event handler", '', "event-handler attributes"], - ["javascript URL", '', "javascript URLs"], + ["non-SVG document", "hello", "not an SVG document"], + ["script", "", "script elements are not allowed"], ["external href", '', "external href"], - ])("rejects %s", async (_name, svg, reason) => { + ])("rejects %s with the shared SVG rules", async (_name, svg, reason) => { const directory = await writeIcon(svg); await expect(readPluginProviderIcon(directory, "icon.svg")).rejects.toThrow( - `icon.svg": ${reason}`, + `Invalid plugin provider icon "icon.svg": ${reason}`, ); }); @@ -78,7 +74,7 @@ describe("readPluginProviderIcon", () => { const directory = await writeIcon(`${" ".repeat(64 * 1024)}`); await expect(readPluginProviderIcon(directory, "icon.svg")).rejects.toThrow( - "file exceeds 64 KiB", + `Invalid plugin provider icon "icon.svg": exceeds 64 KiB`, ); }); }); diff --git a/packages/server/src/server/plugins/provider-icon.ts b/packages/server/src/server/plugins/provider-icon.ts index 9a1e3f6714..af33ea82f5 100644 --- a/packages/server/src/server/plugins/provider-icon.ts +++ b/packages/server/src/server/plugins/provider-icon.ts @@ -1,7 +1,6 @@ import { readFile, realpath, stat } from "node:fs/promises"; import path from "node:path"; - -const MAX_ICON_BYTES = 64 * 1024; +import { findSvgIconProblem } from "@getpaseo/plugin"; export async function readPluginProviderIcon( pluginDirectory: string, @@ -20,10 +19,10 @@ export async function readPluginProviderIcon( if (!iconStat.isFile()) { throw iconError(iconPath, "file does not exist or is not a regular file"); } - if (iconStat.size > MAX_ICON_BYTES) throw iconError(iconPath, "file exceeds 64 KiB"); const svg = await readFile(resolvedIcon, "utf8"); - validateSvg(iconPath, svg); + const problem = findSvgIconProblem(svg); + if (problem) throw iconError(iconPath, problem); return svg; } @@ -38,27 +37,6 @@ function assertInsidePluginDirectory( if (escapesDirectory) throw iconError(iconPath, "path leaves the plugin directory"); } -function validateSvg(iconPath: string, svg: string): void { - if (!/^\s*)/i.test(svg)) throw iconError(iconPath, "file is not an SVG document"); - if (/)/i.test(svg)) throw iconError(iconPath, "script elements are not allowed"); - if (/)/i.test(svg)) { - throw iconError(iconPath, "foreignObject elements are not allowed"); - } - if (/)/i.test(svg)) throw iconError(iconPath, "style elements are not allowed"); - if (/\son[a-z0-9_-]*\s*=/i.test(svg)) { - throw iconError(iconPath, "event-handler attributes are not allowed"); - } - if (/javascript\s*:/i.test(svg)) throw iconError(iconPath, "javascript URLs are not allowed"); - - const hrefPattern = /\s(?:href|xlink:href)\s*=\s*(?:(["'])(.*?)\1|([^\s>]+))/gi; - for (const match of svg.matchAll(hrefPattern)) { - const href = match[2] ?? match[3] ?? ""; - if (!href.startsWith("#")) { - throw iconError(iconPath, "external href references are not allowed"); - } - } -} - function iconError(iconPath: string, reason: string): Error { return new Error(`Invalid plugin provider icon "${iconPath}": ${reason}`); } diff --git a/plugin-examples/local-plugin/client/icons.ts b/plugin-examples/local-plugin/client/icons.ts new file mode 100644 index 0000000000..553838556a --- /dev/null +++ b/plugin-examples/local-plugin/client/icons.ts @@ -0,0 +1,5 @@ +/** Inline SVG icon. `currentColor` follows the surface's icon color. */ +export const counterIcon = ` + + +`; diff --git a/plugin-examples/local-plugin/index.client.tsx b/plugin-examples/local-plugin/index.client.tsx index 4a95c337fc..e086b50573 100644 --- a/plugin-examples/local-plugin/index.client.tsx +++ b/plugin-examples/local-plugin/index.client.tsx @@ -1,11 +1,12 @@ import type { PluginClientContext } from "@getpaseo/plugin/client"; +import { counterIcon } from "./client/icons"; import { contributeClient, ExamplePanel } from "./client/main"; export default function contribute(client: PluginClientContext) { client.addWorkspacePanel({ id: "counter", title: "Plugin counter", - icon: "Blocks", + icon: { svg: counterIcon }, context: "workspace", locations: ["workspace", "explorer"], Component: ExamplePanel, diff --git a/public-docs/plugins/index.md b/public-docs/plugins/index.md index 50d9be9826..b21a637ffa 100644 --- a/public-docs/plugins/index.md +++ b/public-docs/plugins/index.md @@ -222,7 +222,8 @@ client.addCommandCenterItem({ }); ``` -`icon` is a [Lucide](https://lucide.dev/icons/) icon name. +`icon` is a [Lucide](https://lucide.dev/icons/) icon name, inline SVG, or a component. See +[Icons](/docs/plugins/reference#icons). ## Edit and reload diff --git a/public-docs/plugins/reference.md b/public-docs/plugins/reference.md index 4a8f74af9a..7a05329116 100644 --- a/public-docs/plugins/reference.md +++ b/public-docs/plugins/reference.md @@ -162,7 +162,7 @@ guarantee compatibility with another host's renderer. These exact module specifiers use the host's runtime instances. A client bundle that requests another host module fails with `Module "" is not available in plugin client code`. -Do not import `lucide-react-native`, `react-native-svg`, or DOM libraries. Set contribution `icon` fields to a [Lucide icon name](https://lucide.dev/icons/); Paseo validates the name and renders the icon. +Do not import `lucide-react-native`, `react-native-svg`, or DOM libraries. Set contribution `icon` fields to a [Lucide icon name](https://lucide.dev/icons/), inline SVG, or a component; Paseo validates the icon and renders it. See [Icons](#icons). ### Cross-platform rules @@ -338,11 +338,9 @@ Use `runAcpProvider()` from `@getpaseo/plugin/server/acp` to adapt a command-bac hooks only for a vendor's discovery, configuration, notification, or tool-call differences. `ProviderRegistration.icon` is a file path relative to the plugin directory, such as `icon.svg`. -It must resolve inside that directory to a regular SVG file no larger than 64 KiB. The SVG must be -self-contained: scripts, styles, `foreignObject`, event-handler attributes, JavaScript URLs, and -external `href` or `xlink:href` references are rejected. Fragment references such as `#mark` are -allowed. Paseo reads and sanitizes the file when the plugin starts; the string is never an inline -SVG or URL. +It must resolve inside that directory to a regular file that follows the +[SVG icon rules](#svg-rules). Paseo reads and validates the file when the plugin starts; the string +is never inline SVG or a URL. ### Usage sources @@ -516,7 +514,7 @@ bypasses that cache. Entries carry `id`, `account.label`, and `fetchedAt`. Faile on `server_info.features.usageSources`. The older `provider.usage.list` RPC maps the same reports for 0.10 clients and renders problems into its `error` string. -The source icon follows the provider SVG restrictions above. +The source icon is a file path with the same rules as a provider icon. ## Entry point and cleanup @@ -968,10 +966,10 @@ closes the popover. Render the item with the sidebar kit from `@getpaseo/plugin/client/ui`: -| Component | Props and behavior | -| ------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `SidebarRow` | Required `onPress`; optional `icon` (Lucide name or `{ size, color }` component), `label`, `active`, `trailing`, `id`. A full-width row. `trailing` renders beside the row's pressable, so a button in it presses on its own; a press elsewhere in it presses the row. `id` tells rows of one item apart in test IDs. | -| `SidebarSeparator` | No props. The sidebar's separator line, between groups of rows. | +| Component | Props and behavior | +| ------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `SidebarRow` | Required `onPress`; optional `icon` (any [icon](#icons) form), `label`, `active`, `trailing`, `id`. A full-width row. `trailing` renders beside the row's pressable, so a button in it presses on its own; a press elsewhere in it presses the row. `id` tells rows of one item apart in test IDs. | +| `SidebarSeparator` | No props. The sidebar's separator line, between groups of rows. | A popover anchors to the row that was pressed, whether the press landed on the row or on its `trailing` content, so a per-row "More" button opens its popover next to its own row. @@ -1246,14 +1244,82 @@ Showing another toast replaces the currently visible toast. An empty message is ### Icons -`Icon` renders a [Lucide icon](https://lucide.dev/icons/) from Paseo's installed icon set. Plugin bundles do not import -`lucide-react-native` or `react-native-svg`. +Every contribution `icon` field takes one of three forms, typed `PluginIcon` in +`@getpaseo/plugin/client`: -| Prop | Type | Required | Behavior | -| ------- | -------- | -------- | ----------------------------------------------- | -| `name` | `string` | Yes | Lucide icon name. Unknown names render nothing. | -| `size` | `number` | No | Icon width and height. | -| `color` | `string` | No | Icon color. Use a plugin theme token. | +| Form | Example | Use it for | +| ----------- | --------------------------- | --------------------------------------------------- | +| Lucide name | `icon: "Scan"` | Any [Lucide icon](https://lucide.dev/icons/). | +| Inline SVG | `icon: { svg: reviewIcon }` | A brand mark or an icon Lucide does not have. | +| Component | `icon: ReviewBadge` | An icon that changes with state, such as a counter. | + +Attachment sources take a Lucide name or inline SVG (`PluginSerializableIcon`), because each +attached item stores its source's icon. + +Paseo validates the icon when the contribution registers. An unknown Lucide name or an SVG that +breaks a rule fails the plugin with the reason: + +```text +Workspace panel review has an invalid icon: script elements are not allowed +``` + +Paseo draws inline SVG at the surface's icon size and passes the surface's icon color as +`currentColor`. Paint with `currentColor` to follow the theme; fixed fills keep their colors. + +A component receives `PluginIconProps`, `{ size, color }`, and renders within that size. Header +buttons and composer pills pass [`PluginButtonIconProps`](#custom-icons-and-popover-content). + +#### SVG rules + +Inline SVG, provider icons, and usage-source icons follow the same rules: + +- One `` document, no larger than 64 KiB. +- No `