mirror of
https://github.com/getpaseo/paseo.git
synced 2026-12-04 14:16:49 +00:00
Compare commits
11
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
cdec809d91 | ||
|
|
89d7895fa2 | ||
|
|
40ccec39c1 | ||
|
|
c4d1348be4 | ||
|
|
54e4c15912 | ||
|
|
b7c877129d | ||
|
|
abbbecc8a3 | ||
|
|
3484943a7e | ||
|
|
55bba06161 | ||
|
|
4863e7e761 | ||
|
|
ad9073dc8a |
+5
-3
@@ -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
|
||||
|
||||
@@ -745,7 +745,8 @@ async function recordDelayedRunningTransition(
|
||||
|
||||
const prompt = "Second prompt keeps streaming.";
|
||||
gate.holdNextAgentStreamEvent("turn_started");
|
||||
gate.holdNextAgentUpdate(agent.agentId, "running");
|
||||
// Hold every running snapshot until release so the prompt-commit emitState does not leak early.
|
||||
gate.holdAgentUpdates(agent.agentId, "running");
|
||||
gate.holdNextServerMessage("send_agent_message_response");
|
||||
gate.setAgentStreamSuppressed(true);
|
||||
await recordTurnFrames(page, prompt);
|
||||
@@ -773,7 +774,7 @@ async function recordDelayedRunningTransition(
|
||||
await expect(page.getByTestId("turn-working-elapsed")).toBeVisible();
|
||||
gate.releaseHeldServerMessage("send_agent_message_response");
|
||||
responseReleased = true;
|
||||
gate.releaseHeldAgentUpdate(agent.agentId, "running");
|
||||
gate.releaseHeldAgentUpdates(agent.agentId, "running");
|
||||
snapshotReleased = true;
|
||||
} else if (releaseOrder === "response-before-turn") {
|
||||
gate.releaseHeldServerMessage("send_agent_message_response");
|
||||
@@ -782,13 +783,13 @@ async function recordDelayedRunningTransition(
|
||||
gate.releaseHeldAgentStreamEvent("turn_started");
|
||||
turnReleased = true;
|
||||
await expect(page.getByTestId("turn-working-elapsed")).toBeVisible();
|
||||
gate.releaseHeldAgentUpdate(agent.agentId, "running");
|
||||
gate.releaseHeldAgentUpdates(agent.agentId, "running");
|
||||
snapshotReleased = true;
|
||||
} else {
|
||||
gate.releaseHeldServerMessage("send_agent_message_response");
|
||||
responseReleased = true;
|
||||
await recordPaintsFor(page, 80);
|
||||
gate.releaseHeldAgentUpdate(agent.agentId, "running");
|
||||
gate.releaseHeldAgentUpdates(agent.agentId, "running");
|
||||
snapshotReleased = true;
|
||||
await expect(page.getByTestId("turn-working-elapsed")).toBeVisible();
|
||||
gate.releaseHeldAgentStreamEvent("turn_started");
|
||||
@@ -804,7 +805,7 @@ async function recordDelayedRunningTransition(
|
||||
return { frames, checkpoints };
|
||||
} finally {
|
||||
if (!turnReleased) gate.releaseHeldAgentStreamEvent("turn_started");
|
||||
if (!snapshotReleased) gate.releaseHeldAgentUpdate(agent.agentId, "running");
|
||||
if (!snapshotReleased) gate.releaseHeldAgentUpdates(agent.agentId, "running");
|
||||
if (!responseReleased) gate.releaseHeldServerMessage("send_agent_message_response");
|
||||
gate.setAgentStreamSuppressed(false);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,350 @@
|
||||
import { mkdtemp, rm, writeFile } from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
import path from "node:path";
|
||||
import type { Locator, Page } from "@playwright/test";
|
||||
import { expect, test } from "../support/fixtures";
|
||||
import { gotoAppShell } from "../support/helpers/app";
|
||||
import { openCommandCenter } from "../support/helpers/command-center";
|
||||
import { buildAgentRoute } from "../support/helpers/mock-agent";
|
||||
import { connectNewWorkspaceDaemonClient } from "../support/helpers/new-workspace";
|
||||
import { approveClientPluginsInUi } from "../support/helpers/plugin-execution-approval";
|
||||
import { pluginRequirements } from "../support/helpers/plugin-fixture";
|
||||
import { seedWorkspace } from "../support/helpers/seed-client";
|
||||
|
||||
const PLUGIN_ID = "composer-pill-items-e2e";
|
||||
const WIDE = { width: 1440, height: 900 };
|
||||
const COMPACT = { width: 390, height: 844 };
|
||||
|
||||
function pluginSource(workspaceId: string, agentId: string): string {
|
||||
return `import React from "react";
|
||||
import { Pressable, Text, View } from "react-native";
|
||||
import { useWorkspace } from "@getpaseo/plugin/client";
|
||||
import { ComposerPill } from "@getpaseo/plugin/client/ui";
|
||||
|
||||
function InboxScreen({ theme, params }) {
|
||||
return (
|
||||
<View style={{ flex: 1, padding: 24, gap: 8 }}>
|
||||
<Text style={{ color: theme.colors.foreground }}>Inbox screen for {params.agentId}</Text>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
function InboxPopover({ theme, layout, close, openScreen }) {
|
||||
const workspaceName = useWorkspace(${JSON.stringify(workspaceId)}, (w) => w.name);
|
||||
return (
|
||||
<View style={{ gap: 10 }}>
|
||||
<Text style={{ color: theme.colors.foreground, fontSize: 16 }}>Inbox decisions</Text>
|
||||
<Text style={{ color: theme.colors.foregroundMuted }}>Workspace: {workspaceName}</Text>
|
||||
<Text style={{ color: theme.colors.foregroundMuted }}>
|
||||
Presentation: {layout.compact ? "compact" : "wide"}
|
||||
</Text>
|
||||
<Pressable
|
||||
accessibilityRole="button"
|
||||
accessibilityLabel="Open inbox screen"
|
||||
onPress={() => openScreen({ screenId: "inbox", params: { agentId: ${JSON.stringify(agentId)} } })}
|
||||
>
|
||||
<Text style={{ color: theme.colors.foreground }}>Open screen</Text>
|
||||
</Pressable>
|
||||
<Pressable
|
||||
accessibilityRole="button"
|
||||
accessibilityLabel="Close inbox popover"
|
||||
onPress={close}
|
||||
>
|
||||
<Text style={{ color: theme.colors.foreground }}>Done</Text>
|
||||
</Pressable>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
function LivePopover({ theme, close }) {
|
||||
return (
|
||||
<View style={{ gap: 8 }}>
|
||||
<Text style={{ color: theme.colors.foreground }}>Live popover content</Text>
|
||||
<Pressable
|
||||
accessibilityRole="button"
|
||||
accessibilityLabel="Trigger live update"
|
||||
onPress={() => updateLivePopover?.()}
|
||||
>
|
||||
<Text style={{ color: theme.colors.foreground }}>Update</Text>
|
||||
</Pressable>
|
||||
<Pressable
|
||||
accessibilityRole="button"
|
||||
accessibilityLabel="Close live popover"
|
||||
onPress={close}
|
||||
>
|
||||
<Text style={{ color: theme.colors.foreground }}>Close</Text>
|
||||
</Pressable>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
let updateLivePopover = null;
|
||||
|
||||
function QuietPill({ workspaceId }) {
|
||||
const name = useWorkspace(workspaceId, (w) => w.name);
|
||||
if (name !== "Show quiet pill") return null;
|
||||
return <ComposerPill icon="Sparkles" label="Quiet" onPress={() => {}} />;
|
||||
}
|
||||
|
||||
let finishAction = () => {};
|
||||
let actionAttempts = 0;
|
||||
|
||||
function ActionPill() {
|
||||
const [checks, setChecks] = React.useState(0);
|
||||
return (
|
||||
<ComposerPill
|
||||
icon="Play"
|
||||
label={checks === 0 ? "Run check" : "Checks · " + checks}
|
||||
title="Run check action"
|
||||
onPress={async () => {
|
||||
actionAttempts += 1;
|
||||
if (actionAttempts === 1) throw new Error("Action check failed");
|
||||
await new Promise((resolve) => {
|
||||
finishAction = resolve;
|
||||
});
|
||||
setChecks((n) => n + 1);
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function InboxPill({ openPopover }) {
|
||||
return (
|
||||
<ComposerPill
|
||||
icon="Inbox"
|
||||
label="2 decisions"
|
||||
onPress={() => openPopover(InboxPopover)}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
export default function contribute(client) {
|
||||
const workspaceId = ${JSON.stringify(workspaceId)};
|
||||
const agentId = ${JSON.stringify(agentId)};
|
||||
client.addScreen({ id: "inbox", title: "Inbox Screen", Component: InboxScreen });
|
||||
const removeQuiet = client.addComposerPillItem({ id: "quiet", title: "Quiet", Component: QuietPill });
|
||||
const removeAction = client.addComposerPillItem({ id: "action", title: "Run check", Component: ActionPill });
|
||||
const removeInbox = client.addComposerPillItem({ id: "inbox", title: "Inbox decisions", Component: InboxPill });
|
||||
|
||||
const live = client.addComposerPill({
|
||||
id: "live-popover",
|
||||
workspaceId,
|
||||
agentId,
|
||||
button: {
|
||||
title: "Live popover",
|
||||
icon: "Eye",
|
||||
label: "Live",
|
||||
behavior: { kind: "popover", Content: LivePopover },
|
||||
},
|
||||
});
|
||||
|
||||
const dynamicMenu = client.addComposerPill({
|
||||
id: "dynamic-menu",
|
||||
workspaceId,
|
||||
agentId,
|
||||
button: {
|
||||
title: "Dynamic menu",
|
||||
icon: "List",
|
||||
label: "Decisions",
|
||||
behavior: {
|
||||
kind: "menu",
|
||||
items: [
|
||||
{
|
||||
kind: "item",
|
||||
id: "D42",
|
||||
title: "Decision D42",
|
||||
behavior: {
|
||||
kind: "action",
|
||||
onPress() {
|
||||
dynamicMenu.update({ label: "Picked D42" });
|
||||
},
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
client.addCommandCenterItem({
|
||||
id: "finish-check",
|
||||
title: "Finish check action",
|
||||
icon: "Check",
|
||||
context: "workspace",
|
||||
onSelect: () => finishAction(),
|
||||
});
|
||||
updateLivePopover = () =>
|
||||
live.update({
|
||||
label: "Live · 2",
|
||||
behavior: { kind: "popover", Content: LivePopover },
|
||||
});
|
||||
|
||||
return () => {
|
||||
finishAction();
|
||||
removeQuiet();
|
||||
removeAction();
|
||||
removeInbox();
|
||||
live.remove();
|
||||
dynamicMenu.remove();
|
||||
};
|
||||
}
|
||||
`;
|
||||
}
|
||||
|
||||
async function runCommand(page: Page, title: string) {
|
||||
const panel = await openCommandCenter(page);
|
||||
await panel.getByTestId("command-center-input").fill(title);
|
||||
await panel.getByRole("button", { name: title, exact: true }).click();
|
||||
await expect(panel).not.toBeVisible();
|
||||
}
|
||||
|
||||
async function expectStill(subject: Locator) {
|
||||
let previous: Buffer | null = null;
|
||||
await expect
|
||||
.poll(
|
||||
async () => {
|
||||
const current = await subject.screenshot();
|
||||
const still = previous !== null && current.equals(previous);
|
||||
previous = current;
|
||||
return still;
|
||||
},
|
||||
{ intervals: [150] },
|
||||
)
|
||||
.toBe(true);
|
||||
}
|
||||
|
||||
async function qaScreenshot(page: Page, name: string) {
|
||||
const directory = process.env.PASEO_QA_SCREENSHOT_DIR;
|
||||
if (!directory) return;
|
||||
await page.waitForTimeout(300);
|
||||
await page.screenshot({ path: path.join(directory, `${name}.png`) });
|
||||
}
|
||||
|
||||
test("declarative addComposerPillItem + ComposerPill and imperative pill fixes work end-to-end", async ({
|
||||
page,
|
||||
}) => {
|
||||
test.setTimeout(180_000);
|
||||
const workspace = await seedWorkspace({ repoPrefix: "composer-pill-items-" });
|
||||
const agent = await workspace.client.createAgent({
|
||||
provider: "mock",
|
||||
cwd: workspace.repoPath,
|
||||
workspaceId: workspace.workspaceId,
|
||||
title: "Declarative composer pills",
|
||||
model: "e2e-fast-stream",
|
||||
modeId: "load-test",
|
||||
});
|
||||
const client = await connectNewWorkspaceDaemonClient({ ownProjects: false });
|
||||
const config = await client.getDaemonConfig();
|
||||
const directory = await mkdtemp(path.join(tmpdir(), "paseo-pill-items-"));
|
||||
try {
|
||||
await writeFile(
|
||||
path.join(directory, "paseo-plugin.json"),
|
||||
JSON.stringify({ id: PLUGIN_ID, requirements: pluginRequirements }),
|
||||
);
|
||||
await writeFile(
|
||||
path.join(directory, "index.client.tsx"),
|
||||
pluginSource(workspace.workspaceId, agent.id),
|
||||
);
|
||||
await client.patchDaemonConfig({ pluginsEnabled: true });
|
||||
await client.installDirectoryPlugin(directory);
|
||||
|
||||
await page.setViewportSize(WIDE);
|
||||
await gotoAppShell(page);
|
||||
await approveClientPluginsInUi(page, [PLUGIN_ID]);
|
||||
await page.goto(buildAgentRoute(workspace.workspaceId, agent.id));
|
||||
|
||||
const actionPill = page.getByRole("button", { name: "Run check action", exact: true });
|
||||
const inboxPill = page.getByRole("button", { name: "2 decisions", exact: true });
|
||||
await expect(actionPill).toBeVisible();
|
||||
await expect(inboxPill).toBeVisible();
|
||||
|
||||
await test.step("null items leave no empty gap in the composer track", async () => {
|
||||
await expect(page.getByRole("button", { name: "Quiet", exact: true })).toHaveCount(0);
|
||||
const actionBox = (await actionPill.boundingBox())!;
|
||||
const inboxBox = (await inboxPill.boundingBox())!;
|
||||
expect(Math.abs(actionBox.y - inboxBox.y)).toBeLessThan(2);
|
||||
expect(actionBox.height).toBeGreaterThanOrEqual(32);
|
||||
expect(inboxBox.height).toBeGreaterThanOrEqual(32);
|
||||
// 4px track gap between adjacent pills with no empty wrapper gap in between.
|
||||
expect(inboxBox.x - (actionBox.x + actionBox.width)).toBeLessThanOrEqual(8);
|
||||
await qaScreenshot(page, "01-desktop-track");
|
||||
});
|
||||
|
||||
await test.step("ComposerPill shows error toast on rejection, enters pending busy state, and recovers", async () => {
|
||||
await actionPill.click();
|
||||
await expect(page.getByText("Action check failed", { exact: true })).toBeVisible();
|
||||
await expect(actionPill).toBeEnabled();
|
||||
|
||||
await actionPill.click();
|
||||
await expect(actionPill).toBeDisabled();
|
||||
await expect(actionPill).toHaveAttribute("aria-busy", "true");
|
||||
await qaScreenshot(page, "02-desktop-pill-pending");
|
||||
|
||||
await runCommand(page, "Finish check action");
|
||||
await expect(actionPill).toBeEnabled();
|
||||
await expect(actionPill).toContainText("Checks · 1");
|
||||
});
|
||||
|
||||
await test.step("openPopover anchors above the pill on desktop, dismisses cleanly, and openScreen navigates", async () => {
|
||||
await inboxPill.click();
|
||||
const popoverTitle = page.getByText("Inbox decisions", { exact: true });
|
||||
await expect(popoverTitle).toBeInViewport();
|
||||
await expect(page.getByText("Presentation: wide", { exact: true })).toBeVisible();
|
||||
await expectStill(popoverTitle);
|
||||
|
||||
const pillBox = (await inboxPill.boundingBox())!;
|
||||
const popoverBox = (await page
|
||||
.getByTestId(`plugin-composer-pill-${PLUGIN_ID}-inbox-popover`)
|
||||
.boundingBox())!;
|
||||
expect(popoverBox.y + popoverBox.height).toBeLessThanOrEqual(pillBox.y + 1);
|
||||
expect(Math.abs(popoverBox.x - pillBox.x)).toBeLessThan(80);
|
||||
await qaScreenshot(page, "03-desktop-popover");
|
||||
|
||||
await page.keyboard.press("Escape");
|
||||
await expect(popoverTitle).toHaveCount(0);
|
||||
|
||||
await inboxPill.click();
|
||||
await expect(popoverTitle).toBeVisible();
|
||||
await page.getByRole("button", { name: "Open inbox screen", exact: true }).click();
|
||||
await expect(popoverTitle).toHaveCount(0);
|
||||
await expect(page.getByText(`Inbox screen for ${agent.id}`, { exact: true })).toBeVisible();
|
||||
await page.getByTestId("plugin-surface-close").click();
|
||||
await expect(inboxPill).toBeVisible();
|
||||
});
|
||||
|
||||
await test.step("imperative PluginButtonStore fixes: same-Content popover stays open on update and dynamic menu IDs work", async () => {
|
||||
const livePill = page.getByRole("button", { name: "Live popover", exact: true });
|
||||
await livePill.click();
|
||||
await expect(page.getByText("Live popover content", { exact: true })).toBeVisible();
|
||||
|
||||
await page.getByRole("button", { name: "Trigger live update", exact: true }).click();
|
||||
await expect(livePill).toContainText("Live · 2");
|
||||
await expect(page.getByText("Live popover content", { exact: true })).toBeVisible();
|
||||
await page.getByRole("button", { name: "Close live popover", exact: true }).click();
|
||||
await expect(page.getByText("Live popover content", { exact: true })).toHaveCount(0);
|
||||
|
||||
const menuPill = page.getByRole("button", { name: "Dynamic menu", exact: true });
|
||||
await menuPill.click();
|
||||
await page.getByRole("menuitem", { name: "Decision D42", exact: true }).click();
|
||||
await expect(menuPill).toContainText("Picked D42");
|
||||
});
|
||||
|
||||
await test.step("on compact layouts openPopover renders a bottom sheet and dismisses cleanly", async () => {
|
||||
await page.setViewportSize(COMPACT);
|
||||
await expect(inboxPill).toBeVisible();
|
||||
await inboxPill.click();
|
||||
const compactLabel = page.getByText("Presentation: compact", { exact: true });
|
||||
await expect(compactLabel).toBeInViewport();
|
||||
const sheetBox = (await compactLabel.boundingBox())!;
|
||||
expect(sheetBox.y).toBeGreaterThan(COMPACT.height / 2);
|
||||
await qaScreenshot(page, "04-compact-sheet");
|
||||
await page.getByRole("button", { name: "Close inbox popover", exact: true }).click();
|
||||
await expect(compactLabel).toHaveCount(0);
|
||||
});
|
||||
} finally {
|
||||
await client.removePlugin(PLUGIN_ID).catch(() => undefined);
|
||||
await client.patchDaemonConfig({ pluginsEnabled: config.config.pluginsEnabled });
|
||||
await client.close();
|
||||
await rm(directory, { recursive: true, force: true });
|
||||
await workspace.cleanup();
|
||||
}
|
||||
});
|
||||
@@ -27,7 +27,10 @@ import {
|
||||
} from "@getpaseo/plugin/client";
|
||||
import { useQueryClient } from "@tanstack/react-query";
|
||||
import { DocumentFrame, Loading } from "@getpaseo/plugin/client/ui";
|
||||
function Pdf({ file, workspaceId }) {
|
||||
function FileDetailsScreen({ params }) {
|
||||
return <View><Text>File screen: {params.file}</Text></View>;
|
||||
}
|
||||
function Pdf({ file, workspaceId, openScreen }) {
|
||||
usePaseo();
|
||||
useQueryClient();
|
||||
const workspace = useWorkspace(workspaceId, value => ({ id: value.id }));
|
||||
@@ -44,6 +47,9 @@ function Pdf({ file, workspaceId }) {
|
||||
<Text>Path {file.path}</Text>
|
||||
<Text>Bytes {bytes.bytes.length}; URL bytes {urlBytes}</Text>
|
||||
<Text>Workspace {workspace?.id}</Text>
|
||||
<Pressable accessibilityRole="button" onPress={() => openScreen({ screenId: "details", params: { file: file.name } })}>
|
||||
<Text>Open screen from file panel</Text>
|
||||
</Pressable>
|
||||
<DocumentFrame url={href} testID="plugin-pdf-frame" />
|
||||
</View>;
|
||||
}
|
||||
@@ -69,6 +75,7 @@ function Markdown({ file, tab }) {
|
||||
</View>;
|
||||
}
|
||||
export default function contribute(client) {
|
||||
client.addScreen({ id: "details", title: "File details", Component: FileDetailsScreen });
|
||||
client.addFilePanel({ id: "pdf", title: "PDF", icon: "FileText",
|
||||
files: { extensions: ["pdf", "txt"] }, Component: Pdf });
|
||||
client.addFilePanel({ id: "markdown", title: "Plugin Markdown", icon: "FileText",
|
||||
@@ -92,6 +99,16 @@ async function associateMarkdownWithPlugin(page: Page) {
|
||||
async function editMarkdownThroughPlugin(page: Page) {
|
||||
await page.getByRole("button", { name: "Edit Markdown through plugin", exact: true }).click();
|
||||
}
|
||||
async function openFileDetailsScreenFromPanel(page: Page, name: string) {
|
||||
await page.getByRole("button", { name: "Open screen from file panel", exact: true }).click();
|
||||
await expect(page).toHaveURL(
|
||||
new RegExp(`/plugin/${PLUGIN_ID}/surface/details\\?param\\.file=${encodeURIComponent(name)}$`),
|
||||
);
|
||||
await expect(page.getByText(`File screen: ${name}`, { exact: true })).toBeVisible();
|
||||
await page.getByTestId("plugin-surface-close").click();
|
||||
await expect(page.getByText(`PDF plugin: ${name}`, { exact: true })).toBeVisible();
|
||||
}
|
||||
|
||||
/** Opens the tab with Paseo's Markdown panel from "Open with…" and shows its Source view. */
|
||||
async function openBuiltinMarkdownSource(page: Page, name: string) {
|
||||
await page.getByTestId(`workspace-tab-file_${name}`).first().click({ button: "right" });
|
||||
@@ -152,6 +169,7 @@ test("directory plugins render PDF bytes and write Markdown through the file han
|
||||
const pdfScreenshot = testInfo.outputPath("plugin-pdf-web.png");
|
||||
await page.screenshot({ path: pdfScreenshot });
|
||||
await testInfo.attach("plugin-pdf-web", { path: pdfScreenshot, contentType: "image/png" });
|
||||
await openFileDetailsScreenFromPanel(page, "report.pdf");
|
||||
|
||||
// A plugin panel claiming a text file competes with Source, so Paseo asks over the plugin.
|
||||
await openWorkspaceFile(page, "bytes.txt");
|
||||
|
||||
@@ -0,0 +1,288 @@
|
||||
import { mkdtemp, rm, writeFile } from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
import path from "node:path";
|
||||
import type { Locator, TestInfo } from "@playwright/test";
|
||||
import { expect, test, type Page } from "../support/fixtures";
|
||||
import { openCommandCenter } from "../support/helpers/command-center";
|
||||
import { openFileExplorer, openFileFromExplorer } from "../support/helpers/file-explorer";
|
||||
import { openAgentRoute, seedMockAgentWorkspace } from "../support/helpers/mock-agent";
|
||||
import { connectNewWorkspaceDaemonClient } from "../support/helpers/new-workspace";
|
||||
import { approveClientPluginsInUi } from "../support/helpers/plugin-execution-approval";
|
||||
import { pluginRequirements } from "../support/helpers/plugin-fixture";
|
||||
|
||||
const PLUGIN_ID = "tab-set-title-e2e";
|
||||
const WIDE = { width: 1440, height: 900 };
|
||||
|
||||
const CLIENT_SOURCE = `import React from "react";
|
||||
import { Pressable, Text, View } from "react-native";
|
||||
import type {
|
||||
PluginAgentPanelProps,
|
||||
PluginClientContext,
|
||||
PluginFilePanelProps,
|
||||
PluginWorkspacePanelProps,
|
||||
} from "@getpaseo/plugin/client";
|
||||
|
||||
function TitleControls({
|
||||
prefix,
|
||||
nextTitle,
|
||||
tab,
|
||||
}: {
|
||||
prefix: string;
|
||||
nextTitle: string;
|
||||
tab: PluginWorkspacePanelProps["tab"];
|
||||
}) {
|
||||
return (
|
||||
<View style={{ padding: 16, gap: 8 }}>
|
||||
<Text>{prefix} panel</Text>
|
||||
<Pressable
|
||||
accessibilityRole="button"
|
||||
onPress={() => tab.setTitle(" " + nextTitle + " ")}
|
||||
>
|
||||
<Text>Set {prefix} title</Text>
|
||||
</Pressable>
|
||||
<Pressable
|
||||
accessibilityRole="button"
|
||||
onPress={() => tab.setTitle(" ")}
|
||||
>
|
||||
<Text>Whitespace {prefix} title</Text>
|
||||
</Pressable>
|
||||
<Pressable
|
||||
accessibilityRole="button"
|
||||
onPress={() => tab.setTitle(null)}
|
||||
>
|
||||
<Text>Reset {prefix} title</Text>
|
||||
</Pressable>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
function StatusPanel({ tab }: PluginWorkspacePanelProps) {
|
||||
return <TitleControls prefix="status" nextTitle="Status (3)" tab={tab} />;
|
||||
}
|
||||
|
||||
function ExplorerStatusPanel({ tab }: PluginWorkspacePanelProps) {
|
||||
return <TitleControls prefix="explorer" nextTitle="Explorer (7)" tab={tab} />;
|
||||
}
|
||||
|
||||
function InspectorPanel({ tab }: PluginAgentPanelProps) {
|
||||
return <TitleControls prefix="agent" nextTitle="Inspector: live" tab={tab} />;
|
||||
}
|
||||
|
||||
function NotesTxtPanel({ tab }: PluginFilePanelProps) {
|
||||
return <TitleControls prefix="file" nextTitle="Readout" tab={tab} />;
|
||||
}
|
||||
|
||||
export default function contribute(client: PluginClientContext) {
|
||||
client.addWorkspacePanel({
|
||||
id: "status",
|
||||
title: "Status",
|
||||
icon: "PanelsTopLeft",
|
||||
locations: ["workspace", "explorer"],
|
||||
Component: StatusPanel,
|
||||
});
|
||||
client.addWorkspacePanel({
|
||||
id: "explorer-status",
|
||||
title: "Explorer status",
|
||||
icon: "PanelsTopLeft",
|
||||
locations: ["workspace", "explorer"],
|
||||
Component: ExplorerStatusPanel,
|
||||
});
|
||||
client.addAgentPanel({
|
||||
id: "inspector",
|
||||
title: "Inspector",
|
||||
icon: "Scan",
|
||||
locations: ["workspace", "explorer"],
|
||||
Component: InspectorPanel,
|
||||
});
|
||||
client.addFilePanel({
|
||||
id: "txt-viewer",
|
||||
title: "Custom TXT",
|
||||
icon: "FileText",
|
||||
files: { extensions: ["txt"] },
|
||||
Component: NotesTxtPanel,
|
||||
});
|
||||
client.addCommandCenterItem({
|
||||
id: "open-status",
|
||||
title: "Open status panel",
|
||||
icon: "PanelsTopLeft",
|
||||
context: "workspace",
|
||||
onSelect({ workspaceLayout }) {
|
||||
workspaceLayout.open({ panelId: "status" });
|
||||
},
|
||||
});
|
||||
client.addCommandCenterItem({
|
||||
id: "open-explorer-status",
|
||||
title: "Open explorer status panel",
|
||||
icon: "PanelsTopLeft",
|
||||
context: "workspace",
|
||||
onSelect({ workspaceLayout }) {
|
||||
workspaceLayout.open({ panelId: "explorer-status" }, { placement: { type: "explorer" } });
|
||||
},
|
||||
});
|
||||
client.addCommandCenterItem({
|
||||
id: "open-inspector",
|
||||
title: "Open inspector panel",
|
||||
icon: "Scan",
|
||||
context: "agent",
|
||||
onSelect({ workspaceLayout, agent }) {
|
||||
workspaceLayout.open({ panelId: "inspector", params: { agentId: agent.id } });
|
||||
},
|
||||
});
|
||||
return () => {};
|
||||
}
|
||||
`;
|
||||
|
||||
async function runCommand(page: Page, title: string): Promise<void> {
|
||||
const panel = await openCommandCenter(page);
|
||||
await panel.getByTestId("command-center-input").fill(title);
|
||||
await panel.getByRole("button", { name: title, exact: true }).click();
|
||||
await expect(panel).not.toBeVisible();
|
||||
}
|
||||
|
||||
function mainPane(page: Page): Locator {
|
||||
return page.locator('[data-testid^="workspace-pane-"]').filter({ visible: true }).first();
|
||||
}
|
||||
|
||||
function explorer(page: Page): Locator {
|
||||
return page.getByTestId("workspace-explorer-sidebar");
|
||||
}
|
||||
|
||||
function tabChip(scope: Locator, idPart: string): Locator {
|
||||
return scope
|
||||
.locator(
|
||||
`[data-testid^="workspace-tab-"][data-testid*="${idPart}"]:not([data-testid^="workspace-tab-tooltip"]):not([data-testid^="workspace-tab-modified"])`,
|
||||
)
|
||||
.first();
|
||||
}
|
||||
|
||||
async function capture(page: Page, testInfo: TestInfo, name: string): Promise<void> {
|
||||
const screenshot = testInfo.outputPath(`${name}.png`);
|
||||
await page.screenshot({ path: screenshot });
|
||||
await testInfo.attach(name, { path: screenshot, contentType: "image/png" });
|
||||
}
|
||||
|
||||
test("PluginTab.setTitle updates and resets tab labels in main pane, Explorer, agent, and file panels", async ({
|
||||
page,
|
||||
}, testInfo) => {
|
||||
test.setTimeout(180_000);
|
||||
const directory = await mkdtemp(path.join(tmpdir(), "paseo-plugin-tab-set-title-"));
|
||||
const workspace = await seedMockAgentWorkspace({
|
||||
repoPrefix: "plugin-tab-set-title-",
|
||||
title: "Tab Title Agent",
|
||||
repo: {
|
||||
files: [{ path: "notes.txt", content: "Sample notes\n" }],
|
||||
},
|
||||
});
|
||||
const client = await connectNewWorkspaceDaemonClient({ ownProjects: false });
|
||||
const previousConfig = await client.getDaemonConfig();
|
||||
|
||||
await writeFile(
|
||||
path.join(directory, "paseo-plugin.json"),
|
||||
JSON.stringify({ id: PLUGIN_ID, requirements: pluginRequirements }),
|
||||
);
|
||||
await writeFile(path.join(directory, "index.client.tsx"), CLIENT_SOURCE);
|
||||
|
||||
try {
|
||||
await client.patchDaemonConfig({ pluginsEnabled: true });
|
||||
await client.installDirectoryPlugin(directory);
|
||||
await page.setViewportSize(WIDE);
|
||||
await openAgentRoute(page, {
|
||||
workspaceId: workspace.workspaceId,
|
||||
agentId: workspace.agentId,
|
||||
});
|
||||
await approveClientPluginsInUi(page, [PLUGIN_ID]);
|
||||
|
||||
await test.step("main pane workspace panel sets, trims, clears, and resets title + tooltip", async () => {
|
||||
await runCommand(page, "Open status panel");
|
||||
const tab = tabChip(mainPane(page), "_status");
|
||||
await expect(tab).toContainText("Status");
|
||||
await expect(tab).toHaveAttribute("aria-label", "Status");
|
||||
|
||||
await page.getByRole("button", { name: "Set status title", exact: true }).click();
|
||||
await expect(tab).toContainText("Status (3)");
|
||||
await expect(tab).toHaveAttribute("aria-label", "Status (3)");
|
||||
await expect.poll(() => page.title()).toBe("Status (3)");
|
||||
await tab.hover();
|
||||
await expect(page.getByText("Status (3)").last()).toBeVisible();
|
||||
await capture(page, testInfo, "main-pane-title-override");
|
||||
|
||||
await page.getByRole("button", { name: "Whitespace status title", exact: true }).click();
|
||||
await expect(tab).toContainText("Status");
|
||||
await expect(tab).toHaveAttribute("aria-label", "Status");
|
||||
|
||||
await page.getByRole("button", { name: "Set status title", exact: true }).click();
|
||||
await expect(tab).toContainText("Status (3)");
|
||||
|
||||
await page.getByRole("button", { name: "Reset status title", exact: true }).click();
|
||||
await expect(tab).toContainText("Status");
|
||||
await expect.poll(() => page.title()).toBe("Status");
|
||||
});
|
||||
|
||||
await test.step("Explorer workspace panel sets and resets title", async () => {
|
||||
await runCommand(page, "Open explorer status panel");
|
||||
const explorerTab = tabChip(explorer(page), "explorer-status");
|
||||
await expect(explorerTab).toContainText("Explorer status");
|
||||
await expect(explorerTab).toHaveAttribute("aria-label", "Explorer status");
|
||||
|
||||
await page.getByRole("button", { name: "Set explorer title", exact: true }).click();
|
||||
await expect(explorerTab).toContainText("Explorer (7)");
|
||||
await expect(explorerTab).toHaveAttribute("aria-label", "Explorer (7)");
|
||||
await capture(page, testInfo, "explorer-title-override");
|
||||
|
||||
await page.getByRole("button", { name: "Reset explorer title", exact: true }).click();
|
||||
await expect(explorerTab).toContainText("Explorer status");
|
||||
await expect(explorerTab).toHaveAttribute("aria-label", "Explorer status");
|
||||
});
|
||||
|
||||
await test.step("agent panel sets and resets title", async () => {
|
||||
await mainPane(page).getByTestId(`workspace-tab-agent_${workspace.agentId}`).click();
|
||||
await runCommand(page, "Open inspector panel");
|
||||
const agentTab = tabChip(mainPane(page), "inspector");
|
||||
await expect(agentTab).toContainText("Inspector");
|
||||
|
||||
await page.getByRole("button", { name: "Set agent title", exact: true }).click();
|
||||
await expect(agentTab).toContainText("Inspector: live");
|
||||
|
||||
await page.getByRole("button", { name: "Reset agent title", exact: true }).click();
|
||||
await expect(agentTab).toContainText("Inspector");
|
||||
});
|
||||
|
||||
await test.step("file panel sets and resets title", async () => {
|
||||
await openFileExplorer(page);
|
||||
await openFileFromExplorer(page, "notes.txt");
|
||||
await expect(page.getByText("Open .txt files with", { exact: true })).toBeVisible();
|
||||
await page.keyboard.press("Escape");
|
||||
await expect(page.getByText("Open .txt files with", { exact: true })).toBeHidden();
|
||||
|
||||
const fileTab = mainPane(page).getByTestId("workspace-tab-file_notes.txt");
|
||||
await expect(fileTab).toContainText("notes.txt");
|
||||
|
||||
await page.getByRole("button", { name: "Set file title", exact: true }).click();
|
||||
await expect(fileTab).toContainText("Readout");
|
||||
await expect(fileTab).toHaveAttribute("aria-label", "Readout");
|
||||
|
||||
await page.getByRole("button", { name: "Reset file title", exact: true }).click();
|
||||
await expect(fileTab).toContainText("notes.txt");
|
||||
await expect(fileTab).toHaveAttribute("aria-label", "notes.txt");
|
||||
});
|
||||
|
||||
await test.step("removing the plugin clears active title override to Plugin unavailable", async () => {
|
||||
await tabChip(mainPane(page), "_status").click();
|
||||
await page.getByRole("button", { name: "Set status title", exact: true }).click();
|
||||
const tab = tabChip(mainPane(page), "_status");
|
||||
await expect(tab).toContainText("Status (3)");
|
||||
|
||||
await client.removePlugin(PLUGIN_ID);
|
||||
await expect(tab).toContainText("Plugin unavailable", { timeout: 30_000 });
|
||||
await expect(tab).toHaveAttribute("aria-label", "This plugin panel is unavailable");
|
||||
});
|
||||
} finally {
|
||||
await client.removePlugin(PLUGIN_ID).catch(() => undefined);
|
||||
await client
|
||||
.patchDaemonConfig({ pluginsEnabled: previousConfig.config.pluginsEnabled ?? false })
|
||||
.catch(() => undefined);
|
||||
await client.close().catch(() => undefined);
|
||||
await workspace.cleanup().catch(() => undefined);
|
||||
await rm(directory, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
@@ -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();
|
||||
}
|
||||
});
|
||||
|
||||
@@ -42,17 +42,40 @@ import { useAgent, useWorkspace, openExternalUrl } from "@getpaseo/plugin/client
|
||||
import { ExternalLink } from "@getpaseo/plugin/client/ui";
|
||||
import { recordComposerOpen } from "./shared/rpc";
|
||||
|
||||
function WorkspacePanel({ workspaceId, host, layout }) {
|
||||
function WorkspacePanel({ workspaceId, host, layout, openScreen }) {
|
||||
const workspace = useWorkspace(workspaceId, (value) => ({ id: value.id }));
|
||||
const renderCount = useRef(0);
|
||||
renderCount.current += 1;
|
||||
return <View><Text>Workspace bridge {workspace?.id}</Text><Text>Workspace renders {renderCount.current}</Text><Text>Host {host.id}</Text><Text>Layout {layout.compact ? "compact" : "wide"}</Text></View>;
|
||||
return <View>
|
||||
<Text>Workspace bridge {workspace?.id}</Text>
|
||||
<Text>Workspace renders {renderCount.current}</Text>
|
||||
<Text>Host {host.id}</Text>
|
||||
<Text>Layout {layout.compact ? "compact" : "wide"}</Text>
|
||||
<Pressable accessibilityRole="button" onPress={() => openScreen({ screenId: "details", params: { source: "workspace-panel", item: workspaceId } })}><Text>Open screen from workspace panel</Text></Pressable>
|
||||
</View>;
|
||||
}
|
||||
|
||||
function AgentPanel({ workspaceId, agentId, host, layout }) {
|
||||
function AgentPanel({ workspaceId, agentId, host, layout, openScreen }) {
|
||||
const workspace = useWorkspace(workspaceId, (value) => ({ id: value.id }));
|
||||
const agent = useAgent(agentId, (value) => ({ id: value.id }));
|
||||
return <View><Text>Agent bridge {agent?.id}</Text><Text>Workspace {workspace?.id}</Text><Text>Host {host.id}</Text><Text>Layout {layout.compact ? "compact" : "wide"}</Text></View>;
|
||||
return <View>
|
||||
<Text>Agent bridge {agent?.id}</Text>
|
||||
<Text>Workspace {workspace?.id}</Text>
|
||||
<Text>Host {host.id}</Text>
|
||||
<Text>Layout {layout.compact ? "compact" : "wide"}</Text>
|
||||
<Pressable accessibilityRole="button" onPress={() => openScreen({ screenId: "details", params: { source: "agent-panel", item: agentId } })}><Text>Open screen from agent panel</Text></Pressable>
|
||||
</View>;
|
||||
}
|
||||
|
||||
function DetailsScreen({ params, openScreen }) {
|
||||
return <View>
|
||||
<Text>{"Details screen: " + params.source + " / " + params.item}</Text>
|
||||
<Pressable accessibilityRole="button" onPress={() => openScreen({ screenId: "chained", params: { from: params.source ?? "" } })}><Text>Open chained screen</Text></Pressable>
|
||||
</View>;
|
||||
}
|
||||
|
||||
function ChainedScreen({ params }) {
|
||||
return <View><Text>{"Chained screen from " + params.from}</Text></View>;
|
||||
}
|
||||
|
||||
function DirectCollisionSurface({ navigation }) {
|
||||
@@ -127,6 +150,8 @@ function contributeClient(client) {
|
||||
}
|
||||
|
||||
export default function contribute(client) {
|
||||
client.addScreen({ id: "details", title: (params) => "Details: " + (params.source ?? ""), Component: DetailsScreen });
|
||||
client.addScreen({ id: "chained", title: "Chained", Component: ChainedScreen });
|
||||
client.addSurface("collision", DirectCollisionSurface);
|
||||
client.addSurface("sidebar-destination", SidebarCollisionSurface);
|
||||
client.addSidebarItem({ id: "collision", title: "Collision sidebar", icon: "Blocks", surface: "sidebar-destination" });
|
||||
@@ -252,6 +277,34 @@ async function openCompactSidebar(page: Page): Promise<void> {
|
||||
await expect(page.getByTestId("sidebar-search")).toBeVisible();
|
||||
}
|
||||
|
||||
async function openPluginScreenFromButton(
|
||||
page: Page,
|
||||
input: {
|
||||
buttonName: string;
|
||||
screenId: string;
|
||||
params: Record<string, string>;
|
||||
expectedText: string;
|
||||
},
|
||||
): Promise<void> {
|
||||
await page.getByRole("button", { name: input.buttonName, exact: true }).click();
|
||||
const query = Object.entries(input.params)
|
||||
.map(([key, value]) => `${encodeURIComponent(`param.${key}`)}=${encodeURIComponent(value)}`)
|
||||
.join("&");
|
||||
await expect(page).toHaveURL(
|
||||
new RegExp(`/plugin/${PLUGIN_ID}/surface/${input.screenId}\\?${query.replaceAll(".", "\\.")}$`),
|
||||
);
|
||||
await expect(page.getByText(input.expectedText, { exact: true })).toBeVisible();
|
||||
}
|
||||
|
||||
async function closeTopPluginScreen(
|
||||
page: Page,
|
||||
options: { compact?: boolean; expectedText: string },
|
||||
): Promise<void> {
|
||||
const testId = options.compact ? "header-back-button" : "plugin-surface-close";
|
||||
await page.getByTestId(testId).filter({ visible: true }).last().click();
|
||||
await expect(page.getByText(options.expectedText, { exact: true })).toBeVisible();
|
||||
}
|
||||
|
||||
async function capture(page: Page, testInfo: TestInfo, name: string): Promise<void> {
|
||||
const screenshot = testInfo.outputPath(`${name}.png`);
|
||||
await page.screenshot({ path: screenshot });
|
||||
@@ -338,6 +391,24 @@ test.describe("plugin workspace panels and Command Center", () => {
|
||||
await expect(page.getByText(`Host ${getServerId()}`, { exact: true })).toBeVisible();
|
||||
await expect(page.getByText("Layout wide", { exact: true })).toBeVisible();
|
||||
await capture(page, testInfo, "plugin-workspace-panel-wide");
|
||||
await openPluginScreenFromButton(page, {
|
||||
buttonName: "Open screen from workspace panel",
|
||||
screenId: "details",
|
||||
params: { source: "workspace-panel", item: primary.workspaceId },
|
||||
expectedText: `Details screen: workspace-panel / ${primary.workspaceId}`,
|
||||
});
|
||||
await openPluginScreenFromButton(page, {
|
||||
buttonName: "Open chained screen",
|
||||
screenId: "chained",
|
||||
params: { from: "workspace-panel" },
|
||||
expectedText: "Chained screen from workspace-panel",
|
||||
});
|
||||
await closeTopPluginScreen(page, {
|
||||
expectedText: `Details screen: workspace-panel / ${primary.workspaceId}`,
|
||||
});
|
||||
await closeTopPluginScreen(page, {
|
||||
expectedText: `Workspace bridge ${primary.workspaceId}`,
|
||||
});
|
||||
});
|
||||
|
||||
await test.step("plugin links open browser tabs and in-app browsing is unavailable", async () => {
|
||||
@@ -475,6 +546,16 @@ test.describe("plugin workspace panels and Command Center", () => {
|
||||
).toBeVisible();
|
||||
await expect(page.getByText(`Host ${getServerId()}`, { exact: true })).toBeVisible();
|
||||
await expect(page.getByText("Layout compact", { exact: true })).toBeVisible();
|
||||
await openPluginScreenFromButton(page, {
|
||||
buttonName: "Open screen from agent panel",
|
||||
screenId: "details",
|
||||
params: { source: "agent-panel", item: agent.id },
|
||||
expectedText: `Details screen: agent-panel / ${agent.id}`,
|
||||
});
|
||||
await closeTopPluginScreen(page, {
|
||||
compact: true,
|
||||
expectedText: `Agent bridge ${agent.id}`,
|
||||
});
|
||||
});
|
||||
|
||||
await test.step("removing the active plugin renders the panel unavailable", async () => {
|
||||
|
||||
@@ -55,6 +55,7 @@ interface HeldServerMessage {
|
||||
interface PendingServerMessageHold {
|
||||
matches: (message: ClientRequest | null) => boolean;
|
||||
blockAgentStreamFollowers?: boolean;
|
||||
keepHolding?: boolean;
|
||||
}
|
||||
|
||||
function readSessionMessage(message: string | Buffer): ClientRequest | null {
|
||||
@@ -412,7 +413,7 @@ export async function installDaemonWebSocketGate(page: Page, options: { port?: n
|
||||
);
|
||||
if (!matchedHold) return suppressed;
|
||||
const [key, hold] = matchedHold;
|
||||
pendingServerMessageHolds.delete(key);
|
||||
if (!hold.keepHolding) pendingServerMessageHolds.delete(key);
|
||||
heldServerMessages.push({
|
||||
browser: input.browser,
|
||||
message: input.message,
|
||||
@@ -550,6 +551,23 @@ export async function installDaemonWebSocketGate(page: Page, options: { port?: n
|
||||
});
|
||||
});
|
||||
|
||||
const sendHeldServerMessage = (heldServerMessage: HeldServerMessage): void => {
|
||||
heldServerMessage.browser.send(heldServerMessage.message);
|
||||
for (const follower of heldServerMessage.agentStreamFollowers) {
|
||||
heldServerMessage.browser.send(follower);
|
||||
}
|
||||
};
|
||||
|
||||
const releaseFirstHeldMessage = (
|
||||
predicate: (message: HeldServerMessage) => boolean,
|
||||
errorMessage: string,
|
||||
): void => {
|
||||
const index = heldServerMessages.findIndex(predicate);
|
||||
const [heldServerMessage] = index >= 0 ? heldServerMessages.splice(index, 1) : [];
|
||||
if (!heldServerMessage) throw new Error(errorMessage);
|
||||
sendHeldServerMessage(heldServerMessage);
|
||||
};
|
||||
|
||||
return {
|
||||
waitForFileSubscription(path: string): Promise<void> {
|
||||
if (subscribedFilePaths.has(path)) return Promise.resolve();
|
||||
@@ -661,6 +679,13 @@ export async function installDaemonWebSocketGate(page: Page, options: { port?: n
|
||||
matches: (message) => matchesAgentUpdate(message, heldAgentUpdate),
|
||||
});
|
||||
},
|
||||
holdAgentUpdates(agentId: string, status: string): void {
|
||||
const heldAgentUpdate = { agentId, status };
|
||||
pendingServerMessageHolds.set(agentUpdateKey(agentId, status), {
|
||||
matches: (message) => matchesAgentUpdate(message, heldAgentUpdate),
|
||||
keepHolding: true,
|
||||
});
|
||||
},
|
||||
holdNextAgentStreamEvent(type: string): void {
|
||||
pendingServerMessageHolds.set(agentStreamEventKey(type), {
|
||||
matches: (message) => readAgentStreamEventType(message) === type,
|
||||
@@ -690,13 +715,10 @@ export async function installDaemonWebSocketGate(page: Page, options: { port?: n
|
||||
},
|
||||
releaseHeldServerMessage(type?: string): void {
|
||||
const key = type ? serverMessageKey(type) : null;
|
||||
const index = heldServerMessages.findIndex((message) => key === null || message.key === key);
|
||||
const [heldServerMessage] = index >= 0 ? heldServerMessages.splice(index, 1) : [];
|
||||
if (!heldServerMessage) throw new Error("No held server message to release");
|
||||
heldServerMessage.browser.send(heldServerMessage.message);
|
||||
for (const follower of heldServerMessage.agentStreamFollowers) {
|
||||
heldServerMessage.browser.send(follower);
|
||||
}
|
||||
releaseFirstHeldMessage(
|
||||
(message) => key === null || message.key === key,
|
||||
"No held server message to release",
|
||||
);
|
||||
},
|
||||
async waitForHeldAgentUpdate(agentId: string, status: string): Promise<void> {
|
||||
const key = agentUpdateKey(agentId, status);
|
||||
@@ -706,12 +728,20 @@ export async function installDaemonWebSocketGate(page: Page, options: { port?: n
|
||||
},
|
||||
releaseHeldAgentUpdate(agentId: string, status: string): void {
|
||||
const key = agentUpdateKey(agentId, status);
|
||||
const index = heldServerMessages.findIndex((message) => message.key === key);
|
||||
const [heldServerMessage] = index >= 0 ? heldServerMessages.splice(index, 1) : [];
|
||||
if (!heldServerMessage) throw new Error("No held agent update to release");
|
||||
heldServerMessage.browser.send(heldServerMessage.message);
|
||||
for (const follower of heldServerMessage.agentStreamFollowers) {
|
||||
heldServerMessage.browser.send(follower);
|
||||
releaseFirstHeldMessage((message) => message.key === key, "No held agent update to release");
|
||||
},
|
||||
releaseHeldAgentUpdates(agentId: string, status: string): void {
|
||||
const key = agentUpdateKey(agentId, status);
|
||||
pendingServerMessageHolds.delete(key);
|
||||
const matching: HeldServerMessage[] = [];
|
||||
for (let index = heldServerMessages.length - 1; index >= 0; index -= 1) {
|
||||
if (heldServerMessages[index]?.key === key) {
|
||||
matching.unshift(...heldServerMessages.splice(index, 1));
|
||||
}
|
||||
}
|
||||
if (matching.length === 0) throw new Error("No held agent update to release");
|
||||
for (const heldServerMessage of matching) {
|
||||
sendHeldServerMessage(heldServerMessage);
|
||||
}
|
||||
},
|
||||
async waitForHeldAgentStreamEvent(type: string): Promise<void> {
|
||||
@@ -722,13 +752,10 @@ export async function installDaemonWebSocketGate(page: Page, options: { port?: n
|
||||
},
|
||||
releaseHeldAgentStreamEvent(type: string): void {
|
||||
const key = agentStreamEventKey(type);
|
||||
const index = heldServerMessages.findIndex((message) => message.key === key);
|
||||
const [heldServerMessage] = index >= 0 ? heldServerMessages.splice(index, 1) : [];
|
||||
if (!heldServerMessage) throw new Error("No held agent stream event to release");
|
||||
heldServerMessage.browser.send(heldServerMessage.message);
|
||||
for (const follower of heldServerMessage.agentStreamFollowers) {
|
||||
heldServerMessage.browser.send(follower);
|
||||
}
|
||||
releaseFirstHeldMessage(
|
||||
(message) => message.key === key,
|
||||
"No held agent stream event to release",
|
||||
);
|
||||
},
|
||||
async waitForHeldAgentStreamItem(type: string): Promise<void> {
|
||||
const key = agentStreamItemKey(type);
|
||||
@@ -738,13 +765,10 @@ export async function installDaemonWebSocketGate(page: Page, options: { port?: n
|
||||
},
|
||||
releaseHeldAgentStreamItem(type: string): void {
|
||||
const key = agentStreamItemKey(type);
|
||||
const index = heldServerMessages.findIndex((message) => message.key === key);
|
||||
const [heldServerMessage] = index >= 0 ? heldServerMessages.splice(index, 1) : [];
|
||||
if (!heldServerMessage) throw new Error("No held agent stream item to release");
|
||||
heldServerMessage.browser.send(heldServerMessage.message);
|
||||
for (const follower of heldServerMessage.agentStreamFollowers) {
|
||||
heldServerMessage.browser.send(follower);
|
||||
}
|
||||
releaseFirstHeldMessage(
|
||||
(message) => message.key === key,
|
||||
"No held agent stream item to release",
|
||||
);
|
||||
},
|
||||
requestTimelineTail(agentId: string): void {
|
||||
if (!latestServer) throw new Error("No daemon WebSocket is connected");
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
import { useCallback, type ReactNode, type RefObject } from "react";
|
||||
import type { View } from "react-native";
|
||||
import { MenuRoot, useMenuContext } from "@/components/ui/menu";
|
||||
import { PluginPopoverSurface } from "@/plugins/popover";
|
||||
import type { ReactNode } from "react";
|
||||
import { MenuRoot } from "@/components/ui/menu";
|
||||
import { PluginPopoverSurface, usePluginPopoverAnchor } from "@/plugins/popover";
|
||||
import type { SidebarSection } from "@/sidebar-nav/model";
|
||||
|
||||
/**
|
||||
@@ -26,41 +25,7 @@ export function SidebarPopoverRoot({
|
||||
);
|
||||
}
|
||||
|
||||
function assignRef(ref: RefObject<View | null>, node: View | null) {
|
||||
Object.assign(ref, { current: node });
|
||||
}
|
||||
|
||||
/**
|
||||
* Where the popover anchors. `anchorTo` moves it to an element, such as the row just pressed;
|
||||
* `offerAnchor` sets it only when nothing is anchored; `releaseAnchor` drops an element that is
|
||||
* going away; `anchorToFallback` covers an item that anchored nothing.
|
||||
*/
|
||||
export function useSidebarPopoverAnchor(name: string): {
|
||||
anchorTo: (node: View | null) => void;
|
||||
offerAnchor: (node: View | null) => void;
|
||||
releaseAnchor: (node: View | null) => void;
|
||||
anchorToFallback: (fallback: RefObject<View | null>) => void;
|
||||
} {
|
||||
const { triggerRef } = useMenuContext(name);
|
||||
const anchorTo = useCallback((node: View | null) => assignRef(triggerRef, node), [triggerRef]);
|
||||
const offerAnchor = useCallback(
|
||||
(node: View | null) => {
|
||||
if (!triggerRef.current) assignRef(triggerRef, node);
|
||||
},
|
||||
[triggerRef],
|
||||
);
|
||||
const releaseAnchor = useCallback(
|
||||
(node: View | null) => {
|
||||
if (triggerRef.current === node) assignRef(triggerRef, null);
|
||||
},
|
||||
[triggerRef],
|
||||
);
|
||||
const anchorToFallback = useCallback(
|
||||
(fallback: RefObject<View | null>) => offerAnchor(fallback.current),
|
||||
[offerAnchor],
|
||||
);
|
||||
return { anchorTo, offerAnchor, releaseAnchor, anchorToFallback };
|
||||
}
|
||||
export const useSidebarPopoverAnchor = usePluginPopoverAnchor;
|
||||
|
||||
const PLACEMENT = {
|
||||
header: { side: "right", align: "start" },
|
||||
|
||||
@@ -1,4 +1,11 @@
|
||||
import { useCallback, useMemo, useState, type ReactElement, type ReactNode } from "react";
|
||||
import {
|
||||
useCallback,
|
||||
useMemo,
|
||||
useState,
|
||||
type ReactElement,
|
||||
type ReactNode,
|
||||
type RefObject,
|
||||
} from "react";
|
||||
import { Pressable, Text, View } from "react-native";
|
||||
import { GestureDetector } from "react-native-gesture-handler";
|
||||
import Animated from "react-native-reanimated";
|
||||
@@ -42,12 +49,18 @@ import { COMPOSER_PILL_CLEARANCE, composerPillStyles } from "./pill-styles";
|
||||
* or without pills: that keeps the final footer clear, and pills that come and go every turn do not
|
||||
* move the transcript.
|
||||
*/
|
||||
export function ComposerTrackBar({ children }: { children: ReactNode }): ReactElement {
|
||||
export function ComposerTrackBar({
|
||||
children,
|
||||
trackViewportRef,
|
||||
}: {
|
||||
children: ReactNode;
|
||||
trackViewportRef?: RefObject<View | null>;
|
||||
}): ReactElement {
|
||||
const scrollGesture = usePanelAwareHorizontalScrollGesture();
|
||||
const scrollBoundary = useHorizontalScrollBoundary();
|
||||
return (
|
||||
<View style={styles.bar} dataSet={CHAT_COLUMN_RAIL_DATASET} pointerEvents="box-none">
|
||||
<View style={styles.trackViewport} pointerEvents="box-none">
|
||||
<View ref={trackViewportRef} style={styles.trackViewport} pointerEvents="box-none">
|
||||
<GestureDetector gesture={scrollGesture}>
|
||||
<Animated.ScrollView
|
||||
testID="composer-track-scroll"
|
||||
|
||||
@@ -1,6 +1,4 @@
|
||||
import { usePaneContext } from "@/panels/pane-context";
|
||||
import { useCallback, useEffect, useMemo, useState } from "react";
|
||||
import type { PluginFile, PluginTab } from "@getpaseo/plugin/client";
|
||||
import { useCallback, useMemo } from "react";
|
||||
import { Text, View } from "react-native";
|
||||
import { Download } from "lucide-react-native";
|
||||
import { StyleSheet } from "react-native-unistyles";
|
||||
@@ -9,11 +7,11 @@ import { Button } from "@/components/ui/button";
|
||||
import { useRetainedPanelActive } from "@/components/retained-panel";
|
||||
import { useFileHandle, useFileHandleSnapshot } from "@/file-panels/file";
|
||||
import { FilePanelLoading } from "@/file-panels/loading";
|
||||
import { FilePanelPicker, FilePanelView, useFilePanelChoice, type FilePanel } from "@/file-panels";
|
||||
import { FilePanelPicker, FilePanelView, useFilePanelChoice } from "@/file-panels";
|
||||
import { resolveFilePreviewReadTarget } from "@/file-explorer/preview-target";
|
||||
import { useFileDownload } from "@/hooks/use-file-download";
|
||||
import { useAppActivelyVisible } from "@/hooks/use-app-visible";
|
||||
import { usePublishPanelInstanceAttributes } from "@/panels/panel-instance-attributes";
|
||||
import { getComponentMountKey } from "@/panels/panel-instance-attributes";
|
||||
import { useHostRuntimeConnectionStatus } from "@/runtime/host-runtime";
|
||||
import { buildAbsoluteExplorerPath } from "@/utils/explorer-paths";
|
||||
import { formatFileSize } from "@/utils/format-file-size";
|
||||
@@ -79,8 +77,6 @@ export function FilePane({
|
||||
presentable: isActive,
|
||||
lineNavigation: location.lineStart ? navigationRevision : null,
|
||||
});
|
||||
const [modified, setModified] = useState(false);
|
||||
usePublishPanelInstanceAttributes({ modified, suspendPendingSave: handle?.holdWrites });
|
||||
const panelLocation = useMemo(
|
||||
() => ({
|
||||
lineStart: location.lineStart,
|
||||
@@ -121,16 +117,19 @@ export function FilePane({
|
||||
</>
|
||||
);
|
||||
} else {
|
||||
const panelMountKey = panel.builtin
|
||||
? `${panel.id}:${targetKey}`
|
||||
: `${panel.id}:${targetKey}:${getComponentMountKey(panel.contribution.Component)}`;
|
||||
return (
|
||||
<View style={styles.container} testID="workspace-file-pane">
|
||||
<FilePanelPicker choice={choice} />
|
||||
<MountedFilePanel
|
||||
key={`${panel.id}:${targetKey}`}
|
||||
<FilePanelView
|
||||
key={panelMountKey}
|
||||
panel={panel}
|
||||
file={handle.file}
|
||||
params={panelLocation}
|
||||
revision={navigationRevision}
|
||||
onModifiedChange={setModified}
|
||||
suspendPendingSave={handle.holdWrites}
|
||||
/>
|
||||
</View>
|
||||
);
|
||||
@@ -142,34 +141,6 @@ export function FilePane({
|
||||
);
|
||||
}
|
||||
|
||||
/** One panel mount. Its tab reports unsaved changes until the panel unmounts. */
|
||||
function MountedFilePanel({
|
||||
panel,
|
||||
file,
|
||||
params,
|
||||
revision,
|
||||
onModifiedChange,
|
||||
}: {
|
||||
panel: FilePanel;
|
||||
file: PluginFile;
|
||||
params: { path: string; lineStart?: number; lineEnd?: number };
|
||||
revision: number;
|
||||
onModifiedChange: (modified: boolean) => void;
|
||||
}) {
|
||||
const { tabId, state, setCurrentTabState } = usePaneContext();
|
||||
const tab = useMemo<PluginTab>(
|
||||
() => ({
|
||||
id: tabId,
|
||||
setModified: onModifiedChange,
|
||||
state,
|
||||
setState: setCurrentTabState,
|
||||
}),
|
||||
[tabId, onModifiedChange, state, setCurrentTabState],
|
||||
);
|
||||
useEffect(() => () => onModifiedChange(false), [onModifiedChange]);
|
||||
return <FilePanelView panel={panel} file={file} tab={tab} params={params} revision={revision} />;
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create((theme) => ({
|
||||
container: {
|
||||
flex: 1,
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { useWorkspace, useFileUrl, type PluginFilePanelProps } from "@getpaseo/plugin/client";
|
||||
import { useWorkspace, useFileUrl } from "@getpaseo/plugin/client";
|
||||
import type { BuiltinFilePanelProps } from "./panels";
|
||||
import { useCallback, useState } from "react";
|
||||
import { ScrollView, Text, View } from "react-native";
|
||||
import { StyleSheet } from "react-native-unistyles";
|
||||
@@ -11,17 +12,17 @@ import { TextFilePanel, type TextFilePreviewProps } from "./source/panel";
|
||||
import type { RenderingFilePanel, SourceFilePanel } from "./catalog";
|
||||
|
||||
/** Source: the text file panel with no Preview, for text files no other built-in panel claims. */
|
||||
function SourcePanel(props: PluginFilePanelProps) {
|
||||
function SourcePanel(props: BuiltinFilePanelProps) {
|
||||
return <TextFilePanel {...props} />;
|
||||
}
|
||||
|
||||
/** Markdown: the text file panel with the rendered document as its Preview. */
|
||||
function MarkdownPanel(props: PluginFilePanelProps) {
|
||||
function MarkdownPanel(props: BuiltinFilePanelProps) {
|
||||
return <TextFilePanel {...props} preview={MarkdownPreview} />;
|
||||
}
|
||||
|
||||
/** HTML: the text file panel with the sandboxed page as its Preview. */
|
||||
function HtmlPanel(props: PluginFilePanelProps) {
|
||||
function HtmlPanel(props: BuiltinFilePanelProps) {
|
||||
return <TextFilePanel {...props} preview={HtmlPreview} />;
|
||||
}
|
||||
|
||||
@@ -58,7 +59,7 @@ function HtmlPreview({ text }: TextFilePreviewProps) {
|
||||
);
|
||||
}
|
||||
|
||||
function ImagePanel({ file }: PluginFilePanelProps) {
|
||||
function ImagePanel({ file }: BuiltinFilePanelProps) {
|
||||
const url = useFileUrl(file);
|
||||
if (url.status === "loading") return <FilePanelLoading />;
|
||||
if (url.status === "error") return <FilePanelError message={url.error.message} />;
|
||||
@@ -83,7 +84,7 @@ const components = {
|
||||
export function BuiltinFilePanelView({
|
||||
panel,
|
||||
...props
|
||||
}: PluginFilePanelProps & { panel: RenderingFilePanel | SourceFilePanel }) {
|
||||
}: BuiltinFilePanelProps & { panel: RenderingFilePanel | SourceFilePanel }) {
|
||||
const Component = components[panel.id];
|
||||
return <Component {...props} />;
|
||||
}
|
||||
|
||||
@@ -1,8 +1,12 @@
|
||||
import { useMemo } from "react";
|
||||
import type { PluginFilePanelProps } from "@getpaseo/plugin/client";
|
||||
import { useInstalledPlugins } from "@/plugins/registry";
|
||||
import type { PluginFilePanelContribution, InstalledPlugin } from "@/plugins/types";
|
||||
import { filePanelCatalog, type RenderingFilePanel, type SourceFilePanel } from "./catalog";
|
||||
|
||||
/** Props shared by built-in file panels; excludes plugin-owned capabilities such as `openScreen`. */
|
||||
export type BuiltinFilePanelProps = Omit<PluginFilePanelProps, "openScreen">;
|
||||
|
||||
export interface PluginFilePanel {
|
||||
id: string;
|
||||
builtin: false;
|
||||
|
||||
@@ -1,18 +1,45 @@
|
||||
import type { PluginFilePanelProps } from "@getpaseo/plugin/client";
|
||||
import { usePanelTab } from "@/panels/panel-instance-attributes";
|
||||
import { PluginInstallationProvider } from "@/plugins/installation-provider";
|
||||
import { usePluginOpenScreen } from "@/plugins/navigation";
|
||||
import { SurfaceErrorBoundary } from "@/plugins/surface-error-boundary";
|
||||
import type { PluginFilePanel } from "./panels";
|
||||
import type { BuiltinFilePanelProps, PluginFilePanel } from "./panels";
|
||||
|
||||
type PluginFilePanelHostProps = Omit<BuiltinFilePanelProps, "tab"> & {
|
||||
panel: PluginFilePanel;
|
||||
suspendPendingSave?: () => () => void;
|
||||
};
|
||||
|
||||
function MountedPluginFilePanel({
|
||||
panel,
|
||||
suspendPendingSave,
|
||||
...props
|
||||
}: Omit<PluginFilePanelProps, "tab"> & {
|
||||
panel: PluginFilePanel;
|
||||
suspendPendingSave?: () => () => void;
|
||||
}) {
|
||||
const tab = usePanelTab({ suspendPendingSave });
|
||||
const Component = panel.contribution.Component;
|
||||
return <Component {...props} tab={tab} />;
|
||||
}
|
||||
|
||||
export function PluginFilePanelHost({
|
||||
panel,
|
||||
suspendPendingSave,
|
||||
...props
|
||||
}: PluginFilePanelProps & { panel: PluginFilePanel }) {
|
||||
}: PluginFilePanelHostProps) {
|
||||
const { plugin, contribution } = panel;
|
||||
const openScreen = usePluginOpenScreen(plugin);
|
||||
const Component = contribution.Component;
|
||||
return (
|
||||
<SurfaceErrorBoundary installation={plugin} Surface={Component} key={panel.id}>
|
||||
<PluginInstallationProvider plugin={plugin}>
|
||||
<Component {...props} />
|
||||
<MountedPluginFilePanel
|
||||
{...props}
|
||||
openScreen={openScreen}
|
||||
panel={panel}
|
||||
suspendPendingSave={suspendPendingSave}
|
||||
/>
|
||||
</PluginInstallationProvider>
|
||||
</SurfaceErrorBoundary>
|
||||
);
|
||||
|
||||
@@ -8,11 +8,8 @@ import {
|
||||
type ComponentType,
|
||||
type ReactNode,
|
||||
} from "react";
|
||||
import {
|
||||
useFileText,
|
||||
type PluginFilePanelProps,
|
||||
type PluginFilePanelParams,
|
||||
} from "@getpaseo/plugin/client";
|
||||
import { useFileText, type PluginFilePanelParams } from "@getpaseo/plugin/client";
|
||||
import type { BuiltinFilePanelProps } from "../panels";
|
||||
import { Text, View } from "react-native";
|
||||
import { StyleSheet, withUnistyles } from "react-native-unistyles";
|
||||
import { useTranslation } from "react-i18next";
|
||||
@@ -56,12 +53,12 @@ const MAX_EDITABLE_BYTES = 1024 * 1024;
|
||||
/** A rendered view of the file's text: the panel's Preview, shown instead of its source. */
|
||||
export interface TextFilePreviewProps {
|
||||
text: string;
|
||||
params: PluginFilePanelProps["params"];
|
||||
params: BuiltinFilePanelProps["params"];
|
||||
workspaceId: string;
|
||||
host: PluginFilePanelProps["host"];
|
||||
host: BuiltinFilePanelProps["host"];
|
||||
}
|
||||
|
||||
type TextFilePanelProps = PluginFilePanelProps & {
|
||||
type TextFilePanelProps = BuiltinFilePanelProps & {
|
||||
/** The panel's Preview; with one, the toolbar switches between Preview and Source. */
|
||||
preview?: ComponentType<TextFilePreviewProps>;
|
||||
};
|
||||
|
||||
@@ -6,19 +6,40 @@ import type { PluginTheme } from "@getpaseo/plugin";
|
||||
import { withUnistyles } from "react-native-unistyles";
|
||||
import { useIsCompactFormFactor } from "@/constants/layout";
|
||||
import { usePaneContext } from "@/panels/pane-context";
|
||||
import { usePanelTab } from "@/panels/panel-instance-attributes";
|
||||
import { useHosts } from "@/runtime/host-runtime";
|
||||
import { usePluginHostNavigation } from "@/plugins/host-navigation";
|
||||
import { resolvePluginPlatform } from "@/plugins/platform";
|
||||
import { toPluginTheme } from "@/plugins/theme";
|
||||
import type { Theme } from "@/styles/theme";
|
||||
import type { FilePanel } from "./panels";
|
||||
import type { BuiltinFilePanelProps, FilePanel } from "./panels";
|
||||
import type { RenderingFilePanel, SourceFilePanel } from "./catalog";
|
||||
import { BuiltinFilePanelView } from "./builtin";
|
||||
import { PluginFilePanelHost } from "./plugin-host";
|
||||
|
||||
type Props = Pick<PluginFilePanelProps, "file" | "tab" | "params" | "revision"> & {
|
||||
type Props = Pick<PluginFilePanelProps, "file" | "params" | "revision"> & {
|
||||
panel: FilePanel;
|
||||
suspendPendingSave?: () => () => void;
|
||||
};
|
||||
function FilePanelHost({ panel, theme, ...input }: Props & { theme: PluginTheme }) {
|
||||
|
||||
function BuiltinFilePanelHost({
|
||||
panel,
|
||||
suspendPendingSave,
|
||||
...props
|
||||
}: Omit<BuiltinFilePanelProps, "tab"> & {
|
||||
panel: RenderingFilePanel | SourceFilePanel;
|
||||
suspendPendingSave?: () => () => void;
|
||||
}) {
|
||||
const tab = usePanelTab({ suspendPendingSave });
|
||||
return <BuiltinFilePanelView {...props} tab={tab} panel={panel} />;
|
||||
}
|
||||
|
||||
function FilePanelHost({
|
||||
panel,
|
||||
suspendPendingSave,
|
||||
theme,
|
||||
...input
|
||||
}: Props & { theme: PluginTheme }) {
|
||||
const { workspaceId, serverId } = usePaneContext();
|
||||
const compact = useIsCompactFormFactor();
|
||||
const hosts = useHosts();
|
||||
@@ -27,14 +48,21 @@ function FilePanelHost({ panel, theme, ...input }: Props & { theme: PluginTheme
|
||||
const layout = useMemo(() => ({ compact, platform: resolvePluginPlatform() }), [compact]);
|
||||
const stateSource = useMemo(() => createPluginClientStateSource(serverId), [serverId]);
|
||||
const navigation = usePluginHostNavigation(serverId);
|
||||
const props: PluginFilePanelProps = { ...input, workspaceId, theme, host, layout, navigation };
|
||||
const props: Omit<BuiltinFilePanelProps, "tab"> = {
|
||||
...input,
|
||||
workspaceId,
|
||||
theme,
|
||||
host,
|
||||
layout,
|
||||
navigation,
|
||||
};
|
||||
if (panel.builtin)
|
||||
return (
|
||||
<PluginClientStateProvider source={stateSource}>
|
||||
<BuiltinFilePanelView {...props} panel={panel} />
|
||||
<BuiltinFilePanelHost {...props} panel={panel} suspendPendingSave={suspendPendingSave} />
|
||||
</PluginClientStateProvider>
|
||||
);
|
||||
return <PluginFilePanelHost {...props} panel={panel} />;
|
||||
return <PluginFilePanelHost {...props} panel={panel} suspendPendingSave={suspendPendingSave} />;
|
||||
}
|
||||
const ThemedHost = withUnistyles(FilePanelHost);
|
||||
const themeMapping = (theme: Theme) => ({ theme: toPluginTheme(theme) });
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import type { AgentAddress } from "@getpaseo/protocol/addresses";
|
||||
import { memo, useCallback, useMemo, type ReactElement } from "react";
|
||||
import { memo, useCallback, useMemo, useRef, type ReactElement } from "react";
|
||||
import type { View } from "react-native";
|
||||
import { BackgroundWorkTrack, createHostBackgroundWorkModel } from "@/background-work";
|
||||
import { WorkspaceDiffStatPill } from "@/composer/diff-stat-pill";
|
||||
import { AgentTaskList } from "@/composer/task-list";
|
||||
@@ -7,7 +8,7 @@ import { ComposerTrackBar } from "@/composer/tracks";
|
||||
import { useIsCompactFormFactor } from "@/constants/layout";
|
||||
import { usePaneContext } from "@/panels/pane-context";
|
||||
import { useSettings } from "@/hooks/use-settings";
|
||||
import { PluginComposerPills } from "@/plugins";
|
||||
import { PluginComposerPillItems, PluginComposerPills } from "@/plugins";
|
||||
import { useSessionStore } from "@/stores/session-store";
|
||||
import {
|
||||
useArchiveFinishedSubagents,
|
||||
@@ -108,6 +109,7 @@ export const AgentTracks = memo(function AgentTracks({
|
||||
[openSubagentTarget],
|
||||
);
|
||||
const sheetTabFor = useSubagentSheetTab(workspaceKey, tabId);
|
||||
const trackViewportRef = useRef<View | null>(null);
|
||||
const handleOpenChanges = useCallback(() => {
|
||||
if (!workspaceKey) {
|
||||
return;
|
||||
@@ -120,7 +122,7 @@ export const AgentTracks = memo(function AgentTracks({
|
||||
}, [isCompact, openInSidePane, workspaceKey]);
|
||||
|
||||
return (
|
||||
<ComposerTrackBar>
|
||||
<ComposerTrackBar trackViewportRef={trackViewportRef}>
|
||||
<BackgroundWorkTrack model={backgroundModel} count={backgroundWorkCount} />
|
||||
{parentAgentId ? <ParentAgentPill serverId={serverId} parentAgentId={parentAgentId} /> : null}
|
||||
<AgentTaskList tasks={tasks} />
|
||||
@@ -135,6 +137,12 @@ export const AgentTracks = memo(function AgentTracks({
|
||||
archiveFinishedStatus={archiveFinishedSubagents.status}
|
||||
onDetachSubagent={canDetachSubagents ? detachSubagent : undefined}
|
||||
/>
|
||||
<PluginComposerPillItems
|
||||
serverId={serverId}
|
||||
workspaceId={workspaceId}
|
||||
agentId={agentId}
|
||||
fallbackAnchorRef={trackViewportRef}
|
||||
/>
|
||||
<PluginComposerPills
|
||||
serverId={serverId}
|
||||
workspaceId={workspaceId}
|
||||
|
||||
@@ -32,4 +32,45 @@ describe("panel instance attributes", () => {
|
||||
expect(notifications).toBe(2);
|
||||
unsubscribe();
|
||||
});
|
||||
|
||||
test("stores trimmed title overrides independently of modified and clears on empty or whitespace", () => {
|
||||
const first = { serverId: "server", workspaceId: "one", tabId: "tab-title" };
|
||||
const second = { serverId: "server", workspaceId: "two", tabId: "tab-title" };
|
||||
|
||||
setPanelInstanceAttributes(first, { modified: false, title: " Review (3) " });
|
||||
|
||||
expect(getPanelInstanceAttributes(first)).toEqual({
|
||||
modified: false,
|
||||
title: "Review (3)",
|
||||
});
|
||||
expect(getPanelInstanceAttributes(second)).toEqual({ modified: false });
|
||||
|
||||
setPanelInstanceAttributes(first, { modified: true, title: "Review (3)" });
|
||||
expect(getPanelInstanceAttributes(first)).toEqual({
|
||||
modified: true,
|
||||
title: "Review (3)",
|
||||
});
|
||||
|
||||
setPanelInstanceAttributes(first, { modified: true, title: " " });
|
||||
expect(getPanelInstanceAttributes(first)).toEqual({ modified: true });
|
||||
|
||||
setPanelInstanceAttributes(first, { modified: false, title: "" });
|
||||
expect(getPanelInstanceAttributes(first)).toEqual({ modified: false });
|
||||
});
|
||||
|
||||
test("notifies subscribers only when normalized title changes", () => {
|
||||
const identity = { serverId: "server", workspaceId: "workspace", tabId: "title-observed" };
|
||||
let notifications = 0;
|
||||
const unsubscribe = subscribePanelInstanceAttributes(identity, () => {
|
||||
notifications += 1;
|
||||
});
|
||||
|
||||
setPanelInstanceAttributes(identity, { modified: false, title: " " });
|
||||
setPanelInstanceAttributes(identity, { modified: false, title: " Custom " });
|
||||
setPanelInstanceAttributes(identity, { modified: false, title: "Custom" });
|
||||
setPanelInstanceAttributes(identity, { modified: false, title: "" });
|
||||
|
||||
expect(notifications).toBe(2);
|
||||
unsubscribe();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { useCallback, useEffect, useMemo, useSyncExternalStore } from "react";
|
||||
import type { PluginTab } from "@getpaseo/plugin/client";
|
||||
import { useCallback, useEffect, useMemo, useState, useSyncExternalStore } from "react";
|
||||
import { usePaneContext } from "@/panels/pane-context";
|
||||
import { buildWorkspaceTabPersistenceKey } from "@/workspace-tabs/model";
|
||||
|
||||
@@ -10,6 +11,7 @@ export interface PanelInstanceIdentity {
|
||||
|
||||
export interface PanelInstanceAttributes {
|
||||
modified: boolean;
|
||||
title?: string;
|
||||
suspendPendingSave?: () => () => void;
|
||||
}
|
||||
|
||||
@@ -19,6 +21,23 @@ const listenersByPanel = new Map<string, Set<() => void>>();
|
||||
const allListeners = new Set<() => void>();
|
||||
let attributesRevision = 0;
|
||||
|
||||
export function normalizePanelTitle(title: string | null | undefined): string | undefined {
|
||||
const trimmed = title?.trim();
|
||||
return trimmed ? trimmed : undefined;
|
||||
}
|
||||
|
||||
function normalizePanelAttributes(attributes: PanelInstanceAttributes): PanelInstanceAttributes {
|
||||
const title = normalizePanelTitle(attributes.title);
|
||||
const next: PanelInstanceAttributes = { modified: attributes.modified };
|
||||
if (title !== undefined) {
|
||||
next.title = title;
|
||||
}
|
||||
if (attributes.modified && attributes.suspendPendingSave !== undefined) {
|
||||
next.suspendPendingSave = attributes.suspendPendingSave;
|
||||
}
|
||||
return next;
|
||||
}
|
||||
|
||||
function buildWorkspacePanelKey(workspaceKey: string, tabId: string): string {
|
||||
return `${workspaceKey}:${tabId}`;
|
||||
}
|
||||
@@ -47,13 +66,15 @@ export function setPanelInstanceAttributes(
|
||||
): void {
|
||||
const key = buildPanelInstanceKey(identity);
|
||||
const previous = attributesByPanel.get(key) ?? DEFAULT_ATTRIBUTES;
|
||||
const next = normalizePanelAttributes(attributes);
|
||||
if (
|
||||
previous.modified === attributes.modified &&
|
||||
previous.suspendPendingSave === attributes.suspendPendingSave
|
||||
previous.modified === next.modified &&
|
||||
previous.title === next.title &&
|
||||
previous.suspendPendingSave === next.suspendPendingSave
|
||||
) {
|
||||
return;
|
||||
}
|
||||
if (attributes.modified) attributesByPanel.set(key, attributes);
|
||||
if (next.modified || next.title !== undefined) attributesByPanel.set(key, next);
|
||||
else attributesByPanel.delete(key);
|
||||
attributesRevision += 1;
|
||||
for (const listener of listenersByPanel.get(key) ?? []) listener();
|
||||
@@ -127,10 +148,49 @@ export function usePanelInstanceAttributes({
|
||||
export function usePublishPanelInstanceAttributes(attributes: PanelInstanceAttributes): void {
|
||||
const { serverId, workspaceId, tabId } = usePaneContext();
|
||||
const modified = attributes.modified;
|
||||
const title = normalizePanelTitle(attributes.title);
|
||||
const suspendPendingSave = attributes.suspendPendingSave;
|
||||
useEffect(() => {
|
||||
const identity = { serverId, workspaceId, tabId };
|
||||
setPanelInstanceAttributes(identity, { modified, suspendPendingSave });
|
||||
setPanelInstanceAttributes(identity, { modified, title, suspendPendingSave });
|
||||
return () => setPanelInstanceAttributes(identity, DEFAULT_ATTRIBUTES);
|
||||
}, [modified, serverId, suspendPendingSave, tabId, workspaceId]);
|
||||
}, [modified, serverId, suspendPendingSave, tabId, title, workspaceId]);
|
||||
}
|
||||
|
||||
const componentMountKeys = new WeakMap<object, number>();
|
||||
let nextComponentMountKey = 1;
|
||||
|
||||
/** Returns a stable numeric React key for a component function/object identity. */
|
||||
export function getComponentMountKey(component: object): number {
|
||||
let key = componentMountKeys.get(component);
|
||||
if (key === undefined) {
|
||||
key = nextComponentMountKey++;
|
||||
componentMountKeys.set(component, key);
|
||||
}
|
||||
return key;
|
||||
}
|
||||
|
||||
/** Publishes tab state (`modified` and `title`) for the current pane tab and resets it on unmount. */
|
||||
export function usePanelTab(options?: { suspendPendingSave?: () => () => void }): PluginTab {
|
||||
const { tabId, state, setCurrentTabState } = usePaneContext();
|
||||
const [modified, setModified] = useState(false);
|
||||
const [title, setTitleState] = useState<string | undefined>(undefined);
|
||||
const setTitle = useCallback((nextTitle: string | null) => {
|
||||
setTitleState(normalizePanelTitle(nextTitle));
|
||||
}, []);
|
||||
usePublishPanelInstanceAttributes({
|
||||
modified,
|
||||
title,
|
||||
suspendPendingSave: options?.suspendPendingSave,
|
||||
});
|
||||
return useMemo<PluginTab>(
|
||||
() => ({
|
||||
id: tabId,
|
||||
setModified,
|
||||
setTitle,
|
||||
state,
|
||||
setState: setCurrentTabState,
|
||||
}),
|
||||
[setCurrentTabState, setTitle, state, tabId],
|
||||
);
|
||||
}
|
||||
|
||||
@@ -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",
|
||||
}),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -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,
|
||||
},
|
||||
|
||||
@@ -0,0 +1,579 @@
|
||||
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
|
||||
import { PortalProvider } from "@gorhom/portal";
|
||||
import { DaemonClient } from "@getpaseo/client/internal/daemon-client";
|
||||
import React from "react";
|
||||
import { createRoot, type Root } from "react-dom/client";
|
||||
import { Text, View } from "react-native";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { page } from "vitest/browser";
|
||||
import { i18n } from "@/i18n/i18next";
|
||||
import { getFilePanelChoice } from "@/file-panels/choice/registry";
|
||||
import { filePanelRegistration } from "@/panels/file-panel";
|
||||
import { PaneFocusProvider, PaneProvider, type PaneContextValue } from "@/panels/pane-context";
|
||||
import { registerPanel } from "@/panels/panel-registry";
|
||||
import { pluginExecutionApprovals } from "@/plugins/execution-approval";
|
||||
import { pluginRegistry } from "@/plugins/registry";
|
||||
import { pluginPanelRegistration } from "@/plugins/workspace-panels/panel";
|
||||
import {
|
||||
getHostRuntimeStore,
|
||||
type HostRuntimeController,
|
||||
type HostRuntimeSnapshot,
|
||||
} from "@/runtime/host-runtime";
|
||||
import { RetainedPanelActivity } from "@/components/retained-panel";
|
||||
import {
|
||||
WorkspaceTabPresentationResolver,
|
||||
type WorkspaceTabPresentation,
|
||||
} from "@/screens/workspace/workspace-tab-presentation";
|
||||
import type { WorkspaceTabDescriptor } from "@/screens/workspace/workspace-tabs-types";
|
||||
import { useSessionStore, type Agent, type WorkspaceDescriptor } from "@/stores/session-store";
|
||||
import { useWorkspaceLayoutStore } from "@/stores/workspace-layout-store";
|
||||
import { seedSessionHosts, seedSessionWorkspaces } from "@/test/seed-session";
|
||||
|
||||
void i18n;
|
||||
registerPanel(pluginPanelRegistration);
|
||||
registerPanel(filePanelRegistration);
|
||||
|
||||
const SERVER_ID = "tab-title-server";
|
||||
const WORKSPACE_ID = "tab-title-workspace";
|
||||
const AGENT_ID = "tab-title-agent";
|
||||
const PLUGIN_ID = "tab-title-plugin";
|
||||
|
||||
const noop = () => {};
|
||||
|
||||
const FOCUS_VALUE = {
|
||||
isWorkspaceFocused: true,
|
||||
isPaneFocused: true,
|
||||
isInteractive: true,
|
||||
focusPane: noop,
|
||||
} as const;
|
||||
|
||||
const WORKSPACE_TAB: WorkspaceTabDescriptor = {
|
||||
key: "plugin-ws-1",
|
||||
tabId: "plugin-ws-1",
|
||||
kind: "plugin",
|
||||
target: {
|
||||
kind: "plugin",
|
||||
pluginId: PLUGIN_ID,
|
||||
panelId: "overview",
|
||||
context: "workspace",
|
||||
},
|
||||
};
|
||||
|
||||
const AGENT_TAB: WorkspaceTabDescriptor = {
|
||||
key: "plugin-agent-1",
|
||||
tabId: "plugin-agent-1",
|
||||
kind: "plugin",
|
||||
target: {
|
||||
kind: "plugin",
|
||||
pluginId: PLUGIN_ID,
|
||||
panelId: "inspector",
|
||||
context: "agent",
|
||||
agentId: AGENT_ID,
|
||||
},
|
||||
};
|
||||
|
||||
const FILE_TAB: WorkspaceTabDescriptor = {
|
||||
key: "file-txt-1",
|
||||
tabId: "file-txt-1",
|
||||
kind: "file",
|
||||
target: {
|
||||
kind: "file",
|
||||
path: "docs/notes.txt",
|
||||
},
|
||||
};
|
||||
|
||||
const MOUNT_TAB: WorkspaceTabDescriptor = {
|
||||
key: "plugin-mount-1",
|
||||
tabId: "plugin-mount-1",
|
||||
kind: "plugin",
|
||||
target: {
|
||||
kind: "plugin",
|
||||
pluginId: PLUGIN_ID,
|
||||
panelId: "mount-effect",
|
||||
context: "workspace",
|
||||
},
|
||||
};
|
||||
|
||||
function setHostRuntimeClient(serverId: string, client: DaemonClient | null) {
|
||||
const controllers = (
|
||||
getHostRuntimeStore() as unknown as {
|
||||
controllers: Map<string, HostRuntimeController>;
|
||||
}
|
||||
).controllers;
|
||||
const controller = controllers.get(serverId);
|
||||
if (!controller) throw new Error(`Host runtime controller for ${serverId} was not initialized`);
|
||||
(
|
||||
controller as unknown as {
|
||||
updateSnapshot: (
|
||||
patch: Partial<Omit<HostRuntimeSnapshot, "serverId" | "clientGeneration">>,
|
||||
) => void;
|
||||
}
|
||||
).updateSnapshot({ client });
|
||||
}
|
||||
|
||||
function createFakeClient() {
|
||||
const client = new DaemonClient({
|
||||
url: "ws://127.0.0.1:1",
|
||||
clientId: "plugin-tab-title-test",
|
||||
reconnect: { enabled: false },
|
||||
});
|
||||
Object.assign(client, {
|
||||
observeEvents: () => ({
|
||||
ready: Promise.resolve({ subscriptionId: "events" }),
|
||||
subscribe: () => noop,
|
||||
release: async () => undefined,
|
||||
}),
|
||||
readFile: async (_cwd: string, path: string) => ({
|
||||
path,
|
||||
content: "hello from file",
|
||||
encoding: "utf-8",
|
||||
kind: "text",
|
||||
mime: "text/plain",
|
||||
size: 15,
|
||||
modifiedAt: "2026-12-04T00:00:00.000Z",
|
||||
revision: "rev-1",
|
||||
}),
|
||||
subscribeFile: async () => ({
|
||||
initial: {
|
||||
status: "ready",
|
||||
kind: "text",
|
||||
mimeType: "text/plain",
|
||||
size: 15,
|
||||
modifiedAt: "2026-12-04T00:00:00.000Z",
|
||||
revision: "rev-1",
|
||||
},
|
||||
unsubscribe: async () => undefined,
|
||||
}),
|
||||
});
|
||||
return client;
|
||||
}
|
||||
|
||||
function workspaceDescriptor(): 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 agentDescriptor(): Agent {
|
||||
return {
|
||||
serverId: SERVER_ID,
|
||||
id: AGENT_ID,
|
||||
workspaceId: WORKSPACE_ID,
|
||||
provider: "codex",
|
||||
status: "idle",
|
||||
createdAt: new Date("2026-12-04T00:00:00.000Z"),
|
||||
updatedAt: new Date("2026-12-04T00:00:00.000Z"),
|
||||
lastUserMessageAt: null,
|
||||
lastActivityAt: new Date("2026-12-04T00: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 },
|
||||
};
|
||||
}
|
||||
|
||||
function buildBundle(versionLabel: string): string {
|
||||
return `(function(require) {
|
||||
var React = require("react");
|
||||
var RN = require("react-native");
|
||||
function Controls(props) {
|
||||
var prefix = props.prefix;
|
||||
var _useState = React.useState(false);
|
||||
var crashed = _useState[0];
|
||||
var setCrashed = _useState[1];
|
||||
if (crashed) throw new Error(prefix + " crashed");
|
||||
return React.createElement(
|
||||
RN.View,
|
||||
null,
|
||||
React.createElement(RN.Text, null, "${versionLabel}"),
|
||||
React.createElement(
|
||||
RN.Pressable,
|
||||
{
|
||||
accessibilityRole: "button",
|
||||
onPress: function() { props.tab.setTitle(" " + prefix + " Override "); },
|
||||
},
|
||||
React.createElement(RN.Text, null, "Set " + prefix + " title")
|
||||
),
|
||||
React.createElement(
|
||||
RN.Pressable,
|
||||
{
|
||||
accessibilityRole: "button",
|
||||
onPress: function() { props.tab.setTitle(" "); },
|
||||
},
|
||||
React.createElement(RN.Text, null, "Whitespace " + prefix + " title")
|
||||
),
|
||||
React.createElement(
|
||||
RN.Pressable,
|
||||
{
|
||||
accessibilityRole: "button",
|
||||
onPress: function() { props.tab.setTitle(null); },
|
||||
},
|
||||
React.createElement(RN.Text, null, "Reset " + prefix + " title")
|
||||
),
|
||||
React.createElement(
|
||||
RN.Pressable,
|
||||
{
|
||||
accessibilityRole: "button",
|
||||
onPress: function() { setCrashed(true); },
|
||||
},
|
||||
React.createElement(RN.Text, null, "Crash " + prefix + " panel")
|
||||
)
|
||||
);
|
||||
}
|
||||
return {
|
||||
default: function(client) {
|
||||
client.addWorkspacePanel({
|
||||
id: "overview",
|
||||
title: "Overview",
|
||||
icon: "PanelsTopLeft",
|
||||
locations: ["workspace", "explorer"],
|
||||
Component: function(props) {
|
||||
return React.createElement(Controls, { tab: props.tab, prefix: "workspace" });
|
||||
},
|
||||
});
|
||||
client.addAgentPanel({
|
||||
id: "inspector",
|
||||
title: "Inspector",
|
||||
icon: "Scan",
|
||||
locations: ["workspace", "explorer"],
|
||||
Component: function(props) {
|
||||
return React.createElement(Controls, { tab: props.tab, prefix: "agent" });
|
||||
},
|
||||
});
|
||||
client.addFilePanel({
|
||||
id: "txt-viewer",
|
||||
title: "Custom TXT",
|
||||
icon: "FileText",
|
||||
files: { extensions: ["txt"] },
|
||||
Component: function(props) {
|
||||
return React.createElement(Controls, { tab: props.tab, prefix: "file" });
|
||||
},
|
||||
});
|
||||
client.addWorkspacePanel({
|
||||
id: "mount-effect",
|
||||
title: "Static Mount",
|
||||
icon: "PanelsTopLeft",
|
||||
Component: function(props) {
|
||||
React.useEffect(function() {
|
||||
if ("${versionLabel}" === "v1") {
|
||||
props.tab.setTitle("Mounted title");
|
||||
props.tab.setModified(true);
|
||||
} else if ("${versionLabel}" === "v3") {
|
||||
props.tab.setTitle("Mounted v3");
|
||||
}
|
||||
}, []);
|
||||
return React.createElement(RN.Text, null, "mount-${versionLabel}");
|
||||
},
|
||||
});
|
||||
return function() {};
|
||||
}
|
||||
};
|
||||
})`;
|
||||
}
|
||||
|
||||
function installTestPlugin(client: DaemonClient, versionLabel = "v1") {
|
||||
pluginExecutionApprovals.setDecision(SERVER_ID, PLUGIN_ID, "approved");
|
||||
pluginRegistry.installCatalog(
|
||||
SERVER_ID,
|
||||
[
|
||||
{
|
||||
id: PLUGIN_ID,
|
||||
requirements: { paseo: ">=0.8.0" },
|
||||
clientBundle: buildBundle(versionLabel),
|
||||
},
|
||||
],
|
||||
{ client, audio: { play: async () => 0 } },
|
||||
);
|
||||
}
|
||||
|
||||
function PresentationProbe({ tab }: { tab: WorkspaceTabDescriptor }) {
|
||||
return (
|
||||
<WorkspaceTabPresentationResolver tab={tab} serverId={SERVER_ID} workspaceId={WORKSPACE_ID}>
|
||||
{(presentation: WorkspaceTabPresentation) => (
|
||||
<View>
|
||||
<Text testID="probe-label">{presentation.label}</Text>
|
||||
<Text testID="probe-tooltip">{presentation.tooltip}</Text>
|
||||
<Text testID="probe-modified">{String(presentation.modified)}</Text>
|
||||
</View>
|
||||
)}
|
||||
</WorkspaceTabPresentationResolver>
|
||||
);
|
||||
}
|
||||
|
||||
function makePaneContext(tab: WorkspaceTabDescriptor): PaneContextValue {
|
||||
return {
|
||||
serverId: SERVER_ID,
|
||||
workspaceId: WORKSPACE_ID,
|
||||
host: "main",
|
||||
tabId: tab.tabId,
|
||||
target: tab.target,
|
||||
openTab: noop,
|
||||
openPreferredTarget: noop,
|
||||
closeCurrentTab: noop,
|
||||
retargetCurrentTab: noop,
|
||||
setCurrentTabState: noop,
|
||||
openFileInWorkspace: noop,
|
||||
openImportSheet: noop,
|
||||
};
|
||||
}
|
||||
|
||||
describe("PluginTab.setTitle browser integration", () => {
|
||||
let hostElement: HTMLElement;
|
||||
let root: Root;
|
||||
let client: DaemonClient;
|
||||
|
||||
beforeEach(async () => {
|
||||
vi.stubGlobal("React", React);
|
||||
hostElement = document.createElement("div");
|
||||
document.body.appendChild(hostElement);
|
||||
root = createRoot(hostElement);
|
||||
|
||||
await vi.waitFor(() => expect(useWorkspaceLayoutStore.persist.hasHydrated()).toBe(true));
|
||||
useSessionStore.setState((state) => ({ ...state, sessions: {} }));
|
||||
client = createFakeClient();
|
||||
seedSessionHosts([SERVER_ID]);
|
||||
await vi.waitFor(() =>
|
||||
expect(useSessionStore.getState().sessions[SERVER_ID]?.hasRestoredCachedDirectory).toBe(true),
|
||||
);
|
||||
setHostRuntimeClient(SERVER_ID, client);
|
||||
useSessionStore.getState().updateSessionClient(SERVER_ID, client);
|
||||
seedSessionWorkspaces(SERVER_ID, new Map([[WORKSPACE_ID, workspaceDescriptor()]]));
|
||||
useSessionStore.getState().setAgents(SERVER_ID, new Map([[AGENT_ID, agentDescriptor()]]));
|
||||
installTestPlugin(client, "v1");
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
root.unmount();
|
||||
hostElement.remove();
|
||||
pluginRegistry.removeHost(SERVER_ID);
|
||||
pluginExecutionApprovals.clearHost(SERVER_ID);
|
||||
seedSessionHosts([]);
|
||||
});
|
||||
|
||||
it("updates, trims, clears, and resets workspace panel title on unmount, reload, and removal", async () => {
|
||||
const PluginPanel = pluginPanelRegistration.component;
|
||||
const paneContext = makePaneContext(WORKSPACE_TAB);
|
||||
|
||||
const renderHarness = (mountPanel: boolean) => {
|
||||
root.render(
|
||||
<PortalProvider>
|
||||
<PresentationProbe tab={WORKSPACE_TAB} />
|
||||
{mountPanel ? (
|
||||
<PaneProvider value={paneContext}>
|
||||
<PaneFocusProvider value={FOCUS_VALUE}>
|
||||
<PluginPanel />
|
||||
</PaneFocusProvider>
|
||||
</PaneProvider>
|
||||
) : null}
|
||||
</PortalProvider>,
|
||||
);
|
||||
};
|
||||
|
||||
renderHarness(true);
|
||||
await expect.element(page.getByTestId("probe-label")).toHaveTextContent("Overview");
|
||||
await expect.element(page.getByTestId("probe-tooltip")).toHaveTextContent("Overview");
|
||||
|
||||
await page.getByRole("button", { name: "Set workspace title", exact: true }).click();
|
||||
await expect.element(page.getByTestId("probe-label")).toHaveTextContent("workspace Override");
|
||||
await expect.element(page.getByTestId("probe-tooltip")).toHaveTextContent("workspace Override");
|
||||
await expect.element(page.getByTestId("probe-modified")).toHaveTextContent("false");
|
||||
|
||||
await page.getByRole("button", { name: "Whitespace workspace title", exact: true }).click();
|
||||
await expect.element(page.getByTestId("probe-label")).toHaveTextContent("Overview");
|
||||
|
||||
await page.getByRole("button", { name: "Set workspace title", exact: true }).click();
|
||||
await expect.element(page.getByTestId("probe-label")).toHaveTextContent("workspace Override");
|
||||
|
||||
// Plugin reload resets mounted tab title override back to the static title.
|
||||
installTestPlugin(client, "v2");
|
||||
await expect.element(page.getByText("v2")).toBeVisible();
|
||||
await expect.element(page.getByTestId("probe-label")).toHaveTextContent("Overview");
|
||||
|
||||
// Reset via null.
|
||||
await page.getByRole("button", { name: "Set workspace title", exact: true }).click();
|
||||
await expect.element(page.getByTestId("probe-label")).toHaveTextContent("workspace Override");
|
||||
await page.getByRole("button", { name: "Reset workspace title", exact: true }).click();
|
||||
await expect.element(page.getByTestId("probe-label")).toHaveTextContent("Overview");
|
||||
|
||||
// Unmount resets override back to static title.
|
||||
await page.getByRole("button", { name: "Set workspace title", exact: true }).click();
|
||||
await expect.element(page.getByTestId("probe-label")).toHaveTextContent("workspace Override");
|
||||
renderHarness(false);
|
||||
await expect.element(page.getByTestId("probe-label")).toHaveTextContent("Overview");
|
||||
|
||||
// Becoming unavailable (removing plugin) unmounts inner surface and clears override.
|
||||
renderHarness(true);
|
||||
await page.getByRole("button", { name: "Set workspace title", exact: true }).click();
|
||||
await expect.element(page.getByTestId("probe-label")).toHaveTextContent("workspace Override");
|
||||
pluginRegistry.removeHost(SERVER_ID);
|
||||
await expect.element(page.getByTestId("probe-label")).toHaveTextContent("Plugin unavailable");
|
||||
await expect
|
||||
.element(page.getByTestId("probe-tooltip"))
|
||||
.toHaveTextContent("This plugin panel is unavailable");
|
||||
});
|
||||
|
||||
it("updates, resets, and clears agent panel title when agent disappears or panel unmounts", async () => {
|
||||
const PluginPanel = pluginPanelRegistration.component;
|
||||
const paneContext = makePaneContext(AGENT_TAB);
|
||||
|
||||
root.render(
|
||||
<PortalProvider>
|
||||
<PresentationProbe tab={AGENT_TAB} />
|
||||
<PaneProvider value={paneContext}>
|
||||
<PaneFocusProvider value={FOCUS_VALUE}>
|
||||
<PluginPanel />
|
||||
</PaneFocusProvider>
|
||||
</PaneProvider>
|
||||
</PortalProvider>,
|
||||
);
|
||||
await expect.element(page.getByTestId("probe-label")).toHaveTextContent("Inspector");
|
||||
|
||||
await page.getByRole("button", { name: "Set agent title", exact: true }).click();
|
||||
await expect.element(page.getByTestId("probe-label")).toHaveTextContent("agent Override");
|
||||
await expect.element(page.getByTestId("probe-tooltip")).toHaveTextContent("agent Override");
|
||||
|
||||
await page.getByRole("button", { name: "Reset agent title", exact: true }).click();
|
||||
await expect.element(page.getByTestId("probe-label")).toHaveTextContent("Inspector");
|
||||
|
||||
// Removing the agent unmounts the plugin body and clears the override.
|
||||
await page.getByRole("button", { name: "Set agent title", exact: true }).click();
|
||||
await expect.element(page.getByTestId("probe-label")).toHaveTextContent("agent Override");
|
||||
useSessionStore.getState().setAgents(SERVER_ID, new Map());
|
||||
await expect.element(page.getByTestId("probe-label")).toHaveTextContent("Inspector");
|
||||
});
|
||||
|
||||
it("updates, resets, and clears file panel title on panel switch and unmount", async () => {
|
||||
const FilePanel = filePanelRegistration.component;
|
||||
const paneContext = makePaneContext(FILE_TAB);
|
||||
|
||||
const testQueryClient = new QueryClient();
|
||||
const renderFile = (mountPanel: boolean) => {
|
||||
root.render(
|
||||
<QueryClientProvider client={testQueryClient}>
|
||||
<PortalProvider>
|
||||
<PresentationProbe tab={FILE_TAB} />
|
||||
{mountPanel ? (
|
||||
<PaneProvider value={paneContext}>
|
||||
<PaneFocusProvider value={FOCUS_VALUE}>
|
||||
<RetainedPanelActivity active>
|
||||
<FilePanel />
|
||||
</RetainedPanelActivity>
|
||||
</PaneFocusProvider>
|
||||
</PaneProvider>
|
||||
) : null}
|
||||
</PortalProvider>
|
||||
</QueryClientProvider>,
|
||||
);
|
||||
};
|
||||
|
||||
renderFile(true);
|
||||
await expect.element(page.getByTestId("probe-label")).toHaveTextContent("notes.txt");
|
||||
await expect.element(page.getByTestId("probe-tooltip")).toHaveTextContent("docs/notes.txt");
|
||||
await expect.element(page.getByText("Open .txt files with")).toBeVisible();
|
||||
getFilePanelChoice({
|
||||
serverId: SERVER_ID,
|
||||
workspaceId: WORKSPACE_ID,
|
||||
tabId: FILE_TAB.tabId,
|
||||
})?.dismissPicker();
|
||||
|
||||
await page.getByRole("button", { name: "Set file title", exact: true }).click();
|
||||
await expect.element(page.getByTestId("probe-label")).toHaveTextContent("file Override");
|
||||
await expect.element(page.getByTestId("probe-tooltip")).toHaveTextContent("file Override");
|
||||
|
||||
await page.getByRole("button", { name: "Reset file title", exact: true }).click();
|
||||
await expect.element(page.getByTestId("probe-label")).toHaveTextContent("notes.txt");
|
||||
await expect.element(page.getByTestId("probe-tooltip")).toHaveTextContent("docs/notes.txt");
|
||||
|
||||
// Reloading the file plugin clears the active title override.
|
||||
await page.getByRole("button", { name: "Set file title", exact: true }).click();
|
||||
await expect.element(page.getByTestId("probe-label")).toHaveTextContent("file Override");
|
||||
installTestPlugin(client, "v2");
|
||||
await expect.element(page.getByText("v2")).toBeVisible();
|
||||
await expect.element(page.getByTestId("probe-label")).toHaveTextContent("notes.txt");
|
||||
|
||||
// A render error inside the file plugin surface clears the title override too.
|
||||
await page.getByRole("button", { name: "Set file title", exact: true }).click();
|
||||
await expect.element(page.getByTestId("probe-label")).toHaveTextContent("file Override");
|
||||
await page.getByRole("button", { name: "Crash file panel", exact: true }).click();
|
||||
await expect.element(page.getByText("Plugin failed: file crashed")).toBeVisible();
|
||||
await expect.element(page.getByTestId("probe-label")).toHaveTextContent("notes.txt");
|
||||
|
||||
// Re-install to recover from error boundary, then switch the active file panel.
|
||||
installTestPlugin(client, "v3");
|
||||
await expect.element(page.getByText("v3")).toBeVisible();
|
||||
await page.getByRole("button", { name: "Set file title", exact: true }).click();
|
||||
await expect.element(page.getByTestId("probe-label")).toHaveTextContent("file Override");
|
||||
getFilePanelChoice({
|
||||
serverId: SERVER_ID,
|
||||
workspaceId: WORKSPACE_ID,
|
||||
tabId: FILE_TAB.tabId,
|
||||
})?.openWith("builtin:source");
|
||||
await expect.element(page.getByTestId("probe-label")).toHaveTextContent("notes.txt");
|
||||
await expect.element(page.getByTestId("probe-tooltip")).toHaveTextContent("docs/notes.txt");
|
||||
|
||||
// Unmounting clears any override.
|
||||
renderFile(false);
|
||||
await expect.element(page.getByTestId("probe-label")).toHaveTextContent("notes.txt");
|
||||
});
|
||||
|
||||
it("preserves title and modified set in a mount effect and resets on reload", async () => {
|
||||
const PluginPanel = pluginPanelRegistration.component;
|
||||
const paneContext = makePaneContext(MOUNT_TAB);
|
||||
|
||||
root.render(
|
||||
<PortalProvider>
|
||||
<PresentationProbe tab={MOUNT_TAB} />
|
||||
<PaneProvider value={paneContext}>
|
||||
<PaneFocusProvider value={FOCUS_VALUE}>
|
||||
<PluginPanel />
|
||||
</PaneFocusProvider>
|
||||
</PaneProvider>
|
||||
</PortalProvider>,
|
||||
);
|
||||
|
||||
await expect.element(page.getByText("mount-v1")).toBeVisible();
|
||||
await expect.element(page.getByTestId("probe-label")).toHaveTextContent("Mounted title");
|
||||
await expect.element(page.getByTestId("probe-modified")).toHaveTextContent("true");
|
||||
|
||||
// Reloading to v2 (which does not call setTitle/setModified) clears both back to static defaults.
|
||||
installTestPlugin(client, "v2");
|
||||
await expect.element(page.getByText("mount-v2")).toBeVisible();
|
||||
await expect.element(page.getByTestId("probe-label")).toHaveTextContent("Static Mount");
|
||||
await expect.element(page.getByTestId("probe-modified")).toHaveTextContent("false");
|
||||
|
||||
// Reloading to v3 (which calls setTitle in its mount effect) applies the new mount title.
|
||||
installTestPlugin(client, "v3");
|
||||
await expect.element(page.getByText("mount-v3")).toBeVisible();
|
||||
await expect.element(page.getByTestId("probe-label")).toHaveTextContent("Mounted v3");
|
||||
await expect.element(page.getByTestId("probe-modified")).toHaveTextContent("false");
|
||||
});
|
||||
});
|
||||
@@ -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 });
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
@@ -5,6 +5,7 @@ import { describe, expect, it } from "vitest";
|
||||
import type { PluginButton } from "@getpaseo/plugin/client";
|
||||
import type { InstalledPlugin } from "../types";
|
||||
import { PluginButtonStore, buttonMatches } from "./model";
|
||||
import { buttonPageId } from "./validation";
|
||||
|
||||
function installation(): InstalledPlugin {
|
||||
return {
|
||||
@@ -29,6 +30,7 @@ function installation(): InstalledPlugin {
|
||||
workspaceRowBadgeItems: [],
|
||||
filePanels: [],
|
||||
composerItems: [],
|
||||
composerPillItems: [],
|
||||
newWorkspaceItems: [],
|
||||
workspacePanels: [],
|
||||
commandCenterItems: [],
|
||||
@@ -262,3 +264,163 @@ it("keeps the previous descriptor after rejecting an invalid update", () => {
|
||||
registration.remove();
|
||||
plugin.i18n.dispose();
|
||||
});
|
||||
|
||||
it("keeps an open popover open when update keeps the same popover Content reference, and closes on Content, kind, visible, or disabled change", () => {
|
||||
const buttons = store();
|
||||
const plugin = installation();
|
||||
const FirstPopover = () => null;
|
||||
const SecondPopover = () => null;
|
||||
const registration = buttons.addComposerPill(plugin, {
|
||||
id: "inbox",
|
||||
workspaceId: "workspace",
|
||||
agentId: "agent",
|
||||
button: {
|
||||
title: "Inbox",
|
||||
icon: "Scan",
|
||||
label: "1 decision",
|
||||
behavior: { kind: "popover", Content: FirstPopover },
|
||||
},
|
||||
});
|
||||
const key = buttons.getSnapshot()[0].key;
|
||||
buttons.setOpen(key, true);
|
||||
expect(buttons.getSnapshot()[0].open).toBe(true);
|
||||
|
||||
registration.update({
|
||||
label: "2 decisions",
|
||||
behavior: { kind: "popover", Content: FirstPopover },
|
||||
});
|
||||
expect(buttons.getSnapshot()[0].open).toBe(true);
|
||||
expect(buttons.getSnapshot()[0].button.label).toBe("2 decisions");
|
||||
|
||||
registration.update({
|
||||
behavior: { kind: "popover", Content: SecondPopover },
|
||||
});
|
||||
expect(buttons.getSnapshot()[0].open).toBe(false);
|
||||
|
||||
buttons.setOpen(key, true);
|
||||
registration.update({ disabled: true, behavior: { kind: "popover", Content: SecondPopover } });
|
||||
expect(buttons.getSnapshot()[0].open).toBe(false);
|
||||
|
||||
registration.update({ disabled: false });
|
||||
buttons.setOpen(key, true);
|
||||
registration.update({ visible: false, behavior: { kind: "popover", Content: SecondPopover } });
|
||||
expect(buttons.getSnapshot()[0].open).toBe(false);
|
||||
|
||||
registration.update({ visible: true });
|
||||
buttons.setOpen(key, true);
|
||||
registration.update({ behavior: { kind: "action", onPress() {} } });
|
||||
expect(buttons.getSnapshot()[0].open).toBe(false);
|
||||
|
||||
registration.remove();
|
||||
plugin.i18n.dispose();
|
||||
});
|
||||
|
||||
it("accepts non-empty trimmed unique menu entry IDs while keeping top-level button IDs kebab-case", async () => {
|
||||
const buttons = store();
|
||||
const plugin = installation();
|
||||
expect(() =>
|
||||
buttons.addComposerPill(plugin, {
|
||||
id: "D42",
|
||||
workspaceId: "workspace",
|
||||
agentId: "agent",
|
||||
button: button(),
|
||||
}),
|
||||
).toThrow("Invalid plugin button id: D42");
|
||||
|
||||
const pressed: string[] = [];
|
||||
const registration = buttons.addComposerPill(plugin, {
|
||||
id: "inbox",
|
||||
workspaceId: "workspace",
|
||||
agentId: "agent",
|
||||
button: {
|
||||
title: "Inbox",
|
||||
icon: "Scan",
|
||||
behavior: {
|
||||
kind: "menu",
|
||||
items: [
|
||||
{
|
||||
kind: "item",
|
||||
id: " D42 ",
|
||||
title: "Decision 42",
|
||||
behavior: { kind: "action", onPress: () => void pressed.push("D42") },
|
||||
},
|
||||
{ kind: "separator", id: "sep_123e4567-e89b-12d3-a456-426614174000" },
|
||||
{
|
||||
kind: "item",
|
||||
id: "550e8400-e29b-41d4-a716-446655440000",
|
||||
title: "Decision UUID",
|
||||
behavior: { kind: "action", onPress: () => void pressed.push("uuid") },
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const entry = buttons.getSnapshot()[0];
|
||||
expect(entry.button.behavior).toMatchObject({
|
||||
kind: "menu",
|
||||
items: [
|
||||
{ kind: "item", id: "D42" },
|
||||
{ kind: "separator", id: "sep_123e4567-e89b-12d3-a456-426614174000" },
|
||||
{ kind: "item", id: "550e8400-e29b-41d4-a716-446655440000" },
|
||||
],
|
||||
});
|
||||
await buttons.run(entry.key, ["D42"]);
|
||||
await buttons.run(entry.key, ["550e8400-e29b-41d4-a716-446655440000"]);
|
||||
expect(pressed).toEqual(["D42", "uuid"]);
|
||||
|
||||
expect(() =>
|
||||
registration.update({
|
||||
behavior: {
|
||||
kind: "menu",
|
||||
items: [
|
||||
{
|
||||
kind: "item",
|
||||
id: " ",
|
||||
title: "Blank",
|
||||
behavior: { kind: "action", onPress() {} },
|
||||
},
|
||||
],
|
||||
},
|
||||
}),
|
||||
).toThrow();
|
||||
|
||||
expect(() =>
|
||||
registration.update({
|
||||
behavior: {
|
||||
kind: "menu",
|
||||
items: [
|
||||
{
|
||||
kind: "item",
|
||||
id: "D42",
|
||||
title: "First",
|
||||
behavior: { kind: "action", onPress() {} },
|
||||
},
|
||||
{
|
||||
kind: "item",
|
||||
id: " D42 ",
|
||||
title: "Duplicate",
|
||||
behavior: { kind: "action", onPress() {} },
|
||||
},
|
||||
],
|
||||
},
|
||||
}),
|
||||
).toThrow("Duplicate plugin button menu item: D42");
|
||||
|
||||
expect(() =>
|
||||
registration.update({
|
||||
behavior: {
|
||||
kind: "menu",
|
||||
items: [{ kind: "separator", id: "" }],
|
||||
},
|
||||
}),
|
||||
).toThrow();
|
||||
|
||||
registration.remove();
|
||||
plugin.i18n.dispose();
|
||||
});
|
||||
|
||||
it("serializes submenu page IDs without collisions when entry IDs contain slashes", () => {
|
||||
expect(buttonPageId(1, ["a/b"])).not.toBe(buttonPageId(1, ["a", "b"]));
|
||||
expect(buttonPageId(1, ["D42"])).toBe("plugin-button/1/D42");
|
||||
});
|
||||
|
||||
@@ -123,7 +123,12 @@ export class PluginButtonStore {
|
||||
const nextSource = { ...sourceButton, ...patch };
|
||||
const button = validateButton(nextSource, this.validation, installation.i18n.resolve);
|
||||
sourceButton = nextSource;
|
||||
const close = !button.visible || button.disabled || patch.behavior !== undefined;
|
||||
const keepsOpenPopover =
|
||||
entry.button.behavior.kind === "popover" &&
|
||||
button.behavior.kind === "popover" &&
|
||||
entry.button.behavior.Content === button.behavior.Content;
|
||||
const close =
|
||||
!button.visible || button.disabled || (patch.behavior !== undefined && !keepsOpenPopover);
|
||||
this.replace(key, { button, open: close ? false : entry.open });
|
||||
},
|
||||
remove: () => {
|
||||
|
||||
@@ -19,6 +19,22 @@ export function requireButtonId(value: string): string {
|
||||
return value;
|
||||
}
|
||||
|
||||
/** Submenu page IDs joined on `/` must encode segments so arbitrary menu IDs (e.g. `a/b`) stay unique. */
|
||||
export function buttonPageId(key: number, path: readonly string[]): string {
|
||||
return ["plugin-button", String(key), ...path.map((segment) => encodeURIComponent(segment))].join(
|
||||
"/",
|
||||
);
|
||||
}
|
||||
|
||||
function requireMenuEntryId(value: string): string {
|
||||
if (typeof value !== "string") {
|
||||
throw new Error(`Invalid plugin button menu item id: ${String(value)}`);
|
||||
}
|
||||
const id = value.trim();
|
||||
if (!id) throw new Error(`Invalid plugin button menu item id: ${value}`);
|
||||
return id;
|
||||
}
|
||||
|
||||
function optionalBoolean(value: boolean | undefined, fallback: boolean): boolean {
|
||||
if (value === undefined) return fallback;
|
||||
if (typeof value !== "boolean")
|
||||
@@ -61,13 +77,14 @@ function validateBehavior(
|
||||
return {
|
||||
kind: "menu",
|
||||
items: behavior.items.map((item) => {
|
||||
requireButtonId(item.id);
|
||||
if (ids.has(item.id)) throw new Error(`Duplicate plugin button menu item: ${item.id}`);
|
||||
ids.add(item.id);
|
||||
if (item.kind === "separator") return { ...item };
|
||||
const id = requireMenuEntryId(item.id);
|
||||
if (ids.has(id)) throw new Error(`Duplicate plugin button menu item: ${id}`);
|
||||
ids.add(id);
|
||||
if (item.kind === "separator") return { ...item, id };
|
||||
if (item.kind !== "item") throw new Error("Invalid plugin button menu entry");
|
||||
return {
|
||||
...item,
|
||||
id,
|
||||
icon: item.icon === undefined ? undefined : validation.parseIcon(item.icon),
|
||||
title: requireText(item.title, "menu item title", resolve),
|
||||
visible: optionalBoolean(item.visible, true),
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import type {
|
||||
ResolvedPluginButtonBehavior as PluginButtonBehavior,
|
||||
ResolvedPluginButtonMenuEntry as PluginButtonMenuEntry,
|
||||
import {
|
||||
buttonPageId,
|
||||
type ResolvedPluginButtonBehavior as PluginButtonBehavior,
|
||||
type ResolvedPluginButtonMenuEntry as PluginButtonMenuEntry,
|
||||
} from "./validation";
|
||||
import type { PluginButtonIcon, PluginHostProps } from "@getpaseo/plugin/client";
|
||||
import type { PluginTheme } from "@getpaseo/plugin";
|
||||
@@ -210,11 +211,6 @@ function ButtonSurfaceBody({
|
||||
);
|
||||
}
|
||||
|
||||
// Prefixed so plugin pages can share a surface with the host's own pages.
|
||||
function buttonPageId(key: number, path: readonly string[]): string {
|
||||
return ["plugin-button", key, ...path].join("/");
|
||||
}
|
||||
|
||||
type RenderButtonPage = (behavior: PluginButtonBehavior, path: readonly string[]) => ReactNode;
|
||||
|
||||
/** A page for every menu and popover item below `behavior`, depth first. */
|
||||
|
||||
@@ -110,6 +110,7 @@ function plugin(onAgentSelect: AgentCommandItem["onSelect"]): InstalledPlugin {
|
||||
workspaceRowBadgeItems: [],
|
||||
filePanels: [],
|
||||
composerItems: [],
|
||||
composerPillItems: [],
|
||||
newWorkspaceItems: [],
|
||||
workspacePanels: [
|
||||
{
|
||||
|
||||
@@ -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,6 +36,7 @@ function installed(): InstalledPlugin {
|
||||
sidebarViews: [],
|
||||
filePanels: [],
|
||||
composerItems: [],
|
||||
composerPillItems: [],
|
||||
newWorkspaceItems: [],
|
||||
workspaceRowBadgeItems: [],
|
||||
workspacePanels: [],
|
||||
|
||||
@@ -46,6 +46,7 @@ function plugin(): InstalledPlugin {
|
||||
sidebarViews: [],
|
||||
filePanels: [],
|
||||
composerItems: [],
|
||||
composerPillItems: [],
|
||||
newWorkspaceItems: [],
|
||||
workspaceRowBadgeItems: [],
|
||||
workspacePanels: [],
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
import { createContext, useContext } from "react";
|
||||
import type { View } from "react-native";
|
||||
|
||||
/** What the host tells `ComposerPill` about the composer pill item it renders in. */
|
||||
export interface ComposerPillItemFrame {
|
||||
title: string;
|
||||
testID: string;
|
||||
popoverOpen: boolean;
|
||||
isAnchoredTo: (node: View | null) => boolean;
|
||||
/** A pill calls this before its `onPress`, so a popover that press opens anchors to it. */
|
||||
anchorTo: (node: View | null) => void;
|
||||
/** Pills offer themselves on mount, so a popover opened without a press anchors to a pill. */
|
||||
offerAnchor: (node: View | null) => void;
|
||||
releaseAnchor: (node: View | null) => void;
|
||||
}
|
||||
|
||||
export const ComposerPillItemFrameContext = createContext<ComposerPillItemFrame | null>(null);
|
||||
|
||||
export function useComposerPillItemFrame(): ComposerPillItemFrame | null {
|
||||
return useContext(ComposerPillItemFrameContext);
|
||||
}
|
||||
@@ -0,0 +1,472 @@
|
||||
import React, {
|
||||
act,
|
||||
useCallback,
|
||||
useEffect,
|
||||
useMemo,
|
||||
useRef,
|
||||
useState,
|
||||
type ReactNode,
|
||||
} from "react";
|
||||
import { createRoot, type Root } from "react-dom/client";
|
||||
import { Pressable, Text, View, type ViewStyle } from "react-native";
|
||||
import { createPaseoApi } from "@getpaseo/client";
|
||||
import { DaemonClient } from "@getpaseo/client/internal/daemon-client";
|
||||
import { QueryClient } from "@tanstack/react-query";
|
||||
import { router } from "expo-router";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { page } from "vitest/browser";
|
||||
import {
|
||||
useWorkspace,
|
||||
type PluginComposerPillItemProps,
|
||||
type PluginPopoverProps,
|
||||
} from "@getpaseo/plugin/client";
|
||||
import { PluginTranslationRuntime } from "@getpaseo/plugin/client/host";
|
||||
import type { ToastApi } from "@/components/toast-host";
|
||||
import { ToastApiProvider } from "@/contexts/toast-api-context";
|
||||
import { useSessionStore } from "@/stores/session-store";
|
||||
import { seedSessionWorkspaces } from "@/test/seed-session";
|
||||
import { connectedPluginHosts } from "../client-state/connected-hosts";
|
||||
import { workspace as workspaceFixture } from "../client-state/fixtures";
|
||||
import { pluginRegistry } from "../registry";
|
||||
import type { InstalledPlugin } from "../types";
|
||||
import { ComposerPill, PluginComposerPillItems } from "./index";
|
||||
|
||||
// App sources compile against the classic JSX runtime, which expects React on the global.
|
||||
beforeEach(() => vi.stubGlobal("React", React));
|
||||
|
||||
const noop = () => {};
|
||||
const explodeSync = () => {
|
||||
throw new Error("Sync boom");
|
||||
};
|
||||
const rowStyle: ViewStyle = { flexDirection: "row" };
|
||||
const popoverContainerStyle: ViewStyle = { gap: 8 };
|
||||
const anchoredWrapperStyle: ViewStyle = { position: "absolute", top: 700, left: 40 };
|
||||
|
||||
interface Mounted {
|
||||
root: Root;
|
||||
container: HTMLDivElement;
|
||||
}
|
||||
|
||||
const mounted: Mounted[] = [];
|
||||
|
||||
function mount(node: ReactNode, toast: ToastApi): HTMLDivElement {
|
||||
const container = document.createElement("div");
|
||||
document.body.appendChild(container);
|
||||
const root = createRoot(container);
|
||||
act(() => root.render(<ToastApiProvider api={toast}>{node}</ToastApiProvider>));
|
||||
mounted.push({ root, container });
|
||||
return container;
|
||||
}
|
||||
|
||||
function makePlugin(
|
||||
composerPillItems: InstalledPlugin["composerPillItems"],
|
||||
overrides: Partial<InstalledPlugin> = {},
|
||||
): InstalledPlugin {
|
||||
return {
|
||||
lifetime: new AbortController(),
|
||||
locale: "en",
|
||||
i18n: new PluginTranslationRuntime({ getLocale: () => "en", subscribe: () => () => {} }),
|
||||
id: "inbox-plugin",
|
||||
serverId: "host-a",
|
||||
clientBundle: "bundle",
|
||||
queryClient: new QueryClient(),
|
||||
paseo: createPaseoApi(
|
||||
new DaemonClient({
|
||||
url: "ws://127.0.0.1:1",
|
||||
clientId: "composer-pill-items-test",
|
||||
reconnect: { enabled: false },
|
||||
}),
|
||||
),
|
||||
invoke: async () => undefined,
|
||||
subscribe: () => {
|
||||
throw new Error("Subscriptions are not used here");
|
||||
},
|
||||
cleanup: () => undefined,
|
||||
settingsScreens: [],
|
||||
surfaces: [{ id: "details", title: "Details", Component: () => null }],
|
||||
sidebarViews: [],
|
||||
sidebarItems: { header: [], footer: [] },
|
||||
legacySidebarItems: [],
|
||||
workspaceRowBadgeItems: [],
|
||||
filePanels: [],
|
||||
composerItems: [],
|
||||
composerPillItems,
|
||||
newWorkspaceItems: [],
|
||||
workspacePanels: [],
|
||||
commandCenterItems: [],
|
||||
clientSlashCommands: [],
|
||||
attachmentSources: [],
|
||||
themes: [],
|
||||
timelineTransformers: [],
|
||||
timelineRenderers: [],
|
||||
notificationOpenHandlers: [],
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
function setInstalledPlugins(plugins: InstalledPlugin[]) {
|
||||
vi.spyOn(pluginRegistry, "getSnapshot").mockReturnValue(plugins);
|
||||
vi.spyOn(pluginRegistry, "subscribe").mockImplementation(() => () => {});
|
||||
}
|
||||
|
||||
function makeToast(): { toast: ToastApi; errors: string[] } {
|
||||
const errors: string[] = [];
|
||||
const toast = {
|
||||
show: vi.fn(),
|
||||
error: vi.fn((message: string) => {
|
||||
errors.push(message);
|
||||
}),
|
||||
} as unknown as ToastApi;
|
||||
return { toast, errors };
|
||||
}
|
||||
|
||||
afterEach(() => {
|
||||
for (const entry of mounted.splice(0)) {
|
||||
act(() => entry.root.unmount());
|
||||
entry.container.remove();
|
||||
}
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
describe("PluginComposerPillItems & ComposerPill", () => {
|
||||
beforeEach(async () => {
|
||||
await page.viewport(1280, 900);
|
||||
});
|
||||
|
||||
it("mounts per (workspaceId, agentId), passes host props, and returns null cleanly with no wrapper gap", () => {
|
||||
const seen: { workspaceId: string; agentId: string }[] = [];
|
||||
const plugin = makePlugin([
|
||||
{
|
||||
id: "quiet",
|
||||
title: "Quiet",
|
||||
Component({ workspaceId, agentId }: PluginComposerPillItemProps) {
|
||||
seen.push({ workspaceId, agentId });
|
||||
return null;
|
||||
},
|
||||
},
|
||||
{
|
||||
id: "active",
|
||||
title: "Active pill",
|
||||
Component({ workspaceId, agentId }: PluginComposerPillItemProps) {
|
||||
return <ComposerPill icon="Inbox" label={`${workspaceId}:${agentId}`} onPress={noop} />;
|
||||
},
|
||||
},
|
||||
]);
|
||||
setInstalledPlugins([plugin]);
|
||||
const { toast } = makeToast();
|
||||
|
||||
function Harness() {
|
||||
const [agentId, setAgentId] = useState("agent-1");
|
||||
const switchToAgent2 = useCallback(() => setAgentId("agent-2"), []);
|
||||
return (
|
||||
<>
|
||||
<Pressable
|
||||
accessibilityRole="button"
|
||||
accessibilityLabel="Switch agent"
|
||||
onPress={switchToAgent2}
|
||||
>
|
||||
<Text>Switch</Text>
|
||||
</Pressable>
|
||||
<View testID="track-row" style={rowStyle}>
|
||||
<PluginComposerPillItems serverId="host-a" workspaceId="ws-1" agentId={agentId} />
|
||||
</View>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
const container = mount(<Harness />, toast);
|
||||
const trackRow = container.querySelector('[data-testid="track-row"]')!;
|
||||
// Only the active pill renders a child node; the null item adds no wrapper View.
|
||||
expect(trackRow.children).toHaveLength(1);
|
||||
expect(seen).toEqual([{ workspaceId: "ws-1", agentId: "agent-1" }]);
|
||||
expect(trackRow.textContent).toBe("ws-1:agent-1");
|
||||
|
||||
const switchButton = container.querySelector('[aria-label="Switch agent"]') as HTMLElement;
|
||||
act(() => switchButton.click());
|
||||
|
||||
expect(seen).toEqual([
|
||||
{ workspaceId: "ws-1", agentId: "agent-1" },
|
||||
{ workspaceId: "ws-1", agentId: "agent-2" },
|
||||
]);
|
||||
expect(trackRow.textContent).toBe("ws-1:agent-2");
|
||||
});
|
||||
|
||||
it("isolates throwing items behind SurfaceErrorBoundary while siblings remain visible", () => {
|
||||
vi.spyOn(console, "warn").mockImplementation(() => {});
|
||||
const plugin = makePlugin([
|
||||
{
|
||||
id: "broken",
|
||||
title: "Broken",
|
||||
Component() {
|
||||
throw new Error("pill exploded");
|
||||
},
|
||||
},
|
||||
{
|
||||
id: "healthy",
|
||||
title: "Healthy",
|
||||
Component() {
|
||||
return <ComposerPill icon="Check" label="Healthy" onPress={noop} />;
|
||||
},
|
||||
},
|
||||
]);
|
||||
setInstalledPlugins([plugin]);
|
||||
const { toast } = makeToast();
|
||||
|
||||
const container = mount(
|
||||
<View testID="track-row" style={rowStyle}>
|
||||
<PluginComposerPillItems serverId="host-a" workspaceId="ws-1" agentId="agent-1" />
|
||||
</View>,
|
||||
toast,
|
||||
);
|
||||
const trackRow = container.querySelector('[data-testid="track-row"]')!;
|
||||
expect(trackRow.children).toHaveLength(1);
|
||||
expect(trackRow.textContent).toBe("Healthy");
|
||||
});
|
||||
|
||||
it("handles pending-promise busy state, prevents double presses, reports errors in toast, and allows retry", async () => {
|
||||
let finish = () => {};
|
||||
let attempt = 0;
|
||||
const plugin = makePlugin([
|
||||
{
|
||||
id: "run",
|
||||
title: "Run check",
|
||||
Component() {
|
||||
const handleRunPress = useCallback(() => {
|
||||
attempt += 1;
|
||||
if (attempt === 1) return Promise.reject(new Error("Check failed"));
|
||||
return new Promise<void>((resolve) => {
|
||||
finish = resolve;
|
||||
});
|
||||
}, []);
|
||||
return (
|
||||
<ComposerPill
|
||||
icon="Play"
|
||||
label="Run"
|
||||
title="Run check tooltip"
|
||||
onPress={handleRunPress}
|
||||
/>
|
||||
);
|
||||
},
|
||||
},
|
||||
]);
|
||||
setInstalledPlugins([plugin]);
|
||||
const { toast, errors } = makeToast();
|
||||
|
||||
const container = mount(
|
||||
<PluginComposerPillItems serverId="host-a" workspaceId="ws-1" agentId="agent-1" />,
|
||||
toast,
|
||||
);
|
||||
const pill = container.querySelector(
|
||||
'[data-testid="plugin-composer-pill-inbox-plugin-run"]',
|
||||
) as HTMLElement;
|
||||
expect(pill).toBeTruthy();
|
||||
expect(pill.getAttribute("aria-label")).toBe("Run check tooltip");
|
||||
|
||||
// First attempt rejects -> error toast shown, pill recovers for retry.
|
||||
await act(async () => {
|
||||
pill.click();
|
||||
});
|
||||
expect(errors).toEqual(["Check failed"]);
|
||||
expect(pill.getAttribute("aria-disabled")).not.toBe("true");
|
||||
|
||||
// Second attempt stays pending -> blocks repeated press until settled.
|
||||
act(() => {
|
||||
pill.click();
|
||||
});
|
||||
expect(pill.getAttribute("aria-disabled")).toBe("true");
|
||||
expect(pill.getAttribute("aria-busy")).toBe("true");
|
||||
act(() => {
|
||||
pill.click();
|
||||
});
|
||||
expect(attempt).toBe(2);
|
||||
|
||||
await act(async () => {
|
||||
finish();
|
||||
});
|
||||
expect(pill.getAttribute("aria-disabled")).not.toBe("true");
|
||||
expect(pill.getAttribute("aria-busy")).not.toBe("true");
|
||||
});
|
||||
|
||||
it("anchors openPopover above the pill on desktop, provides plugin environment, and navigates via openScreen", async () => {
|
||||
const pushSpy = vi.spyOn(router, "push").mockImplementation(() => {});
|
||||
vi.spyOn(connectedPluginHosts, "getSnapshot").mockReturnValue(["host-a"]);
|
||||
useSessionStore.getState().initializeSession("host-a", null);
|
||||
seedSessionWorkspaces(
|
||||
"host-a",
|
||||
new Map([["ws-1", { ...workspaceFixture, id: "ws-1", name: "My Workspace" }]]),
|
||||
);
|
||||
|
||||
function PopoverBody({ theme, close, openScreen }: PluginPopoverProps) {
|
||||
// Reads from PluginInstallationProvider inside the portal.
|
||||
const workspace = useWorkspace("ws-1", (entry) => entry.name);
|
||||
const titleStyle = useMemo(
|
||||
() => ({ color: theme.colors.foreground }),
|
||||
[theme.colors.foreground],
|
||||
);
|
||||
const handleOpenDetails = useCallback(
|
||||
() => openScreen({ screenId: "details", params: { tab: "inbox" } }),
|
||||
[openScreen],
|
||||
);
|
||||
return (
|
||||
<View style={popoverContainerStyle}>
|
||||
<Text testID="popover-title" style={titleStyle}>
|
||||
Inbox popover ({workspace ?? "no-ws"})
|
||||
</Text>
|
||||
<Pressable
|
||||
accessibilityRole="button"
|
||||
accessibilityLabel="Open details screen"
|
||||
onPress={handleOpenDetails}
|
||||
>
|
||||
<Text>Open screen</Text>
|
||||
</Pressable>
|
||||
<Pressable accessibilityRole="button" accessibilityLabel="Close popover" onPress={close}>
|
||||
<Text>Close</Text>
|
||||
</Pressable>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
const plugin = makePlugin([
|
||||
{
|
||||
id: "inbox",
|
||||
title: "Inbox",
|
||||
Component({ openPopover }: PluginComposerPillItemProps) {
|
||||
const handleOpenPopover = useCallback(() => openPopover(PopoverBody), [openPopover]);
|
||||
return <ComposerPill icon="Inbox" label="2 decisions" onPress={handleOpenPopover} />;
|
||||
},
|
||||
},
|
||||
]);
|
||||
setInstalledPlugins([plugin]);
|
||||
const { toast } = makeToast();
|
||||
|
||||
const container = mount(
|
||||
<View style={anchoredWrapperStyle}>
|
||||
<PluginComposerPillItems serverId="host-a" workspaceId="ws-1" agentId="agent-1" />
|
||||
</View>,
|
||||
toast,
|
||||
);
|
||||
|
||||
const pill = container.querySelector(
|
||||
'[data-testid="plugin-composer-pill-inbox-plugin-inbox"]',
|
||||
) as HTMLElement;
|
||||
act(() => pill.click());
|
||||
|
||||
await expect
|
||||
.poll(() => document.querySelector('[data-testid="popover-title"]')?.textContent)
|
||||
.toBe("Inbox popover (My Workspace)");
|
||||
|
||||
const pillRect = pill.getBoundingClientRect();
|
||||
const popoverSurface = document.querySelector(
|
||||
'[data-testid="plugin-composer-pill-inbox-plugin-inbox-popover"]',
|
||||
) as HTMLElement;
|
||||
expect(popoverSurface).toBeTruthy();
|
||||
await expect
|
||||
.poll(() => popoverSurface.getBoundingClientRect().bottom <= pillRect.top + 1)
|
||||
.toBe(true);
|
||||
|
||||
// Clicking openScreen from inside the popover closes it and navigates.
|
||||
const openScreenBtn = document.querySelector(
|
||||
'[aria-label="Open details screen"]',
|
||||
) as HTMLElement;
|
||||
act(() => openScreenBtn.click());
|
||||
|
||||
expect(pushSpy).toHaveBeenCalledTimes(1);
|
||||
expect(String(pushSpy.mock.calls[0]?.[0])).toContain(
|
||||
"/h/host-a/plugin/inbox-plugin/surface/details",
|
||||
);
|
||||
await expect.poll(() => document.querySelector('[data-testid="popover-title"]')).toBeNull();
|
||||
});
|
||||
|
||||
it("ignores presses when disabled and reports synchronous throws in toast", () => {
|
||||
let pressed = 0;
|
||||
const plugin = makePlugin([
|
||||
{
|
||||
id: "disabled-pill",
|
||||
title: "Disabled",
|
||||
Component() {
|
||||
const incrementPressed = useCallback(() => {
|
||||
pressed += 1;
|
||||
}, []);
|
||||
return <ComposerPill icon="Check" label="Locked" disabled onPress={incrementPressed} />;
|
||||
},
|
||||
},
|
||||
{
|
||||
id: "throws-sync",
|
||||
title: "Throws",
|
||||
Component() {
|
||||
return <ComposerPill icon="Check" label="Explode" onPress={explodeSync} />;
|
||||
},
|
||||
},
|
||||
]);
|
||||
setInstalledPlugins([plugin]);
|
||||
const { toast, errors } = makeToast();
|
||||
|
||||
const container = mount(
|
||||
<PluginComposerPillItems serverId="host-a" workspaceId="ws-1" agentId="agent-1" />,
|
||||
toast,
|
||||
);
|
||||
const disabledPill = container.querySelector(
|
||||
'[data-testid="plugin-composer-pill-inbox-plugin-disabled-pill"]',
|
||||
) as HTMLElement;
|
||||
expect(disabledPill.getAttribute("aria-disabled")).toBe("true");
|
||||
act(() => disabledPill.click());
|
||||
expect(pressed).toBe(0);
|
||||
|
||||
const syncPill = container.querySelector(
|
||||
'[data-testid="plugin-composer-pill-inbox-plugin-throws-sync"]',
|
||||
) as HTMLElement;
|
||||
act(() => syncPill.click());
|
||||
expect(errors).toEqual(["Sync boom"]);
|
||||
});
|
||||
|
||||
it("anchors openPopover above fallbackAnchorRef when an item opens without a mounted ComposerPill", async () => {
|
||||
function FallbackPopoverBody() {
|
||||
return <Text testID="fallback-popover-body">Opened from effect</Text>;
|
||||
}
|
||||
|
||||
const plugin = makePlugin([
|
||||
{
|
||||
id: "effect-only",
|
||||
title: "Effect only",
|
||||
Component({ openPopover }: PluginComposerPillItemProps) {
|
||||
useEffect(() => {
|
||||
openPopover(FallbackPopoverBody);
|
||||
}, [openPopover]);
|
||||
return null;
|
||||
},
|
||||
},
|
||||
]);
|
||||
setInstalledPlugins([plugin]);
|
||||
const { toast } = makeToast();
|
||||
|
||||
function FallbackHarness() {
|
||||
const fallbackAnchorRef = useRef<View | null>(null);
|
||||
return (
|
||||
<View ref={fallbackAnchorRef} testID="fallback-anchor" style={anchoredWrapperStyle}>
|
||||
<PluginComposerPillItems
|
||||
serverId="host-a"
|
||||
workspaceId="ws-1"
|
||||
agentId="agent-1"
|
||||
fallbackAnchorRef={fallbackAnchorRef}
|
||||
/>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
const container = mount(<FallbackHarness />, toast);
|
||||
const anchor = container.querySelector('[data-testid="fallback-anchor"]') as HTMLElement;
|
||||
await expect
|
||||
.poll(() => document.querySelector('[data-testid="fallback-popover-body"]')?.textContent)
|
||||
.toBe("Opened from effect");
|
||||
const popoverSurface = document.querySelector(
|
||||
'[data-testid="plugin-composer-pill-inbox-plugin-effect-only-popover"]',
|
||||
) as HTMLElement;
|
||||
expect(popoverSurface).toBeTruthy();
|
||||
await expect
|
||||
.poll(
|
||||
() =>
|
||||
popoverSurface.getBoundingClientRect().bottom <= anchor.getBoundingClientRect().top + 1,
|
||||
)
|
||||
.toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,234 @@
|
||||
import type { PluginTheme } from "@getpaseo/plugin";
|
||||
import type {
|
||||
PluginComposerPillItemProps,
|
||||
PluginHostProps,
|
||||
PluginOpenScreenInput,
|
||||
PluginPopoverProps,
|
||||
} from "@getpaseo/plugin/client";
|
||||
import { router } from "expo-router";
|
||||
import { useCallback, useMemo, useState, type ComponentType, type RefObject } from "react";
|
||||
import type { View } from "react-native";
|
||||
import { withUnistyles } from "react-native-unistyles";
|
||||
import { MenuRoot } from "@/components/ui/menu";
|
||||
import { pluginScreensHostKey, rememberPluginContributionHost } from "../contribution-host";
|
||||
import { pluginThemeMapping, renderNothing, usePluginItemHost } from "../item-host";
|
||||
import {
|
||||
PluginEnvironmentProvider,
|
||||
PluginPopoverContent,
|
||||
PluginPopoverSurface,
|
||||
usePluginPopoverAnchor,
|
||||
type PluginEnvironment,
|
||||
} from "../popover";
|
||||
import { useInstalledPlugins } from "../registry";
|
||||
import { buildPluginSurfaceRoute } from "../routes";
|
||||
import { parsePluginOpenScreenInput } from "../surface-contribution";
|
||||
import { SurfaceErrorBoundary } from "../surface-error-boundary";
|
||||
import type { InstalledPlugin, PluginComposerPillItemContribution } from "../types";
|
||||
import { ComposerPillItemFrameContext, type ComposerPillItemFrame } from "./frame";
|
||||
|
||||
export { ComposerPill } from "./kit";
|
||||
|
||||
type PopoverContent = ComponentType<PluginPopoverProps>;
|
||||
|
||||
interface ComposerPillItemTarget {
|
||||
plugin: InstalledPlugin;
|
||||
item: PluginComposerPillItemContribution;
|
||||
}
|
||||
|
||||
/**
|
||||
* Declarative composer pill items for one visible agent tab. Each item mounts behind its own error
|
||||
* boundary and plugin environment with no wrapper views, so returning `null` leaves no gap.
|
||||
*/
|
||||
export function PluginComposerPillItems({
|
||||
serverId,
|
||||
workspaceId,
|
||||
agentId,
|
||||
fallbackAnchorRef,
|
||||
}: {
|
||||
serverId: string;
|
||||
workspaceId: string;
|
||||
agentId: string;
|
||||
fallbackAnchorRef?: RefObject<View | null>;
|
||||
}) {
|
||||
const installed = useInstalledPlugins();
|
||||
const targets = useMemo<ComposerPillItemTarget[]>(
|
||||
() =>
|
||||
installed
|
||||
.filter((plugin) => plugin.serverId === serverId)
|
||||
.flatMap((plugin) => plugin.composerPillItems.map((item) => ({ plugin, item }))),
|
||||
[installed, serverId],
|
||||
);
|
||||
return targets.map(({ plugin, item }) => (
|
||||
<ThemedComposerPillItemHost
|
||||
key={`${plugin.id}/${item.id}:${workspaceId}:${agentId}`}
|
||||
plugin={plugin}
|
||||
item={item}
|
||||
workspaceId={workspaceId}
|
||||
agentId={agentId}
|
||||
fallbackAnchorRef={fallbackAnchorRef}
|
||||
uniProps={pluginThemeMapping}
|
||||
/>
|
||||
));
|
||||
}
|
||||
|
||||
function ComposerPillItemHost({
|
||||
plugin,
|
||||
item,
|
||||
workspaceId,
|
||||
agentId,
|
||||
fallbackAnchorRef,
|
||||
theme,
|
||||
}: {
|
||||
plugin: InstalledPlugin;
|
||||
item: PluginComposerPillItemContribution;
|
||||
workspaceId: string;
|
||||
agentId: string;
|
||||
fallbackAnchorRef?: RefObject<View | null>;
|
||||
theme: PluginTheme;
|
||||
}) {
|
||||
const { environment, props: hostProps } = usePluginItemHost(plugin, theme);
|
||||
// The content outlives `open` so the surface can play its exit and native sheet teardown.
|
||||
const [popover, setPopover] = useState<PopoverContent | null>(null);
|
||||
const [popoverOpen, setPopoverOpen] = useState(false);
|
||||
|
||||
const showPopover = useCallback((content: PopoverContent | null) => {
|
||||
// A function passed to a state setter is an updater, so wrap the component.
|
||||
if (content) setPopover(() => content);
|
||||
setPopoverOpen(content !== null);
|
||||
}, []);
|
||||
|
||||
const handleOpenChange = useCallback((open: boolean) => {
|
||||
if (!open) setPopoverOpen(false);
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<SurfaceErrorBoundary
|
||||
installation={plugin}
|
||||
Surface={item.Component}
|
||||
renderError={renderNothing}
|
||||
>
|
||||
<PluginEnvironmentProvider environment={environment}>
|
||||
<MenuRoot compactMode="sheet" open={popoverOpen} onOpenChange={handleOpenChange}>
|
||||
<ComposerPillItemContent
|
||||
plugin={plugin}
|
||||
item={item}
|
||||
workspaceId={workspaceId}
|
||||
agentId={agentId}
|
||||
fallbackAnchorRef={fallbackAnchorRef}
|
||||
hostProps={hostProps}
|
||||
environment={environment}
|
||||
popover={popover}
|
||||
popoverOpen={popoverOpen}
|
||||
showPopover={showPopover}
|
||||
/>
|
||||
</MenuRoot>
|
||||
</PluginEnvironmentProvider>
|
||||
</SurfaceErrorBoundary>
|
||||
);
|
||||
}
|
||||
|
||||
const ThemedComposerPillItemHost = withUnistyles(ComposerPillItemHost);
|
||||
|
||||
function ComposerPillItemContent({
|
||||
plugin,
|
||||
item,
|
||||
workspaceId,
|
||||
agentId,
|
||||
fallbackAnchorRef,
|
||||
hostProps,
|
||||
environment,
|
||||
popover,
|
||||
popoverOpen,
|
||||
showPopover,
|
||||
}: {
|
||||
plugin: InstalledPlugin;
|
||||
item: PluginComposerPillItemContribution;
|
||||
workspaceId: string;
|
||||
agentId: string;
|
||||
fallbackAnchorRef?: RefObject<View | null>;
|
||||
hostProps: PluginHostProps;
|
||||
environment: PluginEnvironment;
|
||||
popover: PopoverContent | null;
|
||||
popoverOpen: boolean;
|
||||
showPopover: (content: PopoverContent | null) => void;
|
||||
}) {
|
||||
const { triggerRef, anchorTo, offerAnchor, releaseAnchor, anchorToFallback } =
|
||||
usePluginPopoverAnchor("PluginComposerPillItem");
|
||||
const title = plugin.i18n.resolve(item.title, plugin.locale);
|
||||
const testID = `plugin-composer-pill-${plugin.id}-${item.id}`;
|
||||
|
||||
const openScreen = useCallback(
|
||||
(input: PluginOpenScreenInput) => {
|
||||
const { screenId, params } = parsePluginOpenScreenInput(plugin, input);
|
||||
rememberPluginContributionHost(pluginScreensHostKey(plugin.id), plugin.serverId);
|
||||
showPopover(null);
|
||||
router.push(
|
||||
buildPluginSurfaceRoute(
|
||||
plugin.serverId,
|
||||
plugin.id,
|
||||
{ kind: "surface", id: screenId },
|
||||
params,
|
||||
),
|
||||
);
|
||||
},
|
||||
[plugin, showPopover],
|
||||
);
|
||||
|
||||
const openPopover = useCallback(
|
||||
(Content: PopoverContent) => {
|
||||
if (fallbackAnchorRef) anchorToFallback(fallbackAnchorRef);
|
||||
showPopover(Content);
|
||||
},
|
||||
[anchorToFallback, fallbackAnchorRef, showPopover],
|
||||
);
|
||||
|
||||
const close = useCallback(() => showPopover(null), [showPopover]);
|
||||
const isAnchoredTo = useCallback(
|
||||
(node: View | null) => triggerRef.current === node,
|
||||
[triggerRef],
|
||||
);
|
||||
|
||||
const frame = useMemo<ComposerPillItemFrame>(
|
||||
() => ({
|
||||
title,
|
||||
testID,
|
||||
popoverOpen,
|
||||
isAnchoredTo,
|
||||
anchorTo,
|
||||
offerAnchor,
|
||||
releaseAnchor,
|
||||
}),
|
||||
[anchorTo, isAnchoredTo, offerAnchor, popoverOpen, releaseAnchor, testID, title],
|
||||
);
|
||||
|
||||
const itemProps = useMemo<PluginComposerPillItemProps>(
|
||||
() => ({ ...hostProps, workspaceId, agentId, openScreen, openPopover }),
|
||||
[agentId, hostProps, openPopover, openScreen, workspaceId],
|
||||
);
|
||||
|
||||
const Item = item.Component;
|
||||
const Popover = popover;
|
||||
|
||||
return (
|
||||
<ComposerPillItemFrameContext.Provider value={frame}>
|
||||
<Item {...itemProps} />
|
||||
{Popover ? (
|
||||
<PluginPopoverSurface
|
||||
sheetTitle={title}
|
||||
side="top"
|
||||
align="start"
|
||||
offset={12}
|
||||
testID={`${testID}-popover`}
|
||||
>
|
||||
<SurfaceErrorBoundary installation={plugin} Surface={Popover}>
|
||||
<PluginEnvironmentProvider environment={environment}>
|
||||
<PluginPopoverContent>
|
||||
<Popover {...hostProps} close={close} openScreen={openScreen} />
|
||||
</PluginPopoverContent>
|
||||
</PluginEnvironmentProvider>
|
||||
</SurfaceErrorBoundary>
|
||||
</PluginPopoverSurface>
|
||||
) : null}
|
||||
</ComposerPillItemFrameContext.Provider>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,171 @@
|
||||
import type { ComposerPillProps } from "@getpaseo/plugin/client/ui";
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
||||
import { Text, View } from "react-native";
|
||||
import { StyleSheet, withUnistyles } from "react-native-unistyles";
|
||||
import { LoadingSpinner } from "@/components/ui/loading-spinner";
|
||||
import { PressHighlight } from "@/components/ui/press-highlight";
|
||||
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
|
||||
import { composerPillStyles } from "@/composer/pill-styles";
|
||||
import { useToast } from "@/contexts/toast-api-context";
|
||||
import type { Theme } from "@/styles/theme";
|
||||
import { toErrorMessage } from "@/utils/error-messages";
|
||||
import { parsePluginIcon, PluginIconView } from "../icons";
|
||||
import { useComposerPillItemFrame } from "./frame";
|
||||
|
||||
const ThemedPluginIconView = withUnistyles(PluginIconView);
|
||||
const ThemedLoadingSpinner = withUnistyles(LoadingSpinner);
|
||||
const mutedIconMapping = (theme: Theme) => ({ color: theme.colors.foregroundMuted });
|
||||
|
||||
function isPromiseLike(value: unknown): value is PromiseLike<unknown> {
|
||||
return (
|
||||
(typeof value === "object" || typeof value === "function") &&
|
||||
value !== null &&
|
||||
"then" in value &&
|
||||
typeof (value as { then?: unknown }).then === "function"
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* A pill above an agent's composer. Matches Paseo's composer pill chrome, pending-promise state,
|
||||
* and error toast handling while anchoring any popover opened by `openPopover` to the pressed pill.
|
||||
*/
|
||||
export function ComposerPill({ icon, label, title, disabled = false, onPress }: ComposerPillProps) {
|
||||
const frame = useComposerPillItemFrame();
|
||||
const toast = useToast();
|
||||
const pillRef = useRef<View | null>(null);
|
||||
const mountedRef = useRef(true);
|
||||
const pendingRef = useRef(false);
|
||||
const [pending, setPending] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
mountedRef.current = true;
|
||||
return () => {
|
||||
mountedRef.current = false;
|
||||
};
|
||||
}, []);
|
||||
|
||||
const offerAnchor = frame?.offerAnchor;
|
||||
const releaseAnchor = frame?.releaseAnchor;
|
||||
useEffect(() => {
|
||||
const node = pillRef.current;
|
||||
offerAnchor?.(node);
|
||||
return () => {
|
||||
releaseAnchor?.(node);
|
||||
};
|
||||
}, [offerAnchor, releaseAnchor]);
|
||||
|
||||
// Parsed at render, not registration, so an invalid icon throws to the item's boundary.
|
||||
const parsedIcon = useMemo(() => parsePluginIcon("Composer pill", icon), [icon]);
|
||||
const tooltipText = title?.trim() || undefined;
|
||||
const accessibleLabel = tooltipText ?? (label.trim() || frame?.title || undefined);
|
||||
const isDisabled = disabled || pending;
|
||||
const isActive = Boolean(frame?.popoverOpen && frame.isAnchoredTo(pillRef.current));
|
||||
const [hovered, setHovered] = useState(false);
|
||||
const handleHoverIn = useCallback(() => setHovered(true), []);
|
||||
const handleHoverOut = useCallback(() => setHovered(false), []);
|
||||
|
||||
const pillStyle = useMemo(
|
||||
() => [
|
||||
composerPillStyles.body,
|
||||
styles.button,
|
||||
((hovered && !isDisabled) || isActive) && composerPillStyles.bodyActive,
|
||||
isDisabled && styles.disabled,
|
||||
],
|
||||
[hovered, isActive, isDisabled],
|
||||
);
|
||||
|
||||
const handlePress = useCallback(() => {
|
||||
if (disabled || pendingRef.current) return;
|
||||
frame?.anchorTo(pillRef.current);
|
||||
try {
|
||||
const result = onPress();
|
||||
if (!isPromiseLike(result)) return;
|
||||
pendingRef.current = true;
|
||||
setPending(true);
|
||||
void Promise.resolve(result)
|
||||
.catch((error: unknown) => {
|
||||
toast.error(toErrorMessage(error));
|
||||
})
|
||||
.finally(() => {
|
||||
pendingRef.current = false;
|
||||
if (mountedRef.current) setPending(false);
|
||||
});
|
||||
} catch (error: unknown) {
|
||||
toast.error(toErrorMessage(error));
|
||||
}
|
||||
}, [disabled, frame, onPress, toast]);
|
||||
|
||||
const accessibilityState = useMemo(
|
||||
() => ({ busy: pending, disabled: isDisabled }),
|
||||
[isDisabled, pending],
|
||||
);
|
||||
|
||||
const trigger = (
|
||||
<PressHighlight
|
||||
ref={pillRef}
|
||||
collapsable={false}
|
||||
testID={frame?.testID}
|
||||
accessibilityRole="button"
|
||||
accessibilityLabel={accessibleLabel}
|
||||
accessibilityState={accessibilityState}
|
||||
aria-busy={pending}
|
||||
disabled={isDisabled}
|
||||
onPress={handlePress}
|
||||
onHoverIn={handleHoverIn}
|
||||
onHoverOut={handleHoverOut}
|
||||
style={pillStyle}
|
||||
highlightStyle={composerPillStyles.bodyActive}
|
||||
>
|
||||
{pending ? (
|
||||
<View style={styles.icon}>
|
||||
<ThemedLoadingSpinner size={14} uniProps={mutedIconMapping} />
|
||||
</View>
|
||||
) : (
|
||||
<View
|
||||
style={styles.icon}
|
||||
accessible={false}
|
||||
accessibilityElementsHidden
|
||||
importantForAccessibility="no-hide-descendants"
|
||||
>
|
||||
<ThemedPluginIconView icon={parsedIcon} size={14} uniProps={mutedIconMapping} />
|
||||
</View>
|
||||
)}
|
||||
{label ? (
|
||||
<Text numberOfLines={1} style={styles.label}>
|
||||
{label}
|
||||
</Text>
|
||||
) : null}
|
||||
</PressHighlight>
|
||||
);
|
||||
|
||||
if (!tooltipText) return trigger;
|
||||
|
||||
return (
|
||||
<Tooltip enabledOnMobile={false}>
|
||||
<TooltipTrigger asChild>{trigger}</TooltipTrigger>
|
||||
<TooltipContent>
|
||||
<Text style={styles.tooltipLabel}>{tooltipText}</Text>
|
||||
</TooltipContent>
|
||||
</Tooltip>
|
||||
);
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create((theme) => ({
|
||||
button: { flexShrink: 1, minWidth: 0, maxWidth: 160 },
|
||||
disabled: { opacity: theme.opacity[50] },
|
||||
tooltipLabel: { fontSize: theme.fontSize.sm, color: theme.colors.foreground },
|
||||
label: {
|
||||
fontSize: theme.fontSize.sm,
|
||||
color: theme.colors.foregroundMuted,
|
||||
flexShrink: 1,
|
||||
},
|
||||
icon: {
|
||||
width: 16,
|
||||
height: 16,
|
||||
alignItems: "center",
|
||||
justifyContent: "center",
|
||||
flexShrink: 0,
|
||||
overflow: "hidden",
|
||||
pointerEvents: "none",
|
||||
},
|
||||
}));
|
||||
@@ -111,6 +111,7 @@ describe("evaluatePluginClientBundle", () => {
|
||||
plugin.addSidebarHeaderItem({ id: "main", title: "Main", Component }),
|
||||
plugin.addSidebarFooterItem({ id: "status", title: "Status", Component }),
|
||||
plugin.addWorkspaceRowBadgeItem({ id: "status", title: "Status", icon: "Blocks", Component }),
|
||||
plugin.addComposerPillItem({ id: "pill-item", title: "Pill", Component }),
|
||||
plugin.addWorkspacePanel({ id: "panel", title: "Panel", icon: "Blocks", context: "workspace", Component }),
|
||||
plugin.addCommandCenterItem({ id: "command", title: "Command", icon: "Blocks", context: "global", onSelect() {} }),
|
||||
plugin.addSlashCommand({ name: "review", description: "Review", argumentHint: "", context: "workspace", onSubmit() {} }),
|
||||
@@ -144,6 +145,7 @@ describe("evaluatePluginClientBundle", () => {
|
||||
plugin.sidebarItems.header,
|
||||
plugin.sidebarItems.footer,
|
||||
plugin.workspaceRowBadgeItems,
|
||||
plugin.composerPillItems,
|
||||
plugin.workspacePanels,
|
||||
plugin.commandCenterItems,
|
||||
plugin.clientSlashCommands,
|
||||
@@ -166,6 +168,7 @@ describe("evaluatePluginClientBundle", () => {
|
||||
plugin.sidebarItems.header,
|
||||
plugin.sidebarItems.footer,
|
||||
plugin.workspaceRowBadgeItems,
|
||||
plugin.composerPillItems,
|
||||
plugin.workspacePanels,
|
||||
plugin.commandCenterItems,
|
||||
plugin.clientSlashCommands,
|
||||
@@ -335,6 +338,43 @@ describe("evaluatePluginClientBundle", () => {
|
||||
).toThrow("Workspace row badge item status is not a component");
|
||||
});
|
||||
|
||||
it("collects composer pill items, releases ids on removal, and rejects invalid or duplicate ones", () => {
|
||||
const plugin = evaluatePluginClientBundle(
|
||||
"example",
|
||||
bundle(`
|
||||
const Item = require("react").memo(function Item() { return null; });
|
||||
const remove = plugin.addComposerPillItem({ id: "inbox", title: " Inbox ", Component: Item });
|
||||
remove();
|
||||
plugin.addComposerPillItem({ id: "inbox", title: " Inbox ", Component: Item });
|
||||
`),
|
||||
);
|
||||
expect(plugin.composerPillItems.map(({ id, title }) => ({ id, title }))).toEqual([
|
||||
{ id: "inbox", title: "Inbox" },
|
||||
]);
|
||||
|
||||
const item = (fields: string) =>
|
||||
bundle(`function Item() { return null; } plugin.addComposerPillItem({ ${fields} });`);
|
||||
expect(() =>
|
||||
evaluatePluginClientBundle(
|
||||
"example",
|
||||
bundle(`
|
||||
function Item() { return null; }
|
||||
plugin.addComposerPillItem({ id: "inbox", title: "One", Component: Item });
|
||||
plugin.addComposerPillItem({ id: "inbox", title: "Two", Component: Item });
|
||||
`),
|
||||
),
|
||||
).toThrow("Duplicate composer pill item: inbox");
|
||||
expect(() =>
|
||||
evaluatePluginClientBundle("example", item(`id: "Inbox", title: "Inbox", Component: Item`)),
|
||||
).toThrow("Invalid composer pill item id: Inbox");
|
||||
expect(() =>
|
||||
evaluatePluginClientBundle("example", item(`id: "inbox", title: " ", Component: Item`)),
|
||||
).toThrow("Composer pill item inbox has no title");
|
||||
expect(() =>
|
||||
evaluatePluginClientBundle("example", item(`id: "inbox", title: "Inbox", Component: "Item"`)),
|
||||
).toThrow("Composer pill item inbox is not a component");
|
||||
});
|
||||
|
||||
it("expands the addSurface and addSidebarItem aliases to a screen and a legacy header item", () => {
|
||||
const plugin = evaluatePluginClientBundle(
|
||||
"example",
|
||||
@@ -475,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(
|
||||
@@ -798,10 +874,10 @@ describe("evaluatePluginClientBundle", () => {
|
||||
const plugin = evaluatePluginClientBundle(
|
||||
"example",
|
||||
`(function(require) {
|
||||
const { Icon, ProviderIcon, Modal, useToast, SettingsSection, SidebarRow, StreamedText } = require("@getpaseo/plugin/client/ui");
|
||||
const { Icon, ProviderIcon, Modal, useToast, SettingsSection, SidebarRow, ComposerPill, StreamedText } = require("@getpaseo/plugin/client/ui");
|
||||
const module = { exports: {} };
|
||||
module.exports.default = function(plugin) {
|
||||
if (typeof Icon !== "function" || typeof ProviderIcon !== "function" || typeof Modal !== "function" || typeof Modal.Content !== "function" || typeof useToast !== "function" || typeof SettingsSection !== "function" || typeof SidebarRow !== "function" || typeof StreamedText !== "function") {
|
||||
if (typeof Icon !== "function" || typeof ProviderIcon !== "function" || typeof Modal !== "function" || typeof Modal.Content !== "function" || typeof useToast !== "function" || typeof SettingsSection !== "function" || typeof SidebarRow !== "function" || typeof ComposerPill !== "function" || typeof StreamedText !== "function") {
|
||||
throw new Error("React Native plugin UI is incomplete");
|
||||
}
|
||||
plugin.addSurface("main", function Surface() { return null; });
|
||||
|
||||
@@ -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,
|
||||
@@ -39,6 +40,7 @@ import type {
|
||||
PluginSidebarItemContribution,
|
||||
PluginWorkspacePanelContribution,
|
||||
PluginWorkspaceRowBadgeItemContribution,
|
||||
PluginComposerPillItemContribution,
|
||||
} from "./types";
|
||||
import type { ComponentType } from "react";
|
||||
import { parsePluginIcon, parseSerializablePluginIcon } from "./icons";
|
||||
@@ -164,6 +166,7 @@ export function runPluginClientBundle(
|
||||
workspaceRowBadgeItems: [],
|
||||
filePanels: [],
|
||||
composerItems: [],
|
||||
composerPillItems: [],
|
||||
newWorkspaceItems: [],
|
||||
workspacePanels: [],
|
||||
commandCenterItems: [],
|
||||
@@ -184,6 +187,7 @@ export function runPluginClientBundle(
|
||||
const workspaceRowItemIds = new Set<string>();
|
||||
const filePanelIds = new Set<string>();
|
||||
const composerItemIds = new Set<string>();
|
||||
const composerPillItemIds = new Set<string>();
|
||||
const newWorkspaceItemIds = new Set<string>();
|
||||
const workspacePanelIds = new Set<string>();
|
||||
const commandCenterItemIds = new Set<string>();
|
||||
@@ -252,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}`);
|
||||
@@ -263,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 = {
|
||||
@@ -322,6 +357,22 @@ export function runPluginClientBundle(
|
||||
() => composerItemIds.delete(normalizedId),
|
||||
);
|
||||
},
|
||||
addComposerPillItem(contribution: PluginComposerPillItemContribution) {
|
||||
const itemId = requireId(contribution.id, "composer pill item id");
|
||||
if (composerPillItemIds.has(itemId))
|
||||
throw new Error(`Duplicate composer pill item: ${itemId}`);
|
||||
const title = normalizePluginText(contribution.title);
|
||||
if (!title) throw new Error(`Composer pill item ${itemId} has no title`);
|
||||
if (!isComponentType(contribution.Component)) {
|
||||
throw new Error(`Composer pill item ${itemId} is not a component`);
|
||||
}
|
||||
composerPillItemIds.add(itemId);
|
||||
return register(
|
||||
collector.composerPillItems,
|
||||
{ id: itemId, title, Component: contribution.Component },
|
||||
() => composerPillItemIds.delete(itemId),
|
||||
);
|
||||
},
|
||||
addNewWorkspaceItem(contribution) {
|
||||
const normalizedId = requireId(contribution.id, "New workspace item id");
|
||||
if (newWorkspaceItemIds.has(normalizedId))
|
||||
@@ -441,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");
|
||||
@@ -690,6 +755,7 @@ export function runPluginClientBundle(
|
||||
workspaceRowBadgeItems: collector.workspaceRowBadgeItems,
|
||||
filePanels: collector.filePanels,
|
||||
composerItems: collector.composerItems,
|
||||
composerPillItems: collector.composerPillItems,
|
||||
newWorkspaceItems: collector.newWorkspaceItems,
|
||||
workspacePanels: collector.workspacePanels as EvaluatedPlugin["workspacePanels"],
|
||||
commandCenterItems: collector.commandCenterItems,
|
||||
|
||||
@@ -61,6 +61,7 @@ function makePlugin(serverId: string): InstalledPlugin {
|
||||
workspaceRowBadgeItems: [],
|
||||
filePanels: [],
|
||||
composerItems: [],
|
||||
composerPillItems: [],
|
||||
newWorkspaceItems: [],
|
||||
workspacePanels: [],
|
||||
commandCenterItems: [],
|
||||
|
||||
@@ -4,3 +4,4 @@ export { PluginSurfaceScreen } from "./surface-screen";
|
||||
export { usePluginAttachmentPicker } from "./attachments/picker";
|
||||
export { PluginResourceAttachmentPill } from "./attachments/pill";
|
||||
export { PluginComposerPills, PluginHeaderButtons, usePluginWorkspaceMenu } from "./buttons/view";
|
||||
export { PluginComposerPillItems } from "./composer-pill-items";
|
||||
|
||||
@@ -63,6 +63,7 @@ function installation(invoked: string[]): InstalledPlugin {
|
||||
workspaceRowBadgeItems: [],
|
||||
filePanels: [],
|
||||
composerItems: [],
|
||||
composerPillItems: [],
|
||||
newWorkspaceItems: [],
|
||||
workspacePanels: [],
|
||||
commandCenterItems: [],
|
||||
|
||||
@@ -0,0 +1,136 @@
|
||||
import type {
|
||||
PluginAgentPanelProps,
|
||||
PluginFilePanelProps,
|
||||
PluginOpenScreenInput,
|
||||
PluginScreenProps,
|
||||
PluginWorkspacePanelProps,
|
||||
} from "@getpaseo/plugin/client";
|
||||
import { PluginTranslationRuntime } from "@getpaseo/plugin/client/host";
|
||||
import { QueryClient } from "@tanstack/react-query";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import type { BuiltinFilePanelProps } from "@/file-panels/panels";
|
||||
import { openPluginScreen } from "./navigation";
|
||||
import type { InstalledPlugin } from "./types";
|
||||
|
||||
function createTestPlugin(screenIds: readonly string[]): InstalledPlugin {
|
||||
return {
|
||||
id: "review",
|
||||
serverId: "host-a",
|
||||
clientBundle: "",
|
||||
lifetime: new AbortController(),
|
||||
locale: "en",
|
||||
i18n: new PluginTranslationRuntime({ getLocale: () => "en", subscribe: () => () => {} }),
|
||||
queryClient: new QueryClient(),
|
||||
paseo: {} as InstalledPlugin["paseo"],
|
||||
invoke: async () => undefined,
|
||||
subscribe: () => {
|
||||
throw new Error("Subscriptions are not used here");
|
||||
},
|
||||
cleanup: () => undefined,
|
||||
settingsScreens: [],
|
||||
surfaces: screenIds.map((id) => ({ id, title: id, Component: () => null })),
|
||||
sidebarViews: [],
|
||||
sidebarItems: { header: [], footer: [] },
|
||||
legacySidebarItems: [],
|
||||
workspaceRowBadgeItems: [],
|
||||
filePanels: [],
|
||||
composerItems: [],
|
||||
composerPillItems: [],
|
||||
newWorkspaceItems: [],
|
||||
workspacePanels: [],
|
||||
commandCenterItems: [],
|
||||
clientSlashCommands: [],
|
||||
attachmentSources: [],
|
||||
themes: [],
|
||||
timelineTransformers: [],
|
||||
timelineRenderers: [],
|
||||
notificationOpenHandlers: [],
|
||||
};
|
||||
}
|
||||
|
||||
describe("openPluginScreen", () => {
|
||||
it("validates screen input, runs beforeNavigate, remembers the host, and pushes the route", () => {
|
||||
const plugin = createTestPlugin(["main", "details"]);
|
||||
const events: string[] = [];
|
||||
|
||||
openPluginScreen({
|
||||
plugin,
|
||||
screen: { screenId: "details", params: { itemId: "42", tab: "diff" } },
|
||||
beforeNavigate: () => events.push("beforeNavigate"),
|
||||
rememberHost: (contributionId, serverId) =>
|
||||
events.push(`remember:${contributionId}:${serverId}`),
|
||||
navigate: (route) => events.push(`navigate:${route}`),
|
||||
});
|
||||
|
||||
expect(events).toEqual([
|
||||
"beforeNavigate",
|
||||
"remember:review/screens:host-a",
|
||||
"navigate:/h/host-a/plugin/review/surface/details?param.itemId=42¶m.tab=diff",
|
||||
]);
|
||||
});
|
||||
|
||||
it("opens screens without params", () => {
|
||||
const plugin = createTestPlugin(["main"]);
|
||||
const routes: string[] = [];
|
||||
|
||||
openPluginScreen({
|
||||
plugin,
|
||||
screen: { screenId: "main" },
|
||||
rememberHost: () => undefined,
|
||||
navigate: (route) => routes.push(route),
|
||||
});
|
||||
|
||||
expect(routes).toEqual(["/h/host-a/plugin/review/surface/main"]);
|
||||
});
|
||||
|
||||
it("rejects unknown screens and invalid inputs before navigating or remembering host", () => {
|
||||
const plugin = createTestPlugin(["main"]);
|
||||
const sideEffects: string[] = [];
|
||||
const call = (screen: unknown) =>
|
||||
openPluginScreen({
|
||||
plugin,
|
||||
screen: screen as PluginOpenScreenInput,
|
||||
beforeNavigate: () => sideEffects.push("beforeNavigate"),
|
||||
rememberHost: () => sideEffects.push("rememberHost"),
|
||||
navigate: () => sideEffects.push("navigate"),
|
||||
});
|
||||
|
||||
expect(() => call({ screenId: "missing" })).toThrow("Plugin screen is unavailable: missing");
|
||||
expect(() => call({ screenId: "main", params: { count: 1 } })).toThrow(
|
||||
"Plugin screen param count must be a string",
|
||||
);
|
||||
expect(() => call("main")).toThrow("openScreen takes { screenId, params? }");
|
||||
expect(sideEffects).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
// Compile-time checks: all plugin panel/screen props include openScreen, while built-in file panels omit it.
|
||||
type _WorkspaceHasOpenScreen = PluginWorkspacePanelProps["openScreen"] extends (
|
||||
input: PluginOpenScreenInput,
|
||||
) => void
|
||||
? true
|
||||
: never;
|
||||
type _AgentHasOpenScreen = PluginAgentPanelProps["openScreen"] extends (
|
||||
input: PluginOpenScreenInput,
|
||||
) => void
|
||||
? true
|
||||
: never;
|
||||
type _FileHasOpenScreen = PluginFilePanelProps["openScreen"] extends (
|
||||
input: PluginOpenScreenInput,
|
||||
) => void
|
||||
? true
|
||||
: never;
|
||||
type _ScreenHasOpenScreen = PluginScreenProps["openScreen"] extends (
|
||||
input: PluginOpenScreenInput,
|
||||
) => void
|
||||
? true
|
||||
: never;
|
||||
type _BuiltinOmitsOpenScreen = "openScreen" extends keyof BuiltinFilePanelProps ? never : true;
|
||||
const _typeChecks: [
|
||||
_WorkspaceHasOpenScreen,
|
||||
_AgentHasOpenScreen,
|
||||
_FileHasOpenScreen,
|
||||
_ScreenHasOpenScreen,
|
||||
_BuiltinOmitsOpenScreen,
|
||||
] = [true, true, true, true, true];
|
||||
void _typeChecks;
|
||||
@@ -1,11 +1,71 @@
|
||||
import { buildPluginSettingsRoute } from "./settings/routes";
|
||||
import { router } from "expo-router";
|
||||
import type { PluginPanelLocation } from "@getpaseo/plugin/client";
|
||||
import { useCallback } from "react";
|
||||
import type {
|
||||
PluginOpenScreenInput,
|
||||
PluginPanelLocation,
|
||||
PluginScreenParams,
|
||||
} from "@getpaseo/plugin/client";
|
||||
import { navigateToWorkspace } from "@/stores/navigation-active-workspace-store";
|
||||
import { useWorkspaceLayoutStore } from "@/stores/workspace-layout-store";
|
||||
import { pluginScreensHostKey, rememberPluginContributionHost } from "./contribution-host";
|
||||
import { buildPluginSurfaceRoute } from "./routes";
|
||||
import { parsePluginOpenScreenInput } from "./surface-contribution";
|
||||
import type { InstalledPlugin } from "./types";
|
||||
import type { PluginNavigation } from "./actions";
|
||||
|
||||
function pushPluginScreenRoute(input: {
|
||||
serverId: string;
|
||||
pluginId: string;
|
||||
screenId: string;
|
||||
params?: PluginScreenParams;
|
||||
navigate?: (route: string) => void;
|
||||
rememberHost?: (contributionId: string, serverId: string) => void;
|
||||
}): void {
|
||||
const {
|
||||
serverId,
|
||||
pluginId,
|
||||
screenId,
|
||||
params,
|
||||
navigate = router.push,
|
||||
rememberHost = rememberPluginContributionHost,
|
||||
} = input;
|
||||
rememberHost(pluginScreensHostKey(pluginId), serverId);
|
||||
navigate(buildPluginSurfaceRoute(serverId, pluginId, { kind: "surface", id: screenId }, params));
|
||||
}
|
||||
|
||||
export function openPluginScreen(input: {
|
||||
plugin: InstalledPlugin;
|
||||
screen: PluginOpenScreenInput;
|
||||
beforeNavigate?: () => void;
|
||||
navigate?: (route: string) => void;
|
||||
rememberHost?: (contributionId: string, serverId: string) => void;
|
||||
}): void {
|
||||
const { plugin, screen, beforeNavigate, navigate, rememberHost } = input;
|
||||
const { screenId, params } = parsePluginOpenScreenInput(plugin, screen);
|
||||
beforeNavigate?.();
|
||||
pushPluginScreenRoute({
|
||||
serverId: plugin.serverId,
|
||||
pluginId: plugin.id,
|
||||
screenId,
|
||||
params,
|
||||
navigate,
|
||||
rememberHost,
|
||||
});
|
||||
}
|
||||
|
||||
export function usePluginOpenScreen(
|
||||
plugin: InstalledPlugin | null,
|
||||
): (input: PluginOpenScreenInput) => void {
|
||||
return useCallback(
|
||||
(screen: PluginOpenScreenInput) => {
|
||||
if (!plugin) throw new Error("Plugin is unavailable");
|
||||
openPluginScreen({ plugin, screen });
|
||||
},
|
||||
[plugin],
|
||||
);
|
||||
}
|
||||
|
||||
export function createPluginNavigation(input: {
|
||||
serverId: string;
|
||||
workspaceId: string | null;
|
||||
@@ -24,25 +84,38 @@ export function createPluginNavigation(input: {
|
||||
router.push(buildPluginSettingsRoute(serverId, pluginId, screenId));
|
||||
},
|
||||
openSurface(pluginId, surfaceId, params) {
|
||||
router.push(
|
||||
buildPluginSurfaceRoute(serverId, pluginId, { kind: "surface", id: 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),
|
||||
});
|
||||
},
|
||||
|
||||
@@ -89,6 +89,7 @@ function makeInstalledPlugin(input: {
|
||||
workspaceRowBadgeItems: [],
|
||||
filePanels: [],
|
||||
composerItems: [],
|
||||
composerPillItems: [],
|
||||
newWorkspaceItems: [],
|
||||
workspacePanels: [],
|
||||
commandCenterItems: [],
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import type { ReactNode } from "react";
|
||||
import { useCallback, type ReactNode, type RefObject } from "react";
|
||||
import { View } from "react-native";
|
||||
import { StyleSheet } from "react-native-unistyles";
|
||||
import { MenuSurface, type MenuSurfaceProps } from "@/components/ui/menu";
|
||||
import { MenuSurface, useMenuContext, type MenuSurfaceProps } from "@/components/ui/menu";
|
||||
import { ToastApiProvider, type useToast } from "@/contexts/toast-context";
|
||||
import type { createPluginClientStateSource } from "./client-state/source";
|
||||
import { PluginInstallationProvider } from "./installation-provider";
|
||||
@@ -53,6 +53,43 @@ export function PluginPopoverContent({ children }: { children: ReactNode }) {
|
||||
return <View style={styles.content}>{children}</View>;
|
||||
}
|
||||
|
||||
function assignRef(ref: RefObject<View | null>, node: View | null) {
|
||||
Object.assign(ref, { current: node });
|
||||
}
|
||||
|
||||
/**
|
||||
* Shared popover anchor plumbing for declarative plugin item slots (`SidebarRow`, `ComposerPill`).
|
||||
* `anchorTo` moves the anchor to the pressed element; `offerAnchor` sets it only when nothing is
|
||||
* anchored; `releaseAnchor` drops a departing element; `anchorToFallback` covers items with none.
|
||||
*/
|
||||
export function usePluginPopoverAnchor(name: string): {
|
||||
triggerRef: RefObject<View | null>;
|
||||
anchorTo: (node: View | null) => void;
|
||||
offerAnchor: (node: View | null) => void;
|
||||
releaseAnchor: (node: View | null) => void;
|
||||
anchorToFallback: (fallback: RefObject<View | null>) => void;
|
||||
} {
|
||||
const { triggerRef } = useMenuContext(name);
|
||||
const anchorTo = useCallback((node: View | null) => assignRef(triggerRef, node), [triggerRef]);
|
||||
const offerAnchor = useCallback(
|
||||
(node: View | null) => {
|
||||
if (!triggerRef.current) assignRef(triggerRef, node);
|
||||
},
|
||||
[triggerRef],
|
||||
);
|
||||
const releaseAnchor = useCallback(
|
||||
(node: View | null) => {
|
||||
if (triggerRef.current === node) assignRef(triggerRef, null);
|
||||
},
|
||||
[triggerRef],
|
||||
);
|
||||
const anchorToFallback = useCallback(
|
||||
(fallback: RefObject<View | null>) => offerAnchor(fallback.current),
|
||||
[offerAnchor],
|
||||
);
|
||||
return { triggerRef, anchorTo, offerAnchor, releaseAnchor, anchorToFallback };
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create((theme) => ({
|
||||
content: { padding: theme.spacing[3], gap: theme.spacing[2] },
|
||||
}));
|
||||
|
||||
@@ -156,6 +156,7 @@ function createInstalledPlugin(serverId: string): InstalledPlugin {
|
||||
workspaceRowBadgeItems: [],
|
||||
filePanels: [],
|
||||
composerItems: [],
|
||||
composerPillItems: [],
|
||||
newWorkspaceItems: [],
|
||||
workspacePanels: [],
|
||||
commandCenterItems: [],
|
||||
|
||||
@@ -11,6 +11,7 @@ export {
|
||||
export { ExternalLink } from "@/components/ui/external-link";
|
||||
|
||||
export { SidebarRow, SidebarSeparator } from "@/plugins/sidebar-items/kit";
|
||||
export { ComposerPill } from "@/plugins/composer-pill-items/kit";
|
||||
export { WorkspaceRowBadge } from "@/plugins/workspace-row-badge-items/kit";
|
||||
|
||||
export { DocumentFrame } from "@/file-panels/document-frame";
|
||||
|
||||
@@ -233,6 +233,7 @@ export class PluginRegistry {
|
||||
workspaceRowBadgeItems: [],
|
||||
filePanels: [],
|
||||
composerItems: [],
|
||||
composerPillItems: [],
|
||||
newWorkspaceItems: [],
|
||||
workspacePanels: [],
|
||||
commandCenterItems: [],
|
||||
|
||||
@@ -40,6 +40,7 @@ function installed(
|
||||
workspaceRowBadgeItems: [],
|
||||
filePanels: [],
|
||||
composerItems: [],
|
||||
composerPillItems: [],
|
||||
newWorkspaceItems: [],
|
||||
workspacePanels: [],
|
||||
commandCenterItems: [],
|
||||
|
||||
@@ -6,7 +6,7 @@ import type {
|
||||
PluginSidebarItemProps,
|
||||
} from "@getpaseo/plugin/client";
|
||||
import type { PluginTheme } from "@getpaseo/plugin";
|
||||
import { router, useGlobalSearchParams, usePathname } from "expo-router";
|
||||
import { useGlobalSearchParams, usePathname } from "expo-router";
|
||||
import { useCallback, useMemo, useState, type ComponentType, type RefObject } from "react";
|
||||
import { type View } from "react-native";
|
||||
import { withUnistyles } from "react-native-unistyles";
|
||||
@@ -20,19 +20,19 @@ import { useToast } from "@/contexts/toast-context";
|
||||
import { useHostRuntimeClient, useHosts } from "@/runtime/host-runtime";
|
||||
import type { Theme } from "@/styles/theme";
|
||||
import { createPluginClientStateSource } from "../client-state/source";
|
||||
import { pluginScreensHostKey, rememberPluginContributionHost } from "../contribution-host";
|
||||
import { openPluginScreen } from "../navigation";
|
||||
import {
|
||||
PluginEnvironmentProvider,
|
||||
PluginPopoverContent,
|
||||
type PluginEnvironment,
|
||||
} from "../popover";
|
||||
import { buildPluginSurfaceRoute, hostIdFromPathname } from "../routes";
|
||||
import { hostIdFromPathname } from "../routes";
|
||||
import {
|
||||
selectPluginSidebarTarget,
|
||||
type PluginSidebarGroup,
|
||||
type PluginSidebarTarget,
|
||||
} from "../sidebar-groups";
|
||||
import { currentPluginScreen, parsePluginOpenScreenInput } from "../surface-contribution";
|
||||
import { currentPluginScreen } from "../surface-contribution";
|
||||
import { SurfaceErrorBoundary } from "../surface-error-boundary";
|
||||
import { toPluginTheme } from "../theme";
|
||||
import type { PluginSidebarSection } from "../types";
|
||||
@@ -178,19 +178,15 @@ function SidebarItemContent({
|
||||
[compact, hostLabel, plugin.serverId, theme],
|
||||
);
|
||||
const openScreen = useCallback(
|
||||
(input: PluginOpenScreenInput) => {
|
||||
const { screenId, params } = parsePluginOpenScreenInput(plugin, input);
|
||||
rememberPluginContributionHost(pluginScreensHostKey(plugin.id), plugin.serverId);
|
||||
showPopover(null);
|
||||
onBeforeNavigate?.();
|
||||
router.push(
|
||||
buildPluginSurfaceRoute(
|
||||
plugin.serverId,
|
||||
plugin.id,
|
||||
{ kind: "surface", id: screenId },
|
||||
params,
|
||||
),
|
||||
);
|
||||
(screen: PluginOpenScreenInput) => {
|
||||
openPluginScreen({
|
||||
plugin,
|
||||
screen,
|
||||
beforeNavigate() {
|
||||
showPopover(null);
|
||||
onBeforeNavigate?.();
|
||||
},
|
||||
});
|
||||
},
|
||||
[onBeforeNavigate, plugin, showPopover],
|
||||
);
|
||||
|
||||
@@ -59,6 +59,7 @@ function installation(
|
||||
})),
|
||||
filePanels: [],
|
||||
composerItems: [],
|
||||
composerPillItems: [],
|
||||
newWorkspaceItems: [],
|
||||
workspacePanels: [],
|
||||
commandCenterItems: [],
|
||||
|
||||
@@ -25,6 +25,7 @@ import {
|
||||
import type { Theme } from "@/styles/theme";
|
||||
import type { ShortcutKey } from "@/utils/format-shortcut";
|
||||
import { usePluginHostNavigation } from "./host-navigation";
|
||||
import { usePluginOpenScreen } from "./navigation";
|
||||
import { PluginIconView } from "./icons";
|
||||
import { toPluginTheme } from "./theme";
|
||||
import { pluginExecutionApprovals, usePluginExecutionDecision } from "./execution-approval";
|
||||
@@ -123,9 +124,17 @@ function SurfaceRenderer({
|
||||
theme: PluginTheme;
|
||||
}) {
|
||||
const navigation = usePluginHostNavigation(host.id);
|
||||
const openScreen = usePluginOpenScreen(plugin);
|
||||
return (
|
||||
<PluginInstallationProvider plugin={plugin}>
|
||||
<Surface theme={theme} host={host} layout={layout} navigation={navigation} params={params} />
|
||||
<Surface
|
||||
theme={theme}
|
||||
host={host}
|
||||
layout={layout}
|
||||
navigation={navigation}
|
||||
params={params}
|
||||
openScreen={openScreen}
|
||||
/>
|
||||
</PluginInstallationProvider>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -73,6 +73,7 @@ function installed(serverId: string, themes: PluginThemeContribution[]): Install
|
||||
workspaceRowBadgeItems: [],
|
||||
filePanels: [],
|
||||
composerItems: [],
|
||||
composerPillItems: [],
|
||||
newWorkspaceItems: [],
|
||||
workspacePanels: [],
|
||||
commandCenterItems: [],
|
||||
|
||||
@@ -30,6 +30,7 @@ function plugin(input: {
|
||||
workspaceRowBadgeItems: [],
|
||||
filePanels: [],
|
||||
composerItems: [],
|
||||
composerPillItems: [],
|
||||
newWorkspaceItems: [],
|
||||
workspacePanels: [],
|
||||
commandCenterItems: [],
|
||||
|
||||
@@ -8,12 +8,15 @@ import type {
|
||||
PluginThemeContribution as SDKPluginThemeContribution,
|
||||
} from "@getpaseo/plugin";
|
||||
import type {
|
||||
PluginAgentPanelParams,
|
||||
PluginAgentPanelProps,
|
||||
PluginFilePanelContribution as SDKPluginFilePanelContribution,
|
||||
PluginCommandCenterItemContribution as SDKPluginCommandCenterItemContribution,
|
||||
PluginClientSlashCommandContribution as SDKPluginClientSlashCommandContribution,
|
||||
PluginComposerItemContribution,
|
||||
PluginNewWorkspaceItemContribution,
|
||||
PluginComposerPillContribution as SDKPluginComposerPillContribution,
|
||||
PluginComposerPillItemContribution as SDKPluginComposerPillItemContribution,
|
||||
PluginSidebarContribution as SDKPluginSidebarContribution,
|
||||
PluginSidebarViewContribution,
|
||||
PluginSidebarItemContribution as SDKPluginSidebarItemContribution,
|
||||
@@ -23,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>;
|
||||
@@ -33,16 +40,34 @@ type PluginThemeContribution = SDKPluginThemeContribution<PluginText>;
|
||||
type PluginCommandCenterItemContribution = SDKPluginCommandCenterItemContribution<PluginText>;
|
||||
type PluginClientSlashCommandContribution = SDKPluginClientSlashCommandContribution<PluginText>;
|
||||
type PluginComposerPillContribution = SDKPluginComposerPillContribution<PluginText>;
|
||||
type PluginComposerPillItemContribution = SDKPluginComposerPillItemContribution<PluginText>;
|
||||
type PluginSidebarContribution = SDKPluginSidebarContribution<PluginText>;
|
||||
type PluginSidebarItemContribution = SDKPluginSidebarItemContribution<PluginText>;
|
||||
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";
|
||||
|
||||
@@ -63,6 +88,7 @@ export interface EvaluatedPlugin {
|
||||
workspaceRowBadgeItems: PluginWorkspaceRowBadgeItemContribution[];
|
||||
filePanels: PluginFilePanelContribution[];
|
||||
composerItems: PluginComposerItemContribution[];
|
||||
composerPillItems: PluginComposerPillItemContribution[];
|
||||
newWorkspaceItems: PluginNewWorkspaceItemContribution[];
|
||||
workspacePanels: EvaluatedPluginWorkspacePanelContribution[];
|
||||
commandCenterItems: PluginCommandCenterItemContribution[];
|
||||
@@ -99,6 +125,7 @@ export type {
|
||||
PluginComposerItemContribution,
|
||||
PluginNewWorkspaceItemContribution,
|
||||
PluginComposerPillContribution,
|
||||
PluginComposerPillItemContribution,
|
||||
PluginSidebarContribution,
|
||||
PluginSidebarItemContribution,
|
||||
PluginWorkspaceRowBadgeItemContribution,
|
||||
@@ -108,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() {};
|
||||
@@ -344,6 +344,30 @@ describe("reading the layout", () => {
|
||||
expect(events).toHaveLength(2);
|
||||
});
|
||||
|
||||
it("reflects dynamic tab title overrides and resets to static title when cleared", () => {
|
||||
const layout = handle();
|
||||
const { tabId } = layout.open({ panelId: "overview" });
|
||||
const events: unknown[] = [];
|
||||
const unsubscribe = layout.subscribe((event) => events.push(event));
|
||||
expect(tab(layout, tabId).title).toBe("overview");
|
||||
|
||||
setPanelInstanceAttributes(
|
||||
{ serverId: SERVER_ID, workspaceId: WORKSPACE_ID, tabId },
|
||||
{ modified: false, title: "Overview (3)" },
|
||||
);
|
||||
expect(tab(layout, tabId).title).toBe("Overview (3)");
|
||||
expect(events).toEqual([{ type: "changed" }]);
|
||||
|
||||
setPanelInstanceAttributes(
|
||||
{ serverId: SERVER_ID, workspaceId: WORKSPACE_ID, tabId },
|
||||
{ modified: false },
|
||||
);
|
||||
expect(tab(layout, tabId).title).toBe("overview");
|
||||
expect(events).toHaveLength(2);
|
||||
|
||||
unsubscribe();
|
||||
});
|
||||
|
||||
it("hands out one handle per workspace", () => {
|
||||
expect(handle()).toBe(handle());
|
||||
expect(handle().workspaceId).toBe(WORKSPACE_ID);
|
||||
@@ -1081,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 };
|
||||
|
||||
@@ -82,12 +82,13 @@ function toPane(pane: SplitPane, kind: PluginPane["kind"]): PluginPane {
|
||||
}
|
||||
|
||||
function toTab(workspace: Workspace, { tab, paneId }: OpenTab): PluginLayoutTab {
|
||||
const attributes = getWorkspacePanelAttributes(workspace.key, tab.tabId);
|
||||
return {
|
||||
id: tab.tabId,
|
||||
paneId,
|
||||
...describePanel(tab.target),
|
||||
...describePanel(workspace.serverId, tab.target),
|
||||
locations: panelLocations(workspace.serverId, tab.target),
|
||||
title: readTabTitle({ ...workspace, target: tab.target }),
|
||||
modified: getWorkspacePanelAttributes(workspace.key, tab.tabId).modified,
|
||||
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");
|
||||
});
|
||||
});
|
||||
@@ -1,12 +1,13 @@
|
||||
import { usePublishPanelInstanceAttributes } from "@/panels/panel-instance-attributes";
|
||||
import { getComponentMountKey, usePanelTab } from "@/panels/panel-instance-attributes";
|
||||
import type {
|
||||
PluginAgentPanelProps,
|
||||
PluginHostProps,
|
||||
PluginPanelTargetParams,
|
||||
PluginWorkspacePanelProps,
|
||||
PluginTab,
|
||||
} from "@getpaseo/plugin/client";
|
||||
import type { PluginTheme } from "@getpaseo/plugin";
|
||||
import { CircleAlert } from "lucide-react-native";
|
||||
import { useMemo, useState } from "react";
|
||||
import { useMemo } from "react";
|
||||
import { Text, View } from "react-native";
|
||||
import { StyleSheet, withUnistyles } from "react-native-unistyles";
|
||||
import invariant from "tiny-invariant";
|
||||
@@ -18,35 +19,146 @@ import { useSessionStore } from "@/stores/session-store";
|
||||
import { useWorkspaceExists } from "@/stores/session-store-hooks";
|
||||
import type { Theme } from "@/styles/theme";
|
||||
import { normalizeWorkspaceOpaqueId } from "@/utils/workspace-identity";
|
||||
import type { PluginWorkspaceTabTarget } from "@/workspace-tabs/model";
|
||||
import { usePluginHostNavigation } from "../host-navigation";
|
||||
import { usePluginOpenScreen } from "../navigation";
|
||||
import { toPluginTheme } from "../theme";
|
||||
import { pluginIconComponent } from "../icons";
|
||||
import { useInstalledPlugin } from "../registry";
|
||||
import { PluginInstallationProvider } from "../installation-provider";
|
||||
import { SurfaceErrorBoundary } from "../surface-error-boundary";
|
||||
import { resolvePluginWorkspacePanel } from "./resolution";
|
||||
import type { EvaluatedPluginWorkspacePanelContribution } from "../types";
|
||||
import {
|
||||
parseRegisteredPluginPanelParams,
|
||||
resolvePluginWorkspacePanel,
|
||||
type ParsedPluginPanelParams,
|
||||
} from "./resolution";
|
||||
import { resolvePluginPlatform } from "../platform";
|
||||
|
||||
const pluginThemeMapping = (theme: Theme) => ({
|
||||
theme: toPluginTheme(theme),
|
||||
});
|
||||
|
||||
function PluginPanelBody({ theme }: { theme: PluginTheme }) {
|
||||
const {
|
||||
serverId,
|
||||
workspaceId,
|
||||
tabId,
|
||||
target,
|
||||
state: tabState,
|
||||
setCurrentTabState,
|
||||
panelRevision,
|
||||
} = usePaneContext();
|
||||
const [modified, setModified] = useState(false);
|
||||
usePublishPanelInstanceAttributes({ modified });
|
||||
const tab = useMemo<PluginTab>(
|
||||
() => ({ id: tabId, state: tabState, setState: setCurrentTabState, setModified }),
|
||||
[tabId, tabState, setCurrentTabState],
|
||||
function MountedPluginPanel({
|
||||
contribution,
|
||||
parsed,
|
||||
theme,
|
||||
host,
|
||||
layout,
|
||||
navigation,
|
||||
openScreen,
|
||||
workspaceId,
|
||||
revision,
|
||||
}: {
|
||||
contribution: EvaluatedPluginWorkspacePanelContribution;
|
||||
parsed: Extract<ParsedPluginPanelParams, { ok: true }>;
|
||||
theme: PluginTheme;
|
||||
host: PluginHostProps["host"];
|
||||
layout: PluginHostProps["layout"];
|
||||
navigation: PluginWorkspacePanelProps["navigation"];
|
||||
openScreen: PluginWorkspacePanelProps["openScreen"];
|
||||
workspaceId: string;
|
||||
revision: number;
|
||||
}) {
|
||||
const tab = usePanelTab();
|
||||
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<PluginPanelTargetParams> = {
|
||||
// COMPAT(pluginPanelFlatProps): added in v0.13.0, remove after 2027-04-23
|
||||
context: "workspace",
|
||||
params: workspaceParams,
|
||||
revision,
|
||||
tab,
|
||||
theme,
|
||||
host,
|
||||
layout,
|
||||
navigation,
|
||||
openScreen,
|
||||
workspaceId,
|
||||
};
|
||||
const Component = contribution.Component;
|
||||
return <Component {...props} />;
|
||||
}
|
||||
|
||||
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,
|
||||
revision,
|
||||
tab,
|
||||
theme,
|
||||
host,
|
||||
layout,
|
||||
navigation,
|
||||
openScreen,
|
||||
workspaceId,
|
||||
// COMPAT(pluginPanelFlatProps): added in v0.13.0, remove after 2027-04-23
|
||||
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");
|
||||
const plugin = useInstalledPlugin(serverId, target.pluginId);
|
||||
const contribution = resolvePluginWorkspacePanel(plugin, target);
|
||||
@@ -67,6 +179,7 @@ function PluginPanelBody({ theme }: { theme: PluginTheme }) {
|
||||
const host = useMemo(() => ({ id: serverId, label: hostLabel }), [hostLabel, serverId]);
|
||||
const layout = useMemo(() => ({ compact, platform: resolvePluginPlatform() }), [compact]);
|
||||
const navigation = usePluginHostNavigation(serverId);
|
||||
const openScreen = usePluginOpenScreen(plugin);
|
||||
|
||||
if (!plugin || !contribution || !workspaceExists) {
|
||||
return <PluginPanelUnavailable />;
|
||||
@@ -74,54 +187,29 @@ function PluginPanelBody({ theme }: { theme: PluginTheme }) {
|
||||
if (!client) {
|
||||
return <PluginPanelUnavailable message="Plugin host is offline." />;
|
||||
}
|
||||
|
||||
let panel;
|
||||
let Surface: unknown;
|
||||
if (contribution.context === "workspace") {
|
||||
const props: PluginWorkspacePanelProps = {
|
||||
// COMPAT(pluginPanelFlatProps): added in v0.13.0, remove after 2027-04-23
|
||||
context: "workspace",
|
||||
params: {},
|
||||
revision: panelRevision ?? 0,
|
||||
tab,
|
||||
theme,
|
||||
host,
|
||||
layout,
|
||||
navigation,
|
||||
workspaceId,
|
||||
};
|
||||
const Component = contribution.Component;
|
||||
Surface = Component;
|
||||
panel = <Component {...props} />;
|
||||
} else if (agentExists && target.context === "agent") {
|
||||
const props: PluginAgentPanelProps = {
|
||||
// COMPAT(pluginPanelFlatProps): added in v0.13.0, remove after 2027-04-23
|
||||
context: "agent",
|
||||
params: { agentId: target.agentId },
|
||||
revision: panelRevision ?? 0,
|
||||
tab,
|
||||
theme,
|
||||
host,
|
||||
layout,
|
||||
navigation,
|
||||
workspaceId,
|
||||
// COMPAT(pluginPanelFlatProps): added in v0.13.0, remove after 2027-04-23
|
||||
agentId: target.agentId,
|
||||
};
|
||||
const Component = contribution.Component;
|
||||
Surface = Component;
|
||||
panel = <Component {...props} />;
|
||||
} else {
|
||||
if (contribution.context === "agent" && !agentExists) {
|
||||
return <PluginPanelUnavailable />;
|
||||
}
|
||||
|
||||
return (
|
||||
<SurfaceErrorBoundary
|
||||
installation={plugin}
|
||||
Surface={Surface}
|
||||
Surface={contribution.Component}
|
||||
key={`${serverId}/${target.pluginId}/${target.panelId}/${target.context}`}
|
||||
>
|
||||
<PluginInstallationProvider plugin={plugin}>{panel}</PluginInstallationProvider>
|
||||
<PluginInstallationProvider plugin={plugin}>
|
||||
<ValidatedPluginPanel
|
||||
contribution={contribution}
|
||||
target={target}
|
||||
theme={theme}
|
||||
host={host}
|
||||
layout={layout}
|
||||
navigation={navigation}
|
||||
openScreen={openScreen}
|
||||
workspaceId={workspaceId}
|
||||
revision={panelRevision ?? 0}
|
||||
/>
|
||||
</PluginInstallationProvider>
|
||||
</SurfaceErrorBoundary>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -27,6 +27,7 @@ function installed(): InstalledPlugin {
|
||||
workspaceRowBadgeItems: [],
|
||||
filePanels: [],
|
||||
composerItems: [],
|
||||
composerPillItems: [],
|
||||
newWorkspaceItems: [],
|
||||
workspacePanels: [
|
||||
{
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { workspaceTabSwitcherPopoverLayout } from "../workspace-tab-layout";
|
||||
import { memo, useCallback, useMemo, useRef, useState } from "react";
|
||||
import { memo, useCallback, useMemo, useRef, useState, type ReactElement } from "react";
|
||||
import { Keyboard, Pressable, Text, View } from "react-native";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { SquarePen, SquareTerminal } from "lucide-react-native";
|
||||
@@ -12,11 +12,12 @@ import {
|
||||
WorkspaceTabOptionRow,
|
||||
type WorkspaceTabPresentation,
|
||||
} from "@/screens/workspace/workspace-tab-presentation";
|
||||
import { useFilePanelOpenWithMenu } from "@/file-panels";
|
||||
import { useFilePanelOpenWithMenu, type FilePanelOpenWithMenu } from "@/file-panels";
|
||||
import { useFileTabMenu } from "@/screens/workspace/use-file-tab-menu";
|
||||
import { MobileTabTrailingAccessory } from "@/screens/workspace/workspace-tab-trailing-accessory";
|
||||
import {
|
||||
buildWorkspaceTabMenuEntries,
|
||||
type WorkspaceTabMenuEntry,
|
||||
type WorkspaceTabMenuLabels,
|
||||
} from "@/screens/workspace/workspace-tab-menu";
|
||||
import type { WorkspaceTabDescriptor } from "@/screens/workspace/workspace-tabs-types";
|
||||
@@ -145,6 +146,52 @@ interface MobileWorkspaceTabSwitcherProps {
|
||||
onCloseOtherTabs: (tabId: string) => Promise<void> | void;
|
||||
}
|
||||
|
||||
function MobileWorkspaceTabOptionRow({
|
||||
presentation,
|
||||
selected,
|
||||
active,
|
||||
onPress,
|
||||
menuTestIDBase,
|
||||
fallbackLabel,
|
||||
menuEntries,
|
||||
openWith,
|
||||
fileMenu,
|
||||
}: {
|
||||
presentation: WorkspaceTabPresentation;
|
||||
selected: boolean;
|
||||
active: boolean;
|
||||
onPress: () => void;
|
||||
menuTestIDBase: string;
|
||||
fallbackLabel: string;
|
||||
menuEntries: WorkspaceTabMenuEntry[];
|
||||
openWith: FilePanelOpenWithMenu;
|
||||
fileMenu: ReactElement | null;
|
||||
}) {
|
||||
const presentationLabel =
|
||||
presentation.titleState === "loading" ? fallbackLabel : presentation.label;
|
||||
const trailingAccessory = useMemo(
|
||||
() => (
|
||||
<MobileTabTrailingAccessory
|
||||
menuTestIDBase={menuTestIDBase}
|
||||
presentationLabel={presentationLabel}
|
||||
menuEntries={menuEntries}
|
||||
openWith={openWith}
|
||||
fileMenu={fileMenu}
|
||||
/>
|
||||
),
|
||||
[fileMenu, menuEntries, menuTestIDBase, openWith, presentationLabel],
|
||||
);
|
||||
return (
|
||||
<WorkspaceTabOptionRow
|
||||
presentation={presentation}
|
||||
selected={selected}
|
||||
active={active}
|
||||
onPress={onPress}
|
||||
trailingAccessory={trailingAccessory}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function MobileWorkspaceTabOption({
|
||||
tab,
|
||||
tabIndex,
|
||||
@@ -247,30 +294,21 @@ function MobileWorkspaceTabOption({
|
||||
testIDBase: menuTestIDBase,
|
||||
onRevealInFiles: onDismissSwitcher,
|
||||
});
|
||||
const trailingAccessory = useMemo(
|
||||
() => (
|
||||
<MobileTabTrailingAccessory
|
||||
const renderPresentation = useCallback(
|
||||
(presentation: WorkspaceTabPresentation) => (
|
||||
<MobileWorkspaceTabOptionRow
|
||||
presentation={presentation}
|
||||
selected={selected}
|
||||
active={active}
|
||||
onPress={onPress}
|
||||
menuTestIDBase={menuTestIDBase}
|
||||
presentationLabel={fallbackLabel}
|
||||
fallbackLabel={fallbackLabel}
|
||||
menuEntries={menuEntries}
|
||||
openWith={openWith}
|
||||
fileMenu={fileMenu}
|
||||
/>
|
||||
),
|
||||
[menuTestIDBase, fallbackLabel, menuEntries, openWith, fileMenu],
|
||||
);
|
||||
|
||||
const renderPresentation = useCallback(
|
||||
(presentation: WorkspaceTabPresentation) => (
|
||||
<WorkspaceTabOptionRow
|
||||
presentation={presentation}
|
||||
selected={selected}
|
||||
active={active}
|
||||
onPress={onPress}
|
||||
trailingAccessory={trailingAccessory}
|
||||
/>
|
||||
),
|
||||
[selected, active, onPress, trailingAccessory],
|
||||
[selected, active, onPress, menuTestIDBase, fallbackLabel, menuEntries, openWith, fileMenu],
|
||||
);
|
||||
|
||||
return (
|
||||
|
||||
@@ -14,6 +14,7 @@ import {
|
||||
import { DropdownMenu, DropdownMenuContent } from "@/components/ui/dropdown-menu";
|
||||
import type { PanelIconProps } from "@/panels/panel-registry";
|
||||
import { getPanelRegistration } from "@/panels/panel-registry";
|
||||
import { usePanelInstanceAttributes } from "@/panels/panel-instance-attributes";
|
||||
import { useViewedAgent } from "@/timeline/use-viewed-agent";
|
||||
import { useWorkspaceDirectory } from "@/stores/session-store-hooks";
|
||||
import type { WorkspaceTabDescriptor } from "@/screens/workspace/workspace-tabs-types";
|
||||
@@ -72,6 +73,12 @@ export function SheetPane({ sheet, onClose, onBack, opener = null, isTop }: Shee
|
||||
workspaceId: host.workspaceId,
|
||||
tabId: tab.tabId,
|
||||
});
|
||||
const attributes = usePanelInstanceAttributes({
|
||||
serverId: host.serverId,
|
||||
workspaceId: host.workspaceId,
|
||||
tabId: tab.tabId,
|
||||
});
|
||||
const title = attributes.title ?? descriptor.label;
|
||||
|
||||
const openTabInFront = useWorkspaceLayoutStore((state) => state.openTabInFront);
|
||||
const { workspaceKey } = host;
|
||||
@@ -82,7 +89,7 @@ export function SheetPane({ sheet, onClose, onBack, opener = null, isTop }: Shee
|
||||
const filePath = tab.target.kind === "file" ? tab.target.path : null;
|
||||
const header = useMemo<SheetHeader>(
|
||||
() => ({
|
||||
title: descriptor.label,
|
||||
title,
|
||||
leading: <ThemedPanelIcon icon={descriptor.icon} size={16} />,
|
||||
back: onBack ? { onPress: onBack } : undefined,
|
||||
// The sheet is for looking; the full-screen glyph takes the tab out of the sheet and into
|
||||
@@ -101,16 +108,7 @@ export function SheetPane({ sheet, onClose, onBack, opener = null, isTop }: Shee
|
||||
</>
|
||||
),
|
||||
}),
|
||||
[
|
||||
descriptor.icon,
|
||||
descriptor.label,
|
||||
filePath,
|
||||
handleOpenAsTab,
|
||||
onBack,
|
||||
onClose,
|
||||
sheet.policy.openAsTab,
|
||||
t,
|
||||
],
|
||||
[descriptor.icon, title, filePath, handleOpenAsTab, onBack, onClose, sheet.policy.openAsTab, t],
|
||||
);
|
||||
|
||||
const tabDescriptor = useMemo<WorkspaceTabDescriptor>(
|
||||
@@ -146,7 +144,7 @@ export function SheetPane({ sheet, onClose, onBack, opener = null, isTop }: Shee
|
||||
<SheetBottomInset
|
||||
style={styles.body}
|
||||
role="dialog"
|
||||
aria-label={descriptor.label}
|
||||
aria-label={title}
|
||||
testID="sheet-tab-body"
|
||||
>
|
||||
<WorkspacePaneContent
|
||||
|
||||
@@ -82,14 +82,16 @@ function WorkspaceTabPresentationResolverInner({
|
||||
(state) => draftKey !== null && hasUnsavedDraft(state, draftKey),
|
||||
);
|
||||
const modified = attributes.modified || draftModified;
|
||||
const label = attributes.title ?? descriptor.label;
|
||||
const tooltip = attributes.title ?? descriptor.tooltip;
|
||||
|
||||
const presentation = useMemo(
|
||||
() => ({
|
||||
key: tab.key,
|
||||
kind: tab.kind,
|
||||
label: descriptor.label,
|
||||
label,
|
||||
subtitle: descriptor.subtitle,
|
||||
tooltip: descriptor.tooltip,
|
||||
tooltip,
|
||||
modified,
|
||||
showCloseButton: registration.showCloseButton,
|
||||
titleState: descriptor.titleState,
|
||||
@@ -98,8 +100,8 @@ function WorkspaceTabPresentationResolverInner({
|
||||
}),
|
||||
[
|
||||
descriptor.icon,
|
||||
descriptor.label,
|
||||
descriptor.tooltip,
|
||||
label,
|
||||
tooltip,
|
||||
descriptor.statusBucket,
|
||||
descriptor.subtitle,
|
||||
descriptor.titleState,
|
||||
|
||||
@@ -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),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -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";
|
||||
|
||||
@@ -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 =
|
||||
|
||||
@@ -199,22 +199,50 @@ describe("plugin panel SDK boundary", () => {
|
||||
it("accepts uniform params and persisted tab state alongside 0.12 panels", () => {
|
||||
expect(
|
||||
typeErrors(`
|
||||
import { type PluginClientContext, type PluginFilePanelProps, type PluginWorkspacePanelProps, type PluginAgentPanelProps, type PluginTab, useTabState } from "@getpaseo/plugin/client";
|
||||
import { type PluginClientContext, type PluginFilePanelProps, type PluginOpenScreenInput, type PluginScreenProps, type PluginWorkspacePanelProps, type PluginAgentPanelProps, type PluginTab, useTabState } from "@getpaseo/plugin/client";
|
||||
import { z } from "zod";
|
||||
function FilePanel({ params, revision, tab, file }: PluginFilePanelProps) {
|
||||
function FilePanel({ params, revision, tab, file, openScreen }: PluginFilePanelProps) {
|
||||
const [state, setState] = useTabState(tab, z.object({ view: z.enum(["preview", "source"]) }), { view: "preview" });
|
||||
setState({ view: "source" });
|
||||
tab.setTitle("Custom file title");
|
||||
tab.setTitle(null);
|
||||
// @ts-expect-error title override must be a string or null
|
||||
tab.setTitle(undefined);
|
||||
// @ts-expect-error title override must be a string or null
|
||||
tab.setTitle(123);
|
||||
tab.setState({ nested: [true, null, 3] });
|
||||
const input: PluginOpenScreenInput = { screenId: "details", params: { path: file.path } };
|
||||
openScreen(input);
|
||||
openScreen({ screenId: "details" });
|
||||
// @ts-expect-error openScreen takes { screenId, params? }
|
||||
openScreen("details");
|
||||
// @ts-expect-error only JSON state crosses the host boundary
|
||||
tab.setState(() => {});
|
||||
// @ts-expect-error params belong to the opener
|
||||
params.path = "other";
|
||||
return null;
|
||||
}
|
||||
function OldWorkspace({ context, workspaceId }: PluginWorkspacePanelProps) { return null; }
|
||||
function OldAgent({ context, workspaceId, agentId }: PluginAgentPanelProps) { return null; }
|
||||
function Agent({ params }: PluginAgentPanelProps) { params.agentId.toUpperCase(); return null; }
|
||||
function OldWorkspace({ context, workspaceId, openScreen }: PluginWorkspacePanelProps) {
|
||||
openScreen({ screenId: "details", params: { workspaceId } });
|
||||
return null;
|
||||
}
|
||||
function OldAgent({ context, workspaceId, agentId, openScreen }: PluginAgentPanelProps) {
|
||||
openScreen({ screenId: "details", params: { agentId } });
|
||||
return null;
|
||||
}
|
||||
function Agent({ params, openScreen }: PluginAgentPanelProps) {
|
||||
params.agentId.toUpperCase();
|
||||
openScreen({ screenId: "details", params: { agentId: params.agentId } });
|
||||
return null;
|
||||
}
|
||||
function Screen({ params, openScreen }: PluginScreenProps) {
|
||||
openScreen({ screenId: "other", params: { from: params.from ?? "screen" } });
|
||||
// @ts-expect-error screen params must be strings
|
||||
openScreen({ screenId: "other", params: { count: 1 } });
|
||||
return null;
|
||||
}
|
||||
function contribute(client: PluginClientContext) {
|
||||
client.addScreen({ id: "details", title: "Details", Component: Screen });
|
||||
client.addWorkspacePanel({ id: "old-workspace", title: "Old", icon: "File", context: "workspace", Component: OldWorkspace });
|
||||
client.addWorkspacePanel({ id: "old-agent", title: "Old", icon: "File", context: "agent", Component: OldAgent });
|
||||
client.addWorkspacePanel({ id: "workspace", title: "Workspace", icon: "File", Component: OldWorkspace });
|
||||
@@ -223,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", () => {
|
||||
@@ -1096,3 +1246,59 @@ describe("agent chat SDK boundary", () => {
|
||||
).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("composer pill item SDK boundary", () => {
|
||||
it("types addComposerPillItem, PluginComposerPillItemProps, and ComposerPill", () => {
|
||||
expect(
|
||||
typeErrors(`
|
||||
import type {
|
||||
PluginClientContext,
|
||||
PluginComposerPillItemContribution,
|
||||
PluginComposerPillItemProps,
|
||||
PluginPopoverProps,
|
||||
} from "@getpaseo/plugin/client";
|
||||
import { ComposerPill, type ComposerPillProps } from "@getpaseo/plugin/client/ui";
|
||||
import { Text } from "react-native";
|
||||
|
||||
function Details({ theme, close, openScreen }: PluginPopoverProps) {
|
||||
openScreen({ screenId: "main", params: { from: "pill" } });
|
||||
close();
|
||||
return <Text style={{ color: theme.colors.foreground }}>Details</Text>;
|
||||
}
|
||||
|
||||
function InboxPill({ workspaceId, agentId, openPopover, openScreen }: PluginComposerPillItemProps) {
|
||||
const props: ComposerPillProps = {
|
||||
icon: "Inbox",
|
||||
label: \`\${workspaceId}:\${agentId}\`,
|
||||
title: "Open inbox",
|
||||
disabled: false,
|
||||
async onPress() {
|
||||
openPopover(Details);
|
||||
},
|
||||
};
|
||||
if (workspaceId === "hidden") return null;
|
||||
if (workspaceId === "screen") {
|
||||
return <ComposerPill icon="ExternalLink" label="Screen" onPress={() => openScreen({ screenId: "main" })} />;
|
||||
}
|
||||
return <ComposerPill {...props} />;
|
||||
}
|
||||
|
||||
export default function contribute(client: PluginClientContext) {
|
||||
const contribution: PluginComposerPillItemContribution = {
|
||||
id: "inbox",
|
||||
title: "Inbox",
|
||||
Component: InboxPill,
|
||||
};
|
||||
const remove: () => void = client.addComposerPillItem(contribution);
|
||||
// @ts-expect-error title is required on composer pill item contribution
|
||||
client.addComposerPillItem({ id: "missing-title", Component: InboxPill });
|
||||
// @ts-expect-error label is required on ComposerPill
|
||||
void (<ComposerPill icon="Inbox" onPress={() => {}} />);
|
||||
// @ts-expect-error onPress is required on ComposerPill
|
||||
void (<ComposerPill icon="Inbox" label="Inbox" />);
|
||||
return remove;
|
||||
}
|
||||
`),
|
||||
).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -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,
|
||||
@@ -95,6 +95,7 @@ export interface PluginSurfaceProps extends PluginNavigableHostProps {}
|
||||
export interface PluginScreenProps extends PluginSurfaceProps {
|
||||
/** The params the screen was opened with; `{}` when none. */
|
||||
params: PluginScreenParams;
|
||||
openScreen(input: PluginOpenScreenInput): void;
|
||||
}
|
||||
|
||||
export interface PluginPopoverProps extends PluginHostProps {
|
||||
@@ -102,6 +103,25 @@ export interface PluginPopoverProps extends PluginHostProps {
|
||||
openScreen(input: PluginOpenScreenInput): void;
|
||||
}
|
||||
|
||||
export interface PluginComposerPillItemProps extends PluginHostProps {
|
||||
workspaceId: string;
|
||||
agentId: string;
|
||||
openScreen(input: PluginOpenScreenInput): void;
|
||||
/** Anchored to the pill on wide layouts; a bottom sheet on compact layouts. */
|
||||
openPopover(Content: ComponentType<PluginPopoverProps>): void;
|
||||
}
|
||||
|
||||
/**
|
||||
* A pill above an agent's composer, mounted for visible agent tabs on the plugin's host.
|
||||
* Render `ComposerPill` from `@getpaseo/plugin/client/ui`, or `null` when there is nothing to show.
|
||||
*/
|
||||
export interface PluginComposerPillItemContribution<Text extends PluginText = string> {
|
||||
id: string;
|
||||
/** Default accessible label and compact sheet title for ComposerPill. */
|
||||
title: Text;
|
||||
Component: ComponentType<PluginComposerPillItemProps>;
|
||||
}
|
||||
|
||||
export interface PluginSidebarItemProps extends PluginHostProps {
|
||||
/** This plugin's screen open on this item's host, with its params, else null. */
|
||||
currentScreen: PluginScreenLocation | null;
|
||||
@@ -180,22 +200,51 @@ 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;
|
||||
/** Shows the tab's unsaved dot and asks before closing. */
|
||||
setModified(modified: boolean): void;
|
||||
/** Opaque persisted JSON. Undefined until written; the panel validates it. */
|
||||
/** Overrides this tab's title while mounted. Pass null or empty string to reset to the static panel title. */
|
||||
setTitle(title: string | null): void;
|
||||
/**
|
||||
* 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;
|
||||
@@ -205,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";
|
||||
@@ -253,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>,
|
||||
@@ -268,6 +351,7 @@ export interface PluginClientContext extends PluginCommandCapabilities, PluginCl
|
||||
addComposerPill(
|
||||
contribution: PluginComposerPillContribution<PluginText>,
|
||||
): PluginButtonRegistration<PluginText>;
|
||||
addComposerPillItem(contribution: PluginComposerPillItemContribution<PluginText>): PluginCleanup;
|
||||
addAttachmentSource(contribution: PluginAttachmentSourceContribution<PluginText>): PluginCleanup;
|
||||
addComposerItem(contribution: PluginComposerItemContribution): PluginCleanup;
|
||||
addNewWorkspaceItem(contribution: PluginNewWorkspaceItemContribution): PluginCleanup;
|
||||
@@ -305,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;
|
||||
|
||||
@@ -3,6 +3,7 @@ export type {
|
||||
PluginHostNavigationActions,
|
||||
PluginTab,
|
||||
PluginPanelProps,
|
||||
PluginPanelParamsSchema,
|
||||
PluginWorkspacePanelParams,
|
||||
PluginAgentPanelParams,
|
||||
PluginFilePanelParams,
|
||||
@@ -19,6 +20,8 @@ export type {
|
||||
PluginSidebarViewProps,
|
||||
PluginSidebarViewContribution,
|
||||
PluginSidebarItemContribution,
|
||||
PluginComposerPillItemProps,
|
||||
PluginComposerPillItemContribution,
|
||||
PluginWorkspaceRowBadgeItemProps,
|
||||
PluginWorkspaceRowBadgeItemContribution,
|
||||
PluginIcon,
|
||||
|
||||
@@ -189,6 +189,18 @@ export interface WorkspaceRowBadgeProps {
|
||||
/** One item on a sidebar workspace row's meta line. Render it from a workspace row badge item's `Component`. */
|
||||
export declare const WorkspaceRowBadge: ComponentType<WorkspaceRowBadgeProps>;
|
||||
|
||||
export interface ComposerPillProps {
|
||||
/** A Lucide icon name, inline SVG, or a component. */
|
||||
icon: PluginIcon;
|
||||
label: string;
|
||||
/** Accessible label and tooltip. Defaults to `label`. */
|
||||
title?: string;
|
||||
disabled?: boolean;
|
||||
onPress(): void | Promise<void>;
|
||||
}
|
||||
/** A pill above an agent's composer. Render it from a composer pill item's `Component`. */
|
||||
export declare const ComposerPill: ComponentType<ComposerPillProps>;
|
||||
|
||||
/** Paseo's loading state. Fills the panel; the panel decides when to show it. */
|
||||
export declare const Loading: ComponentType;
|
||||
|
||||
|
||||
@@ -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`
|
||||
|
||||
@@ -122,7 +122,7 @@ it("keeps historical string descriptor helpers while accepting translated regist
|
||||
expect(
|
||||
typeErrors({
|
||||
"client/example.tsx": `
|
||||
import { defineTranslations, type PluginText, type PluginFilePanelContribution, type PluginClientContext, type PluginScreenContribution, type PluginWorkspacePanelContribution, type PluginSettingsScreenContribution, type PluginSidebarItemContribution, type PluginSidebarContribution, type PluginCommandCenterItemContribution, type PluginClientSlashCommandContribution, type PluginButton, type PluginHeaderButtonContribution, type PluginComposerPillContribution, type PluginButtonMenuEntry } from "@getpaseo/plugin/client";
|
||||
import { defineTranslations, type PluginText, type PluginFilePanelContribution, type PluginClientContext, type PluginScreenContribution, type PluginWorkspacePanelContribution, type PluginSettingsScreenContribution, type PluginSidebarItemContribution, type PluginSidebarContribution, type PluginCommandCenterItemContribution, type PluginClientSlashCommandContribution, type PluginButton, type PluginHeaderButtonContribution, type PluginComposerPillContribution, type PluginComposerPillItemContribution, type PluginButtonMenuEntry } from "@getpaseo/plugin/client";
|
||||
import { z } from "zod";
|
||||
import { defineAttachmentSource, type PluginThemeContribution, type PluginAttachmentSourceContribution } from "@getpaseo/plugin";
|
||||
const messages = defineTranslations({ resources: { en: { title: "Notes" } } });
|
||||
@@ -130,10 +130,10 @@ it("keeps historical string descriptor helpers while accepting translated regist
|
||||
function historicalScreen(screen: PluginScreenContribution) {
|
||||
return typeof screen.title === "function" ? screen.title({}).trim() : screen.title.trim();
|
||||
}
|
||||
function historicalLabels(filePanel: PluginFilePanelContribution, panel: PluginWorkspacePanelContribution, settings: PluginSettingsScreenContribution, sidebar: PluginSidebarItemContribution, legacy: PluginSidebarContribution, command: PluginCommandCenterItemContribution, slash: PluginClientSlashCommandContribution, button: PluginButton, header: PluginHeaderButtonContribution, pill: PluginComposerPillContribution, menu: PluginButtonMenuEntry, theme: PluginThemeContribution, source: PluginAttachmentSourceContribution) {
|
||||
function historicalLabels(filePanel: PluginFilePanelContribution, panel: PluginWorkspacePanelContribution, settings: PluginSettingsScreenContribution, sidebar: PluginSidebarItemContribution, legacy: PluginSidebarContribution, command: PluginCommandCenterItemContribution, slash: PluginClientSlashCommandContribution, button: PluginButton, header: PluginHeaderButtonContribution, pill: PluginComposerPillContribution, pillItem: PluginComposerPillItemContribution, menu: PluginButtonMenuEntry, theme: PluginThemeContribution, source: PluginAttachmentSourceContribution) {
|
||||
filePanel.title.trim(); panel.title.trim(); settings.title.trim(); sidebar.title.trim(); legacy.title.trim(); command.title.trim();
|
||||
slash.description.trim(); slash.argumentHint.trim(); button.title.trim(); button.label?.trim();
|
||||
header.button.title.trim(); pill.button.title.trim(); if (menu.kind === "item") menu.title.trim();
|
||||
header.button.title.trim(); pill.button.title.trim(); pillItem.title.trim(); if (menu.kind === "item") menu.title.trim();
|
||||
theme.name.trim(); source.title.trim(); source.pickerTitle.trim(); source.searchPlaceholder.trim();
|
||||
}
|
||||
function contribute(client: PluginClientContext) {
|
||||
@@ -145,6 +145,7 @@ it("keeps historical string descriptor helpers while accepting translated regist
|
||||
const translated: PluginScreenContribution<PluginText> = { id: "typed", title: messages.message("title"), Component };
|
||||
client.addScreen(translated);
|
||||
client.addSidebarHeaderItem({ id: "notes", title: messages.message("title"), Component });
|
||||
client.addComposerPillItem({ id: "notes", title: messages.message("title"), Component });
|
||||
client.addFilePanel({ id: "notes", title: messages.message("title"), icon: "File", files: { extensions: ["notes"] }, Component });
|
||||
client.addSettingsScreen({ id: "notes", title: messages.message("title"), icon: "File", Component });
|
||||
client.addWorkspacePanel({ id: "notes", title: messages.message("title"), icon: "File", context: "workspace", Component });
|
||||
|
||||
@@ -82,6 +82,7 @@ Use this table as the complete registration checklist.
|
||||
| `plugin.addClientSlashCommand(command)` in the old root entry | `client.addSlashCommand(command)` in `index.client.tsx` |
|
||||
| `plugin.addClientSide(fn)` in the old root entry | Delete the wrapper and move the body of `fn` into the default client entry function |
|
||||
| `client.addComposerPill(pill)` inside the old client callback | `client.addComposerPill(pill)` inside `index.client.tsx` or an imported `client/` function |
|
||||
| New declarative composer pill contribution | `client.addComposerPillItem({ id, title, Component })` in `index.client.tsx`; see [composer pills](reference#composer-pills) |
|
||||
| New composer item contribution | `client.addComposerItem(item)` in `index.client.tsx`; see [composer items](reference#composer-items) |
|
||||
| New New workspace item contribution | `client.addNewWorkspaceItem(item)` in `index.client.tsx`; see [New workspace items](reference#new-workspace-items) |
|
||||
| New header contribution | `client.addHeaderButton({ id, workspaceId, button })` |
|
||||
|
||||
@@ -74,6 +74,7 @@ my-plugin/
|
||||
| 旧根入口中的 `plugin.addClientSlashCommand(command)` | `index.client.tsx` 中的 `client.addSlashCommand(command)` |
|
||||
| 旧根入口中的 `plugin.addClientSide(fn)` | 删除这层包装,把 `fn` 的函数体移入默认的客户端入口函数 |
|
||||
| 旧客户端回调中的 `client.addComposerPill(pill)` | `index.client.tsx` 或被导入的 `client/` 函数中的 `client.addComposerPill(pill)` |
|
||||
| 新的声明式 Composer 标签贡献 | `index.client.tsx` 中的 `client.addComposerPillItem({ id, title, Component })`;见 [Composer 标签](reference#composer-pills) |
|
||||
| 新的编辑器项贡献 | `index.client.tsx` 中的 `client.addComposerItem(item)`;见[编辑器项](reference#composer-items) |
|
||||
| 新的“新建工作区”项贡献 | `index.client.tsx` 中的 `client.addNewWorkspaceItem(item)`;见[新建工作区项](reference#new-workspace-items) |
|
||||
| 新的标题栏贡献 | `client.addHeaderButton({ id, workspaceId, button })` |
|
||||
|
||||
@@ -1177,6 +1177,7 @@ export default function contribute(client: PluginClientContext) {
|
||||
| `host` | Selected host `id` and display `label`. |
|
||||
| `layout` | `compact` and the `ios`, `android`, or `web` platform. |
|
||||
| `params` | The params the screen was opened with, as string keys and values. `{}` when none. |
|
||||
| `openScreen` | Opens one of this plugin's screens on the screen's host: `{ screenId, params? }`. Unknown screen IDs throw. Requires a Paseo app newer than 0.19.1; set [`requirements.app`](#requirements) or check `typeof openScreen === "function"` on older apps. |
|
||||
| `navigation` | Optional client navigation. `openAgent({ agentId, serverId? })` and `openWorkspace({ workspaceId, serverId? })` open targets on `serverId`, or on the selected host when omitted. `openBrowser({ url, workspaceId, serverId? })` is available only on Electron; see [links and browsers](#external-links-and-workspace-browsers). |
|
||||
|
||||
If `navigation?.supportsFocusHost` is true, pass `focusHost: true` to `openAgent` or `openWorkspace`.
|
||||
@@ -2176,22 +2177,47 @@ 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`,
|
||||
`workspaceId`, read-only `params`, `revision`, and `tab`. Workspace panels have empty
|
||||
`PluginWorkspacePanelParams`; agent panels have `PluginAgentPanelParams` containing `agentId`.
|
||||
`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`:
|
||||
|
||||
`tab.setModified(boolean)` marks unsaved work and asks before closing. `tab.state` is opaque
|
||||
- **`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
|
||||
`title` (use `tab.setTitle?.(title)` when supporting older apps). `tab.state` is opaque
|
||||
persisted JSON, initially `undefined`; `tab.setState(value)` replaces it. Each tab owns its state.
|
||||
Paseo stores it without interpreting it. Validate it with `useTabState(tab, schema, defaultState)`:
|
||||
|
||||
@@ -2339,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 |
|
||||
| ---------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
@@ -2369,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:
|
||||
|
||||
@@ -2507,13 +2538,14 @@ for a filename-only selector. At least one extension or filename is required.
|
||||
`PluginFilePanelProps` includes the common `theme`, `host`, `layout`, and optional `navigation`
|
||||
props described under [Theme and layout](#theme-and-layout), plus:
|
||||
|
||||
| Prop | Type | Meaning |
|
||||
| ------------- | ----------------------- | --------------------------------------------------------------------------------------------------- |
|
||||
| `workspaceId` | `string` | Workspace containing the file tab. |
|
||||
| `params` | `PluginFilePanelParams` | Read-only `path`, `lineStart?`, and `lineEnd?` from the opener. |
|
||||
| `revision` | `number` | Increments each time params are re-sent to this tab, even for the same line. |
|
||||
| `file` | `PluginFile` | File capability resolved from `params.path`, stable while the tab shows this file. |
|
||||
| `tab` | `PluginTab` | `setModified`, opaque persisted `state`, and `setState`. See [Workspace panels](#workspace-panels). |
|
||||
| Prop | Type | Meaning |
|
||||
| ------------- | ---------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| `workspaceId` | `string` | Workspace containing the file tab. |
|
||||
| `params` | `PluginFilePanelParams` | Read-only `path`, `lineStart?`, and `lineEnd?` from the opener. |
|
||||
| `revision` | `number` | Increments each time params are re-sent to this tab, even for the same line. |
|
||||
| `file` | `PluginFile` | File capability resolved from `params.path`, stable while the tab shows this file. |
|
||||
| `tab` | `PluginTab` | `setModified`, `setTitle`, opaque persisted `state`, and `setState`. See [Workspace panels](#workspace-panels). |
|
||||
| `openScreen` | `(input: PluginOpenScreenInput) => void` | Opens one of this plugin's screens on the panel's host: `{ screenId, params? }`. Unknown screen IDs throw. Requires a Paseo app newer than 0.19.1; set [`requirements.app`](#requirements) or check `typeof openScreen === "function"` on older apps. |
|
||||
|
||||
Paseo mounts your panel once it knows the file exists and its size, without reading it. The
|
||||
`file` object is stable, and its stat fields hold the latest version Paseo knows. Read them while
|
||||
@@ -3047,13 +3079,78 @@ searches a fixed issue list from a daemon handler and sets the branch and metada
|
||||
|
||||
## Composer pills
|
||||
|
||||
`client.addComposerPill({ id, workspaceId, agentId, button })` uses the same [button descriptor](#button-descriptor)
|
||||
and returns the same registration. It targets one agent's composer track alongside Tasks and
|
||||
The track above the composer shows pills alongside Tasks and Subagents and keeps its space whether or not it has pills, so adding and removing pills does not move the transcript.
|
||||
|
||||
### Declarative composer pills {#declarative-composer-pills}
|
||||
|
||||
`client.addComposerPillItem({ id, title, Component })` mounts `Component` for each visible agent tab on the plugin's host and returns a cleanup function. Use it when a pill derives from reactive plugin state or per-agent queries without registering per agent ahead of time.
|
||||
|
||||
`Component` receives `PluginComposerPillItemProps`:
|
||||
|
||||
| Field | Meaning |
|
||||
| ------------------------- | ------------------------------------------------------------------------------------------------- |
|
||||
| `theme`, `host`, `layout` | As in `PluginScreenProps`. |
|
||||
| `workspaceId`, `agentId` | The tab's workspace and agent IDs. |
|
||||
| `openScreen(input)` | Opens one of this plugin's screens: `{ screenId, params? }`. Unknown screen IDs throw. |
|
||||
| `openPopover(Content)` | Opens `Content` anchored above the pressed pill on wide layouts and as a bottom sheet on compact. |
|
||||
|
||||
`Content` receives `PluginPopoverProps` (`theme`, `host`, `layout`, `close()`, and `openScreen(input)`). Opening a screen closes the popover.
|
||||
|
||||
Render `ComposerPill` from `@getpaseo/plugin/client/ui`, or return `null` when there is nothing to show (returning `null` leaves no gap in the track). An item that throws renders nothing; the rest of the track keeps working.
|
||||
|
||||
| Prop | Meaning |
|
||||
| ---------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| `icon` | Required. Any [icon](#icons) form, drawn at the pill's glyph size. |
|
||||
| `label` | Required. Display text shown inside the pill. |
|
||||
| `title` | Optional. Tooltip and accessible label; defaults to `label`. |
|
||||
| `disabled` | Optional. Prevents presses when `true`. |
|
||||
| `onPress` | Required. `() => void \| Promise<void>`. While a returned promise is pending, the pill shows a spinner and blocks repeat presses; rejections show in a toast. |
|
||||
|
||||
```tsx
|
||||
import type {
|
||||
PluginClientContext,
|
||||
PluginComposerPillItemProps,
|
||||
PluginPopoverProps,
|
||||
} from "@getpaseo/plugin/client";
|
||||
import { ComposerPill } from "@getpaseo/plugin/client/ui";
|
||||
import { Text, View } from "react-native";
|
||||
|
||||
function ReviewSummary({ theme }: PluginPopoverProps) {
|
||||
return (
|
||||
<View>
|
||||
<Text style={{ color: theme.colors.foreground }}>2 checks passing</Text>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
function ReviewPill({ workspaceId, agentId, openPopover }: PluginComposerPillItemProps) {
|
||||
if (!workspaceId || !agentId) return null;
|
||||
return (
|
||||
<ComposerPill
|
||||
icon="Scan"
|
||||
label="Review"
|
||||
title="Open review summary"
|
||||
onPress={() => openPopover(ReviewSummary)}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
export default function contribute(client: PluginClientContext) {
|
||||
return client.addComposerPillItem({
|
||||
id: "review",
|
||||
title: "Review summary",
|
||||
Component: ReviewPill,
|
||||
});
|
||||
}
|
||||
```
|
||||
|
||||
### Imperative composer pills {#imperative-composer-pills}
|
||||
|
||||
`client.addComposerPill({ id, workspaceId, agentId, button })` uses the [button descriptor](#button-descriptor)
|
||||
and returns `{ update, remove }`. It targets one agent's composer track alongside Tasks and
|
||||
Subagents. Composer pills always show the icon and `label` (or `title` when `label` is omitted).
|
||||
Menus and popovers add an upward chevron on every layout, because their surface opens above the
|
||||
pill; actions show none, so a pill that runs on tap reads differently from one that opens something.
|
||||
The track keeps its space above the composer whether or not it has pills, so adding and removing
|
||||
pills does not move the transcript.
|
||||
|
||||
```tsx
|
||||
const pill = client.addComposerPill({
|
||||
@@ -3132,8 +3229,7 @@ The whole trigger opens the surface; there is no split-button behavior.
|
||||
|
||||
### Menu entries
|
||||
|
||||
A menu contains items and separators. IDs use lowercase letters, digits, and hyphens, start with
|
||||
a letter, and are unique within that menu.
|
||||
A menu contains items and separators. Entry IDs can be any non-empty trimmed string (such as `"D42"` or a UUID) and must be unique within that menu.
|
||||
|
||||
```tsx
|
||||
const behavior: PluginButtonBehavior = {
|
||||
@@ -3185,17 +3281,19 @@ The target context is one of:
|
||||
### Updates and lifecycle
|
||||
|
||||
Each registration belongs to one plugin installation, placement, workspace, and (for pills) agent.
|
||||
`id` is plugin-local within that target and uses the same format as menu IDs. The same ID may be
|
||||
used in different targets or placements. Duplicate registration in the same target throws.
|
||||
`id` is plugin-local within that target and uses lowercase letters, digits, and hyphens, starting
|
||||
with a letter. The same ID may be used in different targets or placements. Duplicate registration in
|
||||
the same target throws.
|
||||
|
||||
`update(patch: Partial<PluginButton>)` changes the descriptor in place, preserving identity and
|
||||
order. When changing `behavior`, supply the complete new behavior object. Invalid updates throw
|
||||
without changing the existing button. Subscribe to your own model or the client API and call
|
||||
`update` to publish reactive changes; mutating the original descriptor does not update the UI.
|
||||
|
||||
Hiding or disabling a button closes its surface. Updating its behavior also closes the surface.
|
||||
Hiding preserves the registration, so showing it again restores its position. It does not cancel
|
||||
an action already in progress.
|
||||
Hiding or disabling a button closes its surface. Updating its behavior also closes the surface,
|
||||
except when an already-open popover is updated with `kind: "popover"` and the same `Content`
|
||||
component reference. Hiding preserves the registration, so showing it again restores its position.
|
||||
It does not cancel an action already in progress.
|
||||
|
||||
`remove()` is idempotent. Updates after removal do nothing. Paseo removes outstanding buttons when
|
||||
the plugin installation is disposed (see [Hosts and lifecycle](#hosts-and-lifecycle)). Return cleanup from the client entry for
|
||||
|
||||
@@ -910,6 +910,7 @@ export default function contribute(client: PluginClientContext) {
|
||||
| `host` | 所选主机的 `id` 和显示用的 `label`。 |
|
||||
| `layout` | `compact` 以及 `ios`、`android` 或 `web` 平台。 |
|
||||
| `params` | 打开界面时传入的参数,键和值都是字符串。没有参数时为 `{}`。 |
|
||||
| `openScreen` | 在该界面所属主机上打开此插件的某个界面:`{ screenId, params? }`。未知的界面 ID 会抛出错误。需要高于 0.19.1 的 Paseo 应用;请在 [`requirements.app`](#requirements) 中声明应用版本要求,或在旧版应用上先检查 `typeof openScreen === "function"`。 |
|
||||
| `navigation` | 可选的客户端导航。`openAgent({ agentId, serverId? })` 和 `openWorkspace({ workspaceId, serverId? })` 在 `serverId` 上打开目标,省略时在所选主机上打开。`openBrowser({ url, workspaceId, serverId? })` 仅在 Electron 上可用;见[链接和浏览器](#external-links-and-workspace-browsers)。 |
|
||||
|
||||
路由、标题栏、关闭操作、主机选择器、错误边界和 query client 由 Paseo 负责。界面主体由插件负责。
|
||||
@@ -1754,21 +1755,45 @@ 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`、
|
||||
`workspaceId`、只读的 `params`、`revision` 和 `tab`。工作区面板使用空的
|
||||
`PluginWorkspacePanelParams`;Agent 面板的 `PluginAgentPanelParams` 包含 `agentId`。
|
||||
每次向同一标签页重新发送 params 时,`revision` 都会递增,即使请求与上次相同。
|
||||
`tab.id` 是该标签页在[工作区布局](#workspace-layout)中的 ID。它需要 Paseo 0.19.0 或更高版本。
|
||||
每个面板都接收 `PluginPanelProps<Params>`,包含 `theme`、`host`、`layout`、`navigation`、`openScreen`、
|
||||
`workspaceId`、只读的 `params`、`revision` 和 `tab`:
|
||||
|
||||
`tab.setModified(boolean)` 标记未保存的更改,并在关闭前询问。`tab.state` 是由面板定义的持久化
|
||||
- **`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)` 替换整个值。每个标签页拥有独立状态。
|
||||
Paseo 只保存状态,不解释其内容。用 `useTabState(tab, schema, defaultState)` 验证它:
|
||||
|
||||
@@ -1906,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` | 标签页放在哪里 |
|
||||
| ---------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
@@ -1933,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` 命名空间:
|
||||
|
||||
@@ -2053,13 +2081,14 @@ export default function contribute(client: PluginClientContext) {
|
||||
|
||||
`PluginFilePanelProps` 包含[主题和布局](#theme-and-layout)中介绍的通用属性 `theme`、`host`、`layout` 和可选的 `navigation`,另外还有:
|
||||
|
||||
| 属性 | 类型 | 含义 |
|
||||
| ------------- | ----------------------- | ------------------------------------------------------------------------------------------ |
|
||||
| `workspaceId` | `string` | 包含该文件标签页的工作区。 |
|
||||
| `params` | `PluginFilePanelParams` | 打开请求提供的只读 `path`、`lineStart?` 和 `lineEnd?`。 |
|
||||
| `revision` | `number` | 每次向该标签页重新发送 params 时递增,即使是同一行。 |
|
||||
| `file` | `PluginFile` | 从 `params.path` 解析的文件能力;标签页显示该文件期间保持不变。 |
|
||||
| `tab` | `PluginTab` | `setModified`、持久化的自定义 `state` 和 `setState`。参见[工作区面板](#workspace-panels)。 |
|
||||
| 属性 | 类型 | 含义 |
|
||||
| ------------- | ---------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
|
||||
| `workspaceId` | `string` | 包含该文件标签页的工作区。 |
|
||||
| `params` | `PluginFilePanelParams` | 打开请求提供的只读 `path`、`lineStart?` 和 `lineEnd?`。 |
|
||||
| `revision` | `number` | 每次向该标签页重新发送 params 时递增,即使是同一行。 |
|
||||
| `file` | `PluginFile` | 从 `params.path` 解析的文件能力;标签页显示该文件期间保持不变。 |
|
||||
| `tab` | `PluginTab` | `setModified`、`setTitle`、持久化的自定义 `state` 和 `setState`。参见[工作区面板](#workspace-panels)。 |
|
||||
| `openScreen` | `(input: PluginOpenScreenInput) => void` | 在该面板所属主机上打开此插件的某个界面:`{ screenId, params? }`。未知的界面 ID 会抛出错误。需要高于 0.19.1 的 Paseo 应用;请在 [`requirements.app`](#requirements) 中声明应用版本要求,或在旧版应用上先检查 `typeof openScreen === "function"`。 |
|
||||
|
||||
Paseo 在知道文件存在及其大小后就会挂载你的面板,不会先读取文件。`file` 对象保持不变,它的 stat 字段保存 Paseo 已知的最新版本。请在渲染时读取这些字段;它们变化时不会重新渲染你的面板。面板要通过 `watch` 监听器,或 `useFileText`、`useFileBytes`、`useFileUrl` 引起的重新渲染,得知它们已变化:
|
||||
|
||||
@@ -2476,9 +2505,76 @@ export default function contribute(client: PluginClientContext) {
|
||||
|
||||
## Composer 胶囊 {#composer-pills}
|
||||
|
||||
`client.addComposerPill({ id, workspaceId, agentId, button })` 使用同样的[按钮描述符](#button-descriptor),
|
||||
并返回同样的注册对象。它面向某个 Agent 的 Composer 栏,与 Tasks 和 Subagents 并列。Composer 胶囊始终
|
||||
显示图标和 `label`(省略 `label` 时显示 `title`)。它们从不显示箭头,菜单和弹出框也一样。
|
||||
Composer 上方的轨道与 Tasks、Subagents 并列显示胶囊,无论是否有胶囊都会保留空间,因此增减胶囊不会移动对话记录。
|
||||
|
||||
### 声明式 Composer 胶囊 {#declarative-composer-pills}
|
||||
|
||||
`client.addComposerPillItem({ id, title, Component })` 会为插件所在主机上每个可见的 Agent 标签页挂载 `Component`,并返回一个清理函数。当胶囊由响应式插件状态或按 Agent 查询驱动时使用此方法,无需预先为每个 Agent 注册。
|
||||
|
||||
`Component` 接收 `PluginComposerPillItemProps`:
|
||||
|
||||
| 字段 | 含义 |
|
||||
| ------------------------- | -------------------------------------------------------------------------- |
|
||||
| `theme`、`host`、`layout` | 同 `PluginScreenProps`。 |
|
||||
| `workspaceId`、`agentId` | 当前标签页的工作区与 Agent ID。 |
|
||||
| `openScreen(input)` | 打开此插件的某个界面:`{ screenId, params? }`。未知界面 ID 会抛出错误。 |
|
||||
| `openPopover(Content)` | 在宽布局中锚定于按下的胶囊上方打开 `Content`,在紧凑布局中以底部面板打开。 |
|
||||
|
||||
`Content` 接收 `PluginPopoverProps`(`theme`、`host`、`layout`、`close()` 和 `openScreen(input)`)。打开界面会关闭弹出框。
|
||||
|
||||
使用 `@getpaseo/plugin/client/ui` 中的 `ComposerPill` 渲染,或在无需显示时返回 `null`(返回 `null` 不会在轨道中留下空隙)。抛出错误的项不会渲染,轨道其余部分继续正常工作。
|
||||
|
||||
| Prop | 含义 |
|
||||
| ---------- | ------------------------------------------------------------------------------------------------------------------------- |
|
||||
| `icon` | 必填。任意一种[图标](#icons)形式,以胶囊图标尺寸绘制。 |
|
||||
| `label` | 必填。显示在胶囊内部的文字。 |
|
||||
| `title` | 可选。提示文字与无障碍标签;默认使用 `label`。 |
|
||||
| `disabled` | 可选。为 `true` 时阻止按下。 |
|
||||
| `onPress` | 必填。`() => void \| Promise<void>`。返回的 promise 进行期间胶囊会显示加载指示器并阻止重复按下;拒绝时以 toast 显示错误。 |
|
||||
|
||||
```tsx
|
||||
import type {
|
||||
PluginClientContext,
|
||||
PluginComposerPillItemProps,
|
||||
PluginPopoverProps,
|
||||
} from "@getpaseo/plugin/client";
|
||||
import { ComposerPill } from "@getpaseo/plugin/client/ui";
|
||||
import { Text, View } from "react-native";
|
||||
|
||||
function ReviewSummary({ theme }: PluginPopoverProps) {
|
||||
return (
|
||||
<View>
|
||||
<Text style={{ color: theme.colors.foreground }}>2 checks passing</Text>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
function ReviewPill({ workspaceId, agentId, openPopover }: PluginComposerPillItemProps) {
|
||||
if (!workspaceId || !agentId) return null;
|
||||
return (
|
||||
<ComposerPill
|
||||
icon="Scan"
|
||||
label="Review"
|
||||
title="Open review summary"
|
||||
onPress={() => openPopover(ReviewSummary)}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
export default function contribute(client: PluginClientContext) {
|
||||
return client.addComposerPillItem({
|
||||
id: "review",
|
||||
title: "Review summary",
|
||||
Component: ReviewPill,
|
||||
});
|
||||
}
|
||||
```
|
||||
|
||||
### 命令式 Composer 胶囊 {#imperative-composer-pills}
|
||||
|
||||
`client.addComposerPill({ id, workspaceId, agentId, button })` 使用[按钮描述符](#button-descriptor),
|
||||
并返回 `{ update, remove }`。它面向某个 Agent 的 Composer 栏,与 Tasks 和 Subagents 并列。Composer 胶囊始终
|
||||
显示图标和 `label`(省略 `label` 时显示 `title`)。菜单和弹出框在所有布局中都会添加一个向上的箭头,因为它们的浮层在胶囊上方打开;操作不显示箭头。
|
||||
|
||||
```tsx
|
||||
const pill = client.addComposerPill({
|
||||
@@ -2555,7 +2651,7 @@ type PluginButtonBehavior =
|
||||
|
||||
### 菜单项 {#menu-entries}
|
||||
|
||||
菜单包含条目和分隔线。ID 由小写字母、数字和连字符组成,以字母开头,并且在该菜单内唯一。
|
||||
菜单包含条目和分隔线。条目 ID 可以是任意去除首尾空白后非空的字符串(如 `"D42"` 或 UUID),并且在该菜单内唯一。
|
||||
|
||||
```tsx
|
||||
const behavior: PluginButtonBehavior = {
|
||||
@@ -2607,13 +2703,13 @@ const behavior: PluginButtonBehavior = {
|
||||
### 更新与生命周期 {#updates-and-lifecycle}
|
||||
|
||||
每个注册都属于一个插件安装、一个位置、一个工作区,以及(对于胶囊)一个 Agent。`id` 在该目标内是插件
|
||||
内部的,格式与菜单 ID 相同。同一个 ID 可以用于不同的目标或位置。在同一目标中重复注册会抛出错误。
|
||||
内部的,由小写字母、数字和连字符组成且以字母开头。同一个 ID 可以用于不同的目标或位置。在同一目标中重复注册会抛出错误。
|
||||
|
||||
`update(patch: Partial<PluginButton>)` 原地修改描述符,保留其标识和顺序。修改 `behavior` 时,请提供
|
||||
完整的新 behavior 对象。无效的更新会抛出错误,并且不会改变现有按钮。订阅你自己的模型或客户端 API,并
|
||||
调用 `update` 来发布响应式的变化;修改最初的描述符不会更新 UI。
|
||||
|
||||
隐藏或禁用按钮会关闭它的浮层。更新它的 behavior 也会关闭浮层。隐藏会保留注册,因此再次显示时会恢复它
|
||||
隐藏或禁用按钮会关闭它的浮层。更新它的 behavior 也会关闭浮层,除非将已打开的弹出框更新为同为 `kind: "popover"` 且 `Content` 组件引用相同的描述符。隐藏会保留注册,因此再次显示时会恢复它
|
||||
原来的位置。它不会取消已经在进行中的操作。
|
||||
|
||||
`remove()` 是幂等的。移除之后的更新不起作用。当插件安装被销毁时,Paseo 会移除尚存的按钮(参见[主机与生命周期](#hosts-and-lifecycle))。
|
||||
|
||||
@@ -52,7 +52,8 @@ Register these on `client` in `index.client.tsx`. Each returns a remover. `addHe
|
||||
| `addCommandCenterItem` | A global, workspace, or agent action in the Command Center | Reference > Command Center items | `local-plugin` |
|
||||
| `addSlashCommand` | A `/name args` command that runs plugin code and sends nothing to the agent | Reference > Slash commands | `translations` |
|
||||
| `addHeaderButton` | An action, menu, or popover in the workspace header | Reference > Header buttons | `buttons` |
|
||||
| `addComposerPill` | A button above the composer of one agent, beside Tasks and Subagents | Reference > Composer pills | `local-plugin` |
|
||||
| `addComposerPillItem` | Declarative pills above the composer of visible agent tabs, drawn with `ComposerPill` | Reference > Composer pills | |
|
||||
| `addComposerPill` | An imperative button above the composer of one agent, beside Tasks and Subagents | Reference > Composer pills | `local-plugin` |
|
||||
| `addComposerItem` | Composer controls that change the prompt, model, mode, provider options, or agent metadata through `useComposer()` | Reference > Composer items | `composer-controls` |
|
||||
| `addNewWorkspaceItem` | A field on the New workspace screen that sets the branch, base, isolation, or workspace metadata through `useNewWorkspace()` | Reference > New workspace items | `new-workspace-issues` |
|
||||
| `addAttachmentSource` | Outside resources, such as issues, that the user searches and attaches to a prompt | Reference > Add a composer attachment source | `linear` |
|
||||
@@ -200,11 +201,14 @@ import {
|
||||
type PluginWorkspacePanelProps,
|
||||
useWorkspace,
|
||||
} from "@getpaseo/plugin/client";
|
||||
import { useMemo } from "react";
|
||||
import { useEffect, useMemo } from "react";
|
||||
import { Text, View } from "react-native";
|
||||
|
||||
function Overview({ theme, layout, workspaceId }: PluginWorkspacePanelProps) {
|
||||
function Overview({ theme, layout, workspaceId, tab }: PluginWorkspacePanelProps) {
|
||||
const name = useWorkspace(workspaceId, (workspace) => workspace.name);
|
||||
useEffect(() => {
|
||||
tab.setTitle(name ? `Overview: ${name}` : null);
|
||||
}, [name, tab]);
|
||||
const styles = useMemo(
|
||||
() => ({
|
||||
screen: {
|
||||
@@ -243,7 +247,44 @@ export default function contribute(client: PluginClientContext) {
|
||||
}
|
||||
```
|
||||
|
||||
Register a panel that belongs to one agent with `addAgentPanel`, and read `params.agentId` in it. 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).
|
||||
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
|
||||
|
||||
@@ -294,7 +335,7 @@ export default function contribute(client: PluginClientContext) {
|
||||
}
|
||||
```
|
||||
|
||||
Call `openPopover(Content)` from an item to open a popover instead of a screen. Paseo owns the route, the header, the host picker, and the error boundary of a screen.
|
||||
Call `openPopover(Content)` from an item to open a popover instead of a screen. Screens (`PluginScreenProps`) also receive `openScreen({ screenId, params })` to navigate to another screen of the same plugin (check `typeof openScreen === "function"` or set `requirements.app` from Reference if older apps may run the plugin). Paseo owns the route, the header, the host picker, and the error boundary of a screen.
|
||||
|
||||
### Add a composer control
|
||||
|
||||
@@ -342,6 +383,33 @@ export default function contribute(client: PluginClientContext) {
|
||||
|
||||
Paseo places each control inline when the composer has room, and in the overflow sheet when it does not. On a phone, controls are always in the sheet. Keep effects in an item safe to run twice, because the sheet mounts a second instance. To reach a composer from outside it, call `useComposers({ agentId })`, `useComposers({ focused: true })`, or `client.composers(selector)`.
|
||||
|
||||
### Add a composer pill
|
||||
|
||||
`addComposerPillItem` mounts a component above the composer for each visible agent tab. Render `ComposerPill` from `@getpaseo/plugin/client/ui`, or return `null` when there is nothing to show:
|
||||
|
||||
```tsx
|
||||
// index.client.tsx
|
||||
import type {
|
||||
PluginClientContext,
|
||||
PluginComposerPillItemProps,
|
||||
PluginPopoverProps,
|
||||
} from "@getpaseo/plugin/client";
|
||||
import { ComposerPill } from "@getpaseo/plugin/client/ui";
|
||||
import { Text } from "react-native";
|
||||
|
||||
function StatusPopover({ theme }: PluginPopoverProps) {
|
||||
return <Text style={{ color: theme.colors.foreground }}>Checks passing</Text>;
|
||||
}
|
||||
|
||||
function StatusPill({ openPopover }: PluginComposerPillItemProps) {
|
||||
return <ComposerPill icon="Scan" label="Checks" onPress={() => openPopover(StatusPopover)} />;
|
||||
}
|
||||
|
||||
export default function contribute(client: PluginClientContext) {
|
||||
return client.addComposerPillItem({ id: "checks", title: "Checks", Component: StatusPill });
|
||||
}
|
||||
```
|
||||
|
||||
## Add daemon-side behavior
|
||||
|
||||
Define one Zod contract in `shared/`, handle it in `index.server.ts`, and call it from client code with `useRpc()`. `paseo plugin init` generates this RPC with the same files and export names:
|
||||
|
||||
Reference in New Issue
Block a user