Compare commits

..
Author SHA1 Message Date
paseo-bot[bot] eba7d0ca14 fix(server): keep OpenCode parents usable after child worktree removal
OpenCode keeps the child session after its working directory is removed. Skip runtime reconciliation for that child when OpenCode returns LocationNotFoundError so the parent can resume and accept prompts.
2026-12-04 12:34:35 +00:00
70 changed files with 518 additions and 3594 deletions
@@ -745,8 +745,7 @@ async function recordDelayedRunningTransition(
const prompt = "Second prompt keeps streaming.";
gate.holdNextAgentStreamEvent("turn_started");
// Hold every running snapshot until release so the prompt-commit emitState does not leak early.
gate.holdAgentUpdates(agent.agentId, "running");
gate.holdNextAgentUpdate(agent.agentId, "running");
gate.holdNextServerMessage("send_agent_message_response");
gate.setAgentStreamSuppressed(true);
await recordTurnFrames(page, prompt);
@@ -774,7 +773,7 @@ async function recordDelayedRunningTransition(
await expect(page.getByTestId("turn-working-elapsed")).toBeVisible();
gate.releaseHeldServerMessage("send_agent_message_response");
responseReleased = true;
gate.releaseHeldAgentUpdates(agent.agentId, "running");
gate.releaseHeldAgentUpdate(agent.agentId, "running");
snapshotReleased = true;
} else if (releaseOrder === "response-before-turn") {
gate.releaseHeldServerMessage("send_agent_message_response");
@@ -783,13 +782,13 @@ async function recordDelayedRunningTransition(
gate.releaseHeldAgentStreamEvent("turn_started");
turnReleased = true;
await expect(page.getByTestId("turn-working-elapsed")).toBeVisible();
gate.releaseHeldAgentUpdates(agent.agentId, "running");
gate.releaseHeldAgentUpdate(agent.agentId, "running");
snapshotReleased = true;
} else {
gate.releaseHeldServerMessage("send_agent_message_response");
responseReleased = true;
await recordPaintsFor(page, 80);
gate.releaseHeldAgentUpdates(agent.agentId, "running");
gate.releaseHeldAgentUpdate(agent.agentId, "running");
snapshotReleased = true;
await expect(page.getByTestId("turn-working-elapsed")).toBeVisible();
gate.releaseHeldAgentStreamEvent("turn_started");
@@ -805,7 +804,7 @@ async function recordDelayedRunningTransition(
return { frames, checkpoints };
} finally {
if (!turnReleased) gate.releaseHeldAgentStreamEvent("turn_started");
if (!snapshotReleased) gate.releaseHeldAgentUpdates(agent.agentId, "running");
if (!snapshotReleased) gate.releaseHeldAgentUpdate(agent.agentId, "running");
if (!responseReleased) gate.releaseHeldServerMessage("send_agent_message_response");
gate.setAgentStreamSuppressed(false);
}
@@ -1,350 +0,0 @@
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,10 +27,7 @@ import {
} from "@getpaseo/plugin/client";
import { useQueryClient } from "@tanstack/react-query";
import { DocumentFrame, Loading } from "@getpaseo/plugin/client/ui";
function FileDetailsScreen({ params }) {
return <View><Text>File screen: {params.file}</Text></View>;
}
function Pdf({ file, workspaceId, openScreen }) {
function Pdf({ file, workspaceId }) {
usePaseo();
useQueryClient();
const workspace = useWorkspace(workspaceId, value => ({ id: value.id }));
@@ -47,9 +44,6 @@ function Pdf({ file, workspaceId, openScreen }) {
<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>;
}
@@ -75,7 +69,6 @@ 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",
@@ -99,16 +92,6 @@ 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" });
@@ -169,7 +152,6 @@ 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");
@@ -1,288 +0,0 @@
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 });
}
});
@@ -42,40 +42,17 @@ 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, openScreen }) {
function WorkspacePanel({ workspaceId, host, layout }) {
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>
<Pressable accessibilityRole="button" onPress={() => openScreen({ screenId: "details", params: { source: "workspace-panel", item: workspaceId } })}><Text>Open screen from workspace panel</Text></Pressable>
</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></View>;
}
function AgentPanel({ workspaceId, agentId, host, layout, openScreen }) {
function AgentPanel({ workspaceId, agentId, host, layout }) {
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>
<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>;
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>;
}
function DirectCollisionSurface({ navigation }) {
@@ -150,8 +127,6 @@ 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" });
@@ -277,34 +252,6 @@ 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 });
@@ -391,24 +338,6 @@ 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 () => {
@@ -546,16 +475,6 @@ 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,7 +55,6 @@ interface HeldServerMessage {
interface PendingServerMessageHold {
matches: (message: ClientRequest | null) => boolean;
blockAgentStreamFollowers?: boolean;
keepHolding?: boolean;
}
function readSessionMessage(message: string | Buffer): ClientRequest | null {
@@ -413,7 +412,7 @@ export async function installDaemonWebSocketGate(page: Page, options: { port?: n
);
if (!matchedHold) return suppressed;
const [key, hold] = matchedHold;
if (!hold.keepHolding) pendingServerMessageHolds.delete(key);
pendingServerMessageHolds.delete(key);
heldServerMessages.push({
browser: input.browser,
message: input.message,
@@ -551,23 +550,6 @@ 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();
@@ -679,13 +661,6 @@ 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,
@@ -715,10 +690,13 @@ export async function installDaemonWebSocketGate(page: Page, options: { port?: n
},
releaseHeldServerMessage(type?: string): void {
const key = type ? serverMessageKey(type) : null;
releaseFirstHeldMessage(
(message) => key === null || message.key === key,
"No held server message to release",
);
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);
}
},
async waitForHeldAgentUpdate(agentId: string, status: string): Promise<void> {
const key = agentUpdateKey(agentId, status);
@@ -728,20 +706,12 @@ export async function installDaemonWebSocketGate(page: Page, options: { port?: n
},
releaseHeldAgentUpdate(agentId: string, status: string): void {
const key = agentUpdateKey(agentId, status);
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);
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);
}
},
async waitForHeldAgentStreamEvent(type: string): Promise<void> {
@@ -752,10 +722,13 @@ export async function installDaemonWebSocketGate(page: Page, options: { port?: n
},
releaseHeldAgentStreamEvent(type: string): void {
const key = agentStreamEventKey(type);
releaseFirstHeldMessage(
(message) => message.key === key,
"No held agent stream event to release",
);
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);
}
},
async waitForHeldAgentStreamItem(type: string): Promise<void> {
const key = agentStreamItemKey(type);
@@ -765,10 +738,13 @@ export async function installDaemonWebSocketGate(page: Page, options: { port?: n
},
releaseHeldAgentStreamItem(type: string): void {
const key = agentStreamItemKey(type);
releaseFirstHeldMessage(
(message) => message.key === key,
"No held agent stream item to release",
);
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);
}
},
requestTimelineTail(agentId: string): void {
if (!latestServer) throw new Error("No daemon WebSocket is connected");
@@ -1,6 +1,7 @@
import type { ReactNode } from "react";
import { MenuRoot } from "@/components/ui/menu";
import { PluginPopoverSurface, usePluginPopoverAnchor } from "@/plugins/popover";
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 { SidebarSection } from "@/sidebar-nav/model";
/**
@@ -25,7 +26,41 @@ export function SidebarPopoverRoot({
);
}
export const useSidebarPopoverAnchor = usePluginPopoverAnchor;
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 };
}
const PLACEMENT = {
header: { side: "right", align: "start" },
+3 -16
View File
@@ -1,11 +1,4 @@
import {
useCallback,
useMemo,
useState,
type ReactElement,
type ReactNode,
type RefObject,
} from "react";
import { useCallback, useMemo, useState, type ReactElement, type ReactNode } from "react";
import { Pressable, Text, View } from "react-native";
import { GestureDetector } from "react-native-gesture-handler";
import Animated from "react-native-reanimated";
@@ -49,18 +42,12 @@ 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,
trackViewportRef,
}: {
children: ReactNode;
trackViewportRef?: RefObject<View | null>;
}): ReactElement {
export function ComposerTrackBar({ children }: { children: ReactNode }): ReactElement {
const scrollGesture = usePanelAwareHorizontalScrollGesture();
const scrollBoundary = useHorizontalScrollBoundary();
return (
<View style={styles.bar} dataSet={CHAT_COLUMN_RAIL_DATASET} pointerEvents="box-none">
<View ref={trackViewportRef} style={styles.trackViewport} pointerEvents="box-none">
<View style={styles.trackViewport} pointerEvents="box-none">
<GestureDetector gesture={scrollGesture}>
<Animated.ScrollView
testID="composer-track-scroll"
+38 -9
View File
@@ -1,4 +1,6 @@
import { useCallback, useMemo } from "react";
import { usePaneContext } from "@/panels/pane-context";
import { useCallback, useEffect, useMemo, useState } from "react";
import type { PluginFile, PluginTab } from "@getpaseo/plugin/client";
import { Text, View } from "react-native";
import { Download } from "lucide-react-native";
import { StyleSheet } from "react-native-unistyles";
@@ -7,11 +9,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 } from "@/file-panels";
import { FilePanelPicker, FilePanelView, useFilePanelChoice, type FilePanel } 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 { getComponentMountKey } from "@/panels/panel-instance-attributes";
import { usePublishPanelInstanceAttributes } from "@/panels/panel-instance-attributes";
import { useHostRuntimeConnectionStatus } from "@/runtime/host-runtime";
import { buildAbsoluteExplorerPath } from "@/utils/explorer-paths";
import { formatFileSize } from "@/utils/format-file-size";
@@ -77,6 +79,8 @@ 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,
@@ -117,19 +121,16 @@ 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} />
<FilePanelView
key={panelMountKey}
<MountedFilePanel
key={`${panel.id}:${targetKey}`}
panel={panel}
file={handle.file}
params={panelLocation}
revision={navigationRevision}
suspendPendingSave={handle.holdWrites}
onModifiedChange={setModified}
/>
</View>
);
@@ -141,6 +142,34 @@ 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,
+6 -7
View File
@@ -1,5 +1,4 @@
import { useWorkspace, useFileUrl } from "@getpaseo/plugin/client";
import type { BuiltinFilePanelProps } from "./panels";
import { useWorkspace, useFileUrl, type PluginFilePanelProps } from "@getpaseo/plugin/client";
import { useCallback, useState } from "react";
import { ScrollView, Text, View } from "react-native";
import { StyleSheet } from "react-native-unistyles";
@@ -12,17 +11,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: BuiltinFilePanelProps) {
function SourcePanel(props: PluginFilePanelProps) {
return <TextFilePanel {...props} />;
}
/** Markdown: the text file panel with the rendered document as its Preview. */
function MarkdownPanel(props: BuiltinFilePanelProps) {
function MarkdownPanel(props: PluginFilePanelProps) {
return <TextFilePanel {...props} preview={MarkdownPreview} />;
}
/** HTML: the text file panel with the sandboxed page as its Preview. */
function HtmlPanel(props: BuiltinFilePanelProps) {
function HtmlPanel(props: PluginFilePanelProps) {
return <TextFilePanel {...props} preview={HtmlPreview} />;
}
@@ -59,7 +58,7 @@ function HtmlPreview({ text }: TextFilePreviewProps) {
);
}
function ImagePanel({ file }: BuiltinFilePanelProps) {
function ImagePanel({ file }: PluginFilePanelProps) {
const url = useFileUrl(file);
if (url.status === "loading") return <FilePanelLoading />;
if (url.status === "error") return <FilePanelError message={url.error.message} />;
@@ -84,7 +83,7 @@ const components = {
export function BuiltinFilePanelView({
panel,
...props
}: BuiltinFilePanelProps & { panel: RenderingFilePanel | SourceFilePanel }) {
}: PluginFilePanelProps & { panel: RenderingFilePanel | SourceFilePanel }) {
const Component = components[panel.id];
return <Component {...props} />;
}
-4
View File
@@ -1,12 +1,8 @@
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;
+3 -30
View File
@@ -1,45 +1,18 @@
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 { 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} />;
}
import type { PluginFilePanel } from "./panels";
export function PluginFilePanelHost({
panel,
suspendPendingSave,
...props
}: PluginFilePanelHostProps) {
}: PluginFilePanelProps & { panel: PluginFilePanel }) {
const { plugin, contribution } = panel;
const openScreen = usePluginOpenScreen(plugin);
const Component = contribution.Component;
return (
<SurfaceErrorBoundary installation={plugin} Surface={Component} key={panel.id}>
<PluginInstallationProvider plugin={plugin}>
<MountedPluginFilePanel
{...props}
openScreen={openScreen}
panel={panel}
suspendPendingSave={suspendPendingSave}
/>
<Component {...props} />
</PluginInstallationProvider>
</SurfaceErrorBoundary>
);
@@ -8,8 +8,11 @@ import {
type ComponentType,
type ReactNode,
} from "react";
import { useFileText, type PluginFilePanelParams } from "@getpaseo/plugin/client";
import type { BuiltinFilePanelProps } from "../panels";
import {
useFileText,
type PluginFilePanelProps,
type PluginFilePanelParams,
} from "@getpaseo/plugin/client";
import { Text, View } from "react-native";
import { StyleSheet, withUnistyles } from "react-native-unistyles";
import { useTranslation } from "react-i18next";
@@ -53,12 +56,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: BuiltinFilePanelProps["params"];
params: PluginFilePanelProps["params"];
workspaceId: string;
host: BuiltinFilePanelProps["host"];
host: PluginFilePanelProps["host"];
}
type TextFilePanelProps = BuiltinFilePanelProps & {
type TextFilePanelProps = PluginFilePanelProps & {
/** The panel's Preview; with one, the toolbar switches between Preview and Source. */
preview?: ComponentType<TextFilePreviewProps>;
};
+6 -34
View File
@@ -6,40 +6,19 @@ 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 { BuiltinFilePanelProps, FilePanel } from "./panels";
import type { RenderingFilePanel, SourceFilePanel } from "./catalog";
import type { FilePanel } from "./panels";
import { BuiltinFilePanelView } from "./builtin";
import { PluginFilePanelHost } from "./plugin-host";
type Props = Pick<PluginFilePanelProps, "file" | "params" | "revision"> & {
type Props = Pick<PluginFilePanelProps, "file" | "tab" | "params" | "revision"> & {
panel: FilePanel;
suspendPendingSave?: () => () => void;
};
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 }) {
function FilePanelHost({ panel, theme, ...input }: Props & { theme: PluginTheme }) {
const { workspaceId, serverId } = usePaneContext();
const compact = useIsCompactFormFactor();
const hosts = useHosts();
@@ -48,21 +27,14 @@ function FilePanelHost({
const layout = useMemo(() => ({ compact, platform: resolvePluginPlatform() }), [compact]);
const stateSource = useMemo(() => createPluginClientStateSource(serverId), [serverId]);
const navigation = usePluginHostNavigation(serverId);
const props: Omit<BuiltinFilePanelProps, "tab"> = {
...input,
workspaceId,
theme,
host,
layout,
navigation,
};
const props: PluginFilePanelProps = { ...input, workspaceId, theme, host, layout, navigation };
if (panel.builtin)
return (
<PluginClientStateProvider source={stateSource}>
<BuiltinFilePanelHost {...props} panel={panel} suspendPendingSave={suspendPendingSave} />
<BuiltinFilePanelView {...props} panel={panel} />
</PluginClientStateProvider>
);
return <PluginFilePanelHost {...props} panel={panel} suspendPendingSave={suspendPendingSave} />;
return <PluginFilePanelHost {...props} panel={panel} />;
}
const ThemedHost = withUnistyles(FilePanelHost);
const themeMapping = (theme: Theme) => ({ theme: toPluginTheme(theme) });
+3 -11
View File
@@ -1,6 +1,5 @@
import type { AgentAddress } from "@getpaseo/protocol/addresses";
import { memo, useCallback, useMemo, useRef, type ReactElement } from "react";
import type { View } from "react-native";
import { memo, useCallback, useMemo, type ReactElement } from "react";
import { BackgroundWorkTrack, createHostBackgroundWorkModel } from "@/background-work";
import { WorkspaceDiffStatPill } from "@/composer/diff-stat-pill";
import { AgentTaskList } from "@/composer/task-list";
@@ -8,7 +7,7 @@ import { ComposerTrackBar } from "@/composer/tracks";
import { useIsCompactFormFactor } from "@/constants/layout";
import { usePaneContext } from "@/panels/pane-context";
import { useSettings } from "@/hooks/use-settings";
import { PluginComposerPillItems, PluginComposerPills } from "@/plugins";
import { PluginComposerPills } from "@/plugins";
import { useSessionStore } from "@/stores/session-store";
import {
useArchiveFinishedSubagents,
@@ -109,7 +108,6 @@ export const AgentTracks = memo(function AgentTracks({
[openSubagentTarget],
);
const sheetTabFor = useSubagentSheetTab(workspaceKey, tabId);
const trackViewportRef = useRef<View | null>(null);
const handleOpenChanges = useCallback(() => {
if (!workspaceKey) {
return;
@@ -122,7 +120,7 @@ export const AgentTracks = memo(function AgentTracks({
}, [isCompact, openInSidePane, workspaceKey]);
return (
<ComposerTrackBar trackViewportRef={trackViewportRef}>
<ComposerTrackBar>
<BackgroundWorkTrack model={backgroundModel} count={backgroundWorkCount} />
{parentAgentId ? <ParentAgentPill serverId={serverId} parentAgentId={parentAgentId} /> : null}
<AgentTaskList tasks={tasks} />
@@ -137,12 +135,6 @@ 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,45 +32,4 @@ 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,5 +1,4 @@
import type { PluginTab } from "@getpaseo/plugin/client";
import { useCallback, useEffect, useMemo, useState, useSyncExternalStore } from "react";
import { useCallback, useEffect, useMemo, useSyncExternalStore } from "react";
import { usePaneContext } from "@/panels/pane-context";
import { buildWorkspaceTabPersistenceKey } from "@/workspace-tabs/model";
@@ -11,7 +10,6 @@ export interface PanelInstanceIdentity {
export interface PanelInstanceAttributes {
modified: boolean;
title?: string;
suspendPendingSave?: () => () => void;
}
@@ -21,23 +19,6 @@ 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}`;
}
@@ -66,15 +47,13 @@ export function setPanelInstanceAttributes(
): void {
const key = buildPanelInstanceKey(identity);
const previous = attributesByPanel.get(key) ?? DEFAULT_ATTRIBUTES;
const next = normalizePanelAttributes(attributes);
if (
previous.modified === next.modified &&
previous.title === next.title &&
previous.suspendPendingSave === next.suspendPendingSave
previous.modified === attributes.modified &&
previous.suspendPendingSave === attributes.suspendPendingSave
) {
return;
}
if (next.modified || next.title !== undefined) attributesByPanel.set(key, next);
if (attributes.modified) attributesByPanel.set(key, attributes);
else attributesByPanel.delete(key);
attributesRevision += 1;
for (const listener of listenersByPanel.get(key) ?? []) listener();
@@ -148,49 +127,10 @@ 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, title, suspendPendingSave });
setPanelInstanceAttributes(identity, { modified, suspendPendingSave });
return () => setPanelInstanceAttributes(identity, DEFAULT_ATTRIBUTES);
}, [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],
);
}, [modified, serverId, suspendPendingSave, tabId, workspaceId]);
}
@@ -1,579 +0,0 @@
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");
});
});
@@ -5,7 +5,6 @@ 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 {
@@ -30,7 +29,6 @@ function installation(): InstalledPlugin {
workspaceRowBadgeItems: [],
filePanels: [],
composerItems: [],
composerPillItems: [],
newWorkspaceItems: [],
workspacePanels: [],
commandCenterItems: [],
@@ -264,163 +262,3 @@ 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");
});
+1 -6
View File
@@ -123,12 +123,7 @@ export class PluginButtonStore {
const nextSource = { ...sourceButton, ...patch };
const button = validateButton(nextSource, this.validation, installation.i18n.resolve);
sourceButton = nextSource;
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);
const close = !button.visible || button.disabled || patch.behavior !== undefined;
this.replace(key, { button, open: close ? false : entry.open });
},
remove: () => {
+4 -21
View File
@@ -19,22 +19,6 @@ 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")
@@ -77,14 +61,13 @@ function validateBehavior(
return {
kind: "menu",
items: behavior.items.map((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 };
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 };
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),
+8 -4
View File
@@ -1,7 +1,6 @@
import {
buttonPageId,
type ResolvedPluginButtonBehavior as PluginButtonBehavior,
type ResolvedPluginButtonMenuEntry as PluginButtonMenuEntry,
import type {
ResolvedPluginButtonBehavior as PluginButtonBehavior,
ResolvedPluginButtonMenuEntry as PluginButtonMenuEntry,
} from "./validation";
import type { PluginButtonIcon, PluginHostProps } from "@getpaseo/plugin/client";
import type { PluginTheme } from "@getpaseo/plugin";
@@ -211,6 +210,11 @@ 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,7 +110,6 @@ function plugin(onAgentSelect: AgentCommandItem["onSelect"]): InstalledPlugin {
workspaceRowBadgeItems: [],
filePanels: [],
composerItems: [],
composerPillItems: [],
newWorkspaceItems: [],
workspacePanels: [
{
@@ -36,7 +36,6 @@ function installed(): InstalledPlugin {
sidebarViews: [],
filePanels: [],
composerItems: [],
composerPillItems: [],
newWorkspaceItems: [],
workspaceRowBadgeItems: [],
workspacePanels: [],
@@ -46,7 +46,6 @@ function plugin(): InstalledPlugin {
sidebarViews: [],
filePanels: [],
composerItems: [],
composerPillItems: [],
newWorkspaceItems: [],
workspaceRowBadgeItems: [],
workspacePanels: [],
@@ -1,21 +0,0 @@
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);
}
@@ -1,472 +0,0 @@
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);
});
});
@@ -1,234 +0,0 @@
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>
);
}
@@ -1,171 +0,0 @@
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",
},
}));
+2 -42
View File
@@ -111,7 +111,6 @@ 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() {} }),
@@ -145,7 +144,6 @@ describe("evaluatePluginClientBundle", () => {
plugin.sidebarItems.header,
plugin.sidebarItems.footer,
plugin.workspaceRowBadgeItems,
plugin.composerPillItems,
plugin.workspacePanels,
plugin.commandCenterItems,
plugin.clientSlashCommands,
@@ -168,7 +166,6 @@ describe("evaluatePluginClientBundle", () => {
plugin.sidebarItems.header,
plugin.sidebarItems.footer,
plugin.workspaceRowBadgeItems,
plugin.composerPillItems,
plugin.workspacePanels,
plugin.commandCenterItems,
plugin.clientSlashCommands,
@@ -338,43 +335,6 @@ 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",
@@ -838,10 +798,10 @@ describe("evaluatePluginClientBundle", () => {
const plugin = evaluatePluginClientBundle(
"example",
`(function(require) {
const { Icon, ProviderIcon, Modal, useToast, SettingsSection, SidebarRow, ComposerPill, StreamedText } = require("@getpaseo/plugin/client/ui");
const { Icon, ProviderIcon, Modal, useToast, SettingsSection, SidebarRow, 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 ComposerPill !== "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 StreamedText !== "function") {
throw new Error("React Native plugin UI is incomplete");
}
plugin.addSurface("main", function Surface() { return null; });
-20
View File
@@ -39,7 +39,6 @@ import type {
PluginSidebarItemContribution,
PluginWorkspacePanelContribution,
PluginWorkspaceRowBadgeItemContribution,
PluginComposerPillItemContribution,
} from "./types";
import type { ComponentType } from "react";
import { parsePluginIcon, parseSerializablePluginIcon } from "./icons";
@@ -165,7 +164,6 @@ export function runPluginClientBundle(
workspaceRowBadgeItems: [],
filePanels: [],
composerItems: [],
composerPillItems: [],
newWorkspaceItems: [],
workspacePanels: [],
commandCenterItems: [],
@@ -186,7 +184,6 @@ 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>();
@@ -325,22 +322,6 @@ 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))
@@ -709,7 +690,6 @@ 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,
-1
View File
@@ -61,7 +61,6 @@ function makePlugin(serverId: string): InstalledPlugin {
workspaceRowBadgeItems: [],
filePanels: [],
composerItems: [],
composerPillItems: [],
newWorkspaceItems: [],
workspacePanels: [],
commandCenterItems: [],
-1
View File
@@ -4,4 +4,3 @@ 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,7 +63,6 @@ function installation(invoked: string[]): InstalledPlugin {
workspaceRowBadgeItems: [],
filePanels: [],
composerItems: [],
composerPillItems: [],
newWorkspaceItems: [],
workspacePanels: [],
commandCenterItems: [],
-136
View File
@@ -1,136 +0,0 @@
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&param.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;
+4 -62
View File
@@ -1,71 +1,11 @@
import { buildPluginSettingsRoute } from "./settings/routes";
import { router } from "expo-router";
import { useCallback } from "react";
import type {
PluginOpenScreenInput,
PluginPanelLocation,
PluginScreenParams,
} from "@getpaseo/plugin/client";
import type { PluginPanelLocation } 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;
@@ -84,7 +24,9 @@ export function createPluginNavigation(input: {
router.push(buildPluginSettingsRoute(serverId, pluginId, screenId));
},
openSurface(pluginId, surfaceId, params) {
pushPluginScreenRoute({ serverId, pluginId, screenId: surfaceId, params });
router.push(
buildPluginSurfaceRoute(serverId, pluginId, { kind: "surface", id: surfaceId }, params),
);
},
openWorkspacePanel(pluginId, panelId, location) {
if (!workspaceId) throw new Error("No active workspace");
@@ -89,7 +89,6 @@ function makeInstalledPlugin(input: {
workspaceRowBadgeItems: [],
filePanels: [],
composerItems: [],
composerPillItems: [],
newWorkspaceItems: [],
workspacePanels: [],
commandCenterItems: [],
+2 -39
View File
@@ -1,7 +1,7 @@
import { useCallback, type ReactNode, type RefObject } from "react";
import type { ReactNode } from "react";
import { View } from "react-native";
import { StyleSheet } from "react-native-unistyles";
import { MenuSurface, useMenuContext, type MenuSurfaceProps } from "@/components/ui/menu";
import { MenuSurface, 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,43 +53,6 @@ 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,7 +156,6 @@ function createInstalledPlugin(serverId: string): InstalledPlugin {
workspaceRowBadgeItems: [],
filePanels: [],
composerItems: [],
composerPillItems: [],
newWorkspaceItems: [],
workspacePanels: [],
commandCenterItems: [],
@@ -11,7 +11,6 @@ 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";
-1
View File
@@ -233,7 +233,6 @@ export class PluginRegistry {
workspaceRowBadgeItems: [],
filePanels: [],
composerItems: [],
composerPillItems: [],
newWorkspaceItems: [],
workspacePanels: [],
commandCenterItems: [],
@@ -40,7 +40,6 @@ 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 { useGlobalSearchParams, usePathname } from "expo-router";
import { router, 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 { openPluginScreen } from "../navigation";
import { pluginScreensHostKey, rememberPluginContributionHost } from "../contribution-host";
import {
PluginEnvironmentProvider,
PluginPopoverContent,
type PluginEnvironment,
} from "../popover";
import { hostIdFromPathname } from "../routes";
import { buildPluginSurfaceRoute, hostIdFromPathname } from "../routes";
import {
selectPluginSidebarTarget,
type PluginSidebarGroup,
type PluginSidebarTarget,
} from "../sidebar-groups";
import { currentPluginScreen } from "../surface-contribution";
import { currentPluginScreen, parsePluginOpenScreenInput } from "../surface-contribution";
import { SurfaceErrorBoundary } from "../surface-error-boundary";
import { toPluginTheme } from "../theme";
import type { PluginSidebarSection } from "../types";
@@ -178,15 +178,19 @@ function SidebarItemContent({
[compact, hostLabel, plugin.serverId, theme],
);
const openScreen = useCallback(
(screen: PluginOpenScreenInput) => {
openPluginScreen({
plugin,
screen,
beforeNavigate() {
showPopover(null);
onBeforeNavigate?.();
},
});
(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,
),
);
},
[onBeforeNavigate, plugin, showPopover],
);
@@ -59,7 +59,6 @@ function installation(
})),
filePanels: [],
composerItems: [],
composerPillItems: [],
newWorkspaceItems: [],
workspacePanels: [],
commandCenterItems: [],
+1 -10
View File
@@ -25,7 +25,6 @@ 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";
@@ -124,17 +123,9 @@ 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}
openScreen={openScreen}
/>
<Surface theme={theme} host={host} layout={layout} navigation={navigation} params={params} />
</PluginInstallationProvider>
);
}
-1
View File
@@ -73,7 +73,6 @@ function installed(serverId: string, themes: PluginThemeContribution[]): Install
workspaceRowBadgeItems: [],
filePanels: [],
composerItems: [],
composerPillItems: [],
newWorkspaceItems: [],
workspacePanels: [],
commandCenterItems: [],
@@ -30,7 +30,6 @@ function plugin(input: {
workspaceRowBadgeItems: [],
filePanels: [],
composerItems: [],
composerPillItems: [],
newWorkspaceItems: [],
workspacePanels: [],
commandCenterItems: [],
-4
View File
@@ -14,7 +14,6 @@ import type {
PluginComposerItemContribution,
PluginNewWorkspaceItemContribution,
PluginComposerPillContribution as SDKPluginComposerPillContribution,
PluginComposerPillItemContribution as SDKPluginComposerPillItemContribution,
PluginSidebarContribution as SDKPluginSidebarContribution,
PluginSidebarViewContribution,
PluginSidebarItemContribution as SDKPluginSidebarItemContribution,
@@ -34,7 +33,6 @@ 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 =
@@ -65,7 +63,6 @@ export interface EvaluatedPlugin {
workspaceRowBadgeItems: PluginWorkspaceRowBadgeItemContribution[];
filePanels: PluginFilePanelContribution[];
composerItems: PluginComposerItemContribution[];
composerPillItems: PluginComposerPillItemContribution[];
newWorkspaceItems: PluginNewWorkspaceItemContribution[];
workspacePanels: EvaluatedPluginWorkspacePanelContribution[];
commandCenterItems: PluginCommandCenterItemContribution[];
@@ -102,7 +99,6 @@ export type {
PluginComposerItemContribution,
PluginNewWorkspaceItemContribution,
PluginComposerPillContribution,
PluginComposerPillItemContribution,
PluginSidebarContribution,
PluginSidebarItemContribution,
PluginWorkspaceRowBadgeItemContribution,
@@ -344,30 +344,6 @@ 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);
@@ -82,13 +82,12 @@ 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),
locations: panelLocations(workspace.serverId, tab.target),
title: attributes.title ?? readTabTitle({ ...workspace, target: tab.target }),
modified: attributes.modified,
title: readTabTitle({ ...workspace, target: tab.target }),
modified: getWorkspacePanelAttributes(workspace.key, tab.tabId).modified,
};
}
@@ -1,12 +1,12 @@
import { getComponentMountKey, usePanelTab } from "@/panels/panel-instance-attributes";
import { usePublishPanelInstanceAttributes } from "@/panels/panel-instance-attributes";
import type {
PluginAgentPanelProps,
PluginHostProps,
PluginWorkspacePanelProps,
PluginTab,
} from "@getpaseo/plugin/client";
import type { PluginTheme } from "@getpaseo/plugin";
import { CircleAlert } from "lucide-react-native";
import { useMemo } from "react";
import { useMemo, useState } from "react";
import { Text, View } from "react-native";
import { StyleSheet, withUnistyles } from "react-native-unistyles";
import invariant from "tiny-invariant";
@@ -18,15 +18,12 @@ 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 type { EvaluatedPluginWorkspacePanelContribution } from "../types";
import { resolvePluginWorkspacePanel } from "./resolution";
import { resolvePluginPlatform } from "../platform";
@@ -34,72 +31,22 @@ const pluginThemeMapping = (theme: Theme) => ({
theme: toPluginTheme(theme),
});
const EMPTY_WORKSPACE_PARAMS = {} as const;
function MountedPluginPanel({
contribution,
target,
theme,
host,
layout,
navigation,
openScreen,
workspaceId,
revision,
}: {
contribution: EvaluatedPluginWorkspacePanelContribution;
target: PluginWorkspaceTabTarget;
theme: PluginTheme;
host: PluginHostProps["host"];
layout: PluginHostProps["layout"];
navigation: PluginWorkspacePanelProps["navigation"];
openScreen: PluginWorkspacePanelProps["openScreen"];
workspaceId: string;
revision: number;
}) {
const tab = usePanelTab();
const agentId = target.context === "agent" ? target.agentId : null;
const agentParams = useMemo(() => (agentId ? { agentId } : null), [agentId]);
if (contribution.context === "workspace") {
const props: PluginWorkspacePanelProps = {
// COMPAT(pluginPanelFlatProps): added in v0.13.0, remove after 2027-04-23
context: "workspace",
params: EMPTY_WORKSPACE_PARAMS,
revision,
tab,
theme,
host,
layout,
navigation,
openScreen,
workspaceId,
};
const Component = contribution.Component;
return <Component {...props} />;
}
invariant(agentParams && agentId, "PluginAgentPanel requires agent target");
const props: PluginAgentPanelProps = {
// 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,
};
const Component = contribution.Component;
return <Component {...props} />;
}
function PluginPanelBody({ theme }: { theme: PluginTheme }) {
const { serverId, workspaceId, target, panelRevision } = usePaneContext();
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],
);
invariant(target.kind === "plugin", "PluginPanel requires plugin target");
const plugin = useInstalledPlugin(serverId, target.pluginId);
const contribution = resolvePluginWorkspacePanel(plugin, target);
@@ -120,7 +67,6 @@ 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 />;
@@ -128,30 +74,54 @@ function PluginPanelBody({ theme }: { theme: PluginTheme }) {
if (!client) {
return <PluginPanelUnavailable message="Plugin host is offline." />;
}
if (contribution.context === "agent" && (!agentExists || target.context !== "agent")) {
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 {
return <PluginPanelUnavailable />;
}
return (
<SurfaceErrorBoundary
installation={plugin}
Surface={contribution.Component}
Surface={Surface}
key={`${serverId}/${target.pluginId}/${target.panelId}/${target.context}`}
>
<PluginInstallationProvider plugin={plugin}>
<MountedPluginPanel
key={getComponentMountKey(contribution.Component)}
contribution={contribution}
target={target}
theme={theme}
host={host}
layout={layout}
navigation={navigation}
openScreen={openScreen}
workspaceId={workspaceId}
revision={panelRevision ?? 0}
/>
</PluginInstallationProvider>
<PluginInstallationProvider plugin={plugin}>{panel}</PluginInstallationProvider>
</SurfaceErrorBoundary>
);
}
@@ -27,7 +27,6 @@ function installed(): InstalledPlugin {
workspaceRowBadgeItems: [],
filePanels: [],
composerItems: [],
composerPillItems: [],
newWorkspaceItems: [],
workspacePanels: [
{
@@ -1,5 +1,5 @@
import { workspaceTabSwitcherPopoverLayout } from "../workspace-tab-layout";
import { memo, useCallback, useMemo, useRef, useState, type ReactElement } from "react";
import { memo, useCallback, useMemo, useRef, useState } from "react";
import { Keyboard, Pressable, Text, View } from "react-native";
import { useTranslation } from "react-i18next";
import { SquarePen, SquareTerminal } from "lucide-react-native";
@@ -12,12 +12,11 @@ import {
WorkspaceTabOptionRow,
type WorkspaceTabPresentation,
} from "@/screens/workspace/workspace-tab-presentation";
import { useFilePanelOpenWithMenu, type FilePanelOpenWithMenu } from "@/file-panels";
import { useFilePanelOpenWithMenu } 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";
@@ -146,52 +145,6 @@ 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,
@@ -294,21 +247,30 @@ function MobileWorkspaceTabOption({
testIDBase: menuTestIDBase,
onRevealInFiles: onDismissSwitcher,
});
const renderPresentation = useCallback(
(presentation: WorkspaceTabPresentation) => (
<MobileWorkspaceTabOptionRow
presentation={presentation}
selected={selected}
active={active}
onPress={onPress}
const trailingAccessory = useMemo(
() => (
<MobileTabTrailingAccessory
menuTestIDBase={menuTestIDBase}
fallbackLabel={fallbackLabel}
presentationLabel={fallbackLabel}
menuEntries={menuEntries}
openWith={openWith}
fileMenu={fileMenu}
/>
),
[selected, active, onPress, menuTestIDBase, fallbackLabel, menuEntries, openWith, 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],
);
return (
@@ -14,7 +14,6 @@ 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";
@@ -73,12 +72,6 @@ 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;
@@ -89,7 +82,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,
title: descriptor.label,
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
@@ -108,7 +101,16 @@ export function SheetPane({ sheet, onClose, onBack, opener = null, isTop }: Shee
</>
),
}),
[descriptor.icon, title, filePath, handleOpenAsTab, onBack, onClose, sheet.policy.openAsTab, t],
[
descriptor.icon,
descriptor.label,
filePath,
handleOpenAsTab,
onBack,
onClose,
sheet.policy.openAsTab,
t,
],
);
const tabDescriptor = useMemo<WorkspaceTabDescriptor>(
@@ -144,7 +146,7 @@ export function SheetPane({ sheet, onClose, onBack, opener = null, isTop }: Shee
<SheetBottomInset
style={styles.body}
role="dialog"
aria-label={title}
aria-label={descriptor.label}
testID="sheet-tab-body"
>
<WorkspacePaneContent
@@ -82,16 +82,14 @@ 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,
label: descriptor.label,
subtitle: descriptor.subtitle,
tooltip,
tooltip: descriptor.tooltip,
modified,
showCloseButton: registration.showCloseButton,
titleState: descriptor.titleState,
@@ -100,8 +98,8 @@ function WorkspaceTabPresentationResolverInner({
}),
[
descriptor.icon,
label,
tooltip,
descriptor.label,
descriptor.tooltip,
descriptor.statusBucket,
descriptor.subtitle,
descriptor.titleState,
+5 -89
View File
@@ -199,50 +199,22 @@ 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 PluginOpenScreenInput, type PluginScreenProps, type PluginWorkspacePanelProps, type PluginAgentPanelProps, type PluginTab, useTabState } from "@getpaseo/plugin/client";
import { type PluginClientContext, type PluginFilePanelProps, type PluginWorkspacePanelProps, type PluginAgentPanelProps, type PluginTab, useTabState } from "@getpaseo/plugin/client";
import { z } from "zod";
function FilePanel({ params, revision, tab, file, openScreen }: PluginFilePanelProps) {
function FilePanel({ params, revision, tab, file }: 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, 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 OldWorkspace({ context, workspaceId }: PluginWorkspacePanelProps) { return null; }
function OldAgent({ context, workspaceId, agentId }: PluginAgentPanelProps) { return null; }
function Agent({ params }: PluginAgentPanelProps) { params.agentId.toUpperCase(); 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 });
@@ -1124,59 +1096,3 @@ 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([]);
});
});
-24
View File
@@ -95,7 +95,6 @@ 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 {
@@ -103,25 +102,6 @@ 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;
@@ -205,8 +185,6 @@ export interface PluginTab {
readonly id: string;
/** Shows the tab's unsaved dot and asks before closing. */
setModified(modified: boolean): void;
/** Overrides this tab's title while mounted. Pass null or empty string to reset to the static panel title. */
setTitle(title: string | null): void;
/** Opaque persisted JSON. Undefined until written; the panel validates it. */
readonly state: unknown;
setState(state: JsonValue): void;
@@ -217,7 +195,6 @@ export interface PluginPanelProps<Params> extends PluginNavigableHostProps {
readonly params: Readonly<Params>;
revision: number;
tab: PluginTab;
openScreen(input: PluginOpenScreenInput): void;
}
export interface PluginWorkspacePanelParams {}
export interface PluginAgentPanelParams {
@@ -291,7 +268,6 @@ 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;
-2
View File
@@ -19,8 +19,6 @@ export type {
PluginSidebarViewProps,
PluginSidebarViewContribution,
PluginSidebarItemContribution,
PluginComposerPillItemProps,
PluginComposerPillItemContribution,
PluginWorkspaceRowBadgeItemProps,
PluginWorkspaceRowBadgeItemContribution,
PluginIcon,
-12
View File
@@ -189,18 +189,6 @@ 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;
+3 -4
View File
@@ -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 PluginComposerPillItemContribution, 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 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, pillItem: PluginComposerPillItemContribution, 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, 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(); pillItem.title.trim(); if (menu.kind === "item") menu.title.trim();
header.button.title.trim(); pill.button.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,7 +145,6 @@ 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 });
@@ -5,6 +5,8 @@ import path from "node:path";
import { fileURLToPath } from "node:url";
import { afterEach, beforeEach, describe, expect, test } from "vitest";
import { DaemonClient } from "../../test-utils/daemon-client.js";
import { createTestPaseoDaemon } from "../../test-utils/paseo-daemon.js";
import { createTestLogger } from "../../../test-utils/test-logger.js";
import type { AgentLaunchContext, AgentSession, AgentSessionConfig } from "../agent-sdk-types.js";
import { OpenCodeBridge } from "./opencode/bridge.js";
@@ -315,3 +317,122 @@ describe.each<Mode>(["explicit", "discovered"])("OpenCode v2 %s shared service",
expect((await second!.run(afterClose)).finalText).toBe("RESULT HUB_OK_2");
}, 120_000);
});
test("v2 opens the parent timeline and accepts prompts after a child working directory is removed", async () => {
const fixture = await startFixture("explicit");
const { root, project, service, bridge } = fixture;
const childDirectory = path.join(root, "child");
async function connectToDaemon() {
const provider = new OpenCodeV2AgentClient({
logger: createTestLogger(),
bridge,
settings: {
env: {
[EXTERNAL_SERVER_URL_ENV]: service.url,
[EXTERNAL_SERVER_PASSWORD_ENV]: service.password,
},
},
});
const daemon = await createTestPaseoDaemon({
paseoHomeRoot: path.join(root, "daemon"),
staticDir: root,
cleanup: false,
agentClients: { opencode: provider },
});
const client = new DaemonClient({ url: `ws://127.0.0.1:${daemon.port}/ws` });
const close = async () => {
await client.close();
await daemon.close();
await provider.shutdown();
};
try {
await client.connect();
return { client, close };
} catch (error) {
await close();
throw error;
}
}
function providerHeaders() {
return {
Authorization: `Basic ${Buffer.from(`opencode:${service.password}`).toString("base64")}`,
};
}
function providerClient() {
return OpenCode.make({ baseUrl: service.url, headers: providerHeaders() });
}
let daemon: Awaited<ReturnType<typeof connectToDaemon>> | undefined;
try {
await mkdir(childDirectory);
daemon = await connectToDaemon();
const initialPrompt = scriptedCall("subagent", {
agent: "general",
description: "Create a child session",
prompt: "Say hello",
});
const parent = await daemon.client.createAgent({
cwd: project,
provider: "opencode",
model: SCRIPTED_MODEL,
initialPrompt,
});
expect((await daemon.client.waitForFinish(parent.id, 30_000)).status).toBe("idle");
const persistedParent = await daemon.client.fetchAgent(parent.id);
const parentSessionId = persistedParent?.agent.persistence?.sessionId;
expect(parentSessionId).toBeDefined();
const opencode = providerClient();
const { data: children } = await opencode.session.list({
parentID: parentSessionId,
limit: 100,
});
expect(children).toHaveLength(1);
const childId = children[0]!.id;
await opencode.session.move({ sessionID: childId, directory: childDirectory });
await expect
.poll(async () => (await opencode.session.get({ sessionID: childId })).location.directory)
.toBe(childDirectory);
const readTimeline = (client: DaemonClient) =>
client.fetchAgentTimeline(parent.id, {
direction: "tail",
limit: 0,
projection: "canonical",
});
const before = await readTimeline(daemon.client);
expect(
before.entries.some(
({ item }) => item.type === "user_message" && item.text === initialPrompt,
),
).toBe(true);
await daemon.close();
daemon = undefined;
await rm(childDirectory, { recursive: true });
await service.restart();
expect((await providerClient().session.get({ sessionID: childId })).id).toBe(childId);
const response = await fetch(new URL(`/api/session/${childId}/permission`, service.url), {
headers: providerHeaders(),
});
expect(response.status).toBe(404);
expect(await response.json()).toMatchObject({ _tag: "LocationNotFoundError" });
daemon = await connectToDaemon();
const after = await readTimeline(daemon.client);
expect(after.entries.map(({ item }) => item)).toEqual(before.entries.map(({ item }) => item));
const followUp = scriptedCall("shell", {
command: "printf parent-resumed",
description: "Confirm the parent can run a new turn",
});
await daemon.client.sendMessage(parent.id, followUp);
expect(await daemon.client.waitForFinish(parent.id, 30_000)).toMatchObject({
status: "idle",
lastMessage: expect.stringContaining("parent-resumed"),
});
expect(service.agentRequests.some(({ transcript }) => transcript.includes(followUp))).toBe(
true,
);
} finally {
await daemon?.close();
await stopFixture(fixture);
}
}, 90_000);
@@ -5,6 +5,7 @@ export class OpenCodeHttpError extends Error {
readonly operation: string,
readonly status: number | undefined,
readonly html: boolean,
readonly errorTag?: string,
) {
const statusLabel = status === undefined ? "" : ` (HTTP ${status})`;
super(
@@ -17,6 +18,15 @@ export class OpenCodeHttpError extends Error {
/** True when OpenCode answered 404, directly or as the cause of the client's transport error. */
export function isOpenCodeNotFound(error: unknown): boolean {
return getOpenCodeHttpError(error)?.status === 404;
}
export function isOpenCodeLocationNotFound(error: unknown): boolean {
const failure = getOpenCodeHttpError(error);
return failure?.status === 404 && failure.errorTag === "LocationNotFoundError";
}
function getOpenCodeHttpError(error: unknown): OpenCodeHttpError | undefined {
const failure = error instanceof OpenCodeHttpError ? error : (error as Error | null)?.cause;
return failure instanceof OpenCodeHttpError && failure.status === 404;
return failure instanceof OpenCodeHttpError ? failure : undefined;
}
@@ -47,9 +47,9 @@ export class ScriptedOpenCodeService {
private constructor(
readonly requests: ScriptedRequest[],
readonly root: string,
readonly url: string,
readonly password: string,
private readonly process: ChildProcess,
public url: string,
public password: string,
private process: ChildProcess,
private readonly llm: Server,
) {}
@@ -105,6 +105,26 @@ export class ScriptedOpenCodeService {
}),
);
await options.beforeStart?.({ configDirectory });
try {
const { url, password, child } = await this.launch(root);
return new ScriptedOpenCodeService(requests, root, url, password, child, llm);
} catch (error) {
llm.close();
await rm(root, { recursive: true, force: true });
throw error;
}
}
async restart() {
await this.stopProcess();
await rm(path.join(this.root, "state", "opencode", "service.json"), { force: true });
const { child, url, password } = await ScriptedOpenCodeService.launch(this.root);
this.process = child;
this.url = url;
this.password = password;
}
private static async launch(root: string) {
const child = spawn(
OPENCODE_V2_COMMAND,
["serve", "--service", "--hostname", "127.0.0.1", "--port", "0"],
@@ -124,11 +144,10 @@ export class ScriptedOpenCodeService {
const parsed = content ? (JSON.parse(content) as { url: string; password: string }) : null;
// The service registers before it serves requests.
if (parsed && (await isReady(parsed.url, parsed.password))) {
return new ScriptedOpenCodeService(requests, root, parsed.url, parsed.password, child, llm);
return { ...parsed, child };
}
if (child.exitCode !== null || Date.now() > deadline) {
llm.close();
await rm(root, { recursive: true, force: true });
child.kill();
throw new Error(`OpenCode v2 service did not register (exit ${child.exitCode})`);
}
await delay(100);
@@ -172,10 +191,17 @@ export class ScriptedOpenCodeService {
}
async stop(): Promise<void> {
await this.stopProcess();
await new Promise<void>((resolve) => this.llm.close(() => resolve()));
await rm(this.root, { recursive: true, force: true });
}
private async stopProcess(): Promise<void> {
const exited = new Promise<void>((resolve) => {
if (this.process.exitCode !== null) resolve();
if (this.process.exitCode !== null || this.process.signalCode !== null) resolve();
else this.process.once("exit", () => resolve());
});
if (this.process.exitCode !== null || this.process.signalCode !== null) return;
if (this.process.pid && process.platform !== "win32") {
try {
process.kill(-this.process.pid, "SIGTERM");
@@ -184,9 +210,8 @@ export class ScriptedOpenCodeService {
}
} else this.process.kill("SIGTERM");
await Promise.race([exited, delay(10_000)]);
if (this.process.exitCode === null) this.process.kill("SIGKILL");
await new Promise<void>((resolve) => this.llm.close(() => resolve()));
await rm(this.root, { recursive: true, force: true });
if (this.process.exitCode === null && this.process.signalCode === null)
this.process.kill("SIGKILL");
}
}
@@ -12,6 +12,7 @@ import type { AgentStreamEvent } from "../../../agent-sdk-types.js";
import type { ProviderSubagentInputEvent } from "../../../provider-subagents/store.js";
import { syncTailMessages } from "./history.js";
import { isOpenCodeLocationNotFound } from "../http-error.js";
import { buildOpenCodeSubagentSubtitle } from "../subagent-presentation.js";
import type { V2Api } from "./api.js";
@@ -63,8 +64,8 @@ export class SessionChildren {
try {
await adoptChild(id);
} catch (error) {
if (!isSessionNotFoundError(error)) throw error;
this.remove(id);
if (isSessionNotFoundError(error)) this.remove(id);
else if (!isOpenCodeLocationNotFound(error)) throw error;
}
}
}
@@ -201,10 +202,16 @@ export class SessionChildren {
});
}
private async reconcileChild(info: SessionInfo, parentID: string) {
await this.options.reconcilePermissions(info.id);
let child = this.children.get(info.id);
try {
await this.options.reconcilePermissions(info.id);
if (!child) await this.options.adoptChild?.(info.id);
} catch (error) {
// A child can outlive its worktree. Its runtime cannot be restored until the location returns.
if (isOpenCodeLocationNotFound(error)) return;
throw error;
}
if (!child) {
await this.options.adoptChild?.(info.id);
child = this.children.get(info.id) ?? { parentID, timeline: new V2Timeline(), history: [] };
this.children.set(info.id, child);
}
@@ -9,6 +9,7 @@ export async function validateOpenCodeResponse(
const html = contentType?.includes("text/html") ?? false;
if (response.ok && !html) return response;
let errorTag: string | undefined;
// The SDK needs the original body to decode the provider's missing-session error.
if (response.status === 404 && !html && contentType?.includes("application/json")) {
const body: unknown = await response
@@ -16,8 +17,10 @@ export async function validateOpenCodeResponse(
.json()
.catch(() => null);
if (isSessionNotFoundError(body)) return response;
if (body && typeof body === "object" && "_tag" in body && typeof body._tag === "string")
errorTag = body._tag;
}
const url = request instanceof Request ? request.url : String(request);
throw new OpenCodeHttpError(new URL(url).pathname, response.status, html);
throw new OpenCodeHttpError(new URL(url).pathname, response.status, html, errorTag);
}
-1
View File
@@ -82,7 +82,6 @@ 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 })` |
-1
View File
@@ -74,7 +74,6 @@ 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 })` |
+23 -96
View File
@@ -1177,7 +1177,6 @@ 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`.
@@ -2186,18 +2185,13 @@ export default function contribute(client: PluginClientContext) {
| `Component` | Yes | React Native component matching the selected context's props. |
Every panel receives `PluginPanelProps<Params>` with `theme`, `host`, `layout`, `navigation`,
`openScreen`, `workspaceId`, read-only `params`, `revision`, and `tab`. Workspace panels have empty
`workspaceId`, read-only `params`, `revision`, and `tab`. Workspace panels have empty
`PluginWorkspacePanelParams`; agent panels have `PluginAgentPanelParams` containing `agentId`.
`openScreen({ screenId, params })` opens one of this plugin's screens on the panel's host; unknown
screen IDs throw. `openScreen` on panels requires a Paseo app newer than 0.19.1; set
[`requirements.app`](#requirements) or check `typeof openScreen === "function"` on older apps.
`revision` increments whenever params are re-sent to the same tab, including an
identical request. `tab.id` is the tab's ID in the [workspace layout](#workspace-layout). It requires
Paseo 0.19.0 or later.
`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.
`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
`tab.setModified(boolean)` marks unsaved work and asks before closing. `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)`:
@@ -2513,14 +2507,13 @@ 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`, `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. |
| 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). |
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
@@ -3054,78 +3047,13 @@ searches a fixed issue list from a daemon handler and sets the branch and metada
## Composer pills
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
`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
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({
@@ -3204,7 +3132,8 @@ The whole trigger opens the surface; there is no split-button behavior.
### Menu entries
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.
A menu contains items and separators. IDs use lowercase letters, digits, and hyphens, start with
a letter, and are unique within that menu.
```tsx
const behavior: PluginButtonBehavior = {
@@ -3256,19 +3185,17 @@ 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 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.
`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.
`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,
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.
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.
`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
+15 -86
View File
@@ -910,7 +910,6 @@ 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 负责。界面主体由插件负责。
@@ -1763,15 +1762,13 @@ export default function contribute(client: PluginClientContext) {
| `locations` | 否 | `workspace` 和/或 `explorer`。默认为 `workspace`。 |
| `Component` | 是 | 与所选上下文的属性相匹配的 React Native 组件。 |
每个面板都接收 `PluginPanelProps<Params>`,包含 `theme`、`host`、`layout`、`navigation`、`openScreen`、
每个面板都接收 `PluginPanelProps<Params>`,包含 `theme`、`host`、`layout`、`navigation`、
`workspaceId`、只读的 `params`、`revision` 和 `tab`。工作区面板使用空的
`PluginWorkspacePanelParams`;Agent 面板的 `PluginAgentPanelParams` 包含 `agentId`。
`openScreen({ screenId, params })` 在该面板所属主机上打开此插件的某个界面,未知的界面 ID 会抛出错误;
面板上的 `openScreen` 需要高于 0.19.1 的 Paseo 应用,请在 [`requirements.app`](#requirements) 中声明应用版本要求,或在旧版应用上先检查 `typeof openScreen === "function"`。
每次向同一标签页重新发送 params 时,`revision` 都会递增,即使请求与上次相同。
`tab.id` 是该标签页在[工作区布局](#workspace-layout)中的 ID。它需要 Paseo 0.19.0 或更高版本。
`tab.setModified(boolean)` 标记未保存的更改,并在关闭前询问。`tab.setTitle(title)` 在面板挂载期间覆盖该标签页的标题;传入 `null` 或 `""` 可恢复为面板的静态 `title`(如需兼容旧版应用,请使用 `tab.setTitle?.(title)`)。`tab.state` 是由面板定义的持久化
`tab.setModified(boolean)` 标记未保存的更改,并在关闭前询问。`tab.state` 是由面板定义的持久化
JSON,初始为 `undefined`;`tab.setState(value)` 替换整个值。每个标签页拥有独立状态。
Paseo 只保存状态,不解释其内容。用 `useTabState(tab, schema, defaultState)` 验证它:
@@ -2056,14 +2053,13 @@ 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`、`setTitle`、持久化的自定义 `state` 和 `setState`。参见[工作区面板](#workspace-panels)。 |
| `openScreen` | `(input: PluginOpenScreenInput) => void` | 在该面板所属主机上打开此插件的某个界面:`{ screenId, params? }`。未知的界面 ID 会抛出错误。需要高于 0.19.1 的 Paseo 应用;请在 [`requirements.app`](#requirements) 中声明应用版本要求,或在旧版应用上先检查 `typeof openScreen === "function"`。 |
| 属性 | 类型 | 含义 |
| ------------- | ----------------------- | ------------------------------------------------------------------------------------------ |
| `workspaceId` | `string` | 包含该文件标签页的工作区。 |
| `params` | `PluginFilePanelParams` | 打开请求提供的只读 `path`、`lineStart?` 和 `lineEnd?`。 |
| `revision` | `number` | 每次向该标签页重新发送 params 时递增,即使是同一行。 |
| `file` | `PluginFile` | 从 `params.path` 解析的文件能力;标签页显示该文件期间保持不变。 |
| `tab` | `PluginTab` | `setModified`、持久化的自定义 `state` 和 `setState`。参见[工作区面板](#workspace-panels)。 |
Paseo 在知道文件存在及其大小后就会挂载你的面板,不会先读取文件。`file` 对象保持不变,它的 stat 字段保存 Paseo 已知的最新版本。请在渲染时读取这些字段;它们变化时不会重新渲染你的面板。面板要通过 `watch` 监听器,或 `useFileText`、`useFileBytes`、`useFileUrl` 引起的重新渲染,得知它们已变化:
@@ -2480,76 +2476,9 @@ export default function contribute(client: PluginClientContext) {
## Composer 胶囊 {#composer-pills}
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`)。菜单和弹出框在所有布局中都会添加一个向上的箭头,因为它们的浮层在胶囊上方打开;操作不显示箭头。
`client.addComposerPill({ id, workspaceId, agentId, button })` 使用同样的[按钮描述符](#button-descriptor),
并返回同样的注册对象。它面向某个 Agent 的 Composer 栏,与 Tasks 和 Subagents 并列。Composer 胶囊始终
显示图标和 `label`(省略 `label` 时显示 `title`)。它们从不显示箭头,菜单和弹出框也一样。
```tsx
const pill = client.addComposerPill({
@@ -2626,7 +2555,7 @@ type PluginButtonBehavior =
### 菜单项 {#menu-entries}
菜单包含条目和分隔线。条目 ID 可以是任意去除首尾空白后非空的字符串(如 `"D42"` 或 UUID),并且在该菜单内唯一。
菜单包含条目和分隔线。ID 由小写字母、数字和连字符组成,以字母开头,并且在该菜单内唯一。
```tsx
const behavior: PluginButtonBehavior = {
@@ -2678,13 +2607,13 @@ const behavior: PluginButtonBehavior = {
### 更新与生命周期 {#updates-and-lifecycle}
每个注册都属于一个插件安装、一个位置、一个工作区,以及(对于胶囊)一个 Agent。`id` 在该目标内是插件
内部的,由小写字母、数字和连字符组成且以字母开头。同一个 ID 可以用于不同的目标或位置。在同一目标中重复注册会抛出错误。
内部的,格式与菜单 ID 相同。同一个 ID 可以用于不同的目标或位置。在同一目标中重复注册会抛出错误。
`update(patch: Partial<PluginButton>)` 原地修改描述符,保留其标识和顺序。修改 `behavior` 时,请提供
完整的新 behavior 对象。无效的更新会抛出错误,并且不会改变现有按钮。订阅你自己的模型或客户端 API,并
调用 `update` 来发布响应式的变化;修改最初的描述符不会更新 UI。
隐藏或禁用按钮会关闭它的浮层。更新它的 behavior 也会关闭浮层,除非将已打开的弹出框更新为同为 `kind: "popover"` 且 `Content` 组件引用相同的描述符。隐藏会保留注册,因此再次显示时会恢复它
隐藏或禁用按钮会关闭它的浮层。更新它的 behavior 也会关闭浮层。隐藏会保留注册,因此再次显示时会恢复它
原来的位置。它不会取消已经在进行中的操作。
`remove()` 是幂等的。移除之后的更新不起作用。当插件安装被销毁时,Paseo 会移除尚存的按钮(参见[主机与生命周期](#hosts-and-lifecycle))。
+5 -36
View File
@@ -52,8 +52,7 @@ 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` |
| `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` |
| `addComposerPill` | A 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` |
@@ -201,14 +200,11 @@ import {
type PluginWorkspacePanelProps,
useWorkspace,
} from "@getpaseo/plugin/client";
import { useEffect, useMemo } from "react";
import { useMemo } from "react";
import { Text, View } from "react-native";
function Overview({ theme, layout, workspaceId, tab }: PluginWorkspacePanelProps) {
function Overview({ theme, layout, workspaceId }: PluginWorkspacePanelProps) {
const name = useWorkspace(workspaceId, (workspace) => workspace.name);
useEffect(() => {
tab.setTitle(name ? `Overview: ${name}` : null);
}, [name, tab]);
const styles = useMemo(
() => ({
screen: {
@@ -247,7 +243,7 @@ export default function contribute(client: PluginClientContext) {
}
```
Register a panel that belongs to one agent with `addAgentPanel`, and read `params.agentId` in it. Panels receive `tab` (`id`, `setModified`, `setTitle`, `state`, `setState`): call `tab.setTitle(title)` to override the tab's title while mounted, and `tab.setTitle(null)` to restore the static `title`. Every panel (`PluginWorkspacePanelProps`, `PluginAgentPanelProps`, and `PluginFilePanelProps`) also receives `openScreen({ screenId, params })` to open one of this plugin's screens on that host (check `typeof openScreen === "function"` or set `requirements.app` from Reference if older apps may run the plugin). Command Center callbacks receive `paseo`, `rpc`, `openScreen`, and, in workspace and agent context, `workspaceLayout`, which opens and arranges panes and tabs (Reference > Workspace layout; it names the release that added it).
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).
### Add a screen and a sidebar item
@@ -298,7 +294,7 @@ export default function contribute(client: PluginClientContext) {
}
```
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.
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.
### Add a composer control
@@ -346,33 +342,6 @@ 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: