Compare commits

..
31 changed files with 2330 additions and 190 deletions
+5 -3
View File
@@ -433,7 +433,9 @@ query cache. Explicit SDK targets follow the [host API contract](../public-docs/
Workspace panels, Command Center items, and client slash commands are client contributions. The
daemon transports their compiled bundle without interpreting placement or callbacks. Panel props
contain workspace and agent IDs. Required-selector hooks read normalized client state synchronously
carry `workspaceId`, validated read-only `params` (with host-enforced `agentId` on agent panels),
`revision`, and `tab`; optional `identity(params)` sets the coalescing key on the persisted
`plugin` target. Required-selector hooks read normalized client state synchronously
and use shallow equality, so a panel does not subscribe to fields it does not render. Command
callbacks materialize their snapshots only when invoked. Contribution discovery and panel opening
never fetch active context through plugin RPC. Snapshot DTOs are deeply readonly and frozen at
@@ -442,8 +444,8 @@ runtime so plugin code cannot mutate normalized app state or a memoized selectio
current installed-plugin catalog. A missing contribution renders unavailable inside the tab.
Panels declare `locations: ["workspace", "explorer"]` to opt into Explorer hosting; omission means
workspace only. Location controls hosting, not context. An agent panel target keeps its `agentId`
when moved between hosts. Explorer configuration can create workspace-context panels and remove
existing agent-context instances, but it cannot create an agent panel without an agent-aware command.
and `params` when moved between hosts. UI launchers only offer workspace-context panels whose
`params` schema accepts `{}`.
`AgentChat` renders the agent tab's own chain (`AgentPanelContent` in
`packages/app/src/panels/agent-panel.tsx`) through `packages/app/src/agent-embed`. The chain takes
@@ -326,3 +326,286 @@ test("a file a plugin opens in another workspace waits there on a phone", async
});
});
});
const PARAMS_AND_IDENTITY_ENTRY = `import {
type PluginClientContext,
type PluginWorkspacePanelProps,
useTabState,
useWorkspaceLayout,
} from "@getpaseo/plugin/client";
import { Pressable, Text, View } from "react-native";
import { z } from "zod";
const decisionParams = z.object({ decisionId: z.string() });
const decisionStateSchema = z.object({ note: z.string() });
function DecisionsPanel({
params,
revision,
tab,
theme,
}: PluginWorkspacePanelProps<z.infer<typeof decisionParams>>) {
const [state, setState] = useTabState(tab, decisionStateSchema, { note: "initial" });
return (
<View style={{ flex: 1, padding: 16, gap: 8 }}>
<Text style={{ color: theme.colors.foreground }}>
{\`decision:\${params.decisionId}|rev:\${revision}|state:\${state.note}\`}
</Text>
<Pressable
accessibilityRole="button"
onPress={() => setState({ note: "pinned" })}
>
<Text style={{ color: theme.colors.foreground }}>Pin decision state</Text>
</Pressable>
</View>
);
}
const prParams = z.object({
prNumber: z.number(),
commentId: z.string().optional(),
});
function PrPanel({
workspaceId,
params,
revision,
theme,
}: PluginWorkspacePanelProps<z.infer<typeof prParams>>) {
const readBack = useWorkspaceLayout(workspaceId, (layout) => {
const found = layout.tabs.find((entry) => entry.panelId === "workspace-layout/pr" && entry.params.prNumber === params.prNumber);
return found ? JSON.stringify(found.params) : "missing";
});
return (
<View style={{ flex: 1, padding: 16, gap: 8 }}>
<Text style={{ color: theme.colors.foreground }}>
{\`pr:\${params.prNumber}|comment:\${params.commentId ?? "none"}|rev:\${revision}\`}
</Text>
<Text style={{ color: theme.colors.foregroundMuted }}>
{\`readback:\${params.prNumber}:\${readBack}\`}
</Text>
</View>
);
}
function StaticPanel({ theme }: PluginWorkspacePanelProps) {
return (
<View style={{ flex: 1, padding: 16 }}>
<Text style={{ color: theme.colors.foreground }}>Static parameterless panel</Text>
</View>
);
}
export default function contribute(client: PluginClientContext) {
client.addWorkspacePanel({
id: "decisions",
title: "Decisions",
icon: "ListChecks",
locations: ["explorer"],
params: decisionParams,
Component: DecisionsPanel,
});
client.addWorkspacePanel({
id: "pr",
title: "PR",
icon: "GitPullRequest",
params: prParams,
identity: (p) => String(p.prNumber),
Component: PrPanel,
});
client.addWorkspacePanel({
id: "static",
title: "Static",
icon: "Square",
locations: ["workspace", "explorer"],
Component: StaticPanel,
});
client.addCommandCenterItem({
id: "open-decision-d1",
title: "Open decision D1",
icon: "ListChecks",
context: "workspace",
onSelect({ workspaceLayout }) {
workspaceLayout.open({ panelId: "decisions", params: { decisionId: "D1" } });
},
});
client.addCommandCenterItem({
id: "open-decision-d2",
title: "Open decision D2",
icon: "ListChecks",
context: "workspace",
onSelect({ workspaceLayout }) {
workspaceLayout.open({ panelId: "decisions", params: { decisionId: "D2" } });
},
});
client.addCommandCenterItem({
id: "open-pr-1a",
title: "Open PR 1 comment a",
icon: "GitPullRequest",
context: "workspace",
onSelect({ workspaceLayout }) {
workspaceLayout.open({ panelId: "pr", params: { prNumber: 1, commentId: "a" } });
},
});
client.addCommandCenterItem({
id: "open-pr-2x",
title: "Open PR 2 comment x",
icon: "GitPullRequest",
context: "workspace",
onSelect({ workspaceLayout }) {
workspaceLayout.open({ panelId: "pr", params: { prNumber: 2, commentId: "x" } });
},
});
client.addCommandCenterItem({
id: "open-pr-1b",
title: "Open PR 1 comment b",
icon: "GitPullRequest",
context: "workspace",
onSelect({ workspaceLayout }) {
workspaceLayout.open({ panelId: "pr", params: { prNumber: 1, commentId: "b" } });
},
});
return () => {};
}
`;
async function expectNewTabLauncherPanelAvailability(
page: Page,
input: { present: readonly string[]; absent: readonly string[] },
): Promise<void> {
await mainPanes(page).first().getByTestId("workspace-new-tab-button").click();
const menu = page.getByTestId("workspace-new-tab-menu").filter({ visible: true });
for (const label of input.present) {
await expect(menu.getByText(label, { exact: true })).toBeVisible();
}
for (const label of input.absent) {
await expect(menu.getByText(label, { exact: true })).toHaveCount(0);
}
await page.keyboard.press("Escape");
}
async function expectDecisionsPanel(
page: Page,
input: { tabs: number; decisionId: string; revision: number; stateNote: string },
): Promise<void> {
await expect(
explorer(page)
.getByTestId("workspace-tabs-row")
.getByRole("button", { name: "Decisions", exact: true }),
).toHaveCount(input.tabs);
await expect(
explorer(page).getByText(
`decision:${input.decisionId}|rev:${input.revision}|state:${input.stateNote}`,
{ exact: true },
),
).toBeVisible();
}
async function pinDecisionState(page: Page): Promise<void> {
await explorer(page).getByRole("button", { name: "Pin decision state" }).click();
}
async function expectPrPanel(
page: Page,
input: {
tabs: number;
prNumber: number;
commentId: string;
revision: number;
persistedParams?: { prNumber: number; commentId: string };
},
): Promise<void> {
await expect(
mainPanes(page)
.first()
.getByTestId("workspace-tabs-row")
.getByRole("button", { name: "PR", exact: true }),
).toHaveCount(input.tabs);
await expect(
page.getByText(`pr:${input.prNumber}|comment:${input.commentId}|rev:${input.revision}`, {
exact: true,
}),
).toBeVisible();
if (input.persistedParams) {
await expect(
page.getByText(`readback:${input.prNumber}:${JSON.stringify(input.persistedParams)}`, {
exact: true,
}),
).toBeVisible();
}
}
test("reused Explorer panels and keyed workspace panels deliver params, identity, revision, and tab state", async ({
page,
}) => {
test.setTimeout(180_000);
const example = await copyPluginExample("workspace-layout");
await writeFile(path.join(example.directory, "index.client.tsx"), PARAMS_AND_IDENTITY_ENTRY);
const workspace = await seedMockAgentWorkspace({
repoPrefix: "plugin-params-identity-",
title: AGENT_TITLE,
repo: { files: REPO_FILES },
});
try {
await withPluginInstalled(example.directory, async () => {
await page.setViewportSize(WIDE);
await openAgentRoute(page, workspace);
await approveClientPluginsInUi(page, ["workspace-layout"]);
await test.step("parameterless launcher hides panels with required params and keeps parameterless ones", async () => {
await expectNewTabLauncherPanelAvailability(page, {
present: ["Static"],
absent: ["PR", "Decisions"],
});
});
await test.step("reused Explorer panel updates params in place, bumps revision, and preserves tab.state", async () => {
await runCommand(page, "Open decision D1");
await expectDecisionsPanel(page, {
tabs: 1,
decisionId: "D1",
revision: 1,
stateNote: "initial",
});
await pinDecisionState(page);
await expectDecisionsPanel(page, {
tabs: 1,
decisionId: "D1",
revision: 1,
stateNote: "pinned",
});
await runCommand(page, "Open decision D2");
await expectDecisionsPanel(page, {
tabs: 1,
decisionId: "D2",
revision: 2,
stateNote: "pinned",
});
});
await test.step("keyed panel opens separate tabs per identity key and updates hint params on reveal", async () => {
await runCommand(page, "Open PR 1 comment a");
await expectPrPanel(page, { tabs: 1, prNumber: 1, commentId: "a", revision: 1 });
await runCommand(page, "Open PR 2 comment x");
await expectPrPanel(page, { tabs: 2, prNumber: 2, commentId: "x", revision: 1 });
await runCommand(page, "Open PR 1 comment b");
await expectPrPanel(page, {
tabs: 2,
prNumber: 1,
commentId: "b",
revision: 2,
persistedParams: { prNumber: 1, commentId: "b" },
});
});
});
} finally {
await workspace.cleanup();
await example.cleanup();
}
});
@@ -50,5 +50,60 @@ describe("panel manifest", () => {
expect(panelResourceKey({ kind: "file", path: "src/a.ts" })).not.toBe(
panelResourceKey({ kind: "file", path: "src/b.ts" }),
);
expect(
panelResourceKey({
kind: "plugin",
pluginId: "review",
panelId: "decisions",
context: "workspace",
params: { decisionId: "D1" },
}),
).toBe(
panelResourceKey({
kind: "plugin",
pluginId: "review",
panelId: "decisions",
context: "workspace",
params: { decisionId: "D2" },
}),
);
expect(
panelResourceKey({
kind: "plugin",
pluginId: "review",
panelId: "pr",
context: "workspace",
params: { prNumber: 1, commentId: "a" },
identityKey: "1",
}),
).toBe(
panelResourceKey({
kind: "plugin",
pluginId: "review",
panelId: "pr",
context: "workspace",
params: { prNumber: 1, commentId: "b" },
identityKey: "1",
}),
);
expect(
panelResourceKey({
kind: "plugin",
pluginId: "review",
panelId: "pr",
context: "workspace",
params: { prNumber: 1 },
identityKey: "1",
}),
).not.toBe(
panelResourceKey({
kind: "plugin",
pluginId: "review",
panelId: "pr",
context: "workspace",
params: { prNumber: 2 },
identityKey: "2",
}),
);
});
});
+7 -3
View File
@@ -280,10 +280,14 @@ const manifests = {
singleton: false,
oneTabPerInstance: false,
compactSheet: null,
resourceKey: (target) =>
target.context === "agent"
resourceKey: (target) => {
if (target.identityKey !== undefined) {
return `${target.pluginId}:${target.panelId}:keyed:${target.context}:${target.identityKey}`;
}
return target.context === "agent"
? `${target.pluginId}:${target.panelId}:agent:${target.agentId}`
: `${target.pluginId}:${target.panelId}:workspace`,
: `${target.pluginId}:${target.panelId}:workspace`;
},
// Plugin panels are named by their registration, not by this kind.
public: null,
},
+54 -15
View File
@@ -10,22 +10,67 @@ import type {
} from "@getpaseo/plugin/client";
import type { PluginClientStateSource } from "@getpaseo/plugin/client/host";
import { resolvePluginPanelOpenLocation } from "./workspace-panels/locations";
import { buildPluginPanelTarget } from "./workspace-panels/resolution";
import { parsePluginOpenScreenInput } from "./surface-contribution";
import type { InstalledPlugin } from "./types";
import { pluginWorkspaceLayoutSource } from "./workspace-layout";
export interface PluginPanelOpenPayload {
params?: Record<string, string | number>;
identityKey?: string;
}
export interface PluginNavigation {
openSettings(pluginId: string, screenId: string): void;
openSurface(pluginId: string, surfaceId: string, params?: PluginScreenParams): void;
openWorkspacePanel(pluginId: string, panelId: string, location: PluginPanelLocation): void;
openWorkspacePanel(
pluginId: string,
panelId: string,
location: PluginPanelLocation,
resolved?: PluginPanelOpenPayload,
): void;
openAgentPanel(
pluginId: string,
panelId: string,
agentId: string,
location: PluginPanelLocation,
resolved?: PluginPanelOpenPayload,
): void;
}
export function openPluginPanelFromLegacyCommand(input: {
plugin: InstalledPlugin;
navigation: PluginNavigation;
panelId: string;
agentId?: string;
options?: { location?: PluginPanelLocation };
}): void {
const { plugin, navigation, panelId, agentId, options } = input;
const panel = plugin.workspacePanels.find(
(candidate) =>
candidate.id === panelId && (agentId !== undefined || candidate.context === "workspace"),
);
if (!panel) throw new Error(`Workspace panel is unavailable: ${panelId}`);
const location = resolvePluginPanelOpenLocation(panel, options?.location);
const rawParams = panel.context === "agent" ? { agentId } : {};
const target = buildPluginPanelTarget(plugin.id, panel, rawParams);
if (!target) {
throw new Error(`Panel "${plugin.id}/${panelId}" does not accept these params`);
}
const resolved: PluginPanelOpenPayload | undefined =
target.params !== undefined || target.identityKey !== undefined
? {
...(target.params !== undefined ? { params: target.params } : {}),
...(target.identityKey !== undefined ? { identityKey: target.identityKey } : {}),
}
: undefined;
if (target.context === "workspace") {
navigation.openWorkspacePanel(plugin.id, panelId, location, resolved);
return;
}
navigation.openAgentPanel(plugin.id, panelId, target.agentId, location, resolved);
}
export function createPluginCapabilities(
plugin: InstalledPlugin,
navigation: PluginNavigation,
@@ -67,14 +112,13 @@ export function createPluginAgentActionContext(input: {
agent,
workspaceLayout: pluginWorkspaceLayoutSource(plugin).layout(workspace.id),
openPanel(panelId, options) {
const panel = plugin.workspacePanels.find((candidate) => candidate.id === panelId);
if (!panel) throw new Error(`Workspace panel is unavailable: ${panelId}`);
const location = resolvePluginPanelOpenLocation(panel, options?.location);
if (panel.context === "workspace") {
navigation.openWorkspacePanel(plugin.id, panelId, location);
return;
}
navigation.openAgentPanel(plugin.id, panelId, agent.id, location);
openPluginPanelFromLegacyCommand({
plugin,
navigation,
panelId,
agentId: agent.id,
options,
});
},
};
}
@@ -94,12 +138,7 @@ export function createPluginWorkspaceActionContext(input: {
workspace,
workspaceLayout: pluginWorkspaceLayoutSource(plugin).layout(workspace.id),
openPanel(panelId, options) {
const panel = plugin.workspacePanels.find(
(candidate) => candidate.id === panelId && candidate.context === "workspace",
);
if (!panel) throw new Error(`Workspace panel is unavailable: ${panelId}`);
const location = resolvePluginPanelOpenLocation(panel, options?.location);
navigation.openWorkspacePanel(plugin.id, panelId, location);
openPluginPanelFromLegacyCommand({ plugin, navigation, panelId, options });
},
};
}
@@ -2,9 +2,12 @@ import type { PluginClientStateSource } from "@getpaseo/plugin/client/host";
import type { CommandCenterContribution } from "@/command-center/contributions";
import { getCommandCenterIcon } from "@/command-center/icon";
import { pluginIconComponent } from "../icons";
import { resolvePluginPanelOpenLocation } from "../workspace-panels/locations";
import type { InstalledPlugin } from "../types";
import { createPluginCapabilities, type PluginNavigation } from "../actions";
import {
createPluginCapabilities,
openPluginPanelFromLegacyCommand,
type PluginNavigation,
} from "../actions";
import { pluginWorkspaceLayoutSource } from "../workspace-layout";
export interface PluginCommandCenterSource {
@@ -43,12 +46,12 @@ export function buildPluginCommandCenterContributions(
workspace,
workspaceLayout,
openPanel(panelId, options) {
const panel = plugin.workspacePanels.find(
(candidate) => candidate.id === panelId && candidate.context === "workspace",
);
if (!panel) throw new Error(`Workspace panel is unavailable: ${panelId}`);
const location = resolvePluginPanelOpenLocation(panel, options?.location);
source.navigation.openWorkspacePanel(plugin.id, panelId, location);
openPluginPanelFromLegacyCommand({
plugin,
navigation: source.navigation,
panelId,
options,
});
},
});
return;
@@ -62,14 +65,13 @@ export function buildPluginCommandCenterContributions(
agent,
workspaceLayout,
openPanel(panelId, options) {
const panel = plugin.workspacePanels.find((candidate) => candidate.id === panelId);
if (!panel) throw new Error(`Workspace panel is unavailable: ${panelId}`);
const location = resolvePluginPanelOpenLocation(panel, options?.location);
if (panel.context === "workspace") {
source.navigation.openWorkspacePanel(plugin.id, panelId, location);
return;
}
source.navigation.openAgentPanel(plugin.id, panelId, agent.id, location);
openPluginPanelFromLegacyCommand({
plugin,
navigation: source.navigation,
panelId,
agentId: agent.id,
options,
});
},
});
} catch (error) {
+36
View File
@@ -515,6 +515,42 @@ describe("evaluatePluginClientBundle", () => {
]);
});
it("collects params schema and identity on workspace and agent panels and rejects invalid values", () => {
const plugin = evaluatePluginClientBundle(
"panels",
bundle(`
const { z } = require("zod");
const Component = () => null;
const schema = z.object({ prNumber: z.number() });
const identity = (p) => String(p.prNumber);
plugin.addWorkspacePanel({ id: "pr", title: "PR", icon: "File", params: schema, identity, Component });
plugin.addAgentPanel({ id: "review", title: "Review", icon: "File", params: schema, identity, Component });
`),
);
expect(plugin.workspacePanels[0]?.paramsSchema).toBeDefined();
expect(plugin.workspacePanels[0]?.identity).toBeTypeOf("function");
expect(plugin.workspacePanels[1]?.paramsSchema).toBeDefined();
expect(plugin.workspacePanels[1]?.identity).toBeTypeOf("function");
expect(() =>
evaluatePluginClientBundle(
"panels",
bundle(`
plugin.addWorkspacePanel({ id: "bad-schema", title: "Bad", icon: "File", params: {}, Component: () => null });
`),
),
).toThrow("Workspace panel bad-schema has invalid params schema");
expect(() =>
evaluatePluginClientBundle(
"panels",
bundle(`
plugin.addWorkspacePanel({ id: "bad-identity", title: "Bad", icon: "File", identity: "nope", Component: () => null });
`),
),
).toThrow("Workspace panel bad-identity has invalid identity function");
});
it("registers inline SVG and component icons", () => {
const svg = '<svg viewBox="0 0 24 24"><path fill="currentColor" d="M4 4h16v16H4z" /></svg>';
const plugin = evaluatePluginClientBundle(
+61 -15
View File
@@ -17,6 +17,7 @@ import { type PluginCleanup } from "@getpaseo/plugin";
import {
type PluginClientContext,
type PluginAgentPanelContribution,
type PluginPanelParamsSchema,
type PluginWorkspacePanelContribution as WorkspacePanelInput,
type PluginScreenProps,
type PluginScreenTitle,
@@ -255,7 +256,14 @@ export function runPluginClientBundle(
() => ids.delete(normalizedId),
);
}
function registerPanel(contribution: PluginWorkspacePanelContribution): PluginCleanup {
type EvaluatedPanelRegistrationInput =
| (Omit<Extract<PluginWorkspacePanelContribution, { context: "workspace" }>, "paramsSchema"> & {
params?: PluginPanelParamsSchema;
})
| (Omit<Extract<PluginWorkspacePanelContribution, { context: "agent" }>, "paramsSchema"> & {
params?: PluginPanelParamsSchema;
});
function registerPanel(contribution: EvaluatedPanelRegistrationInput): PluginCleanup {
const normalizedId = requireId(contribution.id, "workspace panel id");
if (workspacePanelIds.has(normalizedId)) {
throw new Error(`Duplicate workspace panel: ${normalizedId}`);
@@ -266,18 +274,42 @@ export function runPluginClientBundle(
if (typeof contribution.Component !== "function") {
throw new Error(`Workspace panel ${normalizedId} is not a component`);
}
let paramsSchema: PluginPanelParamsSchema | undefined;
if (contribution.params !== undefined) {
if (!contribution.params || typeof contribution.params.safeParse !== "function") {
throw new Error(`Workspace panel ${normalizedId} has invalid params schema`);
}
paramsSchema = contribution.params;
}
if (contribution.identity !== undefined && typeof contribution.identity !== "function") {
throw new Error(`Workspace panel ${normalizedId} has invalid identity function`);
}
const locations = normalizePanelLocations(normalizedId, contribution.locations);
workspacePanelIds.add(normalizedId);
return register(
collector.workspacePanels,
{
...contribution,
id: normalizedId,
title,
icon,
locations,
},
() => workspacePanelIds.delete(normalizedId),
const evaluated: EvaluatedPlugin["workspacePanels"][number] =
contribution.context === "agent"
? {
id: normalizedId,
title,
icon,
context: "agent",
locations,
...(paramsSchema ? { paramsSchema } : {}),
...(contribution.identity ? { identity: contribution.identity } : {}),
Component: contribution.Component,
}
: {
id: normalizedId,
title,
icon,
context: "workspace",
locations,
...(paramsSchema ? { paramsSchema } : {}),
...(contribution.identity ? { identity: contribution.identity } : {}),
Component: contribution.Component,
};
return register(collector.workspacePanels, evaluated, () =>
workspacePanelIds.delete(normalizedId),
);
}
const pluginContext: PluginClientContext = {
@@ -460,17 +492,31 @@ export function runPluginClientBundle(
() => filePanelIds.delete(panelId),
);
},
addAgentPanel(contribution: PluginAgentPanelContribution<PluginText>) {
return registerPanel({ ...contribution, context: "agent" });
addAgentPanel(
contribution:
| PluginAgentPanelContribution<PluginText, PluginPanelParamsSchema>
| PluginAgentPanelContribution<PluginText>,
) {
return registerPanel({
...contribution,
context: "agent",
} as Parameters<typeof registerPanel>[0]);
},
addWorkspacePanel(input: WorkspacePanelInput<PluginText>) {
addWorkspacePanel(
input:
| WorkspacePanelInput<PluginText, PluginPanelParamsSchema>
| WorkspacePanelInput<PluginText>,
) {
// COMPAT(pluginAgentPanelAlias): added in v0.13.0, remove after 2027-04-23
if (input.context === "agent") return pluginContext.addAgentPanel(input);
// COMPAT(pluginPanelFlatProps): added in v0.13.0, remove after 2027-04-23
if (input.context !== undefined && input.context !== "workspace") {
throw new Error(`Workspace panel ${input.id} has invalid context`);
}
return registerPanel({ ...input, context: "workspace" });
return registerPanel({
...input,
context: "workspace",
} as Parameters<typeof registerPanel>[0]);
},
addCommandCenterItem(contribution: PluginCommandCenterItemContribution) {
const normalizedId = requireId(contribution.id, "Command Center item id");
+19 -4
View File
@@ -86,21 +86,36 @@ export function createPluginNavigation(input: {
openSurface(pluginId, surfaceId, params) {
pushPluginScreenRoute({ serverId, pluginId, screenId: surfaceId, params });
},
openWorkspacePanel(pluginId, panelId, location) {
openWorkspacePanel(pluginId, panelId, location, resolved) {
if (!workspaceId) throw new Error("No active workspace");
navigateToWorkspace({
serverId,
workspaceId,
target: { kind: "plugin", pluginId, panelId, context: "workspace" },
target: {
kind: "plugin",
pluginId,
panelId,
context: "workspace",
...(resolved?.params !== undefined ? { params: resolved.params } : {}),
...(resolved?.identityKey !== undefined ? { identityKey: resolved.identityKey } : {}),
},
placement: placement(location),
});
},
openAgentPanel(pluginId, panelId, agentId, location) {
openAgentPanel(pluginId, panelId, agentId, location, resolved) {
if (!workspaceId) throw new Error("No active workspace");
navigateToWorkspace({
serverId,
workspaceId,
target: { kind: "plugin", pluginId, panelId, context: "agent", agentId },
target: {
kind: "plugin",
pluginId,
panelId,
context: "agent",
agentId,
...(resolved?.params !== undefined ? { params: resolved.params } : {}),
...(resolved?.identityKey !== undefined ? { identityKey: resolved.identityKey } : {}),
},
placement: placement(location),
});
},
+28 -6
View File
@@ -8,6 +8,8 @@ import type {
PluginThemeContribution as SDKPluginThemeContribution,
} from "@getpaseo/plugin";
import type {
PluginAgentPanelParams,
PluginAgentPanelProps,
PluginFilePanelContribution as SDKPluginFilePanelContribution,
PluginCommandCenterItemContribution as SDKPluginCommandCenterItemContribution,
PluginClientSlashCommandContribution as SDKPluginClientSlashCommandContribution,
@@ -24,9 +26,13 @@ import type {
PluginTimelineRendererContribution,
PluginTimelineTransformerContribution,
PluginNotificationOpenHandler,
PluginIcon,
PluginPanelLocation,
PluginWorkspacePanelContribution as SDKPluginWorkspacePanelContribution,
PluginPanelParamsSchema,
PluginPanelTargetParams,
PluginWorkspacePanelProps,
} from "@getpaseo/plugin/client";
import type { ComponentType } from "react";
type PluginFilePanelContribution = SDKPluginFilePanelContribution<PluginText>;
type PluginAttachmentSourceContribution = SDKPluginAttachmentSourceContribution<PluginText>;
@@ -41,10 +47,27 @@ type PluginWorkspaceRowBadgeItemContribution =
SDKPluginWorkspaceRowBadgeItemContribution<PluginText>;
type PluginScreenContribution = SDKPluginScreenContribution<PluginText>;
type PluginSettingsScreenContribution = SDKPluginSettingsScreenContribution<PluginText>;
type WorkspacePanelInput = SDKPluginWorkspacePanelContribution<PluginText>;
type PluginWorkspacePanelContribution =
| (Extract<WorkspacePanelInput, { context?: "workspace" }> & { context: "workspace" })
| Extract<WorkspacePanelInput, { context: "agent" }>;
export type PluginWorkspacePanelContribution =
| {
id: string;
title: PluginText;
icon: PluginIcon;
context: "workspace";
locations?: readonly PluginPanelLocation[];
paramsSchema?: PluginPanelParamsSchema;
identity?: (params: PluginPanelTargetParams) => string;
Component: ComponentType<PluginWorkspacePanelProps<PluginPanelTargetParams>>;
}
| {
id: string;
title: PluginText;
icon: PluginIcon;
context: "agent";
locations?: readonly PluginPanelLocation[];
paramsSchema?: PluginPanelParamsSchema;
identity?: (params: PluginAgentPanelParams & PluginPanelTargetParams) => string;
Component: ComponentType<PluginAgentPanelProps<PluginPanelTargetParams>>;
};
export type PluginSidebarSection = "header" | "footer";
@@ -112,5 +135,4 @@ export type {
PluginTimelineRendererContribution,
PluginTimelineTransformerContribution,
PluginNotificationOpenHandler,
PluginWorkspacePanelContribution,
};
@@ -71,7 +71,7 @@ function bundle(id: string, register: string) {
return {
id,
requirements: { paseo: ">=0.8.0" },
clientBundle: `(function() { return { default: function(plugin) {
clientBundle: `(function(require) { return { default: function(plugin) {
const Component = function() { return null; };
${register}
return function() {};
@@ -1105,3 +1105,181 @@ describe("reaching the handle outside a panel", () => {
expect(events).toHaveLength(heard);
});
});
describe("author-defined panel params and identity", () => {
const PARAMETERIZED_PANELS = `
const { z } = require("zod");
plugin.addWorkspacePanel({
id: "decisions",
title: "Decisions",
icon: "Square",
locations: ["explorer"],
params: z.object({ decisionId: z.string() }),
Component,
});
plugin.addWorkspacePanel({
id: "pr",
title: "PR",
icon: "Square",
params: z.object({ prNumber: z.number(), commentId: z.string().optional() }),
identity: (p) => String(p.prNumber),
Component,
});
plugin.addWorkspacePanel({
id: "nested-bad",
title: "NestedBad",
icon: "Square",
params: z.object({ nested: z.object({ a: z.string() }) }),
Component,
});
plugin.addWorkspacePanel({
id: "bool-bad",
title: "BoolBad",
icon: "Square",
params: z.object({ flag: z.boolean() }),
Component,
});
plugin.addAgentPanel({
id: "agent-pr",
title: "Agent PR",
icon: "Square",
params: z.object({ prNumber: z.number(), commentId: z.string().optional() }),
identity: (p) => \`\${p.agentId}:\${p.prNumber}\`,
Component,
});
`;
beforeEach(() => {
install(PARAMETERIZED_PANELS);
});
it("reuses a single tab when identity is omitted and updates params in place", () => {
const layout = handle();
const first = layout.open({ panelId: "decisions", params: { decisionId: "D1" } });
expect(tab(layout, first.tabId).params).toEqual({ decisionId: "D1" });
expect(
useWorkspaceLayoutStore.getState().panelRevisionByWorkspace[WORKSPACE_KEY]?.[first.tabId],
).toBe(1);
const second = layout.open({ panelId: "decisions", params: { decisionId: "D2" } });
expect(second).toEqual(first);
expect(layout.get().tabs.filter((open) => open.panelId === "review/decisions")).toHaveLength(1);
expect(tab(layout, first.tabId).params).toEqual({ decisionId: "D2" });
expect(
useWorkspaceLayoutStore.getState().panelRevisionByWorkspace[WORKSPACE_KEY]?.[first.tabId],
).toBe(2);
const background = layout.open(
{ panelId: "decisions", params: { decisionId: "D3" } },
{ intent: "background" },
);
expect(background).toEqual(first);
expect(tab(layout, first.tabId).params).toEqual({ decisionId: "D3" });
expect(
useWorkspaceLayoutStore.getState().panelRevisionByWorkspace[WORKSPACE_KEY]?.[first.tabId],
).toBe(3);
});
it("coalesces keyed tabs by identity(params) and opens separate tabs for distinct keys", () => {
const layout = handle();
const pr1 = layout.open({ panelId: "pr", params: { prNumber: 1, commentId: "a" } });
expect(tab(layout, pr1.tabId).params).toEqual({ prNumber: 1, commentId: "a" });
const pr1Updated = layout.open({ panelId: "pr", params: { prNumber: 1, commentId: "b" } });
expect(pr1Updated).toEqual(pr1);
expect(tab(layout, pr1.tabId).params).toEqual({ prNumber: 1, commentId: "b" });
expect(
useWorkspaceLayoutStore.getState().panelRevisionByWorkspace[WORKSPACE_KEY]?.[pr1.tabId],
).toBe(2);
const pr2 = layout.open({ panelId: "pr", params: { prNumber: 2, commentId: "a" } });
expect(pr2.tabId).not.toBe(pr1.tabId);
expect(layout.get().tabs.filter((open) => open.panelId === "review/pr")).toHaveLength(2);
expect(tab(layout, pr1.tabId).params).toEqual({ prNumber: 1, commentId: "b" });
expect(tab(layout, pr2.tabId).params).toEqual({ prNumber: 2, commentId: "a" });
const pr1Duplicate = layout.open(
{ panelId: "pr", params: { prNumber: 1, commentId: "c" } },
{ intent: "new" },
);
expect(pr1Duplicate.tabId).not.toBe(pr1.tabId);
expect(tab(layout, pr1Duplicate.tabId).params).toEqual({ prNumber: 1, commentId: "c" });
});
it("supports extra params and identity on agent panels alongside required agentId", () => {
const layout = handle();
const first = layout.open({
panelId: "agent-pr",
params: { agentId: "a1", prNumber: 10, commentId: "c1" },
});
expect(tab(layout, first.tabId).params).toEqual({
agentId: "a1",
prNumber: 10,
commentId: "c1",
});
const updated = layout.open({
panelId: "agent-pr",
params: { agentId: "a1", prNumber: 10, commentId: "c2" },
});
expect(updated).toEqual(first);
expect(tab(layout, first.tabId).params).toEqual({
agentId: "a1",
prNumber: 10,
commentId: "c2",
});
const other = layout.open({
panelId: "agent-pr",
params: { agentId: "a1", prNumber: 11 },
});
expect(other.tabId).not.toBe(first.tabId);
expect(tab(layout, other.tabId).params).toEqual({ agentId: "a1", prNumber: 11 });
});
it("rejects invalid, missing, non-flat, or non-primitive params cleanly", () => {
const layout = handle();
const before = layout.get();
for (const target of [
{ panelId: "decisions" },
{ panelId: "decisions", params: { decisionId: 42 } },
{ panelId: "pr", params: { prNumber: "1" } },
{ panelId: "pr", params: { prNumber: Number.NaN } },
{
panelId: "nested-bad",
params: { nested: { a: "x" } } as unknown as PluginPanelTarget["params"],
},
{ panelId: "bool-bad", params: { flag: true } as unknown as PluginPanelTarget["params"] },
{ panelId: "agent-pr", params: { prNumber: 1 } },
{ panelId: "agent-pr", params: { agentId: " ", prNumber: 1 } },
] satisfies PluginPanelTarget[]) {
expect(() => layout.open(target)).toThrow("does not accept these params");
}
expect(layout.get()).toBe(before);
});
it("caches parsed params and keeps generated defaults aligned with identity across reads and reveals", () => {
install(`
const { z } = require("zod");
let count = 0;
plugin.addWorkspacePanel({
id: "generated-default",
title: "Generated",
icon: "Square",
params: z.object({ token: z.string().default(() => String(++count)) }),
identity: (p) => p.token,
Component,
});
`);
const layout = handle();
const opened = layout.open({ panelId: "generated-default" });
const first = layout.get();
const second = layout.get();
expect(second).toBe(first);
expect(tab(layout, opened.tabId).params).toEqual({ token: "1" });
expect(layout.open({ panelId: "generated-default", params: { token: "1" } }).tabId).toBe(
opened.tabId,
);
});
});
@@ -163,7 +163,7 @@ function resolveDestination(
): Destination {
const locations = panelLocations(workspace.serverId, target);
const explorerPaneId = readExplorerPaneId(workspace);
const { panelId } = describePanel(target);
const { panelId } = describePanel(workspace.serverId, target);
// The Explorer is never the focused pane, so a panel that cannot be in a main pane goes there.
const wantsExplorer =
@@ -4,20 +4,23 @@ import type {
PluginPanelTarget,
PluginPanelTargetParams,
} from "@getpaseo/plugin/client";
import { z } from "zod";
import {
findPublicPanel,
panelPublicReference,
type PanelOpenRequest,
} from "@/panels/panel-manifest";
import { panelTargetSupportsHost } from "@/plugins/workspace-panels/locations";
import {
buildPluginPanelTarget,
describePluginPanelParams,
parseRegisteredPluginPanelParams,
resolvePluginWorkspacePanel,
} from "@/plugins/workspace-panels/resolution";
import { normalizeWorkspaceTabTarget } from "@/workspace-tabs/identity";
import type { PluginWorkspaceTabTarget, WorkspaceTabTarget } from "@/workspace-tabs/model";
import type { WorkspaceTabTarget } from "@/workspace-tabs/model";
import { pluginRegistry } from "../../registry";
const PASEO_NAMESPACE = "paseo";
const workspacePanelParams = z.strictObject({});
const agentPanelParams = z.strictObject({ agentId: z.string().trim().min(1) });
export interface ResolvedPanel extends PanelOpenRequest {
/** Always qualified. */
@@ -45,14 +48,42 @@ export function resolvePanel(
return { ...request, panelId };
}
export function describePanel(target: WorkspaceTabTarget): {
export function describePanel(
serverId: string,
target: WorkspaceTabTarget,
): {
panelId: string;
params: PluginPanelTargetParams;
} {
if (target.kind !== "plugin") return panelPublicReference(target);
const plugin =
pluginRegistry
.getSnapshot()
.find((candidate) => candidate.serverId === serverId && candidate.id === target.pluginId) ??
null;
const contribution = resolvePluginWorkspacePanel(plugin, target);
if (contribution) {
try {
const parsed = parseRegisteredPluginPanelParams(contribution, target);
if (parsed.ok) {
return {
panelId: `${target.pluginId}/${target.panelId}`,
params:
parsed.context === "agent"
? { ...parsed.params, agentId: parsed.agentId }
: parsed.params,
};
}
} catch (error) {
console.warn(
`[WorkspaceLayout] Failed to parse params for "${target.pluginId}/${target.panelId}":`,
error,
);
}
}
return {
panelId: `${target.pluginId}/${target.panelId}`,
params: target.context === "agent" ? { agentId: target.agentId } : {},
params: describePluginPanelParams(target),
};
}
@@ -86,16 +117,8 @@ function resolvePluginPanel(
?.workspacePanels.find((candidate) => candidate.id === panelId);
if (!panel) throw notRegistered(qualified);
const base = { kind: "plugin", pluginId, panelId } as const;
let target: PluginWorkspaceTabTarget;
if (panel.context === "agent") {
const parsed = agentPanelParams.safeParse(params);
if (!parsed.success) throw rejectedParams(qualified);
target = { ...base, context: "agent", agentId: parsed.data.agentId };
} else {
if (!workspacePanelParams.safeParse(params).success) throw rejectedParams(qualified);
target = { ...base, context: "workspace" };
}
const target = buildPluginPanelTarget(pluginId, panel, params);
if (!target) throw rejectedParams(qualified);
const normalized = normalizeWorkspaceTabTarget(target);
if (!normalized) throw notRegistered(qualified);
return { target: normalized };
@@ -86,7 +86,7 @@ function toTab(workspace: Workspace, { tab, paneId }: OpenTab): PluginLayoutTab
return {
id: tab.tabId,
paneId,
...describePanel(tab.target),
...describePanel(workspace.serverId, tab.target),
locations: panelLocations(workspace.serverId, tab.target),
title: attributes.title ?? readTabTitle({ ...workspace, target: tab.target }),
modified: attributes.modified,
@@ -0,0 +1,469 @@
/**
* @vitest-environment jsdom
*/
import type { DaemonClient } from "@getpaseo/client/internal/daemon-client";
import React, { act, useMemo } from "react";
import { createRoot, type Root } from "react-dom/client";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { PaneProvider } from "@/panels/pane-context";
import { useSessionStore, type Agent, type WorkspaceDescriptor } from "@/stores/session-store";
import { collectAllTabs, useWorkspaceLayoutStore } from "@/stores/workspace-layout-store";
import { seedSessionHosts, seedSessionWorkspaces } from "@/test/seed-session";
import { pluginExecutionApprovals } from "../execution-approval";
import { pluginRegistry } from "../registry";
import { pluginWorkspaceLayoutSource } from "../workspace-layout";
import { pluginPanelRegistration } from "./panel";
const SERVER_ID = "server-panel-test";
const WORKSPACE_ID = "workspace-panel-test";
const WORKSPACE_KEY = `${SERVER_ID}:${WORKSPACE_ID}`;
function createWorkspaceDescriptor(): WorkspaceDescriptor {
return {
createdAt: null,
lastUserMessageAt: null,
id: WORKSPACE_ID,
projectId: "project-1",
projectDisplayName: "project",
projectRootPath: "/repo",
workspaceDirectory: "/repo",
projectKind: "git",
workspaceKind: "local_checkout",
name: "main",
status: "done",
diffStat: null,
scripts: [],
statusEnteredAt: null,
archivingAt: null,
};
}
function createAgent(id: string): Agent {
return {
serverId: SERVER_ID,
id,
workspaceId: WORKSPACE_ID,
provider: "codex",
status: "idle",
createdAt: new Date("2026-04-01T03:00:00.000Z"),
updatedAt: new Date("2026-04-01T03:00:00.000Z"),
lastUserMessageAt: null,
lastActivityAt: new Date("2026-04-01T03:00:00.000Z"),
capabilities: {
supportsStreaming: true,
supportsSessionPersistence: true,
supportsDynamicModes: true,
supportsMcpServers: true,
supportsReasoningStream: true,
supportsToolInvocations: true,
},
currentModeId: null,
availableModes: [],
pendingPermissions: [],
persistence: null,
title: "Test agent",
cwd: "/repo",
model: null,
parentAgentId: null,
labels: {},
archivedAt: null,
turn: { phase: "idle", cancellationRequestId: null },
};
}
const fakeDaemon = {
observeEvents: () => ({
ready: Promise.resolve({ subscriptionId: "events" }),
subscribe: () => () => undefined,
release: async () => undefined,
}),
} as unknown as DaemonClient;
vi.mock("@/runtime/host-runtime", async (importOriginal) => {
const actual = await importOriginal<typeof import("@/runtime/host-runtime")>();
return {
...actual,
useHostRuntimeClient: () => fakeDaemon,
};
});
function installPluginWithBundle(bundleCode: string) {
pluginExecutionApprovals.setDecision(SERVER_ID, "test-plugin", "approved");
pluginRegistry.installCatalog(
SERVER_ID,
[
{
id: "test-plugin",
requirements: { paseo: ">=0.8.0" },
clientBundle: bundleCode,
},
],
{ client: fakeDaemon, audio: { play: async () => 0 } },
);
const plugin = pluginRegistry.getSnapshot().find((p) => p.id === "test-plugin");
if (!plugin) throw new Error("Failed to install test-plugin");
return plugin;
}
describe("PluginPanel params, identity, revision, and tab.state delivery", () => {
const roots: Root[] = [];
const containers: HTMLElement[] = [];
beforeEach(async () => {
vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
await vi.waitFor(() => expect(useWorkspaceLayoutStore.persist.hasHydrated()).toBe(true));
useSessionStore.setState((state) => ({ ...state, sessions: {} }));
useWorkspaceLayoutStore.setState({
layoutMode: "split-panes",
sheetsByWorkspace: {},
layoutByWorkspace: {},
splitSizesByWorkspace: {},
explorerSidebarPaneIdByWorkspace: {},
sidePaneIdByWorkspace: {},
hiddenAgentIdsByWorkspace: {},
pinnedAgentIdsByWorkspace: {},
focusRestorationByWorkspace: {},
panelRevisionByWorkspace: {},
});
seedSessionHosts([SERVER_ID]);
await vi.waitFor(() =>
expect(useSessionStore.getState().sessions[SERVER_ID]?.hasRestoredCachedDirectory).toBe(true),
);
useSessionStore.getState().updateSessionClient(SERVER_ID, fakeDaemon);
seedSessionWorkspaces(SERVER_ID, new Map([[WORKSPACE_ID, createWorkspaceDescriptor()]]));
});
afterEach(() => {
for (const root of roots.splice(0)) act(() => root.unmount());
for (const container of containers.splice(0)) container.remove();
pluginRegistry.removeHost(SERVER_ID);
pluginExecutionApprovals.clearHost(SERVER_ID);
seedSessionHosts([]);
vi.unstubAllGlobals();
});
function mountTab(tabId: string) {
const container = document.createElement("div");
containers.push(container);
document.body.appendChild(container);
const root = createRoot(container);
roots.push(root);
function Harness({ activeTabId }: { activeTabId: string }) {
const layout = useWorkspaceLayoutStore((s) => s.layoutByWorkspace[WORKSPACE_KEY]);
const revision = useWorkspaceLayoutStore(
(s) => s.panelRevisionByWorkspace[WORKSPACE_KEY]?.[activeTabId] ?? 0,
);
const tab = layout
? collectAllTabs(layout.root).find((candidate) => candidate.tabId === activeTabId)
: undefined;
const PanelComponent = pluginPanelRegistration.component;
const paneValue = useMemo(
() =>
tab
? {
serverId: SERVER_ID,
workspaceId: WORKSPACE_ID,
host: "main" as const,
tabId: tab.tabId,
target: tab.target,
state: tab.state,
panelRevision: revision,
openTab: () => {},
openPreferredTarget: () => {},
closeCurrentTab: () => {},
retargetCurrentTab: () => {},
setCurrentTabState: (nextState: unknown) =>
useWorkspaceLayoutStore
.getState()
.setTabState(WORKSPACE_KEY, tab.tabId, nextState as never),
openFileInWorkspace: () => {},
openImportSheet: () => {},
}
: null,
[tab, revision],
);
if (!paneValue) return null;
return (
<PaneProvider value={paneValue}>
<PanelComponent />
</PaneProvider>
);
}
const render = async () => {
await act(async () => {
root.render(<Harness activeTabId={tabId} />);
});
};
return { container, render };
}
it("delivers updated params, bumps revision, and preserves tab.state when reusing a tab", async () => {
const plugin = installPluginWithBundle(`(function(require) {
const React = require("react");
const { Text, Pressable } = require("react-native");
const { z } = require("zod");
const { useTabState } = require("@getpaseo/plugin/client");
const stateSchema = z.object({ note: z.string() });
function DecisionPanel({ params, revision, tab }) {
const [localCount, setLocalCount] = React.useState(0);
const [tabState, setTabState] = useTabState(tab, stateSchema, { note: "initial" });
return React.createElement(
React.Fragment,
null,
React.createElement(Text, { testID: "output" }, \`\${params.decisionId}|\${revision}|\${tabState.note}|\${localCount}\`),
React.createElement(Pressable, {
testID: "save-state",
onPress: () => {
setLocalCount((n) => n + 1);
setTabState({ note: "saved-note" });
},
})
);
}
return { default: function(client) {
client.addWorkspacePanel({
id: "decision",
title: "Decision",
icon: "File",
params: z.object({ decisionId: z.string() }),
Component: DecisionPanel,
});
return function() {};
}};
})`);
const layout = pluginWorkspaceLayoutSource(plugin).layout(WORKSPACE_ID);
const first = layout.open({ panelId: "decision", params: { decisionId: "D1" } });
const mounted = mountTab(first.tabId);
await mounted.render();
expect(mounted.container.textContent).toBe("D1|1|initial|0");
// Persist tab state and local state on the mounted instance.
const button = mounted.container.querySelector('[data-testid="save-state"]');
expect(button).toBeInstanceOf(HTMLElement);
await act(async () => {
(button as HTMLElement).click();
});
expect(mounted.container.textContent).toBe("D1|1|saved-note|1");
await act(async () => {
layout.open({ panelId: "decision", params: { decisionId: "D2" } });
});
expect(mounted.container.textContent).toBe("D2|2|saved-note|1");
});
it("delivers host-enforced agentId alongside extra params on addAgentPanel", async () => {
useSessionStore.getState().setAgents(SERVER_ID, new Map([["a1", createAgent("a1")]]));
const plugin = installPluginWithBundle(`(function(require) {
const React = require("react");
const { Text } = require("react-native");
const { z } = require("zod");
function AgentPrPanel({ params, revision }) {
return React.createElement(Text, null, \`\${params.agentId}|\${params.prNumber}|\${params.commentId ?? "none"}|\${revision}\`);
}
return { default: function(client) {
client.addAgentPanel({
id: "agent-pr",
title: "Agent PR",
icon: "File",
params: z.object({ prNumber: z.number(), commentId: z.string().optional() }),
identity: (p) => \`\${p.agentId}:\${p.prNumber}\`,
Component: AgentPrPanel,
});
return function() {};
}};
})`);
const layout = pluginWorkspaceLayoutSource(plugin).layout(WORKSPACE_ID);
const opened = layout.open({
panelId: "agent-pr",
params: { agentId: "a1", prNumber: 7, commentId: "c1" },
});
const mounted = mountTab(opened.tabId);
await mounted.render();
expect(mounted.container.textContent).toBe("a1|7|c1|1");
await act(async () => {
layout.open({
panelId: "agent-pr",
params: { agentId: "a1", prNumber: 7, commentId: "c2" },
});
});
expect(mounted.container.textContent).toBe("a1|7|c2|2");
});
it("shows unavailable when a restored tab target fails the current params schema", async () => {
const plugin = installPluginWithBundle(`(function(require) {
const React = require("react");
const { Text } = require("react-native");
return { default: function(client) {
client.addWorkspacePanel({
id: "decision",
title: "Decision",
icon: "File",
Component: () => React.createElement(Text, null, "v1-ok"),
});
return function() {};
}};
})`);
const layout = pluginWorkspaceLayoutSource(plugin).layout(WORKSPACE_ID);
const opened = layout.open({ panelId: "decision" });
const mounted = mountTab(opened.tabId);
await mounted.render();
expect(mounted.container.textContent).toBe("v1-ok");
// Simulate upgrading the plugin to require `decisionId: z.string()` while the old tab remains in layout.
await act(async () => {
installPluginWithBundle(`(function(require) {
const React = require("react");
const { Text } = require("react-native");
const { z } = require("zod");
return { default: function(client) {
client.addWorkspacePanel({
id: "decision",
title: "Decision",
icon: "File",
params: z.object({ decisionId: z.string() }),
Component: ({ params }) => React.createElement(Text, null, params.decisionId.toUpperCase()),
});
return function() {};
}};
})`);
});
expect(mounted.container.textContent).toBe("This plugin panel is unavailable.");
});
it("validates and applies schema defaults when rendering a restored tab target", async () => {
const plugin = installPluginWithBundle(`(function(require) {
const React = require("react");
const { Text } = require("react-native");
return { default: function(client) {
client.addWorkspacePanel({
id: "decision",
title: "Decision",
icon: "File",
Component: () => React.createElement(Text, null, "v1-ok"),
});
return function() {};
}};
})`);
const layout = pluginWorkspaceLayoutSource(plugin).layout(WORKSPACE_ID);
const opened = layout.open({ panelId: "decision" });
const mounted = mountTab(opened.tabId);
await mounted.render();
expect(mounted.container.textContent).toBe("v1-ok");
await act(async () => {
installPluginWithBundle(`(function(require) {
const React = require("react");
const { Text } = require("react-native");
const { z } = require("zod");
return { default: function(client) {
client.addWorkspacePanel({
id: "decision",
title: "Decision",
icon: "File",
params: z.object({ filter: z.string().default("open") }),
Component: ({ params }) => React.createElement(Text, null, params.filter),
});
return function() {};
}};
})`);
});
expect(mounted.container.textContent).toBe("open");
});
it("renders transforming params schemas once on open without rejecting output values", async () => {
const plugin = installPluginWithBundle(`(function(require) {
const React = require("react");
const { Text } = require("react-native");
const { z } = require("zod");
return { default: function(client) {
client.addWorkspacePanel({
id: "transform-pr",
title: "Transform PR",
icon: "File",
params: z.object({
prNumber: z.string().transform(Number),
label: z.string().transform((value) => value + "!"),
}),
identity: (p) => String(p.prNumber),
Component: ({ params, revision }) =>
React.createElement(Text, null, \`\${typeof params.prNumber}:\${params.prNumber}|\${params.label}|\${revision}\`),
});
return function() {};
}};
})`);
const layout = pluginWorkspaceLayoutSource(plugin).layout(WORKSPACE_ID);
const opened = layout.open({
panelId: "transform-pr",
params: { prNumber: "42", label: "hi" },
});
const mounted = mountTab(opened.tabId);
await mounted.render();
expect(mounted.container.textContent).toBe("number:42|hi!|1");
expect(layout.get().tabs.find((tab) => tab.id === opened.tabId)?.params).toEqual({
prNumber: 42,
label: "hi!",
});
await act(async () => {
layout.open({
panelId: "transform-pr",
params: { prNumber: "042", label: "yo" },
});
});
expect(mounted.container.textContent).toBe("number:42|yo!|2");
});
it("reports unexpected params transform errors through SurfaceErrorBoundary", async () => {
const plugin = installPluginWithBundle(`(function(require) {
const React = require("react");
const { Text } = require("react-native");
return { default: function(client) {
client.addWorkspacePanel({
id: "decision",
title: "Decision",
icon: "File",
Component: () => React.createElement(Text, null, "v1-ok"),
});
return function() {};
}};
})`);
const layout = pluginWorkspaceLayoutSource(plugin).layout(WORKSPACE_ID);
const opened = layout.open({ panelId: "decision" });
const mounted = mountTab(opened.tabId);
await mounted.render();
expect(mounted.container.textContent).toBe("v1-ok");
await act(async () => {
installPluginWithBundle(`(function(require) {
const React = require("react");
const { Text } = require("react-native");
const { z } = require("zod");
return { default: function(client) {
client.addWorkspacePanel({
id: "decision",
title: "Decision",
icon: "File",
params: z.object({}).transform(() => {
throw new Error("transform boom");
}),
Component: () => React.createElement(Text, null, "never"),
});
return function() {};
}};
})`);
});
expect(mounted.container.textContent).toBe("Plugin failed: transform boom");
});
});
@@ -2,6 +2,7 @@ import { getComponentMountKey, usePanelTab } from "@/panels/panel-instance-attri
import type {
PluginAgentPanelProps,
PluginHostProps,
PluginPanelTargetParams,
PluginWorkspacePanelProps,
} from "@getpaseo/plugin/client";
import type { PluginTheme } from "@getpaseo/plugin";
@@ -27,18 +28,20 @@ import { useInstalledPlugin } from "../registry";
import { PluginInstallationProvider } from "../installation-provider";
import { SurfaceErrorBoundary } from "../surface-error-boundary";
import type { EvaluatedPluginWorkspacePanelContribution } from "../types";
import { resolvePluginWorkspacePanel } from "./resolution";
import {
parseRegisteredPluginPanelParams,
resolvePluginWorkspacePanel,
type ParsedPluginPanelParams,
} from "./resolution";
import { resolvePluginPlatform } from "../platform";
const pluginThemeMapping = (theme: Theme) => ({
theme: toPluginTheme(theme),
});
const EMPTY_WORKSPACE_PARAMS = {} as const;
function MountedPluginPanel({
contribution,
target,
parsed,
theme,
host,
layout,
@@ -48,7 +51,7 @@ function MountedPluginPanel({
revision,
}: {
contribution: EvaluatedPluginWorkspacePanelContribution;
target: PluginWorkspaceTabTarget;
parsed: Extract<ParsedPluginPanelParams, { ok: true }>;
theme: PluginTheme;
host: PluginHostProps["host"];
layout: PluginHostProps["layout"];
@@ -58,14 +61,23 @@ function MountedPluginPanel({
revision: number;
}) {
const tab = usePanelTab();
const agentId = target.context === "agent" ? target.agentId : null;
const agentParams = useMemo(() => (agentId ? { agentId } : null), [agentId]);
const workspaceParams = useMemo<PluginPanelTargetParams>(
() => Object.freeze({ ...parsed.params }),
[parsed.params],
);
const agentParams = useMemo(
() =>
parsed.context === "agent"
? Object.freeze({ ...parsed.params, agentId: parsed.agentId })
: null,
[parsed],
);
if (contribution.context === "workspace") {
const props: PluginWorkspacePanelProps = {
const props: PluginWorkspacePanelProps<PluginPanelTargetParams> = {
// COMPAT(pluginPanelFlatProps): added in v0.13.0, remove after 2027-04-23
context: "workspace",
params: EMPTY_WORKSPACE_PARAMS,
params: workspaceParams,
revision,
tab,
theme,
@@ -78,8 +90,9 @@ function MountedPluginPanel({
const Component = contribution.Component;
return <Component {...props} />;
}
invariant(agentParams && agentId, "PluginAgentPanel requires agent target");
const props: PluginAgentPanelProps = {
invariant(parsed.context === "agent" && agentParams, "PluginAgentPanel requires agent target");
const props: PluginAgentPanelProps<PluginPanelTargetParams> = {
// COMPAT(pluginPanelFlatProps): added in v0.13.0, remove after 2027-04-23
context: "agent",
params: agentParams,
@@ -92,12 +105,58 @@ function MountedPluginPanel({
openScreen,
workspaceId,
// COMPAT(pluginPanelFlatProps): added in v0.13.0, remove after 2027-04-23
agentId,
agentId: parsed.agentId,
};
const Component = contribution.Component;
return <Component {...props} />;
}
function ValidatedPluginPanel({
contribution,
target,
theme,
host,
layout,
navigation,
openScreen,
workspaceId,
revision,
}: {
contribution: EvaluatedPluginWorkspacePanelContribution;
target: Extract<PluginWorkspaceTabTarget, { kind: "plugin" }>;
theme: PluginTheme;
host: PluginHostProps["host"];
layout: PluginHostProps["layout"];
navigation: PluginWorkspacePanelProps["navigation"];
openScreen: PluginWorkspacePanelProps["openScreen"];
workspaceId: string;
revision: number;
}) {
const parsed = useMemo(
() => parseRegisteredPluginPanelParams(contribution, target),
[contribution, target],
);
if (!parsed.ok) {
return <PluginPanelUnavailable />;
}
return (
<MountedPluginPanel
key={getComponentMountKey(contribution.Component)}
contribution={contribution}
parsed={parsed}
theme={theme}
host={host}
layout={layout}
navigation={navigation}
openScreen={openScreen}
workspaceId={workspaceId}
revision={revision}
/>
);
}
function PluginPanelBody({ theme }: { theme: PluginTheme }) {
const { serverId, workspaceId, target, panelRevision } = usePaneContext();
invariant(target.kind === "plugin", "PluginPanel requires plugin target");
@@ -128,7 +187,7 @@ function PluginPanelBody({ theme }: { theme: PluginTheme }) {
if (!client) {
return <PluginPanelUnavailable message="Plugin host is offline." />;
}
if (contribution.context === "agent" && (!agentExists || target.context !== "agent")) {
if (contribution.context === "agent" && !agentExists) {
return <PluginPanelUnavailable />;
}
@@ -139,8 +198,7 @@ function PluginPanelBody({ theme }: { theme: PluginTheme }) {
key={`${serverId}/${target.pluginId}/${target.panelId}/${target.context}`}
>
<PluginInstallationProvider plugin={plugin}>
<MountedPluginPanel
key={getComponentMountKey(contribution.Component)}
<ValidatedPluginPanel
contribution={contribution}
target={target}
theme={theme}
@@ -1,7 +1,11 @@
import type { EvaluatedPluginWorkspacePanelContribution } from "../types";
import type { InstalledPlugin } from "../types";
import type { PluginPanelParamsSchema, PluginPanelTargetParams } from "@getpaseo/plugin/client";
import { z } from "zod";
import type { EvaluatedPluginWorkspacePanelContribution, InstalledPlugin } from "../types";
import type { PluginWorkspaceTabTarget } from "@/workspace-tabs/model";
const EMPTY_PARAMS_SCHEMA = z.strictObject({});
const AGENT_ID_SCHEMA = z.string().trim().min(1);
export function resolvePluginWorkspacePanel(
plugin: InstalledPlugin | null,
target: PluginWorkspaceTabTarget,
@@ -12,3 +16,213 @@ export function resolvePluginWorkspacePanel(
) ?? null
);
}
export type ParsedPluginPanelParams =
| { ok: false }
| { ok: true; context: "workspace"; params: Record<string, string | number> }
| { ok: true; context: "agent"; agentId: string; params: Record<string, string | number> };
/**
* Validates `rawParams` against `panel`'s schema (plus required `agentId` for agent panels),
* rejects non-flat or non-primitive inputs and outputs, and evaluates `panel.identity(params)`
* on the parsed output. Stores parsed output when the schema is idempotent on it (preserving
* defaults and generated values across renders and identity checks), falling back to caller input
* for non-idempotent transforms so transforms only apply once. Returns `null` when rejected.
*/
export function buildPluginPanelTarget(
pluginId: string,
panel: EvaluatedPluginWorkspacePanelContribution,
rawParams: unknown,
): PluginWorkspaceTabTarget | null {
if (!rawParams || typeof rawParams !== "object" || Array.isArray(rawParams)) {
return null;
}
const input = rawParams as Record<string, unknown>;
const isAgent = panel.context === "agent";
const schema = panel.paramsSchema ?? EMPTY_PARAMS_SCHEMA;
let agentId: string | undefined;
let schemaInput: Record<string, unknown> = input;
if (isAgent) {
const parsedAgentId = AGENT_ID_SCHEMA.safeParse(input.agentId);
if (!parsedAgentId.success) return null;
agentId = parsedAgentId.data;
const { agentId: _agentId, ...extraInput } = input;
schemaInput = extraInput;
}
const storedInput = extractFlatPrimitiveParams(schemaInput, isAgent);
if (!storedInput) return null;
const parsed = schema.safeParse(schemaInput);
if (!parsed.success) return null;
const parsedOutput = extractFlatPrimitiveParams(parsed.data, isAgent);
if (!parsedOutput) return null;
const qualifiedId = `${pluginId}/${panel.id}`;
const storedParams = selectStoredPanelParams(schema, storedInput, parsedOutput, isAgent);
if (panel.context === "agent" && agentId !== undefined) {
const identityKey = evaluateIdentityKey(
qualifiedId,
panel.identity,
Object.freeze({ ...parsedOutput, agentId }),
);
return {
kind: "plugin",
pluginId,
panelId: panel.id,
context: "agent",
agentId,
...(Object.keys(storedParams).length > 0 ? { params: storedParams } : {}),
...(identityKey !== undefined ? { identityKey } : {}),
};
}
const identityKey = evaluateIdentityKey(
qualifiedId,
panel.context === "workspace" ? panel.identity : undefined,
Object.freeze({ ...parsedOutput }),
);
return {
kind: "plugin",
pluginId,
panelId: panel.id,
context: "workspace",
...(Object.keys(storedParams).length > 0 ? { params: storedParams } : {}),
...(identityKey !== undefined ? { identityKey } : {}),
};
}
const parsedPanelParamsCache = new WeakMap<
EvaluatedPluginWorkspacePanelContribution,
WeakMap<PluginWorkspaceTabTarget, ParsedPluginPanelParams>
>();
/**
* Validates stored params on `target` against `panel`'s current schema once per
* `(panel, target)` pair and caches the result so repeated layout reads stay stable.
* Unexpected callback exceptions inside schema transforms are not swallowed.
*/
export function parseRegisteredPluginPanelParams(
panel: EvaluatedPluginWorkspacePanelContribution,
target: PluginWorkspaceTabTarget,
): ParsedPluginPanelParams {
let byTarget = parsedPanelParamsCache.get(panel);
const cached = byTarget?.get(target);
if (cached) return cached;
const computed = computeRegisteredPluginPanelParams(panel, target);
if (!byTarget) {
byTarget = new WeakMap();
parsedPanelParamsCache.set(panel, byTarget);
}
byTarget.set(target, computed);
return computed;
}
function computeRegisteredPluginPanelParams(
panel: EvaluatedPluginWorkspacePanelContribution,
target: PluginWorkspaceTabTarget,
): ParsedPluginPanelParams {
if (target.context !== panel.context) return Object.freeze({ ok: false });
const schema = panel.paramsSchema ?? EMPTY_PARAMS_SCHEMA;
if (panel.context === "agent" && target.context === "agent") {
const parsedAgentId = AGENT_ID_SCHEMA.safeParse(target.agentId);
if (!parsedAgentId.success) return Object.freeze({ ok: false });
const parsed = schema.safeParse(target.params ?? {});
if (!parsed.success) return Object.freeze({ ok: false });
const params = extractFlatPrimitiveParams(parsed.data, true);
if (!params) return Object.freeze({ ok: false });
return Object.freeze({
ok: true,
context: "agent",
agentId: parsedAgentId.data,
params: Object.freeze(params),
});
}
const parsed = schema.safeParse(target.params ?? {});
if (!parsed.success) return Object.freeze({ ok: false });
const params = extractFlatPrimitiveParams(parsed.data, false);
if (!params) return Object.freeze({ ok: false });
return Object.freeze({
ok: true,
context: "workspace",
params: Object.freeze(params),
});
}
/**
* Resolves a workspace panel target with `{}` for parameterless UI launchers.
* Returns `null` for agent panels or panels whose `params` schema rejects `{}`.
*/
export function resolveParameterlessPluginPanelTarget(
pluginId: string,
panel: EvaluatedPluginWorkspacePanelContribution,
): PluginWorkspaceTabTarget | null {
if (panel.context !== "workspace") return null;
return buildPluginPanelTarget(pluginId, panel, {});
}
export function describePluginPanelParams(
target: PluginWorkspaceTabTarget,
): PluginPanelTargetParams {
if (target.context === "agent") {
return { ...target.params, agentId: target.agentId };
}
return { ...target.params };
}
function extractFlatPrimitiveParams(
value: unknown,
omitAgentId: boolean,
): Record<string, string | number> | null {
if (!value || typeof value !== "object" || Array.isArray(value)) return null;
const cleaned: Record<string, string | number> = {};
for (const [key, entry] of Object.entries(value)) {
if (omitAgentId && key === "agentId") continue;
if (entry === undefined) continue;
if (typeof entry === "string") {
cleaned[key] = entry;
continue;
}
if (typeof entry === "number" && Number.isFinite(entry)) {
cleaned[key] = entry;
continue;
}
return null;
}
return cleaned;
}
function selectStoredPanelParams(
schema: PluginPanelParamsSchema,
storedInput: Record<string, string | number>,
parsedOutput: Record<string, string | number>,
omitAgentId: boolean,
): Record<string, string | number> {
const reparsed = schema.safeParse(parsedOutput);
if (!reparsed.success) return storedInput;
const normalized = extractFlatPrimitiveParams(reparsed.data, omitAgentId);
if (!normalized) return storedInput;
return flatParamsEqual(normalized, parsedOutput) ? parsedOutput : storedInput;
}
function flatParamsEqual(
left: Record<string, string | number>,
right: Record<string, string | number>,
): boolean {
const leftKeys = Object.keys(left);
if (leftKeys.length !== Object.keys(right).length) return false;
return leftKeys.every((key) => Object.is(left[key], right[key]));
}
function evaluateIdentityKey<Params>(
qualifiedPanelId: string,
identity: ((params: Params) => string) | undefined,
params: Params,
): string | undefined {
if (!identity) return undefined;
const key = identity(params);
if (typeof key !== "string") {
throw new Error(`Panel "${qualifiedPanelId}" identity must return a string`);
}
return key;
}
@@ -276,3 +276,119 @@ it.each([1, 2])(
expect(visible).toEqual(["agent-a"]);
},
);
it("hydrates legacy plugin tabs without params or identityKey and round-trips parameterized plugin tabs", async () => {
const workspaceKey = "server:workspace";
const values = new Map([
[
"workspace-layout-state",
JSON.stringify({
version: 2,
state: {
layoutByWorkspace: {
[workspaceKey]: {
root: {
kind: "pane",
pane: {
id: "main",
tabIds: ["plugin_workspace_6_review_8_overview"],
focusedTabId: "plugin_workspace_6_review_8_overview",
tabs: [
{
tabId: "plugin_workspace_6_review_8_overview",
target: {
kind: "plugin",
pluginId: "review",
panelId: "overview",
context: "workspace",
},
createdAt: 1,
},
],
},
},
focusedPaneId: "main",
},
},
},
}),
],
]);
const storage: StateStorage = {
getItem: (name) => values.get(name) ?? null,
setItem: (name, value) => {
values.set(name, value);
},
removeItem: (name) => {
values.delete(name);
},
};
const store = createWorkspaceLayoutStore(undefined, storage);
await store.persist.rehydrate();
expect(collectAllTabs(store.getState().layoutByWorkspace[workspaceKey].root)[0]?.target).toEqual({
kind: "plugin",
pluginId: "review",
panelId: "overview",
context: "workspace",
});
store.getState().openTab({
workspaceKey,
target: {
kind: "plugin",
pluginId: "review",
panelId: "pr",
context: "workspace",
params: { prNumber: 42, commentId: "c1" },
identityKey: "42",
},
intent: "reveal",
});
store.getState().openTab({
workspaceKey,
target: {
kind: "plugin",
pluginId: "review",
panelId: "notes",
context: "agent",
agentId: "agent-1",
params: { line: 9 },
identityKey: "agent-1:9",
},
intent: "reveal",
});
const restored = createWorkspaceLayoutStore(undefined, storage);
await restored.persist.rehydrate();
expect(
collectAllTabs(restored.getState().layoutByWorkspace[workspaceKey].root).map(
(tab) => tab.target,
),
).toEqual(
expect.arrayContaining([
{
kind: "plugin",
pluginId: "review",
panelId: "overview",
context: "workspace",
},
{
kind: "plugin",
pluginId: "review",
panelId: "pr",
context: "workspace",
params: { prNumber: 42, commentId: "c1" },
identityKey: "42",
},
{
kind: "plugin",
pluginId: "review",
panelId: "notes",
context: "agent",
agentId: "agent-1",
params: { line: 9 },
identityKey: "agent-1:9",
},
]),
);
});
@@ -62,6 +62,8 @@ const WorkspaceTabTargetStorageSchema = z.discriminatedUnion("kind", [
pluginId: z.string(),
panelId: z.string(),
context: z.literal("workspace"),
params: z.record(z.string(), z.union([z.string(), z.number()])).optional(),
identityKey: z.string().optional(),
}),
z.strictObject({
kind: z.literal("plugin"),
@@ -69,6 +71,8 @@ const WorkspaceTabTargetStorageSchema = z.discriminatedUnion("kind", [
panelId: z.string(),
context: z.literal("agent"),
agentId: z.string(),
params: z.record(z.string(), z.union([z.string(), z.number()])).optional(),
identityKey: z.string().optional(),
}),
]),
]);
@@ -195,4 +195,60 @@ describe("plugin panel tab identity", () => {
expect(workspace).toBe("plugin_workspace_6_review_7_details");
expect(agent).toBe("plugin_agent_6_review_7_details_7_agent-1");
});
it("preserves legacy targets without params or identityKey and distinguishes keyed targets", () => {
const legacy = normalizeWorkspaceTabTarget({
kind: "plugin",
pluginId: "review",
panelId: "details",
context: "workspace",
});
expect(legacy).toEqual({
kind: "plugin",
pluginId: "review",
panelId: "details",
context: "workspace",
});
const pr1a = normalizeWorkspaceTabTarget({
kind: "plugin",
pluginId: "review",
panelId: "pr",
context: "workspace",
params: { prNumber: 1, commentId: "a" },
identityKey: "1",
});
const pr1b = normalizeWorkspaceTabTarget({
kind: "plugin",
pluginId: "review",
panelId: "pr",
context: "workspace",
params: { prNumber: 1, commentId: "b" },
identityKey: "1",
});
const pr2 = normalizeWorkspaceTabTarget({
kind: "plugin",
pluginId: "review",
panelId: "pr",
context: "workspace",
params: { prNumber: 2, commentId: "a" },
identityKey: "2",
});
expect(pr1a).toEqual({
kind: "plugin",
pluginId: "review",
panelId: "pr",
context: "workspace",
params: { prNumber: 1, commentId: "a" },
identityKey: "1",
});
expect(pr1a && pr1b && workspaceTabTargetsEqual(pr1a, pr1b)).toBe(false);
expect(pr1a && pr2 && buildDeterministicWorkspaceTabId(pr1a)).not.toBe(
pr2 && buildDeterministicWorkspaceTabId(pr2),
);
expect(pr1a && pr1b && buildDeterministicWorkspaceTabId(pr1a)).toBe(
pr1b && buildDeterministicWorkspaceTabId(pr1b),
);
});
});
+60 -9
View File
@@ -120,17 +120,29 @@ export function workspaceTabTargetsEqual(
return left.terminalId === right.terminalId;
}
if (left.kind === "plugin" && right.kind === "plugin") {
return (
left.pluginId === right.pluginId &&
left.panelId === right.panelId &&
left.context === right.context &&
(left.context === "workspace" ||
(right.context === "agent" && left.agentId === right.agentId))
);
return pluginTabTargetsEqual(left, right);
}
return secondaryWorkspaceTabTargetsEqual(left, right);
}
function pluginTabTargetsEqual(
left: Extract<WorkspaceTabTarget, { kind: "plugin" }>,
right: Extract<WorkspaceTabTarget, { kind: "plugin" }>,
): boolean {
if (
left.pluginId !== right.pluginId ||
left.panelId !== right.panelId ||
left.context !== right.context ||
left.identityKey !== right.identityKey
) {
return false;
}
if (left.context === "agent" && right.context === "agent" && left.agentId !== right.agentId) {
return false;
}
return recordsShallowEqual(left.params ?? {}, right.params ?? {});
}
function secondaryWorkspaceTabTargetsEqual(
left: WorkspaceTabTarget,
right: WorkspaceTabTarget,
@@ -229,6 +241,9 @@ export function buildDeterministicWorkspaceTabId(target: WorkspaceTabTarget): st
}
if (target.kind === "plugin") {
const identity = `${target.pluginId.length}_${target.pluginId}_${target.panelId.length}_${target.panelId}`;
if (target.identityKey !== undefined) {
return `plugin_key_${target.context}_${identity}_${target.identityKey.length}_${target.identityKey}`;
}
return target.context === "workspace"
? `plugin_workspace_${identity}`
: `plugin_agent_${identity}_${target.agentId.length}_${target.agentId}`;
@@ -236,17 +251,53 @@ export function buildDeterministicWorkspaceTabId(target: WorkspaceTabTarget): st
return `file_${target.path}`;
}
function normalizePluginTargetParams(
value: unknown,
omitAgentId: boolean,
): Record<string, string | number> | undefined {
if (!isPlainRecord(value)) return undefined;
const cleaned: Record<string, string | number> = {};
let hasKeys = false;
for (const [key, entry] of Object.entries(value)) {
if (omitAgentId && key === "agentId") continue;
if (typeof entry === "string" || (typeof entry === "number" && Number.isFinite(entry))) {
cleaned[key] = entry;
hasKeys = true;
}
}
return hasKeys ? cleaned : undefined;
}
function normalizePluginTabTarget(
value: Extract<WorkspaceTabTarget, { kind: "plugin" }>,
): WorkspaceTabTarget | null {
const pluginId = trimNonEmpty(value.pluginId);
const panelId = trimNonEmpty(value.panelId);
if (!pluginId || !panelId) return null;
const identityKey = typeof value.identityKey === "string" ? value.identityKey : undefined;
if (value.context === "workspace") {
return { kind: "plugin", pluginId, panelId, context: "workspace" };
const params = normalizePluginTargetParams(value.params, false);
return {
kind: "plugin",
pluginId,
panelId,
context: "workspace",
...(params ? { params } : {}),
...(identityKey !== undefined ? { identityKey } : {}),
};
}
const agentId = trimNonEmpty(value.agentId);
return agentId ? { kind: "plugin", pluginId, panelId, context: "agent", agentId } : null;
if (!agentId) return null;
const params = normalizePluginTargetParams(value.params, true);
return {
kind: "plugin",
pluginId,
panelId,
context: "agent",
agentId,
...(params ? { params } : {}),
...(identityKey !== undefined ? { identityKey } : {}),
};
}
function trimNonEmpty(value: string | null | undefined): string | null {
@@ -0,0 +1,108 @@
import type { DaemonClient } from "@getpaseo/client/internal/daemon-client";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { pluginExecutionApprovals } from "@/plugins/execution-approval";
import { pluginRegistry } from "@/plugins/registry";
import type { NewTabSelection } from "@/workspace-tabs/new-tab";
import { buildPluginWorkspaceTabLaunchItems } from "./index";
const SERVER_ID = "server-launcher";
const fakeDaemon = {
observeEvents: () => ({
ready: Promise.resolve({ subscriptionId: "events" }),
subscribe: () => () => undefined,
release: async () => undefined,
}),
} as unknown as DaemonClient;
describe("buildPluginWorkspaceTabLaunchItems", () => {
beforeEach(() => {
pluginExecutionApprovals.setDecision(SERVER_ID, "launcher-plugin", "approved");
pluginRegistry.installCatalog(
SERVER_ID,
[
{
id: "launcher-plugin",
requirements: { paseo: ">=0.8.0" },
clientBundle: `(function(require) {
const { z } = require("zod");
const Component = () => null;
return { default: function(client) {
client.addWorkspacePanel({
id: "no-params",
title: "No Params",
icon: "File",
Component,
});
client.addWorkspacePanel({
id: "optional-params",
title: "Optional Params",
icon: "File",
params: z.object({ filter: z.string().default("open") }),
identity: (p) => p.filter,
Component,
});
client.addWorkspacePanel({
id: "required-params",
title: "Required Params",
icon: "File",
params: z.object({ prNumber: z.number() }),
identity: (p) => String(p.prNumber),
Component,
});
client.addWorkspacePanel({
id: "broken-identity",
title: "Broken Identity",
icon: "File",
identity: () => {
throw new Error("identity boom");
},
Component,
});
return function() {};
}};
})`,
},
],
{ client: fakeDaemon, audio: { play: async () => 0 } },
);
});
afterEach(() => {
pluginRegistry.removeHost(SERVER_ID);
pluginExecutionApprovals.clearHost(SERVER_ID);
vi.restoreAllMocks();
});
it("excludes panels whose schema rejects {} and isolates throwing panels", () => {
const warn = vi.spyOn(console, "warn").mockImplementation(() => undefined);
const launched: NewTabSelection[] = [];
const items = buildPluginWorkspaceTabLaunchItems({
plugins: pluginRegistry.getSnapshot(),
serverId: SERVER_ID,
host: "main",
launchSelection: (selection) => () => launched.push(selection),
});
expect(items.map((item) => item.id)).toEqual([
"plugin:launcher-plugin:no-params",
"plugin:launcher-plugin:optional-params",
]);
expect(warn).toHaveBeenCalledTimes(1);
items[1]?.launch({ kind: "open" });
expect(launched).toEqual([
{
kind: "target",
target: {
kind: "plugin",
pluginId: "launcher-plugin",
panelId: "optional-params",
context: "workspace",
params: { filter: "open" },
identityKey: "open",
},
},
]);
});
});
@@ -14,7 +14,9 @@ import { useIsCompactFormFactor } from "@/constants/layout";
import { useDaemonConfig } from "@/hooks/use-daemon-config";
import { pluginIconComponent } from "@/plugins/icons";
import { useInstalledPlugins } from "@/plugins/registry";
import type { InstalledPlugin } from "@/plugins/types";
import { pluginPanelSupportsLocation } from "@/plugins/workspace-panels/locations";
import { resolveParameterlessPluginPanelTarget } from "@/plugins/workspace-panels/resolution";
import { buildSettingsHostSectionRoute } from "@/utils/host-routes";
import type { NewTabSelection } from "@/workspace-tabs/new-tab";
import type { WorkspaceTabTarget } from "@/workspace-tabs/model";
@@ -197,27 +199,12 @@ export function useWorkspaceTabLaunchCatalog(input: {
return item.hidden || !panelSupportsHost(item.panelKind, host) ? [] : [item];
});
const pluginItems: WorkspaceTabLaunchItem[] = [];
for (const plugin of plugins) {
if (plugin.serverId !== serverId) continue;
for (const panel of plugin.workspacePanels) {
if (panel.context !== "workspace") continue;
const location = host === "explorer" ? "explorer" : "workspace";
if (!pluginPanelSupportsLocation(panel, location)) continue;
const selection: NewTabSelection = {
kind: "target",
target: { kind: "plugin", pluginId: plugin.id, panelId: panel.id, context: "workspace" },
};
pluginItems.push({
id: `plugin:${plugin.id}:${panel.id}`,
label: plugin.i18n.resolve(panel.title, plugin.locale),
Icon: pluginIconComponent(panel.icon),
disabled: false,
panelKind: "plugin",
launch: launchSelection(selection),
});
}
}
const pluginItems = buildPluginWorkspaceTabLaunchItems({
plugins,
serverId,
host,
launchSelection,
});
const profiles = resolveTerminalProfiles(config?.terminalProfiles);
const groups: WorkspaceTabLaunchGroup[] = [{ id: "tabs", label: null, items: tabItems }];
@@ -266,4 +253,48 @@ export function useWorkspaceTabLaunchCatalog(input: {
]);
}
/**
* Builds launcher items for parameterless workspace panels registered on `serverId`,
* skipping panels whose `params` schema rejects `{}` and isolating any throwing panel.
*/
export function buildPluginWorkspaceTabLaunchItems(input: {
plugins: readonly InstalledPlugin[];
serverId: string;
host: PaneHost;
launchSelection: (
selection: NewTabSelection,
) => (destination: WorkspaceTabLaunchDestination) => void;
}): WorkspaceTabLaunchItem[] {
const location = input.host === "explorer" ? "explorer" : "workspace";
const pluginItems: WorkspaceTabLaunchItem[] = [];
for (const plugin of input.plugins) {
if (plugin.serverId !== input.serverId) continue;
for (const panel of plugin.workspacePanels) {
if (!pluginPanelSupportsLocation(panel, location)) continue;
try {
const target = resolveParameterlessPluginPanelTarget(plugin.id, panel);
if (!target) continue;
const selection: NewTabSelection = {
kind: "target",
target,
};
pluginItems.push({
id: `plugin:${plugin.id}:${panel.id}`,
label: plugin.i18n.resolve(panel.title, plugin.locale),
Icon: pluginIconComponent(panel.icon),
disabled: false,
panelKind: "plugin",
launch: input.launchSelection(selection),
});
} catch (error) {
console.warn(
`[WorkspaceTabLauncher] Skipping plugin panel "${plugin.id}/${panel.id}" launcher item:`,
error,
);
}
}
}
return pluginItems;
}
export { getBuiltInLaunchOrder } from "./internal/catalog";
+4
View File
@@ -24,6 +24,8 @@ export type PluginWorkspaceTabTarget =
pluginId: string;
panelId: string;
context: "workspace";
params?: Record<string, string | number>;
identityKey?: string;
}
| {
kind: "plugin";
@@ -31,6 +33,8 @@ export type PluginWorkspaceTabTarget =
panelId: string;
context: "agent";
agentId: string;
params?: Record<string, string | number>;
identityKey?: string;
};
export type WorkspaceTabTarget =
+122
View File
@@ -251,6 +251,128 @@ describe("plugin panel SDK boundary", () => {
`),
).toEqual([]);
});
it("infers author-defined params and identity on workspace and agent panels", () => {
expect(
typeErrors(`
import {
type PluginAgentPanelProps,
type PluginClientContext,
type PluginPanelTargetParams,
type PluginWorkspacePanelProps,
} from "@getpaseo/plugin/client";
import { z } from "zod";
const prSchema = z.object({ prNumber: z.number(), commentId: z.string().optional() });
function ExternalPrPanel({ params, revision }: PluginWorkspacePanelProps<z.infer<typeof prSchema>>) {
const pr: number = params.prNumber;
const comment: string | undefined = params.commentId;
const rev: number = revision;
// @ts-expect-error params are read-only
params.prNumber = 2;
void rev;
void comment;
return null;
}
function ExternalAgentReview({ params }: PluginAgentPanelProps<{ file: string; line?: number }>) {
const agentId: string = params.agentId;
const file: string = params.file;
const line: number | undefined = params.line;
// @ts-expect-error params are read-only
params.agentId = "other";
void agentId;
void file;
void line;
return null;
}
function MismatchedWorkspace({ params }: PluginWorkspacePanelProps<{ wrong: string }>) {
void params.wrong;
return null;
}
function contribute(client: PluginClientContext) {
const targetParams: PluginPanelTargetParams = { a: "x", b: 1, c: undefined };
void targetParams;
client.addWorkspacePanel({
id: "pr",
title: "PR",
icon: "GitPullRequest",
params: prSchema,
identity: (p) => String(p.prNumber),
Component: ({ params, revision, tab }) => {
const n: number = params.prNumber;
const c: string | undefined = params.commentId;
const r: number = revision;
void tab.id;
void n;
void c;
void r;
return null;
},
});
client.addWorkspacePanel({
id: "pr-external",
title: "PR",
icon: "GitPullRequest",
params: prSchema,
Component: ExternalPrPanel,
});
client.addAgentPanel({
id: "agent-review",
title: "Review",
icon: "Scan",
params: z.object({ file: z.string(), line: z.number().optional() }),
identity: (p) => \`\${p.agentId}:\${p.file}\`,
Component: ({ params }) => {
const agentId: string = params.agentId;
const file: string = params.file;
const line: number | undefined = params.line;
void agentId;
void file;
void line;
return null;
},
});
client.addAgentPanel({
id: "agent-review-external",
title: "Review",
icon: "Scan",
params: z.object({ file: z.string(), line: z.number().optional() }),
Component: ExternalAgentReview,
});
client.addWorkspacePanel({
id: "nested-bad",
title: "Bad",
icon: "File",
// @ts-expect-error params values must be flat string | number | undefined
params: z.object({ nested: z.object({ a: z.string() }) }),
Component: () => null,
});
client.addAgentPanel({
id: "bool-bad",
title: "Bad",
icon: "File",
// @ts-expect-error params values must be flat string | number | undefined
params: z.object({ flag: z.boolean() }),
Component: () => null,
});
client.addWorkspacePanel({
id: "mismatched-schema",
title: "Bad",
icon: "File",
params: prSchema,
// @ts-expect-error Component params must match the registered params schema
Component: MismatchedWorkspace,
});
client.addWorkspacePanel({
id: "missing-schema",
title: "Bad",
icon: "File",
// @ts-expect-error cannot require custom params without registering a params schema
Component: MismatchedWorkspace,
});
}
`),
).toEqual([]);
});
});
describe("plugin workspace layout SDK boundary", () => {
+127 -18
View File
@@ -5,7 +5,7 @@ import type { PluginPaseoApi } from "./reference-api.js";
import type { AgentTimelineItem, JsonValue } from "@getpaseo/protocol/agent-types";
import type { ZodType, input as ZodInput, output as ZodOutput } from "zod";
import type { PluginFile } from "./file.js";
import type { PluginWorkspaceLayout } from "./workspace-layout.js";
import type { PluginPanelTargetParams, PluginWorkspaceLayout } from "./workspace-layout.js";
import type {
PluginComposer,
PluginComposerItemContribution,
@@ -200,6 +200,13 @@ interface PluginWorkspacePanelBase<Text extends PluginText = string> {
locations?: readonly PluginPanelLocation[];
}
/**
* Per-tab handle passed to every panel component.
*
* `tab.state` is strictly panel-owned, opaque persisted JSON (unlike `params`, which are sent by
* whoever opens or retargets the tab). `tab.state` is never passed to `workspaceLayout.open(...)`
* and is preserved across in-place `params` updates, `revision` bumps, and app reloads.
*/
export interface PluginTab {
/** This tab in its workspace's layout, as `useWorkspaceLayout` reads and arranges it. */
readonly id: string;
@@ -207,18 +214,37 @@ export interface PluginTab {
setModified(modified: boolean): void;
/** Overrides this tab's title while mounted. Pass null or empty string to reset to the static panel title. */
setTitle(title: string | null): void;
/** Opaque persisted JSON. Undefined until written; the panel validates it. */
/**
* Panel-owned persisted JSON state for this tab instance.
* Undefined until the panel calls `setState`; validate it with `useTabState`.
*/
readonly state: unknown;
/** Replaces this tab's persisted UI state. Callers of `workspaceLayout.open` cannot set it. */
setState(state: JsonValue): void;
}
/**
* Props delivered to every workspace, agent, and file panel component.
*
* - **`params`**: caller-sent, read-only inputs and retargeting hints validated by the panel's
* schema (with host-enforced `agentId` on agent panels).
* - **`revision`**: increments every time `workspaceLayout.open` delivers or re-sends `params` to
* this tab (via `"reveal"` or `"background"`), even when `params` values did not change.
* - **`tab`**: handle for panel-owned persisted UI state (`tab.state` / `tab.setState`), dirty
* status (`tab.setModified`), and layout tab ID (`tab.id`).
*/
export interface PluginPanelProps<Params> extends PluginNavigableHostProps {
workspaceId: string;
/** Caller-sent, read-only inputs and retargeting hints for what this tab should show. */
readonly params: Readonly<Params>;
/** Increments on each `workspaceLayout.open` targeting this tab so repeated hints are observable. */
revision: number;
/** Per-tab handle for panel-owned persisted UI state and unsaved-work status. */
tab: PluginTab;
openScreen(input: PluginOpenScreenInput): void;
}
/** Zod schema accepted by `addWorkspacePanel` and `addAgentPanel` for flat primitive `params`. */
export type PluginPanelParamsSchema = ZodType<PluginPanelTargetParams>;
export interface PluginWorkspacePanelParams {}
export interface PluginAgentPanelParams {
readonly agentId: string;
@@ -228,12 +254,16 @@ export interface PluginFilePanelParams {
readonly lineStart?: number;
readonly lineEnd?: number;
}
export interface PluginWorkspacePanelProps extends PluginPanelProps<PluginWorkspacePanelParams> {
export interface PluginWorkspacePanelProps<
Params = PluginWorkspacePanelParams,
> extends PluginPanelProps<Params> {
// COMPAT(pluginPanelFlatProps): added in v0.13.0, remove after 2027-04-23
/** @deprecated Use the panel registration to select the context. */
context: "workspace";
}
export interface PluginAgentPanelProps extends PluginPanelProps<PluginAgentPanelParams> {
export interface PluginAgentPanelProps<
Params = PluginWorkspacePanelParams,
> extends PluginPanelProps<PluginAgentPanelParams & Params> {
// COMPAT(pluginPanelFlatProps): added in v0.13.0, remove after 2027-04-23
/** @deprecated Use the panel registration to select the context. */
context: "agent";
@@ -276,10 +306,40 @@ export interface PluginClientContext extends PluginCommandCapabilities, PluginCl
addSidebarView(contribution: PluginSidebarViewContribution<PluginText>): PluginCleanup;
addSidebarHeaderItem(contribution: PluginSidebarItemContribution<PluginText>): PluginCleanup;
addSidebarFooterItem(contribution: PluginSidebarItemContribution<PluginText>): PluginCleanup;
/**
* Registers an agent-scoped workspace panel.
*
* - **`params`**: optional Zod schema for extra flat `string | number | undefined` fields
* alongside required, host-enforced `agentId: string`. When omitted, `params` is `{ agentId }`.
* - **`identity(params)`**: optional tab-coalescing key over `{ agentId, ...extra }`. Omit to
* keep one tab per `agentId`; return a key so tabs with different keys open separately while
* same-key opens update `params` in place, bump `revision`, and preserve `tab.state`.
*/
addAgentPanel<Schema extends PluginPanelParamsSchema>(
contribution: PluginAgentPanelContribution<PluginText, Schema>,
): PluginCleanup;
/**
* Registers an agent-scoped workspace panel receiving `{ agentId }` in `params`.
*/
addAgentPanel(contribution: PluginAgentPanelContribution<PluginText>): PluginCleanup;
addWorkspaceRowBadgeItem(
contribution: PluginWorkspaceRowBadgeItemContribution<PluginText>,
): PluginCleanup;
/**
* Registers a workspace-scoped panel.
*
* - **`params`**: optional Zod schema for caller-sent, read-only flat `string | number | undefined`
* inputs/hints. Panels whose schema rejects `{}` are omitted from parameterless UI tab launchers.
* - **`identity(params)`**: optional tab-coalescing key. Omit to keep one tab per workspace;
* provide a key so tabs with different keys open separately while same-key opens update
* `params` in place, bump `revision`, and preserve `tab.state`.
*/
addWorkspacePanel<Schema extends PluginPanelParamsSchema>(
contribution: PluginWorkspacePanelContribution<PluginText, Schema>,
): PluginCleanup;
/**
* Registers a workspace-scoped panel receiving `{}` in `params`.
*/
addWorkspacePanel(contribution: PluginWorkspacePanelContribution<PluginText>): PluginCleanup;
addCommandCenterItem(
contribution: PluginCommandCenterItemContribution<PluginText>,
@@ -329,25 +389,74 @@ export interface PluginClientContext extends PluginCommandCapabilities, PluginCl
export type PluginClientContribution = (client: PluginClientContext) => PluginCleanup;
export type PluginWorkspacePanelContribution<Text extends PluginText = string> =
| (PluginWorkspacePanelBase<Text> & {
export type PluginWorkspacePanelContribution<
Text extends PluginText = string,
Schema extends PluginPanelParamsSchema | undefined = undefined,
> = [Schema] extends [PluginPanelParamsSchema]
? PluginWorkspacePanelBase<Text> & {
// COMPAT(pluginPanelFlatProps): added in v0.13.0, remove after 2027-04-23
/** @deprecated Omit context. */
context?: "workspace";
Component: ComponentType<PluginWorkspacePanelProps>;
})
| (PluginWorkspacePanelBase<Text> & {
// COMPAT(pluginAgentPanelAlias): added in v0.13.0, remove after 2027-04-23
/** @deprecated Register with `addAgentPanel`. */
context: "agent";
Component: ComponentType<PluginAgentPanelProps>;
});
/**
* Zod schema validating caller-sent `params` (`Record<string, string | number | undefined>`).
* Panels that reject `{}` are not offered in parameterless UI tab launchers.
*/
params: Schema;
/**
* Maps validated `params` to a tab-coalescing key. Omit to keep one tab per workspace; any
* param excluded from the key acts as a retargeting hint that updates `params` and bumps
* `revision` in place while preserving `tab.state`.
*/
identity?: (params: Readonly<ZodOutput<Schema>>) => string;
Component: ComponentType<PluginWorkspacePanelProps<ZodOutput<Schema>>>;
}
:
| (PluginWorkspacePanelBase<Text> & {
// COMPAT(pluginPanelFlatProps): added in v0.13.0, remove after 2027-04-23
/** @deprecated Omit context. */
context?: "workspace";
params?: undefined;
/**
* Maps `params` (`{}`) to a tab-coalescing key. Omit to keep one tab per workspace.
*/
identity?: (params: Readonly<PluginWorkspacePanelParams>) => string;
Component: ComponentType<PluginWorkspacePanelProps>;
})
| (PluginWorkspacePanelBase<Text> & {
// COMPAT(pluginAgentPanelAlias): added in v0.13.0, remove after 2027-04-23
/** @deprecated Register with `addAgentPanel`. */
context: "agent";
params?: undefined;
identity?: undefined;
Component: ComponentType<PluginAgentPanelProps>;
});
export interface PluginAgentPanelContribution<
export type PluginAgentPanelContribution<
Text extends PluginText = string,
> extends PluginWorkspacePanelBase<Text> {
Component: ComponentType<PluginAgentPanelProps>;
}
Schema extends PluginPanelParamsSchema | undefined = undefined,
> = [Schema] extends [PluginPanelParamsSchema]
? PluginWorkspacePanelBase<Text> & {
/**
* Zod schema for extra caller-sent `params` (`Record<string, string | number | undefined>`)
* alongside host-enforced `agentId: string`.
*/
params: Schema;
/**
* Maps validated `params` (including `agentId`) to a tab-coalescing key. Omit to keep one
* tab per `agentId`; any param excluded from the key acts as a retargeting hint that updates
* `params` and bumps `revision` in place while preserving `tab.state`.
*/
identity?: (params: Readonly<PluginAgentPanelParams & ZodOutput<Schema>>) => string;
Component: ComponentType<PluginAgentPanelProps<ZodOutput<Schema>>>;
}
: PluginWorkspacePanelBase<Text> & {
params?: undefined;
/**
* Maps `params` (`{ agentId }`) to a tab-coalescing key. Omit to keep one tab per `agentId`.
*/
identity?: (params: Readonly<PluginAgentPanelParams>) => string;
Component: ComponentType<PluginAgentPanelProps>;
};
export interface PluginSettingsScreenContribution<Text extends PluginText = string> {
id: string;
+1
View File
@@ -3,6 +3,7 @@ export type {
PluginHostNavigationActions,
PluginTab,
PluginPanelProps,
PluginPanelParamsSchema,
PluginWorkspacePanelParams,
PluginAgentPanelParams,
PluginFilePanelParams,
@@ -15,12 +15,13 @@ export interface PluginWorkspaceLayout {
readonly workspaceId: string;
/**
* Opens a registered panel. With the default intent, `reveal`, an open tab of the same panel and
* identity is focused where it is and gets the params again with a new `revision`; `placement`
* decides where a tab that is not open yet goes.
* Opens a registered panel. With `intent: "reveal"` (default) or `"background"`, an open tab with
* the same panel and `identity` key is reused: its `params` are updated in place and its
* `revision` is incremented while preserving `tab.state`. `placement` decides where a new tab goes.
*
* Throws for a panel that is not registered, params the panel rejects, a placement the panel does
* not allow, or a pane that does not exist.
* Throws for a panel that is not registered, `params` that fail the panel's schema or are not a
* flat record of `string | number | undefined` values, a placement the panel does not allow, or a
* pane that does not exist.
*/
open(target: PluginPanelTarget, options?: PluginOpenTabOptions): PluginTabLocation;
/** Does nothing when no tab has this id. */
@@ -87,7 +88,7 @@ export interface PluginLayoutTab {
readonly paneId: string | null;
/** Always qualified: `paseo/file`, `my-plugin/review`. */
readonly panelId: string;
/** The params that identify what the tab shows. */
/** Read-only caller-supplied params and hints stored on this tab (undefined fields omitted). */
readonly params: PluginPanelTargetParams;
/** Where this tab's panel may live, from its registration. */
readonly locations: readonly PluginPanelLocation[];
@@ -112,7 +113,11 @@ export interface PluginPanelTarget {
params?: PluginPanelTargetParams;
}
export type PluginPanelTargetParams = Readonly<Record<string, string | number>>;
/**
* Flat, primitive caller-supplied params for opening a panel.
* Values must be `string`, finite `number`, or `undefined` so tab targets persist cleanly.
*/
export type PluginPanelTargetParams = Readonly<Record<string, string | number | undefined>>;
/**
* Where a tab goes. On phones and touch tablets, which have no splits, `pane`, `beside` and `split`
+44 -19
View File
@@ -2177,23 +2177,43 @@ export default function contribute(client: PluginClientContext) {
`addWorkspacePanel` and `addAgentPanel` fields:
| Field | Required | Meaning |
| ----------- | -------- | ------------------------------------------------------------- |
| `id` | Yes | Plugin-local panel ID. |
| `title` | Yes | Workspace-tab title. |
| `icon` | Yes | Lucide name, `{ svg }`, or component. See [Icons](#icons). |
| `locations` | No | `workspace` and/or `explorer`. Defaults to `workspace`. |
| `Component` | Yes | React Native component matching the selected context's props. |
| Field | Required | Meaning |
| ----------- | -------- | ------------------------------------------------------------------------------------------------------------------------------ |
| `id` | Yes | Plugin-local panel ID. |
| `title` | Yes | Workspace-tab title. |
| `icon` | Yes | Lucide name, `{ svg }`, or component. See [Icons](#icons). |
| `locations` | No | `workspace` and/or `explorer`. Defaults to `workspace`. |
| `params` | No | Zod schema validating flat `string \| number \| undefined` caller inputs (`agentId` is added by the host for `addAgentPanel`). |
| `identity` | No | `(params) => string` coalescing key. Tabs with the same key reuse one tab; omit for one tab per workspace (or per `agentId`). |
| `Component` | Yes | React Native component receiving `PluginWorkspacePanelProps<Params>` or `PluginAgentPanelProps<ExtraParams>`. |
Every panel receives `PluginPanelProps<Params>` with `theme`, `host`, `layout`, `navigation`,
`openScreen`, `workspaceId`, read-only `params`, `revision`, and `tab`. Workspace panels have empty
`PluginWorkspacePanelParams`; agent panels have `PluginAgentPanelParams` containing `agentId`.
`openScreen({ screenId, params })` opens one of this plugin's screens on the panel's host; unknown
screen IDs throw. `openScreen` on panels requires a Paseo app newer than 0.19.1; set
[`requirements.app`](#requirements) or check `typeof openScreen === "function"` on older apps.
`revision` increments whenever params are re-sent to the same tab, including an
identical request. `tab.id` is the tab's ID in the [workspace layout](#workspace-layout). It requires
Paseo 0.19.0 or later.
`openScreen`, `workspaceId`, read-only `params`, `revision`, and `tab`:
- **`params`** are caller-sent, read-only inputs and retargeting hints validated by the panel's `params` schema. Workspace panels default to `{}`; agent panels always include required `agentId: string` alongside any schema fields. Panels whose `params` schema rejects `{}` are omitted from parameterless UI tab launchers.
- **`identity(params)`** controls tab coalescing. When omitted, a workspace panel keeps one tab per workspace and an agent panel keeps one tab per `agentId`. When provided, tabs with the same key coalesce and different keys open separate tabs; any param excluded from `identity(params)` acts as a retargeting hint.
- **`revision`** increments every time `workspaceLayout.open` delivers or re-sends `params` to the same tab (with `"reveal"` or `"background"`), including an identical request.
- **`tab.state`** is panel-owned, opaque persisted JSON (never passed to `workspaceLayout.open`), preserved across in-place `params` updates, `revision` bumps, and app reloads. `tab.id` is the tab's ID in the [workspace layout](#workspace-layout). It requires Paseo 0.19.0 or later.
- **`openScreen({ screenId, params })`** opens one of this plugin's screens on the panel's host; unknown screen IDs throw. `openScreen` on panels requires a Paseo app newer than 0.19.1; set [`requirements.app`](#requirements) or check `typeof openScreen === "function"` on older apps.
```tsx
const prParams = z.object({
prNumber: z.number(),
commentId: z.string().optional(), // excluded from identity -> retargeting hint
});
client.addWorkspacePanel({
id: "pr",
title: "Pull Request",
icon: "GitPullRequest",
params: prParams,
identity: (p) => String(p.prNumber),
Component({ params, revision, tab }) {
// params is Readonly<{ prNumber: number; commentId?: string }>
return null;
},
});
```
`tab.setModified(boolean)` marks unsaved work and asks before closing. `tab.setTitle(title)` overrides
this tab's title while the panel is mounted; pass `null` or `""` to reset to the panel's static
@@ -2345,9 +2365,12 @@ has this command, a `/aside` slash command, and an outline panel that follows th
For example, closing a terminal tab kills the terminal. `focus`, `close`, and `closePane` do nothing
when no tab or pane has the id.
A `target` is `{ panelId, params? }`. By default, `open` reveals: if a tab of the same panel and
identity is open, Paseo focuses it where it is and sends it the params again with a new `revision`.
`placement` only decides where a tab that is not open yet goes. To move an open tab, call `move`.
A `target` is `{ panelId, params? }`. `params` must be a flat record of `string`, finite `number`,
or `undefined` values (validated against the panel's registered Zod schema; invalid params throw
`Panel "<id>" does not accept these params`). By default, `open` reveals: if a tab of the same panel
and `identity` key is open, Paseo focuses it where it is, updates its `params` in place, preserves
`tab.state`, and increments `revision`. `placement` only decides where a tab that is not open yet
goes. To move an open tab, call `move`.
| `placement` | Where the tab goes |
| ---------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
@@ -2375,7 +2398,9 @@ have loaded.
### Panel IDs
A panel ID is `<pluginId>/<panelId>`. A bare ID means your own panel. Reads always return the
qualified form. A workspace panel takes no params, and an agent panel takes `{ agentId }`.
qualified form. Without a `params` schema, a workspace panel accepts `{}` and an agent panel accepts
`{ agentId }`; with `params`, the panel accepts the schema's flat fields (plus `agentId` for agent
panels).
Paseo's own panels use the `paseo` namespace:
+43 -18
View File
@@ -1755,21 +1755,43 @@ export default function contribute(client: PluginClientContext) {
`addWorkspacePanel` 和 `addAgentPanel` 的字段:
| 字段 | 是否必填 | 含义 |
| ----------- | -------- | --------------------------------------------------- |
| `id` | 是 | 插件内部的面板 ID。 |
| `title` | 是 | 工作区标签页的标题。 |
| `icon` | 是 | Lucide 名称、`{ svg }` 或组件。参见[图标](#icons)。 |
| `locations` | 否 | `workspace` 和/或 `explorer`。默认为 `workspace`。 |
| `Component` | 是 | 与所选上下文的属性相匹配的 React Native 组件。 |
| 字段 | 是否必填 | 含义 |
| ----------- | -------- | ------------------------------------------------------------------------------------------------------------------ |
| `id` | 是 | 插件内部的面板 ID。 |
| `title` | 是 | 工作区标签页的标题。 |
| `icon` | 是 | Lucide 名称、`{ svg }` 或组件。参见[图标](#icons)。 |
| `locations` | 否 | `workspace` 和/或 `explorer`。默认为 `workspace`。 |
| `params` | 否 | 用于验证扁平 `string \| number \| undefined` 调用方输入的 Zod schema(`addAgentPanel` 由宿主自动附加 `agentId`)。 |
| `identity` | 否 | `(params) => string` 合并键函数。相同键复用同一标签页;省略时按工作区(或按 `agentId`)只保留一个标签页。 |
| `Component` | 是 | 接收 `PluginWorkspacePanelProps<Params>` 或 `PluginAgentPanelProps<ExtraParams>` 的 React Native 组件。 |
每个面板都接收 `PluginPanelProps<Params>`,包含 `theme`、`host`、`layout`、`navigation`、`openScreen`、
`workspaceId`、只读的 `params`、`revision` 和 `tab`。工作区面板使用空的
`PluginWorkspacePanelParams`;Agent 面板的 `PluginAgentPanelParams` 包含 `agentId`。
`openScreen({ screenId, params })` 在该面板所属主机上打开此插件的某个界面,未知的界面 ID 会抛出错误;
面板上的 `openScreen` 需要高于 0.19.1 的 Paseo 应用,请在 [`requirements.app`](#requirements) 中声明应用版本要求,或在旧版应用上先检查 `typeof openScreen === "function"`。
每次向同一标签页重新发送 params 时,`revision` 都会递增,即使请求与上次相同。
`tab.id` 是该标签页在[工作区布局](#workspace-layout)中的 ID。它需要 Paseo 0.19.0 或更高版本。
`workspaceId`、只读的 `params`、`revision` 和 `tab`:
- **`params`** 是调用方传入的只读输入和重定向提示,由面板的 `params` schema 验证。工作区面板默认为空对象 `{}`;Agent 面板始终在任意 schema 字段之外包含必填的 `agentId: string`。如果面板的 `params` schema 拒绝 `{}`,它不会出现在无参标签页启动器中。
- **`identity(params)`** 控制标签页合并。省略时,工作区面板每个工作区保留一个标签页,Agent 面板每个 `agentId` 保留一个标签页。提供时,相同键的打开会合并到同一标签页,不同键会打开独立标签页;未包含在 `identity(params)` 中的参数仅作为重定向提示。
- **`revision`** 每次通过 `workspaceLayout.open`(`"reveal"` 或 `"background"`)向同一标签页传递或重发 params 时都会递增,即使值与上次相同。
- **`tab.state`** 是面板自身拥有的持久化不透明 JSON(不能通过 `workspaceLayout.open` 传入),在原地更新 `params`、`revision` 递增和应用重载后仍会保留。`tab.id` 是该标签页在[工作区布局](#workspace-layout)中的 ID。它需要 Paseo 0.19.0 或更高版本。
- **`openScreen({ screenId, params })`** 在该面板所属主机上打开此插件的某个界面,未知的界面 ID 会抛出错误;面板上的 `openScreen` 需要高于 0.19.1 的 Paseo 应用,请在 [`requirements.app`](#requirements) 中声明应用版本要求,或在旧版应用上先检查 `typeof openScreen === "function"`。
```tsx
const prParams = z.object({
prNumber: z.number(),
commentId: z.string().optional(), // excluded from identity -> retargeting hint
});
client.addWorkspacePanel({
id: "pr",
title: "Pull Request",
icon: "GitPullRequest",
params: prParams,
identity: (p) => String(p.prNumber),
Component({ params, revision, tab }) {
// params is Readonly<{ prNumber: number; commentId?: string }>
return null;
},
});
```
`tab.setModified(boolean)` 标记未保存的更改,并在关闭前询问。`tab.setTitle(title)` 在面板挂载期间覆盖该标签页的标题;传入 `null` 或 `""` 可恢复为面板的静态 `title`(如需兼容旧版应用,请使用 `tab.setTitle?.(title)`)。`tab.state` 是由面板定义的持久化
JSON,初始为 `undefined`;`tab.setState(value)` 替换整个值。每个标签页拥有独立状态。
@@ -1909,9 +1931,11 @@ client.addCommandCenterItem({
`close` 和 `closePane` 会询问与关闭按钮相同的问题,并产生相同的效果。例如,关闭终端标签页会终止该终端。
当没有标签页或窗格使用该 ID 时,`focus`、`close` 和 `closePane` 不做任何事。
`target` 是 `{ panelId, params? }`。默认情况下 `open` 执行显示(reveal):如果同一面板、同一标识的标签页已经打开,
Paseo 就在原处聚焦它,并以新的 `revision` 重新把 params 发给它。`placement` 只决定尚未打开的标签页放在哪里。
要移动已打开的标签页,请调用 `move`。
`target` 是 `{ panelId, params? }`。`params` 必须是键为字符串、值为 `string`、有限 `number` 或
`undefined` 的扁平对象(会按面板注册的 Zod schema 验证;无效 params 会抛出
`Panel "<id>" does not accept these params`)。默认情况下 `open` 执行显示(reveal):如果同一面板、
同一 `identity` 键的标签页已经打开,Paseo 就在原处聚焦它、原地更新它的 `params`、保留 `tab.state` 并递增
`revision`。`placement` 只决定尚未打开的标签页放在哪里。要移动已打开的标签页,请调用 `move`。
| `placement` | 标签页放在哪里 |
| ---------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------- |
@@ -1936,8 +1960,9 @@ Paseo 就在原处聚焦它,并以新的 `revision` 重新把 params 发给它
### 面板 ID {#panel-ids}
面板 ID 是 `<pluginId>/<panelId>`。不带前缀的 ID 表示你自己的面板。读取时总是返回完整形式。工作区面板不接受 params,
Agent 面板接受 `{ agentId }`。
面板 ID 是 `<pluginId>/<panelId>`。不带前缀的 ID 表示你自己的面板。读取时总是返回完整形式。未提供
`params` schema 时,工作区面板接受 `{}`,Agent 面板接受 `{ agentId }`;提供 `params` 时,面板接受该
schema 的扁平字段(Agent 面板同时包含 `agentId`)。
Paseo 自带的面板使用 `paseo` 命名空间:
+37
View File
@@ -249,6 +249,43 @@ export default function contribute(client: PluginClientContext) {
Register a panel that belongs to one agent with `addAgentPanel`, and read `params.agentId` in it. Panels receive `tab` (`id`, `setModified`, `setTitle`, `state`, `setState`): call `tab.setTitle(title)` to override the tab's title while mounted, and `tab.setTitle(null)` to restore the static `title`. Every panel (`PluginWorkspacePanelProps`, `PluginAgentPanelProps`, and `PluginFilePanelProps`) also receives `openScreen({ screenId, params })` to open one of this plugin's screens on that host (check `typeof openScreen === "function"` or set `requirements.app` from Reference if older apps may run the plugin). Command Center callbacks receive `paseo`, `rpc`, `openScreen`, and, in workspace and agent context, `workspaceLayout`, which opens and arranges panes and tabs (Reference > Workspace layout; it names the release that added it).
Pass optional `params` (a Zod schema for flat `string | number | undefined` values) and `identity(params)` when a panel accepts caller-sent inputs or opens multiple keyed tabs:
```tsx
// client/pr-panel.tsx
import type { PluginClientContext, PluginWorkspacePanelProps } from "@getpaseo/plugin/client";
import { Text, View } from "react-native";
import { z } from "zod";
const prParams = z.object({
prNumber: z.number(),
commentId: z.string().optional(),
});
function PrPanel({ params, revision, theme }: PluginWorkspacePanelProps<z.infer<typeof prParams>>) {
return (
<View style={{ flex: 1, backgroundColor: theme.colors.surface0 }}>
<Text style={{ color: theme.colors.foreground }}>
PR #{params.prNumber} ({params.commentId ?? "top"}, rev {revision})
</Text>
</View>
);
}
export function registerPrPanel(client: PluginClientContext) {
client.addWorkspacePanel({
id: "pr",
title: "PR",
icon: "GitPullRequest",
params: prParams,
identity: (p) => String(p.prNumber),
Component: PrPanel,
});
}
```
Omit `identity` to keep one tab per workspace (or per `agentId` on `addAgentPanel`) and update its `params` + bump `revision` in place while preserving `tab.state`; provide `identity` to keep one tab per key while any omitted param acts as a retargeting hint. Panels whose `params` schema rejects `{}` are hidden from parameterless UI tab launchers.
### Add a screen and a sidebar item
A sidebar item is a component. It renders one or more `SidebarRow`s and decides what a press does: