From 4da1326b1f0099baa6bd0794db11093020ee3512 Mon Sep 17 00:00:00 2001 From: Gabriele Magno Date: Fri, 30 Oct 2026 16:04:30 +0100 Subject: [PATCH 1/2] Check client registrations against the Paseo version in use ClientRules takes the host version: the app's, a source checkout's (raised to the prerelease that added the newer methods its evaluator defines), or the lowest release requirements.paseo admits when there is no host or the range excludes the host. From 0.13.0-beta.1 it follows that release's evaluate.ts: file panels, translated labels, svg and component icons; from beta.2 agent panels and context-free workspace panels. Methods a version lacks are undefined (and absent to `in`), so guarded calls pass; only a "not a function" TypeError on one is a contract error. client-eval warns when the host accepts the client but the oldest admitted release would reject it; that second evaluation runs in parallel. Supersedes #3. --- THIRD_PARTY_NOTICES | 2 + src/check/bundle.ts | 20 +++- src/check/client-rules.ts | 225 ++++++++++++++++++++++++++++------- src/check/compile.ts | 23 ++++ src/check/eval-worker.ts | 2 +- src/check/index.ts | 80 +++++++++++-- src/check/isolate.ts | 4 +- test/check.test.ts | 3 +- test/client-contract.test.ts | 208 ++++++++++++++++++++++++++++++++ 9 files changed, 511 insertions(+), 56 deletions(-) create mode 100644 test/client-contract.test.ts diff --git a/THIRD_PARTY_NOTICES b/THIRD_PARTY_NOTICES index 7dc3e99..b0f229a 100644 --- a/THIRD_PARTY_NOTICES +++ b/THIRD_PARTY_NOTICES @@ -20,6 +20,8 @@ under dist/ (for example dist/check/client-rules.js), and the notices are kept. src/check/client-rules.ts packages/app/src/plugins/evaluate.ts + packages/app/src/plugins/icons.ts + packages/plugin/src/icons.ts src/check/manifest.ts packages/server/src/server/plugins/manifest.ts packages/protocol/src/plugin-config.ts diff --git a/src/check/bundle.ts b/src/check/bundle.ts index a427638..1d2ca19 100644 --- a/src/check/bundle.ts +++ b/src/check/bundle.ts @@ -10,7 +10,7 @@ import { existsSync } from "node:fs"; import { createRequire } from "node:module"; import { join } from "node:path"; import { gzipSync } from "node:zlib"; -import { ClientRules } from "./client-rules.ts"; +import { CLIENT_CONTEXT_METHODS, ClientRules } from "./client-rules.ts"; import { CLIENT_HOST_MODULES, isHostClientModule, isHostServerModule, isNodeBuiltin, SDK_CLIENT_ONLY } from "./host.ts"; /** Runtime `require("x")` calls left in a compiled bundle, i.e. modules the host must supply. */ @@ -37,6 +37,13 @@ export function chainStub(): unknown { return makeStub(true); } +const stubs = new WeakSet(); + +/** Whether `value` came from a stub host module, like the translation messages an SDK stub returns. */ +export function isStub(value: unknown): boolean { + return typeof value === "function" && stubs.has(value); +} + function makeStub(thenable: boolean): unknown { const target = function () {}; let settled: unknown; @@ -60,6 +67,7 @@ function makeStub(thenable: boolean): unknown { apply: () => makeStub(true), construct: () => makeStub(true) as object, }); + stubs.add(proxy as object); return proxy; } @@ -167,6 +175,8 @@ export interface ClientEvaluation { } export interface ClientEvaluationOptions { + /** The app version whose client contract applies (default: the verified release). */ + paseoVersion?: string; /** Time to let async work in the contribution fail (default 50 ms). */ settleMs?: number; /** The app's Lucide names. When given, unknown contribution icons are contract errors, like in the app. */ @@ -199,13 +209,13 @@ export async function evaluateClientBundle(bundle: string, pluginDir: string, op return (real.has(name) ? tryRequire(req, name) : undefined) ?? chainStub(); }; const setup = evaluateFactory<(client: unknown) => unknown>(bundle, requireModule); - const rules = new ClientRules(options.icons ?? null); + const rules = new ClientRules(options.icons ?? null, options.paseoVersion, isStub); const contributions: ClientContribution[] = []; const client = new Proxy( {}, { get: (_, key) => { - if (typeof key !== "string") return undefined; + if (typeof key !== "string" || !rules.has(key)) return undefined; if (/^add[A-Z]/.test(key)) { return (...args: unknown[]) => { rules.register(key, args); @@ -215,6 +225,8 @@ export async function evaluateClientBundle(bundle: string, pluginDir: string, op } return chainStub(); }, + // `"addFilePanel" in client` is a guard too: true only for methods the app at this version defines. + has: (_, key) => typeof key === "string" && (!/^add[A-Z]/.test(key) || (CLIENT_CONTEXT_METHODS.has(key) && rules.has(key))), }, ); let setupError: string | null = null; @@ -227,7 +239,7 @@ export async function evaluateClientBundle(bundle: string, pluginDir: string, op rules.finish(returned); await new Promise((resolve) => setTimeout(resolve, options.settleMs ?? 50)); } catch (error) { - setupError = (error as Error).message; + if (!rules.threw(error)) setupError = (error as Error).message; } finally { process.off("unhandledRejection", onRejection); } diff --git a/src/check/client-rules.ts b/src/check/client-rules.ts index 5c4f41e..5978970 100644 --- a/src/check/client-rules.ts +++ b/src/check/client-rules.ts @@ -1,16 +1,30 @@ -// Portions adapted from Paseo (https://github.com/getpaseo/paseo) at commit 9bd58f66b2dfc195898bf1178e84f02933c0d41e: -// packages/app/src/plugins/evaluate.ts +// Portions adapted from Paseo (https://github.com/getpaseo/paseo) at commit d34d17a9072149320ace35ec2a2e5c7dcd992cb3: +// packages/app/src/plugins/evaluate.ts, packages/app/src/plugins/icons.ts, packages/plugin/src/icons.ts +// That is tag v0.13.0 (the rules are unchanged in v0.14.0), with the v0.13.0-beta.1 and beta.2 steps. The pre-0.13 +// rules are from commit 9bd58f66b2dfc195898bf1178e84f02933c0d41e, whose evaluate.ts is the one released in 0.11.2 and +// 0.12.0. // Copyright (c) 2025-present Mohamed Boudra. Licensed under the Apache License, Version 2.0; see THIRD_PARTY_NOTICES. // Modified: the registration checks are rewritten as a standalone class with no app or React dependencies, take the -// icon set as a parameter, and collect every violation instead of throwing on the first. +// icon set and host version as parameters, and collect every violation instead of throwing on the first. // // The app's client registration rules. The app throws on the first violation and the whole plugin client fails // to evaluate; the only trace is a console.warn("[Plugins] Failed to evaluate ..."). Here every violation is // collected instead. +import coerce from "semver/functions/coerce.js"; +import compareVersions from "semver/functions/compare.js"; +import parse from "semver/functions/parse.js"; +import { VERIFIED_PASEO } from "../compat.ts"; const CONTRIBUTION_ID = /^[a-z][a-z0-9-]*$/; const PANEL_LOCATIONS = ["workspace", "explorer"]; -const TIMELINE_ITEM_TYPES = new Set(["user_message", "assistant_message", "reasoning", "tool_call", "todo", "error", "compaction"]); +const TIMELINE_ITEM_TYPES = ["user_message", "assistant_message", "reasoning", "tool_call", "todo", "error", "compaction"]; +/** File panels, translated labels, `{ svg }` and component icons, and the notification timeline item. */ +export const CONTRACT_0_13 = "0.13.0-beta.1"; +/** Agent panels, and workspace panels without `context`. */ +export const PANELS_0_13 = "0.13.0-beta.2"; +const LABEL_ERROR = "Plugin label must be a non-empty string or a translation message"; +const SVG_ICON_MAX_BYTES = 64 * 1024; +const EXTERNAL_HREF = /\s(?:href|xlink:href)\s*=\s*(?:(["'])(.*?)\1|([^\s>]+))/gi; type Contribution = Record; @@ -23,6 +37,8 @@ export const CLIENT_CONTEXT_METHODS = new Set([ "addSurface", "addSidebarItem", "addWorkspacePanel", + "addAgentPanel", + "addFilePanel", "addCommandCenterItem", "addSlashCommand", "addAttachmentSource", @@ -33,25 +49,96 @@ export const CLIENT_CONTEXT_METHODS = new Set([ "addHeaderButton", ]); +/** Client context methods that only newer apps have, with the release that added each. Older apps leave them undefined. */ +export const CLIENT_METHOD_SINCE: ReadonlyMap = new Map([ + ["addAgentPanel", PANELS_0_13], + ["addFilePanel", CONTRACT_0_13], +]); + const text = (value: unknown): string => (typeof value === "string" ? value.trim() : ""); const isFunction = (value: unknown): boolean => typeof value === "function"; const isComponentType = (value: unknown): boolean => typeof value === "function" || (typeof value === "object" && value !== null && "$$typeof" in value); +const isSvgIcon = (icon: unknown): icon is { svg: string } => + typeof icon === "object" && icon !== null && !("$$typeof" in icon) && typeof Reflect.get(icon, "svg") === "string"; +const selectorEntries = (entries: unknown, extension: boolean): entries is string[] => + Array.isArray(entries) && + entries.every((entry) => typeof entry === "string" && entry.trim() === entry && entry.length > 0 && !/[\\/*?]/.test(entry) && (!extension || !entry.includes("."))); + +/** A file panel's `files`: only `extensions` (no dots) and optional `filenames`, plain names, at least one in all. */ +function validFileSelector(files: unknown): boolean { + if (!files || typeof files !== "object") return false; + const { extensions, filenames, ...rest } = files as Record; + return Object.keys(rest).length === 0 && selectorEntries(extensions, true) && (filenames === undefined || selectorEntries(filenames, false)) && + extensions.length + (Array.isArray(filenames) ? filenames.length : 0) > 0; +} + +/** findSvgIconProblem: why the app refuses an inline SVG icon, or null. */ +export function svgIconProblem(svg: string): string | null { + if (Buffer.byteLength(svg) > 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)) { + if (!(match[2] ?? match[3] ?? "").startsWith("#")) return "external href references are not allowed"; + } + return null; +} + +/** Whether `version` (an app or source version; a prerelease sorts below its release) is at least `since`. */ +export function atLeast(version: string, since: string): boolean { + const parsed = parse(version) ?? coerce(version); + return parsed !== null && compareVersions(parsed, since) >= 0; +} + +/** Whether `version` has the 0.13 client contract. */ +export function hasContract013(version: string): boolean { + return atLeast(version, CONTRACT_0_13); +} + +/** A TypeError from calling `method` while it is undefined, under any receiver name a bundler gives `client`. */ +function callsMissing(error: unknown, method: string): boolean { + return error instanceof TypeError && new RegExp(`\\b${method} is not a function`).test(error.message); +} /** - * Validates registrations like the app's evaluate.ts. `icons` is the app's Lucide name set; null skips the - * icon rule (no icon list available). + * Validates registrations like the evaluate.ts of the app at `paseoVersion` (default: the verified release). + * `icons` is the app's Lucide name set; null skips the icon-name rule (no icon list available). */ export class ClientRules { readonly errors: string[] = []; private readonly ids = new Map>(); private readonly surfaces = new Set(); private readonly legacySidebarSurfaces: { id: string; surface: string }[] = []; + private readonly absentRead = new Set(); private readonly icons: ReadonlySet | null; + readonly paseoVersion: string; + private readonly modern: boolean; + private readonly flatPanels: boolean; + private readonly isMessage: (value: unknown) => boolean; - constructor(icons: ReadonlySet | null) { + /** + * `isMessage` recognizes the translation messages the SDK's `message()` creates. The evaluator stubs the SDK, so it + * passes its stub check; without one, no value is a message. + */ + constructor(icons: ReadonlySet | null, paseoVersion: string = VERIFIED_PASEO, isMessage: (value: unknown) => boolean = () => false) { this.icons = icons; + this.paseoVersion = paseoVersion; + this.modern = hasContract013(paseoVersion); + this.flatPanels = atLeast(paseoVersion, PANELS_0_13); + this.isMessage = isMessage; + } + + /** Whether the app at this version defines `client.`. A read of a missing one is remembered. */ + has(method: string): boolean { + const since = CLIENT_METHOD_SINCE.get(method); + if (since === undefined || atLeast(this.paseoVersion, since)) return true; + this.absentRead.add(method); + return false; } private fail(message: string): void { @@ -74,20 +161,65 @@ export class ClientRules { seen.add(id); } - private icon(name: unknown): void { + /** + * A label: a non-empty string, and from 0.13 a translation message too. From 0.13 a value that is neither throws + * the SDK's own message (requirePluginText); an empty string gets `missing`, like before 0.13. + */ + private label(value: unknown, missing: string): void { + if (typeof value === "string" ? value.trim() !== "" : this.modern && this.isMessage(value)) return; + this.fail(this.modern && typeof value !== "string" ? LABEL_ERROR : missing); + } + + /** The pre-0.13 rule: a Lucide name only. */ + private lucide(name: unknown, owner: string): void { if (!this.icons) return; const icon = text(name); - if (!this.icons.has(icon)) this.fail(`Unknown Lucide icon: ${String(name)}`); + if (!this.icons.has(icon)) this.fail(this.modern ? `${owner} has an invalid icon: unknown Lucide icon "${icon}"` : `Unknown Lucide icon: ${String(name)}`); + } + + /** The icon rule: before 0.13 a non-empty Lucide name; from 0.13 parsePluginIcon (`serializable` refuses components). */ + private icon(owner: string, icon: unknown, serializable = false): void { + if (!this.modern || typeof icon === "string") { + if (!text(icon)) this.fail(`${owner} has no icon`); + else this.lucide(icon, owner); + return; + } + if (!serializable && isComponentType(icon)) return; + if (!isSvgIcon(icon)) { + this.fail(`${owner} has an invalid icon: expected a Lucide icon name${serializable ? " or { svg }" : ", { svg }, or a component"}`); + return; + } + const problem = svgIconProblem(icon.svg.trim()); + if (problem) this.fail(`${owner} has an invalid icon: ${problem}`); } private sidebarItem(section: "header" | "footer", c: Contribution): void { const id = this.id(c.id, `sidebar ${section} item id`); if (!id) return; this.unique(`sidebar-${section}`, id, `Duplicate sidebar ${section} item`); - if (!text(c.title)) this.fail(`Sidebar item ${id} has no title`); + this.label(c.title, `Sidebar item ${id} has no title`); if (!isComponentType(c.Component)) this.fail(`Sidebar item ${id} is not a component`); } + private panel(c: Contribution, context: unknown): void { + const id = this.id(c.id, "workspace panel id"); + if (!id) return; + this.unique("workspace-panel", id, "Duplicate workspace panel"); + this.label(c.title, `Workspace panel ${id} has no title`); + this.icon(`Workspace panel ${id}`, c.icon); + const contexts = this.flatPanels ? [undefined, "workspace", "agent"] : ["workspace", "agent"]; + if (!contexts.includes(context as string)) this.fail(`Workspace panel ${id} has invalid context`); + if (!isFunction(c.Component)) this.fail(`Workspace panel ${id} is not a component`); + if (c.locations !== undefined) { + const locations = c.locations; + if (!Array.isArray(locations) || locations.length === 0) this.fail(`Workspace panel ${id} must support at least one location`); + else { + for (const location of locations) if (!PANEL_LOCATIONS.includes(location)) this.fail(`Workspace panel ${id} has invalid location: ${String(location)}`); + if (new Set(locations).size !== locations.length) this.fail(`Workspace panel ${id} has duplicate locations`); + } + } + } + /** Checks one `client.(...)` call. */ register(method: string, args: unknown[]): void { const c = (args[0] && typeof args[0] === "object" ? args[0] : {}) as Contribution; @@ -96,8 +228,9 @@ export class ClientRules { const id = this.id(c.id, "settings screen id"); if (!id) return; this.unique("settings-screen", id, "Duplicate settings screen"); - if (!text(c.title)) this.fail(`Invalid settings screen: ${id}`); - this.icon(c.icon); + this.label(c.title, `Invalid settings screen: ${id}`); + if (this.modern) this.icon(`Settings screen ${id}`, c.icon); + else this.lucide(c.icon, `Settings screen ${id}`); return; } case "addScreen": @@ -107,7 +240,8 @@ export class ClientRules { if (!id) return; this.unique("screen", id, "Duplicate screen"); this.surfaces.add(id); - if (typeof screen.title !== "function" && !text(screen.title)) this.fail(`Screen ${id} needs a title: a non-empty string or a function of params`); + const title = screen.title; + if (typeof title !== "function" && !(typeof title === "string" ? title.trim() : this.modern && this.isMessage(title))) this.fail(`Screen ${id} needs a title: a non-empty string or a function of params`); if (!isComponentType(screen.Component)) this.fail(`Screen ${id} is not a component`); return; } @@ -118,63 +252,58 @@ export class ClientRules { case "addSidebarItem": { const id = this.id(c.id, "sidebar item id"); if (!id) return; - if (!text(c.icon)) this.fail(`Sidebar item ${id} has no icon`); - else this.icon(c.icon); + this.icon(`Sidebar item ${id}`, c.icon); const surface = this.id(c.surface, "sidebar surface id"); this.unique("sidebar-header", id, "Duplicate sidebar header item"); - if (!text(c.title)) this.fail(`Sidebar item ${id} has no title`); + this.label(c.title, `Sidebar item ${id} has no title`); if (surface) this.legacySidebarSurfaces.push({ id, surface }); return; } - case "addWorkspacePanel": { - const id = this.id(c.id, "workspace panel id"); + case "addWorkspacePanel": + return this.panel(c, c.context); + case "addAgentPanel": + return this.panel(c, "agent"); + case "addFilePanel": { + const id = this.id(c.id, "file panel id"); if (!id) return; - this.unique("workspace-panel", id, "Duplicate workspace panel"); - if (!text(c.title)) this.fail(`Workspace panel ${id} has no title`); - if (!text(c.icon)) this.fail(`Workspace panel ${id} has no icon`); - if (c.context !== "workspace" && c.context !== "agent") this.fail(`Workspace panel ${id} has invalid context`); - if (!isFunction(c.Component)) this.fail(`Workspace panel ${id} is not a component`); - if (text(c.icon)) this.icon(c.icon); - if (c.locations !== undefined) { - const locations = c.locations; - if (!Array.isArray(locations) || locations.length === 0) this.fail(`Workspace panel ${id} must support at least one location`); - else { - for (const location of locations) if (!PANEL_LOCATIONS.includes(location)) this.fail(`Workspace panel ${id} has invalid location: ${String(location)}`); - if (new Set(locations).size !== locations.length) this.fail(`Workspace panel ${id} has duplicate locations`); - } - } + this.unique("file-panel", id, "Duplicate file panel"); + this.label(c.title, `File panel ${id} has no title`); + this.icon(`File panel ${id}`, c.icon); + if (!validFileSelector(c.files)) this.fail(`File panel ${id} has invalid selector`); + if (!isFunction(c.Component)) this.fail(`File panel ${id} is not a component`); return; } case "addCommandCenterItem": { const id = this.id(c.id, "Command Center item id"); if (!id) return; this.unique("command-center", id, "Duplicate Command Center item"); - if (!text(c.title)) this.fail(`Command Center item ${id} has no title`); - if (!text(c.icon)) this.fail(`Command Center item ${id} has no icon`); + this.label(c.title, `Command Center item ${id} has no title`); + this.icon(`Command Center item ${id}`, c.icon); if (c.context !== "global" && c.context !== "workspace" && c.context !== "agent") this.fail(`Command Center item ${id} has invalid context`); if (!isFunction(c.onSelect)) this.fail(`Command Center item ${id} has no callback`); - if (text(c.icon)) this.icon(c.icon); return; } case "addSlashCommand": { const name = this.id(c.name, "client slash command name"); if (!name) return; this.unique("slash-command", name, "Duplicate client slash command"); - if (!text(c.description)) this.fail(`Client slash command ${name} has no description`); + this.label(c.description, `Client slash command ${name} has no description`); if (c.context !== "workspace" && c.context !== "agent") this.fail(`Client slash command ${name} has invalid context`); if (!isFunction(c.onSubmit)) this.fail(`Client slash command ${name} has no callback`); - if (typeof c.argumentHint !== "string") this.fail(`Client slash command ${name} has no argumentHint string`); + if (typeof c.argumentHint !== "string" && !(this.modern && this.isMessage(c.argumentHint))) { + this.fail(this.modern ? LABEL_ERROR : `Client slash command ${name} has no argumentHint string`); + } return; } case "addAttachmentSource": { const id = this.id(c.id, "attachment source id"); if (!id) return; this.unique("attachment-source", id, "Duplicate attachment source"); - for (const [field, label] of [["title", "title"], ["icon", "icon"], ["pickerTitle", "picker title"], ["searchPlaceholder", "search placeholder"]] as const) { - if (!text(c[field])) this.fail(`Attachment source ${id} has no ${label}`); - } + this.label(c.title, `Attachment source ${id} has no title`); + this.icon(`Attachment source ${id}`, c.icon, true); + this.label(c.pickerTitle, `Attachment source ${id} has no picker title`); + this.label(c.searchPlaceholder, `Attachment source ${id} has no search placeholder`); if (!text((c.search as { name?: unknown } | undefined)?.name)) this.fail(`Attachment source ${id} has no search RPC`); - if (text(c.icon)) this.icon(c.icon); return; } case "addTheme": { @@ -187,8 +316,9 @@ export class ClientRules { if (!id) return; this.unique("timeline-transformer", id, "Duplicate timeline transformer"); const itemType = (c.query as { itemType?: unknown } | undefined)?.itemType; + const itemTypes = this.modern ? [...TIMELINE_ITEM_TYPES, "notification"] : TIMELINE_ITEM_TYPES; if (typeof itemType !== "string") this.fail(`Timeline transformer ${id} has no item type`); - else if (!TIMELINE_ITEM_TYPES.has(itemType)) this.fail(`Timeline transformer ${id} has invalid item type: ${itemType}`); + else if (!itemTypes.includes(itemType)) this.fail(`Timeline transformer ${id} has invalid item type: ${itemType}`); if (!isFunction(c.transform)) this.fail(`Timeline transformer ${id} has no transform`); if (c.id !== id) this.fail(`Invalid timeline transformer id: ${String(c.id)}`); return; @@ -212,6 +342,17 @@ export class ClientRules { } } + /** + * The contribution threw. When it read a method this app version lacks, that is the cause the app would hit too, + * so it is a contract error rather than a possible stub limit. Returns whether it was. + */ + threw(error: unknown): boolean { + const method = [...this.absentRead].find((name) => callsMissing(error, name)); + if (!method) return false; + this.fail(`Paseo ${this.paseoVersion} has no client.${method} (added in ${CLIENT_METHOD_SINCE.get(method)!.replace(/-.*/, "")}), and the contribution threw: ${(error as Error).message}. Guard the call with typeof, or require a newer Paseo`); + return true; + } + /** After setup: the contribution must return a cleanup, and legacy sidebar items need their surface. */ finish(cleanup: unknown): void { if (typeof cleanup !== "function") this.fail("Plugin contribution must return a cleanup function"); diff --git a/src/check/compile.ts b/src/check/compile.ts index 6dacbb0..109e93e 100644 --- a/src/check/compile.ts +++ b/src/check/compile.ts @@ -16,6 +16,7 @@ import { build } from "esbuild"; import { CLIENT_HOST_MODULES, SDK_SPECIFIERS, SERVER_HOST_MODULES } from "./host.ts"; import { describeNoResult, runChild } from "./isolate.ts"; import { layoutMismatch } from "../compat.ts"; +import { atLeast, CLIENT_METHOD_SINCE } from "./client-rules.ts"; import { which } from "../proc.ts"; export type Target = "client" | "server"; @@ -96,6 +97,28 @@ export function findPaseoApp(explicit?: string, env: NodeJS.ProcessEnv = process /** Where the real compiler comes from. Null means the esbuild approximation. */ export type PaseoHost = { kind: "source"; root: string } | ({ kind: "app" } & PaseoApp); +/** + * The app version whose client contract the host has. A source checkout's package version lags main until the next + * release is cut, so it is raised to the release of any newer client method its evaluator already defines. + */ +export function paseoHostVersion(host: PaseoHost | null): string | undefined { + if (!host) return undefined; + if (host.kind === "app") return host.version ?? undefined; + let version: string | undefined; + try { + const declared = JSON.parse(readFileSync(join(host.root, "packages/app/package.json"), "utf8")).version; + if (typeof declared === "string") version = declared; + } catch {} + let evaluator = ""; + try { + evaluator = readFileSync(join(host.root, "packages/app/src/plugins/evaluate.ts"), "utf8"); + } catch {} + for (const [method, since] of CLIENT_METHOD_SINCE) { + if (evaluator.includes(`${method}(`) && (!version || !atLeast(version, since))) version = since; + } + return version; +} + export interface HostSelection { /** A checkout path, null to skip, undefined for PASEO_SOURCE. */ paseoSource?: string | null; diff --git a/src/check/eval-worker.ts b/src/check/eval-worker.ts index 6e8b37f..b667804 100644 --- a/src/check/eval-worker.ts +++ b/src/check/eval-worker.ts @@ -44,7 +44,7 @@ try { ...(await runCleanup(evaluation.cleanup, baseline)), }; } else { - const evaluation = await evaluateClientBundle(bundle, request.pluginDir, { icons: request.icons ? new Set(request.icons) : null }); + const evaluation = await evaluateClientBundle(bundle, request.pluginDir, { icons: request.icons ? new Set(request.icons) : null, paseoVersion: request.paseoVersion }); result = { target: "client", contributions: evaluation.contributions.map((entry) => entry.method), diff --git a/src/check/index.ts b/src/check/index.ts index dcc99a4..64a7afb 100644 --- a/src/check/index.ts +++ b/src/check/index.ts @@ -2,13 +2,18 @@ import { existsSync, readFileSync } from "node:fs"; import { relative, resolve } from "node:path"; import { parseArgs } from "node:util"; +import minVersion from "semver/ranges/min-version.js"; +import validRange from "semver/ranges/valid.js"; +import coerce from "semver/functions/coerce.js"; +import satisfies from "semver/functions/satisfies.js"; import { bundleRequires, disallowedClientRequires, disallowedServerRequires, formatKb, sizeReport } from "./bundle.ts"; -import { compileApprox, CompileError, compileLikePaseo, compileWithHost, describeHost, findEntries, findPaseoApp, findPaseoHost, findPaseoSource, PASEO_COMPILER, PASEO_SOURCE_MISSING } from "./compile.ts"; +import { compileApprox, CompileError, compileLikePaseo, compileWithHost, describeHost, findEntries, findPaseoApp, findPaseoHost, findPaseoSource, paseoHostVersion, PASEO_COMPILER, type PaseoHost, PASEO_SOURCE_MISSING } from "./compile.ts"; +import { hasContract013 } from "./client-rules.ts"; +import { VERIFIED_PASEO } from "../compat.ts"; import { classSyntaxErrors, findHermes, hermesParse, hermesSmoke } from "./hermes.ts"; import { boundaryFindings, dependencyFindings, externalPackages, pluginFiles, typesNodeFinding } from "./imports.ts"; import { cleanupWarning, DEFAULT_EVAL_TIMEOUT_MS, evaluateIsolated } from "./isolate.ts"; import { hostIconNames, iconListProblem, staticIconNames } from "./lucide.ts"; -import { VERIFIED_PASEO } from "../compat.ts"; import { manifestFindings } from "./manifest.ts"; import { UsageError } from "../usage.ts"; @@ -45,6 +50,51 @@ interface Manifest { [key: string]: unknown; } +interface ClientContract { + /** The app version whose registration rules the client is checked against. */ + version: string; + /** The oldest app requirements.paseo admits, when its contract differs from `version`'s. */ + oldest: { version: string; range: string } | null; + /** The host's version when requirements.paseo excludes it: that app would not load the plugin at all. */ + excludedHost: string | null; +} + +/** + * The host's version; without a host, the oldest app requirements.paseo admits; else the verified release. Apps below + * the range skip the plugin, so only the range's lower bound can reach older rules than the host's. + */ +function clientContract(host: PaseoHost | null, dir: string): ClientContract { + let range: unknown; + try { + range = JSON.parse(readFileSync(resolve(dir, "paseo-plugin.json"), "utf8"))?.requirements?.paseo; + } catch {} + const lowest = typeof range === "string" && validRange(range) !== null ? minVersion(range)?.version : undefined; + const hostVersion = paseoHostVersion(host); + // An app the range excludes skips the plugin, so its rules do not apply; the range's own lower bound does. + // Like Paseo's assertPluginCompatibility: a prerelease is admitted when it or its stable core satisfies the range. + const admitted = (version: string) => satisfies(version, range as string, { loose: true }) || satisfies(coerce(version)?.version ?? version, range as string); + const excluded = hostVersion !== undefined && lowest !== undefined && !admitted(hostVersion); + const version = (excluded ? lowest : hostVersion) ?? lowest ?? VERIFIED_PASEO; + const older = lowest !== undefined && hasContract013(version) && !hasContract013(lowest); + return { version, oldest: older ? { version: lowest, range: range as string } : null, excludedHost: excluded ? hostVersion : null }; +} + +function excludedHostNote(contract: ClientContract): string { + return `the installed Paseo ${contract.excludedHost} is outside requirements.paseo, so it would not load this plugin; checked with Paseo ${contract.version} rules instead`; +} + +/** Registration errors the oldest admitted app would raise that the checked host does not, or null. */ +async function olderAppRejection(bundle: string, dir: string, contract: ClientContract, icons: ReadonlySet | null, timeoutMs: number): Promise<{ message: string; errors: string[] } | null> { + if (!contract.oldest) return null; + const outcome = await evaluateIsolated("client", bundle, dir, { timeoutMs, icons, paseoVersion: contract.oldest.version }); + const result = outcome.ok && !("error" in outcome.result) && outcome.result.target === "client" ? outcome.result : null; + if (!result?.contractErrors.length) return null; + return { + message: `Paseo ${contract.oldest.version}, which requirements.paseo "${contract.oldest.range}" admits, would reject this client and show none of its UI. Raise requirements.paseo or use only what that release accepts`, + errors: result.contractErrors, + }; +} + export async function runChecks(pluginDir: string, options: CheckOptions = {}): Promise { const dir = resolve(pluginDir); const results: CheckResult[] = []; @@ -146,10 +196,12 @@ export async function runChecks(pluginDir: string, options: CheckOptions = {}): } const lucide = hostIconNames(host, dir); + const contract = clientContract(host, dir); const evalTimeoutMs = options.evalTimeoutMs ?? DEFAULT_EVAL_TIMEOUT_MS; - const [serverOutcome, clientOutcome] = await Promise.all([ + const [serverOutcome, clientOutcome, older] = await Promise.all([ serverBundle && !realEvalError && !realHandlers ? evaluateIsolated("server", serverBundle, dir, { timeoutMs: evalTimeoutMs }) : null, - clientBundle ? evaluateIsolated("client", clientBundle, dir, { timeoutMs: evalTimeoutMs, icons: lucide?.names ?? null }) : null, + clientBundle ? evaluateIsolated("client", clientBundle, dir, { timeoutMs: evalTimeoutMs, icons: lucide?.names ?? null, paseoVersion: contract.version }) : null, + clientBundle ? olderAppRejection(clientBundle, dir, contract, lucide?.names ?? null, evalTimeoutMs) : null, ]); if (serverBundle) { if (realEvalError) { @@ -185,8 +237,15 @@ export async function runChecks(pluginDir: string, options: CheckOptions = {}): if ("error" in result) add("client-eval", "fail", `client bundle failed to evaluate: ${result.error}`); else if (result.target === "client") { result.icons.forEach((icon) => contributionIcons.add(icon)); - const summary = `contributions: ${result.contributions.join(", ") || "none"}`; - if (result.contractErrors.length) add("client-eval", "fail", "the app would reject this plugin client and show none of its UI", [...result.contractErrors, summary]); + const summary = `contributions: ${result.contributions.join(", ") || "none"} (Paseo ${contract.version} rules)`; + const notes = [ + ...(contract.excludedHost ? [excludedHostNote(contract)] : []), + ...(result.setupError ? [`contribution threw under stub host modules (may be a stub limit): ${result.setupError}`] : []), + ...(cleanupWarning(result) ? [cleanupWarning(result)!] : []), + ]; + if (result.contractErrors.length) add("client-eval", "fail", "the app would reject this plugin client and show none of its UI", [...result.contractErrors, ...notes, summary]); + else if (older) add("client-eval", "warn", older.message, [...older.errors, ...notes, summary]); + else if (contract.excludedHost) add("client-eval", "warn", excludedHostNote(contract), [...notes.slice(1), summary]); else if (result.setupError) add("client-eval", "warn", `contribution threw under stub host modules (may be a stub limit): ${result.setupError}`, [summary]); else if (cleanupWarning(result)) add("client-eval", "warn", cleanupWarning(result)!, [summary]); else add("client-eval", "pass", summary); @@ -329,13 +388,20 @@ export async function checkClient(pluginDir: string, options: CheckOptions = {}) } catch (error) { return { errors: [`client compile failed: ${(error as Error).message}`], notes: [], iconSource: null }; } - const outcome = await evaluateIsolated("client", bundle, dir, { timeoutMs: options.evalTimeoutMs ?? DEFAULT_EVAL_TIMEOUT_MS, icons: lucide?.names ?? null }); + const timeoutMs = options.evalTimeoutMs ?? DEFAULT_EVAL_TIMEOUT_MS; + const contract = clientContract(host, dir); + const [outcome, older] = await Promise.all([ + evaluateIsolated("client", bundle, dir, { timeoutMs, icons: lucide?.names ?? null, paseoVersion: contract.version }), + olderAppRejection(bundle, dir, contract, lucide?.names ?? null, timeoutMs), + ]); const iconSource = lucide?.source ?? null; if (!outcome.ok) return { errors: [outcome.error], notes: [], iconSource }; const result = outcome.result; if ("error" in result) return { errors: [result.error], notes: [], iconSource }; if (result.target !== "client") return null; const notes = [ + ...(contract.excludedHost ? [excludedHostNote(contract)] : []), + ...(older && !result.contractErrors.length ? [`${older.message}: ${older.errors.join("; ")}`] : []), ...(result.setupError ? [`contribution threw under stub host modules (may be a stub limit): ${result.setupError}`] : []), ...(cleanupWarning(result) ? [cleanupWarning(result)!] : []), ...(iconProblem ? [iconProblem] : iconSource ? [] : ["icon names not checked: no Lucide list found"]), diff --git a/src/check/isolate.ts b/src/check/isolate.ts index e346f57..995ebdd 100644 --- a/src/check/isolate.ts +++ b/src/check/isolate.ts @@ -16,6 +16,7 @@ export interface EvalRequest { pluginDir: string; resultFile: string; icons: string[] | null; + paseoVersion?: string; } interface CleanupReport { @@ -107,7 +108,7 @@ export async function evaluateIsolated( target: "server" | "client", bundle: string, pluginDir: string, - options: { timeoutMs?: number; icons?: ReadonlySet | null } = {}, + options: { timeoutMs?: number; icons?: ReadonlySet | null; paseoVersion?: string } = {}, ): Promise { const timeoutMs = options.timeoutMs ?? DEFAULT_EVAL_TIMEOUT_MS; const work = mkdtempSync(join(tmpdir(), "ppd-eval-")); @@ -118,6 +119,7 @@ export async function evaluateIsolated( pluginDir, resultFile: join(work, "result.json"), icons: options.icons ? [...options.icons] : null, + paseoVersion: options.paseoVersion, }; writeFileSync(request.bundleFile, bundle); writeFileSync(join(work, "request.json"), JSON.stringify(request)); diff --git a/test/check.test.ts b/test/check.test.ts index 2e2c2e4..368c36d 100644 --- a/test/check.test.ts +++ b/test/check.test.ts @@ -83,7 +83,8 @@ describe("runChecks", () => { expect(good.find((r) => r.id === "lucide-icons")).toMatchObject({ status: "pass", message: expect.stringMatching(/\d{4} Lucide icons of the Paseo/) }); const bad = await runChecks(BAD, { paseoSource: null }); expect(bad.find((r) => r.id === "lucide-icons")).toMatchObject({ status: "fail", message: expect.stringContaining("NotARealIconName") }); - expect(bad.find((r) => r.id === "client-eval")?.details).toContain("Unknown Lucide icon: NotARealIconName"); + // The message is the installed app's: "Unknown Lucide icon: X" before 0.13, "... has an invalid icon: unknown Lucide icon "X"" from 0.13. + expect(bad.find((r) => r.id === "client-eval")?.details?.some((detail) => /unknown Lucide icon:? "?NotARealIconName/i.test(detail))).toBe(true); }, 120_000); it("fails the bad fixture on boundaries, server evaluation and class syntax", async () => { diff --git a/test/client-contract.test.ts b/test/client-contract.test.ts new file mode 100644 index 0000000..f9d0393 --- /dev/null +++ b/test/client-contract.test.ts @@ -0,0 +1,208 @@ +import { mkdirSync, writeFileSync } from "node:fs"; +import { join } from "node:path"; +import { describe, expect, it } from "vitest"; +import { evaluateClientBundle } from "../src/check/bundle.ts"; +import { ClientRules } from "../src/check/client-rules.ts"; +import { paseoHostVersion } from "../src/check/compile.ts"; +import { checkClient, runChecks } from "../src/check/index.ts"; +import { EXAMPLE, scratch } from "./helpers.ts"; + +const icons = new Set(["FileText"]); +const Component = () => null; +const filePanel = (patch: Record = {}) => ({ id: "pdf", title: "PDF", icon: "FileText", files: { extensions: ["pdf"] }, Component, ...patch }); +const message = { translation: "title" }; +const errors = (version: string, ...calls: [string, Record][]) => { + const rules = new ClientRules(icons, version, (value) => value === message); + for (const [method, contribution] of calls) rules.register(method, [contribution]); + return rules.errors; +}; +const fileCall = 'client.addFilePanel({ id: "pdf", title: "PDF", icon: "FileText", files: { extensions: ["pdf"] }, Component: function () {} })'; +const bundle = (body: string) => `(function(require) { return { default: function(client) { ${body}; return function() {}; } }; })`; + +describe("client contract by Paseo version (evaluate.ts at v0.12.0 and v0.13.0)", () => { + it.each(["0.13.0", "0.13.0-beta.2", "0.14.0"])("accepts 0.13 panels, labels and icons on %s", (version) => { + expect( + errors( + version, + ["addFilePanel", filePanel()], + ["addFilePanel", filePanel({ id: "svg", icon: { svg: '' } })], + ["addFilePanel", filePanel({ id: "drawn", icon: Component })], + ["addAgentPanel", { id: "agent", title: "Agent", icon: "FileText", Component }], + ["addWorkspacePanel", { id: "flat", title: message, icon: "FileText", Component }], + ["addCommandCenterItem", { id: "open", title: "Open", icon: { svg: "" }, context: "global", onSelect: Component }], + ["addTimelineTransformer", { id: "notes", query: { itemType: "notification" }, transform: Component }], + ), + ).toEqual([]); + }); + + it("applies the 0.12 rules to the same registrations on 0.12.0", () => { + expect( + errors( + "0.12.0", + ["addWorkspacePanel", { id: "flat", title: message, icon: { svg: "" }, Component }], + ["addTimelineTransformer", { id: "notes", query: { itemType: "notification" }, transform: Component }], + ["addWorkspacePanel", { id: "named", title: "Named", icon: "Nope", context: "workspace", Component }], + ), + ).toEqual([ + "Workspace panel flat has no title", + "Workspace panel flat has no icon", + "Workspace panel flat has invalid context", + "Timeline transformer notes has invalid item type: notification", + "Unknown Lucide icon: Nope", + ]); + }); + + it("has file panels, labels and icons but not agent or context-free panels on 0.13.0-beta.1", () => { + const rules = new ClientRules(icons, "0.13.0-beta.1", (value) => value === message); + expect([rules.has("addFilePanel"), rules.has("addAgentPanel")]).toEqual([true, false]); + rules.register("addFilePanel", [filePanel({ title: message, icon: { svg: "" } })]); + rules.register("addWorkspacePanel", [{ id: "flat", title: "Flat", icon: "FileText", Component }]); + expect(rules.errors).toEqual(["Workspace panel flat has invalid context"]); + }); + + it("takes only SDK messages as labels, with the SDK's error for anything else", () => { + expect( + errors( + "0.14.0", + ["addSettingsScreen", { id: "fn", title: () => "S", icon: "FileText", Component }], + ["addFilePanel", filePanel({ title: undefined })], + ["addFilePanel", filePanel({ id: "blank", title: " " })], + ["addCommandCenterItem", { id: "obj", title: { key: "x" }, icon: "FileText", context: "global", onSelect: Component }], + ), + ).toEqual([ + "Plugin label must be a non-empty string or a translation message", + "Plugin label must be a non-empty string or a translation message", + "File panel blank has no title", + "Plugin label must be a non-empty string or a translation message", + ]); + }); + + it("uses the 0.13 icon messages, and refuses unsafe SVG and component attachment icons", () => { + expect( + errors( + "0.14.0", + ["addFilePanel", filePanel({ icon: "Nope" })], + ["addFilePanel", filePanel({ id: "blank", icon: " " })], + ["addFilePanel", filePanel({ id: "odd", icon: 1 })], + ["addFilePanel", filePanel({ id: "script", icon: { svg: "" } })], + ["addFilePanel", filePanel({ id: "remote", icon: { svg: '' } })], + ["addAttachmentSource", { id: "drawn", title: "T", icon: Component, pickerTitle: "P", searchPlaceholder: "S", search: { name: "s" } }], + ), + ).toEqual([ + 'File panel pdf has an invalid icon: unknown Lucide icon "Nope"', + "File panel blank has no icon", + "File panel odd has an invalid icon: expected a Lucide icon name, { svg }, or a component", + "File panel script has an invalid icon: script elements are not allowed", + "File panel remote has an invalid icon: external href references are not allowed", + "Attachment source drawn has an invalid icon: expected a Lucide icon name or { svg }", + ]); + }); + + it("shares workspace panel ids with agent panels and rejects other contexts", () => { + expect( + errors( + "0.14.0", + ["addWorkspacePanel", { id: "same", title: "A", icon: "FileText", context: "agent", Component }], + ["addAgentPanel", { id: "same", title: "B", icon: "FileText", Component }], + ["addWorkspacePanel", { id: "odd", title: "C", icon: "FileText", context: "global", Component }], + ), + ).toEqual(["Duplicate workspace panel: same", "Workspace panel odd has invalid context"]); + }); +}); + +describe("file panel selectors", () => { + it.each([{ extensions: ["PDF"] }, { extensions: [], filenames: ["Dockerfile"] }, { extensions: ["md"], filenames: ["README"] }])("accepts %j", (files) => { + expect(errors("0.14.0", ["addFilePanel", filePanel({ files })])).toEqual([]); + }); + + it.each([ + undefined, null, {}, { filenames: ["Makefile"] }, { extensions: [] }, { extensions: [], filenames: [] }, + { extensions: [".pdf"] }, { extensions: ["tar.gz"] }, { extensions: [""] }, { extensions: [" pdf"] }, { extensions: [1] }, + { extensions: ["*"] }, { extensions: [], filenames: ["docs/README"] }, { extensions: [], filenames: ["docs\\README"] }, + { extensions: [], filenames: ["READ?E"] }, { extensions: ["pdf"], filenames: "README" }, { extensions: ["pdf"], globs: ["*.pdf"] }, + ])("rejects %j with the app's message", (files) => { + expect(errors("0.14.0", ["addFilePanel", filePanel({ files })])).toEqual(["File panel pdf has invalid selector"]); + }); + + it("checks duplicate ids, titles and components", () => { + const memo = { $$typeof: Symbol.for("react.memo"), type: Component }; + expect(errors("0.14.0", ["addFilePanel", filePanel()], ["addFilePanel", filePanel({ title: " ", Component: memo })], ["addFilePanel", filePanel({ id: "Bad_Id" })])).toEqual([ + "Duplicate file panel: pdf", + "File panel pdf has no title", + "File panel pdf is not a component", + "Invalid file panel id: Bad_Id", + ]); + }); +}); + +describe("methods an older app lacks", () => { + it("is undefined there, so an unguarded call is a contract error and a guarded one passes", async () => { + const unguarded = await evaluateClientBundle(bundle(fileCall), EXAMPLE, { paseoVersion: "0.12.0", icons }); + expect(unguarded.setupError).toBeNull(); + expect(unguarded.contractErrors).toEqual([expect.stringMatching(/^Paseo 0\.12\.0 has no client\.addFilePanel \(added in 0\.13\.0\), and the contribution threw: /)]); + const guarded = await evaluateClientBundle(bundle(`if (typeof client.addFilePanel === "function") ${fileCall}`), EXAMPLE, { paseoVersion: "0.12.0", icons }); + expect(guarded).toMatchObject({ setupError: null, contractErrors: [], contributions: [] }); + const inGuard = await evaluateClientBundle(bundle(`if ("addFilePanel" in client) ${fileCall}`), EXAMPLE, { paseoVersion: "0.13.0", icons }); + expect(inGuard).toMatchObject({ setupError: null, contractErrors: [], contributions: [{ method: "addFilePanel" }] }); + const modern = await evaluateClientBundle(bundle(fileCall), EXAMPLE, { paseoVersion: "0.13.0", icons }); + expect(modern).toMatchObject({ setupError: null, contractErrors: [], contributions: [{ method: "addFilePanel" }] }); + }); +}); + +describe("a guarded read of a missing method", () => { + it("does not take the blame for an unrelated throw", async () => { + const evaluation = await evaluateClientBundle(bundle(`if (typeof client.addFilePanel === "function") ${fileCall}; JSON.parse("{")`), EXAMPLE, { paseoVersion: "0.12.0", icons }); + expect(evaluation.contractErrors).toEqual([]); + expect(evaluation.setupError).toMatch(/JSON/); + }); + + it("accepts an SDK message stub as a label", async () => { + const withMessage = `const { message } = require("@getpaseo/plugin/client"); client.addFilePanel({ id: "pdf", title: message("title"), icon: "FileText", files: { extensions: ["pdf"] }, Component: function () {} })`; + expect((await evaluateClientBundle(bundle(withMessage), EXAMPLE, { paseoVersion: "0.14.0", icons })).contractErrors).toEqual([]); + }); +}); + +describe("which version ppd check applies", () => { + const plugin = (range: string, body: string) => { + const dir = scratch("ppd-contract-"); + writeFileSync(join(dir, "paseo-plugin.json"), JSON.stringify({ id: "contract", requirements: { paseo: range } })); + writeFileSync(join(dir, "index.client.ts"), `export default function contribute(client: any) {\n ${body};\n return () => {};\n}\n`); + return dir; + }; + const source = (version: string, evaluator: string) => { + const root = scratch("ppd-paseo-source-"); + mkdirSync(join(root, "packages/app/src/plugins"), { recursive: true }); + writeFileSync(join(root, "packages/app/package.json"), JSON.stringify({ version })); + writeFileSync(join(root, "packages/app/src/plugins/evaluate.ts"), evaluator); + return root; + }; + + const sourceHost = (version: string, evaluator: string) => ({ kind: "source" as const, root: source(version, evaluator) }); + + it("uses the oldest app requirements.paseo admits when there is no host", async () => { + const clientEval = async (dir: string) => (await runChecks(dir, { paseoSource: null, paseoApp: null })).find((r) => r.id === "client-eval"); + expect(await clientEval(plugin(">=0.13.0", fileCall))).toMatchObject({ status: "pass", message: "contributions: addFilePanel (Paseo 0.13.0 rules)" }); + expect(await clientEval(plugin(">=0.12.0", fileCall))).toMatchObject({ status: "fail", details: [expect.stringContaining("Paseo 0.12.0 has no client.addFilePanel"), "contributions: none (Paseo 0.12.0 rules)"] }); + }); + + it("warns when the host accepts the client but an older app the range admits rejects it", async () => { + const host = source("0.14.0", ""); + const notes = (await checkClient(plugin(">=0.12.0", fileCall), { paseoSource: host }))?.notes ?? []; + expect(notes[0]).toMatch(/^Paseo 0\.12\.0, which requirements\.paseo ">=0\.12\.0" admits, would reject this client .*: Paseo 0\.12\.0 has no client\.addFilePanel/); + expect((await checkClient(plugin(">=0.13.0", fileCall), { paseoSource: host }))?.notes.filter((note) => note.includes("would reject"))).toEqual([]); + }); + + it("checks against the range's lower bound when the range excludes the installed app", async () => { + const result = await checkClient(plugin(">=0.13.0", 'client.addAgentPanel({ id: "agent", title: "A", icon: "FileText", Component: function () {} })'), { paseoSource: source("0.12.0", "") }); + expect(result?.errors).toEqual([]); + expect(result?.notes[0]).toBe("the installed Paseo 0.12.0 is outside requirements.paseo, so it would not load this plugin; checked with Paseo 0.13.0 rules instead"); + }); + + it("reads a source checkout's version, raised to the release of the newer methods its evaluator defines", () => { + expect(paseoHostVersion(sourceHost("0.12.0", "addAgentPanel(contribution) {}\naddFilePanel(contribution) {}"))).toBe("0.13.0-beta.2"); + expect(paseoHostVersion(sourceHost("0.12.0", "addFilePanel(contribution) {}"))).toBe("0.13.0-beta.1"); + expect(paseoHostVersion(sourceHost("0.12.0", "addWorkspacePanel(contribution) {}"))).toBe("0.12.0"); + expect(paseoHostVersion(sourceHost("0.14.0", "addFilePanel(contribution) {}"))).toBe("0.14.0"); + expect(paseoHostVersion(null)).toBeUndefined(); + }); +}); From f3bca6165b9c5ae1bb766bc5e74e36c03c339b80 Mon Sep 17 00:00:00 2001 From: Gabriele Magno Date: Fri, 30 Oct 2026 16:04:30 +0100 Subject: [PATCH 2/2] docs: version-aware client checks and the Paseo 0.13 contract --- CHANGELOG.md | 6 ++++++ README.md | 2 +- .../src/routes/(docs)/docs/check/+page.svx | 2 +- .../routes/(docs)/docs/compatibility/+page.svx | 2 +- .../(docs)/docs/troubleshooting/+page.svx | 18 ++++++++++++++++++ skills/paseo-plugin-dev/SKILL.md | 2 +- .../references/host-contract.md | 9 +++++---- 7 files changed, 33 insertions(+), 8 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 2c09312..1fd660b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,6 +3,12 @@ ## Unreleased - Verified on Paseo 0.12.0: `ppd daemon up` and `ppd doctor` no longer print the version note on it. +- `ppd check` applies the client registration rules of the Paseo version it checks against: the app's or source checkout's version, or without a host the oldest release `requirements.paseo` admits. From 0.13.0 that includes file panels (`client.addFilePanel`, getpaseo/paseo#7411), agent panels (`client.addAgentPanel`), workspace panels without `context`, translated labels, `{ svg }` and component icons, and the `notification` timeline item. Before, every plugin that used them failed `client-eval`. +- On an app version without a method, `client.` is undefined like in the app: a guarded call passes, an unguarded one fails `client-eval`. +- `client-eval` warns when the host accepts the client but the oldest release `requirements.paseo` admits would reject it. `ppd install` and `ppd dev` print the same warning as a note. +- A source checkout's version is raised to the release of the newer client methods its evaluator defines, since its package version lags main until a release is cut. +- When `requirements.paseo` excludes the installed app (a prerelease counts by its stable core, like in Paseo), `client-eval` checks against the range's lower bound and warns that the app would not load the plugin. +- From 0.13.0 a label is a non-empty string or a message from the SDK's `message()`; anything else gets the SDK's error text. `"addFilePanel" in client` works as a guard. ## 0.1.0 (2026-10-18) diff --git a/README.md b/README.md index 750b344..1271d6a 100644 --- a/README.md +++ b/README.md @@ -146,7 +146,7 @@ Every command has `ppd --help`. | Compile | Paseo's own `compilePlugin`, from the installed app or `PASEO_SOURCE`; an esbuild replica (labeled `APPROXIMATION`) only when neither is found. Compile errors carry file:line:col. | | Client modules | Bundle requires only host-provided modules; no gesture handler, reanimated, safe-area or Lucide imports. | | Server bundle | Requires only host modules and Node built-ins; evaluated in a child process (Paseo's evaluator inside the 120 s compile step with the app or a checkout, a replica with a 30 s limit on the approximation); registered RPCs listed; the returned cleanup is called and handles it leaves open (servers, timers) are warnings. A `process.exit` or a hang fails. | -| Client eval | Factory runs in a child process against stub host modules, with the app's registration rules: ids, contexts, callbacks, duplicates, icons, cleanup. Any violation fails, because the app then drops the whole client. | +| Client eval | Factory runs in a child process against stub host modules, with the registration rules of the checked Paseo version (the app's or checkout's; without either, the oldest release `requirements.paseo` admits): ids, contexts, labels, callbacks, duplicates, icons, file panel selectors, cleanup. A method that version lacks is undefined, as in the app. Any violation fails, because the app then drops the whole client. When the range admits an older release whose rules reject the client, that is a warning. | | Hermes | No class syntax; `hermesc` parse and a smoke run in the Hermes VM when the binaries are found. | | Icons | Every contribution icon exists in the app's Lucide set (read from the app bundle). | | Size, deps, boundaries | Bundle sizes, runtime deps in `dependencies`, client/server import boundaries, `@types/node` range. | diff --git a/docs-site/src/routes/(docs)/docs/check/+page.svx b/docs-site/src/routes/(docs)/docs/check/+page.svx index 3764ec9..6e19e1b 100644 --- a/docs-site/src/routes/(docs)/docs/check/+page.svx +++ b/docs-site/src/routes/(docs)/docs/check/+page.svx @@ -47,7 +47,7 @@ It exits 1 on any `FAIL`; warnings and skips do not fail. All flags are on [Comm | `client-requires` | The client bundle requires only modules the app provides: the SDK, `react`, `react-native`, `react/jsx-runtime`, `zod`, `@tanstack/react-query`. Gesture handler, reanimated, safe-area, SVG, Lucide and DOM packages are not available to plugins. | | `server-requires` | The server bundle requires only host modules and Node built-ins; any other bare require would resolve from Paseo's install, not your plugin. | | `server-eval` | The server contribution runs in a child process and the RPCs it registered are listed: with the app or a checkout, Paseo's own evaluator runs it inside the compile step (120 s limit); on the approximation, a replica runs it with a 30 s limit. The returned cleanup is called; handles it leaves open (servers, timers) are warnings. A `process.exit`, a hang or a missing cleanup function fails. | -| `client-eval` | The client contribution runs in a child process against stub host modules and the app's registration rules: ids, contexts, titles, callbacks, components, duplicates, icons, the cleanup function, and methods the app's client context does not have. Any violation fails, because the app then drops the whole client. | +| `client-eval` | The client contribution runs in a child process against stub host modules and the registration rules of the checked Paseo version: the installed app's or `PASEO_SOURCE`'s, and on the approximation the oldest release `requirements.paseo` admits. The rules cover ids, contexts, titles, callbacks, components, duplicates, icons, file panel selectors, the cleanup function, and methods the app's client context does not have. A method added after that version (`addFilePanel` and `addAgentPanel` in 0.13.0) is undefined, as in the app. Any violation fails, because the app then drops the whole client. When the host accepts the client but the oldest release the range admits would reject it, that is a warning. | | `hermes-class` | No `class` syntax in the client bundle: it crashes plugin loading on Hermes, the phone JavaScript engine. | | `hermes-parse` | `hermesc` compiles the client bundle. Skipped without `hermesc`. | | `hermes-vm` | The Hermes VM evaluates the bundle and runs the contribution. Skipped without the VM. | diff --git a/docs-site/src/routes/(docs)/docs/compatibility/+page.svx b/docs-site/src/routes/(docs)/docs/compatibility/+page.svx index f5e4a49..c09cf49 100644 --- a/docs-site/src/routes/(docs)/docs/compatibility/+page.svx +++ b/docs-site/src/routes/(docs)/docs/compatibility/+page.svx @@ -38,7 +38,7 @@ Windows is not supported. | `@getpaseo/client` and `ws` inside `app.asar` | `agentTimeline` | the call fails naming the modules it looked for. | | `paseo daemon run --home`, `PASEO_HOME`, `PASEO_LISTEN` and the `config.json` keys | `ppd daemon up` | a start failure prints the daemon output and how it was started. | | Accessible names in the web UI ("New workspace", "Open menu", "Workspace actions", "Search commands") | `ppd web`, `PaseoWeb` | a timeout names the label it waited for. | -| Rules vendored from Paseo (client registration, manifest schema, build options) | every `ppd check` (`manifest`, `client-eval`), the client check in `ppd install` and `ppd dev`, and the approximation's compile | drift shows up in the weekly CI job against Paseo main. | +| Rules vendored from Paseo (client registration for 0.12 and 0.13 or later, the release that added each newer client method, manifest schema, build options) | every `ppd check` (`manifest`, `client-eval`), the client check in `ppd install` and `ppd dev`, and the approximation's compile | drift shows up in the weekly CI job against Paseo main. | `ppd daemon up` prints a note when the installed Paseo is not {meta.verifiedPaseo}, and `ppd doctor` shows the same text as a warning on its `paseo CLI` line: diff --git a/docs-site/src/routes/(docs)/docs/troubleshooting/+page.svx b/docs-site/src/routes/(docs)/docs/troubleshooting/+page.svx index fcc33ad..89a759b 100644 --- a/docs-site/src/routes/(docs)/docs/troubleshooting/+page.svx +++ b/docs-site/src/routes/(docs)/docs/troubleshooting/+page.svx @@ -32,7 +32,11 @@ prints the same lines and keeps watching. Each line under `client:` is a registr - `Unknown Lucide icon: X`: the app's Lucide build has no icon named X. - `Command Center item X has no icon`, `Workspace panel X has invalid context`, `Screen X is not a component`. +- `File panel X has invalid selector`: `files` takes only `extensions` (without the dot) and `filenames`, plain + names with no `/`, `\`, `*` or `?`, at least one in all. - `client.X is not part of the app's plugin client context (calling it throws)`. +- `Paseo 0.12.0 has no client.addFilePanel (added in 0.13.0), and the contribution threw: ...`: see + [below](#older-paseo). - `Plugin contribution must return a cleanup function`. Fix the line, save, and `ppd dev` re-checks on reload. `ppd check` reports the same rules as `client-eval`. @@ -89,6 +93,20 @@ approximation; with the app or a checkout the server is evaluated inside the com blocking loop at module load or in `contribute` ends here. `plugin code called process.exit(N)` means what it says: the host would lose the whole plugin process. A timer or server left running after the cleanup is a warning, not a failure. +

Paseo 0.12.0 would reject this client

+ +```text +WARN client-eval Paseo 0.12.0, which requirements.paseo ">=0.12.0" admits, would reject this client and show none of its UI. Raise requirements.paseo or use only what that release accepts + Paseo 0.12.0 has no client.addFilePanel (added in 0.13.0), and the contribution threw: client.addFilePanel is not a function. Guard the call with typeof, or require a newer Paseo + contributions: addFilePanel (Paseo 0.14.0 rules) +``` + +Paseo 0.13.0 added file panels and agent panels (betas: file panels in beta.1, agent and context-free panels in beta.2), made `context` optional on workspace panels, and accepts translated +labels and `{ svg }` or component icons. An older app the range admits throws on these and drops the whole client; +apps below `requirements.paseo` skip the plugin. Declare `"paseo": ">=0.13.0"`, or guard each newer call with +`typeof client.addFilePanel === "function"`. Without a host, `ppd check` applies the oldest admitted release's rules +directly, so the same problem is a `FAIL`. `ppd install` and `ppd dev` print the warning as a `note:` line. +

Dev daemon

no running dev daemon

diff --git a/skills/paseo-plugin-dev/SKILL.md b/skills/paseo-plugin-dev/SKILL.md index e5f2864..6b6a80c 100644 --- a/skills/paseo-plugin-dev/SKILL.md +++ b/skills/paseo-plugin-dev/SKILL.md @@ -30,7 +30,7 @@ These protect the user's real Paseo. Each has a `ppd` guard; keep them when work Run in order. Each step ends on its stated observable. -1. **Contract check**: `ppd check `. Done when there are 0 FAIL. It compiles and evaluates with the installed Paseo app's own compiler and checks icons against the app's Lucide set. Without the app (Linux, CI) it falls back to an esbuild replica and prints `APPROXIMATION`: say so in your report rather than claiming the real host accepted the plugin. `PASEO_SOURCE=` tests against unreleased Paseo instead. +1. **Contract check**: `ppd check `. Done when there are 0 FAIL. It compiles and evaluates with the installed Paseo app's own compiler and checks icons against the app's Lucide set. Without the app (Linux, CI) it falls back to an esbuild replica and prints `APPROXIMATION`: say so in your report rather than claiming the real host accepted the plugin. `PASEO_SOURCE=` tests against unreleased Paseo instead. A `client-eval` WARN naming `requirements.paseo` means the oldest app the range admits would reject the client (file and agent panels need 0.13.0): raise the range or guard the call. 2. **Dev daemon**: `ppd daemon up --workspace --caffeinate`. Done when it prints a URL. It runs detached with a pidfile, so harness time limits do not kill it. Its home is under `$TMPDIR` (on macOS a `/var/folders/...` path, not `/tmp`). 3. **Install**: `ppd install ` (directory) and `ppd install --git` (committed HEAD through the manifest `build`, like a registry install; installed as `-git` next to the directory install). Done when each prints `running` and `client: passes the app's registration rules`, exit 0. `client-rejected` means the app would drop the whole client (an unknown icon, a bad id): fix it before looking at the UI. 4. **Real UI**: `ppd web --shot out/desktop.png --click ""` and `ppd web --viewport 390x844 --shot out/phone.png --command ""`. Done when you have looked at both screenshots and `ppd web` exits 0 with `console errors: none` and `plugin evaluation errors: none`. Console errors alone are not enough: the app reports a client that failed to evaluate only as a warning. diff --git a/skills/paseo-plugin-dev/references/host-contract.md b/skills/paseo-plugin-dev/references/host-contract.md index 4e9eca9..9dbc642 100644 --- a/skills/paseo-plugin-dev/references/host-contract.md +++ b/skills/paseo-plugin-dev/references/host-contract.md @@ -1,6 +1,6 @@ # Paseo plugin host contract -What Paseo 0.11 and 0.12 actually give a plugin at runtime. `ppd check` tests the rows marked (checked). +What Paseo 0.11 to 0.14 actually give a plugin at runtime. `ppd check` tests the rows marked (checked). | Area | Contract | What to do | | --- | --- | --- | @@ -8,8 +8,9 @@ What Paseo 0.11 and 0.12 actually give a plugin at runtime. `ppd check` tests th | Gestures (checked) | No `react-native-gesture-handler` or `react-native-reanimated`. | Build pinch and double tap from `onResponder*` / `PanResponder` and `Animated`. | | Safe area (checked) | Plugin panels get no safe-area insets (getpaseo/paseo#5866, PR #5867). The Android nav bar can cover the last rows. | Pad the bottom yourself; runtime-detect a host `useSafeAreaInsets` export if one appears. | | Horizontal scroll | A plugin horizontal `ScrollView` is not registered with the host, so a fast right swipe on a zoomed page opens the mobile sidebar. | Known limit; keep horizontal panning short or behind a mode. | -| Icons (checked) | Contribution `icon` fields are Lucide names, validated at registration: an unknown name throws, and the app then drops the whole plugin client (every contribution, not only that item) with just a console warning. `Icon` from `/client/react-native` renders nothing for an unknown name. No `lucide-react-native` import. | `ppd check` checks names against the installed app's Lucide set; `ppd install` and `ppd web` report a rejected client. | -| Client registration (checked) | Contribution ids match `/^[a-z][a-z0-9-]*$/` and are unique per kind; `context` and callbacks are validated; the factory must return a cleanup function. Any violation drops the whole client, like an unknown icon. | `ppd check` applies the app's rules. | +| Icons (checked) | Contribution `icon` fields are Lucide names before 0.13.0; from 0.13.0 also `{ svg }` (no scripts, styles, event handlers or external hrefs) or a component (not for attachment sources). They are validated at registration: an unknown name throws, and the app then drops the whole plugin client (every contribution, not only that item) with just a console warning. `Icon` from `/client/react-native` renders nothing for an unknown name. No `lucide-react-native` import. | `ppd check` checks names against the installed app's Lucide set; `ppd install` and `ppd web` report a rejected client. | +| Client registration (checked) | Contribution ids match `/^[a-z][a-z0-9-]*$/` and are unique per kind; `context` and callbacks are validated; file panel selectors list extensions without dots and plain filenames, no paths or wildcards; the factory must return a cleanup function. Any violation drops the whole client, like an unknown icon. | `ppd check` applies the rules of the checked app version. | +| Paseo 0.13 client contract (checked) | 0.13.0 added `client.addFilePanel` and `client.addAgentPanel`, made workspace panel `context` optional, and accepts translated labels and `{ svg }` or component icons. On an older app the new methods are undefined and the rest throws at registration, so the whole client is dropped. Apps below `requirements.paseo` skip the plugin. | Declare `"paseo": ">=0.13.0"`, or guard with `typeof client.addFilePanel === "function"`. `ppd check` warns when the oldest app the range admits would reject the client. | | Cleanup (checked) | The server contribution must return a cleanup too; it runs when the plugin child shuts down (reload, disable, remove). A server, socket or interval it leaves open can keep the old child alive or its port busy for the next load. | Close everything you open; `ppd check` warns about handles left open after cleanup. | | Hermes (checked) | iOS and Android evaluate the client bundle from source on Hermes. Class syntax fails to parse (getpaseo/paseo#5783), including classes inside bundled dependencies. Paseo lowers async/await for you. | Functions and closures instead of classes; check dependencies too. | | Server bundle (checked) | Compiled to one CJS string and `eval`'d in a plugin subprocess. Bare requires other than host modules and Node built-ins resolve from Paseo's install, not the plugin. WASM must be inlined (a 12.6 MB bundle parsed in about 60 ms). No native addons, no file-path WASM, no assumption of system binaries. | Pure JS/WASM dependencies, bundled. | @@ -18,6 +19,6 @@ What Paseo 0.11 and 0.12 actually give a plugin at runtime. `ppd check` tests th | RPC timeout | 30 s per RPC (`REQUEST_TIMEOUT_MS`). Handlers get no abort signal (hooks do get `context.signal`). After a timeout the handler keeps running and holding memory and concurrency. | Deadline every heavy job (`Promise.race`), cap input sizes, test worst-case fixtures with `assertWithinRpcBudget`. Synchronous WASM cannot be interrupted. | | Crashes | A crashed plugin child is not respawned (getpaseo/paseo#6821). One out-of-memory parse takes the plugin down until `paseo plugin reload`. | Size and decompression caps before parsing; stream large formats. | | Response size | Direct websocket messages cap at 100 MiB; clients behind the relay should budget well under 32 MiB. Large base64 images add up fast. | Page or chunk responses; budget bytes per response. | -| MIME and previews | The daemon labels many binaries `application/octet-stream`; the Files tree has no previewer hook for plugins (getpaseo/paseo#3109, #5930). | Detect formats by magic bytes; provide your own entry points (panel, Command Center item, slash command). | +| MIME and previews | Daemons before 0.13.0 label many binaries, PDFs included, `application/octet-stream`. From 0.13.0 a file panel (`client.addFilePanel`) renders the file tab for the extensions and filenames it claims; before that, plugins have no previewer hook (getpaseo/paseo#3109, #5930). | Detect formats by magic bytes; on 0.13.0 and later register a file panel, otherwise provide your own entry points (panel, Command Center item, slash command). | | Media | No native video primitive (#4562). Host `playAudio` exists from 0.11.2. | Plan media features around what the host exposes. | | Theme and layout | Color every `Text` from `theme.colors`; size layout from `layout.compact`. No HTML elements, no `className`. | Test both `ppd web` viewports. |